DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
release: v1.6.10
Bingxi Zhao (Frank)eabc17d79ff3
diff --git a/README.md b/README.mdindex 751d3a5f8..e5dbc39f7 100644--- a/README.md+++ b/README.md@@ -49,6 +49,8 @@### 📦 Releases+> **[2026.9.22]** [v1.6.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.6.10) — Native LightRAG role models, a published index that records and enforces what built it, PDF attachments that follow your parsing engine, visible truncation, and unfiltered provider choices.+> **[2026.9.21]** [v1.6.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.6.9) — Folder-based learning workspaces, daily practice, redesigned Settings, clearer streaming conversations, persistent usage accounting, and recoverable archives with explicit permanent deletion.<details>@@ -212,7 +214,7 @@</details>-> ✨ **v1.6.9 is live.** `pip install -U deeptutor` picks up the latest stable release.+> ✨ **v1.6.10 is live.** `pip install -U deeptutor` picks up the latest stable release.### 📰 Newsdiff --git a/assets/README/README_AR.md b/assets/README/README_AR.mdindex b6808ad0f..55179b8ee 100644--- a/assets/README/README_AR.md+++ b/assets/README/README_AR.md@@ -65,7 +65,7 @@ DeepTutor هو بيئة تعلم أصيلة للوكلاء تربط التدري- **سياق تعلم متصل** — يمكن إعادة استخدام قواعد المعرفة والكتب ومسودات Co-Writer ودفاتر الملاحظات وبنوك الأسئلة والشخصيات والذاكرة عبر سير العمل التي تدعمها، وفقاً لمنح الحساب وسياسات التعلّم.- **التعلّم الغامر بالفيديو** — ألصق رابط YouTube لتشغيل أصلي معزَّز الخصوصية، وترجمات متزامنة، وتدريس مرتكز على الطوابع الزمنية، وتقدّم قابل للاستئناف؛ ويمكن للمشرفين تحويل التشغيل إلى نسخة Invidious ذاتية الاستضافة دون إعادة بناء المواد.- **الوكلاء الفرعيون والشركاء** — من داخل Chat، استشر مُشغِّل وكيل حيّاً (Claude Code أو Codex أو Antigravity أو Kimi أو opencode أو MiMo أو Hermes أو OpenClaw أو DeepSeek) أو Partner، واستورد المحادثات السابقة، وشغّل رفاق IM دائمين على نفس الدماغ.-- **معرفة متعددة المحركات** — مكتبات RAG مُصدَّرة عبر LlamaIndex وPageIndex وGraphRAG وLightRAG، أو LightRAG Server عن بُعد، أو قاعدة معرفة WeKnora ذاتية الاستضافة، أو مكتبة Tencent IMA أو MarginNote 4، أو مخزن Obsidian مرتبط، مع تحليل مستندات قابل للتوصيل.+- **معرفة متعددة المحركات** — مكتبات RAG مُصدَّرة عبر LlamaIndex وPageIndex وGraphRAG وLightRAG، أو LightRAG Server عن بُعد، أو قاعدة معرفة WeKnora ذاتية الاستضافة، أو مكتبة Tencent IMA أو MarginNote 4، أو مخزن Obsidian مرتبط، مع تحليل مستندات قابل للتوصيل. راجع [نماذج أدوار LightRAG الأصلية](../../deeptutor/services/rag/pipelines/lightrag/README.md) لإعدادات مستقلة للاستخراج والاستعلام والرؤية، والإنشاء بالنماذج الافتراضية فقط، وإعادة البناء بعد التأكيد.- **أدوات ومهارات قابلة للتوسيع** — أدوات مدمجة وخوادم MCP وتطبيقات CLI ونماذج توليد الصور/الفيديو/الصوت ومهارات مجتمع قابلة للتثبيت من EduHub.- **ذاكرة قابلة للتدقيق** — تجعل آثار L1 وملخصات أسطح L2 وتركيب L3 التخصيص مرئياً وقابلاً للتحرير؛ ويربط Memory Graph حقائق L2 بأدلة L1 وتركيب L3 بالأسطح المساهمة.@@ -525,6 +525,8 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقايُثبَّت محرك LightRAG المدمج عبر `pip install 'deeptutor[rag-lightrag]'`. تحتوي هذه الإضافة على SDK الخاص بـ LightRAG المدعوم لكنها لا تُثبِّت MinerU. اختر MinerU بشكل مستقل في تحليل المستندات، وإما هيّئ وضعه السحابي أو ثبّت واجهة سطر أوامره المحلية الحالية عندما تحتاج إلى تحليل منظَّم. يقبل MinerU ملفات PDF والصور النقطية الشائعة وDOCX وPPTX وXLSX؛ ويظل الأمر القديم `magic-pdf` مقصوراً على PDF. لا يتطلب وضع النص فقط ومحركات التحليل الأخرى MinerU.+يتطلب استعلام LightRAG الأصلي والفهرسة التزايدية تهيئة التضمين المسجَّلة في الفهرس المنشور، بما يشمل النموذج والبُعد وهوية نقطة النهاية. إذا تغيّرت، فاستعد التهيئة الأصلية أو أعد البناء باستخدام التضمين الحالي؛ والفهارس التي لا تحمل هوية تضمين مسجَّلة تتطلب إعادة البناء. تعرض صفحات تفاصيل قاعدة المعرفة وإصدارات الفهرس إرشادات التعافي، بينما تبقى الملفات متاحة للعرض والتنزيل.+</details><details>diff --git a/assets/README/README_CN.md b/assets/README/README_CN.mdindex 57abd599c..391e5b622 100644--- a/assets/README/README_CN.md+++ b/assets/README/README_CN.md@@ -65,7 +65,7 @@ DeepTutor 是一个智能体原生的学习工作区,将辅导、解题、测- **互联的学习上下文** — 知识库、书籍、Co-Writer 草稿、笔记本、题库、人格预设和 Memory 可在支持它们的工作流中复用,并受账号授权与学习策略约束。- **沉浸式视频学习** — 粘贴 YouTube 链接,即可使用隐私增强的原生播放、同步字幕、基于时间戳的辅导和可续接的学习进度;管理员可以将播放切换到自托管的 Invidious 实例,无需重新构建素材。- **子智能体与 Partners** — 在 Chat 中调用实时智能体运行框架(Claude Code、Codex、Antigravity、Kimi、opencode、MiMo、Hermes、OpenClaw 或 DeepSeek)或 Partner、导入历史对话,并让持久化 IM 伴侣运行在同一套大脑之上。-- **多引擎知识库** — 跨 LlamaIndex、PageIndex、GraphRAG、LightRAG、远程 LightRAG Server、自托管的 WeKnora 知识库、Tencent IMA 或 MarginNote 4 知识库,或链接的 Obsidian vault 的版本化 RAG 知识库,支持可插拔的文档解析。+- **多引擎知识库** — 跨 LlamaIndex、PageIndex、GraphRAG、LightRAG、远程 LightRAG Server、自托管的 WeKnora 知识库、Tencent IMA 或 MarginNote 4 知识库,或链接的 Obsidian vault 的版本化 RAG 知识库,支持可插拔的文档解析。详见[原生 LightRAG 角色模型](../../deeptutor/services/rag/pipelines/lightrag/README.md),了解独立的抽取、查询与视觉设置、仅默认创建以及确认后的重建。- **可扩展工具与技能** — 内置工具、MCP 服务器、CLI 应用、图像 / 视频 / 语音生成模型,以及从 EduHub 安装的社区技能。- **可审计的记忆** — L1 追踪、L2 表面摘要和 L3 综合让个性化透明可编辑;Memory Graph 将 L2 事实关联至 L1 证据,并将 L3 综合关联至参与的表面层。@@ -525,6 +525,8 @@ Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而内置的 LightRAG 引擎通过 `pip install 'deeptutor[rag-lightrag]'` 安装。该额外依赖包含受支持的 LightRAG SDK,但不会安装 MinerU。如需结构化解析,请在文档解析中单独选择 MinerU,并配置其云端模式或安装当前的本地 CLI。MinerU 支持 PDF、常见的光栅图像、DOCX、PPTX 和 XLSX;旧版 `magic-pdf` 命令仍仅支持 PDF。纯文本及其他解析引擎均不需要 MinerU。+原生 LightRAG 的查询与增量索引依赖已发布索引所记录的嵌入配置,包括模型、维度和端点身份。如果该配置发生变化,需要恢复原始配置,或使用当前嵌入重建索引;未记录嵌入身份的索引则必须重建。知识库详情页和索引版本视图会显示恢复指引,同时文件仍可正常查看和下载。+</details><details>diff --git a/assets/README/README_ES.md b/assets/README/README_ES.mdindex cde84d786..f884bc9c6 100644--- a/assets/README/README_ES.md+++ b/assets/README/README_ES.md@@ -65,7 +65,7 @@ DeepTutor es un espacio de trabajo de aprendizaje nativo de agentes que conecta- **Contexto de aprendizaje conectado** — Las bases de conocimiento, los libros, los borradores de Co-Writer, los cuadernos, los bancos de preguntas, las personas y Memory pueden reutilizarse en los flujos de trabajo que los admiten, sujetos a los permisos de la cuenta y a las políticas de aprendizaje.- **Aprendizaje inmersivo por vídeo** — pega un enlace de YouTube para una reproducción nativa con privacidad mejorada, subtítulos sincronizados, tutoría basada en marcas de tiempo y progreso reanudable; los administradores pueden cambiar la reproducción a una instancia de Invidious autoalojada sin reconstruir los materiales.- **Subagentes y Partners** — desde Chat, consulta un entorno de agente en vivo (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw o DeepSeek) o un Partner, importa conversaciones pasadas y ejecuta compañeros IM persistentes con el mismo cerebro.-- **Conocimiento multi-motor** — bibliotecas RAG con versiones: LlamaIndex, PageIndex, GraphRAG, LightRAG, un LightRAG Server remoto, una base de conocimiento WeKnora autoalojada, una biblioteca de Tencent IMA o MarginNote 4, 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, una base de conocimiento WeKnora autoalojada, una biblioteca de Tencent IMA o MarginNote 4, o un vault Obsidian vinculado, con análisis de documentos conectable. Consulta los [modelos de rol nativos de LightRAG](../../deeptutor/services/rag/pipelines/lightrag/README.md) para conocer la configuración independiente de extracción, consulta y visión, la creación limitada a valores predeterminados y las reconstrucciones confirmadas.- **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** — las trazas L1, los resúmenes de superficie L2 y la síntesis L3 hacen visible y editable la personalización; el Memory Graph vincula los hechos L2 con la evidencia L1 y la síntesis L3 con las superficies que contribuyeron a ella.@@ -534,6 +534,8 @@ Al crear una KB, puedes **crear nueva** (subir documentos y construir un índiceEl motor LightRAG integrado se instala con `pip install 'deeptutor[rag-lightrag]'`. Ese extra contiene el SDK de LightRAG compatible pero no instala MinerU. Elige MinerU de forma independiente en Document Parsing y configura su modo en la nube o instala su CLI local vigente cuando se desee un análisis estructurado. MinerU acepta PDF, imágenes rasterizadas comunes, DOCX, PPTX y XLSX; el comando heredado `magic-pdf` sigue limitado a PDF. Text-only y los demás motores de análisis no requieren MinerU.+Las consultas nativas de LightRAG y la indexación incremental requieren la configuración de embeddings registrada por el índice publicado, incluyendo el modelo, la dimensión y la identidad del endpoint. Si cambia, restaura la configuración original o reconstruye con el embedding actual; los índices sin una identidad de embeddings registrada requieren una reconstrucción. Las vistas de detalle de la base de conocimiento y de versión de índice muestran orientación de recuperación, mientras los archivos permanecen disponibles para visualización y descarga.+</details><details>diff --git a/assets/README/README_FR.md b/assets/README/README_FR.mdindex bae1a55ee..932c11e48 100644--- a/assets/README/README_FR.md+++ b/assets/README/README_FR.md@@ -65,7 +65,7 @@ DeepTutor est un espace de travail d'apprentissage natif à l'agent qui connecte- **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 peuvent être réutilisés dans les flux de travail qui les prennent en charge, sous réserve des attributions du compte et des politiques d'apprentissage.- **Apprentissage vidéo immersif** — collez un lien YouTube pour une lecture native avec protection renforcée de la confidentialité, des sous-titres synchronisés, un tutorat ancré dans les horodatages et une progression reprenable ; les administrateurs peuvent basculer la lecture vers une instance Invidious auto-hébergée sans reconstruire les supports.- **Sous-agents et Partners** — depuis Chat, consultez un harness d'agent en direct (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw ou DeepSeek) ou un Partner, importez des 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, un LightRAG Server distant, un déploiement WeKnora auto-hébergé, une bibliothèque Tencent IMA ou MarginNote 4, 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, un déploiement WeKnora auto-hébergé, une bibliothèque Tencent IMA ou MarginNote 4, ou un vault Obsidian lié, avec une analyse de documents enfichable. Consultez les [modèles de rôle LightRAG natifs](../../deeptutor/services/rag/pipelines/lightrag/README.md) pour des paramètres d'extraction, de requête et de vision indépendants, une création limitée aux valeurs par défaut, et des reconstructions confirmées.- **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 ; le Memory Graph relie les faits L2 aux preuves L1 et la synthèse L3 aux surfaces contributrices.@@ -535,6 +535,8 @@ En créant une KB, vous choisissez soit de **créer nouvelle** (uploadez des docLe moteur LightRAG intégré s'installe avec `pip install 'deeptutor[rag-lightrag]'`. Cet extra contient le SDK LightRAG pris en charge mais n'installe pas MinerU. Choisissez MinerU indépendamment dans Analyse de Documents et configurez son mode cloud ou installez sa CLI locale actuelle pour l'analyse structurée. MinerU accepte les PDF, les images raster courantes, les fichiers DOCX, PPTX et XLSX ; l'ancienne commande `magic-pdf` reste limitée aux PDF. Le mode texte seul et les autres moteurs d'analyse n'ont pas besoin de MinerU.+Les requêtes LightRAG natives et l'indexation incrémentielle nécessitent la configuration d'embedding enregistrée par l'index publié, incluant le modèle, la dimension et l'identité du point de terminaison. Si elle change, restaurez la configuration d'origine ou reconstruisez avec l'embedding actuel ; les index sans identité d'embedding enregistrée nécessitent une reconstruction. Les vues de détail de la base de connaissances et de version d'index affichent des conseils de récupération, tandis que les fichiers restent disponibles pour la consultation et le téléchargement.+</details><details>diff --git a/assets/README/README_HI.md b/assets/README/README_HI.mdindex a3de5afff..c9fb92a93 100644--- a/assets/README/README_HI.md+++ b/assets/README/README_HI.md@@ -65,7 +65,7 @@ DeepTutor एक agent-native learning workspace है जो tutoring, problem- **जुड़ा हुआ लर्निंग कॉन्टेक्स्ट** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, और Memory को उन workflows में reuse किया जा सकता है जो उन्हें support करते हैं, account grants और learning policies के अधीन।- **इमर्सिव वीडियो लर्निंग** — privacy-enhanced native playback, synchronized captions, timestamp-grounded tutoring और resumable progress के लिए एक YouTube link paste करें; administrators materials को rebuild किए बिना playback को self-hosted Invidious instance पर switch कर सकते हैं।- **सब-एजेंट और Partners** — Chat से एक live agent harness (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw, या DeepSeek) या एक Partner से सलाह लें, पिछली conversations import करें, और same brain पर persistent IM companions चलाएं।-- **मल्टी-इंजन नॉलेज** — LlamaIndex, PageIndex, GraphRAG, LightRAG, एक remote LightRAG Server, एक self-hosted WeKnora knowledge base, एक Tencent IMA या MarginNote 4 library, या एक linked Obsidian vault के साथ versioned RAG libraries, pluggable document parsing के साथ।+- **मल्टी-इंजन नॉलेज** — LlamaIndex, PageIndex, GraphRAG, LightRAG, एक remote LightRAG Server, एक self-hosted WeKnora knowledge base, एक Tencent IMA या MarginNote 4 library, या एक linked Obsidian vault के साथ versioned RAG libraries, pluggable document parsing के साथ। independent extraction, query और vision settings, default-only creation और confirmed rebuilds के लिए [native LightRAG role models](../../deeptutor/services/rag/pipelines/lightrag/README.md) देखें।- **एक्सटेंसिबल टूल्स और स्किल्स** — 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 L2 facts को L1 evidence से और L3 synthesis को contributing surfaces से link करता है।@@ -525,6 +525,8 @@ KB बनाते समय, आप either **नया create** करतेBuilt-in LightRAG engine `pip install 'deeptutor[rag-lightrag]'` से install होता है। उस extra में supported LightRAG SDK शामिल है लेकिन यह MinerU install नहीं करता। Document Parsing में MinerU को स्वतंत्र रूप से चुनें और structured parsing चाहिए हो तो या तो इसका cloud mode configure करें या इसका current local CLI install करें। MinerU PDF, common raster images, DOCX, PPTX, और XLSX स्वीकार करता है; legacy `magic-pdf` command PDF-only रहता है। Text-only और बाकी parsing engines को MinerU की जरूरत नहीं होती।+Native LightRAG queries और incremental indexing को उस embedding configuration की जरूरत होती है जो published index द्वारा record की गई है, जिसमें model, dimension, और endpoint identity शामिल हैं। अगर यह बदल जाती है, तो original configuration restore करें या current embedding के साथ rebuild करें; जिन indexes में recorded embedding identity नहीं है उन्हें rebuild करना जरूरी है। Knowledge-base detail और index-version views recovery guidance दिखाते हैं, जबकि files viewing और download के लिए उपलब्ध रहती हैं।+</details><details>diff --git a/assets/README/README_JA.md b/assets/README/README_JA.mdindex 887be1794..89bdebe0d 100644--- a/assets/README/README_JA.md+++ b/assets/README/README_JA.md@@ -65,7 +65,7 @@ DeepTutorは、個別指導、問題解決、クイズ生成、研究、ビジ- **接続された学習コンテキスト** — 知識ベース、本、Co-Writerの下書き、ノートブック、問題バンク、ペルソナ、Memoryは、アカウントのグラントと学習ポリシーに従い、それらをサポートするワークフロー間で再利用できます。- **没入型動画学習** — YouTubeリンクを貼り付けるだけで、プライバシー強化ネイティブ再生、同期字幕、タイムスタンプに基づく個別指導、再開可能な進捗を利用できます。管理者は教材を再構築せずに、再生をセルフホストのInvidiousインスタンスへ切り替えられます。- **サブエージェントとPartners** — Chatからライブエージェントハーネス(Claude Code、Codex、Antigravity、Kimi、opencode、MiMo、Hermes、OpenClaw、DeepSeek)またはPartnerに相談し、過去の会話をインポートし、同じブレインで永続的なIMコンパニオンを実行できます。-- **マルチエンジン知識** — LlamaIndex、PageIndex、GraphRAG、LightRAG、リモートのLightRAG Server、セルフホストのWeKnora知識ベース、Tencent IMAまたはMarginNote 4ライブラリ、あるいはリンクされたObsidianボールトにまたがるバージョン管理されたRAGライブラリ(プラグ可能なドキュメント解析付き)。+- **マルチエンジン知識** — LlamaIndex、PageIndex、GraphRAG、LightRAG、リモートのLightRAG Server、セルフホストのWeKnora知識ベース、Tencent IMAまたはMarginNote 4ライブラリ、あるいはリンクされたObsidianボールトにまたがるバージョン管理されたRAGライブラリ(プラグ可能なドキュメント解析付き)。独立した抽出・クエリ・ビジョン設定、デフォルトのみの作成、確認付き再構築については[ネイティブLightRAGロールモデル](../../deeptutor/services/rag/pipelines/lightrag/README.md)を参照してください。- **拡張可能なツールとスキル** — 組み込みツール、MCPサーバー、CLIアプリ、画像/ビデオ/音声生成モデル、EduHubからインストール可能なコミュニティスキル。- **検査可能なメモリ** — L1トレース、L2サーフェスサマリー、L3合成によりパーソナライズが可視化・編集可能となります。Memory GraphはL2の事実をL1の証拠に、L3の合成を寄与したサーフェスに結び付けます。@@ -525,6 +525,8 @@ KBを作成する際は、**新規作成**(ドキュメントをアップロ組み込みLightRAGエンジンは`pip install 'deeptutor[rag-lightrag]'`でインストールします。このエクストラにはサポート対象のLightRAG SDKが含まれますが、MinerUはインストールしません。構造化解析が必要な場合は、Document ParsingでMinerUを個別に選択し、クラウドモードを設定するか、現在のローカルCLIをインストールしてください。MinerUはPDF、一般的なラスター画像、DOCX、PPTX、XLSXを受け付けます。従来の`magic-pdf`コマンドは引き続きPDFのみです。テキストのみおよびその他の解析エンジンはMinerUを必要としません。+ネイティブLightRAGのクエリとインクリメンタルインデックス作成には、モデル、次元、エンドポイントの識別情報を含む、公開されたインデックスに記録された埋め込み設定が必要です。これが変更された場合は、元の設定を復元するか、現在の埋め込みで再構築してください。埋め込みの識別情報が記録されていないインデックスは再構築が必要です。知識ベース詳細ビューとインデックスバージョンビューには復旧ガイダンスが表示され、ファイルは引き続き閲覧・ダウンロードできます。+</details><details>diff --git a/assets/README/README_PL.md b/assets/README/README_PL.mdindex 0cac83022..446503a52 100644--- a/assets/README/README_PL.md+++ b/assets/README/README_PL.md@@ -65,7 +65,7 @@ DeepTutor to natywne dla agentów środowisko nauki, które łączy korepetycje,- **Połączony kontekst uczenia się** — bazy wiedzy, książki, szkice Co-Writer, notatniki, banki pytań, persony i Memory można ponownie wykorzystywać w obsługujących je przepływach pracy, z uwzględnieniem uprawnień konta i polityk nauczania.- **Immersyjne uczenie się z wideo** — wklej link do YouTube, aby korzystać z natywnego odtwarzania o podwyższonej ochronie prywatności, zsynchronizowanych napisów, korepetycji osadzonych w znacznikach czasu i wznawialnych postępów; administratorzy mogą przełączyć odtwarzanie na samodzielnie hostowaną instancję Invidious bez ponownego tworzenia materiałów.- **Subagenty i Partners** — z poziomu Chat konsultuj aktywnie działającego agenta (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw lub DeepSeek) albo Partner, importuj poprzednie konwersacje i uruchamiaj stałych towarzyszy IM na tym samym mózgu.-- **Wielosilnikowa wiedza** — wersjonowane biblioteki RAG z LlamaIndex, PageIndex, GraphRAG, LightRAG, zdalnym LightRAG Server, samodzielnie hostowanym WeKnora, biblioteką Tencent IMA lub MarginNote 4, lub podłączonym vault Obsidian, z podłączalnym parsowaniem dokumentów.+- **Wielosilnikowa wiedza** — wersjonowane biblioteki RAG z LlamaIndex, PageIndex, GraphRAG, LightRAG, zdalnym LightRAG Server, samodzielnie hostowanym WeKnora, biblioteką Tencent IMA lub MarginNote 4, lub podłączonym vault Obsidian, z podłączalnym parsowaniem dokumentów. Zobacz [natywne modele ról LightRAG](../../deeptutor/services/rag/pipelines/lightrag/README.md), aby poznać niezależne ustawienia ekstrakcji, zapytań i wizji, tworzenie ograniczone do wartości domyślnych oraz potwierdzone przebudowy.- **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; Memory Graph łączy fakty L2 z dowodami L1, a syntezę L3 z powierzchniami, które się do niej przyczyniły.@@ -525,6 +525,8 @@ Tworząc KB, albo **tworzysz nową** (przesyłasz dokumenty i budujesz świeżyWbudowany silnik LightRAG instaluje się poleceniem `pip install 'deeptutor[rag-lightrag]'`. Ten dodatek zawiera obsługiwany SDK LightRAG, ale nie instaluje MinerU. Wybierz MinerU niezależnie w Document Parsing i skonfiguruj jego tryb chmurowy albo zainstaluj jego aktualny lokalny CLI, gdy potrzebne jest strukturalne parsowanie. MinerU akceptuje pliki PDF, popularne obrazy rastrowe, DOCX, PPTX i XLSX; starsze polecenie `magic-pdf` nadal obsługuje wyłącznie pliki PDF. Tryb tylko tekstowy i pozostałe silniki parsowania nie wymagają MinerU.+Natywne zapytania LightRAG i indeksowanie przyrostowe wymagają konfiguracji embeddingu zapisanej przez opublikowany indeks, obejmującej model, wymiar i tożsamość punktu końcowego. Jeśli się zmieni, przywróć oryginalną konfigurację lub przebuduj indeks z użyciem aktualnego embeddingu; indeksy bez zapisanej tożsamości embeddingu wymagają przebudowy. Widoki szczegółów bazy wiedzy i wersji indeksu pokazują wskazówki dotyczące odzyskiwania, a pliki pozostają dostępne do przeglądania i pobierania.+</details><details>diff --git a/assets/README/README_PT.md b/assets/README/README_PT.mdindex 8f94c3dbc..e3f5eae90 100644--- a/assets/README/README_PT.md+++ b/assets/README/README_PT.md@@ -65,7 +65,7 @@ O DeepTutor é um espaço de trabalho de aprendizagem nativo de agentes que cone- **Contexto de aprendizagem conectado** — bases de conhecimento, livros, rascunhos Co-Writer, notebooks, bancos de questões, personas e Memory podem ser reutilizados nos fluxos de trabalho que os suportam, sujeitos às concessões da conta e às políticas de aprendizagem.- **Aprendizagem imersiva por vídeo** — cole um link do YouTube para reprodução nativa com privacidade melhorada, legendas sincronizadas, tutoria fundamentada em marcas temporais e progresso retomável; os administradores podem mudar a reprodução para uma instância Invidious auto-hospedada sem reconstruir materiais.- **Subagentes e Partners** — a partir do Chat, consulte um harness de agente ao vivo (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw ou DeepSeek) ou um Partner, importe conversas anteriores e execute companheiros IM persistentes no mesmo cérebro.-- **Conhecimento multi-motor** — bibliotecas RAG com versões: LlamaIndex, PageIndex, GraphRAG, LightRAG, um LightRAG Server remoto, bases de conhecimento WeKnora auto-hospedadas, uma biblioteca Tencent IMA ou MarginNote 4, 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, bases de conhecimento WeKnora auto-hospedadas, uma biblioteca Tencent IMA ou MarginNote 4, ou um vault Obsidian vinculado, com análise de documentos conectável. Consulte os [modelos de função nativos do LightRAG](../../deeptutor/services/rag/pipelines/lightrag/README.md) para configurações independentes de extração, consulta e visão, criação apenas com predefinições e reconstruções confirmadas.- **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; o Memory Graph liga os factos L2 às evidências L1 e a síntese L3 às superfícies contribuintes.@@ -525,6 +525,8 @@ Ao criar uma KB, pode **criar nova** (carregar documentos e construir um índiceO motor LightRAG integrado é instalado com `pip install 'deeptutor[rag-lightrag]'`. Esse extra contém o SDK LightRAG suportado, mas não instala o MinerU. Escolha o MinerU de forma independente em Document Parsing e configure o seu modo cloud ou instale a sua CLI local atual quando quiser análise estruturada. O MinerU aceita PDF, imagens raster comuns, DOCX, PPTX e XLSX; o comando legado `magic-pdf` continua limitado a PDF. O motor Somente Texto e os restantes motores de análise não requerem o MinerU.+As consultas nativas do LightRAG e a indexação incremental exigem a configuração de embedding registada pelo índice publicado, incluindo o modelo, a dimensão e a identidade do endpoint. Se esta mudar, restaure a configuração original ou reconstrua com o embedding atual; os índices sem uma identidade de embedding registada exigem uma reconstrução. As vistas de detalhe da base de conhecimento e de versão do índice mostram orientações de recuperação, enquanto os ficheiros permanecem disponíveis para visualização e download.+</details><details>diff --git a/assets/README/README_RU.md b/assets/README/README_RU.mdindex 97d15b2a8..aef3a6d6f 100644--- a/assets/README/README_RU.md+++ b/assets/README/README_RU.md@@ -65,7 +65,7 @@ DeepTutor — это агентная учебная рабочая среда,- **Связанный контекст обучения** — базы знаний, книги, черновики Co-Writer, блокноты, банки вопросов, персоны и Memory можно повторно использовать в поддерживающих их рабочих процессах с учётом грантов учётной записи и политик обучения.- **Иммерсивное обучение по видео** — вставьте ссылку YouTube для нативного воспроизведения с повышенной конфиденциальностью, синхронизированными субтитрами, репетиторством с привязкой ко временным меткам и возобновляемым прогрессом; администраторы могут переключить воспроизведение на самостоятельно размещённый экземпляр Invidious без пересборки материалов.- **Субагенты и Partners** — из Chat обращайтесь к живой агентной среде (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw или DeepSeek) или к Partner, импортируйте прошлые разговоры и запускайте постоянных IM-компаньонов на том же мозге.-- **Многодвигательные знания** — версионированные RAG-библиотеки на основе LlamaIndex, PageIndex, GraphRAG, LightRAG, удалённого LightRAG Server, самостоятельно размещённого WeKnora, библиотеки Tencent IMA или MarginNote 4, либо связанного хранилища Obsidian, с подключаемым разбором документов.+- **Многодвигательные знания** — версионированные RAG-библиотеки на основе LlamaIndex, PageIndex, GraphRAG, LightRAG, удалённого LightRAG Server, самостоятельно размещённого WeKnora, библиотеки Tencent IMA или MarginNote 4, либо связанного хранилища Obsidian, с подключаемым разбором документов. См. [нативные ролевые модели LightRAG](../../deeptutor/services/rag/pipelines/lightrag/README.md) для независимых настроек извлечения, запросов и обработки изображений, создания только со значениями по умолчанию и подтверждённых пересборок.- **Расширяемые инструменты и навыки** — встроенные инструменты, MCP-серверы, CLI-приложения, модели генерации изображений / видео / голоса и устанавливаемые навыки сообщества из EduHub.- **Проверяемая память** — трассировки L1, сводки поверхностей L2 и синтез L3 делают персонализацию видимой и редактируемой; Memory Graph связывает факты L2 с доказательствами L1, а синтез L3 — с участвующими поверхностями.@@ -525,6 +525,8 @@ Co-Writer — это разделённое рабочее пространстВстроенный движок LightRAG устанавливается командой `pip install 'deeptutor[rag-lightrag]'`. Это дополнение содержит поддерживаемый SDK LightRAG, но не устанавливает MinerU. Выбирайте MinerU отдельно в разделе Разбор документов и либо настройте его облачный режим, либо установите актуальный локальный CLI, если нужен структурированный разбор. MinerU принимает PDF, распространённые растровые изображения, DOCX, PPTX и XLSX; устаревшая команда `magic-pdf` по-прежнему работает только с PDF. Текстовый и другие движки разбора не требуют MinerU.+Нативные запросы LightRAG и инкрементальное индексирование требуют конфигурации встраивания, зафиксированной опубликованным индексом, включая модель, размерность и идентичность конечной точки. Если она меняется, восстановите исходную конфигурацию или пересоберите индекс с текущим встраиванием; индексы без зафиксированной идентичности встраивания требуют пересборки. Раздел сведений о базе знаний и представления версий индекса показывают рекомендации по восстановлению, а файлы остаются доступными для просмотра и скачивания.+</details><details>diff --git a/assets/README/README_TH.md b/assets/README/README_TH.mdindex dc8ce7579..443f627a8 100644--- a/assets/README/README_TH.md+++ b/assets/README/README_TH.md@@ -65,7 +65,7 @@ DeepTutor คือ workspace การเรียนรู้แบบ agent-n- **บริบทการเรียนรู้ที่เชื่อมต่อกัน** — ฐานความรู้, หนังสือ, ร่าง Co-Writer, สมุดบันทึก, คลังคำถาม, บุคลิกภาพ และ Memory สามารถนำมาใช้ซ้ำในเวิร์กโฟลว์ที่รองรับ โดยอยู่ภายใต้สิทธิ์ของบัญชีและนโยบายการเรียนรู้- **การเรียนรู้ผ่านวิดีโออย่างดื่มด่ำ** — วางลิงก์ YouTube เพื่อเล่นวิดีโอแบบ native ที่เพิ่มความเป็นส่วนตัว พร้อมคำบรรยายที่ซิงค์กัน, การสอนพิเศษที่อ้างอิง timestamp และความคืบหน้าที่กลับมาเรียนต่อได้; ผู้ดูแลระบบสามารถเปลี่ยนการเล่นเป็น Invidious instance ที่ self-hosted ได้โดยไม่ต้องสร้างสื่อขึ้นใหม่- **ซับเอเจนต์และ Partners** — จาก Chat คุณสามารถปรึกษา agent harness แบบสด (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw หรือ DeepSeek) หรือ Partner, นำเข้าบทสนทนาในอดีต และรันเพื่อนถาวรบน IM ด้วยสมองเดียวกัน-- **ความรู้หลายเอ็นจิน** — ไลบรารี RAG แบบเวอร์ชันผ่าน LlamaIndex, PageIndex, GraphRAG, LightRAG, LightRAG Server ระยะไกล, WeKnora deployment แบบ self-hosted, ไลบรารี Tencent IMA หรือ MarginNote 4 หรือ Obsidian vault ที่เชื่อมโยง พร้อมการแยกวิเคราะห์เอกสารแบบ pluggable+- **ความรู้หลายเอ็นจิน** — ไลบรารี RAG แบบเวอร์ชันผ่าน LlamaIndex, PageIndex, GraphRAG, LightRAG, LightRAG Server ระยะไกล, WeKnora deployment แบบ self-hosted, ไลบรารี Tencent IMA หรือ MarginNote 4 หรือ Obsidian vault ที่เชื่อมโยง พร้อมการแยกวิเคราะห์เอกสารแบบ pluggable ดู [native LightRAG role models](../../deeptutor/services/rag/pipelines/lightrag/README.md) สำหรับการตั้งค่า extraction, query และ vision ที่เป็นอิสระจากกัน, การสร้างแบบใช้ค่าเริ่มต้นเท่านั้น และการสร้างใหม่ที่ต้องมีการยืนยัน- **เครื่องมือและทักษะที่ขยายได้** — เครื่องมือในตัว, เซิร์ฟเวอร์ MCP, แอป CLI, โมเดลสร้างรูปภาพ/วิดีโอ/เสียง และทักษะชุมชนที่ติดตั้งได้จาก EduHub- **หน่วยความจำที่ตรวจสอบได้** — การติดตาม L1, สรุปพื้นผิว L2 และการสังเคราะห์ L3 ทำให้การปรับแต่งส่วนบุคคลมองเห็นได้และแก้ไขได้; Memory Graph เชื่อมข้อเท็จจริง L2 กับหลักฐาน L1 และการสังเคราะห์ L3 กับพื้นผิวที่มีส่วนร่วม@@ -533,6 +533,8 @@ Knowledge bases คือคอลเลกชันเอกสารที่เอ็นจิน LightRAG ในตัวติดตั้งด้วย `pip install 'deeptutor[rag-lightrag]'` ส่วนเสริมนั้นมี SDK LightRAG ที่รองรับอยู่ แต่ไม่ได้ติดตั้ง MinerU เลือก MinerU แยกต่างหากใน Document Parsing แล้วกำหนดค่าโหมด cloud ของมันหรือติดตั้ง local CLI เวอร์ชันปัจจุบันเมื่อต้องการการแยกวิเคราะห์แบบมีโครงสร้าง MinerU รองรับ PDF, รูปภาพ raster ทั่วไป, DOCX, PPTX และ XLSX; คำสั่ง `magic-pdf` แบบ legacy ยังคงรองรับเฉพาะ PDF เท่านั้น Text-only และเอ็นจินแยกวิเคราะห์อื่น ๆ ไม่จำเป็นต้องใช้ MinerU+การ query และการทำ indexing แบบ incremental ของ LightRAG แบบ native ต้องใช้การตั้งค่า embedding ที่บันทึกไว้โดย index ที่เผยแพร่แล้ว ซึ่งรวมถึง model, dimension และ endpoint identity หากมีการเปลี่ยนแปลง ให้คืนค่าการตั้งค่าเดิมหรือสร้างใหม่ด้วย embedding ปัจจุบัน; index ที่ไม่มีการบันทึก embedding identity ไว้จำเป็นต้องสร้างใหม่ หน้ารายละเอียด knowledge base และหน้า index version จะแสดงคำแนะนำในการกู้คืน ในขณะที่ไฟล์ยังคงเปิดดูและดาวน์โหลดได้อยู่+</details><details>diff --git a/assets/README/README_TW.md b/assets/README/README_TW.mdindex 3364afa0f..2ffb8ee97 100644--- a/assets/README/README_TW.md+++ b/assets/README/README_TW.md@@ -65,7 +65,7 @@ DeepTutor 是代理程式原生的學習工作區,在同一個可擴充系統- **相互連結的學習情境** — 知識庫、書籍、Co-Writer 草稿、筆記本、題庫、角色設定與 Memory 可在支援這些內容的工作流程中重複使用,但仍受帳號授權與學習政策限制。- **沉浸式影片學習** — 貼上 YouTube 連結,即可使用隱私強化的原生播放、同步字幕、以時間戳為依據的教學,以及可續接的學習進度;管理員也能將播放切換至自架的 Invidious 執行個體,無須重新建立素材。- **子代理程式與 Partners** — 可從 Chat 諮詢即時代理程式執行框架(Claude Code、Codex、Antigravity、Kimi、opencode、MiMo、Hermes、OpenClaw 或 DeepSeek)或 Partner、匯入過往對話,並讓持續運作的 IM 夥伴共用同一套核心。-- **多引擎知識系統** — 透過 LlamaIndex、PageIndex、GraphRAG、LightRAG、遠端 LightRAG Server、自架 WeKnora 知識庫、Tencent IMA 或 MarginNote 4 知識庫,或連結的 Obsidian vault 建立版本化 RAG 知識庫,並支援可插拔的文件解析。+- **多引擎知識系統** — 透過 LlamaIndex、PageIndex、GraphRAG、LightRAG、遠端 LightRAG Server、自架 WeKnora 知識庫、Tencent IMA 或 MarginNote 4 知識庫,或連結的 Obsidian vault 建立版本化 RAG 知識庫,並支援可插拔的文件解析。請參閱[原生 LightRAG 角色模型](../../deeptutor/services/rag/pipelines/lightrag/README.md),了解獨立的擷取、查詢與視覺設定、僅預設建立,以及確認後的重建。- **可擴充的工具與技能** — 內建工具、MCP 伺服器、CLI 應用程式、影像/影片/語音生成模型,以及可從 EduHub 安裝的社群技能。- **可檢視的記憶** — L1 軌跡、L2 介面摘要與 L3 綜整讓個人化內容透明且可編輯;Memory Graph 會將 L2 事實連結至 L1 證據,並將 L3 綜整連結至其貢獻來源介面。@@ -525,6 +525,8 @@ Book 會將選定來源轉換成互動式**活書**;它不是靜態 PDF,而內建的 LightRAG 引擎可透過 `pip install 'deeptutor[rag-lightrag]'` 安裝;此額外套件包含明確支援的 LightRAG SDK,但不會安裝 MinerU。若需要結構化解析,請在 Document Parsing 中另行選擇 MinerU,並設定其雲端模式,或安裝目前的本機 CLI。MinerU 支援 PDF、常見點陣圖格式、DOCX、PPTX 與 XLSX;舊版 `magic-pdf` 仍僅支援 PDF。Text-only 與其他解析引擎不需要 MinerU。+原生 LightRAG 的查詢與增量索引,需要已發布索引所記錄的 embedding 設定,包括模型、維度與端點身分。若該設定有變更,請還原原始設定,或以目前的 embedding 重建索引;未記錄 embedding 身分的索引則必須重建。知識庫詳細資料與索引版本檢視會顯示恢復指引,檔案仍可正常檢視與下載。+</details><details>diff --git a/assets/releases/ver1-6-10.md b/assets/releases/ver1-6-10.mdnew file mode 100644index 000000000..fb5839d9b--- /dev/null+++ b/assets/releases/ver1-6-10.md@@ -0,0 +1,49 @@+# DeepTutor v1.6.10 Release Notes++**Release Date:** 2026.09.22++Building on [v1.6.9](ver1-6-9.md), v1.6.10 gives the native LightRAG engine its own role models and makes a published index state what it was built with. Around it: PDF attachments now honor your parsing engine, a generation cut off at its token budget says so instead of failing as a parse error, and model providers are no longer filtered out of services DeepTutor could not pre-verify. Drop-in — no migrations.++## What's New++### Native LightRAG role models++The native LightRAG engine takes a base model of its own, independent of the chat model, with optional per-role overrides for extraction, keyword, query and vision. Vision is off by default on a new configuration. Knowledge-base creation and full rebuilds use the shared engine defaults rather than per-index overrides, and a changed configuration is shown for review before it is submitted.++### An index that records how it was built++Publication pins the extraction and vision identities an index was built with, so later changes to the engine defaults leave an existing index alone. Index versions display their embedding, extraction and vision provenance; an index whose historical identity is unknown stays queryable but refuses incremental writes until a full rebuild. Enabling, disabling or replacing vision or extraction requires a full rebuild, and a rebuild that fails withdraws its publication instead of leaving a half-published index. Credentials are excluded from persisted policy and provenance.++### Embedding compatibility is enforced, not advised++Native LightRAG queries and incremental indexing require the embedding configuration recorded by the published index — model, dimension and endpoint identity. If it changes, restore the original configuration or rebuild with the current embedding. The knowledge-base detail and index-version views carry the recovery guidance, and files stay available for viewing and download throughout.++### PDF attachments follow your parsing engine++A PDF attached to a turn goes through the parser configured in **Settings → Knowledge Base**, with its processing stages visible while it runs. When the global default engine cannot accept a file, DeepTutor falls back to a text-capable engine rather than failing the turn, and a parser failure still falls back to native PDF extraction. Non-PDF turns skip parser setup entirely, and regenerating a turn that carries attachments no longer breaks request validation.++### A truncated answer says it was truncated++Responses now distinguish a complete generation from one cut off at `max_tokens`, so a budget exhausted by a reasoning model no longer surfaces as an undiagnosable parse error. Math animator raises its own budget across retries (capped at twice the base) and tells the retry that the budget, not the format, ran out. Visualize explains a truncated render on screen instead of ending silently, and its temperature and token budget are now configurable in **Settings → Capabilities**.++### Model providers you can configure and test++Provider options are no longer hidden from services DeepTutor could not pre-verify: pick any provider for embedding, search, voice or multimodal, and let the connection test say whether that model actually serves that role. Unrecognized vendors resolve through the generic OpenAI-compatible binding, except for search, which has no generic adapter and is rejected by name. Staging a provider connection also works over plain HTTP, where `crypto.randomUUID` does not exist and the **Continue** button previously did nothing.++### Learning and mastery evidence++Mastery evidence binds to objective and question identity, so a repair applies to the question it came from and a replayed qualitative assessment does not double-count. A mastery card that was never posted can no longer be claimed as delivered, and selected quizzes must complete before delivery. Notebook evidence is decoupled from chat sessions, and the Personalized Learning dashboard no longer crashes on its first card.++### Reliability fixes++Sandboxed execution tolerates a `bwrap` loopback denial on modern Linux and keeps network isolation during fallback. The launcher no longer opens a stray console window that read as "the backend exited", and settings-derived environment keys stop shadowing the live settings API across processes. Research reports recover their labels on a finished reply, GitHub source sync records a confirmed-current source correctly, mastery composer resources match the chat page, persona presets are admin-gated, retry state survives request validation, and tooltips are accessible across the UI.++## Upgrade Notes++Run `pip install -U deeptutor`; Docker users pull `ghcr.io/hkuds/deeptutor:latest`.++- **Existing LightRAG indexes keep working.** They query as before; only incremental writes are gated. An index with no recorded embedding identity, or one whose embedding configuration has changed, asks for a restore or a full rebuild before accepting new documents.+- **Vision indexing is opt-in on new role configurations.** Turning it on (or off, or swapping the model) applies to the next full rebuild, not to an index already published.+- **Provider lists are wider on purpose.** A provider that cannot serve the selected role now fails its connection test instead of being absent from the list. Test before applying.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.6.9...v1.6.10diff --git a/deeptutor/__version__.py b/deeptutor/__version__.pyindex 64034487e..7d672ebb2 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.6.9"+__version__ = "1.6.10"__all__ = ("__version__",)diff --git a/deeptutor/agents/base_agent.py b/deeptutor/agents/base_agent.pyindex 5a4696262..28af59a02 100644--- a/deeptutor/agents/base_agent.py+++ b/deeptutor/agents/base_agent.py@@ -18,13 +18,14 @@ from typing import Any, AsyncGenerator, Awaitable, Callablefrom deeptutor.config.settings import settingsfrom deeptutor.logging import LLMStatsfrom deeptutor.services.config import get_agent_params-from deeptutor.services.llm import complete as llm_completefrom deeptutor.services.llm import (+ StreamOutcome,get_llm_config,get_token_limit_kwargs,prepare_multimodal_messages,supports_response_format,)+from deeptutor.services.llm import complete as llm_completefrom deeptutor.services.llm import stream as llm_streamfrom deeptutor.services.prompt import get_prompt_manager@@ -529,6 +530,7 @@ class BaseAgent(ABC):trace_meta: dict[str, Any] | None = None,reasoning_effort: str | None = None,tools: list[dict[str, Any]] | None = None,+ outcome: StreamOutcome | None = None,) -> AsyncGenerator[str, None]:"""Unified interface for streaming LLM responses.@@ -548,6 +550,10 @@ class BaseAgent(ABC):attachments: Image/file attachments for multimodal input (optional)reasoning_effort: Override the model's thinking level for this onecall (see :meth:`call_llm`).+ outcome: Filled in with the provider's terminal reason and usage+ when the stream ends. An agent that parses the streamed text+ needs it to tell a complete response from one the provider cut+ off at ``max_tokens`` (#1545).Yields:Response chunks as strings@@ -635,6 +641,7 @@ class BaseAgent(ABC):binding=self.binding,messages=messages,max_retries=max_retries,+ outcome=outcome,**kwargs,):full_response += chunkdiff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yamlindex 1fb75c36f..287827a4d 100644--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml@@ -162,6 +162,7 @@ notices:loop_budget_exhausted: "Exploration budget reached; answering with what has been gathered."loop_settlement: "Exploration budget reached; completing required follow-up before the final answer."output_truncated: "The model output reached its token limit; asked it to continue."+ tool_call_truncated: "The model reached its output token limit while writing a tool call, so the call may be incomplete. If this repeats, raise this capability's max tokens or pick a model that reasons less."loop_error_finish: "A step failed ({error}); answering with what has been gathered."provider_retry: "The model provider connection was interrupted; retrying."provider_unavailable: "Unable to reach the model provider. Please retry."diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yamlindex 32bded4da..99c737084 100644--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml@@ -119,6 +119,7 @@ notices:loop_budget_exhausted: "探索轮次预算已用尽,将基于已收集的材料作答。"loop_settlement: "探索轮次预算已用尽;正在完成必要收尾,然后给出最终回答。"output_truncated: "模型输出达到 token 上限,已要求其继续完成回答。"+ tool_call_truncated: "模型在生成工具调用时达到输出 token 上限,该调用可能不完整。若反复出现,请提高该能力的最大输出 token,或改用推理更短的模型。"loop_error_finish: "某一步执行失败({error}),将基于已收集的材料作答。"provider_retry: "模型服务连接中断,正在重试。"provider_unavailable: "无法连接模型服务,请重试。"diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.pyindex 6c9656a01..3a8e2cc30 100644--- a/deeptutor/agents/loop/agent_loop.py+++ b/deeptutor/agents/loop/agent_loop.py@@ -58,6 +58,7 @@ from deeptutor.services.llm import (clean_thinking_tags,supports_streaming,)+from deeptutor.services.llm import finish_was_truncated as _finish_was_truncatedfrom deeptutor.services.llm.capabilities import threads_session_idfrom deeptutor.services.llm.multimodal import should_degrade_to_text, strip_image_parts_inplacefrom deeptutor.services.llm.request_compat import (@@ -92,7 +93,6 @@ MAX_SETTLEMENT_ROUNDS = 3# forced tool-less finish instead of spending the full exploration budget on# the same failure.MAX_REASONING_ONLY_RECOVERIES = 2-_TRUNCATED_FINISH_REASONS = frozenset({"length", "max_tokens", "max_output_tokens"})# The SDK already retries failures that happen before response headers. These# short outer retries also cover SSE connections that fail before yielding any# user-visible output. Once output is visible, replay is unsafe because it can@@ -100,11 +100,6 @@ _TRUNCATED_FINISH_REASONS = frozenset({"length", "max_tokens", "max_output_token_PROVIDER_RETRY_DELAYS = (0.5, 1.5)-def _finish_was_truncated(reason: str | None) -> bool:- """Return whether a provider ended generation because output hit a cap."""- return str(reason or "").strip().lower() in _TRUNCATED_FINISH_REASONS--def _reasoning_budget_exhausted(result: "LLMCallResult", max_tokens: int) -> bool:"""Detect a round that spent its output budget without taking action."""if result.tool_calls or result.visible_text.strip():@@ -645,6 +640,28 @@ class AgentLoop:)tool_names = tuple(str(call.get("name") or "") for call in result.tool_calls)+ if _finish_was_truncated(result.finish_reason):+ # A round that hits the cap *while writing a tool call* never+ # reaches the continuation branch above, so the only thing the+ # reader used to see was the arg guard's "missing <arg>" — which+ # reads as a model that forgot a field, not one whose JSON was+ # cut off mid-argument. That is how a truncated+ # ``submit_visualization`` became an empty canvas with nothing+ # on screen explaining why (#1546).+ await self.stream.progress(+ self.pipeline._t(+ "notices.tool_call_truncated",+ default=(+ "The model reached its output token limit while writing a "+ "tool call, so the call may be incomplete. If this repeats, "+ "raise this capability's max tokens or pick a model that "+ "reasons less."+ ),+ ),+ source=self.source,+ stage=self.stage,+ metadata={"trace_kind": "warning"},+ )output_policy = self.pipeline._capability_tool_round_output_policy(self.context,self._clean(result.text),diff --git a/deeptutor/agents/math_animator/agents/code_generator_agent.py b/deeptutor/agents/math_animator/agents/code_generator_agent.pyindex 0b343640f..b5fded355 100644--- a/deeptutor/agents/math_animator/agents/code_generator_agent.py+++ b/deeptutor/agents/math_animator/agents/code_generator_agent.py@@ -8,9 +8,19 @@ from typing import Anyfrom deeptutor.agents.base_agent import BaseAgentfrom deeptutor.core.trace import build_trace_metadata, new_call_id+from deeptutor.services.llm import StreamOutcomefrom ..models import ConceptAnalysis, GeneratedCode, SceneDesign-from ..utils import build_repair_error_message, extract_json_object+from ..utils import (+ build_repair_error_message,+ describe_unusable_output,+ escalated_max_tokens,+ extract_json_object,+)++#: How much of a failed response to keep in the debug log. Enough to see where+#: a truncated generation stopped, short enough to stay readable (#1545).+_RAW_EXCERPT_CHARS = 200class GeneratedCodeOutputError(ValueError):@@ -148,52 +158,102 @@ class CodeGeneratorAgent(BaseAgent):deliberately narrow boundary covers a successful response whosecontent is blank, reasoning-only, or malformed JSON (#1202). Parsingstays strict and callers never proceed to the renderer with ``code=''``.++ A retry is not a repeat. The provider reports whether it stopped at the+ output cap, and a reasoning model that spent the whole budget on+ chain-of-thought fails that way every time on the same request (#1547),+ so a truncated attempt is retried with a larger budget and a directive+ to keep the reasoning short. Whichever way the attempt failed, the+ reason reaches both the log and the raised error (#1545)."""max_retries = max(0, int(self.get_max_retries()))+ base_max_tokens = max(0, int(self.get_max_tokens() or 0))+ attempts = max_retries + 1last_error: Exception | None = None- for structured_attempt in range(max_retries + 1):- retry_instruction = ""- if structured_attempt:- retry_instruction = (- "\n\nYour previous response contained no usable structured code. "- "Return exactly one JSON object with a non-empty `code` field."- )+ last_failure = ""+ truncations = 0+ for structured_attempt in range(attempts):+ max_tokens = escalated_max_tokens(base_max_tokens, truncations)+ retry_instruction = self._retry_instruction(+ attempt=structured_attempt, after_truncation=truncations > 0+ )+ outcome = StreamOutcome()chunks: list[str] = []async for chunk in self.stream_llm(user_prompt=user_prompt + retry_instruction,system_prompt=system_prompt,response_format={"type": "json_object"},+ max_tokens=max_tokens or None,stage=stage,trace_meta=build_trace_metadata(call_id=new_call_id(call_id_prefix),**trace_meta,structured_attempt=structured_attempt + 1,),+ outcome=outcome,):chunks.append(chunk)+ raw_response = "".join(chunks)try:- generated = GeneratedCode.model_validate(extract_json_object("".join(chunks)))+ generated = GeneratedCode.model_validate(extract_json_object(raw_response))if not generated.code.strip():raise ValueError("structured response has an empty code field")return generatedexcept (json.JSONDecodeError, ValueError) as exc:last_error = exc- if structured_attempt >= max_retries:- break+ last_failure = describe_unusable_output(+ error=exc,+ raw_response=raw_response,+ outcome=outcome,+ max_tokens=max_tokens,+ )+ if outcome.truncated:+ truncations += 1self.logger.warning(- "Math animator %s returned unusable structured output; retrying (%d/%d)",+ "Math animator %s attempt %d/%d produced no usable code: %s",+ stage,+ structured_attempt + 1,+ attempts,+ last_failure,+ )+ self.logger.debug(+ "Math animator %s attempt %d raw response head=%r tail=%r",stage,structured_attempt + 1,- max_retries,+ raw_response[:_RAW_EXCERPT_CHARS],+ raw_response[-_RAW_EXCERPT_CHARS:],)+ if structured_attempt >= max_retries:+ breakawait asyncio.sleep(min(0.25 * (2**structured_attempt), 2.0))- attempts = max_retries + 1raise GeneratedCodeOutputError(- f"Math animator {stage} returned no usable code after {attempts} attempts."+ f"Math animator {stage} returned no usable code after {attempts} attempts. "+ f"Last attempt: {last_failure}") from last_error+ @staticmethod+ def _retry_instruction(*, attempt: int, after_truncation: bool) -> str:+ """The nudge appended to the prompt on retry, matched to the failure."""++ if not attempt:+ return ""+ if after_truncation:+ # Asking again for "structured code" is useless when the previous+ # response was a complete thought and an incomplete answer: the+ # budget, not the format, is what ran out (#1547).+ return (+ "\n\nYour previous response hit the output token limit before the JSON "+ "was complete. Keep your internal reasoning to a few sentences and spend "+ "the budget on the code itself. Return exactly one JSON object with a "+ "non-empty `code` field and nothing else."+ )+ return (+ "\n\nYour previous response contained no usable structured code. "+ "Return exactly one JSON object with a non-empty `code` field."+ )+__all__ = ["CodeGeneratorAgent", "GeneratedCodeOutputError"]diff --git a/deeptutor/agents/math_animator/utils.py b/deeptutor/agents/math_animator/utils.pyindex 267df78fb..6d075a27e 100644--- a/deeptutor/agents/math_animator/utils.py+++ b/deeptutor/agents/math_animator/utils.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport refrom deeptutor.agents._shared.json_output import extract_json_object+from deeptutor.services.llm import StreamOutcome+from deeptutor.services.llm.utils import clean_thinking_tagsdef slugify_filename(value: str, fallback: str) -> str:@@ -45,8 +47,63 @@ def build_repair_error_message(error_message: str) -> str:return text + "\n\nTargeted repair hints:\n- " + "\n- ".join(hints)+def describe_unusable_output(+ *,+ error: Exception | None,+ raw_response: str,+ outcome: StreamOutcome,+ max_tokens: int,+) -> str:+ """Name which of the three code-generation failures actually happened.++ Truncated output, an empty response and malformed JSON all used to surface+ as the same "no usable code" message with the parse error only in the+ traceback, so nobody could tell them apart without patching the file+ (#1545). The three read very differently to whoever has to act: only the+ first one is fixed by raising the budget.+ """++ thinking_chars = max(0, len(raw_response) - len(clean_thinking_tags(raw_response)))+ shape = f"{len(raw_response)} chars"+ if thinking_chars:+ shape += f", {thinking_chars} of them chain-of-thought"+ reason = (outcome.finish_reason or "none").strip() or "none"+ if outcome.truncated:+ reported = ", ".join(+ f"{key}={outcome.usage[key]}"+ for key in ("completion_tokens", "reasoning_tokens")+ if key in outcome.usage+ )+ detail = f"finish_reason={reason}" + (f", {reported}" if reported else "")+ return (+ f"the response ({shape}) was cut off at the {max_tokens}-token output cap "+ f"({detail}), so the code JSON never completed — raise the math animator's "+ "max tokens in Settings → Capabilities, or pick a model that reasons less"+ )+ if not raw_response.strip():+ return f"the model returned no text at all (finish_reason={reason})"+ return f"the response ({shape}) contained no usable JSON object: {error}"+++def escalated_max_tokens(base: int, truncations: int) -> int:+ """Grow the output budget after a truncation instead of repeating it.++ Retrying a truncated generation on the same budget is deterministic waste —+ 9 attempts, 21 minutes, same ending (#1547). The growth is capped at twice+ the configured budget because a ``max_tokens`` above the model's own output+ limit is rejected outright, which would turn a truncated answer into no+ answer at all.+ """++ if base <= 0 or truncations <= 0:+ return base+ return min(int(base * 2), int(base * 1.5**truncations))++__all__ = ["build_repair_error_message",+ "describe_unusable_output",+ "escalated_max_tokens","extract_json_object","slugify_filename","trim_error_message",diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.pyindex d9da67bef..2cb3e914d 100644--- a/deeptutor/agents/research/pipeline.py+++ b/deeptutor/agents/research/pipeline.py@@ -90,7 +90,11 @@ from deeptutor.runtime.registry.tool_registry import get_tool_registryfrom deeptutor.runtime.stream_bus import StreamBusfrom deeptutor.services.config import parse_languagefrom deeptutor.services.config.loader import get_capability_params-from deeptutor.services.llm import get_llm_config, prepare_multimodal_messages+from deeptutor.services.llm import (+ finish_was_truncated,+ get_llm_config,+ prepare_multimodal_messages,+)from deeptutor.services.llm.structured_retry import payload_with_reasoning_retryfrom deeptutor.services.prompt import get_prompt_managerfrom deeptutor.services.prompt.language import append_language_directive@@ -2341,7 +2345,7 @@ def _report_step_incomplete_reason(if step.stream_idle_timeout:return "provider stream went idle before an explicit finish"finish_reason = (step.finish_reason or "").strip().lower()- if finish_reason in {"length", "max_tokens", "max_output_tokens"}:+ if finish_was_truncated(finish_reason):return f"provider stopped at its output limit ({finish_reason})"if len(body) < 80:return f"body is too short ({len(body)} characters)"diff --git a/deeptutor/agents/visualize/capability.py b/deeptutor/agents/visualize/capability.pyindex 5485564cd..938138698 100644--- a/deeptutor/agents/visualize/capability.py+++ b/deeptutor/agents/visualize/capability.py@@ -18,6 +18,7 @@ from deeptutor.runtime.request_contracts import (validate_visualize_request_config,)from deeptutor.runtime.stream_bus import StreamBus+from deeptutor.services.config.capabilities_settings import get_visualize_paramsfrom deeptutor.visualizers.protocol import (REQUESTED_VISUALIZER_KEY,VISUALIZATION_RESULT_KEY,@@ -168,11 +169,21 @@ class VisualizeCapability(TurnCapability):context.allowed_builtin_tools = [name for name in _VISUALIZE_SAFE_BUILTINS if name in allowed]+ # Read the visualize budget instead of stating it here: a reasoning+ # model can spend most of one round on chain-of-thought, which truncated+ # the submit_visualization arguments mid-JSON and left a blank canvas+ # with no error (#1546). The defaults are the values this call used to+ # hardcode, so an untouched install behaves exactly as before.+ try:+ params = get_visualize_params()+ except Exception as exc: # pragma: no cover - defensive config read+ logger.warning("Failed to load visualize params, using defaults: %s", exc)+ params = {}pipeline = AgenticChatPipeline(language=context.language,max_rounds=5,- temperature=0.15,- max_tokens=16000,+ temperature=params.get("temperature", 0.15),+ max_tokens=params.get("max_tokens", 16000),event_source=self.name,event_stage="generating",emit_result=False,diff --git a/deeptutor/api/routers/personas.py b/deeptutor/api/routers/personas.pyindex 27d9e46e4..f3d06c0e9 100644--- a/deeptutor/api/routers/personas.py+++ b/deeptutor/api/routers/personas.py@@ -19,7 +19,6 @@ from __future__ import annotationsfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from deeptutor.multi_user.context import get_current_userfrom deeptutor.multi_user.paths import get_admin_path_servicefrom deeptutor.services.i18n import tfrom deeptutor.services.persona import (@@ -49,16 +48,33 @@ def _admin_persona_service() -> PersonaService:return PersonaService(root=get_admin_path_service().get_workspace_dir() / "personas")+def _persona_presets(service: PersonaService) -> PersonaService | None:+ """The read-only deployment presets, unless ``service`` already holds them.++ ``None`` means the caller is reading the very directory the presets live in+ — the admin on their account-level workspace — where merging would only+ duplicate every row. Deciding that on ``user.is_admin`` instead took "the+ caller is an admin" to mean "the caller is reading the preset directory",+ which stopped being true once each workspace got its own personas+ directory: inside an explicit workspace an admin saw nothing but Default+ while a non-admin on the same workspace saw every preset (#1534).+ """+ presets = _admin_persona_service()+ if presets.root.resolve() == service.root.resolve():+ return None+ return presets++@router.get("/personas")async def list_personas() -> dict[str, list[dict[str, object]]]:service = get_persona_service()own = [info.to_dict() for info in service.list_personas()]- user = get_current_user()- if user.is_admin:+ presets = _persona_presets(service)+ if presets is None:return {"personas": own}own_names = {item["name"] for item in own}merged = list(own)- for preset in _admin_persona_service().list_personas():+ for preset in presets.list_personas():if preset.name in own_names:continueentry = preset.to_dict()@@ -77,10 +93,10 @@ async def get_persona(name: str) -> dict[str, object]:except InvalidPersonaNameError as exc:raise HTTPException(status_code=400, detail=str(exc))- user = get_current_user()- if not user.is_admin:+ presets = _persona_presets(service)+ if presets is not None:try:- detail = _admin_persona_service().get_detail(name).to_dict()+ detail = presets.get_detail(name).to_dict()detail.update({"source": "admin", "read_only": True})return detailexcept (PersonaNotFoundError, InvalidPersonaNameError):diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.pyindex d210c3750..8defce8d2 100644--- a/deeptutor/runtime/launcher.py+++ b/deeptutor/runtime/launcher.py@@ -204,6 +204,25 @@ def _clear_detached_runtime(paths: DetachedLauncherPaths, token: str) -> None:paths.stop.unlink(missing_ok=True)+def _no_window_kwargs() -> dict[str, int]:+ """``Popen`` keywords that keep Windows from allocating a console window.++ The detached worker runs with ``DETACHED_PROCESS``, i.e. with no console of+ its own, so every console program it starts — taskkill, netstat, tasklist,+ npm, the node dev server — makes Windows create a brand-new one: empty+ windows flash on the desktop, and closing the one that ends up hosting node+ delivered CTRL_C_EXIT to it, which the launcher read as "my frontend+ exited" and answered by stopping the backend as well (#1501).++ Stdout and stderr handles are inherited independently of console+ allocation, so a foreground launch still prints exactly as before. Off+ Windows there is nothing to suppress and this is empty.+ """+ if os.name != "nt":+ return {}+ return {"creationflags": subprocess.CREATE_NO_WINDOW} # type: ignore[attr-defined]++def _send_tree_signal(pid: int | None, pgid: int | None, sig: signal.Signals | int) -> None:if pid is None:return@@ -211,7 +230,13 @@ def _send_tree_signal(pid: int | None, pgid: int | None, sig: signal.Signals | icmd = ["taskkill", "/PID", str(pid), "/T"]if sig == KILL_SIGNAL:cmd.append("/F")- subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)+ subprocess.run(+ cmd,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=False,+ **_no_window_kwargs(),+ )returnif os.name != "nt" and pgid is not None:os.killpg(pgid, sig)@@ -276,7 +301,10 @@ def _spawn(command: list[str], *, cwd: Path, env: dict[str, str], name: str) ->"errors": "replace",}if os.name == "nt":- kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]+ kwargs["creationflags"] = (+ subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]+ | subprocess.CREATE_NO_WINDOW # type: ignore[attr-defined]+ )else:kwargs["start_new_session"] = Trueprocess = subprocess.Popen(command, **kwargs) # type: ignore[arg-type,call-overload]@@ -338,6 +366,7 @@ def _port_listeners_windows(port: int) -> list[tuple[int, str]]:capture_output=True,text=True,timeout=5,+ **_no_window_kwargs(),)except Exception:return []@@ -366,6 +395,7 @@ def _port_listeners_windows(port: int) -> list[tuple[int, str]]:capture_output=True,text=True,timeout=3,+ **_no_window_kwargs(),)first = result.stdout.strip().splitlines()[:1]if first and first[0].startswith('"'):@@ -662,7 +692,7 @@ def _ensure_web_dependencies(source: Path, npm: str) -> None:returnaction = "ci" if (source / "package-lock.json").exists() else "install"_log(f"web/node_modules not found — running `npm {action}` in {source} ...")- result = subprocess.run([npm, action], cwd=source)+ result = subprocess.run([npm, action], cwd=source, **_no_window_kwargs())if result.returncode != 0:raise SystemExit(f"`npm {action}` failed (exit {result.returncode}). "@@ -758,7 +788,7 @@ def _ensure_source_production_build(generated_config = [source / "next-env.d.ts", source / "tsconfig.json"]snapshots = {path: path.read_bytes() if path.is_file() else None for path in generated_config}try:- result = subprocess.run([npm, "run", "build"], cwd=source, env=env)+ result = subprocess.run([npm, "run", "build"], cwd=source, env=env, **_no_window_kwargs())finally:for path, original in snapshots.items():if original is None:@@ -1257,8 +1287,10 @@ def start(from deeptutor.services.config import (HTTP_KEEP_ALIVE_TIMEOUT,+ SETTINGS_DERIVED_ENV_KEYS,ensure_runtime_settings_files,export_runtime_settings_to_env,+ get_runtime_settings_service,get_ws_max_size,load_auth_settings,load_launch_settings,@@ -1375,6 +1407,17 @@ def start(# ``__NEXT_PRIVATE_STANDALONE_CONFIG``, so neither long-running child needs# this variable after the build has completed.common_env.pop("DEEPTUTOR_NEXT_DIST_DIR", None)+ # Name the variables the children should read as "the launcher rendered this+ # out of the settings files", so the backend does not mistake our own export+ # for a deployment override and answer forever with the value it started with+ # — that is how the update-check toggle wrote system.json while the live API+ # kept reporting the old state (#1536). A key we then overwrote with a+ # resolved value (a port moved after a conflict, the browser-facing API base)+ # is deliberately left off: there the environment is the newer truth.+ derived_keys = get_runtime_settings_service().settings_derived_keys()+ common_env[SETTINGS_DERIVED_ENV_KEYS] = ",".join(+ sorted(key for key in derived_keys if common_env.get(key) == runtime_env.get(key))+ )backend_cmd = [sys.executable,diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.pyindex 30e21fe68..312f753e2 100644--- a/deeptutor/services/config/__init__.py+++ b/deeptutor/services/config/__init__.py@@ -27,6 +27,7 @@ from .model_catalog import ()from .runtime_settings import (HTTP_KEEP_ALIVE_TIMEOUT,+ SETTINGS_DERIVED_ENV_KEYS,ChatAttachmentLimits,RuntimeSettingsService,ensure_runtime_settings_files,@@ -92,6 +93,7 @@ __all__ = ["TestRun","get_config_test_runner","HTTP_KEEP_ALIVE_TIMEOUT",+ "SETTINGS_DERIVED_ENV_KEYS","ChatAttachmentLimits","RuntimeSettingsService","ensure_runtime_settings_files",diff --git a/deeptutor/services/config/capabilities_settings.py b/deeptutor/services/config/capabilities_settings.pyindex ed99c11e4..ae67a0776 100644--- a/deeptutor/services/config/capabilities_settings.py+++ b/deeptutor/services/config/capabilities_settings.py@@ -44,6 +44,7 @@ _AGENTS_YAML_CAPABILITY_SECTIONS: dict[str, tuple[str, ...]] = {"solve": ("capabilities", "solve"),"research": ("capabilities", "research"),"question": ("capabilities", "question"),+ "visualize": ("capabilities", "visualize"),"co_writer": ("capabilities", "co_writer"),"vision_solver": ("plugins", "vision_solver"),"math_animator": ("plugins", "math_animator"),@@ -53,6 +54,11 @@ _SIMPLE_LLM_DEFAULTS: dict[str, dict[str, Any]] = {"solve": {"temperature": 0.3, "max_tokens": 8192},"research": {"temperature": 0.5, "max_tokens": 16834},"question": {"temperature": 0.7, "max_tokens": 4096},+ # The visualize loop's own defaults, unchanged from when they were written+ # into the pipeline construction: a user who never touches this keeps the+ # behaviour they had, and one whose reasoning model eats the budget can now+ # raise it (#1546).+ "visualize": {"temperature": 0.15, "max_tokens": 16000},"co_writer": {"temperature": 0.6, "max_tokens": 4096},"vision_solver": {"temperature": 0.3, "max_tokens": 12000},"math_animator": {"temperature": 0.2, "max_tokens": 16834},@@ -437,6 +443,17 @@ def save_capabilities_settings(payload: dict[str, Any]) -> dict[str, Any]:return capabilities_settings_dict()+def get_visualize_params() -> dict[str, Any]:+ """Runtime visualize params, read through the same coerce path as the UI.++ The budget used to be a literal in the capability, so ``agents.yaml`` and+ the settings page could not move it and a reasoning model that spent most+ of the budget on chain-of-thought truncated the payload with no recourse+ (#1546).+ """+ return _build_simple_llm_block(_read_agents_yaml(), "visualize")++def get_solve_params() -> dict[str, Any]:"""Runtime solve params, read through the same coerce path as the UI.@@ -456,5 +473,6 @@ def get_solve_params() -> dict[str, Any]:__all__ = ["capabilities_settings_dict","get_solve_params",+ "get_visualize_params","save_capabilities_settings",]diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex 286b92212..4bf6ef832 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -370,6 +370,14 @@ DEFAULT_LIGHTRAG_SERVER_SETTINGS: dict[str, Any] = {}IGNORE_PROCESS_OVERRIDES_ENV = "DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES"++# Names of the variables a parent DeepTutor process rendered out of the settings+# files, handed to its children so they can tell "our own launcher derived this+# from system.json" from "an operator set this in the deployment". Without it the+# launcher's export looks like a deployment override to the backend and the file+# can never win again: toggling "check for updates" wrote system.json while the+# live API kept answering with the value captured at startup (#1536).+SETTINGS_DERIVED_ENV_KEYS = "DEEPTUTOR_SETTINGS_DERIVED_ENV_KEYS"TRUTHY = {"1", "true", "yes", "on"}FALSY = {"0", "false", "no", "off"}@@ -450,6 +458,10 @@ class RuntimeSettingsService:self.process_env = process_env if process_env is not None else os.environself._external_process_keys: set[str] = set()self._internal_exported_values: dict[str, str] = {}+ derived = self.process_env.get(SETTINGS_DERIVED_ENV_KEYS, "") or ""+ self._settings_derived_keys: frozenset[str] = frozenset(+ part.strip() for part in derived.split(",") if part.strip()+ )@classmethoddef get_instance(@@ -719,8 +731,14 @@ class RuntimeSettingsService:def export_environment(self, *, overwrite: bool = True) -> dict[str, str]:env = self.render_environment()for key, value in env.items():- current = os.environ.get(key)- if current and self._internal_exported_values.get(key) != current:+ # Read through the same view the override policy reads, so "the+ # operator set this" means one thing in both places.+ current = self.process_env.get(key)+ if (+ current+ and key not in self._settings_derived_keys+ and self._internal_exported_values.get(key) != current+ ):self._external_process_keys.add(key)if overwrite or key not in os.environ:os.environ[key] = value@@ -728,9 +746,24 @@ class RuntimeSettingsService:self._internal_exported_values[key] = valuereturn env+ def settings_derived_keys(self) -> frozenset[str]:+ """Variables this process exported out of the settings files.++ What a child needs in order to read its inherited environment correctly+ (see :data:`SETTINGS_DERIVED_ENV_KEYS`). Anything the operator had+ already set is excluded: there the environment is the authority and the+ child must keep honouring it, exactly as this process does.+ """+ return frozenset(self._internal_exported_values)+def _process_env_value(self, key: str) -> str:if self._ignore_process_overrides():return ""+ if key in self._settings_derived_keys:+ # A parent DeepTutor process rendered this out of the settings files,+ # so the files stay in charge and a later save takes effect live+ # (#1536). An operator-set variable is never on that list.+ return ""value = self.process_env.get(key, "")if not value:return ""@@ -1455,6 +1488,7 @@ __all__ = ["LITEPARSE_IMAGE_MODES","MINERU_MODE_CLOUD","MINERU_MODE_LOCAL",+ "SETTINGS_DERIVED_ENV_KEYS","ChatAttachmentLimits","RuntimeSettingsService","compute_ws_max_size",diff --git a/deeptutor/services/github_source/sync.py b/deeptutor/services/github_source/sync.pyindex 62dec9245..deb87aca8 100644--- a/deeptutor/services/github_source/sync.py+++ b/deeptutor/services/github_source/sync.py@@ -75,6 +75,37 @@ def _record_sync_failure(kb_name: str, source: dict, base_dir: str, error: str)logger.warning("Could not persist GitHub sync failure status for '%s'", kb_name)+def _record_sync_success(+ kb_name: str,+ source: dict,+ base_dir: str,+ *,+ sha: str,+ files_synced: int | None = None,+) -> None:+ """Persist "GitHub was checked and the source is current".++ A same-SHA check is a successful sync that had nothing to transfer, so it+ owes the same freshness stamp as one that did: without it the hourly+ service read the source as stale forever and re-queried GitHub every+ cycle, and an error left by an earlier transient failure stayed on the+ source after a later check had confirmed it current (#1489). ``files_synced``+ is omitted on that path so the last real transfer's count survives.+ """+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ fields: dict = {} if files_synced is None else {"files_synced": files_synced}+ KnowledgeBaseManager(base_dir=base_dir).update_github_source_state(+ kb_name=kb_name,+ source_id=source["id"],+ last_synced_sha=sha,+ last_synced_at=_utcnow_iso(),+ last_sync_status="success",+ last_sync_error=None,+ **fields,+ )++def _is_markdown(path: str) -> bool:return path.lower().endswith(MARKDOWN_EXTENSIONS)@@ -181,6 +212,7 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=Nonereturn SyncResult(ok=False, error=error)if old_sha and old_sha == latest_sha:+ _record_sync_success(kb_name, source, base_dir, sha=latest_sha)return SyncResult(ok=True, skipped=True)try:@@ -224,16 +256,11 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=None_record_sync_failure(kb_name, source, base_dir, result.error)return result- from deeptutor.knowledge.manager import KnowledgeBaseManager-- manager = KnowledgeBaseManager(base_dir=base_dir)- manager.update_github_source_state(- kb_name=kb_name,- source_id=source["id"],- last_synced_sha=latest_sha,- last_synced_at=_utcnow_iso(),- last_sync_status="success",- last_sync_error=None,+ _record_sync_success(+ kb_name,+ source,+ base_dir,+ sha=latest_sha,files_synced=result.files_added + result.files_updated,)return resultdiff --git a/deeptutor/services/llm/__init__.py b/deeptutor/services/llm/__init__.pyindex 9f37b59eb..922ed14e6 100644--- a/deeptutor/services/llm/__init__.py+++ b/deeptutor/services/llm/__init__.py@@ -98,6 +98,7 @@ from .factory import (stream,)from .multimodal import MultimodalResult, prepare_multimodal_messages+from .types import TRUNCATED_FINISH_REASONS, StreamOutcome, finish_was_truncatedfrom .utils import (build_auth_headers,build_chat_url,@@ -134,6 +135,10 @@ __all__ = [# Multimodal"MultimodalResult","prepare_multimodal_messages",+ # Stream finish reporting+ "StreamOutcome",+ "TRUNCATED_FINISH_REASONS",+ "finish_was_truncated",# Exceptions"LLMError","LLMConfigError",diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 327339451..3a9947a74 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -25,6 +25,7 @@ from .error_mapping import map_errorfrom .multimodal import prepare_multimodal_messagesfrom .provider_core.base import LLMProviderfrom .provider_factory import build_isolated_provider, get_runtime_provider+from .types import StreamOutcomefrom .utils import is_local_llm_serverDEFAULT_MAX_RETRIES = settings.retry.max_retries@@ -528,8 +529,15 @@ async def stream(retry_delay: float = DEFAULT_RETRY_DELAY,exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,allow_image_fallback: bool | None = None,+ outcome: StreamOutcome | None = None,**kwargs: Any,) -> AsyncGenerator[str, None]:+ """Stream a completion as text chunks.++ ``outcome``, when given, is filled with the provider's terminal reason and+ usage once the stream ends. A caller that parses the streamed text needs it+ to tell a complete response from one cut off at ``max_tokens`` (#1545).+ """caller_extra_headers = kwargs.pop("extra_headers", None)reasoning_effort = kwargs.pop("reasoning_effort", None)image_data = kwargs.pop("image_data", None)@@ -611,6 +619,9 @@ async def stream(allow_image_fallback=image_fallback_enabled,**extra_kwargs,)+ if outcome is not None:+ outcome.finish_reason = str(response.finish_reason or "")+ outcome.usage = dict(response.usage or {})if in_think_block:in_think_block = Falseawait queue.put("</think>")diff --git a/deeptutor/services/llm/types.py b/deeptutor/services/llm/types.pyindex 8c0a41e26..695fc0b00 100644--- a/deeptutor/services/llm/types.py+++ b/deeptutor/services/llm/types.py@@ -1,12 +1,43 @@"""Shared LLM response data models."""from collections.abc import AsyncGenerator+from dataclasses import dataclass, fieldimport loggingfrom pydantic import BaseModel, Fieldlogger = logging.getLogger(__name__)+#: Terminal reasons that mean "the provider stopped because output hit a cap",+#: i.e. the response is incomplete rather than finished. One table: the agent+#: loop, the research pipeline and the streaming callers all read this.+TRUNCATED_FINISH_REASONS = frozenset({"length", "max_tokens", "max_output_tokens"})+++def finish_was_truncated(reason: str | None) -> bool:+ """Return whether a provider ended generation because output hit a cap."""+ return str(reason or "").strip().lower() in TRUNCATED_FINISH_REASONS+++@dataclass+class StreamOutcome:+ """How a streamed call ended, for callers that only see text chunks.++ :func:`deeptutor.services.llm.factory.stream` yields strings, so a caller+ parsing the result could not tell a complete response from one the provider+ cut off at ``max_tokens`` — which is how a reasoning model's truncated JSON+ surfaced as an undiagnosable parse error (#1545, #1547). Pass one of these+ in and the stream fills it once the provider reports the finish.+ """++ finish_reason: str = ""+ usage: dict[str, int] = field(default_factory=dict)++ @property+ def truncated(self) -> bool:+ """Whether the provider stopped at an output cap."""+ return finish_was_truncated(self.finish_reason)+class TutorResponse(BaseModel):"""LLM completion response container."""@@ -44,9 +75,12 @@ LLMResponse = TutorResponseStreamChunk = TutorStreamChunk__all__ = [+ "TRUNCATED_FINISH_REASONS","AsyncStreamGenerator","LLMResponse","StreamChunk",+ "StreamOutcome","TutorResponse","TutorStreamChunk",+ "finish_was_truncated",]diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex dda3903c5..ec65c3785 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -3429,3 +3429,44 @@ async def test_native_adapter_tool_argument_previews_reach_the_card(if isinstance(event.metadata.get("ask_user_draft"), dict)}assert call_ids == {"ask-1"}+++async def test_truncated_tool_call_says_the_output_hit_the_limit(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The reader must learn the round was cut off, not just that an arg is missing.++ Visualize's canvas came back empty with nothing on screen explaining why: a+ reasoning model spent the round's budget on ``<think>`` and the tool call's+ JSON stopped mid-argument, so the only trace row was the arg guard's+ "missing query" — which reads as a model that forgot a field (#1546).+ """+ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(+ content="<think>先想清楚画什么</think>",+ tool_calls=[{"id": "a", "name": "web_search", "arguments": '{"que'}],+ finish_reason="length",+ )+ ],+ [_llm_chunk(content="答案", finish_reason="stop")],+ ]+ )+ pipeline = AgenticChatPipeline(language="zh")+ pipeline.registry = _Registry()+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ events = await _run(pipeline, UnifiedContext(session_id="s1", user_message="画一张图"))++ warnings = [+ str(event.content)+ for event in events+ if (event.metadata or {}).get("trace_kind") == "warning"+ ]+ assert any("输出 token 上限" in text for text in warnings)+ # The notice is a report, not a control-flow change: the round is handled+ # exactly as before and the turn still finishes.+ assert _answer_text(events) == "答案"diff --git a/tests/agents/math_animator/test_code_generator_agent.py b/tests/agents/math_animator/test_code_generator_agent.pyindex 21aca4e4c..1257403e0 100644--- a/tests/agents/math_animator/test_code_generator_agent.py+++ b/tests/agents/math_animator/test_code_generator_agent.py@@ -79,3 +79,82 @@ async def test_code_generation_fails_clearly_after_structured_retries(analysis=ConceptAnalysis(),design=SceneDesign(),)+++async def test_truncated_generation_grows_the_budget_and_asks_for_less_reasoning(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A reasoning model that hits the cap must not be asked the same thing again.++ The reporter's run spent 21 minutes on 9 identical attempts: every one was+ cut off at ``max_tokens`` with the whole budget inside ``<think>``, and every+ retry sent the same prompt with the same budget (#1547).+ """++ async def fake_sleep(_delay: float) -> None:+ return None++ monkeypatch.setattr(+ "deeptutor.agents.math_animator.agents.code_generator_agent.asyncio.sleep",+ fake_sleep,+ )+ agent = _agent(monkeypatch, [])+ monkeypatch.setattr(agent, "get_max_retries", lambda: 2)+ monkeypatch.setattr(agent, "get_max_tokens", lambda: 8000)+ calls: list[dict[str, object]] = []++ async def truncated_stream(**kwargs) -> AsyncIterator[str]:+ calls.append(kwargs)+ outcome = kwargs["outcome"]+ outcome.finish_reason = "length"+ outcome.usage = {"completion_tokens": 8000, "reasoning_tokens": 7800}+ yield '<think>Let me reconsider the scene once more…</think>{"code": "from man'++ monkeypatch.setattr(agent, "stream_llm", truncated_stream)++ with pytest.raises(GeneratedCodeOutputError) as raised:+ await agent.generate(+ user_input="Animate a proof",+ output_mode="video",+ analysis=ConceptAnalysis(),+ design=SceneDesign(),+ )++ # Each truncated attempt buys a larger budget, capped at twice the+ # configured one so the request stays inside the model's own output limit.+ assert [call["max_tokens"] for call in calls] == [8000, 12000, 16000]+ assert "token limit" in str(calls[1]["user_prompt"])+ assert "token limit" not in str(calls[0]["user_prompt"])+ # The failure names the cause instead of "no usable code after 3 attempts".+ message = str(raised.value)+ assert "cut off at the 16000-token output cap" in message+ assert "chain-of-thought" in message+ assert "reasoning_tokens=7800" in message+++async def test_malformed_output_is_reported_as_malformed_not_as_a_budget_problem(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Only a truncated attempt is fixed by raising max tokens (#1545)."""+ agent = _agent(monkeypatch, [])+ monkeypatch.setattr(agent, "get_max_retries", lambda: 0)+ monkeypatch.setattr(agent, "get_max_tokens", lambda: 8000)++ async def prose_stream(**kwargs) -> AsyncIterator[str]:+ yield "I cannot write this animation."++ monkeypatch.setattr(agent, "stream_llm", prose_stream)++ with pytest.raises(GeneratedCodeOutputError) as raised:+ await agent.generate(+ user_input="Animate a proof",+ output_mode="video",+ analysis=ConceptAnalysis(),+ design=SceneDesign(),+ )++ message = str(raised.value)+ assert "no usable JSON object" in message+ assert "output cap" not in messagediff --git a/tests/agents/math_animator/test_utils.py b/tests/agents/math_animator/test_utils.pyindex 0982ff5a4..adc6ed059 100644--- a/tests/agents/math_animator/test_utils.py+++ b/tests/agents/math_animator/test_utils.py@@ -1,6 +1,12 @@from __future__ import annotations-from deeptutor.agents.math_animator.utils import build_repair_error_message, extract_json_object+from deeptutor.agents.math_animator.utils import (+ build_repair_error_message,+ describe_unusable_output,+ escalated_max_tokens,+ extract_json_object,+)+from deeptutor.services.llm import StreamOutcomedef test_build_repair_error_message_adds_targeted_3d_point_hint() -> None:@@ -43,3 +49,34 @@ def test_extract_json_object_accepts_prefixed_text_before_json() -> None:assert parsed["rationale"] == "repair"assert "class B(Scene)" in parsed["code"]+++def test_escalated_max_tokens_stops_at_twice_the_configured_budget() -> None:+ """Growth is bounded: a max_tokens above the model's own output limit is+ rejected outright, which would turn a truncated answer into none (#1547)."""+ assert escalated_max_tokens(8000, 0) == 8000+ assert escalated_max_tokens(8000, 1) == 12000+ assert [escalated_max_tokens(8000, n) for n in (2, 3, 9)] == [16000, 16000, 16000]+ assert escalated_max_tokens(0, 3) == 0+++def test_describe_unusable_output_separates_the_three_failures() -> None:+ truncated = StreamOutcome(finish_reason="length", usage={"completion_tokens": 8000})+ assert "cut off at the 8000-token output cap" in describe_unusable_output(+ error=ValueError("x"),+ raw_response='<think>long</think>{"code": "from man',+ outcome=truncated,+ max_tokens=8000,+ )+ assert "no text at all" in describe_unusable_output(+ error=ValueError("x"),+ raw_response=" ",+ outcome=StreamOutcome(finish_reason="stop"),+ max_tokens=8000,+ )+ assert "no usable JSON object" in describe_unusable_output(+ error=ValueError("x"),+ raw_response="Sorry, I cannot.",+ outcome=StreamOutcome(finish_reason="stop"),+ max_tokens=8000,+ )diff --git a/tests/api/test_personas_router.py b/tests/api/test_personas_router.pynew file mode 100644index 000000000..7bf50de5c--- /dev/null+++ b/tests/api/test_personas_router.py@@ -0,0 +1,55 @@+"""Personas API: which read-only presets a workspace-scoped read sees (#1534)."""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from deeptutor.api.routers import personas as router+from deeptutor.services.persona import PersonaService+++def _seed_presets(root: Path) -> PersonaService:+ service = PersonaService(root=root)+ service.create("socratic", "Asks questions", "Answer with a question.")+ return service+++def _route_roots(monkeypatch: pytest.MonkeyPatch, *, presets: Path, active: Path) -> None:+ monkeypatch.setattr(router, "_admin_persona_service", lambda: PersonaService(root=presets))+ monkeypatch.setattr(router, "get_persona_service", lambda: PersonaService(root=active))+++def test_admin_inside_a_workspace_still_sees_the_account_presets(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The reporter's picker: the admin's own workspaces offered no persona.++ Presets live in the account-level workspace, so any read rooted elsewhere —+ including the admin's, once each workspace got its own personas directory —+ has to merge them. Gating that on the role made an admin inside a workspace+ the only user who saw fewer presets than the account holds (#1534).+ """+ presets, workspace = tmp_path / "account" / "personas", tmp_path / "ws-1" / "personas"+ _seed_presets(presets)+ _route_roots(monkeypatch, presets=presets, active=workspace)++ listed = asyncio.run(router.list_personas())["personas"]+ assert [(p["name"], p["source"], p["read_only"]) for p in listed] == [+ ("socratic", "admin", True)+ ]+ assert asyncio.run(router.get_persona("socratic"))["read_only"] is True+++def test_reading_the_preset_directory_itself_lists_each_persona_once(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Unchanged behaviour for the account-level read: no self-merge, editable."""+ presets = tmp_path / "account" / "personas"+ _seed_presets(presets)+ _route_roots(monkeypatch, presets=presets, active=presets)++ listed = asyncio.run(router.list_personas())["personas"]+ assert [(p["name"], p["source"]) for p in listed] == [("socratic", "user")]diff --git a/tests/runtime/test_launcher.py b/tests/runtime/test_launcher.pyindex bb31efb03..8fb2a740a 100644--- a/tests/runtime/test_launcher.py+++ b/tests/runtime/test_launcher.py@@ -744,3 +744,57 @@ def test_ready_timeout_failure_names_the_override(monkeypatch) -> None:)assert launcher.BACKEND_READY_TIMEOUT_ENV in str(excinfo.value)+++def test_windows_children_and_console_tools_allocate_no_console(+ monkeypatch, tmp_path: Path+) -> None:+ """Nothing the console-less detached worker starts may open a window.++ Empty console windows flashed on the desktop for every probe, and the one+ Windows gave the node child was a real hazard: closing it delivered+ CTRL_C_EXIT to node, which the launcher read as its frontend exiting and+ answered by stopping the backend — the whole app died from a window close+ (#1501).+ """+ monkeypatch.setattr(launcher.os, "name", "nt")+ monkeypatch.setattr(launcher.subprocess, "CREATE_NEW_PROCESS_GROUP", 0x200, raising=False)+ monkeypatch.setattr(launcher.subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False)+ runs: list[dict[str, object]] = []+ popens: list[dict[str, object]] = []++ class _Completed:+ returncode = 0+ stdout = ""++ def fake_run(command, **kwargs):+ runs.append({"command": command, "kwargs": kwargs})+ return _Completed()++ class _Process:+ pid = 4242+ stdout = None++ def fake_popen(command, **kwargs):+ popens.append({"command": command, "kwargs": kwargs})+ return _Process()++ monkeypatch.setattr(launcher.subprocess, "run", fake_run)+ monkeypatch.setattr(launcher.subprocess, "Popen", fake_popen)+ monkeypatch.setattr(launcher.threading, "Thread", lambda **_kwargs: _NoopThread())+ monkeypatch.setattr(launcher.shutil, "which", lambda name: name)++ launcher._spawn(["node", "server.js"], cwd=tmp_path, env={}, name="frontend")+ launcher._send_tree_signal(4242, None, launcher.KILL_SIGNAL)+ launcher._port_listeners_windows(3782)+ launcher._ensure_web_dependencies(tmp_path, "npm")++ assert popens[0]["kwargs"]["creationflags"] == 0x200 | 0x08000000+ assert [run["command"][0] for run in runs] == ["taskkill", "netstat", "npm"]+ for run in runs:+ assert run["kwargs"]["creationflags"] == 0x08000000, run["command"]+++class _NoopThread:+ def start(self) -> None:+ return Nonediff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.pyindex 1be4f9de4..1e4e40e5e 100644--- a/tests/services/config/test_runtime_settings.py+++ b/tests/services/config/test_runtime_settings.py@@ -1,10 +1,14 @@from __future__ import annotationsimport json+import osfrom pathlib import Path+import pytest+from deeptutor.services.config.model_catalog import SERVICE_NAMESfrom deeptutor.services.config.runtime_settings import (+ SETTINGS_DERIVED_ENV_KEYS,RuntimeSettingsService,ensure_runtime_settings_files,)@@ -566,6 +570,73 @@ def test_runtime_settings_can_ignore_process_overrides(tmp_path: Path) -> None:assert service.load_auth()["enabled"] is False+def test_update_check_toggle_takes_effect_while_the_launcher_managed_backend_runs(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Saving the toggle must change what the live backend reports (#1536).++ ``deeptutor start`` renders system.json into the backend child's+ environment, so ``DEEPTUTOR_VERSION_CHECK_ENABLED`` used to reach it+ indistinguishable from an operator-set deployment override — and an+ override outranks the file forever. Turning "check for updates" off wrote+ the file while the live API kept answering with the startup value+ (``AFTER_FALSE LIVE=True FILE=False``).+ """+ # ``deeptutor start`` exports with ``overwrite=True`` into its own process+ # environment; the dict keeps this test's export out of the real one.+ monkeypatch.setattr(os, "environ", {})+ launcher = RuntimeSettingsService(tmp_path / "settings", process_env={})+ launcher.save_system({"version_check_enabled": True, "backend_port": 8001})+ rendered = launcher.export_environment(overwrite=True)++ # What the launcher hands its children: the rendered settings, plus the port+ # it resolved after a conflict, plus the list of keys that really did come+ # out of the files.+ child_env = {**rendered, "BACKEND_PORT": "8100"}+ child_env[SETTINGS_DERIVED_ENV_KEYS] = ",".join(+ sorted(+ key+ for key in launcher.settings_derived_keys()+ if child_env.get(key) == rendered.get(key)+ )+ )+ backend = RuntimeSettingsService(tmp_path / "settings", process_env=child_env)++ assert backend.load_system()["version_check_enabled"] is True+ backend.save_system({**backend.load_system(), "version_check_enabled": False})+ assert backend.load_system()["version_check_enabled"] is False+ assert _read_json(backend.path_for("system"))["version_check_enabled"] is False+ backend.save_system({**backend.load_system(), "version_check_enabled": True})+ assert backend.load_system()["version_check_enabled"] is True++ # The port the launcher resolved is not a settings-derived value, so the+ # environment still outranks the file for it.+ assert backend.load_system()["backend_port"] == 8100+++def test_operator_env_still_outranks_the_file_in_a_launcher_child(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A variable the operator set is passed through, not relabelled (#1536)."""+ operator_env = {"DEEPTUTOR_VERSION_CHECK_ENABLED": "false"}+ monkeypatch.setattr(os, "environ", dict(operator_env))+ launcher = RuntimeSettingsService(tmp_path / "settings", process_env=operator_env)+ launcher.save_system({"version_check_enabled": True})++ launcher.export_environment(overwrite=True)+ assert "DEEPTUTOR_VERSION_CHECK_ENABLED" not in launcher.settings_derived_keys()++ backend = RuntimeSettingsService(+ tmp_path / "settings",+ process_env={+ **operator_env,+ SETTINGS_DERIVED_ENV_KEYS: ",".join(sorted(launcher.settings_derived_keys())),+ },+ )+ assert backend.load_system()["version_check_enabled"] is False++def test_chat_attachment_limits_defaults_and_clamping(tmp_path: Path) -> None:service = RuntimeSettingsService(tmp_path / "settings", process_env={})system = service.load_system()diff --git a/tests/services/config/test_visualize_params.py b/tests/services/config/test_visualize_params.pynew file mode 100644index 000000000..f4316fcd6--- /dev/null+++ b/tests/services/config/test_visualize_params.py@@ -0,0 +1,64 @@+"""The visualize loop's output budget must be readable from agents.yaml.++``visualize`` built its pipeline with ``max_tokens=16000`` written into the call,+so a reasoning model that spends most of a round inside ``<think>`` truncated the+``submit_visualization`` arguments mid-JSON and the canvas came back empty — with+no setting anywhere that changed it (#1546).+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest+import yaml++from deeptutor.services.config import capabilities_settings as module+from deeptutor.services.config.capabilities_settings import get_visualize_params+++def _settings_root(tmp_path: Path, content: dict[str, Any]) -> Path:+ settings_dir = tmp_path / "data" / "user" / "settings"+ settings_dir.mkdir(parents=True, exist_ok=True)+ (settings_dir / "agents.yaml").write_text(yaml.dump(content), encoding="utf-8")+ return tmp_path+++def test_visualize_defaults_match_the_previously_hardcoded_call(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """An install that never touched this keeps exactly the old behaviour."""+ monkeypatch.setattr(module, "PROJECT_ROOT", _settings_root(tmp_path, {"capabilities": {}}))++ assert get_visualize_params() == {"temperature": 0.15, "max_tokens": 16000}+++def test_visualize_budget_is_overridable_from_agents_yaml(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ module,+ "PROJECT_ROOT",+ _settings_root(+ tmp_path,+ {"capabilities": {"visualize": {"temperature": 0.4, "max_tokens": 48000}}},+ ),+ )++ assert get_visualize_params() == {"temperature": 0.4, "max_tokens": 48000}+++def test_visualize_is_exposed_to_the_settings_page(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The same block the UI reads and writes, so the page cannot drift."""+ monkeypatch.setattr(module, "PROJECT_ROOT", _settings_root(tmp_path, {"capabilities": {}}))++ payload = module.capabilities_settings_dict()++ assert payload["visualize"] == {"temperature": 0.15, "max_tokens": 16000}++ module.save_capabilities_settings({"visualize": {"max_tokens": 32000}})++ assert get_visualize_params()["max_tokens"] == 32000diff --git a/tests/services/rag/test_lightrag_roles.py b/tests/services/rag/test_lightrag_roles.pyindex ccd221a8d..b8475aef5 100644--- a/tests/services/rag/test_lightrag_roles.py+++ b/tests/services/rag/test_lightrag_roles.py@@ -144,6 +144,15 @@ def role_environment(tmp_path, monkeypatch):"deeptutor.services.embedding.get_embedding_config",lambda: scoped_embedding_config() or state["embedding"],)+ # The knowledge routes resolve a *selected* embedding through the module+ # binding, not the package-level zero-arg alias above, and the selection+ # itself comes from the real catalog. Patching only the alias left the route+ # reading whatever embedding the developer has configured and scoping it for+ # everything downstream, so this fixture's default never reached it.+ monkeypatch.setattr(+ "deeptutor.services.embedding.config.get_embedding_config",+ lambda selection=None, **_kwargs: state["embedding"],+ )yield statereset_current_user(token)diff --git a/tests/services/test_github_source_unchanged_sync.py b/tests/services/test_github_source_unchanged_sync.pynew file mode 100644index 000000000..f886c7b72--- /dev/null+++ b/tests/services/test_github_source_unchanged_sync.py@@ -0,0 +1,82 @@+"""An unchanged GitHub source must still record that it was checked.++``sync_source`` returned ``skipped=True`` without touching the source's state+when the remote branch still pointed at the synced commit, so ``last_synced_at``+never moved: past the 24-hour freshness window the hourly service re-queried+GitHub every cycle and the source stayed stale forever, and an error string from+an earlier transient failure stayed on it after a later check had confirmed the+source current (#1489).+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from deeptutor.services.github_source import sync as sync_module+++class _Client:+ """Answers the SHA probe and fails loudly on any transfer."""++ def __init__(self, sha: str) -> None:+ self.sha = sha++ async def get_latest_commit_sha(self, repo: str, branch: str) -> str:+ return self.sha++ async def get_tree(self, *args: Any, **kwargs: Any):+ raise AssertionError("an unchanged source must not download anything")++ async def compare_commits(self, *args: Any, **kwargs: Any):+ raise AssertionError("an unchanged source must not compare commits")+++def recorded_state(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:+ writes: list[dict[str, Any]] = []++ class _Manager:+ def __init__(self, *, base_dir: str) -> None:+ self.base_dir = base_dir++ def update_github_source_state(self, **fields: Any) -> None:+ writes.append(fields)++ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", _Manager)+ monkeypatch.setattr(+ "deeptutor.services.rag.provider_binding.resolve_bound_provider",+ lambda base_dir, kb_name: "llamaindex",+ )+ return writes+++async def test_unchanged_source_is_marked_fresh_and_its_old_error_cleared(+ tmp_path: Path, recorded_state: list[dict[str, Any]]+) -> None:+ source = {+ "id": "src",+ "repo": "owner/repo",+ "last_synced_sha": "deadbeef",+ "last_synced_at": "2020-01-01T00:00:00Z",+ "last_sync_status": "error",+ "last_sync_error": "rate limited",+ "files_synced": 7,+ }++ result = await sync_module.sync_source(+ "kb", source, base_dir=str(tmp_path), client=_Client("deadbeef")+ )++ assert (result.ok, result.skipped) == (True, True)+ assert len(recorded_state) == 1+ written = recorded_state[0]+ assert written["last_sync_status"] == "success"+ assert written["last_sync_error"] is None+ assert written["last_synced_sha"] == "deadbeef"+ assert written["last_synced_at"] > "2020-01-01T00:00:00Z"+ # Nothing was transferred, so the last real transfer's count must survive.+ assert "files_synced" not in writtendiff --git a/web/app/(workspace)/whisper/page.tsx b/web/app/(workspace)/whisper/page.tsxindex 566709244..1a1718883 100644--- a/web/app/(workspace)/whisper/page.tsx+++ b/web/app/(workspace)/whisper/page.tsx@@ -21,12 +21,7 @@ import {type WhisperSeat,} from "@/lib/whisper-transcript";-function newMessageId(): string {- if (typeof crypto !== "undefined" && "randomUUID" in crypto) {- return crypto.randomUUID();- }- return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;-}+import { randomUuid } from "@/lib/random-uuid";function looksLikeRoomEnded(text: string): boolean {const t = (text || "").toLowerCase();@@ -95,7 +90,7 @@ export default function WhisperPage() {setMessages((prev) => [...prev,{- id: newMessageId(),+ id: randomUuid(),role: "system",text,stage: event.stage,@@ -112,7 +107,7 @@ export default function WhisperPage() {setMessages((prev) => [...prev,{- id: newMessageId(),+ id: randomUuid(),role: "assistant",text,stage: event.stage || undefined,@@ -199,7 +194,7 @@ export default function WhisperPage() {setMessages((prev) => [...prev,{- id: newMessageId(),+ id: randomUuid(),role: "system",text: "Connection failed. Please try again.",},@@ -221,7 +216,7 @@ export default function WhisperPage() {setMessages((prev) => [...prev,{- id: newMessageId(),+ id: randomUuid(),role: "user",text,localSeat: seat,diff --git a/web/components/chat/home/StandaloneComposer.tsx b/web/components/chat/home/StandaloneComposer.tsxindex bdc515f4c..a57c83802 100644--- a/web/components/chat/home/StandaloneComposer.tsx+++ b/web/components/chat/home/StandaloneComposer.tsx@@ -28,6 +28,8 @@ import { useTranslation } from "react-i18next";import ChatComposer from "@/components/chat/home/ChatComposer";import type { ContextBudget } from "@/components/chat/home/ContextBudgetChip";import type { CapabilityDef } from "@/features/capabilities/presentation";+import type { ResourceSelection } from "@/features/chat/ChatStateAdapter";+import type { ComposerResourceCatalog } from "@/hooks/useComposerResources";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";import { useAttachmentLimits } from "@/lib/attachment-limits";@@ -187,6 +189,18 @@ interface StandaloneComposerProps {*/personaSelection?: string;onPersonaSelectionChange?: (persona: string) => void;+ /**+ * Which of the workspace's skills and MCP servers this conversation narrows+ * itself to, and what there is to narrow. Session-level like the persona+ * above: pass the trio and the "+" menu grows the Skills and MCP entries,+ * omit it and the conversation keeps inheriting its workspace untouched.+ * `ChatComposer` needs both halves — it hides an entry whose catalog is+ * empty — which is why a surface that passed neither showed no picker at all+ * while the chat page showed one for the same account (#1534).+ */+ resourceCatalog?: ComposerResourceCatalog;+ resourceSelection?: ResourceSelection;+ onResourceSelectionChange?: (selection: ResourceSelection) => void;/** Hide the My Agents reference entry. */agentsAvailable?: boolean;/** Receives a function that drops text into the textarea (ask_user chips). */@@ -217,6 +231,9 @@ function StandaloneComposerImpl({onLLMSelectionChange,personaSelection,onPersonaSelectionChange,+ resourceCatalog,+ resourceSelection,+ onResourceSelectionChange,agentsAvailable = false,prefillInputRef,contextBudget = null,@@ -880,6 +897,9 @@ function StandaloneComposerImpl({onSubagentBudgetChange={setSubagentBudget}personaSelection={personaSelection}onPersonaSelectionChange={onPersonaSelectionChange}+ resourceCatalog={resourceCatalog}+ resourceSelection={resourceSelection}+ onResourceSelectionChange={onResourceSelectionChange}personaSelectorOpen={personaSelectorOpen}onPersonaSelectorOpenChange={setPersonaSelectorOpen}llmOptions={llmOptions}diff --git a/web/components/learning/LearningWays.tsx b/web/components/learning/LearningWays.tsxindex 460bb8717..ca3947208 100644--- a/web/components/learning/LearningWays.tsx+++ b/web/components/learning/LearningWays.tsx@@ -3,7 +3,10 @@import Link from 'next/link'import { useCallback, useEffect, useId, useRef, useState } from 'react'import { createPortal } from 'react-dom'-import { AnimatePresence, motion, useReducedMotion, type Transition } from 'framer-motion'+// `m`, not `motion`: the app renders inside a strict `LazyMotion`, which+// rejects the full component outright — the learning dashboard crashed on its+// first card instead of animating it (#1549).+import { AnimatePresence, m as motion, useReducedMotion, type Transition } from 'framer-motion'import { ArrowUpRight, ArrowRight, Check, X } from 'lucide-react'import { useTranslation } from 'react-i18next'type LearningKind = LearningSurface['kind']diff --git a/web/components/learning/practice/PracticeSession.tsx b/web/components/learning/practice/PracticeSession.tsxindex d107d5d42..680fea76c 100644--- a/web/components/learning/practice/PracticeSession.tsx+++ b/web/components/learning/practice/PracticeSession.tsx@@ -2,6 +2,7 @@import Markdown from '@/components/common/MarkdownRenderer'import { practiceMarkdown } from '@/lib/practice-content'+import { randomUuid } from '@/lib/random-uuid'import { WorkspaceLabel } from '../LibraryWorkspace'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -193,7 +194,7 @@ function PracticeTurn({setError('')// Retrying a lost response must reuse its ID and exact payload.submission.current ??= {- request_id: crypto.randomUUID(),+ request_id: randomUuid(),version: question.state.version,rating,answer,diff --git a/web/components/quiz/QuizViewer.tsx b/web/components/quiz/QuizViewer.tsxindex e769c120a..b910fa712 100644--- a/web/components/quiz/QuizViewer.tsx+++ b/web/components/quiz/QuizViewer.tsx@@ -55,6 +55,8 @@ import {import { recordQuizResults } from "@/lib/session-api";import { apiUrl } from "@/lib/api";+import { randomUuid } from "@/lib/random-uuid";+/** Resolve a possibly-relative AttachmentStore URL to an absolute one so* ``<img src>`` works regardless of the API/frontend port pairing. */function resolveImageSrc(url: string | null | undefined): string | undefined {@@ -111,10 +113,7 @@ const EMPTY_ANSWER: AnswerState = {};function makeAnswerImageId(): string {- if (typeof crypto !== "undefined" && "randomUUID" in crypto) {- return crypto.randomUUID().replaceAll("-", "").slice(0, 12);- }- return Math.random().toString(36).slice(2, 14);+ return randomUuid().replaceAll("-", "").slice(0, 12);}type JudgmentState = {diff --git a/web/components/settings/ModelsWorkspace.tsx b/web/components/settings/ModelsWorkspace.tsxindex 4470aa519..fc1f9d2ad 100644--- a/web/components/settings/ModelsWorkspace.tsx+++ b/web/components/settings/ModelsWorkspace.tsx@@ -44,6 +44,7 @@ import {workspaceCardClass,} from "./WorkspaceShell";+import { randomUuid } from "@/lib/random-uuid";type ModelPage = "llm" | "embedding" | "search" | "voice" | "multimodal";const PAGE_SERVICES: Record<ModelPage, ServiceName[]> = {llm: ["llm", "task"],@@ -108,42 +109,50 @@ export function ModelsWorkspace({const selectedRow = rows.find((r) => r.key === selected);// Providers and models can be created together in the same draft.const sources = providerRegistry(draft);- const compatible = (service: ServiceName) =>- sources.filter((source) => {- if ("managed_by" in source.source && source.source.managed_by)- return false;- const adapterService = service === "task" ? "llm" : service;- const exact = providers[adapterService]?.some(- (option) =>- option.value === source.provider &&- option.value !== "none" &&- option.status !== "deprecated",- );- const mapped = connectionTargets.find(- (target) => target.provider === source.provider,- )?.services[adapterService];- return Boolean(- exact ||- mapped ||- (service !== "search" && source.service === service) ||- (service === "task" && source.service === "llm") ||- (service !== "search" && source.provider === "custom"),- );- });+ /** Whether a built-in adapter is on record for this vendor and service. */+ const declared = (source: ProviderSource, service: ServiceName) => {+ const adapterService = service === "task" ? "llm" : service;+ const exact = providers[adapterService]?.some(+ (option) =>+ option.value === source.provider &&+ option.value !== "none" &&+ option.status !== "deprecated",+ );+ const mapped = connectionTargets.find(+ (target) => target.provider === source.provider,+ )?.services[adapterService];+ return Boolean(+ exact ||+ mapped ||+ (service !== "search" && source.service === service) ||+ (service === "task" && source.service === "llm") ||+ (service !== "search" && source.provider === "custom"),+ );+ };+ // Not being on record is not a veto for any service. Whether a vendor serves+ // a given model type is not knowable from its registry entry — plenty of+ // OpenAI-compatible endpoints serve embeddings or speech without appearing in+ // that service's table — so every provider is selectable, the ones with no+ // adapter on record are only grouped apart, and a wrong pick is reported by+ // the model test rather than pre-empted here. Managed credentials stay out:+ // that is not a capability judgement, their models arrive with them.+ const selectable = sources.filter(+ (source) => !("managed_by" in source.source && source.source.managed_by),+ );const start = () => {setAdding(true);revealDetail();const preferred = new URLSearchParams(window.location.search).get("provider",);- if (preferred && compatible(newService).some((p) => p.id === preferred))+ if (preferred && selectable.some((p) => p.id === preferred))setNewProvider(preferred);};const create = () => {- const source = compatible(newService).find((p) => p.id === newProvider);+ const source = selectable.find((p) => p.id === newProvider);if (!source) return;- const profileId = `${newService}-profile-${crypto.randomUUID()}`;- const modelId = `${newService}-model-${crypto.randomUUID()}`;+ const profileId = `${newService}-profile-${randomUuid()}`;+ const modelId = `${newService}-model-${randomUuid()}`;const ref = providerAdapter(source,newService,@@ -352,7 +361,8 @@ export function ModelsWorkspace({}}provider={newProvider}onProvider={setNewProvider}- sources={compatible(newService)}+ sources={selectable}+ declared={(source) => declared(source, newService)}onCreate={create}onCancel={() => setAdding(false)}/>@@ -360,7 +370,8 @@ export function ModelsWorkspace({<ModelEditorkey={selectedRow.key}row={selectedRow}- sources={compatible(selectedRow.service)}+ sources={selectable}+ declared={(source) => declared(source, selectedRow.service)}onRemoved={() => setSelected(null)}/>) : (@@ -379,6 +390,41 @@ export function ModelsWorkspace({);}+/**+ * Provider options for one service. Vendors with no adapter on record are+ * offered rather than hidden — they are only separated out, so the list still+ * says which ones are a known quantity without deciding for you.+ */+function ProviderOptions({+ sources,+ declared,+}: {+ sources: ProviderSource[];+ declared: (source: ProviderSource) => boolean;+}) {+ const { t } = useTranslation();+ const option = (p: ProviderSource) => (+ <option key={p.id} value={p.id}>+ {p.name}+ </option>+ );+ const unverified = sources.filter((source) => !declared(source));+ if (!unverified.length) return <>{sources.map(option)}</>;+ const known = sources.filter(declared);+ return (+ <>+ {known.length > 0 && (+ <optgroup label={t("Supported for this model type")}>+ {known.map(option)}+ </optgroup>+ )}+ <optgroup label={t("Not on record — verify with the model test")}>+ {unverified.map(option)}+ </optgroup>+ </>+ );+}+/*** The add flow. It lives in the detail pane, opposite the list, because that is* the one place on the page that means "what you are configuring right now" —@@ -391,6 +437,7 @@ function AddModelPanel({provider,onProvider,sources,+ declared,onCreate,onCancel,}: {@@ -400,6 +447,7 @@ function AddModelPanel({provider: string;onProvider: (value: string) => void;sources: ProviderSource[];+ declared: (source: ProviderSource) => boolean;onCreate: () => void;onCancel: () => void;}) {@@ -444,26 +492,17 @@ function AddModelPanel({onChange={(e) => onProvider(e.target.value)}><option value="">{t("Choose a provider")}</option>- {sources.map((p) => (- <option key={p.id} value={p.id}>- {p.name}- </option>- ))}+ <ProviderOptions sources={sources} declared={declared} /></select></label></div>- {(page === "voice" || page === "multimodal") && (- <p className="mt-3 text-xs leading-relaxed text-[var(--muted-foreground)]">- {t("Only providers with a supported API for this model type are listed. A provider offering a model does not mean its API is integrated here.")}- </p>- )}- {service === "search" && (- <p className="mt-3 text-xs leading-relaxed text-[var(--muted-foreground)]">- {t(- "Search uses providers with a supported search API. A language model listing alone does not confirm search support.",- )}- </p>- )}+ <p className="mt-3 text-xs leading-relaxed text-[var(--muted-foreground)]">+ {t(+ service === "search"+ ? "Every provider is selectable. Search has no generic adapter, so a provider without a search API of its own is rejected by the search test — that is where a wrong pick shows up."+ : "Every provider is selectable. One with no adapter on record for this model type is called as an OpenAI-compatible endpoint derived from its provider URL — add the model, then run the model test to see whether it answers.",+ )}+ </p><div className="mt-5 flex flex-wrap items-center gap-2 border-t border-[color-mix(in_srgb,var(--border)_70%,transparent)] pt-4"><buttontype="button"@@ -485,10 +524,12 @@ type ModelRow = ReturnType<typeof flattenModels>[number];function ModelEditor({row,sources,+ declared,onRemoved,}: {row: ModelRow;sources: ProviderSource[];+ declared: (source: ProviderSource) => boolean;onRemoved: () => void;}) {const { t } = useTranslation();@@ -648,13 +689,20 @@ function ModelEditor({{provider && !sources.some((p) => p.id === provider.id) && (<option value={provider.id}>{provider.name}</option>)}- {sources.map((p) => (- <option key={p.id} value={p.id}>- {p.name}- </option>- ))}+ <ProviderOptions sources={sources} declared={declared} /></select></label>+ {/* Why the test below matters more here: nothing vouches for this+ pairing yet, so say what request it will actually make. */}+ {provider && !declared(provider) && (+ <p className="text-xs leading-relaxed text-[var(--muted-foreground)]">+ {t(+ service === "search"+ ? "No search adapter is on record for this provider, and search has no OpenAI-compatible fallback. Run the test below — it will say so rather than search with the wrong engine."+ : "No adapter for this model type is on record for this provider. DeepTutor calls it as an OpenAI-compatible endpoint derived from the provider URL; run the model test below to confirm it answers.",+ )}+ </p>+ )}<Linkhref={`/settings/connections${provider ? `?provider=${encodeURIComponent(provider.id)}` : ""}`}className="inline-block text-xs text-[var(--muted-foreground)] underline underline-offset-4 transition-colors hover:text-[var(--foreground)]"diff --git a/web/components/settings/ProvidersWorkspace.tsx b/web/components/settings/ProvidersWorkspace.tsxindex be996f9c8..657368d7d 100644--- a/web/components/settings/ProvidersWorkspace.tsx+++ b/web/components/settings/ProvidersWorkspace.tsx@@ -6,6 +6,7 @@ import Link from "next/link";import { ArrowRight, Cable, Plus, Trash2 } from "lucide-react";import { useTranslation } from "react-i18next";import ProviderIcon from "@/components/common/ProviderIcon";+import { randomUuid } from "@/lib/random-uuid";import {useSettings,type CatalogConnection,@@ -107,7 +108,7 @@ export function ProvidersWorkspace() {setAdding(false);return;}- const id = `conn-${crypto.randomUUID()}`;+ const id = `conn-${randomUuid()}`;const entry: CatalogConnection = {id,name: option.label,diff --git a/web/components/space/learning/MasteryComposer.tsx b/web/components/space/learning/MasteryComposer.tsxindex 5c073d723..9c6b179aa 100644--- a/web/components/space/learning/MasteryComposer.tsx+++ b/web/components/space/learning/MasteryComposer.tsx@@ -26,6 +26,8 @@ import StandaloneComposer, {} from "@/components/chat/home/StandaloneComposer";import { MASTERY_CAPABILITY_VALUE } from "@/features/capabilities/presentation";import { useChatStateAdapter } from "@/features/chat/ChatStateAdapter";+import { useChatWorkspaces } from "@/hooks/useChatWorkspaces";+import { useComposerResources } from "@/hooks/useComposerResources";import { useContextBudget } from "@/hooks/useContextBudget";import { useWorkspaceChatActions } from "@/hooks/useWorkspaceChatActions";import {@@ -56,7 +58,14 @@ export function MasteryComposer({setKBs,setLLMSelection,setPersonaSelection,+ setResourceSelection,} = useChatStateAdapter();+ // A mastery session is a chat session in a workspace, so the same skills and+ // MCP servers are on offer here. Without the catalog the composer had no+ // Skills entry at all, and a learner whose workspace allows a skill could+ // only reach it by opening the chat page instead (#1534).+ const { workspaces } = useChatWorkspaces();+ const resourceCatalog = useComposerResources(state.workspaceId, workspaces);// Pins the turn to the tutor loop; returns no capabilities to offer.useWorkspaceChatActions({ pinnedCapability: MASTERY_CAPABILITY_VALUE });const contextBudget = useContextBudget(state.messages);@@ -127,6 +136,9 @@ export function MasteryComposer({onLLMSelectionChange={setLLMSelection}personaSelection={state.personaSelection}onPersonaSelectionChange={setPersonaSelection}+ resourceCatalog={resourceCatalog}+ resourceSelection={state.resourceSelection}+ onResourceSelectionChange={setResourceSelection}onSubmit={handleSubmit}onCancelStreaming={cancelStreamingTurn}// The suggested question *is* the placeholder once there is one: namingdiff --git a/web/components/space/learning/RouteDraftEditor.tsx b/web/components/space/learning/RouteDraftEditor.tsxindex 25cb3d116..737a3cab8 100644--- a/web/components/space/learning/RouteDraftEditor.tsx+++ b/web/components/space/learning/RouteDraftEditor.tsx@@ -3,6 +3,7 @@import { ArrowDown, ArrowUp, Plus, Trash2, X } from "lucide-react";import type { ModuleInit, TopicDraft } from "@/lib/learning-api";+import { randomUuid } from "@/lib/random-uuid";import { useTranslation } from "react-i18next";import type { Translate } from "./format";@@ -13,13 +14,8 @@ import {routeDraftIssues,} from "./route-draft";-let fallbackSequence = 0;-function draftId(kind: "region" | "waypoint"): string {- const random = globalThis.crypto?.randomUUID?.();- return random- ? `draft_${kind}_${random}`- : `draft_${kind}_${Date.now()}_${fallbackSequence++}`;+ return `draft_${kind}_${randomUuid()}`;}/**diff --git a/web/eslint.config.mjs b/web/eslint.config.mjsindex 9f9c0bec1..5758f0bce 100644--- a/web/eslint.config.mjs+++ b/web/eslint.config.mjs@@ -23,6 +23,16 @@ const config = [name: "@/components/ui/Tooltip",message: "Import the canonical @/shared/ui/Tooltip primitive.",},+ {+ // The app tree renders inside a strict `LazyMotion`, which throws+ // on a full `motion` component rather than degrading — one such+ // import crashed the whole learning dashboard (#1549). Stating it+ // here is what stops the next file from finding out at runtime.+ name: "framer-motion",+ importNames: ["motion"],+ message:+ "Import `m as motion`: a full `motion` component throws inside the strict LazyMotion provider.",+ },],},],diff --git a/web/features/settings/sections/CapabilitiesSettingsSection.tsx b/web/features/settings/sections/CapabilitiesSettingsSection.tsxindex f9b7e790b..ba51b9397 100644--- a/web/features/settings/sections/CapabilitiesSettingsSection.tsx+++ b/web/features/settings/sections/CapabilitiesSettingsSection.tsx@@ -61,6 +61,7 @@ interface CapabilitiesSettingsDTO {co_writer: SimpleLLMBlock;vision_solver: SimpleLLMBlock;math_animator: SimpleLLMBlock;+ visualize: SimpleLLMBlock;}function isValidCapabilitiesDTO(@@ -79,7 +80,8 @@ function isValidCapabilitiesDTO(typeof solve.max_rounds === "number" &&typeof solve.max_replans === "number" &&!!v.research &&- !!v.question+ !!v.question &&+ !!v.visualize);}@@ -195,7 +197,12 @@ export default function CapabilitiesSettingsPage() {}function patchSimple(- cap: "solve" | "co_writer" | "vision_solver" | "math_animator",+ cap:+ | "solve"+ | "co_writer"+ | "vision_solver"+ | "math_animator"+ | "visualize",value: Partial<SimpleLLMBlock>,) {if (!settings) return;@@ -500,6 +507,32 @@ export default function CapabilitiesSettingsPage() {/></SettingSection>+ <SettingSection+ title={t("Visualize")}+ description={t("SVG / chart / diagram generation loop.")}+ >+ <NumberRow+ label={t("Temperature")}+ value={settings.visualize.temperature}+ onChange={(n) => patchSimple("visualize", { temperature: n })}+ min={0}+ max={2}+ step={0.05}+ isFloat+ />+ <NumberRow+ label={t("Max tokens")}+ help={t(+ "A reasoning model can spend most of this on internal reasoning; raise it if a canvas comes back empty.",+ )}+ value={settings.visualize.max_tokens}+ onChange={(n) => patchSimple("visualize", { max_tokens: n })}+ min={256}+ max={200000}+ step={100}+ />+ </SettingSection>+<SettingSectiontitle={t("Co-writer")}description={t("Selection edit / inline rewrite agent.")}diff --git a/web/lib/chat-import/agent-store.ts b/web/lib/chat-import/agent-store.tsindex 0aa97832d..b16f6d195 100644--- a/web/lib/chat-import/agent-store.ts+++ b/web/lib/chat-import/agent-store.ts@@ -13,6 +13,7 @@*/import { SOURCE_LABEL } from "./shared";+import { randomUuid } from "../random-uuid";import type { AgentScope, ImportSource } from "./types";export interface ImportAgent {@@ -118,11 +119,7 @@ function tx<T>(/** A fresh, source-namespaced agent id. */export function newAgentId(source: ImportSource): string {- const rand =- typeof crypto !== "undefined" && "randomUUID" in crypto- ? crypto.randomUUID()- : Math.random().toString(36).slice(2);- return `${source}-${rand}`;+ return `${source}-${randomUuid()}`;}export async function saveAgent(agent: ImportAgent): Promise<void> {diff --git a/web/lib/model-settings.ts b/web/lib/model-settings.tsindex 78fcec51b..23f969646 100644--- a/web/lib/model-settings.ts+++ b/web/lib/model-settings.ts@@ -1,4 +1,5 @@import { modelProvider } from "./provider-registry";+import { randomUuid } from "./random-uuid";import type {Catalog,CatalogModel,@@ -154,7 +155,7 @@ export function addDiscoveredModels(return blank.id;}const model: CatalogModel = {- id: `model-${crypto.randomUUID()}`,+ id: `model-${randomUuid()}`,name: value,model: value,};diff --git a/web/lib/provider-registry.ts b/web/lib/provider-registry.tsindex 7869a203f..86e0cf3a1 100644--- a/web/lib/provider-registry.ts+++ b/web/lib/provider-registry.ts@@ -172,10 +172,17 @@ export function providerAdapter(service === "task" ? "llm" : service];const exact = providers[service]?.find((p) => p.value === source.provider);+ // `custom` is the generic OpenAI-compatible binding; every service but search+ // has one, so an unrecognized vendor still resolves through it. Search has no+ // generic adapter, so it keeps the vendor's own name and gets rejected by name+ // rather than masquerading as an OpenAI-compatible search engine.const binding =target?.provider ||exact?.value ||- (service === "llm" || service === "task" || source.service === service+ (service === "llm" ||+ service === "task" ||+ service === "search" ||+ source.service === service? source.provider: "custom");return {diff --git a/web/lib/random-uuid.ts b/web/lib/random-uuid.tsnew file mode 100644index 000000000..9a5d6e2bb--- /dev/null+++ b/web/lib/random-uuid.ts@@ -0,0 +1,40 @@+/**+ * A v4 UUID minted in the browser, on any origin.+ *+ * ``crypto.randomUUID`` is defined only in a secure context, so a deployment+ * reached over plain HTTP — a LAN box, a VPS without TLS — has none, and every+ * caller that reached for it *threw*. On the provider settings page that+ * exception landed inside the "Continue" click handler, before the connection+ * was staged: the button appeared dead, with nothing on screen to explain it.+ *+ * ``crypto.getRandomValues`` carries no such gate, which is why it is the+ * fallback rather than ``Math.random``: same shape, still unguessable. The+ * ``Math.random`` tail is only for a runtime with no Web Crypto at all.+ *+ * ``contracts/parse/turn-command.ts`` states the same decision a second time+ * for ``command_id``, and has to: the architecture keeps ``contracts/`` a leaf+ * (``contracts-are-leaves`` in ``.dependency-cruiser.cjs``), so it cannot+ * import this. Everything outside that layer mints ids here.+ */+export function randomUuid(): string {+ const webCrypto = globalThis.crypto;+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();+ const bytes = new Uint8Array(16);+ if (typeof webCrypto?.getRandomValues === "function") {+ webCrypto.getRandomValues(bytes);+ } else {+ for (let i = 0; i < bytes.length; i += 1) {+ bytes[i] = Math.floor(Math.random() * 256);+ }+ }+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));+ return [+ hex.slice(0, 4).join(""),+ hex.slice(4, 6).join(""),+ hex.slice(6, 8).join(""),+ hex.slice(8, 10).join(""),+ hex.slice(10, 16).join(""),+ ].join("-");+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 37d3f4084..9c273a186 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -4340,7 +4340,6 @@"Search APIs use an engine configuration rather than a model ID or context window.": "Search APIs use an engine configuration rather than a model ID or context window.","Search by model or provider": "Search by model or provider","Search by name": "Search by name",- "Search uses providers with a supported search API. A language model listing alone does not confirm search support.": "Search uses providers with a supported search API. A language model listing alone does not confirm search support.","Select a model to view its settings and connection test.": "Select a model to view its settings and connection test.","Select a provider to edit its connection. Models are managed on their own pages.": "Select a provider to edit its connection. Models are managed on their own pages.","Send dimensions in embedding requests": "Send dimensions in embedding requests",@@ -4386,7 +4385,12 @@"Multimodal generation": "Multimodal generation","Manage speech synthesis and transcription models using saved providers.": "Manage speech synthesis and transcription models using saved providers.","Manage image and video generation models using saved providers.": "Manage image and video generation models using saved providers.",- "Only providers with a supported API for this model type are listed. A provider offering a model does not mean its API is integrated here.": "Only providers with a supported API for this model type are listed. A provider offering a model does not mean its API is integrated here.",+ "Every provider is selectable. One with no adapter on record for this model type is called as an OpenAI-compatible endpoint derived from its provider URL — add the model, then run the model test to see whether it answers.": "Every provider is selectable. One with no adapter on record for this model type is called as an OpenAI-compatible endpoint derived from its provider URL — add the model, then run the model test to see whether it answers.",+ "Every provider is selectable. Search has no generic adapter, so a provider without a search API of its own is rejected by the search test — that is where a wrong pick shows up.": "Every provider is selectable. Search has no generic adapter, so a provider without a search API of its own is rejected by the search test — that is where a wrong pick shows up.",+ "No adapter for this model type is on record for this provider. DeepTutor calls it as an OpenAI-compatible endpoint derived from the provider URL; run the model test below to confirm it answers.": "No adapter for this model type is on record for this provider. DeepTutor calls it as an OpenAI-compatible endpoint derived from the provider URL; run the model test below to confirm it answers.",+ "No search adapter is on record for this provider, and search has no OpenAI-compatible fallback. Run the test below — it will say so rather than search with the wrong engine.": "No search adapter is on record for this provider, and search has no OpenAI-compatible fallback. Run the test below — it will say so rather than search with the wrong engine.",+ "Supported for this model type": "Supported for this model type",+ "Not on record — verify with the model test": "Not on record — verify with the model test","Detected describes model modalities, not API compatibility. Provider support indicates an available integration; test a specific model to verify your account access.": "Detected describes model modalities, not API compatibility. Provider support indicates an available integration; test a specific model to verify your account access.","After applying changes, lower limits take effect immediately. Raising limits needs a backend restart so larger uploads fit through the WebSocket transport.": "After applying changes, lower limits take effect immediately. Raising limits needs a backend restart so larger uploads fit through the WebSocket transport.","Enter a model ID before applying changes.": "Enter a model ID before applying changes.",@@ -4998,5 +5002,7 @@"{{count}} KBs": "{{count}} KBs","{{count}} MCP tools": "{{count}} MCP tools","{{count}} partners": "{{count}} partners",- "{{count}} skills": "{{count}} skills"+ "{{count}} skills": "{{count}} skills",+ "SVG / chart / diagram generation loop.": "SVG / chart / diagram generation loop.",+ "A reasoning model can spend most of this on internal reasoning; raise it if a canvas comes back empty.": "A reasoning model can spend most of this on internal reasoning; raise it if a canvas comes back empty."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex daa2cd011..db9a66bd0 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -4340,7 +4340,6 @@"Search APIs use an engine configuration rather than a model ID or context window.": "搜索 API 配置的是搜索引擎,无需填写 Model ID 或上下文窗口。","Search by model or provider": "搜索模型或提供方名称","Search by name": "搜索名称",- "Search uses providers with a supported search API. A language model listing alone does not confirm search support.": "搜索需要提供方支持相应的搜索 API;仅能获取语言模型列表,不代表支持搜索。","Select a model to view its settings and connection test.": "选择一个模型,查看并编辑参数、测试连接。","Select a provider to edit its connection. Models are managed on their own pages.": "选择提供方编辑连接信息。具体模型在各类模型页面中管理。","Send dimensions in embedding requests": "在嵌入请求中发送维度参数",@@ -4386,7 +4385,12 @@"Multimodal generation": "多模态生成","Manage speech synthesis and transcription models using saved providers.": "使用已配置的提供方管理语音合成与语音识别模型。","Manage image and video generation models using saved providers.": "使用已配置的提供方管理图片与视频生成模型。",- "Only providers with a supported API for this model type are listed. A provider offering a model does not mean its API is integrated here.": "仅显示已适配此类模型 API 的提供方。提供方拥有某个模型,并不代表这里已接入对应的 API。",+ "Every provider is selectable. One with no adapter on record for this model type is called as an OpenAI-compatible endpoint derived from its provider URL — add the model, then run the model test to see whether it answers.": "所有提供方都可以选。尚未登记此类模型适配的提供方,会按 OpenAI 兼容接口调用——端点由提供方 URL 推导。先添加模型,再运行模型测试看它能不能应答。",+ "Every provider is selectable. Search has no generic adapter, so a provider without a search API of its own is rejected by the search test — that is where a wrong pick shows up.": "所有提供方都可以选。搜索没有通用适配器,选了本身不提供搜索 API 的提供方,会被搜索测试直接判错——选错了会在那里显示出来。",+ "No adapter for this model type is on record for this provider. DeepTutor calls it as an OpenAI-compatible endpoint derived from the provider URL; run the model test below to confirm it answers.": "这个提供方尚未登记此类模型的适配。DeepTutor 会把它当作 OpenAI 兼容接口调用,端点由提供方 URL 推导;用下方的模型测试确认它能否应答。",+ "No search adapter is on record for this provider, and search has no OpenAI-compatible fallback. Run the test below — it will say so rather than search with the wrong engine.": "这个提供方尚未登记搜索适配,而搜索没有 OpenAI 兼容的兜底路径。运行下方的测试——它会直接报错,而不是拿错引擎去搜。",+ "Supported for this model type": "已适配此类模型",+ "Not on record — verify with the model test": "未登记 — 请用模型测试验证","Detected describes model modalities, not API compatibility. Provider support indicates an available integration; test a specific model to verify your account access.": "“已检测”表示模型的输入输出模态,不代表 API 兼容。“提供方支持”表示已有对应适配;请测试具体模型以验证账号访问权限。","After applying changes, lower limits take effect immediately. Raising limits needs a backend restart so larger uploads fit through the WebSocket transport.": "应用更改后,调低上限会立即生效;调高上限需要重启后端,以便 WebSocket 接收更大的上传内容。","Enter a model ID before applying changes.": "请先填写模型 ID,再应用更改。",@@ -4998,5 +5002,7 @@"{{count}} KBs": "{{count}} 个知识库","{{count}} MCP tools": "{{count}} 个 MCP 工具","{{count}} partners": "{{count}} 个伙伴",- "{{count}} skills": "{{count}} 个技能"+ "{{count}} skills": "{{count}} 个技能",+ "SVG / chart / diagram generation loop.": "SVG / 图表 / 图示生成流程。",+ "A reasoning model can spend most of this on internal reasoning; raise it if a canvas comes back empty.": "推理模型可能把其中大部分用于内部推理;如果画布返回为空,请提高该上限。"}diff --git a/web/tests/learning-dashboard.spec.tsx b/web/tests/learning-dashboard.spec.tsxindex bfc302206..46bf759f9 100644--- a/web/tests/learning-dashboard.spec.tsx+++ b/web/tests/learning-dashboard.spec.tsx@@ -56,11 +56,16 @@ vi.mock('framer-motion', async () => {return plain}const cache: Record<string, unknown> = {}+ // Both names, one proxy: the app renders inside a strict `LazyMotion`, so its+ // components import `m` rather than `motion` (#1549). A mock that exports only+ // `motion` fails the import itself, which is a mock gap, not a real crash.+ const motion = new Proxy(cache, {+ get: (store, tag: string) =>+ (store[tag] ??= (props: Record<string, unknown>) => createElement(tag, strip(props))),+ })return {- motion: new Proxy(cache, {- get: (store, tag: string) =>- (store[tag] ??= (props: Record<string, unknown>) => createElement(tag, strip(props))),- }),+ motion,+ m: motion,AnimatePresence: ({ children }: { children?: unknown }) => children,useReducedMotion: () => false,}diff --git a/web/tests/provider-registry-workflow.spec.tsx b/web/tests/provider-registry-workflow.spec.tsxindex 302d92a14..8daa76ff6 100644--- a/web/tests/provider-registry-workflow.spec.tsx+++ b/web/tests/provider-registry-workflow.spec.tsx@@ -39,6 +39,11 @@ vi.mock("react-i18next", () => ({s.replace(/{{(\w+)}}/g, (_, name) => String(args?.[name] ?? name)),}),}));+// The embedding editor mounts the knowledge-base usage panel, which fetches.+vi.mock("@/features/knowledge/api/engines", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ getEmbeddingUsage: () => Promise.resolve([]),+}));vi.mock("@/components/settings/CodexOAuthCard", () => ({CodexOAuthCard: () => <div>Codex sign-in</div>,}));@@ -105,6 +110,15 @@ function fixture(): Catalog {};return { version: 1, connections: [], services };}+/** A vendor no service table vouches for, on a connection shared across pages. */+const xai = () => ({+ id: "x",+ name: "xAI",+ provider: "xai",+ api_key: "***",+ base_url: "https://api.x.ai/v1",+ api_version: "",+});let live: Catalog;function Harness({page,@@ -241,6 +255,49 @@ it("search is a flat engine configuration without a fake context or model ID", (expect(screen.queryByLabelText("Model ID")).toBeNull();expect(screen.queryByLabelText("Context length (tokens)")).toBeNull();});+it("offers a provider with no search API and leaves the rejection to the search test", () => {+ live.connections = [xai()];+ render(<Harness page="search" />);+ fireEvent.click(+ screen.getByRole("button", { name: "Add search configuration" }),+ );+ const select = screen.getByLabelText("Configured provider");+ // Nothing says xAI runs a search API, and that is not a veto either: it is+ // offered, grouped apart, and the search test is what rejects it.+ expect(within(select).getByRole("option", { name: "xAI" })).toBeTruthy();+ fireEvent.change(select, { target: { value: "connection:x" } });+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ const profile = mocks.settings.draft.services.search.profiles.at(-1)!;+ // Staged under the vendor's own name: search has no OpenAI-compatible+ // fallback, so `custom` here would only hide which engine was meant.+ expect(profile.provider).toBe("xai");+ expect(+ screen.getByRole("region", { name: "Model connection test" }),+ ).toBeTruthy();+});+it("offers embedding providers with no adapter on record and leaves the verdict to the test", async () => {+ live.connections = [xai()];+ render(<Harness page="embedding" />);+ fireEvent.click(screen.getByRole("button", { name: "Add model" }));+ const select = screen.getByLabelText("Configured provider");+ // Nothing on the backend claims xAI serves embeddings, and that is not a+ // veto: it is offered, grouped apart, and settled by the model test.+ expect(within(select).getByRole("option", { name: "xAI" })).toBeTruthy();+ fireEvent.change(select, { target: { value: "connection:x" } });+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ const profile = mocks.settings.draft.services.embedding.profiles.at(-1)!;+ // `custom` is the OpenAI-compatible binding, whose embedding endpoint the+ // backend derives from the connection URL.+ expect(profile.models[0].provider_ref).toMatchObject({+ connection_id: "x",+ binding: "custom",+ });+ expect(+ screen.getByRole("region", { name: "Model connection test" }),+ ).toBeTruthy();+ // Let the editor's usage fetch land so its state update stays in this test.+ await waitFor(() => expect(screen.queryByText("Loading...")).toBeNull());+});it("invalidates tests on referenced key changes but keeps them after unrelated model edits", () => {const model = live.services.llm.profiles[0].models[0];model.provider_ref = {@@ -347,3 +404,30 @@ it("does not reinterpret old broad multimodal discovery as generation support",expect(screen.getByText("Voice")).toBeTruthy();expect(screen.getByText("Multimodal generation")).toBeTruthy();});+it("adds a provider over plain HTTP, where crypto.randomUUID does not exist", () => {+ // `crypto.randomUUID` is secure-context-only, so a deployment reached over+ // plain HTTP (a LAN box, a VPS without TLS) has none. Minting the connection+ // id used to throw inside the click handler, before anything was staged, so+ // "Continue" did nothing at all and left nothing on screen to explain why.+ const webCrypto = globalThis.crypto as {+ randomUUID?: typeof globalThis.crypto.randomUUID;+ };+ const original = webCrypto?.randomUUID;+ if (webCrypto) webCrypto.randomUUID = undefined;+ try {+ render(<Harness page="providers" />);+ fireEvent.click(screen.getByRole("button", { name: "Add provider" }));+ fireEvent.change(screen.getByLabelText("Provider type"), {+ target: { value: "custom" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ const staged = (mocks.settings.draft.connections ?? []).at(-1)!;+ expect(staged).toMatchObject({ provider: "custom", api_key: "" });+ expect(staged.id).toMatch(/^conn-[0-9a-f-]{36}$/);+ expect(+ screen.getByRole("region", { name: "Provider settings" }),+ ).toBeTruthy();+ } finally {+ if (webCrypto) webCrypto.randomUUID = original;+ }+});