DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
release: v1.5.14
Bingxi Zhao (Frank)7c6bcfaef75e
diff --git a/README.md b/README.mdindex cfcacf30a..e7609f201 100644--- a/README.md+++ b/README.md@@ -49,6 +49,8 @@### 📦 Releases+> **[2026.8.19]** [v1.5.14](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.14) — **Immersive Reading**: a document open beside the thread, cited page by page; DeepTutor configures itself from chat; IMA libraries you browse and write to; a notebook console.+> **[2026.8.17]** [v1.5.13](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.13) — Books stream while they compile, track your progress, and export to Markdown; a cost estimate before you approve a spine; and home starter suggestions drawn from memory.> **[2026.8.13]** [v1.5.12](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.12) — Web search rebuilt with six new providers (**Doubao**, **Bocha**, **Zhipu**, **Firecrawl**, **Qianfan**, **Aliyun IQS**), a **LiteParse** parsing engine, MCP servers that reconnect on credential change, and **CodeBuddy** + **OrcaRouter**.@@ -197,10 +199,10 @@DeepTutor is an agent-native learning workspace that connects tutoring, problem solving, quiz generation, research, visualization, and mastery practice in one extensible system.-- **One runtime for every mode** — Chat, Quiz, Research, Visualize, Solve, and Mastery Path run on the same agent loop, so you switch the objective, not the engine, and context moves with the learner.+- **One runtime for every mode** — Chat, Quiz, Research, Visualize, Solve, Mastery Path, and Immersive Reading run on the same agent loop, so you switch the objective, not the engine, and context moves with the learner.- **Connected learning context** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, and Memory stay available across every workflow instead of living in isolated tools.- **Subagents and Partners** — consult a live coding CLI (Claude Code, Codex, Gemini, Kimi, opencode, or MiMo) or a Partner from any turn (or import their past conversations), and run persistent IM companions on the same brain.-- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, or a linked Obsidian vault, with pluggable document parsing.+- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, a remote LightRAG Server or Tencent IMA library, or a linked Obsidian vault, with pluggable document parsing.- **Extensible tools and skills** — built-in tools, MCP servers, CLI apps, image / video / voice generation models, and installable community skills from EduHub.- **Inspectable memory** — L1 traces, L2 surface summaries, and L3 synthesis make personalization visible and editable, with a Memory Graph that traces every claim back to its evidence.@@ -490,7 +492,7 @@ User-toggleable tools are `brainstorm`, `web_search`, `paper_search`, `reason`,Context comes in two kinds: **sticky session context** (subagent, knowledge bases, persona, model, voice) lives on the composer toolbar and persists across turns; **one-time references** (files, chat history, books, notebooks, question bank, imported agents) come from the `+` menu for a single turn.-Chat is also the launch point for deeper capabilities: **Quiz** for question generation, **Research** for cited reports, **Visualize** for charts / diagrams / animations, and — under *More Capabilities* — **Solve** for worked reasoning and **Mastery Path** for learning-plan flows.+Chat is also the launch point for deeper capabilities: **Quiz** for question generation, **Visualize** for charts / diagrams / animations, **Mastery Path** for learning-plan flows, and **Immersive Reading** — a document open beside the thread, with every claim cited to the page it came from. **Research** for cited reports and **Solve** for worked reasoning sit under *More Capabilities*.</details>@@ -579,7 +581,7 @@ Each chapter compiles into typed blocks — text, callouts, quizzes, flash cards<img src="assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900"></div>-Knowledge bases are the document collections behind RAG — they ground Chat turns, Co-Writer edits, Book generation, and Partner conversations. What's distinctive is a **choice of retrieval engines**: **LlamaIndex** (the default, local vector + BM25), **PageIndex** (hosted, reasoning retrieval with page-level citations), **GraphRAG** and **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval offloaded to an external LightRAG instance you connect over HTTP), **Tencent IMA** (a library you curate in IMA, searched over its OpenAPI), or a linked **Obsidian** vault the tutor reads and writes in place. Each KB is bound to one engine.+Knowledge bases are the document collections behind RAG — they ground Chat turns, Co-Writer edits, Book generation, and Partner conversations. What's distinctive is a **choice of retrieval engines**: **LlamaIndex** (the default, local vector + BM25), **PageIndex** (hosted, reasoning retrieval with page-level citations), **GraphRAG** and **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval offloaded to an external LightRAG instance you connect over HTTP), **Tencent IMA** (a library you curate in IMA — searched, browsed, and written back to over its OpenAPI), or a linked **Obsidian** vault the tutor reads and writes in place. Each KB is bound to one engine.<div align="center"><img src="assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Create a knowledge base" width="900">@@ -596,7 +598,7 @@ Creating a KB, you either **create new** (upload documents and build a fresh ind<img src="assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Space hub" width="900"></div>-Learning Space is the library and personalization layer — where the things that persist live. **Conversations & Materials** holds your chat history, notebooks, and a question bank (each saved question keeps your answer, the reference answer, and an explanation). **Personalization** holds mastery paths, personas (behavior presets such as *peer*, *research-assistant*, *teacher*), skills (`SKILL.md` playbooks the model reads on demand), **MCP Services** — a curated store of hosted MCP servers you install for yourself in one click, plus any remote server you configure by URL — and **CLI Apps**, command-line tools from the [CLI-Anything](https://github.com/HKUDS/CLI-Anything) catalog that the chat agent calls directly, with each app's own usage guide loaded on demand. Everything here can be reused from Chat, Partners, Co-Writer, and Book.+Learning Space is the library and personalization layer — where the things that persist live. **Conversations & Materials** holds your chat history, notebooks — now their own console, with records that move or copy between notebooks and a Markdown export — and a question bank (each saved question keeps your answer, the reference answer, and an explanation). **Personalization** holds mastery paths, personas (behavior presets such as *peer*, *research-assistant*, *teacher*), skills (`SKILL.md` playbooks the model reads on demand), **MCP Services** — a curated store of hosted MCP servers you install for yourself in one click, plus any remote server you configure by URL — and **CLI Apps**, command-line tools from the [CLI-Anything](https://github.com/HKUDS/CLI-Anything) catalog that the chat agent calls directly, with each app's own usage guide loaded on demand. Everything here can be reused from Chat, Partners, Co-Writer, and Book.<div align="center"><img src="assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Import skills from EduHub" width="900">@@ -636,7 +638,7 @@ Settings is the operational control plane, with a live status strip (backend hea<img src="assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor appearance settings and themes" width="900"></div>-Most sections use a draft-and-apply flow, so you can test a provider before committing it. Four themes ship in the box — Default, Cream, Dark, and Glass. Project-root `.env` files are intentionally ignored; runtime configuration lives under `data/user/settings/*.json` unless `DEEPTUTOR_HOME` or `deeptutor start --home` points the app elsewhere.+Most sections use a draft-and-apply flow, so you can test a provider before committing it. You can also just ask in Chat: the assistant reads the current configuration, applies a change, and says whether it needs a restart or a re-index — probing a new model before it commits, so it cannot switch itself onto something unreachable. API keys never pass through the model, which opens the matching form for you instead. Four themes ship in the box — Default, Cream, Dark, and Glass. Project-root `.env` files are intentionally ignored; runtime configuration lives under `data/user/settings/*.json` unless `DEEPTUTOR_HOME` or `deeptutor start --home` points the app elsewhere.**OpenAI Codex OAuth (experimental).** Picking **OpenAI Codex** under Models → LLM replaces the API-key fields with a browser sign-in that runs against your own ChatGPT plan, so no `OPENAI_API_KEY` is needed. Tokens live only in `data/system/user-secrets/<owner>/private/openai-codex/` — in the multi-container Compose deployment, outside every tree the exec sandbox can reach — and DeepTutor never reads or modifies your `~/.codex` CLI login. The model list comes from that account's live catalog; signing in publishes the profile but only becomes the active model when no LLM is configured yet. Because a token authorizes one person's plan, the profile is not shareable through user grants — each account signs in for itself, ordinary users included: their card sits under Models → LLM, and the resulting models, catalog, and sign-out stay private to that account.diff --git a/assets/README/README_AR.md b/assets/README/README_AR.mdindex c162d8b5f..3ce036d21 100644--- a/assets/README/README_AR.md+++ b/assets/README/README_AR.md@@ -60,10 +60,10 @@DeepTutor هو بيئة تعلم أصيلة للوكلاء تربط التدريس وحل المشكلات وتوليد الاختبارات والبحث والتصور وممارسة الإتقان في نظام واحد قابل للتوسيع.-- **بيئة تشغيل واحدة لجميع الأوضاع** — Chat وQuiz وResearch وVisualize وSolve وMastery Path تعمل على نفس حلقة الوكيل، لذا تغيّر الهدف لا المحرك، والسياق يتبع المتعلم.+- **بيئة تشغيل واحدة لجميع الأوضاع** — Chat وQuiz وResearch وVisualize وSolve وMastery Path وImmersive Reading تعمل على نفس حلقة الوكيل، لذا تغيّر الهدف لا المحرك، والسياق يتبع المتعلم.- **سياق تعلم متصل** — قواعد المعرفة والكتب ومسودات Co-Writer ودفاتر الملاحظات وبنوك الأسئلة والشخصيات والذاكرة متاحة في جميع سير العمل بدلاً من العيش في أدوات معزولة.- **الوكلاء الفرعيون والشركاء** — استشارة واجهة CLI برمجية حية (Claude Code أو Codex أو Gemini أو Kimi أو opencode أو MiMo) أو Partner مباشرةً من أي دور (أو استيراد محادثاتهم السابقة)، وتشغيل رفاق IM دائمين على نفس الدماغ.-- **معرفة متعددة المحركات** — مكتبات RAG مُصدَّرة عبر LlamaIndex وPageIndex وGraphRAG وLightRAG أو مخزن Obsidian مرتبط، مع تحليل مستندات قابل للتوصيل.+- **معرفة متعددة المحركات** — مكتبات RAG مُصدَّرة عبر LlamaIndex وPageIndex وGraphRAG وLightRAG، أو LightRAG Server عن بُعد أو مكتبة Tencent IMA، أو مخزن Obsidian مرتبط، مع تحليل مستندات قابل للتوصيل.- **أدوات ومهارات قابلة للتوسيع** — أدوات مدمجة وخوادم MCP وتطبيقات CLI ونماذج توليد الصور/الفيديو/الصوت ومهارات مجتمع قابلة للتثبيت من EduHub.- **ذاكرة قابلة للتدقيق** — آثار L1 وملخصات سطحية L2 وتركيب L3 تجعل التخصيص مرئياً وقابلاً للتحرير، مع Memory Graph يتتبع كل ادعاء إلى دليله.@@ -331,7 +331,7 @@ Chat هي القدرة الافتراضية والمكان الذي يبدأ فيأتي السياق في نوعين: **السياق اللاصق للجلسة** (الوكيل الفرعي وقواعد المعرفة والشخصية والنموذج والصوت) يعيش على شريط أدوات المؤلف ويستمر عبر الأدوار؛ **المراجع لمرة واحدة** (الملفات وتاريخ المحادثة والكتب ودفاتر الملاحظات وبنك الأسئلة والوكلاء المستوردون) تأتي من قائمة `+` لدور واحد.-Chat هي أيضاً نقطة انطلاق للقدرات الأعمق: **Quiz** لتوليد الأسئلة، و**Research** للتقارير المستشهَد بها، و**Visualize** للمخططات / الرسوم البيانية / الرسوم المتحركة، وتحت *المزيد من القدرات* — **Solve** للتفكير المعمق و**Mastery Path** لتدفقات خطط التعلم.+Chat هي أيضاً نقطة انطلاق للقدرات الأعمق: **Quiz** لتوليد الأسئلة، و**Visualize** للمخططات / الرسوم البيانية / الرسوم المتحركة، و**Mastery Path** لتدفقات خطط التعلم، و**Immersive Reading** — مستند مفتوح بجانب المحادثة، حيث يُستشهَد بكل ادعاء بالصفحة التي جاء منها. أما **Research** للتقارير المستشهَد بها و**Solve** للتفكير المعمق فتحت *المزيد من القدرات*.</details>@@ -420,7 +420,7 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقا<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="مركز المعرفة في DeepTutor" width="900"></div>-قواعد المعرفة هي مجموعات المستندات وراء RAG — إنها ترسّخ أدوار Chat وتحرير Co-Writer وتوليد Book ومحادثات Partner. ما يميزها هو **اختيار محرك الاسترجاع**: **LlamaIndex** (الافتراضي، ناقل محلي + BM25)، **PageIndex** (مستضاف، استرجاع تفكيري مع استشهادات على مستوى الصفحة)، **GraphRAG** و**LightRAG** (استرجاع قائم على الرسم البياني المعرفي)، **LightRAG Server** (استرجاع مُحال إلى نسخة LightRAG خارجية تتصل بها عبر HTTP)، **Tencent IMA** (مكتبة تنظّمها ضمن IMA، يُبحث فيها عبر OpenAPI الخاصة بها)، أو مخزن **Obsidian** مرتبط يقرأ المدرس ويكتب فيه في مكانه. كل قاعدة معرفة مرتبطة بمحرك واحد.+قواعد المعرفة هي مجموعات المستندات وراء RAG — إنها ترسّخ أدوار Chat وتحرير Co-Writer وتوليد Book ومحادثات Partner. ما يميزها هو **اختيار محرك الاسترجاع**: **LlamaIndex** (الافتراضي، ناقل محلي + BM25)، **PageIndex** (مستضاف، استرجاع تفكيري مع استشهادات على مستوى الصفحة)، **GraphRAG** و**LightRAG** (استرجاع قائم على الرسم البياني المعرفي)، **LightRAG Server** (استرجاع مُحال إلى نسخة LightRAG خارجية تتصل بها عبر HTTP)، **Tencent IMA** (مكتبة تنظّمها ضمن IMA — يُبحث فيها ويُتصفَّح ويُكتَب إليها عبر OpenAPI الخاصة بها)، أو مخزن **Obsidian** مرتبط يقرأ المدرس ويكتب فيه في مكانه. كل قاعدة معرفة مرتبطة بمحرك واحد.<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="إنشاء قاعدة معرفة" width="900">@@ -437,7 +437,7 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقا<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="مركز فضاء التعلم في DeepTutor" width="900"></div>-فضاء التعلم هو طبقة المكتبة والتخصيص — حيث تعيش الأشياء التي تستمر. **المحادثات والمواد** تحتفظ بتاريخ المحادثة ودفاتر الملاحظات وبنك الأسئلة (كل سؤال محفوظ يحتفظ بإجابتك والإجابة المرجعية وشرحاً). **التخصيص** يحتفظ بمسارات الإتقان والشخصيات (إعدادات السلوك المسبقة مثل *زميل* و*مساعد بحثي* و*معلم*)، والمهارات (دليل `SKILL.md` يقرأه النموذج عند الطلب)، و**خدمات MCP** — متجر مُنسَّق من خوادم MCP المستضافة تُثبّتها لنفسك بنقرة واحدة، بالإضافة إلى أي خادم بعيد تهيّئه بعنوان URL — و**تطبيقات CLI**، أدوات سطر أوامر من كتالوج [CLI-Anything](https://github.com/HKUDS/CLI-Anything) يستدعيها وكيل المحادثة مباشرةً، مع دليل استخدام خاص بكل تطبيق يُحمَّل عند الطلب. كل شيء هنا يمكن إعادة استخدامه من Chat وPartners وCo-Writer وBook.+فضاء التعلم هو طبقة المكتبة والتخصيص — حيث تعيش الأشياء التي تستمر. **المحادثات والمواد** تحتفظ بتاريخ المحادثة ودفاتر الملاحظات — التي أصبحت الآن لوحة تحكم خاصة بها، بسجلات يمكن نقلها أو نسخها بين دفاتر الملاحظات وتصديرها إلى Markdown — وبنك الأسئلة (كل سؤال محفوظ يحتفظ بإجابتك والإجابة المرجعية وشرحاً). **التخصيص** يحتفظ بمسارات الإتقان والشخصيات (إعدادات السلوك المسبقة مثل *زميل* و*مساعد بحثي* و*معلم*)، والمهارات (دليل `SKILL.md` يقرأه النموذج عند الطلب)، و**خدمات MCP** — متجر مُنسَّق من خوادم MCP المستضافة تُثبّتها لنفسك بنقرة واحدة، بالإضافة إلى أي خادم بعيد تهيّئه بعنوان URL — و**تطبيقات CLI**، أدوات سطر أوامر من كتالوج [CLI-Anything](https://github.com/HKUDS/CLI-Anything) يستدعيها وكيل المحادثة مباشرةً، مع دليل استخدام خاص بكل تطبيق يُحمَّل عند الطلب. كل شيء هنا يمكن إعادة استخدامه من Chat وPartners وCo-Writer وBook.<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="استيراد مهارات من EduHub" width="900">@@ -477,7 +477,7 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقا<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="إعدادات المظهر والثيمات في DeepTutor" width="900"></div>-تستخدم معظم الأقسام تدفق صياغة-وتطبيق، لذا يمكنك اختبار مزود قبل الالتزام به. تشحن أربع ثيمات في الصندوق — Default وCream وDark وGlass. ملفات `.env` في جذر المشروع تُتجاهل عمداً؛ يعيش تهيئة وقت التشغيل تحت `data/user/settings/*.json` إلا إذا وجّه `DEEPTUTOR_HOME` أو `deeptutor start --home` التطبيق في مكان آخر.+تستخدم معظم الأقسام تدفق صياغة-وتطبيق، لذا يمكنك اختبار مزود قبل الالتزام به. يمكنك أيضاً أن تطلب ذلك ببساطة في Chat: يقرأ المساعد التهيئة الحالية، ويطبّق التغيير، ويخبرك إن كان يحتاج إلى إعادة تشغيل أو إعادة فهرسة — مع اختبار النموذج الجديد قبل الالتزام به، بحيث لا يمكنه تبديل نفسه إلى شيء يتعذّر الوصول إليه. مفاتيح API لا تمرّ أبداً عبر النموذج، الذي يفتح لك بدلاً من ذلك الاستمارة المطابقة. تشحن أربع ثيمات في الصندوق — Default وCream وDark وGlass. ملفات `.env` في جذر المشروع تُتجاهل عمداً؛ يعيش تهيئة وقت التشغيل تحت `data/user/settings/*.json` إلا إذا وجّه `DEEPTUTOR_HOME` أو `deeptutor start --home` التطبيق في مكان آخر.**OpenAI Codex OAuth (تجريبي).** اختيار **OpenAI Codex** ضمن **النماذج ← LLM** يستبدل حقول مفتاح API بتسجيل دخول عبر المتصفح يعمل مقابل خطة ChatGPT الخاصة بك، لذا لا حاجة إلى `OPENAI_API_KEY`. تعيش الرموز (tokens) فقط في `data/system/user-secrets/<owner>/private/openai-codex/` — في نشر Compose متعدد الحاويات، خارج كل شجرة يمكن لصندوق أمان التنفيذ الوصول إليها — ولا يقرأ DeepTutor أو يعدّل أبداً تسجيل دخولك إلى CLI في `~/.codex`. تأتي قائمة النماذج من الكتالوج الحي لذلك الحساب؛ تسجيل الدخول ينشر الملف الشخصي لكنه لا يصبح النموذج النشط إلا عندما لا يكون هناك LLM مهيأ بعد. ولأن الرمز يخوّل خطة شخص واحد فقط، فالملف الشخصي غير قابل للمشاركة عبر منح المستخدمين — كل حساب يسجّل دخوله بنفسه، بما في ذلك المستخدمون العاديون: تظهر بطاقتهم ضمن **النماذج ← LLM**، وتبقى النماذج الناتجة والكتالوج وتسجيل الخروج خاصة بذلك الحساب.diff --git a/assets/README/README_CN.md b/assets/README/README_CN.mdindex e3814d0b0..b210e7a21 100644--- a/assets/README/README_CN.md+++ b/assets/README/README_CN.md@@ -60,10 +60,10 @@DeepTutor 是一个智能体原生的学习工作区,将辅导、解题、测验生成、研究、可视化和掌握度练习整合在一个可扩展的系统中。-- **统一的运行时** — Chat、Quiz、Research、Visualize、Solve 和 Mastery Path 运行在同一个智能体循环上,切换的是目标,而非引擎,上下文始终随学习者流转。+- **统一的运行时** — Chat、Quiz、Research、Visualize、Solve、Mastery Path 和 Immersive Reading 运行在同一个智能体循环上,切换的是目标,而非引擎,上下文始终随学习者流转。- **互联的学习上下文** — 知识库、书籍、Co-Writer 草稿、笔记本、题库、人格预设和 Memory,在每个工作流中始终可用,而不是各自孤立。- **子智能体与 Partners** — 在任意对话轮次中调用实时运行的编程 CLI(Claude Code、Codex、Gemini、Kimi、opencode 或 MiMo)或 Partner(或导入其历史对话),并在同一大脑上运行持久化的 IM 伴侣。-- **多引擎知识库** — 跨 LlamaIndex、PageIndex、GraphRAG、LightRAG 或链接的 Obsidian vault 的版本化 RAG 知识库,支持可插拔的文档解析。+- **多引擎知识库** — 跨 LlamaIndex、PageIndex、GraphRAG、LightRAG、远程 LightRAG Server 或 Tencent IMA 知识库,或链接的 Obsidian vault 的版本化 RAG 知识库,支持可插拔的文档解析。- **可扩展工具与技能** — 内置工具、MCP 服务器、CLI 应用、图像 / 视频 / 语音生成模型,以及从 EduHub 安装的社区技能。- **可审计的记忆** — L1 追踪、L2 表面摘要和 L3 综合让个性化透明可编辑,Memory Graph 将每一条结论追溯到其原始证据。@@ -331,7 +331,7 @@ Chat 是默认能力,也是大多数工作的起点。单个对话线程可以上下文分为两类:**粘性会话上下文**(子智能体、知识库、人格预设、模型、语音)存在于编辑器工具栏,在各轮次间持续保留;**一次性引用**(文件、聊天历史、书籍、笔记本、题库、导入的智能体)通过 `+` 菜单添加,仅用于单次对话轮次。-Chat 也是进入更深层能力的入口:**Quiz** 用于题目生成,**Research** 用于带引用的报告,**Visualize** 用于图表 / 示意图 / 动画,以及 *更多能力* 下的 **Solve**(有步骤的推理)和 **Mastery Path**(学习计划流程)。+Chat 也是进入更深层能力的入口:**Quiz** 用于题目生成,**Visualize** 用于图表 / 示意图 / 动画,**Mastery Path** 用于学习计划流程,以及 **Immersive Reading** — 在对话旁打开一份文档,每条论断都标注来源页码。**Research**(带引用的报告)和 **Solve**(有步骤的推理)则位于 *更多能力* 之下。</details>@@ -420,7 +420,7 @@ Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor 知识中心" width="900"></div>-知识库是 RAG 背后的文档集合 — 为 Chat 对话、Co-Writer 编辑、Book 生成和 Partner 对话提供依据。其独特之处在于**检索引擎的选择**:**LlamaIndex**(默认,本地向量 + BM25)、**PageIndex**(托管,支持页面级引用的推理检索)、**GraphRAG** 和 **LightRAG**(知识图谱检索)、**LightRAG Server**(将检索卸载至你通过 HTTP 连接的外部 LightRAG 实例)、**Tencent IMA**(在 IMA 中维护的知识库,通过其 OpenAPI 进行检索),或直接在原位读写的链接 **Obsidian** vault。每个 KB 绑定到单一引擎。+知识库是 RAG 背后的文档集合 — 为 Chat 对话、Co-Writer 编辑、Book 生成和 Partner 对话提供依据。其独特之处在于**检索引擎的选择**:**LlamaIndex**(默认,本地向量 + BM25)、**PageIndex**(托管,支持页面级引用的推理检索)、**GraphRAG** 和 **LightRAG**(知识图谱检索)、**LightRAG Server**(将检索卸载至你通过 HTTP 连接的外部 LightRAG 实例)、**Tencent IMA**(在 IMA 中维护的知识库 — 通过其 OpenAPI 进行检索、浏览并写回),或直接在原位读写的链接 **Obsidian** vault。每个 KB 绑定到单一引擎。<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="创建知识库" width="900">@@ -437,7 +437,7 @@ Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor 学习空间中心" width="900"></div>-学习空间是知识库和个性化层 — 持久化内容的存放之处。**对话与素材**保存聊天历史、笔记本和题库(每道保存的题目包含你的答案、参考答案和解析)。**个性化**保存掌握路径、人格预设(如*同伴*、*研究助手*、*教师*等行为预设)、技能(模型按需读取的 `SKILL.md` 剧本)、**MCP 服务** — 一键为自己安装的托管 MCP 服务器精选商店,外加通过 URL 配置的任意远程服务器 — 以及**CLI 应用**,即来自 [CLI-Anything](https://github.com/HKUDS/CLI-Anything) 目录、由聊天智能体直接调用的命令行工具,每个应用的使用指南按需加载。这里的所有内容均可在 Chat、Partners、Co-Writer 和 Book 中复用。+学习空间是知识库和个性化层 — 持久化内容的存放之处。**对话与素材**保存聊天历史、笔记本 — 现已拥有独立的控制台,记录可在笔记本之间移动或复制,并支持导出为 Markdown — 以及题库(每道保存的题目包含你的答案、参考答案和解析)。**个性化**保存掌握路径、人格预设(如*同伴*、*研究助手*、*教师*等行为预设)、技能(模型按需读取的 `SKILL.md` 剧本)、**MCP 服务** — 一键为自己安装的托管 MCP 服务器精选商店,外加通过 URL 配置的任意远程服务器 — 以及**CLI 应用**,即来自 [CLI-Anything](https://github.com/HKUDS/CLI-Anything) 目录、由聊天智能体直接调用的命令行工具,每个应用的使用指南按需加载。这里的所有内容均可在 Chat、Partners、Co-Writer 和 Book 中复用。<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="从 EduHub 导入技能" width="900">@@ -477,7 +477,7 @@ Settings 是操作控制面板,带有实时状态条(后端健康状况与<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor 外观设置与主题" width="900"></div>-大多数部分采用草稿-应用流程,因此你可以在提交前测试提供商配置。开箱即提供四种主题 — Default、Cream、Dark 和 Glass。项目根目录的 `.env` 文件被刻意忽略;运行时配置存储在 `data/user/settings/*.json` 下,除非 `DEEPTUTOR_HOME` 或 `deeptutor start --home` 将应用指向其他位置。+大多数部分采用草稿-应用流程,因此你可以在提交前测试提供商配置。你也可以直接在 Chat 中开口:助手会读取当前配置、应用变更,并告知是否需要重启或重新索引 — 在提交前先探测新模型,因此它不会把自己切换到不可达的配置上。API Key 永远不会经过模型 — 它会为你打开对应的表单来输入。开箱即提供四种主题 — Default、Cream、Dark 和 Glass。项目根目录的 `.env` 文件被刻意忽略;运行时配置存储在 `data/user/settings/*.json` 下,除非 `DEEPTUTOR_HOME` 或 `deeptutor start --home` 将应用指向其他位置。**OpenAI Codex OAuth(实验性)。** 在 **模型 → LLM** 下选择 **OpenAI Codex**,会用基于你自己 ChatGPT 订阅运行的浏览器登录取代 API Key 输入框,因此无需 `OPENAI_API_KEY`。令牌仅保存在 `data/system/user-secrets/<owner>/private/openai-codex/` 中 — 在多容器 Compose 部署中,位于 exec 沙箱可触及的所有目录树之外 — DeepTutor 绝不会读取或修改你的 `~/.codex` CLI 登录状态。模型列表来自该账号的实时目录;只有尚未配置任何 LLM 时,登录后的 Codex 才会成为活跃模型。令牌只授权一个人的订阅,无法通过用户授权共享,因此每个账号都需自行登录 — 普通用户也不例外:他们的卡片位于**模型 → LLM**下,产生的模型、目录和退出登录操作均只对该账号私有。diff --git a/assets/README/README_ES.md b/assets/README/README_ES.mdindex a97c26470..2a017f26c 100644--- a/assets/README/README_ES.md+++ b/assets/README/README_ES.md@@ -60,10 +60,10 @@DeepTutor es un espacio de trabajo de aprendizaje nativo de agentes que conecta tutoría, resolución de problemas, generación de cuestionarios, investigación, visualización y práctica de dominio en un sistema extensible.-- **Un runtime para todos los modos** — Chat, Quiz, Research, Visualize, Solve y Mastery Path corren en el mismo bucle de agente, de modo que cambias el objetivo, no el motor, y el contexto acompaña al estudiante.+- **Un runtime para todos los modos** — Chat, Quiz, Research, Visualize, Solve, Mastery Path e Immersive Reading corren en el mismo bucle de agente, de modo que cambias el objetivo, no el motor, y el contexto acompaña al estudiante.- **Contexto de aprendizaje conectado** — Bases de conocimiento, libros, borradores de Co-Writer, cuadernos, bancos de preguntas, personas y Memory están disponibles en todos los flujos de trabajo en lugar de vivir en herramientas aisladas.- **Subagentes y Partners** — consulta una CLI de codificación en vivo (Claude Code, Codex, Gemini, Kimi, opencode o MiMo) o un Partner desde cualquier turno (o importa sus conversaciones pasadas), y ejecuta compañeros IM persistentes con el mismo cerebro.-- **Conocimiento multi-motor** — bibliotecas RAG con versiones: LlamaIndex, PageIndex, GraphRAG, LightRAG o un vault Obsidian vinculado, con análisis de documentos conectable.+- **Conocimiento multi-motor** — bibliotecas RAG con versiones: LlamaIndex, PageIndex, GraphRAG, LightRAG, un LightRAG Server remoto o una biblioteca de Tencent IMA, o un vault Obsidian vinculado, con análisis de documentos conectable.- **Herramientas y habilidades extensibles** — herramientas integradas, servidores MCP, aplicaciones CLI, modelos de generación de imagen / video / voz, y skills de la comunidad instalables desde EduHub.- **Memoria inspectable** — trazas L1, resúmenes de superficie L2 y síntesis L3 hacen visible y editable la personalización, con un Memory Graph que traza cada afirmación hasta su evidencia.@@ -343,7 +343,7 @@ Las herramientas activables por el usuario son `brainstorm`, `web_search`, `papeEl contexto viene en dos tipos: el **contexto de sesión persistente** (subagente, bases de conocimiento, persona, modelo, voz) vive en la barra de herramientas del compositor y persiste entre turnos; las **referencias de un solo uso** (archivos, historial de chat, libros, cuadernos, banco de preguntas, agentes importados) vienen del menú `+` para un único turno.-Chat es también el punto de lanzamiento para capacidades más profundas: **Quiz** para generación de preguntas, **Research** para informes con citas, **Visualize** para gráficos / diagramas / animaciones, y — bajo *More Capabilities* — **Solve** para razonamiento trabajado y **Mastery Path** para flujos de planes de aprendizaje.+Chat es también el punto de lanzamiento para capacidades más profundas: **Quiz** para generación de preguntas, **Visualize** para gráficos / diagramas / animaciones, **Mastery Path** para flujos de planes de aprendizaje, e **Immersive Reading** — un documento abierto junto al hilo, con cada afirmación citada a la página de la que proviene. **Research** para informes con citas y **Solve** para razonamiento trabajado se encuentran bajo *More Capabilities*.</details>@@ -432,7 +432,7 @@ Cada capítulo se compila en bloques tipados — texto, callouts, quizzes, tarje<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Centro de Conocimiento DeepTutor" width="900"></div>-Las bases de conocimiento son las colecciones de documentos detrás del RAG — fundamentan los turnos de Chat, las ediciones de Co-Writer, la generación de Book y las conversaciones de Partner. Lo que las distingue es la **elección de motores de recuperación**: **LlamaIndex** (el predeterminado, vector local + BM25), **PageIndex** (hospedado, recuperación por razonamiento con citas a nivel de página), **GraphRAG** y **LightRAG** (recuperación por grafo de conocimiento), **LightRAG Server** (recuperación delegada a una instancia externa de LightRAG a la que te conectas por HTTP), **Tencent IMA** (una biblioteca que curas en IMA, consultada a través de su OpenAPI), o un vault **Obsidian** vinculado que el tutor lee y escribe en el lugar. Cada KB está vinculada a un motor.+Las bases de conocimiento son las colecciones de documentos detrás del RAG — fundamentan los turnos de Chat, las ediciones de Co-Writer, la generación de Book y las conversaciones de Partner. Lo que las distingue es la **elección de motores de recuperación**: **LlamaIndex** (el predeterminado, vector local + BM25), **PageIndex** (hospedado, recuperación por razonamiento con citas a nivel de página), **GraphRAG** y **LightRAG** (recuperación por grafo de conocimiento), **LightRAG Server** (recuperación delegada a una instancia externa de LightRAG a la que te conectas por HTTP), **Tencent IMA** (una biblioteca que curas en IMA — consultada, explorada y con escritura de vuelta a través de su OpenAPI), o un vault **Obsidian** vinculado que el tutor lee y escribe en el lugar. Cada KB está vinculada a un motor.<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Crear una base de conocimiento" width="900">@@ -449,7 +449,7 @@ Al crear una KB, puedes **crear nueva** (subir documentos y construir un índice<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Hub del Espacio de Aprendizaje DeepTutor" width="900"></div>-El Espacio de Aprendizaje es la capa de biblioteca y personalización — donde viven las cosas que persisten. **Conversaciones y Materiales** guarda tu historial de chat, cuadernos y un banco de preguntas (cada pregunta guardada conserva tu respuesta, la respuesta de referencia y una explicación). **Personalización** guarda rutas de dominio, personas (preajustes de comportamiento como *compañero*, *asistente de investigación*, *profesor*), skills (guías `SKILL.md` que el modelo lee bajo demanda), **Servicios MCP** — una tienda curada de servidores MCP alojados que instalas para ti mismo con un clic, además de cualquier servidor remoto que configures por URL — y **Aplicaciones CLI**, herramientas de línea de comandos del catálogo [CLI-Anything](https://github.com/HKUDS/CLI-Anything) que el agente de chat invoca directamente, con la guía de uso propia de cada aplicación cargada bajo demanda. Todo aquí se puede reutilizar desde Chat, Partners, Co-Writer y Book.+El Espacio de Aprendizaje es la capa de biblioteca y personalización — donde viven las cosas que persisten. **Conversaciones y Materiales** guarda tu historial de chat, cuadernos — ahora con su propia consola, con registros que se mueven o copian entre cuadernos y una exportación a Markdown — y un banco de preguntas (cada pregunta guardada conserva tu respuesta, la respuesta de referencia y una explicación). **Personalización** guarda rutas de dominio, personas (preajustes de comportamiento como *compañero*, *asistente de investigación*, *profesor*), skills (guías `SKILL.md` que el modelo lee bajo demanda), **Servicios MCP** — una tienda curada de servidores MCP alojados que instalas para ti mismo con un clic, además de cualquier servidor remoto que configures por URL — y **Aplicaciones CLI**, herramientas de línea de comandos del catálogo [CLI-Anything](https://github.com/HKUDS/CLI-Anything) que el agente de chat invoca directamente, con la guía de uso propia de cada aplicación cargada bajo demanda. Todo aquí se puede reutilizar desde Chat, Partners, Co-Writer y Book.<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importar skills desde EduHub" width="900">@@ -489,7 +489,7 @@ Settings es el panel de control operativo, con una tira de estado en vivo (estad<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Configuración de apariencia de DeepTutor y temas" width="900"></div>-La mayoría de las secciones usan un flujo de borrador y aplicación, de modo que puedes probar un proveedor antes de confirmarlo. Cuatro temas se incluyen por defecto — Default, Cream, Dark y Glass. Los archivos `.env` de la raíz del proyecto se ignoran intencionalmente; la configuración de runtime vive bajo `data/user/settings/*.json` a menos que `DEEPTUTOR_HOME` o `deeptutor start --home` apunten la app en otro lugar.+La mayoría de las secciones usan un flujo de borrador y aplicación, de modo que puedes probar un proveedor antes de confirmarlo. También puedes simplemente pedirlo en Chat: el asistente lee la configuración actual, aplica un cambio y te dice si necesita un reinicio o una reindexación — probando un modelo nuevo antes de confirmarlo, de modo que no puede cambiarse a sí mismo hacia algo inalcanzable. Las claves API nunca pasan por el modelo, que en su lugar abre el formulario correspondiente para ti. Cuatro temas se incluyen por defecto — Default, Cream, Dark y Glass. Los archivos `.env` de la raíz del proyecto se ignoran intencionalmente; la configuración de runtime vive bajo `data/user/settings/*.json` a menos que `DEEPTUTOR_HOME` o `deeptutor start --home` apunten la app en otro lugar.**OpenAI Codex OAuth (experimental).** Elegir **OpenAI Codex** bajo Models → LLM reemplaza los campos de clave API por un inicio de sesión en el navegador que se ejecuta contra tu propio plan de ChatGPT, de modo que no se necesita `OPENAI_API_KEY`. Los tokens viven solo en `data/system/user-secrets/<owner>/private/openai-codex/` — en el despliegue multi-contenedor con Compose, fuera de cualquier árbol al que el sandbox de ejecución pueda acceder — y DeepTutor nunca lee ni modifica tu inicio de sesión de la CLI `~/.codex`. La lista de modelos proviene del catálogo en vivo de esa cuenta; iniciar sesión publica el perfil, pero este solo se convierte en el modelo activo cuando todavía no hay ningún LLM configurado, de modo que nunca redirige un despliegue a tus espaldas. Como un token autoriza el plan de una sola persona, el perfil no se puede compartir a través de permisos de usuario — cada cuenta inicia sesión por sí misma, incluidos los usuarios comunes: su tarjeta se encuentra bajo Models → LLM, y los modelos, el catálogo y el cierre de sesión resultantes permanecen privados para esa cuenta, y el navegador debe poder alcanzar la máquina que ejecuta el backend (en un servidor remoto, ejecuta `deeptutor provider login openai-codex` allí en su lugar). Los errores de cuota y las fallas del catálogo se reportan tal cual y nunca recurren a un proveedor de pago. Esta ruta de compatibilidad es experimental: la interfaz upstream puede cambiar.diff --git a/assets/README/README_FR.md b/assets/README/README_FR.mdindex 93bd82108..6af9032a2 100644--- a/assets/README/README_FR.md+++ b/assets/README/README_FR.md@@ -60,10 +60,10 @@DeepTutor est un espace de travail d'apprentissage natif à l'agent qui connecte le tutorat, la résolution de problèmes, la génération de quiz, la recherche, la visualisation et la pratique de maîtrise dans un système extensible.-- **Un seul runtime pour chaque mode** — Chat, Quiz, Research, Visualize, Solve et Mastery Path fonctionnent sur la même boucle d'agent, vous changez donc l'objectif, pas le moteur, et le contexte suit l'apprenant.+- **Un seul runtime pour chaque mode** — Chat, Quiz, Research, Visualize, Solve, Mastery Path et Immersive Reading fonctionnent sur la même boucle d'agent, vous changez donc l'objectif, pas le moteur, et le contexte suit l'apprenant.- **Contexte d'apprentissage connecté** — Les bases de connaissances, les livres, les brouillons Co-Writer, les carnets, les banques de questions, les personas et la Memory restent disponibles dans tous les flux de travail au lieu de vivre dans des outils isolés.- **Sous-agents et Partners** — consultez une CLI de codage en direct (Claude Code, Codex, Gemini, Kimi, opencode ou MiMo) ou un Partner depuis n'importe quel tour (ou importez leurs conversations passées), et exécutez des compagnons IM persistants sur le même cerveau.-- **Connaissances multi-moteur** — bibliothèques RAG versionnées via LlamaIndex, PageIndex, GraphRAG, LightRAG, ou un vault Obsidian lié, avec une analyse de documents enfichable.+- **Connaissances multi-moteur** — bibliothèques RAG versionnées via LlamaIndex, PageIndex, GraphRAG, LightRAG, un LightRAG Server distant ou une bibliothèque Tencent IMA, ou un vault Obsidian lié, avec une analyse de documents enfichable.- **Outils et compétences extensibles** — outils intégrés, serveurs MCP, applications CLI, modèles de génération d'images / vidéos / voix, et compétences communautaires installables depuis EduHub.- **Mémoire inspectable** — les traces L1, les résumés de surface L2 et la synthèse L3 rendent la personnalisation visible et modifiable, avec un Memory Graph qui retrace chaque affirmation jusqu'à son evidence.@@ -353,7 +353,7 @@ Les outils basculables par l'utilisateur sont `brainstorm`, `web_search`, `paperLe contexte se présente en deux types : le **contexte de session persistant** (sous-agent, bases de connaissances, persona, modèle, voix) vit sur la barre d'outils du compositeur et persiste entre les tours ; les **références ponctuelles** (fichiers, historique de chat, livres, carnets, banque de questions, agents importés) proviennent du menu `+` pour un seul tour.-Chat est aussi le point de lancement pour des capacités plus profondes : **Quiz** pour la génération de questions, **Research** pour les rapports cités, **Visualize** pour les graphiques / diagrammes / animations, et — sous *Plus de Capacités* — **Solve** pour le raisonnement guidé et **Mastery Path** pour les flux de plans d'apprentissage.+Chat est aussi le point de lancement pour des capacités plus profondes : **Quiz** pour la génération de questions, **Visualize** pour les graphiques / diagrammes / animations, **Mastery Path** pour les flux de plans d'apprentissage, et **Immersive Reading** — un document ouvert à côté du fil, avec chaque affirmation citée à la page dont elle provient. **Research** pour les rapports cités et **Solve** pour le raisonnement guidé se trouvent sous *Plus de Capacités*.</details>@@ -442,7 +442,7 @@ Chaque chapitre se compile en blocs typés — texte, encadrés, quiz, fiches, c<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Knowledge Center de DeepTutor" width="900"></div>-Les bases de connaissances sont les collections de documents derrière le RAG — elles ancrent les tours de Chat, les éditions Co-Writer, la génération de Book et les conversations Partner. Ce qui est distinctif est un **choix de moteurs de récupération** : **LlamaIndex** (par défaut, vecteur local + BM25), **PageIndex** (hébergé, récupération par raisonnement avec citations au niveau de la page), **GraphRAG** et **LightRAG** (récupération par graphe de connaissances), **LightRAG Server** (récupération déléguée à une instance LightRAG externe connectée via HTTP), **Tencent IMA** (une bibliothèque que vous constituez dans IMA, interrogée via son OpenAPI), ou un vault **Obsidian** lié que le tuteur lit et écrit en place. Chaque KB est liée à un moteur.+Les bases de connaissances sont les collections de documents derrière le RAG — elles ancrent les tours de Chat, les éditions Co-Writer, la génération de Book et les conversations Partner. Ce qui est distinctif est un **choix de moteurs de récupération** : **LlamaIndex** (par défaut, vecteur local + BM25), **PageIndex** (hébergé, récupération par raisonnement avec citations au niveau de la page), **GraphRAG** et **LightRAG** (récupération par graphe de connaissances), **LightRAG Server** (récupération déléguée à une instance LightRAG externe connectée via HTTP), **Tencent IMA** (une bibliothèque que vous constituez dans IMA — interrogée, parcourue et mise à jour via son OpenAPI), ou un vault **Obsidian** lié que le tuteur lit et écrit en place. Chaque KB est liée à un moteur.<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Créer une base de connaissances" width="900">@@ -459,7 +459,7 @@ En créant une KB, vous choisissez soit de **créer nouvelle** (uploadez des doc<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Hub Learning Space de DeepTutor" width="900"></div>-Learning Space est la couche de bibliothèque et de personnalisation — là où vivent les choses qui persistent. **Conversations & Matériaux** contient votre historique de chat, vos carnets et une banque de questions (chaque question sauvegardée conserve votre réponse, la réponse de référence et une explication). **Personnalisation** contient les parcours de maîtrise, les personas (préréglages de comportement comme *pair*, *assistant de recherche*, *enseignant*), les compétences (livrets de jeu `SKILL.md` que le modèle lit à la demande), les **Services MCP** — une boutique organisée de serveurs MCP hébergés que vous installez pour vous-même en un clic, plus tout serveur distant que vous configurez par URL — et les **Applications CLI**, des outils en ligne de commande du catalogue [CLI-Anything](https://github.com/HKUDS/CLI-Anything) que l'agent de chat appelle directement, chaque application chargeant son propre guide d'utilisation à la demande. Tout ici peut être réutilisé depuis Chat, Partners, Co-Writer et Book.+Learning Space est la couche de bibliothèque et de personnalisation — là où vivent les choses qui persistent. **Conversations & Matériaux** contient votre historique de chat, vos carnets — désormais leur propre console, avec des enregistrements qui se déplacent ou se copient entre carnets et un export Markdown — et une banque de questions (chaque question sauvegardée conserve votre réponse, la réponse de référence et une explication). **Personnalisation** contient les parcours de maîtrise, les personas (préréglages de comportement comme *pair*, *assistant de recherche*, *enseignant*), les compétences (livrets de jeu `SKILL.md` que le modèle lit à la demande), les **Services MCP** — une boutique organisée de serveurs MCP hébergés que vous installez pour vous-même en un clic, plus tout serveur distant que vous configurez par URL — et les **Applications CLI**, des outils en ligne de commande du catalogue [CLI-Anything](https://github.com/HKUDS/CLI-Anything) que l'agent de chat appelle directement, chaque application chargeant son propre guide d'utilisation à la demande. Tout ici peut être réutilisé depuis Chat, Partners, Co-Writer et Book.<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importer des compétences depuis EduHub" width="900">@@ -499,7 +499,7 @@ Settings est le plan de contrôle opérationnel, avec une bande de statut en dir<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Paramètres d'apparence et thèmes DeepTutor" width="900"></div>-La plupart des sections utilisent un flux brouillon-et-application, vous pouvez donc tester un fournisseur avant de vous y engager. Quatre thèmes sont livrés dans la boîte — Default, Cream, Dark et Glass. Les fichiers `.env` à la racine du projet sont intentionnellement ignorés ; la configuration d'exécution vit sous `data/user/settings/*.json` sauf si `DEEPTUTOR_HOME` ou `deeptutor start --home` pointe l'application ailleurs.+La plupart des sections utilisent un flux brouillon-et-application, vous pouvez donc tester un fournisseur avant de vous y engager. Vous pouvez aussi simplement demander dans Chat : l'assistant lit la configuration actuelle, applique un changement, et indique s'il nécessite un redémarrage ou une réindexation — sondant un nouveau modèle avant de s'y engager, afin qu'il ne puisse jamais se basculer lui-même vers quelque chose d'inaccessible. Les clés API ne transitent jamais par le modèle, qui ouvre à la place le formulaire correspondant pour vous. Quatre thèmes sont livrés dans la boîte — Default, Cream, Dark et Glass. Les fichiers `.env` à la racine du projet sont intentionnellement ignorés ; la configuration d'exécution vit sous `data/user/settings/*.json` sauf si `DEEPTUTOR_HOME` ou `deeptutor start --home` pointe l'application ailleurs.**OAuth OpenAI Codex (expérimental).** Choisir **OpenAI Codex** sous Modèles → LLM remplace les champs de clé API par une connexion navigateur qui s'exécute contre votre propre forfait ChatGPT, donc aucune `OPENAI_API_KEY` n'est nécessaire. Les jetons résident uniquement dans `data/system/user-secrets/<owner>/private/openai-codex/` — dans le déploiement Compose multi-conteneurs, en dehors de tout arbre que le sandbox d'exécution peut atteindre — et DeepTutor ne lit ni ne modifie jamais votre connexion CLI `~/.codex`. La liste de modèles provient du catalogue en direct de ce compte ; se connecter publie le profil, mais celui-ci ne devient le modèle actif que si aucun LLM n'est encore configuré, donc cela ne redirige jamais un déploiement à votre insu. Parce qu'un jeton autorise le forfait d'une seule personne, le profil n'est pas partageable via les attributions utilisateur — chaque compte doit se connecter pour lui-même, utilisateurs ordinaires compris : leur carte se trouve sous Modèles → LLM, et les modèles, le catalogue et la déconnexion qui en résultent restent privés à ce compte, et le navigateur doit pouvoir atteindre la machine qui exécute le backend (sur un serveur distant, exécutez plutôt `deeptutor provider login openai-codex` là-bas). Les erreurs de quota et les échecs de catalogue sont rapportés tels quels et ne basculent jamais vers un fournisseur payant. Ce chemin de compatibilité est expérimental : l'interface en amont peut changer.diff --git a/assets/README/README_HI.md b/assets/README/README_HI.mdindex 61e32f954..d3f190325 100644--- a/assets/README/README_HI.md+++ b/assets/README/README_HI.md@@ -60,10 +60,10 @@DeepTutor एक agent-native learning workspace है जो tutoring, problem solving, quiz generation, research, visualization, और mastery practice को एक extensible system में जोड़ता है।-- **हर मोड के लिए एक रनटाइम** — Chat, Quiz, Research, Visualize, Solve और Mastery Path एक ही agent loop पर चलते हैं, इसलिए आप objective बदलते हैं, engine नहीं, और context learner के साथ बना रहता है।+- **हर मोड के लिए एक रनटाइम** — Chat, Quiz, Research, Visualize, Solve, Mastery Path और Immersive Reading एक ही agent loop पर चलते हैं, इसलिए आप objective बदलते हैं, engine नहीं, और context learner के साथ बना रहता है।- **जुड़ा हुआ लर्निंग कॉन्टेक्स्ट** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, और Memory सभी workflows में उपलब्ध रहते हैं, isolated tools में बंद रहने की बजाय।- **सब-एजेंट और Partners** — किसी भी turn से एक live coding CLI (Claude Code, Codex, Gemini, Kimi, opencode, या MiMo) या एक Partner से सलाह लें (या उनकी पिछली conversations import करें), और same brain पर persistent IM companions चलाएं।-- **मल्टी-इंजन नॉलेज** — LlamaIndex, PageIndex, GraphRAG, LightRAG या linked Obsidian vault के साथ versioned RAG libraries, pluggable document parsing के साथ।+- **मल्टी-इंजन नॉलेज** — LlamaIndex, PageIndex, GraphRAG, LightRAG, एक remote LightRAG Server या Tencent IMA library, या एक linked Obsidian vault के साथ versioned RAG libraries, pluggable document parsing के साथ।- **एक्सटेंसिबल टूल्स और स्किल्स** — built-in tools, MCP servers, CLI apps, image / video / voice generation models, और EduHub से installable community skills।- **इंस्पेक्टेबल मेमोरी** — L1 traces, L2 surface summaries, और L3 synthesis personalization को visible और editable बनाते हैं, एक Memory Graph के साथ जो हर दावे को उसके साक्ष्य तक trace करता है।@@ -331,7 +331,7 @@ User-toggleable tools हैं `brainstorm`, `web_search`, `paper_search`, `reaContext दो प्रकार की होती है: **sticky session context** (subagent, knowledge bases, persona, model, voice) composer toolbar पर रहती है और turns के पार persist करती है; **एक-बार references** (files, chat history, books, notebooks, question bank, imported agents) एक single turn के लिए `+` menu से आते हैं।-Chat deeper capabilities के लिए launch point भी है: **Quiz** question generation के लिए, **Research** cited reports के लिए, **Visualize** charts / diagrams / animations के लिए, और — *More Capabilities* के नीचे — **Solve** worked reasoning के लिए और **Mastery Path** learning-plan flows के लिए।+Chat deeper capabilities के लिए launch point भी है: **Quiz** question generation के लिए, **Visualize** charts / diagrams / animations के लिए, **Mastery Path** learning-plan flows के लिए, और **Immersive Reading** — एक document जो thread के बगल में खुला रहता है, हर दावे को उस page तक cite करते हुए जहां से वह आया। **Research** cited reports के लिए और **Solve** worked reasoning के लिए *More Capabilities* के नीचे रहते हैं।</details>@@ -420,7 +420,7 @@ Book selected sources को एक interactive **living book** में बद<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900"></div>-Knowledge bases RAG के पीछे document collections हैं — वे Chat turns, Co-Writer edits, Book generation, और Partner conversations को ground करते हैं। जो distinctive है वह है **retrieval engines का choice**: **LlamaIndex** (default, local vector + BM25), **PageIndex** (hosted, reasoning retrieval with page-level citations), **GraphRAG** और **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval एक external LightRAG instance पर offload किया जाता है जिसे आप HTTP पर connect करते हैं), **Tencent IMA** (एक library जिसे आप IMA में curate करते हैं, इसके OpenAPI पर search किया जाता है), या एक linked **Obsidian** vault जिसे tutor in-place पढ़ता और लिखता है। हर KB एक engine से bound होती है।+Knowledge bases RAG के पीछे document collections हैं — वे Chat turns, Co-Writer edits, Book generation, और Partner conversations को ground करते हैं। जो distinctive है वह है **retrieval engines का choice**: **LlamaIndex** (default, local vector + BM25), **PageIndex** (hosted, reasoning retrieval with page-level citations), **GraphRAG** और **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval एक external LightRAG instance पर offload किया जाता है जिसे आप HTTP पर connect करते हैं), **Tencent IMA** (एक library जिसे आप IMA में curate करते हैं — इसके OpenAPI पर search, browse, और write back किया जाता है), या एक linked **Obsidian** vault जिसे tutor in-place पढ़ता और लिखता है। हर KB एक engine से bound होती है।<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="एक knowledge base बनाएं" width="900">@@ -437,7 +437,7 @@ KB बनाते समय, आप either **नया create** करते<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Space hub" width="900"></div>-Learning Space library और personalization layer है — वह जगह जहां persist होने वाली चीजें रहती हैं। **Conversations & Materials** में आपका chat history, notebooks, और एक question bank है (हर saved question आपका जवाब, reference answer, और एक explanation रखता है)। **Personalization** में mastery paths, personas (behavior presets जैसे *peer*, *research-assistant*, *teacher*), skills (`SKILL.md` playbooks जिन्हें model on-demand पढ़ता है), **MCP Services** — hosted MCP servers का एक curated store जिन्हें आप एक click में खुद के लिए install करते हैं, साथ ही कोई भी remote server जिसे आप URL से configure करते हैं — और **CLI Apps** हैं, [CLI-Anything](https://github.com/HKUDS/CLI-Anything) catalog से command-line tools जिन्हें chat agent directly call करता है, हर app की अपनी usage guide on-demand load होती है। यहां सब कुछ Chat, Partners, Co-Writer, और Book से reuse किया जा सकता है।+Learning Space library और personalization layer है — वह जगह जहां persist होने वाली चीजें रहती हैं। **Conversations & Materials** में आपका chat history, notebooks — अब अपना खुद का console, जिसमें records notebooks के बीच move या copy होते हैं और एक Markdown export होता है — और एक question bank है (हर saved question आपका जवाब, reference answer, और एक explanation रखता है)। **Personalization** में mastery paths, personas (behavior presets जैसे *peer*, *research-assistant*, *teacher*), skills (`SKILL.md` playbooks जिन्हें model on-demand पढ़ता है), **MCP Services** — hosted MCP servers का एक curated store जिन्हें आप एक click में खुद के लिए install करते हैं, साथ ही कोई भी remote server जिसे आप URL से configure करते हैं — और **CLI Apps** हैं, [CLI-Anything](https://github.com/HKUDS/CLI-Anything) catalog से command-line tools जिन्हें chat agent directly call करता है, हर app की अपनी usage guide on-demand load होती है। यहां सब कुछ Chat, Partners, Co-Writer, और Book से reuse किया जा सकता है।<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="EduHub से skills import करें" width="900">@@ -477,7 +477,7 @@ Settings operational control plane है, एक live status strip (Backend hea<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor appearance settings and themes" width="900"></div>-अधिकांश sections एक draft-and-apply flow उपयोग करते हैं, इसलिए आप provider को commit करने से पहले test कर सकते हैं। चार themes box में आते हैं — Default, Cream, Dark, और Glass। Project-root `.env` files जानबूझकर ignored हैं; runtime configuration `data/user/settings/*.json` के नीचे रहती है जब तक कि `DEEPTUTOR_HOME` या `deeptutor start --home` app को कहीं और point न करे।+अधिकांश sections एक draft-and-apply flow उपयोग करते हैं, इसलिए आप provider को commit करने से पहले test कर सकते हैं। आप बस Chat में भी पूछ सकते हैं: assistant current configuration पढ़ता है, एक change apply करता है, और बताता है कि उसे restart या re-index चाहिए या नहीं — एक नए model को commit करने से पहले probe करते हुए, इसलिए यह खुद को किसी unreachable चीज़ पर switch नहीं कर सकता। API keys कभी model से नहीं गुजरतीं, जो इसकी बजाय आपके लिए matching form खोल देता है। चार themes box में आते हैं — Default, Cream, Dark, और Glass। Project-root `.env` files जानबूझकर ignored हैं; runtime configuration `data/user/settings/*.json` के नीचे रहती है जब तक कि `DEEPTUTOR_HOME` या `deeptutor start --home` app को कहीं और point न करे।**OpenAI Codex OAuth (experimental).** **Models → LLM** के तहत **OpenAI Codex** चुनना API-key fields को एक browser sign-in से replace कर देता है जो आपके अपने ChatGPT plan के विरुद्ध चलता है, इसलिए किसी `OPENAI_API_KEY` की जरूरत नहीं। Tokens केवल `data/system/user-secrets/<owner>/private/openai-codex/` में रहते हैं — multi-container Compose deployment में, उस हर tree के बाहर जहां exec sandbox पहुंच सकता है — और DeepTutor कभी आपकी `~/.codex` CLI login को न तो पढ़ता है न ही modify करता है। Model list उस account के live catalog से आती है; sign in करना profile को publish करता है लेकिन यह active model तभी बनता है जब अभी तक कोई LLM configure न हो, इसलिए यह कभी भी आपकी जानकारी के बिना किसी deployment को repoint नहीं करता। क्योंकि एक token एक व्यक्ति के plan को authorize करता है, profile user grants के जरिए shareable नहीं है — हर account खुद के लिए sign in करता है, सामान्य users भी शामिल: उनका card **Models → LLM** के तहत रहता है, और resulting models, catalog, और sign-out उस account के लिए private रहते हैं।diff --git a/assets/README/README_JA.md b/assets/README/README_JA.mdindex 046823d6d..16bfc69f6 100644--- a/assets/README/README_JA.md+++ b/assets/README/README_JA.md@@ -60,10 +60,10 @@DeepTutorは、個別指導、問題解決、クイズ生成、研究、ビジュアライゼーション、習熟度練習を1つの拡張可能なシステムに統合したエージェントネイティブな学習ワークスペースです。-- **すべてのモードで1つのランタイム** — Chat、Quiz、Research、Visualize、Solve、Mastery Pathが同じエージェントループで実行されるため、エンジンではなく目的を切り替えます。コンテキストは学習者とともに移動します。+- **すべてのモードで1つのランタイム** — Chat、Quiz、Research、Visualize、Solve、Mastery Path、Immersive Readingが同じエージェントループで実行されるため、エンジンではなく目的を切り替えます。コンテキストは学習者とともに移動します。- **接続された学習コンテキスト** — 知識ベース、本、Co-Writerの下書き、ノートブック、問題バンク、ペルソナ、Memoryが孤立したツールに閉じ込められることなく、すべてのワークフローで利用可能です。- **サブエージェントとPartners** — 任意のターンからライブのコーディングCLI(Claude Code、Codex、Gemini、Kimi、opencode、MiMo)またはPartnerに相談(または過去の会話をインポート)し、同じブレインで永続的なIMコンパニオンを実行します。-- **マルチエンジン知識** — LlamaIndex、PageIndex、GraphRAG、LightRAG、またはリンクされたObsidianボールトにまたがるバージョン管理されたRAGライブラリ(プラグ可能なドキュメント解析付き)。+- **マルチエンジン知識** — LlamaIndex、PageIndex、GraphRAG、LightRAG、リモートのLightRAG ServerまたはTencent IMAライブラリ、あるいはリンクされたObsidianボールトにまたがるバージョン管理されたRAGライブラリ(プラグ可能なドキュメント解析付き)。- **拡張可能なツールとスキル** — 組み込みツール、MCPサーバー、CLIアプリ、画像/ビデオ/音声生成モデル、EduHubからインストール可能なコミュニティスキル。- **検査可能なメモリ** — L1トレース、L2サーフェスサマリー、L3合成によりパーソナライズが可視化・編集可能となり、Memory Graphですべての主張を証拠まで追跡できます。@@ -331,7 +331,7 @@ Chatはデフォルト機能であり、ほとんどの作業が始まる場所コンテキストには2種類あります:**スティッキーセッションコンテキスト**(サブエージェント、知識ベース、ペルソナ、モデル、音声)はコンポーザーツールバーに常駐し、ターンをまたいで持続します。**ワンタイム参照**(ファイル、チャット履歴、本、ノートブック、問題バンク、インポートしたエージェント)は単一のターンのために`+`メニューから追加します。-Chatはより深い機能へのローンチポイントでもあります:問題生成には**Quiz**、引用付きレポートには**Research**、チャート/図/アニメーションには**Visualize**、推論問題解決には**Solve**(「その他の機能」下)、学習計画フローには**Mastery Path**。+Chatはより深い機能へのローンチポイントでもあります:問題生成には**Quiz**、チャート/図/アニメーションには**Visualize**、学習計画フローには**Mastery Path**、そしてスレッドの横でドキュメントを開き、あらゆる主張をその出典ページまで引用する**Immersive Reading**。引用付きレポートの**Research**と推論問題解決の**Solve**は「その他の機能」の下にあります。</details>@@ -420,7 +420,7 @@ Bookは選択したソースをインタラクティブな**生きている本**<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900"></div>-知識ベースはRAGの背後にあるドキュメントコレクションです — Chatターン、Co-Writerの編集、Book生成、Partnerの会話をグラウンドします。特徴的なのは**検索エンジンの選択**です:**LlamaIndex**(デフォルト、ローカルベクター + BM25)、**PageIndex**(ホスト型、ページレベル引用付き推論検索)、**GraphRAG**と**LightRAG**(知識グラフ検索)、**LightRAG Server**(HTTP経由で接続する外部LightRAGインスタンスに検索をオフロード)、**Tencent IMA**(IMAでキュレートするライブラリで、そのOpenAPI経由で検索)、またはチューターがその場で読み書きするリンクされた**Obsidian**ボールト。各KBは1つのエンジンにバインドされます。+知識ベースはRAGの背後にあるドキュメントコレクションです — Chatターン、Co-Writerの編集、Book生成、Partnerの会話をグラウンドします。特徴的なのは**検索エンジンの選択**です:**LlamaIndex**(デフォルト、ローカルベクター + BM25)、**PageIndex**(ホスト型、ページレベル引用付き推論検索)、**GraphRAG**と**LightRAG**(知識グラフ検索)、**LightRAG Server**(HTTP経由で接続する外部LightRAGインスタンスに検索をオフロード)、**Tencent IMA**(IMAでキュレートするライブラリで、そのOpenAPI経由で検索・閲覧・書き戻しが可能)、またはチューターがその場で読み書きするリンクされた**Obsidian**ボールト。各KBは1つのエンジンにバインドされます。<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="知識ベースの作成" width="900">@@ -437,7 +437,7 @@ KBを作成する際は、**新規作成**(ドキュメントをアップロ<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Spaceハブ" width="900"></div>-Learning Spaceはライブラリとパーソナライゼーション層です — 永続するものが置かれる場所です。**会話と素材**にはチャット履歴、ノートブック、問題バンク(各保存された質問にはあなたの回答、参照回答、説明が含まれます)が含まれます。**パーソナライゼーション**には習熟パス、ペルソナ(*peer*、*research-assistant*、*teacher*などの動作プリセット)、スキル(モデルがオンデマンドで読み取る`SKILL.md`プレイブック)、**MCPサービス**(ワンクリックで自分用にインストールできるホスト型MCPサーバーのキュレートされたストアと、URLで設定できる任意のリモートサーバー)、そして**CLIアプリ**(チャットエージェントが直接呼び出す[CLI-Anything](https://github.com/HKUDS/CLI-Anything)カタログのコマンドラインツールで、各アプリ独自の使用ガイドがオンデマンドで読み込まれます)が含まれます。ここのものはすべてChat、Partners、Co-Writer、Bookから再利用できます。+Learning Spaceはライブラリとパーソナライゼーション層です — 永続するものが置かれる場所です。**会話と素材**には、チャット履歴、ノートブック — 今や専用のコンソールを持ち、レコードはノートブック間を移動・コピーでき、Markdownへのエクスポートも可能です — 、そして問題バンク(各保存された質問にはあなたの回答、参照回答、説明が含まれます)が含まれます。**パーソナライゼーション**には習熟パス、ペルソナ(*peer*、*research-assistant*、*teacher*などの動作プリセット)、スキル(モデルがオンデマンドで読み取る`SKILL.md`プレイブック)、**MCPサービス**(ワンクリックで自分用にインストールできるホスト型MCPサーバーのキュレートされたストアと、URLで設定できる任意のリモートサーバー)、そして**CLIアプリ**(チャットエージェントが直接呼び出す[CLI-Anything](https://github.com/HKUDS/CLI-Anything)カタログのコマンドラインツールで、各アプリ独自の使用ガイドがオンデマンドで読み込まれます)が含まれます。ここのものはすべてChat、Partners、Co-Writer、Bookから再利用できます。<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="EduHubからスキルをインポート" width="900">@@ -477,7 +477,7 @@ Settingsはオペレーションコントロールプレーンで、ライブス<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor外観設定とテーマ" width="900"></div>-ほとんどのセクションはドラフトと適用フローを使用するため、コミットする前にプロバイダーをテストできます。4つのテーマが箱に入っています:Default、Cream、Dark、Glass。プロジェクトルートの`.env`ファイルは意図的に無視されます。ランタイム設定は`DEEPTUTOR_HOME`または`deeptutor start --home`でアプリを別の場所に向けない限り、`data/user/settings/*.json`に保存されます。+ほとんどのセクションはドラフトと適用フローを使用するため、コミットする前にプロバイダーをテストできます。Chatで直接依頼するだけでも構いません:アシスタントが現在の設定を読み取り、変更を適用し、再起動または再インデックスが必要かどうかを教えてくれます — コミットする前に新しいモデルをプローブするため、到達不能な設定に自分自身を切り替えてしまうことはありません。APIキーがモデルを経由することは決してなく、代わりに該当するフォームを開いてくれます。4つのテーマが箱に入っています:Default、Cream、Dark、Glass。プロジェクトルートの`.env`ファイルは意図的に無視されます。ランタイム設定は`DEEPTUTOR_HOME`または`deeptutor start --home`でアプリを別の場所に向けない限り、`data/user/settings/*.json`に保存されます。**OpenAI Codex OAuth(実験的)。** Models → LLMで**OpenAI Codex**を選択すると、APIキー入力欄の代わりに、あなた自身のChatGPTプランに対して実行されるブラウザサインインに置き換わるため、`OPENAI_API_KEY`は不要になります。トークンは`data/system/user-secrets/<owner>/private/openai-codex/`にのみ保存され — マルチコンテナのComposeデプロイメントでは、execサンドボックスが到達できるすべてのツリーの外側にあります — DeepTutorがあなたの`~/.codex` CLIログインを読み取ったり変更したりすることは決してありません。モデルリストはそのアカウントのライブカタログから取得されます。サインインするとプロフィールは公開されますが、まだLLMが設定されていない場合にのみアクティブモデルになるため、気づかないうちにデプロイメントの向き先を変えることはありません。トークンは1人のプランを認可するものであるため、このプロフィールはユーザーグラントを通じて共有することはできません — 各アカウントは自分自身でサインインする必要があり(一般ユーザーも含め、そのカードはModels → LLMの下に置かれ、結果として得られるモデル、カタログ、サインアウトはそのアカウントのみに閉じます)、ブラウザはバックエンドを実行しているマシンに到達できなければなりません(リモートサーバーでは、代わりにそこで`deeptutor provider login openai-codex`を実行してください)。クォータエラーとカタログの失敗はそのまま報告され、有料プロバイダーへの自動フォールバックは決して行われません。この互換性パスは実験的です:上流のインターフェースは変更される可能性があります。diff --git a/assets/README/README_PL.md b/assets/README/README_PL.mdindex 816186fe0..e0f356110 100644--- a/assets/README/README_PL.md+++ b/assets/README/README_PL.md@@ -60,10 +60,10 @@DeepTutor to natywne dla agentów środowisko nauki, które łączy korepetycje, rozwiązywanie problemów, generowanie quizów, badania, wizualizacje i ćwiczenia opanowania wiedzy w jednym rozszerzalnym systemie.-- **Jedno środowisko dla wszystkich trybów** — Chat, Quiz, Research, Visualize, Solve i Mastery Path działają na tej samej pętli agenta, więc zmieniasz cel, a nie silnik, a kontekst podąża za uczącym się.+- **Jedno środowisko dla wszystkich trybów** — Chat, Quiz, Research, Visualize, Solve, Mastery Path i Immersive Reading działają na tej samej pętli agenta, więc zmieniasz cel, a nie silnik, a kontekst podąża za uczącym się.- **Połączony kontekst uczenia się** — bazy wiedzy, książki, szkice Co-Writer, notatniki, banki pytań, persony i Memory są dostępne we wszystkich przepływach pracy zamiast żyć w izolowanych narzędziach.- **Subagenty i Partners** — konsultuj działający CLI kodowania (Claude Code, Codex, Gemini, Kimi, opencode lub MiMo) lub Partner z dowolnej tury (lub importuj ich poprzednie konwersacje) i uruchamiaj stałych towarzyszy IM na tym samym mózgu.-- **Wielosilnikowa wiedza** — wersjonowane biblioteki RAG z LlamaIndex, PageIndex, GraphRAG, LightRAG lub podłączonym vault Obsidian, z podłączalnym parsowaniem dokumentów.+- **Wielosilnikowa wiedza** — wersjonowane biblioteki RAG z LlamaIndex, PageIndex, GraphRAG, LightRAG, zdalnym LightRAG Server lub biblioteką Tencent IMA, lub podłączonym vault Obsidian, z podłączalnym parsowaniem dokumentów.- **Rozszerzalne narzędzia i umiejętności** — wbudowane narzędzia, serwery MCP, aplikacje CLI, modele generowania obrazów / wideo / głosu oraz instalowalne umiejętności społecznościowe z EduHub.- **Inspektowalna pamięć** — ślady L1, podsumowania powierzchni L2 i synteza L3 sprawiają, że personalizacja jest widoczna i edytowalna, a Memory Graph śledzi każde twierdzenie z powrotem do jego dowodów.@@ -331,7 +331,7 @@ Narzędzia przełączalne przez użytkownika to `brainstorm`, `web_search`, `papKontekst dzieli się na dwa rodzaje: **trwały kontekst sesji** (subagent, bazy wiedzy, persona, model, głos) żyje na pasku narzędziowym kompozytora i jest zachowany przez tury; **jednorazowe odwołania** (pliki, historia czatu, książki, notatniki, bank pytań, zaimportowani agenci) pochodzą z menu `+` dla jednej tury.-Chat jest również punktem startowym dla głębszych możliwości: **Quiz** do generowania pytań, **Research** do cytowanych raportów, **Visualize** do wykresów / diagramów / animacji i — w sekcji *More Capabilities* — **Solve** do wypracowanego rozumowania i **Mastery Path** do przepływów planu nauki.+Chat jest również punktem startowym dla głębszych możliwości: **Quiz** do generowania pytań, **Visualize** do wykresów / diagramów / animacji, **Mastery Path** do przepływów planu nauki i **Immersive Reading** — dokument otwarty obok wątku, gdzie każde twierdzenie jest cytowane do strony, z której pochodzi. **Research** do cytowanych raportów i **Solve** do wypracowanego rozumowania znajdują się w sekcji *More Capabilities*.</details>@@ -420,7 +420,7 @@ Każdy rozdział kompiluje się do typowanych bloków — tekst, callouts, quizy<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Knowledge Center DeepTutor" width="900"></div>-Bazy wiedzy to kolekcje dokumentów za RAG — ugruntowują tury Chat, edycje Co-Writer, generowanie Book i konwersacje Partner. Wyróżnikiem jest **wybór silnika wyszukiwania**: **LlamaIndex** (domyślny, lokalny wektor + BM25), **PageIndex** (hostowany, wyszukiwanie z rozumowaniem z cytowaniami na poziomie strony), **GraphRAG** i **LightRAG** (wyszukiwanie oparte na grafach wiedzy), **LightRAG Server** (wyszukiwanie odciążone do zewnętrznej instancji LightRAG którą łączysz przez HTTP), **Tencent IMA** (biblioteka którą kurujesz w IMA, przeszukiwana przez jego OpenAPI) lub podłączony vault **Obsidian** który tutor czyta i zapisuje w miejscu. Każda KB jest powiązana z jednym silnikiem.+Bazy wiedzy to kolekcje dokumentów za RAG — ugruntowują tury Chat, edycje Co-Writer, generowanie Book i konwersacje Partner. Wyróżnikiem jest **wybór silnika wyszukiwania**: **LlamaIndex** (domyślny, lokalny wektor + BM25), **PageIndex** (hostowany, wyszukiwanie z rozumowaniem z cytowaniami na poziomie strony), **GraphRAG** i **LightRAG** (wyszukiwanie oparte na grafach wiedzy), **LightRAG Server** (wyszukiwanie odciążone do zewnętrznej instancji LightRAG którą łączysz przez HTTP), **Tencent IMA** (biblioteka którą kurujesz w IMA — przeszukiwana, przeglądana i zapisywana z powrotem przez jego OpenAPI) lub podłączony vault **Obsidian** który tutor czyta i zapisuje w miejscu. Każda KB jest powiązana z jednym silnikiem.<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Tworzenie bazy wiedzy" width="900">@@ -437,7 +437,7 @@ Tworząc KB, albo **tworzysz nową** (przesyłasz dokumenty i budujesz świeży<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Centrum Learning Space DeepTutor" width="900"></div>-Learning Space to biblioteka i warstwa personalizacji — miejsce gdzie żyją rzeczy, które się zachowują. **Conversations & Materials** przechowuje historię czatu, notatniki i bank pytań (każde zapisane pytanie zachowuje twoją odpowiedź, odpowiedź referencyjną i wyjaśnienie). **Personalization** przechowuje ścieżki opanowania, persony (presety zachowań takie jak *peer*, *research-assistant*, *teacher*), umiejętności (podręczniki `SKILL.md` które model czyta na żądanie), **Usługi MCP** — kuratorowany magazyn hostowanych serwerów MCP, które instalujesz dla siebie jednym kliknięciem, plus dowolny zdalny serwer, który skonfigurujesz przez URL — oraz **Aplikacje CLI**, narzędzia wiersza poleceń z katalogu [CLI-Anything](https://github.com/HKUDS/CLI-Anything), które agent czatu wywołuje bezpośrednio, z własnym przewodnikiem użycia każdej aplikacji wczytywanym na żądanie. Wszystko tutaj można ponownie używać z Chat, Partners, Co-Writer i Book.+Learning Space to biblioteka i warstwa personalizacji — miejsce gdzie żyją rzeczy, które się zachowują. **Conversations & Materials** przechowuje historię czatu, notatniki — teraz z własną konsolą, z rekordami które przenosisz lub kopiujesz między notatnikami oraz eksportem do Markdown — i bank pytań (każde zapisane pytanie zachowuje twoją odpowiedź, odpowiedź referencyjną i wyjaśnienie). **Personalization** przechowuje ścieżki opanowania, persony (presety zachowań takie jak *peer*, *research-assistant*, *teacher*), umiejętności (podręczniki `SKILL.md` które model czyta na żądanie), **Usługi MCP** — kuratorowany magazyn hostowanych serwerów MCP, które instalujesz dla siebie jednym kliknięciem, plus dowolny zdalny serwer, który skonfigurujesz przez URL — oraz **Aplikacje CLI**, narzędzia wiersza poleceń z katalogu [CLI-Anything](https://github.com/HKUDS/CLI-Anything), które agent czatu wywołuje bezpośrednio, z własnym przewodnikiem użycia każdej aplikacji wczytywanym na żądanie. Wszystko tutaj można ponownie używać z Chat, Partners, Co-Writer i Book.<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importowanie umiejętności z EduHub" width="900">@@ -477,7 +477,7 @@ Settings to operacyjna płaszczyzna kontroli z paskiem statusu na żywo (stan ba<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Ustawienia wyglądu DeepTutor i motywy" width="900"></div>-Większość sekcji używa przepływu szkic-i-zastosuj, więc możesz testować dostawcę przed jego zatwierdzeniem. Cztery motywy dostarczane w zestawie — Default, Cream, Dark i Glass. Pliki `.env` katalogu głównego projektu są celowo ignorowane; konfiguracja środowiska uruchomieniowego żyje pod `data/user/settings/*.json` chyba że `DEEPTUTOR_HOME` lub `deeptutor start --home` wskaże aplikację gdzie indziej.+Większość sekcji używa przepływu szkic-i-zastosuj, więc możesz testować dostawcę przed jego zatwierdzeniem. Możesz też po prostu zapytać w Chat: asystent odczytuje bieżącą konfigurację, stosuje zmianę i mówi, czy potrzebny jest restart lub ponowne indeksowanie — sprawdzając nowy model zanim go zatwierdzi, więc nie może sam przełączyć się na coś nieosiągalnego. Klucze API nigdy nie przechodzą przez model, który zamiast tego otwiera odpowiedni formularz. Cztery motywy dostarczane w zestawie — Default, Cream, Dark i Glass. Pliki `.env` katalogu głównego projektu są celowo ignorowane; konfiguracja środowiska uruchomieniowego żyje pod `data/user/settings/*.json` chyba że `DEEPTUTOR_HOME` lub `deeptutor start --home` wskaże aplikację gdzie indziej.**OpenAI Codex OAuth (eksperymentalne).** Wybranie **OpenAI Codex** w Models → LLM zastępuje pola klucza API logowaniem przez przeglądarkę, które działa względem twojego własnego planu ChatGPT, więc `OPENAI_API_KEY` nie jest potrzebny. Tokeny żyją wyłącznie w `data/system/user-secrets/<owner>/private/openai-codex/` — w wielokontenerowym wdrożeniu Compose, poza każdym drzewem, do którego ma dostęp piaskownica wykonania kodu — a DeepTutor nigdy nie czyta ani nie modyfikuje twojego logowania CLI `~/.codex`. Lista modeli pochodzi z aktualnego katalogu tego konta; zalogowanie się publikuje profil, ale staje się aktywnym modelem tylko gdy żaden LLM nie jest jeszcze skonfigurowany, więc nigdy nie przekierowuje wdrożenia bez twojej wiedzy. Ponieważ token autoryzuje plan jednej osoby, profilu nie da się współdzielić przez uprawnienia użytkowników — każde konto loguje się osobno, w tym zwykli użytkownicy: ich karta znajduje się w Models → LLM, a wynikowe modele, katalog i wylogowanie pozostają prywatne dla tego konta, a przeglądarka musi dotrzeć do maszyny, na której działa backend (na zdalnym serwerze uruchom tam zamiast tego `deeptutor provider login openai-codex`). Błędy limitu i awarie katalogu są zgłaszane wprost i nigdy nie powodują przełączenia na płatnego dostawcę. Ta ścieżka kompatybilności jest eksperymentalna: interfejs projektu nadrzędnego może się zmienić.diff --git a/assets/README/README_PT.md b/assets/README/README_PT.mdindex 124ce790c..ff2fcf1da 100644--- a/assets/README/README_PT.md+++ b/assets/README/README_PT.md@@ -60,10 +60,10 @@O DeepTutor é um espaço de trabalho de aprendizagem nativo de agentes que conecta tutoria, resolução de problemas, geração de quizzes, pesquisa, visualização e prática de domínio num sistema extensível.-- **Um runtime para todos os modos** — Chat, Quiz, Research, Visualize, Solve e Mastery Path correm no mesmo loop de agente, pelo que muda o objetivo, não o motor, e o contexto acompanha o utilizador.+- **Um runtime para todos os modos** — Chat, Quiz, Research, Visualize, Solve, Mastery Path e Immersive Reading correm no mesmo loop de agente, pelo que muda o objetivo, não o motor, e o contexto acompanha o utilizador.- **Contexto de aprendizado conectado** — bases de conhecimento, livros, rascunhos Co-Writer, cadernos, bancos de questões, personas e Memory permanecem disponíveis em todos os fluxos de trabalho em vez de viverem em ferramentas isoladas.- **Subagentes e Partners** — consultar uma CLI de programação ao vivo (Claude Code, Codex, Gemini, Kimi, opencode ou MiMo) ou um Partner a partir de qualquer turno (ou importar as suas conversas anteriores), e correr companheiros IM persistentes no mesmo cérebro.-- **Conhecimento multi-motor** — bibliotecas RAG com versões: LlamaIndex, PageIndex, GraphRAG, LightRAG ou um vault Obsidian vinculado, com análise de documentos conectável.+- **Conhecimento multi-motor** — bibliotecas RAG com versões: LlamaIndex, PageIndex, GraphRAG, LightRAG, um LightRAG Server remoto ou uma biblioteca Tencent IMA, ou um vault Obsidian vinculado, com análise de documentos conectável.- **Ferramentas e habilidades extensíveis** — ferramentas integradas, servidores MCP, aplicações CLI, modelos de geração de imagem / vídeo / voz e habilidades da comunidade instaláveis do EduHub.- **Memória inspecionável** — rastreamentos L1, resumos de superfície L2 e síntese L3 tornam a personalização visível e editável, com um Memory Graph que rastreia cada afirmação até à sua evidência.@@ -343,7 +343,7 @@ As ferramentas ativáveis pelo utilizador são `brainstorm`, `web_search`, `papeO contexto é de dois tipos: **contexto de sessão fixo** (subagente, bases de conhecimento, persona, modelo, voz) vive na barra de ferramentas do compositor e persiste entre turnos; **referências únicas** (ficheiros, histórico de chat, livros, notebooks, banco de questões, agentes importados) vêm do menu `+` para um único turno.-Chat é também o ponto de lançamento para capacidades mais profundas: **Quiz** para geração de perguntas, **Research** para relatórios com citações, **Visualize** para gráficos / diagramas / animações, e — em *More Capabilities* — **Solve** para raciocínio trabalhado e **Mastery Path** para fluxos de planos de aprendizagem.+Chat é também o ponto de lançamento para capacidades mais profundas: **Quiz** para geração de perguntas, **Visualize** para gráficos / diagramas / animações, **Mastery Path** para fluxos de planos de aprendizagem, e **Immersive Reading** — um documento aberto ao lado do thread, com cada afirmação citada até à página de onde veio. **Research** para relatórios com citações e **Solve** para raciocínio trabalhado ficam em *More Capabilities*.</details>@@ -432,7 +432,7 @@ Cada capítulo compila em blocos tipados — texto, callouts, quizzes, cartões<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Centro de Conhecimento DeepTutor" width="900"></div>-As bases de conhecimento são as coleções de documentos por trás do RAG — fundamentam os turnos do Chat, edições do Co-Writer, geração do Book e conversas do Partner. O que é distintivo é uma **escolha de motores de recuperação**: **LlamaIndex** (o padrão, vetor local + BM25), **PageIndex** (alojado, recuperação de raciocínio com citações ao nível da página), **GraphRAG** e **LightRAG** (recuperação de grafo de conhecimento), **LightRAG Server** (recuperação delegada a uma instância externa de LightRAG conectada via HTTP), **Tencent IMA** (uma biblioteca que cura no IMA, pesquisada através da sua OpenAPI), ou um vault **Obsidian** vinculado que o tutor lê e escreve no lugar. Cada KB está vinculada a um motor.+As bases de conhecimento são as coleções de documentos por trás do RAG — fundamentam os turnos do Chat, edições do Co-Writer, geração do Book e conversas do Partner. O que é distintivo é uma **escolha de motores de recuperação**: **LlamaIndex** (o padrão, vetor local + BM25), **PageIndex** (alojado, recuperação de raciocínio com citações ao nível da página), **GraphRAG** e **LightRAG** (recuperação de grafo de conhecimento), **LightRAG Server** (recuperação delegada a uma instância externa de LightRAG conectada via HTTP), **Tencent IMA** (uma biblioteca que cura no IMA — pesquisada, navegada e escrita de volta através da sua OpenAPI), ou um vault **Obsidian** vinculado que o tutor lê e escreve no lugar. Cada KB está vinculada a um motor.<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Criar uma base de conhecimento" width="900">@@ -449,7 +449,7 @@ Ao criar uma KB, pode **criar nova** (carregar documentos e construir um índice<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Hub do Espaço de Aprendizado DeepTutor" width="900"></div>-O Espaço de Aprendizado é a camada de biblioteca e personalização — onde vivem as coisas que persistem. **Conversas e Materiais** contém o seu histórico de chat, notebooks e um banco de questões (cada pergunta guardada mantém a sua resposta, a resposta de referência e uma explicação). **Personalização** contém caminhos de domínio, personas (predefinições de comportamento como *par*, *assistente de pesquisa*, *professor*), skills (playbooks `SKILL.md` que o modelo lê a pedido), **Serviços MCP** — uma loja curada de servidores MCP alojados que instala para si mesmo com um clique, além de qualquer servidor remoto que configure por URL — e **Aplicações CLI**, ferramentas de linha de comandos do catálogo [CLI-Anything](https://github.com/HKUDS/CLI-Anything) que o agente de chat chama diretamente, com o guia de utilização próprio de cada aplicação carregado a pedido. Tudo aqui pode ser reutilizado a partir do Chat, Partners, Co-Writer e Book.+O Espaço de Aprendizado é a camada de biblioteca e personalização — onde vivem as coisas que persistem. **Conversas e Materiais** contém o seu histórico de chat, notebooks — agora com a sua própria consola, com registos que se movem ou copiam entre notebooks e uma exportação em Markdown — e um banco de questões (cada pergunta guardada mantém a sua resposta, a resposta de referência e uma explicação). **Personalização** contém caminhos de domínio, personas (predefinições de comportamento como *par*, *assistente de pesquisa*, *professor*), skills (playbooks `SKILL.md` que o modelo lê a pedido), **Serviços MCP** — uma loja curada de servidores MCP alojados que instala para si mesmo com um clique, além de qualquer servidor remoto que configure por URL — e **Aplicações CLI**, ferramentas de linha de comandos do catálogo [CLI-Anything](https://github.com/HKUDS/CLI-Anything) que o agente de chat chama diretamente, com o guia de utilização próprio de cada aplicação carregado a pedido. Tudo aqui pode ser reutilizado a partir do Chat, Partners, Co-Writer e Book.<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Importar skills do EduHub" width="900">@@ -489,7 +489,7 @@ Configurações é o plano de controlo operacional, com uma faixa de estado em t<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Configurações de aparência e temas DeepTutor" width="900"></div>-A maioria das secções usa um fluxo de rascunho e aplicação, para que possa testar um provedor antes de o confirmar. Quatro temas incluídos — Default, Cream, Dark e Glass. Os ficheiros `.env` da raiz do projeto são intencionalmente ignorados; a configuração de runtime vive sob `data/user/settings/*.json` a menos que `DEEPTUTOR_HOME` ou `deeptutor start --home` aponte a aplicação para outro lugar.+A maioria das secções usa um fluxo de rascunho e aplicação, para que possa testar um provedor antes de o confirmar. Também pode simplesmente pedir no Chat: o assistente lê a configuração atual, aplica uma alteração e diz se é necessário reiniciar ou reindexar — testando um novo modelo antes de o confirmar, para que nunca possa mudar-se sozinho para algo inacessível. As chaves API nunca passam pelo modelo, que em vez disso abre o formulário correspondente para si. Quatro temas incluídos — Default, Cream, Dark e Glass. Os ficheiros `.env` da raiz do projeto são intencionalmente ignorados; a configuração de runtime vive sob `data/user/settings/*.json` a menos que `DEEPTUTOR_HOME` ou `deeptutor start --home` aponte a aplicação para outro lugar.**OpenAI Codex OAuth (experimental).** Escolher **OpenAI Codex** em Models → LLM substitui os campos de chave API por um login no navegador que corre contra o seu próprio plano ChatGPT, pelo que não é necessária nenhuma `OPENAI_API_KEY`. Os tokens vivem apenas em `data/system/user-secrets/<owner>/private/openai-codex/` — na implementação multi-contentor com Compose, fora de qualquer árvore que o sandbox de execução possa alcançar — e o DeepTutor nunca lê nem modifica o seu login CLI `~/.codex`. A lista de modelos vem do catálogo ao vivo dessa conta; iniciar sessão publica o perfil mas só se torna o modelo ativo quando ainda não há nenhum LLM configurado, pelo que nunca redireciona uma implementação sem o seu conhecimento. Como um token autoriza o plano de uma pessoa, o perfil não é partilhável através de concessões de utilizador — cada conta inicia sessão por si própria, incluindo utilizadores comuns: o seu cartão está em Models → LLM, e os modelos, o catálogo e o logout resultantes permanecem privados dessa conta, e o navegador tem de alcançar a máquina que executa o backend (num servidor remoto, execute `deeptutor provider login openai-codex` lá em vez disso). Erros de quota e falhas de catálogo são reportados tal como ocorrem e nunca recorrem a um provedor pago. Este caminho de compatibilidade é experimental: a interface upstream pode mudar.diff --git a/assets/README/README_RU.md b/assets/README/README_RU.mdindex 6d8ab286b..1a171e8db 100644--- a/assets/README/README_RU.md+++ b/assets/README/README_RU.md@@ -60,10 +60,10 @@DeepTutor — это агентная учебная рабочая среда, объединяющая репетиторство, решение задач, генерацию викторин, исследования, визуализацию и практику освоения в одной расширяемой системе.-- **Единая среда выполнения для всех режимов** — Chat, Quiz, Research, Visualize, Solve и Mastery Path работают на одном цикле агента, поэтому вы переключаете цель, а не движок, и контекст перемещается вместе с учащимся.+- **Единая среда выполнения для всех режимов** — Chat, Quiz, Research, Visualize, Solve, Mastery Path и Immersive Reading работают на одном цикле агента, поэтому вы переключаете цель, а не движок, и контекст перемещается вместе с учащимся.- **Связанный контекст обучения** — базы знаний, книги, черновики Co-Writer, блокноты, банки вопросов, персоны и Memory доступны во всех рабочих процессах, а не живут в изолированных инструментах.- **Субагенты и Partners** — консультируйте живой инструмент кодирования CLI (Claude Code, Codex, Gemini, Kimi, opencode или MiMo) или Partner из любого хода (или импортируйте их прошлые разговоры) и запускайте постоянных IM-компаньонов на том же мозге.-- **Многодвигательные знания** — версионированные RAG-библиотеки на основе LlamaIndex, PageIndex, GraphRAG, LightRAG или связанного хранилища Obsidian с подключаемым разбором документов.+- **Многодвигательные знания** — версионированные RAG-библиотеки на основе LlamaIndex, PageIndex, GraphRAG, LightRAG, удалённого LightRAG Server или библиотеки Tencent IMA, либо связанного хранилища Obsidian, с подключаемым разбором документов.- **Расширяемые инструменты и навыки** — встроенные инструменты, MCP-серверы, CLI-приложения, модели генерации изображений / видео / голоса и устанавливаемые навыки сообщества из EduHub.- **Проверяемая память** — трассировки L1, сводки поверхностей L2 и синтез L3 делают персонализацию видимой и редактируемой, а Memory Graph прослеживает каждое утверждение до его источника.@@ -331,7 +331,7 @@ deeptutor config showКонтекст бывает двух видов: **постоянный контекст сессии** (субагент, базы знаний, персонаж, модель, голос) находится на панели инструментов редактора и сохраняется между ходами; **одноразовые ссылки** (файлы, история чата, книги, блокноты, банк вопросов, импортированные агенты) берутся из меню `+` для одного хода.-Чат также является точкой запуска более глубоких возможностей: **Quiz** для генерации вопросов, **Research** для цитируемых отчётов, **Visualize** для графиков / диаграмм / анимаций, и — в разделе *Дополнительные возможности* — **Solve** для обоснованных рассуждений и **Mastery Path** для учебных планов.+Чат также является точкой запуска более глубоких возможностей: **Quiz** для генерации вопросов, **Visualize** для графиков / диаграмм / анимаций, **Mastery Path** для учебных планов, и **Immersive Reading** — документ, открытый рядом с потоком чата, где каждое утверждение процитировано со страницы, откуда оно взято. **Research** для цитируемых отчётов и **Solve** для обоснованных рассуждений находятся в разделе *Дополнительные возможности*.</details>@@ -420,7 +420,7 @@ Co-Writer — это разделённое рабочее пространст<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="Центр Знаний DeepTutor" width="900"></div>-Базы знаний — это коллекции документов для RAG, которые обосновывают ходы Chat, редакции Co-Writer, генерацию Book и разговоры с Партнёрами. Отличительной чертой является **выбор движков поиска**: **LlamaIndex** (по умолчанию, локальный вектор + BM25), **PageIndex** (размещённый, поиск с рассуждением с цитатами на уровне страницы), **GraphRAG** и **LightRAG** (поиск на основе графа знаний), **LightRAG Server** (поиск, делегированный внешнему экземпляру LightRAG, подключаемому по HTTP), **Tencent IMA** (библиотека, которую вы курируете в IMA, доступная для поиска через её OpenAPI), или связанное хранилище **Obsidian**, которое репетитор читает и записывает на месте. Каждая KB привязана к одному движку.+Базы знаний — это коллекции документов для RAG, которые обосновывают ходы Chat, редакции Co-Writer, генерацию Book и разговоры с Партнёрами. Отличительной чертой является **выбор движков поиска**: **LlamaIndex** (по умолчанию, локальный вектор + BM25), **PageIndex** (размещённый, поиск с рассуждением с цитатами на уровне страницы), **GraphRAG** и **LightRAG** (поиск на основе графа знаний), **LightRAG Server** (поиск, делегированный внешнему экземпляру LightRAG, подключаемому по HTTP), **Tencent IMA** (библиотека, которую вы курируете в IMA — доступная для поиска, просмотра и записи через её OpenAPI), или связанное хранилище **Obsidian**, которое репетитор читает и записывает на месте. Каждая KB привязана к одному движку.<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Создание базы знаний" width="900">@@ -437,7 +437,7 @@ Co-Writer — это разделённое рабочее пространст<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="Хаб Пространства Обучения DeepTutor" width="900"></div>-Пространство Обучения — это библиотека и уровень персонализации — место, где живут постоянные вещи. **Разговоры и материалы** содержат историю чата, блокноты и банк вопросов (каждый сохранённый вопрос хранит ваш ответ, эталонный ответ и объяснение). **Персонализация** содержит пути мастерства, персонажей (поведенческие пресеты, такие как *коллега*, *исследовательский ассистент*, *учитель*), навыки (сценарии `SKILL.md`, которые модель читает по требованию), **MCP-сервисы** — курируемый каталог размещённых MCP-серверов, которые вы устанавливаете для себя в один клик, а также любой удалённый сервер, который вы настраиваете по URL, — и **CLI-приложения** — инструменты командной строки из каталога [CLI-Anything](https://github.com/HKUDS/CLI-Anything), которые чат-агент вызывает напрямую, причём собственное руководство по использованию каждого приложения загружается по требованию. Всё здесь можно повторно использовать из Chat, Partners, Co-Writer и Book.+Пространство Обучения — это библиотека и уровень персонализации — место, где живут постоянные вещи. **Разговоры и материалы** содержат историю чата, блокноты — теперь это отдельная консоль, где записи можно перемещать или копировать между блокнотами, а также экспортировать в Markdown — и банк вопросов (каждый сохранённый вопрос хранит ваш ответ, эталонный ответ и объяснение). **Персонализация** содержит пути мастерства, персонажей (поведенческие пресеты, такие как *коллега*, *исследовательский ассистент*, *учитель*), навыки (сценарии `SKILL.md`, которые модель читает по требованию), **MCP-сервисы** — курируемый каталог размещённых MCP-серверов, которые вы устанавливаете для себя в один клик, а также любой удалённый сервер, который вы настраиваете по URL, — и **CLI-приложения** — инструменты командной строки из каталога [CLI-Anything](https://github.com/HKUDS/CLI-Anything), которые чат-агент вызывает напрямую, причём собственное руководство по использованию каждого приложения загружается по требованию. Всё здесь можно повторно использовать из Chat, Partners, Co-Writer и Book.<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="Импорт навыков из EduHub" width="900">@@ -477,7 +477,7 @@ Co-Writer — это разделённое рабочее пространст<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="Настройки внешнего вида и темы DeepTutor" width="900"></div>-Большинство разделов используют поток черновика и применения, поэтому вы можете протестировать провайдера перед подтверждением. В комплект входят четыре темы — Default, Cream, Dark и Glass. Корневые файлы `.env` проекта намеренно игнорируются; конфигурация среды выполнения хранится в `data/user/settings/*.json`, если только `DEEPTUTOR_HOME` или `deeptutor start --home` не указывает приложению другое место.+Большинство разделов используют поток черновика и применения, поэтому вы можете протестировать провайдера перед подтверждением. Вы также можете просто попросить об этом в Chat: ассистент читает текущую конфигурацию, применяет изменение и сообщает, требуется ли перезапуск или переиндексация — предварительно проверяя новую модель перед её применением, поэтому он не может переключить себя на что-то недостижимое. API-ключи никогда не проходят через модель — вместо этого она открывает для вас соответствующую форму. В комплект входят четыре темы — Default, Cream, Dark и Glass. Корневые файлы `.env` проекта намеренно игнорируются; конфигурация среды выполнения хранится в `data/user/settings/*.json`, если только `DEEPTUTOR_HOME` или `deeptutor start --home` не указывает приложению другое место.**OpenAI Codex OAuth (экспериментально).** Выбор **OpenAI Codex** в разделе Модели → LLM заменяет поля API-ключа входом через браузер, который выполняется по вашему собственному плану ChatGPT, поэтому `OPENAI_API_KEY` не требуется. Токены хранятся только в `data/system/user-secrets/<owner>/private/openai-codex/` — в многоконтейнерном развёртывании Compose это за пределами любого дерева, доступного песочнице выполнения, — и DeepTutor никогда не читает и не изменяет вашу CLI-авторизацию `~/.codex`. Список моделей формируется из актуального каталога этой учётной записи; вход публикует профиль, но тот становится активной моделью, только если LLM ещё не настроен, поэтому вход никогда не перенаправляет развёртывание втихую. Поскольку токен авторизует план одного человека, профиль нельзя передать через гранты для пользователей — каждая учётная запись входит сама за себя, включая обычных пользователей: их карточка находится в разделе Модели → LLM, а получившиеся модели, каталог и выход из системы остаются приватными для этой учётной записи. Ошибки квоты и сбои каталога показываются как есть и никогда не приводят к переключению на платного провайдера. Этот путь совместимости экспериментален: вышестоящий интерфейс может измениться.diff --git a/assets/README/README_TH.md b/assets/README/README_TH.mdindex aeff66d27..e9040fd11 100644--- a/assets/README/README_TH.md+++ b/assets/README/README_TH.md@@ -60,10 +60,10 @@DeepTutor คือ workspace การเรียนรู้แบบ agent-native ที่เชื่อมต่อการสอนพิเศษ, การแก้ปัญหา, การสร้าง quiz, การวิจัย, การสร้างภาพ และการฝึกความเชี่ยวชาญในระบบที่ขยายได้หนึ่งเดียว-- **รันไทม์เดียวสำหรับทุกโหมด** — Chat, Quiz, Research, Visualize, Solve และ Mastery Path บนลูป agent เดียวกัน คุณเปลี่ยนวัตถุประสงค์ ไม่ใช่เอ็นจิน และบริบทเดินทางไปพร้อมกับผู้เรียน+- **รันไทม์เดียวสำหรับทุกโหมด** — Chat, Quiz, Research, Visualize, Solve, Mastery Path และ Immersive Reading บนลูป agent เดียวกัน คุณเปลี่ยนวัตถุประสงค์ ไม่ใช่เอ็นจิน และบริบทเดินทางไปพร้อมกับผู้เรียน- **บริบทการเรียนรู้ที่เชื่อมต่อกัน** — ฐานความรู้, หนังสือ, ร่าง Co-Writer, สมุดบันทึก, คลังคำถาม, บุคลิกภาพ และ Memory พร้อมใช้งานในทุกเวิร์กโฟลว์ แทนที่จะอยู่ในเครื่องมือที่แยกจากกัน- **ซับเอเจนต์และ Partners** — ปรึกษา coding CLI แบบสด (Claude Code, Codex, Gemini, Kimi, opencode หรือ MiMo) หรือ Partner จากทุก turn (หรือนำเข้าบทสนทนาในอดีต) และรันเพื่อนถาวรบน IM ด้วยสมองเดียวกัน-- **ความรู้หลายเอ็นจิน** — ไลบรารี RAG แบบเวอร์ชันผ่าน LlamaIndex, PageIndex, GraphRAG, LightRAG หรือ Obsidian vault ที่เชื่อมโยง พร้อมการแยกวิเคราะห์เอกสารแบบ pluggable+- **ความรู้หลายเอ็นจิน** — ไลบรารี RAG แบบเวอร์ชันผ่าน LlamaIndex, PageIndex, GraphRAG, LightRAG, LightRAG Server ระยะไกล หรือไลบรารี Tencent IMA หรือ Obsidian vault ที่เชื่อมโยง พร้อมการแยกวิเคราะห์เอกสารแบบ pluggable- **เครื่องมือและทักษะที่ขยายได้** — เครื่องมือในตัว, เซิร์ฟเวอร์ MCP, แอป CLI, โมเดลสร้างรูปภาพ/วิดีโอ/เสียง และทักษะชุมชนที่ติดตั้งได้จาก EduHub- **หน่วยความจำที่ตรวจสอบได้** — การติดตาม L1, สรุปพื้นผิว L2 และการสังเคราะห์ L3 ทำให้การปรับแต่งส่วนบุคคลมองเห็นได้และแก้ไขได้ พร้อม Memory Graph ที่ติดตามทุกการอ้างสิทธิ์กลับไปสู่หลักฐาน@@ -331,7 +331,7 @@ Chat คือความสามารถเริ่มต้นและสบริบทมีสองประเภท: **sticky session context** (subagent, knowledge bases, persona, model, voice) อยู่บน composer toolbar และคงอยู่ตลอด turns; **one-time references** (ไฟล์, ประวัติ chat, หนังสือ, notebooks, question bank, imported agents) มาจากเมนู `+` สำหรับ turn เดียว-Chat ยังเป็นจุดเปิดตัวสำหรับความสามารถที่ลึกกว่า: **Quiz** สำหรับการสร้างคำถาม, **Research** สำหรับรายงานที่อ้างอิง, **Visualize** สำหรับ charts / diagrams / animations และ — ภายใต้ *More Capabilities* — **Solve** สำหรับการให้เหตุผลแบบมีขั้นตอน และ **Mastery Path** สำหรับ learning-plan flows+Chat ยังเป็นจุดเปิดตัวสำหรับความสามารถที่ลึกกว่า: **Quiz** สำหรับการสร้างคำถาม, **Visualize** สำหรับ charts / diagrams / animations, **Mastery Path** สำหรับ learning-plan flows และ **Immersive Reading** — เอกสารที่เปิดอยู่ข้าง thread โดยทุกการอ้างสิทธิ์ถูกอ้างอิงกลับไปยังหน้าที่มันมาจาก **Research** สำหรับรายงานที่อ้างอิง และ **Solve** สำหรับการให้เหตุผลแบบมีขั้นตอน อยู่ภายใต้ *More Capabilities*</details>@@ -420,7 +420,7 @@ Book แปลงแหล่งที่มาที่เลือกให้<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900"></div>-Knowledge bases คือคอลเลกชันเอกสารที่อยู่เบื้องหลัง RAG — รองรับ Chat turns, Co-Writer edits, Book generation และบทสนทนา Partner สิ่งที่โดดเด่นคือ **การเลือกเอ็นจิน retrieval**: **LlamaIndex** (ค่าเริ่มต้น, local vector + BM25), **PageIndex** (hosted, reasoning retrieval พร้อม page-level citations), **GraphRAG** และ **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval ที่ offload ไปยัง LightRAG instance ภายนอกที่คุณเชื่อมต่อผ่าน HTTP), **Tencent IMA** (ไลบรารีที่คุณคัดสรรใน IMA ค้นหาผ่าน OpenAPI ของมัน) หรือ **Obsidian** vault ที่เชื่อมโยง tutor อ่านและเขียนในที่ KB แต่ละอันถูกผูกกับเอ็นจินหนึ่ง+Knowledge bases คือคอลเลกชันเอกสารที่อยู่เบื้องหลัง RAG — รองรับ Chat turns, Co-Writer edits, Book generation และบทสนทนา Partner สิ่งที่โดดเด่นคือ **การเลือกเอ็นจิน retrieval**: **LlamaIndex** (ค่าเริ่มต้น, local vector + BM25), **PageIndex** (hosted, reasoning retrieval พร้อม page-level citations), **GraphRAG** และ **LightRAG** (knowledge-graph retrieval), **LightRAG Server** (retrieval ที่ offload ไปยัง LightRAG instance ภายนอกที่คุณเชื่อมต่อผ่าน HTTP), **Tencent IMA** (ไลบรารีที่คุณคัดสรรใน IMA — ค้นหา เรียกดู และเขียนกลับผ่าน OpenAPI ของมัน) หรือ **Obsidian** vault ที่เชื่อมโยง tutor อ่านและเขียนในที่ KB แต่ละอันถูกผูกกับเอ็นจินหนึ่ง<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="สร้าง knowledge base" width="900">@@ -437,7 +437,7 @@ Knowledge bases คือคอลเลกชันเอกสารที่<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Space hub" width="900"></div>-Learning Space คือชั้น library และ personalization — ที่ซึ่งสิ่งที่คงอยู่ถาวรอาศัยอยู่ **Conversations & Materials** เก็บประวัติ chat, notebooks และ question bank (แต่ละคำถามที่บันทึกเก็บคำตอบของคุณ, คำตอบอ้างอิง และคำอธิบาย) **Personalization** เก็บ mastery paths, personas (พฤติกรรมที่ตั้งค่าล่วงหน้าเช่น *peer*, *research-assistant*, *teacher*), skills (`SKILL.md` playbooks ที่ model อ่านตามต้องการ), **MCP Services** — คลังที่คัดสรรของเซิร์ฟเวอร์ MCP แบบ hosted ที่คุณติดตั้งให้ตัวเองได้ในคลิกเดียว รวมถึงเซิร์ฟเวอร์ remote ใด ๆ ที่คุณกำหนดค่าผ่าน URL — และ **CLI Apps** เครื่องมือบรรทัดคำสั่งจาก catalog [CLI-Anything](https://github.com/HKUDS/CLI-Anything) ที่ chat agent เรียกใช้โดยตรง พร้อมคู่มือการใช้งานของแต่ละแอปที่โหลดตามต้องการ ทุกอย่างที่นี่สามารถนำมาใช้ซ้ำได้จาก Chat, Partners, Co-Writer และ Book+Learning Space คือชั้น library และ personalization — ที่ซึ่งสิ่งที่คงอยู่ถาวรอาศัยอยู่ **Conversations & Materials** เก็บประวัติ chat, notebooks — ตอนนี้มีคอนโซลเป็นของตัวเอง พร้อมรายการที่ย้ายหรือคัดลอกระหว่าง notebooks ได้ และการ export เป็น Markdown — และ question bank (แต่ละคำถามที่บันทึกเก็บคำตอบของคุณ, คำตอบอ้างอิง และคำอธิบาย) **Personalization** เก็บ mastery paths, personas (พฤติกรรมที่ตั้งค่าล่วงหน้าเช่น *peer*, *research-assistant*, *teacher*), skills (`SKILL.md` playbooks ที่ model อ่านตามต้องการ), **MCP Services** — คลังที่คัดสรรของเซิร์ฟเวอร์ MCP แบบ hosted ที่คุณติดตั้งให้ตัวเองได้ในคลิกเดียว รวมถึงเซิร์ฟเวอร์ remote ใด ๆ ที่คุณกำหนดค่าผ่าน URL — และ **CLI Apps** เครื่องมือบรรทัดคำสั่งจาก catalog [CLI-Anything](https://github.com/HKUDS/CLI-Anything) ที่ chat agent เรียกใช้โดยตรง พร้อมคู่มือการใช้งานของแต่ละแอปที่โหลดตามต้องการ ทุกอย่างที่นี่สามารถนำมาใช้ซ้ำได้จาก Chat, Partners, Co-Writer และ Book<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="นำเข้า skills จาก EduHub" width="900">@@ -477,7 +477,7 @@ Settings คือ control plane การดำเนินงาน พร้<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor appearance settings and themes" width="900"></div>-ส่วนส่วนใหญ่ใช้ draft-and-apply flow เพื่อให้คุณทดสอบ provider ก่อนยืนยัน ธีมสี่แบบมาในกล่อง — Default, Cream, Dark และ Glass ไฟล์ `.env` ที่ root ของโปรเจกต์ถูกเพิกเฉยโดยเจตนา; การกำหนดค่า runtime อยู่ใน `data/user/settings/*.json` เว้นแต่ `DEEPTUTOR_HOME` หรือ `deeptutor start --home` จะชี้แอปไปที่อื่น+ส่วนส่วนใหญ่ใช้ draft-and-apply flow เพื่อให้คุณทดสอบ provider ก่อนยืนยัน คุณยังสามารถแค่ถามใน Chat ได้เช่นกัน: ผู้ช่วยจะอ่านการกำหนดค่าปัจจุบัน, ใช้การเปลี่ยนแปลง และบอกว่าจำเป็นต้องรีสตาร์ทหรือ re-index หรือไม่ — โดยทดสอบ model ใหม่ก่อนที่จะยืนยัน จึงไม่สามารถเปลี่ยนตัวเองไปยังสิ่งที่เข้าถึงไม่ได้ API keys จะไม่ผ่านเข้าไปใน model เลย ซึ่งจะเปิดฟอร์มที่ตรงกันให้คุณแทน ธีมสี่แบบมาในกล่อง — Default, Cream, Dark และ Glass ไฟล์ `.env` ที่ root ของโปรเจกต์ถูกเพิกเฉยโดยเจตนา; การกำหนดค่า runtime อยู่ใน `data/user/settings/*.json` เว้นแต่ `DEEPTUTOR_HOME` หรือ `deeptutor start --home` จะชี้แอปไปที่อื่น**OpenAI Codex OAuth (ทดลอง)** การเลือก **OpenAI Codex** ภายใต้ **Models → LLM** จะแทนที่ช่อง API key ด้วยการลงชื่อเข้าใช้ผ่านเบราว์เซอร์ที่รันกับแผน ChatGPT ของคุณเอง จึงไม่จำเป็นต้องใช้ `OPENAI_API_KEY` Tokens อยู่เฉพาะใน `data/system/user-secrets/<owner>/private/openai-codex/` — ในการปรับใช้แบบ multi-container ด้วย Compose จะอยู่นอกเหนือทุก tree ที่ exec sandbox สามารถเข้าถึงได้ — และ DeepTutor จะไม่อ่านหรือแก้ไข `~/.codex` CLI login ของคุณเลย รายการ model มาจาก catalog แบบสดของบัญชีนั้น; การลงชื่อเข้าใช้จะเผยแพร่โปรไฟล์ แต่จะกลายเป็น model ที่ใช้งานอยู่ก็ต่อเมื่อยังไม่มีการกำหนดค่า LLM ใด ๆ เท่านั้น จึงไม่มีทางเปลี่ยนทิศทางของการปรับใช้โดยที่คุณไม่รู้ตัว เนื่องจาก token อนุญาตให้ใช้แผนของคนคนเดียว โปรไฟล์นี้จึงไม่สามารถแชร์ผ่าน per-user grants ได้ — แต่ละบัญชีต้องลงชื่อเข้าใช้ด้วยตัวเอง รวมถึงผู้ใช้ทั่วไปด้วย: การ์ดของพวกเขาจะอยู่ภายใต้ **Models → LLM** และ models, catalog และการลงชื่อออกที่ได้จะเป็นส่วนตัวเฉพาะบัญชีนั้นเท่านั้น และเบราว์เซอร์ต้องเข้าถึงเครื่องที่รัน backend ได้ (บนเซิร์ฟเวอร์ remote ให้รัน `deeptutor provider login openai-codex` ที่นั่นแทน) ข้อผิดพลาดเรื่อง quota และความล้มเหลวของ catalog จะถูกรายงานตามจริงและจะไม่ตกกลับไปใช้ provider แบบเสียเงินแทนเด็ดขาด เส้นทาง compatibility นี้ยังอยู่ในขั้นทดลอง: อินเทอร์เฟซต้นทางอาจเปลี่ยนแปลงได้diff --git a/assets/README/README_TW.md b/assets/README/README_TW.mdindex 0be271426..6fb927d64 100644--- a/assets/README/README_TW.md+++ b/assets/README/README_TW.md@@ -60,10 +60,10 @@DeepTutor 是代理程式原生的學習工作區,在同一個可擴充系統中串聯教學、解題、測驗生成、研究、視覺化與精熟練習。-- **所有模式共用一套執行階段** — Chat、Quiz、Research、Visualize、Solve 與 Mastery Path 在同一個代理程式迴圈上運作;你切換的是目標而非引擎,學習情境會一路跟隨學習者。+- **所有模式共用一套執行階段** — Chat、Quiz、Research、Visualize、Solve、Mastery Path 與 Immersive Reading 在同一個代理程式迴圈上運作;你切換的是目標而非引擎,學習情境會一路跟隨學習者。- **相互連結的學習情境** — 知識庫、書籍、Co-Writer 草稿、筆記本、題庫、角色設定與 Memory 在每個工作流程中皆可使用,不再分散於彼此隔離的工具。- **子代理程式與 Partners** — 可在任何回合諮詢即時程式設計 CLI(Claude Code、Codex、Gemini、Kimi、opencode 或 MiMo)或 Partner(也能匯入其過往對話),並讓持續運作的 IM 夥伴共用同一套核心。-- **多引擎知識系統** — 透過 LlamaIndex、PageIndex、GraphRAG、LightRAG 或連結的 Obsidian vault 建立版本化 RAG 知識庫,並支援可插拔的文件解析。+- **多引擎知識系統** — 透過 LlamaIndex、PageIndex、GraphRAG、LightRAG、遠端 LightRAG Server 或 Tencent IMA 知識庫,或連結的 Obsidian vault 建立版本化 RAG 知識庫,並支援可插拔的文件解析。- **可擴充的工具與技能** — 內建工具、MCP 伺服器、CLI 應用程式、影像/影片/語音生成模型,以及可從 EduHub 安裝的社群技能。- **可檢視的記憶** — L1 軌跡、L2 介面摘要與 L3 綜整讓個人化內容透明且可編輯;Memory Graph 可將每項主張追溯到其證據。@@ -331,7 +331,7 @@ Chat 是預設能力,也是大多數工作的起點。單一對話可以進行情境分成兩類:**固定的工作階段情境**(子代理程式、知識庫、角色設定、模型、語音)位於輸入框工具列,並會延續到後續回合;**單次參照**(檔案、聊天記錄、書籍、筆記本、題庫、匯入的代理程式)則從 `+` 選單加入,只用於單一回合。-Chat 也是進階能力的起點:**Quiz** 用於產生題目、**Research** 用於建立附引用的報告、**Visualize** 用於圖表/圖解/動畫;在 *More Capabilities* 下,還有提供完整推理解題過程的 **Solve**,以及學習計畫流程的 **Mastery Path**。+Chat 也是進階能力的起點:**Quiz** 用於產生題目、**Visualize** 用於圖表/圖解/動畫、**Mastery Path** 用於學習計畫流程,以及 **Immersive Reading** — 在對話旁開啟文件,每項主張都會標註出自哪一頁。**Research**(建立附引用的報告)與 **Solve**(提供完整推理解題過程)則歸在 *More Capabilities* 之下。</details>@@ -420,7 +420,7 @@ Book 會將選定來源轉換成互動式**活書**;它不是靜態 PDF,而<img src="../../assets/figs/web-1.4.6+/knowledge/00-overview.png" alt="DeepTutor Knowledge Center" width="900"></div>-知識庫是 RAG 背後的文件集合,可為 Chat 回合、Co-Writer 編輯、Book 生成與 Partner 對話提供依據。其特色在於可**選擇檢索引擎**:**LlamaIndex**(預設,本機 vector+BM25)、**PageIndex**(託管式、可推理的檢索並附頁面層級引用)、**GraphRAG** 與 **LightRAG**(知識圖譜檢索)、**LightRAG Server**(透過 HTTP 連接的外部 LightRAG 執行個體負責檢索)、**Tencent IMA**(在 IMA 中整理並透過其 OpenAPI 搜尋的知識庫),或讓導師就地讀寫的已連結 **Obsidian** vault。每個知識庫都會繫結至單一引擎。+知識庫是 RAG 背後的文件集合,可為 Chat 回合、Co-Writer 編輯、Book 生成與 Partner 對話提供依據。其特色在於可**選擇檢索引擎**:**LlamaIndex**(預設,本機 vector+BM25)、**PageIndex**(託管式、可推理的檢索並附頁面層級引用)、**GraphRAG** 與 **LightRAG**(知識圖譜檢索)、**LightRAG Server**(透過 HTTP 連接的外部 LightRAG 執行個體負責檢索)、**Tencent IMA**(在 IMA 中整理的知識庫 — 透過其 OpenAPI 進行搜尋、瀏覽與寫回),或讓導師就地讀寫的已連結 **Obsidian** vault。每個知識庫都會繫結至單一引擎。<div align="center"><img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="建立知識庫" width="900">@@ -437,7 +437,7 @@ Book 會將選定來源轉換成互動式**活書**;它不是靜態 PDF,而<img src="../../assets/figs/web-1.4.6+/learning-space/00-overview.png" alt="DeepTutor Learning Space 中心" width="900"></div>-Learning Space 是資源庫與個人化層,也是各種持續保存內容所在之處。**Conversations & Materials** 保存聊天記錄、筆記本與題庫(每道儲存的題目都會保留你的答案、參考答案與解說)。**Personalization** 保存精熟學習路徑、角色設定(例如 *同儕*、*研究助理*、*教師*等行為預設)、技能(模型按需讀取的 `SKILL.md` 操作手冊)、**MCP Services**(為自己一鍵安裝的託管式 MCP 伺服器精選商店,以及你透過 URL 設定的任何遠端伺服器),還有 **CLI Apps**:來自 [CLI-Anything](https://github.com/HKUDS/CLI-Anything) 型錄的命令列工具,聊天代理程式可直接呼叫,並按需載入各應用程式的使用指南。這裡的所有內容都能從 Chat、Partners、Co-Writer 與 Book 重複使用。+Learning Space 是資源庫與個人化層,也是各種持續保存內容所在之處。**Conversations & Materials** 保存聊天記錄、筆記本 — 現已擁有專屬控制台,紀錄可在筆記本之間搬移或複製,並支援匯出為 Markdown — 與題庫(每道儲存的題目都會保留你的答案、參考答案與解說)。**Personalization** 保存精熟學習路徑、角色設定(例如 *同儕*、*研究助理*、*教師*等行為預設)、技能(模型按需讀取的 `SKILL.md` 操作手冊)、**MCP Services**(為自己一鍵安裝的託管式 MCP 伺服器精選商店,以及你透過 URL 設定的任何遠端伺服器),還有 **CLI Apps**:來自 [CLI-Anything](https://github.com/HKUDS/CLI-Anything) 型錄的命令列工具,聊天代理程式可直接呼叫,並按需載入各應用程式的使用指南。這裡的所有內容都能從 Chat、Partners、Co-Writer 與 Book 重複使用。<div align="center"><img src="../../assets/figs/web-1.4.6+/learning-space/07-%20download%20skills%20from%20eduhub.png" alt="從 EduHub 匯入技能" width="900">@@ -477,7 +477,7 @@ Settings 是操作控制中心,提供即時狀態列(後端健康狀況,<img src="../../assets/figs/web-1.4.6+/settings/01-appearance%20settings.png" alt="DeepTutor 外觀設定與主題" width="900"></div>-大多數區段採用草稿後套用的流程,因此可先測試供應商再確認變更。內建四種主題:Default、Cream、Dark 與 Glass。系統會刻意忽略專案根目錄的 `.env` 檔案;除非 `DEEPTUTOR_HOME` 或 `deeptutor start --home` 將應用程式指向其他位置,否則執行階段設定位於 `data/user/settings/*.json`。+大多數區段採用草稿後套用的流程,因此可先測試供應商再確認變更。你也可以直接在 Chat 中提出要求:助理會讀取目前設定、套用變更,並告知是否需要重新啟動或重新建立索引 — 在正式套用新模型前先行探測,因此不會把自己切換到無法連線的設定上。API key 絕不會經過模型,助理會改為替你開啟對應的表單。內建四種主題:Default、Cream、Dark 與 Glass。系統會刻意忽略專案根目錄的 `.env` 檔案;除非 `DEEPTUTOR_HOME` 或 `deeptutor start --home` 將應用程式指向其他位置,否則執行階段設定位於 `data/user/settings/*.json`。**OpenAI Codex OAuth(實驗性功能)。** 在 Models → LLM 下選擇 **OpenAI Codex** 後,API key 欄位會改為透過瀏覽器登入自己的 ChatGPT 方案,因此不需要 `OPENAI_API_KEY`。Token 只會存放在 `data/system/user-secrets/<owner>/private/openai-codex/`;在多容器 Compose 部署中,此位置不屬於 exec 沙箱可觸及的任何目錄,而 DeepTutor 絕不會讀取或修改 `~/.codex` CLI 登入。模型清單來自該帳號的即時型錄;登入會發布設定檔,但只有在尚未設定 LLM 時,才會將其設為目前使用的模型。由於 token 授權的是個人方案,該設定檔不能透過使用者授權分享;每個帳號(包括一般使用者)都要自行登入。其卡片位於 Models → LLM,產生的模型、型錄與登出狀態也只屬於該帳號。diff --git a/assets/releases/ver1-5-14.md b/assets/releases/ver1-5-14.mdnew file mode 100644index 000000000..ebda25d6f--- /dev/null+++ b/assets/releases/ver1-5-14.md@@ -0,0 +1,58 @@+# DeepTutor v1.5.14 Release Notes++**Release Date:** 2026.08.19++[v1.5.13](ver1-5-13.md) made a book something you read. This one puts the assistant next to what you are reading: a document opens beside the thread, and every claim comes back with the page it came from. Three other shifts sit around it — DeepTutor can configure itself from a chat turn, a Tencent IMA library becomes something you browse and write to rather than only search, and notebooks get a console of their own. Drop-in — no migrations, nothing to re-index.++## What's New++### Immersive Reading — the document open beside the thread++Pick **Immersive Reading** in the capability menu and open a PDF, a slide deck, or any document the knowledge base already accepts. The reader takes about two thirds of the workspace, the conversation keeps the rest, and the seam between them drags.++The assistant reads the same units you see — PDF pages, slides, or roughly page-sized sections for formats that have no pages of their own — so an answer cites `[p.12]` and the reader scrolls there and highlights the sentence behind the claim. Select a passage and ask about it, highlight as you go and attach notes, then take your marks with you: export a **real annotated PDF** that opens with the highlights intact in Preview or Acrobat, or Markdown to paste into your own notes.++Two decisions make it grounded rather than merely confident. A reading turn keeps the whole chat surface — web search, code execution, your other knowledge bases — because the five reading tools are *added* to it, never substituted for it. And before the model runs at all, DeepTutor runs your own question against the open document and hands it the top hits, so grounding happens even with models that would never have called a read tool on their own. It is a plain search, not a second LLM pass: no extra tokens, no latency before the first word.++### Ask DeepTutor to configure itself++"Switch the interface to Chinese and use a better PDF parser" is now something you say rather than something you go and click. A turn can inspect the install, apply a setting, install a parsing engine or fetch its model weights — following the log live inside the single call instead of polling for it — and ask you for a credential.++Three rules keep that from being reckless. **A new model or provider is probed before it is committed**, against a candidate configuration that never reaches disk, so the assistant cannot switch itself onto something unreachable and cut off its own power supply mid-conversation. **API keys never enter the model's context**: it opens the matching form and your browser posts the key straight to the server. And every knob it can touch is one row in a single table carrying its own scope and effect, so you are told whether a change is instant, needs a restart, or invalidates your embeddings — instead of finding out later.++### Tencent IMA: a library you browse and write to++An IMA library was searchable and nothing else. It now also answers "what is actually in here" — the knowledge-base file list reads the library's own browse API instead of reporting a connected base as non-enumerable, and a listing cut short by its request budget is labelled a lower bound rather than passed off as a total.++From a chat turn you can list the library, read a whole source rather than the retrieved fragments, search your notes by recency, add URLs for IMA to ingest, and write a note back. These tools are additive: `rag` still serves an IMA library, because it is genuinely searchable over HTTP, and attaching one no longer costs you web search or your other bases.++### Connected knowledge bases are searchable again++v1.5.13 stopped Book from sweeping connected knowledge bases: the sweep returned nothing, and "nothing" was indistinguishable from a source with no relevant content. That fix was drawn too wide. Only an Obsidian vault (no index at all) and a connected subagent (not a document collection) are genuinely unreachable — a `linked` folder mounts an index built elsewhere, and LightRAG Server and IMA offload retrieval over HTTP. All three were being set aside, so every book quietly dropped them. Retrieval now asks whether a base *can be retrieved from*, not whether it is connected.++### Notebooks get a console++Notebooks moved out of the Space document layout into their own full-height console at `/notebook` (the old link redirects, deep links included). Records can be copied or moved between notebooks, and a whole notebook exports as one Markdown document.++Three defects went with it. Concurrent saves could clobber one another; each notebook now has its own lock and every write is atomic, so a crash leaves the previous file rather than a truncated one. A notebook whose file is damaged is surfaced as a flagged row instead of vanishing from the list. And renaming a record used to clear its knowledge-base link, because the API forwarded every field whether or not you sent it.++### Settings writes stop overwriting each other++Two writers shared `interface.json` and neither's lock covered the other. Measured before the fix, six preference saves racing six writes from a chat turn lost every one of the saves. Both now go through one lock and one atomic replace. Separately, the settings endpoints stopped writing back the defaults-merged view of your settings: changing your theme used to freeze that day's defaults into your file as explicit choices, so you silently stopped following later changes to any of them.++### Assorted++- **The capability menu was regrouped.** Chat, Quiz, Visualize, Mastery Path, and Immersive Reading are one click away; Research and Solve moved under *More Capabilities*. The grouping is now purely about menu order — it used to key off which engine a capability ran on, which meant the menu could not be reordered without lying about the engine.+- **`write_note` reports a failure it used to hide.** A record id came back even when no notebook accepted the write, and that was read as success.+- **A damaged notebook no longer takes a chat turn down** while resolving notebook references, and `/notebook/health` is reachable again — it was declared after `/{notebook_id}` and had been shadowed by it.++## Upgrade Notes++`pip install -U deeptutor`; Docker users pull `ghcr.io/hkuds/deeptutor:latest`. No schema changes, no re-index, no migration.++- **Immersive Reading stores materials per user** under a new `reading` workspace directory, created on first use. Nothing is written until you open a document.+- **The capability picker looks different.** Research and Solve are now under *More Capabilities*; nothing was removed, and a session that was using either keeps working.+- **Reading needs no new Python dependency** (PyMuPDF is already core), and the PDF viewer ships with the frontend bundle — source installs pick it up on the next `npm install`.+- **A scanned, image-only document is rejected with an explanation** rather than opening as an empty reader. Run it through OCR first, or index it in a knowledge base with a parsing engine that does OCR.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.5.13...v1.5.14diff --git a/deeptutor/__version__.py b/deeptutor/__version__.pyindex a34051a30..391d9166e 100644--- a/deeptutor/__version__.py+++ b/deeptutor/__version__.py@@ -6,6 +6,6 @@ before publishing to PyPI; the web sidebar badge and CLI banner read from thisfile directly."""-__version__ = "1.5.13"+__version__ = "1.5.14"__all__ = ("__version__",)diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex 2c232f5b7..e3f6b3584 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -1469,10 +1469,11 @@ class AgenticChatPipeline:Retrieval cannot answer "how many files are in here" — the passages itreturns say nothing about the size of the collection they came from. The- inventory is a filesystem fact, so it is read here (off the event loop,- one directory walk per KB) and rendered into the system prompt, which- keeps the prompt byte-stable for the whole turn and makes counts- answerable without a tool round-trip.+ inventory is read here instead (off the event loop: a directory walk per+ local KB, and a cached browse call for a connected library that exposes+ one) and rendered into the system prompt, which keeps the prompt+ byte-stable for the whole turn and makes counts answerable without a tool+ round-trip.PageIndex KBs are excluded: ``_pageindex_system_note`` already liststheir documents, with the doc_ids its MCP tools need. Fails soft — a KBdiff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 279f9996d..a8a17bc28 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -331,6 +331,7 @@ from deeptutor.api.routers import (question,question_notebook,quiz_judge,+ reading,sessions,settings,skills,@@ -391,6 +392,7 @@ app.include_router(notebook.router, prefix="/api/v1/notebook", tags=["notebook"], dependencies=_auth)app.include_router(book.router, prefix="/api/v1/book", tags=["book"], dependencies=_auth)+app.include_router(reading.router, prefix="/api/v1/reading", tags=["reading"], dependencies=_auth)app.include_router(memory.router, prefix="/api/v1/memory", tags=["memory"], dependencies=_auth)app.include_router(capabilities_settings.router,diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 6c771987e..4a4b867b3 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -68,6 +68,7 @@ from deeptutor.services.rag.linked_kb import (probe_linked_folder,)from deeptutor.services.rag.pipelines.ima.client import (+ MAX_PAGE_LIMIT,ImaAPIError,ImaAuthError,ImaClient,@@ -1846,7 +1847,9 @@ class ListImaRequest(BaseModel):client_id: str = ""api_key: str = ""cursor: str = ""- limit: int = Field(default=20, ge=1, le=20)+ # IMA documents this call's page size as 1..50; the picker asks for one+ # screenful and pages for the rest.+ limit: int = Field(default=20, ge=1, le=MAX_PAGE_LIMIT)class ImaKnowledgeBaseSummary(BaseModel):diff --git a/deeptutor/api/routers/notebook.py b/deeptutor/api/routers/notebook.pyindex 345cd7b1a..f5dd904a5 100644--- a/deeptutor/api/routers/notebook.py+++ b/deeptutor/api/routers/notebook.py@@ -7,16 +7,39 @@ import jsonfrom typing import AsyncGenerator, Literalfrom fastapi import APIRouter, HTTPException-from fastapi.responses import StreamingResponse+from fastapi.responses import PlainTextResponse, StreamingResponsefrom pydantic import BaseModelfrom deeptutor.agents.notebook import NotebookSummarizeAgentfrom deeptutor.services.llm import clean_thinking_tagsfrom deeptutor.services.notebook import notebook_manager+from deeptutor.services.notebook.service import NotebookCorruptedErrorrouter = APIRouter()+def _unreadable(exc: NotebookCorruptedError) -> HTTPException:+ """Translate a damaged notebook file into a response the UI can explain.++ 409 rather than 500: the request was fine, the stored file is not, and+ the client can act on it (restore a backup, delete the notebook).++ Every endpoint re-raises through this before its generic `except+ Exception`, because that generic clause would otherwise flatten a+ diagnosable "your file is damaged" into an anonymous 500. The contract is+ covered by a test that walks the routes, so a new endpoint that forgets+ it fails CI rather than degrading quietly.+ """+ return HTTPException(+ status_code=409,+ detail={+ "code": "notebook_unreadable",+ "notebook_id": exc.notebook_id,+ "message": str(exc),+ },+ )++# === Request/Response Models ===@@ -58,7 +81,12 @@ class RemoveRecordRequest(BaseModel):class UpdateRecordRequest(BaseModel):- """Update an existing notebook record."""+ """Update an existing notebook record.++ Only the fields the client actually sends are forwarded (see+ ``exclude_unset`` at the call site), which is what keeps ``kb_name``+ from being wiped by a request that merely renames the record.+ """title: str | None = Nonesummary: str | None = None@@ -68,6 +96,12 @@ class UpdateRecordRequest(BaseModel):kb_name: str | None = None+class MoveRecordRequest(BaseModel):+ """Move or copy a record into another notebook."""++ target_notebook_id: str++# === API Endpoints ===@@ -137,6 +171,15 @@ async def _stream_add_record_with_summary(yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"+# NOTE: every literal path below must stay above the `/{notebook_id}` routes.+# FastAPI matches in declaration order, so a literal declared later is shadowed+# by the parameterised route and becomes unreachable.[email protected]("/health")+async def health_check():+ """Health check"""+ return {"status": "healthy", "service": "notebook"}++@router.get("/list")async def list_notebooks():"""@@ -148,6 +191,8 @@ async def list_notebooks():try:notebooks = notebook_manager.list_notebooks()return {"notebooks": notebooks, "total": len(notebooks)}+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -163,6 +208,8 @@ async def get_statistics():try:stats = notebook_manager.get_statistics()return stats+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -186,6 +233,8 @@ async def create_notebook(request: CreateNotebookRequest):icon=request.icon,)return {"success": True, "notebook": notebook}+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -208,6 +257,8 @@ async def get_notebook(notebook_id: str):return notebookexcept HTTPException:raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -237,6 +288,8 @@ async def update_notebook(notebook_id: str, request: UpdateNotebookRequest):return {"success": True, "notebook": notebook}except HTTPException:raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -259,6 +312,8 @@ async def delete_notebook(notebook_id: str):return {"success": True, "message": "Notebook deleted successfully"}except HTTPException:raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -292,6 +347,8 @@ async def add_record(request: AddRecordRequest):"record": result["record"],"added_to_notebooks": result["added_to_notebooks"],}+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -325,6 +382,8 @@ async def remove_record(notebook_id: str, record_id: str):return {"success": True, "message": "Record removed successfully"}except HTTPException:raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@@ -333,26 +392,77 @@ async def remove_record(notebook_id: str, record_id: str):async def update_record(notebook_id: str, record_id: str, request: UpdateRecordRequest):"""Update an existing notebook record in place."""try:+ # Forward only what the client actually sent. Passing every field+ # unconditionally would hand `kb_name=None` to the service on every+ # request and clear the record's knowledge-base link as a side effect+ # of renaming it; the service's sentinel default only works if an+ # omitted field never reaches it.+ changes = request.model_dump(exclude_unset=True)+ if not changes:+ raise HTTPException(status_code=400, detail="No fields to update")updated = notebook_manager.update_record(notebook_id=notebook_id,record_id=record_id,- title=request.title,- summary=request.summary,- user_query=request.user_query,- output=request.output,- metadata=request.metadata,- kb_name=request.kb_name,+ **changes,)if not updated:raise HTTPException(status_code=404, detail="Record not found")return {"success": True, "record": updated}except HTTPException:raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)except Exception as e:raise HTTPException(status_code=500, detail=str(e))[email protected]("/health")-async def health_check():- """Health check"""- return {"status": "healthy", "service": "notebook"}[email protected]("/{notebook_id}/records/{record_id}/copy")+async def copy_record(notebook_id: str, record_id: str, request: MoveRecordRequest):+ """Duplicate a record into another notebook under a fresh id."""+ try:+ copied = notebook_manager.copy_record(notebook_id, record_id, request.target_notebook_id)+ if not copied:+ raise HTTPException(status_code=404, detail="Record or target notebook not found")+ return {"success": True, "record": copied}+ except HTTPException:+ raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/{notebook_id}/records/{record_id}/move")+async def move_record(notebook_id: str, record_id: str, request: MoveRecordRequest):+ """Move a record from this notebook into another one."""+ try:+ moved = notebook_manager.move_record(notebook_id, record_id, request.target_notebook_id)+ if not moved:+ raise HTTPException(status_code=404, detail="Record or target notebook not found")+ return {"success": True, "record": moved}+ except HTTPException:+ raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))++[email protected]("/{notebook_id}/export", response_class=PlainTextResponse)+async def export_notebook(notebook_id: str):+ """Render the whole notebook as a single Markdown document."""+ try:+ markdown = notebook_manager.export_markdown(notebook_id)+ if markdown is None:+ raise HTTPException(status_code=404, detail="Notebook not found")+ return PlainTextResponse(+ markdown,+ media_type="text/markdown; charset=utf-8",+ headers={"Content-Disposition": f'attachment; filename="{notebook_id}.md"'},+ )+ except HTTPException:+ raise+ except NotebookCorruptedError as exc:+ raise _unreadable(exc)+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.pynew file mode 100644index 000000000..ba892d981--- /dev/null+++ b/deeptutor/api/routers/reading.py@@ -0,0 +1,364 @@+"""Immersive reading API — materials, unit text, annotations, export.++A thin adapter over :mod:`deeptutor.reading`: it validates HTTP inputs, maps+engine errors to status codes, and streams bytes. No reading logic lives here,+so the router and the capability's tools cannot drift apart — both call the same+service functions.++Per-user isolation comes from the path service, exactly as for notebooks: the+store resolves ``<user workspace>/reading`` at call time, so a request already+scoped to a user by the auth dependency reaches only that user's materials.++The raw-file route returns a ``FileResponse``, which serves HTTP Range requests.+That matters: it is what lets pdf.js load a large PDF incrementally instead of+pulling the whole file before rendering page one.+"""++from __future__ import annotations++import logging+from pathlib import Path+import shutil+import tempfile+from typing import Any, Literal++from fastapi import APIRouter, HTTPException, Query, UploadFile+from fastapi.params import File+from fastapi.responses import FileResponse, Response+from pydantic import BaseModel, Field++from deeptutor.reading import (+ ANNOTATION_COLORS,+ Annotation,+ MaterialNotFound,+ ReadingError,+ ReadingStore,+ export_material,+ render_outline,+)+from deeptutor.utils.document_validator import DocumentValidator++logger = logging.getLogger(__name__)++router = APIRouter()++# Streaming upload ceiling. Same number the extractor enforces, so a file that+# passes here cannot then be rejected deeper in with a less helpful message.+MAX_MATERIAL_BYTES = DocumentValidator.MAX_FILE_SIZE+_UPLOAD_CHUNK = 1024 * 1024+++def _store() -> ReadingStore:+ return ReadingStore()+++def _http_error(exc: Exception) -> HTTPException:+ """Map an engine error to the status code that describes it.++ 404 for "no such material", 400 for everything the caller can fix (bad+ locator, unsupported format, no extractable text). A 500 is reserved for+ failures that are genuinely ours.+ """+ if isinstance(exc, MaterialNotFound):+ return HTTPException(status_code=404, detail=str(exc))+ if isinstance(exc, ReadingError):+ return HTTPException(status_code=400, detail=str(exc))+ logger.warning("unexpected reading error", exc_info=True)+ return HTTPException(status_code=500, detail="The reader could not complete that request.")+++# === Models ===================================================================+++class MaterialInfo(BaseModel):+ material_id: str+ filename: str+ unit: str+ unit_count: int+ mime: str = ""+ title: str = ""+ byte_size: int = 0+ char_count: int = 0+ created_at: float = 0.0+ has_raw_view: bool = False+ annotation_count: int = 0+++class MaterialDetail(MaterialInfo):+ outline: list[dict[str, Any]] = Field(default_factory=list)+ outline_text: str = ""+++class UnitText(BaseModel):+ locator: int+ unit: str+ text: str+++class AnnotationPayload(BaseModel):+ """An annotation as the reader sends it.++ ``rects`` are normalised to the unit box (0..1, origin top-left) by the+ client, because only the client knows the rendered geometry. They are still+ re-validated server-side — an inverted or out-of-range rectangle is ordered+ and clipped rather than trusted.+ """++ annotation_id: str = ""+ locator: int = Field(ge=1)+ kind: Literal["highlight", "underline", "note"] = "highlight"+ color: str = "yellow"+ quote: str = ""+ note: str = ""+ rects: list[list[float]] = Field(default_factory=list)++ def to_annotation(self) -> Annotation:+ return Annotation.from_dict(+ {+ "annotation_id": self.annotation_id,+ "locator": self.locator,+ "kind": self.kind,+ "color": self.color if self.color in ANNOTATION_COLORS else "yellow",+ "quote": self.quote,+ "note": self.note,+ "rects": self.rects,+ "author": "user",+ }+ )+++class AnnotationInfo(BaseModel):+ annotation_id: str+ locator: int+ kind: str+ color: str+ quote: str+ note: str+ rects: list[list[float]]+ author: str+ created_at: float+ updated_at: float+++class SupportedFormats(BaseModel):+ extensions: list[str]+ max_bytes: int+ raw_view_extensions: list[str]+++# === Routes ===================================================================++[email protected]("/supported-formats", response_model=SupportedFormats)+async def supported_formats() -> SupportedFormats:+ """What the reader accepts — the single source of truth for the file picker."""+ from deeptutor.reading.extract import RAW_VIEW_EXTENSIONS+ from deeptutor.utils.document_extractor import SUPPORTED_DOC_EXTENSIONS++ return SupportedFormats(+ extensions=sorted(SUPPORTED_DOC_EXTENSIONS),+ max_bytes=MAX_MATERIAL_BYTES,+ raw_view_extensions=sorted(RAW_VIEW_EXTENSIONS),+ )++[email protected]("/materials", response_model=list[MaterialInfo])+async def list_materials() -> list[MaterialInfo]:+ store = _store()+ try:+ return [_info(store, manifest) for manifest in store.list_materials()]+ except Exception as exc:+ raise _http_error(exc) from exc++[email protected]("/materials", response_model=MaterialDetail)+async def upload_material(file: UploadFile = File(...)) -> MaterialDetail: # noqa: B008+ """Ingest an uploaded document and return it ready to read.++ The upload is streamed to a temp file with a running size check, so an+ oversized file is rejected before it is fully buffered rather than after.+ """+ filename = (file.filename or "").strip()+ if not filename:+ raise HTTPException(status_code=400, detail="The upload has no filename.")++ tmp_dir = Path(tempfile.mkdtemp(prefix="dt-reading-"))+ tmp_path = tmp_dir / Path(filename).name+ written = 0+ try:+ with tmp_path.open("wb") as sink:+ while chunk := await file.read(_UPLOAD_CHUNK):+ written += len(chunk)+ if written > MAX_MATERIAL_BYTES:+ raise HTTPException(+ status_code=413,+ detail=(+ f"{filename} exceeds the "+ f"{MAX_MATERIAL_BYTES // (1024 * 1024)} MB limit."+ ),+ )+ sink.write(chunk)+ if written == 0:+ raise HTTPException(status_code=400, detail=f"{filename} is empty.")++ store = _store()+ manifest = store.ingest(tmp_path, filename=filename)+ return _detail(store, manifest)+ except HTTPException:+ raise+ except Exception as exc:+ raise _http_error(exc) from exc+ finally:+ shutil.rmtree(tmp_dir, ignore_errors=True)++[email protected]("/materials/{material_id}", response_model=MaterialDetail)+async def get_material(material_id: str) -> MaterialDetail:+ store = _store()+ try:+ return _detail(store, store.manifest(material_id))+ except Exception as exc:+ raise _http_error(exc) from exc++[email protected]("/materials/{material_id}")+async def delete_material(material_id: str) -> dict[str, Any]:+ store = _store()+ try:+ removed = store.delete(material_id)+ except Exception as exc:+ raise _http_error(exc) from exc+ if not removed:+ raise HTTPException(status_code=404, detail=f"material {material_id!r} not found")+ return {"status": "ok", "material_id": material_id}++[email protected]("/materials/{material_id}/units/{locator}", response_model=UnitText)+async def get_unit(material_id: str, locator: int) -> UnitText:+ """One unit's text — the reader's text view, and the only view for non-PDFs."""+ store = _store()+ try:+ manifest = store.manifest(material_id)+ return UnitText(+ locator=locator,+ unit=manifest.unit,+ text=store.unit_text(material_id, locator),+ )+ except Exception as exc:+ raise _http_error(exc) from exc++[email protected]("/materials/{material_id}/raw")+async def get_raw(material_id: str) -> FileResponse:+ """The original bytes, for the faithful viewer. Serves Range requests."""+ store = _store()+ try:+ manifest = store.manifest(material_id)+ path = store.raw_path(material_id)+ except Exception as exc:+ raise _http_error(exc) from exc+ if path is None or not path.is_file():+ raise HTTPException(+ status_code=404,+ detail=f"{manifest.filename} has no stored original to render.",+ )+ return FileResponse(+ path,+ media_type=manifest.mime or "application/octet-stream",+ filename=manifest.filename,+ content_disposition_type="inline",+ )++[email protected]("/materials/{material_id}/annotations", response_model=list[AnnotationInfo])+async def list_annotations(material_id: str) -> list[AnnotationInfo]:+ store = _store()+ try:+ return [_annotation_info(row) for row in store.annotations(material_id)]+ except Exception as exc:+ raise _http_error(exc) from exc++[email protected]("/materials/{material_id}/annotations", response_model=AnnotationInfo)+async def save_annotation(material_id: str, payload: AnnotationPayload) -> AnnotationInfo:+ """Create or update one annotation (id absent = create)."""+ store = _store()+ try:+ saved = store.save_annotation(material_id, payload.to_annotation())+ except Exception as exc:+ raise _http_error(exc) from exc+ return _annotation_info(saved)++[email protected]("/materials/{material_id}/annotations/{annotation_id}")+async def delete_annotation(material_id: str, annotation_id: str) -> dict[str, Any]:+ store = _store()+ try:+ removed = store.delete_annotation(material_id, annotation_id)+ except Exception as exc:+ raise _http_error(exc) from exc+ if not removed:+ raise HTTPException(status_code=404, detail="annotation not found")+ return {"status": "ok", "annotation_id": annotation_id}++[email protected]("/materials/{material_id}/export")+async def export(+ material_id: str,+ fmt: Literal["auto", "pdf", "markdown"] = Query("auto"),+) -> Response:+ """Download the material with its annotations applied.++ ``pdf`` writes real PDF annotations into a copy of the original, so the+ export keeps working outside DeepTutor; ``markdown`` returns the marks as+ text, which is what every non-PDF format gets.+ """+ store = _store()+ try:+ result = export_material(store, material_id, fmt=fmt)+ except Exception as exc:+ raise _http_error(exc) from exc+ return Response(+ content=result.data,+ media_type=result.media_type,+ headers={+ "Content-Disposition": _attachment_header(result.filename),+ "Content-Length": str(result.byte_size),+ },+ )+++# === Helpers ==================================================================+++def _info(store: ReadingStore, manifest: Any) -> MaterialInfo:+ return MaterialInfo(+ **manifest.to_dict() | {"annotation_count": len(store.annotations(manifest.material_id))}+ )+++def _detail(store: ReadingStore, manifest: Any) -> MaterialDetail:+ outline = store.outline(manifest.material_id)+ return MaterialDetail(+ **manifest.to_dict()+ | {+ "annotation_count": len(store.annotations(manifest.material_id)),+ "outline": [entry.to_dict() for entry in outline],+ "outline_text": render_outline(store, manifest.material_id),+ }+ )+++def _annotation_info(row: Annotation) -> AnnotationInfo:+ return AnnotationInfo(**row.to_dict())+++def _attachment_header(filename: str) -> str:+ """RFC 5987 disposition so non-ASCII names survive the round trip."""+ from urllib.parse import quote++ ascii_fallback = filename.encode("ascii", "ignore").decode("ascii") or "export"+ return f"attachment; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quote(filename)}"+++__all__ = ["MAX_MATERIAL_BYTES", "router"]diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 5ce7fbb94..bfea48fb7 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -50,7 +50,10 @@ from deeptutor.services.path_service import get_path_servicefrom deeptutor.services.settings.interface_settings import (DEFAULT_UI_SETTINGS as INTERFACE_DEFAULTS,)-from deeptutor.services.settings.interface_settings import resolve_languages+from deeptutor.services.settings.interface_settings import (+ atomic_update,+ resolve_languages,+)from deeptutor.services.settings.starter_settings import (TRACE_COUNT_RANGE as STARTER_TRACE_COUNT_RANGE,)@@ -370,10 +373,26 @@ def get_enabled_optional_tools() -> list[str]:def save_ui_settings(settings: dict[str, Any]) -> None:- settings_file = _settings_file()- settings_file.parent.mkdir(parents=True, exist_ok=True)- with open(settings_file, "w", encoding="utf-8") as handle:- json.dump(settings, handle, ensure_ascii=False, indent=2)+ """Replace the whole stored UI settings document.++ Writes through ``atomic_update`` rather than opening the file here, so this+ module and the setup capability — which both write ``interface.json`` —+ share one lock and one atomic replace. A lock held by only one of two+ writers protects nothing: measured with the old direct write, six concurrent+ router saves alongside six capability writes lost every one of the router's.++ Prefer :func:`patch_ui_settings` for changing individual fields. This+ replaces the whole document, so a caller that builds it from+ ``load_ui_settings`` writes the merged defaults back as stored values and+ stops following later changes to any of them.+ """+ payload = dict(settings)+ atomic_update(_settings_file(), lambda _stored: payload)+++def patch_ui_settings(**fields: Any) -> None:+ """Change individual UI fields without rewriting the rest of the document."""+ atomic_update(_settings_file(), lambda stored: {**stored, **fields})def _require_settings_admin() -> None:@@ -1298,17 +1317,13 @@ async def fetch_models_from_provider(payload: FetchModelsPayload):@router.put("/theme")async def update_theme(update: ThemeUpdate):- current_ui = load_ui_settings()- current_ui["theme"] = update.theme- save_ui_settings(current_ui)+ patch_ui_settings(theme=update.theme)return {"theme": update.theme}@router.put("/language")async def update_language(update: LanguageUpdate):- current_ui = load_ui_settings()- current_ui["language"] = update.language- save_ui_settings(current_ui)+ patch_ui_settings(language=update.language)return {"language": update.language}@@ -1319,9 +1334,7 @@ async def update_voice_autoplay(update: VoiceAutoplayUpdate):A personal UI preference (any authenticated user); the chat surface layersa per-session override on top of this value."""- current_ui = load_ui_settings()- current_ui["voice_autoplay"] = update.voice_autoplay- save_ui_settings(current_ui)+ patch_ui_settings(voice_autoplay=update.voice_autoplay)return {"voice_autoplay": update.voice_autoplay}@@ -1333,9 +1346,7 @@ async def update_chat_response_timeout(update: ChatResponseTimeoutUpdate):video generation can take longer than the old 60s default, so this isuser-adjustable; the chat surface reads it client-side."""- current_ui = load_ui_settings()- current_ui["chat_response_timeout"] = update.chat_response_timeout- save_ui_settings(current_ui)+ patch_ui_settings(chat_response_timeout=update.chat_response_timeout)return {"chat_response_timeout": update.chat_response_timeout}@@ -1371,11 +1382,12 @@ async def update_ui_settings(update: UISettingsUpdate):by the frontend override saved values. Fields not in the frontend payload(even if they equal the model defaults) are omitted from the merge."""- current_ui = load_ui_settings()dump = update.model_dump(exclude_unset=True) # Only merge explicitly provided fields- current_ui.update(dump)- save_ui_settings(current_ui)- return current_ui+ # Merged into the stored document, not into the defaults-merged view: saving+ # that view back would freeze today's defaults as this user's explicit+ # choices. The response keeps returning the merged view clients expect.+ patch_ui_settings(**dump)+ return load_ui_settings()@router.post("/reset")@@ -1409,26 +1421,20 @@ async def get_sidebar_settings():@router.put("/sidebar/description")async def update_sidebar_description(update: SidebarDescriptionUpdate):- current_ui = load_ui_settings()- current_ui["sidebar_description"] = update.description- save_ui_settings(current_ui)+ patch_ui_settings(sidebar_description=update.description)return {"description": update.description}@router.put("/sidebar/nav-order")async def update_sidebar_nav_order(update: SidebarNavOrderUpdate):- current_ui = load_ui_settings()- current_ui["sidebar_nav_order"] = update.nav_order.model_dump()- save_ui_settings(current_ui)+ patch_ui_settings(sidebar_nav_order=update.nav_order.model_dump())return {"nav_order": update.nav_order.model_dump()}@router.put("/enabled-tools")async def update_enabled_tools(update: EnabledToolsUpdate):sanitized = _sanitize_enabled_tools(update.enabled_tools)- current_ui = load_ui_settings()- current_ui["enabled_optional_tools"] = sanitized- save_ui_settings(current_ui)+ patch_ui_settings(enabled_optional_tools=sanitized)return {"enabled_optional_tools": sanitized}diff --git a/deeptutor/book/agents/source_explorer.py b/deeptutor/book/agents/source_explorer.pyindex 45de2669c..8cb6ea1e4 100644--- a/deeptutor/book/agents/source_explorer.py+++ b/deeptutor/book/agents/source_explorer.py@@ -331,28 +331,33 @@ class SourceExplorer(BaseAgent):@staticmethoddef partition_knowledge_bases(kb_list: list[str]) -> tuple[list[str], list[str]]:- """Split *kb_list* into (retrievable, connected).-- Connected KBs are pointers — an Obsidian vault, a subagent CLI, a remote- LightRAG or IMA library — with no local index for ``rag_search`` to hit.- Sweeping them anyway returned nothing and looked identical to a source- that simply had no relevant content, so the reader never learned their- vault contributed zero. Reaching them properly means driving each- capability, which is a separate piece of work; naming them is the- honest interim.+ """Split *kb_list* into (retrievable, unreachable).++ Only the KBs ``rag_search`` genuinely cannot reach are set aside: an+ Obsidian vault (no index — its capability navigates live files) and a+ connected subagent (not a document collection). Sweeping those returned+ nothing and looked identical to a source that simply had no relevant+ content, so the reader never learned their vault contributed zero;+ reaching them properly means driving each capability, which is separate+ work, and naming them is the honest interim.++ Every other pointer KB *is* retrievable and is swept normally — a+ ``linked`` folder mounts an index built elsewhere, and ``lightrag_server``+ / ``ima`` offload retrieval over HTTP. Treating "connected" as+ "unsearchable" silently dropped those sources from every book."""retrievable: list[str] = []- connected: list[str] = []+ unreachable: list[str] = []for kb in kb_list:try:- from deeptutor.knowledge.kb_types import is_connected_kb+ from deeptutor.knowledge.kb_types import supports_rag_retrievalfrom deeptutor.multi_user.knowledge_access import resolve_kb_metadatameta = resolve_kb_metadata(kb)except Exception: # noqa: BLE001 - unresolvable → treat as ordinarymeta = None- (connected if meta and is_connected_kb(meta) else retrievable).append(kb)- return retrievable, connected+ (retrievable if supports_rag_retrieval(meta) else unreachable).append(kb)+ return retrievable, unreachableasync def _retrieve_kb_chunks(self,diff --git a/deeptutor/capabilities/ima/__init__.py b/deeptutor/capabilities/ima/__init__.pynew file mode 100644index 000000000..61c682182--- /dev/null+++ b/deeptutor/capabilities/ima/__init__.py@@ -0,0 +1,6 @@+"""IMA loop capability — inventory, source reading and authoring over a live library."""++from deeptutor.capabilities.ima.capability import ImaCapability+from deeptutor.capabilities.ima.tools import IMA_TOOL_NAMES, IMA_TOOL_TYPES++__all__ = ["IMA_TOOL_NAMES", "IMA_TOOL_TYPES", "ImaCapability"]diff --git a/deeptutor/capabilities/ima/binding.py b/deeptutor/capabilities/ima/binding.pynew file mode 100644index 000000000..c90ce262d--- /dev/null+++ b/deeptutor/capabilities/ima/binding.py@@ -0,0 +1,117 @@+"""Resolve which connected Tencent IMA libraries the current turn can reach.++The binding is derived once per turn from the user's selected knowledge bases:+every selection whose KB metadata is ``type == ima`` becomes a library the IMA+tools may operate on. Unlike the Obsidian binding (one live vault per turn) all+selected IMA libraries are kept, because a turn can legitimately browse one and+read from another — the tools take an explicit ``kb_name`` when there is more+than one.++Credentials are deliberately *not* part of a binding. What a tool call carries is+the KB reference; the credential pair is loaded from ``kb_config.json`` at call+time by :func:`resolve_client`, which also re-runs the per-user access check. So+no secret is ever placed in tool kwargs (where a trace or a log could pick it up),+and a model cannot reach a library by naming one that was not selected.+"""++from __future__ import annotations++from dataclasses import dataclass++from deeptutor.core.context import UnifiedContext+from deeptutor.knowledge.kb_types import IMA_KB_TYPE++# Cached on context.metadata: a tuple of bindings, empty once we have looked and+# found none. Absence of the key means "not resolved yet".+_CACHE_KEY = "_ima_bindings"+++@dataclass(frozen=True, slots=True)+class ImaBinding:+ """One selected knowledge base that points at a Tencent IMA library."""++ kb_ref: str+ """The reference as the user selected it (name or id) — what tools pass back."""++ name: str+ """Display name, used to match a model-supplied ``kb_name``."""++ knowledge_base_id: str+ """Which IMA library this KB reads. Not a secret (it is shown in the UI)."""+++def ima_bindings(context: UnifiedContext) -> tuple[ImaBinding, ...]:+ """Every connected IMA library among this turn's selected knowledge bases."""+ cached = context.metadata.get(_CACHE_KEY)+ if cached is not None:+ return tuple(cached)+ resolved = _resolve(context)+ context.metadata[_CACHE_KEY] = resolved+ return resolved+++def select_binding(+ bindings: tuple[ImaBinding, ...],+ kb_name: str | None = None,+) -> ImaBinding | None:+ """The binding a tool call targets, chosen from what the turn made available.++ With one selected library the argument is optional (and ignored when it does+ not match, since there is no ambiguity to resolve). With several, an+ unmatched name resolves to ``None`` so the tool can ask for a valid one+ instead of silently operating on the wrong library. A pure function over the+ turn's bindings — the model can only ever reach a library that was selected.+ """+ if not bindings:+ return None+ requested = str(kb_name or "").strip()+ if not requested:+ return bindings[0] if len(bindings) == 1 else None+ for binding in bindings:+ if requested in {binding.kb_ref, binding.name, binding.knowledge_base_id}:+ return binding+ return bindings[0] if len(bindings) == 1 else None+++def resolve_client(kb_ref: str, *, for_write: bool = False):+ """An :class:`ImaClient` for *kb_ref*, after re-checking the user's access.++ Raises ``ImaNotConfiguredError`` when the KB (or the account settings) lacks+ a complete credential pair, and ``fastapi.HTTPException`` when the reference+ is not accessible to the current user — writes require write access, since+ they modify the user's own IMA library.+ """+ from deeptutor.multi_user.knowledge_access import resolve_kb+ from deeptutor.services.rag.pipelines.ima.client import ImaClient+ from deeptutor.services.rag.pipelines.ima.config import resolve_kb_config+ from deeptutor.services.rag.provider_binding import load_kb_config_entry++ resource = resolve_kb(str(kb_ref), require_write=for_write)+ entry = load_kb_config_entry(resource.base_dir, resource.name)+ return ImaClient(resolve_kb_config(entry))+++def _resolve(context: UnifiedContext) -> tuple[ImaBinding, ...]:+ from deeptutor.multi_user.knowledge_access import resolve_kb_metadata++ bindings: list[ImaBinding] = []+ seen: set[str] = set()+ for raw in context.knowledge_bases or []:+ ref = str(raw).strip()+ if not ref or ref in seen:+ continue+ seen.add(ref)+ meta = resolve_kb_metadata(ref)+ if not meta or meta.get("type") != IMA_KB_TYPE:+ continue+ bindings.append(+ ImaBinding(+ kb_ref=ref,+ name=str(meta.get("name") or ref),+ knowledge_base_id=str(meta.get("knowledge_base_id") or ""),+ )+ )+ return tuple(bindings)+++__all__ = ["ImaBinding", "ima_bindings", "resolve_client", "select_binding"]diff --git a/deeptutor/capabilities/ima/capability.py b/deeptutor/capabilities/ima/capability.pynew file mode 100644index 000000000..3a963452d--- /dev/null+++ b/deeptutor/capabilities/ima/capability.py@@ -0,0 +1,103 @@+"""IMA loop capability — inventory, source reading and authoring over a live library.++Active whenever one of the turn's selected knowledge bases is a connected Tencent+IMA library (resolved by :mod:`deeptutor.capabilities.ima.binding`).++Unlike the Obsidian and subagent capabilities this is a *plain*+:class:`~deeptutor.capabilities.protocol.LoopCapability`, not a+:class:`~deeptutor.capabilities.protocol.KnowledgeCapability`: it **adds** its+tools to chat's normal surface instead of replacing it. That difference is not+stylistic — it follows from what the KB actually is. An Obsidian vault has no+index at all, so ``rag`` is useless against it and the capability must own the+turn. An IMA library is genuinely searchable over HTTP: the ``ima`` RAG provider+answers ``rag`` calls for it. Retrieval therefore stays where it belongs, and+these tools add only what retrieval cannot do — enumerate the library, read a+whole source, search notes by recency, and write back.++Keeping the surface additive also means a turn that attaches an IMA library+alongside other knowledge bases (or that needs web search) does not lose those+abilities, which an exclusive capability would strip.+"""++from __future__ import annotations++from importlib import resources+from typing import Any++from deeptutor.capabilities.ima.binding import ima_bindings+from deeptutor.capabilities.ima.tools import BINDINGS_KWARG, IMA_TOOL_NAMES+from deeptutor.capabilities.protocol import PromptBlock+from deeptutor.core.context import UnifiedContext+++class ImaCapability:+ """Turn-scoped integration for connected Tencent IMA knowledge bases."""++ name = "ima"+ owned_tools = IMA_TOOL_NAMES++ def is_active(self, context: UnifiedContext) -> bool:+ return bool(ima_bindings(context))++ def system_block(+ self,+ context: UnifiedContext,+ *,+ language: str,+ prompts: dict[str, Any],+ ) -> PromptBlock | None:+ bindings = ima_bindings(context)+ if not bindings:+ return None+ override = _prompt_text(prompts, ("ima", "system"))+ content = override or _load_system_prompt(language)+ names = (+ "、".join(binding.name for binding in bindings)+ if _is_zh(language)+ else ", ".join(binding.name for binding in bindings)+ )+ return PromptBlock("ima", content.replace("{kb_names}", names))++ def augment_kwargs(+ self,+ tool_name: str,+ kwargs: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ if tool_name not in IMA_TOOL_NAMES:+ return kwargs+ bindings = ima_bindings(context)+ if not bindings:+ return kwargs+ # Server-owned: overwrite any model-supplied value so a turn can only+ # reach the libraries the user actually attached. Credentials are not+ # part of this payload — the tools load them per call.+ updated = dict(kwargs)+ updated[BINDINGS_KWARG] = bindings+ return updated++ def pre_loop_seed(self, context: UnifiedContext) -> str:+ _ = context+ return ""+++def _prompt_text(prompts: dict[str, Any], path: tuple[str, ...]) -> str:+ value: Any = prompts+ for key in path:+ if not isinstance(value, dict):+ return ""+ value = value.get(key)+ return value if isinstance(value, str) and value else ""+++def _is_zh(language: str) -> bool:+ return str(language or "en").lower().startswith("zh")+++def _load_system_prompt(language: str) -> str:+ lang = "zh" if _is_zh(language) else "en"+ prompt = resources.files(__package__).joinpath("prompts", lang, "system.md")+ return prompt.read_text(encoding="utf-8").strip()+++__all__ = ["ImaCapability"]diff --git a/deeptutor/capabilities/ima/prompts/en/system.md b/deeptutor/capabilities/ima/prompts/en/system.mdnew file mode 100644index 000000000..5df2388db--- /dev/null+++ b/deeptutor/capabilities/ima/prompts/en/system.md@@ -0,0 +1,33 @@+# Tencent IMA Library++The user has attached their Tencent IMA knowledge base **{kb_names}** to this+turn. Its documents live in IMA, not on this machine: everything below is an API+call against the user's own library. Your normal tools stay available — the IMA+tools are additional.++## Which tool answers which question++- **"What does the material say about X?"** → `rag` with this knowledge base.+ That is IMA's semantic search, and it stays the way to find content.+- **"What's in here?" / "Is document X in it?" / "What's in that folder?"** →+ `ima_list`. Retrieval only reports what a query happened to match, so it can+ never establish what the library contains. Never infer the inventory from+ retrieved passages, and never claim the document list cannot be read.+- **"Give me the whole document" / a retrieved snippet is too thin** →+ `ima_read` with the item's `media_id` (from `ima_list` or a citation).+- **"My latest notes" / "what did I write about X?"** → `ima_note_search`.+ Notes carry created/updated timestamps; knowledge-base documents do not, so+ recency questions about documents can only be answered by the order `ima_list`+ returns them in — say so rather than inventing dates.++## Writing (only when asked)++`ima_add_url` collects web pages into the library and `ima_write_note` saves a+note. Both modify the user's own IMA account, so use them only when the user+asked to save, collect, or record something — never as a side effect of+answering. Appending to an existing note cannot be undone: only append to a note+the user actually named, otherwise create a new one. Nothing you can call+deletes or overwrites their material.++Answer grounded in what you read, citing document or note titles. If the library+does not cover something, say so instead of guessing.diff --git a/deeptutor/capabilities/ima/prompts/zh/system.md b/deeptutor/capabilities/ima/prompts/zh/system.mdnew file mode 100644index 000000000..6c7f77c24--- /dev/null+++ b/deeptutor/capabilities/ima/prompts/zh/system.md@@ -0,0 +1,24 @@+# 腾讯 IMA 知识库++用户已把腾讯 IMA 知识库 **{kb_names}** 挂载到本轮对话。它的文档存放在 IMA 而不在本机,+下面每一项都是对用户自己那个库的接口调用。你原有的工具依然可用,IMA 工具是额外增加的。++## 什么问题用什么工具++- **「资料里怎么说 X」** → 对该知识库调用 `rag`。那就是 IMA 的语义检索,找内容仍然走它。+- **「这里面有什么」「有没有某个文档」「那个文件夹里是什么」** → `ima_list`。+ 检索只能反映某次查询命中了什么,永远无法说明库里到底有哪些东西。+ 不要用检索到的片段去推断文档构成,也不要声称读不到文档清单。+- **「把整篇给我」或检索片段太薄** → 用条目的 `media_id`(来自 `ima_list` 或引用)调 `ima_read`。+- **「我最近的笔记」「我写过什么关于 X 的」** → `ima_note_search`。+ 笔记带创建/更新时间,知识库文档没有时间字段;因此关于文档「最新」的问题只能依据+ `ima_list` 的返回顺序,如实说明,不要编造日期。++## 写入(仅在用户要求时)++`ima_add_url` 把网页收进知识库,`ima_write_note` 保存笔记。两者都会改动用户自己的 IMA 账号,+所以只有在用户明确要求保存、收藏、记录时才使用,绝不作为回答的副作用。+往已有笔记追加内容不可撤销:只追加到用户明确指名的那篇,否则新建一篇。+你能调用的工具都不会删除或覆盖用户的资料。++回答要基于你读到的内容,并标注文档或笔记标题。库里没有覆盖的内容,如实说明,不要猜。diff --git a/deeptutor/capabilities/ima/tools.py b/deeptutor/capabilities/ima/tools.pynew file mode 100644index 000000000..4e5a79086--- /dev/null+++ b/deeptutor/capabilities/ima/tools.py@@ -0,0 +1,476 @@+"""IMA tools — the agentic surface over a connected Tencent IMA library.++Five tools, auto-mounted only when a ``type: ima`` knowledge base is selected+(see :class:`~deeptutor.capabilities.ima.capability.ImaCapability`). They cover+the questions retrieval structurally cannot answer, plus the two additive writes:++* ``ima_list`` — browse what the library holds, folder by folder. "What's in+ here", "did I add X", "show me the folder Y" are inventory questions; a+ similarity search cannot answer them.+* ``ima_read`` — the full source text of one item, when a retrieved snippet is+ not enough.+* ``ima_note_search`` — search or list IMA notes, newest first. Notes are the+ only IMA objects carrying timestamps, so this is what answers "my most recent+ notes".+* ``ima_add_url`` — collect a web page / WeChat article into the library.+* ``ima_write_note`` — create a note, or append to one the user named.++The turn's available libraries are injected server-side as ``_ima_bindings``;+the model supplies at most a ``kb_name`` to pick between them, and credentials+are loaded per call from the KB's own config (never passed through kwargs).+"""++from __future__ import annotations++import json+from typing import Any++from deeptutor.capabilities.ima.binding import ImaBinding, resolve_client, select_binding+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult++# The IMA service modules are imported lazily inside the methods that need them:+# this module is imported while ``deeptutor.tools.builtin`` builds the global tool+# table, and reaching into ``deeptutor.services.rag`` at import time would close+# a cycle through the runtime tool registry.++# Tool names mounted together when an IMA library is selected. Single source of+# truth so the mount policy and the registration list can't disagree.+IMA_TOOL_NAMES: tuple[str, ...] = (+ "ima_list",+ "ima_read",+ "ima_note_search",+ "ima_add_url",+ "ima_write_note",+)++# Injected by the capability: the turn's selected IMA libraries.+BINDINGS_KWARG = "_ima_bindings"++_KB_NAME_PARAM = ToolParameter(+ name="kb_name",+ type="string",+ description=("Which attached IMA knowledge base to use. Optional when only one is attached."),+ required=False,+)+++def _note_sort(name: Any) -> int:+ """Map a tool-level sort name onto IMA's numeric ``sort_type``."""+ from deeptutor.services.rag.pipelines.ima.notes import (+ SORT_BY_CREATED,+ SORT_BY_TITLE,+ SORT_BY_UPDATED,+ )++ return {+ "updated": SORT_BY_UPDATED,+ "created": SORT_BY_CREATED,+ "title": SORT_BY_TITLE,+ }.get(str(name or "updated"), SORT_BY_UPDATED)+++class _ImaTool(BaseTool):+ """Shared binding resolution and uniform error handling for IMA tools."""++ #: Writes re-check the user's write access to the knowledge base.+ writes = False++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.services.rag.pipelines.ima.config import ImaNotConfiguredError+ from deeptutor.services.rag.pipelines.ima.envelope import (+ ImaAPIError,+ ImaAuthError,+ ImaRateLimitError,+ )++ bindings = _bindings(kwargs)+ binding = select_binding(bindings, kwargs.get("kb_name"))+ if binding is None:+ return _err(_no_binding_message(bindings))+ try:+ client = resolve_client(binding.kb_ref, for_write=self.writes)+ except ImaNotConfiguredError as exc:+ return _err(str(exc))+ except Exception:+ return _err(+ f"'{binding.name}' is not available on this turn"+ f"{' with write access' if self.writes else ''}."+ )+ try:+ return await self._run(client, binding, kwargs)+ except ImaAuthError:+ return _err("Tencent IMA rejected the credentials for this knowledge base.")+ except ImaRateLimitError:+ return _err("Tencent IMA is rate-limiting requests. Try again shortly.")+ except ImaAPIError as exc:+ return _err(str(exc))+ except ValueError as exc:+ return _err(str(exc))++ async def _run(+ self,+ client: Any,+ binding: ImaBinding,+ kwargs: dict[str, Any],+ ) -> ToolResult: # pragma: no cover - abstract+ raise NotImplementedError+++class ImaListTool(_ImaTool):+ """Browse a connected IMA library's contents."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="ima_list",+ description=(+ "List what a connected Tencent IMA knowledge base actually holds: its "+ "documents and folders. Use this for inventory questions ('what is in "+ "here', 'is document X present', 'show me folder Y') — retrieval only "+ "reports what a query matched. Pass a folder_id from a previous call to "+ "look inside that folder."+ ),+ parameters=[+ _KB_NAME_PARAM,+ ToolParameter(+ name="folder_id",+ type="string",+ description="Folder to open, from an earlier listing. Omit for the top level.",+ required=False,+ ),+ ToolParameter(+ name="limit",+ type="integer",+ description="Max entries to return (1-50, default 50).",+ required=False,+ ),+ ToolParameter(+ name="cursor",+ type="string",+ description="Continuation cursor from an earlier call's next_cursor.",+ required=False,+ ),+ ],+ )++ async def _run(self, client, binding, kwargs):+ page = await client.get_knowledge_list(+ folder_id=str(kwargs.get("folder_id") or ""),+ cursor=str(kwargs.get("cursor") or ""),+ limit=kwargs.get("limit") or 50,+ )+ return _ok(+ {+ "knowledge_base": binding.name,+ "path": list(page.path),+ "folders": [+ {+ "folder_id": folder.folder_id,+ "name": folder.name,+ "documents": folder.file_number,+ "subfolders": folder.folder_number,+ }+ for folder in page.folders+ ],+ "documents": [+ {"media_id": document.media_id, "title": document.title}+ for document in page.documents+ ],+ "next_cursor": page.next_cursor,+ "is_end": page.is_end,+ }+ )+++class ImaReadTool(_ImaTool):+ """Read one IMA item's full source text."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="ima_read",+ description=(+ "Read the full text of one item in a connected Tencent IMA knowledge "+ "base, identified by the media_id from ima_list or a retrieval citation. "+ "Use it when a retrieved snippet is too short to answer from."+ ),+ parameters=[+ ToolParameter(+ name="media_id",+ type="string",+ description="Item id from ima_list or a retrieval result.",+ ),+ _KB_NAME_PARAM,+ ],+ )++ async def _run(self, client, binding, kwargs):+ from deeptutor.services.rag.pipelines.ima import media as media_ops+ from deeptutor.services.rag.pipelines.ima import sources as source_policy++ media_id = str(kwargs.get("media_id") or "").strip()+ if not media_id:+ raise ValueError("media_id is required.")+ media = await client.get_media_content(media_id)+ text = await media_ops.extract_text(+ media,+ max_chars=source_policy.MAX_FULLTEXT_CHARS,+ )+ if not text:+ return _err(+ "That item has no readable text — it may be an image, an audio file, "+ "or a format Tencent IMA does not expose over the API."+ )+ return _ok(+ {+ "knowledge_base": binding.name,+ "media_id": media_id,+ "truncated": len(text) >= source_policy.MAX_FULLTEXT_CHARS,+ "content": text,+ }+ )+++class ImaNoteSearchTool(_ImaTool):+ """Search or list the user's IMA notes."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="ima_note_search",+ description=(+ "Search the user's Tencent IMA notes, or list them newest-first when no "+ "query is given. Notes are the only IMA objects with timestamps, so this "+ "is how to answer 'my latest notes' or 'what did I write about X'."+ ),+ parameters=[+ ToolParameter(+ name="query",+ type="string",+ description="Text to match. Omit to list notes in sort order.",+ required=False,+ ),+ ToolParameter(+ name="in_content",+ type="boolean",+ description="Search note bodies instead of titles (default false).",+ required=False,+ ),+ ToolParameter(+ name="sort",+ type="string",+ description="Order: updated (default), created, or title.",+ required=False,+ enum=["updated", "created", "title"],+ ),+ ToolParameter(+ name="limit",+ type="integer",+ description="Max notes to return (1-50, default 20).",+ required=False,+ ),+ _KB_NAME_PARAM,+ ],+ )++ async def _run(self, client, binding, kwargs):+ notes, is_end = await client.notes.search_notes(+ str(kwargs.get("query") or ""),+ by_content=bool(kwargs.get("in_content")),+ sort_type=_note_sort(kwargs.get("sort")),+ limit=kwargs.get("limit") or 20,+ )+ return _ok(+ {+ "notes": [+ {+ "note_id": note.note_id,+ "title": note.title,+ "summary": note.summary,+ "notebook": note.folder_name,+ "created_at": note.created_at,+ "updated_at": note.updated_at,+ }+ for note in notes+ ],+ "is_end": is_end,+ }+ )+++class ImaAddUrlTool(_ImaTool):+ """Collect web pages into a connected IMA library."""++ writes = True++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="ima_add_url",+ description=(+ "Add web pages or WeChat articles (up to 10 URLs) to a connected Tencent "+ "IMA knowledge base, so IMA indexes them for later retrieval. Only call "+ "this when the user asked to save or collect something — it modifies "+ "their library. Video pages (Bilibili / YouTube) and local files are not "+ "supported by IMA's API."+ ),+ parameters=[+ ToolParameter(+ name="urls",+ type="array",+ description="1-10 http(s) URLs to add.",+ items={"type": "string"},+ ),+ _KB_NAME_PARAM,+ ToolParameter(+ name="folder_id",+ type="string",+ description="Target folder from ima_list. Omit for the library root.",+ required=False,+ ),+ ],+ )++ async def _run(self, client, binding, kwargs):+ urls = _string_list(kwargs.get("urls"))+ unsupported = [url for url in urls if not _is_supported_url(url)]+ if unsupported:+ return _err(+ "Tencent IMA cannot add these over its API (video pages and local files "+ f"must be added in the IMA desktop app): {', '.join(unsupported)}"+ )+ results = await client.import_urls(urls, folder_id=str(kwargs.get("folder_id") or ""))+ added = [result for result in results if result.ok]+ failed = [result for result in results if not result.ok]+ return ToolResult(+ content=json.dumps(+ {+ "knowledge_base": binding.name,+ "added": [{"url": item.url, "media_id": item.media_id} for item in added],+ "failed": [{"url": item.url, "code": item.code} for item in failed],+ },+ ensure_ascii=False,+ ),+ success=bool(added),+ )+++class ImaWriteNoteTool(_ImaTool):+ """Create an IMA note, or append to an existing one."""++ writes = True++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="ima_write_note",+ description=(+ "Write a Markdown note into the user's Tencent IMA account. Creates a new "+ "note by default; pass note_id to append to that note instead. Appending "+ "cannot be undone, so only append to a note the user explicitly named — "+ "otherwise create a new one. Only call this when the user asked to save "+ "something."+ ),+ parameters=[+ ToolParameter(+ name="content",+ type="string",+ description="Markdown body. Start with a '# Heading' to title a new note.",+ ),+ ToolParameter(+ name="note_id",+ type="string",+ description=(+ "Append to this note (from ima_note_search) instead of creating one."+ ),+ required=False,+ ),+ ToolParameter(+ name="notebook_id",+ type="string",+ description="Notebook for a new note. Omit for the default location.",+ required=False,+ ),+ _KB_NAME_PARAM,+ ],+ )++ async def _run(self, client, binding, kwargs):+ content = str(kwargs.get("content") or "").strip()+ note_id = str(kwargs.get("note_id") or "").strip()+ if note_id:+ written = await client.notes.append_note(note_id, content)+ return _ok({"note_id": written, "action": "appended"})+ written = await client.notes.create_note(+ content,+ folder_id=str(kwargs.get("notebook_id") or ""),+ )+ if not written:+ return _err("Tencent IMA did not return a note id; the note may not have been saved.")+ return _ok({"note_id": written, "action": "created"})+++def _bindings(kwargs: dict[str, Any]) -> tuple[ImaBinding, ...]:+ raw = kwargs.get(BINDINGS_KWARG)+ if not raw:+ return ()+ return tuple(item for item in raw if isinstance(item, ImaBinding))+++def _no_binding_message(bindings: tuple[ImaBinding, ...]) -> str:+ if not bindings:+ return "No Tencent IMA knowledge base is attached to this turn; IMA tools are unavailable."+ names = ", ".join(binding.name for binding in bindings)+ return f"Specify which IMA knowledge base to use with kb_name. Attached: {names}."+++def _string_list(value: Any) -> list[str]:+ if isinstance(value, str):+ candidates = [value]+ elif isinstance(value, (list, tuple)):+ candidates = [str(item) for item in value]+ else:+ raise ValueError("urls must be a list of strings.")+ urls = [item.strip() for item in candidates if str(item).strip()]+ if not urls:+ raise ValueError("At least one URL is required.")+ return urls+++# IMA's API refuses these; failing locally keeps the model from reporting a+# confusing upstream error for something that was never going to work.+_UNSUPPORTED_URL_MARKERS: tuple[str, ...] = (+ "bilibili.com/video/",+ "youtube.com/watch",+ "youtu.be/",+)+++def _is_supported_url(url: str) -> bool:+ lowered = url.lower()+ if not lowered.startswith(("http://", "https://")):+ return False+ return not any(marker in lowered for marker in _UNSUPPORTED_URL_MARKERS)+++def _ok(payload: Any) -> ToolResult:+ return ToolResult(content=json.dumps(payload, ensure_ascii=False), success=True)+++def _err(message: str) -> ToolResult:+ return ToolResult(content=message, success=False)+++IMA_TOOL_TYPES: tuple[type[BaseTool], ...] = (+ ImaListTool,+ ImaReadTool,+ ImaNoteSearchTool,+ ImaAddUrlTool,+ ImaWriteNoteTool,+)++__all__ = [+ "BINDINGS_KWARG",+ "IMA_TOOL_NAMES",+ "IMA_TOOL_TYPES",+ "ImaAddUrlTool",+ "ImaListTool",+ "ImaNoteSearchTool",+ "ImaReadTool",+ "ImaWriteNoteTool",+]diff --git a/deeptutor/capabilities/reading/__init__.py b/deeptutor/capabilities/reading/__init__.pynew file mode 100644index 000000000..e5c516b12--- /dev/null+++ b/deeptutor/capabilities/reading/__init__.py@@ -0,0 +1,33 @@+"""Immersive reading loop capability.++``ImmersiveReadingCapability`` (the *mode* the user picks in the composer)+is deliberately NOT re-exported here. It imports the agentic chat pipeline,+which imports the built-in tool registry, which imports this package for+``READING_TOOL_TYPES`` — re-exporting it closes that cycle at interpreter+start. The mode is loaded lazily by class path from+``runtime.bootstrap.builtin_capabilities``, exactly as mastery's is.+"""++from deeptutor.capabilities.reading.capability import (+ MATERIAL_ID_KEY,+ VIEWPORT_KEY,+ ReadingCapability,+ resolve_material_id,+ resolve_viewport,+)+from deeptutor.capabilities.reading.tools import (+ MATERIAL_KWARG,+ READING_TOOL_NAMES,+ READING_TOOL_TYPES,+)++__all__ = [+ "MATERIAL_ID_KEY",+ "MATERIAL_KWARG",+ "READING_TOOL_NAMES",+ "READING_TOOL_TYPES",+ "VIEWPORT_KEY",+ "ReadingCapability",+ "resolve_material_id",+ "resolve_viewport",+]diff --git a/deeptutor/capabilities/reading/capability.py b/deeptutor/capabilities/reading/capability.pynew file mode 100644index 000000000..ae7a1936d--- /dev/null+++ b/deeptutor/capabilities/reading/capability.py@@ -0,0 +1,288 @@+"""Immersive-reading loop capability.++Active whenever the turn carries an open reading material. It augments the+normal chat surface (it is not a :class:`KnowledgeCapability` — the user keeps+web search, code execution and everything else) with the five reading tools, and+tells the model three things it cannot infer: what document is open, where the+user is currently looking, and how to cite.++**The locate pre-pass.** The capability implements the optional async+``pre_loop`` hook, but *without* a second LLM loop: it runs the same+deterministic search the model would have run, on the user's own question, and+folds the hits into the turn's seed. That choice is deliberate —++* it costs no tokens and adds no latency before the first token,+* it is fully deterministic, so it can be tested rather than sampled, and+* it fixes the real failure it exists for: weak models under native tool calling+ often never call a read tool at all (the same observation+ :mod:`deeptutor.capabilities.explore_context` was built around). Handing the+ model "your question matches page 12 and page 17" up front means grounding+ happens even when the model would not have asked for it.++**Why materials do not enter ``source_index``.** Reading material is addressed by+locator through this capability's own store, never flattened into the per-turn+attached-sources map. That keeps ``ExploreContextCapability`` inactive on reading+turns (it activates on a non-empty ``source_index``), so the two pre-passes can+never both read the same document — no coordination code required in either.+"""++from __future__ import annotations++import asyncio+from importlib import resources+import logging+from typing import Any++import yaml++from deeptutor.capabilities.protocol import PromptBlock+from deeptutor.capabilities.reading.tools import (+ MATERIAL_KWARG,+ READING_TOOL_NAMES,+)+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus++logger = logging.getLogger(__name__)++# Metadata keys the frontend sets on a reading turn.+MATERIAL_ID_KEY = "reading_material_id"+VIEWPORT_KEY = "reading_viewport"+# Set by the mode shell. Distinguishes "the user is in reading mode with nothing+# open yet" from "this is an ordinary chat turn" — the two need different prompts+# and only one of them may answer a document question.+MODE_KEY = "immersive_reading_mode"++# Hits the locate pre-pass folds into the seed. Enough to point at the right+# part of a document, few enough that it cannot crowd out the conversation.+LOCATE_HITS = 4+LOCATE_SNIPPET_CHARS = 260++_PROMPT_CACHE: dict[str, dict[str, Any]] = {}+++def _load_prompts(language: str) -> dict[str, Any]:+ lang = "zh" if str(language or "en").lower().startswith("zh") else "en"+ cached = _PROMPT_CACHE.get(lang)+ if cached is not None:+ return cached+ try:+ text = (+ resources.files(__package__)+ .joinpath("prompts", lang, "reading.yaml")+ .read_text(encoding="utf-8")+ )+ data = yaml.safe_load(text)+ except Exception:+ logger.warning("failed to load reading prompts (%s)", lang, exc_info=True)+ data = None+ result = data if isinstance(data, dict) else {}+ _PROMPT_CACHE[lang] = result+ return result+++def resolve_material_id(context: UnifiedContext) -> str:+ """The material the turn is reading, or "" when none is open."""+ return str((context.metadata or {}).get(MATERIAL_ID_KEY) or "").strip()+++def resolve_viewport(context: UnifiedContext) -> dict[str, Any]:+ """What the user is looking at right now, as reported by the reader."""+ raw = (context.metadata or {}).get(VIEWPORT_KEY)+ return raw if isinstance(raw, dict) else {}+++class ReadingCapability:+ """Turn-scoped integration for immersive reading."""++ name = "immersive_reading"+ owned_tools: tuple[str, ...] = READING_TOOL_NAMES++ def is_active(self, context: UnifiedContext) -> bool:+ """Active with a document open, and also with the mode merely selected.++ The second half is not cosmetic. Without it, a turn taken in reading mode+ before any document is open was an ordinary chat turn — so a question+ like "what does the section on positional encoding say?" was answered+ from the model's memory of a similar paper, complete with a confident+ section number and a verbatim-looking quote, and nothing in the answer+ revealed that no document had been read. Activating here lets the prompt+ say the reader is empty, and mounts tools whose guard says the same.+ """+ if resolve_material_id(context):+ return True+ return bool((context.metadata or {}).get(MODE_KEY))++ # -- prompt -----------------------------------------------------------++ def system_block(+ self,+ context: UnifiedContext,+ *,+ language: str,+ prompts: dict[str, Any],+ ) -> PromptBlock | None:+ del prompts # the capability owns its own prompt file+ own = _load_prompts(language)+ material_id = resolve_material_id(context)+ if not material_id:+ # Mode selected, nothing open. The one thing the model must not do is+ # answer a document question from memory. With neither a material nor+ # the mode there is nothing to say — this is a plain chat turn.+ if not (context.metadata or {}).get(MODE_KEY):+ return None+ empty = str(own.get("no_material") or "").strip()+ return PromptBlock(name="immersive_reading", content=empty) if empty else None++ playbook = str(own.get("playbook") or "").strip()+ if not playbook:+ return None++ facts = self._material_facts(material_id, language=language)+ if not facts:+ # The material vanished (deleted in another tab). Say so rather than+ # promising the model a document it cannot read.+ return PromptBlock(+ name="immersive_reading",+ content=str(own.get("material_missing") or "").strip()+ or "The reading material is unavailable.",+ )+ return PromptBlock(name="immersive_reading", content=f"{playbook}\n\n{facts}")++ def _material_facts(self, material_id: str, *, language: str) -> str:+ """Describe the open document: identity, size, unit word, viewport."""+ try:+ from deeptutor.reading import ReadingStore, material_summary++ store = ReadingStore()+ manifest = store.manifest(material_id)+ annotation_count = len(store.annotations(material_id))+ except Exception:+ logger.info("reading material %s unavailable for prompt", material_id, exc_info=True)+ return ""++ own = _load_prompts(language)+ template = str(own.get("material_facts") or "").strip()+ if not template:+ return ""+ return template.format(+ summary=material_summary(manifest),+ unit=manifest.unit,+ unit_count=manifest.unit_count,+ annotations=annotation_count,+ )++ # -- tool kwargs ------------------------------------------------------++ def augment_kwargs(+ self,+ tool_name: str,+ kwargs: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ """Bind the open material to this capability's tools, server-side.++ The model never names a material, so it can neither read a document the+ user has not opened nor mistype an id.+ """+ if tool_name not in READING_TOOL_NAMES:+ return kwargs+ material_id = resolve_material_id(context)+ if not material_id:+ return kwargs+ return {**kwargs, MATERIAL_KWARG: material_id}++ # -- seeds ------------------------------------------------------------++ def pre_loop_seed(self, context: UnifiedContext) -> str:+ """Report the viewport — cheap, synchronous, no I/O.++ Kept separate from the locate pre-pass so that "the user is looking at+ page 12" reaches the model even when the search finds nothing.+ """+ if not resolve_material_id(context):+ return ""+ viewport = resolve_viewport(context)+ locator = _as_int(viewport.get("locator"))+ selection = str(viewport.get("selection") or "").strip()+ parts: list[str] = []+ if locator:+ parts.append(f"The reader is currently showing locator {locator}.")+ if selection:+ parts.append(f'The user has selected this text: "{_clip(selection, 600)}"')+ return " ".join(parts)++ async def pre_loop(+ self,+ context: UnifiedContext,+ stream: StreamBus,+ *,+ usage: Any | None = None,+ ) -> PromptBlock | None:+ """Deterministically locate the user's question in the document.++ No LLM call, so ``usage`` is untouched and the turn's first token is not+ delayed. ``stream`` is accepted to satisfy the hook's signature; there is+ no progress worth narrating for a few milliseconds of local search.+ """+ del stream, usage+ material_id = resolve_material_id(context)+ question = (context.user_message or "").strip()+ if not material_id or len(question) < 3:+ return None++ try:+ hits = await asyncio.to_thread(self._locate, material_id, question)+ except Exception:+ logger.info("reading locate pre-pass failed", exc_info=True)+ return None+ if not hits:+ return None++ own = _load_prompts(context.language or "en")+ header = str(own.get("locate_header") or "").strip() or (+ "Search of the open document for the user's question found:"+ )+ lines = [header]+ lines.extend(hits)+ return PromptBlock(name="immersive_reading_locate", content="\n".join(lines))++ @staticmethod+ def _locate(material_id: str, question: str) -> list[str]:+ from deeptutor.reading import ReadingStore, search_material++ store = ReadingStore()+ manifest = store.manifest(material_id)+ result = search_material(store, material_id, question, limit=LOCATE_HITS)+ if result.is_empty:+ return []+ confidence = "verbatim" if result.mode in ("exact", "normalised") else "loose"+ return [+ f"- {manifest.unit} {hit.locator} ({confidence}): "+ f"{_clip(hit.snippet, LOCATE_SNIPPET_CHARS)}"+ for hit in result.hits+ ]+++def _as_int(value: Any) -> int:+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return 0+ return parsed if parsed > 0 else 0+++def _clip(text: str, limit: int) -> str:+ flat = " ".join((text or "").split())+ return flat if len(flat) <= limit else flat[: limit - 1] + "…"+++__all__ = [+ "LOCATE_HITS",+ "MATERIAL_ID_KEY",+ "MODE_KEY",+ "VIEWPORT_KEY",+ "ReadingCapability",+ "resolve_material_id",+ "resolve_viewport",+]diff --git a/deeptutor/capabilities/reading/mode.py b/deeptutor/capabilities/reading/mode.pynew file mode 100644index 000000000..02c600f7b--- /dev/null+++ b/deeptutor/capabilities/reading/mode.py@@ -0,0 +1,58 @@+"""Immersive Reading capability — the chat agent loop, reading a document.++There is no bespoke pipeline: the standard agentic chat loop IS the reader. This+capability only marks the turn and runs that pipeline. Everything specific to+reading is contributed by the loop capability+(:class:`deeptutor.capabilities.reading.capability.ReadingCapability`), which+mounts the five reading tools, binds the open material server-side, injects the+reading playbook and runs the deterministic locate pre-pass.++The split matters for a practical reason: the *mode* is what the user picks in+the composer, while the *loop capability* activates on whether a document is+actually open. Selecting the mode with no document open therefore still gives a+perfectly ordinary chat turn — the reader panel is showing its file picker, and+there is nothing to ground an answer in yet.++Design axiom (shared with chat / solve / mastery): the intelligence lives at the+loop's exit — the model decides what to read and what to cite — while the+deterministic parts (which units exist, whether a quote is really on the page it+claims) are engine calls behind tools.+"""++from __future__ import annotations++from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline+from deeptutor.capabilities.reading.capability import (+ MATERIAL_ID_KEY,+ MODE_KEY,+ resolve_material_id,+)+from deeptutor.capabilities.reading.tools import READING_TOOL_NAMES+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+++class ImmersiveReadingCapability(BaseCapability):+ manifest = CapabilityManifest(+ name="immersive_reading",+ description=(+ "Read a document alongside the assistant, which cites the exact "+ "page or section behind every claim."+ ),+ stages=["responding"],+ tools_used=[*READING_TOOL_NAMES, "web_search", "code_execution", "reason"],+ cli_aliases=["reading", "read"],+ )++ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:+ # Normalised so the flag and the id can never disagree: the loop+ # capability keys off the id alone, and a turn with no document open is+ # deliberately just a normal chat turn.+ material_id = resolve_material_id(context)+ context.metadata[MATERIAL_ID_KEY] = material_id+ context.metadata[MODE_KEY] = True+ await AgenticChatPipeline(language=context.language).run(context, stream)+++__all__ = ["ImmersiveReadingCapability"]diff --git a/deeptutor/capabilities/reading/prompts/en/reading.yaml b/deeptutor/capabilities/reading/prompts/en/reading.yamlnew file mode 100644index 000000000..7a8e9549b--- /dev/null+++ b/deeptutor/capabilities/reading/prompts/en/reading.yaml@@ -0,0 +1,73 @@+# Prompt fragments for the immersive-reading capability.+#+# ``playbook`` is the invariant part: how to work in this mode. ``material_facts``+# is formatted per turn with the open document's identity. Keep them separate so+# a wording change never has to be duplicated across formats.++playbook: |+ ## Immersive reading++ The user is reading a document in a reader panel beside this conversation. You+ can see the document only through your reading tools — never assume its+ contents, and never answer from memory of a similar text.++ How to work:++ 1. To find where something is discussed, call `material_outline` (structure) or+ `search_material` (full text). Both return locators.+ 2. Read the actual text with `read_material` before making any claim about the+ document. Search snippets are windowed and may cut mid-sentence — quoting+ one produces a citation that does not match the page. If you did not read+ it, you do not know it.+ 3. Call `reader_goto` whenever you reference a specific passage, passing the+ verbatim quote. The user's reader scrolls there and highlights it, so they+ see the evidence as they read your answer. Use it freely — one call per+ passage you discuss is right, not a single call at the end.+ 4. Cite as `[p.12]` right after the claim it supports. Always that exact form,+ whatever the document's units are called (write `[p.12]` even for a chapter+ or a slide). Use `[p.12,17]` for several and `[p.12-14]` for a range. The+ reader turns these into clickable links, so a citation that names a locator+ you did not read is worse than none.++ Write the sentence however reads best; you do not have to avoid naming the+ location in words. If you write "…on page 3 … [p.3]", the reader merges the+ two into one link on the phrase itself, so it never comes out doubled.+ 5. `reader_annotate` leaves a durable mark the user can export with their own+ annotations. Use it when they ask you to mark something up — not as a+ substitute for explaining.++ If the document does not answer the question, say so and say what it does+ cover. Do not fill the gap from general knowledge without labelling it as+ outside the document.++material_facts: |+ ### Open document++ {summary}. One locator = one {unit}; valid locators are 1..{unit_count}.+ Existing annotations: {annotations}.++material_missing: |+ ## Immersive reading++ The document the user was reading is no longer available — it may have been+ removed. Tell them, and ask them to open it again rather than guessing at its+ contents.++locate_header: |+ ### Where the user's question appears in the document+ (Automatic search of the open document — verify by reading before you cite.)++no_material: |+ ## Immersive reading — no document open++ The user is in reading mode but has not opened a document yet; the reader panel+ is showing its file picker. You therefore have NO document to read.++ If their question is about a document — its sections, its wording, where+ something appears, what page something is on — say plainly that nothing is open+ yet and ask them to drop a file into the reader. Do **not** answer from your own+ knowledge of a paper or book with a similar title: a page number or a quotation+ recalled from memory is indistinguishable, to the reader, from one taken out of+ the file they meant to open, and that is the worst possible failure here.++ Anything not about a document, answer normally.diff --git a/deeptutor/capabilities/reading/prompts/zh/reading.yaml b/deeptutor/capabilities/reading/prompts/zh/reading.yamlnew file mode 100644index 000000000..397d56fb7--- /dev/null+++ b/deeptutor/capabilities/reading/prompts/zh/reading.yaml@@ -0,0 +1,61 @@+# 沉浸式阅读能力的提示词片段。+#+# ``playbook`` 是不变部分(在这个模式下如何工作);``material_facts`` 每轮按+# 当前打开的文档格式化。二者分开,措辞调整就不必在多处重复。++playbook: |+ ## 沉浸式阅读++ 用户正在本次对话旁边的阅读器里读一份文档。你只能通过阅读工具看到这份文档 ——+ 不要凭空假设它的内容,也不要凭对类似文本的记忆作答。++ 工作方式:++ 1. 要找某个内容在哪里,调用 `material_outline`(结构)或 `search_material`+ (全文)。两者都会返回定位号。+ 2. 在对文档下任何判断之前,先用 `read_material` 读到真实原文。检索结果里的+ 片段是截断的窗口、可能从句子中间切开 —— 直接引用它会得到一条与原页对不上的+ 引文。没读过就不算知道。+ 3. 每当你引用某个具体段落,调用 `reader_goto` 并传入逐字原文。用户的阅读器会+ 滚动到那里并高亮,让他们边读你的回答边看到依据。放心多次调用 —— 讨论几处+ 就调几次才对,不要攒到最后只调一次。+ 4. 在正文里紧跟着被支撑的论断写 `[p.12]`。无论该文档的单元叫什么(章、页、+ 幻灯片),都统一写成 `[p.12]`。多个用 `[p.12,17]`,范围用 `[p.12-14]`。+ 阅读器会把它们变成可点击的链接,所以引用一个你没读过的定位号比不引用更糟。++ 句子怎么读得顺就怎么写,不必回避用文字说出位置。如果你写「……位于第 3 页+ ……[p.3]」,阅读器会把两者合并成短语上的一个链接,不会重复出现。+ 5. `reader_annotate` 会留下持久的标注,用户导出标注文件时会带上。用户要求你+ 划重点/做批注时才用,它不能替代讲解。++ 如果文档回答不了这个问题,就直接说明,并说清文档实际覆盖了什么。不要在不标注+ "这超出文档范围"的情况下用通用知识补上。++material_facts: |+ ### 当前打开的文档++ {summary}。一个定位号 = 一个 {unit};有效定位号为 1..{unit_count}。+ 已有标注数:{annotations}。++material_missing: |+ ## 沉浸式阅读++ 用户此前在读的文档已不可用(可能已被删除)。请告知用户,并请他们重新打开,+ 不要猜测其内容。++locate_header: |+ ### 用户问题在文档中的出现位置+ (对已打开文档的自动检索结果 —— 引用前请先读原文核实。)++no_material: |+ ## 沉浸式阅读 —— 尚未打开文档++ 用户处于阅读模式,但还没有打开任何文档,阅读器上显示的是文件选择界面。因此你+ **没有任何文档可读**。++ 如果用户的问题是关于某份文档的 —— 它的章节、原文措辞、某处在哪里、某内容在第+ 几页 —— 请直接说明目前还没有打开文档,并请他把文件拖进阅读器。**不要**凭你对+ 同名或类似论文/书籍的记忆作答:凭记忆说出的页码或引文,在用户看来与从他本想打开+ 的那份文件里读到的完全无法区分,而这是这里最糟糕的一种失败。++ 与文档无关的问题,正常回答即可。diff --git a/deeptutor/capabilities/reading/tools.py b/deeptutor/capabilities/reading/tools.pynew file mode 100644index 000000000..872fb9a13--- /dev/null+++ b/deeptutor/capabilities/reading/tools.py@@ -0,0 +1,573 @@+"""Tools the immersive-reading capability mounts on the chat loop.++Two families, and the split matters:++**Reading** — ``material_outline`` / ``search_material`` / ``read_material``.+These are how the model gets grounded. Because the material is stored per unit,+every one of them returns a *locator*, so a claim is traceable to "page 12" as a+by-product of how the evidence was fetched rather than as an afterthought the+model has to remember to add.++**Driving the reader** — ``reader_goto`` / ``reader_annotate``. These reach out+of the conversation and act on what the user is looking at. ``reader_goto`` is+the one that makes the mode feel alive: ask "what does chapter three argue?" and+the page turns itself.++The two are guarded differently, on purpose. A **highlight** must be real, so it+is drawn only where the quoted text actually occurs; an unverifiable quote still+moves the view, without lighting anything up. A **saved annotation** is stronger+still — it persists and is written into the exported PDF — so it is refused+outright unless the quote checks out. The asymmetry matters in practice: a user+reading an English paper in Chinese gets translated "quotes" that can never match+verbatim, and refusing to move for those made the reader look broken.++The material id is never a parameter: the capability injects ``_material_id``+server-side via ``augment_kwargs``, so the model cannot read a document the user+has not opened, and cannot get the id wrong. Each call builds its own store,+matching the REST router, so concurrent turns never share mutable state.++UI side-effects travel on ``ToolResult.metadata`` under ``reader_action``, which+the pipeline already forwards to the client as part of the ``tool_result``+event — no new stream channel, no change to the chat engine.+"""++from __future__ import annotations++import asyncio+import logging+from typing import Any++from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult+from deeptutor.tools.prompting import load_prompt_hints++logger = logging.getLogger(__name__)++# Mounted together whenever a reading material is open on the turn. Kept here so+# the mount policy and the registration list cannot drift apart.+READING_TOOL_NAMES: tuple[str, ...] = (+ "material_outline",+ "search_material",+ "read_material",+ "reader_goto",+ "reader_annotate",+)++# Private, server-injected kwarg carrying the open material.+MATERIAL_KWARG = "_material_id"++_SEARCH_DEFAULT_LIMIT = 8+_SEARCH_MAX_LIMIT = 20+++class _ReadingToolBase(BaseTool):+ """Shared plumbing: resolve the injected material and the store."""++ def get_prompt_hints(self, language: str = "en"):+ return load_prompt_hints(self.name, language=language)++ @staticmethod+ def _material_id(kwargs: dict[str, Any]) -> str:+ material_id = str(kwargs.get(MATERIAL_KWARG) or "").strip()+ if not material_id:+ raise _NoMaterial()+ return material_id++ @staticmethod+ def _store():+ # Imported inside the call: ``reading.store`` reaches the path service,+ # which reaches the runtime and the tool registry — importing it at+ # module scope would close that cycle through the builtin registry.+ from deeptutor.reading import ReadingStore++ return ReadingStore()++ @staticmethod+ def _failure(message: str) -> ToolResult:+ return ToolResult(content=message, success=False)+++class _NoMaterial(RuntimeError):+ """Raised when the turn has no open material (should be unreachable)."""+++def _guard(func):+ """Turn engine errors into readable tool failures instead of turn deaths.++ A model that asked for page 900 of a 12-page document should be told so and+ given another round, not take the whole turn down with it.+ """++ async def wrapper(self: _ReadingToolBase, **kwargs: Any) -> ToolResult:+ from deeptutor.reading import ReadingError++ try:+ return await func(self, **kwargs)+ except _NoMaterial:+ return self._failure(+ "No reading material is open. Ask the user to open a document in the reader."+ )+ except ReadingError as exc:+ return self._failure(str(exc))+ except Exception: # pragma: no cover - defensive+ logger.warning("reading tool %s failed", getattr(self, "name", "?"), exc_info=True)+ return self._failure("The reader could not complete that request.")++ return wrapper+++class MaterialOutlineTool(_ReadingToolBase):+ """The map of the open document — always cheaper than reading to find out."""++ name = "material_outline"++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="material_outline",+ description=(+ "Show the structure of the document the user is reading: its "+ "size and an outline with the locator (page / chapter / slide / "+ "section number) of each heading. Call this FIRST when you need "+ "to find where something is discussed — it is far cheaper than "+ "reading units one by one to look for it."+ ),+ parameters=[],+ )++ @_guard+ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.reading import render_outline++ material_id = self._material_id(kwargs)+ store = self._store()+ text = await asyncio.to_thread(render_outline, store, material_id)+ return ToolResult(content=text, metadata={"material_id": material_id})+++class SearchMaterialTool(_ReadingToolBase):+ """Locator-addressed search — the retrieval substitute for this mode."""++ name = "search_material"++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="search_material",+ description=(+ "Search the full text of the document the user is reading. "+ "Returns matching locators (page / chapter / slide / section "+ "numbers) with a snippet from each. Use this to find where a "+ "term, name, formula or phrase appears, then read those "+ "locators with read_material."+ ),+ parameters=[+ ToolParameter(+ name="query",+ type="string",+ description=(+ "Words or a phrase to look for. A verbatim phrase from "+ "the document matches most precisely."+ ),+ ),+ ToolParameter(+ name="limit",+ type="integer",+ description=f"Maximum matches to return (default {_SEARCH_DEFAULT_LIMIT}).",+ required=False,+ ),+ ],+ )++ @_guard+ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.reading import search_material++ material_id = self._material_id(kwargs)+ query = str(kwargs.get("query") or "").strip()+ if not query:+ return self._failure("search_material needs a non-empty query.")+ limit = _clamp_int(kwargs.get("limit"), _SEARCH_DEFAULT_LIMIT, 1, _SEARCH_MAX_LIMIT)++ store = self._store()+ manifest = await asyncio.to_thread(store.manifest, material_id)+ result = await asyncio.to_thread(search_material, store, material_id, query, limit=limit)++ unit = manifest.unit+ if result.is_empty:+ return ToolResult(+ content=(+ f'No match for "{query}". Try fewer or different words, or '+ f"call material_outline to see what the document covers."+ ),+ metadata={"material_id": material_id, "hits": []},+ )++ lines = [+ f'{len(result.hits)} match(es) for "{query}"'+ f"{' (loose term match — verify before citing)' if result.mode == 'terms' else ''}:"+ ]+ for hit in result.hits:+ lines.append(f"- {unit} {hit.locator}: {hit.snippet}")+ if result.truncated:+ lines.append("… more matches exist; narrow the query or raise the limit.")+ # Next-step guidance sits in the tool output, not only in the system+ # prompt: it reaches the model at the moment it is holding the result,+ # which is when it decides whether to quote a snippet directly. These+ # snippets are windowed and may cut mid-sentence, so quoting one+ # verbatim produces a citation that does not match the document.+ lines.append(+ f"→ These are windowed snippets, not the source. Read the {unit}(s) "+ "with read_material before quoting, then call reader_goto to show "+ "the user the passage."+ )++ return ToolResult(+ content="\n".join(lines),+ sources=[+ {+ "type": "reading",+ "material_id": material_id,+ "title": manifest.filename,+ "page": hit.locator,+ "content": hit.snippet,+ }+ for hit in result.hits+ ],+ metadata={+ "material_id": material_id,+ "mode": result.mode,+ "hits": [hit.to_dict() for hit in result.hits],+ },+ )+++class ReadMaterialTool(_ReadingToolBase):+ """Verbatim text of specific units — the grounding primitive."""++ name = "read_material"++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="read_material",+ description=(+ "Read the exact text of specific parts of the document the user "+ "is reading, addressed by locator (page / chapter / slide / "+ "section number). Accepts a single number ('12'), a range "+ "('12-14') or a list ('3,12,17'). Every claim you make about "+ "the document should come from text you read here, and should "+ "cite the locator it came from."+ ),+ parameters=[+ ToolParameter(+ name="locators",+ type="string",+ description=(+ "Which parts to read: '12', '12-14', or '3,12,17'. "+ "Locators are 1-indexed and match what the reader shows."+ ),+ ),+ ],+ )++ @_guard+ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.reading import render_units++ material_id = self._material_id(kwargs)+ spec = kwargs.get("locators")+ if spec is None or (isinstance(spec, str) and not spec.strip()):+ return self._failure("read_material needs a locator, e.g. '12' or '12-14'.")++ store = self._store()+ manifest = await asyncio.to_thread(store.manifest, material_id)+ rendered = await asyncio.to_thread(render_units, store, material_id, spec)++ if rendered.is_empty:+ return ToolResult(+ content=(+ f"Those {manifest.unit}s contain no extractable text "+ "(they may be images or scans)."+ ),+ metadata={"material_id": material_id, "locators": list(rendered.locators)},+ )+ followup = (+ "\n\n→ Now call reader_goto with the verbatim sentence you are "+ "about to cite, so the user sees it highlighted, and cite it in "+ "prose as [p.N]."+ )+ return ToolResult(+ content=rendered.text + followup,+ sources=[+ {+ "type": "reading",+ "material_id": material_id,+ "title": manifest.filename,+ "page": locator,+ }+ for locator in rendered.locators+ ],+ metadata={+ "material_id": material_id,+ "locators": list(rendered.locators),+ "truncated": rendered.truncated,+ },+ )+++class ReaderGotoTool(_ReadingToolBase):+ """Move the user's viewport — refused unless the quote checks out."""++ name = "reader_goto"++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="reader_goto",+ description=(+ "Scroll the user's reader to a specific locator and highlight "+ "the passage you are talking about. Use it whenever you "+ "reference a specific part of the document, so the user sees "+ "what you are reading. Pass the exact quote you are referring "+ "to — if it does not appear in the document the jump is "+ "refused, so quote verbatim rather than paraphrasing."+ ),+ parameters=[+ ToolParameter(+ name="locator",+ type="integer",+ description="The page / chapter / slide / section number to show.",+ ),+ ToolParameter(+ name="quote",+ type="string",+ description=(+ "Verbatim text from that locator to highlight. Keep it "+ "short (one sentence or phrase) and copy it exactly."+ ),+ required=False,+ ),+ ],+ )++ @_guard+ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.reading import verify_quote++ material_id = self._material_id(kwargs)+ store = self._store()+ manifest = await asyncio.to_thread(store.manifest, material_id)++ locator = _as_locator(kwargs.get("locator"))+ if not 1 <= locator <= manifest.unit_count:+ return self._failure(+ f"reader_goto needs a locator between 1 and {manifest.unit_count}."+ )+ quote = str(kwargs.get("quote") or "").strip()++ if not quote:+ # No claim to verify: a bare navigation request is honoured.+ return _goto_result(material_id, locator, quote="", manifest=manifest)++ check = await asyncio.to_thread(verify_quote, store, material_id, locator, quote)+ if not check.verified:+ # Move anyway, without a highlight.+ #+ # The locator came from text the model just read; the quote is only+ # what the highlight needs. Refusing the whole jump made the reader+ # sit still for the most ordinary case there is — answering in one+ # language about a document written in another, where the "quote" is+ # the model's own translation and can never match verbatim. Landing+ # on the right page with no highlight is far more useful than not+ # moving at all, and it never paints a highlight over the wrong words.+ return _goto_result(+ material_id,+ locator,+ quote="",+ manifest=manifest,+ unverified_quote=quote,+ )+ target = check.found_locator or locator+ return _goto_result(+ material_id,+ target,+ quote=quote,+ manifest=manifest,+ corrected_from=locator if target != locator else None,+ )+++class ReaderAnnotateTool(_ReadingToolBase):+ """Leave a durable mark on the document, exportable with the user's own."""++ name = "reader_annotate"++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="reader_annotate",+ description=(+ "Mark a passage in the user's document with an optional note. "+ "The mark persists, appears in the reader's annotation list, "+ "and is included when the user exports their annotated file. "+ "Use it when the user asks you to highlight, mark up or "+ "annotate something — not for ordinary explanation."+ ),+ parameters=[+ ToolParameter(+ name="locator",+ type="integer",+ description="The page / chapter / slide / section number to mark.",+ ),+ ToolParameter(+ name="quote",+ type="string",+ description="Verbatim text from that locator to mark. Must appear there.",+ ),+ ToolParameter(+ name="note",+ type="string",+ description="Optional note to attach to the mark.",+ required=False,+ ),+ ToolParameter(+ name="color",+ type="string",+ description="Highlight colour.",+ required=False,+ enum=["yellow", "green", "blue", "pink", "purple"],+ ),+ ],+ )++ @_guard+ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.reading import ANNOTATION_COLORS, Annotation, verify_quote++ material_id = self._material_id(kwargs)+ store = self._store()+ manifest = await asyncio.to_thread(store.manifest, material_id)++ locator = _as_locator(kwargs.get("locator"))+ if not 1 <= locator <= manifest.unit_count:+ return self._failure(+ f"reader_annotate needs a locator between 1 and {manifest.unit_count}."+ )+ quote = str(kwargs.get("quote") or "").strip()+ if not quote:+ return self._failure("reader_annotate needs the verbatim quote to mark.")++ check = await asyncio.to_thread(verify_quote, store, material_id, locator, quote)+ if not check.verified:+ return self._failure(+ "That quote does not appear in this document, so nothing was marked. "+ "Read the passage first and copy it exactly."+ )+ target = check.found_locator or locator++ colour = str(kwargs.get("color") or "").strip().lower()+ annotation = Annotation(+ annotation_id="",+ locator=target,+ kind="highlight",+ color=colour if colour in ANNOTATION_COLORS else "yellow",+ quote=quote,+ note=str(kwargs.get("note") or "").strip(),+ author="assistant",+ )+ saved = await asyncio.to_thread(store.save_annotation, material_id, annotation)++ return ToolResult(+ content=(+ f"Marked {manifest.unit} {target}: “{_ellipsis(quote, 80)}”"+ f"{f' — {saved.note}' if saved.note else ''}"+ ),+ metadata={+ "material_id": material_id,+ "reader_action": "annotate",+ "annotation": saved.to_dict(),+ # Marking is also a reason to look: carry the jump so the client+ # can reveal the mark it just made without a second tool call.+ "locator": target,+ "quote": quote,+ },+ )+++def _goto_result(+ material_id: str,+ locator: int,+ *,+ quote: str,+ manifest: Any,+ corrected_from: int | None = None,+ unverified_quote: str = "",+) -> ToolResult:+ note = ""+ if corrected_from is not None:+ note = (+ f" (that passage is on {manifest.unit} {locator}, "+ f"not {manifest.unit} {corrected_from} — cite {locator})"+ )+ elif unverified_quote:+ # Say why nothing lit up, so the model can supply source-language text+ # next time instead of repeating a translation or a paraphrase.+ note = (+ " — but nothing was highlighted: that wording does not appear "+ "verbatim in the document. To highlight a passage, pass the text "+ "exactly as the document writes it, in its own language"+ )+ return ToolResult(+ content=f"Reader moved to {manifest.unit} {locator}{note}.",+ metadata={+ "material_id": material_id,+ "reader_action": "goto",+ "locator": locator,+ "quote": quote,+ "corrected_from": corrected_from,+ },+ )+++def _clamp_int(value: Any, default: int, low: int, high: int) -> int:+ """Clamp a *bounded preference* (a result limit) into range."""+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return default+ return max(low, min(high, parsed))+++def _as_locator(value: Any) -> int:+ """Parse a locator without clamping it.++ Deliberately not clamped: silently turning "page 900" into the last page+ would have the model cite text the user never asked about, and it would+ contradict ``parse_locators``, which drops out-of-range values. An invalid+ locator becomes 0 and the caller reports the real range.+ """+ try:+ return int(value)+ except (TypeError, ValueError):+ return 0+++def _ellipsis(text: str, limit: int) -> str:+ flat = " ".join((text or "").split())+ return flat if len(flat) <= limit else flat[: limit - 1] + "…"+++READING_TOOL_TYPES: tuple[type[BaseTool], ...] = (+ MaterialOutlineTool,+ SearchMaterialTool,+ ReadMaterialTool,+ ReaderGotoTool,+ ReaderAnnotateTool,+)+++__all__ = [+ "MATERIAL_KWARG",+ "READING_TOOL_NAMES",+ "READING_TOOL_TYPES",+ "MaterialOutlineTool",+ "ReadMaterialTool",+ "ReaderAnnotateTool",+ "ReaderGotoTool",+ "SearchMaterialTool",+]diff --git a/deeptutor/capabilities/registry.py b/deeptutor/capabilities/registry.pyindex bec40a4e1..3fbc4c02e 100644--- a/deeptutor/capabilities/registry.py+++ b/deeptutor/capabilities/registry.py@@ -3,9 +3,12 @@from __future__ import annotationsfrom deeptutor.capabilities.explore_context import ExploreContextCapability+from deeptutor.capabilities.ima import ImaCapabilityfrom deeptutor.capabilities.mastery import MasteryLoopCapabilityfrom deeptutor.capabilities.obsidian import ObsidianCapabilityfrom deeptutor.capabilities.protocol import LoopCapability+from deeptutor.capabilities.reading import ReadingCapability+from deeptutor.capabilities.setup import SetupCapabilityfrom deeptutor.capabilities.solve import SolveLoopCapabilityfrom deeptutor.capabilities.subagent import SubagentCapabilityfrom deeptutor.core.context import UnifiedContext@@ -15,7 +18,20 @@ LOOP_CAPABILITIES: tuple[LoopCapability, ...] = (SolveLoopCapability(),ObsidianCapability(),SubagentCapability(),+ # Additive (not a KnowledgeCapability): an IMA library is searchable over+ # HTTP, so ``rag`` keeps serving it and these tools only add what retrieval+ # cannot do. See ``capabilities/ima/capability.py``.+ ImaCapability(),+ # Additive: reading material is addressed by locator through this+ # capability's own store, so chat keeps its whole surface (web search, code,+ # rag over other KBs) while gaining the five reading tools on top.+ ReadingCapability(),ExploreContextCapability(),+ # Additive as well: configuring the app is something the user asks for in+ # the middle of other work, so the turn keeps its normal surface. Activation+ # is gated on objective signals, not on the model's sense of relevance —+ # see ``capabilities/setup/binding.py``.+ SetupCapability(),)diff --git a/deeptutor/capabilities/setup/__init__.py b/deeptutor/capabilities/setup/__init__.pynew file mode 100644index 000000000..42bba49fe--- /dev/null+++ b/deeptutor/capabilities/setup/__init__.py@@ -0,0 +1,6 @@+"""Setup loop capability — DeepTutor inspecting and changing its own configuration."""++from deeptutor.capabilities.setup.capability import SetupCapability+from deeptutor.capabilities.setup.tools import SETUP_TOOL_NAMES, SETUP_TOOL_TYPES++__all__ = ["SETUP_TOOL_NAMES", "SETUP_TOOL_TYPES", "SetupCapability"]diff --git a/deeptutor/capabilities/setup/access.py b/deeptutor/capabilities/setup/access.pynew file mode 100644index 000000000..8b6eeff3c--- /dev/null+++ b/deeptutor/capabilities/setup/access.py@@ -0,0 +1,104 @@+"""Who may let the setup agent change what.++Two rules, both inherited from where the settings files already live rather+than invented here:++*Personal* rows are the ones :class:`~deeptutor.services.path_service.PathService`+already resolves per user — a write lands in the caller's own+``settings/interface.json`` and is invisible to everyone else. Any signed-in+person may therefore change their own.++*Global* rows are the shared deployment settings under+``data/user/settings`` (``get_runtime_settings_dir`` does not go through the+per-user path service). Changing one changes it for every account on the+install, which is exactly the boundary+:func:`deeptutor.api.routers.settings._require_settings_admin` already guards —+so the capability requires the same administrator role rather than inventing a+softer rule for the chat surface than the settings page enforces.++A **partner is refused outright**, for either scope. A partner is a synthetic+user whose owner is a real account: its turns resolve ownership to that person+(:func:`~deeptutor.multi_user.paths.get_owner_path_service`), so honouring a+configuration request from an IM-facing companion would mean letting whoever is+chatting with it reconfigure the owner's DeepTutor — including, if the owner is+an administrator, the whole deployment.+"""++from __future__ import annotations++from dataclasses import dataclass++from deeptutor.services.config.settings_spec import Scope+++@dataclass(frozen=True, slots=True)+class AccessDecision:+ """Whether a write may proceed, and what to tell the model when it may not.++ ``reason`` is written for the model to relay to the user, so it names the+ human remedy ("ask an administrator") rather than the internal rule.+ """++ allowed: bool+ reason: str = ""+++def _is_partner_turn() -> bool:+ try:+ from deeptutor.multi_user.context import get_current_user+ from deeptutor.services.partners.scope import is_partner_user_id++ return bool(is_partner_user_id(get_current_user().id))+ except Exception: # noqa: BLE001 - no multi-user layer configured+ return False+++def _is_admin() -> bool:+ """Whether the caller may change deployment-wide settings.++ A missing multi-user layer means a single-user install, whose only user *is*+ the administrator — so ImportError grants. Any other failure is narrowed to+ a refusal: if identity cannot be resolved, granting administrator rights is+ the wrong way to be wrong, and the caller still keeps their personal+ preferences either way.+ """+ try:+ from deeptutor.multi_user.context import get_current_user+ except ImportError:+ return True+ try:+ return bool(get_current_user().is_admin)+ except Exception: # noqa: BLE001 - unresolvable identity: refuse, do not grant+ return False+++def can_write(scope: Scope) -> AccessDecision:+ """Decide whether the current turn may write a row of the given scope."""+ if _is_partner_turn():+ return AccessDecision(+ allowed=False,+ reason=(+ "Configuration cannot be changed from a partner conversation. "+ "The owner can make this change in DeepTutor directly."+ ),+ )+ if scope == "personal":+ return AccessDecision(allowed=True)+ if _is_admin():+ return AccessDecision(allowed=True)+ return AccessDecision(+ allowed=False,+ reason=(+ "This is a deployment-wide setting that applies to every account, so only an "+ "administrator can change it. Personal preferences (interface language, reply "+ "language, theme) can still be changed here."+ ),+ )+++def writable_scopes() -> tuple[Scope, ...]:+ """Scopes the current turn may write — used to describe the surface up front."""+ return tuple(scope for scope in ("personal", "global") if can_write(scope).allowed)+++__all__ = ["AccessDecision", "can_write", "writable_scopes"]diff --git a/deeptutor/capabilities/setup/apply.py b/deeptutor/capabilities/setup/apply.pynew file mode 100644index 000000000..dc87d7ad5--- /dev/null+++ b/deeptutor/capabilities/setup/apply.py@@ -0,0 +1,249 @@+"""Commit one configuration change, or refuse to.++The order of the steps below is the whole point of this module, and it is+deliberately the *opposite* of the obvious one (write, then check):++1. resolve the row and check the caller may write its scope,+2. check the value is one the row actually offers,+3. run the row's ``probe`` against a **candidate** configuration that is not+ on disk,+4. only then write.++Probing before the write is what keeps the assistant from unplugging itself.+The chat model is configured by one of these rows; if a bad value were written+first and verified afterwards, the very next turn — including the turn that+would undo the mistake — would run on a model that cannot be reached, and the+user would be left in a conversation that no longer answers. With this order a+failed probe costs one message, and the stored configuration never moved.++The previous value travels back in :class:`ApplyOutcome` so an undo needs no+extra machinery: the model reverts by applying the row again with+``previous``.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++from deeptutor.capabilities.setup.access import can_write+from deeptutor.services.config.settings_spec import (+ ProbeResult,+ SettingSpec,+ get_setting_spec,+)+++@dataclass(frozen=True, slots=True)+class SideEffect:+ """Another setting that moved as a consequence of the one that was written."""++ key: str+ label: str+ previous: str+ value: str++ def to_dict(self) -> dict[str, Any]:+ return {+ "key": self.key,+ "label": self.label,+ "previous": self.previous,+ "value": self.value,+ }+++@dataclass(frozen=True, slots=True)+class ApplyOutcome:+ """Result of one apply attempt, shaped for both the model and the UI."""++ ok: bool+ key: str+ value: str = ""+ previous: str = ""+ label: str = ""+ effect: str = ""+ effect_detail: str = ""+ error: str = ""+ probe: ProbeResult | None = None+ side_effects: tuple[SideEffect, ...] = ()+ metadata: dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "ok": self.ok,+ "key": self.key,+ "value": self.value,+ "previous": self.previous,+ "label": self.label,+ "effect": self.effect,+ "effect_detail": self.effect_detail,+ }+ if self.side_effects:+ payload["also_changed"] = [effect.to_dict() for effect in self.side_effects]+ if self.error:+ payload["error"] = self.error+ if self.probe is not None:+ payload["probe"] = {+ "ok": self.probe.ok,+ "detail": self.probe.detail,+ "elapsed_ms": self.probe.elapsed_ms,+ }+ if self.metadata:+ payload["metadata"] = dict(self.metadata)+ return payload+++def _neighbour_values(spec: SettingSpec) -> dict[str, tuple[str, str]]:+ """Current ``{key: (label, value)}`` of the other rows in this row's area.++ Read either side of a write so a change that moves a *second* setting is+ reported rather than discovered by the user later. This is not hypothetical:+ ``interface.json`` predates the split between interface and reply language,+ so a file that has never stored a reply language inherits the interface one+ — setting the UI to Chinese also switches replies to Chinese. Detecting that+ generically is what keeps the agent honest without a table of known+ couplings that would inevitably go stale.+ """+ from deeptutor.services.config.settings_spec import specs_for_area++ out: dict[str, tuple[str, str]] = {}+ for other in specs_for_area(spec.area):+ if other.key == spec.key:+ continue+ try:+ out[other.key] = (other.label, other.read())+ except Exception: # noqa: BLE001 - a row we cannot read is one we cannot compare+ continue+ return out+++def _diff_neighbours(+ before: dict[str, tuple[str, str]],+ after: dict[str, tuple[str, str]],+) -> tuple[SideEffect, ...]:+ changed: list[SideEffect] = []+ for key, (label, new_value) in after.items():+ if key not in before:+ continue+ _, old_value = before[key]+ if old_value != new_value:+ changed.append(SideEffect(key=key, label=label, previous=old_value, value=new_value))+ return tuple(changed)+++def _choice_error(spec: SettingSpec, value: str) -> str | None:+ choices = spec.choices()+ if not choices:+ return (+ f"'{spec.label}' has no configured options yet, so there is nothing to select. "+ "It has to be set up in Settings first."+ )+ match = next((choice for choice in choices if choice.value == value), None)+ if match is None:+ offered = ", ".join(choice.value for choice in choices)+ return (+ f"'{value}' is not one of the available options for {spec.label}. Options: {offered}."+ )+ if not match.available:+ return f"'{match.label}' is listed but not usable yet: {match.description or 'it needs setup first'}"+ return None+++async def apply_setting(key: str, value: str) -> ApplyOutcome:+ """Validate, probe and commit ``value`` for the row named ``key``."""+ spec = get_setting_spec(key)+ if spec is None:+ return ApplyOutcome(ok=False, key=key, value=value, error=f"Unknown setting '{key}'.")++ decision = can_write(spec.scope)+ if not decision.allowed:+ return ApplyOutcome(+ ok=False,+ key=spec.key,+ value=value,+ label=spec.label,+ effect=spec.effect,+ error=decision.reason,+ )++ previous = spec.read()+ if value == previous:+ return ApplyOutcome(+ ok=True,+ key=spec.key,+ value=value,+ previous=previous,+ label=spec.label,+ effect="instant",+ effect_detail="Already set to that value; nothing changed.",+ metadata={"unchanged": True},+ )++ error = _choice_error(spec, value)+ if error is None and spec.validate is not None:+ error = spec.validate(value)+ if error:+ return ApplyOutcome(+ ok=False,+ key=spec.key,+ value=value,+ previous=previous,+ label=spec.label,+ effect=spec.effect,+ error=error,+ )++ probe_result: ProbeResult | None = None+ if spec.probe is not None:+ probe_result = await spec.probe(value)+ if not probe_result.ok:+ return ApplyOutcome(+ ok=False,+ key=spec.key,+ value=value,+ previous=previous,+ label=spec.label,+ effect=spec.effect,+ probe=probe_result,+ error=(+ f"{spec.label} was left unchanged: the new selection could not be reached. "+ f"{probe_result.detail}".strip()+ ),+ )++ neighbours_before = _neighbour_values(spec)+ try:+ spec.write(value)+ except Exception as exc: # noqa: BLE001 - surface the failure, keep the old value+ return ApplyOutcome(+ ok=False,+ key=spec.key,+ value=value,+ previous=previous,+ label=spec.label,+ effect=spec.effect,+ probe=probe_result,+ error=f"Could not save the change: {exc}",+ )+ side_effects = _diff_neighbours(neighbours_before, _neighbour_values(spec))++ # Read back rather than trusting the write: a row's writer normalises what+ # it stores (the catalog rewrites ids, the parsing settings coerce shapes),+ # so this is where a value that was silently adjusted becomes visible+ # instead of being reported to the user as an exact match.+ stored = spec.read()+ return ApplyOutcome(+ ok=True,+ key=spec.key,+ value=stored,+ previous=previous,+ label=spec.label,+ effect=spec.effect,+ effect_detail=spec.effect_detail,+ probe=probe_result,+ side_effects=side_effects,+ metadata={} if stored == value else {"adjusted_from": value},+ )+++__all__ = ["ApplyOutcome", "apply_setting"]diff --git a/deeptutor/capabilities/setup/binding.py b/deeptutor/capabilities/setup/binding.pynew file mode 100644index 000000000..04f06bcd2--- /dev/null+++ b/deeptutor/capabilities/setup/binding.py@@ -0,0 +1,255 @@+"""Decide whether a turn is a setup turn, and what is missing from the install.++Two questions live here.++**What is missing** (:func:`setup_gaps`) reads the same spec rows the tools+write, so "what would I offer to fix" and "what can I change" can never drift+apart. A gap is only reported when it costs the user a capability they would+otherwise expect — no embedding model means knowledge bases cannot be built, a+text-only parser means PDFs lose their tables — never as a nag about taste+(nobody needs to be told their theme is the default one).++**Whether to take part** (:func:`is_setup_turn`) deliberately does not ask the+model to sniff intent. An implicitly-mounted capability that activates whenever+an LLM *feels* configuration might be relevant is the failure mode that makes+such a feature obnoxious: it surfaces in unrelated conversations, and the tools+it mounts distract from what was actually asked. Activation here needs one of+three objective signals — the user picked the capability, the message pairs an+action word with a configuration object, or this is the user's first+conversation on an install that still has a real gap (once, ever).++Everything is cached on ``context.metadata`` so the several hooks that run per+turn share one filesystem pass, matching how the other capabilities bind.+"""++from __future__ import annotations++from dataclasses import dataclass+import re+from typing import Any++from deeptutor.core.context import UnifiedContext++_GAPS_CACHE_KEY = "_setup_gaps"+_ACTIVE_CACHE_KEY = "_setup_active"++# Capability name the user can select explicitly (the settings-page entry point+# opens a chat with this preselected).+SETUP_CAPABILITY_NAME = "setup"++# Persisted per user in interface.json: the first-run offer is made once, not+# at the start of every new conversation.+INTRO_SHOWN_KEY = "setup_intro_shown"+++@dataclass(frozen=True, slots=True)+class SetupGap:+ """One thing the install cannot currently do, and the row that fixes it."""++ key: str+ area: str+ summary: str+ remedy: str+ blocking: bool = False++ def to_dict(self) -> dict[str, Any]:+ return {+ "key": self.key,+ "area": self.area,+ "summary": self.summary,+ "remedy": self.remedy,+ "blocking": self.blocking,+ }+++def setup_gaps() -> tuple[SetupGap, ...]:+ """Capabilities the current configuration cannot deliver.++ Failures are swallowed: a gap report is advisory, and a settings file that+ cannot be read should not take down the turn that was going to help fix it.+ """+ from deeptutor.services.config.settings_spec import setting_specs++ gaps: list[SetupGap] = []+ try:+ specs = setting_specs()+ except Exception: # noqa: BLE001 - advisory only+ return ()++ def _has_selection(key: str) -> bool:+ spec = specs.get(key)+ if spec is None:+ return True+ try:+ current = spec.read()+ return bool(current) and any(+ choice.value == current and choice.available for choice in spec.choices()+ )+ except Exception: # noqa: BLE001 - treat an unreadable row as configured+ return True++ if not _has_selection("catalog.embedding"):+ gaps.append(+ SetupGap(+ key="catalog.embedding",+ area="models",+ summary="No embedding model is selected.",+ remedy=("Knowledge bases cannot be built or searched until one is configured."),+ blocking=True,+ )+ )+ if not _has_selection("catalog.search"):+ gaps.append(+ SetupGap(+ key="catalog.search",+ area="models",+ summary="No web search provider is selected.",+ remedy="Web search is unavailable until one is configured.",+ )+ )++ try:+ parsing = specs.get("document_parsing.engine")+ if parsing is not None and parsing.read() == "text_only":+ better = [+ choice+ for choice in parsing.choices()+ if choice.value != "text_only" and choice.available+ ]+ gaps.append(+ SetupGap(+ key="document_parsing.engine",+ area="parsing",+ summary="Documents are parsed with the built-in text-only extractor.",+ remedy=(+ "Tables, formulas and layout are lost. "+ + (+ f"{len(better)} better engine(s) are already installed and can be "+ "selected."+ if better+ else "A stronger engine can be installed in one step."+ )+ ),+ )+ )+ except Exception: # noqa: BLE001 - advisory only+ pass++ return tuple(gaps)+++def cached_gaps(context: UnifiedContext) -> tuple[SetupGap, ...]:+ cached = context.metadata.get(_GAPS_CACHE_KEY)+ if cached is not None:+ return cached+ gaps = setup_gaps()+ context.metadata[_GAPS_CACHE_KEY] = gaps+ return gaps+++# Intent detection requires an action AND an object, so "配置文件太大了" or+# "change the subject" cannot pull the capability into an unrelated turn.+_ACTION_PATTERN = re.compile(+ r"(设置|设定|配置|设好|设成|切换|切成|切到|换成|换到|换个|换掉|改成|改为|改用"+ r"|调整|调成|启用|开启|安装|下载|装上|配一下|连上)"+ r"|(\bconfigure\b|\bconfiguration\b|\bset\s?up\b|\bsetup\b|\bswitch\b|\bchange\b"+ r"|\benable\b|\binstall\b|\bdownload\b|\bset\s+the\b|\bsettings\b)",+ re.IGNORECASE,+)++_OBJECT_PATTERN = re.compile(+ r"(语言|界面|主题|皮肤|模型|嵌入|向量|解析引擎|解析器|引擎"+ r"|搜索引擎|搜索服务|联网搜索|偏好设置|设置项)"+ r"|(\blanguage\b|\btheme\b|\bmodel\b|\bembedding\b|\bparser\b|\bparsing\b|\bengine\b"+ r"|\bweb\s+search\b|\bsearch\s+provider\b|\bprovider\b|\bpreferences?\b)",+ re.IGNORECASE,+)++# Phrases that are unambiguous on their own — the user naming the act of+# configuring DeepTutor itself.+_DIRECT_PATTERN = re.compile(+ r"(帮我配置|帮我设置|自己配置|配置一下\s*deeptutor|设置一下\s*deeptutor|初始化配置)"+ r"|(\bconfigure\s+deeptutor\b|\bset\s?up\s+deeptutor\b|\bsetup\s+wizard\b)",+ re.IGNORECASE,+)+++def message_signals_setup(message: str) -> bool:+ text = str(message or "")+ if not text.strip():+ return False+ if _DIRECT_PATTERN.search(text):+ return True+ return bool(_ACTION_PATTERN.search(text) and _OBJECT_PATTERN.search(text))+++def _intro_pending(context: UnifiedContext) -> bool:+ """First-run offer: a real gap, a fresh conversation, and not yet offered."""+ if context.conversation_history:+ return False+ try:+ from deeptutor.services.settings.interface_settings import get_ui_settings++ if bool(get_ui_settings().get(INTRO_SHOWN_KEY)):+ return False+ except Exception: # noqa: BLE001 - unreadable settings: do not nag+ return False+ return any(gap.blocking for gap in cached_gaps(context))+++def mark_intro_shown() -> None:+ """Record that the first-run offer has been made, so it is not repeated."""+ try:+ from deeptutor.services.settings.interface_settings import set_ui_setting++ set_ui_setting(INTRO_SHOWN_KEY, True)+ except Exception: # noqa: BLE001 - best effort+ pass+++def setup_activation(context: UnifiedContext) -> str:+ """Why this turn is a setup turn: ``explicit`` / ``intent`` / ``intro`` / ``""``.++ The reason is carried, not just the boolean, because the three cases are not+ interchangeable. Only ``intro`` may spend the once-ever first-run offer: an+ earlier version marked it spent from ``system_block``, which meant the first+ time a user asked for anything at all ("change the theme") the offer was+ silently consumed and a genuinely unconfigured install was never proactively+ helped. ``intro`` also earns an extra prompt note, since opening a+ conversation the user did not start on this subject calls for a different+ tone than answering a direct request.++ The check order matters: the two cheap signals are evaluated before+ ``_intro_pending``, which reads settings and computes the install's gaps.+ """+ cached = context.metadata.get(_ACTIVE_CACHE_KEY)+ if cached is not None:+ return str(cached)+ if context.active_capability == SETUP_CAPABILITY_NAME:+ reason = "explicit"+ elif message_signals_setup(context.user_message):+ reason = "intent"+ elif _intro_pending(context):+ reason = "intro"+ else:+ reason = ""+ context.metadata[_ACTIVE_CACHE_KEY] = reason+ return reason+++def is_setup_turn(context: UnifiedContext) -> bool:+ """Whether the setup capability takes part in this turn."""+ return bool(setup_activation(context))+++__all__ = [+ "INTRO_SHOWN_KEY",+ "SETUP_CAPABILITY_NAME",+ "SetupGap",+ "cached_gaps",+ "is_setup_turn",+ "mark_intro_shown",+ "message_signals_setup",+ "setup_activation",+ "setup_gaps",+]diff --git a/deeptutor/capabilities/setup/capability.py b/deeptutor/capabilities/setup/capability.pynew file mode 100644index 000000000..343538ecb--- /dev/null+++ b/deeptutor/capabilities/setup/capability.py@@ -0,0 +1,116 @@+"""Setup loop capability — DeepTutor configuring its own install.++A *plain* :class:`~deeptutor.capabilities.protocol.LoopCapability`, not a+:class:`~deeptutor.capabilities.protocol.KnowledgeCapability`: configuring the+app is something the user asks for in the middle of ordinary work ("switch to+Chinese and use a better PDF parser"), so the turn keeps its normal tool+surface — knowledge bases, web search, the lot — and these four tools are added+on top. An exclusive capability would strip exactly the abilities a+configuration conversation is often about.++Activation is decided by :func:`~deeptutor.capabilities.setup.binding.is_setup_turn`+on objective signals rather than by the model's sense of relevance; see that+module for why.++The system block carries the install's current gaps. That is what lets the+model open with something useful ("your knowledge bases can't be built yet —+no embedding model is selected") instead of a menu, and it costs one filesystem+pass that ``is_active`` has already paid for.+"""++from __future__ import annotations++from importlib import resources+from typing import Any++from deeptutor.capabilities.protocol import PromptBlock+from deeptutor.capabilities.setup.binding import (+ SETUP_CAPABILITY_NAME,+ cached_gaps,+ is_setup_turn,+ mark_intro_shown,+ setup_activation,+)+from deeptutor.capabilities.setup.tools import SETUP_TOOL_NAMES+from deeptutor.core.context import UnifiedContext+++class SetupCapability:+ """Turn-scoped ability to inspect and change DeepTutor's own configuration."""++ name = SETUP_CAPABILITY_NAME+ owned_tools = SETUP_TOOL_NAMES++ def is_active(self, context: UnifiedContext) -> bool:+ return is_setup_turn(context)++ def system_block(+ self,+ context: UnifiedContext,+ *,+ language: str,+ prompts: dict[str, Any],+ ) -> PromptBlock | None:+ reason = setup_activation(context)+ if not reason:+ return None+ override = _prompt_text(prompts, ("setup", "system"))+ content = override or _load_system_prompt(language)++ gaps = cached_gaps(context)+ if gaps:+ lines = "\n".join(f"- {gap.summary} {gap.remedy}".strip() for gap in gaps)+ content = f"{content}\n\n## What this install is currently missing\n{lines}"+ else:+ content = f"{content}\n\n## What this install is currently missing\n- Nothing."++ if reason == "intro":+ # The user did not raise this subject, so the opening has to earn its+ # place: name the one thing that is missing, offer to fix it, and+ # drop it if they would rather do something else.+ content = (+ f"{content}\n\n## This is the user's first conversation\n"+ "They have not asked about configuration. Answer whatever they "+ "actually said first. Then, in one or two sentences at the end, "+ "mention the single most important gap above and offer to set it "+ "up. Do not list every gap, do not open with it, and do not "+ "raise it again if they move on."+ )+ # Spent only here: an explicit or intent-driven turn must not consume+ # the one proactive offer an unconfigured install gets.+ mark_intro_shown()+ return PromptBlock(SETUP_CAPABILITY_NAME, content)++ def augment_kwargs(+ self,+ tool_name: str,+ kwargs: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ # Nothing server-owned to inject: these tools address settings by key+ # and resolve scope from the caller's own identity, so there is no+ # turn-scoped handle the model could otherwise forge.+ _ = (tool_name, context)+ return kwargs++ def pre_loop_seed(self, context: UnifiedContext) -> str:+ _ = context+ return ""+++def _prompt_text(prompts: dict[str, Any], path: tuple[str, ...]) -> str:+ value: Any = prompts+ for key in path:+ if not isinstance(value, dict):+ return ""+ value = value.get(key)+ return value if isinstance(value, str) and value else ""+++def _load_system_prompt(language: str) -> str:+ lang = "zh" if str(language or "en").lower().startswith("zh") else "en"+ prompt = resources.files(__package__).joinpath("prompts", lang, "system.md")+ return prompt.read_text(encoding="utf-8").strip()+++__all__ = ["SetupCapability"]diff --git a/deeptutor/capabilities/setup/jobs.py b/deeptutor/capabilities/setup/jobs.pynew file mode 100644index 000000000..a9b2d3c85--- /dev/null+++ b/deeptutor/capabilities/setup/jobs.py@@ -0,0 +1,279 @@+"""Long-running setup work: installing a parsing engine, fetching its weights.++Both jobs already exist as background subprocess managers with a cursor-based+line log — the settings page starts one and polls it. This module wraps them so+the *chat* surface can run the same job differently: start it, then follow the+log to completion inside a single tool call, relaying each new line through the+turn's event sink.++That shape is chosen for the user, not for convenience. A model that had to+poll would burn one LLM round-trip per check, so progress would arrive in+lurches between silences, and a ten-minute model download would cost a dozen+paid turns. Following the log inside one call gives a live feed for the price+of one.++What may be run is fixed by the same allow-lists the HTTP endpoints use+(``ENGINE_PIP_SPECS``, ``ENGINE_MODEL_DOWNLOADERS``, MinerU's own resolver).+The model supplies an engine id, never a package name or a command, so no+prompt — or anything an attacker managed to get into one — can turn this into+arbitrary installation.+"""++from __future__ import annotations++import asyncio+from collections.abc import Awaitable, Callable+from dataclasses import dataclass, field+from typing import Any, Literal++JobAction = Literal["install_engine", "download_models"]++# A job may legitimately run for a long time (multi-GB weights over a slow+# link). The cap only bounds how long the *tool call* follows it: the job keeps+# running in the background afterwards and the user is told how to check back,+# rather than the turn hanging indefinitely.+_MAX_FOLLOW_SECONDS = 30 * 60+_POLL_INTERVAL_SECONDS = 1.0+# Emit a keep-alive after this much silence. Must stay comfortably under the+# chat client's smallest configurable response timeout (30s), which measures+# time since the last event rather than total turn duration.+_HEARTBEAT_SECONDS = 15.0+++@dataclass(frozen=True, slots=True)+class JobOutcome:+ ok: bool+ action: str+ engine: str+ state: str = ""+ message: str = ""+ lines: list[str] = field(default_factory=list)+ still_running: bool = False++ def to_dict(self) -> dict[str, Any]:+ return {+ "ok": self.ok,+ "action": self.action,+ "engine": self.engine,+ "state": self.state,+ "message": self.message,+ # Only the tail is returned to the model: the full log streamed to+ # the user live, and a pip transcript would otherwise crowd out the+ # turn's context for no decision-making value.+ "log_tail": self.lines[-20:],+ "still_running": self.still_running,+ }+++def available_jobs() -> list[dict[str, Any]]:+ """Describe every setup job that could be started right now.++ Availability is computed from the engine registry, so an engine that is+ already installed does not offer an install, and an engine with no+ downloader does not offer a download.+ """+ from deeptutor.services.parsing.engines._install import (+ installable_engines,+ model_downloadable_engines,+ )+ from deeptutor.services.parsing.engines.factory import is_engine_available, list_engines++ out: list[dict[str, Any]] = []+ installable = installable_engines()+ downloadable = model_downloadable_engines()+ for engine in list_engines():+ engine_id = str(engine.get("id") or "")+ if not engine_id:+ continue+ installed = is_engine_available(engine_id)+ if engine_id in installable and not installed:+ out.append(+ {+ "action": "install_engine",+ "engine": engine_id,+ "label": f"Install {engine.get('name') or engine_id}",+ "detail": str(engine.get("description") or ""),+ }+ )+ if engine_id in downloadable and installed:+ out.append(+ {+ "action": "download_models",+ "engine": engine_id,+ "label": f"Download {engine.get('name') or engine_id} model weights",+ "detail": "Required before this engine can parse locally. Several GB.",+ }+ )+ # MinerU downloads its weights through its own CLI rather than the shared+ # downloader table, so it is not in ``model_downloadable_engines`` today. The+ # membership check keeps this from becoming a duplicate entry if it is ever+ # added there — the loop above would already have listed it.+ if "mineru" not in downloadable and is_engine_available("mineru"):+ out.append(+ {+ "action": "download_models",+ "engine": "mineru",+ "label": "Download MinerU model weights",+ "detail": "Required for local MinerU parsing. Several GB.",+ }+ )+ return out+++def _start_install(engine: str) -> tuple[bool, str, Any]:+ from deeptutor.services.parsing.engines._install import (+ ENGINE_PIP_SPECS,+ get_background_job_manager,+ )++ specs = ENGINE_PIP_SPECS.get(engine)+ if not specs:+ return False, f"There is no one-step install for the '{engine}' engine.", None+ manager = get_background_job_manager()+ started = manager.start_install(engine=engine, specs=specs)+ return bool(started.get("ok")), str(started.get("message") or ""), manager+++def _start_model_download(engine: str) -> tuple[bool, str, Any]:+ if engine == "mineru":+ return _start_mineru_download()++ from deeptutor.services.parsing.engines._install import (+ get_background_job_manager,+ model_downloadable_engines,+ resolve_model_downloader,+ )++ if engine not in model_downloadable_engines():+ return False, f"The '{engine}' engine has no model download step.", None+ cmd = resolve_model_downloader(engine)+ if not cmd:+ return (+ False,+ (+ f"The {engine} model downloader was not found. Reinstalling the engine puts "+ "its command back on PATH."+ ),+ None,+ )+ manager = get_background_job_manager()+ started = manager.start_model_download(engine=engine, cmd=cmd)+ return bool(started.get("ok")), str(started.get("message") or ""), manager+++def _start_mineru_download() -> tuple[bool, str, Any]:+ from deeptutor.services.config.runtime_settings import get_runtime_settings_service+ from deeptutor.services.parsing.engines.mineru.models import (+ get_model_download_manager,+ resolve_models_downloader,+ )++ settings = get_runtime_settings_service().load_document_parsing()+ engine_settings = (settings.get("engines") or {}).get("mineru") or {}+ resolved = resolve_models_downloader(str(engine_settings.get("local_cli_path") or ""))+ if not resolved.get("found"):+ return (+ False,+ (+ "The MinerU model downloader was not found. MinerU 2.x needs to be installed "+ "first (its 1.x predecessor has no one-step download)."+ ),+ None,+ )+ manager = get_model_download_manager()+ started = manager.start(+ downloader=str(resolved.get("path") or ""),+ model_type=str(engine_settings.get("model_version") or "pipeline"),+ source=str(engine_settings.get("model_download_source") or "huggingface"),+ endpoint=str(engine_settings.get("model_download_endpoint") or ""),+ )+ return bool(started.get("ok")), str(started.get("message") or ""), manager+++async def run_job(+ action: str,+ engine: str,+ *,+ on_line: Callable[[str], Awaitable[None]] | None = None,+) -> JobOutcome:+ """Start a setup job and follow its log until it ends.++ ``on_line`` receives each new log line as it appears so the caller can+ relay it live. Returns once the job reaches a terminal state, or once the+ follow budget runs out — in which case ``still_running`` is True and the+ job continues in the background.+ """+ normalized = str(action or "").strip().lower()+ engine_id = str(engine or "").strip().lower().replace("-", "_")++ if normalized == "install_engine":+ ok, message, manager = _start_install(engine_id)+ elif normalized == "download_models":+ ok, message, manager = _start_model_download(engine_id)+ else:+ return JobOutcome(+ ok=False,+ action=normalized,+ engine=engine_id,+ message=f"Unknown setup job '{action}'.",+ )++ if not ok or manager is None:+ return JobOutcome(ok=False, action=normalized, engine=engine_id, message=message)++ lines: list[str] = []+ cursor = 0+ waited = 0.0+ quiet = 0.0+ state = "running"+ final_message = ""+ while waited < _MAX_FOLLOW_SECONDS:+ # ``status`` only touches an in-memory buffer under a short lock, but it+ # is still a blocking call — keep it off the event loop so the turn's+ # other streaming is not stalled by it.+ status = await asyncio.to_thread(manager.status, cursor)+ cursor = int(status.get("next_cursor") or cursor)+ new_lines = [str(line) for line in status.get("lines") or []]+ for text in new_lines:+ lines.append(text)+ if on_line is not None:+ await on_line(text)+ quiet = 0.0 if new_lines else quiet + _POLL_INTERVAL_SECONDS+ state = str(status.get("state") or "running")+ final_message = str(status.get("message") or "")+ if state in {"done", "failed", "cancelled"}:+ break+ if quiet >= _HEARTBEAT_SECONDS and on_line is not None:+ # Long silences are normal — pip downloading a large wheel emits+ # nothing for minutes. The chat client times out on *time since the+ # last event*, not total duration, so without a heartbeat the user's+ # turn is declared dead while the install is healthy and running.+ await on_line(f"… still working ({int(waited)}s elapsed)")+ quiet = 0.0+ await asyncio.sleep(_POLL_INTERVAL_SECONDS)+ waited += _POLL_INTERVAL_SECONDS++ if state == "running":+ return JobOutcome(+ ok=True,+ action=normalized,+ engine=engine_id,+ state=state,+ message=(+ f"Still running after {_MAX_FOLLOW_SECONDS // 60} minutes; it continues in "+ "the background. Check back with inspect_setup."+ ),+ lines=lines,+ still_running=True,+ )+ return JobOutcome(+ ok=state == "done",+ action=normalized,+ engine=engine_id,+ state=state,+ message=final_message,+ lines=lines,+ )+++__all__ = ["JobAction", "JobOutcome", "available_jobs", "run_job"]diff --git a/deeptutor/capabilities/setup/prompts/en/system.md b/deeptutor/capabilities/setup/prompts/en/system.mdnew file mode 100644index 000000000..953c7c51e--- /dev/null+++ b/deeptutor/capabilities/setup/prompts/en/system.md@@ -0,0 +1,80 @@+# Configuring DeepTutor++You can read and change this DeepTutor install's own configuration. Your normal+tools stay available — these four are additional.++## Always look before you offer++Call `inspect_setup` before proposing anything. One call reports the whole+install — current values, which options exist here, what is missing, which+installs or downloads are possible — so call it once and work from that, not+once per area. Never offer an option you have not seen in its output, and never+claim something is unavailable without looking.++Read the permission fields while you are there. A setting with+`writable: false`, or a job with `runnable: false`, cannot be done from this+conversation no matter how it is phrased — say who can do it and what the+alternative is instead of offering to try.++## Confirm with the user, then act++Use `ask_user` to confirm any change before `apply_setting`. Put the options+straight from `inspect_setup` into the card — its `label` and `description` are+already written for that. Bundle related questions into one card rather than+asking twice.++Two exceptions, where you should just do it and say so:++- The user already named exactly what they want ("switch the interface to+ Chinese") — that *is* the confirmation.+- The change is reversible, personal, and obvious in effect (language, theme).++## Say what a change costs++`apply_setting` returns an `effect`. Report it in your reply, in the user's+language:++- `instant` — nothing more to do.+- `restart` — the value only takes hold when DeepTutor restarts. Say so plainly.+- `reindex` — existing derived data no longer matches. For the embedding model+ this means every knowledge base has to be rebuilt before it can be searched+ again. Never present this as a free switch.++If the result carries `also_changed`, a second setting moved with the first —+say so. Setting the interface language on an install that never had a separate+reply language, for example, switches replies too. The user should hear that+from you, not discover it.++The chat and embedding models are connection-tested before anything is saved.+If the test fails nothing was changed — report the failure and what it suggests+(wrong key, unreachable endpoint, model not available on that plan), and leave+the old setting alone. To undo a change, call `apply_setting` again with the+`previous` value it returned.++## Never handle secrets++You must not ask the user to type an API key, token, or password into the chat,+and must not repeat one back if they do. When a step needs credentials, call+`request_credential`: it shows the user a card that opens the settings page+where the value is entered directly. Tell them what to fill in there, and pick+up once they say it is done.++## Installs and downloads++`run_setup_job` installs a parsing engine or fetches its model weights. Weights+are typically several gigabytes and take minutes — ask first with `ask_user`,+say how big it is, and only offer jobs that `inspect_setup` listed under+`jobs_available`. Progress streams to the user while it runs, so do not narrate+each line back; summarise the outcome when it finishes.++## Stay proportionate++Fix what the user asked about. If you noticed something else worth changing,+mention it in one sentence at the end — do not turn a request to switch themes+into a configuration review. If the user is in the middle of other work and+configuration only came up in passing, answer briefly and let them get back to+it.++If something cannot be changed from here — a deployment-wide setting when the+user is not an administrator — say who can change it and what the alternative+is, rather than trying and reporting a failure.diff --git a/deeptutor/capabilities/setup/prompts/zh/system.md b/deeptutor/capabilities/setup/prompts/zh/system.mdnew file mode 100644index 000000000..1d3e4fd91--- /dev/null+++ b/deeptutor/capabilities/setup/prompts/zh/system.md@@ -0,0 +1,44 @@+# 配置 DeepTutor++你可以读取并修改这个 DeepTutor 实例自身的配置。你原有的工具依然可用——这四个是额外增加的。++## 先看,再提议++在提出任何建议之前先调用 `inspect_setup`。一次调用就会报告整个实例的情况——当前取值、本机有哪些可选项、缺了什么、可以执行哪些安装或下载——所以只调一次并据此工作,不要按区域反复调用。不要提供任何你没在它输出里见过的选项,也不要在没查看的情况下断言某项不可用。++顺便读一下权限字段。`writable: false` 的设置项、`runnable: false` 的任务,无论怎么措辞都无法在这次对话里完成——直接说明谁能做、有什么替代方案,而不要提议去试。++## 先跟用户确认,再动手++在调用 `apply_setting` 之前,用 `ask_user` 确认。把 `inspect_setup` 给出的选项原样放进卡片——它的 `label` 和 `description` 就是为此写好的。相关的问题合并成一张卡片,不要分两次问。++两种例外,直接做并说明即可:++- 用户已经明确说清了要什么("把界面切成中文")——这本身就是确认。+- 改动可逆、属于个人偏好、效果一目了然(语言、主题)。++## 说清楚这次改动的代价++`apply_setting` 会返回 `effect`。用用户的语言在回复里说明:++- `instant`——无需其他操作。+- `restart`——重启 DeepTutor 后才会生效,要直说。+- `reindex`——已有的派生数据不再匹配。对嵌入模型来说,这意味着所有知识库都必须重建后才能重新检索。绝不要把它说成零代价的切换。++如果结果里带了 `also_changed`,说明有第二项设置跟着变了——要说出来。比如在从未单独设过回答语言的实例上改界面语言,回答语言也会一起变。这件事应该由你告诉用户,而不是让对方自己发现。++聊天模型和嵌入模型在保存前会先做连通性测试。测试失败时什么都没改——如实报告失败原因和它意味着什么(密钥不对、地址不通、该套餐没有这个模型),并保持原设置不变。要撤销一次改动,用它返回的 `previous` 值再调用一次 `apply_setting`。++## 绝不经手密钥++不要让用户把 API key、令牌或密码输入到聊天里,用户即使发了也不要复述。需要凭据时调用 `request_credential`:它会给用户一张卡片,跳转到直接录入的设置页。告诉用户在那里填什么,等对方说填好了再继续。++## 安装与下载++`run_setup_job` 用来安装解析引擎或拉取它的模型权重。权重通常有几个 GB、需要数分钟——先用 `ask_user` 询问,说明体积,并且只提供 `inspect_setup` 在 `jobs_available` 里列出的任务。运行过程中进度会实时推送给用户,所以不要逐行复述,结束时总结结果即可。++## 保持分寸++只解决用户问的那件事。如果你顺带发现了别的值得改的地方,在结尾用一句话提一下——不要把"换个主题"变成一次配置大检查。如果用户正在做别的事、配置只是顺口提到,就简短作答,让对方继续原来的工作。++如果某项在这里改不了——比如用户不是管理员而这是部署级设置——直接说明谁能改、有什么替代方案,而不是先尝试再报告失败。diff --git a/deeptutor/capabilities/setup/tools.py b/deeptutor/capabilities/setup/tools.pynew file mode 100644index 000000000..2ae588180--- /dev/null+++ b/deeptutor/capabilities/setup/tools.py@@ -0,0 +1,345 @@+"""The four tools through which DeepTutor configures itself.++They are deliberately generic: each one walks+:mod:`deeptutor.services.config.settings_spec` rather than knowing anything+about a particular setting, so a new knob becomes reachable by adding a spec+row and touching nothing here.++``inspect_setup``+ Read the install: current values, what else each row offers, what is+ missing, and which long-running jobs could be started.++``apply_setting``+ Commit one row, after the checks in :mod:`deeptutor.capabilities.setup.apply`.++``request_credential``+ The one thing the agent is *not* allowed to do itself. Anything that needs+ an API key hands off to the settings page, so credentials never enter the+ model's context, the conversation history, or the session transcript.++``run_setup_job``+ Install an engine or fetch its weights, following the log live.++Asking the user a question is not among them: ``ask_user`` already does that,+already renders a card with clickable options, and already pauses the turn+until the answer arrives. The spec rows return their options in exactly that+card's ``{label, description}`` shape, so a proposal is a plain ``ask_user``+call rather than a bespoke second mechanism.+"""++from __future__ import annotations++import json+from typing import Any++from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult++SETUP_TOOL_NAMES: tuple[str, ...] = (+ "inspect_setup",+ "apply_setting",+ "request_credential",+ "run_setup_job",+)++# Services whose configuration involves a secret. Each maps to the settings+# route that already owns its provider form.+_CREDENTIAL_ROUTES: dict[str, tuple[str, str]] = {+ "llm": ("/settings/llm", "chat model provider"),+ "embedding": ("/settings/embedding", "embedding model provider"),+ "search": ("/settings/search", "web search provider"),+ "parsing": ("/settings/document-parsing", "document parsing engine"),+}+++def _ok(payload: Any, **metadata: Any) -> ToolResult:+ return ToolResult(+ content=json.dumps(payload, ensure_ascii=False),+ success=True,+ metadata=dict(metadata),+ )+++def _err(message: str, **metadata: Any) -> ToolResult:+ return ToolResult(content=message, success=False, metadata=dict(metadata))+++class InspectSetupTool(BaseTool):+ """Report what the install is configured to do, and what it cannot."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="inspect_setup",+ description=(+ "Read DeepTutor's own configuration: every setting you can "+ "change, its current value, the other values it accepts, what "+ "changing it would cost, plus anything missing from this "+ "install and any install/download jobs available. Call this "+ "FIRST — before offering the user any configuration change — "+ "so what you offer matches what this machine actually has."+ ),+ parameters=[+ ToolParameter(+ name="area",+ type="string",+ description=(+ "Optional filter: 'interface' (language, theme), "+ "'models' (chat / embedding / search), 'parsing' "+ "(document engine). Omit for everything."+ ),+ required=False,+ enum=["interface", "models", "parsing"],+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.capabilities.setup.access import can_write+ from deeptutor.capabilities.setup.binding import setup_gaps+ from deeptutor.capabilities.setup.jobs import available_jobs+ from deeptutor.services.config.settings_spec import specs_for_area++ area = str(kwargs.get("area") or "").strip().lower()+ rows: list[dict[str, Any]] = []+ for spec in specs_for_area(area):+ decision = can_write(spec.scope)+ try:+ current = spec.read()+ choices = spec.choices()+ except Exception as exc: # noqa: BLE001 - one bad row must not hide the rest+ rows.append({"key": spec.key, "label": spec.label, "error": str(exc)[:200]})+ continue+ rows.append(+ {+ "key": spec.key,+ "label": spec.label,+ "area": spec.area,+ "summary": spec.summary,+ "scope": spec.scope,+ "effect": spec.effect,+ "effect_detail": spec.effect_detail,+ "writable": decision.allowed,+ "not_writable_because": decision.reason,+ "current": current,+ "current_label": next(+ (c.label for c in choices if c.value == current),+ "" if current else "not set",+ ),+ "options": [+ {+ "value": c.value,+ "label": c.label,+ "description": c.description,+ "available": c.available,+ }+ for c in choices+ ],+ }+ )++ # Installing an engine or fetching weights changes the machine for+ # every account, so it carries the same gate as a global setting. The+ # verdict rides on each job: without it the model reads a job list it+ # cannot run and offers the user something that will be refused.+ jobs_decision = can_write("global")+ jobs = [+ {+ **job,+ "runnable": jobs_decision.allowed,+ "not_runnable_because": jobs_decision.reason,+ }+ for job in available_jobs()+ ]++ payload = {+ "settings": rows,+ "gaps": [gap.to_dict() for gap in setup_gaps()],+ "jobs_available": jobs,+ }+ return _ok(payload, setup_inspect=payload)+++class ApplySettingTool(BaseTool):+ """Commit one setting after validating and probing it."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="apply_setting",+ description=(+ "Change one DeepTutor setting. The value must be one of the "+ "options inspect_setup reported for that key. Settings that "+ "can break the assistant (the chat and embedding models) are "+ "connection-tested before anything is saved, and are left "+ "untouched when the test fails. Confirm with the user via "+ "ask_user before calling this, then report the returned "+ "'effect' — some changes need a restart or a knowledge-base "+ "rebuild. To undo, call again with the returned 'previous'."+ ),+ parameters=[+ ToolParameter(+ name="key",+ type="string",+ description="Setting key exactly as reported by inspect_setup.",+ ),+ ToolParameter(+ name="value",+ type="string",+ description="One of that setting's option values (not its label).",+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.capabilities.setup.apply import apply_setting++ key = str(kwargs.get("key") or "").strip()+ value = str(kwargs.get("value") or "").strip()+ if not key or not value:+ return _err("apply_setting needs both 'key' and 'value'.")++ outcome = await apply_setting(key, value)+ payload = outcome.to_dict()+ if not outcome.ok:+ return ToolResult(+ content=json.dumps(payload, ensure_ascii=False),+ success=False,+ metadata={"setup_apply": payload},+ )+ # ``setup_applied`` tells the frontend which slice of its cached+ # settings just went stale; the UI re-reads that slice instead of+ # showing a value the backend no longer holds.+ return _ok(payload, setup_apply=payload, setup_applied={"key": outcome.key})+++class RequestCredentialTool(BaseTool):+ """Hand a credential-entering step back to the user's own settings page."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="request_credential",+ description=(+ "Use when a change needs an API key, token or password. You "+ "must NEVER ask the user to type a secret into the chat and "+ "must never handle one yourself: this shows the user a card "+ "that opens the right settings page, where the value is "+ "entered directly into DeepTutor. Call it, tell the user what "+ "to do there, and continue once they say they are done."+ ),+ parameters=[+ ToolParameter(+ name="service",+ type="string",+ description="Which provider needs credentials.",+ enum=["llm", "embedding", "search", "parsing"],+ ),+ ToolParameter(+ name="reason",+ type="string",+ description=(+ "One line explaining to the user why this is needed, in their language."+ ),+ required=False,+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ service = str(kwargs.get("service") or "").strip().lower()+ route = _CREDENTIAL_ROUTES.get(service)+ if route is None:+ return _err(+ f"Unknown service '{service}'. Expected one of: "+ f"{', '.join(sorted(_CREDENTIAL_ROUTES))}."+ )+ path, label = route+ payload = {+ "service": service,+ "label": label,+ "settings_path": path,+ "reason": str(kwargs.get("reason") or "").strip(),+ }+ return _ok(+ {+ **payload,+ "status": "handed_off",+ "note": (+ "The user was shown a card linking to the settings page. Secrets are "+ "never entered through chat."+ ),+ },+ setup_credential=payload,+ )+++class RunSetupJobTool(BaseTool):+ """Install a parsing engine or download its model weights."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="run_setup_job",+ description=(+ "Install a document-parsing engine, or download the model "+ "weights it needs. Only engines inspect_setup listed under "+ "'jobs_available' can be run. These take minutes and model "+ "weights can be several gigabytes — ask the user with "+ "ask_user before starting, and say how large it is. Progress "+ "streams to the user while it runs."+ ),+ parameters=[+ ToolParameter(+ name="action",+ type="string",+ description="What to run.",+ enum=["install_engine", "download_models"],+ ),+ ToolParameter(+ name="engine",+ type="string",+ description="Engine id exactly as reported by inspect_setup.",+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.capabilities.setup.access import can_write+ from deeptutor.capabilities.setup.jobs import run_job++ # Installing software and writing multi-gigabyte weights changes the+ # machine for every account on it, so it sits behind the same gate as+ # the other deployment-wide changes.+ decision = can_write("global")+ if not decision.allowed:+ return _err(decision.reason)++ action = str(kwargs.get("action") or "").strip()+ engine = str(kwargs.get("engine") or "").strip()+ if not action or not engine:+ return _err("run_setup_job needs both 'action' and 'engine'.")++ event_sink = kwargs.get("event_sink")++ async def _on_line(line: str) -> None:+ if event_sink is None:+ return+ await event_sink("tool_log", line, {"setup_job": {"action": action, "engine": engine}})++ outcome = await run_job(action, engine, on_line=_on_line)+ payload = outcome.to_dict()+ if not outcome.ok:+ return ToolResult(+ content=json.dumps(payload, ensure_ascii=False),+ success=False,+ metadata={"setup_job": payload},+ )+ # An install changes which engines are selectable, so the settings UI+ # must re-read the parsing slice even though no setting was written.+ return _ok(payload, setup_job=payload, setup_applied={"key": "document_parsing.engine"})+++SETUP_TOOL_TYPES: tuple[type[BaseTool], ...] = (+ InspectSetupTool,+ ApplySettingTool,+ RequestCredentialTool,+ RunSetupJobTool,+)++__all__ = ["SETUP_TOOL_NAMES", "SETUP_TOOL_TYPES"]diff --git a/deeptutor/i18n/metadata_i18n.py b/deeptutor/i18n/metadata_i18n.pyindex 15d743ce6..002fd214b 100644--- a/deeptutor/i18n/metadata_i18n.py+++ b/deeptutor/i18n/metadata_i18n.py@@ -31,6 +31,10 @@ _CAPABILITY_DESCRIPTIONS: dict[str, dict[str, str]] = {"en": "Create visual explanations such as SVG, charts, Mermaid, HTML, or Manim.","zh": "生成 SVG、图表、Mermaid、HTML 或 Manim 等可视化讲解。",},+ "immersive_reading": {+ "en": "Read a document with the assistant, cited page by page.",+ "zh": "与助手一起阅读文档,逐页标明出处。",+ },}_TOOL_DESCRIPTIONS: dict[str, dict[str, str]] = {diff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.pyindex 937e8f0c8..90247178e 100644--- a/deeptutor/knowledge/kb_types.py+++ b/deeptutor/knowledge/kb_types.py@@ -87,11 +87,33 @@ CONNECTED_KB_TYPES = frozenset()+# Connected kinds the ``rag`` tool cannot retrieve from: an Obsidian vault has no+# index at all (its capability navigates the live files) and a subagent is not a+# document collection. The other connected kinds ARE retrievable — ``linked``+# mounts an index built elsewhere, while ``lightrag_server`` and ``ima`` offload+# retrieval over HTTP — so "connected" must never be used as a synonym for+# "unsearchable" (it once cost Book generation every one of those sources).+NON_RETRIEVABLE_KB_TYPES = frozenset({OBSIDIAN_KB_TYPE, SUBAGENT_KB_TYPE})++def is_connected_kb(entry: Any) -> bool:"""True for pointer KBs whose data lives outside ``data/knowledge_bases``."""return isinstance(entry, dict) and entry.get("type") in CONNECTED_KB_TYPES+def supports_rag_retrieval(entry: Any) -> bool:+ """Whether the ``rag`` tool can retrieve from this KB.++ True for every ordinary indexed KB and for the connected kinds that resolve+ to an index or a retrieval API. Callers that need "can I sweep this KB with+ ``rag_search``?" must ask this rather than :func:`is_connected_kb`, whose+ answer is about where the *documents* live.+ """+ if not isinstance(entry, dict):+ return True+ return entry.get("type") not in NON_RETRIEVABLE_KB_TYPES++def supports_local_raw_files(entry: Any) -> bool:"""Whether the KB owns a DeepTutor-managed local ``raw/`` directory.@@ -120,7 +142,9 @@ __all__ = ["LIGHTRAG_SERVER_KB_TYPE","IMA_KB_TYPE","CONNECTED_KB_TYPES",+ "NON_RETRIEVABLE_KB_TYPES","is_connected_kb","supports_local_raw_files",+ "supports_rag_retrieval","external_root_of",]diff --git a/deeptutor/knowledge/manifest.py b/deeptutor/knowledge/manifest.pyindex 37a5e4c63..2b9ab9915 100644--- a/deeptutor/knowledge/manifest.py+++ b/deeptutor/knowledge/manifest.py@@ -15,6 +15,15 @@ consumers can never disagree:* the ``kb_files`` tool enumerates on demand (:func:`render_manifest_report`)for the full list, which a system-prompt manifest deliberately truncates.+Most inventories are a directory walk. A *connected* KB whose documents live+behind an API has no directory, but that does not always mean the inventory is+unknowable: when the service exposes a listing call, this module reads it through+:data:`_REMOTE_INVENTORY_READERS` and reports the result exactly like a local one+(Tencent IMA's ``get_knowledge_list`` is the first such reader). Only when there+is no reader, or the call fails, does a KB fall back to being reported as+non-enumerable. A remote listing may be bounded by a request budget, in which+case the count is flagged as a lower bound rather than being presented as a total.+Deliberately NOT reported: how many documents made it into the *index*. Everyper-file index record available is unreliable — LlamaIndex's ``docstore.json``counts nodes (chunk-level, so it drifts with the chunking config and costs a@@ -27,7 +36,7 @@ document set plus the KB's index *status* and stops there.from __future__ import annotations-from collections.abc import Iterator, Mapping, Sequence+from collections.abc import Callable, Iterator, Mapping, Sequencefrom dataclasses import dataclassimport fnmatchimport os@@ -58,13 +67,35 @@ UNAVAILABLE_MISSING = "missing"# KB types that hold no local document set at all: their content lives behind# an API. Reporting them as "0 documents" would be a lie, so they are reported-# as non-enumerable instead.+# as non-enumerable unless a remote reader below can list them for real._NON_DOCUMENT_KB_TYPES: dict[str, str] = {LIGHTRAG_SERVER_KB_TYPE: UNAVAILABLE_REMOTE,IMA_KB_TYPE: UNAVAILABLE_REMOTE,SUBAGENT_KB_TYPE: UNAVAILABLE_AGENT,}+# The document names a connected KB's own service can list, plus whether that+# listing is complete. ``None`` means the inventory could not be read at all, so+# the KB is reported as non-enumerable — the pre-reader behaviour.+RemoteInventoryReader = Callable[[Mapping[str, Any]], "tuple[list[str], bool] | None"]+++def _ima_inventory(entry: Mapping[str, Any]) -> tuple[list[str], bool] | None:+ """List a connected Tencent IMA library through its own browse API."""+ from deeptutor.services.rag.pipelines.ima.inventory import read_inventory++ inventory = read_inventory(entry)+ if inventory is None:+ return None+ return list(inventory.documents), inventory.complete+++# Connected KB types whose inventory is readable over their API. Imported lazily+# inside each reader so this module stays free of service-layer imports.+_REMOTE_INVENTORY_READERS: dict[str, RemoteInventoryReader] = {+ IMA_KB_TYPE: _ima_inventory,+}+@dataclass(frozen=True)class KbDocument:@@ -98,6 +129,9 @@ class KbManifest:unavailable: str = """""Reason code from this module's ``UNAVAILABLE_*`` set; ``""`` when listable."""+ total_is_lower_bound: bool = False+ """True when a bounded remote listing stopped early — ``total`` is "at least"."""+@propertydef enumerable(self) -> bool:return not self.unavailable@@ -180,6 +214,10 @@ def build_manifest("pattern": pattern.strip(),}+ reader = _REMOTE_INVENTORY_READERS.get(kb_type)+ if reader is not None:+ return _remote_manifest(manifest_fields, record, reader=reader, limit=limit)+root = document_root(kb_dir, record)if root is None:return KbManifest(**manifest_fields, unavailable=_NON_DOCUMENT_KB_TYPES[kb_type])@@ -199,6 +237,39 @@ def build_manifest()+def _remote_manifest(+ fields: dict[str, Any],+ entry: Mapping[str, Any],+ *,+ reader: RemoteInventoryReader,+ limit: int,+) -> KbManifest:+ """Build a manifest from a connected service's own document listing.++ Failing to reach the service is reported as non-enumerable rather than as an+ empty KB — the same distinction the local path draws for a missing folder.+ Sizes are unknown over an API, so documents carry ``0`` and the renderers+ omit the size rather than printing a misleading "0 B".+ """+ try:+ listing = reader(entry)+ except Exception:+ listing = None+ if listing is None:+ return KbManifest(**fields, unavailable=UNAVAILABLE_REMOTE)++ names, complete = listing+ matched_names = _filter_names(names, fields["pattern"])+ kept = matched_names[: max(0, limit)]+ return KbManifest(+ **fields,+ total=len(names),+ matched=len(matched_names),+ documents=tuple(KbDocument(name=name, size=0) for name in kept),+ total_is_lower_bound=not complete,+ )++def _filter_names(names: Sequence[str], pattern: str) -> list[str]:if not pattern:return list(names)@@ -265,7 +336,8 @@ _NOTE_TEXT: dict[str, dict[str, str]] = {"en": {"header": ("[Knowledge Base Inventory]\n"- "What the attached knowledge bases actually contain, read from disk."+ "What the attached knowledge bases actually contain, read from the "+ "knowledge bases themselves."),"empty": "no documents yet","total": "{count} document{plural}",@@ -280,7 +352,7 @@ _NOTE_TEXT: dict[str, dict[str, str]] = {),},"zh": {- "header": "[知识库清单]\n以下是已挂载知识库的真实文档构成,直接读取自磁盘。",+ "header": "[知识库清单]\n以下是已挂载知识库的真实文档构成,直接读取自各知识库本身。","empty": "暂无文档","total": "共 {count} 个文档","omitted": "另有 {count} 个未列出,可用 kb_files 查看完整清单",@@ -322,8 +394,14 @@ def _colon(language: str) -> str:return ":" if language == "zh" else ": "-def _count(text: Mapping[str, str], key: str, count: int) -> str:- return text[key].format(count=count, plural="" if count == 1 else "s")+def _total_label(manifest: KbManifest, text: Mapping[str, str]) -> str:+ """The document count, marked as a lower bound when the listing was bounded."""+ count = f"{manifest.total}+" if manifest.total_is_lower_bound else str(manifest.total)+ return text["total"].format(count=count, plural="" if manifest.total == 1 else "s")+++def _total_number(manifest: KbManifest) -> str:+ return f"{manifest.total}+" if manifest.total_is_lower_bound else str(manifest.total)def _qualifier(manifest: KbManifest, language: str) -> str:@@ -363,7 +441,7 @@ def _note_line(manifest: KbManifest, language: str) -> str:if manifest.omitted:tail = text["omitted"].format(count=manifest.omitted)listed = f"{listed}({tail})" if language == "zh" else f"{listed} ({tail})"- return f"{head}{_count(text, 'total', manifest.total)} — {listed}"+ return f"{head}{_total_label(manifest, text)} — {listed}"def render_manifest_report(manifest: KbManifest, *, language: str) -> str:@@ -381,7 +459,7 @@ def render_manifest_report(manifest: KbManifest, *, language: str) -> str:text["heading"].format(name=manifest.name,qualifier=qualifier,- total=manifest.total,+ total=_total_number(manifest),plural="" if manifest.total == 1 else "s",)]@@ -395,12 +473,17 @@ def render_manifest_report(manifest: KbManifest, *, language: str) -> str:text["omitted"].format(shown=len(manifest.documents), omitted=manifest.omitted))lines.extend(- f"{index}. {document.name} ({_human_size(document.size)})"+ f"{index}. {document.name}{_size_suffix(document.size)}"for index, document in enumerate(manifest.documents, start=1))return "\n".join(lines)+def _size_suffix(size: int) -> str:+ """`` (1.2 MB)``, or nothing when the size is unknown (remote listings)."""+ return f" ({_human_size(size)})" if size > 0 else ""++def _human_size(size: int) -> str:if size < 1024:return f"{size} B"diff --git a/deeptutor/reading/__init__.py b/deeptutor/reading/__init__.pynew file mode 100644index 000000000..4c7ed34aa--- /dev/null+++ b/deeptutor/reading/__init__.py@@ -0,0 +1,81 @@+"""Immersive reading engine — materials, locators, annotations, export.++A *material* is a file the user reads: it is cut once into **units** and stored+per-unit, so every later operation addresses it by **locator** (a 1-indexed unit+number that means page / chapter / slide / section depending on the format).+That one abstraction is what lets a model cite "page 12" and the reader scroll+to page 12 without either side knowing the file is a PDF.++Layering, bottom-up — each layer depends only on the ones above it in this list:++* :mod:`.models` — dataclasses and errors. No I/O, no imports from siblings.+* :mod:`.extract` — file → units. The only module that knows about formats.+* :mod:`.search` — pure locator-addressed matching over ``(locator, text)``.+* :mod:`.store` — durable per-material layout, atomic writes, annotations.+* :mod:`.service` — the composition callers use (read / search / outline /+ quote verification).+* :mod:`.export` — the annotated artefacts a user can take away.++Nothing here imports the chat loop, the tool registry or FastAPI, so the engine+is testable on its own and the capability that drives it+(:mod:`deeptutor.capabilities.reading`) stays a thin shell.+"""++from __future__ import annotations++from deeptutor.reading.export import ExportFormat, ExportResult, export_material+from deeptutor.reading.extract import Extraction, extract_material+from deeptutor.reading.models import (+ ANNOTATION_COLORS,+ Annotation,+ AnnotationKind,+ MaterialManifest,+ MaterialNotFound,+ OutlineEntry,+ ReadingError,+ Rect,+ SearchHit,+ UnitKind,+)+from deeptutor.reading.search import SearchResult, search_units+from deeptutor.reading.service import (+ QuoteCheck,+ RenderedUnits,+ material_summary,+ parse_locators,+ render_outline,+ render_units,+ search_material,+ verify_quote,+)+from deeptutor.reading.store import ReadingStore, content_hash++__all__ = [+ "ANNOTATION_COLORS",+ "Annotation",+ "AnnotationKind",+ "ExportFormat",+ "ExportResult",+ "Extraction",+ "MaterialManifest",+ "MaterialNotFound",+ "OutlineEntry",+ "QuoteCheck",+ "ReadingError",+ "ReadingStore",+ "Rect",+ "RenderedUnits",+ "SearchHit",+ "SearchResult",+ "UnitKind",+ "content_hash",+ "export_material",+ "extract_material",+ "material_summary",+ "parse_locators",+ "render_outline",+ "render_units",+ "search_material",+ "search_units",+ "verify_quote",+]diff --git a/deeptutor/reading/export.py b/deeptutor/reading/export.pynew file mode 100644index 000000000..6bc4f7ae0--- /dev/null+++ b/deeptutor/reading/export.py@@ -0,0 +1,256 @@+"""Export a material together with the marks the reader made on it.++Two shapes, because they answer different needs:++* **PDF** (``fmt="pdf"``) — the original file with *real* PDF annotations written+ in via PyMuPDF. The point is portability: the result opens in Preview, Acrobat+ or Chrome with the highlights and notes intact, so a user's reading survives+ leaving DeepTutor. Only available for materials that kept their raw bytes.+* **Markdown** (``fmt="markdown"``) — the marks themselves, in locator order,+ each with its quote and note. Works for every format, and is what a user+ actually wants to paste into their own notes.++Coordinate handling is the one subtle part. Annotations are stored normalised+against the *visual* unit box (origin top-left, y down) because that is what the+browser measured. ``page.rect`` is the same visual box — PyMuPDF already applies+``/Rotate`` — so scaling by its width/height lands the rectangle where the user+drew it. Writing an annotation, however, addresses the page's *unrotated* space,+so a rotated page needs ``derotation_matrix`` applied on the way in. Skipping+that step is what makes highlights land sideways on scanned documents.+"""++from __future__ import annotations++from dataclasses import dataclass+import logging+from typing import Literal++from deeptutor.reading.models import (+ ANNOTATION_COLORS,+ DEFAULT_ANNOTATION_COLOR,+ Annotation,+ MaterialManifest,+ ReadingError,+)+from deeptutor.reading.store import ReadingStore++logger = logging.getLogger(__name__)++ExportFormat = Literal["auto", "pdf", "markdown"]++# Notes attached to a whole unit have no geometry; anchor their sticky icon a+# little inside the top-left corner so it is visible but not clipped.+_NOTE_FALLBACK_INSET = 24.0+++@dataclass(frozen=True, slots=True)+class ExportResult:+ """A ready-to-download artefact."""++ filename: str+ media_type: str+ data: bytes++ @property+ def byte_size(self) -> int:+ return len(self.data)+++def export_material(+ store: ReadingStore,+ material_id: str,+ *,+ fmt: ExportFormat = "auto",+) -> ExportResult:+ """Export *material_id*, choosing the richest available shape for ``auto``."""+ manifest = store.manifest(material_id)+ annotations = store.annotations(material_id)++ resolved = fmt+ if resolved == "auto":+ resolved = "pdf" if manifest.has_raw_view else "markdown"+ if resolved == "pdf" and not manifest.has_raw_view:+ raise ReadingError(+ f"{manifest.filename} has no original PDF to annotate — export it as Markdown instead."+ )++ if resolved == "pdf":+ return _export_pdf(store, manifest, annotations)+ return _export_markdown(store, manifest, annotations)+++# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+++def _export_pdf(+ store: ReadingStore,+ manifest: MaterialManifest,+ annotations: list[Annotation],+) -> ExportResult:+ raw_path = store.raw_path(manifest.material_id)+ if raw_path is None or not raw_path.is_file():+ raise ReadingError(f"{manifest.filename}: the original file is no longer available")++ stem = _stem(manifest.filename)+ filename = f"{stem}-annotated.pdf"++ if not annotations:+ # Nothing to draw — hand back the original bytes rather than paying a+ # re-serialisation that could only degrade the file.+ return ExportResult(+ filename=filename,+ media_type="application/pdf",+ data=raw_path.read_bytes(),+ )++ try:+ import pymupdf+ except ImportError as exc: # pragma: no cover - pymupdf is a core dep+ raise ReadingError("Annotated PDF export needs PyMuPDF") from exc++ by_locator: dict[int, list[Annotation]] = {}+ for annotation in annotations:+ by_locator.setdefault(annotation.locator, []).append(annotation)++ try:+ with pymupdf.open(raw_path) as doc:+ for locator, rows in sorted(by_locator.items()):+ if not 1 <= locator <= doc.page_count:+ continue+ page = doc[locator - 1]+ for annotation in rows:+ _draw_annotation(pymupdf, page, annotation)+ data = doc.tobytes(deflate=True, garbage=3)+ except ReadingError:+ raise+ except Exception as exc:+ raise ReadingError(f"{manifest.filename}: failed to write annotations ({exc})") from exc++ return ExportResult(filename=filename, media_type="application/pdf", data=data)+++def _draw_annotation(pymupdf, page, annotation: Annotation) -> None:+ """Write one stored annotation onto *page* as a native PDF annotation."""+ rects = _page_rects(pymupdf, page, annotation)+ colour = ANNOTATION_COLORS.get(annotation.color, ANNOTATION_COLORS[DEFAULT_ANNOTATION_COLOR])+ body = _annotation_body(annotation)++ try:+ if annotation.kind == "note" or not rects:+ point = (+ rects[0].tl+ if rects+ else pymupdf.Point(+ page.rect.x0 + _NOTE_FALLBACK_INSET,+ page.rect.y0 + _NOTE_FALLBACK_INSET,+ )+ )+ annot = page.add_text_annot(point, body or annotation.quote or "Note")+ elif annotation.kind == "underline":+ annot = page.add_underline_annot(rects)+ else:+ annot = page.add_highlight_annot(rects)+ if annotation.kind != "note":+ annot.set_colors(stroke=colour)+ if body:+ annot.set_info(content=body)+ annot.update()+ except Exception:+ # One bad rectangle must not lose the other marks on the page.+ logger.warning(+ "Skipped annotation %s on locator %s during export",+ annotation.annotation_id,+ annotation.locator,+ exc_info=True,+ )+++def _page_rects(pymupdf, page, annotation: Annotation) -> list:+ """Stored normalised rects → PyMuPDF rects in the page's own space."""+ visual = page.rect+ width, height = visual.width, visual.height+ if width <= 0 or height <= 0:+ return []++ derotate = page.derotation_matrix if page.rotation else None+ out = []+ for rect in annotation.rects:+ box = rect.clamped()+ if box.is_degenerate:+ continue+ absolute = pymupdf.Rect(+ visual.x0 + box.x0 * width,+ visual.y0 + box.y0 * height,+ visual.x0 + box.x1 * width,+ visual.y0 + box.y1 * height,+ )+ if derotate is not None:+ absolute = absolute * derotate+ out.append(absolute)+ return out+++def _annotation_body(annotation: Annotation) -> str:+ """The text carried inside the PDF annotation's popup."""+ note = (annotation.note or "").strip()+ if note:+ return note+ return ""+++# ---------------------------------------------------------------------------+# Markdown+# ---------------------------------------------------------------------------+++def _export_markdown(+ store: ReadingStore,+ manifest: MaterialManifest,+ annotations: list[Annotation],+) -> ExportResult:+ unit_word = manifest.unit.capitalize()+ lines: list[str] = [f"# {manifest.title or _stem(manifest.filename)}", ""]+ lines.append(f"*{manifest.filename} — {manifest.unit_count} {manifest.unit}s*")+ lines.append("")++ if not annotations:+ lines.append("_No annotations yet._")+ lines.append("")+ else:+ current: int | None = None+ for annotation in annotations:+ if annotation.locator != current:+ current = annotation.locator+ lines.append(f"## {unit_word} {current}")+ lines.append("")+ quote = " ".join((annotation.quote or "").split())+ if quote:+ lines.append(f"> {quote}")+ lines.append("")+ note = (annotation.note or "").strip()+ if note:+ for note_line in note.splitlines():+ lines.append(note_line.rstrip())+ lines.append("")+ if not quote and not note:+ lines.append(f"_({annotation.kind} with no text)_")+ lines.append("")++ text = "\n".join(lines).rstrip() + "\n"+ return ExportResult(+ filename=f"{_stem(manifest.filename)}-annotations.md",+ media_type="text/markdown; charset=utf-8",+ data=text.encode("utf-8"),+ )+++def _stem(filename: str) -> str:+ from pathlib import Path++ stem = Path(filename or "material").stem.strip()+ return stem or "material"+++__all__ = ["ExportFormat", "ExportResult", "export_material"]diff --git a/deeptutor/reading/extract.py b/deeptutor/reading/extract.pynew file mode 100644index 000000000..b651f3b96--- /dev/null+++ b/deeptutor/reading/extract.py@@ -0,0 +1,315 @@+"""Cut a source file into addressable units (the locator space).++One job, no I/O beyond reading the source: given a path, return the unit texts+plus what a unit *is* for that format. Everything else in the reading engine+consumes :class:`Extraction` and never looks at the original bytes again —+which is what keeps store, search, outline and export format-agnostic.++Per-format strategy, and why:++* **PDF** — PyMuPDF, one unit per physical page. Done here rather than through+ the shared text extractor because that one joins the pages into a single+ string; we need them apart. Physical pages are also the only unit that lines+ up with what the reader renders, so PDFs are the one format with a faithful+ raw view.+* **PPTX** — the shared extractor already emits ``--- Slide N ---`` separators,+ so we split on those instead of re-implementing python-pptx handling.+* **everything else** (EPUB, DOCX, XLSX, TXT, MD, code, …) — the shared+ extractor's plain text, cut into fixed-size *sections* on paragraph+ boundaries.++The last bullet is a deliberate trade-off for EPUB: chapter-accurate cutting+would mean reaching into the extractor's private per-chapter helpers, coupling+this module to their internals. Since a non-PDF material is read from extracted+text anyway (no faithful raw view), a section is nearly as good a handle as a+chapter, and the seam stays clean. Chapter cutting can be added later as one+more branch here without touching a single consumer.+"""++from __future__ import annotations++from dataclasses import dataclass, field+import logging+from pathlib import Path+import re++from deeptutor.reading.models import OutlineEntry, ReadingError, UnitKind++logger = logging.getLogger(__name__)++# Target size of a synthesised "section". Chosen to land near the character+# count of one dense printed page (~3k), so a section feels like a page to the+# reader and to the model's sense of "how much is this".+SECTION_TARGET_CHARS = 2800+# Never emit a section longer than this even if no paragraph break was found —+# a minified file or a single 200k-character line must still be addressable.+SECTION_HARD_CHARS = 4200++_SLIDE_SEPARATOR = re.compile(r"^--- Slide \d+ ---$", re.MULTILINE)+# Title candidates: a markdown heading, or the first non-trivial line.+_MD_HEADING = re.compile(r"^\s{0,3}#{1,6}\s+(?P<title>.+?)\s*#*\s*$")++# Formats whose original bytes the browser can render faithfully next to the+# extracted text. Only PDF today; adding one means teaching the reader pane to+# render it, not changing this engine.+RAW_VIEW_EXTENSIONS = frozenset({".pdf"})+++@dataclass(frozen=True, slots=True)+class Extraction:+ """The result of cutting one source file into units."""++ units: tuple[str, ...]+ unit: UnitKind+ extractor: str+ has_raw_view: bool = False+ title: str = ""+ # Only populated when the format carries its own structure (PDF bookmarks).+ # Otherwise the outline is synthesised later from unit first lines, so that+ # a material without bookmarks is still navigable by meaning.+ outline: tuple[OutlineEntry, ...] = field(default_factory=tuple)++ @property+ def char_count(self) -> int:+ return sum(len(u) for u in self.units)+++def extract_material(path: str | Path) -> Extraction:+ """Cut *path* into units, dispatching on its extension.++ Raises :class:`ReadingError` when the file cannot be read at all, or when+ it yields no text — an image-only scan, for instance, which the reader+ would otherwise present as an empty document with no explanation.+ """+ source = Path(path)+ if not source.is_file():+ raise ReadingError(f"{source.name}: file not found")++ suffix = source.suffix.lower()+ if suffix == ".pdf":+ extraction = _extract_pdf(source)+ elif suffix == ".pptx":+ extraction = _extract_slides(source)+ else:+ extraction = _extract_sections(source)++ if not any(unit.strip() for unit in extraction.units):+ raise ReadingError(+ f"{source.name}: no readable text could be extracted. "+ "A scanned document needs OCR before it can be read here."+ )+ return extraction+++# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+++def _extract_pdf(source: Path) -> Extraction:+ try:+ import pymupdf+ except ImportError as exc: # pragma: no cover - pymupdf is a core dep+ raise ReadingError("PDF reading needs PyMuPDF (pip install pymupdf)") from exc++ try:+ with pymupdf.open(source) as doc:+ if doc.is_encrypted and not doc.authenticate(""):+ raise ReadingError(f"{source.name} is encrypted and cannot be read")+ units = tuple((page.get_text() or "") for page in doc)+ outline = _pdf_outline(doc, page_count=len(units))+ title = str((doc.metadata or {}).get("title") or "").strip()+ except ReadingError:+ raise+ except Exception as exc:+ raise ReadingError(f"{source.name}: failed to read PDF ({exc})") from exc++ return Extraction(+ units=units,+ unit="page",+ extractor="pymupdf",+ has_raw_view=True,+ title=title,+ outline=outline,+ )+++def _pdf_outline(doc: object, *, page_count: int) -> tuple[OutlineEntry, ...]:+ """Map the PDF's bookmark tree to outline rows, dropping unusable ones.++ A bookmark pointing outside the page range (some generators emit 0 or a+ stale page) is skipped rather than clamped, so the model is never sent to a+ locator that does not correspond to the heading it asked for.+ """+ try:+ toc = doc.get_toc() # type: ignore[attr-defined]+ except Exception:+ logger.debug("PDF has no readable table of contents", exc_info=True)+ return ()++ entries: list[OutlineEntry] = []+ for row in toc or []:+ if not isinstance(row, (list, tuple)) or len(row) < 3:+ continue+ try:+ level, title, page = int(row[0]), str(row[1]).strip(), int(row[2])+ except (TypeError, ValueError):+ continue+ if not title or not (1 <= page <= page_count):+ continue+ entries.append(OutlineEntry(locator=page, title=title, level=max(1, level)))+ return tuple(entries)+++# ---------------------------------------------------------------------------+# Slides+# ---------------------------------------------------------------------------+++def _extract_slides(source: Path) -> Extraction:+ text = _shared_extract(source)+ parts = [part.strip() for part in _SLIDE_SEPARATOR.split(text)]+ units = tuple(part for part in parts if part)+ if not units:+ # The extractor found text but no slide separators (legacy .ppt via the+ # raw-OOXML fallback). Treat it as flat text rather than losing it.+ return _sections_from_text(text, extractor="pptx-text")+ return Extraction(units=units, unit="slide", extractor="pptx")+++# ---------------------------------------------------------------------------+# Flat text → sections+# ---------------------------------------------------------------------------+++def _extract_sections(source: Path) -> Extraction:+ return _sections_from_text(_shared_extract(source), extractor="text")+++def _sections_from_text(text: str, *, extractor: str) -> Extraction:+ return Extraction(units=split_into_sections(text), unit="section", extractor=extractor)+++def split_into_sections(text: str) -> tuple[str, ...]:+ """Cut flat text into sections, preferring paragraph boundaries.++ Greedy accumulation up to :data:`SECTION_TARGET_CHARS`, flushing at the+ paragraph that crosses it. A single paragraph longer than+ :data:`SECTION_HARD_CHARS` is hard-split so that pathological input (one+ enormous line) stays addressable.+ """+ normalised = text.replace("\r\n", "\n").replace("\r", "\n").strip()+ if not normalised:+ return ()++ sections: list[str] = []+ buffer: list[str] = []+ size = 0++ def flush() -> None:+ nonlocal size+ if buffer:+ joined = "\n\n".join(buffer).strip()+ if joined:+ sections.append(joined)+ buffer.clear()+ size = 0++ for paragraph in normalised.split("\n\n"):+ block = paragraph.strip()+ if not block:+ continue+ for piece in _hard_split(block, SECTION_HARD_CHARS):+ buffer.append(piece)+ size += len(piece)+ if size >= SECTION_TARGET_CHARS:+ flush()+ flush()+ return tuple(sections)+++def _hard_split(block: str, limit: int) -> list[str]:+ """Break an over-long paragraph at whitespace near *limit*, else mid-word."""+ if len(block) <= limit:+ return [block]+ pieces: list[str] = []+ remaining = block+ while len(remaining) > limit:+ window = remaining[:limit]+ cut = window.rfind(" ")+ if cut < limit // 2:+ cut = limit+ pieces.append(remaining[:cut].strip())+ remaining = remaining[cut:].strip()+ if remaining:+ pieces.append(remaining)+ return [piece for piece in pieces if piece]+++def _shared_extract(source: Path) -> str:+ """Read *source* through the shared text extractor.++ Reuses the same code path chat attachments use, so a format that works as+ an attachment works as reading material — and gaining a format there gains+ it here for free. ``max_chars=None`` because the reading store keeps the+ full text on disk; the per-turn budget is enforced later, per unit read.+ ``max_bytes`` stays at the validator ceiling rather than ``None`` so a+ pathological upload still fails fast instead of being read into memory.+ """+ from deeptutor.utils.document_extractor import (+ DocumentExtractionError,+ extract_text_from_path,+ )+ from deeptutor.utils.document_validator import DocumentValidator++ try:+ return extract_text_from_path(+ source, max_bytes=DocumentValidator.MAX_FILE_SIZE, max_chars=None+ )+ except DocumentExtractionError as exc:+ raise ReadingError(f"{source.name}: {exc}") from exc+ except OSError as exc:+ raise ReadingError(f"{source.name}: could not be read ({exc})") from exc+++def synthesise_outline(units: tuple[str, ...] | list[str]) -> tuple[OutlineEntry, ...]:+ """Build a fallback outline: one row per unit, labelled by its first line.++ Used for every material whose format carries no structure of its own. The+ label matters more than it looks: without it ``material_outline`` would+ return a bare count and the model would have to read units blindly to find+ anything.+ """+ entries: list[OutlineEntry] = []+ for index, unit in enumerate(units, start=1):+ entries.append(+ OutlineEntry(locator=index, title=first_line_label(unit), level=1, synthesised=True)+ )+ return tuple(entries)+++def first_line_label(unit: str, *, limit: int = 90) -> str:+ """A short human label for a unit: its heading, else its first real line."""+ for raw_line in unit.splitlines():+ line = raw_line.strip()+ if len(line) < 2:+ continue+ heading = _MD_HEADING.match(line)+ if heading:+ line = heading.group("title").strip()+ if not line:+ continue+ return line if len(line) <= limit else line[: limit - 1].rstrip() + "…"+ return ""+++__all__ = [+ "RAW_VIEW_EXTENSIONS",+ "SECTION_HARD_CHARS",+ "SECTION_TARGET_CHARS",+ "Extraction",+ "extract_material",+ "first_line_label",+ "split_into_sections",+ "synthesise_outline",+]diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.pynew file mode 100644index 000000000..ee0c1bd85--- /dev/null+++ b/deeptutor/reading/models.py@@ -0,0 +1,284 @@+"""Data model for immersive reading — materials, locators, annotations.++The central abstraction is the **locator**: a 1-indexed address into a material+that means "page" for a PDF, "chapter" for an EPUB, "slide" for a deck and+"section" for a flat text file. Every tool, API route and UI affordance speaks+locators, so nothing downstream branches on the source format; only+:mod:`deeptutor.reading.extract` knows how a format is cut into units, and the+manifest records which word to show the user (:attr:`MaterialManifest.unit`).++Rectangles on an annotation are stored **normalised** (0..1 of the unit's+width/height, origin top-left, y growing downwards). That is the browser's+coordinate space and also PyMuPDF's page space, so highlights survive zoom,+re-render and export without a second transform.+"""++from __future__ import annotations++from dataclasses import dataclass, field, replace+import time+from typing import Any, Literal++# What one locator addresses, per source format. Purely presentational for the+# model and the UI ("page 12" vs "chapter 3"); the addressing is identical.+UnitKind = Literal["page", "chapter", "slide", "section"]++AnnotationKind = Literal["highlight", "underline", "note"]++# Palette offered by the reader toolbar. Kept server-side too so an annotation+# arriving from an older client (or a tool call) can be validated rather than+# trusted, and so the PDF export can map a name to real ink.+ANNOTATION_COLORS: dict[str, tuple[float, float, float]] = {+ "yellow": (0.99, 0.87, 0.35),+ "green": (0.55, 0.86, 0.58),+ "blue": (0.48, 0.75, 0.98),+ "pink": (0.98, 0.63, 0.78),+ "purple": (0.78, 0.68, 0.98),+}++DEFAULT_ANNOTATION_COLOR = "yellow"+++class ReadingError(RuntimeError):+ """A reading operation failed in a way the user should see.++ Carries a user-facing message; the API layer maps it to a 4xx and the tool+ layer returns it as a failed :class:`~deeptutor.core.tool_protocol.ToolResult`+ so the model can recover instead of the turn dying.+ """+++class MaterialNotFound(ReadingError):+ """The requested material id does not exist in this user's store."""+++@dataclass(frozen=True, slots=True)+class Rect:+ """A normalised rectangle within one unit: 0..1, origin top-left."""++ x0: float+ y0: float+ x1: float+ y1: float++ def clamped(self) -> "Rect":+ """Order the corners and clip to the unit box.++ A selection dragged past the page edge, or bottom-up, still yields a+ usable rectangle instead of an inverted or out-of-bounds one.+ """++ def clip(value: float) -> float:+ return min(1.0, max(0.0, float(value)))++ x0, x1 = sorted((clip(self.x0), clip(self.x1)))+ y0, y1 = sorted((clip(self.y0), clip(self.y1)))+ return Rect(x0=x0, y0=y0, x1=x1, y1=y1)++ @property+ def is_degenerate(self) -> bool:+ """Whether the rectangle encloses no area (a zero-width caret)."""+ return (self.x1 - self.x0) <= 0 or (self.y1 - self.y0) <= 0++ def to_list(self) -> list[float]:+ return [self.x0, self.y0, self.x1, self.y1]++ @classmethod+ def from_any(cls, value: Any) -> "Rect | None":+ """Parse a rectangle from a list/tuple or a mapping, or return None.++ Tolerant by design: rectangles arrive from the browser, from stored+ JSON and (potentially) from a model tool call, and one malformed row+ must not discard an otherwise valid annotation.+ """+ if isinstance(value, Rect):+ return value.clamped()+ if isinstance(value, (list, tuple)) and len(value) == 4:+ try:+ return cls(*(float(v) for v in value)).clamped()+ except (TypeError, ValueError):+ return None+ if isinstance(value, dict):+ try:+ return cls(+ x0=float(value["x0"]),+ y0=float(value["y0"]),+ x1=float(value["x1"]),+ y1=float(value["y1"]),+ ).clamped()+ except (KeyError, TypeError, ValueError):+ return None+ return None+++@dataclass(frozen=True, slots=True)+class OutlineEntry:+ """One row of a material's outline.++ ``level`` is 1-based nesting depth. ``title`` is the document's own heading+ when the format carries one (PDF bookmarks, EPUB spine titles), otherwise a+ synthesised first-line label so the model can still navigate by meaning+ rather than by guessing locators.+ """++ locator: int+ title: str+ level: int = 1+ synthesised: bool = False++ def to_dict(self) -> dict[str, Any]:+ return {+ "locator": self.locator,+ "title": self.title,+ "level": self.level,+ "synthesised": self.synthesised,+ }+++@dataclass(frozen=True, slots=True)+class SearchHit:+ """One search match, addressed by locator with surrounding context."""++ locator: int+ snippet: str+ offset: int+ match: str++ def to_dict(self) -> dict[str, Any]:+ return {+ "locator": self.locator,+ "snippet": self.snippet,+ "offset": self.offset,+ "match": self.match,+ }+++@dataclass(frozen=True, slots=True)+class MaterialManifest:+ """Everything about a material except its text and its annotations."""++ material_id: str+ filename: str+ unit: UnitKind+ unit_count: int+ mime: str = ""+ title: str = ""+ source_hash: str = ""+ extractor: str = ""+ byte_size: int = 0+ char_count: int = 0+ created_at: float = field(default_factory=time.time)+ # Present only when the raw file can be rendered faithfully in the browser+ # (today: PDF). Other formats read from extracted text, so the reader shows+ # its text view and the export falls back to a Markdown excerpt.+ has_raw_view: bool = False++ def to_dict(self) -> dict[str, Any]:+ return {+ "material_id": self.material_id,+ "filename": self.filename,+ "unit": self.unit,+ "unit_count": self.unit_count,+ "mime": self.mime,+ "title": self.title,+ "source_hash": self.source_hash,+ "extractor": self.extractor,+ "byte_size": self.byte_size,+ "char_count": self.char_count,+ "created_at": self.created_at,+ "has_raw_view": self.has_raw_view,+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> "MaterialManifest":+ unit = str(data.get("unit") or "page")+ return cls(+ material_id=str(data.get("material_id") or ""),+ filename=str(data.get("filename") or ""),+ unit=unit if unit in ("page", "chapter", "slide", "section") else "page", # type: ignore[arg-type]+ unit_count=int(data.get("unit_count") or 0),+ mime=str(data.get("mime") or ""),+ title=str(data.get("title") or ""),+ source_hash=str(data.get("source_hash") or ""),+ extractor=str(data.get("extractor") or ""),+ byte_size=int(data.get("byte_size") or 0),+ char_count=int(data.get("char_count") or 0),+ created_at=float(data.get("created_at") or 0.0),+ has_raw_view=bool(data.get("has_raw_view")),+ )+++@dataclass(frozen=True, slots=True)+class Annotation:+ """One user (or model) mark on a material.++ ``quote`` is the text the mark covers — it is what makes an annotation+ portable: the Markdown export, the chat context and the "jump back to this+ mark" affordance all read the quote, not the geometry. ``rects`` is optional+ for exactly that reason; a note attached to a whole unit has none.+ """++ annotation_id: str+ locator: int+ kind: AnnotationKind = "highlight"+ color: str = DEFAULT_ANNOTATION_COLOR+ quote: str = ""+ note: str = ""+ rects: tuple[Rect, ...] = ()+ author: str = "user"+ created_at: float = field(default_factory=time.time)+ updated_at: float = field(default_factory=time.time)++ def touched(self, **changes: Any) -> "Annotation":+ return replace(self, updated_at=time.time(), **changes)++ def to_dict(self) -> dict[str, Any]:+ return {+ "annotation_id": self.annotation_id,+ "locator": self.locator,+ "kind": self.kind,+ "color": self.color,+ "quote": self.quote,+ "note": self.note,+ "rects": [r.to_list() for r in self.rects],+ "author": self.author,+ "created_at": self.created_at,+ "updated_at": self.updated_at,+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> "Annotation":+ kind = str(data.get("kind") or "highlight")+ color = str(data.get("color") or DEFAULT_ANNOTATION_COLOR)+ rects = tuple(+ rect+ for rect in (Rect.from_any(raw) for raw in (data.get("rects") or []))+ if rect is not None and not rect.is_degenerate+ )+ return cls(+ annotation_id=str(data.get("annotation_id") or ""),+ locator=max(1, int(data.get("locator") or 1)),+ kind=kind if kind in ("highlight", "underline", "note") else "highlight", # type: ignore[arg-type]+ color=color if color in ANNOTATION_COLORS else DEFAULT_ANNOTATION_COLOR,+ quote=str(data.get("quote") or ""),+ note=str(data.get("note") or ""),+ rects=rects,+ author=str(data.get("author") or "user"),+ created_at=float(data.get("created_at") or 0.0),+ updated_at=float(data.get("updated_at") or 0.0),+ )+++__all__ = [+ "ANNOTATION_COLORS",+ "DEFAULT_ANNOTATION_COLOR",+ "Annotation",+ "AnnotationKind",+ "MaterialManifest",+ "MaterialNotFound",+ "OutlineEntry",+ "ReadingError",+ "Rect",+ "SearchHit",+ "UnitKind",+]diff --git a/deeptutor/reading/search.py b/deeptutor/reading/search.pynew file mode 100644index 000000000..4d51447be--- /dev/null+++ b/deeptutor/reading/search.py@@ -0,0 +1,239 @@+"""Locator-addressed full-text search over one material.++This is what replaces retrieval inside immersive reading. A material lives in a+few hundred unit files at most, so a linear scan is milliseconds — and unlike a+vector search, **every hit already carries its locator**, which is the whole+point: the model can cite "page 12" because that is literally what it searched.++Matching is deliberately layered, cheapest first, and reports which layer fired+so the model can tell a verbatim hit from a loose one:++1. ``exact`` — the query as written, case-insensitive.+2. ``normalised`` — whitespace collapsed and punctuation-insensitive, so a+ quote copied out of a PDF still matches text that wrapped mid-phrase.+3. ``terms`` — units ranked by how many of the query's terms they contain.+ The fallback that keeps a natural-language question from returning nothing.++Pure functions over ``(locator, text)`` pairs: no store, no I/O, no config.+"""++from __future__ import annotations++from dataclasses import dataclass+import re+from typing import Iterable, Literal, Sequence++from deeptutor.reading.models import SearchHit++MatchMode = Literal["exact", "normalised", "terms"]++DEFAULT_LIMIT = 12+SNIPPET_RADIUS = 140++# Characters that differ between "the same" text in a PDF and in a chat message:+# any whitespace run, and the punctuation families that get transliterated+# (curly vs straight quotes, en/em dashes, CJK vs ASCII commas).+_WS_RUN = re.compile(r"\s+")+_SOFT_PUNCT = re.compile(r"[‘’“”–—\-_'\"`,,、;;::.。!!??()()\[\]【】]")+# ``\w`` is Unicode-aware for str patterns, so this keeps CJK together too.+_TERM_SPLIT = re.compile(r"\W+", re.UNICODE)+# Terms this short carry no signal in the ranking fallback (English stop-ish+# noise and single CJK particles), so they are dropped rather than diluting it.+_MIN_TERM_LEN = 2+_CJK = re.compile(r"[㐀-䶿一-鿿豈--ヿ]")+++@dataclass(frozen=True, slots=True)+class SearchResult:+ """Hits for one query, plus which matching layer produced them."""++ hits: tuple[SearchHit, ...]+ mode: MatchMode | None+ truncated: bool = False++ @property+ def is_empty(self) -> bool:+ return not self.hits++ def to_dict(self) -> dict[str, object]:+ return {+ "hits": [hit.to_dict() for hit in self.hits],+ "mode": self.mode,+ "truncated": self.truncated,+ }+++def normalise(text: str) -> str:+ """Collapse whitespace and soften punctuation for tolerant comparison."""+ return _WS_RUN.sub(" ", _SOFT_PUNCT.sub("", text or "")).strip().lower()+++def terms_of(query: str) -> tuple[str, ...]:+ """Split *query* into ranking terms, dropping noise-length fragments.++ CJK runs have no word separators, so ``\\W+`` alone would yield one giant+ term and the ranking layer would degenerate into exact matching. Runs of+ three or more CJK characters are therefore expanded into overlapping+ bigrams, which is what lets a Chinese query match partially.+ """+ raw = [term for term in _TERM_SPLIT.split((query or "").lower()) if term]+ expanded: list[str] = []+ for term in raw:+ if len(term) >= 3 and _CJK.search(term):+ expanded.extend(term[i : i + 2] for i in range(len(term) - 1))+ elif len(term) >= _MIN_TERM_LEN:+ expanded.append(term)+ # Preserve first-seen order while de-duplicating overlapping bigrams.+ return tuple(dict.fromkeys(expanded))+++def search_units(+ units: Iterable[tuple[int, str]],+ query: str,+ *,+ limit: int = DEFAULT_LIMIT,+) -> SearchResult:+ """Search *units* for *query*, escalating through the matching layers.++ ``units`` is consumed once, so a generator straight off the store is fine.+ """+ needle = (query or "").strip()+ if not needle:+ return SearchResult(hits=(), mode=None)++ materialised = [(locator, text or "") for locator, text in units]+ bounded = max(1, int(limit))++ for mode in ("exact", "normalised"):+ hits = _literal_hits(materialised, needle, mode=mode, limit=bounded + 1)+ if hits:+ return SearchResult(+ hits=tuple(hits[:bounded]),+ mode=mode, # type: ignore[arg-type]+ truncated=len(hits) > bounded,+ )++ ranked = _term_hits(materialised, needle, limit=bounded + 1)+ if not ranked:+ return SearchResult(hits=(), mode=None)+ return SearchResult(+ hits=tuple(ranked[:bounded]),+ mode="terms",+ truncated=len(ranked) > bounded,+ )+++def locate_quote(text: str, quote: str) -> int:+ """Character offset of *quote* in *text*, or -1.++ Used to verify a model-supplied quote actually appears on the unit it+ claims, before the reader is told to jump there. Falls back to the+ normalised comparison so a quote that lost a line-break still verifies —+ the offset then points at the normalised position, which is close enough+ for "is this real?" but is not used for geometry.+ """+ if not text or not quote:+ return -1+ direct = text.lower().find(quote.lower())+ if direct >= 0:+ return direct+ return normalise(text).find(normalise(quote))+++def _literal_hits(+ units: Sequence[tuple[int, str]],+ needle: str,+ *,+ mode: str,+ limit: int,+) -> list[SearchHit]:+ hits: list[SearchHit] = []+ target = needle.lower() if mode == "exact" else normalise(needle)+ if not target:+ return hits+ for locator, text in units:+ haystack = text.lower() if mode == "exact" else normalise(text)+ position = haystack.find(target)+ if position < 0:+ continue+ # Snippet always comes from the ORIGINAL text: a normalised offset does+ # not index the original, so for that layer we anchor on the first term+ # instead of trusting the position.+ anchor = position if mode == "exact" else _first_term_offset(text, needle)+ hits.append(+ SearchHit(+ locator=locator,+ snippet=_snippet(text, anchor, len(needle)),+ offset=max(0, anchor),+ match=needle,+ )+ )+ if len(hits) >= limit:+ break+ return hits+++def _term_hits(+ units: Sequence[tuple[int, str]],+ needle: str,+ *,+ limit: int,+) -> list[SearchHit]:+ query_terms = terms_of(needle)+ if not query_terms:+ return []+ scored: list[tuple[int, int, SearchHit]] = []+ for locator, text in units:+ lowered = text.lower()+ present = [term for term in query_terms if term in lowered]+ if not present:+ continue+ anchor = min(lowered.find(term) for term in present)+ scored.append(+ (+ len(present),+ -locator,+ SearchHit(+ locator=locator,+ snippet=_snippet(text, anchor, len(present[0])),+ offset=max(0, anchor),+ match=" ".join(present),+ ),+ )+ )+ # Most terms matched wins; ties resolve to the earlier locator so results+ # read in document order rather than arbitrarily.+ scored.sort(key=lambda row: (-row[0], -row[1]))+ return [hit for _, _, hit in scored[:limit]]+++def _first_term_offset(text: str, needle: str) -> int:+ lowered = text.lower()+ for term in terms_of(needle):+ found = lowered.find(term)+ if found >= 0:+ return found+ return 0+++def _snippet(text: str, offset: int, match_len: int) -> str:+ """A one-line window around *offset*, with ellipses when clipped."""+ if not text:+ return ""+ start = max(0, offset - SNIPPET_RADIUS)+ end = min(len(text), offset + max(1, match_len) + SNIPPET_RADIUS)+ window = _WS_RUN.sub(" ", text[start:end]).strip()+ prefix = "…" if start > 0 else ""+ suffix = "…" if end < len(text) else ""+ return f"{prefix}{window}{suffix}"+++__all__ = [+ "DEFAULT_LIMIT",+ "MatchMode",+ "SearchResult",+ "locate_quote",+ "normalise",+ "search_units",+ "terms_of",+]diff --git a/deeptutor/reading/service.py b/deeptutor/reading/service.pynew file mode 100644index 000000000..ab137bc42--- /dev/null+++ b/deeptutor/reading/service.py@@ -0,0 +1,240 @@+"""Composition layer over the reading engine.++Everything a caller wants to *do* with a material lives here, so the two+callers — the capability's tools and the REST router — share one implementation+and stay dumb adapters. Nothing in this module knows about tools, HTTP, the+chat loop or the LLM; it takes a :class:`~deeptutor.reading.store.ReadingStore`+and returns plain data.++The locator grammar (``"12"``, ``"12-14"``, ``"3,12,17"``) is parsed here too:+it is the syntax the model types, so it needs one tolerant parser with one set+of rules rather than a regex per call site.+"""++from __future__ import annotations++from dataclasses import dataclass+import re+from typing import Sequence++from deeptutor.reading.models import MaterialManifest, OutlineEntry, ReadingError+from deeptutor.reading.search import SearchResult, locate_quote, search_units+from deeptutor.reading.store import MAX_READ_CHARS, ReadingStore++# How many locators one read may request. Guards the context budget before any+# file is opened; the character ceiling in the store guards it afterwards.+MAX_LOCATORS_PER_READ = 24+# Outline rows rendered for the model in one go. A 900-page book's full outline+# would itself blow the prompt, so long outlines are summarised by level.+MAX_OUTLINE_ROWS = 120++_RANGE = re.compile(r"^\s*(\d+)\s*(?:[-–—:]\s*(\d+))?\s*$")+++@dataclass(frozen=True, slots=True)+class RenderedUnits:+ """Unit text prepared for a model, with an explicit truncation signal."""++ text: str+ locators: tuple[int, ...]+ truncated: bool+ unit: str++ @property+ def is_empty(self) -> bool:+ return not self.text.strip()+++@dataclass(frozen=True, slots=True)+class QuoteCheck:+ """Whether a claimed quote really appears where it was claimed."""++ verified: bool+ locator: int+ quote: str+ found_locator: int | None = None++ @property+ def moved(self) -> bool:+ """True when the quote exists, but on a different locator."""+ return self.found_locator is not None and self.found_locator != self.locator+++def parse_locators(spec: str | int | Sequence[int], unit_count: int) -> list[int]:+ """Parse a locator spec into an ascending, de-duplicated, in-range list.++ Accepts an int, a sequence of ints, or a string of comma-separated numbers+ and ranges. Out-of-range values are dropped rather than clamped — silently+ turning "page 900" into "page 12" would make the model cite text the user+ never asked about. Raises when the spec parses to nothing at all, so the+ tool can tell the model what it did wrong.+ """+ if unit_count <= 0:+ raise ReadingError("this material has no readable units")++ raw: list[int] = []+ if isinstance(spec, int):+ raw = [spec]+ elif isinstance(spec, str):+ for chunk in spec.replace(",", ",").split(","):+ if not chunk.strip():+ continue+ match = _RANGE.match(chunk)+ if not match:+ continue+ start = int(match.group(1))+ end = int(match.group(2)) if match.group(2) else start+ if end < start:+ start, end = end, start+ # Bound the expansion before allocating: "1-100000" must not+ # materialise a hundred thousand integers to then discard them.+ raw.extend(range(start, min(end, start + MAX_LOCATORS_PER_READ) + 1))+ else:+ for value in spec or []:+ try:+ raw.append(int(value))+ except (TypeError, ValueError):+ continue++ in_range = sorted({value for value in raw if 1 <= value <= unit_count})+ if not in_range:+ raise ReadingError(f"no valid locator in {spec!r} — this material has 1..{unit_count}.")+ return in_range[:MAX_LOCATORS_PER_READ]+++def render_units(+ store: ReadingStore,+ material_id: str,+ spec: str | int | Sequence[int],+ *,+ max_chars: int = MAX_READ_CHARS,+) -> RenderedUnits:+ """Read the requested units and render them with locator headers.++ The header format matches what the shared text extractor already emits+ (``--- Page 12 ---``), so a model that has seen a DeepTutor attachment+ recognises the shape without being taught twice.+ """+ manifest = store.manifest(material_id)+ locators = parse_locators(spec, manifest.unit_count)+ rows, truncated = store.read_units(material_id, locators, max_chars=max_chars)++ label = manifest.unit.capitalize()+ blocks: list[str] = []+ for locator, text in rows:+ body = text.strip()+ blocks.append(+ f"--- {label} {locator} ---\n{body}" if body else f"--- {label} {locator} ---\n(empty)"+ )+ rendered = "\n\n".join(blocks)+ if truncated:+ rendered += (+ f"\n\n[truncated — the requested range exceeds the {max_chars}-character "+ f"read limit. Read fewer {manifest.unit}s at a time.]"+ )+ return RenderedUnits(+ text=rendered,+ locators=tuple(locator for locator, _ in rows),+ truncated=truncated,+ unit=manifest.unit,+ )+++def search_material(+ store: ReadingStore,+ material_id: str,+ query: str,+ *,+ limit: int = 12,+) -> SearchResult:+ """Search one material, streaming its units through the matcher."""+ store.manifest(material_id)+ return search_units(store.iter_units(material_id), query, limit=limit)+++def verify_quote(store: ReadingStore, material_id: str, locator: int, quote: str) -> QuoteCheck:+ """Check that *quote* appears on *locator*, and find it if it does not.++ This is the guard in front of ``reader_goto``: a hallucinated quote would+ otherwise yank the user's viewport to an arbitrary page. When the quote+ turns out to live elsewhere, the real locator is reported so the caller can+ correct the jump instead of cancelling it.+ """+ manifest = store.manifest(material_id)+ text = (quote or "").strip()+ if not text:+ return QuoteCheck(verified=False, locator=locator, quote="")+ if 1 <= locator <= manifest.unit_count:+ if locate_quote(store.unit_text(material_id, locator), text) >= 0:+ return QuoteCheck(verified=True, locator=locator, quote=text, found_locator=locator)+ found = search_units(store.iter_units(material_id), text, limit=1)+ if found.hits and found.mode in ("exact", "normalised"):+ hit = found.hits[0]+ return QuoteCheck(verified=True, locator=locator, quote=text, found_locator=hit.locator)+ return QuoteCheck(verified=False, locator=locator, quote=text)+++def render_outline(store: ReadingStore, material_id: str) -> str:+ """A compact outline for the model: one line per row, locator first."""+ manifest = store.manifest(material_id)+ entries = store.outline(material_id)+ label = manifest.unit+ header = (+ f"{manifest.filename} — {manifest.unit_count} {label}s"+ f"{f', titled “{manifest.title}”' if manifest.title else ''}"+ )+ if not entries:+ return f"{header}\n(no outline available; read {label}s directly)"++ trimmed, omitted = _trim_outline(entries)+ lines = [header, ""]+ for entry in trimmed:+ indent = " " * max(0, entry.level - 1)+ title = entry.title or "(untitled)"+ lines.append(f"{indent}{label} {entry.locator}: {title}")+ if omitted:+ lines.append(f"… {omitted} more rows omitted; ask for a range to see them.")+ return "\n".join(lines)+++def _trim_outline(entries: Sequence[OutlineEntry]) -> tuple[list[OutlineEntry], int]:+ """Bound an outline, preferring shallow rows when it must be cut.++ Dropping the deepest levels first keeps the document's shape legible; the+ alternative (a hard head-slice) would strand the model in chapter one.+ """+ if len(entries) <= MAX_OUTLINE_ROWS:+ return list(entries), 0+ for max_level in range(1, 7):+ kept = [entry for entry in entries if entry.level <= max_level]+ if len(kept) > MAX_OUTLINE_ROWS:+ shallower = [entry for entry in entries if entry.level < max_level]+ if shallower:+ return shallower[:MAX_OUTLINE_ROWS], len(entries) - len(+ shallower[:MAX_OUTLINE_ROWS]+ )+ break+ return list(entries[:MAX_OUTLINE_ROWS]), len(entries) - MAX_OUTLINE_ROWS+++def material_summary(manifest: MaterialManifest) -> str:+ """One line describing a material, for prompts and pickers."""+ size_kb = max(1, manifest.byte_size // 1024)+ return (+ f"{manifest.filename} ({manifest.unit_count} {manifest.unit}s, "+ f"{manifest.char_count} chars, {size_kb} KB)"+ )+++__all__ = [+ "MAX_LOCATORS_PER_READ",+ "MAX_OUTLINE_ROWS",+ "QuoteCheck",+ "RenderedUnits",+ "material_summary",+ "parse_locators",+ "render_outline",+ "render_units",+ "search_material",+ "verify_quote",+]diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.pynew file mode 100644index 000000000..6c0e2f0ff--- /dev/null+++ b/deeptutor/reading/store.py@@ -0,0 +1,471 @@+"""On-disk store for reading materials and their annotations.++Layout, one directory per material::++ <root>/<material_id>/+ manifest.json # MaterialManifest+ outline.json # OutlineEntry rows (document's own, or synthesised)+ units/0001.txt # one file per locator+ raw/<filename> # the original bytes, for the faithful viewer+ annotations.json # Annotation rows++One file per unit is the point of the layout: ``read_material(locator=12)``+opens one small file instead of deserialising the whole document, so a 600-page+PDF costs the same per read as a 3-page one.++``material_id`` is the content hash, which makes re-uploading the same file a+no-op that lands the user back on their existing annotations instead of a fresh+empty copy.++Writes go through :func:`_atomic_write` (temp file in the same directory, then+``os.replace``) under a per-material re-entrant lock, so a concurrent annotation+save and export can never observe a half-written JSON file — the failure mode+that produced the corrupted-notebook reports.+"""++from __future__ import annotations++from contextlib import contextmanager+from dataclasses import replace as dataclass_replace+import hashlib+import json+import logging+import os+from pathlib import Path+import re+import shutil+import threading+import time+from typing import Any, Iterator, Sequence+import uuid++from deeptutor.reading.extract import extract_material, synthesise_outline+from deeptutor.reading.models import (+ Annotation,+ MaterialManifest,+ MaterialNotFound,+ OutlineEntry,+ ReadingError,+)++logger = logging.getLogger(__name__)++MANIFEST_NAME = "manifest.json"+OUTLINE_NAME = "outline.json"+ANNOTATIONS_NAME = "annotations.json"+UNITS_DIR = "units"+RAW_DIR = "raw"++# Material ids are content hashes, so this is both an id validator and the+# traversal guard for every path built from a caller-supplied id.+_MATERIAL_ID_RE = re.compile(r"^[0-9a-f]{8,64}$")+_ID_LENGTH = 16++# Hard ceiling on how much unit text one tool call may return, so a model asking+# for "1-400" cannot blow the turn's context budget. The tool reports the+# truncation rather than silently trimming.+MAX_READ_CHARS = 60_000+++def _atomic_write(path: Path, payload: str) -> None:+ """Write *payload* to *path* atomically within the same directory."""+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.parent / f".{path.name}.{uuid.uuid4().hex[:8]}.tmp"+ try:+ tmp.write_text(payload, encoding="utf-8")+ os.replace(tmp, path)+ finally:+ tmp.unlink(missing_ok=True)+++def _read_json(path: Path) -> Any:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, json.JSONDecodeError):+ logger.warning("Unreadable reading-store file: %s", path, exc_info=True)+ return None+++def content_hash(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()[:_ID_LENGTH]+++class ReadingStore:+ """Materials and annotations for one user's workspace."""++ def __init__(self, root: Path | str | None = None) -> None:+ self._root_override = Path(root) if root is not None else None+ self._locks_guard = threading.Lock()+ self._locks: dict[str, threading.RLock] = {}++ # -- paths ------------------------------------------------------------++ @property+ def root(self) -> Path:+ """The materials root, resolved lazily.++ Lazy so tests (and the pure-engine tests especially) can construct a+ store against a temp dir without booting the path service, and so a+ per-user path service installed after construction is still honoured.+ """+ if self._root_override is not None:+ return self._root_override+ from deeptutor.services.path_service import PathService++ return PathService.get_instance().get_workspace_feature_dir("reading")++ def _dir(self, material_id: str) -> Path:+ return self.root / self._validate_id(material_id)++ @staticmethod+ def _validate_id(material_id: str) -> str:+ candidate = str(material_id or "").strip().lower()+ if not _MATERIAL_ID_RE.match(candidate):+ raise ReadingError(f"invalid material id: {material_id!r}")+ return candidate++ @staticmethod+ def _unit_file(material_dir: Path, locator: int) -> Path:+ return material_dir / UNITS_DIR / f"{locator:04d}.txt"++ @contextmanager+ def _locked(self, material_id: str) -> Iterator[None]:+ with self._locks_guard:+ lock = self._locks.get(material_id)+ if lock is None:+ lock = threading.RLock()+ self._locks[material_id] = lock+ with lock:+ yield++ # -- ingest -----------------------------------------------------------++ def ingest(self, source: Path | str, *, filename: str | None = None) -> MaterialManifest:+ """Extract *source* into the store and return its manifest.++ Idempotent on content: a file whose hash is already present is not+ re-extracted, and its annotations are left untouched.+ """+ path = Path(source)+ try:+ data = path.read_bytes()+ except OSError as exc:+ raise ReadingError(f"{path.name}: could not be read ({exc})") from exc+ if not data:+ raise ReadingError(f"{path.name} is empty")++ material_id = content_hash(data)+ display_name = (filename or path.name).strip() or path.name++ with self._locked(material_id):+ existing = self._load_manifest(material_id)+ if existing is not None and self._is_complete(material_id, existing):+ return existing++ extraction = extract_material(path)+ material_dir = self._dir(material_id)+ units_dir = material_dir / UNITS_DIR+ # A previous partial ingest (crash between unit writes) must not+ # leave stale units behind that would read as real content.+ if units_dir.exists():+ shutil.rmtree(units_dir, ignore_errors=True)+ units_dir.mkdir(parents=True, exist_ok=True)++ for index, unit in enumerate(extraction.units, start=1):+ self._unit_file(material_dir, index).write_text(unit, encoding="utf-8")++ raw_path: Path | None = None+ if extraction.has_raw_view:+ raw_dir = material_dir / RAW_DIR+ raw_dir.mkdir(parents=True, exist_ok=True)+ raw_path = raw_dir / _safe_filename(display_name, fallback=path.name)+ raw_path.write_bytes(data)++ outline = extraction.outline or synthesise_outline(extraction.units)+ _atomic_write(+ material_dir / OUTLINE_NAME,+ json.dumps([entry.to_dict() for entry in outline], ensure_ascii=False),+ )++ manifest = MaterialManifest(+ material_id=material_id,+ filename=display_name,+ unit=extraction.unit,+ unit_count=len(extraction.units),+ mime=_guess_mime(display_name),+ title=extraction.title or Path(display_name).stem,+ source_hash=material_id,+ extractor=extraction.extractor,+ byte_size=len(data),+ char_count=extraction.char_count,+ created_at=time.time(),+ has_raw_view=raw_path is not None,+ )+ # Manifest last: its presence is the "this material is usable"+ # signal, so it must not appear before the units it describes.+ _atomic_write(+ material_dir / MANIFEST_NAME,+ json.dumps(manifest.to_dict(), ensure_ascii=False, indent=2),+ )+ return manifest++ def _is_complete(self, material_id: str, manifest: MaterialManifest) -> bool:+ """Whether a previously ingested material is still fully on disk."""+ material_dir = self._dir(material_id)+ if manifest.unit_count <= 0:+ return False+ if not self._unit_file(material_dir, manifest.unit_count).exists():+ return False+ if manifest.has_raw_view and self._find_raw(material_dir) is None:+ return False+ return True++ # -- read -------------------------------------------------------------++ def _load_manifest(self, material_id: str) -> MaterialManifest | None:+ data = _read_json(self._dir(material_id) / MANIFEST_NAME)+ if not isinstance(data, dict):+ return None+ manifest = MaterialManifest.from_dict(data)+ return manifest if manifest.material_id else None++ def manifest(self, material_id: str) -> MaterialManifest:+ manifest = self._load_manifest(material_id)+ if manifest is None:+ raise MaterialNotFound(f"material {material_id!r} not found")+ return manifest++ def exists(self, material_id: str) -> bool:+ try:+ return self._load_manifest(material_id) is not None+ except ReadingError:+ return False++ def list_materials(self) -> list[MaterialManifest]:+ """All usable materials, newest first. Unreadable dirs are skipped."""+ root = self.root+ if not root.is_dir():+ return []+ found: list[MaterialManifest] = []+ for child in root.iterdir():+ if not child.is_dir() or not _MATERIAL_ID_RE.match(child.name):+ continue+ manifest = self._load_manifest(child.name)+ if manifest is not None:+ found.append(manifest)+ return sorted(found, key=lambda m: m.created_at, reverse=True)++ def unit_text(self, material_id: str, locator: int) -> str:+ """Text of one unit. Raises when the locator is out of range."""+ manifest = self.manifest(material_id)+ if not 1 <= locator <= manifest.unit_count:+ raise ReadingError(+ f"{manifest.unit} {locator} is out of range — "+ f"this material has {manifest.unit_count}."+ )+ path = self._unit_file(self._dir(material_id), locator)+ try:+ return path.read_text(encoding="utf-8")+ except FileNotFoundError:+ return ""+ except OSError as exc:+ raise ReadingError(f"could not read {manifest.unit} {locator} ({exc})") from exc++ def read_units(+ self,+ material_id: str,+ locators: Sequence[int],+ *,+ max_chars: int = MAX_READ_CHARS,+ ) -> tuple[list[tuple[int, str]], bool]:+ """Read several units in ascending order, bounded by *max_chars*.++ Returns ``(rows, truncated)``. Bounding here rather than at the tool+ keeps every caller (tool, API, export) honest about the same ceiling,+ and ``truncated`` lets the caller say so out loud instead of silently+ dropping evidence.+ """+ manifest = self.manifest(material_id)+ wanted = sorted({int(loc) for loc in locators if 1 <= int(loc) <= manifest.unit_count})+ rows: list[tuple[int, str]] = []+ budget = max(0, int(max_chars))+ truncated = False+ for locator in wanted:+ text = self.unit_text(material_id, locator)+ if len(text) > budget:+ if budget > 0:+ rows.append((locator, text[:budget]))+ truncated = True+ break+ rows.append((locator, text))+ budget -= len(text)+ if len(wanted) < len({int(loc) for loc in locators}):+ truncated = True+ return rows, truncated++ def outline(self, material_id: str) -> list[OutlineEntry]:+ """The material's outline, rebuilt from units if the file is missing."""+ manifest = self.manifest(material_id)+ rows = _read_json(self._dir(material_id) / OUTLINE_NAME)+ if isinstance(rows, list) and rows:+ entries: list[OutlineEntry] = []+ for row in rows:+ if not isinstance(row, dict):+ continue+ try:+ entries.append(+ OutlineEntry(+ locator=int(row["locator"]),+ title=str(row.get("title") or ""),+ level=max(1, int(row.get("level") or 1)),+ synthesised=bool(row.get("synthesised")),+ )+ )+ except (KeyError, TypeError, ValueError):+ continue+ if entries:+ return entries+ units = tuple(+ self.unit_text(material_id, locator) for locator in range(1, manifest.unit_count + 1)+ )+ return list(synthesise_outline(units))++ def iter_units(self, material_id: str) -> Iterator[tuple[int, str]]:+ """Stream every unit in order — for search and export."""+ manifest = self.manifest(material_id)+ for locator in range(1, manifest.unit_count + 1):+ yield locator, self.unit_text(material_id, locator)++ def raw_path(self, material_id: str) -> Path | None:+ """The stored original file, or None for text-only materials."""+ manifest = self.manifest(material_id)+ if not manifest.has_raw_view:+ return None+ return self._find_raw(self._dir(material_id))++ @staticmethod+ def _find_raw(material_dir: Path) -> Path | None:+ raw_dir = material_dir / RAW_DIR+ if not raw_dir.is_dir():+ return None+ for candidate in sorted(raw_dir.iterdir()):+ if candidate.is_file():+ return candidate+ return None++ def delete(self, material_id: str) -> bool:+ material_dir = self._dir(material_id)+ if not material_dir.is_dir():+ return False+ with self._locked(material_id):+ shutil.rmtree(material_dir, ignore_errors=True)+ return not material_dir.exists()++ # -- annotations ------------------------------------------------------++ def annotations(self, material_id: str) -> list[Annotation]:+ """All annotations, ordered by locator then creation time."""+ self.manifest(material_id)+ rows = _read_json(self._dir(material_id) / ANNOTATIONS_NAME)+ if not isinstance(rows, list):+ return []+ parsed = [+ Annotation.from_dict(row)+ for row in rows+ if isinstance(row, dict) and row.get("annotation_id")+ ]+ return sorted(parsed, key=lambda a: (a.locator, a.created_at))++ def _write_annotations(self, material_id: str, rows: Sequence[Annotation]) -> None:+ _atomic_write(+ self._dir(material_id) / ANNOTATIONS_NAME,+ json.dumps([row.to_dict() for row in rows], ensure_ascii=False, indent=2),+ )++ def save_annotation(self, material_id: str, annotation: Annotation) -> Annotation:+ """Insert or update one annotation and return the stored row.++ Read-modify-write under the material lock, so two rapid highlights from+ the same reader cannot clobber each other.+ """+ manifest = self.manifest(material_id)+ if not 1 <= annotation.locator <= manifest.unit_count:+ raise ReadingError(+ f"{manifest.unit} {annotation.locator} is out of range — "+ f"this material has {manifest.unit_count}."+ )+ with self._locked(material_id):+ existing = self.annotations(material_id)+ stored = annotation+ if not stored.annotation_id:+ stored = dataclass_replace(stored, annotation_id=uuid.uuid4().hex[:12])+ now = time.time()+ index = next(+ (i for i, row in enumerate(existing) if row.annotation_id == stored.annotation_id),+ None,+ )+ if index is None:+ stored = dataclass_replace(+ stored,+ created_at=stored.created_at or now,+ updated_at=now,+ )+ existing.append(stored)+ else:+ stored = dataclass_replace(+ stored,+ created_at=existing[index].created_at or now,+ updated_at=now,+ )+ existing[index] = stored+ self._write_annotations(material_id, existing)+ return stored++ def delete_annotation(self, material_id: str, annotation_id: str) -> bool:+ self.manifest(material_id)+ target = str(annotation_id or "").strip()+ if not target:+ return False+ with self._locked(material_id):+ existing = self.annotations(material_id)+ remaining = [row for row in existing if row.annotation_id != target]+ if len(remaining) == len(existing):+ return False+ self._write_annotations(material_id, remaining)+ return True+++def _safe_filename(name: str, *, fallback: str) -> str:+ """A filesystem-safe basename for the stored original.++ The display name is echoed back in downloads, so it is sanitised rather+ than trusted: no directory parts, no traversal, bounded length.+ """+ base = Path(str(name or "")).name.strip()+ base = re.sub(r"[\x00-\x1f]", "", base)+ base = base.replace(os.sep, "_")+ if os.altsep:+ base = base.replace(os.altsep, "_")+ base = base.strip(". ") or Path(fallback).name or "material"+ return base[:180]+++def _guess_mime(filename: str) -> str:+ import mimetypes++ mime, _ = mimetypes.guess_type(filename)+ return mime or "application/octet-stream"+++__all__ = [+ "ANNOTATIONS_NAME",+ "MANIFEST_NAME",+ "MAX_READ_CHARS",+ "OUTLINE_NAME",+ "RAW_DIR",+ "UNITS_DIR",+ "ReadingStore",+ "content_hash",+]diff --git a/deeptutor/runtime/bootstrap/builtin_capabilities.py b/deeptutor/runtime/bootstrap/builtin_capabilities.pyindex 462d3188b..f9a252029 100644--- a/deeptutor/runtime/bootstrap/builtin_capabilities.py+++ b/deeptutor/runtime/bootstrap/builtin_capabilities.py@@ -8,4 +8,5 @@ BUILTIN_CAPABILITY_CLASSES: dict[str, str] = {"math_animator": "deeptutor.agents.math_animator.capability:MathAnimatorCapability","visualize": "deeptutor.agents.visualize.capability:VisualizeCapability","mastery_path": "deeptutor.capabilities.mastery.capability:MasteryPathCapability",+ "immersive_reading": "deeptutor.capabilities.reading.mode:ImmersiveReadingCapability",}diff --git a/deeptutor/services/config/settings_spec.py b/deeptutor/services/config/settings_spec.pynew file mode 100644index 000000000..e8894b3f5--- /dev/null+++ b/deeptutor/services/config/settings_spec.py@@ -0,0 +1,697 @@+"""Machine-readable description of what a DeepTutor install can be told to be.++Every knob the setup capability is allowed to change is one :class:`SettingSpec`+row here, and each row carries its own ``read`` / ``choices`` / ``write`` /+``probe``. That keeps the agent-facing tools+(:mod:`deeptutor.capabilities.setup.tools`) completely generic: they walk this+table instead of branching per setting, so a new knob becomes reachable by+adding a row — never by editing a tool, a prompt, or the API.++Rows derive their options from the modules that already own them (the parsing+engine registry, the model catalog, the search provider table), so this file+adds a *description* of the writable surface without becoming a second source+of truth for what a valid value is.++Three fields exist because changing a setting is not free:++``scope``+ ``personal`` rows live in the caller's own ``settings/interface.json``;+ ``global`` rows live in the shared deployment settings and are+ administrator-only. This mirrors where the files already are — a personal+ row is one that :class:`~deeptutor.services.path_service.PathService`+ already resolves per user, a global row is one read through+ :func:`~deeptutor.services.config.loader.get_runtime_settings_dir`.++``effect``+ What the user must still do for the change to take hold: ``instant``+ (nothing), ``restart`` (the value is only injected into subprocess env at+ launch), or ``reindex`` (derived data — embeddings — no longer matches the+ new setting). The setup agent is required to report this; keeping it as+ data rather than prompt etiquette is what makes that reliable.++``probe``+ An optional pre-commit connectivity check run against a *candidate*+ catalog that was never written to disk. Rows that can silently break the+ assistant's own next turn define one, and+ :func:`~deeptutor.capabilities.setup.apply.apply_setting` refuses to commit+ a value whose probe fails. Without it an agent could switch the chat model+ to something unreachable and take away its own power supply, leaving the+ user stranded mid-conversation with no way to ask for a fix.++Secrets are deliberately unrepresentable here: no row accepts an API key.+Credentials reach the server through the frontend's own card (see+``request_credential`` in the setup capability) so they never enter the model's+context, the conversation history, or the session transcript on disk.++Imports of the rest of DeepTutor are deferred into the row callables on+purpose: this module is imported from ``deeptutor.capabilities``, and a+top-level import of the model catalog or the parsing engines would close an+import cycle through ``services.config.__init__``.+"""++from __future__ import annotations++from collections.abc import Awaitable, Callable+from dataclasses import dataclass, field+from typing import Any, Literal++Scope = Literal["personal", "global"]+Effect = Literal["instant", "restart", "reindex"]++# Areas group rows for ``inspect_setup`` so the agent can ask about one part of+# the install ("what's my parsing set up like?") without reading everything.+Area = Literal["interface", "models", "parsing"]+++@dataclass(frozen=True, slots=True)+class SettingChoice:+ """One selectable value, shaped so it can be rendered as an ask_user option.++ ``label`` / ``description`` map onto the ``{label, description}`` pair the+ ``ask_user`` card already renders, so a proposal never needs to reformat.+ ``available`` is False for a choice that is legal but not usable yet — a+ parsing engine whose package is not installed — which the setup agent turns+ into an install offer rather than hiding.+ """++ value: str+ label: str+ description: str = ""+ available: bool = True+ current: bool = False+++@dataclass(frozen=True, slots=True)+class ProbeResult:+ """Outcome of a pre-commit connectivity check."""++ ok: bool+ detail: str = ""+ elapsed_ms: int = 0+++@dataclass(frozen=True, slots=True)+class SettingSpec:+ """One writable knob, self-contained enough that tools stay generic."""++ key: str+ area: Area+ scope: Scope+ effect: Effect+ label: str+ summary: str+ read: Callable[[], str]+ choices: Callable[[], tuple[SettingChoice, ...]]+ write: Callable[[str], None]+ # Optional extra validation beyond "the value is one of ``choices``".+ # Returns an error message, or None when the value is acceptable.+ validate: Callable[[str], str | None] | None = None+ # Pre-commit connectivity check against a candidate that is not on disk.+ probe: Callable[[str], Awaitable[ProbeResult]] | None = None+ # Human-readable consequence, surfaced verbatim by the agent alongside the+ # ``effect`` code so the user learns what they still have to do.+ effect_detail: str = ""+ metadata: dict[str, Any] = field(default_factory=dict)++ def current_choice(self) -> SettingChoice | None:+ current = self.read()+ for choice in self.choices():+ if choice.value == current:+ return choice+ return None+++# --------------------------------------------------------------------------+# interface.json rows (personal scope)+# --------------------------------------------------------------------------++_LANGUAGE_CHOICES: tuple[tuple[str, str, str], ...] = (+ ("en", "English", "Interface and replies in English."),+ ("zh", "简体中文", "Interface and replies in Simplified Chinese."),+)++_THEME_CHOICES: tuple[tuple[str, str, str], ...] = (+ ("snow", "Default", "Pure-white neutral theme."),+ ("light", "Light", "Warm light theme."),+ ("dark", "Dark", "Dark theme."),+ ("glass", "Glass", "Translucent theme with blur."),+)+++def _read_ui(key: str, default: str) -> Callable[[], str]:+ def _read() -> str:+ from deeptutor.services.settings.interface_settings import get_ui_settings++ value = get_ui_settings().get(key, default)+ return str(value or default)++ return _read+++def _write_ui(key: str) -> Callable[[str], None]:+ def _write(value: str) -> None:+ from deeptutor.services.settings.interface_settings import set_ui_setting++ set_ui_setting(key, value)++ return _write+++def _static_choices(+ rows: tuple[tuple[str, str, str], ...],+ current: Callable[[], str],+) -> Callable[[], tuple[SettingChoice, ...]]:+ def _choices() -> tuple[SettingChoice, ...]:+ active = current()+ return tuple(+ SettingChoice(value=value, label=label, description=desc, current=value == active)+ for value, label, desc in rows+ )++ return _choices+++def _interface_specs() -> list[SettingSpec]:+ language_read = _read_ui("language", "en")+ response_read = _read_ui("response_language", "en")+ theme_read = _read_ui("theme", "snow")+ return [+ SettingSpec(+ key="interface.language",+ area="interface",+ scope="personal",+ effect="instant",+ label="Interface language",+ summary="Language of the DeepTutor UI (menus, buttons, settings).",+ read=language_read,+ choices=_static_choices(_LANGUAGE_CHOICES, language_read),+ write=_write_ui("language"),+ ),+ SettingSpec(+ key="interface.response_language",+ area="interface",+ scope="personal",+ effect="instant",+ label="Reply language",+ summary="Language the assistant writes its answers in.",+ read=response_read,+ choices=_static_choices(_LANGUAGE_CHOICES, response_read),+ write=_write_ui("response_language"),+ effect_detail="Applies from the next turn onwards.",+ ),+ SettingSpec(+ key="interface.theme",+ area="interface",+ scope="personal",+ effect="instant",+ label="Theme",+ summary="Visual theme of the web interface.",+ read=theme_read,+ choices=_static_choices(_THEME_CHOICES, theme_read),+ write=_write_ui("theme"),+ ),+ ]+++# --------------------------------------------------------------------------+# document_parsing.json rows (global scope)+# --------------------------------------------------------------------------+++def _read_parsing_engine() -> str:+ from deeptutor.services.config.runtime_settings import get_runtime_settings_service++ settings = get_runtime_settings_service().load_document_parsing()+ return str(settings.get("engine") or "text_only")+++def _write_parsing_engine(value: str) -> None:+ from deeptutor.services.config.runtime_settings import get_runtime_settings_service++ service = get_runtime_settings_service()+ settings = service.load_document_parsing()+ settings["engine"] = value+ service.save_document_parsing(settings)+++def _parsing_engine_choices() -> tuple[SettingChoice, ...]:+ """Engine options, with availability answered by the engine registry itself.++ ``list_engines`` reports whether each engine's package actually imports, so+ an engine that merely *could* be installed still appears — the setup agent+ turns an unavailable choice into an install offer instead of pretending the+ engine does not exist.+ """+ from deeptutor.services.parsing.engines._install import installable_engines+ from deeptutor.services.parsing.engines.factory import list_engines++ active = _read_parsing_engine()+ installable = installable_engines()+ out: list[SettingChoice] = []+ for engine in list_engines():+ engine_id = str(engine.get("id") or "")+ if not engine_id:+ continue+ available = bool(engine.get("available"))+ description = str(engine.get("description") or "")+ if not available:+ description = (+ f"{description} Not installed yet"+ f"{'; can be installed in one step.' if engine_id in installable else '.'}"+ ).strip()+ out.append(+ SettingChoice(+ value=engine_id,+ label=str(engine.get("name") or engine_id),+ description=description,+ available=available,+ current=engine_id == active,+ )+ )+ return tuple(out)+++def _validate_parsing_engine(value: str) -> str | None:+ from deeptutor.services.parsing.engines.factory import is_engine_available++ if is_engine_available(value):+ return None+ return (+ f"The '{value}' engine is not installed, so selecting it would break document "+ "parsing. Install it first with run_setup_job."+ )+++def _parsing_specs() -> list[SettingSpec]:+ return [+ SettingSpec(+ key="document_parsing.engine",+ area="parsing",+ scope="global",+ effect="instant",+ label="Document parsing engine",+ summary=(+ "Which engine converts uploaded PDFs and Office files into text. "+ "Heavier engines read layout, tables and formulas more faithfully."+ ),+ read=_read_parsing_engine,+ choices=_parsing_engine_choices,+ write=_write_parsing_engine,+ validate=_validate_parsing_engine,+ effect_detail=(+ "Applies to documents parsed from now on; already-parsed documents keep "+ "their existing text until they are re-uploaded."+ ),+ )+ ]+++# --------------------------------------------------------------------------+# model_catalog.json rows (global scope)+# --------------------------------------------------------------------------++# ``llm`` and ``embedding`` select a profile *and* a model, so their value is+# the composite below; ``search`` selects a profile alone.+_COMPOSITE_SEPARATOR = "::"+++def _compose(profile_id: str, model_id: str) -> str:+ return f"{profile_id}{_COMPOSITE_SEPARATOR}{model_id}"+++def _decompose(value: str) -> tuple[str, str]:+ profile_id, _, model_id = str(value or "").partition(_COMPOSITE_SEPARATOR)+ return profile_id, model_id+++def _catalog_service():+ from deeptutor.services.config.model_catalog import get_model_catalog_service++ return get_model_catalog_service()+++def _read_catalog_model(service_name: str) -> Callable[[], str]:+ def _read() -> str:+ service = _catalog_service()+ catalog = service.load()+ profile = service.get_active_profile(catalog, service_name)+ model = service.get_active_model(catalog, service_name)+ if not profile:+ return ""+ return _compose(str(profile.get("id") or ""), str((model or {}).get("id") or ""))++ return _read+++def _catalog_model_choices(service_name: str) -> Callable[[], tuple[SettingChoice, ...]]:+ def _choices() -> tuple[SettingChoice, ...]:+ service = _catalog_service()+ catalog = service.load()+ active = _read_catalog_model(service_name)()+ out: list[SettingChoice] = []+ for profile in catalog.get("services", {}).get(service_name, {}).get("profiles", []) or []:+ profile_id = str(profile.get("id") or "")+ profile_name = str(profile.get("name") or profile_id)+ binding = str(profile.get("binding") or "")+ for model in profile.get("models", []) or []:+ model_id = str(model.get("id") or "")+ value = _compose(profile_id, model_id)+ model_name = str(model.get("name") or model.get("model") or model_id)+ out.append(+ SettingChoice(+ value=value,+ label=f"{model_name} · {profile_name}",+ description=f"Served by {binding or 'an OpenAI-compatible endpoint'}.",+ current=value == active,+ )+ )+ return tuple(out)++ return _choices+++def _write_catalog_model(service_name: str) -> Callable[[str], None]:+ def _write(value: str) -> None:+ profile_id, model_id = _decompose(value)++ def _mutate(catalog: dict[str, Any]) -> None:+ service = catalog.setdefault("services", {}).setdefault(service_name, {})+ service["active_profile_id"] = profile_id+ service["active_model_id"] = model_id++ _catalog_service().update(_mutate)+ _clear_runtime_caches()++ return _write+++def _read_catalog_profile(service_name: str) -> Callable[[], str]:+ def _read() -> str:+ service = _catalog_service()+ profile = service.get_active_profile(service.load(), service_name)+ return str((profile or {}).get("id") or "")++ return _read+++def _catalog_profile_choices(service_name: str) -> Callable[[], tuple[SettingChoice, ...]]:+ def _choices() -> tuple[SettingChoice, ...]:+ from deeptutor.services.config.provider_runtime import SEARCH_PROVIDERS++ service = _catalog_service()+ catalog = service.load()+ active = _read_catalog_profile(service_name)()+ out: list[SettingChoice] = []+ for profile in catalog.get("services", {}).get(service_name, {}).get("profiles", []) or []:+ profile_id = str(profile.get("id") or "")+ provider = str(profile.get("provider") or "")+ spec = SEARCH_PROVIDERS.get(provider)+ has_key = bool(str(profile.get("api_key") or "").strip())+ needs_key = bool(spec and spec.requires_api_key)+ description = f"{spec.label} provider." if spec else f"{provider} provider."+ if needs_key and not has_key:+ description += " No API key stored yet."+ out.append(+ SettingChoice(+ value=profile_id,+ label=str(profile.get("name") or provider or profile_id),+ description=description,+ available=not (needs_key and not has_key),+ current=profile_id == active,+ )+ )+ return tuple(out)++ return _choices+++def _write_catalog_profile(service_name: str) -> Callable[[str], None]:+ def _write(value: str) -> None:+ def _mutate(catalog: dict[str, Any]) -> None:+ service = catalog.setdefault("services", {}).setdefault(service_name, {})+ service["active_profile_id"] = value++ _catalog_service().update(_mutate)+ _clear_runtime_caches()++ return _write+++def _clear_runtime_caches() -> None:+ """Drop resolved-config caches so a committed change takes effect at once.++ Without this the running process keeps answering from the config it+ resolved before the write, and the user is told the model changed while+ the next turn still runs on the old one.+ """+ try:+ from deeptutor.services.llm import clear_llm_config_cache++ clear_llm_config_cache()+ except Exception: # noqa: BLE001 - best effort; a stale cache is not fatal+ pass+++def _candidate_catalog(service_name: str, value: str, *, with_model: bool) -> dict[str, Any]:+ """Catalog as it *would* be, without writing anything to disk.++ ``resolve_*_runtime_config`` accepts an explicit catalog, which is what+ makes probe-before-commit possible: the candidate selection is resolved and+ exercised while the stored configuration is still untouched.+ """+ from copy import deepcopy++ catalog = deepcopy(_catalog_service().load())+ service = catalog.setdefault("services", {}).setdefault(service_name, {})+ if with_model:+ profile_id, model_id = _decompose(value)+ service["active_profile_id"] = profile_id+ service["active_model_id"] = model_id+ else:+ service["active_profile_id"] = value+ return catalog+++# A probe runs inside a live chat turn, with the user waiting on it, so it is+# bounded far more tightly than an ordinary model call. The runtime's own+# defaults are wrong here in both directions: ``max_retries`` is 8 with a 5s+# base delay, and each attempt carries a 120s transport timeout, so an endpoint+# that accepts the connection and then hangs would keep the turn — and the whole+# conversation — waiting sixteen minutes before reporting a failure the user+# could have been told about in twenty seconds. One attempt, hard deadline.+_PROBE_TIMEOUT_SECONDS = 25.0+_PROBE_MAX_RETRIES = 0+++def _timed_out(started: float) -> ProbeResult:+ import time++ return ProbeResult(+ ok=False,+ detail=(+ f"No response within {int(_PROBE_TIMEOUT_SECONDS)}s. The endpoint may be "+ "unreachable from this machine, or the address may be wrong."+ ),+ elapsed_ms=int((time.monotonic() - started) * 1000),+ )+++async def _probe_llm(value: str) -> ProbeResult:+ """Smallest real completion against the candidate selection."""+ import asyncio+ import time++ from deeptutor.services.config.provider_runtime import resolve_llm_runtime_config+ from deeptutor.services.llm import complete as llm_complete+ from deeptutor.services.llm import get_token_limit_kwargs++ started = time.monotonic()+ try:+ resolved = resolve_llm_runtime_config(+ catalog=_candidate_catalog("llm", value, with_model=True)+ )+ if not resolved.model:+ return ProbeResult(ok=False, detail="No model resolved from that selection.")+ await asyncio.wait_for(+ llm_complete(+ model=resolved.model,+ prompt="ping",+ system_prompt="Reply with the single word OK.",+ binding=resolved.binding,+ api_key=resolved.api_key or "sk-no-key-required",+ base_url=resolved.effective_url or resolved.base_url or "",+ api_version=resolved.api_version,+ temperature=0.0,+ extra_headers=resolved.extra_headers,+ reasoning_effort=resolved.reasoning_effort,+ max_retries=_PROBE_MAX_RETRIES,+ **get_token_limit_kwargs(resolved.model, max_tokens=64),+ ),+ timeout=_PROBE_TIMEOUT_SECONDS,+ )+ except (TimeoutError, asyncio.TimeoutError):+ return _timed_out(started)+ except Exception as exc: # noqa: BLE001 - any failure means "do not commit"+ return ProbeResult(+ ok=False,+ detail=_redact(str(exc))[:300],+ elapsed_ms=int((time.monotonic() - started) * 1000),+ )+ # An empty completion is deliberately accepted: the probe verifies that the+ # endpoint and credentials work, not that the model is talkative. A+ # reasoning model can legitimately spend the whole 64-token budget thinking.+ return ProbeResult(ok=True, elapsed_ms=int((time.monotonic() - started) * 1000))+++async def _probe_embedding(value: str) -> ProbeResult:+ """Embed one short string with the candidate selection."""+ import asyncio+ import time++ from deeptutor.services.config.provider_runtime import resolve_embedding_runtime_config+ from deeptutor.services.embedding.client import EmbeddingClient+ from deeptutor.services.embedding.config import EmbeddingConfig++ started = time.monotonic()+ try:+ resolved = resolve_embedding_runtime_config(+ catalog=_candidate_catalog("embedding", value, with_model=True)+ )+ if not resolved.model:+ return ProbeResult(ok=False, detail="No embedding model resolved from that selection.")+ # ``dim=0`` / ``send_dimensions=False`` mirror the settings smoke test:+ # sending no ``dimensions=`` parameter keeps Matryoshka models from+ # simply echoing back whatever width we asked for.+ client = EmbeddingClient(+ EmbeddingConfig(+ model=resolved.model,+ api_key=resolved.api_key,+ base_url=resolved.base_url,+ effective_url=resolved.effective_url,+ binding=resolved.binding,+ provider_name=resolved.provider_name,+ provider_mode=resolved.provider_mode,+ api_version=resolved.api_version,+ extra_headers=resolved.extra_headers,+ dim=0,+ send_dimensions=False,+ # Clamped to the probe budget rather than the configured+ # timeout, which is sized for indexing a whole corpus.+ request_timeout=max(1, min(resolved.request_timeout, int(_PROBE_TIMEOUT_SECONDS))),+ batch_size=max(1, resolved.batch_size),+ batch_delay=max(0.0, resolved.batch_delay),+ )+ )+ vectors = await asyncio.wait_for(client.embed(["ping"]), timeout=_PROBE_TIMEOUT_SECONDS)+ if not vectors or not vectors[0]:+ return ProbeResult(ok=False, detail="The endpoint returned an empty embedding.")+ except (TimeoutError, asyncio.TimeoutError):+ return _timed_out(started)+ except Exception as exc: # noqa: BLE001 - any failure means "do not commit"+ return ProbeResult(+ ok=False,+ detail=_redact(str(exc))[:300],+ elapsed_ms=int((time.monotonic() - started) * 1000),+ )+ return ProbeResult(ok=True, elapsed_ms=int((time.monotonic() - started) * 1000))+++def _redact(text: str) -> str:+ """Strip anything that looks like a bearer token out of an error string.++ Provider errors often echo the request headers back. The setup agent puts+ probe failures in front of the model verbatim so it can explain them, so+ this is the boundary where a leaked key would enter the context.+ """+ import re++ redacted = re.sub(r"(sk-|Bearer\s+)[A-Za-z0-9_\-]{8,}", r"\1***", text)+ return re.sub(r"[A-Za-z0-9_\-]{32,}", "***", redacted)+++def _catalog_specs() -> list[SettingSpec]:+ return [+ SettingSpec(+ key="catalog.llm",+ area="models",+ scope="global",+ effect="instant",+ label="Chat model",+ summary="The language model that answers in chat and drives every capability.",+ read=_read_catalog_model("llm"),+ choices=_catalog_model_choices("llm"),+ write=_write_catalog_model("llm"),+ probe=_probe_llm,+ effect_detail="Applies from the next turn onwards.",+ ),+ SettingSpec(+ key="catalog.embedding",+ area="models",+ scope="global",+ effect="reindex",+ label="Embedding model",+ summary="The model that turns documents into vectors for knowledge-base search.",+ read=_read_catalog_model("embedding"),+ choices=_catalog_model_choices("embedding"),+ write=_write_catalog_model("embedding"),+ probe=_probe_embedding,+ effect_detail=(+ "Existing knowledge bases were indexed with the previous model and must be "+ "rebuilt before they can be searched again — vectors from two different "+ "models are not comparable."+ ),+ ),+ SettingSpec(+ key="catalog.search",+ area="models",+ scope="global",+ effect="instant",+ label="Web search provider",+ summary="Which service answers web_search calls.",+ read=_read_catalog_profile("search"),+ choices=_catalog_profile_choices("search"),+ write=_write_catalog_profile("search"),+ effect_detail="Applies from the next search onwards.",+ ),+ ]+++# --------------------------------------------------------------------------+# Registry+# --------------------------------------------------------------------------+++def setting_specs() -> dict[str, SettingSpec]:+ """All writable rows, keyed by ``key``, in stable presentation order.++ Built per call rather than at import time: every row closes over deferred+ imports, and building lazily keeps this module importable from+ ``deeptutor.capabilities`` without closing an import cycle.+ """+ rows = [*_interface_specs(), *_parsing_specs(), *_catalog_specs()]+ return {spec.key: spec for spec in rows}+++def get_setting_spec(key: str) -> SettingSpec | None:+ return setting_specs().get(str(key or "").strip())+++def specs_for_area(area: str) -> tuple[SettingSpec, ...]:+ wanted = str(area or "").strip().lower()+ return tuple(spec for spec in setting_specs().values() if not wanted or spec.area == wanted)+++SETTING_AREAS: tuple[str, ...] = ("interface", "models", "parsing")++__all__ = [+ "SETTING_AREAS",+ "Area",+ "Effect",+ "ProbeResult",+ "Scope",+ "SettingChoice",+ "SettingSpec",+ "get_setting_spec",+ "setting_specs",+ "specs_for_area",+]diff --git a/deeptutor/services/notebook/service.py b/deeptutor/services/notebook/service.pyindex b4552bfc4..fdb80ea1a 100644--- a/deeptutor/services/notebook/service.py+++ b/deeptutor/services/notebook/service.py@@ -7,17 +7,24 @@ can operate on the same files under ``data/user``.from __future__ import annotations+from collections.abc import Iterator+from contextlib import contextmanagerfrom enum import Enumimport json+import loggingfrom pathlib import Path+import threadingimport timeimport uuidfrom pydantic import BaseModel+from deeptutor.services.file_io import atomic_write_jsonfrom deeptutor.services.llm import clean_thinking_tagsfrom deeptutor.services.path_service import get_path_service+logger = logging.getLogger(__name__)+class RecordType(str, Enum):"""Notebook record type."""@@ -60,6 +67,21 @@ class Notebook(BaseModel):_UNSET = object()+class NotebookCorruptedError(RuntimeError):+ """A notebook file exists on disk but its JSON could not be parsed.++ Raised instead of silently reporting "no such notebook" so a damaged+ file surfaces as a real error the caller can show, rather than as a+ notebook that appears to have vanished while its data is still there.+ """++ def __init__(self, notebook_id: str, path: Path, cause: Exception) -> None:+ super().__init__(f"Notebook {notebook_id!r} is unreadable ({path}): {cause}")+ self.notebook_id = notebook_id+ self.path = path+ self.cause = cause++def _clean_record_summary(summary: str) -> str:"""Remove private model scratchpads before notebook summaries are persisted."""return clean_thinking_tags(str(summary or "")).strip()@@ -78,41 +100,102 @@ class NotebookManager:self.base_dir = base_dir_pathself.base_dir.mkdir(parents=True, exist_ok=True)self.index_file = self.base_dir / "notebooks_index.json"+ # One re-entrant lock per notebook, plus one for the shared index.+ # Every read-modify-write cycle below runs under the matching lock so+ # two concurrent saves cannot both load the same revision and clobber+ # one another. Writes themselves go through ``atomic_write_json``, so+ # a reader never observes a half-written file even across processes;+ # the locks close the remaining same-process lost-update window.+ # Lock order is always notebook-then-index, never the reverse.+ self._locks_guard = threading.Lock()+ self._notebook_locks: dict[str, threading.RLock] = {}+ self._index_lock = threading.RLock()self._ensure_index()+ @contextmanager+ def _locked(self, notebook_id: str) -> Iterator[None]:+ """Hold the per-notebook lock for one read-modify-write cycle."""+ with self._locks_guard:+ lock = self._notebook_locks.get(notebook_id)+ if lock is None:+ lock = threading.RLock()+ self._notebook_locks[notebook_id] = lock+ with lock:+ yield+def _ensure_index(self) -> None:if not self.index_file.exists():- with open(self.index_file, "w", encoding="utf-8") as f:- json.dump({"notebooks": []}, f, indent=2, ensure_ascii=False)+ atomic_write_json(self.index_file, {"notebooks": []})def _load_index(self) -> dict:try:with open(self.index_file, encoding="utf-8") as f:return json.load(f)- except Exception:+ except FileNotFoundError:return {"notebooks": []}+ except Exception as exc:+ # The index is a derived cache: every entry can be rebuilt from the+ # notebook files themselves, so recovering here loses nothing.+ logger.warning("notebook index unreadable (%s); rebuilding", exc)+ return {"notebooks": self._rebuild_index_entries()}++ def _rebuild_index_entries(self) -> list[dict]:+ """Reconstruct index rows by scanning the notebook files on disk."""+ entries: list[dict] = []+ for path in sorted(self.base_dir.glob("*.json")):+ if path == self.index_file:+ continue+ try:+ with open(path, encoding="utf-8") as f:+ notebook = json.load(f)+ except Exception:+ continue+ entries.append(self._index_row(notebook))+ return entries++ @staticmethod+ def _index_row(notebook: dict) -> dict:+ """Project a full notebook down to the fields the index carries."""+ return {+ "id": notebook["id"],+ "name": notebook.get("name", ""),+ "description": notebook.get("description", ""),+ "created_at": notebook.get("created_at", 0.0),+ "updated_at": notebook.get("updated_at", 0.0),+ "record_count": len(notebook.get("records", [])),+ "color": notebook.get("color", "#3B82F6"),+ "icon": notebook.get("icon", "book"),+ }def _save_index(self, index: dict) -> None:- with open(self.index_file, "w", encoding="utf-8") as f:- json.dump(index, f, indent=2, ensure_ascii=False)+ atomic_write_json(self.index_file, index)def _get_notebook_file(self, notebook_id: str) -> Path:return self.base_dir / f"{notebook_id}.json"def _load_notebook(self, notebook_id: str) -> dict | None:+ """Return the notebook, or ``None`` when no such file exists.++ A file that exists but cannot be parsed raises+ :class:`NotebookCorruptedError` rather than returning ``None`` —+ conflating the two is what made damaged notebooks look deleted.+ """filepath = self._get_notebook_file(notebook_id)if not filepath.exists():return Nonetry:with open(filepath, encoding="utf-8") as f:notebook = json.load(f)- except Exception:+ except FileNotFoundError:return None+ except Exception as exc:+ logger.error("notebook %s failed to load from %s: %s", notebook_id, filepath, exc)+ raise NotebookCorruptedError(notebook_id, filepath, exc) from excif self._sanitize_loaded_notebook(notebook):try:self._save_notebook(notebook)except Exception:- pass+ logger.warning("could not persist sanitized notebook %s", notebook_id)return notebookdef _sanitize_loaded_notebook(self, notebook: dict) -> bool:@@ -131,23 +214,23 @@ class NotebookManager:return changeddef _save_notebook(self, notebook: dict) -> None:- filepath = self._get_notebook_file(notebook["id"])- with open(filepath, "w", encoding="utf-8") as f:- json.dump(notebook, f, indent=2, ensure_ascii=False)+ atomic_write_json(self._get_notebook_file(notebook["id"]), notebook)def _touch_index_entry(self, notebook_id: str, notebook: dict) -> None:- index = self._load_index()- for nb_info in index.get("notebooks", []):- if nb_info["id"] != notebook_id:- continue- nb_info["name"] = notebook.get("name", nb_info.get("name", ""))- nb_info["description"] = notebook.get("description", nb_info.get("description", ""))- nb_info["updated_at"] = notebook["updated_at"]- nb_info["record_count"] = len(notebook.get("records", []))- nb_info["color"] = notebook.get("color", nb_info.get("color", "#3B82F6"))- nb_info["icon"] = notebook.get("icon", nb_info.get("icon", "book"))- break- self._save_index(index)+ """Refresh this notebook's index row, re-adding it if it went missing."""+ with self._index_lock:+ index = self._load_index()+ rows = index.setdefault("notebooks", [])+ row = self._index_row(notebook)+ for position, nb_info in enumerate(rows):+ if nb_info.get("id") == notebook_id:+ # Keep created_at from the index when the file lacks it.+ row["created_at"] = notebook.get("created_at", nb_info.get("created_at", 0.0))+ rows[position] = row+ break+ else:+ rows.append(row)+ self._save_index(index)# === Notebook Operations ===@@ -168,45 +251,81 @@ class NotebookManager:"icon": icon,}- self._save_notebook(notebook)+ with self._locked(notebook_id):+ self._save_notebook(notebook)+ self._touch_index_entry(notebook_id, notebook)+ return notebook- index = self._load_index()- index["notebooks"].append(+ def list_notebooks(self) -> list[dict]:+ """List every notebook on disk, newest first.++ Rows come from the index rather than from parsing each notebook in+ full, and the index is reconciled against the directory first, so a+ notebook whose index row was lost still shows up. A notebook whose+ file is damaged is reported with ``unreadable`` set instead of being+ dropped — silently omitting it is what made data look deleted.+ """+ damaged: list[dict] = []+ with self._index_lock:+ index = self._load_index()+ rows = {str(row.get("id")): row for row in index.get("notebooks", []) if row.get("id")}++ on_disk = {+ path.stem for path in self.base_dir.glob("*.json") if path != self.index_file+ }+ # Drop rows whose file is gone; adopt files the index never learned+ # about. Only the unknown files are parsed — indexed ones are taken+ # at their word, which keeps listing O(index) rather than O(content).+ changed = False+ for notebook_id in list(rows):+ if notebook_id not in on_disk:+ rows.pop(notebook_id)+ changed = True+ for notebook_id in sorted(on_disk - rows.keys()):+ try:+ notebook = self._load_notebook(notebook_id)+ except NotebookCorruptedError:+ # Surface it as a placeholder instead of dropping it: the+ # file is still on disk and the user needs to know that.+ damaged.append({"id": notebook_id, "unreadable": True})+ continue+ if notebook:+ rows[notebook_id] = self._index_row(notebook)+ changed = True+ if changed:+ self._save_index({"notebooks": list(rows.values())})++ notebooks: list[dict] = [{"id": notebook_id,- "name": name,- "description": description,- "created_at": now,- "updated_at": now,- "record_count": 0,- "color": color,- "icon": icon,+ "name": row.get("name", ""),+ "description": row.get("description", ""),+ "created_at": row.get("created_at", 0.0),+ "updated_at": row.get("updated_at", 0.0),+ "record_count": row.get("record_count", 0),+ "color": row.get("color", "#3B82F6"),+ "icon": row.get("icon", "book"),}- )- self._save_index(index)- return notebook-- def list_notebooks(self) -> list[dict]:- index = self._load_index()- notebooks: list[dict] = []-- for nb_info in index.get("notebooks", []):- notebook = self._load_notebook(nb_info["id"])- if notebook:- notebooks.append(- {- "id": notebook["id"],- "name": notebook["name"],- "description": notebook.get("description", ""),- "created_at": notebook["created_at"],- "updated_at": notebook["updated_at"],- "record_count": len(notebook.get("records", [])),- "color": notebook.get("color", "#3B82F6"),- "icon": notebook.get("icon", "book"),- }- )-+ for notebook_id, row in rows.items()+ ]notebooks.sort(key=lambda x: x["updated_at"], reverse=True)++ # Damaged notebooks have no trustworthy metadata to sort by, so they+ # ride at the end with just enough for the UI to flag them.+ for entry in damaged:+ notebooks.append(+ {+ "id": entry["id"],+ "name": entry["id"],+ "description": "",+ "created_at": 0.0,+ "updated_at": 0.0,+ "record_count": 0,+ "color": "#3B82F6",+ "icon": "book",+ "unreadable": True,+ }+ )return notebooksdef get_notebook(self, notebook_id: str) -> dict | None:@@ -220,34 +339,39 @@ class NotebookManager:color: str | None = None,icon: str | None = None,) -> dict | None:- notebook = self._load_notebook(notebook_id)- if not notebook:- return None-- if name is not None:- notebook["name"] = name- if description is not None:- notebook["description"] = description- if color is not None:- notebook["color"] = color- if icon is not None:- notebook["icon"] = icon-- notebook["updated_at"] = time.time()- self._save_notebook(notebook)- self._touch_index_entry(notebook_id, notebook)- return notebook+ with self._locked(notebook_id):+ notebook = self._load_notebook(notebook_id)+ if not notebook:+ return None++ if name is not None:+ notebook["name"] = name+ if description is not None:+ notebook["description"] = description+ if color is not None:+ notebook["color"] = color+ if icon is not None:+ notebook["icon"] = icon++ notebook["updated_at"] = time.time()+ self._save_notebook(notebook)+ self._touch_index_entry(notebook_id, notebook)+ return notebookdef delete_notebook(self, notebook_id: str) -> bool:- filepath = self._get_notebook_file(notebook_id)- if not filepath.exists():- return False-- filepath.unlink()- index = self._load_index()- index["notebooks"] = [nb for nb in index["notebooks"] if nb["id"] != notebook_id]- self._save_index(index)- return True+ with self._locked(notebook_id):+ filepath = self._get_notebook_file(notebook_id)+ if not filepath.exists():+ return False++ filepath.unlink()+ with self._index_lock:+ index = self._load_index()+ index["notebooks"] = [+ nb for nb in index.get("notebooks", []) if nb.get("id") != notebook_id+ ]+ self._save_index(index)+ return True# === Record Operations ===@@ -283,14 +407,25 @@ class NotebookManager:added_to: list[str] = []for notebook_id in notebook_ids:- notebook = self._load_notebook(notebook_id)- if not notebook:- continue- notebook["records"].append(record)- notebook["updated_at"] = now- self._save_notebook(notebook)- self._touch_index_entry(notebook_id, notebook)- added_to.append(notebook_id)+ # One lock per notebook rather than one around the whole loop:+ # the notebooks are independent files and nothing here reads two+ # of them at once, so a single wide lock would only add contention.+ with self._locked(notebook_id):+ try:+ notebook = self._load_notebook(notebook_id)+ except NotebookCorruptedError:+ logger.warning("skipping unreadable notebook %s while saving", notebook_id)+ continue+ if not notebook:+ continue+ # Each notebook stores its own copy. They share a record id so+ # the save is traceable, but editing one does not touch the+ # others — use ``copy_record`` for an explicit independent copy.+ notebook.setdefault("records", []).append(dict(record))+ notebook["updated_at"] = now+ self._save_notebook(notebook)+ self._touch_index_entry(notebook_id, notebook)+ added_to.append(notebook_id)return {"record": record, "added_to_notebooks": added_to}@@ -322,37 +457,45 @@ class NotebookManager:metadata: dict | None = None,kb_name: str | None | object = _UNSET,) -> dict | None:- notebook = self._load_notebook(notebook_id)- if not notebook:- return None-- updated_record: dict | None = None- for record in notebook.get("records", []):- if str(record.get("id", "")) != str(record_id):- continue- if title is not None:- record["title"] = title- if summary is not None:- record["summary"] = _clean_record_summary(summary)- if user_query is not None:- record["user_query"] = user_query- if output is not None:- record["output"] = output- if metadata is not None:- current_metadata = record.get("metadata", {}) or {}- record["metadata"] = {**current_metadata, **metadata}- if kb_name is not _UNSET:- record["kb_name"] = kb_name- updated_record = record- break-- if updated_record is None:- return None-- notebook["updated_at"] = time.time()- self._save_notebook(notebook)- self._touch_index_entry(notebook_id, notebook)- return updated_record+ """Edit one record in place. Only this notebook's copy is affected.++ Every parameter defaults to "leave alone". ``kb_name`` additionally+ distinguishes *omitted* from an explicit ``None``, so a caller that+ only renames a record cannot accidentally drop its knowledge-base+ link — pass ``kb_name=None`` when clearing it is what you mean.+ """+ with self._locked(notebook_id):+ notebook = self._load_notebook(notebook_id)+ if not notebook:+ return None++ updated_record: dict | None = None+ for record in notebook.get("records", []):+ if str(record.get("id", "")) != str(record_id):+ continue+ if title is not None:+ record["title"] = title+ if summary is not None:+ record["summary"] = _clean_record_summary(summary)+ if user_query is not None:+ record["user_query"] = user_query+ if output is not None:+ record["output"] = output+ if metadata is not None:+ current_metadata = record.get("metadata", {}) or {}+ record["metadata"] = {**current_metadata, **metadata}+ if kb_name is not _UNSET:+ record["kb_name"] = kb_name+ updated_record = record+ break++ if updated_record is None:+ return None++ notebook["updated_at"] = time.time()+ self._save_notebook(notebook)+ self._touch_index_entry(notebook_id, notebook)+ return updated_recorddef get_records_by_references(self, notebook_references: list[dict]) -> list[dict]:resolved: list[dict] = []@@ -366,7 +509,13 @@ class NotebookManager:for record_id in (ref.get("record_ids") or [])if str(record_id).strip()]- notebook = self._load_notebook(notebook_id)+ try:+ notebook = self._load_notebook(notebook_id)+ except NotebookCorruptedError:+ # Resolving references feeds a chat turn; one damaged notebook+ # must not take the whole turn down with it.+ logger.warning("skipping unreadable notebook %s while resolving refs", notebook_id)+ continueif not notebook:continue@@ -383,35 +532,129 @@ class NotebookManager:return resolveddef remove_record(self, notebook_id: str, record_id: str) -> bool:+ with self._locked(notebook_id):+ notebook = self._load_notebook(notebook_id)+ if not notebook:+ return False++ records = notebook.get("records", [])+ original_count = len(records)+ notebook["records"] = [r for r in records if str(r.get("id")) != str(record_id)]++ if len(notebook["records"]) == original_count:+ return False++ notebook["updated_at"] = time.time()+ self._save_notebook(notebook)+ self._touch_index_entry(notebook_id, notebook)+ return True++ def copy_record(+ self, source_notebook_id: str, record_id: str, target_notebook_id: str+ ) -> dict | None:+ """Duplicate a record into another notebook under a fresh id.++ The copy is independent from the moment it lands: editing either side+ leaves the other untouched. Returns ``None`` when the source record or+ the target notebook does not exist.+ """+ if source_notebook_id == target_notebook_id:+ return None++ source_record = self.get_record(source_notebook_id, record_id)+ if source_record is None:+ return None++ copied = dict(source_record)+ copied["id"] = str(uuid.uuid4())[:8]+ copied["metadata"] = {+ **(source_record.get("metadata") or {}),+ "copied_from": {"notebook_id": source_notebook_id, "record_id": record_id},+ }++ with self._locked(target_notebook_id):+ target = self._load_notebook(target_notebook_id)+ if not target:+ return None+ target.setdefault("records", []).append(copied)+ target["updated_at"] = time.time()+ self._save_notebook(target)+ self._touch_index_entry(target_notebook_id, target)+ return copied++ def move_record(+ self, source_notebook_id: str, record_id: str, target_notebook_id: str+ ) -> dict | None:+ """Move a record between notebooks.++ Writes the copy first and only then removes the original, so an+ interruption leaves the record duplicated rather than destroyed.+ """+ copied = self.copy_record(source_notebook_id, record_id, target_notebook_id)+ if copied is None:+ return None+ if not self.remove_record(source_notebook_id, record_id):+ # The copy already landed; report it rather than failing outright.+ logger.warning(+ "moved record %s into %s but could not remove the original from %s",+ record_id,+ target_notebook_id,+ source_notebook_id,+ )+ return copied++ def export_markdown(self, notebook_id: str) -> str | None:+ """Render a whole notebook as one Markdown document."""notebook = self._load_notebook(notebook_id)if not notebook:- return False+ return None- original_count = len(notebook["records"])- notebook["records"] = [r for r in notebook["records"] if r["id"] != record_id]+ lines: list[str] = [f"# {notebook.get('name', notebook_id)}"]+ description = str(notebook.get("description") or "").strip()+ if description:+ lines.append("")+ lines.append(f"> {description}")- if len(notebook["records"]) == original_count:- return False-- notebook["updated_at"] = time.time()- self._save_notebook(notebook)- self._touch_index_entry(notebook_id, notebook)- return True+ for record in notebook.get("records", []):+ lines.append("")+ lines.append("---")+ lines.append("")+ lines.append(f"## {record.get('title') or '(untitled)'}")++ created_at = record.get("created_at")+ stamp = (+ time.strftime("%Y-%m-%d %H:%M", time.localtime(created_at)) if created_at else ""+ )+ meta_bits = [bit for bit in (str(record.get("type") or ""), stamp) if bit]+ if meta_bits:+ lines.append("")+ lines.append(f"*{' · '.join(meta_bits)}*")++ summary = str(record.get("summary") or "").strip()+ if summary:+ lines.append("")+ lines.append(f"> {summary}")++ output = str(record.get("output") or "").strip()+ if output:+ lines.append("")+ lines.append(output)++ return "\n".join(lines) + "\n"def get_statistics(self) -> dict:notebooks = self.list_notebooks()total_records = 0- type_counts = {- "solve": 0,- "question": 0,- "research": 0,- "chat": 0,- "co_writer": 0,- }+ # Derived from the enum so a newly added record type is counted the+ # day it is introduced, instead of silently missing from the totals.+ type_counts = {member.value: 0 for member in RecordType}for nb_info in notebooks:- notebook = self._load_notebook(nb_info["id"])+ try:+ notebook = self._load_notebook(nb_info["id"])+ except NotebookCorruptedError:+ continueif notebook:for record in notebook.get("records", []):total_records += 1diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.pyindex 5e8302cf6..1597f1f4d 100644--- a/deeptutor/services/path_service.py+++ b/deeptutor/services/path_service.py@@ -53,6 +53,7 @@ WorkspaceFeature = Literal["co-writer","chat","book",+ "reading",]diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.pyindex 7c97e340e..1249d1d30 100644--- a/deeptutor/services/rag/factory.py+++ b/deeptutor/services/rag/factory.py@@ -271,8 +271,10 @@ def list_pipelines() -> List[Dict[str, Any]]:"description": ("Retrieval offloaded to a knowledge base you keep in Tencent IMA. ""No local index and no copy — connect a KB to its IMA library and "- "query it over IMA's OpenAPI. Documents are added in IMA itself. "- "Requires an IMA Client ID and API key."+ "query it over IMA's OpenAPI. Chat can also browse the library's "+ "documents, read a full source, search your IMA notes, and (when "+ "you ask) collect a web page or save a note. Uploading files still "+ "happens in IMA itself. Requires an IMA Client ID and API key."),# A thin HTTPS client with no install; readiness is only about the# account credentials. The library id stays per-KB, set at connectdiff --git a/deeptutor/services/rag/pipelines/ima/__init__.py b/deeptutor/services/rag/pipelines/ima/__init__.pyindex 8cc71e474..0b4e2eab7 100644--- a/deeptutor/services/rag/pipelines/ima/__init__.py+++ b/deeptutor/services/rag/pipelines/ima/__init__.py@@ -1,13 +1,24 @@-"""Retrieval-only RAG pipeline backed by a Tencent IMA knowledge base.+"""Tencent IMA integration — retrieval, inventory and authoring over a live library.A KB bound to the ``ima`` provider is a connection pointer to a library the userkeeps in IMA (https://ima.qq.com) and curates there. DeepTutor never indexes or-stores anything locally: retrieval calls IMA's ``search_knowledge`` OpenAPI and-uses a bounded read-only source fallback when a match has no snippet. DeepTutor's-chat LLM still writes the answer. The IMA credentials are configured once for the-account on the engine page (a KB may override them to reach another account); the-knowledge base id is always per-KB. See ``client`` for the wire and ``probe`` for-the connect-time health check.+stores anything locally; everything is an OpenAPI call:++* :mod:`.pipeline` — the ``rag`` engine: ``search_knowledge`` plus a bounded+ full-text top-up for matches whose snippet is too thin to reason from.+* :mod:`.inventory` — what the library *contains* (``get_knowledge_list``), which+ is what makes "list the documents in this knowledge base" answerable; read from+ the synchronous manifest layer, so it is blocking and cached.+* :mod:`.notes` — the notes module, including the sort orders that answer "my+ most recent items" (knowledge items carry no timestamps; notes do).+* :mod:`.client` — the knowledge-base method table, with :mod:`.transport`,+ :mod:`.envelope`, :mod:`.models` and :mod:`.media` underneath it.+* :mod:`.probe` — the connect-time health check.++The IMA credentials are configured once for the account on the engine page (a KB+may override them to reach another account); the knowledge base id is always+per-KB. The agentic surface over these calls is+:mod:`deeptutor.capabilities.ima`."""from __future__ import annotationsdiff --git a/deeptutor/services/rag/pipelines/ima/client.py b/deeptutor/services/rag/pipelines/ima/client.pyindex f88839033..96ce8918a 100644--- a/deeptutor/services/rag/pipelines/ima/client.py+++ b/deeptutor/services/rag/pipelines/ima/client.py@@ -1,91 +1,67 @@-"""Thin async HTTP client for Tencent IMA's knowledge-base OpenAPI.--Every IMA call is ``POST https://ima.qq.com/openapi/wiki/v1/<method>`` with a-JSON body, authenticated by two headers, and answers with a-``{"code", "msg", "data"}`` envelope where ``code == 0`` means success. Only the-read-only calls DeepTutor needs are wrapped:--* ``search_knowledge`` — retrieval inside one knowledge base. Returns matching- items with a ``highlight_content`` snippet, cursor-paginated.-* ``search_knowledge_base`` — lists knowledge bases available to the supplied- credentials so users do not need to copy an internal id by hand.-* ``get_knowledge_base`` — a KB's name/description, used to confirm at connect- time that the credentials work and the id resolves.-* ``get_media_info`` / ``get_doc_content`` — bounded fallback content for- title-only search matches.--Writing to IMA is deliberately out of scope: a connected KB is a read-only-pointer, and documents are added in IMA itself.--Mirrors :class:`LightRagServerClient`: a fresh :class:`httpx.AsyncClient` per-call so the object is safe to construct once and reuse, and an injectable-``transport`` so tests can stub the wire without a live server.+"""Client for Tencent IMA's knowledge-base OpenAPI (``/openapi/wiki/v1``).++A method table over the calls DeepTutor needs, with the wire mechanics delegated+to :class:`~deeptutor.services.rag.pipelines.ima.transport.ImaTransport`, the+payload decoding to :mod:`.models`, and file downloads to :mod:`.media`:++Reading+ * ``search_knowledge`` — retrieval inside one knowledge base; returns matched+ items with a ``highlight_content`` snippet, cursor-paginated.+ * ``get_knowledge_list`` — *browse* a knowledge base (or one of its folders)+ and see what it actually holds. This is the inventory call: retrieval can+ only report what a query matched, never what a library contains.+ * ``search_knowledge_base`` / ``get_knowledge_base`` — which libraries these+ credentials can reach, and one library's name / description (which doubles+ as the connect-time credential check).+ * ``get_media_info`` (+ the notes module's ``get_doc_content``) — full source+ text for one item.++Writing+ * ``import_urls`` — add web pages / WeChat articles to a library.+ * the notes module (see :class:`ImaNotesClient`) — create or append notes.++Uploading local *files* is deliberately still out of scope: IMA's upload is a+four-step transaction ending in a signed direct-to-COS PUT, which needs its own+credential handling and size/type preflight. Deleting anything in IMA is out of+scope permanently — a connected KB never destroys the user's own library."""from __future__ import annotations-from dataclasses import dataclass-import logging-from pathlib import PurePosixPathfrom typing import Any, Optional-from urllib.parse import unquote, urlparseimport httpx+from . import media as media_opsfrom .config import ImaConfig--logger = logging.getLogger(__name__)--API_BASE_URL = "https://ima.qq.com"-_API_PREFIX = "/openapi/wiki/v1"-_NOTE_API_PREFIX = "/openapi/note/v1"--# Official IMA media links are short-lived Tencent COS URLs. Restricting the-# downloader to that boundary prevents a compromised API response from turning-# retrieval into an SSRF primitive. IMA's own credentials are never attached to-# this separate client.-_COS_ROOT_DOMAIN = "myqcloud.com"-_FORBIDDEN_MEDIA_HEADERS = frozenset(- {- "connection",- "content-length",- "cookie",- "host",- "proxy-authorization",- "transfer-encoding",- }+from .envelope import ImaAPIError, ImaAuthError, ImaRateLimitError+from .media import MAX_MEDIA_BYTES, ImaMediaContent+from .models import (+ ImaImportedUrl,+ ImaKnowledgePage,+ parse_imported_urls,+ parse_knowledge_bases,+ parse_knowledge_page,)-MAX_MEDIA_BYTES = 20 * 1024 * 1024+from .notes import ImaNotesClient+from .transport import API_BASE_URL, DEFAULT_TIMEOUT, ImaTransport++# IMA's documented page bounds for every ``limit``-taking knowledge-base call.+MAX_PAGE_LIMIT = 50-# Envelope codes worth naming. IMA returns hundreds of business codes; these are-# the two classes a caller reacts to differently from a generic failure.-_CREDENTIAL_CODES = frozenset({20004, 200002})-_RATE_LIMIT_CODES = frozenset({20002, 110021})+# ``get_knowledge_base`` takes ids in batches, capped by IMA at 20.+MAX_DETAIL_IDS = 20++# ``import_urls`` accepts 1-10 URLs per call.+MAX_IMPORT_URLS = 10# ``search_knowledge`` is cursor-paginated. Retrieval feeds an LLM prompt, so a# couple of pages is plenty — this bounds the calls a single search can make._MAX_SEARCH_PAGES = 3--class ImaAPIError(RuntimeError):- """Raised when IMA returns an error envelope or an unexpected payload."""---class ImaAuthError(ImaAPIError):- """Raised when IMA rejects the client id / API key pair."""---class ImaRateLimitError(ImaAPIError):- """Raised when IMA rate-limits the request."""---@dataclass(frozen=True)-class ImaMediaContent:- """One IMA item's content, as either note text or downloaded file bytes."""-- text: str = ""- data: bytes = b""- filename: str = ""+# Media type IMA assigns to a note linked into a knowledge base. Its text comes+# from the notes module rather than a file download.+_NOTE_MEDIA_TYPE = 11class ImaClient:@@ -95,109 +71,126 @@ class ImaClient:self,config: ImaConfig,*,- timeout: float = 30.0,+ timeout: float = DEFAULT_TIMEOUT,transport: Optional[httpx.AsyncBaseTransport] = None,) -> None:self._config = configself._timeout = timeoutself._transport = transport+ self._wire = ImaTransport(config, timeout=timeout, transport=transport)+ self._notes = ImaNotesClient(config, timeout=timeout, transport=transport)- def _open(self) -> httpx.AsyncClient:- return httpx.AsyncClient(- base_url=API_BASE_URL,- headers={- "Content-Type": "application/json",- "ima-openapi-clientid": self._config.client_id,- "ima-openapi-apikey": self._config.api_key,- },- timeout=self._timeout,- transport=self._transport,- )+ @property+ def notes(self) -> ImaNotesClient:+ """The notes-module client sharing this client's credentials."""+ return self._notes- async def _post(- self,- method: str,- body: dict[str, Any],- *,- prefix: str = _API_PREFIX,- ) -> dict[str, Any]:- """POST one IMA method and return its unwrapped ``data`` object."""- async with self._open() as client:- resp = await client.post(f"{prefix}/{method}", json=body)- if resp.status_code == 429:- raise ImaRateLimitError("IMA rate limit reached. Try again shortly.")- try:- payload = resp.json()- except Exception as exc:- raise ImaAPIError(- f"IMA returned a non-JSON response with status {resp.status_code}"- ) from exc- if not isinstance(payload, dict):- raise ImaAPIError(f"IMA returned an unexpected payload: {payload!r}")-- code = payload.get("code")- message = str(payload.get("msg") or "").strip()- if code == 0:- data = payload.get("data")- return data if isinstance(data, dict) else {}- if code in _CREDENTIAL_CODES:- raise ImaAuthError(message or "IMA rejected the client ID / API key.")- if code in _RATE_LIMIT_CODES:- raise ImaRateLimitError(message or "IMA rate limit reached.")- raise ImaAPIError(message or f"IMA request failed with code {code}.")+ @property+ def knowledge_base_id(self) -> str:+ return self._config.knowledge_base_id# ----- retrieval ------------------------------------------------------- async def search_knowledge(self, query: str, *, limit: int) -> list[dict[str, Any]]:- """Return up to *limit* matching items from the bound knowledge base.+ async def search_knowledge(self, query: str, *, limit: int) -> ImaKnowledgePage:+ """Return up to *limit* matching documents from the bound knowledge base.- Each item is ``{"media_id", "title", "parent_folder_id",- "highlight_content"}``. Pages are followed until the result is full,- IMA reports the end of the list, or the page budget runs out.+ Pages are followed until the result is full, IMA reports the end of the+ list, or the page budget runs out. Matched *folders* are kept separate+ from matched documents (IMA returns both) so retrieval never treats a+ folder as a source."""- items: list[dict[str, Any]] = []+ documents = []+ folders = []cursor = ""+ is_end = Falsefor _ in range(_MAX_SEARCH_PAGES):- data = await self._post(- "search_knowledge",- {- "query": query,- "cursor": cursor,- "knowledge_base_id": self._config.knowledge_base_id,- },+ page = parse_knowledge_page(+ await self._wire.post(+ "search_knowledge",+ {+ "query": query,+ "cursor": cursor,+ "knowledge_base_id": self._config.knowledge_base_id,+ },+ ))- page = data.get("info_list")- if isinstance(page, list):- items.extend(entry for entry in page if isinstance(entry, dict))- cursor = str(data.get("next_cursor") or "")- if len(items) >= limit or data.get("is_end") or not cursor:+ documents.extend(page.documents)+ folders.extend(page.folders)+ cursor = page.next_cursor+ is_end = page.is_end+ if len(documents) >= limit or page.is_end or not cursor:break- return items[:limit]+ return ImaKnowledgePage(+ documents=tuple(documents[:limit]),+ folders=tuple(folders),+ next_cursor=cursor,+ is_end=is_end,+ )++ async def get_knowledge_list(+ self,+ *,+ folder_id: str = "",+ cursor: str = "",+ limit: int = MAX_PAGE_LIMIT,+ ) -> ImaKnowledgePage:+ """Return one page of the bound knowledge base's contents.++ Omitting *folder_id* lists the library root; passing one descends into+ that folder. The response carries documents, subfolders and a breadcrumb.+ """+ return parse_knowledge_page(+ await self._wire.post("get_knowledge_list", self._list_body(folder_id, cursor, limit))+ )++ def get_knowledge_list_sync(+ self,+ *,+ folder_id: str = "",+ cursor: str = "",+ limit: int = MAX_PAGE_LIMIT,+ ) -> ImaKnowledgePage:+ """Blocking :meth:`get_knowledge_list`, for the synchronous manifest layer."""+ return parse_knowledge_page(+ self._wire.post_sync("get_knowledge_list", self._list_body(folder_id, cursor, limit))+ )++ def _list_body(self, folder_id: str, cursor: str, limit: int) -> dict[str, Any]:+ body: dict[str, Any] = {+ "knowledge_base_id": self._config.knowledge_base_id,+ "cursor": str(cursor or ""),+ "limit": page_limit(limit),+ }+ folder = str(folder_id or "").strip()+ # The root folder id equals the knowledge base id; sending it is+ # equivalent to omitting the field, so it is dropped for clarity.+ if folder and folder != self._config.knowledge_base_id:+ body["folder_id"] = folder+ return body++ async def get_media_info(self, media_id: str) -> dict[str, Any]:+ """Return one item's metadata (media type, note link, download URL)."""+ normalized = str(media_id or "").strip()+ if not normalized:+ return {}+ return await self._wire.post("get_media_info", {"media_id": normalized})async def get_media_content(self, media_id: str) -> ImaMediaContent | None:- """Fetch full content for one search result when IMA omitted a snippet.+ """Fetch full content for one knowledge item.- IMA notes are returned as plain text by the notes API. File media is- streamed from the short-lived COS URL with a hard byte limit. Missing- or inaccessible media returns ``None`` so retrieval can degrade to the- result title without failing the whole search.+ IMA notes are returned as plain text by the notes module. File media is+ streamed from the short-lived COS URL with a hard byte limit. Missing or+ inaccessible media returns ``None`` so a caller can degrade to the item's+ title instead of failing outright."""- normalized_id = str(media_id or "").strip()- if not normalized_id:+ info = await self.get_media_info(media_id)+ if not info:return None- info = await self._post("get_media_info", {"media_id": normalized_id})- note_info = info.get("notebook_ext_info")- if info.get("media_type") == 11 and isinstance(note_info, dict):- note_id = str(note_info.get("notebook_id") or "").strip()- if note_id:- data = await self._post(- "get_doc_content",- {"note_id": note_id, "target_content_format": 0},- prefix=_NOTE_API_PREFIX,- )- content = str(data.get("content") or "").strip()- return ImaMediaContent(text=content) if content else None+ note_id = _linked_note_id(info)+ if note_id:+ content = await self._notes.get_note_content(note_id)+ return ImaMediaContent(text=content) if content else Noneurl_info = info.get("url_info")if not isinstance(url_info, dict):@@ -205,34 +198,47 @@ class ImaClient:url = str(url_info.get("url") or "").strip()if not url:return None- headers = _media_headers(url_info.get("headers"))- return await self._download_media(url, headers=headers)-- async def _download_media(- self,- url: str,- *,- headers: dict[str, str],- ) -> ImaMediaContent:- _validate_media_url(url)- async with httpx.AsyncClient(+ return await media_ops.download_media(+ url,+ headers=media_ops.media_headers(url_info.get("headers")),timeout=self._timeout,transport=self._transport,- follow_redirects=False,- ) as client:- async with client.stream("GET", url, headers=headers) as response:- response.raise_for_status()- length = response.headers.get("content-length")- if length and length.isdigit() and int(length) > MAX_MEDIA_BYTES:- raise ImaAPIError("IMA media exceeds the 20 MB retrieval limit.")- body = bytearray()- async for chunk in response.aiter_bytes():- body.extend(chunk)- if len(body) > MAX_MEDIA_BYTES:- raise ImaAPIError("IMA media exceeds the 20 MB retrieval limit.")-- filename = _media_filename(url, response.headers.get("content-type"))- return ImaMediaContent(data=bytes(body), filename=filename)+ )++ # ----- writing --------------------------------------------------------++ async def import_urls(self, urls: list[str], *, folder_id: str = "") -> list[ImaImportedUrl]:+ """Add up to :data:`MAX_IMPORT_URLS` web pages to the bound library.++ IMA reports a per-URL verdict rather than failing the batch, so partial+ success is normal and is returned as-is for the caller to report.+ """+ cleaned: list[str] = []+ for raw in urls:+ url = str(raw or "").strip()+ if url and url not in cleaned:+ cleaned.append(url)+ if not cleaned:+ raise ValueError("At least one URL is required.")+ if len(cleaned) > MAX_IMPORT_URLS:+ raise ValueError(f"IMA accepts at most {MAX_IMPORT_URLS} URLs per call.")++ # ``folder_id`` is required here, and the root folder's id is the+ # knowledge base id itself.+ target = str(folder_id or "").strip() or self._config.knowledge_base_id+ data = await self._wire.post(+ "import_urls",+ {+ "urls": cleaned,+ "knowledge_base_id": self._config.knowledge_base_id,+ "folder_id": target,+ },+ )+ results = parse_imported_urls(data)+ if results:+ return results+ # Some responses acknowledge the batch without echoing per-URL rows.+ return [ImaImportedUrl(url=url, ok=True) for url in cleaned]# ----- probing --------------------------------------------------------@@ -241,69 +247,58 @@ class ImaClient:query: str = "",*,cursor: str = "",- limit: int = 20,+ limit: int = MAX_DETAIL_IDS,) -> dict[str, Any]:"""Return one page of knowledge bases available to these credentials.- Official docs name the wire fields ``id`` / ``name`` while current live- responses also use ``kb_id`` / ``kb_name``. Both are normalized here.A single batch details request enriches descriptions when possible; thatoptional request never prevents a usable name list from being returned.+ Since IMA caps a details batch at :data:`MAX_DETAIL_IDS` while a listing+ page can hold more, libraries past that point simply come back without a+ description — every one is still listed and selectable.+ The shape is the one the connect flow's API contract expects."""- if not 1 <= limit <= 20:- raise ValueError("IMA knowledge base list limit must be between 1 and 20.")-- data = await self._post(- "search_knowledge_base",- {- "query": str(query or "").strip(),- "cursor": str(cursor or "").strip(),- "limit": limit,- },+ bases, cursor_state = parse_knowledge_bases(+ await self._wire.post(+ "search_knowledge_base",+ {+ "query": str(query or "").strip(),+ "cursor": str(cursor or "").strip(),+ "limit": page_limit(limit),+ },+ ))- entries: list[tuple[str, str]] = []- seen: set[str] = set()- page = data.get("info_list")- if isinstance(page, list):- for raw in page:- if not isinstance(raw, dict):- continue- kb_id = str(raw.get("id") or raw.get("kb_id") or "").strip()- name = str(raw.get("name") or raw.get("kb_name") or "").strip()- if not kb_id or not name or kb_id in seen:- continue- seen.add(kb_id)- entries.append((kb_id, name))details: dict[str, dict[str, Any]] = {}- if entries:+ if bases:try:- details = await self.get_knowledge_bases([kb_id for kb_id, _ in entries])+ details = await self.get_knowledge_bases(+ [base.id for base in bases[:MAX_DETAIL_IDS]]+ )except Exception:# Names from search_knowledge_base are sufficient for selection;# description lookup is intentionally best-effort.details = {}knowledge_bases = []- for kb_id, name in entries:- raw_description = details.get(kb_id, {}).get("description")+ for base in bases:+ raw_description = details.get(base.id, {}).get("description")description = str(raw_description).strip() if raw_description is not None else ""knowledge_bases.append({- "id": kb_id,- "name": name,+ "id": base.id,+ "name": base.name,"description": description or None,})-return {"knowledge_bases": knowledge_bases,- "next_cursor": str(data.get("next_cursor") or ""),- "is_end": bool(data.get("is_end")),+ "next_cursor": cursor_state.next_cursor,+ "is_end": cursor_state.is_end,}async def get_knowledge_bases(self, ids: list[str]) -> dict[str, dict[str, Any]]:- """Return details for at most 20 knowledge base ids."""+ """Return details for at most :data:`MAX_DETAIL_IDS` knowledge base ids."""normalized: list[str] = []for item in ids:kb_id = str(item or "").strip()@@ -311,10 +306,12 @@ class ImaClient:normalized.append(kb_id)if not normalized:return {}- if len(normalized) > 20:- raise ValueError("IMA accepts at most 20 knowledge base IDs per request.")+ if len(normalized) > MAX_DETAIL_IDS:+ raise ValueError(+ f"IMA accepts at most {MAX_DETAIL_IDS} knowledge base IDs per request."+ )- data = await self._post("get_knowledge_base", {"ids": normalized})+ data = await self._wire.post("get_knowledge_base", {"ids": normalized})infos = data.get("infos")if not isinstance(infos, dict):return {}@@ -331,50 +328,34 @@ class ImaClient:return (await self.get_knowledge_bases([kb_id])).get(kb_id, {})-def _validate_media_url(url: str) -> None:- parsed = urlparse(url)- hostname = (parsed.hostname or "").rstrip(".").lower()- if parsed.scheme != "https" or not hostname:- raise ImaAPIError("IMA media URL must use HTTPS.")- if hostname != _COS_ROOT_DOMAIN and not hostname.endswith(f".{_COS_ROOT_DOMAIN}"):- raise ImaAPIError("IMA media URL is outside Tencent COS.")---def _media_headers(raw: Any) -> dict[str, str]:- if not isinstance(raw, dict):- return {}- return {- str(key): str(value)- for key, value in raw.items()- if str(key).lower() not in _FORBIDDEN_MEDIA_HEADERS and isinstance(value, (str, int, float))- }---def _media_filename(url: str, content_type: str | None) -> str:- name = unquote(PurePosixPath(urlparse(url).path).name).strip()- if "." in name:- return name- extensions = {- "application/pdf": ".pdf",- "application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",- "application/json": ".json",- "text/csv": ".csv",- "text/html": ".html",- "text/markdown": ".md",- "text/plain": ".txt",- }- media_type = str(content_type or "").partition(";")[0].strip().lower()- return f"{name or 'ima-document'}{extensions.get(media_type, '')}"+def page_limit(limit: Any, *, maximum: int = MAX_PAGE_LIMIT) -> int:+ """Clamp a caller's page size into IMA's documented ``1..maximum`` range."""+ try:+ value = int(limit)+ except (TypeError, ValueError):+ return maximum+ return max(1, min(value, maximum))+++def _linked_note_id(info: dict[str, Any]) -> str:+ """The note id behind a note-type knowledge item, if this item is one."""+ note_info = info.get("notebook_ext_info")+ if info.get("media_type") != _NOTE_MEDIA_TYPE or not isinstance(note_info, dict):+ return ""+ return str(note_info.get("notebook_id") or note_info.get("doc_id") or "").strip()__all__ = ["API_BASE_URL",+ "MAX_DETAIL_IDS",+ "MAX_IMPORT_URLS",+ "MAX_MEDIA_BYTES",+ "MAX_PAGE_LIMIT","ImaAPIError","ImaAuthError","ImaClient","ImaMediaContent",+ "ImaNotesClient","ImaRateLimitError",- "MAX_MEDIA_BYTES",+ "page_limit",]diff --git a/deeptutor/services/rag/pipelines/ima/envelope.py b/deeptutor/services/rag/pipelines/ima/envelope.pynew file mode 100644index 000000000..bebae83ae--- /dev/null+++ b/deeptutor/services/rag/pipelines/ima/envelope.py@@ -0,0 +1,109 @@+"""The response envelope every Tencent IMA OpenAPI call answers with.++Both IMA modules (``/openapi/wiki/v1`` and ``/openapi/note/v1``) wrap their+payload in a status envelope and return HTTP 200 even for business failures, so+unwrapping it is where *all* IMA error handling happens. This module is the one+place that knows its shape, and the exception classes it raises live here too —+the envelope's status code is what decides which one a caller sees.++Field names+-----------+IMA's own reference documents the envelope as ``{"retcode", "errmsg", "data"}``+while live responses have also been observed using ``{"code", "msg", "data"}``.+Both spellings are accepted (:data:`_CODE_KEYS` / :data:`_MESSAGE_KEYS`): a+mismatch here would not degrade gracefully — reading only one spelling turns+every successful call into "request failed with code None", which is exactly the+kind of failure a wire-format assumption should never be able to cause.++Status codes worth naming are the two classes a caller reacts to differently+from a generic failure: rejected credentials and rate limiting. Everything else+surfaces IMA's own message, which the API documents as safe to show the user.+"""++from __future__ import annotations++from typing import Any++# Accepted spellings of the envelope's status fields, in priority order.+_CODE_KEYS: tuple[str, ...] = ("retcode", "code")+_MESSAGE_KEYS: tuple[str, ...] = ("errmsg", "msg")++# Credential rejection: the client id / API key pair was refused.+_CREDENTIAL_CODES = frozenset({20004, 200002})++# Rate limiting: the key exceeded its call frequency. Both modules' codes.+_RATE_LIMIT_CODES = frozenset({20002, 110021})++# Transient upstream failures IMA documents as retryable. Mapped to a plain+# API error, but with a message that says so.+_RETRYABLE_CODES = frozenset({110010, 100003})+++class ImaAPIError(RuntimeError):+ """Raised when IMA returns an error envelope or an unexpected payload."""+++class ImaAuthError(ImaAPIError):+ """Raised when IMA rejects the client id / API key pair."""+++class ImaRateLimitError(ImaAPIError):+ """Raised when IMA rate-limits the request."""+++def unwrap(payload: Any, *, status_code: int) -> dict[str, Any]:+ """Return the envelope's ``data`` object, or raise the mapped error.++ ``status_code`` is the HTTP status the payload arrived with; it only matters+ when the body is unusable, so the raised message can name it.+ """+ if not isinstance(payload, dict):+ raise ImaAPIError(f"IMA returned an unexpected payload with status {status_code}.")++ code = _first_present(payload, _CODE_KEYS)+ message = _message_of(payload)+ if _is_success(code):+ data = payload.get("data")+ return data if isinstance(data, dict) else {}+ if code in _CREDENTIAL_CODES:+ raise ImaAuthError(message or "IMA rejected the client ID / API key.")+ if code in _RATE_LIMIT_CODES:+ raise ImaRateLimitError(message or "IMA rate limit reached.")+ if code in _RETRYABLE_CODES:+ raise ImaAPIError(message or f"IMA is temporarily unavailable (code {code}). Try again.")+ if code is None:+ # Neither spelling present: the body is not an IMA envelope at all.+ raise ImaAPIError(f"IMA returned an unrecognized response with status {status_code}.")+ raise ImaAPIError(message or f"IMA request failed with code {code}.")+++def _first_present(payload: dict[str, Any], keys: tuple[str, ...]) -> int | None:+ """The first key's value coerced to int, or ``None`` when none is usable."""+ for key in keys:+ if key not in payload:+ continue+ try:+ return int(payload[key])+ except (TypeError, ValueError):+ continue+ return None+++def _message_of(payload: dict[str, Any]) -> str:+ for key in _MESSAGE_KEYS:+ value = payload.get(key)+ if value:+ return str(value).strip()+ return ""+++def _is_success(code: int | None) -> bool:+ return code == 0+++__all__ = [+ "ImaAPIError",+ "ImaAuthError",+ "ImaRateLimitError",+ "unwrap",+]diff --git a/deeptutor/services/rag/pipelines/ima/inventory.py b/deeptutor/services/rag/pipelines/ima/inventory.pynew file mode 100644index 000000000..a4d7e20b1--- /dev/null+++ b/deeptutor/services/rag/pipelines/ima/inventory.py@@ -0,0 +1,209 @@+"""What a connected IMA library actually contains — its document inventory.++Retrieval answers "what does the material say"; it cannot answer "what is in+here" or "did I add X". For an indexed KB the answer is a directory walk. For an+IMA library the equivalent is ``get_knowledge_list``, which browses the library's+folder tree, and this module turns that into the same flat list of relative paths+:mod:`deeptutor.knowledge.manifest` produces for a local KB — so "list what's in+this knowledge base" works the same whether the documents sit on disk or in IMA.++Two properties make it usable from the manifest layer:++* **Blocking.** The manifest is deliberately synchronous (it is called from a+ worker thread, and from the chat pipeline's prompt assembly), so the traversal+ uses the transport's blocking flavour instead of forcing that whole path async.+* **Cached.** A manifest is rebuilt on every turn's system prompt; without a+ cache that would be a fresh IMA round-trip per turn. Entries expire after+ :data:`CACHE_TTL_SECONDS`, which is short enough that a document added in IMA+ shows up almost immediately and long enough that a burst of turns costs one+ traversal.++The traversal is bounded on purpose (:data:`MAX_REQUESTS`): a huge library must+not stall prompt assembly. When the budget runs out the result is marked+incomplete and the count it reports is a lower bound, never a confident total.+"""++from __future__ import annotations++from collections import deque+from dataclasses import dataclass+import logging+import threading+import time+from typing import Any, Mapping, Optional++from .config import ImaNotConfiguredError, resolve_kb_config++logger = logging.getLogger(__name__)++# Requests one traversal may spend. With IMA's 50-item pages this covers the+# first few hundred documents, including a level or two of folders.+MAX_REQUESTS = 8++PAGE_SIZE = 50++CACHE_TTL_SECONDS = 60.0++# Failures are cached too, briefly. Without this, an unreachable library would be+# retried on every single turn's prompt assembly — paying the timeout each time.+FAILURE_TTL_SECONDS = 30.0++# This runs while a turn's system prompt is being assembled, so it must never be+# what makes a turn feel slow: a stalled IMA gives up quickly rather than holding+# the default 30 s.+TIMEOUT_SECONDS = 6.0++# Folder nesting to descend. Deep trees are truncated rather than walked+# exhaustively — the inventory is an overview, not a mirror.+MAX_DEPTH = 3+++@dataclass(frozen=True, slots=True)+class ImaInventory:+ """A connected IMA library's documents, as folder-relative paths."""++ documents: tuple[str, ...] = ()+ complete: bool = True+ """False when the request budget ran out — ``documents`` is then a prefix."""+++# key -> (expires_at, inventory or None). ``None`` is a cached *failure*.+_CACHE: dict[str, tuple[float, Optional[ImaInventory]]] = {}+_CACHE_LOCK = threading.Lock()++# Distinguishes "nothing cached" from "a cached failure", which is itself a+# ``None`` result worth honouring.+_MISS = object()+++def read_inventory(+ entry: Mapping[str, Any],+ *,+ client_factory=None,+ use_cache: bool = True,+) -> Optional[ImaInventory]:+ """Return the inventory of the IMA library *entry* points at.++ ``None`` means "cannot be determined" (missing credentials, or IMA+ unreachable) — distinct from an empty library, which is an empty inventory.+ ``client_factory`` (config → client) is the test seam.+ """+ try:+ config = resolve_kb_config(dict(entry))+ except ImaNotConfiguredError:+ return None++ cache_key = f"{config.client_id}:{config.knowledge_base_id}"+ if use_cache:+ cached = _cached(cache_key)+ if cached is not _MISS:+ return cached # type: ignore[return-value]++ if client_factory is not None:+ client = client_factory(config)+ else:+ from .client import ImaClient++ client = ImaClient(config, timeout=TIMEOUT_SECONDS)++ try:+ inventory = _traverse(client, config.knowledge_base_id)+ except Exception as exc:+ logger.warning(+ "Could not read the IMA document inventory for '%s' (%s)",+ config.knowledge_base_id,+ type(exc).__name__,+ )+ if use_cache:+ _store(cache_key, None, ttl=FAILURE_TTL_SECONDS)+ return None++ if use_cache:+ _store(cache_key, inventory, ttl=CACHE_TTL_SECONDS)+ return inventory+++def clear_cache() -> None:+ """Drop every cached inventory (used by tests and after a KB is re-bound)."""+ with _CACHE_LOCK:+ _CACHE.clear()+++def _traverse(client, root_id: str) -> ImaInventory:+ """Breadth-first walk of the library, folder paths flattened like a local KB.++ ``truncated`` records whether anything was left unvisited — a folder still+ queued, a page still to fetch, or a subtree below :data:`MAX_DEPTH`. It is+ tracked explicitly rather than inferred from the request count so a traversal+ that happens to finish on its last allowed request is still reported as+ complete.+ """+ documents: list[str] = []+ seen_folders: set[str] = set()+ # (folder_id, path prefix, depth); the root folder's id is the library id.+ queue: deque[tuple[str, str, int]] = deque([(root_id, "", 0)])+ requests = 0+ truncated = False++ while queue:+ folder_id, prefix, depth = queue.popleft()+ cursor = ""+ while True:+ if requests >= MAX_REQUESTS:+ truncated = True+ break+ page = client.get_knowledge_list_sync(+ folder_id=folder_id,+ cursor=cursor,+ limit=PAGE_SIZE,+ )+ requests += 1+ for document in page.documents:+ documents.append(f"{prefix}{document.title}" if prefix else document.title)+ for folder in page.folders:+ if folder.folder_id in seen_folders or folder.folder_id == folder_id:+ continue+ seen_folders.add(folder.folder_id)+ if depth >= MAX_DEPTH:+ truncated = True+ continue+ queue.append((folder.folder_id, f"{prefix}{folder.name}/", depth + 1))+ cursor = page.next_cursor+ if page.is_end or not cursor:+ break+ if truncated and requests >= MAX_REQUESTS:+ break++ return ImaInventory(documents=tuple(documents), complete=not truncated and not queue)+++def _cached(key: str) -> Any:+ """The cached value, or :data:`_MISS` when absent or expired."""+ now = time.monotonic()+ with _CACHE_LOCK:+ hit = _CACHE.get(key)+ if hit is None:+ return _MISS+ expires_at, inventory = hit+ if now >= expires_at:+ _CACHE.pop(key, None)+ return _MISS+ return inventory+++def _store(key: str, inventory: Optional[ImaInventory], *, ttl: float) -> None:+ with _CACHE_LOCK:+ _CACHE[key] = (time.monotonic() + ttl, inventory)+++__all__ = [+ "CACHE_TTL_SECONDS",+ "FAILURE_TTL_SECONDS",+ "MAX_DEPTH",+ "MAX_REQUESTS",+ "PAGE_SIZE",+ "TIMEOUT_SECONDS",+ "ImaInventory",+ "clear_cache",+ "read_inventory",+]diff --git a/deeptutor/services/rag/pipelines/ima/media.py b/deeptutor/services/rag/pipelines/ima/media.pynew file mode 100644index 000000000..309faa079--- /dev/null+++ b/deeptutor/services/rag/pipelines/ima/media.py@@ -0,0 +1,182 @@+"""Fetching and reading one IMA item's actual content.++An IMA knowledge item is either a *note* (whose text the notes API returns+directly) or a *file* (which IMA hands over as a short-lived Tencent COS+download URL). This module owns the file half — the download and the text+extraction — so both retrieval (``pipeline``) and the capability's ``ima_read``+tool read documents through exactly one implementation.++Security boundary+-----------------+The download URL arrives inside an API response, so it is treated as untrusted+input: it must be HTTPS and inside Tencent COS (:data:`_COS_ROOT_DOMAIN`), which+prevents a tampered or buggy response from turning retrieval into an SSRF+primitive. Redirects are not followed, IMA's own credentials are never attached+to this separate client, and hop-by-hop / identity headers are stripped from+whatever header set the response asked us to send. Size is capped+(:data:`MAX_MEDIA_BYTES`) both by the advertised ``content-length`` and while+streaming, so a mis-sized response cannot exhaust memory.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from pathlib import PurePath, PurePosixPath+from typing import Optional+from urllib.parse import unquote, urlparse++import httpx++from deeptutor.utils.document_extractor import (+ SUPPORTED_DOC_EXTENSIONS,+ extract_text_from_bytes,+)++from .envelope import ImaAPIError++# Official IMA media links are short-lived Tencent COS URLs; the downloader+# refuses anything outside that boundary.+_COS_ROOT_DOMAIN = "myqcloud.com"++# Headers we never forward, whatever the API response asks for: hop-by-hop+# fields and anything that would carry identity to COS.+_FORBIDDEN_MEDIA_HEADERS = frozenset(+ {+ "connection",+ "content-length",+ "cookie",+ "host",+ "proxy-authorization",+ "transfer-encoding",+ }+)++MAX_MEDIA_BYTES = 20 * 1024 * 1024++_CONTENT_TYPE_EXTENSIONS: dict[str, str] = {+ "application/pdf": ".pdf",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",+ "application/json": ".json",+ "text/csv": ".csv",+ "text/html": ".html",+ "text/markdown": ".md",+ "text/plain": ".txt",+}+++@dataclass(frozen=True)+class ImaMediaContent:+ """One IMA item's content, as either note text or downloaded file bytes."""++ text: str = ""+ data: bytes = b""+ filename: str = ""+++async def download_media(+ url: str,+ *,+ headers: dict[str, str],+ timeout: float,+ transport: Optional[httpx.AsyncBaseTransport] = None,+) -> ImaMediaContent:+ """Stream a COS media URL into memory, bounded by :data:`MAX_MEDIA_BYTES`."""+ validate_media_url(url)+ async with httpx.AsyncClient(+ timeout=timeout,+ transport=transport,+ follow_redirects=False,+ ) as client:+ async with client.stream("GET", url, headers=headers) as response:+ response.raise_for_status()+ length = response.headers.get("content-length")+ if length and length.isdigit() and int(length) > MAX_MEDIA_BYTES:+ raise ImaAPIError("IMA media exceeds the 20 MB retrieval limit.")+ body = bytearray()+ async for chunk in response.aiter_bytes():+ body.extend(chunk)+ if len(body) > MAX_MEDIA_BYTES:+ raise ImaAPIError("IMA media exceeds the 20 MB retrieval limit.")+ filename = media_filename(url, response.headers.get("content-type"))+ return ImaMediaContent(data=bytes(body), filename=filename)+++async def extract_text(+ media: ImaMediaContent | None,+ *title_candidates: str,+ max_chars: int,+) -> str:+ """Plain text for *media*, truncated to *max_chars* (``""`` when unreadable).++ Note text is already plain. File bytes are decoded by+ :func:`~deeptutor.utils.document_extractor.extract_text_from_bytes`, which+ needs a filename to pick a decoder — the download's own filename or the+ item title, whichever carries a supported extension. Extraction is CPU-bound+ (PDF / Office parsing), so it runs in a worker thread.+ """+ if media is None:+ return ""+ if media.text:+ return media.text[:max_chars].strip()+ if not media.data:+ return ""+ filename = _extractable_filename(media.filename, *title_candidates)+ if not filename:+ return ""+ return await asyncio.to_thread(+ extract_text_from_bytes,+ filename,+ media.data,+ max_bytes=MAX_MEDIA_BYTES,+ max_chars=max_chars,+ )+++def validate_media_url(url: str) -> None:+ parsed = urlparse(url)+ hostname = (parsed.hostname or "").rstrip(".").lower()+ if parsed.scheme != "https" or not hostname:+ raise ImaAPIError("IMA media URL must use HTTPS.")+ if hostname != _COS_ROOT_DOMAIN and not hostname.endswith(f".{_COS_ROOT_DOMAIN}"):+ raise ImaAPIError("IMA media URL is outside Tencent COS.")+++def media_headers(raw: object) -> dict[str, str]:+ """The subset of a response's suggested download headers we will forward."""+ if not isinstance(raw, dict):+ return {}+ return {+ str(key): str(value)+ for key, value in raw.items()+ if str(key).lower() not in _FORBIDDEN_MEDIA_HEADERS and isinstance(value, (str, int, float))+ }+++def media_filename(url: str, content_type: str | None) -> str:+ """A filename for the download, inferring an extension when the path lacks one."""+ name = unquote(PurePosixPath(urlparse(url).path).name).strip()+ if "." in name:+ return name+ media_type = str(content_type or "").partition(";")[0].strip().lower()+ return f"{name or 'ima-document'}{_CONTENT_TYPE_EXTENSIONS.get(media_type, '')}"+++def _extractable_filename(*candidates: str) -> str:+ for candidate in candidates:+ if candidate and PurePath(candidate).suffix.lower() in SUPPORTED_DOC_EXTENSIONS:+ return candidate+ return ""+++__all__ = [+ "MAX_MEDIA_BYTES",+ "ImaMediaContent",+ "download_media",+ "extract_text",+ "media_filename",+ "media_headers",+ "validate_media_url",+]diff --git a/deeptutor/services/rag/pipelines/ima/models.py b/deeptutor/services/rag/pipelines/ima/models.pynew file mode 100644index 000000000..62d7d6fa1--- /dev/null+++ b/deeptutor/services/rag/pipelines/ima/models.py@@ -0,0 +1,343 @@+"""Typed views over IMA's wire payloads, and the parsers that produce them.++Every IMA list response is a bag of loosely-typed dicts whose field names differ+between the documented reference and live responses, and whose entries mix+*documents* with *folders* — ``get_knowledge_list`` returns both by design, and+``search_knowledge`` also matches folder names. Parsing that in the client would+scatter the same defensive ``str(raw.get(...) or "")`` over every method and let+a folder leak into retrieval results as a document with no content (which is how+a folder used to end up cited as a source).++So the wire shapes are decoded exactly once, here:++* :func:`parse_knowledge_page` splits a page into documents and folders,+ discarding entries that identify as neither;+* the notes payloads are deeply nested (``docs[].doc.basic_info.docid``), which+ :func:`parse_note` flattens into something a tool can render directly.++These types carry no behaviour and no I/O, so the client, the inventory reader,+the retrieval pipeline and the capability's tools can all share them without a+cycle.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Mapping+++@dataclass(frozen=True, slots=True)+class ImaDocument:+ """One document in a knowledge base (a file, a web page, or a linked note)."""++ media_id: str+ title: str+ parent_folder_id: str = ""+ highlight: str = ""+ """Matched snippet — search results only; empty for a plain listing."""+++@dataclass(frozen=True, slots=True)+class ImaFolder:+ """One folder in a knowledge base's tree."""++ folder_id: str+ name: str+ file_number: int = 0+ folder_number: int = 0+ parent_folder_id: str = ""+++@dataclass(frozen=True, slots=True)+class ImaKnowledgePage:+ """One cursor page of a knowledge base's contents."""++ documents: tuple[ImaDocument, ...] = ()+ folders: tuple[ImaFolder, ...] = ()+ path: tuple[str, ...] = ()+ """Breadcrumb folder names for the listed location, outermost first."""++ next_cursor: str = ""+ is_end: bool = False+++@dataclass(frozen=True, slots=True)+class ImaKnowledgeBase:+ """One knowledge base available to a credential pair."""++ id: str+ name: str+ description: str | None = None+++@dataclass(frozen=True, slots=True)+class ImaNote:+ """One note, flattened from the notes API's nested payload."""++ note_id: str+ title: str+ summary: str = ""+ folder_name: str = ""+ created_at: int = 0+ """Unix milliseconds, or ``0`` when absent."""++ updated_at: int = 0+++@dataclass(frozen=True, slots=True)+class ImaNotebook:+ """One notebook (a notes folder)."""++ folder_id: str+ name: str+ note_number: int = 0+++@dataclass(frozen=True, slots=True)+class ImaImportedUrl:+ """The per-URL verdict ``import_urls`` reports."""++ url: str+ ok: bool+ media_id: str = ""+ code: int = 0+++@dataclass(frozen=True, slots=True)+class ImaPageCursor:+ """Cursor state shared by every paginated notes/knowledge response."""++ next_cursor: str = ""+ is_end: bool = False+++# ---------------------------------------------------------------------------+# Knowledge base parsing+# ---------------------------------------------------------------------------++# ``get_knowledge_list`` names the document array ``knowledge_list`` while+# ``search_knowledge`` names it ``info_list``; folders have been observed under+# both ``folder_list`` and ``folders``. Accepting each spelling keeps one parser+# for both calls.+_DOCUMENT_KEYS: tuple[str, ...] = ("knowledge_list", "info_list")+_FOLDER_KEYS: tuple[str, ...] = ("folder_list", "folders")+++def parse_knowledge_page(data: Mapping[str, Any]) -> ImaKnowledgePage:+ """Decode one page of ``get_knowledge_list`` / ``search_knowledge``."""+ documents: list[ImaDocument] = []+ folders: list[ImaFolder] = []+ seen_documents: set[str] = set()+ seen_folders: set[str] = set()++ for raw in _entries(data, _DOCUMENT_KEYS):+ # A folder can appear inside the document array (search matches folder+ # names, and a listing mixes both), identified by carrying a folder id+ # and no media id. Route it to the folder list instead of inventing a+ # content-less document.+ folder = _folder_from(raw)+ if folder is not None and not _text(raw, "media_id"):+ if folder.folder_id not in seen_folders:+ seen_folders.add(folder.folder_id)+ folders.append(folder)+ continue+ document = _document_from(raw)+ if document is not None and document.media_id not in seen_documents:+ seen_documents.add(document.media_id)+ documents.append(document)++ for raw in _entries(data, _FOLDER_KEYS):+ folder = _folder_from(raw)+ if folder is not None and folder.folder_id not in seen_folders:+ seen_folders.add(folder.folder_id)+ folders.append(folder)++ return ImaKnowledgePage(+ documents=tuple(documents),+ folders=tuple(folders),+ path=_breadcrumb(data.get("current_path")),+ next_cursor=str(data.get("next_cursor") or ""),+ is_end=bool(data.get("is_end")),+ )+++def parse_knowledge_bases(data: Mapping[str, Any]) -> tuple[list[ImaKnowledgeBase], ImaPageCursor]:+ """Decode one page of ``search_knowledge_base``.++ The reference names the fields ``id`` / ``name``; live responses have also+ used ``kb_id`` / ``kb_name``. Both are accepted.+ """+ bases: list[ImaKnowledgeBase] = []+ seen: set[str] = set()+ for raw in _entries(data, ("info_list",)):+ kb_id = _text(raw, "id") or _text(raw, "kb_id")+ name = _text(raw, "name") or _text(raw, "kb_name")+ if not kb_id or not name or kb_id in seen:+ continue+ seen.add(kb_id)+ bases.append(ImaKnowledgeBase(id=kb_id, name=name))+ cursor = ImaPageCursor(+ next_cursor=str(data.get("next_cursor") or ""),+ is_end=bool(data.get("is_end")),+ )+ return bases, cursor+++def parse_imported_urls(data: Mapping[str, Any]) -> list[ImaImportedUrl]:+ """Decode ``import_urls``' per-URL results."""+ results: list[ImaImportedUrl] = []+ for raw in _entries(data, ("url_data_list", "info_list", "data_list")):+ url = _text(raw, "url")+ if not url:+ continue+ code = _int(raw.get("ret_code"))+ results.append(+ ImaImportedUrl(+ url=url,+ ok=code == 0,+ media_id=_text(raw, "media_id"),+ code=code,+ )+ )+ return results+++# ---------------------------------------------------------------------------+# Notes parsing+# ---------------------------------------------------------------------------+++def parse_note(raw: Any) -> ImaNote | None:+ """Flatten one note entry from any of the notes list/search payloads.++ Handles the three nestings the notes API uses for the same object:+ ``{"doc": {"basic_info": {...}}}`` (search), ``{"basic_info": {...}}``+ (listing) and a bare basic-info dict.+ """+ basic = _basic_info(raw, outer_keys=("doc",))+ if basic is None:+ return None+ note_id = _text(basic, "docid") or _text(basic, "doc_id")+ if not note_id:+ return None+ if _int(basic.get("status")) == 1: # deleted+ return None+ return ImaNote(+ note_id=note_id,+ title=_text(basic, "title") or "(untitled)",+ summary=_text(basic, "summary"),+ folder_name=_text(basic, "folder_name"),+ created_at=_int(basic.get("create_time")),+ updated_at=_int(basic.get("modify_time")),+ )+++def parse_notebook(raw: Any) -> ImaNotebook | None:+ """Flatten one notebook entry from ``list_note_folder_by_cursor``."""+ basic = _basic_info(raw, outer_keys=("folder",))+ if basic is None:+ return None+ folder_id = _text(basic, "folder_id")+ if not folder_id or _int(basic.get("status")) == 1:+ return None+ return ImaNotebook(+ folder_id=folder_id,+ name=_text(basic, "name") or "(unnamed)",+ note_number=_int(basic.get("note_number")),+ )+++# ---------------------------------------------------------------------------+# helpers+# ---------------------------------------------------------------------------+++def _entries(data: Mapping[str, Any], keys: tuple[str, ...]) -> list[Mapping[str, Any]]:+ for key in keys:+ value = data.get(key)+ if isinstance(value, list):+ return [item for item in value if isinstance(item, Mapping)]+ return []+++def _document_from(raw: Mapping[str, Any]) -> ImaDocument | None:+ media_id = _text(raw, "media_id")+ title = _text(raw, "title")+ if not media_id and not title:+ return None+ return ImaDocument(+ media_id=media_id,+ title=title or media_id,+ parent_folder_id=_text(raw, "parent_folder_id"),+ highlight=_text(raw, "highlight_content"),+ )+++def _folder_from(raw: Mapping[str, Any]) -> ImaFolder | None:+ folder_id = _text(raw, "folder_id")+ if not folder_id:+ return None+ return ImaFolder(+ folder_id=folder_id,+ name=_text(raw, "name") or _text(raw, "title") or folder_id,+ file_number=_int(raw.get("file_number")),+ folder_number=_int(raw.get("folder_number")),+ parent_folder_id=_text(raw, "parent_folder_id"),+ )+++def _breadcrumb(raw: Any) -> tuple[str, ...]:+ if not isinstance(raw, list):+ return ()+ names = []+ for entry in raw:+ if not isinstance(entry, Mapping):+ continue+ name = _text(entry, "name")+ if name:+ names.append(name)+ return tuple(names)+++def _basic_info(raw: Any, *, outer_keys: tuple[str, ...]) -> Mapping[str, Any] | None:+ """Peel the notes API's wrapper layers down to the basic-info dict."""+ if not isinstance(raw, Mapping):+ return None+ node: Mapping[str, Any] = raw+ for key in outer_keys:+ inner = node.get(key)+ if isinstance(inner, Mapping):+ node = inner+ inner = node.get("basic_info")+ if isinstance(inner, Mapping):+ node = inner+ return node+++def _text(raw: Mapping[str, Any], key: str) -> str:+ value = raw.get(key)+ return str(value).strip() if value is not None else ""+++def _int(value: Any) -> int:+ try:+ return int(value)+ except (TypeError, ValueError):+ return 0+++__all__ = [+ "ImaDocument",+ "ImaFolder",+ "ImaImportedUrl",+ "ImaKnowledgeBase",+ "ImaKnowledgePage",+ "ImaNote",+ "ImaNotebook",+ "ImaPageCursor",+ "parse_imported_urls",+ "parse_knowledge_bases",+ "parse_knowledge_page",+ "parse_note",+ "parse_notebook",+]diff --git a/deeptutor/services/rag/pipelines/ima/notes.py b/deeptutor/services/rag/pipelines/ima/notes.pynew file mode 100644index 000000000..994bb0b36--- /dev/null+++ b/deeptutor/services/rag/pipelines/ima/notes.py@@ -0,0 +1,240 @@+"""Client for Tencent IMA's notes OpenAPI (``/openapi/note/v1``).++Notes are the other half of a user's IMA account: a knowledge base holds files+and web pages, while notes are the text the user writes, and a note can also be+linked *into* a knowledge base (media type 11) — which is why retrieval already+needed this module to read a matched note's body.++Exposed here: searching notes (with IMA's own sort orders, the only place in the+API where "my most recent items" is answerable, since notes carry create/modify+timestamps and knowledge items do not), browsing notebooks, reading a note's+plain text, and the two additive writes — create a note, append to a note.+Nothing deletes or overwrites.++Field-name compatibility+------------------------+The reference names the note identifier ``doc_id`` while other IMA surfaces have+used ``note_id`` for the same value. Requests send both spellings: unknown body+fields are ignored by the API, so sending both is strictly safer than betting on+one and having every call 404.+"""++from __future__ import annotations++from typing import Any, Optional++import httpx++from .config import ImaConfig+from .models import ImaNote, ImaNotebook, ImaPageCursor, parse_note, parse_notebook+from .transport import DEFAULT_TIMEOUT, NOTE_PREFIX, ImaTransport++# ``content_format`` / ``target_content_format`` enum values IMA documents.+MARKDOWN_FORMAT = 1+PLAIN_TEXT_FORMAT = 0++# ``sort_type`` values. Recency is the default because "my latest notes" is the+# question this module exists to answer.+SORT_BY_UPDATED = 0+SORT_BY_CREATED = 1+SORT_BY_TITLE = 2+SORT_BY_SIZE = 3+SORT_TYPES = frozenset({SORT_BY_UPDATED, SORT_BY_CREATED, SORT_BY_TITLE, SORT_BY_SIZE})++# ``search_type`` values: match titles only, or full text.+SEARCH_BY_TITLE = 0+SEARCH_BY_CONTENT = 1++# The notes list endpoints are cursor-paginated; the notebook listing starts at+# the literal cursor "0" rather than an empty string.+NOTEBOOK_FIRST_CURSOR = "0"++MAX_NOTE_PAGE_LIMIT = 50+++class ImaNotesClient:+ """Stateless wrapper over the IMA notes OpenAPI."""++ def __init__(+ self,+ config: ImaConfig,+ *,+ timeout: float = DEFAULT_TIMEOUT,+ transport: Optional[httpx.AsyncBaseTransport] = None,+ ) -> None:+ self._wire = ImaTransport(config, timeout=timeout, transport=transport)++ async def _post(self, method: str, body: dict[str, Any]) -> dict[str, Any]:+ return await self._wire.post(method, body, prefix=NOTE_PREFIX)++ # ----- reading --------------------------------------------------------++ async def search_notes(+ self,+ query: str = "",+ *,+ by_content: bool = False,+ sort_type: int = SORT_BY_UPDATED,+ limit: int = 20,+ start: int = 0,+ ) -> tuple[list[ImaNote], bool]:+ """Search notes, newest-updated first by default.++ An empty *query* lists notes in ``sort_type`` order, which is how "my+ latest notes" is answered. Returns the notes plus whether IMA reported+ the end of the result set. Pagination is a half-open ``[start, end)``+ window rather than a cursor.+ """+ size = _note_limit(limit)+ text = str(query or "").strip()+ search_type = SEARCH_BY_CONTENT if by_content else SEARCH_BY_TITLE+ data = await self._post(+ "search_note_book",+ {+ "search_type": search_type,+ "sort_type": sort_type if sort_type in SORT_TYPES else SORT_BY_UPDATED,+ "query_info": ({"content": text} if by_content else {"title": text}),+ "start": max(0, int(start)),+ "end": max(0, int(start)) + size,+ },+ )+ notes = _notes_from(data, ("docs", "note_book_list"))+ return notes[:size], bool(data.get("is_end"))++ async def list_notebooks(+ self,+ *,+ cursor: str = NOTEBOOK_FIRST_CURSOR,+ limit: int = MAX_NOTE_PAGE_LIMIT,+ ) -> tuple[list[ImaNotebook], ImaPageCursor]:+ """Return one page of the user's notebooks."""+ data = await self._post(+ "list_note_folder_by_cursor",+ {"cursor": str(cursor or NOTEBOOK_FIRST_CURSOR), "limit": _note_limit(limit)},+ )+ notebooks: list[ImaNotebook] = []+ raw_list = data.get("note_book_folders")+ if isinstance(raw_list, list):+ for raw in raw_list:+ notebook = parse_notebook(raw)+ if notebook is not None:+ notebooks.append(notebook)+ return notebooks, _cursor_of(data)++ async def list_notes(+ self,+ *,+ folder_id: str = "",+ cursor: str = "",+ limit: int = MAX_NOTE_PAGE_LIMIT,+ ) -> tuple[list[ImaNote], ImaPageCursor]:+ """Return one page of notes inside *folder_id* (root when omitted)."""+ body: dict[str, Any] = {"cursor": str(cursor or ""), "limit": _note_limit(limit)}+ folder = str(folder_id or "").strip()+ if folder:+ body["folder_id"] = folder+ data = await self._post("list_note_by_folder_id", body)+ return _notes_from(data, ("note_book_list", "docs")), _cursor_of(data)++ async def get_note_content(self, note_id: str, *, as_markdown: bool = False) -> str:+ """Return one note's text, or ``""`` when it has none.++ Plain text is IMA's recommended (and only reliably supported) target+ format; *as_markdown* is accepted for callers that want to try the+ Markdown variant.+ """+ identifier = str(note_id or "").strip()+ if not identifier:+ return ""+ data = await self._post(+ "get_doc_content",+ {+ "doc_id": identifier,+ "note_id": identifier,+ "target_content_format": MARKDOWN_FORMAT if as_markdown else PLAIN_TEXT_FORMAT,+ },+ )+ return str(data.get("content") or "").strip()++ # ----- additive writes ------------------------------------------------++ async def create_note(self, content: str, *, folder_id: str = "") -> str:+ """Create a note from Markdown and return its id.++ IMA takes the title from the Markdown body's leading heading, so callers+ that want a specific title should include one.+ """+ body_text = str(content or "").strip()+ if not body_text:+ raise ValueError("Note content is required.")+ body: dict[str, Any] = {"content_format": MARKDOWN_FORMAT, "content": body_text}+ folder = str(folder_id or "").strip()+ if folder:+ body["folder_id"] = folder+ data = await self._post("import_doc", body)+ return str(data.get("doc_id") or data.get("note_id") or "").strip()++ async def append_note(self, note_id: str, content: str) -> str:+ """Append Markdown to an existing note and return its id.++ Appending mutates a note the user owns and cannot be undone, so callers+ must have an explicitly identified target — never a guessed one.+ """+ identifier = str(note_id or "").strip()+ if not identifier:+ raise ValueError("A target note id is required.")+ body_text = str(content or "").strip()+ if not body_text:+ raise ValueError("Content to append is required.")+ data = await self._post(+ "append_doc",+ {+ "doc_id": identifier,+ "note_id": identifier,+ "content_format": MARKDOWN_FORMAT,+ "content": body_text,+ },+ )+ return str(data.get("doc_id") or data.get("note_id") or identifier).strip()+++def _notes_from(data: dict[str, Any], keys: tuple[str, ...]) -> list[ImaNote]:+ for key in keys:+ raw_list = data.get(key)+ if not isinstance(raw_list, list):+ continue+ notes = [note for note in (parse_note(raw) for raw in raw_list) if note is not None]+ if notes or raw_list:+ return notes+ return []+++def _cursor_of(data: dict[str, Any]) -> ImaPageCursor:+ return ImaPageCursor(+ next_cursor=str(data.get("next_cursor") or ""),+ is_end=bool(data.get("is_end")),+ )+++def _note_limit(limit: Any) -> int:+ try:+ value = int(limit)+ except (TypeError, ValueError):+ return MAX_NOTE_PAGE_LIMIT+ return max(1, min(value, MAX_NOTE_PAGE_LIMIT))+++__all__ = [+ "MARKDOWN_FORMAT",+ "MAX_NOTE_PAGE_LIMIT",+ "NOTEBOOK_FIRST_CURSOR",+ "PLAIN_TEXT_FORMAT",+ "SEARCH_BY_CONTENT",+ "SEARCH_BY_TITLE",+ "SORT_BY_CREATED",+ "SORT_BY_SIZE",+ "SORT_BY_TITLE",+ "SORT_BY_UPDATED",+ "SORT_TYPES",+ "ImaNotesClient",+]diff --git a/deeptutor/services/rag/pipelines/ima/pipeline.py b/deeptutor/services/rag/pipelines/ima/pipeline.pyindex 701c97b21..7a30c8712 100644--- a/deeptutor/services/rag/pipelines/ima/pipeline.py+++ b/deeptutor/services/rag/pipelines/ima/pipeline.py@@ -4,28 +4,28 @@ Implements the same contract as the other pipelines (see ``..base.RAGPipeline``)but owns no index: an ``ima`` KB is a connection pointer (``type: ima`` in``kb_config.json``) to a library the user keeps in IMA and curates there. Only:meth:`search` does real work — it resolves the KB's credentials, asks IMA for-matching passages, and shapes them for the ``rag`` tool. Documents are added in-IMA, so :meth:`initialize` / :meth:`add_documents` are not part of this engine's-job and fail with a clear message; :meth:`delete` is a no-op because deleting the-KB only drops DeepTutor's pointer (handled by the manager) and must never touch-the user's IMA library.+matching passages, tops the thin ones up with real source text, and shapes them+for the ``rag`` tool. Documents are added in IMA (or through the IMA capability's+own tools), so :meth:`initialize` / :meth:`add_documents` are not part of this+engine's job and fail with a clear message; :meth:`delete` is a no-op because+deleting the KB only drops DeepTutor's pointer (handled by the manager) and must+never touch the user's IMA library.++The retrieval *policy* — which matches deserve a full-text fetch — lives in+:mod:`.sources`; this module only orchestrates."""from __future__ import annotationsimport asyncioimport logging-from pathlib import PurePathfrom typing import Any, Dict, List, Optionalfrom deeptutor.runtime.home import get_runtime_data_rootfrom deeptutor.services.rag.provider_binding import load_kb_config_entry-from deeptutor.utils.document_extractor import (- SUPPORTED_DOC_EXTENSIONS,- extract_text_from_bytes,-)-from .client import MAX_MEDIA_BYTES, ImaMediaContent+from . import media as media_ops+from . import sources as source_policyfrom .config import ImaNotConfiguredError, resolve_kb_configlogger = logging.getLogger(__name__)@@ -37,11 +37,7 @@ DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")# highlight snippet per item rather than whole documents, so this is a passage# budget, not a document budget._DEFAULT_TOP_K = 10--# Full-document retrieval is only a fallback for title-only IMA matches. Keep-# its network and prompt footprint predictable even when ``top_k`` is large.-_MAX_FULLTEXT_ITEMS = 3-_MAX_FULLTEXT_CHARS = 12_000+_MAX_TOP_K = 50class ImaPipeline:@@ -68,7 +64,7 @@ class ImaPipeline:requested = int(kwargs.get("top_k") or _DEFAULT_TOP_K)except (TypeError, ValueError):return _DEFAULT_TOP_K- return max(1, min(requested, 50))+ return max(1, min(requested, _MAX_TOP_K))# ----- retrieval ------------------------------------------------------@@ -80,14 +76,14 @@ class ImaPipeline:try:client = self._client(config)- items = await client.search_knowledge(query, limit=self._top_k(kwargs))+ page = await client.search_knowledge(query, limit=self._top_k(kwargs))except Exception as exc:self.logger.error("IMA search failed for '%s': %s", kb_name, exc)return self._error_result(query, exc, error_type="retrieval_error")- sources = _sources_from_items(items)- await self._hydrate_title_only_sources(client, sources)- content = _render_context(sources)+ sources = source_policy.documents_to_sources(page.documents)+ await self._hydrate(client, sources)+ content = source_policy.render_context(sources)return {"query": query,"answer": content,@@ -96,27 +92,41 @@ class ImaPipeline:"provider": PROVIDER,}- async def _hydrate_title_only_sources(self, client, sources: list[dict[str, Any]]) -> None:- remaining = _MAX_FULLTEXT_ITEMS- for source in sources:- if remaining == 0:- break- if source["content"] or not source["chunk_id"]:- continue- remaining -= 1- try:- media = await client.get_media_content(source["chunk_id"])- source["content"] = await _extract_media_text(media, source["title"])- except Exception as exc:- # Search results remain useful as title-only references. One- # unavailable document must not discard the other matches.- # HTTP errors may contain a signed COS URL; log only the error+ async def _hydrate(self, client, sources: list[dict[str, Any]]) -> None:+ """Replace thin or missing snippets with real source text, concurrently.++ Each fetch is independent, so they run together — a search that needs+ four documents costs one round-trip's latency, not four. A document that+ cannot be loaded keeps its snippet (or stays a title-only reference):+ one unavailable file must never discard the other matches.+ """+ targets = source_policy.hydration_targets(sources)+ if not targets:+ return+ results = await asyncio.gather(+ *(self._fetch_text(client, sources[index]) for index in targets),+ return_exceptions=True,+ )+ for index, result in zip(targets, results):+ if isinstance(result, BaseException):+ # HTTP errors may embed a signed COS URL; log only the error# class so short-lived download credentials never reach logs.self.logger.warning("Could not load IMA media '%s' (%s)",- source["chunk_id"],- type(exc).__name__,+ sources[index]["chunk_id"],+ type(result).__name__,)+ elif result:+ sources[index]["content"] = result++ @staticmethod+ async def _fetch_text(client, source: dict[str, Any]) -> str:+ media = await client.get_media_content(source["chunk_id"])+ return await media_ops.extract_text(+ media,+ source["title"],+ max_chars=source_policy.MAX_FULLTEXT_CHARS,+ )def _error_result(self, query: str, exc: Exception, *, error_type: str) -> Dict[str, Any]:return {@@ -147,64 +157,4 @@ class ImaPipeline:return True-def _sources_from_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Map IMA search items into DeepTutor's ``sources`` shape.-- ``highlight_content`` is the matched snippet IMA returns; items whose match- was on the title alone carry none and are still listed, so the model can see- the document exists even without a quotable passage.- """- sources: list[dict[str, Any]] = []- for item in items:- title = str(item.get("title") or "").strip()- media_id = str(item.get("media_id") or "").strip()- if not title and not media_id:- continue- sources.append(- {- "title": title or media_id,- "content": str(item.get("highlight_content") or "").strip(),- "source": title or media_id,- "chunk_id": media_id,- }- )- return sources---async def _extract_media_text(media: ImaMediaContent | None, title: str) -> str:- if media is None:- return ""- if media.text:- return media.text[:_MAX_FULLTEXT_CHARS].strip()- if not media.data:- return ""-- filename = _extractable_filename(title, media.filename)- if not filename:- return ""- return await asyncio.to_thread(- extract_text_from_bytes,- filename,- media.data,- max_bytes=MAX_MEDIA_BYTES,- max_chars=_MAX_FULLTEXT_CHARS,- )---def _extractable_filename(*candidates: str) -> str:- for candidate in candidates:- if PurePath(candidate).suffix.lower() in SUPPORTED_DOC_EXTENSIONS:- return candidate- return ""---def _render_context(sources: list[dict[str, Any]]) -> str:- """Flatten retrieved snippets into the grounded context block."""- blocks = [- f"[{index}] {source['title']}\n{source['content']}".rstrip()- for index, source in enumerate(sources, start=1)- ]- return "\n\n".join(blocks)--__all__ = ["ImaPipeline", "PROVIDER"]diff --git a/deeptutor/services/rag/pipelines/ima/probe.py b/deeptutor/services/rag/pipelines/ima/probe.pyindex 008476c28..de572f658 100644--- a/deeptutor/services/rag/pipelines/ima/probe.py+++ b/deeptutor/services/rag/pipelines/ima/probe.py@@ -15,8 +15,9 @@ from __future__ import annotationsfrom dataclasses import asdict, dataclassfrom typing import Any, Optional-from .client import ImaAuthError, ImaClient+from .client import ImaClientfrom .config import ImaConfig+from .envelope import ImaAuthError@dataclassdiff --git a/deeptutor/services/rag/pipelines/ima/sources.py b/deeptutor/services/rag/pipelines/ima/sources.pynew file mode 100644index 000000000..f55a0c566--- /dev/null+++ b/deeptutor/services/rag/pipelines/ima/sources.py@@ -0,0 +1,105 @@+"""Shaping IMA search results into the grounded context the ``rag`` tool expects.++IMA answers a search with one *highlight snippet* per matched item — often a+single sentence, and nothing at all when the match was on the title. Handing+those straight to the model is what made a connected IMA library feel thin+compared to an indexed KB, whose chunks are whole passages.++So retrieval has two stages, and this module owns the policy for the second:++1. map matched documents into DeepTutor's ``sources`` shape;+2. decide which of them are worth spending a full-text fetch on+ (:func:`hydration_targets`) — items with *no* snippet first, then items whose+ snippet is too thin to reason from, best-ranked first, bounded by a budget so+ one search cannot turn into a dozen downloads.++Kept separate from :mod:`.pipeline` (which orchestrates the calls) and+:mod:`.client` (which makes them) so the retrieval policy can be reasoned about+and tested without a transport.+"""++from __future__ import annotations++from typing import Any, Iterable, Sequence++from .models import ImaDocument++# A snippet shorter than this is treated as a hint that a document matched, not+# as usable evidence, so it is a candidate for full-text hydration.+MIN_USEFUL_SNIPPET_CHARS = 240++# How many documents one retrieval may fetch in full. Bounds both the network+# cost and the prompt footprint even when ``top_k`` is large.+DEFAULT_HYDRATION_BUDGET = 4++# Per-document character cap for hydrated full text.+MAX_FULLTEXT_CHARS = 12_000+++def documents_to_sources(documents: Iterable[ImaDocument]) -> list[dict[str, Any]]:+ """Map matched IMA documents into DeepTutor's ``sources`` shape.++ Items whose match was on the title alone carry no snippet and are still+ listed, so the model can see the document exists even before (or without)+ hydration.+ """+ sources: list[dict[str, Any]] = []+ for document in documents:+ title = document.title or document.media_id+ if not title:+ continue+ sources.append(+ {+ "title": title,+ "content": document.highlight,+ "source": title,+ "chunk_id": document.media_id,+ }+ )+ return sources+++def hydration_targets(+ sources: Sequence[dict[str, Any]],+ *,+ budget: int = DEFAULT_HYDRATION_BUDGET,+ min_chars: int = MIN_USEFUL_SNIPPET_CHARS,+) -> list[int]:+ """Indices of the sources worth fetching in full, in priority order.++ Snippet-less matches come first (they carry no evidence at all), then thin+ snippets in rank order. Sources without an item id cannot be fetched and are+ never returned.+ """+ if budget <= 0:+ return []+ empty: list[int] = []+ thin: list[int] = []+ for index, source in enumerate(sources):+ if not source.get("chunk_id"):+ continue+ content = str(source.get("content") or "").strip()+ if not content:+ empty.append(index)+ elif len(content) < min_chars:+ thin.append(index)+ return (empty + thin)[:budget]+++def render_context(sources: Sequence[dict[str, Any]]) -> str:+ """Flatten retrieved snippets into the grounded context block."""+ blocks = [+ f"[{index}] {source.get('title') or ''}\n{source.get('content') or ''}".rstrip()+ for index, source in enumerate(sources, start=1)+ ]+ return "\n\n".join(blocks)+++__all__ = [+ "DEFAULT_HYDRATION_BUDGET",+ "MAX_FULLTEXT_CHARS",+ "MIN_USEFUL_SNIPPET_CHARS",+ "documents_to_sources",+ "hydration_targets",+ "render_context",+]diff --git a/deeptutor/services/rag/pipelines/ima/transport.py b/deeptutor/services/rag/pipelines/ima/transport.pynew file mode 100644index 000000000..52632fcfc--- /dev/null+++ b/deeptutor/services/rag/pipelines/ima/transport.py@@ -0,0 +1,122 @@+"""HTTP transport shared by every Tencent IMA OpenAPI call.++All IMA methods are ``POST https://ima.qq.com/<prefix>/<method>`` with a JSON+body and two credential headers, so the wire mechanics are identical across the+knowledge-base (``wiki``) and notes modules. Concentrating them here leaves the+client classes as nothing but method tables, and leaves exactly one place that+attaches credentials.++A fresh ``httpx`` client per call (mirroring ``LightRagServerClient``) keeps the+object safe to construct once and reuse from anywhere, and the injectable+``transport`` lets tests stub the wire without a live server.++Both an async and a blocking flavour of the same call are exposed. The async one+serves retrieval and the tool layer; the blocking one exists for the knowledge-base+*inventory*, which is read from the deliberately synchronous manifest layer (see+:mod:`deeptutor.knowledge.manifest`) — giving it a blocking call here is far less+invasive than making that whole path async, and both share this module's URL,+header and envelope handling.+"""++from __future__ import annotations++from typing import Any, Optional++import httpx++from .config import ImaConfig+from .envelope import ImaRateLimitError, unwrap++API_BASE_URL = "https://ima.qq.com"+WIKI_PREFIX = "/openapi/wiki/v1"+NOTE_PREFIX = "/openapi/note/v1"++DEFAULT_TIMEOUT = 30.0+++def build_headers(config: ImaConfig) -> dict[str, str]:+ """The credential headers every IMA request carries."""+ return {+ "Content-Type": "application/json",+ "ima-openapi-clientid": config.client_id,+ "ima-openapi-apikey": config.api_key,+ }+++class ImaTransport:+ """POST one IMA method and return its unwrapped ``data`` object."""++ def __init__(+ self,+ config: ImaConfig,+ *,+ timeout: float = DEFAULT_TIMEOUT,+ transport: Optional[httpx.AsyncBaseTransport] = None,+ ) -> None:+ self.config = config+ self.timeout = timeout+ self.transport = transport++ async def post(+ self,+ method: str,+ body: dict[str, Any],+ *,+ prefix: str = WIKI_PREFIX,+ ) -> dict[str, Any]:+ async with httpx.AsyncClient(+ base_url=API_BASE_URL,+ headers=build_headers(self.config),+ timeout=self.timeout,+ transport=self.transport,+ ) as client:+ response = await client.post(f"{prefix}/{method}", json=body)+ return self._unwrap(response)++ def post_sync(+ self,+ method: str,+ body: dict[str, Any],+ *,+ prefix: str = WIKI_PREFIX,+ ) -> dict[str, Any]:+ with httpx.Client(+ base_url=API_BASE_URL,+ headers=build_headers(self.config),+ timeout=self.timeout,+ transport=_sync_transport(self.transport),+ ) as client:+ response = client.post(f"{prefix}/{method}", json=body)+ return self._unwrap(response)++ @staticmethod+ def _unwrap(response: httpx.Response) -> dict[str, Any]:+ # A transport-level 429 never reaches the envelope, so it is mapped here+ # to the same error the envelope's rate-limit codes raise.+ if response.status_code == 429:+ raise ImaRateLimitError("IMA rate limit reached. Try again shortly.")+ try:+ payload = response.json()+ except Exception:+ payload = None+ return unwrap(payload, status_code=response.status_code)+++def _sync_transport(transport: Optional[httpx.AsyncBaseTransport]) -> Optional[httpx.BaseTransport]:+ """Reuse an injected test transport for blocking calls when it supports them.++ ``httpx.MockTransport`` implements both the sync and async protocols, so a+ test's stub works for either flavour; a genuinely async-only transport is+ ignored rather than passed to a blocking client that cannot drive it.+ """+ return transport if isinstance(transport, httpx.BaseTransport) else None+++__all__ = [+ "API_BASE_URL",+ "DEFAULT_TIMEOUT",+ "NOTE_PREFIX",+ "WIKI_PREFIX",+ "ImaTransport",+ "build_headers",+]diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 1367232df..1254de9ce 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -11,6 +11,7 @@ from contextvars import Tokenfrom dataclasses import dataclass, fieldimport jsonimport logging+import refrom typing import TYPE_CHECKING, Any, Literalfrom deeptutor.core.stream import StreamEvent, StreamEventType@@ -201,6 +202,44 @@ def _mastery_path_id(value: Any) -> str:return str(value or "").strip()+# Reading material ids are content hashes; anything else is a client bug or an+# injection attempt, so the shape is enforced here rather than deeper in.+_READING_ID_RE = re.compile(r"^[0-9a-f]{8,64}$")+# A selection is quoted back into the prompt, so it is bounded here — the+# reader has no reason to send more, and a runaway selection must not eat the+# turn's context budget.+READING_SELECTION_MAX_CHARS = 2000+++def _reading_material_id(value: Any) -> str:+ """Normalize the immersive-reading material bound to this turn."""+ candidate = str(value or "").strip().lower()+ return candidate if _READING_ID_RE.match(candidate) else ""+++def _reading_viewport(value: Any) -> dict[str, Any]:+ """Normalize what the reader reports it is showing.++ Both fields are optional: a freshly opened document has no locator yet, and+ most turns carry no selection. Absent keys are omitted rather than zeroed so+ the capability's prompt block can distinguish "nothing selected" from an+ empty selection.+ """+ if not isinstance(value, dict):+ return {}+ viewport: dict[str, Any] = {}+ try:+ locator = int(value.get("locator") or 0)+ except (TypeError, ValueError):+ locator = 0+ if locator > 0:+ viewport["locator"] = locator+ selection = str(value.get("selection") or "").strip()+ if selection:+ viewport["selection"] = selection[:READING_SELECTION_MAX_CHARS]+ return viewport++def _llm_selection_dict(value: Any) -> dict[str, str] | None:from deeptutor.services.model_selection import LLMSelection@@ -246,6 +285,12 @@ def _request_snapshot_metadata(mastery_path_id = _mastery_path_id(payload.get("mastery_path_id"))if mastery_path_id:snapshot["masteryPathId"] = mastery_path_id+ # Persisted so a regenerate re-runs with the same document open. Without it+ # the reading capability would be inactive on the retry and the answer would+ # silently lose its grounding.+ reading_material_id = _reading_material_id(payload.get("reading_material_id"))+ if reading_material_id:+ snapshot["readingMaterialId"] = reading_material_idif persona:snapshot["persona"] = personaif memory_references:@@ -1127,6 +1172,15 @@ class TurnRuntimeManager:else snapshot.get("bookReferences") or []),"mastery_path_id": mastery_path_id,+ # Recovered from the original turn's snapshot so the regenerate runs+ # against the same document. An explicit override wins (the reader+ # may have moved on), and the viewport is deliberately not restored —+ # "where the user was looking" is stale by definition on a retry.+ "reading_material_id": _reading_material_id(+ overrides.get("reading_material_id")+ if "reading_material_id" in overrides+ else snapshot.get("readingMaterialId")+ ),"config": config,}if llm_selection:@@ -1828,6 +1882,11 @@ class TurnRuntimeManager:"book_references": book_references,"mastery_path_id": _mastery_path_id(payload.get("mastery_path_id")),"mastery_path_lease_managed": capability_name == "mastery_path",+ # Immersive reading: the open material activates the reading+ # capability and binds its tools; the viewport tells the+ # model where the user is actually looking.+ "reading_material_id": _reading_material_id(payload.get("reading_material_id")),+ "reading_viewport": _reading_viewport(payload.get("reading_viewport")),"book_context": book_context,"book_context_warnings": book_context_result.warnings,"memory_references": memory_references,diff --git a/deeptutor/services/settings/interface_settings.py b/deeptutor/services/settings/interface_settings.pyindex 5af5e904c..584e4f790 100644--- a/deeptutor/services/settings/interface_settings.py+++ b/deeptutor/services/settings/interface_settings.py@@ -7,8 +7,12 @@ This is the canonical backend source for user-selected UI language/theme storedfrom __future__ import annotations-from collections.abc import Mapping+from collections.abc import Callable, Mappingimport json+import os+from pathlib import Path+import tempfile+import threadingfrom typing import Anyfrom deeptutor.services.path_service import get_path_service@@ -21,6 +25,26 @@ DEFAULT_UI_SETTINGS: dict[str, Any] = {}+_LOCKS_GUARD = threading.Lock()+_LOCKS: dict[str, threading.Lock] = {}+++def _settings_lock(path: Path) -> threading.Lock:+ """One lock per settings file, so a write only serialises its own file.++ Keyed by resolved path rather than a single global lock because in a+ multi-user deployment each account has its own ``interface.json``; making+ them contend would serialise unrelated users' preference writes.+ """+ key = str(path.resolve() if path.is_absolute() else path)+ with _LOCKS_GUARD:+ lock = _LOCKS.get(key)+ if lock is None:+ lock = threading.Lock()+ _LOCKS[key] = lock+ return lock++def _interface_settings_file():# Resolved on every call so a per-user PathService (set after auth)# routes reads to the caller's own ``settings/interface.json`` instead@@ -93,6 +117,88 @@ def get_ui_settings() -> dict[str, Any]:return DEFAULT_UI_SETTINGS.copy()+def atomic_update(+ settings_file: Path, mutate: Callable[[dict[str, Any]], Mapping[str, Any]]+) -> dict[str, Any]:+ """Read, mutate and replace a settings file as one indivisible step.++ Takes the path rather than resolving it, so every writer of a given file+ shares one lock even though they resolve the path themselves — the settings+ router and the setup capability both write ``interface.json`` and a lock+ only one of them takes is not a lock. Measured with each module writing+ directly: six router writes racing six capability writes lost every one of+ the router's.++ ``mutate`` receives the raw stored mapping — never the defaults-merged view,+ since writing that back would freeze today's defaults as the user's explicit+ choices — and returns what should be on disk. The write is a temp-file+ rename, so a crash or a full disk leaves the previous file rather than a+ truncated one; a half-written ``interface.json`` is what would drop a user+ back to English and the default theme.+ """+ with _settings_lock(settings_file):+ stored: dict[str, Any] = {}+ if settings_file.exists():+ try:+ with open(settings_file, encoding="utf-8") as f:+ loaded = json.load(f)+ if isinstance(loaded, dict):+ stored = loaded+ except Exception:+ # A corrupt file is replaced rather than inherited: reads already+ # fall back to defaults, so preserving the broken bytes would only+ # keep the user stuck with settings that do not apply.+ stored = {}+ payload = dict(mutate(stored))+ settings_file.parent.mkdir(parents=True, exist_ok=True)+ fd, temp_name = tempfile.mkstemp(+ prefix=f".{settings_file.name}.", suffix=".tmp", dir=settings_file.parent+ )+ temp_path = Path(temp_name)+ try:+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:+ json.dump(payload, f, ensure_ascii=False, indent=2)+ f.write("\n")+ f.flush()+ os.fsync(f.fileno())+ os.replace(temp_path, settings_file)+ finally:+ temp_path.unlink(missing_ok=True)+ return payload+++def update_ui_settings(patch: Mapping[str, Any]) -> dict[str, Any]:+ """Merge ``patch`` into the stored settings, leaving every other field intact.++ Merged into the *raw* stored mapping rather than into+ :func:`get_ui_settings`, whose return value is defaults-merged. Writing that+ merged view back would materialise every current default as an explicit+ stored value, so a user who once changed their theme would silently stop+ following later changes to any other default — the file would already+ contain a frozen copy of the defaults as they were that day.++ Returns the mapping now on disk.+ """+ updates = dict(patch)++ def _mutate(stored: dict[str, Any]) -> dict[str, Any]:+ stored.update(updates)+ return stored++ return atomic_update(_interface_settings_file(), _mutate)+++def replace_ui_settings(settings: Mapping[str, Any]) -> dict[str, Any]:+ """Replace the stored settings wholesale (reset, and full-document saves)."""+ payload = dict(settings)+ return atomic_update(_interface_settings_file(), lambda _stored: payload)+++def set_ui_setting(key: str, value: Any) -> dict[str, Any]:+ """Persist one field, leaving every other field intact."""+ return update_ui_settings({key: value})++def get_ui_language(default: str = "en") -> str:"""Get current UI language.diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex 824d7066b..edaa6fb9d 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -7,8 +7,11 @@ import jsonimport loggingfrom typing import Any+from deeptutor.capabilities.ima import IMA_TOOL_TYPESfrom deeptutor.capabilities.mastery import MASTERY_TOOL_TYPESfrom deeptutor.capabilities.obsidian import OBSIDIAN_TOOL_TYPES+from deeptutor.capabilities.reading import READING_TOOL_TYPES+from deeptutor.capabilities.setup import SETUP_TOOL_TYPESfrom deeptutor.capabilities.solve import SOLVE_TOOL_TYPESfrom deeptutor.capabilities.subagent import SUBAGENT_TOOL_TYPESfrom deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult@@ -1597,6 +1600,16 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (# capability runs the turn exclusively on it when a connected agent is the# selected KB.*SUBAGENT_TOOL_TYPES,+ # Tencent IMA tools — globally registered; the IMA capability mounts them+ # (additively, alongside rag) when a connected IMA library is selected.+ *IMA_TOOL_TYPES,+ # Immersive-reading tools — globally registered; the reading capability+ # mounts them (additively) and binds the open material server-side, so they+ # are inert on a turn with no document open.+ *READING_TOOL_TYPES,+ # Self-configuration tools — globally registered; the setup capability+ # mounts them (additively) on a turn that is actually about configuration.+ *SETUP_TOOL_TYPES,# Partner-only memory + history tools. Globally registered so schemas/API# stay stable, but never mounted in product chat: the partner runtime# force-mounts them (and suppresses chat's read_memory/write_memory) ondiff --git a/deeptutor/tools/write_note.py b/deeptutor/tools/write_note.pyindex 307134b42..b7cf8a66c 100644--- a/deeptutor/tools/write_note.py+++ b/deeptutor/tools/write_note.py@@ -248,6 +248,21 @@ def _do_append(notebook_name=notebook_name,error="Notebook service did not return a record id.",)+ # A record id comes back even when no notebook accepted the write — the+ # service skips notebooks that are missing or damaged. Reporting success+ # off the id alone would tell the model it saved something it did not.+ added_to = (outcome or {}).get("added_to_notebooks") or []+ if notebook_id not in added_to:+ return WriteOutcome(+ ok=False,+ mode="append",+ notebook_id=notebook_id,+ notebook_name=notebook_name,+ error=(+ f"Notebook {notebook_name!r} did not accept the record. "+ "Its file may be missing or damaged."+ ),+ )return WriteOutcome(ok=True,mode="append",@@ -293,7 +308,19 @@ def _do_edit(error="record_id is required in edit mode.",)- existing = manager.get_record(notebook_id, rid) if hasattr(manager, "get_record") else None+ try:+ existing = manager.get_record(notebook_id, rid) if hasattr(manager, "get_record") else None+ except Exception as exc:+ # A damaged notebook file raises here. Report it as a tool result the+ # model can act on rather than letting it escape into the agent loop.+ logger.warning("write_note(edit): could not read notebook", exc_info=True)+ return WriteOutcome(+ ok=False,+ mode="edit",+ notebook_id=notebook_id,+ notebook_name=notebook_name,+ error=f"Could not read notebook {notebook_name!r}: {exc}",+ )if existing is None:return WriteOutcome(ok=False,diff --git a/deeptutor_cli/notebook.py b/deeptutor_cli/notebook.pyindex 4c86f3ed5..129705a25 100644--- a/deeptutor_cli/notebook.py+++ b/deeptutor_cli/notebook.py@@ -8,6 +8,7 @@ from pathlib import Pathimport typerfrom deeptutor.app import DeepTutorApp+from deeptutor.services.notebook.service import NotebookCorruptedErrorfrom .common import console, print_notebook_table@@ -36,7 +37,12 @@ def register(app: typer.Typer) -> None:) -> None:"""Show a notebook and its records."""client = DeepTutorApp()- notebook = client.get_notebook(notebook_id)+ try:+ notebook = client.get_notebook(notebook_id)+ except NotebookCorruptedError as exc:+ # The file is still on disk; say so instead of dumping a traceback.+ console.print(f"[red]Notebook file is damaged:[/] {exc}")+ raise typer.Exit(code=1)if notebook is None:console.print(f"[red]Notebook not found:[/] {notebook_id}")raise typer.Exit(code=1)@@ -59,7 +65,11 @@ def register(app: typer.Typer) -> None:) -> None:"""Delete a notebook record."""client = DeepTutorApp()- success = client.remove_record(notebook_id, record_id)+ try:+ success = client.remove_record(notebook_id, record_id)+ except NotebookCorruptedError as exc:+ console.print(f"[red]Notebook file is damaged:[/] {exc}")+ raise typer.Exit(code=1)if not success:console.print(f"[red]Record not found:[/] {record_id}")raise typer.Exit(code=1)diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 580084673..a36aa5af0 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -264,7 +264,7 @@ def test_list_ima_rejects_missing_credentials(payload: dict) -> None:assert "required" in response.json()["detail"][email protected]("limit", [0, 21])[email protected]("limit", [0, 51])def test_list_ima_validates_official_page_limit(limit: int) -> None:with TestClient(_build_app()) as client:response = client.post(diff --git a/tests/api/test_main_notebook_router.py b/tests/api/test_main_notebook_router.pyindex 70af1815f..1a3188692 100644--- a/tests/api/test_main_notebook_router.py+++ b/tests/api/test_main_notebook_router.py@@ -159,3 +159,156 @@ def test_stream_add_record_with_summary_strips_thinking_tags(detail = manager.get_notebook(nb["id"])assert detail is not Noneassert detail["records"][0]["summary"] == "Final reusable summary."+++def test_health_is_not_shadowed_by_the_notebook_id_route(manager: NotebookManager) -> None:+ """`/health` is a literal path and must win over `/{notebook_id}`.++ Declared after the parameterised route it returned 404 "Notebook not+ found", because FastAPI matched `health` as an id.+ """+ with TestClient(_build_app(manager)) as client:+ resp = client.get("/api/v1/notebook/health")++ assert resp.status_code == 200+ assert resp.json()["status"] == "healthy"+++def test_renaming_a_record_over_http_keeps_its_kb_name(manager: NotebookManager) -> None:+ """The PUT endpoint must forward only the fields the client sent."""+ notebook_id = manager.create_notebook("KB")["id"]+ record = manager.add_record(+ notebook_ids=[notebook_id],+ record_type="chat",+ title="Original",+ user_query="q",+ output="o",+ kb_name="physics",+ )["record"]++ with TestClient(_build_app(manager)) as client:+ resp = client.put(+ f"/api/v1/notebook/{notebook_id}/records/{record['id']}",+ json={"title": "Renamed"},+ )++ assert resp.status_code == 200+ updated = resp.json()["record"]+ assert updated["title"] == "Renamed"+ assert updated["kb_name"] == "physics"+++def test_record_kb_name_can_still_be_cleared_explicitly(manager: NotebookManager) -> None:+ notebook_id = manager.create_notebook("KB")["id"]+ record = manager.add_record(+ notebook_ids=[notebook_id],+ record_type="chat",+ title="Original",+ user_query="q",+ output="o",+ kb_name="physics",+ )["record"]++ with TestClient(_build_app(manager)) as client:+ resp = client.put(+ f"/api/v1/notebook/{notebook_id}/records/{record['id']}",+ json={"kb_name": None},+ )++ assert resp.status_code == 200+ assert resp.json()["record"]["kb_name"] is None+++def test_move_and_copy_endpoints(manager: NotebookManager) -> None:+ source = manager.create_notebook("Source")["id"]+ target = manager.create_notebook("Target")["id"]+ record = manager.add_record(+ notebook_ids=[source],+ record_type="chat",+ title="Travelling",+ user_query="q",+ output="o",+ )["record"]++ with TestClient(_build_app(manager)) as client:+ copy_resp = client.post(+ f"/api/v1/notebook/{source}/records/{record['id']}/copy",+ json={"target_notebook_id": target},+ )+ assert copy_resp.status_code == 200+ assert copy_resp.json()["record"]["id"] != record["id"]++ move_resp = client.post(+ f"/api/v1/notebook/{source}/records/{record['id']}/move",+ json={"target_notebook_id": target},+ )+ assert move_resp.status_code == 200++ assert manager.get_record(source, record["id"]) is None+ assert len(manager.get_records(target)) == 2+++def test_export_returns_markdown(manager: NotebookManager) -> None:+ notebook_id = manager.create_notebook("Exported")["id"]+ manager.add_record(+ notebook_ids=[notebook_id],+ record_type="chat",+ title="First entry",+ user_query="q",+ output="Body text.",+ )++ with TestClient(_build_app(manager)) as client:+ resp = client.get(f"/api/v1/notebook/{notebook_id}/export")++ assert resp.status_code == 200+ assert resp.headers["content-type"].startswith("text/markdown")+ assert "## First entry" in resp.text+++def test_damaged_notebook_returns_a_named_conflict(manager: NotebookManager) -> None:+ (manager.base_dir / "broken01.json").write_text("{ not json", encoding="utf-8")++ with TestClient(_build_app(manager)) as client:+ resp = client.get("/api/v1/notebook/broken01")++ assert resp.status_code == 409+ assert resp.json()["detail"]["code"] == "notebook_unreadable"+++def test_every_notebook_endpoint_reports_damage_as_409(manager: NotebookManager) -> None:+ """No endpoint may flatten a damaged file into an anonymous 500.++ Each endpoint wraps its body in `except Exception -> 500`, which swallows+ NotebookCorruptedError unless it is re-raised first. This walks the real+ request surface so an endpoint added later without that guard fails here+ rather than degrading quietly in production.+ """+ (manager.base_dir / "broken01.json").write_text("{ not json", encoding="utf-8")+ healthy = manager.create_notebook("Healthy")["id"]++ requests = [+ ("GET", "/api/v1/notebook/broken01", None),+ ("PUT", "/api/v1/notebook/broken01", {"name": "Renamed"}),+ ("GET", "/api/v1/notebook/broken01/export", None),+ ("DELETE", "/api/v1/notebook/broken01/records/whatever", None),+ ("PUT", "/api/v1/notebook/broken01/records/whatever", {"title": "x"}),+ (+ "POST",+ "/api/v1/notebook/broken01/records/whatever/copy",+ {"target_notebook_id": healthy},+ ),+ (+ "POST",+ "/api/v1/notebook/broken01/records/whatever/move",+ {"target_notebook_id": healthy},+ ),+ ]++ with TestClient(_build_app(manager)) as client:+ for method, url, body in requests:+ resp = client.request(method, url, json=body)+ assert resp.status_code == 409, f"{method} {url} returned {resp.status_code}"+ assert resp.json()["detail"]["code"] == "notebook_unreadable", (+ f"{method} {url} lost the structured reason"+ )diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex 5f06d36c4..55ca07bfa 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -1473,3 +1473,61 @@ def test_get_ui_settings_not_registered_on_gated_router() -> None:}assert "GET" not in gated_methods, f"GET /ui must not be on the gated router: {gated_methods}"assert "PUT" in gated_methods+++def test_ui_writes_are_atomic_and_serialised(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:+ """Both writers of interface.json must share one lock and one atomic replace.++ The router and the setup capability write the same file. While each opened+ it directly, twelve concurrent writes left two fields on disk — a lock only+ one side takes is not a lock, and a plain ``open(..., "w")`` can also leave+ a truncated file behind a crash.+ """+ import threading++ from deeptutor.services.settings import interface_settings++ settings_file = tmp_path / "interface.json"+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)+ monkeypatch.setattr(interface_settings, "_interface_settings_file", lambda: settings_file)++ def via_router(index: int) -> None:+ for _ in range(20):+ settings_router.patch_ui_settings(**{f"router_{index}": index})++ def via_capability(index: int) -> None:+ for _ in range(20):+ interface_settings.set_ui_setting(f"cap_{index}", index)++ threads = [threading.Thread(target=via_router, args=(i,)) for i in range(6)]+ threads += [threading.Thread(target=via_capability, args=(i,)) for i in range(6)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ stored = json.loads(settings_file.read_text(encoding="utf-8"))+ assert {f"router_{i}" for i in range(6)} <= set(stored)+ assert {f"cap_{i}" for i in range(6)} <= set(stored)+++async def test_ui_endpoints_do_not_freeze_defaults_into_the_file(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Changing one preference must not persist every current default alongside it.++ ``load_ui_settings`` returns a defaults-merged view; the endpoints used to+ save that view straight back, so the first time anyone changed their theme+ the file gained an explicit copy of every default as it stood that day —+ and that user silently stopped following later changes to any of them.+ """+ settings_file = tmp_path / "interface.json"+ monkeypatch.setattr(settings_router, "_settings_file", lambda: settings_file)++ await settings_router.update_theme(settings_router.ThemeUpdate(theme="dark"))++ stored = json.loads(settings_file.read_text(encoding="utf-8"))+ assert stored == {"theme": "dark"}, f"only the changed field belongs on disk: {stored}"+ # The read path still reports the full picture.+ assert settings_router.load_ui_settings()["language"] == "en"diff --git a/tests/book/test_source_partitioning.py b/tests/book/test_source_partitioning.pyindex cea4b8eb2..4c5b44c12 100644--- a/tests/book/test_source_partitioning.py+++ b/tests/book/test_source_partitioning.py@@ -1,9 +1,13 @@-"""Retrieval must tell indexed knowledge bases apart from connected pointers.+"""Retrieval must tell searchable knowledge bases apart from unreachable ones.-A connected KB — an Obsidian vault, a subagent CLI, a remote LightRAG or IMA-library — has no local index, so `rag_search` returns nothing. Sweeping them-anyway looked exactly like a source with no relevant content, so a reader who-attached their vault never learned it contributed zero.+An Obsidian vault (no index) and a subagent CLI (not a document collection)+return nothing from `rag_search`. Sweeping them anyway looked exactly like a+source with no relevant content, so a reader who attached their vault never+learned it contributed zero — they are named instead.++The other pointer kinds ARE searchable and must be swept: a `linked` folder+mounts an index built elsewhere, and `lightrag_server` / `ima` offload retrieval+over HTTP. Excluding every "connected" KB silently dropped those sources."""from __future__ import annotations@@ -37,7 +41,7 @@ def fake_metadata(monkeypatch):return table-def test_connected_kbs_are_separated_from_indexed_ones(fake_metadata) -> None:+def test_unreachable_kbs_are_separated_from_searchable_ones(fake_metadata) -> None:fake_metadata.update({"my-vault": {"type": "obsidian"},@@ -45,18 +49,34 @@ def test_connected_kbs_are_separated_from_indexed_ones(fake_metadata) -> None:"papers": {"type": "local"},})- retrievable, connected = SourceExplorer.partition_knowledge_bases(+ retrievable, unreachable = SourceExplorer.partition_knowledge_bases(["papers", "my-vault", "my-agent"])assert retrievable == ["papers"]- assert sorted(connected) == ["my-agent", "my-vault"]+ assert sorted(unreachable) == ["my-agent", "my-vault"]+++def test_http_backed_and_linked_pointers_are_still_swept(fake_metadata) -> None:+ """These have an index or a retrieval API — dropping them cost every book."""+ fake_metadata.update(+ {+ "ima-lib": {"type": "ima", "knowledge_base_id": "kb-1"},+ "lightrag": {"type": "lightrag_server", "server_url": "https://x.invalid"},+ "linked": {"type": "linked", "external_path": "/tmp/elsewhere"},+ }+ )+ retrievable, unreachable = SourceExplorer.partition_knowledge_bases(+ ["ima-lib", "lightrag", "linked"]+ )+ assert sorted(retrievable) == ["ima-lib", "lightrag", "linked"]+ assert unreachable == []def test_unresolvable_references_are_treated_as_ordinary(fake_metadata) -> None:"""A KB we cannot resolve must not be silently dropped from the sweep."""- retrievable, connected = SourceExplorer.partition_knowledge_bases(["mystery"])+ retrievable, unreachable = SourceExplorer.partition_knowledge_bases(["mystery"])assert retrievable == ["mystery"]- assert connected == []+ assert unreachable == []# ── Balanced slice ──────────────────────────────────────────────────────diff --git a/tests/capabilities/test_ima_capability.py b/tests/capabilities/test_ima_capability.pynew file mode 100644index 000000000..9c8d00f77--- /dev/null+++ b/tests/capabilities/test_ima_capability.py@@ -0,0 +1,498 @@+"""Tests for the IMA loop capability: binding, additive mounting, tools.++Two design decisions are pinned here because getting either wrong is silent:++* **The capability is additive, not exclusive.** An IMA library is searchable over+ HTTP, so ``rag`` must keep serving it and chat's own tools must survive. If this+ ever became a ``KnowledgeCapability``, attaching an IMA library would quietly+ strip web search, memory and every other built-in from the turn.+* **Credentials never travel through tool kwargs.** The capability injects only+ the turn's library bindings (name + library id); each tool loads the credential+ pair itself, re-checking the user's access, so a trace or log of tool arguments+ cannot leak a key and a model cannot name a library that was not attached.+"""++from __future__ import annotations++import asyncio+import json+from typing import Any++import pytest++from deeptutor.agents._shared.tool_composition import ToolMountFlags, compose_enabled_tools+from deeptutor.capabilities import any_exclusive_capability_active+from deeptutor.capabilities.ima import IMA_TOOL_NAMES, ImaCapability+from deeptutor.capabilities.ima import binding as ima_binding+from deeptutor.capabilities.ima import tools as ima_tools+from deeptutor.capabilities.ima.binding import ImaBinding, select_binding+from deeptutor.capabilities.ima.tools import (+ BINDINGS_KWARG,+ ImaAddUrlTool,+ ImaListTool,+ ImaNoteSearchTool,+ ImaReadTool,+ ImaWriteNoteTool,+)+from deeptutor.core.context import UnifiedContext+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.rag.pipelines.ima.config import ImaNotConfiguredError+from deeptutor.services.rag.pipelines.ima.envelope import ImaAuthError+from deeptutor.services.rag.pipelines.ima.media import ImaMediaContent+from deeptutor.services.rag.pipelines.ima.models import (+ ImaDocument,+ ImaFolder,+ ImaImportedUrl,+ ImaKnowledgePage,+ ImaNote,+)++LIBRARY = ImaBinding(kb_ref="ima知识库", name="ima知识库", knowledge_base_id="kb-1")+OTHER = ImaBinding(kb_ref="Research", name="Research", knowledge_base_id="kb-2")+++def _context(kbs: list[str]) -> UnifiedContext:+ return UnifiedContext(user_message="q", knowledge_bases=kbs)+++def _metadata(kb_type: str, name: str = "ima知识库") -> dict[str, Any]:+ return {"name": name, "type": kb_type, "knowledge_base_id": "kb-1"}+++class _ClientStub:+ def __init__(self, **behaviour: Any) -> None:+ self._behaviour = behaviour+ self.calls: list[tuple[str, dict]] = []+ self.notes = _NotesStub(self)++ async def get_knowledge_list(self, **kwargs):+ self.calls.append(("get_knowledge_list", kwargs))+ return self._result("page")++ async def get_media_content(self, media_id: str):+ self.calls.append(("get_media_content", {"media_id": media_id}))+ return self._result("media")++ async def import_urls(self, urls, *, folder_id=""):+ self.calls.append(("import_urls", {"urls": urls, "folder_id": folder_id}))+ return self._result("imported")++ def _result(self, key: str):+ value = self._behaviour.get(key)+ if isinstance(value, Exception):+ raise value+ return value+++class _NotesStub:+ def __init__(self, owner: _ClientStub) -> None:+ self._owner = owner++ async def search_notes(self, query="", **kwargs):+ self._owner.calls.append(("search_notes", {"query": query, **kwargs}))+ return self._owner._behaviour.get("notes", ([], True))++ async def create_note(self, content, *, folder_id=""):+ self._owner.calls.append(("create_note", {"content": content, "folder_id": folder_id}))+ return self._owner._behaviour.get("created", "n1")++ async def append_note(self, note_id, content):+ self._owner.calls.append(("append_note", {"note_id": note_id, "content": content}))+ return self._owner._behaviour.get("appended", note_id)+++def _run(tool, **kwargs):+ return asyncio.run(tool.execute(**kwargs))+++def _payload(result):+ return json.loads(result.content)+++def stub_client(monkeypatch: pytest.MonkeyPatch):+ """Install a client stub, and record how it was resolved."""+ created: dict[str, Any] = {}++ def install(**behaviour):+ client = _ClientStub(**behaviour)++ def resolve(kb_ref: str, *, for_write: bool = False):+ created["kb_ref"] = kb_ref+ created["for_write"] = for_write+ return client++ monkeypatch.setattr(ima_tools, "resolve_client", resolve)+ return client++ install.created = created # type: ignore[attr-defined]+ return install+++# ---------------------------------------------------------------------------+# binding+# ---------------------------------------------------------------------------+++class TestBinding:+ def test_only_ima_knowledge_bases_bind(self, monkeypatch: pytest.MonkeyPatch) -> None:+ metadata = {"ima知识库": _metadata("ima"), "Papers": {"name": "Papers"}}+ monkeypatch.setattr(ima_binding, "resolve_kb_metadata", metadata.get, raising=False)+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ metadata.get,+ raising=False,+ )++ bindings = ima_binding.ima_bindings(_context(["ima知识库", "Papers"]))++ assert [binding.name for binding in bindings] == ["ima知识库"]++ def test_resolution_is_cached_on_the_turn(self, monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []++ def resolve(ref: str):+ calls.append(ref)+ return _metadata("ima")++ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata", resolve, raising=False+ )+ context = _context(["ima知识库"])++ ima_binding.ima_bindings(context)+ ima_binding.ima_bindings(context)++ assert calls == ["ima知识库"]++ def test_a_single_library_needs_no_kb_name(self) -> None:+ assert select_binding((LIBRARY,)) is LIBRARY+ assert select_binding((LIBRARY,), "typo") is LIBRARY++ def test_several_libraries_require_an_unambiguous_name(self) -> None:+ assert select_binding((LIBRARY, OTHER)) is None+ assert select_binding((LIBRARY, OTHER), "Research") is OTHER+ assert select_binding((LIBRARY, OTHER), "kb-1") is LIBRARY+ assert select_binding((LIBRARY, OTHER), "nope") is None++ def test_no_libraries_binds_to_nothing(self) -> None:+ assert select_binding(()) is None+++# ---------------------------------------------------------------------------+# capability wiring+# ---------------------------------------------------------------------------+++class TestCapability:+ def test_active_only_when_an_ima_library_is_attached(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda ref: _metadata("ima") if ref == "ima知识库" else {"name": ref},+ raising=False,+ )+ capability = ImaCapability()++ assert capability.is_active(_context(["ima知识库"])) is True+ assert capability.is_active(_context(["Papers"])) is False+ assert capability.is_active(_context([])) is False++ def test_the_capability_is_additive_not_exclusive(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """rag stays mounted, chat's built-ins survive, IMA tools are added."""+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda _ref: _metadata("ima"),+ raising=False,+ )+ context = _context(["ima知识库"])++ assert any_exclusive_capability_active(context) is False++ composed = compose_enabled_tools(+ registry=get_tool_registry(),+ requested_tools=["web_search"],+ optional_whitelist=["web_search"],+ mount_flags=ToolMountFlags(has_kb=True),+ capability_owned=IMA_TOOL_NAMES,+ exclusive=False,+ )++ assert "rag" in composed+ assert "kb_files" in composed+ assert "web_search" in composed+ assert set(IMA_TOOL_NAMES).issubset(composed)++ def test_system_block_names_the_attached_libraries(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda _ref: _metadata("ima"),+ raising=False,+ )++ block = ImaCapability().system_block(_context(["ima知识库"]), language="zh", prompts={})++ assert block is not None+ assert "ima知识库" in block.content+ assert "{kb_names}" not in block.content++ def test_no_system_block_without_a_library(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda _ref: None,+ raising=False,+ )++ assert ImaCapability().system_block(_context(["x"]), language="en", prompts={}) is None++ def test_bindings_are_injected_and_carry_no_credentials(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda _ref: {+ **_metadata("ima"),+ # Even if a credential leaked into KB metadata, it must not be+ # forwarded into tool kwargs.+ "api_key": "secret",+ "client_id": "secret",+ },+ raising=False,+ )+ context = _context(["ima知识库"])++ kwargs = ImaCapability().augment_kwargs("ima_list", {"folder_id": "f1"}, context)++ assert [binding.name for binding in kwargs[BINDINGS_KWARG]] == ["ima知识库"]+ assert "secret" not in json.dumps(+ [+ binding.__dict__ if hasattr(binding, "__dict__") else str(binding)+ for binding in kwargs[BINDINGS_KWARG]+ ],+ default=str,+ )++ def test_a_model_supplied_bindings_value_is_overwritten(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda _ref: _metadata("ima"),+ raising=False,+ )++ kwargs = ImaCapability().augment_kwargs(+ "ima_list", {BINDINGS_KWARG: [OTHER]}, _context(["ima知识库"])+ )++ assert [binding.knowledge_base_id for binding in kwargs[BINDINGS_KWARG]] == ["kb-1"]++ def test_other_tools_kwargs_are_untouched(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "deeptutor.multi_user.knowledge_access.resolve_kb_metadata",+ lambda _ref: _metadata("ima"),+ raising=False,+ )++ kwargs = ImaCapability().augment_kwargs("rag", {"query": "q"}, _context(["ima知识库"]))++ assert kwargs == {"query": "q"}++ def test_every_owned_tool_is_registered(self) -> None:+ registry = get_tool_registry()+ for name in IMA_TOOL_NAMES:+ assert registry.get(name) is not None+++# ---------------------------------------------------------------------------+# tools+# ---------------------------------------------------------------------------+++class TestTools:+ def test_without_a_binding_the_tool_says_so(self) -> None:+ result = _run(ImaListTool(), **{BINDINGS_KWARG: []})++ assert result.success is False+ assert "No Tencent IMA knowledge base" in result.content++ def test_ambiguous_libraries_ask_for_a_name(self) -> None:+ result = _run(ImaListTool(), **{BINDINGS_KWARG: [LIBRARY, OTHER]})++ assert result.success is False+ assert "kb_name" in result.content+ assert "Research" in result.content++ def test_list_returns_documents_folders_and_the_breadcrumb(self, stub_client) -> None:+ stub_client(+ page=ImaKnowledgePage(+ documents=(ImaDocument(media_id="m1", title="Alpha"),),+ folders=(ImaFolder(folder_id="f1", name="Papers", file_number=2),),+ path=("Library",),+ next_cursor="c2",+ )+ )++ result = _run(ImaListTool(), folder_id="f1", limit=10, **{BINDINGS_KWARG: [LIBRARY]})+ payload = _payload(result)++ assert payload["documents"] == [{"media_id": "m1", "title": "Alpha"}]+ assert payload["folders"][0]["folder_id"] == "f1"+ assert payload["path"] == ["Library"]+ assert payload["next_cursor"] == "c2"++ def test_list_is_a_read_and_targets_the_selected_library(self, stub_client) -> None:+ client = stub_client(page=ImaKnowledgePage())++ _run(ImaListTool(), **{BINDINGS_KWARG: [LIBRARY]})++ assert stub_client.created == {"kb_ref": "ima知识库", "for_write": False}+ assert client.calls[0][0] == "get_knowledge_list"++ def test_read_returns_extracted_text(self, stub_client) -> None:+ stub_client(media=ImaMediaContent(text="the whole document"))++ payload = _payload(_run(ImaReadTool(), media_id="m1", **{BINDINGS_KWARG: [LIBRARY]}))++ assert payload["content"] == "the whole document"+ assert payload["truncated"] is False++ def test_read_requires_a_media_id(self, stub_client) -> None:+ stub_client(media=None)++ result = _run(ImaReadTool(), **{BINDINGS_KWARG: [LIBRARY]})++ assert result.success is False+ assert "media_id is required" in result.content++ def test_read_reports_an_item_with_no_text(self, stub_client) -> None:+ stub_client(media=None)++ result = _run(ImaReadTool(), media_id="m1", **{BINDINGS_KWARG: [LIBRARY]})++ assert result.success is False+ assert "no readable text" in result.content++ def test_note_search_reports_timestamps(self, stub_client) -> None:+ stub_client(+ notes=(+ [ImaNote(note_id="n1", title="Plasma", summary="s", updated_at=222)],+ True,+ )+ )++ payload = _payload(_run(ImaNoteSearchTool(), **{BINDINGS_KWARG: [LIBRARY]}))++ assert payload["notes"][0]["updated_at"] == 222+ assert payload["is_end"] is True++ def test_note_search_maps_the_sort_name(self, stub_client) -> None:+ client = stub_client(notes=([], True))++ _run(ImaNoteSearchTool(), sort="created", **{BINDINGS_KWARG: [LIBRARY]})++ assert client.calls[0][1]["sort_type"] == 1++ def test_add_url_requires_write_access(self, stub_client) -> None:+ stub_client(imported=[ImaImportedUrl(url="https://a.test", ok=True, media_id="m1")])++ _run(ImaAddUrlTool(), urls=["https://a.test"], **{BINDINGS_KWARG: [LIBRARY]})++ assert stub_client.created["for_write"] is True++ def test_add_url_reports_partial_failure(self, stub_client) -> None:+ stub_client(+ imported=[+ ImaImportedUrl(url="https://a.test", ok=True, media_id="m1"),+ ImaImportedUrl(url="https://b.test", ok=False, code=110001),+ ]+ )++ result = _run(+ ImaAddUrlTool(),+ urls=["https://a.test", "https://b.test"],+ **{BINDINGS_KWARG: [LIBRARY]},+ )+ payload = _payload(result)++ assert result.success is True+ assert payload["added"] == [{"url": "https://a.test", "media_id": "m1"}]+ assert payload["failed"] == [{"url": "https://b.test", "code": 110001}]++ @pytest.mark.parametrize(+ "url",+ [+ "https://www.bilibili.com/video/BV1",+ "https://www.youtube.com/watch?v=x",+ "file:///Users/me/page.html",+ ],+ )+ def test_add_url_rejects_what_ima_cannot_accept(self, stub_client, url: str) -> None:+ client = stub_client(imported=[])++ result = _run(ImaAddUrlTool(), urls=[url], **{BINDINGS_KWARG: [LIBRARY]})++ assert result.success is False+ assert "desktop app" in result.content+ assert client.calls == []++ def test_write_note_creates_by_default(self, stub_client) -> None:+ client = stub_client(created="n9")++ payload = _payload(+ _run(ImaWriteNoteTool(), content="# T\nbody", **{BINDINGS_KWARG: [LIBRARY]})+ )++ assert payload == {"note_id": "n9", "action": "created"}+ assert client.calls[0][0] == "create_note"+ assert stub_client.created["for_write"] is True++ def test_write_note_appends_to_a_named_note(self, stub_client) -> None:+ client = stub_client(appended="n1")++ payload = _payload(+ _run(+ ImaWriteNoteTool(),+ content="more",+ note_id="n1",+ **{BINDINGS_KWARG: [LIBRARY]},+ )+ )++ assert payload == {"note_id": "n1", "action": "appended"}+ assert client.calls[0][0] == "append_note"++ def test_missing_credentials_are_explained(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def resolve(_ref: str, *, for_write: bool = False):+ raise ImaNotConfiguredError("missing API key")++ monkeypatch.setattr(ima_tools, "resolve_client", resolve)++ result = _run(ImaListTool(), **{BINDINGS_KWARG: [LIBRARY]})++ assert result.success is False+ assert "missing API key" in result.content++ def test_inaccessible_knowledge_base_is_reported(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def resolve(_ref: str, *, for_write: bool = False):+ raise RuntimeError("403")++ monkeypatch.setattr(ima_tools, "resolve_client", resolve)++ result = _run(ImaWriteNoteTool(), content="x", **{BINDINGS_KWARG: [LIBRARY]})++ assert result.success is False+ assert "write access" in result.content++ def test_upstream_auth_failure_is_reported_cleanly(self, stub_client) -> None:+ stub_client(page=ImaAuthError("rejected"))++ result = _run(ImaListTool(), **{BINDINGS_KWARG: [LIBRARY]})++ assert result.success is False+ assert "rejected the credentials" in result.contentdiff --git a/tests/capabilities/test_setup_capability.py b/tests/capabilities/test_setup_capability.pynew file mode 100644index 000000000..0a0738076--- /dev/null+++ b/tests/capabilities/test_setup_capability.py@@ -0,0 +1,703 @@+"""Tests for the setup capability: what it may change, and what it must refuse.++Four properties are pinned here because each one fails silently if it breaks:++* **Probe before commit.** The chat model is one of the rows this capability+ writes. If a value were stored before being verified, a bad selection would+ leave the user in a conversation that can no longer answer — including the+ turn that would undo it. The test asserts the stored value is untouched after+ a failing probe, not merely that an error was returned.+* **Scope is enforced, not advertised.** Personal rows are per-user files;+ global rows are the shared deployment settings. A non-administrator writing a+ global row, or a partner writing anything, must be refused at the apply+ boundary rather than by prompt instruction.+* **Activation is objective.** An implicitly-mounted capability that fires on+ the model's sense of relevance shows up in unrelated conversations. The+ activation tests are the guard on that.+* **Coupled settings are reported.** ``interface.json`` inherits the reply+ language from the interface one, so changing the UI language moves a second+ setting. The apply result has to say so.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest++from deeptutor.agents._shared.tool_composition import ToolMountFlags, compose_enabled_tools+from deeptutor.capabilities import active_loop_capabilities, any_exclusive_capability_active+from deeptutor.capabilities.setup import SETUP_TOOL_NAMES, SetupCapability+from deeptutor.capabilities.setup.apply import apply_setting+from deeptutor.capabilities.setup.binding import message_signals_setup, setup_gaps+from deeptutor.capabilities.setup.jobs import run_job+from deeptutor.capabilities.setup.tools import (+ ApplySettingTool,+ InspectSetupTool,+ RequestCredentialTool,+ RunSetupJobTool,+)+from deeptutor.core.context import UnifiedContext+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.config import settings_spec as spec_module+from deeptutor.services.config.settings_spec import ProbeResult, setting_specs+++def isolated_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """Route every settings read/write for this test into ``tmp_path``.++ Both roots are redirected because the two scopes genuinely live in+ different places: personal rows resolve through the path service, global+ rows through the runtime settings directory. A test that redirected only+ one would write the developer's real configuration.+ """+ from deeptutor.services.config import model_catalog, runtime_settings+ from deeptutor.services.path_service import PathService+ from deeptutor.services.settings import interface_settings++ user_root = tmp_path / "user"+ global_settings = tmp_path / "global" / "settings"+ global_settings.mkdir(parents=True, exist_ok=True)+ service = PathService(workspace_root=user_root)++ monkeypatch.setattr(interface_settings, "get_path_service", lambda: service)+ monkeypatch.setattr(model_catalog, "get_path_service", lambda: service)+ monkeypatch.setattr(runtime_settings, "_global_settings_dir", lambda: global_settings)+ return tmp_path+++def _seed_catalog(tmp_path: Path, *, service: str, profile: str, model: str) -> None:+ """Write a catalog with one selectable model for ``service``."""+ from deeptutor.services.config.model_catalog import get_model_catalog_service++ catalog_service = get_model_catalog_service()+ catalog = catalog_service.load()+ catalog["services"][service] = {+ "active_profile_id": profile,+ "active_model_id": model,+ "profiles": [+ {+ "id": profile,+ "name": "Test profile",+ "binding": "openai",+ "base_url": "https://example.invalid/v1",+ "api_key": "sk-test",+ "models": [{"id": model, "name": model, "model": model}],+ }+ ],+ }+ catalog_service.save(catalog)+++# ---------------------------------------------------------------------------+# Spec table+# ---------------------------------------------------------------------------+++def test_every_spec_row_is_readable_and_offers_choices(isolated_settings: Path) -> None:+ specs = setting_specs()+ assert specs, "the spec table must not be empty"+ for key, spec in specs.items():+ assert spec.key == key+ assert spec.scope in {"personal", "global"}+ assert spec.effect in {"instant", "restart", "reindex"}+ assert spec.label and spec.summary+ spec.read()+ spec.choices()+++async def test_no_row_accepts_a_free_form_value(isolated_settings: Path) -> None:+ """Every row is an enumeration, which is what keeps secrets off this surface.++ ``request_credential`` exists because a key must never enter the model's+ context. That guarantee rests on the apply path refusing anything that is+ not one of the row's offered choices — if any row accepted arbitrary text,+ the model could be talked into writing a credential into it. Asserted per+ row rather than by naming suspicious keys, so a row added later is covered+ automatically.+ """+ for key in setting_specs():+ outcome = await apply_setting(key, "sk-arbitrary-free-form-value")+ assert not outcome.ok, f"{key} accepted a value it never offered"+++# ---------------------------------------------------------------------------+# Apply: validation, scope, probe, rollback+# ---------------------------------------------------------------------------+++async def test_apply_personal_setting_persists(isolated_settings: Path) -> None:+ from deeptutor.services.settings.interface_settings import get_ui_settings++ outcome = await apply_setting("interface.theme", "dark")++ assert outcome.ok+ assert outcome.value == "dark"+ assert outcome.previous == "snow"+ assert get_ui_settings()["theme"] == "dark"+++async def test_apply_reports_a_coupled_setting(isolated_settings: Path) -> None:+ outcome = await apply_setting("interface.language", "zh")++ assert outcome.ok+ coupled = {effect.key for effect in outcome.side_effects}+ assert "interface.response_language" in coupled, (+ "changing the interface language also switches replies on a file that "+ "predates the split; the user has to be told"+ )+++async def test_apply_can_be_reverted_with_the_returned_previous(+ isolated_settings: Path,+) -> None:+ from deeptutor.services.settings.interface_settings import get_ui_settings++ forward = await apply_setting("interface.theme", "glass")+ back = await apply_setting("interface.theme", forward.previous)++ assert back.ok+ assert get_ui_settings()["theme"] == "snow"+++async def test_apply_rejects_a_value_outside_the_offered_choices(+ isolated_settings: Path,+) -> None:+ from deeptutor.services.settings.interface_settings import get_ui_settings++ outcome = await apply_setting("interface.language", "klingon")++ assert not outcome.ok+ assert "not one of the available options" in outcome.error+ assert get_ui_settings()["language"] == "en"+++async def test_apply_rejects_an_unknown_key(isolated_settings: Path) -> None:+ outcome = await apply_setting("nope.nope", "x")++ assert not outcome.ok+ assert "Unknown setting" in outcome.error+++async def test_apply_rejects_an_engine_that_is_not_installed(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A selectable-but-missing engine must not be committed.++ ``list_engines`` deliberately reports engines that are not installed so the+ agent can offer to install them; committing one anyway would leave document+ parsing pointed at an engine that raises on first use.+ """+ from deeptutor.services.config.runtime_settings import get_runtime_settings_service+ from deeptutor.services.parsing.engines import factory++ monkeypatch.setattr(factory, "is_engine_available", lambda name: name == "text_only")++ outcome = await apply_setting("document_parsing.engine", "docling")++ assert not outcome.ok+ stored = get_runtime_settings_service().load_document_parsing()+ assert stored["engine"] == "text_only"+++async def test_a_failing_probe_leaves_the_stored_value_untouched(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The self-lockout guard: an unreachable model is never committed."""+ _seed_catalog(isolated_settings, service="llm", profile="p1", model="m1")++ from deeptutor.services.config.model_catalog import get_model_catalog_service++ catalog_service = get_model_catalog_service()+ catalog = catalog_service.load()+ catalog["services"]["llm"]["profiles"][0]["models"].append(+ {"id": "m2", "name": "m2", "model": "m2"}+ )+ catalog_service.save(catalog)++ async def _always_fails(value: str) -> ProbeResult:+ return ProbeResult(ok=False, detail="connection refused")++ monkeypatch.setattr(spec_module, "_probe_llm", _always_fails)++ outcome = await apply_setting("catalog.llm", "p1::m2")++ assert not outcome.ok+ assert outcome.probe is not None and not outcome.probe.ok+ assert "connection refused" in outcome.error+ stored = get_model_catalog_service().load()["services"]["llm"]+ assert stored["active_model_id"] == "m1", "a failed probe must not move the selection"+++async def test_a_passing_probe_commits(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _seed_catalog(isolated_settings, service="llm", profile="p1", model="m1")++ from deeptutor.services.config.model_catalog import get_model_catalog_service++ catalog_service = get_model_catalog_service()+ catalog = catalog_service.load()+ catalog["services"]["llm"]["profiles"][0]["models"].append(+ {"id": "m2", "name": "m2", "model": "m2"}+ )+ catalog_service.save(catalog)++ probed: list[str] = []++ async def _passes(value: str) -> ProbeResult:+ probed.append(value)+ return ProbeResult(ok=True, elapsed_ms=12)++ monkeypatch.setattr(spec_module, "_probe_llm", _passes)++ outcome = await apply_setting("catalog.llm", "p1::m2")++ assert outcome.ok, outcome.error+ assert probed == ["p1::m2"], "the candidate must be probed before it is stored"+ stored = get_model_catalog_service().load()["services"]["llm"]+ assert stored["active_model_id"] == "m2"+++# ---------------------------------------------------------------------------+# Scope enforcement+# ---------------------------------------------------------------------------+++async def test_a_non_admin_cannot_write_a_global_row(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.capabilities.setup import access++ monkeypatch.setattr(access, "_is_admin", lambda: False)+ monkeypatch.setattr(access, "_is_partner_turn", lambda: False)++ outcome = await apply_setting("document_parsing.engine", "markitdown")++ assert not outcome.ok+ assert "administrator" in outcome.error+++async def test_a_non_admin_can_still_write_a_personal_row(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.capabilities.setup import access++ monkeypatch.setattr(access, "_is_admin", lambda: False)+ monkeypatch.setattr(access, "_is_partner_turn", lambda: False)++ outcome = await apply_setting("interface.theme", "dark")++ assert outcome.ok+++async def test_a_partner_turn_is_refused_for_every_scope(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A partner acts under its owner's identity — it must not reconfigure them."""+ from deeptutor.capabilities.setup import access++ monkeypatch.setattr(access, "_is_partner_turn", lambda: True)++ personal = await apply_setting("interface.theme", "dark")+ global_row = await apply_setting("document_parsing.engine", "markitdown")++ assert not personal.ok+ assert not global_row.ok+ assert "partner" in personal.error.lower()+++async def test_run_setup_job_is_refused_for_a_non_admin(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Installing software changes the machine for every account on it."""+ from deeptutor.capabilities.setup import access++ monkeypatch.setattr(access, "_is_admin", lambda: False)+ monkeypatch.setattr(access, "_is_partner_turn", lambda: False)++ result = await RunSetupJobTool().execute(action="install_engine", engine="docling")++ assert not result.success+ assert "administrator" in result.content+++# ---------------------------------------------------------------------------+# Jobs+# ---------------------------------------------------------------------------+++async def test_run_job_refuses_an_unknown_action(isolated_settings: Path) -> None:+ outcome = await run_job("rm_rf", "docling")++ assert not outcome.ok+ assert "Unknown setup job" in outcome.message+++async def test_run_job_refuses_an_engine_outside_the_install_allow_list(+ isolated_settings: Path,+) -> None:+ """The model names an engine id, never a package — the allow-list decides."""+ outcome = await run_job("install_engine", "requests")++ assert not outcome.ok+ assert "no one-step install" in outcome.message+++# ---------------------------------------------------------------------------+# Tools+# ---------------------------------------------------------------------------+++async def test_inspect_reports_rows_gaps_and_jobs(isolated_settings: Path) -> None:+ result = await InspectSetupTool().execute()++ payload = json.loads(result.content)+ assert result.success+ assert {"settings", "gaps", "jobs_available"} <= set(payload)+ keys = {row["key"] for row in payload["settings"]}+ assert "interface.language" in keys+ assert "document_parsing.engine" in keys+ for row in payload["settings"]:+ assert "effect" in row and "scope" in row and "options" in row+++async def test_inspect_filters_by_area(isolated_settings: Path) -> None:+ result = await InspectSetupTool().execute(area="interface")++ payload = json.loads(result.content)+ assert {row["area"] for row in payload["settings"]} == {"interface"}+++async def test_apply_tool_marks_the_ui_slice_stale(isolated_settings: Path) -> None:+ """The frontend caches UI preferences; the result has to invalidate them."""+ result = await ApplySettingTool().execute(key="interface.theme", value="dark")++ assert result.success+ assert result.metadata.get("setup_applied") == {"key": "interface.theme"}+++async def test_credential_tool_hands_off_without_touching_the_secret(+ isolated_settings: Path,+) -> None:+ result = await RequestCredentialTool().execute(service="llm", reason="需要密钥")++ payload: dict[str, Any] = result.metadata["setup_credential"]+ assert result.success+ assert payload["settings_path"] == "/settings/llm"+ assert "api_key" not in result.content+ assert payload["reason"] == "需要密钥"+++async def test_credential_tool_rejects_an_unknown_service(isolated_settings: Path) -> None:+ result = await RequestCredentialTool().execute(service="mainframe")++ assert not result.success+++# ---------------------------------------------------------------------------+# Activation+# ---------------------------------------------------------------------------+++ "message",+ [+ "把界面语言切成中文",+ "界面换成英文吧",+ "帮我配置一下 DeepTutor",+ "能不能换个解析引擎",+ "我想改用别的嵌入模型",+ "switch the chat model to something faster",+ "install a better pdf parser",+ "set up web search for me",+ ],+)+def test_activates_on_a_configuration_request(message: str) -> None:+ assert message_signals_setup(message)+++ "message",+ [+ "这个配置文件太大了打不开",+ "change the subject please",+ "帮我总结这篇论文",+ "用中文回答我",+ "模型是怎么训练的?",+ "下载这篇论文的 PDF",+ "这个引擎的原理是什么",+ "search for papers about transformers",+ "解释一下 embedding 的原理",+ "",+ ],+)+def test_stays_out_of_unrelated_turns(message: str) -> None:+ assert not message_signals_setup(message)+++def test_explicit_selection_activates_without_an_intent_match(+ isolated_settings: Path,+) -> None:+ context = UnifiedContext(+ user_message="hello",+ active_capability="setup",+ conversation_history=[{"role": "user", "content": "hi"}],+ )++ assert SetupCapability().is_active(context)+++def test_capability_is_additive_not_exclusive() -> None:+ """A configuration request often arrives mid-task; the turn keeps its tools."""+ assert not getattr(SetupCapability(), "exclusive_tools", False)+++def test_setup_tools_reach_the_turns_tool_surface(isolated_settings: Path) -> None:+ """The wiring test: registry → active capability → composed tool list.++ Registering the capability and registering its tools are two separate+ steps, and getting either wrong leaves the model with a prompt telling it+ to call tools it cannot see.+ """+ context = UnifiedContext(+ user_message="把界面语言切成中文",+ conversation_history=[{"role": "user", "content": "hi"}],+ )+ active = active_loop_capabilities(context)+ assert any(cap.name == "setup" for cap in active)++ composed = compose_enabled_tools(+ registry=get_tool_registry(),+ requested_tools=["web_search"],+ optional_whitelist=["web_search"],+ mount_flags=ToolMountFlags(),+ capability_owned=tuple(name for cap in active for name in cap.owned_tools),+ exclusive=any_exclusive_capability_active(context),+ )++ assert set(SETUP_TOOL_NAMES).issubset(composed)+ assert "web_search" in composed, "additive: the turn keeps its normal surface"+++def test_setup_tools_stay_off_an_unrelated_turn(isolated_settings: Path) -> None:+ context = UnifiedContext(+ user_message="帮我总结这篇论文",+ conversation_history=[{"role": "user", "content": "hi"}],+ )+ active = active_loop_capabilities(context)++ assert not any(cap.name == "setup" for cap in active)+ composed = compose_enabled_tools(+ registry=get_tool_registry(),+ requested_tools=["web_search"],+ optional_whitelist=["web_search"],+ mount_flags=ToolMountFlags(),+ capability_owned=tuple(name for cap in active for name in cap.owned_tools),+ exclusive=any_exclusive_capability_active(context),+ )+ assert not set(SETUP_TOOL_NAMES) & set(composed)+++def test_owned_tools_match_the_registered_names() -> None:+ assert SetupCapability().owned_tools == SETUP_TOOL_NAMES+++# ---------------------------------------------------------------------------+# Robustness regressions — each of these was a real defect+# ---------------------------------------------------------------------------+++async def test_a_hung_endpoint_cannot_hang_the_turn(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A probe is bounded by its own deadline, not the runtime's retry policy.++ The LLM runtime defaults to 8 retries with a 120s transport timeout each, so+ an endpoint that accepts the connection and then goes quiet would have kept+ a live chat turn waiting roughly a quarter of an hour before reporting a+ failure. The probe therefore sets its own deadline and disables retries.+ """+ import asyncio++ from deeptutor.services.config.settings_spec import _PROBE_TIMEOUT_SECONDS, _probe_llm++ _seed_catalog(isolated_settings, service="llm", profile="p1", model="m1")+ seen: dict[str, Any] = {}++ async def _never_answers(*args: Any, **kwargs: Any) -> str:+ seen.update(kwargs)+ await asyncio.sleep(3600)+ return "unreachable"++ import deeptutor.services.llm as llm_module++ monkeypatch.setattr(llm_module, "complete", _never_answers)+ monkeypatch.setattr(spec_module, "_PROBE_TIMEOUT_SECONDS", 0.2)++ result = await asyncio.wait_for(_probe_llm("p1::m1"), timeout=10)++ assert not result.ok+ assert "No response within" in result.detail+ assert seen.get("max_retries") == 0, "a probe must not inherit the runtime's 8 retries"+ assert _PROBE_TIMEOUT_SECONDS <= 60, "the shipped deadline must stay inside a turn's patience"+++def test_the_first_run_offer_is_not_spent_by_an_ordinary_request(+ isolated_settings: Path,+) -> None:+ """Only an ``intro`` activation may consume the once-ever proactive offer.++ Marking it from every setup turn meant the first time a user asked for+ anything at all ("change the theme") the offer was silently used up, and an+ install that genuinely needed help was never offered any.+ """+ from deeptutor.capabilities.setup.binding import setup_activation++ capability = SetupCapability()+ asked = UnifiedContext(+ user_message="把界面主题换成暗色",+ conversation_history=[{"role": "user", "content": "hi"}],+ )+ assert setup_activation(asked) == "intent"+ capability.system_block(asked, language="zh", prompts={})++ fresh = UnifiedContext(user_message="你好", conversation_history=[])+ assert setup_activation(fresh) == "intro", "the first-run offer must still be available"+++def test_the_first_run_offer_is_spent_once(isolated_settings: Path) -> None:+ from deeptutor.capabilities.setup.binding import setup_activation++ capability = SetupCapability()+ first = UnifiedContext(user_message="你好", conversation_history=[])+ assert setup_activation(first) == "intro"+ block = capability.system_block(first, language="en", prompts={})+ assert block is not None+ assert "first conversation" in block.content++ second = UnifiedContext(user_message="你好", conversation_history=[])+ assert setup_activation(second) == "", "the offer must not repeat every new chat"+++def test_concurrent_preference_writes_do_not_lose_updates(isolated_settings: Path) -> None:+ """``interface.json`` is a read-modify-write on a shared document.++ Unlocked, twelve concurrent writers left two of their fields on disk — the+ rest were overwritten by whichever writer had read an older snapshot.+ """+ import json as json_module+ import threading++ from deeptutor.services.settings.interface_settings import (+ _interface_settings_file,+ set_ui_setting,+ )++ def writer(index: int) -> None:+ for _ in range(20):+ set_ui_setting(f"probe_{index}", index)++ threads = [threading.Thread(target=writer, args=(i,)) for i in range(12)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ stored = json_module.loads(_interface_settings_file().read_text(encoding="utf-8"))+ assert {f"probe_{i}" for i in range(12)} <= set(stored)+++def test_unresolvable_identity_refuses_global_writes(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Failing to resolve who is asking must not grant administrator rights."""+ from deeptutor.capabilities.setup import access++ def _explode() -> Any:+ raise RuntimeError("identity backend down")++ monkeypatch.setattr(access, "_is_partner_turn", lambda: False)+ monkeypatch.setattr("deeptutor.multi_user.context.get_current_user", _explode)++ assert access.can_write("global").allowed is False+ assert access.can_write("personal").allowed is True, "personal rows stay reachable"+++async def test_a_silent_job_still_emits_progress(+ isolated_settings: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A quiet install must not look dead to the chat client.++ The client times out on time since the last event, and pip can download a+ large wheel for minutes without printing anything — so a job that only+ relays real output would have its turn declared dead while healthy.+ """+ from deeptutor.capabilities.setup import jobs++ class _SilentManager:+ def __init__(self) -> None:+ self.polls = 0++ def status(self, cursor: int = 0) -> dict[str, Any]:+ self.polls += 1+ state = "running" if self.polls < 8 else "done"+ return {"state": state, "lines": [], "next_cursor": 0, "message": "Finished."}++ manager = _SilentManager()+ monkeypatch.setattr(jobs, "_start_install", lambda engine: (True, "", manager))+ monkeypatch.setattr(jobs, "_POLL_INTERVAL_SECONDS", 0.01)+ monkeypatch.setattr(jobs, "_HEARTBEAT_SECONDS", 0.02)++ beats: list[str] = []++ async def _on_line(line: str) -> None:+ beats.append(line)++ outcome = await jobs.run_job("install_engine", "docling", on_line=_on_line)++ assert outcome.ok+ assert beats, "a silent job must still emit keep-alives"+ assert all("still working" in beat for beat in beats)+++def test_setup_jobs_are_never_listed_twice(isolated_settings: Path) -> None:+ from deeptutor.capabilities.setup.jobs import available_jobs++ jobs = [(job["action"], job["engine"]) for job in available_jobs()]+ assert len(jobs) == len(set(jobs))+++def test_system_block_names_the_installs_gaps(isolated_settings: Path) -> None:+ context = UnifiedContext(user_message="帮我配置一下 DeepTutor")++ block = SetupCapability().system_block(context, language="zh", prompts={})++ assert block is not None+ assert "missing" in block.content+ assert setup_gaps(), "a fresh install has gaps, so the block should list them"diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.pyindex 5a876eb03..afd51c173 100644--- a/tests/core/test_capabilities_runtime.py+++ b/tests/core/test_capabilities_runtime.py@@ -75,6 +75,7 @@ def test_builtin_capability_registry_covers_documented_capabilities() -> None:"math_animator","visualize","mastery_path",+ "immersive_reading",}diff --git a/tests/knowledge/test_ima_kb.py b/tests/knowledge/test_ima_kb.pyindex 8d81f2fb7..a9ef7af63 100644--- a/tests/knowledge/test_ima_kb.py+++ b/tests/knowledge/test_ima_kb.py@@ -122,10 +122,20 @@ def test_has_no_local_document_root(tmp_path) -> None:assert document_root(manager.base_dir / "IMA", entry) is None-def test_documents_are_reported_as_non_enumerable(tmp_path) -> None:- # IMA holds the documents behind its API; reporting "0 documents" would lie.+def test_documents_are_non_enumerable_when_the_library_is_unreachable(+ tmp_path, monkeypatch+) -> None:+ """The inventory comes from IMA's browse API; unreachable ≠ "0 documents".++ The reader is stubbed to report "cannot determine" (no network in tests), and+ the manifest must then degrade to "not listable" rather than claiming the+ library is empty. Enumeration of a reachable library is covered in+ ``tests/services/rag/test_ima_inventory.py``.+ """+ from deeptutor.knowledge import manifest as manifest_modulefrom deeptutor.knowledge.manifest import UNAVAILABLE_REMOTE, build_manifest+ monkeypatch.setitem(manifest_module._REMOTE_INVENTORY_READERS, "ima", lambda _entry: None)manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))entry = _register(manager)@@ -133,3 +143,22 @@ def test_documents_are_reported_as_non_enumerable(tmp_path) -> None:assert manifest.unavailable == UNAVAILABLE_REMOTEassert manifest.total == 0+++def test_a_reachable_library_enumerates_its_documents(tmp_path, monkeypatch) -> None:+ """The point of the browse API: "what's in here" is answerable for IMA too."""+ from deeptutor.knowledge import manifest as manifest_module+ from deeptutor.knowledge.manifest import build_manifest++ monkeypatch.setitem(+ manifest_module._REMOTE_INVENTORY_READERS,+ "ima",+ lambda _entry: (["a.pdf", "Papers/b.md"], True),+ )+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))+ entry = _register(manager)++ manifest = build_manifest(name="IMA", kb_dir=manager.base_dir / "IMA", entry=entry)++ assert manifest.enumerable+ assert [document.name for document in manifest.documents] == ["a.pdf", "Papers/b.md"]diff --git a/tests/reading/test_capability.py b/tests/reading/test_capability.pynew file mode 100644index 000000000..c2325f671--- /dev/null+++ b/tests/reading/test_capability.py@@ -0,0 +1,596 @@+"""Capability-level tests: activation, prompt, kwarg binding, locate pass, tools.++The store is isolated by pointing ``DEEPTUTOR_HOME`` at a temp dir and resetting+the path-service singleton, so the tools exercise their real resolution path+(``ReadingStore()`` with no arguments) rather than a hand-injected store.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.capabilities.explore_context import ExploreContextCapability+from deeptutor.capabilities.reading import (+ MATERIAL_ID_KEY,+ MATERIAL_KWARG,+ READING_TOOL_NAMES,+ VIEWPORT_KEY,+ ReadingCapability,+)+from deeptutor.capabilities.reading.tools import (+ MaterialOutlineTool,+ ReaderAnnotateTool,+ ReaderGotoTool,+ ReadMaterialTool,+ SearchMaterialTool,+)+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.services.path_service import PathService++pymupdf = pytest.importorskip("pymupdf")+++PAGES = [+ "Chapter one. Sequence models process tokens one at a time.",+ "Chapter two. Transformers use scaled dot-product attention over all tokens.",+ "Chapter three. Positional encoding injects order into the representation.",+]+++def reading_home(monkeypatch, tmp_path: Path):+ """A real per-user store rooted in a temp DEEPTUTOR_HOME."""+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ yield tmp_path+ PathService.reset_instance()+++def material(reading_home: Path):+ from deeptutor.reading import ReadingStore++ source = reading_home / "attention.pdf"+ doc = pymupdf.open()+ for body in PAGES:+ page = doc.new_page()+ page.insert_textbox(pymupdf.Rect(50, 50, 545, 780), body, fontsize=11)+ doc.set_toc([[1, "Introduction", 1], [1, "Transformers", 2]])+ doc.save(source)+ doc.close()++ store = ReadingStore()+ return store.ingest(source)+++def _context(material_id: str = "", **metadata) -> UnifiedContext:+ meta = dict(metadata)+ if material_id:+ meta[MATERIAL_ID_KEY] = material_id+ return UnifiedContext(+ session_id="s1",+ user_message=meta.pop("user_message", "what is attention?"),+ metadata=meta,+ )+++# ---------------------------------------------------------------------------+# activation and isolation+# ---------------------------------------------------------------------------+++def test_capability_activates_only_when_a_material_is_open() -> None:+ capability = ReadingCapability()++ assert capability.is_active(_context("abc123ff")) is True+ assert capability.is_active(_context()) is False+ assert capability.is_active(_context(**{MATERIAL_ID_KEY: " "})) is False+++def test_reading_turns_do_not_activate_the_explore_context_pre_pass() -> None:+ """Two pre-passes must never read the same document.++ Reading material is addressed by locator through the reading store and is+ deliberately absent from ``source_index``, which is exactly what keeps+ explore_context dormant — no coordination code in either capability.+ """+ context = _context("abc123ff")++ assert ReadingCapability().is_active(context) is True+ assert ExploreContextCapability().is_active(context) is False+++def test_capability_owns_exactly_the_five_reading_tools() -> None:+ assert ReadingCapability().owned_tools == READING_TOOL_NAMES+ assert len(READING_TOOL_NAMES) == 5+ # Additive, not exclusive: chat keeps its own surface on a reading turn.+ assert getattr(ReadingCapability(), "exclusive_tools", False) is False+++# ---------------------------------------------------------------------------+# prompt+# ---------------------------------------------------------------------------+++def test_system_block_states_the_unit_range_and_citation_form(material) -> None:+ block = ReadingCapability().system_block(+ _context(material.material_id), language="en", prompts={}+ )++ assert block is not None+ assert "[p.12]" in block.content+ assert "1..3" in block.content+ assert "attention.pdf" in block.content+ assert "reader_goto" in block.content+++def test_system_block_is_localised(material) -> None:+ block = ReadingCapability().system_block(+ _context(material.material_id), language="zh", prompts={}+ )++ assert block is not None+ assert "沉浸式阅读" in block.content+ assert "[p.12]" in block.content+++def test_system_block_reports_a_material_that_disappeared(material) -> None:+ from deeptutor.reading import ReadingStore++ ReadingStore().delete(material.material_id)++ block = ReadingCapability().system_block(+ _context(material.material_id), language="en", prompts={}+ )++ assert block is not None+ assert "no longer available" in block.content+++def test_no_system_block_without_a_material() -> None:+ assert ReadingCapability().system_block(_context(), language="en", prompts={}) is None+++# ---------------------------------------------------------------------------+# kwarg binding+# ---------------------------------------------------------------------------+++def test_augment_kwargs_binds_the_material_to_reading_tools_only() -> None:+ capability = ReadingCapability()+ context = _context("abc123ff")++ bound = capability.augment_kwargs("read_material", {"locators": "2"}, context)+ untouched = capability.augment_kwargs("web_search", {"query": "x"}, context)++ assert bound[MATERIAL_KWARG] == "abc123ff"+ assert MATERIAL_KWARG not in untouched+++def test_augment_kwargs_is_a_noop_without_an_open_material() -> None:+ bound = ReadingCapability().augment_kwargs("read_material", {"locators": "2"}, _context())+ assert MATERIAL_KWARG not in bound+++# ---------------------------------------------------------------------------+# seeds+# ---------------------------------------------------------------------------+++def test_pre_loop_seed_reports_viewport_and_selection() -> None:+ context = _context(+ "abc123ff",+ **{VIEWPORT_KEY: {"locator": 7, "selection": "scaled dot-product attention"}},+ )++ seed = ReadingCapability().pre_loop_seed(context)++ assert "locator 7" in seed+ assert "scaled dot-product attention" in seed+++def test_pre_loop_seed_is_empty_when_nothing_is_open() -> None:+ assert ReadingCapability().pre_loop_seed(_context()) == ""+++async def test_locate_pre_pass_points_at_the_matching_locator(material) -> None:+ context = _context(material.material_id, user_message="what is scaled dot-product attention?")++ block = await ReadingCapability().pre_loop(context, StreamBus())++ assert block is not None+ assert "page 2" in block.content+ assert "verbatim" in block.content or "loose" in block.content+++async def test_locate_pre_pass_stays_silent_when_nothing_matches(material) -> None:+ context = _context(material.material_id, user_message="quantum flux capacitor calibration")++ assert await ReadingCapability().pre_loop(context, StreamBus()) is None+++async def test_locate_pre_pass_costs_no_tokens(material) -> None:+ """The pre-pass is deterministic search, not a second LLM loop."""++ class _Usage:+ def __init__(self) -> None:+ self.calls: list[object] = []++ def __getattr__(self, name): # pragma: no cover - fails the test if hit+ raise AssertionError(f"usage.{name} must not be touched by the locate pass")++ context = _context(material.material_id, user_message="attention")++ block = await ReadingCapability().pre_loop(context, StreamBus(), usage=_Usage())++ assert block is not None+++async def test_locate_pre_pass_survives_a_deleted_material(material) -> None:+ from deeptutor.reading import ReadingStore++ ReadingStore().delete(material.material_id)+ context = _context(material.material_id, user_message="attention")++ assert await ReadingCapability().pre_loop(context, StreamBus()) is None+++# ---------------------------------------------------------------------------+# tools+# ---------------------------------------------------------------------------+++async def test_outline_tool_returns_the_documents_own_headings(material) -> None:+ result = await MaterialOutlineTool().execute(**{MATERIAL_KWARG: material.material_id})++ assert result.success is True+ assert "Transformers" in result.content+++async def test_search_tool_returns_locators_and_citation_sources(material) -> None:+ result = await SearchMaterialTool().execute(+ **{MATERIAL_KWARG: material.material_id, "query": "scaled dot-product"}+ )++ assert "page 2" in result.content+ assert [s["page"] for s in result.sources] == [2]+ assert result.sources[0]["type"] == "reading"+++async def test_search_tool_explains_a_miss_instead_of_failing(material) -> None:+ result = await SearchMaterialTool().execute(+ **{MATERIAL_KWARG: material.material_id, "query": "zzzzqqqq"}+ )++ assert result.success is True+ assert "No match" in result.content+++async def test_read_tool_renders_locator_headers(material) -> None:+ result = await ReadMaterialTool().execute(+ **{MATERIAL_KWARG: material.material_id, "locators": "1-2"}+ )++ assert "--- Page 1 ---" in result.content+ assert "--- Page 2 ---" in result.content+ assert [s["page"] for s in result.sources] == [1, 2]+++async def test_read_tool_reports_an_impossible_locator_without_dying(material) -> None:+ result = await ReadMaterialTool().execute(+ **{MATERIAL_KWARG: material.material_id, "locators": "900"}+ )++ assert result.success is False+ assert "1..3" in result.content+++async def test_tools_report_a_missing_material_binding() -> None:+ result = await ReadMaterialTool().execute(locators="1")++ assert result.success is False+ assert "No reading material is open" in result.content+++async def test_goto_emits_a_reader_action_for_the_client(material) -> None:+ result = await ReaderGotoTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "scaled dot-product",+ }+ )++ assert result.success is True+ assert result.metadata["reader_action"] == "goto"+ assert result.metadata["locator"] == 2+ assert result.metadata["quote"] == "scaled dot-product"+++async def test_a_hallucinated_quote_never_paints_a_highlight(material) -> None:+ """The view may still move; the ink may not.++ Highlighting invented text would put the assistant's fabrication on the page+ itself, which is the one outcome worth refusing. Moving to the locator is+ harmless by comparison — and see the translation tests below for why refusing+ the move as well was the wrong trade.+ """+ result = await ReaderGotoTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "the reptilian moon conspiracy",+ }+ )++ assert result.metadata["quote"] == ""+++async def test_goto_corrects_the_locator_when_the_quote_lives_elsewhere(material) -> None:+ result = await ReaderGotoTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 1,+ "quote": "scaled dot-product",+ }+ )++ assert result.success is True+ assert result.metadata["locator"] == 2+ assert result.metadata["corrected_from"] == 1+ assert "not page 1" in result.content+++async def test_bare_goto_without_a_quote_is_honoured(material) -> None:+ result = await ReaderGotoTool().execute(**{MATERIAL_KWARG: material.material_id, "locator": 3})++ assert result.success is True+ assert result.metadata["locator"] == 3+++async def test_goto_rejects_an_out_of_range_locator(material) -> None:+ result = await ReaderGotoTool().execute(**{MATERIAL_KWARG: material.material_id, "locator": 99})++ assert result.success is False+ assert "between 1 and 3" in result.content+++async def test_annotate_persists_a_mark_attributed_to_the_assistant(material) -> None:+ from deeptutor.reading import ReadingStore++ result = await ReaderAnnotateTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "scaled dot-product",+ "note": "the core mechanism",+ "color": "green",+ }+ )++ assert result.success is True+ stored = ReadingStore().annotations(material.material_id)+ assert len(stored) == 1+ assert stored[0].author == "assistant"+ assert stored[0].color == "green"+ assert stored[0].note == "the core mechanism"+ assert result.metadata["reader_action"] == "annotate"+++async def test_annotate_refuses_a_quote_that_is_not_in_the_document(material) -> None:+ from deeptutor.reading import ReadingStore++ result = await ReaderAnnotateTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "not present anywhere",+ }+ )++ assert result.success is False+ assert ReadingStore().annotations(material.material_id) == []+++async def test_annotate_falls_back_to_a_valid_colour(material) -> None:+ from deeptutor.reading import ReadingStore++ await ReaderAnnotateTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "scaled dot-product",+ "color": "neon-chartreuse",+ }+ )++ assert ReadingStore().annotations(material.material_id)[0].color == "yellow"+++async def test_tool_definitions_never_expose_the_material_id() -> None:+ for tool_type in (+ MaterialOutlineTool,+ SearchMaterialTool,+ ReadMaterialTool,+ ReaderGotoTool,+ ReaderAnnotateTool,+ ):+ definition = tool_type().get_definition()+ names = {p.name for p in definition.parameters}+ assert MATERIAL_KWARG not in names+ assert "material_id" not in names+++# ---------------------------------------------------------------------------+# reading mode with nothing open+# ---------------------------------------------------------------------------+#+# Regression: the capability used to activate only on an open material, so a turn+# taken in reading mode before opening anything was an ordinary chat turn. Asking+# "what does the section on positional encoding say, and where is it?" then+# produced a confident answer about a *different* paper — section number, page+# number and a verbatim-looking quote, all from the model's memory — with nothing+# to tell the reader that no document had been read.+++def _mode_context(**metadata) -> UnifiedContext:+ from deeptutor.capabilities.reading.capability import MODE_KEY++ return _context(**{MODE_KEY: True, **metadata})+++def test_capability_activates_on_the_mode_even_with_nothing_open() -> None:+ assert ReadingCapability().is_active(_mode_context()) is True+++def test_an_ordinary_chat_turn_is_still_untouched() -> None:+ assert ReadingCapability().is_active(_context()) is False+++def test_the_empty_reader_prompt_forbids_answering_from_memory() -> None:+ block = ReadingCapability().system_block(_mode_context(), language="en", prompts={})++ assert block is not None+ content = block.content.lower()+ assert "no document" in content or "not opened" in content+ # The specific failure it exists to prevent must be named, not implied.+ assert "memory" in content+ assert "ask them to drop a file" in content or "open" in content+++def test_the_empty_reader_prompt_is_localised() -> None:+ block = ReadingCapability().system_block(_mode_context(), language="zh", prompts={})++ assert block is not None+ assert "没有任何文档可读" in block.content+++def test_nothing_open_means_no_viewport_seed_and_no_locate_pass() -> None:+ from deeptutor.capabilities.reading.capability import VIEWPORT_KEY++ context = _mode_context(**{VIEWPORT_KEY: {"locator": 4, "selection": "stale"}})++ # A viewport with no document behind it is meaningless; it must not reach the+ # model as if a document were open.+ assert ReadingCapability().pre_loop_seed(context) == ""+++async def test_locate_pass_is_skipped_with_nothing_open() -> None:+ context = _mode_context(user_message="what does chapter three say?")+ assert await ReadingCapability().pre_loop(context, StreamBus()) is None+++async def test_reading_tools_report_the_empty_reader_rather_than_guessing() -> None:+ """The tools are mounted, and their guard is the second line of defence."""+ result = await ReadMaterialTool().execute(locators="1")++ assert result.success is False+ assert "no reading material is open" in result.content.lower()+++# ---------------------------------------------------------------------------+# reader_goto: moving vs highlighting+# ---------------------------------------------------------------------------+#+# The locator and the quote are trusted differently. The locator comes from text+# the model just read; the quote is only what the highlight needs. Refusing the+# whole jump when a quote could not be verified made the reader sit still for the+# most ordinary case there is — answering in one language about a document+# written in another, where the "quote" is the model's own translation.+++async def test_goto_moves_without_highlighting_when_the_quote_is_a_translation(+ material,+) -> None:+ result = await ReaderGotoTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "Transformer 使用缩放点积注意力",+ }+ )++ assert result.success is True+ assert result.metadata["reader_action"] == "goto"+ assert result.metadata["locator"] == 2+ # No highlight: the words are not on the page in that form.+ assert result.metadata["quote"] == ""+ # And the model is told why, so it can pass source-language text next time.+ assert "verbatim" in result.content+++async def test_goto_moves_without_highlighting_for_a_paraphrase(material) -> None:+ result = await ReaderGotoTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "transformers apply scaled dot product attention across all tokens",+ }+ )++ assert result.success is True+ assert result.metadata["locator"] == 2+ assert result.metadata["quote"] == ""+++async def test_a_verbatim_quote_still_highlights(material) -> None:+ result = await ReaderGotoTool().execute(+ **{MATERIAL_KWARG: material.material_id, "locator": 2, "quote": "scaled dot-product"}+ )++ assert result.metadata["quote"] == "scaled dot-product"+++async def test_an_out_of_range_locator_is_still_refused(material) -> None:+ """Moving is forgiving; inventing a page is not."""+ result = await ReaderGotoTool().execute(+ **{MATERIAL_KWARG: material.material_id, "locator": 99, "quote": "anything"}+ )++ assert result.success is False+ assert "reader_action" not in (result.metadata or {})+++async def test_saved_annotations_stay_strict(material) -> None:+ """A mark persists and is exported, so it may not land on unverified text."""+ from deeptutor.reading import ReadingStore++ result = await ReaderAnnotateTool().execute(+ **{+ MATERIAL_KWARG: material.material_id,+ "locator": 2,+ "quote": "Transformer 使用缩放点积注意力",+ }+ )++ assert result.success is False+ assert ReadingStore().annotations(material.material_id) == []diff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.pynew file mode 100644index 000000000..4428d8f2b--- /dev/null+++ b/tests/reading/test_engine.py@@ -0,0 +1,625 @@+"""Engine-level tests for immersive reading: extract → store → search → export.++These exercise the pure engine against a temp root, so nothing here needs the+path service, a user workspace, or an LLM.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.reading import (+ Annotation,+ MaterialNotFound,+ ReadingError,+ ReadingStore,+ Rect,+ export_material,+ parse_locators,+ render_outline,+ render_units,+ search_material,+ verify_quote,+)+from deeptutor.reading.extract import (+ SECTION_TARGET_CHARS,+ extract_material,+ first_line_label,+ split_into_sections,+)+from deeptutor.reading.search import normalise, search_units, terms_of++pymupdf = pytest.importorskip("pymupdf")+++# ---------------------------------------------------------------------------+# fixtures+# ---------------------------------------------------------------------------+++def _write_pdf(path: Path, pages: list[str], *, toc: list | None = None) -> Path:+ doc = pymupdf.open()+ for body in pages:+ page = doc.new_page()+ page.insert_textbox(pymupdf.Rect(50, 50, 545, 780), body, fontsize=11)+ if toc:+ doc.set_toc(toc)+ doc.save(path)+ doc.close()+ return path+++def pdf_path(tmp_path: Path) -> Path:+ return _write_pdf(+ tmp_path / "attention.pdf",+ [+ "Chapter one. Introduction to sequence models and their limits.",+ "Chapter two. Transformers use scaled dot-product attention.",+ "Chapter three. Positional encoding injects order information.",+ ],+ toc=[[1, "Introduction", 1], [1, "Transformers", 2], [2, "Positional encoding", 3]],+ )+++def store(tmp_path: Path) -> ReadingStore:+ return ReadingStore(root=tmp_path / "materials")+++# ---------------------------------------------------------------------------+# extract+# ---------------------------------------------------------------------------+++def test_pdf_extracts_one_unit_per_page_with_its_own_outline(pdf_path: Path) -> None:+ extraction = extract_material(pdf_path)++ assert extraction.unit == "page"+ assert len(extraction.units) == 3+ assert "scaled dot-product" in extraction.units[1]+ assert extraction.has_raw_view is True+ # The document's own bookmarks win over synthesised labels.+ assert [(e.locator, e.title) for e in extraction.outline] == [+ (1, "Introduction"),+ (2, "Transformers"),+ (3, "Positional encoding"),+ ]+ assert extraction.outline[2].level == 2+++def test_pdf_outline_drops_bookmarks_pointing_outside_the_page_range(tmp_path: Path) -> None:+ path = _write_pdf(tmp_path / "bad_toc.pdf", ["only page"], toc=[[1, "Ghost", 1]])+ doc = pymupdf.open(path)+ # Rewrite the bookmark to a page that does not exist, the way some+ # generators do; the extractor must skip it rather than clamp it.+ doc.set_toc([[1, "Ghost", 1]])+ doc.save(tmp_path / "bad_toc2.pdf")+ doc.close()++ extraction = extract_material(tmp_path / "bad_toc2.pdf")+ assert all(1 <= e.locator <= len(extraction.units) for e in extraction.outline)+++def test_text_file_is_cut_into_sections_on_paragraph_boundaries(tmp_path: Path) -> None:+ paragraph = "Dense prose about attention mechanisms. " * 30 # ~1.2k chars+ path = tmp_path / "notes.md"+ path.write_text("\n\n".join([paragraph] * 8), encoding="utf-8")++ extraction = extract_material(path)++ assert extraction.unit == "section"+ assert extraction.has_raw_view is False+ assert len(extraction.units) > 1+ # Cuts land on paragraph boundaries, so no unit starts mid-sentence.+ assert all(unit.startswith("Dense prose") for unit in extraction.units)+++def test_pptx_slides_become_units_when_the_extractor_marks_them(tmp_path: Path) -> None:+ pytest.importorskip("pptx")+ from pptx import Presentation+ from pptx.util import Inches++ prs = Presentation()+ for text in ("First slide body", "Second slide body"):+ slide = prs.slides.add_slide(prs.slide_layouts[5])+ box = slide.shapes.add_textbox(Inches(1), Inches(1), Inches(4), Inches(1))+ box.text_frame.text = text+ path = tmp_path / "deck.pptx"+ prs.save(path)++ extraction = extract_material(path)++ assert extraction.unit == "slide"+ assert len(extraction.units) == 2+ assert "First slide body" in extraction.units[0]+++def test_empty_and_unreadable_sources_raise_reading_error(tmp_path: Path) -> None:+ missing = tmp_path / "nope.pdf"+ with pytest.raises(ReadingError):+ extract_material(missing)++ blank = tmp_path / "blank.txt"+ blank.write_text(" \n\n ", encoding="utf-8")+ with pytest.raises(ReadingError):+ extract_material(blank)+++def test_a_single_enormous_line_is_still_split(tmp_path: Path) -> None:+ path = tmp_path / "minified.txt"+ path.write_text("x" * (SECTION_TARGET_CHARS * 4), encoding="utf-8")++ units = split_into_sections(path.read_text(encoding="utf-8"))++ assert len(units) > 1+ assert all(units)+++def test_first_line_label_prefers_a_markdown_heading() -> None:+ assert first_line_label("## Attention\n\nbody text") == "Attention"+ assert first_line_label("plain first line\nsecond") == "plain first line"+ assert first_line_label("\n\n") == ""+++# ---------------------------------------------------------------------------+# store+# ---------------------------------------------------------------------------+++def test_ingest_writes_units_raw_and_manifest(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ assert manifest.unit_count == 3+ assert manifest.has_raw_view is True+ assert manifest.filename == "attention.pdf"+ assert store.exists(manifest.material_id)+ assert store.unit_text(manifest.material_id, 2).find("scaled dot-product") >= 0+ raw = store.raw_path(manifest.material_id)+ assert raw is not None and raw.read_bytes()[:5] == b"%PDF-"+++def test_reingesting_the_same_bytes_reuses_the_material_and_its_annotations(+ store: ReadingStore, pdf_path: Path, tmp_path: Path+) -> None:+ first = store.ingest(pdf_path)+ store.save_annotation(+ first.material_id,+ Annotation(annotation_id="", locator=2, quote="attention", note="key idea"),+ )++ copy = tmp_path / "renamed.pdf"+ copy.write_bytes(pdf_path.read_bytes())+ second = store.ingest(copy)++ assert second.material_id == first.material_id+ assert [a.note for a in store.annotations(second.material_id)] == ["key idea"]+++def test_unknown_material_and_bad_id_are_distinguishable(store: ReadingStore) -> None:+ with pytest.raises(MaterialNotFound):+ store.manifest("0123456789abcdef")+ with pytest.raises(ReadingError):+ store.manifest("../../etc/passwd")+ with pytest.raises(ReadingError):+ store.manifest("NOT-HEX")+++def test_out_of_range_locator_reports_the_real_range(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)+ with pytest.raises(ReadingError) as excinfo:+ store.unit_text(manifest.material_id, 99)+ assert "3" in str(excinfo.value)+++def test_read_units_is_bounded_and_says_so(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ rows, truncated = store.read_units(manifest.material_id, [1, 2, 3], max_chars=40)++ assert truncated is True+ assert sum(len(text) for _, text in rows) <= 40+++def test_list_materials_is_newest_first_and_skips_junk(+ store: ReadingStore, pdf_path: Path, tmp_path: Path+) -> None:+ first = store.ingest(pdf_path)+ other = _write_pdf(tmp_path / "second.pdf", ["another document body"])+ second = store.ingest(other)+ (store.root / "not-a-material").mkdir(parents=True, exist_ok=True)++ ids = [m.material_id for m in store.list_materials()]++ assert set(ids) == {first.material_id, second.material_id}+ assert len(ids) == 2+++def test_delete_removes_everything(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)+ assert store.delete(manifest.material_id) is True+ assert store.exists(manifest.material_id) is False+ assert store.delete(manifest.material_id) is False+++def test_partial_ingest_is_repaired_on_the_next_upload(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)+ # Simulate a crash between unit writes: the last unit is gone but the+ # manifest still claims it.+ (store.root / manifest.material_id / "units" / "0003.txt").unlink()++ reingested = store.ingest(pdf_path)++ assert reingested.unit_count == 3+ assert store.unit_text(reingested.material_id, 3).strip() != ""+++# ---------------------------------------------------------------------------+# annotations+# ---------------------------------------------------------------------------+++def test_annotations_round_trip_with_generated_ids(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ saved = store.save_annotation(+ manifest.material_id,+ Annotation(+ annotation_id="",+ locator=1,+ quote="Introduction",+ note="start here",+ rects=(Rect(0.1, 0.2, 0.5, 0.25),),+ ),+ )++ assert saved.annotation_id+ stored = store.annotations(manifest.material_id)+ assert len(stored) == 1+ assert stored[0].rects[0].to_list() == [0.1, 0.2, 0.5, 0.25]+++def test_saving_the_same_id_updates_in_place_and_keeps_created_at(+ store: ReadingStore, pdf_path: Path+) -> None:+ manifest = store.ingest(pdf_path)+ first = store.save_annotation(+ manifest.material_id, Annotation(annotation_id="", locator=1, note="v1")+ )++ updated = store.save_annotation(+ manifest.material_id,+ Annotation(annotation_id=first.annotation_id, locator=1, note="v2"),+ )++ assert updated.created_at == first.created_at+ assert updated.updated_at >= first.updated_at+ assert [a.note for a in store.annotations(manifest.material_id)] == ["v2"]+++def test_annotation_on_a_nonexistent_locator_is_rejected(+ store: ReadingStore, pdf_path: Path+) -> None:+ manifest = store.ingest(pdf_path)+ with pytest.raises(ReadingError):+ store.save_annotation(manifest.material_id, Annotation(annotation_id="", locator=42))+++def test_delete_annotation_reports_whether_it_existed(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)+ saved = store.save_annotation(+ manifest.material_id, Annotation(annotation_id="", locator=1, note="x")+ )++ assert store.delete_annotation(manifest.material_id, saved.annotation_id) is True+ assert store.delete_annotation(manifest.material_id, saved.annotation_id) is False+ assert store.annotations(manifest.material_id) == []+++def test_malformed_rects_and_colors_are_normalised_not_trusted() -> None:+ parsed = Annotation.from_dict(+ {+ "annotation_id": "a1",+ "locator": 2,+ "kind": "scribble",+ "color": "neon",+ "rects": [[0.9, 0.9, 0.1, 0.1], "garbage", [0, 0, 0, 0], {"x0": 0, "y0": 0}],+ }+ )++ assert parsed.kind == "highlight"+ assert parsed.color == "yellow"+ # Inverted rect is ordered; degenerate and unparseable rects are dropped.+ assert [r.to_list() for r in parsed.rects] == [[0.1, 0.1, 0.9, 0.9]]+++# ---------------------------------------------------------------------------+# search+# ---------------------------------------------------------------------------+++def test_exact_search_returns_the_locator_and_a_snippet(+ store: ReadingStore, pdf_path: Path+) -> None:+ manifest = store.ingest(pdf_path)++ result = search_material(store, manifest.material_id, "scaled dot-product")++ assert result.mode == "exact"+ assert [hit.locator for hit in result.hits] == [2]+ assert "dot-product" in result.hits[0].snippet+++def test_search_tolerates_line_wrapped_quotes() -> None:+ units = [(1, "Transformers use scaled\ndot-product attention today.")]++ result = search_units(units, "scaled dot-product attention")++ assert result.mode == "normalised"+ assert result.hits[0].locator == 1+++def test_term_ranking_is_the_fallback_and_prefers_more_matches() -> None:+ units = [+ (1, "positional encoding only"),+ (2, "attention and positional encoding together"),+ (3, "nothing relevant here"),+ ]++ result = search_units(units, "attention positional encoding")++ assert result.mode == "terms"+ assert result.hits[0].locator == 2+++def test_search_returns_empty_for_a_blank_or_unmatched_query() -> None:+ units = [(1, "alpha beta")]+ assert search_units(units, " ").is_empty+ assert search_units(units, "zzzzqqq").is_empty+++def test_cjk_queries_are_bigram_expanded_so_they_match_partially() -> None:+ assert "注意" in terms_of("注意力机制")+ units = [(1, "本页讨论注意力机制的实现"), (2, "无关内容")]++ result = search_units(units, "注意力机制的推导")++ assert result.hits[0].locator == 1+++def test_normalise_softens_quotes_and_whitespace() -> None:+ assert normalise("“Hello, world!”") == normalise("Hello world")+++def test_search_marks_truncation_when_more_hits_exist() -> None:+ units = [(i, "needle here") for i in range(1, 8)]++ result = search_units(units, "needle", limit=3)++ assert len(result.hits) == 3+ assert result.truncated is True+++# ---------------------------------------------------------------------------+# service+# ---------------------------------------------------------------------------+++ ("spec", "expected"),+ [+ ("2", [2]),+ (2, [2]),+ ("1-3", [1, 2, 3]),+ ("1–3", [1, 2, 3]),+ ("3,1", [1, 3]),+ ("1, 1, 2", [1, 2]),+ ([3, 2], [2, 3]),+ ("2-1", [1, 2]),+ ],+)+def test_parse_locators_accepts_the_grammar_the_model_types(spec, expected) -> None:+ assert parse_locators(spec, unit_count=3) == expected+++def test_parse_locators_drops_out_of_range_and_raises_when_nothing_is_left() -> None:+ assert parse_locators("2,99", unit_count=3) == [2]+ with pytest.raises(ReadingError):+ parse_locators("99", unit_count=3)+ with pytest.raises(ReadingError):+ parse_locators("garbage", unit_count=3)+++def test_parse_locators_bounds_an_absurd_range_without_materialising_it() -> None:+ assert len(parse_locators("1-100000", unit_count=500)) <= 24+++def test_render_units_labels_by_unit_kind(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ rendered = render_units(store, manifest.material_id, "1-2")++ assert "--- Page 1 ---" in rendered.text+ assert "--- Page 2 ---" in rendered.text+ assert rendered.locators == (1, 2)+ assert rendered.truncated is False+++def test_render_units_announces_truncation(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ rendered = render_units(store, manifest.material_id, "1-3", max_chars=30)++ assert rendered.truncated is True+ assert "truncated" in rendered.text+++def test_render_outline_uses_the_documents_own_titles(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ text = render_outline(store, manifest.material_id)++ assert "page 2: Transformers" in text+ assert "attention.pdf" in text+++def test_render_outline_falls_back_to_first_lines(store: ReadingStore, tmp_path: Path) -> None:+ path = tmp_path / "plain.md"+ path.write_text("# Alpha\nbody\n\n" + ("filler. " * 500) + "\n\n# Beta\nmore", encoding="utf-8")+ manifest = store.ingest(path)++ text = render_outline(store, manifest.material_id)++ assert "Alpha" in text+++def test_verify_quote_confirms_a_real_quote(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ check = verify_quote(store, manifest.material_id, 2, "scaled dot-product")++ assert check.verified is True+ assert check.moved is False+++def test_verify_quote_finds_the_right_locator_when_the_model_guessed_wrong(+ store: ReadingStore, pdf_path: Path+) -> None:+ manifest = store.ingest(pdf_path)++ check = verify_quote(store, manifest.material_id, 1, "scaled dot-product")++ assert check.verified is True+ assert check.found_locator == 2+ assert check.moved is True+++def test_verify_quote_rejects_a_hallucinated_quote(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)++ check = verify_quote(store, manifest.material_id, 2, "quantum flux capacitor")++ assert check.verified is False+++# ---------------------------------------------------------------------------+# export+# ---------------------------------------------------------------------------+++def test_pdf_export_writes_real_annotations_back_into_the_file(+ store: ReadingStore, pdf_path: Path+) -> None:+ manifest = store.ingest(pdf_path)+ store.save_annotation(+ manifest.material_id,+ Annotation(+ annotation_id="",+ locator=2,+ kind="highlight",+ color="green",+ quote="scaled dot-product",+ note="the core mechanism",+ rects=(Rect(0.1, 0.1, 0.8, 0.15),),+ ),+ )++ result = export_material(store, manifest.material_id, fmt="pdf")++ assert result.filename == "attention-annotated.pdf"+ assert result.media_type == "application/pdf"+ with pymupdf.open(stream=result.data, filetype="pdf") as doc:+ annots = list(doc[1].annots())+ assert len(annots) == 1+ assert annots[0].info.get("content") == "the core mechanism"+++def test_pdf_export_with_no_annotations_returns_the_original_bytes(+ store: ReadingStore, pdf_path: Path+) -> None:+ manifest = store.ingest(pdf_path)++ result = export_material(store, manifest.material_id, fmt="pdf")++ assert result.data == pdf_path.read_bytes()+++def test_pdf_export_survives_one_unusable_annotation(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)+ store.save_annotation(+ manifest.material_id,+ Annotation(annotation_id="", locator=1, kind="note", note="whole-page note"),+ )+ store.save_annotation(+ manifest.material_id,+ Annotation(+ annotation_id="",+ locator=2,+ kind="highlight",+ quote="attention",+ rects=(Rect(0.2, 0.2, 0.7, 0.26),),+ ),+ )++ result = export_material(store, manifest.material_id, fmt="pdf")++ with pymupdf.open(stream=result.data, filetype="pdf") as doc:+ assert len(list(doc[0].annots())) == 1+ assert len(list(doc[1].annots())) == 1+++def test_markdown_export_lists_marks_in_locator_order(store: ReadingStore, pdf_path: Path) -> None:+ manifest = store.ingest(pdf_path)+ store.save_annotation(+ manifest.material_id,+ Annotation(annotation_id="", locator=3, quote="Positional encoding", note="later"),+ )+ store.save_annotation(+ manifest.material_id,+ Annotation(annotation_id="", locator=1, quote="Introduction", note="first"),+ )++ result = export_material(store, manifest.material_id, fmt="markdown")+ text = result.data.decode("utf-8")++ assert result.filename == "attention-annotations.md"+ assert text.index("Page 1") < text.index("Page 3")+ assert "> Introduction" in text+ assert "first" in text+++def test_markdown_export_handles_a_material_with_no_annotations(+ store: ReadingStore, tmp_path: Path+) -> None:+ path = tmp_path / "notes.txt"+ path.write_text("some readable content here", encoding="utf-8")+ manifest = store.ingest(path)++ result = export_material(store, manifest.material_id, fmt="markdown")++ assert "No annotations yet" in result.data.decode("utf-8")+++def test_auto_export_picks_pdf_for_pdfs_and_markdown_otherwise(+ store: ReadingStore, pdf_path: Path, tmp_path: Path+) -> None:+ pdf_manifest = store.ingest(pdf_path)+ text_path = tmp_path / "notes.txt"+ text_path.write_text("readable content", encoding="utf-8")+ text_manifest = store.ingest(text_path)++ assert export_material(store, pdf_manifest.material_id).media_type == "application/pdf"+ assert "markdown" in export_material(store, text_manifest.material_id).media_type+++def test_pdf_export_is_refused_for_a_text_only_material(+ store: ReadingStore, tmp_path: Path+) -> None:+ path = tmp_path / "notes.txt"+ path.write_text("readable content", encoding="utf-8")+ manifest = store.ingest(path)++ with pytest.raises(ReadingError):+ export_material(store, manifest.material_id, fmt="pdf")diff --git a/tests/reading/test_mode_registration.py b/tests/reading/test_mode_registration.pynew file mode 100644index 000000000..4fc93e682--- /dev/null+++ b/tests/reading/test_mode_registration.py@@ -0,0 +1,65 @@+"""The immersive-reading mode must be resolvable by the orchestrator.++This file exists because of a real failure: the loop capability and its tools+were registered, but the *mode* the composer sends as ``capability`` was not, so+every turn died with "Unknown capability: immersive_reading". The two registries+are separate on purpose — one holds modes the user picks, the other holds+turn-scoped loop capabilities — and nothing previously forced them to agree.+"""++from __future__ import annotations++import pytest++from deeptutor.capabilities.reading import READING_TOOL_NAMES+from deeptutor.capabilities.registry import LOOP_CAPABILITIES, capability_tool_owners+from deeptutor.runtime.bootstrap.builtin_capabilities import BUILTIN_CAPABILITY_CLASSES+from deeptutor.runtime.registry.capability_registry import get_capability_registry+++def test_immersive_reading_is_a_resolvable_mode() -> None:+ registry = get_capability_registry()++ capability = registry.get("immersive_reading")++ assert capability is not None, (+ "the composer sends capability='immersive_reading'; without a registered "+ "mode the orchestrator rejects the turn before it starts"+ )+ assert capability.manifest.name == "immersive_reading"++[email protected]("name", sorted(BUILTIN_CAPABILITY_CLASSES))+def test_every_declared_mode_loads_and_reports_its_own_name(name: str) -> None:+ """A typo in the class path or a mismatched manifest name fails here.++ Both are silent otherwise: the mode simply disappears from the list and the+ only symptom is a rejected turn.+ """+ capability = get_capability_registry().get(name)++ assert capability is not None, f"{name} is declared but does not load"+ assert capability.manifest.name == name+++def test_the_reading_mode_and_its_loop_capability_are_both_registered() -> None:+ """The feature needs both halves: the mode routes the turn, the loop+ capability supplies the tools once a document is open."""+ assert get_capability_registry().get("immersive_reading") is not None+ assert any(cap.name == "immersive_reading" for cap in LOOP_CAPABILITIES)+++def test_reading_tools_are_attributed_to_the_reading_capability() -> None:+ owners = capability_tool_owners()++ for tool in READING_TOOL_NAMES:+ assert owners.get(tool) == "immersive_reading", (+ f"{tool} must be grouped under its owning capability in the settings UI"+ )+++def test_the_mode_declares_the_tools_it_actually_mounts() -> None:+ manifest = get_capability_registry().get("immersive_reading").manifest++ for tool in READING_TOOL_NAMES:+ assert tool in manifest.tools_useddiff --git a/tests/reading/test_router.py b/tests/reading/test_router.pynew file mode 100644index 000000000..30d90f10c--- /dev/null+++ b/tests/reading/test_router.py@@ -0,0 +1,361 @@+"""Router tests for the reading API, driven through a real ASGI client.++Mounted on a bare FastAPI app rather than the full one so the suite does not+boot every other router; the routes themselves are the real ones.+"""++from __future__ import annotations++import io+from pathlib import Path++from fastapi import FastAPI+from fastapi.testclient import TestClient+import pytest++from deeptutor.api.routers import reading+from deeptutor.services.path_service import PathService++pymupdf = pytest.importorskip("pymupdf")+++PAGES = [+ "Chapter one. Sequence models read tokens one at a time.",+ "Chapter two. Transformers use scaled dot-product attention.",+]+++def client(monkeypatch, tmp_path: Path):+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ app = FastAPI()+ app.include_router(reading.router, prefix="/api/v1/reading")+ with TestClient(app) as test_client:+ yield test_client+ PathService.reset_instance()+++def _pdf_bytes(pages: list[str] = PAGES, *, toc: bool = True) -> bytes:+ doc = pymupdf.open()+ for body in pages:+ page = doc.new_page()+ page.insert_textbox(pymupdf.Rect(50, 50, 545, 780), body, fontsize=11)+ if toc:+ doc.set_toc([[1, "Introduction", 1], [1, "Transformers", 2]])+ data = doc.tobytes()+ doc.close()+ return data+++def _upload(client: TestClient, name: str = "attention.pdf", data: bytes | None = None):+ payload = data if data is not None else _pdf_bytes()+ response = client.post(+ "/api/v1/reading/materials",+ files={"file": (name, io.BytesIO(payload), "application/pdf")},+ )+ assert response.status_code == 200, response.text+ return response.json()+++# ---------------------------------------------------------------------------+# materials+# ---------------------------------------------------------------------------+++def test_upload_returns_a_readable_material_with_its_outline(client: TestClient) -> None:+ body = _upload(client)++ assert body["unit"] == "page"+ assert body["unit_count"] == 2+ assert body["has_raw_view"] is True+ assert body["annotation_count"] == 0+ assert [row["title"] for row in body["outline"]] == ["Introduction", "Transformers"]+ assert "attention.pdf" in body["outline_text"]+++def test_upload_rejects_an_empty_file(client: TestClient) -> None:+ response = client.post(+ "/api/v1/reading/materials",+ files={"file": ("empty.pdf", io.BytesIO(b""), "application/pdf")},+ )++ assert response.status_code == 400+++def test_upload_rejects_an_oversized_file(client: TestClient, monkeypatch) -> None:+ monkeypatch.setattr(reading, "MAX_MATERIAL_BYTES", 1024)++ response = client.post(+ "/api/v1/reading/materials",+ files={"file": ("big.txt", io.BytesIO(b"x" * 4096), "text/plain")},+ )++ assert response.status_code == 413+++def test_upload_of_an_image_only_pdf_explains_itself(client: TestClient) -> None:+ doc = pymupdf.open()+ doc.new_page() # a page with no text at all+ blank = doc.tobytes()+ doc.close()++ response = client.post(+ "/api/v1/reading/materials",+ files={"file": ("scan.pdf", io.BytesIO(blank), "application/pdf")},+ )++ assert response.status_code == 400+ assert "OCR" in response.json()["detail"]+++def test_list_materials_reports_annotation_counts(client: TestClient) -> None:+ material = _upload(client)+ client.put(+ f"/api/v1/reading/materials/{material['material_id']}/annotations",+ json={"locator": 1, "quote": "Sequence models", "note": "n"},+ )++ rows = client.get("/api/v1/reading/materials").json()++ assert len(rows) == 1+ assert rows[0]["annotation_count"] == 1+++def test_get_material_404s_for_an_unknown_id(client: TestClient) -> None:+ response = client.get("/api/v1/reading/materials/0123456789abcdef")+ assert response.status_code == 404+++def test_get_material_400s_for_a_traversal_attempt(client: TestClient) -> None:+ response = client.get("/api/v1/reading/materials/..%2F..%2Fetc")+ assert response.status_code in (400, 404)+++def test_delete_material_is_idempotent_then_404s(client: TestClient) -> None:+ material = _upload(client)+ material_id = material["material_id"]++ assert client.delete(f"/api/v1/reading/materials/{material_id}").status_code == 200+ assert client.delete(f"/api/v1/reading/materials/{material_id}").status_code == 404+++def test_supported_formats_names_pdf_as_the_faithful_view(client: TestClient) -> None:+ body = client.get("/api/v1/reading/supported-formats").json()++ assert ".pdf" in body["extensions"]+ assert ".epub" in body["extensions"]+ assert body["raw_view_extensions"] == [".pdf"]+ assert body["max_bytes"] > 0+++# ---------------------------------------------------------------------------+# unit text and raw bytes+# ---------------------------------------------------------------------------+++def test_unit_text_is_addressed_by_locator(client: TestClient) -> None:+ material = _upload(client)++ body = client.get(f"/api/v1/reading/materials/{material['material_id']}/units/2").json()++ assert body["locator"] == 2+ assert body["unit"] == "page"+ assert "scaled dot-product" in body["text"]+++def test_unit_text_out_of_range_is_a_400_with_the_real_range(client: TestClient) -> None:+ material = _upload(client)++ response = client.get(f"/api/v1/reading/materials/{material['material_id']}/units/99")++ assert response.status_code == 400+ assert "2" in response.json()["detail"]+++def test_raw_route_serves_the_pdf_inline_and_accepts_ranges(client: TestClient) -> None:+ material = _upload(client)++ response = client.get(f"/api/v1/reading/materials/{material['material_id']}/raw")++ assert response.status_code == 200+ assert response.headers["content-type"] == "application/pdf"+ assert "inline" in response.headers["content-disposition"]+ assert response.content[:5] == b"%PDF-"++ partial = client.get(+ f"/api/v1/reading/materials/{material['material_id']}/raw",+ headers={"Range": "bytes=0-99"},+ )+ # Range support is what lets pdf.js stream a large book.+ assert partial.status_code == 206+ assert len(partial.content) == 100+++def test_raw_route_404s_for_a_text_only_material(client: TestClient) -> None:+ material = _upload(client, name="notes.txt", data=b"plain readable text content")++ response = client.get(f"/api/v1/reading/materials/{material['material_id']}/raw")++ assert response.status_code == 404+++# ---------------------------------------------------------------------------+# annotations+# ---------------------------------------------------------------------------+++def test_annotation_create_update_list_delete_round_trip(client: TestClient) -> None:+ material = _upload(client)+ base = f"/api/v1/reading/materials/{material['material_id']}/annotations"++ created = client.put(+ base,+ json={+ "locator": 2,+ "kind": "highlight",+ "color": "blue",+ "quote": "scaled dot-product",+ "note": "core",+ "rects": [[0.1, 0.2, 0.6, 0.24]],+ },+ ).json()+ assert created["annotation_id"]+ assert created["author"] == "user"+ assert created["rects"] == [[0.1, 0.2, 0.6, 0.24]]++ updated = client.put(+ base,+ json={+ "annotation_id": created["annotation_id"],+ "locator": 2,+ "quote": "scaled dot-product",+ "note": "revised",+ },+ ).json()+ assert updated["note"] == "revised"++ rows = client.get(base).json()+ assert len(rows) == 1++ assert client.delete(f"{base}/{created['annotation_id']}").status_code == 200+ assert client.get(base).json() == []+ assert client.delete(f"{base}/{created['annotation_id']}").status_code == 404+++def test_annotation_on_an_out_of_range_locator_is_a_400(client: TestClient) -> None:+ material = _upload(client)++ response = client.put(+ f"/api/v1/reading/materials/{material['material_id']}/annotations",+ json={"locator": 99, "quote": "x"},+ )++ assert response.status_code == 400+++def test_annotation_locator_must_be_positive(client: TestClient) -> None:+ material = _upload(client)++ response = client.put(+ f"/api/v1/reading/materials/{material['material_id']}/annotations",+ json={"locator": 0, "quote": "x"},+ )++ assert response.status_code == 422+++def test_unknown_colour_is_normalised_rather_than_rejected(client: TestClient) -> None:+ material = _upload(client)++ created = client.put(+ f"/api/v1/reading/materials/{material['material_id']}/annotations",+ json={"locator": 1, "quote": "Sequence models", "color": "neon"},+ ).json()++ assert created["color"] == "yellow"+++def test_inverted_rects_are_ordered_server_side(client: TestClient) -> None:+ material = _upload(client)++ created = client.put(+ f"/api/v1/reading/materials/{material['material_id']}/annotations",+ json={"locator": 1, "quote": "x", "rects": [[0.9, 0.9, 0.2, 0.2]]},+ ).json()++ assert created["rects"] == [[0.2, 0.2, 0.9, 0.9]]+++# ---------------------------------------------------------------------------+# export+# ---------------------------------------------------------------------------+++def test_pdf_export_contains_the_annotation(client: TestClient) -> None:+ material = _upload(client)+ client.put(+ f"/api/v1/reading/materials/{material['material_id']}/annotations",+ json={+ "locator": 2,+ "quote": "scaled dot-product",+ "note": "core mechanism",+ "rects": [[0.1, 0.1, 0.8, 0.16]],+ },+ )++ response = client.get(f"/api/v1/reading/materials/{material['material_id']}/export")++ assert response.status_code == 200+ assert response.headers["content-type"] == "application/pdf"+ assert "attention-annotated.pdf" in response.headers["content-disposition"]+ with pymupdf.open(stream=response.content, filetype="pdf") as doc:+ annots = list(doc[1].annots())+ assert len(annots) == 1+ assert annots[0].info.get("content") == "core mechanism"+++def test_markdown_export_is_the_default_for_text_materials(client: TestClient) -> None:+ material = _upload(client, name="notes.md", data=b"# Alpha\n\nsome readable body text")+ client.put(+ f"/api/v1/reading/materials/{material['material_id']}/annotations",+ json={"locator": 1, "quote": "readable body", "note": "keep"},+ )++ response = client.get(f"/api/v1/reading/materials/{material['material_id']}/export")++ assert "markdown" in response.headers["content-type"]+ text = response.content.decode("utf-8")+ assert "> readable body" in text+ assert "keep" in text+++def test_pdf_export_is_refused_for_a_text_material(client: TestClient) -> None:+ material = _upload(client, name="notes.txt", data=b"plain readable text content")++ response = client.get(+ f"/api/v1/reading/materials/{material['material_id']}/export",+ params={"fmt": "pdf"},+ )++ assert response.status_code == 400+++def test_export_filename_survives_non_ascii(client: TestClient) -> None:+ material = _upload(client, name="注意力机制.pdf")++ response = client.get(f"/api/v1/reading/materials/{material['material_id']}/export")++ disposition = response.headers["content-disposition"]+ assert "filename*=UTF-8''" in disposition+++def test_export_rejects_an_unknown_format(client: TestClient) -> None:+ material = _upload(client)++ response = client.get(+ f"/api/v1/reading/materials/{material['material_id']}/export",+ params={"fmt": "docx"},+ )++ assert response.status_code == 422diff --git a/tests/reading/test_turn_wiring.py b/tests/reading/test_turn_wiring.pynew file mode 100644index 000000000..fd828368a--- /dev/null+++ b/tests/reading/test_turn_wiring.py@@ -0,0 +1,125 @@+"""Turn-runtime wiring for immersive reading.++The reader's state reaches the model through three seams in+``turn_runtime``: normalisation of the client's fields, the request snapshot+persisted with the user message, and the recovery of that snapshot on a+regenerate. Each is covered here because each fails silently — a turn simply+loses its grounding and the answer quietly gets worse.+"""++from __future__ import annotations++import pytest++from deeptutor.services.session.turn_runtime import (+ READING_SELECTION_MAX_CHARS,+ _reading_material_id,+ _reading_viewport,+ _request_snapshot_metadata,+)++# ---------------------------------------------------------------------------+# material id normalisation+# ---------------------------------------------------------------------------+++ "value",+ ["0123456789abcdef", "ABCDEF0123456789", " 0123456789abcdef ", "0123abcd"],+)+def test_content_hash_shaped_ids_are_accepted_and_lowercased(value: str) -> None:+ assert _reading_material_id(value) == value.strip().lower()+++ "value",+ [+ None,+ "",+ " ",+ "../../etc/passwd",+ "not-hex",+ "0123", # too short to be a content hash+ "z" * 16,+ "0123456789abcdef/../..",+ 123,+ {"id": "0123456789abcdef"},+ ],+)+def test_anything_not_shaped_like_a_material_id_is_rejected(value: object) -> None:+ """The id becomes a filesystem path, so the shape is enforced at the edge."""+ assert _reading_material_id(value) == ""+++# ---------------------------------------------------------------------------+# viewport normalisation+# ---------------------------------------------------------------------------+++def test_viewport_carries_locator_and_selection() -> None:+ assert _reading_viewport({"locator": 12, "selection": "some text"}) == {+ "locator": 12,+ "selection": "some text",+ }+++def test_absent_viewport_fields_are_omitted_not_zeroed() -> None:+ """ "No selection" and "an empty selection" must not look the same."""+ assert _reading_viewport({"locator": 3}) == {"locator": 3}+ assert _reading_viewport({"selection": "x"}) == {"selection": "x"}+ assert _reading_viewport({}) == {}+ assert _reading_viewport({"locator": 0, "selection": " "}) == {}++[email protected]("value", [None, "not a dict", 7, [1, 2]])+def test_malformed_viewport_degrades_to_empty(value: object) -> None:+ assert _reading_viewport(value) == {}+++def test_nonsense_locators_are_dropped() -> None:+ assert _reading_viewport({"locator": -4}) == {}+ assert _reading_viewport({"locator": "abc"}) == {}+ assert _reading_viewport({"locator": None}) == {}+++def test_selection_is_bounded_because_it_enters_the_prompt() -> None:+ viewport = _reading_viewport({"selection": "x" * (READING_SELECTION_MAX_CHARS * 3)})+ assert len(viewport["selection"]) == READING_SELECTION_MAX_CHARS+++# ---------------------------------------------------------------------------+# snapshot persistence+# ---------------------------------------------------------------------------+++def _snapshot(payload: dict) -> dict:+ metadata = _request_snapshot_metadata(+ content="hi",+ capability="",+ payload=payload,+ attachments=[],+ config={},+ notebook_references=[],+ history_references=[],+ question_notebook_references=[],+ book_references=[],+ persona="",+ memory_references=[],+ llm_selection=None,+ )+ return metadata["request_snapshot"]+++def test_open_material_is_persisted_with_the_user_message() -> None:+ """A regenerate must re-run with the same document open."""+ snapshot = _snapshot({"reading_material_id": "0123456789abcdef"})+ assert snapshot["readingMaterialId"] == "0123456789abcdef"+++def test_a_plain_chat_turn_carries_no_reading_key() -> None:+ assert "readingMaterialId" not in _snapshot({})+ assert "readingMaterialId" not in _snapshot({"reading_material_id": ""})+++def test_a_bogus_id_is_not_persisted() -> None:+ assert "readingMaterialId" not in _snapshot({"reading_material_id": "../../etc"})diff --git a/tests/services/rag/test_ima_client_surface.py b/tests/services/rag/test_ima_client_surface.pynew file mode 100644index 000000000..8c957909d--- /dev/null+++ b/tests/services/rag/test_ima_client_surface.py@@ -0,0 +1,414 @@+"""Tests for the IMA calls beyond retrieval: envelope, browse, import, notes.++Retrieval itself is covered by ``test_ima_pipeline``. This module pins the parts+that make an IMA library *usable* rather than merely searchable:++* the status envelope in both documented spellings — the failure this guards+ against is silent and total (reading only one spelling turns every successful+ call into an error), so it is asserted directly rather than assumed;+* ``get_knowledge_list``: the browse call that answers "what is in this library",+ including the folder/document split and the root-folder convention;+* ``import_urls`` and the notes module: the additive writes;+* ``page_limit``: IMA's documented 1..50 bound.++Everything runs against an injected ``httpx.MockTransport`` — no network.+"""++from __future__ import annotations++import asyncio+import json++import httpx+import pytest++from deeptutor.services.rag.pipelines.ima.client import (+ API_BASE_URL,+ MAX_IMPORT_URLS,+ MAX_PAGE_LIMIT,+ ImaAPIError,+ ImaAuthError,+ ImaClient,+ ImaRateLimitError,+ page_limit,+)+from deeptutor.services.rag.pipelines.ima.config import ImaConfig+from deeptutor.services.rag.pipelines.ima.envelope import unwrap+from deeptutor.services.rag.pipelines.ima.models import parse_knowledge_page, parse_note+from deeptutor.services.rag.pipelines.ima.notes import SORT_BY_CREATED, SORT_BY_UPDATED++CONFIG = ImaConfig(client_id="cid", api_key="key", knowledge_base_id="kb-1")+++def _client(handler) -> ImaClient:+ return ImaClient(CONFIG, transport=httpx.MockTransport(handler))+++def _responder(data: dict, *, style: str = "code"):+ """A handler returning ``data`` in one of the two envelope spellings."""++ def handler(request: httpx.Request) -> httpx.Response:+ if style == "retcode":+ return httpx.Response(200, json={"retcode": 0, "errmsg": "成功", "data": data})+ return httpx.Response(200, json={"code": 0, "msg": "ok", "data": data})++ return handler+++# ---------------------------------------------------------------------------+# envelope+# ---------------------------------------------------------------------------+++class TestEnvelope:+ @pytest.mark.parametrize(+ "payload",+ [+ {"code": 0, "msg": "ok", "data": {"value": 1}},+ {"retcode": 0, "errmsg": "成功", "data": {"value": 1}},+ {"retcode": "0", "data": {"value": 1}},+ ],+ )+ def test_success_is_unwrapped_in_either_spelling(self, payload: dict) -> None:+ assert unwrap(payload, status_code=200) == {"value": 1}++ @pytest.mark.parametrize("field", ["code", "retcode"])+ def test_credential_rejection_maps_to_auth_error_in_either_spelling(self, field: str) -> None:+ with pytest.raises(ImaAuthError):+ unwrap({field: 20004, "msg": "bad key"}, status_code=200)++ @pytest.mark.parametrize("field", ["code", "retcode"])+ def test_rate_limit_maps_to_rate_limit_error_in_either_spelling(self, field: str) -> None:+ with pytest.raises(ImaRateLimitError):+ unwrap({field: 110021}, status_code=200)++ def test_retryable_upstream_failure_says_so(self) -> None:+ with pytest.raises(ImaAPIError, match="temporarily unavailable"):+ unwrap({"retcode": 110010}, status_code=200)++ def test_business_error_surfaces_ima_message(self) -> None:+ with pytest.raises(ImaAPIError, match="参数非法"):+ unwrap({"retcode": 110001, "errmsg": "参数非法"}, status_code=200)++ def test_payload_without_any_status_field_is_rejected(self) -> None:+ with pytest.raises(ImaAPIError, match="unrecognized"):+ unwrap({"data": {"value": 1}}, status_code=200)++ def test_non_dict_payload_is_rejected(self) -> None:+ with pytest.raises(ImaAPIError, match="unexpected payload"):+ unwrap(["not", "an", "envelope"], status_code=200)++ def test_client_accepts_a_retcode_response_end_to_end(self) -> None:+ """The guard that matters: a retcode-only deployment must still work."""+ page = asyncio.run(+ _client(+ _responder(+ {"knowledge_list": [{"media_id": "m1", "title": "Alpha"}], "is_end": True},+ style="retcode",+ )+ ).get_knowledge_list()+ )++ assert [document.title for document in page.documents] == ["Alpha"]+++# ---------------------------------------------------------------------------+# browse+# ---------------------------------------------------------------------------+++class TestKnowledgeList:+ def test_root_listing_posts_the_documented_body(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json={"code": 0, "data": {"is_end": True}})++ asyncio.run(_client(handler).get_knowledge_list())++ assert seen["url"] == f"{API_BASE_URL}/openapi/wiki/v1/get_knowledge_list"+ assert seen["body"] == {"knowledge_base_id": "kb-1", "cursor": "", "limit": MAX_PAGE_LIMIT}++ def test_folder_id_equal_to_the_library_id_is_dropped(self) -> None:+ """IMA's root folder id *is* the knowledge base id — sending it is noise."""+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json={"code": 0, "data": {"is_end": True}})++ asyncio.run(_client(handler).get_knowledge_list(folder_id="kb-1"))++ assert "folder_id" not in seen["body"]++ def test_subfolder_listing_sends_the_folder(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json={"code": 0, "data": {"is_end": True}})++ asyncio.run(_client(handler).get_knowledge_list(folder_id="f-9", cursor="c1", limit=10))++ assert seen["body"] == {+ "knowledge_base_id": "kb-1",+ "cursor": "c1",+ "limit": 10,+ "folder_id": "f-9",+ }++ def test_documents_folders_and_breadcrumb_are_separated(self) -> None:+ page = parse_knowledge_page(+ {+ "knowledge_list": [+ {"media_id": "m1", "title": "Alpha"},+ {"folder_id": "f1", "name": "Papers", "file_number": 2, "folder_number": 1},+ ],+ "current_path": [{"folder_id": "root", "name": "Library"}],+ "next_cursor": "c2",+ "is_end": False,+ }+ )++ assert [document.title for document in page.documents] == ["Alpha"]+ assert [folder.name for folder in page.folders] == ["Papers"]+ assert page.folders[0].file_number == 2+ assert page.path == ("Library",)+ assert (page.next_cursor, page.is_end) == ("c2", False)++ def test_entries_that_are_neither_are_discarded(self) -> None:+ page = parse_knowledge_page({"knowledge_list": [{"highlight_content": "orphan"}, {}]})++ assert page.documents == ()+ assert page.folders == ()++ def test_duplicate_ids_within_a_page_are_collapsed(self) -> None:+ page = parse_knowledge_page(+ {+ "knowledge_list": [+ {"media_id": "m1", "title": "Alpha"},+ {"media_id": "m1", "title": "Alpha again"},+ ]+ }+ )++ assert len(page.documents) == 1++ def test_blocking_flavour_shares_the_same_wire(self) -> None:+ """The manifest layer is synchronous; its call must be identical."""+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["headers"] = dict(request.headers)+ return httpx.Response(+ 200,+ json={"code": 0, "data": {"knowledge_list": [{"media_id": "m", "title": "T"}]}},+ )++ page = _client(handler).get_knowledge_list_sync()++ assert [document.title for document in page.documents] == ["T"]+ assert seen["headers"]["ima-openapi-clientid"] == "cid"+++class TestPageLimit:+ @pytest.mark.parametrize(+ ("requested", "expected"),+ [(0, 1), (1, 1), (50, 50), (51, 50), (None, 50), ("nonsense", 50)],+ )+ def test_limits_are_clamped_to_the_documented_range(self, requested, expected: int) -> None:+ assert page_limit(requested) == expected+++# ---------------------------------------------------------------------------+# writes+# ---------------------------------------------------------------------------+++class TestImportUrls:+ def test_urls_are_posted_with_the_root_folder_convention(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(+ 200,+ json={+ "code": 0,+ "data": {+ "url_data_list": [+ {"url": "https://a.test", "ret_code": 0, "media_id": "m1"},+ {"url": "https://b.test", "ret_code": 110001},+ ]+ },+ },+ )++ results = asyncio.run(_client(handler).import_urls(["https://a.test", " https://b.test "]))++ # Root folder is addressed by the knowledge base id itself.+ assert seen["body"] == {+ "urls": ["https://a.test", "https://b.test"],+ "knowledge_base_id": "kb-1",+ "folder_id": "kb-1",+ }+ assert [(item.url, item.ok, item.media_id) for item in results] == [+ ("https://a.test", True, "m1"),+ ("https://b.test", False, ""),+ ]++ def test_a_batch_without_per_url_rows_is_reported_as_accepted(self) -> None:+ results = asyncio.run(_client(_responder({})).import_urls(["https://a.test"]))++ assert [(item.url, item.ok) for item in results] == [("https://a.test", True)]++ def test_duplicates_are_collapsed_and_the_batch_is_bounded(self) -> None:+ client = _client(_responder({}))++ results = asyncio.run(client.import_urls(["https://a.test", "https://a.test"]))+ assert len(results) == 1++ with pytest.raises(ValueError, match=f"at most {MAX_IMPORT_URLS}"):+ asyncio.run(client.import_urls([f"https://{i}.test" for i in range(11)]))++ with pytest.raises(ValueError, match="At least one URL"):+ asyncio.run(client.import_urls([" "]))+++class TestNotes:+ def test_search_defaults_to_recency_and_a_title_query(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json={"retcode": 0, "data": {"docs": [], "is_end": True}})++ asyncio.run(_client(handler).notes.search_notes("plasma", limit=5))++ assert seen["url"] == f"{API_BASE_URL}/openapi/note/v1/search_note_book"+ assert seen["body"] == {+ "search_type": 0,+ "sort_type": SORT_BY_UPDATED,+ "query_info": {"title": "plasma"},+ "start": 0,+ "end": 5,+ }++ def test_content_search_and_sort_order_are_honoured(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json={"retcode": 0, "data": {"docs": []}})++ asyncio.run(+ _client(handler).notes.search_notes(+ "plasma", by_content=True, sort_type=SORT_BY_CREATED, limit=3+ )+ )++ assert seen["body"]["search_type"] == 1+ assert seen["body"]["sort_type"] == SORT_BY_CREATED+ assert seen["body"]["query_info"] == {"content": "plasma"}++ def test_search_flattens_the_nested_note_payload(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "retcode": 0,+ "data": {+ "docs": [+ {+ "doc": {+ "basic_info": {+ "docid": "n1",+ "title": "Plasma notes",+ "summary": "about plasma",+ "folder_name": "Physics",+ "create_time": 111,+ "modify_time": 222,+ }+ }+ },+ {"doc": {"basic_info": {"docid": "n2", "title": "Gone", "status": 1}}},+ ],+ "is_end": True,+ },+ },+ )++ notes, is_end = asyncio.run(_client(handler).notes.search_notes())++ assert [(note.note_id, note.title, note.updated_at) for note in notes] == [+ ("n1", "Plasma notes", 222)+ ]+ assert is_end is True++ def test_notebook_listing_starts_at_the_zero_cursor(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return httpx.Response(+ 200,+ json={+ "retcode": 0,+ "data": {+ "note_book_folders": [+ {+ "folder": {+ "basic_info": {+ "folder_id": "f1",+ "name": "Physics",+ "note_number": 4,+ }+ }+ }+ ],+ "next_cursor": "c2",+ },+ },+ )++ notebooks, cursor = asyncio.run(_client(handler).notes.list_notebooks())++ assert seen["body"]["cursor"] == "0"+ assert [(book.folder_id, book.note_number) for book in notebooks] == [("f1", 4)]+ assert cursor.next_cursor == "c2"++ def test_create_note_sends_markdown_and_returns_the_id(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ seen["body"] = json.loads(request.content)+ return httpx.Response(200, json={"retcode": 0, "data": {"doc_id": "n9"}})++ note_id = asyncio.run(_client(handler).notes.create_note("# Title\nbody", folder_id="f1"))++ assert note_id == "n9"+ assert seen["url"].endswith("/openapi/note/v1/import_doc")+ assert seen["body"] == {+ "content_format": 1,+ "content": "# Title\nbody",+ "folder_id": "f1",+ }++ def test_append_note_requires_a_target_and_content(self) -> None:+ client = _client(_responder({"doc_id": "n1"}))++ assert asyncio.run(client.notes.append_note("n1", "more")) == "n1"+ with pytest.raises(ValueError, match="target note id"):+ asyncio.run(client.notes.append_note(" ", "more"))+ with pytest.raises(ValueError, match="Content to append"):+ asyncio.run(client.notes.append_note("n1", " "))++ def test_note_parsing_accepts_a_bare_basic_info_dict(self) -> None:+ note = parse_note({"basic_info": {"doc_id": "n1", "title": "T"}})++ assert note is not None+ assert (note.note_id, note.title) == ("n1", "T")diff --git a/tests/services/rag/test_ima_inventory.py b/tests/services/rag/test_ima_inventory.pynew file mode 100644index 000000000..d575e9c0f--- /dev/null+++ b/tests/services/rag/test_ima_inventory.py@@ -0,0 +1,351 @@+"""Tests for the IMA document inventory, and the manifest that consumes it.++The behaviour under test is the one that made a connected IMA library feel broken:+asked "what are my latest 5 documents", the model was *told* by the system prompt+that the document list could not be read, so it declined. It can be read — IMA+exposes ``get_knowledge_list`` — and these tests pin both halves:++* :mod:`~deeptutor.services.rag.pipelines.ima.inventory` — folder traversal,+ request budget, and the cache that keeps a per-turn manifest from re-fetching;+* :mod:`deeptutor.knowledge.manifest` — an ``ima`` KB now enumerates for real,+ falls back to "not listable" only when the library cannot be reached, and marks+ a budget-truncated count as a lower bound rather than a total.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.knowledge.manifest import (+ UNAVAILABLE_REMOTE,+ build_manifest,+ render_manifest_note,+ render_manifest_report,+)+from deeptutor.services.rag.pipelines.ima import inventory as inventory_module+from deeptutor.services.rag.pipelines.ima.inventory import (+ MAX_REQUESTS,+ ImaInventory,+ clear_cache,+ read_inventory,+)+from deeptutor.services.rag.pipelines.ima.models import ImaDocument, ImaFolder, ImaKnowledgePage++ENTRY = {+ "type": "ima",+ "rag_provider": "ima",+ "client_id": "cid",+ "api_key": "key",+ "knowledge_base_id": "kb-1",+}+++class _ListStub:+ """A blocking ``get_knowledge_list_sync`` over a scripted folder tree."""++ def __init__(self, tree: dict[str, list[list]], *, error: Exception | None = None) -> None:+ # tree: folder_id -> list of pages, each page a list of documents/folders+ self._tree = tree+ self._error = error+ self.calls: list[tuple[str, str]] = []++ def get_knowledge_list_sync(self, *, folder_id="", cursor="", limit=50) -> ImaKnowledgePage:+ if self._error is not None:+ raise self._error+ self.calls.append((folder_id, cursor))+ pages = self._tree.get(folder_id, [[]])+ index = int(cursor or 0)+ entries = pages[index] if index < len(pages) else []+ is_last = index >= len(pages) - 1+ return ImaKnowledgePage(+ documents=tuple(item for item in entries if isinstance(item, ImaDocument)),+ folders=tuple(item for item in entries if isinstance(item, ImaFolder)),+ next_cursor="" if is_last else str(index + 1),+ is_end=is_last,+ )+++def _doc(title: str) -> ImaDocument:+ return ImaDocument(media_id=f"m-{title}", title=title)+++def _folder(name: str) -> ImaFolder:+ return ImaFolder(folder_id=f"f-{name}", name=name)++[email protected](autouse=True)+def _clean_cache():+ clear_cache()+ yield+ clear_cache()+++# ---------------------------------------------------------------------------+# traversal+# ---------------------------------------------------------------------------+++class TestTraversal:+ def test_root_documents_are_listed(self) -> None:+ stub = _ListStub({"kb-1": [[_doc("a.pdf"), _doc("b.md")]]})++ result = read_inventory(ENTRY, client_factory=lambda _c: stub, use_cache=False)++ assert result == ImaInventory(documents=("a.pdf", "b.md"), complete=True)++ def test_folders_are_descended_and_prefixed_like_a_local_path(self) -> None:+ stub = _ListStub(+ {+ "kb-1": [[_doc("top.pdf"), _folder("Papers")]],+ "f-Papers": [[_doc("inner.pdf"), _folder("2026")]],+ "f-2026": [[_doc("recent.pdf")]],+ }+ )++ result = read_inventory(ENTRY, client_factory=lambda _c: stub, use_cache=False)++ assert result is not None+ assert result.documents == (+ "top.pdf",+ "Papers/inner.pdf",+ "Papers/2026/recent.pdf",+ )+ assert result.complete is True++ def test_pagination_within_a_folder_is_followed(self) -> None:+ stub = _ListStub({"kb-1": [[_doc("a")], [_doc("b")], [_doc("c")]]})++ result = read_inventory(ENTRY, client_factory=lambda _c: stub, use_cache=False)++ assert result is not None+ assert result.documents == ("a", "b", "c")+ assert [cursor for _folder_id, cursor in stub.calls] == ["", "1", "2"]++ def test_request_budget_marks_the_count_as_incomplete(self) -> None:+ # Every page reports more to come, so the budget is what stops it.+ stub = _ListStub({"kb-1": [[_doc(f"d{i}")] for i in range(MAX_REQUESTS + 5)]})++ result = read_inventory(ENTRY, client_factory=lambda _c: stub, use_cache=False)++ assert result is not None+ assert len(stub.calls) == MAX_REQUESTS+ assert result.complete is False++ def test_a_cycle_in_the_folder_graph_cannot_loop(self) -> None:+ stub = _ListStub(+ {+ "kb-1": [[_folder("A")]],+ "f-A": [[_folder("A"), _doc("inside")]],+ }+ )++ result = read_inventory(ENTRY, client_factory=lambda _c: stub, use_cache=False)++ assert result is not None+ assert result.documents == ("A/inside",)++ def test_unreachable_library_is_unknown_not_empty(self) -> None:+ stub = _ListStub({}, error=RuntimeError("offline"))++ assert read_inventory(ENTRY, client_factory=lambda _c: stub, use_cache=False) is None++ def test_missing_credentials_are_unknown(self) -> None:+ assert read_inventory({"type": "ima"}, client_factory=lambda _c: None) is None++ def test_the_production_path_drives_the_real_client(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Without a factory the reader builds a real client: exercise that seam.++ Everything from the credential headers through the status envelope to the+ blocking transport runs here — the one part of the chain the scripted stub+ above deliberately replaces.+ """+ import httpx++ from deeptutor.services.rag.pipelines.ima import client as client_module++ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["path"] = request.url.path+ seen["clientid"] = request.headers.get("ima-openapi-clientid")+ return httpx.Response(+ 200,+ json={+ "retcode": 0,+ "data": {+ "knowledge_list": [{"media_id": "m1", "title": "最新收集.pdf"}],+ "is_end": True,+ },+ },+ )++ real_client = client_module.ImaClient++ def build(config, **kwargs):+ kwargs.pop("transport", None)+ return real_client(config, transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr(client_module, "ImaClient", build)++ result = read_inventory(ENTRY, use_cache=False)++ assert result is not None+ assert result.documents == ("最新收集.pdf",)+ assert seen["path"] == "/openapi/wiki/v1/get_knowledge_list"+ assert seen["clientid"] == "cid"+++class TestCache:+ def test_a_second_read_is_served_from_cache(self) -> None:+ stub = _ListStub({"kb-1": [[_doc("a")]]})++ first = read_inventory(ENTRY, client_factory=lambda _c: stub)+ second = read_inventory(ENTRY, client_factory=lambda _c: stub)++ assert first == second+ assert len(stub.calls) == 1++ def test_expiry_refetches(self, monkeypatch: pytest.MonkeyPatch) -> None:+ stub = _ListStub({"kb-1": [[_doc("a")]]})+ clock = {"now": 1_000.0}+ monkeypatch.setattr(inventory_module.time, "monotonic", lambda: clock["now"])++ read_inventory(ENTRY, client_factory=lambda _c: stub)+ clock["now"] += inventory_module.CACHE_TTL_SECONDS + 1+ read_inventory(ENTRY, client_factory=lambda _c: stub)++ assert len(stub.calls) == 2++ def test_a_failure_is_cached_briefly_too(self) -> None:+ """An unreachable library must not be retried on every turn's prompt."""+ stub = _ListStub({}, error=RuntimeError("offline"))++ assert read_inventory(ENTRY, client_factory=lambda _c: stub) is None+ assert read_inventory(ENTRY, client_factory=lambda _c: stub) is None++ def test_a_cached_failure_expires_sooner_than_a_success(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ clock = {"now": 1_000.0}+ monkeypatch.setattr(inventory_module.time, "monotonic", lambda: clock["now"])+ failing = _ListStub({}, error=RuntimeError("offline"))++ read_inventory(ENTRY, client_factory=lambda _c: failing)+ clock["now"] += inventory_module.FAILURE_TTL_SECONDS + 1+ working = _ListStub({"kb-1": [[_doc("a")]]})+ result = read_inventory(ENTRY, client_factory=lambda _c: working)++ assert result is not None+ assert result.documents == ("a",)++ def test_libraries_are_cached_separately(self) -> None:+ stub = _ListStub({"kb-1": [[_doc("a")]], "kb-2": [[_doc("b")]]})+ other = {**ENTRY, "knowledge_base_id": "kb-2"}++ read_inventory(ENTRY, client_factory=lambda _c: stub)+ read_inventory(other, client_factory=lambda _c: stub)++ assert len(stub.calls) == 2+++# ---------------------------------------------------------------------------+# manifest integration+# ---------------------------------------------------------------------------+++def _patch_reader(monkeypatch: pytest.MonkeyPatch, result) -> None:+ """Swap the manifest's IMA reader for a scripted one."""+ from deeptutor.knowledge import manifest as manifest_module++ monkeypatch.setitem(+ manifest_module._REMOTE_INVENTORY_READERS,+ "ima",+ lambda _entry: result,+ )+++class TestManifestEnumeratesIma:+ def test_documents_are_reported_like_a_local_kb(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _patch_reader(monkeypatch, (["a.pdf", "Papers/b.md"], True))++ manifest = build_manifest(name="IMA", kb_dir=tmp_path / "IMA", entry=ENTRY)++ assert manifest.enumerable+ assert manifest.total == 2+ assert [document.name for document in manifest.documents] == ["a.pdf", "Papers/b.md"]+ assert manifest.total_is_lower_bound is False++ def test_the_report_omits_unknown_sizes(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _patch_reader(monkeypatch, (["a.pdf"], True))++ manifest = build_manifest(name="IMA", kb_dir=tmp_path / "IMA", entry=ENTRY)+ report = render_manifest_report(manifest, language="en")++ assert "1. a.pdf" in report+ assert "0 B" not in report++ def test_a_truncated_listing_is_reported_as_a_lower_bound(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _patch_reader(monkeypatch, ([f"d{i}.pdf" for i in range(400)], False))++ manifest = build_manifest(name="IMA", kb_dir=tmp_path / "IMA", entry=ENTRY, limit=2)++ assert manifest.total_is_lower_bound is True+ assert "400+" in render_manifest_report(manifest, language="en")+ assert "400+" in render_manifest_note([manifest], language="zh")++ def test_pattern_filtering_works_over_a_remote_listing(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _patch_reader(monkeypatch, (["a.pdf", "notes.md", "Papers/b.pdf"], True))++ manifest = build_manifest(name="IMA", kb_dir=tmp_path / "IMA", entry=ENTRY, pattern="*.pdf")++ assert manifest.total == 3+ assert manifest.matched == 2+ assert [document.name for document in manifest.documents] == ["a.pdf", "Papers/b.pdf"]++ def test_an_unreachable_library_falls_back_to_not_listable(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _patch_reader(monkeypatch, None)++ manifest = build_manifest(name="IMA", kb_dir=tmp_path / "IMA", entry=ENTRY)++ assert not manifest.enumerable+ assert manifest.unavailable == UNAVAILABLE_REMOTE+ assert "remote server" in render_manifest_report(manifest, language="en")++ def test_a_reader_that_raises_is_treated_as_unreachable(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from deeptutor.knowledge import manifest as manifest_module++ def boom(_entry):+ raise RuntimeError("offline")++ monkeypatch.setitem(manifest_module._REMOTE_INVENTORY_READERS, "ima", boom)++ manifest = build_manifest(name="IMA", kb_dir=tmp_path / "IMA", entry=ENTRY)++ assert manifest.unavailable == UNAVAILABLE_REMOTE++ def test_an_empty_library_is_reported_as_empty_not_unknown(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _patch_reader(monkeypatch, ([], True))++ manifest = build_manifest(name="IMA", kb_dir=tmp_path / "IMA", entry=ENTRY)++ assert manifest.enumerable+ assert manifest.total == 0+ assert "no documents" in render_manifest_report(manifest, language="en")diff --git a/tests/services/rag/test_ima_pipeline.py b/tests/services/rag/test_ima_pipeline.pyindex d1d6bd679..798f3b0c4 100644--- a/tests/services/rag/test_ima_pipeline.py+++ b/tests/services/rag/test_ima_pipeline.py@@ -2,9 +2,9 @@The engine is a thin HTTPS client over IMA's knowledge-base OpenAPI. We exercise:-* the client wire shapes (POST path, auth headers, ``{code,msg,data}`` envelope,- cursor pagination, error-code mapping) against an injected- ``httpx.MockTransport`` — no network,+* the client wire shapes (POST path, auth headers, the status envelope in both of+ its documented spellings, cursor pagination, error-code mapping) against an+ injected ``httpx.MockTransport`` — no network,* the connect-time probe verdict (credentials accepted / library resolves),* the pipeline's ``search`` (reads the per-KB binding from ``kb_config.json``,shapes the result, and fails cleanly when unconfigured/unreachable),@@ -36,8 +36,13 @@ from deeptutor.services.rag.pipelines.ima.config import (ImaNotConfiguredError,config_from_entry,)+from deeptutor.services.rag.pipelines.ima.models import parse_knowledge_pagefrom deeptutor.services.rag.pipelines.ima.pipeline import ImaPipelinefrom deeptutor.services.rag.pipelines.ima.probe import probe_knowledge_base+from deeptutor.services.rag.pipelines.ima.sources import (+ DEFAULT_HYDRATION_BUDGET,+ MIN_USEFUL_SNIPPET_CHARS,+)CONFIG = ImaConfig(client_id="cid", api_key="key", knowledge_base_id="kb-1")@@ -146,10 +151,10 @@ class TestClientWire:cursors.append(body["cursor"])return _ok(pages[len(cursors) - 1])- items = asyncio.run(_client(handler).search_knowledge("q", limit=10))+ page = asyncio.run(_client(handler).search_knowledge("q", limit=10))assert cursors == ["", "c2"]- assert [item["media_id"] for item in items] == ["m1", "m2"]+ assert [document.media_id for document in page.documents] == ["m1", "m2"]def test_search_stops_once_limit_is_reached(self) -> None:calls = 0@@ -168,10 +173,10 @@ class TestClientWire:})- items = asyncio.run(_client(handler).search_knowledge("q", limit=2))+ page = asyncio.run(_client(handler).search_knowledge("q", limit=2))assert calls == 1- assert len(items) == 2+ assert len(page.documents) == 2def test_search_page_budget_bounds_pagination(self) -> None:# A server that never reports the end must not spin forever.@@ -249,7 +254,10 @@ class TestClientWire:"notebook_ext_info": {"notebook_id": "note-1"},})+ # Both documented spellings of the note id are sent, so the call+ # works whichever one this deployment expects.assert json.loads(request.content) == {+ "doc_id": "note-1","note_id": "note-1","target_content_format": 0,}@@ -348,10 +356,18 @@ class TestClientKnowledgeBaseList:}assert page == {"knowledge_bases": [], "next_cursor": "", "is_end": True}- @pytest.mark.parametrize("limit", [0, 21])- def test_list_rejects_limits_outside_ima_bounds(self, limit: int) -> None:- with pytest.raises(ValueError, match="between 1 and 20"):- asyncio.run(_client(lambda _request: _ok({})).search_knowledge_bases(limit=limit))+ @pytest.mark.parametrize(("requested", "sent"), [(0, 1), (99, 50), ("x", 50)])+ def test_list_clamps_limits_into_ima_bounds(self, requested, sent: int) -> None:+ """IMA documents 1..50; a caller's value is clamped, never rejected."""+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = json.loads(request.content)+ return _ok({"info_list": [], "is_end": True})++ asyncio.run(_client(handler).search_knowledge_bases(limit=requested))++ assert seen["body"]["limit"] == sentdef test_list_deduplicates_and_enriches_descriptions(self) -> None:seen_bodies: list[dict] = []@@ -576,27 +592,38 @@ def _kb_config(tmp_path: Path, entry: dict) -> str:return str(base)+def _thick(text: str) -> str:+ """A snippet long enough that retrieval treats it as usable evidence."""+ return text + " " + "x" * MIN_USEFUL_SNIPPET_CHARS++class _SearchStub:+ """A client stub taking wire-shaped items, so parsing stays under test too."""+def __init__(self,items: list[dict] | None = None,error: Exception | None = None,media: dict[str, ImaMediaContent | None] | None = None,+ media_error: Exception | None = None,) -> None:self._items = items or []self._error = errorself._media = media or {}+ self._media_error = media_errorself.limit: int | None = Noneself.media_calls: list[str] = []- async def search_knowledge(self, query: str, *, limit: int) -> list[dict]:+ async def search_knowledge(self, query: str, *, limit: int):self.limit = limitif self._error is not None:raise self._error- return self._items+ return parse_knowledge_page({"info_list": self._items, "is_end": True})async def get_media_content(self, media_id: str) -> ImaMediaContent | None:self.media_calls.append(media_id)+ if self._media_error is not None:+ raise self._media_errorreturn self._media.get(media_id)@@ -614,8 +641,8 @@ class TestPipelineSearch:)stub = _SearchStub([- {"media_id": "m1", "title": "Alpha", "highlight_content": "alpha text"},- {"media_id": "m2", "title": "Beta", "highlight_content": "beta text"},+ {"media_id": "m1", "title": "Alpha", "highlight_content": _thick("alpha text")},+ {"media_id": "m2", "title": "Beta", "highlight_content": _thick("beta text")},])pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)@@ -629,6 +656,8 @@ class TestPipelineSearch:assert "[1] Alpha" in result["content"]assert "alpha text" in result["content"]assert result["answer"] == result["content"]+ # Snippets this substantial need no full-text top-up.+ assert stub.media_calls == []def test_title_only_match_is_kept_without_a_snippet(self, tmp_path) -> None:base = _kb_config(@@ -659,43 +688,117 @@ class TestPipelineSearch:assert result["sources"][0]["content"] == "quotable full text"assert stub.media_calls == ["m1"]- def test_existing_snippet_skips_full_content_fetch(self, tmp_path) -> None:+ def test_substantial_snippet_skips_full_content_fetch(self, tmp_path) -> None:base = _kb_config(tmp_path,{"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},)+ snippet = _thick("snippet")stub = _SearchStub(- [{"media_id": "m1", "title": "Alpha", "highlight_content": "snippet"}],+ [{"media_id": "m1", "title": "Alpha", "highlight_content": snippet}],media={"m1": ImaMediaContent(text="full text")},)pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)result = asyncio.run(pipeline.search("q", "IMA"))- assert result["sources"][0]["content"] == "snippet"+ assert result["sources"][0]["content"] == snippetassert stub.media_calls == []- def test_full_content_fallback_is_limited_to_three_items(self, tmp_path) -> None:+ def test_thin_snippet_is_topped_up_with_source_text(self, tmp_path) -> None:+ """One matched sentence is a hint, not evidence — read the real document."""base = _kb_config(tmp_path,{"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},)- items = [{"media_id": f"m{i}", "title": f"Doc {i}"} for i in range(4)]+ stub = _SearchStub(+ [{"media_id": "m1", "title": "Alpha", "highlight_content": "one line"}],+ media={"m1": ImaMediaContent(text="the whole document")},+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert result["sources"][0]["content"] == "the whole document"+ assert stub.media_calls == ["m1"]++ def test_snippetless_matches_are_topped_up_before_thin_ones(self, tmp_path) -> None:+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ stub = _SearchStub(+ [+ {"media_id": "thin", "title": "Thin", "highlight_content": "hint"},+ {"media_id": "empty", "title": "Empty"},+ ],+ media={+ "thin": ImaMediaContent(text="thin full"),+ "empty": ImaMediaContent(text="empty full"),+ },+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ asyncio.run(pipeline.search("q", "IMA"))++ assert stub.media_calls[0] == "empty"++ def test_unreadable_source_keeps_the_other_matches(self, tmp_path) -> None:+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ stub = _SearchStub(+ [+ {"media_id": "m1", "title": "Alpha", "highlight_content": "hint"},+ {"media_id": "m2", "title": "Beta", "highlight_content": _thick("beta")},+ ],+ media_error=RuntimeError("cos down"),+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert [source["title"] for source in result["sources"]] == ["Alpha", "Beta"]+ assert result["sources"][0]["content"] == "hint"++ def test_matched_folders_never_become_sources(self, tmp_path) -> None:+ """IMA also matches folder names; a folder is not a citable document."""+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ stub = _SearchStub(+ [+ {"folder_id": "f1", "name": "Papers", "file_number": 3},+ {"media_id": "m1", "title": "Alpha", "highlight_content": _thick("alpha")},+ ]+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert [source["title"] for source in result["sources"]] == ["Alpha"]++ def test_full_content_fallback_respects_its_budget(self, tmp_path) -> None:+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ count = DEFAULT_HYDRATION_BUDGET + 2+ items = [{"media_id": f"m{i}", "title": f"Doc {i}"} for i in range(count)]stub = _SearchStub(items,- media={f"m{i}": ImaMediaContent(text=f"text {i}") for i in range(4)},+ media={f"m{i}": ImaMediaContent(text=f"text {i}") for i in range(count)},)pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)result = asyncio.run(pipeline.search("q", "IMA"))- assert stub.media_calls == ["m0", "m1", "m2"]- assert [source["content"] for source in result["sources"]] == [- "text 0",- "text 1",- "text 2",- "",- ]+ assert sorted(stub.media_calls) == sorted(f"m{i}" for i in range(DEFAULT_HYDRATION_BUDGET))+ hydrated = [source for source in result["sources"] if source["content"]]+ assert len(hydrated) == DEFAULT_HYDRATION_BUDGET+ assert result["sources"][-1]["content"] == ""def test_downloaded_text_file_is_extracted(self, tmp_path) -> None:base = _kb_config(@@ -747,7 +850,9 @@ class TestPipelineSearch:def factory(config: ImaConfig):seen.append(config)- return _SearchStub([{"media_id": "m1", "title": "Alpha", "highlight_content": "a"}])+ return _SearchStub(+ [{"media_id": "m1", "title": "Alpha", "highlight_content": _thick("a")}]+ )pipeline = ImaPipeline(kb_base_dir=base, client_factory=factory)diff --git a/tests/services/test_notebook_service.py b/tests/services/test_notebook_service.pyindex a99961afb..6cdd0fac8 100644--- a/tests/services/test_notebook_service.py+++ b/tests/services/test_notebook_service.py@@ -67,3 +67,168 @@ def test_get_notebook_repairs_existing_thinking_tags_in_summary(tmp_path) -> Nonassert repaired is not Noneassert repaired["records"][0]["summary"] == "Reusable summary."assert "old reasoning" not in path.read_text(encoding="utf-8")+++def test_concurrent_add_record_keeps_every_record(tmp_path) -> None:+ """Forty parallel saves must all land, and must not corrupt the file.++ Before per-notebook locking + atomic writes, this lost records at two+ writers and left unparseable JSON at forty — which surfaced to users as+ a notebook that had silently vanished.+ """+ import threading++ manager = NotebookManager(base_dir=str(tmp_path))+ notebook_id = manager.create_notebook("Race")["id"]++ def save(index: int) -> None:+ manager.add_record(+ notebook_ids=[notebook_id],+ record_type=RecordType.CHAT,+ title=f"record-{index}",+ user_query="q",+ output="body" * 500,+ )++ threads = [threading.Thread(target=save, args=(i,)) for i in range(40)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ stored = manager.get_notebook(notebook_id)+ assert stored is not None+ assert len(stored["records"]) == 40+ assert {row["record_count"] for row in manager.list_notebooks()} == {40}+++def test_update_record_leaves_unmentioned_kb_name_alone(tmp_path) -> None:+ """Renaming a record must not clear its knowledge-base link."""+ manager = NotebookManager(base_dir=str(tmp_path))+ notebook_id = manager.create_notebook("KB")["id"]+ record = manager.add_record(+ notebook_ids=[notebook_id],+ record_type=RecordType.CHAT,+ title="Original",+ user_query="q",+ output="o",+ kb_name="physics",+ )["record"]++ updated = manager.update_record(notebook_id, record["id"], title="Renamed")++ assert updated is not None+ assert updated["title"] == "Renamed"+ assert updated["kb_name"] == "physics"++ cleared = manager.update_record(notebook_id, record["id"], kb_name=None)+ assert cleared is not None+ assert cleared["kb_name"] is None+++def test_damaged_notebook_is_reported_not_hidden(tmp_path) -> None:+ """A file that exists but does not parse must never look like a deletion."""+ import pytest++ from deeptutor.services.notebook.service import NotebookCorruptedError++ manager = NotebookManager(base_dir=str(tmp_path))+ (tmp_path / "broken01.json").write_text("{ not json", encoding="utf-8")++ listed = {row["id"]: row for row in manager.list_notebooks()}+ assert listed["broken01"]["unreadable"] is True++ with pytest.raises(NotebookCorruptedError):+ manager.get_notebook("broken01")+++def test_list_notebooks_adopts_files_missing_from_the_index(tmp_path) -> None:+ """A notebook whose index row was lost is still listed."""+ manager = NotebookManager(base_dir=str(tmp_path))+ notebook_id = manager.create_notebook("Orphaned")["id"]++ manager.index_file.write_text('{"notebooks": []}', encoding="utf-8")++ listed = {row["id"] for row in manager.list_notebooks()}+ assert notebook_id in listed+++def test_copy_record_is_independent_of_its_source(tmp_path) -> None:+ manager = NotebookManager(base_dir=str(tmp_path))+ source = manager.create_notebook("Source")["id"]+ target = manager.create_notebook("Target")["id"]+ record = manager.add_record(+ notebook_ids=[source],+ record_type=RecordType.CHAT,+ title="Shared",+ user_query="q",+ output="o",+ )["record"]++ copied = manager.copy_record(source, record["id"], target)+ assert copied is not None+ assert copied["id"] != record["id"]++ manager.update_record(target, copied["id"], title="Edited in target")++ assert manager.get_record(source, record["id"])["title"] == "Shared"+ assert manager.get_record(target, copied["id"])["title"] == "Edited in target"+++def test_move_record_leaves_the_source_notebook(tmp_path) -> None:+ manager = NotebookManager(base_dir=str(tmp_path))+ source = manager.create_notebook("Source")["id"]+ target = manager.create_notebook("Target")["id"]+ record = manager.add_record(+ notebook_ids=[source],+ record_type=RecordType.CHAT,+ title="Travelling",+ user_query="q",+ output="o",+ )["record"]++ moved = manager.move_record(source, record["id"], target)++ assert moved is not None+ assert manager.get_record(source, record["id"]) is None+ assert manager.get_records(target)[0]["title"] == "Travelling"+++def test_statistics_counts_every_record_type(tmp_path) -> None:+ """The per-type breakdown must add up to the total, tutorbot included."""+ manager = NotebookManager(base_dir=str(tmp_path))+ notebook_id = manager.create_notebook("Stats")["id"]+ for record_type in (RecordType.CHAT, RecordType.TUTORBOT, RecordType.RESEARCH):+ manager.add_record(+ notebook_ids=[notebook_id],+ record_type=record_type,+ title=str(record_type),+ user_query="q",+ output="o",+ )++ stats = manager.get_statistics()++ assert stats["records_by_type"]["tutorbot"] == 1+ assert sum(stats["records_by_type"].values()) == stats["total_records"] == 3+++def test_export_markdown_renders_titles_and_bodies(tmp_path) -> None:+ manager = NotebookManager(base_dir=str(tmp_path))+ notebook_id = manager.create_notebook("Exported", description="A short blurb")["id"]+ manager.add_record(+ notebook_ids=[notebook_id],+ record_type=RecordType.CHAT,+ title="First entry",+ user_query="q",+ output="Body text.",+ summary="One-line summary.",+ )++ markdown = manager.export_markdown(notebook_id)++ assert markdown is not None+ assert "# Exported" in markdown+ assert "> A short blurb" in markdown+ assert "## First entry" in markdown+ assert "Body text." in markdowndiff --git a/tests/tools/test_write_note.py b/tests/tools/test_write_note.pyindex 962c5c948..14507301b 100644--- a/tests/tools/test_write_note.py+++ b/tests/tools/test_write_note.py@@ -316,3 +316,53 @@ def test_clips_oversized_title_and_note() -> None:assert len(manager.last_add["title"]) <= MAX_TITLE_CHARS + 1# The clipped note appears in the body with an ellipsis.assert "…" in manager.last_add["output"]+++def test_append_reports_failure_when_no_notebook_accepted_it(tmp_path) -> None:+ """A record id comes back even when nothing was written — don't trust it.++ ``add_record`` skips notebooks that are missing or damaged but still+ returns the record it built, so reporting success off the id alone told+ the model it had saved something that never landed.+ """+ from deeptutor.services.notebook.service import NotebookManager+ from deeptutor.tools.write_note import write_note++ manager = NotebookManager(base_dir=str(tmp_path))+ notebook_id = manager.create_notebook("Target")["id"]+ # Corrupt the file after listing has learned about it, so the notebook is+ # a valid choice that nonetheless cannot accept the write.+ (manager.base_dir / f"{notebook_id}.json").write_text("{ broken", encoding="utf-8")++ outcome = write_note(+ mode="append",+ notebook_id=notebook_id,+ title="Should not succeed",+ content="body",+ notebook_manager=manager,+ conversation_history=[],+ current_user_message="hi",+ )++ assert outcome.ok is False+ assert "did not accept" in (outcome.error or "")+++def test_edit_reports_a_damaged_notebook_instead_of_raising(tmp_path) -> None:+ from deeptutor.services.notebook.service import NotebookManager+ from deeptutor.tools.write_note import write_note++ manager = NotebookManager(base_dir=str(tmp_path))+ notebook_id = manager.create_notebook("Target")["id"]+ (manager.base_dir / f"{notebook_id}.json").write_text("{ broken", encoding="utf-8")++ outcome = write_note(+ mode="edit",+ notebook_id=notebook_id,+ record_id="whatever",+ title="New title",+ notebook_manager=manager,+ )++ assert outcome.ok is False+ assert "Could not read notebook" in (outcome.error or "")diff --git a/web/app/(utility)/notebook/page.tsx b/web/app/(utility)/notebook/page.tsxindex e803e4fb8..a5d1ba4ae 100644--- a/web/app/(utility)/notebook/page.tsx+++ b/web/app/(utility)/notebook/page.tsx@@ -1,666 +1,32 @@"use client";-import dynamic from "next/dynamic";-import Link from "next/link";-import { useCallback, useEffect, useState } from "react";-import {- AlertTriangle,- Bookmark,- ChevronDown,- ExternalLink,- FolderOpen,- Loader2,- MessageSquare,- NotebookPen,- Pencil,- Plus,- Trash2,- X,-} from "lucide-react";-import { useTranslation } from "react-i18next";-import {- createCategory,- deleteCategory,- deleteNotebookEntry,- listCategories,- listNotebookEntries,- removeEntryFromCategory,- renameCategory,- updateNotebookEntry,- type NotebookCategory,- type NotebookEntry,-} from "@/lib/notebook-api";+import { Suspense } from "react";+import { useSearchParams } from "next/navigation";+import { Loader2 } from "lucide-react";+import NotebookConsole from "@/components/notebook/NotebookConsole";-const MarkdownRenderer = dynamic(- () => import("@/components/common/MarkdownRenderer"),- { ssr: false },-);+// `/notebook` is the Notebooks console. The Question Bank — a separate+// feature that happens to share the word in its API path — lives at+// `/space/questions`.-type FilterMode = "all" | "bookmarked" | "wrong";+function NotebookRoute() {+ const searchParams = useSearchParams();+ // Deep links from Memory arrive as `/notebook?notebook=<id>`.+ const requested = searchParams.get("notebook");-export default function NotebookPage() {- const { t } = useTranslation();- const [items, setItems] = useState<NotebookEntry[]>([]);- const [total, setTotal] = useState(0);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [refreshing, setRefreshing] = useState(false);- const [filter, setFilter] = useState<FilterMode>("all");- const [activeCategoryId, setActiveCategoryId] = useState<number | null>(null);- const [categories, setCategories] = useState<NotebookCategory[]>([]);- const [pendingId, setPendingId] = useState<number | null>(null);-- const [showCategoryManager, setShowCategoryManager] = useState(false);- const [newCatName, setNewCatName] = useState("");- const [renamingCat, setRenamingCat] = useState<{- id: number;- name: string;- } | null>(null);-- const loadCategories = useCallback(async () => {- try {- setCategories(await listCategories());- } catch {- /* ignore */- }- }, []);-- const loadItems = useCallback(- async (mode: FilterMode, catId: number | null) => {- setRefreshing(true);- setError(null);- try {- const response = await listNotebookEntries({- bookmarked: mode === "bookmarked" ? true : undefined,- is_correct: mode === "wrong" ? false : undefined,- category_id: catId ?? undefined,- limit: 200,- });- setItems(response.items);- setTotal(response.total);- } catch (err) {- setError(String(err instanceof Error ? err.message : err));- } finally {- setLoading(false);- setRefreshing(false);- }- },- [],- );-- useEffect(() => {- void loadItems(filter, activeCategoryId);- void loadCategories();- }, [filter, activeCategoryId, loadItems, loadCategories]);-- const handleToggleBookmark = useCallback(- async (item: NotebookEntry) => {- const next = !item.bookmarked;- setPendingId(item.id);- try {- await updateNotebookEntry(item.id, { bookmarked: next });- setItems((prev) =>- filter === "bookmarked" && !next- ? prev.filter((e) => e.id !== item.id)- : prev.map((e) =>- e.id === item.id ? { ...e, bookmarked: next } : e,- ),- );- if (filter === "bookmarked" && !next)- setTotal((p) => Math.max(0, p - 1));- } catch {- /* ignore */- }- setPendingId(null);- },- [filter],- );-- const handleDelete = useCallback(- async (item: NotebookEntry) => {- if (!window.confirm(t("Delete this entry?"))) return;- setPendingId(item.id);- try {- await deleteNotebookEntry(item.id);- setItems((prev) => prev.filter((e) => e.id !== item.id));- setTotal((p) => Math.max(0, p - 1));- } catch {- /* ignore */- }- setPendingId(null);- },- [t],- );-- const handleRemoveFromCategory = useCallback(- async (item: NotebookEntry) => {- if (activeCategoryId === null) return;- setPendingId(item.id);- try {- await removeEntryFromCategory(item.id, activeCategoryId);- setItems((prev) => prev.filter((e) => e.id !== item.id));- setTotal((p) => Math.max(0, p - 1));- } catch {- /* ignore */- }- setPendingId(null);- },- [activeCategoryId],- );-- const handleCreateCategory = useCallback(async () => {- if (!newCatName.trim()) return;- try {- await createCategory(newCatName.trim());- setNewCatName("");- await loadCategories();- } catch {- /* ignore */- }- }, [loadCategories, newCatName]);-- const handleRenameCategory = useCallback(async () => {- if (!renamingCat || !renamingCat.name.trim()) return;- try {- await renameCategory(renamingCat.id, renamingCat.name.trim());- setRenamingCat(null);- await loadCategories();- } catch {- /* ignore */- }- }, [loadCategories, renamingCat]);-- const handleDeleteCategory = useCallback(- async (catId: number) => {- if (!window.confirm(t("Delete this category?"))) return;- try {- await deleteCategory(catId);- if (activeCategoryId === catId) setActiveCategoryId(null);- await loadCategories();- } catch {- /* ignore */- }- },- [activeCategoryId, loadCategories, t],- );-- const FILTERS: { mode: FilterMode; label: string }[] = [- { mode: "all", label: "All" },- { mode: "bookmarked", label: "Bookmarked" },- { mode: "wrong", label: "Wrong Only" },- ];+ return <NotebookConsole initialNotebookId={requested} />;+}+export default function NotebookPage() {return (- <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">- <div className="mx-auto max-w-[960px] px-6 py-8">- {/* Header */}- <div className="mb-6 flex items-start justify-between">- <div>- <h1 className="font-serif text-[24px] font-semibold tracking-tight text-[var(--foreground)]">- {t("Question Bank")}- </h1>- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- {t("Review and organize quiz questions across sessions.")}- </p>- </div>- </div>-- <div- className={`mb-4 overflow-hidden rounded-xl border transition-colors ${showCategoryManager ? "border-[var(--border)] bg-[var(--card)]" : "border-[var(--border)]/50 bg-transparent"}`}- >- <button- onClick={() => setShowCategoryManager((v) => !v)}- className="flex w-full items-center justify-between px-4 py-2.5 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/40"- >- <span className="flex items-center gap-2">- <FolderOpen className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />- {t("Manage Categories")}- {categories.length > 0 && (- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] text-[var(--muted-foreground)]">- {categories.length}- </span>- )}- </span>- <ChevronDown- className={`h-3.5 w-3.5 text-[var(--muted-foreground)] transition-transform duration-200 ${showCategoryManager ? "rotate-180" : ""}`}- />- </button>-- {showCategoryManager && (- <div className="border-t border-[var(--border)] px-4 pb-4 pt-3">- <div className="space-y-1.5">- {categories.map((cat) => (- <div- key={cat.id}- className="flex items-center justify-between gap-2 rounded-lg bg-[var(--muted)]/30 px-3 py-2"- >- {renamingCat?.id === cat.id ? (- <input- autoFocus- value={renamingCat.name}- onChange={(e) =>- setRenamingCat({- ...renamingCat,- name: e.target.value,- })- }- onKeyDown={(e) => {- if (e.key === "Enter") void handleRenameCategory();- if (e.key === "Escape") setRenamingCat(null);- }}- onBlur={() => void handleRenameCategory()}- className="flex-1 rounded border border-[var(--border)] bg-[var(--background)] px-2 py-0.5 text-[12px] text-[var(--foreground)] outline-none"- />- ) : (- <span className="text-[12px] text-[var(--foreground)]">- {cat.name}- <span className="ml-1.5 text-[var(--muted-foreground)]">- ({cat.entry_count})- </span>- </span>- )}- <div className="flex items-center gap-1">- <button- onClick={() =>- setRenamingCat({ id: cat.id, name: cat.name })- }- className="rounded p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <Pencil size={12} />- </button>- <button- onClick={() => void handleDeleteCategory(cat.id)}- className="rounded p-1 text-[var(--muted-foreground)] transition-colors hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-950/30"- >- <Trash2 size={12} />- </button>- </div>- </div>- ))}- {!categories.length && (- <p className="py-2 text-center text-[12px] text-[var(--muted-foreground)]">- {t("No categories yet.")}- </p>- )}- </div>- <div className="mt-3 flex items-center gap-1.5">- <input- value={newCatName}- onChange={(e) => setNewCatName(e.target.value)}- onKeyDown={(e) =>- e.key === "Enter" && void handleCreateCategory()- }- placeholder={t("New category name...")}- className="flex-1 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[12px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"- />- <button- onClick={() => void handleCreateCategory()}- disabled={!newCatName.trim()}- className="rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-white disabled:opacity-30"- >- <Plus size={13} />- </button>- </div>- </div>- )}+ <Suspense+ fallback={+ <div className="flex h-full items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" /></div>-- {/* Filter bar */}- <div className="mb-5 flex items-center justify-between border-b border-[var(--border)]/50 pb-3">- <div className="flex items-center gap-1 overflow-x-auto">- {FILTERS.map(({ mode, label }) => {- const active = filter === mode && activeCategoryId === null;- return (- <button- key={mode}- onClick={() => {- setFilter(mode);- setActiveCategoryId(null);- }}- className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${- active- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {t(label)}- </button>- );- })}- {categories.length > 0 && (- <span className="mx-1 text-[var(--border)]">|</span>- )}- {categories.map((cat) => {- const active = activeCategoryId === cat.id;- return (- <button- key={cat.id}- onClick={() => {- setActiveCategoryId(cat.id);- setFilter("all");- }}- className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${- active- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- <FolderOpen size={12} />- {cat.name}- </button>- );- })}- </div>- <span className="shrink-0 text-[12px] text-[var(--muted-foreground)]">- {t("Total")}: {total}- </span>- </div>-- {/* Content */}- {loading ? (- <div className="flex min-h-[420px] items-center justify-center">- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />- </div>- ) : error ? (- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-red-300 text-center dark:border-red-900">- <div className="mb-3 rounded-xl bg-red-50 p-2.5 text-red-500 dark:bg-red-950/30">- <AlertTriangle size={18} />- </div>- <p className="text-[14px] font-medium text-[var(--foreground)]">- {t("Failed to load entries")}- </p>- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">- {error}- </p>- <button- onClick={() => void loadItems(filter, activeCategoryId)}- className="mt-3 rounded-lg bg-[var(--primary)] px-4 py-1.5 text-[12px] font-medium text-white"- >- {t("Retry")}- </button>- </div>- ) : items.length === 0 ? (- <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">- <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">- <NotebookPen size={18} />- </div>- <p className="text-[14px] font-medium text-[var(--foreground)]">- {t("No entries yet")}- </p>- <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">- {t("Questions from your quizzes will appear here.")}- </p>- </div>- ) : (- <ul className="flex flex-col gap-3">- {items.map((item) => {- const disabled = pendingId === item.id;- return (- <li- key={item.id}- className={`rounded-xl border border-[var(--border)] px-5 py-4 transition-opacity ${- disabled ? "opacity-60" : ""- }`}- >- {/* Question header */}- <div className="mb-3 flex items-start justify-between gap-3">- <div className="min-w-0 flex-1">- <div className="mb-1.5 flex flex-wrap items-center gap-1.5">- {item.difficulty && (- <span- className={`rounded-md px-1.5 py-0.5 text-[10px] font-medium uppercase ${- item.difficulty === "hard"- ? "bg-red-50 text-red-600 dark:bg-red-950/30 dark:text-red-400"- : item.difficulty === "medium"- ? "bg-amber-50 text-amber-600 dark:bg-amber-950/30 dark:text-amber-400"- : "bg-green-50 text-green-600 dark:bg-green-950/30 dark:text-green-400"- }`}- >- {item.difficulty}- </span>- )}- {item.question_type && (- <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">- {item.question_type}- </span>- )}- <span- className={`rounded-md px-1.5 py-0.5 text-[10px] font-semibold ${- item.is_correct- ? "bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400"- : "bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400"- }`}- >- {item.is_correct ? t("Correct") : t("Incorrect")}- </span>- </div>- <div className="text-[14px] font-medium text-[var(--foreground)]">- <MarkdownRenderer- content={item.question}- variant="prose"- className="text-[14px] leading-relaxed"- />- </div>- </div>- <div className="flex items-center gap-1">- <button- onClick={() => void handleToggleBookmark(item)}- disabled={disabled}- title={- item.bookmarked ? t("Remove Bookmark") : t("Bookmark")- }- className={`rounded-lg p-1.5 transition-colors disabled:opacity-40 ${- item.bookmarked- ? "text-[var(--primary)]"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- <Bookmark- className="h-4 w-4"- fill={item.bookmarked ? "currentColor" : "none"}- />- </button>- {activeCategoryId !== null && (- <button- onClick={() => void handleRemoveFromCategory(item)}- disabled={disabled}- title={t("Remove from category")}- className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-40"- >- <X className="h-4 w-4" />- </button>- )}- <button- onClick={() => void handleDelete(item)}- disabled={disabled}- title={t("Delete")}- className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:opacity-40"- >- <Trash2 className="h-4 w-4" />- </button>- </div>- </div>-- {/* Options for choice questions */}- {item.options && Object.keys(item.options).length > 0 && (- <div className="mb-3 space-y-1.5">- {Object.entries(item.options).map(([key, text]) => {- const isUserAnswer =- item.user_answer?.toUpperCase() === key.toUpperCase();- const isCorrectAnswer =- item.correct_answer?.toUpperCase() ===- key.toUpperCase();- const isWrongPick = isUserAnswer && !item.is_correct;- return (- <div- key={key}- className={`flex items-start gap-2.5 rounded-lg border px-3 py-2 text-[13px] transition-colors ${- isCorrectAnswer- ? "border-green-200 bg-green-50/60 dark:border-green-900 dark:bg-green-950/20"- : isWrongPick- ? "border-red-200 bg-red-50/60 dark:border-red-900 dark:bg-red-950/20"- : "border-transparent bg-[var(--muted)]/30"- }`}- >- <span- className={`mt-px shrink-0 font-semibold ${- isCorrectAnswer- ? "text-green-600 dark:text-green-400"- : isWrongPick- ? "text-red-600 dark:text-red-400"- : "text-[var(--muted-foreground)]"- }`}- >- {key}.- </span>- <span- className={`flex-1 ${- isCorrectAnswer || isWrongPick- ? "text-[var(--foreground)]"- : "text-[var(--muted-foreground)]"- }`}- >- {text}- </span>- {isCorrectAnswer && (- <span className="mt-px shrink-0 text-[10px] font-medium text-green-600 dark:text-green-400">- ✓ {t("Correct")}- </span>- )}- {isWrongPick && (- <span className="mt-px shrink-0 text-[10px] font-medium text-red-600 dark:text-red-400">- ✗ {t("Your pick")}- </span>- )}- </div>- );- })}- </div>- )}-- {/* Answers for coding / written / fill-in questions */}- {(!item.options ||- Object.keys(item.options).length === 0) && (- <div className="mb-3 space-y-2 text-[13px]">- <div- className={`rounded-lg border px-3 py-2.5 ${- !item.is_correct- ? "border-red-200/60 bg-red-50/40 dark:border-red-900/40 dark:bg-red-950/15"- : "border-green-200/60 bg-green-50/40 dark:border-green-900/40 dark:bg-green-950/15"- }`}- >- <div- className={`mb-1 text-[11px] font-medium uppercase tracking-wide ${- !item.is_correct- ? "text-red-500 dark:text-red-400"- : "text-green-600 dark:text-green-400"- }`}- >- {t("Your Answer")} {item.is_correct ? "✓" : "✗"}- </div>- <div className="text-[var(--foreground)]">- {item.user_answer ? (- item.question_type === "coding" ? (- <MarkdownRenderer- content={`\`\`\`python\n${item.user_answer}\n\`\`\``}- variant="prose"- className="text-[13px]"- />- ) : (- <MarkdownRenderer- content={item.user_answer}- variant="prose"- className="text-[13px] leading-relaxed"- />- )- ) : (- <span className="text-[var(--muted-foreground)]">- —- </span>- )}- </div>- </div>- <div className="rounded-lg border border-green-200/60 bg-green-50/40 px-3 py-2.5 dark:border-green-900/40 dark:bg-green-950/15">- <div className="mb-1 text-[11px] font-medium uppercase tracking-wide text-green-600 dark:text-green-400">- {t("Reference Answer")}- </div>- <div className="text-[var(--foreground)]">- {item.correct_answer ? (- item.question_type === "coding" ? (- <MarkdownRenderer- content={- item.correct_answer- .trimStart()- .startsWith("```")- ? item.correct_answer- : `\`\`\`python\n${item.correct_answer}\n\`\`\``- }- variant="prose"- className="text-[13px]"- />- ) : (- <MarkdownRenderer- content={item.correct_answer}- variant="prose"- className="text-[13px] leading-relaxed"- />- )- ) : (- <span className="text-[var(--muted-foreground)]">- —- </span>- )}- </div>- </div>- </div>- )}-- {/* Explanation */}- {item.explanation && (- <div className="mb-3 rounded-lg border border-blue-200/60 bg-blue-50/30 px-3 py-2.5 dark:border-blue-900/40 dark:bg-blue-950/15">- <div className="mb-1 text-[11px] font-medium uppercase tracking-wide text-blue-600 dark:text-blue-400">- {t("Explanation")}- </div>- <div className="text-[13px] leading-relaxed text-[var(--foreground)]">- <MarkdownRenderer- content={item.explanation}- variant="prose"- className="text-[13px] leading-relaxed"- />- </div>- </div>- )}-- {/* Footer */}- <div className="mt-3 flex flex-wrap items-center justify-between gap-2 text-[11px]">- <div className="flex items-center gap-2">- <Link- href={`/?session=${encodeURIComponent(item.session_id)}`}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2.5 py-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <ExternalLink size={10} />- {item.session_title || t("Original Session")}- </Link>- {item.followup_session_id && (- <Link- href={`/?session=${encodeURIComponent(item.followup_session_id)}`}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-2.5 py-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- <MessageSquare size={10} />- {t("Follow-up")}- </Link>- )}- </div>- <span className="text-[var(--muted-foreground)]">- {new Date(item.created_at * 1000).toLocaleString()}- </span>- </div>- </li>- );- })}- </ul>- )}- </div>- </div>+ }+ >+ <NotebookRoute />+ </Suspense>);}diff --git a/web/app/(utility)/space/notebooks/page.tsx b/web/app/(utility)/space/notebooks/page.tsxindex be165efc8..2529f3df0 100644--- a/web/app/(utility)/space/notebooks/page.tsx+++ b/web/app/(utility)/space/notebooks/page.tsx@@ -1,5 +1,20 @@-import NotebooksSection from "@/components/space/NotebooksSection";+import { redirect } from "next/navigation";-export default function SpaceNotebooksPage() {- return <NotebooksSection />;+// Notebooks moved out of the Space document layout to their own full-height+// console at /notebook. This route stays behind so existing links and+// bookmarks keep working; it forwards the `?notebook=<id>` deep link too.+export default async function SpaceNotebooksPage({+ searchParams,+}: {+ searchParams: Promise<Record<string, string | string[] | undefined>>;+}) {+ const params = await searchParams;+ const requested = params.notebook;+ const notebookId = Array.isArray(requested) ? requested[0] : requested;++ redirect(+ notebookId+ ? `/notebook?notebook=${encodeURIComponent(notebookId)}`+ : "/notebook",+ );}diff --git a/web/app/(workspace)/book/components/blocks/BlockBodyEditor.tsx b/web/app/(workspace)/book/components/blocks/BlockBodyEditor.tsxindex 9306b45e8..6c8ff34b8 100644--- a/web/app/(workspace)/book/components/blocks/BlockBodyEditor.tsx+++ b/web/app/(workspace)/book/components/blocks/BlockBodyEditor.tsx@@ -57,7 +57,10 @@ export default function BlockBodyEditor({if (event.key === "Escape") {event.preventDefault();onCancel();- } else if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ } else if (+ event.key === "Enter" &&+ (event.metaKey || event.ctrlKey)+ ) {event.preventDefault();void commit();}diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 8ad55063b..4de69c2f3 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -13,6 +13,7 @@ import { useParams, useRouter } from "next/navigation";import {BarChart3,+ BookOpenText,BrainCircuit,Clapperboard,Code2,@@ -64,6 +65,8 @@ import {type MessageRequestSnapshot,} from "@/context/UnifiedChatContext";import { useAppShell } from "@/context/AppShellContext";++import { READER_ASK_EVENT, ReaderPane } from "@/components/reading/ReaderPane";import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";import {@@ -75,6 +78,8 @@ import { readChatLaunchIntent } from "@/lib/chat-launch-intent";import { useAttachmentLimits } from "@/lib/attachment-limits";import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";+import { useSetupSync } from "@/hooks/useSetupSync";+import { consumePendingPrompt } from "@/lib/pending-prompt";import {loadCapabilityPlaygroundConfigs,resolveCapabilityPlaygroundConfig,@@ -210,11 +215,16 @@ interface CapabilityDef {icon: LucideIcon;allowedTools: ToolName[];defaultTools: ToolName[];- // Loop-engine capabilities run on the chat agent loop (solve / mastery) rather- // than a bespoke pipeline. They are collapsed into the "More" flyout in the- // capability picker instead of listed directly. Driven by the loop-capability- // registry on the backend; mirrored here as a static flag.- loopEngine?: boolean;+ /**+ * Collapse this capability into the picker's "More" flyout instead of listing+ * it directly.+ *+ * Purely about presentation — which handful of modes deserve to be one click+ * away. It used to key off whether a capability ran on the chat agent loop,+ * which conflated an implementation detail with menu order and meant the menu+ * could not be reordered without lying about the engine.+ */+ secondary?: boolean;}const CAPABILITIES: CapabilityDef[] = [@@ -242,7 +252,7 @@ const CAPABILITIES: CapabilityDef[] = [icon: BrainCircuit,allowedTools: ["web_search", "code_execution", "reason"],defaultTools: ["web_search", "code_execution", "reason"],- loopEngine: true,+ secondary: true,},{value: "deep_question",@@ -259,6 +269,7 @@ const CAPABILITIES: CapabilityDef[] = [icon: Microscope,allowedTools: ["web_search", "paper_search", "code_execution"],defaultTools: ["web_search", "paper_search", "code_execution"],+ secondary: true,},{value: "visualize",@@ -279,7 +290,16 @@ const CAPABILITIES: CapabilityDef[] = [// These are only the extra optional tools the tutor may also reach for.allowedTools: ["web_search", "code_execution"],defaultTools: [],- loopEngine: true,+ },+ {+ value: "immersive_reading",+ label: "Immersive Reading",+ description: "Read a document with the assistant, cited line by line",+ icon: BookOpenText,+ // The five reading tools auto-mount server-side once a document is open;+ // these are the extra tools the assistant may also reach for while reading.+ allowedTools: ["web_search", "code_execution", "reason"],+ defaultTools: [],},];@@ -583,6 +603,32 @@ export default function ChatPage() {prefillInputRef.current?.(text);}, []);+ // A message handed over by another page (Settings' "set up with DeepTutor"+ // button). Prefilled rather than sent: the user reads what will be asked and+ // presses enter themselves. Consumed once, so a refresh does not retype it.+ //+ // Retried on a short bounded schedule rather than fired once: the composer+ // installs its prefill bridge from its own effect, and it is not mounted at+ // all while a session is still loading. A single attempt would land on a null+ // ref and drop the message silently — the user arrives from Settings at an+ // empty box with no idea the button did anything.+ useEffect(() => {+ const pending = consumePendingPrompt();+ if (!pending) return;+ let attempts = 0;+ let timer: ReturnType<typeof setTimeout>;+ const attempt = () => {+ if (prefillInputRef.current) {+ handlePrefillComposer(pending);+ return;+ }+ if (attempts++ >= 20) return; // ~2s, then give up quietly+ timer = setTimeout(attempt, 100);+ };+ timer = setTimeout(attempt, 0);+ return () => clearTimeout(timer);+ }, [handlePrefillComposer]);+// A clickable node inside an inlined visualization SVG (data-prompt) — and the// html widget's sendPrompt bridge — dispatch this window event; mirror it into// the composer as a prefilled follow-up (user confirms before sending).@@ -595,6 +641,30 @@ export default function ChatPage() {return () => window.removeEventListener("dt:visualize-prompt", onVizPrompt);}, [handlePrefillComposer]);+ // "Ask about this" on a reader selection. Prefilled rather than sent, and+ // shaped as a quote plus a locator so the model can verify it against the+ // document instead of taking the user's paraphrase on faith.+ useEffect(() => {+ const onReaderAsk = (event: Event) => {+ const detail = (+ event as CustomEvent<{+ quote?: string;+ locator?: number;+ unit?: string;+ }>+ ).detail;+ const quote = (detail?.quote || "").trim();+ if (!quote) return;+ const unit = detail?.unit || "page";+ const where = detail?.locator ? ` (${unit} ${detail.locator})` : "";+ handlePrefillComposer(+ `> ${quote}\n\n${t("Explain this passage")}${where}: `,+ );+ };+ window.addEventListener(READER_ASK_EVENT, onReaderAsk);+ return () => window.removeEventListener(READER_ASK_EVENT, onReaderAsk);+ }, [handlePrefillComposer, t]);+const activeCap = useMemo(() => getCapability(state.activeCapability),[state.activeCapability],@@ -602,6 +672,7 @@ export default function ChatPage() {const isQuizMode = activeCap.value === "deep_question";const isVisualizeMode = activeCap.value === "visualize";const isResearchMode = activeCap.value === "deep_research";+ const isReadingMode = activeCap.value === "immersive_reading";const capabilityNeedsConfig = isQuizMode || isVisualizeMode || isResearchMode;// Edit-invalidates-confirm wrappers — flipping any field after the user@@ -653,6 +724,10 @@ export default function ChatPage() {ensureActivityPanelOpen();}}, [capabilityNeedsConfig, ensureActivityPanelOpen]);+ // Adopt UI preferences the assistant changed mid-conversation: the browser+ // otherwise keeps serving its own cached language/theme and the user is told+ // "done" while nothing visibly changes.+ useSetupSync(state.messages);const hasMessages = state.messages.length > 0;// Time-of-day greeting: seeded once on mount from the user's local clock so// the heading stays stable while they're on the page. State (not useMemo)@@ -1902,339 +1977,358 @@ export default function ChatPage() {messages={state.messages}viewerPanelRef={viewerPanelRef}/>- <div- // When the preview drawer is open AND the viewport is wide enough,- // push the chat content to the left by the drawer's width so the two- // panels live side-by-side (matches Claude desktop). On smaller- // screens the drawer overlays — squeezing a phone-width chat into- // the remaining ~30 px would be useless. The actual padding +- // transition lives in `chat-preview-shell` (globals.css) so we can- // hand-tune it without fighting Tailwind's arbitrary-value parser.- data-preview-open={previewSource ? "true" : "false"}- data-viewer-open={viewerPanelOpen ? "true" : "false"}- className="chat-preview-shell flex h-full flex-col overflow-hidden bg-[var(--background)]"- >- <div className="mx-auto flex w-full max-w-[960px] flex-wrap items-center justify-between gap-x-3 gap-y-1.5 px-6 pt-3 pb-0">- <div className="group/title min-w-0 flex flex-1 items-center gap-2">- {sessionTitleEditing ? (- <input- ref={titleInputRef}- value={sessionTitleDraft}- onChange={(event) => setSessionTitleDraft(event.target.value)}- onBlur={() => void commitSessionTitleEdit()}- onKeyDown={handleSessionTitleKeyDown}- disabled={sessionTitleSaving}- aria-label={t("Session title")}- className="min-w-0 flex-1 rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 font-serif text-[17px] font-semibold tracking-[-0.01em] text-[var(--foreground)] shadow-sm outline-none transition focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/20 disabled:opacity-60"- maxLength={100}+ {/* Positioning context for the reader pane. AppShell's own content box+ is not positioned, so without this the absolutely-positioned pane+ would escape and cover the sidebar. */}+ <div className="relative h-full overflow-hidden">+ {/* The reader slides in from the left and the chat column shrinks to+ make room. Rendered as a sibling with its own transform rather than+ wrapping the chat, so switching modes never remounts the chat tree —+ a remount would refetch every piece of session metadata and stall the+ UI for seconds (the regression behind the slow session-open bug). */}+ <div+ data-reader-open={isReadingMode ? "true" : "false"}+ className="dt-reader-shell"+ >+ {isReadingMode && <ReaderPane onClose={() => setCapability("")} />}+ </div>+ <div+ // When the preview drawer is open AND the viewport is wide enough,+ // push the chat content to the left by the drawer's width so the two+ // panels live side-by-side (matches Claude desktop). On smaller+ // screens the drawer overlays — squeezing a phone-width chat into+ // the remaining ~30 px would be useless. The actual padding ++ // transition lives in `chat-preview-shell` (globals.css) so we can+ // hand-tune it without fighting Tailwind's arbitrary-value parser.+ data-preview-open={previewSource ? "true" : "false"}+ data-viewer-open={viewerPanelOpen ? "true" : "false"}+ data-reader-open={isReadingMode ? "true" : "false"}+ className="chat-preview-shell flex h-full flex-col overflow-hidden bg-[var(--background)]"+ >+ <div className="mx-auto flex w-full max-w-[960px] flex-wrap items-center justify-between gap-x-3 gap-y-1.5 px-6 pt-3 pb-0">+ <div className="group/title min-w-0 flex flex-1 items-center gap-2">+ {sessionTitleEditing ? (+ <input+ ref={titleInputRef}+ value={sessionTitleDraft}+ onChange={(event) =>+ setSessionTitleDraft(event.target.value)+ }+ onBlur={() => void commitSessionTitleEdit()}+ onKeyDown={handleSessionTitleKeyDown}+ disabled={sessionTitleSaving}+ aria-label={t("Session title")}+ className="min-w-0 flex-1 rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 font-serif text-[17px] font-semibold tracking-[-0.01em] text-[var(--foreground)] shadow-sm outline-none transition focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/20 disabled:opacity-60"+ maxLength={100}+ />+ ) : (+ <button+ type="button"+ onClick={startSessionTitleEdit}+ disabled={!canRenameSession}+ title={+ canRenameSession+ ? t("Click to rename session")+ : t("Start a conversation to rename")+ }+ className="inline-flex min-w-0 max-w-full items-center gap-2 rounded-xl px-2 py-1 text-left font-serif text-[17px] font-semibold tracking-[-0.01em] text-[var(--foreground)] transition hover:bg-[var(--muted)]/55 disabled:cursor-default disabled:hover:bg-transparent"+ >+ <span className="truncate">{displaySessionTitle}</span>+ {canRenameSession ? (+ <PenLine className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)] opacity-0 transition-opacity group-hover/title:opacity-100" />+ ) : null}+ </button>+ )}+ {sessionTitleSaving ? (+ <span className="shrink-0 text-xs text-[var(--muted-foreground)]">+ {t("Saving...")}+ </span>+ ) : null}+ {sessionTitleError ? (+ <span className="shrink-0 text-xs text-[var(--destructive)]">+ {sessionTitleError}+ </span>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-0.5">+ <HeaderActionButton+ onClick={() => setShowSaveModal(true)}+ disabled={!chatSavePayload}+ icon={BookmarkPlus}+ label={t("Save to Notebook")}/>- ) : (- <button- type="button"- onClick={startSessionTitleEdit}- disabled={!canRenameSession}- title={- canRenameSession- ? t("Click to rename session")- : t("Start a conversation to rename")- }- className="inline-flex min-w-0 max-w-full items-center gap-2 rounded-xl px-2 py-1 text-left font-serif text-[17px] font-semibold tracking-[-0.01em] text-[var(--foreground)] transition hover:bg-[var(--muted)]/55 disabled:cursor-default disabled:hover:bg-transparent"- >- <span className="truncate">{displaySessionTitle}</span>- {canRenameSession ? (- <PenLine className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)] opacity-0 transition-opacity group-hover/title:opacity-100" />- ) : null}- </button>- )}- {sessionTitleSaving ? (- <span className="shrink-0 text-xs text-[var(--muted-foreground)]">- {t("Saving...")}- </span>- ) : null}- {sessionTitleError ? (- <span className="shrink-0 text-xs text-[var(--destructive)]">- {sessionTitleError}- </span>- ) : null}- </div>- <div className="flex shrink-0 items-center gap-0.5">- <HeaderActionButton- onClick={() => setShowSaveModal(true)}- disabled={!chatSavePayload}- icon={BookmarkPlus}- label={t("Save to Notebook")}- />- <HeaderActionButton- onClick={handleDownloadMarkdown}- disabled={!state.messages.length}- icon={Download}- label={t("Download Markdown")}- title={t("Download chat history as Markdown")}- />- <HeaderActionButton- onClick={toggleViewerPanel}- active={viewerPanelOpen}- icon={PanelRight}- label={t("Activity")}- title={t("Session activity, attachments & previews")}- />+ <HeaderActionButton+ onClick={handleDownloadMarkdown}+ disabled={!state.messages.length}+ icon={Download}+ label={t("Download Markdown")}+ title={t("Download chat history as Markdown")}+ />+ <HeaderActionButton+ onClick={toggleViewerPanel}+ active={viewerPanelOpen}+ icon={PanelRight}+ label={t("Activity")}+ title={t("Session activity, attachments & previews")}+ />+ </div></div>- </div>- <div className="flex w-full flex-1 min-h-0 flex-col">- {sessionLoading ? (- <div className="flex w-full flex-1 min-h-0 justify-center px-6">- <div className="h-full w-full max-w-[960px]">- <SessionLoadingView onCancel={cancelSessionLoad} />+ <div className="flex w-full flex-1 min-h-0 flex-col">+ {sessionLoading ? (+ <div className="flex w-full flex-1 min-h-0 justify-center px-6">+ <div className="h-full w-full max-w-[960px]">+ <SessionLoadingView onCancel={cancelSessionLoad} />+ </div></div>- </div>- ) : !hasMessages ? (- <div className="flex w-full flex-1 min-h-0 items-end justify-center pb-14 animate-fade-in px-6">- <div className="w-full max-w-[960px] flex items-center justify-center gap-4">- <img- src="/logo_black.png"- alt="DeepTutor"- width={40}- height={40}- className="h-10 w-10 select-none"- draggable={false}- />- <h1 className="font-serif text-[40px] font-medium leading-[1.1] tracking-[-0.015em] text-[var(--foreground)]">- {t(welcomeGreeting)}- </h1>+ ) : !hasMessages ? (+ <div className="flex w-full flex-1 min-h-0 items-end justify-center pb-14 animate-fade-in px-6">+ <div className="w-full max-w-[960px] flex items-center justify-center gap-4">+ <img+ src="/logo_black.png"+ alt="DeepTutor"+ width={40}+ height={40}+ className="h-10 w-10 select-none"+ draggable={false}+ />+ <h1 className="font-serif text-[40px] font-medium leading-[1.1] tracking-[-0.015em] text-[var(--foreground)]">+ {t(welcomeGreeting)}+ </h1>+ </div></div>- </div>- ) : (- // Positioned wrapper spanning exactly the scrollport, so the- // turn navigator can overlay the left gutter without living- // inside the masked scroll container (its top/bottom fade- // would clip the rail's ends).- <div className="relative flex w-full flex-1 min-h-0 flex-col">- <div- ref={messagesContainerRef}- data-chat-scroll-root="true"- onScroll={handleMessagesScroll}- onClick={handleMessagesClick}- // `both-edges` reserves the scrollbar gutter on both sides so- // the inner mx-auto column centers on the same axis as the- // header and composer (siblings outside this scrollport) on- // classic-scrollbar platforms; plain `stable` would shift it- // ~half a scrollbar-width left of them.- className={`w-full flex-1 min-h-0 overflow-y-auto [scrollbar-gutter:stable_both-edges] ${hasMessages ? "pt-6" : "pt-2 pb-6"}`}- style={- hasMessages- ? (() => {- // The bottom 40 px of the messages area fades to- // transparent so content "dissolves" into the composer- // gutter. Without enough bottom padding, the fade- // overlaps the last assistant paragraph and looks like- // a stuck scroll — the user reaches scrollHeight but- // can still see only a faded sliver of text. paddingBottom- // is sized so the fade falls over empty space.- const maskImage =- "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)";- return {- paddingBottom: "48px",- WebkitMaskImage: maskImage,- maskImage,- };- })()- : undefined- }- >+ ) : (+ // Positioned wrapper spanning exactly the scrollport, so the+ // turn navigator can overlay the left gutter without living+ // inside the masked scroll container (its top/bottom fade+ // would clip the rail's ends).+ <div className="relative flex w-full flex-1 min-h-0 flex-col"><div- data-chat-column="true"- className="mx-auto w-full max-w-[960px] space-y-9 px-6"+ ref={messagesContainerRef}+ data-chat-scroll-root="true"+ onScroll={handleMessagesScroll}+ onClick={handleMessagesClick}+ // `both-edges` reserves the scrollbar gutter on both sides so+ // the inner mx-auto column centers on the same axis as the+ // header and composer (siblings outside this scrollport) on+ // classic-scrollbar platforms; plain `stable` would shift it+ // ~half a scrollbar-width left of them.+ className={`w-full flex-1 min-h-0 overflow-y-auto [scrollbar-gutter:stable_both-edges] ${hasMessages ? "pt-6" : "pt-2 pb-6"}`}+ style={+ hasMessages+ ? (() => {+ // The bottom 40 px of the messages area fades to+ // transparent so content "dissolves" into the composer+ // gutter. Without enough bottom padding, the fade+ // overlaps the last assistant paragraph and looks like+ // a stuck scroll — the user reaches scrollHeight but+ // can still see only a faded sliver of text. paddingBottom+ // is sized so the fade falls over empty space.+ const maskImage =+ "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)";+ return {+ paddingBottom: "48px",+ WebkitMaskImage: maskImage,+ maskImage,+ };+ })()+ : undefined+ }>- <ChatMessageList- messages={state.messages}- isStreaming={state.isStreaming}- sessionId={state.sessionId}- language={state.language}- onCopyAssistantMessage={copyAssistantMessage}- onRegenerateMessage={handleRegenerateMessage}- onConfirmOutline={handleConfirmOutline}- onPreviewAttachment={handlePreviewMessageAttachment}- onDeleteTurn={deleteTurn}- selectedBranches={state.selectedBranches}- onEditMessage={editMessage}- onSwitchBranch={switchBranch}- onSubmitUserReply={submitUserReply}- /><div- ref={messagesEndRef}- className="h-px w-full shrink-0"- />+ data-chat-column="true"+ className="mx-auto w-full max-w-[960px] space-y-9 px-6"+ >+ <ChatMessageList+ messages={state.messages}+ isStreaming={state.isStreaming}+ sessionId={state.sessionId}+ language={state.language}+ onCopyAssistantMessage={copyAssistantMessage}+ onRegenerateMessage={handleRegenerateMessage}+ onConfirmOutline={handleConfirmOutline}+ onPreviewAttachment={handlePreviewMessageAttachment}+ onDeleteTurn={deleteTurn}+ selectedBranches={state.selectedBranches}+ onEditMessage={editMessage}+ onSwitchBranch={switchBranch}+ onSubmitUserReply={submitUserReply}+ />+ <div+ ref={messagesEndRef}+ className="h-px w-full shrink-0"+ />+ </div></div>+ <TurnNavigator+ entries={chatOutline}+ scrollRootRef={messagesContainerRef}+ onJump={jumpToTurn}+ onJumpToBottom={resumeFollowingLatest}+ /></div>- <TurnNavigator- entries={chatOutline}- scrollRootRef={messagesContainerRef}- onJump={jumpToTurn}- onJumpToBottom={resumeFollowingLatest}- />- </div>- )}+ )}- {/* Anchors the conversation to the path it is advancing. Only when+ {/* Anchors the conversation to the path it is advancing. Only whenthe mastery capability is actually driving this turn — a stalepath id on a plain chat would be a lie. */}- {state.activeCapability === "mastery_path" &&- state.masteryPathId && (- <MasteryPathStrip pathId={state.masteryPathId} />- )}-- <ChatComposer- composerRef={composerRef}- capMenuRef={capMenuRef}- capBtnRef={capBtnRef}- spaceMenuRef={spaceMenuRef}- spaceBtnRef={spaceBtnRef}- dragCounter={dragCounter}- dragging={dragging}- capMenuOpen={capMenuOpen}- spaceMenuOpen={spaceMenuOpen}- hasMessages={hasMessages}- attachments={attachments}- attachmentError={attachmentError}- activeCap={activeCap}- knowledgeBases={kbOptions}- connectedAgents={agentOptions}- selectedAgent={selectedAgent}- onSelectAgent={handleSelectAgent}- subagentBudget={subagentBudget}- onSubagentBudgetChange={setSubagentBudget}- llmOptions={llmOptions}- activeLLMDefault={activeLLMDefault}- llmSelection={state.llmSelection}- llmOptionsLoading={llmOptionsLoading}- llmOptionsError={llmOptionsError}- onRefreshLLMOptions={() =>- void refreshLLMOptions({ force: true })- }- contextBudget={contextBudget}- selectedBookReferences={selectedBookReferences}- selectedNotebookRecords={selectedNotebookRecords}- selectedHistorySessions={selectedHistorySessions}- selectedAgentSessions={selectedAgentSessions}- selectedQuestionEntries={selectedQuestionEntries}- notebookReferenceGroups={notebookReferenceGroups}- selectedPersona={null}- selectedMemoryFiles={selectedMemoryFiles}- selectedKnowledgeBases={selectedKbOnly}- isStreaming={state.isStreaming}- isVisualizeMode={isVisualizeMode}- capabilityNeedsConfig={capabilityNeedsConfig}- capabilityConfigConfirmed={capabilityConfigConfirmed}- onRequestConfigConfirm={ensureActivityPanelOpen}- capabilities={CAPABILITIES}- onSetCapMenuOpen={setCapMenuOpen}- onSetSpaceMenuOpen={setSpaceMenuOpen}- onToggleKB={handleToggleKB}- onSelectLLM={setLLMSelection}- onSelectNotebookPicker={handleSelectNotebookPicker}- onSelectBookPicker={handleSelectBookPicker}- onSelectHistoryPicker={handleSelectHistoryPicker}- onSelectAgentsPicker={handleSelectAgentsPicker}- onSelectQuestionBankPicker={handleSelectQuestionBankPicker}- onSelectPersonaPicker={handleSelectPersonaPicker}- onSelectMemoryPicker={handleSelectMemoryPicker}- onClearPersona={handleClearPersona}- personaSelection={state.personaSelection}- onPersonaSelectionChange={setPersonaSelection}- personaSelectorOpen={personaSelectorOpen}- onPersonaSelectorOpenChange={setPersonaSelectorOpen}- onToggleMemoryFile={handleToggleMemoryFile}- onSend={handleSend}- onRemoveAttachment={removeAttachment}- onPreviewAttachment={handlePreviewPendingAttachment}- onRemoveHistory={handleRemoveHistory}- onRemoveAgent={handleRemoveAgent}- onRemoveBookReference={handleRemoveBookReference}- onRemoveNotebook={handleRemoveNotebook}- onRemoveQuestion={handleRemoveQuestion}- onDragEnter={handleDragEnter}- onDragLeave={handleDragLeave}- onDragOver={handleDragOver}- onDrop={handleDrop}- onPaste={handlePaste}- onAddFiles={handleAddFiles}- onSelectCapability={handleSelectCapability}- onCancelStreaming={cancelStreamingTurn}- prefillInputRef={prefillInputRef}- />- {/* Starter chips sit between the composer and the spacer, so they+ {state.activeCapability === "mastery_path" &&+ state.masteryPathId && (+ <MasteryPathStrip pathId={state.masteryPathId} />+ )}++ <ChatComposer+ composerRef={composerRef}+ capMenuRef={capMenuRef}+ capBtnRef={capBtnRef}+ spaceMenuRef={spaceMenuRef}+ spaceBtnRef={spaceBtnRef}+ dragCounter={dragCounter}+ dragging={dragging}+ capMenuOpen={capMenuOpen}+ spaceMenuOpen={spaceMenuOpen}+ hasMessages={hasMessages}+ attachments={attachments}+ attachmentError={attachmentError}+ activeCap={activeCap}+ knowledgeBases={kbOptions}+ connectedAgents={agentOptions}+ selectedAgent={selectedAgent}+ onSelectAgent={handleSelectAgent}+ subagentBudget={subagentBudget}+ onSubagentBudgetChange={setSubagentBudget}+ llmOptions={llmOptions}+ activeLLMDefault={activeLLMDefault}+ llmSelection={state.llmSelection}+ llmOptionsLoading={llmOptionsLoading}+ llmOptionsError={llmOptionsError}+ onRefreshLLMOptions={() =>+ void refreshLLMOptions({ force: true })+ }+ contextBudget={contextBudget}+ selectedBookReferences={selectedBookReferences}+ selectedNotebookRecords={selectedNotebookRecords}+ selectedHistorySessions={selectedHistorySessions}+ selectedAgentSessions={selectedAgentSessions}+ selectedQuestionEntries={selectedQuestionEntries}+ notebookReferenceGroups={notebookReferenceGroups}+ selectedPersona={null}+ selectedMemoryFiles={selectedMemoryFiles}+ selectedKnowledgeBases={selectedKbOnly}+ isStreaming={state.isStreaming}+ isVisualizeMode={isVisualizeMode}+ capabilityNeedsConfig={capabilityNeedsConfig}+ capabilityConfigConfirmed={capabilityConfigConfirmed}+ onRequestConfigConfirm={ensureActivityPanelOpen}+ capabilities={CAPABILITIES}+ onSetCapMenuOpen={setCapMenuOpen}+ onSetSpaceMenuOpen={setSpaceMenuOpen}+ onToggleKB={handleToggleKB}+ onSelectLLM={setLLMSelection}+ onSelectNotebookPicker={handleSelectNotebookPicker}+ onSelectBookPicker={handleSelectBookPicker}+ onSelectHistoryPicker={handleSelectHistoryPicker}+ onSelectAgentsPicker={handleSelectAgentsPicker}+ onSelectQuestionBankPicker={handleSelectQuestionBankPicker}+ onSelectPersonaPicker={handleSelectPersonaPicker}+ onSelectMemoryPicker={handleSelectMemoryPicker}+ onClearPersona={handleClearPersona}+ personaSelection={state.personaSelection}+ onPersonaSelectionChange={setPersonaSelection}+ personaSelectorOpen={personaSelectorOpen}+ onPersonaSelectorOpenChange={setPersonaSelectorOpen}+ onToggleMemoryFile={handleToggleMemoryFile}+ onSend={handleSend}+ onRemoveAttachment={removeAttachment}+ onPreviewAttachment={handlePreviewPendingAttachment}+ onRemoveHistory={handleRemoveHistory}+ onRemoveAgent={handleRemoveAgent}+ onRemoveBookReference={handleRemoveBookReference}+ onRemoveNotebook={handleRemoveNotebook}+ onRemoveQuestion={handleRemoveQuestion}+ onDragEnter={handleDragEnter}+ onDragLeave={handleDragLeave}+ onDragOver={handleDragOver}+ onDrop={handleDrop}+ onPaste={handlePaste}+ onAddFiles={handleAddFiles}+ onSelectCapability={handleSelectCapability}+ onCancelStreaming={cancelStreamingTurn}+ prefillInputRef={prefillInputRef}+ />+ {/* Starter chips sit between the composer and the spacer, so theyride up with the composer on the empty screen and disappear themoment the conversation has a first message. Clicking one sendsit through the normal send path: this page is already a draftsession when it has no messages, so that both creates thesession and starts it on the topic. */}- {!hasMessages ? (- <StarterSuggestions- onPick={(prompt) => void handleSend(prompt)}- disabled={state.isStreaming}+ {!hasMessages ? (+ <StarterSuggestions+ onPick={(prompt) => void handleSend(prompt)}+ disabled={state.isStreaming}+ />+ ) : null}+ <div+ aria-hidden="true"+ className="shrink-0"+ style={{+ flexGrow: hasMessages ? 0 : 1.4,+ transition: "flex-grow 650ms cubic-bezier(0.16, 1, 0.3, 1)",+ }}/>- ) : null}- <div- aria-hidden="true"- className="shrink-0"- style={{- flexGrow: hasMessages ? 0 : 1.4,- transition: "flex-grow 650ms cubic-bezier(0.16, 1, 0.3, 1)",- }}+ </div>+ <NotebookRecordPicker+ open={showNotebookPicker}+ onClose={handleCloseNotebookPicker}+ onApply={handleApplyNotebookRecords}+ />+ <BookReferencePicker+ open={showBookPicker}+ initialReferences={selectedBookReferences}+ onClose={handleCloseBookPicker}+ onApply={handleApplyBookReferences}+ />+ <HistorySessionPicker+ open={showHistoryPicker}+ onClose={handleCloseHistoryPicker}+ onApply={handleApplyHistorySessions}+ />+ <MyAgentsPicker+ open={showAgentsPicker}+ onClose={handleCloseAgentsPicker}+ onApply={handleApplyAgentSessions}+ />+ <QuestionBankPicker+ open={showQuestionBankPicker}+ onClose={handleCloseQuestionBankPicker}+ onApply={handleApplyQuestionEntries}+ />+ <MemoryPicker+ open={showMemoryPicker}+ initialFiles={selectedMemoryFiles}+ onClose={handleCloseMemoryPicker}+ onApply={handleApplyMemoryFiles}+ />+ <SaveToNotebookModal+ open={showSaveModal}+ payload={chatSavePayload}+ messages={chatSaveMessages}+ onClose={handleCloseSaveModal}+ />+ <FilePreviewDrawer+ open={previewSource !== null}+ source={previewSource}+ onClose={handleClosePreview}+ />+ <SessionViewerPanel+ ref={viewerPanelRef}+ open={viewerPanelOpen && previewSource === null}+ sessionId={state.sessionId}+ activity={sessionActivity}+ configSection={capabilityConfigSection}+ onClose={() => setViewerOpen(false)}+ onAutoOpen={() => setViewerOpen(true)}/></div>- <NotebookRecordPicker- open={showNotebookPicker}- onClose={handleCloseNotebookPicker}- onApply={handleApplyNotebookRecords}- />- <BookReferencePicker- open={showBookPicker}- initialReferences={selectedBookReferences}- onClose={handleCloseBookPicker}- onApply={handleApplyBookReferences}- />- <HistorySessionPicker- open={showHistoryPicker}- onClose={handleCloseHistoryPicker}- onApply={handleApplyHistorySessions}- />- <MyAgentsPicker- open={showAgentsPicker}- onClose={handleCloseAgentsPicker}- onApply={handleApplyAgentSessions}- />- <QuestionBankPicker- open={showQuestionBankPicker}- onClose={handleCloseQuestionBankPicker}- onApply={handleApplyQuestionEntries}- />- <MemoryPicker- open={showMemoryPicker}- initialFiles={selectedMemoryFiles}- onClose={handleCloseMemoryPicker}- onApply={handleApplyMemoryFiles}- />- <SaveToNotebookModal- open={showSaveModal}- payload={chatSavePayload}- messages={chatSaveMessages}- onClose={handleCloseSaveModal}- />- <FilePreviewDrawer- open={previewSource !== null}- source={previewSource}- onClose={handleClosePreview}- />- <SessionViewerPanel- ref={viewerPanelRef}- open={viewerPanelOpen && previewSource === null}- sessionId={state.sessionId}- activity={sessionActivity}- configSection={capabilityConfigSection}- onClose={() => setViewerOpen(false)}- onAutoOpen={() => setViewerOpen(true)}- /></div></GeogebraTabProvider></QuizFollowupProvider>diff --git a/web/app/(workspace)/layout.tsx b/web/app/(workspace)/layout.tsxindex 1e0f8b9c8..b3f23775b 100644--- a/web/app/(workspace)/layout.tsx+++ b/web/app/(workspace)/layout.tsx@@ -3,6 +3,7 @@ import AppShell from "@/components/layout/AppShell";import { CapabilityAccessProvider } from "@/components/access/CapabilityAccessContext";import CapabilityGate from "@/components/access/CapabilityGate";import { UnifiedChatProvider } from "@/context/UnifiedChatContext";+import { ReadingProvider } from "@/context/ReadingContext";export default function WorkspaceLayout({children,@@ -12,9 +13,14 @@ export default function WorkspaceLayout({return (<CapabilityAccessProvider><UnifiedChatProvider>- <AppShell sidebar={<WorkspaceSidebar />}>- <CapabilityGate>{children}</CapabilityGate>- </AppShell>+ {/* Above the page on purpose: sending the first message navigates+ /home → /home/<id>, which remounts the page. The open document+ must not die with it. */}+ <ReadingProvider>+ <AppShell sidebar={<WorkspaceSidebar />}>+ <CapabilityGate>{children}</CapabilityGate>+ </AppShell>+ </ReadingProvider></UnifiedChatProvider></CapabilityAccessProvider>);diff --git a/web/app/globals.css b/web/app/globals.cssindex 15f5cd97f..59aef7cf5 100644--- a/web/app/globals.css+++ b/web/app/globals.css@@ -785,6 +785,210 @@ body[data-picker-open] .dt-mark-pulse {}}+/* ─── Immersive reading ───────────────────────────────────────────────────+ The reader occupies the left ~2/3 and the chat column shrinks into the+ remaining third. Both sides animate the same distance over the same+ duration, so the pane appears to push the chat aside rather than slide+ over it.++ Padding rather than a flex sibling: the chat shell is not remounted when+ the mode toggles, so switching in and out never refetches session state.++ Below `lg` the reader takes the whole width and the chat is reachable by+ leaving the mode — a 380 px phone cannot usefully show both. */+.dt-reader-shell {+ position: absolute;+ inset: 0 auto 0 0;+ z-index: 30;+ width: 100%;+ display: flex;+ transform: translateX(-100%);+ transition:+ transform 240ms cubic-bezier(0.32, 0.72, 0, 1),+ visibility 240ms;+ visibility: hidden;+}+.dt-reader-shell[data-reader-open="true"] {+ transform: translateX(0);+ visibility: visible;+}+.dt-reader-shell > * {+ flex: 1;+ min-width: 0;+}+.chat-preview-shell {+ padding-left: 0;+ transition:+ padding-right 220ms ease-out,+ padding-left 240ms cubic-bezier(0.32, 0.72, 0, 1);+}+@media (min-width: 1024px) {+ /* The seam is user-draggable: `ReaderResizeHandle` writes `--reader-width`,+ and BOTH sides read it through the same `min()` so the pane edge and the+ chat's padding can never disagree — a mismatch would show as a gap or an+ overlap while dragging. The ceiling keeps the conversation usable no matter+ what is stored; the handle enforces a floor in px. */+ .dt-reader-shell {+ width: min(var(--reader-width, 64%), 82%);+ }+ .chat-preview-shell[data-reader-open="true"] {+ padding-left: min(var(--reader-width, 64%), 82%);+ }+ /* While dragging, both sides must track the cursor frame-for-frame rather+ than easing along behind it. */+ :root[data-reader-resizing="true"] .dt-reader-shell,+ :root[data-reader-resizing="true"] .chat-preview-shell {+ transition: none;+ }+}++/* The drag seam itself: a wide, invisible hit area with a hairline that only+ appears on hover or focus, so the split does not draw attention to itself+ while reading. */+.dt-reader-resize {+ touch-action: none;+}+@media (max-width: 1023px) {+ /* Below `lg` the reader takes the full width and there is no seam to drag. */+ .dt-reader-resize {+ display: none;+ }+}++/* pdf.js text layer. Flattened from pdfjs-dist's own stylesheet (which uses+ nested CSS this build's PostCSS pipeline does not compile) and scoped to the+ class pdf.js itself sets. The spans are transparent and sit exactly over the+ rendered glyphs — that alignment is what makes text selection in the reader+ land on the words the user is pointing at. */+.textLayer {+ position: absolute;+ inset: 0;+ overflow: clip;+ opacity: 1;+ line-height: 1;+ text-align: initial;+ letter-spacing: normal;+ word-spacing: normal;+ text-size-adjust: none;+ forced-color-adjust: none;+ transform-origin: 0 0;+ caret-color: CanvasText;+ z-index: 0;+ --min-font-size: 1;+ --text-scale-factor: calc(+ var(--total-scale-factor, 1) * var(--min-font-size)+ );+ --min-font-size-inv: calc(1 / var(--min-font-size));+}+.textLayer span,+.textLayer br {+ color: transparent;+ position: absolute;+ white-space: pre;+ cursor: text;+ transform-origin: 0% 0%;+ user-select: text;+}+.textLayer > :not(.markedContent),+.textLayer .markedContent span:not(.markedContent) {+ z-index: 1;+ --font-height: 0;+ --scale-x: 1;+ --rotate: 0deg;+ font-size: calc(var(--text-scale-factor) * var(--font-height));+ transform: rotate(var(--rotate)) scaleX(var(--scale-x))+ scale(var(--min-font-size-inv));+}+.textLayer .markedContent {+ display: contents;+}+.textLayer ::selection {+ /* The glyphs are transparent, so the selection tint IS the affordance. */+ background: rgb(59 130 246 / 0.32);+}++/* Highlight painted by `reader_goto`: pulses to catch the eye, then SETTLES at+ a still-visible tint rather than fading away.+ It persists until the next jump replaces it, because the question it answers+ — "which words is the assistant citing?" — is one the reader asks while+ reading the answer, not in the two seconds after the page moved. A highlight+ that vanished on a timer was simply missed. */+.dt-reader-flash {+ background: rgb(96 165 250 / 0.3);+ animation: dt-reader-flash 1.5s ease-out forwards;+ mix-blend-mode: multiply;+}+@keyframes dt-reader-flash {+ 0%,+ 22% {+ background: rgb(96 165 250 / 0.62);+ box-shadow: 0 0 0 3px rgb(96 165 250 / 0.55);+ }+ 100% {+ background: rgb(96 165 250 / 0.3);+ box-shadow: 0 0 0 1px rgb(96 165 250 / 0.28);+ }+}+@media (prefers-reduced-motion: reduce) {+ .dt-reader-flash {+ animation: none;+ box-shadow: 0 0 0 1px rgb(96 165 250 / 0.28);+ }+}++/* Citation chips in assistant prose. Styled by href prefix so the reading+ feature adds no props to the shared Markdown renderer. */+a[href^="#dt-locator-"] {+ display: inline-flex;+ align-items: center;+ border-radius: 5px;+ background: color-mix(in srgb, var(--primary) 12%, transparent);+ padding: 0 4px;+ font-family: var(--font-geist-mono, ui-monospace), monospace;+ font-size: 0.78em;+ font-weight: 500;+ line-height: 1.5;+ color: var(--primary);+ text-decoration: none;+ vertical-align: baseline;+ transition:+ background 120ms ease-out,+ color 120ms ease-out;+}+a[href^="#dt-locator-"]:hover {+ background: color-mix(in srgb, var(--primary) 22%, transparent);+}++/* Slimmer scrollbars inside the reader so the document, not the chrome,+ holds the eye.++ Deliberately NO `scroll-behavior: smooth` here. It would turn every+ `scrollTop` assignment into an animation, and programmatic smooth scrolling+ is silently a no-op in some embedded browsers — which would make citation+ jumps do nothing at all. A jump should also be instant on its merits: easing+ through 400 pages to reach a citation is slow and disorienting. The motion in+ this feature belongs to the pane sliding in and to the highlight pulse. */+.dt-reader-scroll {+ scrollbar-width: thin;+}+.dt-reader-scroll::-webkit-scrollbar {+ width: 9px;+ height: 9px;+}+.dt-reader-scroll::-webkit-scrollbar-thumb {+ background: color-mix(in srgb, var(--foreground) 18%, transparent);+ border-radius: 999px;+ border: 2px solid transparent;+ background-clip: content-box;+}+.dt-reader-scroll::-webkit-scrollbar-thumb:hover {+ background: color-mix(in srgb, var(--foreground) 30%, transparent);+ background-clip: content-box;+}+.dt-reader-scroll::-webkit-scrollbar-track {+ background: transparent;+}+/* Sidebar tooltip */.dt-tooltip-wrapper {@apply relative inline-flex;diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex 35bc0537b..b0948b662 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -89,7 +89,7 @@ interface CapabilityDef {allowedTools: string[];// Loop-engine capabilities (solve / mastery) run on the chat agent loop and// are collapsed into the "More" flyout instead of listed directly.- loopEngine?: boolean;+ secondary?: boolean;}/** One row in the capability picker — shared by the built-in list and the@@ -888,7 +888,7 @@ export default memo(function ChatComposer({className="dt-popup-up absolute bottom-full left-0 z-50 mb-1.5 w-[260px] overflow-visible rounded-xl border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md">{capabilities- .filter((cap) => !cap.loopEngine)+ .filter((cap) => !cap.secondary).map((cap) => (<CapMenuItemkey={cap.value}@@ -899,7 +899,7 @@ export default memo(function ChatComposer({))}{(() => {const loopCaps = capabilities.filter(- (cap) => cap.loopEngine,+ (cap) => cap.secondary,);if (loopCaps.length === 0) return null;const loopSelected = loopCaps.some(diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex 19fd8da35..5af68cac6 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -61,6 +61,8 @@ import {extractAskUserPayload,extractMessageSegments,} from "./AskUserOptions";+import { SetupCredentialCard } from "./SetupCredentialCard";+import { extractSetupCredential } from "@/lib/setup-signals";import ContextReferenceTree, {type ContextTreeItem,} from "./ContextReferenceTree";@@ -377,6 +379,13 @@ const AssistantMessage = memo(function AssistantMessage({[msg.events],);+ // Set by ``request_credential`` when a configuration step needs a secret the+ // assistant must not handle itself.+ const setupCredential = useMemo(+ () => extractSetupCredential(msg.events),+ [msg.events],+ );+// Interleaved segments for the default chat surface — text emitted// before the ask_user call renders above the card; text emitted by// the resumed iteration renders below it. Only walked when this@@ -521,6 +530,10 @@ const AssistantMessage = memo(function AssistantMessage({}}/>) : null}+ {/* Credential hand-off sits below whichever body branch rendered: it+ supplements the answer ("here's where to paste the key") rather than+ replacing it, and applies to every branch. */}+ {setupCredential ? <SetupCredentialCard data={setupCredential} /> : null}</>);});diff --git a/web/components/chat/home/SessionActivityPanel.tsx b/web/components/chat/home/SessionActivityPanel.tsxindex 360f40edb..d2c7c4d47 100644--- a/web/components/chat/home/SessionActivityPanel.tsx+++ b/web/components/chat/home/SessionActivityPanel.tsx@@ -162,7 +162,7 @@ const SPACE_CATEGORIES: Record<string, SpaceCategoryDef> = {},notebooks: {key: "notebooks",- href: "/space/notebooks",+ href: "/notebook",label: "Notebooks",icon: NotebookPen,},diff --git a/web/components/chat/home/SetupCredentialCard.tsx b/web/components/chat/home/SetupCredentialCard.tsxnew file mode 100644index 000000000..1b5959722--- /dev/null+++ b/web/components/chat/home/SetupCredentialCard.tsx@@ -0,0 +1,59 @@+"use client";++import { memo } from "react";+import { useRouter } from "next/navigation";+import { useTranslation } from "react-i18next";++import type { SetupCredentialData } from "@/lib/setup-signals";++/**+ * The hand-off card for a configuration step that needs a secret.+ *+ * The assistant is not allowed to collect API keys: anything it types passes+ * through the model's context and is written to the session transcript. So+ * `request_credential` stops at the boundary and emits this card, which sends+ * the user to the settings page that already owns the provider form. The value+ * is entered there, straight into DeepTutor, and never travels through the+ * conversation.+ *+ * Mirrors `deeptutor.capabilities.setup.tools.RequestCredentialTool`; the+ * payload is read by `extractSetupCredential` in `lib/setup-signals.ts`.+ */+export const SetupCredentialCard = memo(function SetupCredentialCard({+ data,+}: {+ data: SetupCredentialData;+}) {+ const { t } = useTranslation();+ const router = useRouter();++ return (+ <div className="mt-3 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-[0_1px_2px_rgba(0,0,0,0.04),0_4px_14px_rgba(0,0,0,0.04)]">+ <div className="flex items-start gap-3">+ <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--foreground)_8%,transparent)] text-[12px] text-[var(--foreground)]/70">+ 🔑+ </div>+ <div className="flex-1">+ <div className="text-[13px] font-medium leading-snug text-[var(--foreground)]">+ {t("This step needs credentials")}+ </div>+ <div className="mt-0.5 text-[11px] leading-relaxed text-[var(--muted-foreground)]">+ {data.reason ||+ t(+ "Enter the key on the settings page — never in chat, so it stays out of the conversation.",+ )}+ </div>+ <button+ type="button"+ onClick={() => router.push(data.settingsPath)}+ className="mt-3 inline-flex items-center gap-1.5 rounded-full border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[11.5px] font-medium text-[var(--foreground)] transition hover:bg-[color-mix(in_srgb,var(--foreground)_5%,transparent)]"+ >+ {t("Open settings")}+ <span aria-hidden>→</span>+ </button>+ </div>+ </div>+ </div>+ );+});+SetupCredentialCard.displayName = "SetupCredentialCard";diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsxindex fa5c5e3de..d854fedf1 100644--- a/web/components/common/AssistantResponse.tsx+++ b/web/components/common/AssistantResponse.tsx@@ -4,11 +4,13 @@ import { Fragment, memo, useMemo } from "react";import MarkdownRenderer from "@/components/common/MarkdownRenderer";import ModelThinkingCard from "@/components/common/ModelThinkingCard";+import { useReading } from "@/context/ReadingContext";import {hasVisibleMarkdownContent,repairMalformedStrongEmphasis,stripArtifactAnnotations,} from "@/lib/markdown-display";+import { linkifyLocatorCitations } from "@/lib/reading-citations";import { parseModelThinkingSegments } from "@/lib/think-segments";import { useSmoothStreamText } from "@/hooks/useSmoothStreamText";@@ -32,9 +34,23 @@ function AssistantResponseImpl({isStreaming = false,}: AssistantResponseProps) {const displayContent = useSmoothStreamText(content, isStreaming);+ // Immersive reading only: turn `[p.12]` citations into anchors the reader+ // pane intercepts. Outside that mode `material` is null (there is no+ // provider on most surfaces, and none when no document is open), so this is a+ // no-op and every other chat surface renders byte-identically to before.+ const { material } = useReading();+ const citedContent = useMemo(+ () =>+ material+ ? linkifyLocatorCitations(displayContent, {+ maxLocator: material.unit_count,+ })+ : displayContent,+ [displayContent, material],+ );const segments = useMemo(- () => parseModelThinkingSegments(stripArtifactAnnotations(displayContent)),- [displayContent],+ () => parseModelThinkingSegments(stripArtifactAnnotations(citedContent)),+ [citedContent],);// Decide whether the message has anything worth rendering. We consider bothdiff --git a/web/components/common/Tooltip.tsx b/web/components/common/Tooltip.tsxindex d6a3beb6a..7648bbb20 100644--- a/web/components/common/Tooltip.tsx+++ b/web/components/common/Tooltip.tsx@@ -13,24 +13,34 @@ import type { ReactNode } from "react";export default function Tooltip({label,side = "bottom",+ suppressed = false,children,}: {label: string;/** Which side of the trigger the label appears on. */side?: "top" | "bottom";+ /**+ * Hide the label while keeping the trigger mounted. Set this when the+ * trigger has opened something of its own (a menu, a popover): the pointer+ * is still over the button, so the tooltip would otherwise sit on top of+ * the very surface it just opened.+ */+ suppressed?: boolean;children: ReactNode;}) {const place = side === "bottom" ? "top-full mt-1.5" : "bottom-full mb-1.5";return (<span className="group/tip relative inline-flex">{children}- <span- role="tooltip"- aria-hidden- className={`pointer-events-none absolute left-1/2 z-[80] -translate-x-1/2 ${place} whitespace-nowrap rounded-md bg-[var(--foreground)] px-2 py-1 text-[11px] font-medium leading-none text-[var(--background)] opacity-0 shadow-md transition-opacity duration-100 group-focus-within/tip:opacity-100 group-hover/tip:opacity-100 group-hover/tip:delay-150`}- >- {label}- </span>+ {suppressed ? null : (+ <span+ role="tooltip"+ aria-hidden+ className={`pointer-events-none absolute left-1/2 z-[80] -translate-x-1/2 ${place} whitespace-nowrap rounded-md bg-[var(--foreground)] px-2 py-1 text-[11px] font-medium leading-none text-[var(--background)] opacity-0 shadow-md transition-opacity duration-100 group-focus-within/tip:opacity-100 group-hover/tip:opacity-100 group-hover/tip:delay-150`}+ >+ {label}+ </span>+ )}</span>);}diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsxindex 4964b5168..a325ffc7e 100644--- a/web/components/knowledge/EngineDetail.tsx+++ b/web/components/knowledge/EngineDetail.tsx@@ -148,7 +148,7 @@ const ENGINE_PREREQUISITES: Record<string, string> = {"Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.",lightrag:"Graph + vector retrieval with multimodal parsing. Needs the optional dependency installed; indexing is LLM-heavy. Requires active chat and embedding models; multimodal also needs a vision model.",- ima: "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",+ ima: "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key. Chat searches it, browses its documents, reads full sources, and — only when you ask — collects a web page or saves a note.",};function StatusBadge({ status }: { status: ProviderConnectionStatus }) {diff --git a/web/components/knowledge/ImaConnectionFields.tsx b/web/components/knowledge/ImaConnectionFields.tsxindex b9bf74a02..4036de8f0 100644--- a/web/components/knowledge/ImaConnectionFields.tsx+++ b/web/components/knowledge/ImaConnectionFields.tsx@@ -22,7 +22,7 @@ export default function ImaConnectionFields({<div className="space-y-3"><p className="text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">{t(- "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.",+ "DeepTutor searches and browses this library, and reads full sources when a matched snippet is too short. It only writes to IMA when you ask it to.",)}</p>diff --git a/web/components/memory/MemorySection.tsx b/web/components/memory/MemorySection.tsxindex d6288de2c..ce4f816a8 100644--- a/web/components/memory/MemorySection.tsx+++ b/web/components/memory/MemorySection.tsx@@ -226,8 +226,8 @@ function entityDeepLinkUrl(surface: Surface, ent: Entity): string | null {case "notebook": {const nbId = asString(m.notebook_id);return nbId- ? `/space/notebooks?notebook=${encodeURIComponent(nbId)}`- : "/space/notebooks";+ ? `/notebook?notebook=${encodeURIComponent(nbId)}`+ : "/notebook";}case "book":return `/book?book=${encodeURIComponent(ent.id)}`;diff --git a/web/components/notebook/NotebookConsole.tsx b/web/components/notebook/NotebookConsole.tsxnew file mode 100644index 000000000..f23c57138--- /dev/null+++ b/web/components/notebook/NotebookConsole.tsx@@ -0,0 +1,627 @@+"use client";++import Link from "next/link";+import { useRouter } from "next/navigation";+import { useCallback, useMemo, useState } from "react";+import {+ AlertTriangle,+ ArrowLeft,+ Check,+ Download,+ Loader2,+ NotebookPen,+ Pencil,+ Plus,+ Search,+ Trash2,+ X,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import Tooltip from "@/components/common/Tooltip";+import { ConfirmDialog } from "@/components/ui/ConfirmDialog";+import NotebookRecordRow from "@/components/notebook/NotebookRecordRow";+import { useNotebookLibrary } from "@/components/notebook/useNotebookLibrary";+import { notify } from "@/lib/notifications";+import { exportNotebookMarkdown } from "@/lib/notebook-api";++const SWATCHES = [+ "#6366F1",+ "#3B82F6",+ "#10B981",+ "#F59E0B",+ "#EF4444",+ "#8B5CF6",+ "#64748B",+];++interface NotebookConsoleProps {+ /** Notebook to open on arrival, e.g. from a `?notebook=<id>` deep link. */+ initialNotebookId?: string | null;+}++export default function NotebookConsole({+ initialNotebookId,+}: NotebookConsoleProps) {+ const { t } = useTranslation();+ const router = useRouter();+ const library = useNotebookLibrary(initialNotebookId);++ const [notebookQuery, setNotebookQuery] = useState("");+ const [recordQuery, setRecordQuery] = useState("");+ const [expandedRecordId, setExpandedRecordId] = useState<string | null>(null);+ const [creating, setCreating] = useState(false);+ const [newName, setNewName] = useState("");+ const [newDescription, setNewDescription] = useState("");+ const [editingMeta, setEditingMeta] = useState(false);+ const [metaName, setMetaName] = useState("");+ const [metaDescription, setMetaDescription] = useState("");+ const [metaColor, setMetaColor] = useState(SWATCHES[0]);+ const [banner, setBanner] = useState<string | null>(null);+ const [confirmingDelete, setConfirmingDelete] = useState(false);+ const [deleting, setDeleting] = useState(false);++ const { notebooks, selected, selectedId } = library;++ const visibleNotebooks = useMemo(() => {+ const needle = notebookQuery.trim().toLowerCase();+ if (!needle) return notebooks;+ return notebooks.filter((notebook) =>+ `${notebook.name} ${notebook.description ?? ""}`+ .toLowerCase()+ .includes(needle),+ );+ }, [notebooks, notebookQuery]);++ const visibleRecords = useMemo(() => {+ const records = selected?.records ?? [];+ const needle = recordQuery.trim().toLowerCase();+ if (!needle) return records;+ return records.filter((record) =>+ `${record.title} ${record.summary ?? ""} ${record.output ?? ""}`+ .toLowerCase()+ .includes(needle),+ );+ }, [selected, recordQuery]);++ const handleCreate = useCallback(async () => {+ if (!newName.trim()) return;+ try {+ await library.create(newName, newDescription);+ setNewName("");+ setNewDescription("");+ setCreating(false);+ } catch (err) {+ setBanner(err instanceof Error ? err.message : String(err));+ }+ }, [library, newName, newDescription]);++ const beginMetaEdit = useCallback(() => {+ if (!selected) return;+ setMetaName(selected.name);+ setMetaDescription(selected.description ?? "");+ setMetaColor(selected.color ?? SWATCHES[0]);+ setEditingMeta(true);+ }, [selected]);++ const saveMeta = useCallback(async () => {+ if (!selectedId || !metaName.trim()) return;+ try {+ await library.rename(selectedId, {+ name: metaName.trim(),+ description: metaDescription.trim(),+ color: metaColor,+ });+ setEditingMeta(false);+ } catch (err) {+ setBanner(err instanceof Error ? err.message : String(err));+ }+ }, [library, selectedId, metaName, metaDescription, metaColor]);++ const handleDeleteNotebook = useCallback(async () => {+ if (!selected) return;+ const name = selected.name;+ setDeleting(true);+ try {+ await library.remove(selected.id);+ notify(t('Deleted "{{name}}"', { name }), { tone: "success" });+ setConfirmingDelete(false);+ } catch (err) {+ setBanner(err instanceof Error ? err.message : String(err));+ } finally {+ setDeleting(false);+ }+ }, [library, selected, t]);++ const handleExport = useCallback(async () => {+ if (!selected) return;+ try {+ const markdown = await exportNotebookMarkdown(selected.id);+ const blob = new Blob([markdown], {+ type: "text/markdown;charset=utf-8",+ });+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = `${selected.name || selected.id}.md`;+ anchor.click();+ URL.revokeObjectURL(url);+ notify(t("Notebook exported"), { tone: "success" });+ } catch (err) {+ setBanner(err instanceof Error ? err.message : String(err));+ }+ }, [selected, t]);++ const openSession = useCallback(+ (sessionId: string) => {+ router.push(`/?session=${encodeURIComponent(sessionId)}`);+ },+ [router],+ );++ if (library.loading) {+ return (+ <div className="flex h-full items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ );+ }++ return (+ <div className="flex h-full min-h-0 bg-[var(--background)]">+ {/* ── Notebook rail ─────────────────────────────────── */}+ <aside className="flex w-[250px] shrink-0 flex-col border-r border-[var(--border)]">+ <div className="flex flex-col gap-2.5 px-3 pb-2.5 pt-3">+ <Link+ href="/space"+ className="group inline-flex w-fit items-center gap-1.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ <ArrowLeft+ size={13}+ strokeWidth={1.8}+ className="transition-transform group-hover:-translate-x-0.5"+ />+ {t("Learning Space")}+ </Link>++ <div className="flex items-center justify-between">+ <h1 className="flex items-center gap-1.5 font-serif text-[15px] font-semibold tracking-tight text-[var(--foreground)]">+ <NotebookPen size={14} strokeWidth={1.7} />+ {t("Notebooks")}+ <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-normal tabular-nums text-[var(--muted-foreground)]">+ {notebooks.length}+ </span>+ </h1>+ <button+ type="button"+ onClick={() => setCreating((v) => !v)}+ title={t("New notebook")}+ aria-expanded={creating}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <Plus size={15} />+ </button>+ </div>++ {creating && (+ <div className="flex flex-col gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2">+ <input+ autoFocus+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void handleCreate();+ if (e.key === "Escape") setCreating(false);+ }}+ placeholder={t("Notebook name")}+ className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ <input+ value={newDescription}+ onChange={(e) => setNewDescription(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void handleCreate();+ if (e.key === "Escape") setCreating(false);+ }}+ placeholder={t("Description (optional)")}+ className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ <div className="flex gap-1.5">+ <button+ type="button"+ onClick={() => void handleCreate()}+ disabled={!newName.trim()}+ className="flex-1 rounded-md bg-[var(--primary)] px-2 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-40"+ >+ {t("Create")}+ </button>+ <button+ type="button"+ onClick={() => setCreating(false)}+ className="rounded-md border border-[var(--border)] px-2 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ {t("Cancel")}+ </button>+ </div>+ </div>+ )}++ {notebooks.length > 6 && (+ <div className="relative">+ <Search+ size={12}+ className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]"+ />+ <input+ value={notebookQuery}+ onChange={(e) => setNotebookQuery(e.target.value)}+ placeholder={t("Filter notebooks")}+ className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] py-1.5 pl-7 pr-2 text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ </div>+ )}+ </div>++ <nav className="min-h-0 flex-1 overflow-y-auto px-2 pb-3">+ {visibleNotebooks.map((notebook) => {+ const active = selectedId === notebook.id;+ return (+ <button+ key={notebook.id}+ type="button"+ onClick={() => library.select(notebook.id)}+ aria-current={active ? "true" : undefined}+ className={`group/nb relative mb-0.5 flex w-full items-start gap-2 rounded-lg py-2 pl-3 pr-2 text-left transition-[background-color,color] duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40 ${+ active+ ? "bg-[var(--primary)]/10"+ : "hover:bg-[var(--muted)]/50"+ }`}+ >+ {/* A left rail on the active row: the dot alone carries the+ notebook's colour, not its selected state. */}+ <span+ aria-hidden+ className={`absolute left-0 top-1/2 w-[2.5px] -translate-y-1/2 rounded-r-full bg-[var(--primary)] transition-all duration-200 ${+ active ? "h-[62%] opacity-100" : "h-0 opacity-0"+ }`}+ />+ <span+ aria-hidden+ className="mt-1.5 h-2 w-2 shrink-0 rounded-full"+ style={{ backgroundColor: notebook.color || "#6366F1" }}+ />+ <span className="min-w-0 flex-1">+ <span className="flex items-center gap-1.5">+ <span+ className={`min-w-0 flex-1 truncate text-[12.5px] ${active ? "font-semibold text-[var(--foreground)]" : "font-medium text-[var(--foreground)]/85"}`}+ >+ {notebook.name}+ </span>+ {notebook.unreadable ? (+ <AlertTriangle+ size={11}+ className="shrink-0 text-[var(--destructive)]"+ />+ ) : (+ <span className="shrink-0 text-[10.5px] tabular-nums text-[var(--muted-foreground)]">+ {notebook.record_count ?? 0}+ </span>+ )}+ </span>+ {notebook.description && (+ <span className="mt-0.5 block truncate text-[11px] text-[var(--muted-foreground)]">+ {notebook.description}+ </span>+ )}+ </span>+ </button>+ );+ })}++ {!visibleNotebooks.length && (+ <p+ data-test="notebooks-empty"+ className="px-2 py-8 text-center text-[12px] text-[var(--muted-foreground)]"+ >+ {notebooks.length+ ? t("No notebooks match your filter.")+ : t("No notebooks yet.")}+ </p>+ )}+ </nav>+ </aside>++ {/* ── Records ───────────────────────────────────────── */}+ <section className="flex min-w-0 flex-1 flex-col">+ {banner && (+ <div+ role="alert"+ className="flex items-center gap-2 border-b border-[var(--destructive)]/30 bg-[var(--destructive)]/10 px-4 py-2 text-[12px] text-[var(--destructive)]"+ >+ <AlertTriangle size={13} />+ <span className="flex-1">{banner}</span>+ <button type="button" onClick={() => setBanner(null)}>+ <X size={13} />+ </button>+ </div>+ )}++ {library.error ? (+ <ConsoleNotice+ tone="error"+ title={t("Could not load your notebooks")}+ detail={library.error}+ action={+ <button+ type="button"+ onClick={() => void library.reload()}+ className="rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)]"+ >+ {t("Retry")}+ </button>+ }+ />+ ) : !selected && !library.detailLoading ? (+ <ConsoleNotice+ tone="empty"+ title={+ library.detailError+ ? t("This notebook could not be opened")+ : t("No notebook selected")+ }+ detail={+ library.detailError ??+ t("Pick a notebook on the left, or create one to get started.")+ }+ />+ ) : (+ <>+ <header className="flex shrink-0 flex-col gap-2 border-b border-[var(--border)] px-4 py-3">+ {editingMeta ? (+ <div className="flex flex-col gap-2">+ <input+ autoFocus+ value={metaName}+ onChange={(e) => setMetaName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void saveMeta();+ if (e.key === "Escape") setEditingMeta(false);+ }}+ placeholder={t("Notebook name")}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[14px] font-semibold text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ <input+ value={metaDescription}+ onChange={(e) => setMetaDescription(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void saveMeta();+ if (e.key === "Escape") setEditingMeta(false);+ }}+ placeholder={t("Description (optional)")}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ <div className="flex items-center gap-2">+ <div className="flex items-center gap-1">+ {SWATCHES.map((swatch) => (+ <button+ key={swatch}+ type="button"+ onClick={() => setMetaColor(swatch)}+ aria-label={swatch}+ className={`h-4 w-4 rounded-full transition-transform ${metaColor === swatch ? "ring-2 ring-[var(--foreground)]/40 ring-offset-1 ring-offset-[var(--background)]" : "hover:scale-110"}`}+ style={{ backgroundColor: swatch }}+ />+ ))}+ </div>+ <button+ type="button"+ onClick={() => void saveMeta()}+ disabled={!metaName.trim()}+ className="ml-auto inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-40"+ >+ <Check size={12} />+ {t("Save")}+ </button>+ <button+ type="button"+ onClick={() => setEditingMeta(false)}+ className="rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ {t("Cancel")}+ </button>+ </div>+ </div>+ ) : (+ <div className="flex items-center gap-2.5">+ <span+ aria-hidden+ className="h-2.5 w-2.5 shrink-0 rounded-full"+ style={{ backgroundColor: selected?.color || "#6366F1" }}+ />+ <div className="min-w-0 flex-1">+ <h2 className="truncate text-[14.5px] font-semibold tracking-tight text-[var(--foreground)]">+ {selected?.name}+ </h2>+ {selected?.description && (+ <p className="truncate text-[11.5px] text-[var(--muted-foreground)]">+ {selected.description}+ </p>+ )}+ </div>+ <span className="shrink-0 text-[11px] tabular-nums text-[var(--muted-foreground)]">+ {selected?.records.length ?? 0} {t("records")}+ </span>+ <div className="flex shrink-0 items-center gap-0.5">+ <HeaderAction+ label={t("Edit notebook")}+ icon={Pencil}+ onClick={beginMetaEdit}+ />+ <HeaderAction+ label={t("Export as Markdown")}+ icon={Download}+ onClick={() => void handleExport()}+ />+ <HeaderAction+ label={t("Delete notebook")}+ icon={Trash2}+ tone="danger"+ onClick={() => setConfirmingDelete(true)}+ />+ </div>+ </div>+ )}++ {(selected?.records.length ?? 0) > 8 && !editingMeta && (+ <div className="relative">+ <Search+ size={12}+ className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]"+ />+ <input+ value={recordQuery}+ onChange={(e) => setRecordQuery(e.target.value)}+ placeholder={t("Search records in this notebook")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] py-1.5 pl-8 pr-2 text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ </div>+ )}+ </header>++ <div className="min-h-0 flex-1 overflow-y-auto">+ {library.detailLoading ? (+ <div className="flex h-full items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : visibleRecords.length ? (+ <div className="divide-y divide-[var(--border)]/70">+ {visibleRecords.map((record) => (+ <NotebookRecordRow+ key={record.id}+ record={record}+ notebooks={notebooks}+ currentNotebookId={selected!.id}+ expanded={expandedRecordId === record.id}+ onToggle={() =>+ setExpandedRecordId(+ expandedRecordId === record.id ? null : record.id,+ )+ }+ onEdit={library.editRecord}+ onDelete={library.removeRecord}+ onRelocate={library.relocateRecord}+ onOpenSession={openSession}+ />+ ))}+ </div>+ ) : (+ <ConsoleNotice+ tone="empty"+ title={+ recordQuery+ ? t("No records match your search")+ : t("This notebook is empty")+ }+ detail={+ recordQuery+ ? t("Try a different word.")+ : t(+ "Save something to it from a chat, research run, or Co-Writer document.",+ )+ }+ />+ )}+ </div>+ </>+ )}+ </section>++ <ConfirmDialog+ open={confirmingDelete && Boolean(selected)}+ title={t("Delete this notebook?")}+ confirmLabel={t("Delete")}+ tone="danger"+ busy={deleting}+ onConfirm={() => void handleDeleteNotebook()}+ onCancel={() => setConfirmingDelete(false)}+ >+ <p className="text-[13px] leading-relaxed text-[var(--muted-foreground)]">+ {(selected?.record_count ?? 0) > 0+ ? t(+ '"{{name}}" and its {{count}} records will be deleted. This cannot be undone.',+ {+ name: selected?.name ?? "",+ count: selected?.record_count ?? 0,+ },+ )+ : t('"{{name}}" will be deleted.', { name: selected?.name ?? "" })}+ </p>+ </ConfirmDialog>+ </div>+ );+}++function HeaderAction({+ label,+ icon: Icon,+ onClick,+ tone = "default",+}: {+ label: string;+ icon: typeof Pencil;+ onClick: () => void;+ tone?: "default" | "danger";+}) {+ return (+ <Tooltip label={label} side="bottom">+ <button+ type="button"+ onClick={onClick}+ aria-label={label}+ className={`inline-flex h-7 w-7 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-[background-color,color,transform] duration-150 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40 ${+ tone === "danger"+ ? "hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)]"+ : "hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ }`}+ >+ <Icon size={13} />+ </button>+ </Tooltip>+ );+}++function ConsoleNotice({+ tone,+ title,+ detail,+ action,+}: {+ tone: "empty" | "error";+ title: string;+ detail: string;+ action?: React.ReactNode;+}) {+ const Icon = tone === "error" ? AlertTriangle : NotebookPen;+ return (+ <div+ role={tone === "error" ? "alert" : undefined}+ className="flex h-full flex-col items-center justify-center gap-2.5 px-6 py-16 text-center"+ >+ <span+ className={`flex h-9 w-9 items-center justify-center rounded-xl ${+ tone === "error"+ ? "bg-[var(--destructive)]/10 text-[var(--destructive)]"+ : "bg-[var(--muted)] text-[var(--muted-foreground)]"+ }`}+ >+ <Icon size={16} />+ </span>+ <p className="text-[13.5px] font-medium text-[var(--foreground)]">+ {title}+ </p>+ <p className="max-w-sm text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">+ {detail}+ </p>+ {action}+ </div>+ );+}diff --git a/web/components/notebook/NotebookRecordActions.tsx b/web/components/notebook/NotebookRecordActions.tsxnew file mode 100644index 000000000..4b7a556fa--- /dev/null+++ b/web/components/notebook/NotebookRecordActions.tsx@@ -0,0 +1,219 @@+"use client";++import { useEffect, useRef, useState } from "react";+import {+ ArrowLeft,+ Copy,+ CornerUpRight,+ MoreHorizontal,+ Pencil,+ Trash2,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import Tooltip from "@/components/common/Tooltip";+import type { NotebookSummary } from "@/lib/notebook-api";++type Panel = "root" | "move" | "copy";++interface NotebookRecordActionsProps {+ targets: NotebookSummary[];+ disabled?: boolean;+ onEdit: () => void;+ onDelete: () => void;+ onRelocate: (targetNotebookId: string, mode: "move" | "copy") => void;+}++/**+ * The per-record action menu.+ *+ * One always-present trigger rather than a cluster of icons that appears on+ * hover: the row keeps a stable shape, the affordance is discoverable, and+ * every destination fits in one place. Picking a notebook swaps the menu's+ * panel in place instead of opening a nested popover — no second layer to+ * position, and the back arrow keeps the path obvious.+ */+export default function NotebookRecordActions({+ targets,+ disabled = false,+ onEdit,+ onDelete,+ onRelocate,+}: NotebookRecordActionsProps) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const [panel, setPanel] = useState<Panel>("root");+ const containerRef = useRef<HTMLDivElement>(null);++ // Close on outside click and on Escape. A pointerdown listener rather than+ // onBlur: blur fires before the click lands on a menu item, which would+ // cancel the very action the user is choosing.+ // Always reopen on the root panel — a menu that remembers it was left on+ // the destination list would be disorienting next time round.+ const close = () => {+ setOpen(false);+ setPanel("root");+ };++ useEffect(() => {+ if (!open) return;+ const onPointerDown = (event: PointerEvent) => {+ if (!containerRef.current?.contains(event.target as Node)) {+ setOpen(false);+ setPanel("root");+ }+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.stopPropagation();+ setOpen(false);+ setPanel("root");+ }+ };+ document.addEventListener("pointerdown", onPointerDown);+ document.addEventListener("keydown", onKeyDown);+ return () => {+ document.removeEventListener("pointerdown", onPointerDown);+ document.removeEventListener("keydown", onKeyDown);+ };+ }, [open]);++ return (+ <div ref={containerRef} className="relative shrink-0">+ <Tooltip label={t("Record actions")} side="bottom" suppressed={open}>+ <button+ type="button"+ disabled={disabled}+ aria-haspopup="menu"+ aria-expanded={open}+ aria-label={t("Record actions")}+ onClick={() => (open ? close() : setOpen(true))}+ className={`inline-flex h-7 w-7 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-[background-color,color,opacity,transform] duration-150 active:scale-[0.97] hover:bg-[var(--muted)] hover:text-[var(--foreground)] focus-visible:bg-[var(--muted)] focus-visible:text-[var(--foreground)] focus-visible:outline-none disabled:opacity-30 ${+ open+ ? "bg-[var(--muted)] text-[var(--foreground)] opacity-100"+ : "opacity-0 group-hover/row:opacity-100 group-focus-within/row:opacity-100"+ }`}+ >+ <MoreHorizontal size={15} />+ </button>+ </Tooltip>++ {open && (+ <div+ role="menu"+ className="animate-pop-in absolute right-0 top-full z-50 mt-1 w-[min(240px,calc(100vw-32px))] origin-top-right overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--popover)] shadow-lg backdrop-blur-md"+ >+ {panel === "root" ? (+ <div className="p-1">+ <MenuItem+ icon={Pencil}+ label={t("Edit")}+ onClick={() => {+ close();+ onEdit();+ }}+ />+ {targets.length > 0 && (+ <>+ <MenuItem+ icon={CornerUpRight}+ label={t("Move to")}+ hasSubmenu+ onClick={() => setPanel("move")}+ />+ <MenuItem+ icon={Copy}+ label={t("Copy to")}+ hasSubmenu+ onClick={() => setPanel("copy")}+ />+ </>+ )}+ <div className="my-1 h-px bg-[var(--border)]/60" />+ <MenuItem+ icon={Trash2}+ label={t("Delete")}+ tone="danger"+ onClick={() => {+ close();+ onDelete();+ }}+ />+ </div>+ ) : (+ <div className="p-1">+ <button+ type="button"+ onClick={() => setPanel("root")}+ className="mb-0.5 flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/60 hover:text-[var(--foreground)]"+ >+ <ArrowLeft size={12} />+ {panel === "move" ? t("Move to") : t("Copy to")}+ </button>+ <div className="max-h-[220px] overflow-y-auto">+ {targets.map((notebook) => (+ <button+ key={notebook.id}+ type="button"+ role="menuitem"+ onClick={() => {+ close();+ onRelocate(notebook.id, panel === "move" ? "move" : "copy");+ }}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[12.5px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/70"+ >+ <span+ aria-hidden+ className="h-2 w-2 shrink-0 rounded-full"+ style={{ backgroundColor: notebook.color || "#6366F1" }}+ />+ <span className="min-w-0 flex-1 truncate">+ {notebook.name}+ </span>+ <span className="shrink-0 text-[10.5px] tabular-nums text-[var(--muted-foreground)]">+ {notebook.record_count ?? 0}+ </span>+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ );+}++function MenuItem({+ icon: Icon,+ label,+ onClick,+ tone = "default",+ hasSubmenu = false,+}: {+ icon: typeof Pencil;+ label: string;+ onClick: () => void;+ tone?: "default" | "danger";+ hasSubmenu?: boolean;+}) {+ return (+ <button+ type="button"+ role="menuitem"+ onClick={onClick}+ className={`flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left text-[12.5px] transition-colors ${+ tone === "danger"+ ? "text-[var(--destructive)] hover:bg-[var(--destructive)]/10"+ : "text-[var(--foreground)] hover:bg-[var(--muted)]/70"+ }`}+ >+ <Icon size={13} className="shrink-0 opacity-70" />+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {hasSubmenu && (+ <span aria-hidden className="shrink-0 text-[var(--muted-foreground)]">+ ›+ </span>+ )}+ </button>+ );+}diff --git a/web/components/notebook/NotebookRecordRow.tsx b/web/components/notebook/NotebookRecordRow.tsxnew file mode 100644index 000000000..a7d58b04a--- /dev/null+++ b/web/components/notebook/NotebookRecordRow.tsx@@ -0,0 +1,492 @@+"use client";++import dynamic from "next/dynamic";+import { useEffect, useState } from "react";+import {+ Bot,+ ChevronRight,+ ExternalLink,+ MessageSquare,+ NotebookPen,+ Pencil,+ Search,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import { ConfirmDialog } from "@/components/ui/ConfirmDialog";+import NotebookRecordActions from "@/components/notebook/NotebookRecordActions";+import { notify } from "@/lib/notifications";+import type { NotebookRecordItem, NotebookSummary } from "@/lib/notebook-api";++const MarkdownRenderer = dynamic(+ () => import("@/components/common/MarkdownRenderer"),+ { ssr: false },+);++interface NotebookRecordRowProps {+ record: NotebookRecordItem;+ notebooks: NotebookSummary[];+ currentNotebookId: string;+ expanded: boolean;+ onToggle: () => void;+ onEdit: (+ recordId: string,+ changes: { title?: string; summary?: string; output?: string },+ ) => Promise<void>;+ onDelete: (recordId: string) => Promise<void>;+ onRelocate: (+ recordId: string,+ targetNotebookId: string,+ mode: "move" | "copy",+ ) => Promise<void>;+ onOpenSession: (sessionId: string) => void;+}++const BADGES: Record<+ string,+ { labelKey: string; className: string; icon: typeof MessageSquare }+> = {+ chat: {+ labelKey: "Chat",+ className: "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300",+ icon: MessageSquare,+ },+ tutorbot: {+ labelKey: "Partner",+ className:+ "bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300",+ icon: Bot,+ },+ research: {+ labelKey: "Research",+ className:+ "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",+ icon: Search,+ },+ co_writer: {+ labelKey: "Co-Writer",+ className:+ "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",+ icon: Pencil,+ },+};++const FALLBACK_BADGE = {+ className:+ "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400",+ icon: NotebookPen,+};++/** Which confirmation the dialog is currently asking for, if any. */+type Pending = null | "delete" | "discard";++export default function NotebookRecordRow({+ record,+ notebooks,+ currentNotebookId,+ expanded,+ onToggle,+ onEdit,+ onDelete,+ onRelocate,+ onOpenSession,+}: NotebookRecordRowProps) {+ const { t } = useTranslation();+ const [editing, setEditing] = useState(false);+ const [previewing, setPreviewing] = useState(false);+ const [busy, setBusy] = useState(false);+ const [pending, setPending] = useState<Pending>(null);+ const [draftTitle, setDraftTitle] = useState(record.title);+ const [draftSummary, setDraftSummary] = useState(record.summary ?? "");+ const [draftOutput, setDraftOutput] = useState(record.output ?? "");+ const [failure, setFailure] = useState<string | null>(null);++ // Re-seed the draft whenever a different record lands in this row, or the+ // saved values change underneath an idle editor.+ useEffect(() => {+ if (editing) return;+ setDraftTitle(record.title);+ setDraftSummary(record.summary ?? "");+ setDraftOutput(record.output ?? "");+ }, [record.id, record.title, record.summary, record.output, editing]);++ const badge = BADGES[record.type] ?? null;+ const BadgeIcon = badge?.icon ?? FALLBACK_BADGE.icon;+ const partnerName =+ typeof record.metadata?.partner_name === "string"+ ? record.metadata.partner_name.trim()+ : "";+ const badgeLabel = badge+ ? record.type === "tutorbot" && partnerName+ ? partnerName+ : t(badge.labelKey)+ : record.type;++ const sessionId = String(record.metadata?.session_id ?? "");+ const canOpenSession = record.type === "chat" && Boolean(sessionId);+ const moveTargets = notebooks.filter(+ (n) => n.id !== currentNotebookId && !n.unreadable,+ );++ const dirty =+ draftTitle !== record.title ||+ draftSummary !== (record.summary ?? "") ||+ draftOutput !== (record.output ?? "");++ const startEditing = () => {+ setDraftTitle(record.title);+ setDraftSummary(record.summary ?? "");+ setDraftOutput(record.output ?? "");+ setFailure(null);+ setPreviewing(false);+ setEditing(true);+ };++ const leaveEditor = () => {+ setEditing(false);+ setFailure(null);+ setPending(null);+ };++ const requestCancel = () => {+ if (dirty) {+ setPending("discard");+ return;+ }+ leaveEditor();+ };++ const save = async () => {+ if (!draftTitle.trim()) {+ setFailure(t("A record needs a title."));+ return;+ }+ setBusy(true);+ setFailure(null);+ try {+ // Send only what actually changed — the backend treats an omitted+ // field as "leave alone", which is how a rename keeps the record's+ // other values intact.+ const changes: { title?: string; summary?: string; output?: string } = {};+ if (draftTitle !== record.title) changes.title = draftTitle.trim();+ if (draftSummary !== (record.summary ?? ""))+ changes.summary = draftSummary;+ if (draftOutput !== (record.output ?? "")) changes.output = draftOutput;+ if (Object.keys(changes).length) await onEdit(record.id, changes);+ setEditing(false);+ notify(t("Record saved"), { tone: "success" });+ } catch (err) {+ setFailure(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ };++ const runDelete = async () => {+ setBusy(true);+ setPending(null);+ try {+ await onDelete(record.id);+ notify(t("Record deleted"), { tone: "success" });+ } catch (err) {+ setFailure(err instanceof Error ? err.message : String(err));+ setBusy(false);+ }+ };++ const runRelocate = async (targetId: string, mode: "move" | "copy") => {+ const target = notebooks.find((n) => n.id === targetId);+ setBusy(true);+ setFailure(null);+ try {+ await onRelocate(record.id, targetId, mode);+ notify(+ mode === "move"+ ? t('Moved to "{{name}}"', { name: target?.name ?? targetId })+ : t('Copied to "{{name}}"', { name: target?.name ?? targetId }),+ { tone: "success" },+ );+ } catch (err) {+ setFailure(err instanceof Error ? err.message : String(err));+ } finally {+ setBusy(false);+ }+ };++ const timestamp = record.created_at+ ? new Date(record.created_at * 1000).toLocaleString()+ : "";++ return (+ <div+ className={`group/row transition-opacity duration-150 ${busy ? "pointer-events-none opacity-50" : ""}`}+ >+ <div className="flex items-center gap-2.5 px-3 transition-colors duration-150 hover:bg-[var(--muted)]/40">+ <button+ type="button"+ onClick={onToggle}+ className="flex min-w-0 flex-1 items-center gap-2.5 py-2.5 text-left focus-visible:outline-none"+ aria-expanded={expanded}+ >+ <ChevronRight+ size={13}+ className={`shrink-0 text-[var(--muted-foreground)] transition-transform duration-200 ${expanded ? "rotate-90" : ""}`}+ />+ <span+ className={`inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium ${badge?.className ?? FALLBACK_BADGE.className}`}+ >+ <BadgeIcon size={10} />+ {badgeLabel}+ </span>+ <span className="min-w-0 flex-1 truncate text-[13px] font-medium text-[var(--foreground)]">+ {record.title}+ </span>+ </button>++ {/* The timestamp holds its place whether or not the row is hovered —+ swapping it out for the action button made rows twitch. */}+ <span className="shrink-0 text-[11px] tabular-nums text-[var(--muted-foreground)]">+ {timestamp}+ </span>++ <NotebookRecordActions+ targets={moveTargets}+ disabled={busy}+ onEdit={() => {+ if (!expanded) onToggle();+ startEditing();+ }}+ onDelete={() => setPending("delete")}+ onRelocate={(targetId, mode) => void runRelocate(targetId, mode)}+ />+ </div>++ {expanded && (+ <div className="animate-pop-in px-3 pb-4 pl-9">+ {failure && (+ <p+ role="alert"+ className="mb-2.5 rounded-lg bg-[var(--destructive)]/10 px-3 py-2 text-[12px] text-[var(--destructive)]"+ >+ {failure}+ </p>+ )}++ {editing ? (+ <RecordEditor+ title={draftTitle}+ summary={draftSummary}+ output={draftOutput}+ previewing={previewing}+ busy={busy}+ dirty={dirty}+ onTitleChange={setDraftTitle}+ onSummaryChange={setDraftSummary}+ onOutputChange={setDraftOutput}+ onTogglePreview={() => setPreviewing((v) => !v)}+ onSave={() => void save()}+ onCancel={requestCancel}+ />+ ) : (+ <>+ {record.summary && (+ <p className="mb-2.5 text-[12.5px] leading-6 text-[var(--foreground)]/80">+ {record.summary}+ </p>+ )}+ {record.type !== "chat" && record.user_query && (+ <p className="mb-2.5 text-[12px] text-[var(--muted-foreground)]">+ <span className="font-medium">{t("Query:")}</span>{" "}+ {record.user_query}+ </p>+ )}+ {canOpenSession && (+ <button+ type="button"+ onClick={() => onOpenSession(sessionId)}+ className="mb-2.5 inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[11.5px] font-medium text-[var(--foreground)] transition-[background-color,border-color,color,transform] duration-150 active:scale-[0.98] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"+ >+ <ExternalLink size={12} />+ {t("Open chat session")}+ </button>+ )}+ <div className="max-h-[420px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--muted)]/25 px-3 py-2.5">+ <MarkdownRenderer+ content={record.output || ""}+ variant="prose"+ className="text-[12.5px] leading-relaxed text-[var(--foreground)]"+ />+ </div>+ </>+ )}+ </div>+ )}++ <ConfirmDialog+ open={pending === "delete"}+ title={t("Delete this record?")}+ confirmLabel={t("Delete")}+ tone="danger"+ busy={busy}+ onConfirm={() => void runDelete()}+ onCancel={() => setPending(null)}+ >+ <p className="text-[13px] leading-relaxed text-[var(--muted-foreground)]">+ {t('"{{title}}" will be removed from this notebook.', {+ title: record.title,+ })}+ </p>+ </ConfirmDialog>++ <ConfirmDialog+ open={pending === "discard"}+ title={t("Discard your changes?")}+ confirmLabel={t("Discard")}+ tone="danger"+ onConfirm={leaveEditor}+ onCancel={() => setPending(null)}+ >+ <p className="text-[13px] leading-relaxed text-[var(--muted-foreground)]">+ {t("Your edits to this record have not been saved yet.")}+ </p>+ </ConfirmDialog>+ </div>+ );+}++/**+ * The record editor.+ *+ * Fields read as one continuous document — title, then summary, then body —+ * rather than three boxed inputs, so editing feels like working on the+ * record instead of filling a form.+ */+function RecordEditor({+ title,+ summary,+ output,+ previewing,+ busy,+ dirty,+ onTitleChange,+ onSummaryChange,+ onOutputChange,+ onTogglePreview,+ onSave,+ onCancel,+}: {+ title: string;+ summary: string;+ output: string;+ previewing: boolean;+ busy: boolean;+ dirty: boolean;+ onTitleChange: (value: string) => void;+ onSummaryChange: (value: string) => void;+ onOutputChange: (value: string) => void;+ onTogglePreview: () => void;+ onSave: () => void;+ onCancel: () => void;+}) {+ const { t } = useTranslation();++ return (+ <div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)]">+ <div className="flex flex-col gap-1 border-b border-[var(--border)]/70 px-3 py-2.5">+ <input+ autoFocus+ value={title}+ onChange={(e) => onTitleChange(e.target.value)}+ placeholder={t("Record title")}+ aria-label={t("Record title")}+ className="w-full border-0 bg-transparent p-0 text-[13.5px] font-semibold text-[var(--foreground)] outline-none placeholder:font-normal placeholder:text-[var(--muted-foreground)]"+ />+ <textarea+ value={summary}+ onChange={(e) => onSummaryChange(e.target.value)}+ placeholder={t("Short summary")}+ aria-label={t("Short summary")}+ rows={2}+ className="w-full resize-none border-0 bg-transparent p-0 text-[12.5px] leading-6 text-[var(--foreground)]/80 outline-none placeholder:text-[var(--muted-foreground)]"+ />+ </div>++ <div className="flex items-center justify-between border-b border-[var(--border)]/70 bg-[var(--muted)]/25 px-3 py-1.5">+ <span className="text-[10.5px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Body")}+ </span>+ {/* A segmented switch rather than a toggling button: both states stay+ visible, so it never reads as "what am I looking at now?". */}+ <div+ role="tablist"+ aria-label={t("Body")}+ className="flex items-center gap-0.5 rounded-lg bg-[var(--muted)]/70 p-0.5"+ >+ {[+ { key: "write", label: t("Write"), active: !previewing },+ { key: "preview", label: t("Preview"), active: previewing },+ ].map((tab) => (+ <button+ key={tab.key}+ type="button"+ role="tab"+ aria-selected={tab.active}+ onClick={() => {+ if (!tab.active) onTogglePreview();+ }}+ className={`rounded-md px-2 py-0.5 text-[11px] font-medium transition-[background-color,color] duration-150 ${+ tab.active+ ? "bg-[var(--background)] text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {tab.label}+ </button>+ ))}+ </div>+ </div>++ {previewing ? (+ <div className="max-h-[380px] min-h-[180px] overflow-y-auto px-3 py-2.5">+ <MarkdownRenderer+ content={output || t("Nothing to preview yet.")}+ variant="prose"+ className="text-[12.5px] leading-relaxed text-[var(--foreground)]"+ />+ </div>+ ) : (+ <textarea+ value={output}+ onChange={(e) => onOutputChange(e.target.value)}+ rows={14}+ spellCheck={false}+ aria-label={t("Body")}+ className="max-h-[380px] min-h-[180px] w-full resize-y border-0 bg-transparent px-3 py-2.5 font-mono text-[12px] leading-relaxed text-[var(--foreground)] outline-none"+ />+ )}++ <div className="flex items-center justify-end gap-2 border-t border-[var(--border)]/70 px-3 py-2">+ {dirty && (+ <span className="mr-auto text-[11px] text-[var(--muted-foreground)]">+ {t("Unsaved changes")}+ </span>+ )}+ <button+ type="button"+ onClick={onCancel}+ disabled={busy}+ className="rounded-lg px-2.5 py-1.5 text-[12.5px] text-[var(--muted-foreground)] transition-colors duration-150 hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={onSave}+ disabled={busy || !dirty}+ className="rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] transition-[opacity,transform] duration-150 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {t("Save")}+ </button>+ </div>+ </div>+ );+}diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsxindex c1861ff2a..708534322 100644--- a/web/components/notebook/SaveToNotebookModal.tsx+++ b/web/components/notebook/SaveToNotebookModal.tsx@@ -6,6 +6,7 @@ import {Loader2,MessageSquare,NotebookPen,+ Plus,Sparkles,User,} from "lucide-react";@@ -14,6 +15,7 @@ import PickerShell from "@/components/common/PickerShell";import PickerHeader from "@/components/common/PickerHeader";import { apiFetch, apiUrl } from "@/lib/api";import {+ createNotebook,listNotebooks,type NotebookSummary as RealNotebookSummary,} from "@/lib/notebook-api";@@ -162,6 +164,10 @@ export default function SaveToNotebookModal({const [selectedMessageIdx, setSelectedMessageIdx] = useState<Set<number>>(new Set(),);+ // Creating a notebook without leaving the dialog: having to go find the+ // Notebooks page mid-save was the single most-reported friction here.+ const [newNotebookName, setNewNotebookName] = useState("");+ const [isCreatingNotebook, setIsCreatingNotebook] = useState(false);const abortRef = useRef<AbortController | null>(null);const hasMessageSelection = Array.isArray(messages) && messages.length > 0;@@ -175,6 +181,7 @@ export default function SaveToNotebookModal({setError("");setSelectedIds([]);setTitleEdited(false);+ setNewNotebookName("");if (hasMessageSelection && messages) {setSelectedMessageIdx(new Set(messages.map((_, idx) => idx)));setTitle(deriveTitle(messages, payload?.title || ""));@@ -186,7 +193,9 @@ export default function SaveToNotebookModal({void (async () => {try {const list = await listNotebooks();- setNotebooks(list);+ // Damaged notebooks cannot accept a record — the backend skips them+ // — so they are not offered as a destination.+ setNotebooks(list.filter((notebook) => !notebook.unreadable));} catch {setNotebooks([]);} finally {@@ -195,6 +204,24 @@ export default function SaveToNotebookModal({})();}, [open, payload, messages, hasMessageSelection]);+ const handleCreateNotebook = async () => {+ const name = newNotebookName.trim();+ if (!name || isCreatingNotebook) return;+ setIsCreatingNotebook(true);+ setError("");+ try {+ const created = await createNotebook({ name });+ setNotebooks((prev) => [created, ...prev]);+ // Pre-select it: the user made this notebook in order to save here.+ setSelectedIds([created.id]);+ setNewNotebookName("");+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setIsCreatingNotebook(false);+ }+ };+const orderedSelectedMessages = useMemo<NotebookSaveMessage[]>(() => {if (!hasMessageSelection || !messages) return [];const indexes = Array.from(selectedMessageIdx).sort((a, b) => a - b);@@ -350,11 +377,32 @@ export default function SaveToNotebookModal({String(event.payload.detail || t("Failed to save to notebook.")),);} else if (type === "result") {+ // The backend skips notebooks it cannot write to and still+ // returns a record, so success has to be judged by which+ // notebooks actually accepted it — not by the response arriving.+ const accepted = Array.isArray(event.payload.added_to_notebooks)+ ? (event.payload.added_to_notebooks as string[])+ : [];+ const rejected = selectedIds.filter((id) => !accepted.includes(id));+ if (!accepted.length) {+ throw new Error(+ t(+ "No notebook accepted this save. Their files may be missing or damaged.",+ ),+ );+ }const summary = String(event.payload.summary || finalSummary);setSummaryPreview(summary);+ if (rejected.length) {+ // Partial success: the save happened, but say what missed.+ const names = rejected+ .map((id) => notebooks.find((n) => n.id === id)?.name ?? id)+ .join("、");+ setError(t("Could not save to: {{names}}", { names }));+ }onSaved?.({ summary });setIsLoading(false);- onClose();+ if (!rejected.length) onClose();return;}}@@ -539,12 +587,35 @@ export default function SaveToNotebookModal({<Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" /></div>) : notebooks.length === 0 ? (- <div className="flex flex-col items-center gap-2 px-3 py-6 text-center text-sm text-[var(--muted-foreground)]">+ <div className="flex flex-col items-center gap-2.5 px-3 py-6 text-center text-sm text-[var(--muted-foreground)]"><NotebookPen className="h-5 w-5 text-[var(--muted-foreground)]/60" />- <span>{t("No notebooks found.")}</span>- <span className="text-[11px] text-[var(--muted-foreground)]/80">- {t("Create one from the Knowledge → Notebooks page.")}- </span>+ <span>{t("No notebooks yet.")}</span>+ <div className="flex w-full max-w-xs items-center gap-1.5">+ <input+ value={newNotebookName}+ onChange={(event) =>+ setNewNotebookName(event.target.value)+ }+ onKeyDown={(event) => {+ if (event.key === "Enter") void handleCreateNotebook();+ }}+ placeholder={t("Name your first notebook")}+ className="flex-1 rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ <button+ type="button"+ onClick={() => void handleCreateNotebook()}+ disabled={!newNotebookName.trim() || isCreatingNotebook}+ className="inline-flex items-center gap-1 rounded-lg bg-[var(--primary)] px-2.5 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] disabled:opacity-40"+ >+ {isCreatingNotebook ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Plus className="h-3.5 w-3.5" />+ )}+ {t("Create")}+ </button>+ </div></div>) : (notebooks.map((notebook) => {diff --git a/web/components/notebook/useNotebookLibrary.ts b/web/components/notebook/useNotebookLibrary.tsnew file mode 100644index 000000000..923345e86--- /dev/null+++ b/web/components/notebook/useNotebookLibrary.ts@@ -0,0 +1,284 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ createNotebook,+ deleteNotebook,+ deleteNotebookRecord,+ getNotebook,+ listNotebooks,+ relocateNotebookRecord,+ updateNotebook,+ updateNotebookRecord,+ type NotebookRecordItem,+ type NotebookSummary,+} from "@/lib/notebook-api";++/**+ * Every notebook read/write the console needs, in one place.+ *+ * The UI components below stay presentational: they render what this hook+ * exposes and call back into it. Mutations update local state optimistically+ * where the server response is predictable (rename, delete) and re-fetch+ * where it is not (create, move), so the list never shows a stale count.+ */++export interface NotebookLibrary {+ notebooks: NotebookSummary[];+ selectedId: string | null;+ selected: NotebookDetailState | null;+ loading: boolean;+ detailLoading: boolean;+ error: string | null;+ detailError: string | null;+ select: (notebookId: string) => void;+ reload: () => Promise<void>;+ create: (name: string, description: string) => Promise<string | null>;+ rename: (+ notebookId: string,+ changes: { name?: string; description?: string; color?: string },+ ) => Promise<void>;+ remove: (notebookId: string) => Promise<void>;+ editRecord: (+ recordId: string,+ changes: { title?: string; summary?: string; output?: string },+ ) => Promise<void>;+ removeRecord: (recordId: string) => Promise<void>;+ relocateRecord: (+ recordId: string,+ targetNotebookId: string,+ mode: "move" | "copy",+ ) => Promise<void>;+}++export interface NotebookDetailState extends NotebookSummary {+ records: NotebookRecordItem[];+}++function messageOf(error: unknown): string {+ if (error instanceof Error) return error.message;+ return String(error);+}++export function useNotebookLibrary(initialId?: string | null): NotebookLibrary {+ const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);+ const [selectedId, setSelectedId] = useState<string | null>(+ initialId ?? null,+ );+ const [selected, setSelected] = useState<NotebookDetailState | null>(null);+ const [loading, setLoading] = useState(true);+ const [detailLoading, setDetailLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [detailError, setDetailError] = useState<string | null>(null);++ // Detail fetches are racy — clicking through the list fires several. Only+ // the newest one is allowed to write state, otherwise a slow earlier+ // response can overwrite the notebook the user is actually looking at.+ const detailRequestRef = useRef(0);++ const loadDetail = useCallback(async (notebookId: string) => {+ const requestId = ++detailRequestRef.current;+ setDetailLoading(true);+ setDetailError(null);+ try {+ const data = await getNotebook(notebookId);+ if (detailRequestRef.current !== requestId) return;+ setSelected({ ...data, records: data.records ?? [] });+ } catch (err) {+ if (detailRequestRef.current !== requestId) return;+ setSelected(null);+ setDetailError(messageOf(err));+ } finally {+ if (detailRequestRef.current === requestId) setDetailLoading(false);+ }+ }, []);++ const reload = useCallback(async () => {+ setError(null);+ try {+ const next = await listNotebooks();+ setNotebooks(next);+ setSelectedId((current) => {+ if (current && next.some((n) => n.id === current)) return current;+ return next.length ? next[0].id : null;+ });+ } catch (err) {+ setError(messageOf(err));+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void reload();+ }, [reload]);++ useEffect(() => {+ if (!selectedId) {+ setSelected(null);+ return;+ }+ void loadDetail(selectedId);+ }, [selectedId, loadDetail]);++ const select = useCallback((notebookId: string) => {+ setSelectedId(notebookId);+ }, []);++ const create = useCallback(+ async (name: string, description: string) => {+ const trimmed = name.trim();+ if (!trimmed) return null;+ const created = await createNotebook({+ name: trimmed,+ description: description.trim(),+ });+ await reload();+ setSelectedId(created.id);+ return created.id;+ },+ [reload],+ );++ const rename = useCallback(+ async (+ notebookId: string,+ changes: { name?: string; description?: string; color?: string },+ ) => {+ const updated = await updateNotebook(notebookId, changes);+ setNotebooks((prev) =>+ prev.map((n) => (n.id === notebookId ? { ...n, ...updated } : n)),+ );+ setSelected((prev) =>+ prev && prev.id === notebookId ? { ...prev, ...updated } : prev,+ );+ },+ [],+ );++ const remove = useCallback(+ async (notebookId: string) => {+ await deleteNotebook(notebookId);+ setNotebooks((prev) => prev.filter((n) => n.id !== notebookId));+ setSelectedId((current) => {+ if (current !== notebookId) return current;+ const rest = notebooks.filter((n) => n.id !== notebookId);+ return rest.length ? rest[0].id : null;+ });+ },+ [notebooks],+ );++ // Keep the sidebar's record count honest after any record-level change+ // without paying for a full list refetch.+ const adjustCount = useCallback((notebookId: string, delta: number) => {+ setNotebooks((prev) =>+ prev.map((n) =>+ n.id === notebookId+ ? { ...n, record_count: Math.max(0, (n.record_count ?? 0) + delta) }+ : n,+ ),+ );+ }, []);++ const editRecord = useCallback(+ async (+ recordId: string,+ changes: { title?: string; summary?: string; output?: string },+ ) => {+ if (!selectedId) return;+ const updated = await updateNotebookRecord(selectedId, recordId, changes);+ setSelected((prev) =>+ prev+ ? {+ ...prev,+ records: prev.records.map((r) =>+ r.id === recordId ? { ...r, ...updated } : r,+ ),+ }+ : prev,+ );+ },+ [selectedId],+ );++ const removeRecord = useCallback(+ async (recordId: string) => {+ if (!selectedId) return;+ await deleteNotebookRecord(selectedId, recordId);+ setSelected((prev) =>+ prev+ ? { ...prev, records: prev.records.filter((r) => r.id !== recordId) }+ : prev,+ );+ adjustCount(selectedId, -1);+ },+ [selectedId, adjustCount],+ );++ const relocateRecord = useCallback(+ async (+ recordId: string,+ targetNotebookId: string,+ mode: "move" | "copy",+ ) => {+ if (!selectedId) return;+ await relocateNotebookRecord(+ selectedId,+ recordId,+ targetNotebookId,+ mode,+ );+ if (mode === "move") {+ setSelected((prev) =>+ prev+ ? {+ ...prev,+ records: prev.records.filter((r) => r.id !== recordId),+ }+ : prev,+ );+ adjustCount(selectedId, -1);+ }+ adjustCount(targetNotebookId, 1);+ },+ [selectedId, adjustCount],+ );++ return useMemo(+ () => ({+ notebooks,+ selectedId,+ selected,+ loading,+ detailLoading,+ error,+ detailError,+ select,+ reload,+ create,+ rename,+ remove,+ editRecord,+ removeRecord,+ relocateRecord,+ }),+ [+ notebooks,+ selectedId,+ selected,+ loading,+ detailLoading,+ error,+ detailError,+ select,+ reload,+ create,+ rename,+ remove,+ editRecord,+ removeRecord,+ relocateRecord,+ ],+ );+}diff --git a/web/components/reading/AnnotationLayer.tsx b/web/components/reading/AnnotationLayer.tsxnew file mode 100644index 000000000..85970d269--- /dev/null+++ b/web/components/reading/AnnotationLayer.tsx@@ -0,0 +1,106 @@+"use client";++import type { AnnotationItem, NormalisedRect } from "@/lib/reading-api";++/** Ink for each palette colour, tuned to stay readable over black-on-white text. */+const COLOR_INK: Record<string, string> = {+ yellow: "250 220 90",+ green: "140 219 148",+ blue: "122 192 250",+ pink: "250 161 199",+ purple: "199 174 250",+};++function ink(color: string): string {+ return COLOR_INK[color] ?? COLOR_INK.yellow;+}++export interface AnnotationLayerProps {+ annotations: AnnotationItem[];+ highlightedAnnotationId?: string | null;+ flashRects?: NormalisedRect[];+ onAnnotationClick?: (annotation: AnnotationItem) => void;+}++/**+ * Overlay that paints stored marks over one rendered unit.+ *+ * Positioned entirely in percentages from the annotation's normalised rects, so+ * it needs no measurement and stays correct through zoom and pane resizing.+ *+ * `multiply` blending is what makes a highlight look like a highlighter rather+ * than a coloured box on top of the words: the text below stays fully legible+ * instead of being tinted.+ *+ * The layer itself is click-through (`pointer-events-none`); only the marks take+ * clicks, so highlighting never blocks text selection on the layer beneath.+ */+export function AnnotationLayer({+ annotations,+ highlightedAnnotationId,+ flashRects,+ onAnnotationClick,+}: AnnotationLayerProps) {+ return (+ <div className="pointer-events-none absolute inset-0">+ {annotations.map((annotation) =>+ annotation.rects.map((rect, index) => {+ const [x0, y0, x1, y1] = rect;+ const isFocused = annotation.annotation_id === highlightedAnnotationId;+ const isUnderline = annotation.kind === "underline";+ return (+ <button+ key={`${annotation.annotation_id}-${index}`}+ type="button"+ title={annotation.note || annotation.quote || undefined}+ onClick={() => onAnnotationClick?.(annotation)}+ className={[+ "pointer-events-auto absolute cursor-pointer transition-[box-shadow,filter] duration-150",+ isUnderline ? "" : "mix-blend-multiply",+ isFocused ? "ring-2 ring-[var(--ring)] ring-offset-1" : "",+ ]+ .filter(Boolean)+ .join(" ")}+ style={{+ left: `${x0 * 100}%`,+ top: `${y0 * 100}%`,+ width: `${Math.max(0, x1 - x0) * 100}%`,+ height: `${Math.max(0, y1 - y0) * 100}%`,+ background: isUnderline+ ? undefined+ : `rgb(${ink(annotation.color)} / ${isFocused ? 0.85 : 0.6})`,+ borderBottom: isUnderline+ ? `2px solid rgb(${ink(annotation.color)})`+ : undefined,+ borderRadius: isUnderline ? 0 : 2,+ }}+ >+ {annotation.author === "assistant" && index === 0 && (+ <span+ aria-hidden+ className="absolute -top-1 -right-1 h-1.5 w-1.5 rounded-full bg-[var(--primary)] shadow-sm"+ />+ )}+ </button>+ );+ }),+ )}+ {(flashRects ?? []).map((rect, index) => {+ const [x0, y0, x1, y1] = rect;+ return (+ <span+ key={`flash-${index}`}+ aria-hidden+ className="dt-reader-flash absolute rounded-[2px]"+ style={{+ left: `${x0 * 100}%`,+ top: `${y0 * 100}%`,+ width: `${Math.max(0, x1 - x0) * 100}%`,+ height: `${Math.max(0, y1 - y0) * 100}%`,+ }}+ />+ );+ })}+ </div>+ );+}diff --git a/web/components/reading/AnnotationList.tsx b/web/components/reading/AnnotationList.tsxnew file mode 100644index 000000000..639000dcf--- /dev/null+++ b/web/components/reading/AnnotationList.tsx@@ -0,0 +1,139 @@+"use client";++import { useMemo } from "react";+import { Bot, Sparkles, Trash2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { AnnotationItem, UnitKind } from "@/lib/reading-api";+import { unitLabel } from "./TextUnitView";++const SWATCH: Record<string, string> = {+ yellow: "#facd5a",+ green: "#8cdb94",+ blue: "#7ac0fa",+ pink: "#faa1c7",+ purple: "#c7aefa",+};++export interface AnnotationListProps {+ annotations: AnnotationItem[];+ unit: UnitKind;+ activeId: string | null;+ onSelect: (annotation: AnnotationItem) => void;+ onDelete: (annotation: AnnotationItem) => void;+}++/**+ * The marks made on this material, grouped by locator.+ *+ * Grouped rather than flat because a reader thinks in "what did I mark on page+ * 12", and because it makes the assistant's own marks legible in context next to+ * the user's own.+ */+export function AnnotationList({+ annotations,+ unit,+ activeId,+ onSelect,+ onDelete,+}: AnnotationListProps) {+ const { t } = useTranslation();++ const groups = useMemo(() => {+ const byLocator = new Map<number, AnnotationItem[]>();+ for (const annotation of annotations) {+ const bucket = byLocator.get(annotation.locator) ?? [];+ bucket.push(annotation);+ byLocator.set(annotation.locator, bucket);+ }+ return [...byLocator.entries()].sort((a, b) => a[0] - b[0]);+ }, [annotations]);++ if (!annotations.length) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">+ <Sparkles size={18} className="text-[var(--muted-foreground)]/60" />+ <p className="text-[12px] font-medium text-[var(--foreground)]">+ {t("No annotations yet")}+ </p>+ <p className="max-w-[220px] text-[11px] leading-relaxed text-[var(--muted-foreground)]">+ {t("Select text in the document to highlight it or attach a note.")}+ </p>+ </div>+ );+ }++ return (+ <div className="dt-reader-scroll h-full overflow-y-auto px-2.5 py-2">+ {groups.map(([locator, rows]) => (+ <section key={locator} className="mb-3 last:mb-1">+ <h4 className="sticky top-0 z-10 mb-1 bg-[var(--background)]/95 px-1 py-1 font-mono text-[10px] uppercase tracking-[0.06em] text-[var(--muted-foreground)] backdrop-blur">+ {t(unitLabel(unit))} {locator}+ </h4>+ <ul className="space-y-1">+ {rows.map((annotation) => (+ <li key={annotation.annotation_id}>+ <div+ role="button"+ tabIndex={0}+ onClick={() => onSelect(annotation)}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onSelect(annotation);+ }+ }}+ className={`group/anno relative w-full cursor-pointer rounded-lg border px-2.5 py-2 text-left transition ${+ annotation.annotation_id === activeId+ ? "border-[var(--ring)] bg-[var(--muted)]/60"+ : "border-transparent hover:border-[var(--border)] hover:bg-[var(--muted)]/40"+ }`}+ >+ <span+ aria-hidden+ className="absolute left-0 top-2 bottom-2 w-[3px] rounded-full"+ style={{ background: SWATCH[annotation.color] ?? SWATCH.yellow }}+ />+ {annotation.quote && (+ <p className="line-clamp-3 pl-1.5 text-[12px] leading-[1.55] text-[var(--foreground)]">+ {annotation.quote}+ </p>+ )}+ {annotation.note && (+ <p className="mt-1 line-clamp-3 pl-1.5 text-[11px] leading-[1.5] text-[var(--muted-foreground)]">+ {annotation.note}+ </p>+ )}+ <div className="mt-1 flex items-center gap-1.5 pl-1.5">+ {annotation.author === "assistant" && (+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/10 px-1.5 py-[1px] text-[10px] font-medium text-[var(--primary)]">+ <Bot size={9} />+ {t("AI")}+ </span>+ )}+ {annotation.kind === "underline" && (+ <span className="text-[10px] text-[var(--muted-foreground)]">+ {t("Underline")}+ </span>+ )}+ </div>+ <button+ type="button"+ title={t("Delete annotation")}+ aria-label={t("Delete annotation")}+ onClick={(event) => {+ event.stopPropagation();+ onDelete(annotation);+ }}+ className="absolute right-1.5 top-1.5 inline-flex h-6 w-6 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-0 transition hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] focus-visible:opacity-100 group-hover/anno:opacity-100"+ >+ <Trash2 size={12} />+ </button>+ </div>+ </li>+ ))}+ </ul>+ </section>+ ))}+ </div>+ );+}diff --git a/web/components/reading/AnnotationPopover.tsx b/web/components/reading/AnnotationPopover.tsxnew file mode 100644index 000000000..21af37f5b--- /dev/null+++ b/web/components/reading/AnnotationPopover.tsx@@ -0,0 +1,223 @@+"use client";++import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { Highlighter, MessageSquareQuote, StickyNote, Underline } from "lucide-react";+import { useTranslation } from "react-i18next";+import { ANNOTATION_COLORS, type AnnotationColor } from "@/lib/reading-api";++const SWATCH: Record<AnnotationColor, string> = {+ yellow: "#facd5a",+ green: "#8cdb94",+ blue: "#7ac0fa",+ pink: "#faa1c7",+ purple: "#c7aefa",+};++export interface AnnotationPopoverProps {+ /** Viewport coordinates of the selection's end. */+ anchor: { x: number; y: number };+ quote: string;+ onHighlight: (color: AnnotationColor) => void;+ onUnderline: (color: AnnotationColor) => void;+ onNote: (note: string, color: AnnotationColor) => void;+ onAsk: () => void;+ onDismiss: () => void;+}++/**+ * Toolbar that appears over a selection.+ *+ * Positioned in fixed coordinates and then clamped to the window after mount, so+ * a selection near the top or right edge still shows the whole toolbar instead of+ * being cut off — the failure people actually hit, since the interesting text is+ * often at the top of a page.+ *+ * Dismissal is on Escape and on pointerdown outside. Deliberately not on blur:+ * clicking a colour swatch blurs the toolbar, and a blur-based dismissal would+ * race the click and eat every second annotation.+ */+export function AnnotationPopover({+ anchor,+ quote,+ onHighlight,+ onUnderline,+ onNote,+ onAsk,+ onDismiss,+}: AnnotationPopoverProps) {+ const { t } = useTranslation();+ const ref = useRef<HTMLDivElement | null>(null);+ const [color, setColor] = useState<AnnotationColor>("yellow");+ const [noteOpen, setNoteOpen] = useState(false);+ const [note, setNote] = useState("");+ const [position, setPosition] = useState({ left: anchor.x, top: anchor.y });++ useLayoutEffect(() => {+ const element = ref.current;+ if (!element) return;+ const box = element.getBoundingClientRect();+ const margin = 10;+ // Prefer above the selection; flip below when there is no room up there.+ let top = anchor.y - box.height - margin;+ if (top < margin) top = anchor.y + 24;+ const left = Math.min(+ Math.max(margin, anchor.x - box.width / 2),+ window.innerWidth - box.width - margin,+ );+ setPosition({ left, top: Math.min(top, window.innerHeight - box.height - margin) });+ }, [anchor.x, anchor.y, noteOpen]);++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.stopPropagation();+ onDismiss();+ }+ };+ const onPointerDown = (event: PointerEvent) => {+ if (!ref.current?.contains(event.target as Node)) onDismiss();+ };+ document.addEventListener("keydown", onKey);+ // Capture phase: the reader's own mouseup handler would otherwise clear the+ // selection before this listener ran.+ document.addEventListener("pointerdown", onPointerDown, true);+ return () => {+ document.removeEventListener("keydown", onKey);+ document.removeEventListener("pointerdown", onPointerDown, true);+ };+ }, [onDismiss]);++ return (+ <div+ ref={ref}+ role="dialog"+ aria-label={t("Annotate selection")}+ style={{ left: position.left, top: position.top }}+ className="dt-reader-popover fixed z-[70] w-max max-w-[min(360px,92vw)] rounded-xl border border-[var(--border)] bg-[var(--popover)] p-1.5 shadow-[0_10px_30px_-12px_rgba(0,0,0,0.35)]"+ >+ <div className="flex items-center gap-1">+ <div className="flex items-center gap-0.5 pr-1">+ {ANNOTATION_COLORS.map((swatch) => (+ <button+ key={swatch}+ type="button"+ title={t(swatchLabel(swatch))}+ aria-label={t(swatchLabel(swatch))}+ aria-pressed={color === swatch}+ onClick={() => setColor(swatch)}+ className={`h-5 w-5 rounded-full border transition ${+ color === swatch+ ? "border-[var(--foreground)] scale-110"+ : "border-black/10 hover:scale-105"+ }`}+ style={{ background: SWATCH[swatch] }}+ />+ ))}+ </div>+ <span className="h-5 w-px bg-[var(--border)]" aria-hidden />+ <IconButton+ icon={Highlighter}+ label={t("Highlight")}+ onClick={() => onHighlight(color)}+ />+ <IconButton+ icon={Underline}+ label={t("Underline")}+ onClick={() => onUnderline(color)}+ />+ <IconButton+ icon={StickyNote}+ label={t("Add note")}+ active={noteOpen}+ onClick={() => setNoteOpen((open) => !open)}+ />+ <IconButton+ icon={MessageSquareQuote}+ label={t("Ask about this")}+ onClick={onAsk}+ />+ </div>++ {noteOpen && (+ <div className="mt-1.5 border-t border-[var(--border)] pt-1.5">+ <p className="mb-1 line-clamp-2 px-1 text-[11px] italic text-[var(--muted-foreground)]">+ “{quote}”+ </p>+ <textarea+ autoFocus+ value={note}+ onChange={(event) => setNote(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ onNote(note, color);+ }+ }}+ rows={3}+ placeholder={t("Your note…")}+ className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-[12px] leading-relaxed text-[var(--foreground)] outline-none transition focus:border-[var(--ring)] focus:ring-2 focus:ring-[var(--ring)]/20"+ />+ <div className="mt-1 flex items-center justify-end gap-1.5">+ <button+ type="button"+ onClick={onDismiss}+ className="rounded-lg px-2 py-1 text-[11px] text-[var(--muted-foreground)] transition hover:bg-[var(--muted)]"+ >+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={() => onNote(note, color)}+ className="rounded-lg bg-[var(--primary)] px-2.5 py-1 text-[11px] font-medium text-[var(--primary-foreground)] transition hover:opacity-90"+ >+ {t("Save note")}+ </button>+ </div>+ </div>+ )}+ </div>+ );+}++function IconButton({+ icon: Icon,+ label,+ onClick,+ active,+}: {+ icon: typeof Highlighter;+ label: string;+ onClick: () => void;+ active?: boolean;+}) {+ return (+ <button+ type="button"+ title={label}+ aria-label={label}+ onClick={onClick}+ className={`inline-flex h-7 w-7 items-center justify-center rounded-lg transition ${+ active+ ? "bg-[var(--muted)] text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ }`}+ >+ <Icon size={14} />+ </button>+ );+}++function swatchLabel(color: AnnotationColor): string {+ switch (color) {+ case "green":+ return "Green";+ case "blue":+ return "Blue";+ case "pink":+ return "Pink";+ case "purple":+ return "Purple";+ default:+ return "Yellow";+ }+}diff --git a/web/components/reading/MaterialPicker.tsx b/web/components/reading/MaterialPicker.tsxnew file mode 100644index 000000000..5fd6ee190--- /dev/null+++ b/web/components/reading/MaterialPicker.tsx@@ -0,0 +1,224 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { FileText, Loader2, Trash2, Upload } from "lucide-react";+import { useTranslation } from "react-i18next";+import {+ deleteMaterial,+ getSupportedFormats,+ listMaterials,+ uploadMaterial,+ type MaterialDetail,+ type MaterialInfo,+} from "@/lib/reading-api";++export interface MaterialPickerProps {+ onOpen: (material: MaterialDetail | MaterialInfo) => void;+ /** Bumped by the parent to force a reload after an external change. */+ refreshToken?: number;+}++/**+ * Empty state of the reader: drop a file in, or reopen one already read.+ *+ * Uploads are content-addressed server-side, so re-adding a file the user has+ * read before reopens it *with its annotations* rather than creating a duplicate.+ * The copy says so, because otherwise the behaviour looks like a bug.+ */+export function MaterialPicker({ onOpen, refreshToken = 0 }: MaterialPickerProps) {+ const { t } = useTranslation();+ const inputRef = useRef<HTMLInputElement | null>(null);+ const [materials, setMaterials] = useState<MaterialInfo[]>([]);+ const [accept, setAccept] = useState<string>("");+ const [maxBytes, setMaxBytes] = useState(0);+ const [busy, setBusy] = useState(false);+ const [dragging, setDragging] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);++ const reload = useCallback(async () => {+ try {+ setMaterials(await listMaterials());+ } catch {+ // A listing failure must not block uploading — leave the list empty.+ setMaterials([]);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void reload();+ }, [reload, refreshToken]);++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const formats = await getSupportedFormats();+ if (cancelled) return;+ setAccept(formats.extensions.join(","));+ setMaxBytes(formats.max_bytes);+ } catch {+ // Leave `accept` empty: the file dialog then shows everything and the+ // server rejects what it cannot read, with a message.+ }+ })();+ return () => {+ cancelled = true;+ };+ }, []);++ const ingest = useCallback(+ async (file: File | undefined | null) => {+ if (!file || busy) return;+ setBusy(true);+ setError(null);+ try {+ const material = await uploadMaterial(file);+ await reload();+ onOpen(material);+ } catch (uploadError) {+ setError(+ uploadError instanceof Error+ ? uploadError.message+ : t("This file could not be opened."),+ );+ } finally {+ setBusy(false);+ }+ },+ [busy, onOpen, reload, t],+ );++ const remove = useCallback(+ async (materialId: string) => {+ try {+ await deleteMaterial(materialId);+ } catch {+ // Fall through to the reload: if it is already gone, the list is right.+ }+ await reload();+ },+ [reload],+ );++ return (+ <div className="flex h-full flex-col items-center overflow-y-auto px-6 py-8">+ <div className="w-full max-w-[520px]">+ <div+ onDragOver={(event) => {+ event.preventDefault();+ setDragging(true);+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={(event) => {+ event.preventDefault();+ setDragging(false);+ void ingest(event.dataTransfer.files?.[0]);+ }}+ onClick={() => inputRef.current?.click()}+ role="button"+ tabIndex={0}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ inputRef.current?.click();+ }+ }}+ className={`flex cursor-pointer flex-col items-center justify-center gap-2.5 rounded-2xl border-2 border-dashed px-6 py-10 text-center transition ${+ dragging+ ? "border-[var(--ring)] bg-[var(--primary)]/[0.06]"+ : "border-[var(--border)] hover:border-[var(--ring)]/60 hover:bg-[var(--muted)]/30"+ }`}+ >+ {busy ? (+ <Loader2 size={20} className="animate-spin text-[var(--muted-foreground)]" />+ ) : (+ <Upload size={20} className="text-[var(--muted-foreground)]" />+ )}+ <p className="font-serif text-[16px] font-medium text-[var(--foreground)]">+ {busy ? t("Preparing document…") : t("Open a document to read")}+ </p>+ <p className="max-w-[360px] text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Drop a PDF, EPUB, Word, slide deck or text file here. The assistant reads it with you and cites what it uses.",+ )}+ {maxBytes > 0+ ? ` ${t("Up to {{mb}} MB.", { mb: Math.floor(maxBytes / (1024 * 1024)) })}`+ : ""}+ </p>+ <input+ ref={inputRef}+ type="file"+ accept={accept || undefined}+ className="hidden"+ onChange={(event) => {+ void ingest(event.target.files?.[0]);+ // Reset so choosing the same file twice still fires a change.+ event.target.value = "";+ }}+ />+ </div>++ {error && (+ <p+ role="alert"+ className="mt-3 rounded-lg border border-[var(--destructive)]/30 bg-[var(--destructive)]/[0.06] px-3 py-2 text-[11.5px] leading-relaxed text-[var(--destructive)]"+ >+ {error}+ </p>+ )}++ {!loading && materials.length > 0 && (+ <div className="mt-7">+ <h3 className="mb-2 px-1 font-mono text-[10px] uppercase tracking-[0.07em] text-[var(--muted-foreground)]">+ {t("Recently read")}+ </h3>+ <ul className="space-y-1">+ {materials.map((material) => (+ <li key={material.material_id}>+ <div className="group/mat flex items-center gap-2.5 rounded-xl border border-transparent px-2.5 py-2 transition hover:border-[var(--border)] hover:bg-[var(--muted)]/40">+ <button+ type="button"+ onClick={() => onOpen(material)}+ className="flex min-w-0 flex-1 items-center gap-2.5 text-left"+ >+ <FileText+ size={15}+ className="shrink-0 text-[var(--muted-foreground)]"+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[12.5px] font-medium text-[var(--foreground)]">+ {material.filename}+ </span>+ <span className="block truncate font-mono text-[10.5px] text-[var(--muted-foreground)]">+ {material.unit_count} {material.unit}+ {material.unit_count === 1 ? "" : "s"}+ {material.annotation_count > 0+ ? ` · ${t("{{count}} annotations", {+ count: material.annotation_count,+ })}`+ : ""}+ </span>+ </span>+ </button>+ <button+ type="button"+ title={t("Remove")}+ aria-label={t("Remove")}+ onClick={() => void remove(material.material_id)}+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--muted-foreground)] opacity-0 transition hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] focus-visible:opacity-100 group-hover/mat:opacity-100"+ >+ <Trash2 size={12.5} />+ </button>+ </div>+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/components/reading/PdfDocumentView.tsx b/web/components/reading/PdfDocumentView.tsxnew file mode 100644index 000000000..ddbec9275--- /dev/null+++ b/web/components/reading/PdfDocumentView.tsx@@ -0,0 +1,432 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import { loadPdfjs, type PdfDocument } from "@/lib/pdfjs-loader";+import type { AnnotationItem, NormalisedRect } from "@/lib/reading-api";+import { rawMaterialUrl } from "@/lib/reading-api";+import { domRangeForQuote } from "@/lib/reading-quote-locator";+import {+ cleanQuote,+ locatorOfSelection,+ normaliseRects,+} from "@/lib/reading-selection";+import { PdfPage } from "./PdfPage";++/** Pages kept rendered on each side of the viewport. */+const RENDER_MARGIN = 1;+/** How long a `reader_goto` highlight pulses before fading. */+const PAGE_GAP = 16;++export interface SelectionPayload {+ locator: number;+ quote: string;+ rects: NormalisedRect[];+ /** Viewport coordinates of the selection, for popover placement. */+ anchor: { x: number; y: number };+}++export interface JumpRequest {+ locator: number;+ quote?: string;+ /** Changes on every request so repeats of the same target still fire. */+ nonce: number;+}++export interface PdfDocumentViewProps {+ materialId: string;+ unitCount: number;+ annotations: AnnotationItem[];+ jump: JumpRequest | null;+ highlightedAnnotationId?: string | null;+ onSelection: (payload: SelectionPayload | null) => void;+ onAnnotationClick?: (annotation: AnnotationItem) => void;+ onVisibleLocatorChange?: (locator: number) => void;+}++/**+ * Scrolling PDF view with windowed rendering.+ *+ * Every page is laid out at its real height from the start (measured from page+ * one and refined as pages render), so the scrollbar is honest and jumping to a+ * locator lands in the right place without rendering the pages in between. Only+ * pages near the viewport hold a canvas — a 600-page book would otherwise+ * exhaust canvas memory long before the user reached the end.+ */+export function PdfDocumentView({+ materialId,+ unitCount,+ annotations,+ jump,+ highlightedAnnotationId,+ onSelection,+ onAnnotationClick,+ onVisibleLocatorChange,+}: PdfDocumentViewProps) {+ const { t } = useTranslation();+ const scrollRef = useRef<HTMLDivElement | null>(null);+ // Loaded document and load error are both tagged with the material they+ // belong to, so switching documents invalidates them by derivation instead of+ // by a synchronous reset inside the effect (which would cascade a render).+ const [loaded, setLoaded] = useState<{+ materialId: string;+ doc: PdfDocument;+ ratio: number;+ } | null>(null);+ const [loadError, setLoadError] = useState<{+ materialId: string;+ message: string;+ } | null>(null);+ const [pageWidth, setPageWidth] = useState(0);+ const [visibleLocator, setVisibleLocator] = useState(1);+ // Tagged with the jump's nonce for the same reason: a stale flash cannot+ // outlive the request that produced it.+ const [flash, setFlash] = useState<{+ nonce: number;+ locator: number;+ rects: NormalisedRect[];+ } | null>(null);++ const doc = loaded?.materialId === materialId ? loaded.doc : null;+ const fallbackRatio =+ loaded?.materialId === materialId ? loaded.ratio : 1.414; // A4 until measured+ const error = loadError?.materialId === materialId ? loadError.message : null;++ // -- document ------------------------------------------------------------++ useEffect(() => {+ let cancelled = false;+ // The loading task — not the document proxy — owns `destroy()`, and+ // destroying it is what releases the worker port and the buffered file.+ let task: { destroy: () => Promise<void> } | null = null;++ (async () => {+ try {+ const pdfjs = await loadPdfjs();+ const loadingTask = pdfjs.getDocument({+ url: rawMaterialUrl(materialId),+ // The raw route sits behind the session cookie like every other API+ // route; pdf.js does its own fetching, so it needs telling.+ withCredentials: true,+ });+ task = loadingTask;+ const opened: PdfDocument = await loadingTask.promise;+ if (cancelled) return;+ const first = await opened.getPage(1);+ const viewport = first.getViewport({ scale: 1 });+ if (cancelled) return;+ setLoaded({+ materialId,+ doc: opened,+ ratio: viewport.width > 0 ? viewport.height / viewport.width : 1.414,+ });+ } catch (caught) {+ if (cancelled) return;+ setLoadError({+ materialId,+ message:+ caught instanceof Error+ ? caught.message+ : t("This document could not be opened."),+ });+ }+ })();++ return () => {+ cancelled = true;+ // Release the worker's copy of the file; without this each opened+ // document leaks a worker port for the life of the session.+ void task?.destroy();+ };+ }, [materialId, t]);++ // -- width ---------------------------------------------------------------++ useEffect(() => {+ const element = scrollRef.current;+ if (!element) return;+ const measure = () => {+ // Leave room for the scrollbar gutter and the page's own margin.+ const available = element.clientWidth - 48;+ setPageWidth(Math.max(240, Math.min(1100, available)));+ };+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ return () => observer.disconnect();+ }, [doc]);++ // -- which page is on screen --------------------------------------------++ /**+ * Track the page on screen from scroll position, measured directly.+ *+ * Deliberately not an `IntersectionObserver`. That was the first+ * implementation and it does not fire at all in some embedded browsers — which+ * silently froze the render window at page 1, so scrolling to page 10 showed a+ * blank placeholder forever. Rect maths on a throttled scroll event has no+ * such dependency, and "which page covers the most of the viewport" is a+ * question it answers directly.+ */+ useEffect(() => {+ const root = scrollRef.current;+ if (!root || !doc) return;++ let frame = 0;+ const measure = () => {+ frame = 0;+ const rootRect = root.getBoundingClientRect();+ const pages = root.querySelectorAll<HTMLElement>("[data-reader-unit]");+ let best: { locator: number; covered: number } | null = null;+ for (const page of pages) {+ const rect = page.getBoundingClientRect();+ const covered =+ Math.min(rect.bottom, rootRect.bottom) - Math.max(rect.top, rootRect.top);+ if (covered <= 0) continue;+ const locator = Number(page.dataset.readerUnit ?? "0");+ if (!locator) continue;+ if (!best || covered > best.covered) best = { locator, covered };+ }+ if (best) setVisibleLocator((current) => (current === best.locator ? current : best.locator));+ };++ const onScroll = () => {+ // One measurement per frame: a fast flick fires scroll dozens of times and+ // each measurement walks every page element.+ if (!frame) frame = window.requestAnimationFrame(measure);+ };++ measure();+ root.addEventListener("scroll", onScroll, { passive: true });+ return () => {+ root.removeEventListener("scroll", onScroll);+ if (frame) window.cancelAnimationFrame(frame);+ };+ }, [doc, unitCount, pageWidth]);++ useEffect(() => {+ onVisibleLocatorChange?.(visibleLocator);+ }, [visibleLocator, onVisibleLocatorChange]);++ /**+ * Which pages hold a canvas: those near the viewport, plus those near an+ * outstanding jump target.+ *+ * The jump anchor matters — a jump to a distant page has to render it *before*+ * its text layer can be searched for the quote, and waiting for the smooth+ * scroll to bring it into view first would time the search out.+ */+ const isActive = useCallback(+ (locator: number) => {+ const near = (anchor: number) => Math.abs(locator - anchor) <= RENDER_MARGIN;+ return near(visibleLocator) || (jump ? near(jump.locator) : false);+ },+ [visibleLocator, jump],+ );++ // -- jumping -------------------------------------------------------------++ const scrollToLocator = useCallback((locator: number) => {+ const root = scrollRef.current;+ if (!root) return false;+ const target = root.querySelector<HTMLElement>(+ `[data-reader-unit="${locator}"]`,+ );+ if (!target) return false;+ // Measured, not `offsetTop`: the nearest positioned ancestor is the reader+ // shell (it is absolutely positioned), not this scroll container, so+ // `offsetTop` is off by the header's height. Rect maths is independent of+ // the offset-parent chain and cannot drift when the chrome above changes.+ const top =+ target.getBoundingClientRect().top -+ root.getBoundingClientRect().top ++ root.scrollTop -+ PAGE_GAP;+ // Assigned, never animated. Programmatic smooth scrolling is silently a+ // no-op in some embedded browsers, and `scroll-behavior` in CSS would make+ // this assignment inherit that failure — a citation jump that does nothing+ // is far worse than one that does not glide.+ root.scrollTop = Math.max(0, top);+ return true;+ }, []);++ useEffect(() => {+ if (!jump || !doc) return;+ const locator = Math.min(Math.max(1, jump.locator), unitCount);+ const nonce = jump.nonce;+ const quote = jump.quote;+ let cancelled = false;+ let timer: number | undefined;++ // Scrolling and searching both wait a frame: the jump may have just widened+ // the render window, and the target page needs to exist in the DOM first.+ let scrollTries = 0;+ const run = () => {+ if (cancelled) return;+ if (!scrollToLocator(locator)) {+ // The page div may not be in the DOM for a frame after a jump widens the+ // render window. Bounded, so a locator that never appears (a truncated+ // document, say) cannot spin forever.+ scrollTries += 1;+ if (scrollTries <= 20) timer = window.setTimeout(run, 120);+ return;+ }+ if (!quote) return;+ let attempts = 0;+ const findQuote = () => {+ if (cancelled) return;+ attempts += 1;+ const root = scrollRef.current;+ const page = root?.querySelector<HTMLElement>(+ `[data-reader-unit="${locator}"]`,+ );+ const layer = page?.querySelector<HTMLElement>(".textLayer");+ if (layer && layer.childElementCount > 0) {+ const range = domRangeForQuote(layer, quote);+ const box = page?.getBoundingClientRect();+ if (range && box) {+ const rects = normaliseRects([...range.getClientRects()], {+ left: box.left,+ top: box.top,+ width: box.width,+ height: box.height,+ });+ if (rects.length) {+ setFlash({ nonce, locator, rects });+ return;+ }+ }+ }+ // Keep trying on a miss rather than giving up: a text layer is populated+ // progressively, so "has some children" does not mean "has all of them"+ // — a quote spanning a not-yet-rendered span would be lost forever if+ // the first non-empty poll were treated as final. Bounded, so a quote+ // that genuinely is not on the page (an image caption, a scan) stops+ // polling; the page is still scrolled into view, which is the useful+ // part of the request.+ if (attempts < 25) timer = window.setTimeout(findQuote, 120);+ };+ timer = window.setTimeout(findQuote, 140);+ };+ timer = window.setTimeout(run, 0);++ return () => {+ cancelled = true;+ if (timer) window.clearTimeout(timer);+ };+ }, [jump, doc, unitCount, scrollToLocator]);++ // Tagged with the nonce that produced it, so the previous jump's highlight is+ // superseded by derivation — no timer, and no way for a stale highlight to+ // outlive the request behind it. The mark itself persists until then; see the+ // `dt-reader-flash` rules for why it does not fade out.+ const activeFlash = flash && jump && flash.nonce === jump.nonce ? flash : null;++ // -- selection -----------------------------------------------------------++ const handlePointerUp = useCallback(() => {+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {+ onSelection(null);+ return;+ }+ const range = selection.getRangeAt(0);+ const root = scrollRef.current;+ if (!root || !root.contains(range.commonAncestorContainer)) {+ onSelection(null);+ return;+ }+ const quote = cleanQuote(selection.toString());+ if (!quote) {+ onSelection(null);+ return;+ }++ // Attribute the selection to the page it started on, and measure against+ // that page's box so the rects are in its own normalised space.+ const startElement =+ range.startContainer.nodeType === Node.ELEMENT_NODE+ ? (range.startContainer as HTMLElement)+ : range.startContainer.parentElement;+ const page = startElement?.closest<HTMLElement>("[data-reader-unit]");+ const locator = locatorOfSelection([+ Number(page?.dataset.readerUnit ?? "0") || null,+ ]);+ if (!page || !locator) {+ onSelection(null);+ return;+ }++ const box = page.getBoundingClientRect();+ const clientRects = [...range.getClientRects()];+ const rects = normaliseRects(clientRects, {+ left: box.left,+ top: box.top,+ width: box.width,+ height: box.height,+ });+ if (!rects.length) {+ onSelection(null);+ return;+ }+ const last = clientRects[clientRects.length - 1];+ onSelection({+ locator,+ quote,+ rects,+ anchor: { x: last.left + last.width / 2, y: last.top },+ });+ }, [onSelection]);++ // -- render --------------------------------------------------------------++ if (error) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 px-8 text-center">+ <p className="text-[13px] font-medium text-[var(--foreground)]">+ {t("This document could not be opened.")}+ </p>+ <p className="max-w-[420px] text-[12px] text-[var(--muted-foreground)]">+ {error}+ </p>+ </div>+ );+ }++ return (+ <div+ ref={scrollRef}+ onMouseUp={handlePointerUp}+ className="dt-reader-scroll h-full overflow-y-auto overscroll-contain bg-[var(--muted)]/40 px-6 py-4"+ >+ {!doc ? (+ <div className="flex h-full items-center justify-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 size={14} className="animate-spin" />+ {t("Opening document…")}+ </div>+ ) : (+ <div className="flex flex-col items-center" style={{ gap: PAGE_GAP }}>+ {Array.from({ length: unitCount }, (_, index) => index + 1).map(+ (locator) => (+ <PdfPage+ key={locator}+ doc={doc}+ locator={locator}+ width={pageWidth}+ fallbackRatio={fallbackRatio}+ active={isActive(locator)}+ annotations={annotations}+ highlightedAnnotationId={highlightedAnnotationId}+ flashRects={+ activeFlash?.locator === locator ? activeFlash.rects : undefined+ }+ onAnnotationClick={onAnnotationClick}+ />+ ),+ )}+ </div>+ )}+ </div>+ );+}diff --git a/web/components/reading/PdfPage.tsx b/web/components/reading/PdfPage.tsxnew file mode 100644index 000000000..715392ca3--- /dev/null+++ b/web/components/reading/PdfPage.tsx@@ -0,0 +1,213 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ loadPdfjs,+ outputScale,+ type PdfDocument,+} from "@/lib/pdfjs-loader";+import type { AnnotationItem } from "@/lib/reading-api";+import { AnnotationLayer } from "./AnnotationLayer";++export interface PdfPageProps {+ doc: PdfDocument;+ locator: number;+ /** CSS width the page should occupy; height follows the page's aspect ratio. */+ width: number;+ /** Placeholder aspect ratio (height / width) until the real page is measured. */+ fallbackRatio: number;+ /** False while the page is far outside the viewport — keeps memory bounded. */+ active: boolean;+ annotations: AnnotationItem[];+ highlightedAnnotationId?: string | null;+ /** Transient highlight from `reader_goto`, as normalised rects. */+ flashRects?: Array<[number, number, number, number]>;+ onAnnotationClick?: (annotation: AnnotationItem) => void;+}++/**+ * One rendered PDF page: canvas, selectable text layer, annotation overlay.+ *+ * Rendering is gated on `active` and every effect cancels its in-flight work,+ * because scrolling a long document mounts and unmounts pages faster than+ * pdf.js can finish: without cancellation the canvas of a page that scrolled+ * away keeps decoding, and a late `render` can paint over a newer one.+ *+ * The page keeps its measured height while inactive, so deactivating it does not+ * collapse the scroll container and yank the reader's position.+ */+export function PdfPage({+ doc,+ locator,+ width,+ fallbackRatio,+ active,+ annotations,+ highlightedAnnotationId,+ flashRects,+ onAnnotationClick,+}: PdfPageProps) {+ const { t } = useTranslation();+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const textLayerRef = useRef<HTMLDivElement | null>(null);+ const [ratio, setRatio] = useState<number | null>(null);+ const [failed, setFailed] = useState(false);++ const height = Math.round(width * (ratio ?? fallbackRatio));++ useEffect(() => {+ if (!active || width <= 0) return;+ let cancelled = false;+ let renderTask: { cancel: () => void } | null = null;+ let textLayer: { cancel: () => void } | null = null;++ (async () => {+ try {+ const pdfjs = await loadPdfjs();+ const page = await doc.getPage(locator);+ if (cancelled) return;++ const base = page.getViewport({ scale: 1 });+ if (base.width > 0) {+ setRatio(base.height / base.width);+ }+ const scale = width / base.width;+ const viewport = page.getViewport({ scale });++ // Canvas and text layer are rendered CONCURRENTLY and independently.+ // The text layer needs only the viewport and the page's text content —+ // it has no dependency on the bitmap being finished — so chaining it+ // behind the canvas render promise only made selection and quote+ // highlighting hostage to that promise settling. Some embedded browsers+ // paint the page but never settle it, which produced a document that+ // looked perfect and could not be selected at all.+ const paintCanvas = async () => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const dpr = outputScale();+ canvas.width = Math.floor(viewport.width * dpr);+ canvas.height = Math.floor(viewport.height * dpr);+ canvas.style.width = `${Math.floor(viewport.width)}px`;+ canvas.style.height = `${Math.floor(viewport.height)}px`;+ // `canvas` only, never alongside `canvasContext`: pdf.js documents the+ // context parameter as backwards-compatibility requiring+ // `canvas: null`, and passing both is an unsupported combination.+ renderTask = page.render({+ canvas,+ viewport,+ transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,+ });+ await (renderTask as unknown as { promise: Promise<void> }).promise;+ };++ const buildTextLayer = async () => {+ const textContent = await page.getTextContent();+ // Re-checked after the await: two runs of this effect (a resize+ // mid-render) would otherwise both reach `render()` on the same+ // container and the loser would wipe the winner's spans.+ if (cancelled) return;+ const container = textLayerRef.current;+ if (!container) return;+ container.replaceChildren();+ // pdf.js positions the spans with `--total-scale-factor`; without it+ // every run collapses to the same tiny size and selection is useless.+ container.style.setProperty("--total-scale-factor", String(scale));+ const layer = new pdfjs.TextLayer({+ textContentSource: textContent,+ container,+ viewport,+ });+ textLayer = layer as unknown as { cancel: () => void };+ await layer.render();+ };++ // allSettled: a canvas failure must not cost the page its text layer,+ // and vice versa. Failures are reported below only if BOTH sides failed,+ // since either one alone still leaves a usable page.+ const outcomes = await Promise.allSettled([paintCanvas(), buildTextLayer()]);+ if (cancelled) return;+ const fatal = outcomes.every(+ (outcome) =>+ outcome.status === "rejected" &&+ (outcome.reason as { name?: string } | null)?.name !==+ "RenderingCancelledException",+ );+ setFailed(fatal);+ } catch (error) {+ // pdf.js throws RenderingCancelledException on a cancelled task — that+ // is the normal path when scrolling, not a failure to report.+ const name = (error as { name?: string } | null)?.name ?? "";+ if (!cancelled && name !== "RenderingCancelledException") {+ setFailed(true);+ }+ }+ })();++ return () => {+ cancelled = true;+ try {+ renderTask?.cancel();+ } catch {+ // Already settled.+ }+ try {+ textLayer?.cancel();+ } catch {+ // Already settled.+ }+ };+ }, [doc, locator, width, active]);++ // Free the canvas bitmap when the page scrolls far away. Without this a+ // 600-page document accumulates every page it ever showed.+ useEffect(() => {+ if (active) return;+ const canvas = canvasRef.current;+ if (canvas) {+ canvas.width = 0;+ canvas.height = 0;+ }+ textLayerRef.current?.replaceChildren();+ }, [active]);++ const pageAnnotations = useMemo(+ () => annotations.filter((a) => a.locator === locator),+ [annotations, locator],+ );++ return (+ <div+ data-reader-unit={locator}+ className="relative mx-auto shrink-0 overflow-hidden rounded-[10px] bg-white shadow-[0_1px_3px_rgba(0,0,0,0.10),0_8px_24px_-12px_rgba(0,0,0,0.18)] ring-1 ring-black/[0.06]"+ style={{ width, height }}+ >+ <canvas ref={canvasRef} className="block h-full w-full" />+ <div+ ref={textLayerRef}+ className="textLayer"+ // The text layer is the selection surface; annotations sit above it but+ // must not swallow drags, so only this layer takes pointer events.+ style={{ pointerEvents: "auto" }}+ />+ <AnnotationLayer+ annotations={pageAnnotations}+ highlightedAnnotationId={highlightedAnnotationId}+ flashRects={flashRects}+ onAnnotationClick={onAnnotationClick}+ />+ {!active && (+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center">+ <span className="font-mono text-[11px] text-black/25">{locator}</span>+ </div>+ )}+ {failed && (+ <div className="absolute inset-0 flex items-center justify-center bg-white/90 px-6 text-center">+ <span className="text-[12px] text-[var(--muted-foreground)]">+ {t("This page could not be rendered.")}+ </span>+ </div>+ )}+ </div>+ );+}diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsxnew file mode 100644index 000000000..8ef544b89--- /dev/null+++ b/web/components/reading/ReaderPane.tsx@@ -0,0 +1,518 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ Crosshair,+ Download,+ FileText,+ List,+ Loader2,+ PanelRightClose,+ PanelRightOpen,+ X,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import { useReading } from "@/context/ReadingContext";+import {+ READER_ACTION_EVENT,+ READER_TURN_END_EVENT,+ type ReaderActionPayload,+} from "@/lib/reading-reader-action";+import { locatorFromHref } from "@/lib/reading-citations";+import {+ fetchExport,+ type AnnotationColor,+ type AnnotationItem,+} from "@/lib/reading-api";+import { AnnotationList } from "./AnnotationList";+import { AnnotationPopover } from "./AnnotationPopover";+import { MaterialPicker } from "./MaterialPicker";+import {+ PdfDocumentView,+ type JumpRequest,+ type SelectionPayload,+} from "./PdfDocumentView";+import { ReaderResizeHandle } from "./ReaderResizeHandle";+import { TextUnitView, unitLabel } from "./TextUnitView";++/** Event the reader dispatches to prefill the composer from a selection. */+export const READER_ASK_EVENT = "dt:reader-ask";+const AUTO_JUMP_KEY = "dt.reader.autoJump";++export interface ReaderPaneProps {+ onClose: () => void;+}++/**+ * The reading pane: document on the left of the chat, with its own annotations.+ *+ * Two behaviours are worth calling out because they were explicit product+ * decisions rather than defaults:+ *+ * * **Auto-jump is a user-owned toggle, not a rate limit.** The assistant may+ * call `reader_goto` as often as it likes — once per passage it discusses is+ * the intended usage. When the toggle is on, the view follows every call, so+ * the reader watches the model read. When it is off, jumps are ignored and the+ * citations in the answer remain clickable, so the user stays in control of+ * their own scroll position. The preference persists across sessions.+ * * **Annotations are optimistic.** A highlight appears the moment it is drawn+ * and is reconciled with the server's row when the write returns; a failed+ * write removes it again and surfaces the error. Waiting for a round trip+ * before showing ink makes highlighting feel broken.+ */+export function ReaderPane({ onClose }: ReaderPaneProps) {+ const { t } = useTranslation();+ // Document + annotations live in the provider (workspace layout), so they+ // survive the remount that sending the first message causes.+ const {+ material,+ annotations,+ loading: loadingMaterial,+ error: notice,+ openMaterial,+ closeMaterial,+ saveMark,+ removeMark,+ mergeMark,+ dismissError,+ setError,+ reportViewport,+ } = useReading();++ const [activeAnnotationId, setActiveAnnotationId] = useState<string | null>(null);+ const [selection, setSelection] = useState<SelectionPayload | null>(null);+ const [jump, setJump] = useState<JumpRequest | null>(null);+ // `null` = follow the document: show the panel once there is something in it.+ // An empty panel is a whole column of nothing next to the page, which reads as+ // a layout bug rather than an affordance. An explicit true/false means the+ // user decided, and that wins from then on.+ const [annotationPanel, setAnnotationPanel] = useState<boolean | null>(null);+ const [showOutline, setShowOutline] = useState(false);+ const [autoJump, setAutoJump] = useState(true);+ const [exporting, setExporting] = useState(false);+ const [currentLocator, setCurrentLocator] = useState(1);+ const nonceRef = useRef(0);++ // -- persisted auto-jump preference --------------------------------------++ useEffect(() => {+ try {+ const stored = window.localStorage.getItem(AUTO_JUMP_KEY);+ if (stored !== null) setAutoJump(stored === "1");+ } catch {+ // Private mode / storage disabled — keep the default.+ }+ }, []);++ const toggleAutoJump = useCallback(() => {+ setAutoJump((current) => {+ const next = !current;+ try {+ window.localStorage.setItem(AUTO_JUMP_KEY, next ? "1" : "0");+ } catch {+ // Non-fatal: the toggle still works for this session.+ }+ return next;+ });+ }, []);+++ // -- viewport reporting --------------------------------------------------++ const handleVisibleLocator = useCallback(+ (locator: number) => {+ setCurrentLocator(locator);+ reportViewport({ locator });+ },+ [reportViewport],+ );++ useEffect(() => {+ reportViewport({ selection: selection?.quote ?? "" });+ }, [selection, reportViewport]);++ // -- reader actions from the assistant -----------------------------------++ const requestJump = useCallback((locator: number, quote?: string) => {+ nonceRef.current += 1;+ setJump({ locator, quote, nonce: nonceRef.current });+ }, []);++ useEffect(() => {+ const onReaderAction = (event: Event) => {+ const detail = (event as CustomEvent<ReaderActionPayload>).detail;+ if (!detail || !material) return;+ // Ignore actions aimed at a document that is no longer open — a stale+ // event replayed from an earlier turn must not move the current view.+ if (detail.material_id && detail.material_id !== material.material_id) return;++ if (detail.reader_action === "annotate" && detail.annotation) {+ const incoming = detail.annotation as unknown as AnnotationItem;+ if (incoming.annotation_id) {+ mergeMark(incoming);+ }+ }+ if (!autoJump) return;+ const locator = Number(detail.locator ?? 0);+ if (locator >= 1) requestJump(locator, detail.quote || undefined);+ };+ window.addEventListener(READER_ACTION_EVENT, onReaderAction);+ return () => window.removeEventListener(READER_ACTION_EVENT, onReaderAction);+ }, [material, autoJump, requestJump, mergeMark]);++ /**+ * Follow the answer when the model did not move the reader itself.+ *+ * `reader_goto` is the intended path and gives a highlighted quote; this is+ * the safety net for the turns where the model cites `[p.5]` in prose and+ * simply never calls it. Without it the reader sits on page 1 next to an+ * answer about page 5, which reads as broken no matter whose fault it is.+ *+ * Deliberately the FIRST citation of the LAST answer, and only when auto-jump+ * is on: it is the same promise the toggle makes — the view follows what the+ * assistant is talking about.+ */+ useEffect(() => {+ const onTurnEnd = (event: Event) => {+ const moved = (event as CustomEvent<{ moved?: boolean }>).detail?.moved;+ if (moved || !autoJump || !material) return;+ // One frame later: the final answer is still being committed to the DOM+ // as the turn closes.+ const timer = window.setTimeout(() => {+ const answers = document.querySelectorAll('[role="article"]');+ const last = answers[answers.length - 1];+ const anchor = last?.querySelector<HTMLAnchorElement>(+ 'a[href^="#dt-locator-"]',+ );+ const locator = locatorFromHref(anchor?.getAttribute("href"));+ if (locator) requestJump(locator);+ }, 120);+ return () => window.clearTimeout(timer);+ };+ window.addEventListener(READER_TURN_END_EVENT, onTurnEnd);+ return () => window.removeEventListener(READER_TURN_END_EVENT, onTurnEnd);+ }, [autoJump, material, requestJump]);++ /**+ * Citation clicks in assistant prose, intercepted in the CAPTURE phase.+ *+ * It has to be capture, and it has to be here. The shared Markdown renderer+ * calls `preventDefault()` on *every* `#`-prefixed link before looking for an+ * element with that id (RichMarkdownRenderer's hash-link branch), and the chat+ * page's own delegated handler bails on `event.defaultPrevented`. A citation+ * would therefore be swallowed in the bubble phase and do nothing at all.+ * Capture runs before React dispatches any of that, and `stopPropagation`+ * keeps the renderer's hash handling from firing afterwards.+ */+ useEffect(() => {+ const onClick = (event: MouseEvent) => {+ // Leave modified clicks to the browser — a user opening a citation in a+ // new tab is asking for the link, not for the reader to move.+ if (event.button !== 0) return;+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;+ const target = event.target as HTMLElement | null;+ const anchor = target?.closest?.("a[href]") as HTMLAnchorElement | null;+ const locator = locatorFromHref(anchor?.getAttribute("href"));+ if (!locator) return;+ event.preventDefault();+ event.stopPropagation();+ requestJump(locator);+ };+ document.addEventListener("click", onClick, true);+ return () => document.removeEventListener("click", onClick, true);+ }, [requestJump]);++ // -- annotations ---------------------------------------------------------++ const commitSelection = useCallback(+ (kind: "highlight" | "underline" | "note", color: AnnotationColor, note = "") => {+ if (!selection || !material) return;+ const temporaryId = `pending-${Date.now()}-${Math.round(Math.random() * 1e6)}`;+ const now = Date.now() / 1000;+ void saveMark(+ {+ locator: selection.locator,+ kind: kind === "note" ? "highlight" : kind,+ color,+ quote: selection.quote,+ note,+ rects: selection.rects,+ },+ {+ annotation_id: temporaryId,+ locator: selection.locator,+ kind: kind === "note" ? "highlight" : kind,+ color,+ quote: selection.quote,+ note,+ rects: selection.rects,+ author: "user",+ created_at: now,+ updated_at: now,+ },+ );+ setSelection(null);+ window.getSelection()?.removeAllRanges();+ },+ [selection, material, saveMark],+ );++ const askAboutSelection = useCallback(() => {+ if (!selection || !material) return;+ window.dispatchEvent(+ new CustomEvent(READER_ASK_EVENT, {+ detail: {+ quote: selection.quote,+ locator: selection.locator,+ unit: material.unit,+ },+ }),+ );+ setSelection(null);+ window.getSelection()?.removeAllRanges();+ }, [selection, material]);++ // -- export --------------------------------------------------------------++ const runExport = useCallback(async () => {+ if (!material || exporting) return;+ setExporting(true);+ dismissError();+ try {+ const { blob, filename } = await fetchExport(material.material_id);+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = filename;+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ // Revoke on the next frame: revoking synchronously can cancel the download+ // in some browsers before it has read the blob.+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);+ } catch (error) {+ setError(error instanceof Error ? error.message : t("Export failed."));+ } finally {+ setExporting(false);+ }+ }, [material, exporting, t, dismissError, setError]);++ // -- render --------------------------------------------------------------++ const showAnnotations = annotationPanel ?? annotations.length > 0;+ const unitWord = material ? t(unitLabel(material.unit)) : "";+ const outlineRows = useMemo(+ () => (material?.outline ?? []).filter((row) => row.title.trim().length > 0),+ [material],+ );++ return (+ <div className="relative flex h-full min-w-0 flex-col border-r border-[var(--border)] bg-[var(--background)]">+ <ReaderResizeHandle />+ <header className="flex h-11 shrink-0 items-center gap-1 border-b border-[var(--border)] px-2.5">+ <FileText size={14} className="shrink-0 text-[var(--muted-foreground)]" />+ <span+ className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-[var(--foreground)]"+ title={material?.filename}+ >+ {material?.filename ?? t("Immersive reading")}+ </span>++ {material && (+ <>+ <span className="shrink-0 font-mono text-[10.5px] tabular-nums text-[var(--muted-foreground)]">+ {unitWord} {currentLocator}/{material.unit_count}+ </span>+ {outlineRows.length > 0 && (+ <HeaderButton+ icon={List}+ label={t("Outline")}+ active={showOutline}+ onClick={() => setShowOutline((open) => !open)}+ />+ )}+ <HeaderButton+ icon={Crosshair}+ label={+ autoJump+ ? t("Auto-jump on — the view follows what the assistant reads")+ : t("Auto-jump off — the assistant will not move your view")+ }+ active={autoJump}+ onClick={toggleAutoJump}+ />+ <HeaderButton+ icon={exporting ? Loader2 : Download}+ label={t("Export annotated file")}+ spinning={exporting}+ onClick={() => void runExport()}+ />+ <HeaderButton+ icon={showAnnotations ? PanelRightClose : PanelRightOpen}+ label={t("Annotations")}+ active={showAnnotations}+ onClick={() => setAnnotationPanel(!showAnnotations)}+ // The panel itself only exists at `lg` and up — there is no room+ // for it beside the document on a narrow screen. Hiding the+ // trigger too keeps it from being a button that does nothing.+ className="hidden lg:inline-flex"+ />+ <HeaderButton icon={X} label={t("Close document")} onClick={closeMaterial} />+ </>+ )}+ {!material && (+ <HeaderButton icon={X} label={t("Close reader")} onClick={onClose} />+ )}+ </header>++ {notice && (+ <div+ role="alert"+ className="flex items-start gap-2 border-b border-[var(--destructive)]/25 bg-[var(--destructive)]/[0.06] px-3 py-2"+ >+ <p className="flex-1 text-[11.5px] leading-relaxed text-[var(--destructive)]">+ {notice}+ </p>+ <button+ type="button"+ onClick={dismissError}+ className="text-[var(--destructive)]/70 transition hover:text-[var(--destructive)]"+ aria-label={t("Dismiss")}+ >+ <X size={12} />+ </button>+ </div>+ )}++ {showOutline && material && outlineRows.length > 0 && (+ <nav className="dt-reader-scroll max-h-[34%] shrink-0 overflow-y-auto border-b border-[var(--border)] bg-[var(--muted)]/25 px-2 py-1.5">+ <ul>+ {outlineRows.map((row, index) => (+ <li key={`${row.locator}-${index}`}>+ <button+ type="button"+ onClick={() => {+ requestJump(row.locator);+ setShowOutline(false);+ }}+ style={{ paddingLeft: `${6 + (row.level - 1) * 12}px` }}+ className="flex w-full items-baseline gap-2 rounded-md py-[3px] pr-2 text-left transition hover:bg-[var(--muted)]"+ >+ <span className="min-w-0 flex-1 truncate text-[11.5px] text-[var(--foreground)]">+ {row.title}+ </span>+ <span className="shrink-0 font-mono text-[10px] tabular-nums text-[var(--muted-foreground)]">+ {row.locator}+ </span>+ </button>+ </li>+ ))}+ </ul>+ </nav>+ )}++ <div className="flex min-h-0 flex-1">+ <div className="min-w-0 flex-1">+ {loadingMaterial ? (+ <div className="flex h-full items-center justify-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 size={14} className="animate-spin" />+ {t("Opening document…")}+ </div>+ ) : !material ? (+ <MaterialPicker onOpen={(candidate) => void openMaterial(candidate)} />+ ) : material.has_raw_view ? (+ <PdfDocumentView+ materialId={material.material_id}+ unitCount={material.unit_count}+ annotations={annotations}+ jump={jump}+ highlightedAnnotationId={activeAnnotationId}+ onSelection={setSelection}+ onAnnotationClick={(annotation) =>+ setActiveAnnotationId(annotation.annotation_id)+ }+ onVisibleLocatorChange={handleVisibleLocator}+ />+ ) : (+ <TextUnitView+ materialId={material.material_id}+ unit={material.unit}+ unitCount={material.unit_count}+ annotations={annotations}+ jump={jump}+ highlightedAnnotationId={activeAnnotationId}+ onSelection={setSelection}+ onAnnotationClick={(annotation) =>+ setActiveAnnotationId(annotation.annotation_id)+ }+ onVisibleLocatorChange={handleVisibleLocator}+ />+ )}+ </div>++ {material && showAnnotations && (+ <aside className="hidden w-[248px] shrink-0 border-l border-[var(--border)] bg-[var(--background)] lg:block">+ <AnnotationList+ annotations={annotations}+ unit={material.unit}+ activeId={activeAnnotationId}+ onSelect={(annotation) => {+ setActiveAnnotationId(annotation.annotation_id);+ requestJump(annotation.locator, annotation.quote || undefined);+ }}+ onDelete={(annotation) => void removeMark(annotation)}+ />+ </aside>+ )}+ </div>++ {selection && material && (+ <AnnotationPopover+ anchor={selection.anchor}+ quote={selection.quote}+ onHighlight={(color) => commitSelection("highlight", color)}+ onUnderline={(color) => commitSelection("underline", color)}+ onNote={(note, color) => commitSelection("note", color, note)}+ onAsk={askAboutSelection}+ onDismiss={() => setSelection(null)}+ />+ )}+ </div>+ );+}++function HeaderButton({+ icon: Icon,+ label,+ onClick,+ active,+ spinning,+ className = "",+}: {+ icon: typeof FileText;+ label: string;+ onClick: () => void;+ active?: boolean;+ spinning?: boolean;+ className?: string;+}) {+ return (+ <button+ type="button"+ title={label}+ aria-label={label}+ aria-pressed={active}+ disabled={spinning}+ onClick={onClick}+ className={`h-7 w-7 shrink-0 items-center justify-center rounded-lg transition disabled:cursor-default ${+ className || "inline-flex"+ } ${+ active+ ? "bg-[var(--primary)]/12 text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ }`}+ >+ <Icon size={14} className={spinning ? "animate-spin" : undefined} />+ </button>+ );+}diff --git a/web/components/reading/ReaderResizeHandle.tsx b/web/components/reading/ReaderResizeHandle.tsxnew file mode 100644index 000000000..77ea74c86--- /dev/null+++ b/web/components/reading/ReaderResizeHandle.tsx@@ -0,0 +1,205 @@+"use client";++import { useCallback, useEffect, useRef } from "react";+import { useTranslation } from "react-i18next";+import {+ READER_STEP_PX,+ READER_WIDTH_KEY,+ READER_WIDTH_VAR,+ clampReaderWidth,+ parseStoredWidth,+} from "@/lib/reading-split";++/**+ * The draggable seam between the document and the conversation.+ *+ * The width is **not** React state. Both sides of the split read the same+ * `--reader-width` custom property — the pane for its own width, the chat shell+ * for its left padding — so the drag writes that one property and both edges+ * move together, locked, without re-rendering either tree. A pointermove that+ * re-rendered the message list would be visibly janky; this is the same approach+ * the session viewer panel already uses for its edge.+ *+ * Also focusable: arrow keys nudge, Home resets. A split that can only be set by+ * dragging is unusable for anyone not using a mouse, and this is the kind of+ * control people do reach for by keyboard.+ */++function containerWidth(element: HTMLElement | null): number {+ const shell = element?.closest<HTMLElement>(".dt-reader-shell");+ const parent = shell?.parentElement;+ return parent?.getBoundingClientRect().width ?? 0;+}++function containerLeft(element: HTMLElement | null): number {+ const shell = element?.closest<HTMLElement>(".dt-reader-shell");+ return shell?.getBoundingClientRect().left ?? 0;+}++function applyWidth(px: number): void {+ document.documentElement.style.setProperty(READER_WIDTH_VAR, `${px}px`);+}++/**+ * Apply a width with the easing suppressed, then restore it.+ *+ * The chat side animates its padding so that *opening* the reader glides. A+ * keyboard nudge is not an opening — it is a direct adjustment, and easing each+ * 24px step over 240ms makes the seam feel like it is dragging behind the key+ * press. The drag path suppresses the same transition for its whole duration;+ * this is the discrete equivalent.+ */+function applyWidthImmediately(px: number): void {+ const root = document.documentElement;+ root.dataset.readerResizing = "true";+ applyWidth(px);+ // Two frames: one for the write to land, one for the layout to settle before+ // easing is allowed back. `setTimeout(0)` would sometimes restore it early and+ // animate the tail of the step.+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ delete root.dataset.readerResizing;+ });+ });+}++/** Current width in px, measured rather than remembered. */+function currentWidth(element: HTMLElement | null): number {+ const shell = element?.closest<HTMLElement>(".dt-reader-shell");+ return shell?.getBoundingClientRect().width ?? 0;+}++export function ReaderResizeHandle() {+ const { t } = useTranslation();+ const ref = useRef<HTMLDivElement | null>(null);++ // Restore after mount, not during render: the server has no localStorage, and+ // the CSS fallback (a percentage) is what both sides use until then.+ useEffect(() => {+ let stored: number | null = null;+ try {+ stored = parseStoredWidth(window.localStorage.getItem(READER_WIDTH_KEY));+ } catch {+ // Storage unavailable — keep the CSS default.+ }+ if (stored === null) return;+ applyWidthImmediately(clampReaderWidth(stored, containerWidth(ref.current)));+ }, []);++ const persist = useCallback((px: number) => {+ try {+ window.localStorage.setItem(READER_WIDTH_KEY, String(px));+ } catch {+ // Non-fatal: the split still holds for this session.+ }+ }, []);++ const startDrag = useCallback(+ (event: React.PointerEvent) => {+ if (event.button !== 0) return;+ event.preventDefault();+ const element = ref.current;+ const available = containerWidth(element);+ const left = containerLeft(element);++ // Killing the transition for the duration is what makes the edge track the+ // cursor frame-for-frame instead of easing along behind it.+ document.documentElement.dataset.readerResizing = "true";+ document.body.style.userSelect = "none";+ document.body.style.cursor = "col-resize";++ let frame = 0;+ let pendingX = event.clientX;+ let latest = clampReaderWidth(pendingX - left, available);++ const apply = () => {+ frame = 0;+ latest = clampReaderWidth(pendingX - left, available);+ applyWidth(latest);+ };+ const onMove = (moveEvent: PointerEvent) => {+ // Coalesce to one write per frame: pointermove fires faster than the+ // display refreshes.+ pendingX = moveEvent.clientX;+ if (!frame) frame = requestAnimationFrame(apply);+ };+ const onUp = () => {+ if (frame) cancelAnimationFrame(frame);+ delete document.documentElement.dataset.readerResizing;+ document.body.style.userSelect = "";+ document.body.style.cursor = "";+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onUp);+ window.removeEventListener("pointercancel", onUp);+ persist(latest);+ };+ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", onUp);+ // A cancelled pointer (a system gesture taking over) must still clean up,+ // or the page is left with text selection disabled and a resize cursor.+ window.addEventListener("pointercancel", onUp);+ },+ [persist],+ );++ const nudge = useCallback(+ (delta: number) => {+ const element = ref.current;+ const next = clampReaderWidth(currentWidth(element) + delta, containerWidth(element));+ applyWidthImmediately(next);+ persist(next);+ },+ [persist],+ );++ const reset = useCallback(() => {+ document.documentElement.style.removeProperty(READER_WIDTH_VAR);+ try {+ window.localStorage.removeItem(READER_WIDTH_KEY);+ } catch {+ // Nothing to clean up.+ }+ }, []);++ const onKeyDown = useCallback(+ (event: React.KeyboardEvent) => {+ const step = event.shiftKey ? READER_STEP_PX * 4 : READER_STEP_PX;+ if (event.key === "ArrowLeft") {+ event.preventDefault();+ nudge(-step);+ } else if (event.key === "ArrowRight") {+ event.preventDefault();+ nudge(step);+ } else if (event.key === "Home") {+ event.preventDefault();+ reset();+ }+ },+ [nudge, reset],+ );++ return (+ <div+ ref={ref}+ role="separator"+ aria-orientation="vertical"+ aria-label={t("Resize the reader")}+ tabIndex={0}+ onPointerDown={startDrag}+ onKeyDown={onKeyDown}+ onDoubleClick={reset}+ title={t("Drag to resize · double-click to reset")}+ className="dt-reader-resize group/resize absolute inset-y-0 right-0 z-20 flex w-3 translate-x-1/2 cursor-col-resize items-center justify-center outline-none"+ >+ {/* The visible line is thin; the hit area above is comfortable. */}+ <span+ aria-hidden+ className="h-full w-px bg-transparent transition-colors duration-150 group-hover/resize:bg-[var(--ring)]/50 group-focus-visible/resize:bg-[var(--ring)]"+ />+ <span+ aria-hidden+ className="absolute h-8 w-1 rounded-full bg-transparent transition-colors duration-150 group-hover/resize:bg-[var(--ring)]/70 group-focus-visible/resize:bg-[var(--ring)]"+ />+ </div>+ );+}diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsxnew file mode 100644index 000000000..c3a119725--- /dev/null+++ b/web/components/reading/TextUnitView.tsx@@ -0,0 +1,239 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { AnnotationItem, UnitKind } from "@/lib/reading-api";+import { getUnitText } from "@/lib/reading-api";+import { segmentTextByQuotes } from "@/lib/reading-quote-locator";+import { cleanQuote } from "@/lib/reading-selection";+import type { JumpRequest, SelectionPayload } from "./PdfDocumentView";++const COLOR_INK: Record<string, string> = {+ yellow: "250 220 90",+ green: "140 219 148",+ blue: "122 192 250",+ pink: "250 161 199",+ purple: "199 174 250",+};++export interface TextUnitViewProps {+ materialId: string;+ unit: UnitKind;+ unitCount: number;+ annotations: AnnotationItem[];+ jump: JumpRequest | null;+ highlightedAnnotationId?: string | null;+ onSelection: (payload: SelectionPayload | null) => void;+ onAnnotationClick?: (annotation: AnnotationItem) => void;+ onVisibleLocatorChange?: (locator: number) => void;+}++/**+ * One-unit-at-a-time reader for materials with no faithful raw view.+ *+ * EPUB, DOCX, slides and plain text are read from extracted text, so there is no+ * page image to overlay. Highlights are therefore anchored to the *quote* rather+ * than to geometry: the text reflows with the pane, and a stored rectangle would+ * drift away from its words. Selections made here are saved with no rects, which+ * is exactly what the Markdown export consumes.+ */+export function TextUnitView({+ materialId,+ unit,+ unitCount,+ annotations,+ jump,+ highlightedAnnotationId,+ onSelection,+ onAnnotationClick,+ onVisibleLocatorChange,+}: TextUnitViewProps) {+ const { t } = useTranslation();+ const containerRef = useRef<HTMLDivElement | null>(null);+ const [locator, setLocator] = useState(1);+ const [text, setText] = useState("");+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ setLocator(1);+ }, [materialId]);++ useEffect(() => {+ let cancelled = false;+ setLoading(true);+ setError(null);+ (async () => {+ try {+ const unitText = await getUnitText(materialId, locator);+ if (!cancelled) setText(unitText.text);+ } catch (loadError) {+ if (!cancelled) {+ setError(+ loadError instanceof Error ? loadError.message : t("Could not load this section."),+ );+ }+ } finally {+ if (!cancelled) setLoading(false);+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [materialId, locator, t]);++ useEffect(() => {+ onVisibleLocatorChange?.(locator);+ }, [locator, onVisibleLocatorChange]);++ // Responding to a command from outside React (the assistant asked the reader+ // to move), not deriving state from props — so setting state here is the+ // intended shape. The locator is also user-controlled via the arrows, which is+ // why it cannot simply be computed from `jump`.+ useEffect(() => {+ if (!jump) return;+ const target = Math.min(Math.max(1, jump.locator), unitCount);+ setLocator(target);+ // Assigned rather than animated: programmatic smooth scrolling is a silent+ // no-op in some embedded browsers, and landing at the top of the section is+ // the part that matters. CSS `scroll-behavior` supplies the easing.+ if (containerRef.current) containerRef.current.scrollTop = 0;+ }, [jump, unitCount]);++ const runs = useMemo(+ () => segmentTextByQuotes(text, annotations.filter((a) => a.locator === locator)),+ [text, annotations, locator],+ );++ const handlePointerUp = useCallback(() => {+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) {+ onSelection(null);+ return;+ }+ const range = selection.getRangeAt(0);+ if (!containerRef.current?.contains(range.commonAncestorContainer)) {+ onSelection(null);+ return;+ }+ const quote = cleanQuote(selection.toString());+ if (!quote) {+ onSelection(null);+ return;+ }+ const rects = [...range.getClientRects()];+ const last = rects[rects.length - 1];+ onSelection({+ locator,+ quote,+ // No geometry: a reflowing text view has none worth storing.+ rects: [],+ anchor: last+ ? { x: last.left + last.width / 2, y: last.top }+ : { x: 0, y: 0 },+ });+ }, [locator, onSelection]);++ const canPrev = locator > 1;+ const canNext = locator < unitCount;++ return (+ <div className="flex h-full flex-col bg-[var(--background)]">+ <div className="flex items-center justify-center gap-2 border-b border-[var(--border)] px-4 py-2">+ <button+ type="button"+ disabled={!canPrev}+ onClick={() => setLocator((current) => Math.max(1, current - 1))}+ className="inline-flex h-7 w-7 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-35 disabled:hover:bg-transparent"+ aria-label={t("Previous")}+ >+ <ChevronLeft size={15} />+ </button>+ <span className="min-w-[120px] text-center font-mono text-[11px] tabular-nums text-[var(--muted-foreground)]">+ {t("{{unit}} {{n}} of {{total}}", {+ unit: t(unitLabel(unit)),+ n: locator,+ total: unitCount,+ })}+ </span>+ <button+ type="button"+ disabled={!canNext}+ onClick={() => setLocator((current) => Math.min(unitCount, current + 1))}+ className="inline-flex h-7 w-7 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-35 disabled:hover:bg-transparent"+ aria-label={t("Next")}+ >+ <ChevronRight size={15} />+ </button>+ </div>++ <div+ ref={containerRef}+ data-reader-unit={locator}+ onMouseUp={handlePointerUp}+ className="dt-reader-scroll flex-1 overflow-y-auto overscroll-contain px-8 py-7"+ >+ {loading ? (+ <div className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 size={14} className="animate-spin" />+ {t("Loading…")}+ </div>+ ) : error ? (+ <p className="text-[12px] text-[var(--muted-foreground)]">{error}</p>+ ) : (+ <article className="mx-auto max-w-[68ch] whitespace-pre-wrap font-serif text-[15px] leading-[1.75] text-[var(--foreground)] selection:bg-[var(--primary)]/20">+ {runs.length === 0 ? (+ <span className="text-[var(--muted-foreground)]">+ {t("This section has no extractable text.")}+ </span>+ ) : (+ runs.map((run, index) =>+ run.mark ? (+ <mark+ key={index}+ title={run.mark.note || undefined}+ onClick={() => onAnnotationClick?.(run.mark as AnnotationItem)}+ className={`cursor-pointer rounded-[2px] px-[1px] text-[var(--foreground)] ${+ run.mark.annotation_id === highlightedAnnotationId+ ? "ring-2 ring-[var(--ring)]"+ : ""+ }`}+ style={{+ background:+ run.mark.kind === "underline"+ ? "transparent"+ : `rgb(${COLOR_INK[run.mark.color] ?? COLOR_INK.yellow} / 0.55)`,+ borderBottom:+ run.mark.kind === "underline"+ ? `2px solid rgb(${COLOR_INK[run.mark.color] ?? COLOR_INK.yellow})`+ : undefined,+ }}+ >+ {run.text}+ </mark>+ ) : (+ <span key={index}>{run.text}</span>+ ),+ )+ )}+ </article>+ )}+ </div>+ </div>+ );+}++/** Translatable label for a unit kind. Keys are literal so i18n can find them. */+export function unitLabel(unit: UnitKind): string {+ switch (unit) {+ case "chapter":+ return "Chapter";+ case "slide":+ return "Slide";+ case "section":+ return "Section";+ default:+ return "Page";+ }+}diff --git a/web/components/settings/SettingsHub.tsx b/web/components/settings/SettingsHub.tsxindex a24450b0b..ad9af5ce1 100644--- a/web/components/settings/SettingsHub.tsx+++ b/web/components/settings/SettingsHub.tsx@@ -2,10 +2,12 @@import { useCallback, useEffect, useMemo, useState } from "react";import Link from "next/link";+import { useRouter } from "next/navigation";import { useTranslation } from "react-i18next";-import { ChevronRight, Rocket, type LucideIcon } from "lucide-react";+import { ChevronRight, Rocket, Sparkles, type LucideIcon } from "lucide-react";import { apiFetch, apiUrl } from "@/lib/api";+import { setPendingPrompt } from "@/lib/pending-prompt";import {serviceReadiness,useSettings,@@ -34,6 +36,7 @@ type NetworkPreview = {export default function SettingsHub() {const { i18n } = useTranslation();+ const router = useRouter();const zh = i18n.language?.toLowerCase().startsWith("zh");const tr = useCallback((l: Lang) => (zh ? l.zh : l.en), [zh]);@@ -102,14 +105,35 @@ export default function SettingsHub() {})}</p></div>- <button- type="button"- onClick={startTour}- className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)]/60 px-3 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"- >- <Rocket size={13} />- {tr({ zh: "引导", en: "Tour" })}- </button>+ <div className="flex shrink-0 items-center gap-2">+ {/* Explicit entry point into the setup capability. It opens chat with+ the request already typed rather than sending it, so the user+ stays in control of what is asked. */}+ <button+ type="button"+ onClick={() => {+ setPendingPrompt(+ tr({+ zh: "帮我配置一下 DeepTutor,先看看现在缺什么。",+ en: "Help me configure DeepTutor — start by checking what's missing.",+ }),+ );+ router.push("/home");+ }}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)]/60 px-3 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"+ >+ <Sparkles size={13} />+ {tr({ zh: "让 DeepTutor 帮我配", en: "Set up with DeepTutor" })}+ </button>+ <button+ type="button"+ onClick={startTour}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)]/60 px-3 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"+ >+ <Rocket size={13} />+ {tr({ zh: "引导", en: "Tour" })}+ </button>+ </div></header><SettingsStatusPanel />diff --git a/web/components/space/NotebooksSection.tsx b/web/components/space/NotebooksSection.tsxdeleted file mode 100644index f33c104ae..000000000--- a/web/components/space/NotebooksSection.tsx+++ /dev/null@@ -1,496 +0,0 @@-"use client";--import dynamic from "next/dynamic";-import { useCallback, useEffect, useState } from "react";-import { useRouter } from "next/navigation";-import { useTranslation } from "react-i18next";-import {- ArrowRight,- Bot,- ChevronDown,- ChevronRight,- ExternalLink,- Loader2,- MessageSquare,- NotebookPen,- Pencil,- Plus,- Search,- Trash2,-} from "lucide-react";-import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";-import {- createNotebook,- deleteNotebook,- getNotebook,- listNotebooks,-} from "@/lib/notebook-api";--const MarkdownRenderer = dynamic(- () => import("@/components/common/MarkdownRenderer"),- { ssr: false },-);--interface NotebookInfo {- id: string;- name: string;- description?: string;- record_count?: number;- color?: string;- icon?: string;- updated_at?: number;-}--interface NotebookRecord {- id: string;- type: string;- title: string;- summary?: string;- user_query?: string;- output: string;- metadata?: Record<string, unknown>;- created_at?: number;-}--interface NotebookDetail extends NotebookInfo {- records: NotebookRecord[];-}--export default function NotebooksSection() {- const { t } = useTranslation();- const router = useRouter();-- const [notebooks, setNotebooks] = useState<NotebookInfo[]>([]);- const [loading, setLoading] = useState(true);- const [newName, setNewName] = useState("");- const [newDescription, setNewDescription] = useState("");- const [selectedId, setSelectedId] = useState<string | null>(null);- const [selected, setSelected] = useState<NotebookDetail | null>(null);- const [detailLoading, setDetailLoading] = useState(false);- const [expandedRecordId, setExpandedRecordId] = useState<string | null>(null);-- const loadDetail = useCallback(- async (notebookId: string, list?: NotebookInfo[]) => {- setSelectedId(notebookId);- setExpandedRecordId(null);- setDetailLoading(true);- try {- const info = (list ?? notebooks).find((n) => n.id === notebookId);- const data = await getNotebook(notebookId);- const records: NotebookRecord[] = (data.records || []).map((rec) => ({- id: String(rec.id),- type: String(rec.type),- title: rec.title,- summary: rec.summary,- user_query: rec.user_query,- output: rec.output,- metadata: rec.metadata,- created_at: rec.created_at,- }));- setSelected({- id: notebookId,- name: data.name ?? info?.name ?? "",- description: data.description ?? info?.description,- record_count: records.length,- color: data.color ?? info?.color,- icon: data.icon ?? info?.icon,- updated_at: data.updated_at ?? info?.updated_at,- records,- });- } catch {- setSelected(null);- } finally {- setDetailLoading(false);- }- },- [notebooks],- );-- const load = useCallback(async () => {- setLoading(true);- try {- const nbs = await listNotebooks();- const next: NotebookInfo[] = nbs.map((nb) => ({- id: String(nb.id),- name: nb.name,- description: nb.description,- record_count: nb.record_count ?? 0,- color: nb.color,- icon: nb.icon,- updated_at: nb.updated_at,- }));- setNotebooks(next);- if (selectedId && next.some((n) => n.id === selectedId)) {- void loadDetail(selectedId, next);- } else if (!selectedId && next.length > 0) {- void loadDetail(next[0].id, next);- } else if (selectedId && !next.some((n) => n.id === selectedId)) {- setSelectedId(null);- setSelected(null);- }- } finally {- setLoading(false);- }- }, [loadDetail, selectedId]);-- useEffect(() => {- void load();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- const handleCreate = async () => {- if (!newName.trim()) return;- await createNotebook({- name: newName.trim(),- description: newDescription.trim(),- });- setNewName("");- setNewDescription("");- await load();- };-- const handleDelete = async (notebookId: string, name: string) => {- if (!window.confirm(t('Delete notebook "{{name}}"?', { name }))) return;- await deleteNotebook(notebookId);- if (selectedId === notebookId) {- setSelectedId(null);- setSelected(null);- }- await load();- };-- const openRecord = (record: NotebookRecord) => {- const sessionId = String(record.metadata?.session_id || "");- if (!sessionId) return;- if (record.type === "chat") {- router.push(`/?session=${encodeURIComponent(sessionId)}`);- }- };-- const formatTimestamp = (value?: number) => {- if (!value) return t("Unknown time");- return new Date(value * 1000).toLocaleString();- };-- const getRecordBadge = (record: NotebookRecord) => {- switch (record.type) {- case "chat":- return {- label: t("Chat"),- color: "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300",- icon: MessageSquare,- };- case "tutorbot": {- // Partner conversations carry the partner's name in metadata so the- // badge reads as that partner's own category, not a generic "Chat".- const partnerName =- typeof record.metadata?.partner_name === "string"- ? record.metadata.partner_name.trim()- : "";- return {- label: partnerName || t("Partner"),- color:- "bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300",- icon: Bot,- };- }- case "research":- return {- label: t("Research"),- color:- "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",- icon: Search,- };- case "co_writer":- return {- label: t("Co-Writer"),- color:- "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",- icon: Pencil,- };- default:- return {- label: record.type,- color:- "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400",- icon: NotebookPen,- };- }- };-- if (loading) {- return (- <div className="flex items-center justify-center py-20">- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />- </div>- );- }-- return (- <div className="space-y-6">- <SpaceSectionHeader- icon={NotebookPen}- title={t("Notebooks")}- description={t(- "Save and organize outputs from chat, research, and Co-Writer sessions into a personal library.",- )}- meta={- <span className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">- {notebooks.length} {t("notebooks.count.suffix")}- </span>- }- />-- {/* Create notebook */}- <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">- <div className="mb-4 flex items-center gap-2">- <Plus size={15} className="text-[var(--muted-foreground)]" />- <h2 className="text-[13.5px] font-semibold text-[var(--foreground)]">- {t("Create notebook")}- </h2>- <span className="ml-1 text-[11.5px] text-[var(--muted-foreground)]">- {t("Give it a name and short description.")}- </span>- </div>-- <div className="grid gap-3 md:grid-cols-[1fr_1fr_auto]">- <input- value={newName}- onChange={(event) => setNewName(event.target.value)}- placeholder={t("Notebook name")}- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- <input- value={newDescription}- onChange={(event) => setNewDescription(event.target.value)}- placeholder={t("Description")}- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- <button- onClick={() => void handleCreate()}- disabled={!newName.trim()}- className="rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[13px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"- >- {t("Create")}- </button>- </div>- </section>-- {/* Notebook list */}- <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">- <div className="mb-4 flex items-center justify-between gap-2">- <div className="flex items-center gap-2">- <NotebookPen size={15} className="text-[var(--muted-foreground)]" />- <h2 className="text-[13.5px] font-semibold text-[var(--foreground)]">- {t("Your notebooks")}- </h2>- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] tabular-nums text-[var(--muted-foreground)]">- {notebooks.length}- </span>- </div>- <span className="text-[11.5px] text-[var(--muted-foreground)]">- {t("Click a notebook to inspect its records.")}- </span>- </div>-- <div className="grid gap-5 xl:grid-cols-[280px_minmax(0,1fr)]">- <div className="xl:sticky xl:top-8 xl:max-h-[calc(100vh-12rem)] space-y-2 overflow-y-auto pr-1">- {notebooks.map((notebook) => {- const active = selectedId === notebook.id;- return (- <div- key={notebook.id}- className={`group relative w-full rounded-xl border p-3.5 text-left transition-all ${- active- ? "border-[var(--primary)]/40 bg-[var(--primary)]/[0.08] shadow-sm"- : "border-[var(--border)] bg-[var(--background)] hover:border-[var(--foreground)]/20 hover:bg-[var(--muted)]/30"- }`}- >- <button- type="button"- onClick={() => void loadDetail(notebook.id)}- className="block w-full text-left"- >- <div className="flex items-start gap-2.5">- <div- className="mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full ring-2 ring-[var(--background)]"- style={{- backgroundColor: notebook.color || "var(--primary)",- }}- />- <div className="min-w-0 flex-1">- <div className="truncate text-[13.5px] font-semibold text-[var(--foreground)]">- {notebook.name}- </div>- <p className="mt-0.5 line-clamp-1 min-h-[1.1em] text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">- {notebook.description || (- <span className="italic text-[var(--muted-foreground)]/60">- {t("No description.")}- </span>- )}- </p>- <div className="mt-2 flex items-center justify-between gap-2 text-[10.5px] tabular-nums text-[var(--muted-foreground)]">- <span>- {notebook.record_count ?? 0} {t("records")}- </span>- <span className="truncate text-right">- {notebook.updated_at- ? formatTimestamp(notebook.updated_at)- : ""}- </span>- </div>- </div>- </div>- </button>- <button- type="button"- onClick={(event) => {- event.stopPropagation();- void handleDelete(notebook.id, notebook.name);- }}- title={t("Delete")}- className="absolute right-1.5 top-1.5 rounded-md p-1.5 text-[var(--muted-foreground)] opacity-0 transition-opacity hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] group-hover:opacity-100"- >- <Trash2 size={12} />- </button>- </div>- );- })}-- {!notebooks.length && (- <div className="rounded-xl border border-dashed border-[var(--border)] px-6 py-10 text-center text-[13px] text-[var(--muted-foreground)]">- {t("No notebooks yet. Create one to organize outputs.")}- </div>- )}- </div>-- <div className="flex min-h-[560px] flex-col overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)] p-4 xl:h-[calc(100vh-12rem)]">- {detailLoading ? (- <div className="flex min-h-[320px] items-center justify-center">- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />- </div>- ) : selected ? (- <div className="flex min-h-0 flex-1 flex-col">- <div className="mb-3 flex shrink-0 items-center justify-between gap-4 pb-3">- <div className="flex items-center gap-2.5">- <div- className="h-2.5 w-2.5 rounded-full"- style={{- backgroundColor: selected.color || "var(--primary)",- }}- />- <h3 className="text-[15px] font-semibold text-[var(--foreground)]">- {selected.name}- </h3>- {selected.description && (- <span className="text-[12px] text-[var(--muted-foreground)]">- — {selected.description}- </span>- )}- </div>- <span className="text-[11px] tabular-nums text-[var(--muted-foreground)]">- {selected.records?.length || 0} {t("records")}- </span>- </div>-- <div className="min-h-0 flex-1 overflow-y-auto pr-1">- <div className="divide-y divide-[var(--border)]">- {selected.records?.map((record) => {- const badge = getRecordBadge(record);- const BadgeIcon = badge.icon;- const expanded = expandedRecordId === record.id;- const canOpenSession =- record.type === "chat" &&- Boolean(record.metadata?.session_id);- const sessionLabel = t("Open chat session");-- return (- <div key={record.id} className="group">- <button- onClick={() =>- setExpandedRecordId(expanded ? null : record.id)- }- className="flex w-full items-center gap-3 px-1 py-3.5 text-left transition-colors hover:bg-[var(--muted)]/30"- >- <span className="shrink-0 text-[var(--muted-foreground)]">- {expanded ? (- <ChevronDown size={14} />- ) : (- <ChevronRight size={14} />- )}- </span>- <span- className={`inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-0.5 text-[11px] font-medium ${badge.color}`}- >- <BadgeIcon size={11} />- {badge.label}- </span>- <span className="min-w-0 flex-1 truncate text-[13px] font-medium text-[var(--foreground)]">- {record.title}- </span>- <span className="shrink-0 text-[11px] tabular-nums text-[var(--muted-foreground)]">- {formatTimestamp(record.created_at)}- </span>- </button>-- {expanded && (- <div className="pb-4 pl-8 pr-1">- {record.summary && (- <p className="mb-3 text-[13px] leading-6 text-[var(--foreground)]/85">- {record.summary}- </p>- )}- {record.type !== "chat" && record.user_query && (- <div className="mb-3 flex items-baseline gap-2 text-[12px]">- <span className="shrink-0 font-medium text-[var(--muted-foreground)]">- {t("Query:")}- </span>- <span className="text-[var(--foreground)]/70">- {record.user_query}- </span>- </div>- )}-- {canOpenSession && (- <button- onClick={() => openRecord(record)}- className="mb-3 inline-flex items-center gap-2 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3.5 py-2 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/8 hover:text-[var(--primary)]"- >- <ExternalLink size={13} />- {sessionLabel}- <ArrowRight size={13} />- </button>- )}-- <div className="max-h-[320px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--muted)]/30 p-3">- <MarkdownRenderer- content={record.output || ""}- variant="prose"- className="text-[12px] leading-5 text-[var(--foreground)]"- />- </div>- </div>- )}- </div>- );- })}-- {!selected.records?.length && (- <div className="px-6 py-12 text-center text-[13px] text-[var(--muted-foreground)]">- {t("This notebook is empty for now.")}- </div>- )}- </div>- </div>- </div>- ) : (- <div className="flex min-h-[320px] items-center justify-center rounded-2xl border border-dashed border-[var(--border)] text-[13px] text-[var(--muted-foreground)]">- {t("Select a notebook to inspect its saved records.")}- </div>- )}- </div>- </div>- </section>- </div>- );-}diff --git a/web/components/space/SpaceDashboard.tsx b/web/components/space/SpaceDashboard.tsxindex a217f04b6..9854cbb54 100644--- a/web/components/space/SpaceDashboard.tsx+++ b/web/components/space/SpaceDashboard.tsx@@ -82,7 +82,7 @@ const GROUPS: DashboardGroup[] = [},{key: "notebooks",- href: "/space/notebooks",+ href: "/notebook",icon: NotebookPen,title: { zh: "笔记本", en: "Notebooks" },blurb: {diff --git a/web/components/space/learning/ActivityTimeline.tsx b/web/components/space/learning/ActivityTimeline.tsxindex f633c4419..3c773f4d9 100644--- a/web/components/space/learning/ActivityTimeline.tsx+++ b/web/components/space/learning/ActivityTimeline.tsx@@ -100,7 +100,10 @@ function describe(case "mastery.assessed":return event.payload?.passed? tr(`${name} 的解释达标`, `Explanation accepted for ${name}`)- : tr(`${name} 的解释还不够`, `Explanation not yet sufficient for ${name}`);+ : tr(+ `${name} 的解释还不够`,+ `Explanation not yet sufficient for ${name}`,+ );case "path.saved":return tr("保存了路径状态", "Path state saved");default:diff --git a/web/components/space/learning/ObjectiveDetail.tsx b/web/components/space/learning/ObjectiveDetail.tsxindex 01b1711de..65346f157 100644--- a/web/components/space/learning/ObjectiveDetail.tsx+++ b/web/components/space/learning/ObjectiveDetail.tsx@@ -73,12 +73,15 @@ export function ObjectiveDetail({)}<div className="min-w-0"><div className="text-[var(--foreground)]">- {attempt.prompt || tr("(题面已不可用)", "(prompt unavailable)")}+ {attempt.prompt ||+ tr("(题面已不可用)", "(prompt unavailable)")}</div><div className="text-[var(--muted-foreground)]">{tr("你答:", "You said: ")}{attempt.answer || tr("(空)", "(blank)")}- <span className="ml-2">{formatRelative(attempt.at, zh)}</span>+ <span className="ml-2">+ {formatRelative(attempt.at, zh)}+ </span></div></div></li>@@ -91,9 +94,15 @@ export function ObjectiveDetail({<Row label={tr("错因", "Error diagnosis")}>{report.errors.map((record) => (<span key={record.id} className="mr-2">- {tr(ERROR_TYPE_CN[record.error_type] ?? record.error_type, record.error_type)}+ {tr(+ ERROR_TYPE_CN[record.error_type] ?? record.error_type,+ record.error_type,+ )}{record.retries > 0 &&- tr(` · 重试 ${record.retries} 次`, ` · ${record.retries} retries`)}+ tr(+ ` · 重试 ${record.retries} 次`,+ ` · ${record.retries} retries`,+ )}{record.status === "graduated" && tr(" · 已订正", " · cleared")}</span>))}@@ -121,12 +130,20 @@ function GateBar({ report, tr }: { report: ObjectiveReport; tr: Translate }) {<div className="flex items-baseline justify-between text-xs"><span className="text-[var(--muted-foreground)]">{report.gate === "qualitative"- ? tr("定性门槛:用自己的话讲清楚", "Qualitative gate: explain it in your own words")- : tr(`定量门槛:${thresholdPct}%`, `Quantitative gate: ${thresholdPct}%`)}+ ? tr(+ "定性门槛:用自己的话讲清楚",+ "Qualitative gate: explain it in your own words",+ )+ : tr(+ `定量门槛:${thresholdPct}%`,+ `Quantitative gate: ${thresholdPct}%`,+ )}</span><spanclassName={- report.mastered ? "text-green-500" : "text-[var(--muted-foreground)]"+ report.mastered+ ? "text-green-500"+ : "text-[var(--muted-foreground)]"}>{pct}%@@ -148,7 +165,13 @@ function GateBar({ report, tr }: { report: ObjectiveReport; tr: Translate }) {);}-function Row({ label, children }: { label: string; children: React.ReactNode }) {+function Row({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {return (<div className="text-xs"><div className="text-[var(--muted-foreground)]">{label}</div>diff --git a/web/components/space/learning/PathMap.tsx b/web/components/space/learning/PathMap.tsxindex a4e07e7ad..f910ab1fc 100644--- a/web/components/space/learning/PathMap.tsx+++ b/web/components/space/learning/PathMap.tsx@@ -113,7 +113,9 @@ export function PathMap({<spanclassName={`text-xs ${STATUS_META[kp.status].className}`}>- {zh ? STATUS_META[kp.status].cn : STATUS_META[kp.status].en}+ {zh+ ? STATUS_META[kp.status].cn+ : STATUS_META[kp.status].en}</span></button>{open &&diff --git a/web/context/ReadingContext.tsx b/web/context/ReadingContext.tsxnew file mode 100644index 000000000..8d1947c6b--- /dev/null+++ b/web/context/ReadingContext.tsx@@ -0,0 +1,231 @@+"use client";++import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from "react";+import {+ deleteAnnotation as deleteAnnotationApi,+ getMaterial,+ listAnnotations,+ saveAnnotation,+ type AnnotationDraft,+ type AnnotationItem,+ type MaterialDetail,+ type MaterialInfo,+} from "@/lib/reading-api";+import {+ setReadingMaterial,+ setReadingViewport,+} from "@/lib/reading-turn-state";++/**+ * The open document and its annotations, owned above the chat page.+ *+ * This provider lives in the workspace layout, NOT inside the chat page, and+ * that placement is the whole point: sending the first message of a session+ * changes the URL from `/home` to `/home/<id>`, which remounts the page+ * component. State held inside the reader pane died with it, so the document+ * vanished the moment the user asked their first question. The layout persists+ * across that navigation — which is exactly why `UnifiedChatProvider` sits there+ * too.+ *+ * The viewport (scroll position, selection) is deliberately NOT state: it+ * changes on every scroll tick and nothing renders from it, so it goes straight+ * into the module cell in `reading-turn-state` and is read once when a turn is+ * sent. Keeping it out of here is what stops scrolling the PDF from re-rendering+ * the message list.+ */+export interface ReadingContextValue {+ material: MaterialDetail | null;+ annotations: AnnotationItem[];+ loading: boolean;+ /** Last failure worth showing the user; cleared by `dismissError`. */+ error: string | null;+ openMaterial: (candidate: MaterialDetail | MaterialInfo) => Promise<void>;+ closeMaterial: () => void;+ /** Insert or update an annotation, optimistically. */+ saveMark: (draft: AnnotationDraft, optimistic: AnnotationItem) => Promise<void>;+ /** Remove an annotation, optimistically. */+ removeMark: (annotation: AnnotationItem) => Promise<void>;+ /** Accept a mark the assistant just made (arrives via a tool result). */+ mergeMark: (annotation: AnnotationItem) => void;+ dismissError: () => void;+ setError: (message: string) => void;+ /** Report scroll position / selection. Does not trigger a render. */+ reportViewport: (next: { locator?: number; selection?: string }) => void;+}++const noop = () => {};++const ReadingContext = createContext<ReadingContextValue>({+ material: null,+ annotations: [],+ loading: false,+ error: null,+ openMaterial: async () => {},+ closeMaterial: noop,+ saveMark: async () => {},+ removeMark: async () => {},+ mergeMark: noop,+ dismissError: noop,+ setError: noop,+ reportViewport: noop,+});++export function ReadingProvider({ children }: { children: ReactNode }) {+ const [material, setMaterial] = useState<MaterialDetail | null>(null);+ const [annotations, setAnnotations] = useState<AnnotationItem[]>([]);+ const [loading, setLoading] = useState(false);+ const [error, setErrorState] = useState<string | null>(null);+ // Guards against a slow open landing after the user opened something else.+ const openTokenRef = useRef(0);++ // Mirror the open document into the turn-state cell, which is what the chat+ // reads when it sends. One effect rather than writes scattered through the+ // mutators, so the two can never disagree.+ useEffect(() => {+ setReadingMaterial(material?.material_id ?? null);+ }, [material]);++ const openMaterial = useCallback(+ async (candidate: MaterialDetail | MaterialInfo) => {+ const token = ++openTokenRef.current;+ setLoading(true);+ setErrorState(null);+ try {+ const detail =+ "outline" in candidate+ ? (candidate as MaterialDetail)+ : await getMaterial(candidate.material_id);+ const marks = await listAnnotations(detail.material_id);+ if (token !== openTokenRef.current) return;+ setMaterial(detail);+ setAnnotations(marks);+ } catch (caught) {+ if (token !== openTokenRef.current) return;+ setErrorState(+ caught instanceof Error ? caught.message : "This document could not be opened.",+ );+ } finally {+ if (token === openTokenRef.current) setLoading(false);+ }+ },+ [],+ );++ const closeMaterial = useCallback(() => {+ // Bump the token so an open still in flight cannot resurrect the document.+ openTokenRef.current += 1;+ setMaterial(null);+ setAnnotations([]);+ setErrorState(null);+ setReadingViewport({ locator: 0, selection: "" });+ }, []);++ const saveMark = useCallback(+ async (draft: AnnotationDraft, optimistic: AnnotationItem) => {+ const materialId = material?.material_id;+ if (!materialId) return;+ // Shown immediately: waiting for a round trip before any ink appears+ // makes highlighting feel broken.+ setAnnotations((current) => [...current, optimistic]);+ try {+ const saved = await saveAnnotation(materialId, draft);+ setAnnotations((current) =>+ current.map((row) =>+ row.annotation_id === optimistic.annotation_id ? saved : row,+ ),+ );+ } catch (caught) {+ setAnnotations((current) =>+ current.filter((row) => row.annotation_id !== optimistic.annotation_id),+ );+ setErrorState(+ caught instanceof Error ? caught.message : "That annotation could not be saved.",+ );+ }+ },+ [material],+ );++ const removeMark = useCallback(+ async (annotation: AnnotationItem) => {+ const materialId = material?.material_id;+ if (!materialId) return;+ let previous: AnnotationItem[] = [];+ setAnnotations((current) => {+ previous = current;+ return current.filter((row) => row.annotation_id !== annotation.annotation_id);+ });+ try {+ await deleteAnnotationApi(materialId, annotation.annotation_id);+ } catch {+ // Put it back: pretending a failed delete succeeded would lose the mark+ // on the next reload.+ setAnnotations(previous);+ setErrorState("That annotation could not be removed.");+ }+ },+ [material],+ );++ const mergeMark = useCallback((annotation: AnnotationItem) => {+ if (!annotation?.annotation_id) return;+ setAnnotations((current) => [+ ...current.filter((row) => row.annotation_id !== annotation.annotation_id),+ annotation,+ ]);+ }, []);++ const reportViewport = useCallback(+ (next: { locator?: number; selection?: string }) => setReadingViewport(next),+ [],+ );++ const dismissError = useCallback(() => setErrorState(null), []);+ const setError = useCallback((message: string) => setErrorState(message), []);++ const value = useMemo<ReadingContextValue>(+ () => ({+ material,+ annotations,+ loading,+ error,+ openMaterial,+ closeMaterial,+ saveMark,+ removeMark,+ mergeMark,+ dismissError,+ setError,+ reportViewport,+ }),+ [+ material,+ annotations,+ loading,+ error,+ openMaterial,+ closeMaterial,+ saveMark,+ removeMark,+ mergeMark,+ dismissError,+ setError,+ reportViewport,+ ],+ );++ return <ReadingContext.Provider value={value}>{children}</ReadingContext.Provider>;+}++export function useReading(): ReadingContextValue {+ return useContext(ReadingContext);+}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex 688d30e67..d459a9a9b 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -39,6 +39,8 @@ import {} from "@/lib/stream";import { hasPendingAskUserInMessages } from "@/lib/ask-user-state";import { notify } from "@/lib/notifications";+import { forwardReaderAction } from "@/lib/reading-reader-action";+import { readingTurnFields } from "@/lib/reading-turn-state";import i18n from "i18next";import {normalizeBookReferences,@@ -1121,6 +1123,11 @@ export function UnifiedChatProvider({(runnerKey: string, event: StreamEvent) => {const runner = runnersRef.current.get(runnerKey);const effectiveKey = runner?.key || runnerKey;+ // Reading tools ask the reader to act (scroll to a locator, show a mark+ // they just made) by tagging their result metadata. Re-broadcast it as a+ // DOM event so the reader pane can listen without the chat knowing it+ // exists — the same pattern the visualize prompt bridge uses.+ forwardReaderAction(event);if (event.type === "session") {const sessionId =(event.metadata as { session_id?: string } | undefined)?.session_id ||@@ -1704,6 +1711,12 @@ export function UnifiedChatProvider({...(effectiveMasteryPathId? { mastery_path_id: effectiveMasteryPathId }: {}),+ // Immersive reading. Gated on the capability as well as on an open+ // document: the reader outlives both a mode switch and a new session, so+ // without the capability check every later turn would still carry it.+ // Read from a module cell rather than context state so scrolling the+ // reader never re-renders the chat.+ ...readingTurnFields(effectiveCapability),// Always sent (possibly ""): an explicit key is the backend's signal// to persist the value into session.preferences — "" clears back to// Default. Omitting the key would make the backend fall back to thediff --git a/web/hooks/useMasteryPathActivity.ts b/web/hooks/useMasteryPathActivity.tsindex cc6477bb5..c5c90e060 100644--- a/web/hooks/useMasteryPathActivity.ts+++ b/web/hooks/useMasteryPathActivity.ts@@ -68,7 +68,10 @@ export function mergeEventBatch(/** Where the next read should start from after consuming ``batch``. */export function latestRevision(since: number, batch: MasteryEvent[]): number {- return batch.reduce((highest, event) => Math.max(highest, event.revision), since);+ return batch.reduce(+ (highest, event) => Math.max(highest, event.revision),+ since,+ );}export function useMasteryPathActivity(@@ -96,7 +99,10 @@ export function useMasteryPathActivity(const controller = new AbortController();const poll = async () => {- if (typeof document !== "undefined" && document.visibilityState !== "visible")+ if (+ typeof document !== "undefined" &&+ document.visibilityState !== "visible"+ )return;const since =cursorRef.current.pathId === pathId ? cursorRef.current.revision : 0;diff --git a/web/hooks/useSetupSync.ts b/web/hooks/useSetupSync.tsnew file mode 100644index 000000000..dbfa6ca1b--- /dev/null+++ b/web/hooks/useSetupSync.ts@@ -0,0 +1,91 @@+"use client";++import { useEffect, useRef } from "react";++import { apiFetch, apiUrl } from "@/lib/api";+import {+ resolveResponseLanguage,+ writeStoredLanguage,+ writeStoredResponseLanguage,+ type AppLanguage,+} from "@/context/app-shell-storage";+import { setTheme, type Theme } from "@/lib/theme";+import { collectAppliedSettingIds } from "@/lib/setup-signals";+import type { StreamEvent } from "@/lib/unified-ws";++const THEMES: readonly Theme[] = ["light", "dark", "glass", "snow"];++function asTheme(value: unknown): Theme | null {+ return typeof value === "string" && (THEMES as readonly string[]).includes(value)+ ? (value as Theme)+ : null;+}++/**+ * Re-read UI preferences after the assistant changes them from within chat.+ *+ * The browser is the source of truth for language and theme: the app shell+ * reads them from localStorage and only consults the server when localStorage+ * holds nothing at all (see `AppShellContext`). That is right for a person+ * switching languages in one tab, but it means a change the assistant makes+ * on the server is invisible here — the user is told "done" while the+ * interface stays exactly as it was, which reads as a broken promise.+ *+ * So the backend's `apply_setting` tags its result with `setup_applied`, and+ * this hook treats that tag as "your cached copy is stale": it re-reads the+ * server's UI settings once and writes them through the same storage helpers a+ * manual change would use. Those helpers emit the storage events the app shell+ * already listens to, so the whole UI switches over without a reload.+ *+ * Each tool call is honoured once — replayed history and re-renders must not+ * keep overwriting a preference the user has since changed by hand.+ */+export function useSetupSync(+ messages: ReadonlyArray<{ events?: StreamEvent[] }> | undefined,+): void {+ const handledRef = useRef<Set<string>>(new Set());++ useEffect(() => {+ const fresh = collectAppliedSettingIds(messages).filter(+ (id) => !handledRef.current.has(id),+ );+ if (fresh.length === 0) return;+ for (const id of fresh) handledRef.current.add(id);++ let cancelled = false;+ void (async () => {+ try {+ const res = await apiFetch(apiUrl("/api/v1/settings/ui"));+ if (!res.ok || cancelled) return;+ const payload = (await res.json()) as {+ language?: unknown;+ response_language?: unknown;+ theme?: unknown;+ };+ if (cancelled) return;+ if (payload.language === "zh" || payload.language === "en") {+ writeStoredLanguage(payload.language);+ writeStoredResponseLanguage(+ resolveResponseLanguage(+ typeof payload.response_language === "string"+ ? payload.response_language+ : null,+ payload.language,+ ),+ );+ }+ const theme = asTheme(payload.theme);+ if (theme) setTheme(theme);+ } catch {+ // A preference that failed to refresh is a cosmetic miss: the value is+ // stored server-side and the next load picks it up.+ }+ })();++ return () => {+ cancelled = true;+ };+ }, [messages]);+}++export type { AppLanguage };diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.tsindex b5735a10b..afeeab53d 100644--- a/web/lib/notebook-api.ts+++ b/web/lib/notebook-api.ts@@ -1,11 +1,13 @@import { apiFetch, apiUrl } from "@/lib/api";-// ── Real notebook system (file-backed under data/user/workspace/notebook) ──+// ── Notebooks (file-backed under data/user/workspace/notebook) ──//-// Notebooks created in the Knowledge → Notebooks tab and consumed everywhere-// chat output is saved (SaveToNotebookModal) or referenced-// (NotebookRecordPicker) live in this system. They are distinct from the-// "Question Notebook" categories below which only track quiz entries.+// Notebooks live at /notebook and collect saved output from chat, research+// and Co-Writer (written by SaveToNotebookModal, read back by+// NotebookRecordPicker). They are a different feature from the Question+// Bank at /space/questions further down this file, which only tracks quiz+// entries — the two share the "notebook" word in their API paths for+// historical reasons, nothing else.export type NotebookRecordType =| "solve"@@ -24,6 +26,8 @@ export interface NotebookSummary {record_count?: number;created_at?: number;updated_at?: number;+ /** Set when the file is on disk but could not be parsed. */+ unreadable?: boolean;}export interface NotebookRecordItem {@@ -117,6 +121,70 @@ export async function deleteNotebookRecord(if (!response.ok) throw new Error(`Request failed: ${response.status}`);}+/**+ * Edit one record in place.+ *+ * Send only the fields being changed: the backend distinguishes an omitted+ * field from an explicit `null`, so spreading a whole record in here would+ * rewrite values the user never touched.+ */+export async function updateNotebookRecord(+ notebookId: string,+ recordId: string,+ changes: {+ title?: string;+ summary?: string;+ user_query?: string;+ output?: string;+ metadata?: Record<string, unknown>;+ kb_name?: string | null;+ },+): Promise<NotebookRecordItem> {+ const response = await apiFetch(+ apiUrl(`/api/v1/notebook/${notebookId}/records/${recordId}`),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(changes),+ },+ );+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);+ const data = (await response.json()) as { record: NotebookRecordItem };+ return data.record;+}++/** Move a record to another notebook, or copy it there under a new id. */+export async function relocateNotebookRecord(+ notebookId: string,+ recordId: string,+ targetNotebookId: string,+ mode: "move" | "copy",+): Promise<NotebookRecordItem> {+ const response = await apiFetch(+ apiUrl(`/api/v1/notebook/${notebookId}/records/${recordId}/${mode}`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ target_notebook_id: targetNotebookId }),+ },+ );+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);+ const data = (await response.json()) as { record: NotebookRecordItem };+ return data.record;+}++/** Fetch a whole notebook rendered as one Markdown document. */+export async function exportNotebookMarkdown(+ notebookId: string,+): Promise<string> {+ const response = await apiFetch(+ apiUrl(`/api/v1/notebook/${notebookId}/export`),+ { cache: "no-store" },+ );+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);+ return await response.text();+}+// ── Question notebook (quiz entries + categories) ─────────────────export interface NotebookAnswerImage {diff --git a/web/lib/pdfjs-loader.ts b/web/lib/pdfjs-loader.tsnew file mode 100644index 000000000..61dc5808e--- /dev/null+++ b/web/lib/pdfjs-loader.ts@@ -0,0 +1,55 @@+/**+ * Single place pdf.js is loaded and configured.+ *+ * The library and its worker are ~1.5 MB together, so they are imported+ * dynamically: a user who never opens the reader never downloads them. The+ * promise is memoised, so the many pages of one document share one module+ * instance and one worker.+ *+ * The worker URL is built with `new URL(..., import.meta.url)` rather than a+ * hand-written public path, which lets the bundler fingerprint and serve the+ * worker file itself — a hard-coded `/pdf.worker.mjs` would have to be copied+ * into `public/` by a build step and would break the moment the version bumps.+ */++import type * as PdfjsModule from "pdfjs-dist";++export type Pdfjs = typeof PdfjsModule;+export type PdfDocument = Awaited<+ ReturnType<Pdfjs["getDocument"]>["promise"]+>;+export type PdfPageProxy = Awaited<ReturnType<PdfDocument["getPage"]>>;++let pending: Promise<Pdfjs> | null = null;++export function loadPdfjs(): Promise<Pdfjs> {+ if (pending) return pending;+ pending = (async () => {+ const pdfjs = await import("pdfjs-dist");+ if (!pdfjs.GlobalWorkerOptions.workerSrc) {+ pdfjs.GlobalWorkerOptions.workerSrc = new URL(+ "pdfjs-dist/build/pdf.worker.min.mjs",+ import.meta.url,+ ).toString();+ }+ return pdfjs;+ })().catch((error) => {+ // Do not cache a failure: a transient chunk-load error must not disable the+ // reader for the rest of the session.+ pending = null;+ throw error;+ });+ return pending;+}++/**+ * Device-pixel scale for crisp canvas rendering, bounded.+ *+ * Uncapped DPR on a 3× phone screen makes a full-page canvas large enough to be+ * dropped by mobile Safari's canvas memory limit, which shows as a blank page+ * rather than an error — hence the cap.+ */+export function outputScale(): number {+ if (typeof window === "undefined") return 1;+ return Math.min(2, Math.max(1, window.devicePixelRatio || 1));+}diff --git a/web/lib/pending-prompt.ts b/web/lib/pending-prompt.tsnew file mode 100644index 000000000..8cd955aae--- /dev/null+++ b/web/lib/pending-prompt.ts@@ -0,0 +1,36 @@+/**+ * Hand a starting message from one page to the chat composer on another.+ *+ * Used by the Settings hub's "let DeepTutor configure this" entry point: the+ * button navigates to chat and the composer opens with the request already+ * typed, so the user reads and sends it rather than arriving at an empty box+ * wondering what to say.+ *+ * sessionStorage rather than a query parameter on purpose — the chat route is+ * a catch-all segment, and reading search params there would pull the whole+ * page into a client-side bailout for what is a one-shot hand-off. It is also+ * consumed exactly once: a refresh must not retype a message the user already+ * sent or deliberately cleared.+ */+const PENDING_PROMPT_KEY = "deeptutor.pendingPrompt";++export function setPendingPrompt(text: string): void {+ if (typeof window === "undefined") return;+ try {+ window.sessionStorage.setItem(PENDING_PROMPT_KEY, text);+ } catch {+ // Private-mode browsers reject sessionStorage; the user still lands on+ // chat, just with an empty composer.+ }+}++export function consumePendingPrompt(): string {+ if (typeof window === "undefined") return "";+ try {+ const value = window.sessionStorage.getItem(PENDING_PROMPT_KEY);+ if (value) window.sessionStorage.removeItem(PENDING_PROMPT_KEY);+ return value ?? "";+ } catch {+ return "";+ }+}diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.tsnew file mode 100644index 000000000..f999de331--- /dev/null+++ b/web/lib/reading-api.ts@@ -0,0 +1,239 @@+import { apiFetch, apiUrl } from "@/lib/api";++// ── Immersive reading (materials under data/user/workspace/reading) ──+//+// A *material* is a document the user reads in the reader pane. It is cut once+// into **units** and addressed by **locator** — a 1-indexed unit number that+// means page / chapter / slide / section depending on the source format. The+// unit word is carried on the material so the UI can say "page 12" or+// "chapter 3" without ever branching on the file type itself.++export type UnitKind = "page" | "chapter" | "slide" | "section";+export type AnnotationKind = "highlight" | "underline" | "note";+export type ExportFormat = "auto" | "pdf" | "markdown";++/** Palette offered by the annotation toolbar; mirrored server-side. */+export const ANNOTATION_COLORS = [+ "yellow",+ "green",+ "blue",+ "pink",+ "purple",+] as const;+export type AnnotationColor = (typeof ANNOTATION_COLORS)[number];++export interface MaterialInfo {+ material_id: string;+ filename: string;+ unit: UnitKind;+ unit_count: number;+ mime: string;+ title: string;+ byte_size: number;+ char_count: number;+ created_at: number;+ /** True when the original bytes can be rendered faithfully (PDF today). */+ has_raw_view: boolean;+ annotation_count: number;+}++export interface OutlineRow {+ locator: number;+ title: string;+ level: number;+ synthesised: boolean;+}++export interface MaterialDetail extends MaterialInfo {+ outline: OutlineRow[];+ outline_text: string;+}++/**+ * A rectangle normalised to its unit box: 0..1, origin top-left, y downwards.+ *+ * Normalised because the reader re-renders at whatever zoom and width the pane+ * happens to have; storing pixels would pin a highlight to one viewport. The+ * same space is what the PDF export expects, so no second transform is needed+ * on the way out.+ */+export type NormalisedRect = [number, number, number, number];++export interface AnnotationItem {+ annotation_id: string;+ locator: number;+ kind: AnnotationKind;+ color: string;+ quote: string;+ note: string;+ rects: NormalisedRect[];+ /** "user" or "assistant" — the model can annotate too. */+ author: string;+ created_at: number;+ updated_at: number;+}++export interface AnnotationDraft {+ annotation_id?: string;+ locator: number;+ kind?: AnnotationKind;+ color?: string;+ quote?: string;+ note?: string;+ rects?: NormalisedRect[];+}++export interface SupportedFormats {+ extensions: string[];+ max_bytes: number;+ raw_view_extensions: string[];+}++const BASE = "/api/v1/reading";++/** Surface the server's own message — it explains what the user can do next. */+async function unwrap<T>(response: Response): Promise<T> {+ if (response.ok) return (await response.json()) as T;+ let detail = `Request failed: ${response.status}`;+ try {+ const body = (await response.json()) as { detail?: unknown };+ if (typeof body?.detail === "string" && body.detail) detail = body.detail;+ } catch {+ // Non-JSON error body (a proxy page, say) — keep the status line.+ }+ throw new Error(detail);+}++export async function getSupportedFormats(): Promise<SupportedFormats> {+ return unwrap(await apiFetch(apiUrl(`${BASE}/supported-formats`)));+}++export async function listMaterials(): Promise<MaterialInfo[]> {+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials`), { cache: "no-store" }),+ );+}++export async function uploadMaterial(file: File): Promise<MaterialDetail> {+ const form = new FormData();+ form.append("file", file, file.name);+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials`), { method: "POST", body: form }),+ );+}++export async function getMaterial(+ materialId: string,+): Promise<MaterialDetail> {+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}`), {+ cache: "no-store",+ }),+ );+}++export async function deleteMaterial(materialId: string): Promise<void> {+ await unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}`), {+ method: "DELETE",+ }),+ );+}++export async function getUnitText(+ materialId: string,+ locator: number,+): Promise<{ locator: number; unit: UnitKind; text: string }> {+ return unwrap(+ await apiFetch(+ apiUrl(`${BASE}/materials/${materialId}/units/${locator}`),+ { cache: "no-store" },+ ),+ );+}++/** URL of the original bytes. Served with Range support so pdf.js can stream. */+export function rawMaterialUrl(materialId: string): string {+ return apiUrl(`${BASE}/materials/${materialId}/raw`);+}++export async function listAnnotations(+ materialId: string,+): Promise<AnnotationItem[]> {+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/annotations`), {+ cache: "no-store",+ }),+ );+}++export async function saveAnnotation(+ materialId: string,+ draft: AnnotationDraft,+): Promise<AnnotationItem> {+ return unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/annotations`), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(draft),+ }),+ );+}++export async function deleteAnnotation(+ materialId: string,+ annotationId: string,+): Promise<void> {+ await unwrap(+ await apiFetch(+ apiUrl(`${BASE}/materials/${materialId}/annotations/${annotationId}`),+ { method: "DELETE" },+ ),+ );+}++/**+ * Fetch the annotated export as a blob.+ *+ * Deliberately a fetch rather than a plain link: the download must carry the+ * session credentials `apiFetch` attaches, and a bare `<a href>` would not.+ */+export async function fetchExport(+ materialId: string,+ fmt: ExportFormat = "auto",+): Promise<{ blob: Blob; filename: string }> {+ const response = await apiFetch(+ apiUrl(`${BASE}/materials/${materialId}/export?fmt=${fmt}`),+ );+ if (!response.ok) {+ await unwrap(response);+ throw new Error(`Export failed: ${response.status}`);+ }+ return {+ blob: await response.blob(),+ filename: filenameFromDisposition(response.headers.get("content-disposition")),+ };+}++/**+ * Parse a filename out of a Content-Disposition header.+ *+ * Prefers the RFC 5987 `filename*` form so non-ASCII titles (a Chinese paper,+ * say) keep their name instead of arriving as the stripped ASCII fallback.+ */+export function filenameFromDisposition(+ header: string | null,+ fallback = "export",+): string {+ if (!header) return fallback;+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(header);+ if (encoded?.[1]) {+ try {+ return decodeURIComponent(encoded[1].trim());+ } catch {+ // Malformed percent-encoding — fall through to the plain form.+ }+ }+ const plain = /filename="?([^";]+)"?/i.exec(header);+ return plain?.[1]?.trim() || fallback;+}diff --git a/web/lib/reading-citations.ts b/web/lib/reading-citations.tsnew file mode 100644index 000000000..6d1458d92--- /dev/null+++ b/web/lib/reading-citations.ts@@ -0,0 +1,264 @@+/**+ * Locator citations in assistant prose: `[p.12]`, `[p.12,17]`, `[p.12-14]`.+ *+ * The model is asked for that one form regardless of what the document's units+ * are called, so there is a single pattern to parse and the UI decides whether+ * to *show* "page 12" or "chapter 12" from the material's own unit word.+ *+ * ## Why rewrite to a link instead of rendering a component+ *+ * Citations become ordinary Markdown links (`[p.12](#dt-locator-12)`), which the+ * existing renderer turns into ordinary anchors; the reader then catches clicks+ * with one delegated listener. That keeps this feature out of the shared+ * Markdown renderer entirely — no new props, no new branches in code that every+ * other chat surface also runs.+ *+ * ## Why code spans are excluded first+ *+ * A bracketed token inside code is code, not a citation. DeepTutor has already+ * shipped the bug where `[0]` in a snippet was linkified into a citation anchor+ * (issue #468), so this parser masks fenced blocks and inline code *before*+ * matching rather than hoping the pattern is narrow enough.+ */++/** One parsed citation and the locators it points at. */+export interface LocatorCitation {+ /** Exact source text, e.g. `"[p.12,17]"`. */+ raw: string;+ /** Locators in ascending order, de-duplicated. */+ locators: number[];+ /** Character offsets of `raw` within the input. */+ start: number;+ end: number;+}++/** Anchor prefix the reader listens for. */+export const LOCATOR_HREF_PREFIX = "#dt-locator-";++/** Largest locator span a single `[p.a-b]` may expand to. */+const MAX_RANGE_SPAN = 40;++// `[p.` then digits with , - – separators, then `]` — but not when followed by+// `(`, which would mean it is already a Markdown link's label.+const CITATION = /\[p\.\s*(\d[\d\s,–—-]*)\]/gi;++/**+ * Character ranges occupied by fenced blocks or inline code.+ *+ * Fences are matched first and their interiors skipped wholesale, so a stray+ * backtick inside a fence cannot desynchronise the inline-code scan.+ */+export function codeRanges(text: string): Array<[number, number]> {+ const ranges: Array<[number, number]> = [];+ const fence = /(^|\n)[ \t]*(`{3,}|~{3,})[^\n]*\n?[\s\S]*?(?:\n[ \t]*\2[ \t]*(?=\n|$)|$)/g;+ let match: RegExpExecArray | null;+ while ((match = fence.exec(text)) !== null) {+ ranges.push([match.index, match.index + match[0].length]);+ }++ const inFence = (index: number) =>+ ranges.some(([from, to]) => index >= from && index < to);++ // Inline code: the shortest run of backticks that closes with the same count.+ const inline = /(`+)(?:[^`]|(?!\1)`)*?\1/g;+ while ((match = inline.exec(text)) !== null) {+ if (!inFence(match.index)) {+ ranges.push([match.index, match.index + match[0].length]);+ }+ }+ return ranges.sort((a, b) => a[0] - b[0]);+}++function parseLocatorList(body: string): number[] {+ const found = new Set<number>();+ for (const chunk of body.split(",")) {+ const piece = chunk.trim();+ if (!piece) continue;+ const range = /^(\d+)\s*[–—-]\s*(\d+)$/.exec(piece);+ if (range) {+ let from = Number(range[1]);+ let to = Number(range[2]);+ if (from > to) [from, to] = [to, from];+ for (let n = from; n <= Math.min(to, from + MAX_RANGE_SPAN); n += 1) {+ if (n >= 1) found.add(n);+ }+ continue;+ }+ const single = /^(\d+)$/.exec(piece);+ if (single) {+ const n = Number(single[1]);+ if (n >= 1) found.add(n);+ }+ }+ return [...found].sort((a, b) => a - b);+}+++/**+ * Words a model uses when it names a location in prose, per unit kind.+ *+ * Matched case-insensitively and in both scripts, because the answer's language+ * follows the user's, not the document's.+ */+const SPELLED_OUT_LOCATION = new RegExp(+ "(?:" ++ // English: "page 3", "on pages 3", "chapter 3", "slide 3", "section 3"+ "(?:pages?|chapters?|slides?|sections?)\\s*(\\d+)" ++ "|" ++ // Chinese: "第 3 页", "第3章", "第 3 节", "第3张幻灯片"+ "第\\s*(\\d+)\\s*(?:页|章|节|张幻灯片|张)" ++ ")",+ "gi",+);++/** How far back from a citation we look for the phrase it duplicates. */+const ABSORB_WINDOW = 90;++interface Absorption {+ /** Character range of the prose phrase to turn into the link. */+ start: number;+ end: number;+ /** The phrase itself, kept verbatim so the sentence still reads naturally. */+ label: string;+}++/**+ * Find a spelled-out location just before *citation* that names the same unit.+ *+ * Models answering "where is it?" naturally write the location into the+ * sentence — "is located on page 3 of the document [p.3]" — leaving the marker+ * as a second, redundant copy. Rather than fight that with prompt rules (which+ * a fast model ignores) or delete the words (which breaks the sentence), the+ * phrase itself becomes the link and the marker is dropped. One link, in the+ * place the reader is already looking.+ */+function findAbsorbablePhrase(+ text: string,+ citation: LocatorCitation,+ skip: Array<[number, number]>,+): Absorption | null {+ // Only for single-locator citations: "[p.12,17]" has no one phrase to absorb.+ if (citation.locators.length !== 1) return null;+ const locator = citation.locators[0];++ const from = Math.max(0, citation.start - ABSORB_WINDOW);+ const window = text.slice(from, citation.start);+ // Never reach across a sentence boundary or a link that is already there.+ const lastBreak = Math.max(+ window.lastIndexOf("."),+ window.lastIndexOf("。"),+ window.lastIndexOf("\n"),+ window.lastIndexOf(")"),+ window.lastIndexOf("]"),+ );+ const searchFrom = from + (lastBreak >= 0 ? lastBreak + 1 : 0);+ const searchable = text.slice(searchFrom, citation.start);++ let best: Absorption | null = null;+ SPELLED_OUT_LOCATION.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = SPELLED_OUT_LOCATION.exec(searchable)) !== null) {+ const value = Number(match[1] ?? match[2]);+ if (value !== locator) continue;+ const start = searchFrom + match.index;+ const end = start + match[0].length;+ if (skip.some(([lo, hi]) => start < hi && end > lo)) continue;+ // Keep the LAST match: it is the one adjacent to the citation.+ best = { start, end, label: match[0] };+ }+ return best;+}++/** Every citation in *text*, skipping code spans. */+export function findLocatorCitations(text: string): LocatorCitation[] {+ if (!text) return [];+ const skip = codeRanges(text);+ const masked = (index: number) =>+ skip.some(([from, to]) => index >= from && index < to);++ const out: LocatorCitation[] = [];+ CITATION.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = CITATION.exec(text)) !== null) {+ const start = match.index;+ if (masked(start)) continue;+ // Already a Markdown link label — leave it alone.+ if (text[start + match[0].length] === "(") continue;+ const locators = parseLocatorList(match[1]);+ if (!locators.length) continue;+ out.push({+ raw: match[0],+ locators,+ start,+ end: start + match[0].length,+ });+ }+ return out;+}++/**+ * Rewrite citations into Markdown links the reader can intercept.+ *+ * `maxLocator` (the material's unit count) drops references the document cannot+ * have: a link to page 900 of a 12-page PDF would be a dead end, and leaving it+ * as plain text is a more honest signal than a link that goes nowhere.+ */+export function linkifyLocatorCitations(+ text: string,+ options: { maxLocator?: number } = {},+): string {+ const citations = findLocatorCitations(text);+ if (!citations.length) return text;+ const { maxLocator } = options;++ const skip = codeRanges(text);+ let out = "";+ let cursor = 0;+ for (const citation of citations) {+ const locators =+ typeof maxLocator === "number" && maxLocator > 0+ ? citation.locators.filter((n) => n <= maxLocator)+ : citation.locators;+ if (!locators.length) {+ out += text.slice(cursor, citation.end);+ cursor = citation.end;+ continue;+ }++ const href = `${LOCATOR_HREF_PREFIX}${locators[0]}`;+ const absorbed =+ locators.length === citation.locators.length+ ? findAbsorbablePhrase(text, citation, skip)+ : null;++ if (absorbed && absorbed.start >= cursor) {+ // Link the phrase, then skip the marker and the whitespace that led to it+ // so the sentence closes cleanly: "…located on [page 3](…) of the+ // document." rather than "…of the document ."+ out += text.slice(cursor, absorbed.start);+ out += `[${absorbed.label}](${href})`;+ const between = text.slice(absorbed.end, citation.start);+ out += between.replace(/\s+$/, "");+ cursor = citation.end;+ continue;+ }++ out += text.slice(cursor, citation.start);+ out += `[p.${locators.join(",")}](${href})`;+ cursor = citation.end;+ }+ return out + text.slice(cursor);+}++/** Locator encoded in an anchor href, or null when it is a different link. */+export function locatorFromHref(href: string | null | undefined): number | null {+ if (!href || !href.startsWith(LOCATOR_HREF_PREFIX)) return null;+ const parsed = Number(href.slice(LOCATOR_HREF_PREFIX.length));+ return Number.isInteger(parsed) && parsed >= 1 ? parsed : null;+}++/** Human label for a locator, using the material's own unit word. */+export function locatorLabel(unit: string, locator: number): string {+ const word = unit || "page";+ return `${word} ${locator}`;+}diff --git a/web/lib/reading-quote-locator.ts b/web/lib/reading-quote-locator.tsnew file mode 100644index 000000000..783b1cb17--- /dev/null+++ b/web/lib/reading-quote-locator.ts@@ -0,0 +1,298 @@+/**+ * Find a quote inside a rendered text layer, tolerantly.+ *+ * This is what turns "the model cited this sentence" into a highlight on the+ * page. It cannot be a plain `indexOf`: a pdf.js text layer splits a line into+ * many spans and preserves the PDF's own hard wraps, so the quote the model+ * copied out of the *extracted text* rarely matches the DOM text character for+ * character.+ *+ * The approach is to build a whitespace-collapsed projection of the layer's text+ * together with a map back to (segment, offset) positions, search in the+ * projection, then translate the hit back. Punctuation is softened the same way+ * the backend's matcher softens it, so curly quotes and dashes do not break a+ * match that a human would call identical.+ *+ * Pure over an array of segment strings, so the search is testable without a+ * DOM; the caller supplies the segments and maps the result back onto nodes.+ */++export interface QuotePosition {+ /** Index into the segments array. */+ segment: number;+ /** Character offset within that segment. */+ offset: number;+}++export interface QuoteRange {+ start: QuotePosition;+ end: QuotePosition;+ /** Which matching pass found it — callers may want to warn on "loose". */+ mode: "exact" | "collapsed" | "softened";+}++/** Punctuation that commonly differs between a PDF and a copied quote. */+const SOFT_CHARS = new Set([+ "‘", "’", "“", "”", "–", "—", "-", "_", "'", '"', "`",+ ",", ",", "、", ";", ";", ":", ":", ".", "。",+ "!", "!", "?", "?", "(", ")", "(", ")",+ "[", "]", "【", "】",+]);++interface Projection {+ text: string;+ /** For each character in `text`, where it came from. */+ origin: QuotePosition[];+}++interface ProjectOptions {+ soften: boolean;+ /**+ * Treat each segment boundary as whitespace.+ *+ * pdf.js splits a line into spans at visual breaks, and a span usually does+ * NOT end with a space — so `"…explicitly. Sinusoidal"` followed by+ * `"positional encodings…"` concatenates to `"Sinusoidalpositional"` and a+ * quote containing the space between them can never match. Inserting the+ * boundary space fixes Latin text; for CJK, which has no inter-word spaces,+ * the inserted space is what *breaks* a match. Neither choice is right for+ * both scripts, so both projections are tried.+ */+ joinWithSpace: boolean;+}++function project(segments: string[], options: ProjectOptions): Projection {+ const { soften, joinWithSpace } = options;+ let text = "";+ const origin: QuotePosition[] = [];+ let pendingSpace = false;++ for (let segment = 0; segment < segments.length; segment += 1) {+ if (joinWithSpace && segment > 0 && text.length > 0) pendingSpace = true;+ const value = segments[segment] ?? "";+ for (let offset = 0; offset < value.length; offset += 1) {+ const char = value[offset];+ if (/\s/.test(char)) {+ // Collapse any whitespace run to a single space, emitted lazily so a+ // trailing run never appears in the projection.+ if (text.length > 0) pendingSpace = true;+ continue;+ }+ if (soften && SOFT_CHARS.has(char)) continue;+ if (pendingSpace) {+ text += " ";+ origin.push({ segment, offset });+ pendingSpace = false;+ }+ text += char.toLowerCase();+ origin.push({ segment, offset });+ }+ }+ return { text, origin };+}++function projectQuote(quote: string, options: ProjectOptions): string {+ return project([quote], options).text;+}++function rangeFrom(+ projection: Projection,+ index: number,+ length: number,+ mode: QuoteRange["mode"],+): QuoteRange | null {+ const start = projection.origin[index];+ const lastChar = projection.origin[index + length - 1];+ if (!start || !lastChar) return null;+ return {+ start,+ // End offsets are exclusive, matching DOM Range semantics.+ end: { segment: lastChar.segment, offset: lastChar.offset + 1 },+ mode,+ };+}++/**+ * Locate *quote* within *segments*.+ *+ * Escalates through three passes and reports which one matched, so a caller can+ * treat a softened hit as lower-confidence. Returns null when even the softened+ * pass fails — better no highlight than a highlight on the wrong sentence.+ */+export function findQuoteRange(+ segments: string[],+ quote: string,+): QuoteRange | null {+ const needleRaw = (quote || "").trim();+ if (!needleRaw || !segments.length) return null;++ // Escalate cheapest-first, and try both boundary treatments at each strength+ // before loosening further: a Latin quote needs the joining space, a CJK one+ // needs its absence, and getting a strict match under either beats a loose+ // match under the other.+ const passes: Array<{ soften: boolean; joinWithSpace: boolean; mode: QuoteRange["mode"] }> = [+ { soften: false, joinWithSpace: true, mode: "collapsed" },+ { soften: false, joinWithSpace: false, mode: "collapsed" },+ { soften: true, joinWithSpace: true, mode: "softened" },+ { soften: true, joinWithSpace: false, mode: "softened" },+ ];++ for (const pass of passes) {+ const haystack = project(segments, pass);+ const needle = projectQuote(needleRaw, pass);+ if (!needle) continue;+ const at = haystack.text.indexOf(needle);+ if (at >= 0) return rangeFrom(haystack, at, needle.length, pass.mode);+ }++ // Last resort: the longest prefix of the quote that does appear. A model often+ // quotes a sentence and then keeps writing its own words, so the head is the+ // reliable part — but a *fixed* head length is not, because it may itself run+ // past where the document stops matching. Binary search works because prefix+ // matching is monotonic: if a prefix of length L is present, so is every+ // shorter one.+ for (const joinWithSpace of [true, false]) {+ const haystack = project(segments, { soften: true, joinWithSpace });+ const needle = projectQuote(needleRaw, { soften: true, joinWithSpace });+ const longest = longestPrefixMatch(haystack.text, needle);+ if (longest) {+ return rangeFrom(haystack, longest.at, longest.length, "softened");+ }+ }+ return null;+}++/** Shortest prefix worth highlighting, and the share of the quote it must cover. */+const MIN_PREFIX_CHARS = 12;+const MIN_PREFIX_SHARE = 0.25;++function longestPrefixMatch(+ haystack: string,+ needle: string,+): { at: number; length: number } | null {+ const floor = Math.max(+ MIN_PREFIX_CHARS,+ Math.ceil(needle.length * MIN_PREFIX_SHARE),+ );+ if (needle.length < floor) return null;++ let low = floor;+ let high = needle.length;+ let best: { at: number; length: number } | null = null;+ while (low <= high) {+ const mid = (low + high) >> 1;+ const at = haystack.indexOf(needle.slice(0, mid));+ if (at >= 0) {+ best = { at, length: mid };+ low = mid + 1;+ } else {+ high = mid - 1;+ }+ }+ return best;+}++/**+ * Split plain unit text into marked and unmarked runs.+ *+ * Used by the text view (non-PDF materials), where highlights cannot be+ * geometric: the text reflows with the pane width, so a stored rectangle would+ * drift. Anchoring on the quote instead makes a mark reflow-proof — and it is+ * the same anchor the Markdown export uses, so the two always agree.+ *+ * Overlapping marks are resolved by taking the earliest, longest one and+ * skipping any that would intersect it; a nested highlight would otherwise+ * produce nested `<mark>` runs whose colours multiply into mud.+ */+export function segmentTextByQuotes<T extends { quote: string }>(+ text: string,+ marks: T[],+): Array<{ text: string; mark: T | null }> {+ if (!text) return [];+ const found: Array<{ start: number; end: number; mark: T }> = [];+ const haystack = text.toLowerCase();++ for (const mark of marks) {+ const needle = (mark.quote || "").trim().toLowerCase();+ if (needle.length < 2) continue;+ let at = haystack.indexOf(needle);+ if (at < 0) {+ // Fall back to whitespace-collapsed matching for a quote that was copied+ // out of a re-wrapped rendering of this same text.+ const collapsed = needle.replace(/\s+/g, " ");+ at = haystack.replace(/\s+/g, " ").indexOf(collapsed);+ if (at < 0) continue;+ // The offset is in collapsed space and cannot index `text`; skip rather+ // than mark the wrong run.+ continue;+ }+ found.push({ start: at, end: at + needle.length, mark });+ }++ found.sort((a, b) => a.start - b.start || b.end - a.end);+ const kept: typeof found = [];+ for (const candidate of found) {+ if (kept.some((k) => candidate.start < k.end && candidate.end > k.start)) {+ continue;+ }+ kept.push(candidate);+ }++ const runs: Array<{ text: string; mark: T | null }> = [];+ let cursor = 0;+ for (const range of kept) {+ if (range.start > cursor) {+ runs.push({ text: text.slice(cursor, range.start), mark: null });+ }+ runs.push({ text: text.slice(range.start, range.end), mark: range.mark });+ cursor = range.end;+ }+ if (cursor < text.length) {+ runs.push({ text: text.slice(cursor), mark: null });+ }+ return runs;+}++/** Collect the text nodes of a rendered layer, in document order. */+export function collectTextNodes(container: Element): Text[] {+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);+ const nodes: Text[] = [];+ let current = walker.nextNode();+ while (current) {+ nodes.push(current as Text);+ current = walker.nextNode();+ }+ return nodes;+}++/**+ * Build a DOM Range for *quote* inside *container*, or null.+ *+ * Kept separate from {@link findQuoteRange} so the search logic stays pure and+ * this adapter stays trivial enough to eyeball.+ */+export function domRangeForQuote(+ container: Element,+ quote: string,+): Range | null {+ const nodes = collectTextNodes(container);+ if (!nodes.length) return null;+ const found = findQuoteRange(+ nodes.map((node) => node.textContent ?? ""),+ quote,+ );+ if (!found) return null;++ const startNode = nodes[found.start.segment];+ const endNode = nodes[found.end.segment];+ if (!startNode || !endNode) return null;++ const range = document.createRange();+ try {+ range.setStart(startNode, Math.min(found.start.offset, startNode.length));+ range.setEnd(endNode, Math.min(found.end.offset, endNode.length));+ } catch {+ return null;+ }+ return range.collapsed ? null : range;+}diff --git a/web/lib/reading-reader-action.ts b/web/lib/reading-reader-action.tsnew file mode 100644index 000000000..7ed796369--- /dev/null+++ b/web/lib/reading-reader-action.ts@@ -0,0 +1,118 @@+/**+ * Bridge from a reading tool's result to the reader pane.+ *+ * The reading tools signal UI intent on their `ToolResult.metadata` under+ * `reader_action` — `goto` to move the view, `annotate` to surface a mark the+ * assistant just made. The chat forwards that as a DOM event and the reader pane+ * listens; neither side imports the other, so the chat needs no knowledge of the+ * reader and vice versa (the same seam the visualize-prompt bridge uses).+ *+ * The extraction is defensive because the metadata crosses the wire: anything+ * unrecognised is dropped rather than dispatched.+ */++/** Event name the reader pane listens on. */+export const READER_ACTION_EVENT = "dt:reader-action";+/**+ * Fired once a turn finishes, saying whether it ever moved the reader.+ *+ * The model is asked to call `reader_goto` for each passage it discusses, and+ * mostly does — but not always, and a turn that cites `[p.5]` while the reader+ * sits on page 1 looks broken regardless of whose fault it is. The pane uses+ * this to fall back to the first citation in the answer, so the view follows the+ * *answer* rather than the model's diligence.+ */+export const READER_TURN_END_EVENT = "dt:reader-turn-end";++/** Turns that have already moved the reader, so the fallback stays quiet. */+const movedTurns = new Set<string>();+/** Bound so a long session cannot accumulate ids forever. */+const MAX_TRACKED_TURNS = 64;++function rememberMoved(turnId: string): void {+ if (!turnId) return;+ if (movedTurns.size >= MAX_TRACKED_TURNS) movedTurns.clear();+ movedTurns.add(turnId);+}++export interface ReaderActionPayload {+ material_id?: string;+ reader_action: "goto" | "annotate";+ locator?: number;+ quote?: string;+ annotation?: Record<string, unknown>;+}++/**+ * Extract a reader action from a stream event's metadata, or null.+ *+ * A tool's own `ToolResult.metadata` does not arrive at the top level of the+ * event: the dispatcher nests it under `tool_metadata`, alongside its own trace+ * keys (see `core/agentic/tool_dispatch.py`). Reading the top level only —+ * which looks right and type-checks fine — silently finds nothing, so the+ * reader never moves. The top level is still checked as a fallback in case a+ * caller emits the event directly.+ */+export function readerActionFrom(event: {+ type?: string;+ metadata?: unknown;+}): ReaderActionPayload | null {+ if (event?.type !== "tool_result") return null;+ const metadata = event.metadata;+ if (!metadata || typeof metadata !== "object") return null;++ const outer = metadata as Record<string, unknown>;+ const nested = outer.tool_metadata;+ const raw = (+ nested && typeof nested === "object" ? nested : outer+ ) as Record<string, unknown>;+ const action = raw.reader_action;+ if (action !== "goto" && action !== "annotate") return null;++ const payload: ReaderActionPayload = { reader_action: action };+ if (typeof raw.material_id === "string" && raw.material_id) {+ payload.material_id = raw.material_id;+ }+ const locator = Number(raw.locator);+ if (Number.isInteger(locator) && locator >= 1) payload.locator = locator;+ if (typeof raw.quote === "string" && raw.quote) payload.quote = raw.quote;+ if (raw.annotation && typeof raw.annotation === "object") {+ payload.annotation = raw.annotation as Record<string, unknown>;+ }+ return payload;+}++/**+ * Dispatch whatever *event* means for the reader.+ *+ * Called for every stream event; almost all of them are neither a reader action+ * nor a turn ending, and cost one string comparison.+ */+export function forwardReaderAction(event: {+ type?: string;+ metadata?: unknown;+ turn_id?: string;+}): void {+ if (typeof window === "undefined") return;+ const turnId = String(event?.turn_id || "");++ const payload = readerActionFrom(event);+ if (payload) {+ if (payload.reader_action === "goto") rememberMoved(turnId);+ window.dispatchEvent(new CustomEvent(READER_ACTION_EVENT, { detail: payload }));+ return;+ }++ if (event?.type === "done") {+ const moved = turnId ? movedTurns.has(turnId) : false;+ movedTurns.delete(turnId);+ window.dispatchEvent(+ new CustomEvent(READER_TURN_END_EVENT, { detail: { moved } }),+ );+ }+}++/** Test seam: forget which turns have moved the reader. */+export function resetReaderActionTracking(): void {+ movedTurns.clear();+}diff --git a/web/lib/reading-selection.ts b/web/lib/reading-selection.tsnew file mode 100644index 000000000..ed93cccc3--- /dev/null+++ b/web/lib/reading-selection.ts@@ -0,0 +1,135 @@+/**+ * Selection geometry: browser client rects → normalised annotation rects.+ *+ * Everything here is pure so it can be tested without a DOM: callers pass the+ * rectangles they already measured. The output space is the one the store and+ * the PDF export both speak — 0..1 of the unit box, origin top-left.+ *+ * Two behaviours are worth stating, because both were failure modes in the+ * hand-rolled version:+ *+ * * **Line merging.** A selection spanning a wrapped phrase yields one client+ * rect per line, plus slivers where the range clips a character box. Slivers+ * render as visual noise, so rects are merged per text line and the+ * degenerate ones dropped.+ * * **Clamping.** A drag that leaves the page produces rects outside the box.+ * They are clipped rather than discarded, so the highlight still covers the+ * part of the text that *is* on the page.+ */++export interface Box {+ left: number;+ top: number;+ width: number;+ height: number;+}++export type NormalisedRect = [number, number, number, number];++/** Rects thinner or shorter than this (in px) are selection artefacts. */+const MIN_RECT_PX = 2;+/** Vertical overlap ratio above which two rects count as the same line. */+const SAME_LINE_OVERLAP = 0.5;++function clamp01(value: number): number {+ if (!Number.isFinite(value)) return 0;+ return Math.min(1, Math.max(0, value));+}++/**+ * Group rects into text lines by vertical overlap, then union each group.+ *+ * Overlap rather than equal tops: sub/superscripts and mixed font sizes on one+ * line have different tops but clearly belong together.+ */+export function mergeRectsByLine(rects: Box[]): Box[] {+ const usable = rects.filter(+ (rect) => rect.width >= MIN_RECT_PX && rect.height >= MIN_RECT_PX,+ );+ if (!usable.length) return [];++ const sorted = [...usable].sort((a, b) => a.top - b.top || a.left - b.left);+ const lines: Box[][] = [];+ for (const rect of sorted) {+ const line = lines.find((candidate) => {+ const probe = candidate[0];+ const overlap =+ Math.min(probe.top + probe.height, rect.top + rect.height) -+ Math.max(probe.top, rect.top);+ const shorter = Math.min(probe.height, rect.height);+ return shorter > 0 && overlap / shorter >= SAME_LINE_OVERLAP;+ });+ if (line) line.push(rect);+ else lines.push([rect]);+ }++ return lines.map((line) => {+ const left = Math.min(...line.map((r) => r.left));+ const top = Math.min(...line.map((r) => r.top));+ const right = Math.max(...line.map((r) => r.left + r.width));+ const bottom = Math.max(...line.map((r) => r.top + r.height));+ return { left, top, width: right - left, height: bottom - top };+ });+}++/**+ * Convert client rects to normalised rects relative to *container*.+ *+ * Both inputs are viewport-space rects (what `getBoundingClientRect` returns),+ * so scroll position cancels out and no scroll offset is needed.+ */+export function normaliseRects(rects: Box[], container: Box): NormalisedRect[] {+ if (container.width <= 0 || container.height <= 0) return [];+ return mergeRectsByLine(rects)+ .map((rect): NormalisedRect => {+ const x0 = clamp01((rect.left - container.left) / container.width);+ const y0 = clamp01((rect.top - container.top) / container.height);+ const x1 = clamp01(+ (rect.left + rect.width - container.left) / container.width,+ );+ const y1 = clamp01(+ (rect.top + rect.height - container.top) / container.height,+ );+ return [Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)];+ })+ .filter(([x0, y0, x1, y1]) => x1 - x0 > 0.001 && y1 - y0 > 0.001);+}++/** Union of normalised rects, for positioning a popover over a selection. */+export function unionRect(rects: NormalisedRect[]): NormalisedRect | null {+ if (!rects.length) return null;+ return [+ Math.min(...rects.map((r) => r[0])),+ Math.min(...rects.map((r) => r[1])),+ Math.max(...rects.map((r) => r[2])),+ Math.max(...rects.map((r) => r[3])),+ ];+}++/**+ * Tidy a selected string for storage as a quote.+ *+ * pdf.js text layers introduce line breaks wherever the PDF did, so the raw+ * selection is full of hard wraps. Collapsing them is what makes the quote+ * match the stored unit text server-side — the verification step that gates+ * `reader_goto` depends on it.+ */+export function cleanQuote(raw: string, limit = 2000): string {+ const flat = (raw || "").replace(/\s+/g, " ").trim();+ return flat.length <= limit ? flat : flat.slice(0, limit);+}++/**+ * Which locator a selection belongs to, given the elements it spans.+ *+ * A selection dragged across a page boundary is attributed to where it+ * *started*, matching how the user thinks about it, instead of being rejected.+ */+export function locatorOfSelection(+ locators: Array<number | null>,+): number | null {+ for (const locator of locators) {+ if (typeof locator === "number" && locator >= 1) return locator;+ }+ return null;+}diff --git a/web/lib/reading-split.ts b/web/lib/reading-split.tsnew file mode 100644index 000000000..39bb39ba6--- /dev/null+++ b/web/lib/reading-split.ts@@ -0,0 +1,50 @@+/**+ * Geometry of the reader/chat split.+ *+ * Pure so the boundary arithmetic — the part that is easy to get wrong and+ * invisible when it is — can be tested without a DOM. The component that drags+ * the seam only measures and writes; every decision about *what* width is+ * allowed happens here.+ */++/** Narrow enough to be useless as a reader below this. */+export const READER_MIN_PX = 360;+/** Always leave the conversation at least this much. */+export const CHAT_MIN_PX = 380;+/** No reason to go wider than this even on a huge display. */+export const READER_MAX_PX = 1400;+/** Arrow-key step; Shift multiplies it. */+export const READER_STEP_PX = 24;++/** CSS custom property both sides of the split read. */+export const READER_WIDTH_VAR = "--reader-width";+/** localStorage key for the user's chosen width. */+export const READER_WIDTH_KEY = "dt.reader.width";++/**+ * Clamp a candidate reader width so neither side can be squeezed out of use.+ *+ * `available` is the width of the box the two panes share. When it is unknown+ * (server render, or a measurement taken before layout) only the absolute+ * bounds apply — the CSS carries its own percentage ceiling for that case, so a+ * stored pixel value can never paint over the conversation either way.+ *+ * The floor wins over the ceiling on a genuinely narrow container: a reader+ * clamped to 40px would be worse than one that overflows slightly, and below+ * `lg` the split does not exist at all.+ */+export function clampReaderWidth(px: number, available: number): number {+ if (!Number.isFinite(px)) return READER_MIN_PX;+ const ceiling =+ available > 0+ ? Math.min(READER_MAX_PX, available - CHAT_MIN_PX)+ : READER_MAX_PX;+ return Math.round(Math.max(READER_MIN_PX, Math.min(px, Math.max(READER_MIN_PX, ceiling))));+}++/** Parse a persisted width, or null when there is nothing usable stored. */+export function parseStoredWidth(raw: string | null): number | null {+ if (!raw) return null;+ const parsed = Number(raw);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;+}diff --git a/web/lib/reading-turn-state.ts b/web/lib/reading-turn-state.tsnew file mode 100644index 000000000..220855b5d--- /dev/null+++ b/web/lib/reading-turn-state.ts@@ -0,0 +1,88 @@+/**+ * The reader's live state, read once when a chat turn is sent.+ *+ * Deliberately a module-level cell rather than React state on a shared context.+ * The viewport changes on every scroll tick; if the chat subscribed to it, every+ * pixel of scrolling would re-render the whole message list. Nothing renders+ * from these values — they are only read at send time — so a plain cell is both+ * cheaper and more honest about that.+ *+ * Written by the reader pane; read by the chat's turn builder.+ */++/** The capability value the composer sends for immersive reading. */+export const READING_CAPABILITY = "immersive_reading";++export interface ReadingTurnState {+ materialId: string | null;+ locator: number;+ selection: string;+}++const state: ReadingTurnState = {+ materialId: null,+ locator: 0,+ selection: "",+};++export function setReadingMaterial(materialId: string | null): void {+ state.materialId = materialId;+ if (!materialId) {+ // Closing a document must not leave its viewport behind: the next turn+ // would tell the model the user is looking at a page of a closed file.+ state.locator = 0;+ state.selection = "";+ }+}++export function setReadingViewport(next: {+ locator?: number;+ selection?: string;+}): void {+ if (typeof next.locator === "number" && Number.isFinite(next.locator)) {+ state.locator = next.locator > 0 ? Math.floor(next.locator) : 0;+ }+ if (typeof next.selection === "string") {+ state.selection = next.selection;+ }+}++export function getReadingTurnState(): ReadingTurnState {+ return { ...state };+}++/**+ * Turn fields to merge into a `start_turn` payload.+ *+ * Empty unless the turn is *actually* an immersive-reading turn — the caller+ * passes the capability it is about to send, and anything else gets nothing.+ *+ * Both halves of that condition are load-bearing. The open document lives in a+ * provider mounted in the workspace layout so it survives the remount that+ * sending the first message causes, which also means it survives switching modes+ * and starting a new session. Keying only on "is a document open" therefore+ * attached the reader to *every* later turn: a fresh chat session, in Chat mode,+ * would open with "I see you're reading …" and cite pages from a document the+ * user had moved on from.+ */+export function readingTurnFields(capability: string | null | undefined): {+ reading_material_id?: string;+ reading_viewport?: { locator?: number; selection?: string };+} {+ if (capability !== READING_CAPABILITY) return {};+ if (!state.materialId) return {};+ const viewport: { locator?: number; selection?: string } = {};+ if (state.locator > 0) viewport.locator = state.locator;+ if (state.selection) viewport.selection = state.selection;+ return {+ reading_material_id: state.materialId,+ ...(Object.keys(viewport).length ? { reading_viewport: viewport } : {}),+ };+}++/** Test seam: reset the cell between cases. */+export function resetReadingTurnState(): void {+ state.materialId = null;+ state.locator = 0;+ state.selection = "";+}diff --git a/web/lib/setup-signals.ts b/web/lib/setup-signals.tsnew file mode 100644index 000000000..12ab9e084--- /dev/null+++ b/web/lib/setup-signals.ts@@ -0,0 +1,92 @@+import type { StreamEvent } from "@/lib/unified-ws";++/**+ * Reading the setup capability's signals off a turn's event stream.+ *+ * Kept as pure functions, apart from the components that render them, for the+ * same reason `lib/ask-user-state.ts` is: the interesting logic is which events+ * count and how they are deduplicated, and that deserves tests that do not need+ * a DOM.+ *+ * Mirrors the metadata written by `deeptutor/capabilities/setup/tools.py`.+ */++/** Hand-off card shown when a step needs a credential the assistant must not touch. */+export interface SetupCredentialData {+ service: string;+ label: string;+ settingsPath: string;+ reason: string;+}++function toolMetadataOf(event: StreamEvent): Record<string, unknown> | null {+ if (event.type !== "tool_result") return null;+ const meta = (event.metadata ?? {}) as Record<string, unknown>;+ const toolMetadata = meta.tool_metadata;+ if (!toolMetadata || typeof toolMetadata !== "object") return null;+ return toolMetadata as Record<string, unknown>;+}++/**+ * The most recent credential hand-off in this message, if any.+ *+ * `settingsPath` is required to be an in-app settings route: it is rendered as+ * a navigation target, and constraining it here means a malformed or hostile+ * value cannot turn the card into an open redirect.+ */+export function extractSetupCredential(+ events: StreamEvent[] | undefined,+): SetupCredentialData | null {+ if (!events || events.length === 0) return null;+ let latest: SetupCredentialData | null = null;+ for (const event of events) {+ const toolMetadata = toolMetadataOf(event);+ if (!toolMetadata) continue;+ const raw = toolMetadata.setup_credential;+ if (!raw || typeof raw !== "object") continue;+ const payload = raw as Record<string, unknown>;+ const settingsPath = String(payload.settings_path ?? "").trim();+ if (!settingsPath.startsWith("/settings")) continue;+ latest = {+ service: String(payload.service ?? ""),+ label: String(payload.label ?? ""),+ settingsPath,+ reason: String(payload.reason ?? ""),+ };+ }+ return latest;+}++/**+ * Stable ids for every `setup_applied` signal across a conversation.+ *+ * One id per tool call, so a caller can honour each exactly once: replayed+ * history and ordinary re-renders must not keep re-applying a preference the+ * user may have changed by hand since. Falls back to key+seq when the transport+ * did not carry a tool call id, which still distinguishes separate writes.+ */+export function collectAppliedSettingIds(+ messages: ReadonlyArray<{ events?: StreamEvent[] }> | undefined,+): string[] {+ if (!messages || messages.length === 0) return [];+ const ids: string[] = [];+ const seen = new Set<string>();+ for (const message of messages) {+ for (const event of message.events ?? []) {+ const toolMetadata = toolMetadataOf(event);+ if (!toolMetadata) continue;+ const applied = toolMetadata.setup_applied;+ if (!applied || typeof applied !== "object") continue;+ const meta = (event.metadata ?? {}) as Record<string, unknown>;+ const callId =+ (event as { tool_call_id?: string }).tool_call_id ??+ (typeof meta.tool_call_id === "string" ? meta.tool_call_id : "");+ const key = String((applied as Record<string, unknown>).key ?? "");+ const id = callId || (key ? `${key}:${event.seq ?? ""}` : "");+ if (!id || seen.has(id)) continue;+ seen.add(id);+ ids.push(id);+ }+ }+ return ids;+}diff --git a/web/lib/space-items.ts b/web/lib/space-items.tsindex a54381113..471f921cf 100644--- a/web/lib/space-items.ts+++ b/web/lib/space-items.ts@@ -45,7 +45,7 @@ export const SPACE_ITEMS: SpaceItem[] = [},{key: "notebooks",- href: "/space/notebooks",+ href: "/notebook",label: "Notebooks",description:"Organize saved outputs from chat, research, Co-Writer, and more.",diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 7652de9d4..6ac9b230e 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -77,6 +77,15 @@ export interface StartTurnMessage {}[];/** Persistent mastery state to use independently of this chat session. */mastery_path_id?: string;+ /** Immersive reading: the document open in the reader pane, if any. Its+ * presence is what activates the reading capability for the turn. */+ reading_material_id?: string;+ /** What the reader is showing right now — the locator on screen and any text+ * the user has selected. Advisory context, not a citation. */+ reading_viewport?: {+ locator?: number;+ selection?: string;+ };persona?: string;llm_selection?: LLMSelection | null;/** Edit-branching: when present (even as ``null``) the new user messagediff --git a/web/lib/use-book-stream.ts b/web/lib/use-book-stream.tsindex ecc91628e..daace5d1e 100644--- a/web/lib/use-book-stream.ts+++ b/web/lib/use-book-stream.ts@@ -111,13 +111,15 @@ export function useBookStream(/** Normalized `kind` for a book event, wherever the backend put it. */export function bookEventKind(event: BookWsEvent): string {- const metadata = (event.metadata as Record<string, unknown> | undefined) || {};+ const metadata =+ (event.metadata as Record<string, unknown> | undefined) || {};return String(metadata.kind || event.content || "");}/** The page a book event refers to, or `null` for book-level events. */export function bookEventPageId(event: BookWsEvent): string | null {- const metadata = (event.metadata as Record<string, unknown> | undefined) || {};+ const metadata =+ (event.metadata as Record<string, unknown> | undefined) || {};const pageId = metadata.page_id;return typeof pageId === "string" && pageId ? pageId : null;}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 37aa4bb0b..9df882e82 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2190,6 +2190,9 @@"Unanswered questions will be submitted as skipped.": "Unanswered questions will be submitted as skipped.","Your answers": "Your answers","{{count}} questions — tap a tab to switch.": "{{count}} questions — tap a tab to switch.",+ "Enter the key on the settings page — never in chat, so it stays out of the conversation.": "Enter the key on the settings page — never in chat, so it stays out of the conversation.",+ "Open settings": "Open settings",+ "This step needs credentials": "This step needs credentials","Close tab": "Close tab","Close viewer": "Close viewer","Loading {{host}}…": "Loading {{host}}…",@@ -2537,11 +2540,11 @@"Text-only": "Text-only","Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.": "Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.","Knowledge Center": "Knowledge Center",- "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",+ "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key. Chat searches it, browses its documents, reads full sources, and — only when you ask — collects a web page or saves a note.": "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key. Chat searches it, browses its documents, reads full sources, and — only when you ask — collects a web page or saves a note.","One IMA account reaches every library in it, so this pair is shared by all your Tencent IMA knowledge bases. Connecting one then only asks which library to point at. A knowledge base can still carry its own credentials to reach a second account.": "One IMA account reaches every library in it, so this pair is shared by all your Tencent IMA knowledge bases. Connecting one then only asks which library to point at. A knowledge base can still carry its own credentials to reach a second account.","Enter your IMA Client ID": "Enter your IMA Client ID","Enter your IMA API key": "Enter your IMA API key",- "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.": "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.",+ "DeepTutor searches and browses this library, and reads full sources when a matched snippet is too short. It only writes to IMA when you ask it to.": "DeepTutor searches and browses this library, and reads full sources when a matched snippet is too short. It only writes to IMA when you ask it to.","Client ID": "Client ID","Using the IMA credentials configured for this engine in the Knowledge Center.": "Using the IMA credentials configured for this engine in the Knowledge Center.","Use other credentials": "Use other credentials",@@ -3070,5 +3073,99 @@"Generate a chapter on this": "Generate a chapter on this","This book was written without reading your sources.": "This book was written without reading your sources.","Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.": "Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.",- "Source sweep failed": "Source sweep failed"+ "Source sweep failed": "Source sweep failed",+ "A record needs a title.": "A record needs a title.",+ "Body": "Body",+ "Copy to notebook": "Copy to notebook",+ "Could not load your notebooks": "Could not load your notebooks",+ "Delete \"{{name}}\" and its {{count}} records? This cannot be undone.": "Delete \"{{name}}\" and its {{count}} records? This cannot be undone.",+ "Delete \"{{name}}\"?": "Delete \"{{name}}\"?",+ "Delete notebook": "Delete notebook",+ "Delete the record \"{{title}}\"?": "Delete the record \"{{title}}\"?",+ "Description (optional)": "Description (optional)",+ "Discard your unsaved changes?": "Discard your unsaved changes?",+ "Edit Markdown": "Edit Markdown",+ "Edit notebook": "Edit notebook",+ "Filter notebooks": "Filter notebooks",+ "Move to notebook": "Move to notebook",+ "Name your first notebook": "Name your first notebook",+ "New notebook": "New notebook",+ "No notebook selected": "No notebook selected",+ "No notebooks match your filter.": "No notebooks match your filter.",+ "No notebooks yet.": "No notebooks yet.",+ "No records match your search": "No records match your search",+ "Pick a notebook on the left, or create one to get started.": "Pick a notebook on the left, or create one to get started.",+ "Record title": "Record title",+ "Save something to it from a chat, research run, or Co-Writer document.": "Save something to it from a chat, research run, or Co-Writer document.",+ "Search records in this notebook": "Search records in this notebook",+ "Short summary": "Short summary",+ "This notebook could not be opened": "This notebook could not be opened",+ "This notebook is empty": "This notebook is empty",+ "Try a different word.": "Try a different word.",+ "No notebook accepted this save. Their files may be missing or damaged.": "No notebook accepted this save. Their files may be missing or damaged.",+ "Could not save to: {{names}}": "Could not save to: {{names}}",+ "Record actions": "Record actions",+ "Copy to": "Copy to",+ "Record saved": "Record saved",+ "Record deleted": "Record deleted",+ "Moved to \"{{name}}\"": "Moved to \"{{name}}\"",+ "Copied to \"{{name}}\"": "Copied to \"{{name}}\"",+ "Delete this record?": "Delete this record?",+ "\"{{title}}\" will be removed from this notebook.": "\"{{title}}\" will be removed from this notebook.",+ "Discard your changes?": "Discard your changes?",+ "Discard": "Discard",+ "Your edits to this record have not been saved yet.": "Your edits to this record have not been saved yet.",+ "Write": "Write",+ "Delete this notebook?": "Delete this notebook?",+ "\"{{name}}\" and its {{count}} records will be deleted. This cannot be undone.": "\"{{name}}\" and its {{count}} records will be deleted. This cannot be undone.",+ "\"{{name}}\" will be deleted.": "\"{{name}}\" will be deleted.",+ "Deleted \"{{name}}\"": "Deleted \"{{name}}\"",+ "Notebook exported": "Notebook exported",+ "Immersive Reading": "Immersive Reading",+ "Read a document with the assistant, cited line by line": "Read a document with the assistant, cited line by line",+ "Immersive reading": "Immersive reading",+ "Open a document to read": "Open a document to read",+ "Drop a PDF, EPUB, Word, slide deck or text file here. The assistant reads it with you and cites what it uses.": "Drop a PDF, EPUB, Word, slide deck or text file here. The assistant reads it with you and cites what it uses.",+ "Up to {{mb}} MB.": "Up to {{mb}} MB.",+ "Preparing document…": "Preparing document…",+ "Opening document…": "Opening document…",+ "Recently read": "Recently read",+ "Close document": "Close document",+ "Close reader": "Close reader",+ "Export annotated file": "Export annotated file",+ "Export failed.": "Export failed.",+ "Annotations": "Annotations",+ "Auto-jump on — the view follows what the assistant reads": "Auto-jump on — the view follows what the assistant reads",+ "Auto-jump off — the assistant will not move your view": "Auto-jump off — the assistant will not move your view",+ "Annotate selection": "Annotate selection",+ "Highlight": "Highlight",+ "Underline": "Underline",+ "Add note": "Add note",+ "Ask about this": "Ask about this",+ "Your note…": "Your note…",+ "Save note": "Save note",+ "Yellow": "Yellow",+ "Green": "Green",+ "Blue": "Blue",+ "Pink": "Pink",+ "Purple": "Purple",+ "No annotations yet": "No annotations yet",+ "Select text in the document to highlight it or attach a note.": "Select text in the document to highlight it or attach a note.",+ "Delete annotation": "Delete annotation",+ "{{count}} annotations": "{{count}} annotations",+ "AI": "AI",+ "Page": "Page",+ "Chapter": "Chapter",+ "Slide": "Slide",+ "{{unit}} {{n}} of {{total}}": "{{unit}} {{n}} of {{total}}",+ "This document could not be opened.": "This document could not be opened.",+ "This file could not be opened.": "This file could not be opened.",+ "This page could not be rendered.": "This page could not be rendered.",+ "This section has no extractable text.": "This section has no extractable text.",+ "Could not load this section.": "Could not load this section.",+ "That annotation could not be saved.": "That annotation could not be saved.",+ "That annotation could not be removed.": "That annotation could not be removed.",+ "Explain this passage": "Explain this passage",+ "Resize the reader": "Resize the reader",+ "Drag to resize · double-click to reset": "Drag to resize · double-click to reset"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 2063b39dd..dacfdf257 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2190,6 +2190,9 @@"Unanswered questions will be submitted as skipped.": "未回答的问题将作为「已跳过」提交。","Your answers": "你的回答","{{count}} questions — tap a tab to switch.": "{{count}} 个问题 — 点击标签切换。",+ "Enter the key on the settings page — never in chat, so it stays out of the conversation.": "请在设置页填写密钥——不要填在聊天里,这样它不会进入对话记录。",+ "Open settings": "打开设置",+ "This step needs credentials": "这一步需要凭据","Close tab": "关闭标签页","Close viewer": "关闭查看器","Loading {{host}}…": "正在加载 {{host}}…",@@ -2537,11 +2540,11 @@"Text-only": "仅文本","Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.": "内置纯文本提取,支持 PDF、Office 和文本文件。无需可选解析包、模型下载、OCR 或版面重建。","Knowledge Center": "知识中心",- "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key; retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "托管引擎:知识库存放在腾讯 IMA,DeepTutor 不保留副本。需配置 IMA Client ID 和 API 密钥;检索为只读,并在 IMA 未返回命中片段时限量读取原文。",+ "Hosted engine: the library lives in Tencent IMA and DeepTutor keeps no copy. Requires an IMA Client ID and API key. Chat searches it, browses its documents, reads full sources, and — only when you ask — collects a web page or saves a note.": "托管引擎:知识库存放在腾讯 IMA,DeepTutor 不保留副本。需配置 IMA Client ID 和 API 密钥。对话可以检索、浏览其中的文档、读取原文,并且只有在你要求时才会收藏网页或保存笔记。","One IMA account reaches every library in it, so this pair is shared by all your Tencent IMA knowledge bases. Connecting one then only asks which library to point at. A knowledge base can still carry its own credentials to reach a second account.": "一个 IMA 账号可访问其名下所有知识库,因此这组凭证由你全部的腾讯 IMA 知识库共用。之后连接知识库时只需选择指向哪个库。单个知识库仍可填写自己的凭证以连接另一个账号。","Enter your IMA Client ID": "输入你的 IMA Client ID","Enter your IMA API key": "输入你的 IMA API 密钥",- "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.": "DeepTutor 会检索 IMA,并在命中结果缺少片段时限量读取原文;不会向 IMA 写入内容。",+ "DeepTutor searches and browses this library, and reads full sources when a matched snippet is too short. It only writes to IMA when you ask it to.": "DeepTutor 会检索并浏览这个知识库,命中片段太短时读取原文;只有在你要求时才会向 IMA 写入内容。","Client ID": "Client ID","Using the IMA credentials configured for this engine in the Knowledge Center.": "正在使用知识中心里为该引擎配置的 IMA 凭证。","Use other credentials": "使用其他凭证",@@ -3070,5 +3073,99 @@"Generate a chapter on this": "就此生成一章","This book was written without reading your sources.": "这本书生成时没有读取你的资料来源。","Retrieval failed while planning it, so the chapters come from the proposal alone. Rebuilding will try your knowledge bases again.": "规划阶段检索失败,因此各章仅基于方案生成。重建会重新尝试读取你的知识库。",- "Source sweep failed": "来源扫描失败"+ "Source sweep failed": "来源扫描失败",+ "A record needs a title.": "记录需要一个标题。",+ "Body": "正文",+ "Copy to notebook": "复制到笔记本",+ "Could not load your notebooks": "无法加载你的笔记本",+ "Delete \"{{name}}\" and its {{count}} records? This cannot be undone.": "删除「{{name}}」及其 {{count}} 条记录?此操作无法撤销。",+ "Delete \"{{name}}\"?": "删除「{{name}}」?",+ "Delete notebook": "删除笔记本",+ "Delete the record \"{{title}}\"?": "删除记录「{{title}}」?",+ "Description (optional)": "描述(可选)",+ "Discard your unsaved changes?": "放弃未保存的修改?",+ "Edit Markdown": "编辑 Markdown",+ "Edit notebook": "编辑笔记本",+ "Filter notebooks": "筛选笔记本",+ "Move to notebook": "移动到笔记本",+ "Name your first notebook": "为第一个笔记本起名",+ "New notebook": "新建笔记本",+ "No notebook selected": "未选择笔记本",+ "No notebooks match your filter.": "没有匹配的笔记本。",+ "No notebooks yet.": "还没有笔记本。",+ "No records match your search": "没有匹配的记录",+ "Pick a notebook on the left, or create one to get started.": "从左侧选择一个笔记本,或新建一个开始使用。",+ "Record title": "记录标题",+ "Save something to it from a chat, research run, or Co-Writer document.": "从对话、研究或智能写作中保存内容到这里。",+ "Search records in this notebook": "在此笔记本中搜索记录",+ "Short summary": "简短摘要",+ "This notebook could not be opened": "无法打开这个笔记本",+ "This notebook is empty": "这个笔记本还是空的",+ "Try a different word.": "换个关键词试试。",+ "No notebook accepted this save. Their files may be missing or damaged.": "没有笔记本接收这次保存,它们的文件可能丢失或损坏。",+ "Could not save to: {{names}}": "未能保存到:{{names}}",+ "Record actions": "记录操作",+ "Copy to": "复制到",+ "Record saved": "记录已保存",+ "Record deleted": "记录已删除",+ "Moved to \"{{name}}\"": "已移动到「{{name}}」",+ "Copied to \"{{name}}\"": "已复制到「{{name}}」",+ "Delete this record?": "删除这条记录?",+ "\"{{title}}\" will be removed from this notebook.": "「{{title}}」将从这个笔记本中移除。",+ "Discard your changes?": "放弃修改?",+ "Discard": "放弃",+ "Your edits to this record have not been saved yet.": "你对这条记录的修改尚未保存。",+ "Write": "编辑",+ "Delete this notebook?": "删除这个笔记本?",+ "\"{{name}}\" and its {{count}} records will be deleted. This cannot be undone.": "「{{name}}」及其 {{count}} 条记录将被删除,此操作无法撤销。",+ "\"{{name}}\" will be deleted.": "「{{name}}」将被删除。",+ "Deleted \"{{name}}\"": "已删除「{{name}}」",+ "Notebook exported": "笔记本已导出",+ "Immersive Reading": "沉浸式阅读",+ "Read a document with the assistant, cited line by line": "与助手一起读文档,逐句给出出处",+ "Immersive reading": "沉浸式阅读",+ "Open a document to read": "打开一份文档开始阅读",+ "Drop a PDF, EPUB, Word, slide deck or text file here. The assistant reads it with you and cites what it uses.": "把 PDF、EPUB、Word、幻灯片或文本文件拖到这里。助手会和你一起读,并标明它引用了哪里。",+ "Up to {{mb}} MB.": "最大 {{mb}} MB。",+ "Preparing document…": "正在准备文档…",+ "Opening document…": "正在打开文档…",+ "Recently read": "最近阅读",+ "Close document": "关闭文档",+ "Close reader": "关闭阅读器",+ "Export annotated file": "导出带标注的文件",+ "Export failed.": "导出失败。",+ "Annotations": "标注",+ "Auto-jump on — the view follows what the assistant reads": "自动跟随已开启 —— 视图会跟着助手读到的位置移动",+ "Auto-jump off — the assistant will not move your view": "自动跟随已关闭 —— 助手不会移动你的视图",+ "Annotate selection": "标注所选内容",+ "Highlight": "高亮",+ "Underline": "下划线",+ "Add note": "添加批注",+ "Ask about this": "就此提问",+ "Your note…": "写下你的批注…",+ "Save note": "保存批注",+ "Yellow": "黄色",+ "Green": "绿色",+ "Blue": "蓝色",+ "Pink": "粉色",+ "Purple": "紫色",+ "No annotations yet": "还没有标注",+ "Select text in the document to highlight it or attach a note.": "在文档里选中文字即可高亮或添加批注。",+ "Delete annotation": "删除标注",+ "{{count}} annotations": "{{count}} 条标注",+ "AI": "AI",+ "Page": "页",+ "Chapter": "章",+ "Slide": "幻灯片",+ "{{unit}} {{n}} of {{total}}": "第 {{n}} {{unit}} / 共 {{total}}",+ "This document could not be opened.": "这份文档无法打开。",+ "This file could not be opened.": "这个文件无法打开。",+ "This page could not be rendered.": "这一页无法渲染。",+ "This section has no extractable text.": "这一节没有可提取的文字。",+ "Could not load this section.": "无法加载这一节。",+ "That annotation could not be saved.": "这条标注保存失败。",+ "That annotation could not be removed.": "这条标注删除失败。",+ "Explain this passage": "解释这段内容",+ "Resize the reader": "调整阅读器宽度",+ "Drag to resize · double-click to reset": "拖动调整宽度 · 双击恢复默认"}diff --git a/web/package-lock.json b/web/package-lock.jsonindex d462f0148..956753632 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -20,6 +20,7 @@"lucide-react": "^0.562.0","mermaid": "^11.14.0","next": "^16.2.3",+ "pdfjs-dist": "^6.2.108","react": "^19.0.0","react-chartjs-2": "^5.3.1","react-dom": "^19.0.0",@@ -1183,6 +1184,256 @@"langium": "^4.0.0"}},+ "node_modules/@napi-rs/canvas": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.6.tgz",+ "integrity": "sha512-Ud4d0jLr9vSaakvfOTIjgP3hoY8kMIYgHC4mtE4L0bP3St9lf6TyCVsInvFIOEofzcUeMfDydHDy8Fs2WuWz+A==",+ "license": "MIT",+ "optional": true,+ "workspaces": [+ "e2e/*"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ },+ "optionalDependencies": {+ "@napi-rs/canvas-android-arm64": "1.0.6",+ "@napi-rs/canvas-darwin-arm64": "1.0.6",+ "@napi-rs/canvas-darwin-x64": "1.0.6",+ "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.6",+ "@napi-rs/canvas-linux-arm64-gnu": "1.0.6",+ "@napi-rs/canvas-linux-arm64-musl": "1.0.6",+ "@napi-rs/canvas-linux-riscv64-gnu": "1.0.6",+ "@napi-rs/canvas-linux-x64-gnu": "1.0.6",+ "@napi-rs/canvas-linux-x64-musl": "1.0.6",+ "@napi-rs/canvas-win32-arm64-msvc": "1.0.6",+ "@napi-rs/canvas-win32-x64-msvc": "1.0.6"+ }+ },+ "node_modules/@napi-rs/canvas-android-arm64": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.0.6.tgz",+ "integrity": "sha512-CZUmZEyN/cmSN1OhRJ44vBE6xyb5ekBbsIF8dqNgizbnAiHSFNi8eAA4oyyIAe5KzJ72K16OKC2lAynZLhv32Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-darwin-arm64": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.0.6.tgz",+ "integrity": "sha512-FGJsIngRfS9LDaX4t/lFthqn2Km6b61ONzjJFC6+yuabL1NgaK7x0fwrj8276OQFkjCvSpJZ7+CeZWgcy03F2w==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-darwin-x64": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.0.6.tgz",+ "integrity": "sha512-wLDrtfX9V4bu6O55/WwGvPVCjfunL2bEm59lzIFk9ZQOt7oJrPzdx/ytZiQr6bMZ9XOFwvXujszYtpoCK7yUbg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.0.6.tgz",+ "integrity": "sha512-8TllEP/9UPDVxrBN/tnbGBsxxwG8Eo2tgyW8wDy+Gi9rm9si2I6MsDv9MlfI3a7JOuzkBcurHYDHZxwLgzAIdA==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-arm64-gnu": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.0.6.tgz",+ "integrity": "sha512-YF15AKoGrgU7aoA03CR+cATCRPQcVt6L14Lb/a9hqK7pT7/DhIkqh4qyl+a2GLfqx++yIIJfBuZ3sHM3zlXM1Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-arm64-musl": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.0.6.tgz",+ "integrity": "sha512-zXeVWNFpj720HZln0bfAs+1/nP3Wy6Z5hUw60UJu+cvgips5jZtuX2+EjDHFk98q3BY35GaE1TQLwE9S244vPA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-riscv64-gnu": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.0.6.tgz",+ "integrity": "sha512-kvy1Ypq4ODEI2WRNGvs588qTMcWCjlEIuZRyW8JXpiBnMUirgxQukIDFVDQEcrLlHP5cqZ9cvvfOkBJ7koOktA==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-x64-gnu": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.0.6.tgz",+ "integrity": "sha512-czHnfLgSCl48iluS6bNrytGYhsbSTUuIvMucAwO0mPEj1uhkHk6SUiRI0xoqv0PSFzpGFfSnQvFpm7vV+tDO+A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-linux-x64-musl": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.0.6.tgz",+ "integrity": "sha512-afsg6GyfUx8qZzjsywjimXUEWcSWETY5F80hmMb2FWVSXkRbor8IpftY2gXnasq+Y42Xug/76qTHwqvti7HRTw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-win32-arm64-msvc": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.0.6.tgz",+ "integrity": "sha512-byzha357piy0wgK6IZOQtU4plpt94f6CxHFS7LhJpWYrDWWT/AitQNxRMfCNNaQHZXUB3BwNhQSfH2RpiZ0WaQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },+ "node_modules/@napi-rs/canvas-win32-x64-msvc": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.0.6.tgz",+ "integrity": "sha512-gWLOgKGZz3hZhzg49q2PJIURwy2pCWh1zvNFXmLO1yineOPhEpoL3EV6/VIjOiKa1l2P6ieP12Eo385u1MLLVQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 10"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ }+ },"node_modules/@napi-rs/wasm-runtime": {"version": "0.2.12","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",@@ -8533,6 +8784,18 @@"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==","license": "MIT"},+ "node_modules/pdfjs-dist": {+ "version": "6.2.108",+ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.2.108.tgz",+ "integrity": "sha512-YxFb+SQcodN2rnX9Tn3dHYlqfb7NjlzzfONPpJd+AKoKtUjEdevTfbC07d5TcczzOK6261auRkP/M8OBHs9vFQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22.13.0 || >=24"+ },+ "optionalDependencies": {+ "@napi-rs/canvas": "^1.0.0"+ }+ },"node_modules/performance-now": {"version": "2.1.0","resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",diff --git a/web/package.json b/web/package.jsonindex 2b859eb37..e163b4464 100644--- a/web/package.json+++ b/web/package.json@@ -33,6 +33,7 @@"lucide-react": "^0.562.0","mermaid": "^11.14.0","next": "^16.2.3",+ "pdfjs-dist": "^6.2.108","react": "^19.0.0","react-chartjs-2": "^5.3.1","react-dom": "^19.0.0",diff --git a/web/tests/chat-launch-intent.test.ts b/web/tests/chat-launch-intent.test.tsindex a6b587063..18853d8e0 100644--- a/web/tests/chat-launch-intent.test.ts+++ b/web/tests/chat-launch-intent.test.ts@@ -34,7 +34,10 @@ test("tools are collected verbatim for the caller to validate", () => {});test("a blank mastery path id is dropped rather than bound", () => {- assert.equal(readChatLaunchIntent("?mastery_path_id=%20%20").masteryPathId, null);+ assert.equal(+ readChatLaunchIntent("?mastery_path_id=%20%20").masteryPathId,+ null,+ );assert.deepEqual(readChatLaunchIntent(""), {capability: null,tools: [],diff --git a/web/tests/mastery-path-activity.test.ts b/web/tests/mastery-path-activity.test.tsindex dc1a6f3e7..15c4561b1 100644--- a/web/tests/mastery-path-activity.test.ts+++ b/web/tests/mastery-path-activity.test.ts@@ -30,7 +30,10 @@ function feed(pathId: string, revisions: number[]): ActivityFeed {}test("an incremental batch appends and advances the cursor", () => {- const merged = mergeEventBatch(feed("p1", [1, 2]), "p1", 2, [event(3), event(4)]);+ const merged = mergeEventBatch(feed("p1", [1, 2]), "p1", 2, [+ event(3),+ event(4),+ ]);assert.deepEqual(merged.events.map((e) => e.revision),[1, 2, 3, 4],diff --git a/web/tests/reading-citations.test.ts b/web/tests/reading-citations.test.tsnew file mode 100644index 000000000..3927419da--- /dev/null+++ b/web/tests/reading-citations.test.ts@@ -0,0 +1,241 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ LOCATOR_HREF_PREFIX,+ codeRanges,+ findLocatorCitations,+ linkifyLocatorCitations,+ locatorFromHref,+ locatorLabel,+} from "../lib/reading-citations";++test("parses a single locator citation", () => {+ const found = findLocatorCitations("Attention is all you need [p.12] here.");+ assert.equal(found.length, 1);+ assert.deepEqual(found[0].locators, [12]);+ assert.equal(found[0].raw, "[p.12]");+});++test("parses lists and ranges, sorted and de-duplicated", () => {+ assert.deepEqual(findLocatorCitations("[p.17,12]")[0].locators, [12, 17]);+ assert.deepEqual(findLocatorCitations("[p.12-14]")[0].locators, [12, 13, 14]);+ assert.deepEqual(findLocatorCitations("[p.14-12]")[0].locators, [12, 13, 14]);+ assert.deepEqual(findLocatorCitations("[p.3,3,4]")[0].locators, [3, 4]);+ assert.deepEqual(findLocatorCitations("[p. 12 , 17 ]")[0].locators, [12, 17]);+});++test("accepts en dash and em dash ranges the model may emit", () => {+ assert.deepEqual(findLocatorCitations("[p.2–3]")[0].locators, [2, 3]);+ assert.deepEqual(findLocatorCitations("[p.2—3]")[0].locators, [2, 3]);+});++test("bounds an absurd range instead of expanding it", () => {+ const found = findLocatorCitations("[p.1-100000]");+ assert.ok(found[0].locators.length <= 41);+});++test("ignores brackets that are not locator citations", () => {+ for (const input of ["[12]", "[page 12]", "[p.]", "[p.abc]", "[web-1]", "[0]"]) {+ assert.deepEqual(findLocatorCitations(input), [], input);+ }+});++test("rejects locator zero", () => {+ assert.deepEqual(findLocatorCitations("[p.0]"), []);+});++test("does not touch citations inside inline code", () => {+ const text = "Use `arr[p.12]` as the index.";+ assert.deepEqual(findLocatorCitations(text), []);+ assert.equal(linkifyLocatorCitations(text), text);+});++test("does not touch citations inside fenced code blocks", () => {+ const text = ["Look at this:", "", "```python", "x = data[p.12]", "```", "", "Then [p.3]."].join(+ "\n",+ );+ const found = findLocatorCitations(text);+ assert.equal(found.length, 1);+ assert.deepEqual(found[0].locators, [3]);+});++test("handles tilde fences and multiple fences", () => {+ const text = ["~~~", "a[p.1]", "~~~", "prose [p.2]", "```", "b[p.3]", "```"].join("\n");+ const found = findLocatorCitations(text);+ assert.deepEqual(+ found.map((c) => c.locators),+ [[2]],+ );+});++test("an unterminated fence swallows the rest, as Markdown does", () => {+ const text = ["```", "x[p.9]", "still code [p.10]"].join("\n");+ assert.deepEqual(findLocatorCitations(text), []);+});++test("codeRanges reports fenced and inline spans in order", () => {+ const ranges = codeRanges("a `b` c\n```\nd\n```\n");+ assert.ok(ranges.length >= 2);+ for (let i = 1; i < ranges.length; i += 1) {+ assert.ok(ranges[i][0] >= ranges[i - 1][0]);+ }+});++test("leaves an existing markdown link label alone", () => {+ const text = "see [p.12](https://example.com) for details";+ assert.deepEqual(findLocatorCitations(text), []);+ assert.equal(linkifyLocatorCitations(text), text);+});++test("linkify rewrites to an anchor the reader can intercept", () => {+ assert.equal(+ linkifyLocatorCitations("Grounded [p.12] claim."),+ `Grounded [p.12](${LOCATOR_HREF_PREFIX}12) claim.`,+ );+});++test("linkify keeps a multi-locator label but targets the first", () => {+ assert.equal(+ linkifyLocatorCitations("Both [p.12,17] agree."),+ `Both [p.12,17](${LOCATOR_HREF_PREFIX}12) agree.`,+ );+});++test("linkify handles several citations in one paragraph", () => {+ assert.equal(+ linkifyLocatorCitations("First [p.1], then [p.2]."),+ `First [p.1](${LOCATOR_HREF_PREFIX}1), then [p.2](${LOCATOR_HREF_PREFIX}2).`,+ );+});++test("linkify drops locators the document cannot have", () => {+ // A link to page 900 of a 12-page PDF is a dead end; plain text is honest.+ assert.equal(+ linkifyLocatorCitations("Claim [p.900].", { maxLocator: 12 }),+ "Claim [p.900].",+ );+ assert.equal(+ linkifyLocatorCitations("Claim [p.3,900].", { maxLocator: 12 }),+ `Claim [p.3](${LOCATOR_HREF_PREFIX}3).`,+ );+});++test("linkify is idempotent", () => {+ const once = linkifyLocatorCitations("Grounded [p.5] claim.");+ assert.equal(linkifyLocatorCitations(once), once);+});++test("linkify leaves text without citations untouched", () => {+ const text = "No citations here at all.";+ assert.equal(linkifyLocatorCitations(text), text);+ assert.equal(linkifyLocatorCitations(""), "");+});++test("locatorFromHref only accepts the reader's own anchors", () => {+ assert.equal(locatorFromHref(`${LOCATOR_HREF_PREFIX}12`), 12);+ assert.equal(locatorFromHref("#references"), null);+ assert.equal(locatorFromHref(`${LOCATOR_HREF_PREFIX}0`), null);+ assert.equal(locatorFromHref(`${LOCATOR_HREF_PREFIX}abc`), null);+ assert.equal(locatorFromHref(null), null);+ assert.equal(locatorFromHref(undefined), null);+});++test("locatorLabel uses the material's own unit word", () => {+ assert.equal(locatorLabel("page", 12), "page 12");+ assert.equal(locatorLabel("chapter", 3), "chapter 3");+ assert.equal(locatorLabel("", 1), "page 1");+});++// ── Absorbing a spelled-out location ────────────────────────────────────────+// A model answering "where is it?" writes the location into the sentence and+// then appends the marker too, leaving two copies. The phrase becomes the link+// and the marker is dropped, so exactly one link survives — in the place the+// reader is already looking.++test("absorbs 'on page 3' and drops the trailing marker", () => {+ assert.equal(+ linkifyLocatorCitations(+ "The section on Positional encoding is located on page 3 of the document [p.3].",+ ),+ `The section on Positional encoding is located on [page 3](${LOCATOR_HREF_PREFIX}3) of the document.`,+ );+});++test("absorbs when the marker sits immediately after the phrase", () => {+ assert.equal(+ linkifyLocatorCitations("It appears on page 7 [p.7]."),+ `It appears on [page 7](${LOCATOR_HREF_PREFIX}7).`,+ );+});++test("absorbs chapter, slide and section wording too", () => {+ assert.equal(+ linkifyLocatorCitations("Discussed in chapter 4 [p.4]."),+ `Discussed in [chapter 4](${LOCATOR_HREF_PREFIX}4).`,+ );+ assert.equal(+ linkifyLocatorCitations("See slide 9 [p.9]."),+ `See [slide 9](${LOCATOR_HREF_PREFIX}9).`,+ );+});++test("absorbs Chinese location wording", () => {+ assert.equal(+ linkifyLocatorCitations("该节位于第 3 页 [p.3]。"),+ `该节位于[第 3 页](${LOCATOR_HREF_PREFIX}3)。`,+ );+ assert.equal(+ linkifyLocatorCitations("见第4章 [p.4]。"),+ `见[第4章](${LOCATOR_HREF_PREFIX}4)。`,+ );+});++test("does not absorb a phrase naming a different locator", () => {+ // "page 5" is not what [p.3] points at, so both stay as they are.+ assert.equal(+ linkifyLocatorCitations("Unlike page 5, this is explained here [p.3]."),+ `Unlike page 5, this is explained here [p.3](${LOCATOR_HREF_PREFIX}3).`,+ );+});++test("does not reach across a sentence boundary", () => {+ assert.equal(+ linkifyLocatorCitations("It is on page 3. A different claim follows [p.3]."),+ `It is on page 3. A different claim follows [p.3](${LOCATOR_HREF_PREFIX}3).`,+ );+});++test("does not absorb from inside code", () => {+ const text = "Set `page 3` in the config, as documented [p.3].";+ assert.equal(+ linkifyLocatorCitations(text),+ `Set \`page 3\` in the config, as documented [p.3](${LOCATOR_HREF_PREFIX}3).`,+ );+});++test("leaves a multi-locator citation as a marker", () => {+ // There is no single phrase for "[p.3,7]" to absorb.+ assert.equal(+ linkifyLocatorCitations("Both places discuss it on page 3 [p.3,7]."),+ `Both places discuss it on page 3 [p.3,7](${LOCATOR_HREF_PREFIX}3).`,+ );+});++test("absorption survives several citations in one answer", () => {+ assert.equal(+ linkifyLocatorCitations("First on page 1 [p.1], then on page 2 [p.2]."),+ `First on [page 1](${LOCATOR_HREF_PREFIX}1), then on [page 2](${LOCATOR_HREF_PREFIX}2).`,+ );+});++test("a marker with no nearby phrase still renders as a marker", () => {+ assert.equal(+ linkifyLocatorCitations("Order is injected explicitly rather than learned [p.3]."),+ `Order is injected explicitly rather than learned [p.3](${LOCATOR_HREF_PREFIX}3).`,+ );+});++test("absorption is still idempotent", () => {+ const once = linkifyLocatorCitations("It is on page 3 of the document [p.3].");+ assert.equal(linkifyLocatorCitations(once), once);+});diff --git a/web/tests/reading-quote-locator.test.ts b/web/tests/reading-quote-locator.test.tsnew file mode 100644index 000000000..538174ab5--- /dev/null+++ b/web/tests/reading-quote-locator.test.ts@@ -0,0 +1,145 @@+import test from "node:test";+import assert from "node:assert/strict";+import { findQuoteRange } from "../lib/reading-quote-locator";++// A pdf.js text layer splits a line into many spans and keeps the PDF's own+// hard wraps, so these segment arrays mimic what the DOM actually contains.+const SPANS = [+ "Transformers use ",+ "scaled dot-product\n",+ "attention over all ",+ "tokens.",+];++// Regression: a real pdf.js text layer splits at visual line breaks and its+// spans do NOT end with whitespace, so naive concatenation glues the last word+// of one line to the first word of the next ("Sinusoidalpositional"). The+// fixture above happens to end every span with a space, which hid this.+const REAL_LAYER_SPANS = [+ "Positional encoding",+ "Because attention is permutation invariant, order must be injected explicitly. Sinusoidal",+ "positional encodings add a fixed pattern to each embedding, letting the model infer",+ "relative offsets without learning them from scratch.",+];++test("finds a quote across a span boundary that carries no trailing space", () => {+ const found = findQuoteRange(+ REAL_LAYER_SPANS,+ "Sinusoidal positional encodings add a fixed pattern to each embedding",+ );+ assert.ok(found, "quote spanning the un-spaced boundary must be found");+ assert.equal(found.start.segment, 1);+ assert.equal(found.end.segment, 2);+ assert.equal(found.mode, "collapsed");+});++test("a quote wholly inside one un-spaced span still matches", () => {+ const found = findQuoteRange(REAL_LAYER_SPANS, "permutation invariant");+ assert.ok(found);+ assert.equal(found.start.segment, 1);+});++test("CJK still matches across boundaries, where no space belongs", () => {+ // The joining space would break this one, so the no-join pass has to exist.+ const found = findQuoteRange(["本文讨论注意", "力机制的实现"], "注意力机制");+ assert.ok(found);+ assert.equal(found.start.segment, 0);+ assert.equal(found.end.segment, 1);+});++test("finds a quote that spans several spans and a hard wrap", () => {+ const found = findQuoteRange(SPANS, "scaled dot-product attention");+ assert.ok(found);+ assert.equal(found.start.segment, 1);+ assert.equal(found.start.offset, 0);+ assert.equal(found.end.segment, 2);+ assert.equal(found.mode, "collapsed");+});++test("is case-insensitive", () => {+ assert.ok(findQuoteRange(SPANS, "SCALED DOT-PRODUCT"));+});++test("tolerates collapsed whitespace differences in the quote", () => {+ assert.ok(findQuoteRange(SPANS, "scaled dot-product\n\tattention"));+});++test("softens punctuation the PDF renders differently", () => {+ const spans = ["He said “hello world” loudly"];+ const found = findQuoteRange(spans, '"hello world"');+ assert.ok(found);+ assert.equal(found.mode, "softened");+});++test("softens a dash mismatch", () => {+ const found = findQuoteRange(["a state—of—the—art result"], "state-of-the-art");+ assert.ok(found);+});++test("falls back to the longest matching prefix of a drifting quote", () => {+ const spans = ["Positional encoding injects order information into the model."];+ const found = findQuoteRange(+ spans,+ "Positional encoding injects order information and then some words that are not in the document at all",+ );+ assert.ok(found);+ assert.equal(found.mode, "softened");+ assert.equal(found.start.segment, 0);+ assert.equal(found.start.offset, 0);+ // Stops where the document stops agreeing, rather than at a fixed fraction.+ assert.ok(found.end.offset > 40 && found.end.offset < 60);+});++test("a prefix too short to be credible is not highlighted", () => {+ // Only "the " would match — far below the share of the quote required.+ assert.equal(+ findQuoteRange(+ ["the model is described here"],+ "the quick brown fox jumps over the lazy dog repeatedly and often",+ ),+ null,+ );+});++test("returns null rather than guessing when the quote is absent", () => {+ assert.equal(findQuoteRange(SPANS, "quantum flux capacitor calibration"), null);+});++test("returns null for empty inputs", () => {+ assert.equal(findQuoteRange([], "anything"), null);+ assert.equal(findQuoteRange(SPANS, ""), null);+ assert.equal(findQuoteRange(SPANS, " "), null);+});++test("a very short quote does not trigger the head fallback", () => {+ // "zzz" is absent; the head fallback needs >= 8 chars, so this must be null+ // rather than matching something arbitrary.+ assert.equal(findQuoteRange(SPANS, "zzz"), null);+});++test("end offset is exclusive, as DOM Range expects", () => {+ const found = findQuoteRange(["abcdef"], "abc");+ assert.ok(found);+ assert.equal(found.start.offset, 0);+ assert.equal(found.end.offset, 3);+});++test("finds a match at the very end of the last segment", () => {+ const found = findQuoteRange(SPANS, "tokens");+ assert.ok(found);+ assert.equal(found.start.segment, 3);+ assert.equal(found.end.offset, 6);+});++test("handles CJK text without whitespace cues", () => {+ const found = findQuoteRange(["本文讨论", "注意力机制的实现细节"], "注意力机制");+ assert.ok(found);+ assert.equal(found.start.segment, 1);+});++test("leading and trailing whitespace in segments does not shift the match", () => {+ const found = findQuoteRange([" ", " alpha beta ", " "], "alpha beta");+ assert.ok(found);+ assert.equal(found.start.segment, 1);+ assert.equal(found.start.offset, 2);+});diff --git a/web/tests/reading-reader-action.test.ts b/web/tests/reading-reader-action.test.tsnew file mode 100644index 000000000..8f7212686--- /dev/null+++ b/web/tests/reading-reader-action.test.ts@@ -0,0 +1,207 @@+import test from "node:test";+import assert from "node:assert/strict";+import { readerActionFrom } from "../lib/reading-reader-action";++// The shape the dispatcher actually emits: the tool's own metadata is NESTED+// under `tool_metadata`, next to the dispatcher's trace keys. Reading the top+// level instead type-checks fine and silently never matches — which is exactly+// how the reader ended up ignoring every reader_goto the model made.+const realEvent = (toolMetadata: Record<string, unknown>) => ({+ type: "tool_result",+ metadata: {+ tool: "reader_goto",+ trace_kind: "tool_result",+ trace_id: "chat-1",+ tool_metadata: toolMetadata,+ },+});++test("reads a goto out of the dispatcher's nested metadata", () => {+ const action = readerActionFrom(+ realEvent({+ material_id: "d138eacaad029843",+ reader_action: "goto",+ locator: 5,+ quote: "Removing recurrence entirely",+ corrected_from: null,+ }),+ );+ assert.ok(action);+ assert.equal(action.reader_action, "goto");+ assert.equal(action.locator, 5);+ assert.equal(action.quote, "Removing recurrence entirely");+ assert.equal(action.material_id, "d138eacaad029843");+});++test("reads an annotate, carrying the stored row", () => {+ const action = readerActionFrom(+ realEvent({+ reader_action: "annotate",+ locator: 2,+ annotation: { annotation_id: "abc123", locator: 2, quote: "x" },+ }),+ );+ assert.ok(action);+ assert.equal(action.reader_action, "annotate");+ assert.equal((action.annotation as { annotation_id: string }).annotation_id, "abc123");+});++test("still accepts a flat payload, for events emitted directly", () => {+ const action = readerActionFrom({+ type: "tool_result",+ metadata: { reader_action: "goto", locator: 3 },+ });+ assert.ok(action);+ assert.equal(action.locator, 3);+});++test("ignores tool results that carry no reader action", () => {+ assert.equal(+ readerActionFrom(realEvent({ material_id: "abc", locators: [1, 2] })),+ null,+ );+ assert.equal(+ readerActionFrom({ type: "tool_result", metadata: { tool: "web_search" } }),+ null,+ );+});++test("ignores every other event type", () => {+ for (const type of ["content", "tool_call", "done", "sources", "error"]) {+ assert.equal(+ readerActionFrom({ type, metadata: { tool_metadata: { reader_action: "goto", locator: 1 } } }),+ null,+ type,+ );+ }+});++test("drops nonsense locators rather than jumping somewhere arbitrary", () => {+ assert.equal(readerActionFrom(realEvent({ reader_action: "goto", locator: 0 }))?.locator, undefined);+ assert.equal(readerActionFrom(realEvent({ reader_action: "goto", locator: -2 }))?.locator, undefined);+ assert.equal(+ readerActionFrom(realEvent({ reader_action: "goto", locator: "abc" }))?.locator,+ undefined,+ );+});++test("tolerates malformed metadata", () => {+ assert.equal(readerActionFrom({ type: "tool_result" }), null);+ assert.equal(readerActionFrom({ type: "tool_result", metadata: null }), null);+ assert.equal(readerActionFrom({ type: "tool_result", metadata: "nope" }), null);+ assert.equal(+ readerActionFrom({ type: "tool_result", metadata: { tool_metadata: "nope" } }),+ null,+ );+});++// ── Turn-end fallback ───────────────────────────────────────────────────────+// The model is asked to call reader_goto per passage, and mostly does — but a+// turn that cites [p.5] while the reader sits on page 1 looks broken regardless+// of whose fault it is. The pane needs to know whether the turn ever moved it.++import {+ READER_TURN_END_EVENT,+ forwardReaderAction,+ resetReaderActionTracking,+} from "../lib/reading-reader-action";++/** Minimal window stub: these functions only dispatch DOM events. */+function withWindow<T>(run: (seen: Array<{ type: string; detail: unknown }>) => T): T {+ const seen: Array<{ type: string; detail: unknown }> = [];+ const previous = (globalThis as { window?: unknown }).window;+ (globalThis as { window?: unknown }).window = {+ dispatchEvent: (e: { type: string; detail: unknown }) => {+ seen.push({ type: e.type, detail: e.detail });+ return true;+ },+ };+ class FakeCustomEvent {+ type: string;+ detail: unknown;+ constructor(type: string, init?: { detail?: unknown }) {+ this.type = type;+ this.detail = init?.detail;+ }+ }+ const prevCE = (globalThis as { CustomEvent?: unknown }).CustomEvent;+ (globalThis as { CustomEvent?: unknown }).CustomEvent = FakeCustomEvent;+ try {+ return run(seen);+ } finally {+ (globalThis as { window?: unknown }).window = previous;+ (globalThis as { CustomEvent?: unknown }).CustomEvent = prevCE;+ }+}++const gotoEvent = (turnId: string) => ({+ type: "tool_result",+ turn_id: turnId,+ metadata: { tool_metadata: { reader_action: "goto", locator: 5 } },+});++test("a turn that moved the reader reports moved=true", () => {+ resetReaderActionTracking();+ withWindow((seen) => {+ forwardReaderAction(gotoEvent("turn-1"));+ forwardReaderAction({ type: "done", turn_id: "turn-1" });+ const end = seen.find((e) => e.type === READER_TURN_END_EVENT);+ assert.ok(end);+ assert.deepEqual(end.detail, { moved: true });+ });+});++test("a turn that never moved it reports moved=false, so the pane can follow", () => {+ resetReaderActionTracking();+ withWindow((seen) => {+ forwardReaderAction({ type: "content", turn_id: "turn-2" });+ forwardReaderAction({ type: "done", turn_id: "turn-2" });+ const end = seen.find((e) => e.type === READER_TURN_END_EVENT);+ assert.deepEqual(end?.detail, { moved: false });+ });+});++test("turns are tracked separately", () => {+ resetReaderActionTracking();+ withWindow((seen) => {+ forwardReaderAction(gotoEvent("turn-a"));+ forwardReaderAction({ type: "done", turn_id: "turn-b" });+ assert.deepEqual(+ seen.find((e) => e.type === READER_TURN_END_EVENT)?.detail,+ { moved: false },+ );+ forwardReaderAction({ type: "done", turn_id: "turn-a" });+ assert.deepEqual(+ seen.filter((e) => e.type === READER_TURN_END_EVENT)[1]?.detail,+ { moved: true },+ );+ });+});++test("a turn's record is cleared once it ends", () => {+ resetReaderActionTracking();+ withWindow((seen) => {+ forwardReaderAction(gotoEvent("turn-3"));+ forwardReaderAction({ type: "done", turn_id: "turn-3" });+ forwardReaderAction({ type: "done", turn_id: "turn-3" });+ const ends = seen.filter((e) => e.type === READER_TURN_END_EVENT);+ assert.deepEqual(ends[0].detail, { moved: true });+ assert.deepEqual(ends[1].detail, { moved: false });+ });+});++test("annotate alone does not count as having moved the reader", () => {+ resetReaderActionTracking();+ withWindow((seen) => {+ forwardReaderAction({+ type: "tool_result",+ turn_id: "turn-4",+ metadata: { tool_metadata: { reader_action: "annotate", locator: 2, annotation: { annotation_id: "a" } } },+ });+ forwardReaderAction({ type: "done", turn_id: "turn-4" });+ assert.deepEqual(+ seen.find((e) => e.type === READER_TURN_END_EVENT)?.detail,+ { moved: false },+ );+ });+});diff --git a/web/tests/reading-selection.test.ts b/web/tests/reading-selection.test.tsnew file mode 100644index 000000000..3887d1d37--- /dev/null+++ b/web/tests/reading-selection.test.ts@@ -0,0 +1,111 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ cleanQuote,+ locatorOfSelection,+ mergeRectsByLine,+ normaliseRects,+ unionRect,+} from "../lib/reading-selection";++const box = (left: number, top: number, width: number, height: number) => ({+ left,+ top,+ width,+ height,+});++const PAGE = box(100, 200, 800, 1000);++test("merges rects that share a text line into one", () => {+ const merged = mergeRectsByLine([+ box(10, 10, 50, 14),+ box(60, 10, 40, 14),+ box(10, 30, 90, 14),+ ]);+ assert.equal(merged.length, 2);+ assert.deepEqual(merged[0], box(10, 10, 90, 14));+});++test("treats vertically overlapping rects of different heights as one line", () => {+ // A superscript sits higher and is shorter, but belongs to the same line.+ const merged = mergeRectsByLine([box(10, 10, 50, 14), box(60, 8, 8, 8)]);+ assert.equal(merged.length, 1);+});++test("drops sliver rects the browser emits at range edges", () => {+ const merged = mergeRectsByLine([box(10, 10, 50, 14), box(61, 10, 1, 14)]);+ assert.equal(merged.length, 1);+ assert.deepEqual(merged[0], box(10, 10, 50, 14));+});++test("no usable rects yields nothing rather than a degenerate box", () => {+ assert.deepEqual(mergeRectsByLine([]), []);+ assert.deepEqual(mergeRectsByLine([box(0, 0, 0, 0)]), []);+ assert.deepEqual(mergeRectsByLine([box(5, 5, 1, 1)]), []);+});++test("normalises to 0..1 of the container box", () => {+ const rects = normaliseRects([box(100, 200, 400, 100)], PAGE);+ assert.deepEqual(rects, [[0, 0, 0.5, 0.1]]);+});++test("normalisation is scroll-independent because both rects are viewport-space", () => {+ const scrolled = normaliseRects(+ [box(100 - 300, 200 - 300, 400, 100)],+ box(100 - 300, 200 - 300, 800, 1000),+ );+ assert.deepEqual(scrolled, [[0, 0, 0.5, 0.1]]);+});++test("clips a selection dragged off the page instead of discarding it", () => {+ const rects = normaliseRects([box(0, 100, 2000, 200)], PAGE);+ assert.equal(rects.length, 1);+ const [x0, y0, x1, y1] = rects[0];+ assert.ok(x0 >= 0 && y0 >= 0 && x1 <= 1 && y1 <= 1);+ assert.ok(x1 - x0 > 0);+});++test("a zero-sized container yields no rects rather than dividing by zero", () => {+ assert.deepEqual(normaliseRects([box(0, 0, 10, 10)], box(0, 0, 0, 0)), []);+});++test("drops rects that normalise to nothing", () => {+ // Entirely above the page: clamps to a zero-height sliver, so it is dropped.+ assert.deepEqual(normaliseRects([box(100, 0, 400, 4)], PAGE), []);+});++test("unionRect wraps every rect", () => {+ assert.deepEqual(+ unionRect([+ [0.1, 0.1, 0.4, 0.2],+ [0.05, 0.3, 0.6, 0.35],+ ]),+ [0.05, 0.1, 0.6, 0.35],+ );+ assert.equal(unionRect([]), null);+});++test("cleanQuote collapses the hard wraps a pdf text layer introduces", () => {+ assert.equal(+ cleanQuote("Transformers use scaled\n dot-product\tattention today."),+ "Transformers use scaled dot-product attention today.",+ );+});++test("cleanQuote bounds an enormous selection", () => {+ assert.equal(cleanQuote("x".repeat(5000)).length, 2000);+ assert.equal(cleanQuote("x".repeat(50), 10).length, 10);+});++test("cleanQuote tolerates empty input", () => {+ assert.equal(cleanQuote(""), "");+ assert.equal(cleanQuote(" \n "), "");+});++test("a cross-page selection is attributed to where it started", () => {+ assert.equal(locatorOfSelection([3, 4]), 3);+ assert.equal(locatorOfSelection([null, 4]), 4);+ assert.equal(locatorOfSelection([null, null]), null);+ assert.equal(locatorOfSelection([0, 2]), 2);+});diff --git a/web/tests/reading-split.test.ts b/web/tests/reading-split.test.tsnew file mode 100644index 000000000..971f67011--- /dev/null+++ b/web/tests/reading-split.test.ts@@ -0,0 +1,66 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ CHAT_MIN_PX,+ READER_MAX_PX,+ READER_MIN_PX,+ clampReaderWidth,+ parseStoredWidth,+} from "../lib/reading-split";++test("keeps a reasonable width untouched", () => {+ assert.equal(clampReaderWidth(900, 1380), 900);+ assert.equal(clampReaderWidth(600, 1380), 600);+});++test("never lets the reader get too narrow to read", () => {+ assert.equal(clampReaderWidth(50, 1380), READER_MIN_PX);+ assert.equal(clampReaderWidth(0, 1380), READER_MIN_PX);+ assert.equal(clampReaderWidth(-400, 1380), READER_MIN_PX);+});++test("always leaves the conversation a usable column", () => {+ const available = 1380;+ const widest = clampReaderWidth(99999, available);+ assert.equal(available - widest, CHAT_MIN_PX);+});++test("respects the absolute ceiling on a very wide display", () => {+ // 4000 - 380 = 3620, but no reader needs to be wider than READER_MAX_PX.+ assert.equal(clampReaderWidth(99999, 4000), READER_MAX_PX);+});++test("on a narrow container the reader floor wins over the chat floor", () => {+ // 600 - 380 = 220, below the reader minimum. Overflowing slightly beats a+ // 220px reader; below `lg` the split does not exist at all.+ assert.equal(clampReaderWidth(500, 600), READER_MIN_PX);+});++test("an unknown container falls back to the absolute bounds", () => {+ // Server render, or a measurement taken before layout. The CSS carries its+ // own percentage ceiling for exactly this case.+ assert.equal(clampReaderWidth(99999, 0), READER_MAX_PX);+ assert.equal(clampReaderWidth(900, 0), 900);+ assert.equal(clampReaderWidth(10, -1), READER_MIN_PX);+});++test("nonsense input degrades to the minimum rather than NaN", () => {+ assert.equal(clampReaderWidth(Number.NaN, 1380), READER_MIN_PX);+ assert.equal(clampReaderWidth(Number.POSITIVE_INFINITY, 1380), READER_MIN_PX);+});++test("always returns a whole pixel", () => {+ assert.equal(clampReaderWidth(700.6, 1380), 701);+ assert.ok(Number.isInteger(clampReaderWidth(612.4, 1380)));+});++test("parseStoredWidth accepts a stored number and rejects junk", () => {+ assert.equal(parseStoredWidth("820"), 820);+ assert.equal(parseStoredWidth("820.5"), 820.5);+ assert.equal(parseStoredWidth(null), null);+ assert.equal(parseStoredWidth(""), null);+ assert.equal(parseStoredWidth("wide"), null);+ assert.equal(parseStoredWidth("0"), null);+ assert.equal(parseStoredWidth("-500"), null);+ assert.equal(parseStoredWidth("Infinity"), null);+});diff --git a/web/tests/reading-turn-state.test.ts b/web/tests/reading-turn-state.test.tsnew file mode 100644index 000000000..750100c9c--- /dev/null+++ b/web/tests/reading-turn-state.test.ts@@ -0,0 +1,81 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ READING_CAPABILITY,+ getReadingTurnState,+ readingTurnFields,+ resetReadingTurnState,+ setReadingMaterial,+ setReadingViewport,+} from "../lib/reading-turn-state";++test.beforeEach(() => resetReadingTurnState());++test("carries the document and viewport on a reading turn", () => {+ setReadingMaterial("d138eacaad029843");+ setReadingViewport({ locator: 3, selection: "attention" });++ assert.deepEqual(readingTurnFields(READING_CAPABILITY), {+ reading_material_id: "d138eacaad029843",+ reading_viewport: { locator: 3, selection: "attention" },+ });+});++// Regression: the open document lives in a provider mounted in the workspace+// layout, so it survives a mode switch AND a new session. Keying only on "is a+// document open" attached the reader to every later turn — a brand-new chat+// session would open with "I see you're reading …" and cite pages from a+// document the user had moved on from.+test("carries nothing once the user switches to another mode", () => {+ setReadingMaterial("d138eacaad029843");+ setReadingViewport({ locator: 3 });++ for (const capability of ["", "deep_solve", "deep_research", "mastery_path", "visualize"]) {+ assert.deepEqual(readingTurnFields(capability), {}, capability);+ }+});++test("carries nothing when the capability is absent", () => {+ setReadingMaterial("d138eacaad029843");+ assert.deepEqual(readingTurnFields(null), {});+ assert.deepEqual(readingTurnFields(undefined), {});+});++test("the document itself is kept, so returning to the mode resumes it", () => {+ setReadingMaterial("d138eacaad029843");+ setReadingViewport({ locator: 7 });++ // Away…+ assert.deepEqual(readingTurnFields("deep_solve"), {});+ // …and back, with the reader still where it was.+ assert.equal(getReadingTurnState().materialId, "d138eacaad029843");+ assert.equal(readingTurnFields(READING_CAPABILITY).reading_viewport?.locator, 7);+});++test("carries nothing in reading mode with no document open", () => {+ assert.deepEqual(readingTurnFields(READING_CAPABILITY), {});+});++test("closing the document clears its viewport too", () => {+ setReadingMaterial("d138eacaad029843");+ setReadingViewport({ locator: 9, selection: "x" });+ setReadingMaterial(null);++ assert.deepEqual(readingTurnFields(READING_CAPABILITY), {});+ assert.deepEqual(getReadingTurnState(), { materialId: null, locator: 0, selection: "" });+});++test("a viewport with no locator or selection is omitted, not sent empty", () => {+ setReadingMaterial("d138eacaad029843");+ assert.deepEqual(readingTurnFields(READING_CAPABILITY), {+ reading_material_id: "d138eacaad029843",+ });+});++test("nonsense viewport values are ignored", () => {+ setReadingMaterial("d138eacaad029843");+ setReadingViewport({ locator: -3 });+ assert.equal(readingTurnFields(READING_CAPABILITY).reading_viewport, undefined);+ setReadingViewport({ locator: 2.7 });+ assert.equal(readingTurnFields(READING_CAPABILITY).reading_viewport?.locator, 2);+});diff --git a/web/tests/setup-signals.test.ts b/web/tests/setup-signals.test.tsnew file mode 100644index 000000000..774be8216--- /dev/null+++ b/web/tests/setup-signals.test.ts@@ -0,0 +1,137 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ collectAppliedSettingIds,+ extractSetupCredential,+} from "../lib/setup-signals";+import type { StreamEvent } from "../lib/unified-ws";++function toolResult(+ toolMetadata: Record<string, unknown>,+ extra: Partial<StreamEvent> = {},+): StreamEvent {+ return {+ type: "tool_result",+ source: "test",+ stage: "loop",+ content: "",+ metadata: { tool_metadata: toolMetadata },+ session_id: "session-1",+ turn_id: "turn-1",+ seq: 1,+ timestamp: 0,+ ...extra,+ } as StreamEvent;+}++test("extractSetupCredential reads the hand-off payload", () => {+ const data = extractSetupCredential([+ toolResult({+ setup_credential: {+ service: "llm",+ label: "chat model provider",+ settings_path: "/settings/llm",+ reason: "需要 API key",+ },+ }),+ ]);+ assert.deepEqual(data, {+ service: "llm",+ label: "chat model provider",+ settingsPath: "/settings/llm",+ reason: "需要 API key",+ });+});++test("extractSetupCredential keeps the most recent hand-off", () => {+ const data = extractSetupCredential([+ toolResult({ setup_credential: { settings_path: "/settings/llm" } }),+ toolResult({ setup_credential: { settings_path: "/settings/search" } }),+ ]);+ assert.equal(data?.settingsPath, "/settings/search");+});++test("extractSetupCredential refuses a path outside settings", () => {+ // The path is navigated to, so anything that is not an in-app settings route+ // would make the card an open redirect.+ for (const path of [+ "https://evil.example.com",+ "//evil.example.com",+ "/home",+ "",+ ]) {+ assert.equal(+ extractSetupCredential([+ toolResult({ setup_credential: { settings_path: path } }),+ ]),+ null,+ `should reject ${path}`,+ );+ }+});++test("extractSetupCredential ignores unrelated tool results", () => {+ assert.equal(+ extractSetupCredential([+ toolResult({ ask_user: { questions: [] } }),+ toolResult({ setup_inspect: { settings: [] } }),+ ]),+ null,+ );+ assert.equal(extractSetupCredential([]), null);+ assert.equal(extractSetupCredential(undefined), null);+});++test("collectAppliedSettingIds returns one id per applied change", () => {+ const ids = collectAppliedSettingIds([+ {+ events: [+ toolResult(+ { setup_applied: { key: "interface.language" } },+ { tool_call_id: "call-1" } as Partial<StreamEvent>,+ ),+ toolResult(+ { setup_applied: { key: "interface.theme" } },+ { tool_call_id: "call-2" } as Partial<StreamEvent>,+ ),+ ],+ },+ ]);+ assert.deepEqual(ids, ["call-1", "call-2"]);+});++test("collectAppliedSettingIds deduplicates a replayed tool call", () => {+ // History replay re-delivers the same event; honouring it twice would+ // overwrite a preference the user has since changed by hand.+ const event = toolResult(+ { setup_applied: { key: "interface.theme" } },+ { tool_call_id: "call-1" } as Partial<StreamEvent>,+ );+ const ids = collectAppliedSettingIds([{ events: [event] }, { events: [event] }]);+ assert.deepEqual(ids, ["call-1"]);+});++test("collectAppliedSettingIds falls back to key and seq without a call id", () => {+ const ids = collectAppliedSettingIds([+ {+ events: [+ toolResult({ setup_applied: { key: "interface.theme" } }, { seq: 7 }),+ toolResult({ setup_applied: { key: "interface.theme" } }, { seq: 9 }),+ ],+ },+ ]);+ assert.deepEqual(ids, ["interface.theme:7", "interface.theme:9"]);+});++test("collectAppliedSettingIds ignores turns that changed nothing", () => {+ assert.deepEqual(+ collectAppliedSettingIds([+ { events: [toolResult({ setup_inspect: { settings: [] } })] },+ { events: [] },+ {},+ ]),+ [],+ );+ assert.deepEqual(collectAppliedSettingIds(undefined), []);+});