Skip to content

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

prepare v1.3.9 release

Bingxi Zhao (Frank)72bcdd77d854
diff --git a/README.md b/README.md
index 6035513f8..549c8b6d6 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,8 @@
### 📦 Releases
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot Zulip and NVIDIA NIM support, safer thinking-model routing, `deeptutor start`, sidebar tooltips, and session-store parity.
+
> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Optional multi-user deployments with isolated user workspaces, admin grants, auth routes, and scoped runtime access.
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Thinking-model/provider fixes, visible Knowledge index history, and safer Co-Writer clear/template editing.
@@ -50,11 +52,11 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Text/code/SVG attachments, one-command Setup Tour, Markdown chat export, compact KB management UI.
-> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Document attachments (PDF/DOCX/XLSX/PPTX), reasoning thinking-block display, Soul template editor, Co-Writer save-to-notebook.
-
<details>
<summary><b>Past releases (more than 2 weeks ago)</b></summary>
+> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Document attachments (PDF/DOCX/XLSX/PPTX), reasoning thinking-block display, Soul template editor, Co-Writer save-to-notebook.
+
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — User-authored Skills system, chat input performance overhaul, TutorBot auto-start, Book Library UI, visualization fullscreen.
> **[2026.4.21]** [v1.2.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.1) — Per-stage token limits, Regenerate response across all entry points, RAG & Gemma compatibility fixes.
diff --git a/assets/README/README_AR.md b/assets/README/README_AR.md
index 70253db96..0036d6b89 100644
--- a/assets/README/README_AR.md
+++ b/assets/README/README_AR.md
@@ -28,6 +28,10 @@
### 📦 الإصدارات
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — دعم TutorBot لقناتي Zulip وNVIDIA NIM، توجيه أكثر أمانًا لنماذج التفكير، أمر `deeptutor start`، تلميحات الشريط الجانبي، وتكافؤ مخزن الجلسات.
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — نشر اختياري متعدد المستخدمين مع مساحات عمل معزولة، صلاحيات يديرها المسؤول، مسارات مصادقة، ووصول runtime محدود النطاق.
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — إصلاحات نماذج التفكير / المزودين، إظهار تاريخ فهرس المعرفة، وزيادة أمان مسح Co-Writer وتحرير القوالب.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — اختيار النماذج عبر الكتالوج في الدردشة وTutorBot، إعادة فهرسة RAG أكثر أمانًا، إصلاحات حد الرموز في OpenAI Responses، والتحقق من محرر Skills.
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — مرفقات نص / شيفرة / SVG، جولة إعداد بأمر واحد، تصدير الدردشة Markdown، واجهة إدارة KB مدمجة.
+<details>
+<summary><b>إصدارات أقدم (أكثر من أسبوعين)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — مرفقات مستندات (PDF/DOCX/XLSX/PPTX)، عرض كتلة تفكير النموذج، محرّر قوالب Soul، حفظ Co-Writer في الدفتر.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — نظام Skills من إنشاء المستخدم، تحسين أداء إدخال الدردشة، بدء تلقائي لـ TutorBot، واجهة مكتبة الكتب، تصور بملء الشاشة.
@@ -60,10 +67,6 @@
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «أجب الآن» شامل، مزامنة تمرير Co-Writer، لوحة إعدادات موحّدة، زر إيقاف أثناء البث.
-
-<details>
-<summary><b>إصدارات أقدم (أكثر من أسبوعين)</b></summary>
-
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — إعادة هيكلة تحليل صيغ LaTeX في الكتل؛ فحص تشخيص LLM عبر `agents.yaml`؛ إصلاح تمرير رؤوس HTTP إضافية؛ إصلاح UUID في SaveToNotebook؛ إرشادات Docker وLLM محلي.
> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — جلسات قابلة للإشارة عبر URL؛ سمة Snow؛ نبض WebSocket وإعادة اتصال تلقائية؛ تحسين أداء ChatComposer؛ إعادة هيكلة سجل مزوّدي التضمين؛ مزوّد بحث Serper.
diff --git a/assets/README/README_CN.md b/assets/README/README_CN.md
index 7523e8cff..76e4de54b 100644
--- a/assets/README/README_CN.md
+++ b/assets/README/README_CN.md
@@ -28,6 +28,10 @@
### 📦 版本发布
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot 支持 Zulip 与 NVIDIA NIM,思考模型路由更安全,新增 `deeptutor start`,侧栏提示与会话存储一致性提升。
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — 可选多用户部署,隔离用户工作区、管理员授权、认证路由与作用域运行时访问。
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — 思考模型/提供商修复,知识索引历史可见,Co-Writer 清空与模板编辑更安全。
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — 聊天与 TutorBot 基于目录的模型选择,更安全的 RAG 重建索引,OpenAI Responses token 上限修复,Skills 编辑器校验。
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — 文本/代码/SVG 附件,一键 Setup Tour,Markdown 聊天导出,紧凑知识库管理界面。
+<details>
+<summary><b>更早发布(两周以前)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — 文档附件(PDF/DOCX/XLSX/PPTX),推理思维块展示,Soul 模板编辑器,Co-Writer 保存至笔记本。
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — 用户自建 Skills 体系,聊天输入性能重构,TutorBot 自动启动,图书库 UI,可视化全屏。
@@ -56,9 +63,6 @@
> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine「活书」编译器,多文档 Co-Writer,交互式 HTML 可视化,题库 @ 提及。
-<details>
-<summary><b>更早发布(两周以前)</b></summary>
-
> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — 基于 Schema 的 Channels 标签页,RAG 单一流水线收敛,聊天提示外置。
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — 通用「立即回答」,Co-Writer 滚动同步,统一设置面板,流式停止按钮。
diff --git a/assets/README/README_ES.md b/assets/README/README_ES.md
index 87a39d281..b5b99444a 100644
--- a/assets/README/README_ES.md
+++ b/assets/README/README_ES.md
@@ -28,6 +28,10 @@
### 📦 Lanzamientos
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot con Zulip y NVIDIA NIM, enrutamiento más seguro para modelos de razonamiento, `deeptutor start`, tooltips laterales y paridad del almacén de sesiones.
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Despliegues multiusuario opcionales con espacios aislados, permisos de administrador, rutas de autenticación y acceso runtime acotado.
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Correcciones de modelo de razonamiento/proveedor, historial de índice de conocimiento visible, vaciado de Co-Writer y edición de plantillas más seguros.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Selección de modelos por catálogo en chat y TutorBot, reindexación RAG más segura, límites de tokens en OpenAI Responses, validación del editor de Skills.
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Adjuntos texto/código/SVG, Setup Tour en un comando, exportación Markdown del chat, UI compacta de KB.
+<details>
+<summary><b>Lanzamientos anteriores (más de 2 semanas)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Adjuntos PDF/DOCX/XLSX/PPTX, bloques de razonamiento, editor de plantillas Soul, Co-Writer guarda en cuaderno.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Skills de usuario, rendimiento del input de chat, autoarranque TutorBot, UI de biblioteca de libros, visualización a pantalla completa.
@@ -56,9 +63,6 @@
> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Compilador Book Engine «libro vivo», Co-Writer multi-documento, visualizaciones HTML, @ en banco de preguntas.
-<details>
-<summary><b>Lanzamientos anteriores (más de 2 semanas)</b></summary>
-
> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Pestaña Channels por esquema, pipeline RAG único, prompts externos.
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «Responder ahora», sincronización de scroll Co-Writer, panel de ajustes unificado, botón Detener en streaming.
diff --git a/assets/README/README_FR.md b/assets/README/README_FR.md
index b83870266..eee926b14 100644
--- a/assets/README/README_FR.md
+++ b/assets/README/README_FR.md
@@ -28,6 +28,10 @@
### 📦 Versions
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot prend en charge Zulip et NVIDIA NIM, routage plus sûr des modèles de raisonnement, `deeptutor start`, infobulles latérales et parité du stockage de sessions.
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Déploiements multi-utilisateurs optionnels avec espaces isolés, droits admin, routes d’authentification et accès runtime limité.
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Correctifs modèles de raisonnement / fournisseurs, historique d’index des connaissances visible, vidage Co-Writer et édition de modèles plus sûrs.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Sélection de modèles par catalogue (chat et TutorBot), réindexation RAG plus sûre, plafonds de tokens OpenAI Responses, validation de l’éditeur Skills.
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — PJ texte/code/SVG, Setup Tour en une commande, export Markdown du chat, UI KB compacte.
+<details>
+<summary><b>Anciennes versions (plus de 2 semaines)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — PJ documents, blocs de raisonnement, éditeur de modèles Soul, Co-Writer vers carnet.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Skills utilisateur, perf. saisie chat, démarrage auto TutorBot, UI bibliothèque, plein écran visualisation.
@@ -56,9 +63,6 @@
> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Compilateur Book Engine « livre vivant », Co-Writer multi-documents, HTML interactif, @ dans la banque de questions.
-<details>
-<summary><b>Anciennes versions (plus de 2 semaines)</b></summary>
-
> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Onglet Channels piloté par schéma, pipeline RAG unique, prompts externalisés.
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — « Répondre maintenant », sync défilement Co-Writer, panneau réglages unifié, bouton Stop streaming.
diff --git a/assets/README/README_HI.md b/assets/README/README_HI.md
index bdac53dd0..908e06bbe 100644
--- a/assets/README/README_HI.md
+++ b/assets/README/README_HI.md
@@ -28,6 +28,10 @@
### 📦 रिलीज़
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot में Zulip और NVIDIA NIM सपोर्ट, thinking-model routing अधिक सुरक्षित, `deeptutor start`, sidebar tooltips, और session-store parity।
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — वैकल्पिक multi-user deployments: isolated user workspaces, admin grants, auth routes, और scoped runtime access।
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — थिंकिंग-मॉडल/प्रोवाइडर फिक्स, विज़िबल नॉलेज इंडेक्स हिस्ट्री, और सेफर Co-Writer क्लियर/टेम्पलेट एडिटिंग।
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — चैट और TutorBot के लिए कैटलॉग-बेस्ड मॉडल सिलेक्शन, सेफर RAG री-इंडेक्सिंग, OpenAI Responses टोकन-लिमिट फिक्स, और Skills एडिटर वैलिडेशन।
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — टेक्स्ट / कोड / SVG संलग्नक, एक-कमांड सेटअप टूर, Markdown चैट निर्यात, कॉम्पैक्ट KB प्रबंधन UI।
+<details>
+<summary><b>पुराने रिलीज़ (2 सप्ताह से अधिक पहले)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — दस्तावेज़ संलग्नक (PDF/DOCX/XLSX/PPTX), तर्क मॉडल सोच-ब्लॉक, Soul टेम्पलेट संपादक, Co-Writer से नोटबुक सहेजें।
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — उपयोगकर्ता-लिखित Skills, चैट इनपुट प्रदर्शन ओवरहॉल, TutorBot ऑटो-स्टार्ट, बुक लाइब्रेरी UI, विज़ुअलाइज़ेशन फ़ुलस्क्रीन।
@@ -60,10 +67,6 @@
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — सार्वभौमिक «अभी उत्तर दें», Co-Writer स्क्रॉल सिंक, एकीकृत सेटिंग्स पैनल, स्ट्रीमिंग Stop बटन।
-
-<details>
-<summary><b>पुराने रिलीज़ (2 सप्ताह से अधिक पहले)</b></summary>
-
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX ब्लॉक गणित पार्सिंग ओवरहॉल; `agents.yaml` के माध्यम से LLM डायग्नोस्टिक प्रोब; अतिरिक्त हेडर फॉरवर्डिंग फिक्स; SaveToNotebook UUID फिक्स; Docker + स्थानीय LLM मार्गदर्शिका।
> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — URL-आधारित बुकमार्क योग्य सत्र; Snow थीम; WebSocket हार्टबीट व ऑटो-रीकनेक्ट; ChatComposer प्रदर्शन सुधार; एम्बेडिंग प्रदाता रजिस्ट्री ओवरहॉल; Serper खोज प्रदाता।
diff --git a/assets/README/README_JA.md b/assets/README/README_JA.md
index f09125a76..4a4d3dc61 100644
--- a/assets/README/README_JA.md
+++ b/assets/README/README_JA.md
@@ -28,6 +28,10 @@
### 📦 リリース
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot の Zulip/NVIDIA NIM 対応、思考モデルルーティングの安全化、`deeptutor start`、サイドバーツールチップ、セッションストア整合性。
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — 任意のマルチユーザー展開、分離されたユーザーワークスペース、管理者権限付与、認証ルート、スコープ付き実行時アクセス。
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — 思考モデル/プロバイダー修正、ナレッジインデックス履歴の表示、Co-Writer のクリア・テンプレート編集の安全性向上。
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — チャットと TutorBot のカタログベースモデル選択、RAG 再インデックスの安全性向上、OpenAI Responses トークン上限修正、Skills エディター検証。
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — テキスト/コード/SVG 添付ファイル、一コマンド Setup Tour、Markdown チャットエクスポート、コンパクトな KB 管理 UI。
+<details>
+<summary><b>過去のリリース(2週間以上前)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — ドキュメント添付ファイル(PDF/DOCX/XLSX/PPTX)、推論思考ブロック表示、Soul テンプレートエディター、Co-Writer からノートブックへの保存。
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — ユーザー作成 Skills システム、チャット入力パフォーマンス改善、TutorBot 自動起動、書籍ライブラリ UI、ビジュアライゼーション全画面表示。
@@ -56,9 +63,6 @@
> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine「生きた本」コンパイラー、マルチドキュメント Co-Writer、インタラクティブ HTML ビジュアライゼーション、質問バンク @-メンション。
-<details>
-<summary><b>過去のリリース(2週間以上前)</b></summary>
-
> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — スキーマ駆動の Channels タブ、RAG 単一パイプライン統合、チャットプロンプトの外部化。
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — ユニバーサル「今すぐ回答」、Co-Writer スクロール同期、統一設定パネル、ストリーミング停止ボタン。
diff --git a/assets/README/README_PL.md b/assets/README/README_PL.md
index 0328535f5..e49ce0046 100644
--- a/assets/README/README_PL.md
+++ b/assets/README/README_PL.md
@@ -28,6 +28,10 @@
### 📦 Wydania
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot obsługuje Zulip i NVIDIA NIM, bezpieczniejszy routing modeli rozumujących, `deeptutor start`, podpowiedzi w pasku bocznym i parytet magazynu sesji.
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Opcjonalne wdrożenia multi-user z izolowanymi workspace’ami, uprawnieniami admina, trasami auth i scoped runtime access.
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Poprawki modeli rozumujących/dostawców, widoczna historia indeksu wiedzy, bezpieczniejsze czyszczenie Co-Writer i edycja szablonów.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Wybór modeli z katalogu w czacie i TutorBot, bezpieczniejsza ponowna indeksacja RAG, poprawki limitu tokenów OpenAI Responses, walidacja edytora Skills.
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Załączniki tekst / kod / SVG, konfiguracja jednym poleceniem, eksport czatu Markdown, zwarty interfejs zarządzania KB.
+<details>
+<summary><b>Starsze wydania (ponad 2 tygodnie temu)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Załączniki dokumentów (PDF/DOCX/XLSX/PPTX), blok rozumowania modelu, edytor szablonów Soul, zapis z Co-Writer do notesu.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — System Skills tworzonych przez użytkownika, optymalizacja wydajności wpisywania w czacie, autostart TutorBot, UI biblioteki książek, wizualizacje pełnoekranowe.
@@ -56,9 +63,6 @@
> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Kompilator Book Engine „żywych książek", Co-Writer wielodokumentowy, interaktywne wizualizacje HTML, @-wzmianki banku pytań na czacie.
-<details>
-<summary><b>Starsze wydania (ponad 2 tygodnie temu)</b></summary>
-
> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Zakładka Channels oparta na schemacie, konsolidacja RAG w jednym potoku, zewnętrzne prompty czatu.
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Uniwersalne „Odpowiedz teraz", synchronizacja przewijania Co-Writer, zunifikowany panel ustawień, przycisk Stop przy strumieniowaniu.
diff --git a/assets/README/README_PT.md b/assets/README/README_PT.md
index a34888b6b..9ceab420e 100644
--- a/assets/README/README_PT.md
+++ b/assets/README/README_PT.md
@@ -28,6 +28,10 @@
### 📦 Lançamentos
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot com Zulip e NVIDIA NIM, roteamento mais seguro para modelos de raciocínio, `deeptutor start`, tooltips na barra lateral e paridade do store de sessões.
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Deploys multiusuário opcionais com workspaces isolados, concessões de admin, rotas de autenticação e acesso runtime com escopo.
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Correções de modelos de raciocínio/provedores, histórico de índice de conhecimento visível e edição de templates e limpeza do Co-Writer mais seguros.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Seleção de modelos por catálogo no chat e TutorBot, reindexação RAG mais segura, correções de limite de tokens do OpenAI Responses e validação do editor Skills.
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Anexos de texto / código / SVG, tour de configuração em um comando, exportação do chat Markdown, UI compacta de gestão de KB.
+<details>
+<summary><b>Lançamentos anteriores (há mais de 2 semanas)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Anexos de documentos (PDF/DOCX/XLSX/PPTX), exibição do bloco de raciocínio, editor de modelos Soul, salvar no caderno a partir do Co-Writer.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Skills criados pelo usuário, melhoria de desempenho do input de chat, início automático do TutorBot, UI da biblioteca de livros, visualização em tela cheia.
@@ -60,10 +67,6 @@
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — «Responder agora» universal, sincronização de rolagem no Co-Writer, painel de configurações unificado, botão Stop em streaming.
-
-<details>
-<summary><b>Lançamentos anteriores (há mais de 2 semanas)</b></summary>
-
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — Reformulação do parsing de LaTeX em bloco; sonda de diagnóstico LLM via `agents.yaml`; correção do encaminhamento de cabeçalhos extras; correção de UUID no SaveToNotebook; guia Docker + LLM local.
> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — Sessões com URL marcável; tema Snow; heartbeat WebSocket e reconexão automática; desempenho do ChatComposer; reformulação do registro de provedores de embeddings; provedor de busca Serper.
diff --git a/assets/README/README_RU.md b/assets/README/README_RU.md
index 6a7a2fd60..60445c853 100644
--- a/assets/README/README_RU.md
+++ b/assets/README/README_RU.md
@@ -28,6 +28,10 @@
### 📦 Релизы
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot получил Zulip и NVIDIA NIM, более безопасный роутинг thinking-моделей, `deeptutor start`, подсказки сайдбара и паритет хранилищ сессий.
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — Опциональные multi-user развёртывания с изолированными рабочими пространствами, admin grants, auth routes и scoped runtime access.
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — Исправления для thinking-моделей/провайдеров, видимая история индекса знаний, более безопасные очистка Co-Writer и редактирование шаблонов.
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Выбор моделей через каталог в чате и TutorBot, более безопасная переиндексация RAG, исправления лимита токенов OpenAI Responses, валидация редактора Skills.
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — Вложения текста / кода / SVG, тур настройки одной командой, экспорт чата в Markdown, компактный UI управления KB.
+<details>
+<summary><b>Прошлые релизы (более 2 недель назад)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — Вложения документов (PDF/DOCX/XLSX/PPTX), блок размышлений модели рассуждений, редактор шаблонов Soul, сохранение из Co-Writer в блокнот.
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — Пользовательские Skills, оптимизация ввода в чате, авто-старт TutorBot, UI библиотеки книг, полноэкранные визуализации.
@@ -60,10 +67,6 @@
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Универсальный «Ответить сейчас», синхронизация прокрутки Co-Writer, единая панель настроек, кнопка Stop при стриминге.
-
-<details>
-<summary><b>Прошлые релизы (более 2 недель назад)</b></summary>
-
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — переработка разбора блочных формул LaTeX; LLM-диагностика через `agents.yaml`; исправление пересылки дополнительных заголовков; исправление UUID в SaveToNotebook; руководство по Docker и локальным LLM.
> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — сессии с URL-закладками; тема Snow; heartbeat WebSocket и авто-переподключение; ускорение ChatComposer; переработка реестра провайдеров эмбеддингов; провайдер поиска Serper.
diff --git a/assets/README/README_TH.md b/assets/README/README_TH.md
index 20f5d6ec1..b60217a7c 100644
--- a/assets/README/README_TH.md
+++ b/assets/README/README_TH.md
@@ -28,6 +28,10 @@
### 📦 ประวัติการเผยแพร่
+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot รองรับ Zulip และ NVIDIA NIM, routing ของ thinking-model ปลอดภัยขึ้น, `deeptutor start`, tooltip ใน sidebar, และ session-store parity
+
+> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — deployment แบบ multi-user ที่เปิดได้ตามต้องการ พร้อม workspace แยกผู้ใช้, admin grants, auth routes, และ scoped runtime access
+
> **[2026.5.4]** [v1.3.7](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.7) — แก้ไข thinking-model/provider, แสดงประวัติ Knowledge index, และ Co-Writer clear/template editing ปลอดภัยขึ้น
> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — เลือกโมเดลจากคาตาล็อกสำหรับแชตและ TutorBot, RAG re-indexing ปลอดภัยขึ้น, แก้ token-limit ของ OpenAI Responses, และตรวจสอบ Skills editor
@@ -48,6 +52,9 @@
> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — แนบข้อความ / โค้ด / SVG, Setup Tour คำสั่งเดียว, ส่งออกแชต Markdown, UI จัดการ KB แบบกะทัดรัด
+<details>
+<summary><b>รุ่นที่ผ่านมา (มากกว่า 2 สัปดาห์ที่แล้ว)</b></summary>
+
> **[2026.4.24]** [v1.2.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.3) — แนบเอกสาร (PDF/DOCX/XLSX/PPTX), แสดงบล็อกการคิดของโมเดลให้เหตุผล, ตัวแก้เทมเพลต Soul, บันทึก Co-Writer ลงสมุด
> **[2026.4.22]** [v1.2.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.2) — ระบบ Skills ที่ผู้ใช้สร้าง, ปรับประสิทธิ์อินพุตแชต, TutorBot สตาร์ทอัตโนมัติ, UI ห้องสมุดหนังสือ, โหมดเต็มจอของการแสดงผล
@@ -60,10 +67,6 @@
> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — ปุ่ม "ตอบเลย" ครอบคลุมทุกความสามารถ, Co-Writer scroll sync, แผงตั้งค่ารวม, ปุ่ม Stop ระหว่างสตรีม
-
-<details>
-<summary><b>รุ่นที่ผ่านมา (มากกว่า 2 สัปดาห์ที่แล้ว)</b></summary>
-
> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — ปรับปรุงการ parse LaTeX block math, ตั้งค่า LLM probe ผ่าน agents.yaml, forward extra headers ใน LLM factory, แก้ UUID ของ SaveToNotebookModal, คำแนะนำ Docker + local LLM และขยาย test suite
> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — URL-based chat routing พร้อม bookmark ได้, ธีม Snow, WebSocket heartbeat & auto-reconnect พร้อม resume, ปรับ ChatComposer ให้เร็วขึ้น, overhaul embedding provider registry, Serper search provider, streaming idle timeout และขยาย test suite
diff --git a/assets/releases/ver1-3-9.md b/assets/releases/ver1-3-9.md
new file mode 100644
index 000000000..8fe5915b2
--- /dev/null
+++ b/assets/releases/ver1-3-9.md
@@ -0,0 +1,95 @@
+# DeepTutor v1.3.9 Release Notes
+
+**Release Date:** 2026.05.09
+
+v1.3.9 builds on the v1.3.8 multi-user foundation with broader TutorBot
+deployment options, safer provider routing for thinking models, and a smoother
+web onboarding path. It adds Zulip and NVIDIA NIM support, improves startup
+ergonomics, and folds in the main issue fixes reported after the last release.
+
+## Highlights
+
+### TutorBot Channel and Provider Expansion
+
+- **Zulip is now a TutorBot channel** - bots can listen to private messages and
+ stream topics, enforce `allow_from`, choose mention-only or open stream
+ replies, and bridge Zulip's event queue into the async TutorBot bus.
+- **Math and files work better in Zulip** - LaTeX is converted to Zulip-friendly
+ KaTeX markup, upload/download calls use configurable retry behavior, and
+ attachment filenames include upload-path digests to avoid collisions.
+- **Zulip topics keep conversations separated** - stream topics now become part
+ of the chat/session key, with a stable `(no topic)` fallback for empty topics.
+- **TutorBot supports NVIDIA NIM** - `nvidia_nim` is available in TutorBot
+ provider config and registry detection, including NIM's streaming behavior
+ that omits unsupported `stream_options`.
+
+### Model and Runtime Reliability
+
+- **Configured context windows are respected** - the safety ceiling is raised to
+ 1,000,000 tokens while the large-model fallback remains 65,536, so explicit
+ 128K-style model settings are no longer silently clamped.
+- **Qwen vision detection is fixed** - Qwen VL models are treated as
+ vision-capable across DashScope, OpenAI-compatible, and custom bindings.
+- **Minimal thinking mode is provider-safe** - DeepSeek, DashScope, VolcEngine,
+ BytePlus, and MiniMax no longer receive a rejected top-level
+ `reasoning_effort=minimal`; DeepTutor sends the provider-specific disable
+ signal instead.
+- **DeepSeek v4 costs are tracked** - research token accounting includes
+ `deepseek-v4-flash` and `deepseek-v4-pro` pricing entries.
+
+### Web and CLI Polish
+
+- **`deeptutor start` launches the full web stack** - the CLI now delegates to
+ `scripts/start_web.py` so backend and frontend can be started from one
+ command, and launcher failures propagate through the CLI exit code.
+- **Sidebar onboarding is clearer** - primary navigation icons now expose
+ scoped, localized tooltips with descriptions and keyboard focus support.
+- **Multi-line user messages stay readable** - chat message rendering preserves
+ Shift+Enter line breaks, fixing code blocks and structured prompts that were
+ previously collapsed into one line.
+- **Assigned resources are easier to understand** - model-selection summaries
+ and read-only knowledge-base actions now present clearer labels for
+ non-admin, grant-scoped sessions.
+
+### Multi-User and Session Store Parity
+
+- **Assigned model options match the selector contract** - non-admin LLM choices
+ now return profile names, model names, labels, and active/default metadata in
+ the same shape expected by the web model selector.
+- **PocketBase sessions support more chat flows** - message metadata can be
+ persisted, last-message lookup is available, and message deletion works with
+ PocketBase string IDs as well as SQLite integer IDs.
+- **Regenerate remains storage-neutral** - turn retry logic can remove the last
+ assistant message without assuming the backing session store uses integer
+ primary keys.
+
+## Tests
+
+- Added Zulip channel coverage for config parsing, permission checks, duplicate
+ filtering, mentions, stream topic scoping, attachment extraction, retry
+ behavior, LaTeX conversion, typing status, sending, uploads, and startup
+ failures.
+- Added TutorBot NVIDIA NIM provider tests for registry detection, schema
+ acceptance, and streaming request compatibility.
+- Added LLM regression tests for Qwen vision capability, explicit context-window
+ budgets, and minimal-thinking provider kwargs.
+- Added CLI coverage so `deeptutor start` propagates the launcher exit code.
+- Added research token-pricing coverage for the DeepSeek v4 model entries.
+
+## Upgrade Notes
+
+- Install or refresh the `.[tutorbot]` extra, or `requirements/tutorbot.txt`, to
+ include the new `zulip>=0.8.0,<1.0.0` dependency before enabling Zulip bots.
+- Configure Zulip bots with `site`, `email`, `apiKey`, `allowFrom`, and
+ `groupPolicy`; use `mention` for safer stream deployments and `open` only
+ when every stream message should reach the bot.
+- If you use `LLM_REASONING_EFFORT=minimal` with DeepSeek, DashScope,
+ VolcEngine, BytePlus, or MiniMax, keep the setting as-is; v1.3.9 translates it
+ to the correct provider-specific disable payload.
+- Large configured context windows may now be honored instead of capped at
+ 65,536 tokens, so verify provider limits and expected prompt-cost behavior.
+- Optional PocketBase deployments should ensure the `messages` collection has a
+ `metadata_json` JSON field before relying on regenerate/session metadata
+ parity.
+
+**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.8...v1.3.9
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index bc4a6a4e7..fa400597b 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -36,18 +36,20 @@ from deeptutor.knowledge.initializer import KnowledgeBaseInitializer
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.knowledge.naming import validate_knowledge_base_name
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
-from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
-from deeptutor.services.rag.factory import DEFAULT_PROVIDER
-from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.multi_user.context import get_current_user
from deeptutor.multi_user.knowledge_access import (
assert_writable,
current_kb_base_dir,
current_kb_manager,
- list_visible_knowledge_bases as list_visible_kb_access,
manager_for_resource,
resolve_kb,
)
+from deeptutor.multi_user.knowledge_access import (
+ list_visible_knowledge_bases as list_visible_kb_access,
+)
+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
+from deeptutor.services.rag.factory import DEFAULT_PROVIDER
+from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.utils.document_validator import DocumentValidator
from deeptutor.utils.error_utils import format_exception_message
@@ -780,9 +782,9 @@ async def list_knowledge_bases():
source="admin" if get_current_user().is_admin else "user",
assigned=False,
read_only=False,
- provenance_label=access_by_id.get(
- f"{own_prefix}{info['name']}", {}
- ).get("provenance_label"),
+ provenance_label=access_by_id.get(f"{own_prefix}{info['name']}", {}).get(
+ "provenance_label"
+ ),
)
)
except Exception as e:
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index b8c3f2955..c92e1de60 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -19,17 +19,18 @@ from pydantic import BaseModel
logger = logging.getLogger(__name__)
+from deeptutor.multi_user.context import get_current_user
+from deeptutor.multi_user.model_access import allowed_llm_options, redacted_model_access
from deeptutor.services.config import get_config_test_runner, get_model_catalog_service
from deeptutor.services.embedding.client import reset_embedding_client
from deeptutor.services.llm.client import reset_llm_client
from deeptutor.services.llm.config import clear_llm_config_cache
from deeptutor.services.model_selection import list_llm_options
from deeptutor.services.path_service import get_path_service
-from deeptutor.multi_user.context import get_current_user
-from deeptutor.multi_user.model_access import allowed_llm_options, redacted_model_access
router = APIRouter()
+
def _settings_file():
return get_path_service().get_settings_file("interface")
@@ -37,6 +38,7 @@ def _settings_file():
def _tour_cache_file():
return get_path_service().get_settings_dir() / ".tour_cache.json"
+
DEFAULT_SIDEBAR_NAV_ORDER = {
"start": ["/", "/history", "/knowledge", "/notebook"],
"learnResearch": ["/question", "/solver", "/research", "/co_writer"],
diff --git a/deeptutor/api/routers/skills.py b/deeptutor/api/routers/skills.py
index 042e3d7b8..77c672cc9 100644
--- a/deeptutor/api/routers/skills.py
+++ b/deeptutor/api/routers/skills.py
@@ -15,7 +15,6 @@ from pydantic import BaseModel, Field
from deeptutor.multi_user.context import get_current_user
from deeptutor.multi_user.skill_access import (
- assert_skill_allowed,
assigned_skill_detail,
assigned_skill_ids,
assigned_skill_infos,
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index 750e85989..8827af415 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -40,8 +40,11 @@ async def unified_websocket(ws: WebSocket) -> None:
# Token is read from the ?token= query param (WebSocket headers can't
# carry cookies cross-origin in all browsers).
# Uses the same local jwt.decode() path — no network call.
- from deeptutor.multi_user.context import reset_current_user, set_current_user
- from deeptutor.multi_user.context import user_from_token_payload
+ from deeptutor.multi_user.context import (
+ reset_current_user,
+ set_current_user,
+ user_from_token_payload,
+ )
from deeptutor.multi_user.paths import local_admin_user
from deeptutor.services.auth import AUTH_ENABLED, decode_token
diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.py
index 6d3c3a53c..a48dac499 100644
--- a/deeptutor/multi_user/identity.py
+++ b/deeptutor/multi_user/identity.py
@@ -121,7 +121,7 @@ def _migrate_secret() -> None:
logger.warning("Failed to migrate legacy auth secret: %s", exc)
-def load_users(
+def load_users( # nosec B107 - empty defaults mean "no env fallback supplied".
env_username: str = "",
env_password_hash: str = "",
) -> dict[str, dict[str, Any]]:
@@ -188,7 +188,10 @@ def save_user(username: str, hashed_password: str, role: Role = "user") -> dict[
return record
-def list_user_info(env_username: str = "", env_password_hash: str = "") -> list[dict[str, Any]]:
+def list_user_info( # nosec B107 - empty defaults mean "no env fallback supplied".
+ env_username: str = "",
+ env_password_hash: str = "",
+) -> list[dict[str, Any]]:
return [
{
"id": record.get("id", ""),
diff --git a/deeptutor/multi_user/knowledge_access.py b/deeptutor/multi_user/knowledge_access.py
index 603faa0c4..05514c987 100644
--- a/deeptutor/multi_user/knowledge_access.py
+++ b/deeptutor/multi_user/knowledge_access.py
@@ -92,7 +92,9 @@ def resolve_kb(kb_ref: str, *, require_write: bool = False) -> KnowledgeResource
if name not in assigned_names:
raise HTTPException(status_code=403, detail="Knowledge base is not assigned to you")
if require_write:
- raise HTTPException(status_code=403, detail="Assigned admin knowledge bases are read-only")
+ raise HTTPException(
+ status_code=403, detail="Assigned admin knowledge bases are read-only"
+ )
return KnowledgeResource(
id=f"admin:kb:{name}",
name=name,
@@ -137,7 +139,9 @@ def resolve_kb(kb_ref: str, *, require_write: bool = False) -> KnowledgeResource
if name in assigned_names:
if require_write:
- raise HTTPException(status_code=403, detail="Assigned admin knowledge bases are read-only")
+ raise HTTPException(
+ status_code=403, detail="Assigned admin knowledge bases are read-only"
+ )
return KnowledgeResource(
id=f"admin:kb:{name}",
name=name,
diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.py
index ed884b6d4..084f2a3bf 100644
--- a/deeptutor/multi_user/model_access.py
+++ b/deeptutor/multi_user/model_access.py
@@ -85,21 +85,26 @@ def redacted_model_access(user_id: str | None = None) -> dict[str, list[dict[str
return result
-def allowed_llm_options() -> list[dict[str, Any]]:
+def allowed_llm_options() -> dict[str, Any]:
user = get_current_user()
if user.is_admin:
return list_llm_options(admin_catalog())
- return [
+ options = [
{
"profile_id": item.get("profile_id"),
"model_id": item.get("model_id"),
+ "profile_name": item.get("name") or item.get("profile_id") or "LLM",
+ "model_name": item.get("name") or item.get("model") or item.get("model_id"),
"label": item.get("name") or item.get("model") or item.get("model_id"),
"model": item.get("model") or "",
+ "provider": "",
"source": "admin",
+ "is_active_default": False,
}
for item in redacted_model_access(user.id).get("llm", [])
if item.get("available")
]
+ return {"active": None, "options": options}
def apply_allowed_llm_selection(selection: dict[str, Any] | None) -> dict[str, Any] | None:
diff --git a/deeptutor/multi_user/paths.py b/deeptutor/multi_user/paths.py
index ba7c19781..6df323607 100644
--- a/deeptutor/multi_user/paths.py
+++ b/deeptutor/multi_user/paths.py
@@ -8,7 +8,7 @@ from typing import Iterator
from deeptutor.services.path_service import PathService
-from .models import CurrentUser, LOCAL_ADMIN_ID, LOCAL_ADMIN_USERNAME, UserScope
+from .models import LOCAL_ADMIN_ID, LOCAL_ADMIN_USERNAME, CurrentUser, UserScope
PROJECT_ROOT = Path(__file__).resolve().parents[2]
ADMIN_WORKSPACE_ROOT = PROJECT_ROOT / "data"
diff --git a/deeptutor/multi_user/router.py b/deeptutor/multi_user/router.py
index dfc0fa7c8..4e1d22aec 100644
--- a/deeptutor/multi_user/router.py
+++ b/deeptutor/multi_user/router.py
@@ -21,7 +21,7 @@ from .grants import load_grant, save_grant
from .identity import get_user_by_id, list_user_info
from .knowledge_access import admin_kb_base_dir, list_visible_knowledge_bases
from .model_access import redacted_model_access
-from .paths import MULTI_USER_ROOT, get_admin_path_service, get_current_path_service
+from .paths import MULTI_USER_ROOT, get_admin_path_service
from .skill_access import assigned_skill_ids
router = APIRouter()
diff --git a/deeptutor/services/config/knowledge_base_config.py b/deeptutor/services/config/knowledge_base_config.py
index 2f406cb54..d29660933 100644
--- a/deeptutor/services/config/knowledge_base_config.py
+++ b/deeptutor/services/config/knowledge_base_config.py
@@ -37,7 +37,9 @@ class KnowledgeBaseConfigService:
@classmethod
def get_instance(cls, config_path: Path | None = None) -> "KnowledgeBaseConfigService":
- resolved = (config_path or get_path_service().get_knowledge_bases_root() / "kb_config.json").resolve()
+ resolved = (
+ config_path or get_path_service().get_knowledge_bases_root() / "kb_config.json"
+ ).resolve()
key = str(resolved)
if key not in cls._instances:
cls._instances[key] = cls(resolved)
diff --git a/deeptutor/services/llm/cloud_provider.py b/deeptutor/services/llm/cloud_provider.py
index 4a3eaaa7d..92b21e47c 100644
--- a/deeptutor/services/llm/cloud_provider.py
+++ b/deeptutor/services/llm/cloud_provider.py
@@ -86,15 +86,17 @@ _ssl_warning_logged = False
# Providers that handle thinking mode through extra_body (rather than
# top-level reasoning_effort). "minimal" means disable thinking — these
# providers reject the literal "minimal" value and expect extra_body instead.
-_BINDINGS_WITH_EXTRA_BODY_THINKING = frozenset({
- "deepseek",
- "dashscope",
- "volcengine",
- "volcengine_coding_plan",
- "byteplus",
- "byteplus_coding_plan",
- "minimax",
-})
+_BINDINGS_WITH_EXTRA_BODY_THINKING = frozenset(
+ {
+ "deepseek",
+ "dashscope",
+ "volcengine",
+ "volcengine_coding_plan",
+ "byteplus",
+ "byteplus_coding_plan",
+ "minimax",
+ }
+)
def _looks_like_unsupported_response_format(error_text: str) -> bool:
@@ -343,8 +345,7 @@ async def _openai_complete(
if isinstance(reasoning_effort, str) and reasoning_effort.strip():
effort = reasoning_effort.strip()
if not (
- effort.lower() == "minimal"
- and binding.lower() in _BINDINGS_WITH_EXTRA_BODY_THINKING
+ effort.lower() == "minimal" and binding.lower() in _BINDINGS_WITH_EXTRA_BODY_THINKING
):
data["reasoning_effort"] = effort
@@ -513,8 +514,7 @@ async def _openai_stream(
if isinstance(reasoning_effort, str) and reasoning_effort.strip():
effort = reasoning_effort.strip()
if not (
- effort.lower() == "minimal"
- and binding.lower() in _BINDINGS_WITH_EXTRA_BODY_THINKING
+ effort.lower() == "minimal" and binding.lower() in _BINDINGS_WITH_EXTRA_BODY_THINKING
):
data["reasoning_effort"] = effort
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index fe1b703fd..b684a6fff 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -311,9 +311,7 @@ class OpenAICompatProvider(LLMProvider):
# Providers with thinking_style handle thinking via extra_body.
# "minimal" means disable thinking — only send via extra_body, never
# as a top-level reasoning_effort (e.g. DeepSeek rejects it).
- if wire_effort and not (
- spec and spec.thinking_style and semantic_effort == "minimal"
- ):
+ if wire_effort and not (spec and spec.thinking_style and semantic_effort == "minimal"):
kwargs["reasoning_effort"] = wire_effort
if spec and spec.thinking_style and reasoning_effort is not None:
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index a8a6eb547..60f4896e7 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -273,25 +273,22 @@ class PocketBaseSessionStore:
capability: str = "",
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
+ metadata: dict[str, Any] | None = None,
) -> int:
now = time.time()
def _add():
- record = (
- _pb()
- .collection("messages")
- .create(
- {
- "session_id": session_id,
- "role": role,
- "content": content or "",
- "capability": capability or "",
- "events_json": events or [],
- "attachments_json": attachments or [],
- "msg_created_at": now,
- }
- )
- )
+ payload = {
+ "session_id": session_id,
+ "role": role,
+ "content": content or "",
+ "capability": capability or "",
+ "events_json": events or [],
+ "attachments_json": attachments or [],
+ "metadata_json": metadata or {},
+ "msg_created_at": now,
+ }
+ record = _pb().collection("messages").create(payload)
# Update session title if still default
sessions = (
_pb()
@@ -313,6 +310,45 @@ class PocketBaseSessionStore:
logger.warning(f"add_message failed: {exc}")
return 0
+ async def delete_message(self, message_id: int | str) -> bool:
+ def _delete():
+ _pb().collection("messages").delete(str(message_id))
+ return True
+
+ try:
+ return await asyncio.to_thread(_delete)
+ except Exception as exc:
+ logger.warning(f"delete_message failed: {exc}")
+ return False
+
+ async def get_last_message(
+ self, session_id: str, role: str | None = None
+ ) -> dict[str, Any] | None:
+ filter_str = f'session_id="{session_id}"'
+ if role:
+ filter_str += f' && role="{role}"'
+
+ def _get():
+ records = (
+ _pb()
+ .collection("messages")
+ .get_full_list(
+ query_params={
+ "filter": filter_str,
+ "sort": "-msg_created_at",
+ "perPage": 1,
+ }
+ )
+ )
+ return records[0] if records else None
+
+ try:
+ record = await asyncio.to_thread(_get)
+ return self._message_record_to_dict(record) if record is not None else None
+ except Exception as exc:
+ logger.warning(f"get_last_message failed: {exc}")
+ return None
+
async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
def _get():
return (
@@ -350,6 +386,7 @@ class PocketBaseSessionStore:
"capability": getattr(record, "capability", "") or "",
"events": _json_loads(getattr(record, "events_json", None), []),
"attachments": _json_loads(getattr(record, "attachments_json", None), []),
+ "metadata": _json_loads(getattr(record, "metadata_json", None), {}),
"created_at": _to_float(getattr(record, "msg_created_at", None)),
}
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index e4765903b..0746d67d0 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -48,8 +48,15 @@ class SessionStoreProtocol(Protocol):
capability: str = "",
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
+ metadata: dict[str, Any] | None = None,
) -> int: ...
+ async def delete_message(self, message_id: int | str) -> bool: ...
+
+ async def get_last_message(
+ self, session_id: str, role: str | None = None
+ ) -> dict[str, Any] | None: ...
+
async def get_messages(self, session_id: str) -> list[dict[str, Any]]: ...
async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]: ...
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index b62e14252..c18682a9d 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -614,13 +614,13 @@ class SQLiteSessionStore:
metadata,
)
- def _delete_message_sync(self, message_id: int) -> bool:
+ def _delete_message_sync(self, message_id: int | str) -> bool:
with self._connect() as conn:
cur = conn.execute("DELETE FROM messages WHERE id = ?", (int(message_id),))
conn.commit()
return cur.rowcount > 0
- async def delete_message(self, message_id: int) -> bool:
+ async def delete_message(self, message_id: int | str) -> bool:
return await self._run(self._delete_message_sync, message_id)
def _get_last_message_sync(
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index ce57789f7..b703bd657 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -516,7 +516,7 @@ class TurnRuntimeManager:
if turn_id:
previous_turn_id = turn_id
break
- await self.store.delete_message(int(last_message["id"]))
+ await self.store.delete_message(last_message["id"])
preferences = session.get("preferences") or {}
overrides = overrides or {}
@@ -860,9 +860,7 @@ class TurnRuntimeManager:
s for s in auto_pool if s in allowed_skills or s in user_owned
]
else:
- explicit = [
- s for s in requested_skills if isinstance(s, str) and s != "auto"
- ]
+ explicit = [s for s in requested_skills if isinstance(s, str) and s != "auto"]
resolved_skills = [
s for s in explicit if s in allowed_skills or s in user_owned
]
diff --git a/deeptutor/tutorbot/channels/zulip.py b/deeptutor/tutorbot/channels/zulip.py
index b53f51709..686ecea24 100644
--- a/deeptutor/tutorbot/channels/zulip.py
+++ b/deeptutor/tutorbot/channels/zulip.py
@@ -3,17 +3,18 @@
from __future__ import annotations
import asyncio
+from collections import deque
+import hashlib
+from pathlib import Path
import re
import threading
import time
-from collections import deque
-from pathlib import Path
from typing import Any, Literal
from urllib.parse import unquote
-import requests
from loguru import logger
from pydantic import Field
+import requests
from deeptutor.tutorbot.bus.events import OutboundMessage
from deeptutor.tutorbot.bus.queue import MessageBus
@@ -304,13 +305,15 @@ class ZulipChannel(BaseChannel):
stream_name = display_recipient.get("name", str(display_recipient))
else:
stream_name = str(display_recipient)
- chat_id = f"stream:{stream_name}"
+ topic = self._topic_label(subject)
+ chat_id = self._stream_chat_id(stream_name, topic)
if self.config.group_policy == "mention":
if not self._is_mentioned(message):
return
- content = f"**[{stream_name} > {subject}]** {content}"
+ content = f"**[{stream_name} > {topic}]** {content}"
elif msg_type == "private":
chat_id = f"pm:{sender_id}"
+ topic = ""
else:
return
@@ -328,7 +331,7 @@ class ZulipChannel(BaseChannel):
metadata["stream"] = display_recipient.get("name", str(display_recipient))
else:
metadata["stream"] = display_recipient
- metadata["topic"] = subject
+ metadata["topic"] = topic
else:
metadata["recipient_user_id"] = sender_id
@@ -337,9 +340,7 @@ class ZulipChannel(BaseChannel):
media_paths = self._download_attachments(message)
if self._loop and not self._loop.is_closed():
- asyncio.run_coroutine_threadsafe(
- self._start_typing_async(chat_id), self._loop
- )
+ asyncio.run_coroutine_threadsafe(self._start_typing_async(chat_id), self._loop)
asyncio.run_coroutine_threadsafe(
self._handle_message(
sender_id=composite_sender,
@@ -347,10 +348,25 @@ class ZulipChannel(BaseChannel):
content=content,
media=media_paths,
metadata=metadata,
+ session_key=self._session_key_for(chat_id),
),
self._loop,
)
+ @staticmethod
+ def _topic_label(subject: Any) -> str:
+ topic = str(subject or "").strip()
+ return topic or "(no topic)"
+
+ @classmethod
+ def _stream_chat_id(cls, stream_name: str, topic: str) -> str:
+ return f"stream:{stream_name}:{cls._topic_label(topic)}"
+
+ def _session_key_for(self, chat_id: str) -> str | None:
+ if chat_id.startswith("stream:"):
+ return f"{self.name}:{chat_id}"
+ return None
+
def _is_mentioned(self, message: dict) -> bool:
if self._bot_user_id is None:
return False
@@ -371,9 +387,8 @@ class ZulipChannel(BaseChannel):
media_dir = get_media_dir("zulip")
for name, path_id in upload_links:
- url = f"{self.config.site}{path_id}"
- safe_name = re.sub(r'[^\w.\-]', '_', unquote(name)) if name else f"attachment_{len(paths)}"
- dest = media_dir / safe_name
+ url = f"{self.config.site.rstrip('/')}{path_id}"
+ dest = self._attachment_destination(media_dir, name, path_id, len(paths))
if dest.exists():
paths.append(str(dest))
@@ -395,7 +410,28 @@ class ZulipChannel(BaseChannel):
return paths
@staticmethod
- def _extract_upload_links(content: str, content_type: str = "text/x-markdown") -> list[tuple[str, str]]:
+ def _safe_attachment_name(name: str, fallback: str) -> str:
+ raw_name = unquote(name or "").strip() or fallback
+ safe_name = re.sub(r"[^\w.\-]", "_", raw_name).strip("._")
+ return safe_name or fallback
+
+ @classmethod
+ def _attachment_destination(
+ cls,
+ media_dir: Path,
+ name: str,
+ path_id: str,
+ index: int,
+ ) -> Path:
+ fallback = f"attachment_{index}"
+ filename = cls._safe_attachment_name(name or Path(unquote(path_id)).name, fallback)
+ digest = hashlib.sha256(path_id.encode("utf-8")).hexdigest()[:12]
+ return media_dir / f"{digest}_{filename}"
+
+ @staticmethod
+ def _extract_upload_links(
+ content: str, content_type: str = "text/x-markdown"
+ ) -> list[tuple[str, str]]:
links: list[tuple[str, str]] = []
seen: set[str] = set()
@@ -565,10 +601,12 @@ class ZulipChannel(BaseChannel):
try:
while self._running and self._client:
try:
- self._client.set_typing_status({
- "op": "start",
- "to": [int(recipient_user_id)],
- })
+ self._client.set_typing_status(
+ {
+ "op": "start",
+ "to": [int(recipient_user_id)],
+ }
+ )
except Exception as e:
logger.debug("Zulip typing status error: {}", e)
await asyncio.sleep(4)
@@ -577,9 +615,11 @@ class ZulipChannel(BaseChannel):
finally:
if self._client:
try:
- self._client.set_typing_status({
- "op": "stop",
- "to": [int(recipient_user_id)],
- })
+ self._client.set_typing_status(
+ {
+ "op": "stop",
+ "to": [int(recipient_user_id)],
+ }
+ )
except Exception:
pass
diff --git a/deeptutor/tutorbot/providers/openai_compat_provider.py b/deeptutor/tutorbot/providers/openai_compat_provider.py
index f18efe554..4a33e7ada 100644
--- a/deeptutor/tutorbot/providers/openai_compat_provider.py
+++ b/deeptutor/tutorbot/providers/openai_compat_provider.py
@@ -277,9 +277,7 @@ class OpenAICompatProvider(LLMProvider):
# Providers that handle thinking via extra_body don't need a
# top-level reasoning_effort when the intent is to disable thinking.
- if reasoning_effort and not (
- extra and reasoning_effort.lower() == "minimal"
- ):
+ if reasoning_effort and not (extra and reasoning_effort.lower() == "minimal"):
kwargs["reasoning_effort"] = reasoning_effort
if tools:
diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.py
index 71ce99fa6..47d81426c 100644
--- a/deeptutor_cli/main.py
+++ b/deeptutor_cli/main.py
@@ -106,12 +106,14 @@ def run_capability(
@app.command()
def start() -> None:
"""Launch backend + frontend together."""
+ from pathlib import Path
import subprocess
import sys
- from pathlib import Path
script = str(Path(__file__).resolve().parent.parent / "scripts" / "start_web.py")
- subprocess.run([sys.executable, script])
+ result = subprocess.run([sys.executable, script], check=False)
+ if result.returncode:
+ raise typer.Exit(code=result.returncode)
@app.command()
diff --git a/scripts/start_web.py b/scripts/start_web.py
index e158c4b74..40f4ca8e6 100644
--- a/scripts/start_web.py
+++ b/scripts/start_web.py
@@ -511,8 +511,7 @@ def main() -> None:
return os.getenv(key, default)
auth_enabled = (
- _root_env_value("NEXT_PUBLIC_AUTH_ENABLED")
- or _root_env_value("AUTH_ENABLED", "false")
+ _root_env_value("NEXT_PUBLIC_AUTH_ENABLED") or _root_env_value("AUTH_ENABLED", "false")
).lower() in {"1", "true", "yes", "on"}
npm = shutil.which("npm")
diff --git a/tests/agents/research/test_token_tracker_pricing.py b/tests/agents/research/test_token_tracker_pricing.py
new file mode 100644
index 000000000..8db401444
--- /dev/null
+++ b/tests/agents/research/test_token_tracker_pricing.py
@@ -0,0 +1,14 @@
+"""Pricing table regression tests for research token tracking."""
+
+from deeptutor.agents.research.utils.token_tracker import get_model_pricing
+
+
+def test_deepseek_v4_pricing_entries() -> None:
+ assert get_model_pricing("deepseek-v4-flash") == {
+ "input": 0.00014,
+ "output": 0.00028,
+ }
+ assert get_model_pricing("deepseek-v4-pro") == {
+ "input": 0.000435,
+ "output": 0.00087,
+ }
diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py
index ca19ad5d7..d3c2cdbfa 100644
--- a/tests/cli/test_chat_cli.py
+++ b/tests/cli/test_chat_cli.py
@@ -127,3 +127,20 @@ def test_session_list_command_uses_shared_store(monkeypatch) -> None:
assert result.exit_code == 0, result.output
assert "session-1" in result.output
assert "Algebra" in result.output
+
+
+def test_start_command_propagates_start_web_exit_code(monkeypatch) -> None:
+ class Result:
+ returncode = 7
+
+ def _fake_run(cmd, check=False): # noqa: ANN001
+ assert check is False
+ assert cmd[0]
+ assert cmd[1].endswith("scripts/start_web.py")
+ return Result()
+
+ monkeypatch.setattr("subprocess.run", _fake_run)
+
+ result = runner.invoke(app, ["start"])
+
+ assert result.exit_code == 7
diff --git a/tests/multi_user/test_grants_and_settings.py b/tests/multi_user/test_grants_and_settings.py
index 0c6ea6392..62db8eb9d 100644
--- a/tests/multi_user/test_grants_and_settings.py
+++ b/tests/multi_user/test_grants_and_settings.py
@@ -1,5 +1,5 @@
-import pytest
from fastapi import HTTPException
+import pytest
from deeptutor.api.routers import settings as settings_router
from deeptutor.multi_user.context import reset_current_user, set_current_user
@@ -13,7 +13,9 @@ def make_user(tmp_path, role="user"):
id=uid,
username="admin" if role == "admin" else "alice",
role=role,
- scope=UserScope(kind="admin" if role == "admin" else "user", user_id=uid, root=tmp_path / uid),
+ scope=UserScope(
+ kind="admin" if role == "admin" else "user", user_id=uid, root=tmp_path / uid
+ ),
)
@@ -21,8 +23,12 @@ def test_grants_reject_secret_material(tmp_path, monkeypatch):
from deeptutor.multi_user import grants, identity
monkeypatch.setattr(grants, "GRANTS_DIR", tmp_path / "grants")
- monkeypatch.setattr(identity, "get_user_by_id", lambda user_id: ("alice", {}) if user_id == "u_alice" else None)
- monkeypatch.setattr(grants, "get_user_by_id", lambda user_id: ("alice", {}) if user_id == "u_alice" else None)
+ monkeypatch.setattr(
+ identity, "get_user_by_id", lambda user_id: ("alice", {}) if user_id == "u_alice" else None
+ )
+ monkeypatch.setattr(
+ grants, "get_user_by_id", lambda user_id: ("alice", {}) if user_id == "u_alice" else None
+ )
with pytest.raises(ValueError):
save_grant("u_alice", {"models": {"llm": [{"profile_id": "p", "api_key": "sk"}]}})
diff --git a/tests/multi_user/test_settings_status_redaction.py b/tests/multi_user/test_settings_status_redaction.py
index d7ccef891..a2021b2ca 100644
--- a/tests/multi_user/test_settings_status_redaction.py
+++ b/tests/multi_user/test_settings_status_redaction.py
@@ -28,9 +28,7 @@ def test_status_redacts_model_for_non_admin(mu_isolated_root, as_user, monkeypat
monkeypatch.setattr(system_router, "get_llm_config", lambda: _FakeLLM())
monkeypatch.setattr(system_router, "get_embedding_config", lambda: _FakeEmbedding())
- monkeypatch.setattr(
- system_router, "resolve_search_runtime_config", lambda: _FakeSearch()
- )
+ monkeypatch.setattr(system_router, "resolve_search_runtime_config", lambda: _FakeSearch())
with as_user("u_alice", role="user"):
result = asyncio.run(system_router.get_system_status())
@@ -60,9 +58,7 @@ def test_status_keeps_model_for_admin(mu_isolated_root, as_user, monkeypatch):
monkeypatch.setattr(system_router, "get_llm_config", lambda: _FakeLLM())
monkeypatch.setattr(system_router, "get_embedding_config", lambda: _FakeEmbedding())
- monkeypatch.setattr(
- system_router, "resolve_search_runtime_config", lambda: _FakeSearch()
- )
+ monkeypatch.setattr(system_router, "resolve_search_runtime_config", lambda: _FakeSearch())
with as_user("u_admin", role="admin"):
result = asyncio.run(system_router.get_system_status())
diff --git a/tests/multi_user/test_skill_resolution_scoped.py b/tests/multi_user/test_skill_resolution_scoped.py
index cd0aed294..1e9ddee3d 100644
--- a/tests/multi_user/test_skill_resolution_scoped.py
+++ b/tests/multi_user/test_skill_resolution_scoped.py
@@ -2,8 +2,8 @@
from __future__ import annotations
-import pytest
from fastapi import HTTPException
+import pytest
from deeptutor.multi_user import grants as grants_mod
from deeptutor.multi_user.skill_access import (
@@ -31,9 +31,7 @@ def _grant_skills(uid: str, names: list[str]) -> None:
def test_assigned_skill_loads_admin_skill_body(mu_isolated_root, as_user):
- admin_skills_root = (
- mu_isolated_root / "data" / "user" / "workspace" / "skills"
- ).resolve()
+ admin_skills_root = (mu_isolated_root / "data" / "user" / "workspace" / "skills").resolve()
_write_skill(admin_skills_root, "research-mode", "Use citations rigorously.")
_grant_skills("u_alice", ["research-mode"])
diff --git a/tests/multi_user/test_ui_language_scoping.py b/tests/multi_user/test_ui_language_scoping.py
index ddb0fb93e..1d4b5e6dd 100644
--- a/tests/multi_user/test_ui_language_scoping.py
+++ b/tests/multi_user/test_ui_language_scoping.py
@@ -10,9 +10,7 @@ from deeptutor.services.settings.interface_settings import (
)
-def test_get_ui_language_reads_per_user_interface_json(
- mu_isolated_root, as_user
-):
+def test_get_ui_language_reads_per_user_interface_json(mu_isolated_root, as_user):
# Admin's interface.json says English…
admin_settings = mu_isolated_root / "data" / "user" / "settings" / "interface.json"
admin_settings.parent.mkdir(parents=True, exist_ok=True)
diff --git a/tests/services/llm/test_capabilities.py b/tests/services/llm/test_capabilities.py
index 91c7f51a1..e9e02a29e 100644
--- a/tests/services/llm/test_capabilities.py
+++ b/tests/services/llm/test_capabilities.py
@@ -55,3 +55,8 @@ def test_moonshot_vision_models() -> None:
# Text-only Moonshot models stay False
assert supports_vision("moonshot", "moonshot-v1-8k") is False
assert supports_vision("moonshot", "kimi-latest") is False
+
+
+def test_qwen_model_override_enables_vision() -> None:
+ assert supports_vision("dashscope", "qwen-vl-plus") is True
+ assert supports_vision("openai", "qwen2.5-vl-72b-instruct") is True
diff --git a/tests/services/llm/test_openai_compat_reasoning_content.py b/tests/services/llm/test_openai_compat_reasoning_content.py
index ead717dd6..6494cfe68 100644
--- a/tests/services/llm/test_openai_compat_reasoning_content.py
+++ b/tests/services/llm/test_openai_compat_reasoning_content.py
@@ -9,9 +9,11 @@ import pytest
from deeptutor.services.llm.provider_core.openai_compat_provider import (
OpenAICompatProvider as ServicesOpenAICompatProvider,
)
+from deeptutor.services.provider_registry import find_by_name as find_service_provider
from deeptutor.tutorbot.providers.openai_compat_provider import (
OpenAICompatProvider as TutorBotOpenAICompatProvider,
)
+from deeptutor.tutorbot.providers.registry import find_by_name as find_tutorbot_provider
def _response_with_reasoning_only():
@@ -60,3 +62,54 @@ def test_parse_chunks_keeps_reasoning_content_out_of_visible_content(provider_cl
assert response.content is None
assert response.reasoning_content == "internal reasoning"
+
+
+def _build_services_kwargs(provider_name: str, reasoning_effort: str) -> dict:
+ provider = ServicesOpenAICompatProvider.__new__(ServicesOpenAICompatProvider)
+ provider.default_model = "deepseek-v4-pro"
+ provider._spec = find_service_provider(provider_name)
+ return provider._build_kwargs(
+ messages=[{"role": "user", "content": "hello"}],
+ tools=None,
+ model=None,
+ max_tokens=32,
+ temperature=0.7,
+ reasoning_effort=reasoning_effort,
+ tool_choice=None,
+ )
+
+
+def _build_tutorbot_kwargs(provider_name: str, reasoning_effort: str) -> dict:
+ provider = TutorBotOpenAICompatProvider.__new__(TutorBotOpenAICompatProvider)
+ provider.default_model = "deepseek-v4-pro"
+ provider._spec = find_tutorbot_provider(provider_name)
+ return provider._build_kwargs(
+ messages=[{"role": "user", "content": "hello"}],
+ tools=None,
+ model=None,
+ max_tokens=32,
+ temperature=0.7,
+ reasoning_effort=reasoning_effort,
+ tool_choice=None,
+ )
+
+
+def test_services_provider_minimal_reasoning_uses_extra_body_only() -> None:
+ kwargs = _build_services_kwargs("deepseek", "minimal")
+
+ assert "reasoning_effort" not in kwargs
+ assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
+
+
+def test_services_dashscope_minimal_reasoning_uses_enable_thinking_only() -> None:
+ kwargs = _build_services_kwargs("dashscope", "minimal")
+
+ assert "reasoning_effort" not in kwargs
+ assert kwargs["extra_body"] == {"enable_thinking": False}
+
+
+def test_tutorbot_provider_minimal_reasoning_uses_extra_body_only() -> None:
+ kwargs = _build_tutorbot_kwargs("deepseek", "minimal")
+
+ assert "reasoning_effort" not in kwargs
+ assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
diff --git a/tests/services/tutorbot/test_zulip_channel.py b/tests/services/tutorbot/test_zulip_channel.py
index cffcc9f8c..2ca408dd2 100644
--- a/tests/services/tutorbot/test_zulip_channel.py
+++ b/tests/services/tutorbot/test_zulip_channel.py
@@ -5,6 +5,8 @@ from __future__ import annotations
import asyncio
from collections import deque
from pathlib import Path
+import sys
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -243,7 +245,11 @@ class TestDownloadAttachments:
"content": "Check ![img.png](/user_uploads/2/ce/abc/img.png)",
"content_type": "text/x-markdown",
}
- with patch.object(ch, "_extract_upload_links", return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")]):
+ with patch.object(
+ ch,
+ "_extract_upload_links",
+ return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
+ ):
with patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get:
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
@@ -255,7 +261,10 @@ class TestDownloadAttachments:
assert len(paths) == 1
mock_get.assert_called_once()
call_url = mock_get.call_args[0][0]
- assert call_url == "https://example.zulipchat.com/user_uploads/2/ce/abc/img.png"
+ assert (
+ call_url
+ == "https://example.zulipchat.com/user_uploads/2/ce/abc/img.png"
+ )
def test_no_uploads_returns_empty(self):
ch = _make_channel()
@@ -270,13 +279,36 @@ class TestDownloadAttachments:
"content": "![img.png](/user_uploads/2/ce/abc/img.png)",
"content_type": "text/x-markdown",
}
- with patch.object(ch, "_extract_upload_links", return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")]):
- from unittest.mock import mock_open
+ with patch.object(
+ ch,
+ "_extract_upload_links",
+ return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
+ ):
from pathlib import Path as RealPath
+ from unittest.mock import mock_open
+
with patch.object(RealPath, "exists", return_value=True):
paths = ch._download_attachments(message)
assert len(paths) == 1
+ def test_attachment_destination_uses_upload_path_digest(self, tmp_path: Path):
+ first = ZulipChannel._attachment_destination(
+ tmp_path,
+ "image.png",
+ "/user_uploads/2/aa/first/image.png",
+ 0,
+ )
+ second = ZulipChannel._attachment_destination(
+ tmp_path,
+ "image.png",
+ "/user_uploads/2/bb/second/image.png",
+ 0,
+ )
+
+ assert first != second
+ assert first.name.endswith("_image.png")
+ assert second.name.endswith("_image.png")
+
class TestConvertLatexToZulip:
def test_inline_math(self):
@@ -295,17 +327,13 @@ class TestConvertLatexToZulip:
assert "E = mc^2" in result
def test_mixed_inline_and_display(self):
- result = ZulipChannel._convert_latex_to_zulip(
- "Inline $a+b$ and display:\n$$c+d$$"
- )
+ result = ZulipChannel._convert_latex_to_zulip("Inline $a+b$ and display:\n$$c+d$$")
assert "$$a+b$$" in result
assert "```math" in result
assert "c+d" in result
def test_code_block_preserved(self):
- result = ZulipChannel._convert_latex_to_zulip(
- "```python\nx = $1 + $2\n```"
- )
+ result = ZulipChannel._convert_latex_to_zulip("```python\nx = $1 + $2\n```")
assert "```python" in result
assert "$1 + $2" in result
@@ -332,9 +360,7 @@ class TestConvertZulipLatexToStandard:
assert result == "The value $x^2$ is positive"
def test_display_math(self):
- result = ZulipChannel._convert_zulip_latex_to_standard(
- "```math\n\\int_a^b f(x) dx\n```"
- )
+ result = ZulipChannel._convert_zulip_latex_to_standard("```math\n\\int_a^b f(x) dx\n```")
assert "$$" in result
assert "\\int_a^b f(x) dx" in result
assert "```math" not in result
@@ -348,9 +374,7 @@ class TestConvertZulipLatexToStandard:
assert "c+d" in result
def test_code_block_preserved(self):
- result = ZulipChannel._convert_zulip_latex_to_standard(
- "```python\nx = $$1 + $$2\n```"
- )
+ result = ZulipChannel._convert_zulip_latex_to_standard("```python\nx = $$1 + $$2\n```")
assert "```python" in result
assert "$$1 + $$2" in result
@@ -379,7 +403,7 @@ class TestBuildSendRequest:
"stream": "general",
"topic": "hello",
}
- req = ch._build_send_request("stream:general", "Hello world", metadata)
+ req = ch._build_send_request("stream:general:hello", "Hello world", metadata)
assert req["type"] == "stream"
assert req["to"] == "general"
assert req["subject"] == "hello"
@@ -557,8 +581,32 @@ class TestOnMessage:
await asyncio.sleep(0.1)
call_args = ch.bus.publish_inbound.call_args[0][0]
+ assert call_args.chat_id == "stream:general:test topic"
+ assert call_args.session_key_override == "zulip:stream:general:test topic"
assert "**[general > test topic]**" in call_args.content
+ @pytest.mark.asyncio
+ async def test_empty_stream_topic_gets_stable_no_topic_scope(self):
+ ch = _make_channel(group_policy="open")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="",
+ content="Hello",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ call_args = ch.bus.publish_inbound.call_args[0][0]
+ assert call_args.chat_id == "stream:general:(no topic)"
+ assert call_args.session_key_override == "zulip:stream:general:(no topic)"
+
class TestSend:
@pytest.mark.asyncio
@@ -667,7 +715,8 @@ class TestUploadAndSend:
await ch.send(msg)
upload_calls = [
- c for c in mock_client.call_endpoint.call_args_list
+ c
+ for c in mock_client.call_endpoint.call_args_list
if c.kwargs.get("url") == "user_uploads"
]
assert len(upload_calls) == 1
@@ -747,7 +796,9 @@ class TestCallWithRetry:
def test_retries_on_failure(self):
ch = _make_channel()
- fn = MagicMock(side_effect=[Exception("fail"), Exception("fail again"), {"result": "success"}])
+ fn = MagicMock(
+ side_effect=[Exception("fail"), Exception("fail again"), {"result": "success"}]
+ )
with patch("time.sleep"):
result = ch._call_with_retry(fn)
assert result == {"result": "success"}
@@ -770,11 +821,12 @@ class TestStart:
assert ch._running is False
@pytest.mark.asyncio
- async def test_start_profile_failure(self):
+ async def test_start_profile_failure(self, monkeypatch):
ch = _make_channel()
+ fake_zulip = SimpleNamespace(Client=MagicMock())
+ monkeypatch.setitem(sys.modules, "zulip", fake_zulip)
with patch("deeptutor.tutorbot.channels.zulip.ZulipChannel._call_with_retry") as mock_retry:
mock_retry.return_value = {"result": "error"}
- with patch("zulip.Client"):
- await ch.start()
+ await ch.start()
assert ch._running is False
diff --git a/web/app/(admin)/admin/users/page.tsx b/web/app/(admin)/admin/users/page.tsx
index adbce065d..aa996f3f2 100644
--- a/web/app/(admin)/admin/users/page.tsx
+++ b/web/app/(admin)/admin/users/page.tsx
@@ -233,94 +233,94 @@ export default function AdminUsersPage() {
const canManageAssignments = !isAdmin && Boolean(user.id);
return (
<Fragment key={user.username}>
- <tr
- className="group hover:bg-[var(--background)]/50 transition-colors"
- >
- <td className="px-5 py-3.5 font-medium text-[var(--foreground)]">
- {user.username}
- {isSelf && (
- <span className="ml-2 text-xs text-[var(--muted-foreground)]">
- (you)
- </span>
- )}
- </td>
- <td className="px-5 py-3.5">
- <span
- className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium
+ <tr className="group hover:bg-[var(--background)]/50 transition-colors">
+ <td className="px-5 py-3.5 font-medium text-[var(--foreground)]">
+ {user.username}
+ {isSelf && (
+ <span className="ml-2 text-xs text-[var(--muted-foreground)]">
+ (you)
+ </span>
+ )}
+ </td>
+ <td className="px-5 py-3.5">
+ <span
+ className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium
${
user.role === "admin"
? "bg-purple-500/15 text-purple-600 dark:text-purple-400"
: "bg-[var(--muted)]/50 text-[var(--muted-foreground)]"
}`}
- >
- {user.role === "admin" ? <Shield size={11} /> : null}
- {user.role}
- </span>
- </td>
- <td className="px-5 py-3.5 text-[var(--muted-foreground)]">
- {formatDate(user.created_at)}
- </td>
- <td className="px-5 py-3.5">
- <div className="flex items-center justify-end gap-1.5">
- {canManageAssignments && (
+ >
+ {user.role === "admin" ? (
+ <Shield size={11} />
+ ) : null}
+ {user.role}
+ </span>
+ </td>
+ <td className="px-5 py-3.5 text-[var(--muted-foreground)]">
+ {formatDate(user.created_at)}
+ </td>
+ <td className="px-5 py-3.5">
+ <div className="flex items-center justify-end gap-1.5">
+ {canManageAssignments && (
+ <button
+ onClick={() =>
+ setExpandedUserId((current) =>
+ current === user.id ? null : user.id,
+ )
+ }
+ title="Manage assignments"
+ className="rounded-lg p-1.5 text-[var(--muted-foreground)]
+ hover:bg-[var(--background)] hover:text-[var(--foreground)]
+ transition-colors"
+ >
+ <SlidersHorizontal size={15} />
+ </button>
+ )}
<button
- onClick={() =>
- setExpandedUserId((current) =>
- current === user.id ? null : user.id,
- )
+ onClick={() => handleToggleRole(user)}
+ disabled={isSelf}
+ title={
+ isSelf
+ ? "Cannot change your own role"
+ : user.role === "admin"
+ ? "Demote to user"
+ : "Promote to admin"
}
- title="Manage assignments"
className="rounded-lg p-1.5 text-[var(--muted-foreground)]
- hover:bg-[var(--background)] hover:text-[var(--foreground)]
- transition-colors"
- >
- <SlidersHorizontal size={15} />
- </button>
- )}
- <button
- onClick={() => handleToggleRole(user)}
- disabled={isSelf}
- title={
- isSelf
- ? "Cannot change your own role"
- : user.role === "admin"
- ? "Demote to user"
- : "Promote to admin"
- }
- className="rounded-lg p-1.5 text-[var(--muted-foreground)]
hover:bg-[var(--background)] hover:text-[var(--foreground)]
disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
- >
- {user.role === "admin" ? (
- <ShieldOff size={15} />
- ) : (
- <Shield size={15} />
- )}
- </button>
- <button
- onClick={() => handleDelete(user.username)}
- disabled={isSelf}
- title={
- isSelf
- ? "Cannot delete your own account"
- : `Delete ${user.username}`
- }
- className="rounded-lg p-1.5 text-[var(--muted-foreground)]
+ >
+ {user.role === "admin" ? (
+ <ShieldOff size={15} />
+ ) : (
+ <Shield size={15} />
+ )}
+ </button>
+ <button
+ onClick={() => handleDelete(user.username)}
+ disabled={isSelf}
+ title={
+ isSelf
+ ? "Cannot delete your own account"
+ : `Delete ${user.username}`
+ }
+ className="rounded-lg p-1.5 text-[var(--muted-foreground)]
hover:bg-red-500/10 hover:text-red-500
disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
- >
- <Trash2 size={15} />
- </button>
- </div>
- </td>
- </tr>
- {canManageAssignments && expandedUserId === user.id && (
- <tr>
- <td colSpan={4} className="p-0">
- <GrantEditor userId={user.id} />
+ >
+ <Trash2 size={15} />
+ </button>
+ </div>
</td>
</tr>
- )}
+ {canManageAssignments && expandedUserId === user.id && (
+ <tr>
+ <td colSpan={4} className="p-0">
+ <GrantEditor userId={user.id} />
+ </td>
+ </tr>
+ )}
</Fragment>
);
})}
diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx
index e11fdad2a..448ebca16 100644
--- a/web/app/(utility)/settings/page.tsx
+++ b/web/app/(utility)/settings/page.tsx
@@ -693,7 +693,8 @@ function SettingsPageContent() {
const activeProfile = getActiveProfile(draft, activeService);
const activeModel = getActiveModel(draft, activeService);
const hasUnsavedChanges =
- catalogEditable === true && JSON.stringify(catalog) !== JSON.stringify(draft);
+ catalogEditable === true &&
+ JSON.stringify(catalog) !== JSON.stringify(draft);
const searchProviderRaw =
activeService === "search"
? (activeProfile?.provider || "").trim().toLowerCase()
@@ -1185,729 +1186,749 @@ function SettingsPageContent() {
{/* ── Runtime status ── */}
{catalogEditable === true && (
<>
- <div className="mb-8 grid grid-cols-2 overflow-hidden rounded-xl border border-[var(--border)]/60 sm:grid-cols-4">
- <div
- className="px-4 py-3.5"
- title={status?.backend.timestamp || t("Backend status")}
- >
- <div className="flex items-center gap-2">
- <span
- className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
- status?.backend.status === "online",
- false,
- )}`}
- />
- <span
- className={`${labelClass("md")} text-[var(--muted-foreground)]`}
- >
- {t("Backend")}
- </span>
- </div>
- <div className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]">
- {status?.backend.status === "online"
- ? t("Online")
- : t("Checking")}
- </div>
- <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {(() => {
- const ts = status?.backend.timestamp;
- if (!ts) return "—";
- const parsed = new Date(ts);
- if (Number.isNaN(parsed.getTime())) return "";
- return parsed.toLocaleTimeString(
- language === "zh" ? "zh-CN" : "en-US",
- { hour: "2-digit", minute: "2-digit" },
- );
- })()}
- </div>
- </div>
-
- {SERVICES.map((service, i) => {
- const profile = getActiveProfile(draft, service);
- const model = getActiveModel(draft, service);
- const serviceStatus =
- service === "llm"
- ? status?.llm
- : service === "embedding"
- ? status?.embeddings
- : status?.search;
- const runtimeModel =
- service === "llm"
- ? status?.llm.model
- : service === "embedding"
- ? status?.embeddings.model
- : undefined;
- const configured =
- service === "search"
- ? Boolean(profile?.provider || status?.search.provider)
- : Boolean(model?.model || runtimeModel);
- const pendingApply = servicePendingApply(catalog, draft, service);
- const detail = activeModelDetail(profile, model, service, t);
- const profileName = profile?.name || t("No profile");
- const isActiveTab = activeService === service;
- const borderClasses =
- i === 0
- ? "border-l border-[var(--border)]/40"
- : i === 1
- ? "border-t border-[var(--border)]/40 sm:border-t-0 sm:border-l"
- : "border-t border-l border-[var(--border)]/40 sm:border-t-0";
- return (
- <button
- key={service}
- type="button"
- onClick={() => setActiveService(service)}
- title={`${serviceLabel(service, t)} · ${profileName} · ${detail}`}
- className={`relative px-4 py-3.5 text-left transition-colors ${borderClasses} ${
- isActiveTab
- ? "bg-[var(--muted)]/55"
- : "hover:bg-[var(--muted)]/30"
- }`}
+ <div className="mb-8 grid grid-cols-2 overflow-hidden rounded-xl border border-[var(--border)]/60 sm:grid-cols-4">
+ <div
+ className="px-4 py-3.5"
+ title={status?.backend.timestamp || t("Backend status")}
>
<div className="flex items-center gap-2">
<span
className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
- configured,
- Boolean(serviceStatus?.error),
+ status?.backend.status === "online",
+ false,
)}`}
/>
<span
- className={`truncate ${labelClass("md")} text-[var(--muted-foreground)]`}
+ className={`${labelClass("md")} text-[var(--muted-foreground)]`}
>
- {serviceLabel(service, t)}
+ {t("Backend")}
</span>
- {pendingApply && (
- <span className="ml-auto shrink-0 text-[10px] font-medium text-amber-600 dark:text-amber-400">
- {t("Pending")}
- </span>
- )}
</div>
<div className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]">
- {detail}
+ {status?.backend.status === "online"
+ ? t("Online")
+ : t("Checking")}
</div>
<div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {profileName}
+ {(() => {
+ const ts = status?.backend.timestamp;
+ if (!ts) return "—";
+ const parsed = new Date(ts);
+ if (Number.isNaN(parsed.getTime())) return "";
+ return parsed.toLocaleTimeString(
+ language === "zh" ? "zh-CN" : "en-US",
+ { hour: "2-digit", minute: "2-digit" },
+ );
+ })()}
</div>
- </button>
- );
- })}
- </div>
+ </div>
- {/* ── Service Configuration ── */}
- <div className="mb-8">
- <div className="mb-5 flex items-center justify-between">
- <div className="flex items-center gap-1">
- {(["llm", "embedding", "search"] as const).map((service) => (
- <button
- key={service}
- data-tour={`tour-${service}`}
- onClick={() => setActiveService(service)}
- className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- activeService === service
- ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- {serviceIcon(service)}
- {service.toUpperCase()}
- <span className="text-[11px] text-[var(--muted-foreground)]/60">
- {draft.services[service].profiles.length}
- </span>
- </button>
- ))}
- </div>
- <div className="flex items-center gap-2">
- <button
- onClick={addProfile}
- className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- <Plus className="h-3 w-3" />
- {t("Profile")}
- </button>
- {activeService !== "search" && (
- <button
- onClick={addModel}
- className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- <Plus className="h-3 w-3" />
- {t("Model")}
- </button>
- )}
+ {SERVICES.map((service, i) => {
+ const profile = getActiveProfile(draft, service);
+ const model = getActiveModel(draft, service);
+ const serviceStatus =
+ service === "llm"
+ ? status?.llm
+ : service === "embedding"
+ ? status?.embeddings
+ : status?.search;
+ const runtimeModel =
+ service === "llm"
+ ? status?.llm.model
+ : service === "embedding"
+ ? status?.embeddings.model
+ : undefined;
+ const configured =
+ service === "search"
+ ? Boolean(profile?.provider || status?.search.provider)
+ : Boolean(model?.model || runtimeModel);
+ const pendingApply = servicePendingApply(
+ catalog,
+ draft,
+ service,
+ );
+ const detail = activeModelDetail(profile, model, service, t);
+ const profileName = profile?.name || t("No profile");
+ const isActiveTab = activeService === service;
+ const borderClasses =
+ i === 0
+ ? "border-l border-[var(--border)]/40"
+ : i === 1
+ ? "border-t border-[var(--border)]/40 sm:border-t-0 sm:border-l"
+ : "border-t border-l border-[var(--border)]/40 sm:border-t-0";
+ return (
+ <button
+ key={service}
+ type="button"
+ onClick={() => setActiveService(service)}
+ title={`${serviceLabel(service, t)} · ${profileName} · ${detail}`}
+ className={`relative px-4 py-3.5 text-left transition-colors ${borderClasses} ${
+ isActiveTab
+ ? "bg-[var(--muted)]/55"
+ : "hover:bg-[var(--muted)]/30"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <span
+ className={`h-1.5 w-1.5 rounded-full ${statusDotClass(
+ configured,
+ Boolean(serviceStatus?.error),
+ )}`}
+ />
+ <span
+ className={`truncate ${labelClass("md")} text-[var(--muted-foreground)]`}
+ >
+ {serviceLabel(service, t)}
+ </span>
+ {pendingApply && (
+ <span className="ml-auto shrink-0 text-[10px] font-medium text-amber-600 dark:text-amber-400">
+ {t("Pending")}
+ </span>
+ )}
+ </div>
+ <div className="mt-2 truncate text-[13px] font-medium text-[var(--foreground)]">
+ {detail}
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
+ {profileName}
+ </div>
+ </button>
+ );
+ })}
</div>
- </div>
- {activeProfile ? (
- <div className="grid grid-cols-[200px_1fr] gap-5">
- {/* ── Profile list ── */}
- <div className="space-y-2">
- {draft.services[activeService].profiles.map((profile) => {
- const isActive =
- profile.id ===
- draft.services[activeService].active_profile_id;
- const activeProfileModel =
- activeService === "search"
- ? null
- : (profile.models.find(
- (model) =>
- model.id ===
- draft.services[activeService].active_model_id,
- ) ??
- profile.models[0] ??
- null);
- const profileDetail = activeProfileDetail(
- profile,
- activeService,
- t,
- );
- const modelDetail = activeModelDetail(
- profile,
- activeProfileModel,
- activeService,
- t,
- );
- return (
+ {/* ── Service Configuration ── */}
+ <div className="mb-8">
+ <div className="mb-5 flex items-center justify-between">
+ <div className="flex items-center gap-1">
+ {(["llm", "embedding", "search"] as const).map((service) => (
<button
- key={profile.id}
- onClick={() =>
- mutateCatalog((next) => {
- next.services[activeService].active_profile_id =
- profile.id;
- if (activeService !== "search") {
- next.services[activeService].active_model_id =
- profile.models[0]?.id ?? null;
- }
- })
- }
- className={`relative w-full overflow-hidden rounded-xl px-3.5 py-3 text-left transition-colors ${
- isActive
- ? "bg-[var(--muted)]/60 text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/30"
+ key={service}
+ data-tour={`tour-${service}`}
+ onClick={() => setActiveService(service)}
+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
+ activeService === service
+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
}`}
>
- {isActive && (
- <span className="absolute inset-y-3 left-0 w-0.5 rounded-r-full bg-[var(--foreground)]/80" />
- )}
- <div className="truncate text-[13px] font-semibold">
- {profile.name}
- </div>
- <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
- {profileDetail}
- </div>
- {isActive ? (
- <div className="mt-2.5 border-t border-[var(--border)]/40 pt-2">
- <div
- className={`${labelClass("sm")} text-[var(--muted-foreground)]/70`}
- >
- {activeService === "search"
- ? t("Active provider")
- : t("Active model")}
- </div>
- <div className="mt-0.5 truncate text-[12px] font-medium text-[var(--foreground)]">
- {modelDetail}
- </div>
- </div>
- ) : (
- activeService !== "search" && (
- <div className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
- {t("{{count}} models", {
- count: profile.models.length,
- })}
- </div>
- )
- )}
+ {serviceIcon(service)}
+ {service.toUpperCase()}
+ <span className="text-[11px] text-[var(--muted-foreground)]/60">
+ {draft.services[service].profiles.length}
+ </span>
</button>
- );
- })}
- <button
- onClick={removeActiveProfile}
- disabled={!activeProfile}
- className="flex w-full items-center gap-1.5 rounded-lg px-3 py-2 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
- >
- <Trash2 className="h-3 w-3" />
- {t("Delete profile")}
- </button>
+ ))}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={addProfile}
+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Plus className="h-3 w-3" />
+ {t("Profile")}
+ </button>
+ {activeService !== "search" && (
+ <button
+ onClick={addModel}
+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
+ >
+ <Plus className="h-3 w-3" />
+ {t("Model")}
+ </button>
+ )}
+ </div>
</div>
- {/* ── Editor ── */}
- <div className="space-y-5">
- <div className="rounded-xl border border-[var(--border)] p-5">
- <div className="mb-4 text-[13px] font-medium text-[var(--foreground)]">
- {t("Profile")}
- </div>
- <div className="grid gap-4 sm:grid-cols-2">
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Name")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.name}
- onChange={(e) =>
- updateProfileField("name", e.target.value)
- }
- />
- </div>
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Provider")}
- </div>
- <div className="relative">
- <select
- className={selectClass}
- value={
- activeService === "search"
- ? activeProfile.provider || ""
- : activeProfile.binding || ""
+ {activeProfile ? (
+ <div className="grid grid-cols-[200px_1fr] gap-5">
+ {/* ── Profile list ── */}
+ <div className="space-y-2">
+ {draft.services[activeService].profiles.map((profile) => {
+ const isActive =
+ profile.id ===
+ draft.services[activeService].active_profile_id;
+ const activeProfileModel =
+ activeService === "search"
+ ? null
+ : (profile.models.find(
+ (model) =>
+ model.id ===
+ draft.services[activeService].active_model_id,
+ ) ??
+ profile.models[0] ??
+ null);
+ const profileDetail = activeProfileDetail(
+ profile,
+ activeService,
+ t,
+ );
+ const modelDetail = activeModelDetail(
+ profile,
+ activeProfileModel,
+ activeService,
+ t,
+ );
+ return (
+ <button
+ key={profile.id}
+ onClick={() =>
+ mutateCatalog((next) => {
+ next.services[activeService].active_profile_id =
+ profile.id;
+ if (activeService !== "search") {
+ next.services[activeService].active_model_id =
+ profile.models[0]?.id ?? null;
+ }
+ })
}
- onChange={(e) => {
- const val = e.target.value;
- const field =
- activeService === "search"
- ? "provider"
- : "binding";
- updateProfileField(field, val);
- const match = (providers[activeService] || []).find(
- (p) => p.value === val,
- );
- if (match?.base_url) {
- updateProfileField("base_url", match.base_url);
- }
- if (
- activeService === "embedding" &&
- match?.default_dim
- ) {
- updateModelField("dimension", match.default_dim);
- }
- }}
- >
- <option className={selectOptionClass} value="">
- {t("Select provider...")}
- </option>
- {(providers[activeService] || []).map((p) => (
- <option
- className={selectOptionClass}
- key={p.value}
- value={p.value}
- >
- {p.label}
- </option>
- ))}
- </select>
- <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />
- </div>
- {showSearchProviderWarning && (
- <p
- className={`mt-1.5 text-[11px] ${
- isSupportedSearchProvider
- ? "text-emerald-600 dark:text-emerald-400"
- : isDeprecatedSearchProvider
- ? "text-amber-600 dark:text-amber-400"
- : "text-red-500"
+ className={`relative w-full overflow-hidden rounded-xl px-3.5 py-3 text-left transition-colors ${
+ isActive
+ ? "bg-[var(--muted)]/60 text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/30"
}`}
>
- {isSupportedSearchProvider
- ? isPerplexityMissingKey
- ? t(
- "Perplexity requires API key. It will fail hard without credentials.",
- )
- : t("Supported provider.")
- : isDeprecatedSearchProvider
- ? t(
- "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.",
- )
- : t(
- "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.",
- )}
- </p>
- )}
- </div>
- <div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {activeService === "embedding"
- ? t("Endpoint URL")
- : t("Base URL")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.base_url}
- onChange={(e) =>
- updateProfileField("base_url", e.target.value)
- }
- placeholder={
- activeService === "embedding"
- ? "https://api.openai.com/v1/embeddings"
- : "https://api.openai.com/v1"
- }
- />
- {activeService === "embedding" && (
- <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">
- {t(
- "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.",
+ {isActive && (
+ <span className="absolute inset-y-3 left-0 w-0.5 rounded-r-full bg-[var(--foreground)]/80" />
)}
- </p>
- )}
- </div>
- <div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("API Key")}
- </div>
- <div className="relative">
- <input
- type={showApiKey ? "text" : "password"}
- autoComplete="new-password"
- spellCheck={false}
- className={`${inputClass} pr-10 font-mono`}
- value={activeProfile.api_key}
- onChange={(e) =>
- updateProfileField("api_key", e.target.value)
- }
- placeholder="sk-..."
- />
- <button
- type="button"
- onClick={() => setShowApiKey((prev) => !prev)}
- className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- aria-label={
- showApiKey ? t("Hide API key") : t("Show API key")
- }
- title={
- showApiKey ? t("Hide API key") : t("Show API key")
- }
- >
- {showApiKey ? (
- <EyeOff className="h-4 w-4" />
+ <div className="truncate text-[13px] font-semibold">
+ {profile.name}
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">
+ {profileDetail}
+ </div>
+ {isActive ? (
+ <div className="mt-2.5 border-t border-[var(--border)]/40 pt-2">
+ <div
+ className={`${labelClass("sm")} text-[var(--muted-foreground)]/70`}
+ >
+ {activeService === "search"
+ ? t("Active provider")
+ : t("Active model")}
+ </div>
+ <div className="mt-0.5 truncate text-[12px] font-medium text-[var(--foreground)]">
+ {modelDetail}
+ </div>
+ </div>
) : (
- <Eye className="h-4 w-4" />
+ activeService !== "search" && (
+ <div className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">
+ {t("{{count}} models", {
+ count: profile.models.length,
+ })}
+ </div>
+ )
)}
</button>
- </div>
- </div>
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("API Version")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.api_version}
- onChange={(e) =>
- updateProfileField("api_version", e.target.value)
- }
- placeholder={t("Optional")}
- />
- </div>
- {activeService === "search" ? (
- <div>
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Proxy")}
- </div>
- <input
- className={inputClass}
- value={activeProfile.proxy || ""}
- onChange={(e) =>
- updateProfileField("proxy", e.target.value)
- }
- placeholder="http://127.0.0.1:7890 (optional)"
- />
- </div>
- ) : (
- <div className="sm:col-span-2">
- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Extra Headers (JSON)")}
- </div>
- <textarea
- className={`${inputClass} min-h-[84px] resize-y`}
- value={stringifyExtraHeaders(
- activeProfile.extra_headers,
- )}
- onChange={(e) =>
- updateProfileField("extra_headers", e.target.value)
- }
- placeholder='{"APP-Code":"your-app-code"}'
- />
- </div>
- )}
+ );
+ })}
+ <button
+ onClick={removeActiveProfile}
+ disabled={!activeProfile}
+ className="flex w-full items-center gap-1.5 rounded-lg px-3 py-2 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
+ >
+ <Trash2 className="h-3 w-3" />
+ {t("Delete profile")}
+ </button>
</div>
- </div>
- {activeService !== "search" && (
- <div className="rounded-xl border border-[var(--border)] p-5">
- <div className="mb-4 flex items-center justify-between">
- <div className="text-[13px] font-medium text-[var(--foreground)]">
- {t("Models")}
+ {/* ── Editor ── */}
+ <div className="space-y-5">
+ <div className="rounded-xl border border-[var(--border)] p-5">
+ <div className="mb-4 text-[13px] font-medium text-[var(--foreground)]">
+ {t("Profile")}
</div>
- <button
- onClick={removeActiveModel}
- disabled={!activeModel}
- className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
- >
- <Trash2 className="h-3 w-3" />
- {t("Delete")}
- </button>
- </div>
- {activeProfile.models.length > 0 && (
- <div className="mb-4 flex flex-wrap gap-1.5">
- {activeProfile.models.map((model) => (
- <button
- key={model.id}
- onClick={() =>
- mutateCatalog((next) => {
- next.services[activeService].active_model_id =
- model.id;
- })
- }
- className={`rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
- model.id ===
- draft.services[activeService].active_model_id
- ? "bg-[var(--foreground)] font-medium text-[var(--background)] shadow-sm"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
- }`}
- >
- <span className="inline-flex items-center gap-1.5">
- {model.id ===
- draft.services[activeService]
- .active_model_id && (
- <CheckCircle2 className="h-3 w-3" />
- )}
- {model.name}
- </span>
- </button>
- ))}
- </div>
- )}
- {activeModel && (
<div className="grid gap-4 sm:grid-cols-2">
<div>
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Label")}
+ {t("Name")}
+ </div>
+ <input
+ className={inputClass}
+ value={activeProfile.name}
+ onChange={(e) =>
+ updateProfileField("name", e.target.value)
+ }
+ />
+ </div>
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Provider")}
+ </div>
+ <div className="relative">
+ <select
+ className={selectClass}
+ value={
+ activeService === "search"
+ ? activeProfile.provider || ""
+ : activeProfile.binding || ""
+ }
+ onChange={(e) => {
+ const val = e.target.value;
+ const field =
+ activeService === "search"
+ ? "provider"
+ : "binding";
+ updateProfileField(field, val);
+ const match = (
+ providers[activeService] || []
+ ).find((p) => p.value === val);
+ if (match?.base_url) {
+ updateProfileField(
+ "base_url",
+ match.base_url,
+ );
+ }
+ if (
+ activeService === "embedding" &&
+ match?.default_dim
+ ) {
+ updateModelField(
+ "dimension",
+ match.default_dim,
+ );
+ }
+ }}
+ >
+ <option className={selectOptionClass} value="">
+ {t("Select provider...")}
+ </option>
+ {(providers[activeService] || []).map((p) => (
+ <option
+ className={selectOptionClass}
+ key={p.value}
+ value={p.value}
+ >
+ {p.label}
+ </option>
+ ))}
+ </select>
+ <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />
+ </div>
+ {showSearchProviderWarning && (
+ <p
+ className={`mt-1.5 text-[11px] ${
+ isSupportedSearchProvider
+ ? "text-emerald-600 dark:text-emerald-400"
+ : isDeprecatedSearchProvider
+ ? "text-amber-600 dark:text-amber-400"
+ : "text-red-500"
+ }`}
+ >
+ {isSupportedSearchProvider
+ ? isPerplexityMissingKey
+ ? t(
+ "Perplexity requires API key. It will fail hard without credentials.",
+ )
+ : t("Supported provider.")
+ : isDeprecatedSearchProvider
+ ? t(
+ "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.",
+ )
+ : t(
+ "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.",
+ )}
+ </p>
+ )}
+ </div>
+ <div className="sm:col-span-2">
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {activeService === "embedding"
+ ? t("Endpoint URL")
+ : t("Base URL")}
</div>
<input
className={inputClass}
- value={activeModel.name}
+ value={activeProfile.base_url}
onChange={(e) =>
- updateModelField("name", e.target.value)
+ updateProfileField("base_url", e.target.value)
+ }
+ placeholder={
+ activeService === "embedding"
+ ? "https://api.openai.com/v1/embeddings"
+ : "https://api.openai.com/v1"
}
/>
+ {activeService === "embedding" && (
+ <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">
+ {t(
+ "Embedding requests are sent to this URL exactly; DeepTutor does not append /embeddings or /api/embed at request time.",
+ )}
+ </p>
+ )}
+ </div>
+ <div className="sm:col-span-2">
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("API Key")}
+ </div>
+ <div className="relative">
+ <input
+ type={showApiKey ? "text" : "password"}
+ autoComplete="new-password"
+ spellCheck={false}
+ className={`${inputClass} pr-10 font-mono`}
+ value={activeProfile.api_key}
+ onChange={(e) =>
+ updateProfileField("api_key", e.target.value)
+ }
+ placeholder="sk-..."
+ />
+ <button
+ type="button"
+ onClick={() => setShowApiKey((prev) => !prev)}
+ className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ aria-label={
+ showApiKey
+ ? t("Hide API key")
+ : t("Show API key")
+ }
+ title={
+ showApiKey
+ ? t("Hide API key")
+ : t("Show API key")
+ }
+ >
+ {showApiKey ? (
+ <EyeOff className="h-4 w-4" />
+ ) : (
+ <Eye className="h-4 w-4" />
+ )}
+ </button>
+ </div>
</div>
<div>
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Model ID")}
+ {t("API Version")}
</div>
<input
className={inputClass}
- value={activeModel.model}
+ value={activeProfile.api_version}
onChange={(e) =>
- updateModelField("model", e.target.value)
+ updateProfileField("api_version", e.target.value)
}
- placeholder="gpt-4o"
+ placeholder={t("Optional")}
/>
</div>
- {activeService === "llm" && (
- <>
+ {activeService === "search" ? (
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Proxy")}
+ </div>
+ <input
+ className={inputClass}
+ value={activeProfile.proxy || ""}
+ onChange={(e) =>
+ updateProfileField("proxy", e.target.value)
+ }
+ placeholder="http://127.0.0.1:7890 (optional)"
+ />
+ </div>
+ ) : (
+ <div className="sm:col-span-2">
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Extra Headers (JSON)")}
+ </div>
+ <textarea
+ className={`${inputClass} min-h-[84px] resize-y`}
+ value={stringifyExtraHeaders(
+ activeProfile.extra_headers,
+ )}
+ onChange={(e) =>
+ updateProfileField(
+ "extra_headers",
+ e.target.value,
+ )
+ }
+ placeholder='{"APP-Code":"your-app-code"}'
+ />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {activeService !== "search" && (
+ <div className="rounded-xl border border-[var(--border)] p-5">
+ <div className="mb-4 flex items-center justify-between">
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ {t("Models")}
+ </div>
+ <button
+ onClick={removeActiveModel}
+ disabled={!activeModel}
+ className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"
+ >
+ <Trash2 className="h-3 w-3" />
+ {t("Delete")}
+ </button>
+ </div>
+ {activeProfile.models.length > 0 && (
+ <div className="mb-4 flex flex-wrap gap-1.5">
+ {activeProfile.models.map((model) => (
+ <button
+ key={model.id}
+ onClick={() =>
+ mutateCatalog((next) => {
+ next.services[
+ activeService
+ ].active_model_id = model.id;
+ })
+ }
+ className={`rounded-lg px-3 py-1.5 text-[13px] transition-colors ${
+ model.id ===
+ draft.services[activeService].active_model_id
+ ? "bg-[var(--foreground)] font-medium text-[var(--background)] shadow-sm"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
+ }`}
+ >
+ <span className="inline-flex items-center gap-1.5">
+ {model.id ===
+ draft.services[activeService]
+ .active_model_id && (
+ <CheckCircle2 className="h-3 w-3" />
+ )}
+ {model.name}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ {activeModel && (
+ <div className="grid gap-4 sm:grid-cols-2">
<div>
<div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
- {t("Context Window")}
+ {t("Label")}
</div>
<input
className={inputClass}
- inputMode="numeric"
- value={activeModel.context_window || ""}
+ value={activeModel.name}
onChange={(e) =>
- updateContextWindowField(e.target.value)
+ updateModelField("name", e.target.value)
}
- placeholder="65536"
/>
</div>
- <div className="rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/30 px-3.5 py-3">
- <div className="flex items-center justify-between gap-3">
- <div
- className={`${labelClass("lg")} text-[var(--muted-foreground)]/70`}
- >
- {t("Source")}
- </div>
- <span className="rounded-full border border-[var(--border)]/70 bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--foreground)]">
- {formatContextWindowSource(
- activeModel.context_window_source,
- t,
- )}
- </span>
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Model ID")}
</div>
- <p className="mt-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {activeModel.context_window_source ===
- "metadata"
- ? t(
- "Detected from the provider during the latest LLM test and saved into model_catalog.json.",
- )
- : activeModel.context_window_source ===
- "default"
- ? t(
- "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.",
- )
- : activeModel.context_window_source ===
- "manual"
+ <input
+ className={inputClass}
+ value={activeModel.model}
+ onChange={(e) =>
+ updateModelField("model", e.target.value)
+ }
+ placeholder="gpt-4o"
+ />
+ </div>
+ {activeService === "llm" && (
+ <>
+ <div>
+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t("Context Window")}
+ </div>
+ <input
+ className={inputClass}
+ inputMode="numeric"
+ value={activeModel.context_window || ""}
+ onChange={(e) =>
+ updateContextWindowField(e.target.value)
+ }
+ placeholder="65536"
+ />
+ </div>
+ <div className="rounded-xl border border-[var(--border)]/70 bg-[var(--muted)]/30 px-3.5 py-3">
+ <div className="flex items-center justify-between gap-3">
+ <div
+ className={`${labelClass("lg")} text-[var(--muted-foreground)]/70`}
+ >
+ {t("Source")}
+ </div>
+ <span className="rounded-full border border-[var(--border)]/70 bg-[var(--card)] px-2.5 py-1 text-[11px] font-medium text-[var(--foreground)]">
+ {formatContextWindowSource(
+ activeModel.context_window_source,
+ t,
+ )}
+ </span>
+ </div>
+ <p className="mt-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
+ {activeModel.context_window_source ===
+ "metadata"
? t(
- "Manual override from Settings. Save Draft to persist your edit.",
+ "Detected from the provider during the latest LLM test and saved into model_catalog.json.",
)
- : t(
- "Run the LLM test to auto-fill this field, or enter a value manually.",
- )}
- </p>
- {activeModel.context_window_detected_at && (
- <div className="mt-2 text-[11px] text-[var(--muted-foreground)]/70">
- {t("Detected at")}:{" "}
- {formatContextWindowUpdatedAt(
- activeModel.context_window_detected_at,
- language,
+ : activeModel.context_window_source ===
+ "default"
+ ? t(
+ "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.",
+ )
+ : activeModel.context_window_source ===
+ "manual"
+ ? t(
+ "Manual override from Settings. Save Draft to persist your edit.",
+ )
+ : t(
+ "Run the LLM test to auto-fill this field, or enter a value manually.",
+ )}
+ </p>
+ {activeModel.context_window_detected_at && (
+ <div className="mt-2 text-[11px] text-[var(--muted-foreground)]/70">
+ {t("Detected at")}:{" "}
+ {formatContextWindowUpdatedAt(
+ activeModel.context_window_detected_at,
+ language,
+ )}
+ </div>
)}
</div>
- )}
- </div>
- </>
- )}
- {activeService === "embedding" && (
- <div>
- <div className="mb-1.5 flex items-center justify-between gap-2">
- <span className="text-[12px] text-[var(--muted-foreground)]">
- {t("Dimension")}
- </span>
- <label className="inline-flex cursor-pointer items-center gap-1.5 text-[11px] text-[var(--muted-foreground)] select-none">
- <input
- type="checkbox"
- className="h-3 w-3 cursor-pointer accent-[var(--foreground)]"
- checked={
- activeModel.send_dimensions !== false
- }
- onChange={(e) =>
- updateModelBoolField(
- "send_dimensions",
- e.target.checked,
- )
+ </>
+ )}
+ {activeService === "embedding" && (
+ <div>
+ <div className="mb-1.5 flex items-center justify-between gap-2">
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ {t("Dimension")}
+ </span>
+ <label className="inline-flex cursor-pointer items-center gap-1.5 text-[11px] text-[var(--muted-foreground)] select-none">
+ <input
+ type="checkbox"
+ className="h-3 w-3 cursor-pointer accent-[var(--foreground)]"
+ checked={
+ activeModel.send_dimensions !== false
+ }
+ onChange={(e) =>
+ updateModelBoolField(
+ "send_dimensions",
+ e.target.checked,
+ )
+ }
+ />
+ <span>{t("Send dimensions")}</span>
+ <span
+ tabIndex={0}
+ className="group/info relative inline-flex cursor-help focus:outline-none"
+ >
+ <Info className="h-3 w-3 opacity-50 transition-opacity group-hover/info:opacity-100 group-focus/info:opacity-100" />
+ <span
+ role="tooltip"
+ className="pointer-events-none absolute top-full left-1/2 z-20 mt-1.5 w-64 -translate-x-1/2 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2.5 text-[11px] leading-relaxed text-[var(--foreground)] opacity-0 shadow-lg transition-opacity duration-75 group-hover/info:opacity-100 group-focus/info:opacity-100"
+ >
+ {t(
+ "Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.",
+ )}
+ </span>
+ </span>
+ </label>
+ </div>
+ <DimensionField
+ activeModel={activeModel}
+ activeBinding={activeProfile?.binding}
+ capabilities={embeddingCapabilities}
+ embeddingDefaultDim={embeddingDefaultDim}
+ inputClass={inputClass}
+ onChangeDimension={(value) =>
+ updateModelField("dimension", value)
}
/>
- <span>{t("Send dimensions")}</span>
- <span
- tabIndex={0}
- className="group/info relative inline-flex cursor-help focus:outline-none"
- >
- <Info className="h-3 w-3 opacity-50 transition-opacity group-hover/info:opacity-100 group-focus/info:opacity-100" />
- <span
- role="tooltip"
- className="pointer-events-none absolute top-full left-1/2 z-20 mt-1.5 w-64 -translate-x-1/2 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2.5 text-[11px] leading-relaxed text-[var(--foreground)] opacity-0 shadow-lg transition-opacity duration-75 group-hover/info:opacity-100 group-focus/info:opacity-100"
- >
- {t(
- "Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.",
- )}
- </span>
- </span>
- </label>
- </div>
- <DimensionField
- activeModel={activeModel}
- activeBinding={activeProfile?.binding}
- capabilities={embeddingCapabilities}
- embeddingDefaultDim={embeddingDefaultDim}
- inputClass={inputClass}
- onChangeDimension={(value) =>
- updateModelField("dimension", value)
- }
- />
+ </div>
+ )}
</div>
)}
</div>
)}
</div>
- )}
- </div>
- </div>
- ) : (
- <div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">
- {t("No profiles configured. Add a profile to start.")}
+ </div>
+ ) : (
+ <div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">
+ {t("No profiles configured. Add a profile to start.")}
+ </div>
+ )}
</div>
- )}
- </div>
- {/* ── Diagnostics ── */}
- <div className="mb-6 rounded-xl border border-[var(--border)]">
- <div className="flex items-center justify-between px-5 py-3.5">
- <button
- type="button"
- onClick={() => setDiagnosticsOpen((v) => !v)}
- className="flex min-w-0 flex-1 items-center gap-2 text-left"
- aria-expanded={diagnosticsOpen}
- >
- <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
- <span className="text-[13px] font-medium text-[var(--foreground)]">
- {t("Diagnostics")}
- </span>
- {testRunning && (
- <Loader2 className="h-3 w-3 animate-spin text-[var(--primary)]" />
+ {/* ── Diagnostics ── */}
+ <div className="mb-6 rounded-xl border border-[var(--border)]">
+ <div className="flex items-center justify-between px-5 py-3.5">
+ <button
+ type="button"
+ onClick={() => setDiagnosticsOpen((v) => !v)}
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ aria-expanded={diagnosticsOpen}
+ >
+ <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />
+ <span className="text-[13px] font-medium text-[var(--foreground)]">
+ {t("Diagnostics")}
+ </span>
+ {testRunning && (
+ <Loader2 className="h-3 w-3 animate-spin text-[var(--primary)]" />
+ )}
+ </button>
+ <div className="ml-3 flex items-center gap-3">
+ <button
+ type="button"
+ onClick={() => {
+ if (!diagnosticsOpen) setDiagnosticsOpen(true);
+ runDetailedTest();
+ }}
+ disabled={testRunning !== null}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
+ >
+ {serviceIcon(activeService)}
+ {t("Run test")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setDiagnosticsOpen((v) => !v)}
+ className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ aria-label={
+ diagnosticsOpen
+ ? t("Collapse diagnostics")
+ : t("Expand diagnostics")
+ }
+ aria-expanded={diagnosticsOpen}
+ >
+ <ChevronDown
+ className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`}
+ />
+ </button>
+ </div>
+ </div>
+ {diagnosticsOpen && (
+ <div className="border-t border-[var(--border)] px-5 py-4">
+ <p className="mb-3 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.",
+ { service: activeService },
+ )}
+ </p>
+ <pre className="max-h-[360px] overflow-y-auto rounded-lg bg-[#0f0f0f] p-4 font-mono text-[12px] leading-6 text-[#777] dark:bg-[#0a0a0a]">
+ {logs}
+ </pre>
+ </div>
)}
- </button>
- <div className="ml-3 flex items-center gap-3">
- <button
- type="button"
- onClick={() => {
- if (!diagnosticsOpen) setDiagnosticsOpen(true);
- runDetailedTest();
- }}
- disabled={testRunning !== null}
- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"
- >
- {serviceIcon(activeService)}
- {t("Run test")}
- </button>
- <button
- type="button"
- onClick={() => setDiagnosticsOpen((v) => !v)}
- className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
- aria-label={
- diagnosticsOpen
- ? t("Collapse diagnostics")
- : t("Expand diagnostics")
- }
- aria-expanded={diagnosticsOpen}
- >
- <ChevronDown
- className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`}
- />
- </button>
</div>
- </div>
- {diagnosticsOpen && (
- <div className="border-t border-[var(--border)] px-5 py-4">
- <p className="mb-3 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- {t(
- "Streams config snapshot, request target, response summary, and service-specific validation for the active {{service}} profile.",
- { service: activeService },
- )}
- </p>
- <pre className="max-h-[360px] overflow-y-auto rounded-lg bg-[#0f0f0f] p-4 font-mono text-[12px] leading-6 text-[#777] dark:bg-[#0a0a0a]">
- {logs}
- </pre>
- </div>
- )}
- </div>
- {/* ── Footer note ── */}
- <p className="mt-2 pb-4 text-[11px] leading-relaxed text-[var(--muted-foreground)]/40">
- {t("settings.configNote")}
- </p>
+ {/* ── Footer note ── */}
+ <p className="mt-2 pb-4 text-[11px] leading-relaxed text-[var(--muted-foreground)]/40">
+ {t("settings.configNote")}
+ </p>
</>
)}
</div>
{/* ── Spotlight overlay (tour onboarding) ── */}
- {catalogEditable === true && tourGuideStep >= 0 && tourGuideStep < TOUR_GUIDE_STEPS.length && (
- <SpotlightOverlay
- stepIndex={tourGuideStep}
- onNext={() => {
- if (tourGuideStep < TOUR_GUIDE_STEPS.length - 1) {
- setTourGuideStep((s) => s + 1);
- } else {
- setTourGuideStep(-1);
- }
- }}
- onSkip={() => setTourGuideStep(-1)}
- />
- )}
+ {catalogEditable === true &&
+ tourGuideStep >= 0 &&
+ tourGuideStep < TOUR_GUIDE_STEPS.length && (
+ <SpotlightOverlay
+ stepIndex={tourGuideStep}
+ onNext={() => {
+ if (tourGuideStep < TOUR_GUIDE_STEPS.length - 1) {
+ setTourGuideStep((s) => s + 1);
+ } else {
+ setTourGuideStep(-1);
+ }
+ }}
+ onSkip={() => setTourGuideStep(-1)}
+ />
+ )}
</div>
);
}
diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsx
index baae2d7d3..2297fb550 100644
--- a/web/app/(workspace)/agents/page.tsx
+++ b/web/app/(workspace)/agents/page.tsx
@@ -1504,7 +1504,9 @@ function ProfilesTab({
}),
});
if (tplRes.status === 409) {
- onToast(t("A soul with this id already exists, try another name"));
+ onToast(
+ t("A soul with this id already exists, try another name"),
+ );
return false;
}
if (!tplRes.ok) {
diff --git a/web/app/globals.css b/web/app/globals.css
index 744d3d33d..3772d5d3e 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -568,33 +568,33 @@
}
}
-/* Tooltip Component Styles */
-.tooltip-wrapper {
+/* Sidebar tooltip */
+.dt-tooltip-wrapper {
@apply relative inline-flex;
}
-.tooltip-content {
+.dt-tooltip-content {
@apply absolute z-50 rounded-lg bg-[var(--popover)] px-3 py-1.5 text-xs shadow-md text-[var(--popover-foreground)] pointer-events-none;
- animation: tooltip-fade-in 150ms ease-out;
+ animation: dt-tooltip-fade-in 150ms ease-out;
}
-.tooltip-label {
+.dt-tooltip-label {
@apply font-medium truncate;
}
-.tooltip-desc {
+.dt-tooltip-desc {
@apply mt-0.5 text-[11px] text-[var(--muted-foreground)] truncate;
}
-.tooltip-content[data-side="right"] {
+.dt-tooltip-content[data-side="right"] {
@apply left-full top-1/2 -translate-y-1/2 ml-2 max-w-[200px];
}
-.tooltip-content[data-side="bottom"] {
+.dt-tooltip-content[data-side="bottom"] {
@apply bottom-[-40px] left-1/2 -translate-x-1/2 max-w-[180px];
}
-@keyframes tooltip-fade-in {
+@keyframes dt-tooltip-fade-in {
from {
opacity: 0;
}
diff --git a/web/components/chat/home/ModelSelector.tsx b/web/components/chat/home/ModelSelector.tsx
index 502ea621c..d41a9e475 100644
--- a/web/components/chat/home/ModelSelector.tsx
+++ b/web/components/chat/home/ModelSelector.tsx
@@ -85,15 +85,15 @@ export default function ModelSelector({
: allowSystemDefault && !selectedSelection
? defaultLabel
: selectedOption?.model_name || t("Select model");
- const detail = selectedOption
- ? `${selectedOption.profile_name} | ${providerLabel(selectedOption)}`
- : allowSystemDefault && !selectedSelection
- ? defaultDetail
- : error
- ? t("Could not load models")
- : options.length === 0
- ? t("No configured models")
- : t("Choose a model");
+ const detail = (() => {
+ if (selectedOption) {
+ return `${selectedOption.profile_name} | ${providerLabel(selectedOption)}`;
+ }
+ if (allowSystemDefault && !selectedSelection) return defaultDetail;
+ if (error) return t("Could not load models");
+ if (options.length === 0) return t("No configured models");
+ return t("Choose a model");
+ })();
const menuPlacementClass =
placement === "bottom" ? "top-full mt-1.5" : "bottom-full mb-1.5";
diff --git a/web/components/knowledge/KnowledgeBaseListItem.tsx b/web/components/knowledge/KnowledgeBaseListItem.tsx
index be1e9832f..c13275b1f 100644
--- a/web/components/knowledge/KnowledgeBaseListItem.tsx
+++ b/web/components/knowledge/KnowledgeBaseListItem.tsx
@@ -117,7 +117,11 @@ export default function KnowledgeBaseListItem({
onDelete();
}}
disabled={kb.read_only}
- title={kb.read_only ? t("Assigned knowledge bases are read-only") : t("Delete")}
+ title={
+ kb.read_only
+ ? t("Assigned knowledge bases are read-only")
+ : t("Delete")
+ }
className="rounded p-1 text-[var(--muted-foreground)] hover:bg-red-50 hover:text-red-600 disabled:cursor-not-allowed disabled:opacity-30 dark:hover:bg-red-950/30"
>
<Trash2 className="h-3 w-3" />
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 98b71516f..305dab4a9 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -157,20 +157,19 @@ export function SidebarShell({
<nav className="flex w-full flex-col items-center gap-1 px-1.5">
{PRIMARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
- const tooltipProps = item.tooltipKey
- ? { description: t(item.tooltipKey) }
- : {}; // Pass description to tooltip if it exists
+ const description = item.tooltipKey
+ ? t(item.tooltipKey)
+ : undefined;
return (
<Tooltip
key={item.href}
label={t(item.label)}
+ description={description}
side="right"
- {...tooltipProps}
>
<Link
- key={item.href}
href={item.href}
- title={t(item.label) as string}
+ aria-label={t(item.label)}
className={`relative flex h-9 w-9 items-center justify-center rounded-xl transition-all duration-150 ${
active
? "bg-[var(--background)]/80 text-[var(--foreground)] shadow-sm"
diff --git a/web/components/space/MemorySection.tsx b/web/components/space/MemorySection.tsx
index 6943498f9..491e09457 100644
--- a/web/components/space/MemorySection.tsx
+++ b/web/components/space/MemorySection.tsx
@@ -153,7 +153,9 @@ export default function MemorySection() {
setEditors((prev) => ({ ...prev, [activeTab]: d[activeTab] || "" }));
setToast(t("{{label}} saved", { label: t(tab.label) }));
} catch (error) {
- setToast(error instanceof Error ? error.message : t("Memory save failed"));
+ setToast(
+ error instanceof Error ? error.message : t("Memory save failed"),
+ );
} finally {
setSaving(false);
}
diff --git a/web/components/ui/Tooltip.tsx b/web/components/ui/Tooltip.tsx
index c79851942..1140a3555 100644
--- a/web/components/ui/Tooltip.tsx
+++ b/web/components/ui/Tooltip.tsx
@@ -49,7 +49,7 @@ export function Tooltip({
return (
<div
- className="tooltip-wrapper"
+ className="dt-tooltip-wrapper"
onMouseEnter={showTooltip}
onMouseLeave={hideTooltip}
onFocus={showNow}
@@ -60,12 +60,12 @@ export function Tooltip({
{visible && (
<div
id={tooltipId}
- className="tooltip-content"
+ className="dt-tooltip-content"
data-side={side}
role="tooltip"
>
- <div className="tooltip-label">{label}</div>
- {description && <div className="tooltip-desc">{description}</div>}
+ <div className="dt-tooltip-label">{label}</div>
+ {description && <div className="dt-tooltip-desc">{description}</div>}
</div>
)}
</div>
diff --git a/web/features/multi-user/api.ts b/web/features/multi-user/api.ts
index 49780562e..ad57e6292 100644
--- a/web/features/multi-user/api.ts
+++ b/web/features/multi-user/api.ts
@@ -12,24 +12,37 @@ async function readError(res: Response, fallback: string): Promise<string> {
export async function fetchAdminResources(): Promise<MultiUserResources> {
const res = await apiFetch(apiUrl("/api/v1/multi-user/admin/resources"));
- if (!res.ok) throw new Error(await readError(res, "Failed to load assignable resources"));
+ if (!res.ok)
+ throw new Error(
+ await readError(res, "Failed to load assignable resources"),
+ );
return (await res.json()) as MultiUserResources;
}
export async function fetchUserGrant(userId: string): Promise<GrantPayload> {
- const res = await apiFetch(apiUrl(`/api/v1/multi-user/users/${encodeURIComponent(userId)}/grants`));
- if (!res.ok) throw new Error(await readError(res, "Failed to load user grant"));
+ const res = await apiFetch(
+ apiUrl(`/api/v1/multi-user/users/${encodeURIComponent(userId)}/grants`),
+ );
+ if (!res.ok)
+ throw new Error(await readError(res, "Failed to load user grant"));
const data = await res.json();
return data.grant as GrantPayload;
}
-export async function saveUserGrant(userId: string, grant: GrantPayload): Promise<GrantPayload> {
- const res = await apiFetch(apiUrl(`/api/v1/multi-user/users/${encodeURIComponent(userId)}/grants`), {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ grant }),
- });
- if (!res.ok) throw new Error(await readError(res, "Failed to save user grant"));
+export async function saveUserGrant(
+ userId: string,
+ grant: GrantPayload,
+): Promise<GrantPayload> {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/multi-user/users/${encodeURIComponent(userId)}/grants`),
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ grant }),
+ },
+ );
+ if (!res.ok)
+ throw new Error(await readError(res, "Failed to save user grant"));
const data = await res.json();
return data.grant as GrantPayload;
}
diff --git a/web/features/multi-user/components/AssignedBadge.tsx b/web/features/multi-user/components/AssignedBadge.tsx
index 4c3a3fe4f..5fb5847f0 100644
--- a/web/features/multi-user/components/AssignedBadge.tsx
+++ b/web/features/multi-user/components/AssignedBadge.tsx
@@ -1,4 +1,8 @@
-export function AssignedBadge({ label = "Assigned by admin" }: { label?: string }) {
+export function AssignedBadge({
+ label = "Assigned by admin",
+}: {
+ label?: string;
+}) {
return (
<span className="inline-flex items-center rounded-full border border-emerald-500/25 bg-emerald-500/10 px-2 py-0.5 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
{label}
diff --git a/web/features/multi-user/components/GrantEditor.tsx b/web/features/multi-user/components/GrantEditor.tsx
index 4a7132669..32354ced7 100644
--- a/web/features/multi-user/components/GrantEditor.tsx
+++ b/web/features/multi-user/components/GrantEditor.tsx
@@ -18,7 +18,12 @@ function emptyGrant(userId: string): GrantPayload {
};
}
-function hasModel(grant: GrantPayload, service: "llm" | "embedding" | "search", profileId: string, modelId?: string) {
+function hasModel(
+ grant: GrantPayload,
+ service: "llm" | "embedding" | "search",
+ profileId: string,
+ modelId?: string,
+) {
return grant.models[service].some((item) => {
if (item.profile_id !== profileId) return false;
if (!modelId) return true;
@@ -52,7 +57,9 @@ export function GrantEditor({ userId }: { userId: string }) {
})
.catch((error) => {
setSaveState("error");
- setMessage(error instanceof Error ? error.message : "Failed to load grants");
+ setMessage(
+ error instanceof Error ? error.message : "Failed to load grants",
+ );
})
.finally(() => {
if (!cancelled) setLoading(false);
@@ -63,14 +70,23 @@ export function GrantEditor({ userId }: { userId: string }) {
}, [userId]);
const currentFingerprint = useMemo(() => grantFingerprint(grant), [grant]);
- const dirty = Boolean(savedFingerprint) && currentFingerprint !== savedFingerprint;
+ const dirty =
+ Boolean(savedFingerprint) && currentFingerprint !== savedFingerprint;
const kbIds = useMemo(
- () => new Set(grant.knowledge_bases.map((item) => String(item.resource_id || item.id || ""))),
+ () =>
+ new Set(
+ grant.knowledge_bases.map((item) =>
+ String(item.resource_id || item.id || ""),
+ ),
+ ),
[grant.knowledge_bases],
);
const skillIds = useMemo(
- () => new Set(grant.skills.map((item) => String(item.skill_id || item.id || ""))),
+ () =>
+ new Set(
+ grant.skills.map((item) => String(item.skill_id || item.id || "")),
+ ),
[grant.skills],
);
@@ -80,7 +96,8 @@ export function GrantEditor({ userId }: { userId: string }) {
(total, service) =>
total +
grant.models[service].reduce((serviceTotal, item) => {
- if (Array.isArray(item.model_ids)) return serviceTotal + item.model_ids.length;
+ if (Array.isArray(item.model_ids))
+ return serviceTotal + item.model_ids.length;
return serviceTotal + 1;
}, 0),
0,
@@ -91,7 +108,11 @@ export function GrantEditor({ userId }: { userId: string }) {
const saving = saveState === "saving";
const controlsDisabled = loading || saving;
- function toggleModel(service: "llm" | "embedding" | "search", profileId: string, modelId?: string) {
+ function toggleModel(
+ service: "llm" | "embedding" | "search",
+ profileId: string,
+ modelId?: string,
+ ) {
setGrant((current) => {
const next = structuredClone(current) as GrantPayload;
const items = next.models[service];
@@ -103,14 +124,22 @@ export function GrantEditor({ userId }: { userId: string }) {
}
const existing = items.find((item) => item.profile_id === profileId);
if (!existing) {
- items.push({ profile_id: profileId, model_ids: [modelId], source: "admin" });
+ items.push({
+ profile_id: profileId,
+ model_ids: [modelId],
+ source: "admin",
+ });
return next;
}
- const modelIds = new Set(Array.isArray(existing.model_ids) ? existing.model_ids : []);
+ const modelIds = new Set(
+ Array.isArray(existing.model_ids) ? existing.model_ids : [],
+ );
if (modelIds.has(modelId)) modelIds.delete(modelId);
else modelIds.add(modelId);
existing.model_ids = Array.from(modelIds);
- next.models[service] = items.filter((item) => Array.isArray(item.model_ids) ? item.model_ids.length > 0 : true);
+ next.models[service] = items.filter((item) =>
+ Array.isArray(item.model_ids) ? item.model_ids.length > 0 : true,
+ );
return next;
});
}
@@ -120,8 +149,13 @@ export function GrantEditor({ userId }: { userId: string }) {
const next = structuredClone(current) as GrantPayload;
const exists = kbIds.has(resourceId);
next.knowledge_bases = exists
- ? next.knowledge_bases.filter((item) => String(item.resource_id || item.id || "") !== resourceId)
- : [...next.knowledge_bases, { resource_id: resourceId, name, access: "read", source: "admin" }];
+ ? next.knowledge_bases.filter(
+ (item) => String(item.resource_id || item.id || "") !== resourceId,
+ )
+ : [
+ ...next.knowledge_bases,
+ { resource_id: resourceId, name, access: "read", source: "admin" },
+ ];
return next;
});
}
@@ -131,7 +165,9 @@ export function GrantEditor({ userId }: { userId: string }) {
const next = structuredClone(current) as GrantPayload;
const exists = skillIds.has(name);
next.skills = exists
- ? next.skills.filter((item) => String(item.skill_id || item.id || "") !== name)
+ ? next.skills.filter(
+ (item) => String(item.skill_id || item.id || "") !== name,
+ )
: [...next.skills, { skill_id: name, access: "use", source: "admin" }];
return next;
});
@@ -192,7 +228,8 @@ export function GrantEditor({ userId }: { userId: string }) {
Assign access
</h2>
<p className="mt-0.5 text-xs text-[var(--muted-foreground)]">
- Admin resources stay linked server-side; users only receive allowed access.
+ Admin resources stay linked server-side; users only receive
+ allowed access.
</p>
</div>
<div className="flex flex-wrap gap-1.5 text-[11px] text-[var(--muted-foreground)]">
@@ -212,21 +249,44 @@ export function GrantEditor({ userId }: { userId: string }) {
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-5 [scrollbar-gutter:stable]">
<div className="grid gap-5 md:grid-cols-3">
<section className="min-w-0">
- <h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">Models</h3>
+ <h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ Models
+ </h3>
<div className="space-y-3 text-xs">
{(["llm", "embedding"] as const).map((service) => (
<div key={service} className="space-y-1.5">
- <div className="font-medium text-[var(--foreground)]">{service.toUpperCase()}</div>
+ <div className="font-medium text-[var(--foreground)]">
+ {service.toUpperCase()}
+ </div>
{(resources?.models[service] || []).map((profile) => (
- <div key={profile.profile_id} className="rounded-lg border border-[var(--border)]/60 p-2">
- <div className="mb-1 truncate text-[var(--muted-foreground)]">{profile.name}</div>
+ <div
+ key={profile.profile_id}
+ className="rounded-lg border border-[var(--border)]/60 p-2"
+ >
+ <div className="mb-1 truncate text-[var(--muted-foreground)]">
+ {profile.name}
+ </div>
{(profile.models || []).map((model) => (
- <label key={model.model_id} className="flex cursor-pointer items-center gap-2 py-1 text-[var(--foreground)]">
+ <label
+ key={model.model_id}
+ className="flex cursor-pointer items-center gap-2 py-1 text-[var(--foreground)]"
+ >
<input
type="checkbox"
- checked={hasModel(grant, service, profile.profile_id, model.model_id)}
+ checked={hasModel(
+ grant,
+ service,
+ profile.profile_id,
+ model.model_id,
+ )}
disabled={controlsDisabled}
- onChange={() => toggleModel(service, profile.profile_id, model.model_id)}
+ onChange={() =>
+ toggleModel(
+ service,
+ profile.profile_id,
+ model.model_id,
+ )
+ }
/>
<span className="truncate">{model.name}</span>
</label>
@@ -236,14 +296,21 @@ export function GrantEditor({ userId }: { userId: string }) {
</div>
))}
<div className="space-y-1.5">
- <div className="font-medium text-[var(--foreground)]">SEARCH</div>
+ <div className="font-medium text-[var(--foreground)]">
+ SEARCH
+ </div>
{(resources?.models.search || []).map((profile) => (
- <label key={profile.profile_id} className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--border)]/60 p-2 text-[var(--foreground)]">
+ <label
+ key={profile.profile_id}
+ className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--border)]/60 p-2 text-[var(--foreground)]"
+ >
<input
type="checkbox"
checked={hasModel(grant, "search", profile.profile_id)}
disabled={controlsDisabled}
- onChange={() => toggleModel("search", profile.profile_id)}
+ onChange={() =>
+ toggleModel("search", profile.profile_id)
+ }
/>
<span className="truncate">{profile.name}</span>
</label>
@@ -252,10 +319,15 @@ export function GrantEditor({ userId }: { userId: string }) {
</div>
</section>
<section className="min-w-0">
- <h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">Knowledge</h3>
+ <h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ Knowledge
+ </h3>
<div className="space-y-1.5 text-xs">
{(resources?.knowledge_bases || []).map((kb) => (
- <label key={kb.resource_id} className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--border)]/60 p-2 text-[var(--foreground)]">
+ <label
+ key={kb.resource_id}
+ className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--border)]/60 p-2 text-[var(--foreground)]"
+ >
<input
type="checkbox"
checked={kbIds.has(kb.resource_id)}
@@ -268,10 +340,15 @@ export function GrantEditor({ userId }: { userId: string }) {
</div>
</section>
<section className="min-w-0">
- <h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">Skills</h3>
+ <h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">
+ Skills
+ </h3>
<div className="space-y-1.5 text-xs">
{(resources?.skills || []).map((skill) => (
- <label key={skill.name} className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--border)]/60 p-2 text-[var(--foreground)]">
+ <label
+ key={skill.name}
+ className="flex cursor-pointer items-center gap-2 rounded-lg border border-[var(--border)]/60 p-2 text-[var(--foreground)]"
+ >
<input
type="checkbox"
checked={skillIds.has(skill.name)}
@@ -287,7 +364,10 @@ export function GrantEditor({ userId }: { userId: string }) {
</div>
<div className="flex shrink-0 items-center justify-between gap-3 border-t border-[var(--border)] bg-[var(--card)] px-5 py-3">
- <div aria-live="polite" className={`flex min-w-0 items-center gap-1.5 text-xs ${statusTone}`}>
+ <div
+ aria-live="polite"
+ className={`flex min-w-0 items-center gap-1.5 text-xs ${statusTone}`}
+ >
{saveState === "error" ? (
<AlertCircle className="h-3.5 w-3.5 shrink-0" />
) : saveState === "saved" && !dirty ? (
@@ -307,7 +387,11 @@ export function GrantEditor({ userId }: { userId: string }) {
) : (
<Save className="h-3 w-3" />
)}
- {saving ? "Saving..." : saveState === "saved" && !dirty ? "Saved" : "Save assignments"}
+ {saving
+ ? "Saving..."
+ : saveState === "saved" && !dirty
+ ? "Saved"
+ : "Save assignments"}
</button>
</div>
</div>
diff --git a/web/features/multi-user/components/ModelAccessSummary.tsx b/web/features/multi-user/components/ModelAccessSummary.tsx
index 77395cad2..a0a521ffc 100644
--- a/web/features/multi-user/components/ModelAccessSummary.tsx
+++ b/web/features/multi-user/components/ModelAccessSummary.tsx
@@ -17,9 +17,12 @@ export function ModelAccessSummary({ access }: { access: ModelAccess }) {
<div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5">
<div className="mb-2 flex items-center justify-between gap-3">
<div>
- <h2 className="text-[15px] font-semibold text-[var(--foreground)]">Model access</h2>
+ <h2 className="text-[15px] font-semibold text-[var(--foreground)]">
+ Model access
+ </h2>
<p className="mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">
- Your administrator manages these model endpoints. Keys stay on the server and are never shown here.
+ Your administrator manages these model endpoints. Keys stay on the
+ server and are never shown here.
</p>
</div>
<AssignedBadge />
@@ -28,7 +31,10 @@ export function ModelAccessSummary({ access }: { access: ModelAccess }) {
{rows.map(([key, label, Icon]) => {
const items = access[key] || [];
return (
- <div key={key} className="rounded-xl border border-[var(--border)]/70 bg-[var(--background)]/40 p-4">
+ <div
+ key={key}
+ className="rounded-xl border border-[var(--border)]/70 bg-[var(--background)]/40 p-4"
+ >
<div className="flex items-center gap-2 text-[12px] font-medium text-[var(--muted-foreground)]">
<Icon className="h-3.5 w-3.5" />
{label}
@@ -36,8 +42,13 @@ export function ModelAccessSummary({ access }: { access: ModelAccess }) {
{items.length ? (
<div className="mt-3 space-y-2">
{items.map((item, index) => (
- <div key={`${item.profile_id}-${item.model_id}-${index}`} className="text-[13px] text-[var(--foreground)]">
- <div className="truncate font-medium">{itemLabel(item)}</div>
+ <div
+ key={`${item.profile_id}-${item.model_id}-${index}`}
+ className="text-[13px] text-[var(--foreground)]"
+ >
+ <div className="truncate font-medium">
+ {itemLabel(item)}
+ </div>
<div className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">
{item.available === false ? "Unavailable" : "Ready"}
</div>
@@ -45,7 +56,9 @@ export function ModelAccessSummary({ access }: { access: ModelAccess }) {
))}
</div>
) : (
- <div className="mt-3 text-[12px] text-[var(--muted-foreground)]">Not assigned yet</div>
+ <div className="mt-3 text-[12px] text-[var(--muted-foreground)]">
+ Not assigned yet
+ </div>
)}
</div>
);
diff --git a/web/features/multi-user/types.ts b/web/features/multi-user/types.ts
index 0db41eb11..94dcfd6e9 100644
--- a/web/features/multi-user/types.ts
+++ b/web/features/multi-user/types.ts
@@ -29,10 +29,22 @@ export type GrantPayload = {
export type MultiUserResources = {
models: {
- llm: Array<{ profile_id: string; name: string; models?: Array<{ model_id: string; name: string; model?: string }> }>;
- embedding: Array<{ profile_id: string; name: string; models?: Array<{ model_id: string; name: string; model?: string }> }>;
+ llm: Array<{
+ profile_id: string;
+ name: string;
+ models?: Array<{ model_id: string; name: string; model?: string }>;
+ }>;
+ embedding: Array<{
+ profile_id: string;
+ name: string;
+ models?: Array<{ model_id: string; name: string; model?: string }>;
+ }>;
search: Array<{ profile_id: string; name: string; provider?: string }>;
};
- knowledge_bases: Array<{ resource_id: string; name: string; source: "admin" }>;
+ knowledge_bases: Array<{
+ resource_id: string;
+ name: string;
+ source: "admin";
+ }>;
skills: Array<{ name: string; description?: string; tags?: string[] }>;
};
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index 47c73815d..fe162882a 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -63,9 +63,12 @@ export async function listRagProviders(options?: { force?: boolean }) {
return withClientCache<RagProviderSummary[]>(
`${KNOWLEDGE_CACHE_PREFIX}providers`,
async () => {
- const response = await apiFetch(apiUrl("/api/v1/knowledge/rag-providers"), {
- cache: "no-store",
- });
+ const response = await apiFetch(
+ apiUrl("/api/v1/knowledge/rag-providers"),
+ {
+ cache: "no-store",
+ },
+ );
const data = await response.json();
return Array.isArray(data?.providers) ? data.providers : [];
},
diff --git a/web/next.config.js b/web/next.config.js
index b4a5d9dd8..498b9dd74 100644
--- a/web/next.config.js
+++ b/web/next.config.js
@@ -14,7 +14,10 @@ function parseDotenvFile(filePath) {
.map((line) => {
const idx = line.indexOf("=");
const key = line.slice(0, idx).trim();
- const value = line.slice(idx + 1).trim().replace(/^['"]|['"]$/g, "");
+ const value = line
+ .slice(idx + 1)
+ .trim()
+ .replace(/^['"]|['"]$/g, "");
return [key, value];
}),
);