DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
prepare v1.3.10 release
Bingxi Zhao (Frank)ac8f00bd65a6
diff --git a/.env.example b/.env.exampleindex ecde8bbae..1b817f9d2 100644--- a/.env.example+++ b/.env.example@@ -127,9 +127,12 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=# from http://localhost:${BACKEND_PORT}. Leave blank for the standard# local setup.NEXT_PUBLIC_API_BASE=-# Optional extra origin appended to the FastAPI CORS allowlist (e.g. a-# custom domain). localhost / 127.0.0.1 / Docker hosts are always allowed.+# Optional extra origin(s) appended to the FastAPI CORS allowlist (e.g. a+# custom domain). Use CORS_ORIGINS for comma/newline-separated lists.+# localhost / 127.0.0.1 are always allowed. When AUTH_ENABLED=false,+# other http(s) browser origins are allowed for local/single-user Docker use.CORS_ORIGIN=+CORS_ORIGINS=# ---------------------------------------------------------------------# 6. Securitydiff --git a/README.md b/README.mdindex 549c8b6d6..3300eba0d 100644--- a/README.md+++ b/README.md@@ -28,6 +28,8 @@### 📦 Releases+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Remote Docker CORS recovery, `DISABLE_SSL_VERIFY` across SDK providers, safer code-block citations, and optional Matrix E2EE add-on.+> **[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.@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Versioned KB indexes with re-index workflow, rebuilt Knowledge workspace, embedding auto-discovery with new adapters, Space hub.+<details>+<summary><b>Past releases (more than 2 weeks ago)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Persistent chat attachments with file-preview drawer, attachment-aware capability pipelines, TutorBot Markdown export.> **[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.-<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.@@ -195,7 +197,7 @@ During the install step, the tour asks which dependency profile you want:|:---|:---|:---|| Web app (recommended) | CLI + API server + RAG/document parsing | Most first-time users || Web + TutorBot | Adds TutorBot engine and common channel SDKs | If you want autonomous tutor bots or channel integrations |-| Web + TutorBot + Matrix | Adds Matrix / Element channel support | Only if you already have `libolm` installed or are ready to install it |+| Web + TutorBot + Matrix | Adds Matrix / Element channel support without E2EE | If you need Matrix/Element rooms; install `matrix-e2e` only for encrypted rooms || Math Animator add-on | Installs Manim separately | Only if you need animation generation and have LaTeX/ffmpeg/system build tools ready |Once the wizard finishes:@@ -256,7 +258,8 @@ python -m pip install -e ".[server]"# Optional add-ons — install only the ones you need:# python -m pip install -e ".[tutorbot]" # TutorBot engine + channel SDKs-# python -m pip install -e ".[tutorbot,matrix]" # TutorBot + Matrix channel; requires libolm+# python -m pip install -e ".[tutorbot,matrix]" # TutorBot + Matrix channel without E2EE/libolm+# python -m pip install -e ".[matrix-e2e]" # Optional encrypted Matrix rooms; requires libolm# python -m pip install -e ".[math-animator]" # Manim; also requires LaTeX/ffmpeg/system build tools# python -m pip install -e ".[all]" # Everything above + dev tools@@ -590,7 +593,8 @@ These directories survive `docker compose down` and are reused on the next `dock| `POCKETBASE_PORT` | No | Docker port mapping for the optional PocketBase sidecar (default `8090`) || `NEXT_PUBLIC_API_BASE_EXTERNAL` | No | Public backend URL for cloud deployment || `NEXT_PUBLIC_API_BASE` | No | Direct backend URL override for the Next.js client |-| `CORS_ORIGIN` | No | Extra origin appended to the FastAPI CORS allowlist |+| `CORS_ORIGIN` | No | Single extra origin appended to the FastAPI CORS allowlist |+| `CORS_ORIGINS` | No | Comma/newline-separated extra origins for authenticated remote deployments || `DISABLE_SSL_VERIFY` | No | Disable outbound TLS verification (default `false`) || `AUTH_ENABLED` | No | Require login when `true` (default `false`) || `NEXT_PUBLIC_AUTH_ENABLED` | No | Optional frontend override; blank derives from `AUTH_ENABLED` |diff --git a/assets/README/README_AR.md b/assets/README/README_AR.mdindex 0036d6b89..62157c004 100644--- a/assets/README/README_AR.md+++ b/assets/README/README_AR.md@@ -28,6 +28,8 @@### 📦 الإصدارات+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — إصلاح CORS في Docker البعيد، وتفعيل `DISABLE_SSL_VERIFY` عبر مزوّدي SDK، وحماية اقتباسات كتل الكود، وجعل Matrix E2EE إضافة اختيارية.+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — دعم TutorBot لقناتي Zulip وNVIDIA NIM، توجيه أكثر أمانًا لنماذج التفكير، أمر `deeptutor start`، تلميحات الشريط الجانبي، وتكافؤ مخزن الجلسات.> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — نشر اختياري متعدد المستخدمين مع مساحات عمل معزولة، صلاحيات يديرها المسؤول، مسارات مصادقة، ووصول runtime محدود النطاق.@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — فهارس KB ذات إصدار مع سير إعادة الفهرسة، إعادة بناء مساحة المعرفة، اكتشاف تلقائي للتضمين مع محولات جديدة، مركز Space.+<details>+<summary><b>إصدارات أقدم (أكثر من أسبوعين)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — مرفقات دردشة دائمة مع درج معاينة الملفات، خطوط أنابيب قدرات تدرك المرفقات، تصدير Markdown لـ TutorBot.> **[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، واجهة مكتبة الكتب، تصور بملء الشاشة.diff --git a/assets/README/README_CN.md b/assets/README/README_CN.mdindex 76e4de54b..6e6ebfca4 100644--- a/assets/README/README_CN.md+++ b/assets/README/README_CN.md@@ -28,6 +28,8 @@### 📦 版本发布+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — 修复远程 Docker CORS、SDK Provider 的 `DISABLE_SSL_VERIFY`、代码块引用误注入,并将 Matrix E2EE 改为可选扩展。+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot 支持 Zulip 与 NVIDIA NIM,思考模型路由更安全,新增 `deeptutor start`,侧栏提示与会话存储一致性提升。> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — 可选多用户部署,隔离用户工作区、管理员授权、认证路由与作用域运行时访问。@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — 版本化知识库索引与重建工作流,知识工作区重构,嵌入自动发现与新适配器,Space 枢纽。+<details>+<summary><b>更早发布(两周以前)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — 聊天附件持久化与文件预览抽屉,感知附件的能力流水线,TutorBot Markdown 导出。> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — 文本/代码/SVG 附件,一键 Setup Tour,Markdown 聊天导出,紧凑知识库管理界面。-<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,可视化全屏。@@ -196,7 +198,7 @@ python scripts/start_tour.py|:---|:---|:---|| Web app(推荐) | CLI + API + RAG/文档解析 | 大多数首次用户 || Web + TutorBot | 增加 TutorBot 与常见频道 SDK | 需要自主导师或频道集成 |-| Web + TutorBot + Matrix | Matrix/Element | 已安装或愿意安装 `libolm` 时 |+| Web + TutorBot + Matrix | 非 E2EE Matrix/Element | 需要 Matrix/Element 房间;加密房间再单独安装 `matrix-e2e` || 数学动画扩展 | 单独安装 Manim | 需要动画且已备好 LaTeX/ffmpeg 等 |向导结束后:@@ -233,7 +235,8 @@ python -m pip install -e ".[server]"# 可选扩展(按需):# python -m pip install -e ".[tutorbot]"-# python -m pip install -e ".[tutorbot,matrix]" # 需要 libolm+# python -m pip install -e ".[tutorbot,matrix]" # 非 E2EE Matrix,无需 libolm+# python -m pip install -e ".[matrix-e2e]" # 加密 Matrix 房间;需要 libolm# python -m pip install -e ".[math-animator]"# python -m pip install -e ".[all]"@@ -543,7 +546,8 @@ FRONTEND_PORT=4000| `POCKETBASE_PORT` | 否 | 可选 PocketBase 侧车在 Docker 中的端口映射(默认 `8090`) || `NEXT_PUBLIC_API_BASE_EXTERNAL` | 否 | 云端部署时对外可访问的后端 URL || `NEXT_PUBLIC_API_BASE` | 否 | Next.js 客户端直连后端的 URL 覆盖 |-| `CORS_ORIGIN` | 否 | 追加到 FastAPI CORS 允许列表的额外 Origin |+| `CORS_ORIGIN` | 否 | 追加到 FastAPI CORS 允许列表的单个额外 Origin |+| `CORS_ORIGINS` | 否 | 认证远程部署可用的逗号/换行分隔额外 Origins || `DISABLE_SSL_VERIFY` | 否 | 关闭出站 TLS 校验(默认 `false`) || `AUTH_ENABLED` | 否 | 为 `true` 时要求登录(默认 `false`) || `NEXT_PUBLIC_AUTH_ENABLED` | 否 | 前端可选覆盖;留空则从 `AUTH_ENABLED` 推导 |diff --git a/assets/README/README_ES.md b/assets/README/README_ES.mdindex b5b99444a..5d80cd32e 100644--- a/assets/README/README_ES.md+++ b/assets/README/README_ES.md@@ -28,6 +28,8 @@### 📦 Lanzamientos+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Corrección de CORS en Docker remoto, `DISABLE_SSL_VERIFY` en proveedores SDK, citas seguras en bloques de código y E2EE de Matrix como complemento opcional.+> **[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.@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Índices KB versionados y flujo de reindexación, espacio de conocimiento rehecho, autodetección de embeddings, hub Space.+<details>+<summary><b>Lanzamientos anteriores (más de 2 semanas)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Adjuntos persistentes y cajón de vista previa, pipelines conscientes de adjuntos, exportación Markdown de TutorBot.> **[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.diff --git a/assets/README/README_FR.md b/assets/README/README_FR.mdindex eee926b14..16fb146a8 100644--- a/assets/README/README_FR.md+++ b/assets/README/README_FR.md@@ -28,6 +28,8 @@### 📦 Versions+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Correction du CORS Docker distant, `DISABLE_SSL_VERIFY` pour les fournisseurs SDK, citations sûres dans les blocs de code, et E2EE Matrix en extension optionnelle.+> **[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é.@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Index KB versionnés et flux de réindexation, espace connaissances refait, auto-détection d’embeddings, hub Space.+<details>+<summary><b>Anciennes versions (plus de 2 semaines)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Pièces jointes persistantes et tiroir d’aperçu, pipelines sensibles aux PJ, export Markdown TutorBot.> **[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.diff --git a/assets/README/README_HI.md b/assets/README/README_HI.mdindex 908e06bbe..54ec91a84 100644--- a/assets/README/README_HI.md+++ b/assets/README/README_HI.md@@ -28,6 +28,8 @@### 📦 रिलीज़+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Remote Docker CORS, SDK providers में `DISABLE_SSL_VERIFY`, code-block citations ठीक हुए; Matrix E2EE अब optional add-on है।+> **[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।@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — संस्करणित KB इंडेक्स व पुनः-अनुक्रमण वर्कफ़्लो, नॉलेज वर्कस्पेस पुनर्निर्माण, नए अडैप्टर के साथ एम्बेडिंग ऑटो-डिस्कवरी, Space हब।+<details>+<summary><b>पुराने रिलीज़ (2 सप्ताह से अधिक पहले)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — फ़ाइल-पूर्वावलोकन दराज के साथ स्थायी चैट संलग्नक, संलग्नक-जागरूक क्षमता पाइपलाइन, TutorBot Markdown निर्यात।> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — टेक्स्ट / कोड / SVG संलग्नक, एक-कमांड सेटअप टूर, 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, विज़ुअलाइज़ेशन फ़ुलस्क्रीन।diff --git a/assets/README/README_JA.md b/assets/README/README_JA.mdindex 4a4d3dc61..b3b160d26 100644--- a/assets/README/README_JA.md+++ b/assets/README/README_JA.md@@ -28,6 +28,8 @@### 📦 リリース+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — リモート Docker の CORS、SDK Provider の `DISABLE_SSL_VERIFY`、コードブロックの引用誤変換を修正し、Matrix E2EE を任意アドオン化。+> **[2026.5.9]** [v1.3.9](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.9) — TutorBot の Zulip/NVIDIA NIM 対応、思考モデルルーティングの安全化、`deeptutor start`、サイドバーツールチップ、セッションストア整合性。> **[2026.5.8]** [v1.3.8](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.8) — 任意のマルチユーザー展開、分離されたユーザーワークスペース、管理者権限付与、認証ルート、スコープ付き実行時アクセス。@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — バージョン管理付き KB インデックスと再インデックスワークフロー、ナレッジワークスペース再設計、埋め込み自動検出と新アダプター、Space ハブ。+<details>+<summary><b>過去のリリース(2週間以上前)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — チャット添付ファイルの永続化とファイルプレビュードロワー、添付ファイル対応機能パイプライン、TutorBot Markdown エクスポート。> **[2026.4.25]** [v1.2.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.4) — テキスト/コード/SVG 添付ファイル、一コマンド Setup Tour、Markdown チャットエクスポート、コンパクトな 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、ビジュアライゼーション全画面表示。diff --git a/assets/README/README_PL.md b/assets/README/README_PL.mdindex e49ce0046..a3857bfc3 100644--- a/assets/README/README_PL.md+++ b/assets/README/README_PL.md@@ -28,6 +28,8 @@### 📦 Wydania+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Poprawki CORS dla zdalnego Dockera, `DISABLE_SSL_VERIFY` w providerach SDK, cytowań w blokach kodu oraz Matrix E2EE jako opcjonalny dodatek.+> **[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.@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Wersjonowane indeksy KB z przepływem ponownej indeksacji, przebudowana przestrzeń wiedzy, automatyczne wykrywanie embeddingów z nowymi adapterami, hub Space.+<details>+<summary><b>Starsze wydania (ponad 2 tygodnie temu)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Trwałe załączniki czatu z szufladą podglądu plików, potoki zdolności świadome załączników, eksport Markdown TutorBot.> **[2026.4.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.diff --git a/assets/README/README_PT.md b/assets/README/README_PT.mdindex 9ceab420e..429cdcb82 100644--- a/assets/README/README_PT.md+++ b/assets/README/README_PT.md@@ -28,6 +28,8 @@### 📦 Lançamentos+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Correção de CORS em Docker remoto, `DISABLE_SSL_VERIFY` nos provedores SDK, citações seguras em blocos de código e E2EE do Matrix como add-on opcional.+> **[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.@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Índices KB versionados com fluxo de reindexação, espaço de conhecimento reconstruído, autodetecção de embeddings com novos adaptadores, hub Space.+<details>+<summary><b>Lançamentos anteriores (há mais de 2 semanas)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Anexos de chat persistentes com gaveta de pré-visualização, pipelines de capacidade cientes de anexos, exportação Markdown do TutorBot.> **[2026.4.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.diff --git a/assets/README/README_RU.md b/assets/README/README_RU.mdindex 60445c853..d35d8ac32 100644--- a/assets/README/README_RU.md+++ b/assets/README/README_RU.md@@ -28,6 +28,8 @@### 📦 Релизы+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — Исправлены CORS для удалённого Docker, `DISABLE_SSL_VERIFY` в SDK-провайдерах, цитаты в блоках кода; Matrix E2EE стал опциональным аддоном.+> **[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.@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — Версионированные индексы KB с процессом переиндексации, перестроенное рабочее пространство знаний, автообнаружение эмбеддингов с новыми адаптерами, хаб Space.+<details>+<summary><b>Прошлые релизы (более 2 недель назад)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — Постоянные вложения в чате с ящиком предпросмотра, пайплайны возможностей с учётом вложений, экспорт Markdown для TutorBot.> **[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 библиотеки книг, полноэкранные визуализации.diff --git a/assets/README/README_TH.md b/assets/README/README_TH.mdindex b60217a7c..7bd546603 100644--- a/assets/README/README_TH.md+++ b/assets/README/README_TH.md@@ -28,6 +28,8 @@### 📦 ประวัติการเผยแพร่+> **[2026.5.10]** [v1.3.10](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.10) — แก้ CORS สำหรับ Docker ระยะไกล, `DISABLE_SSL_VERIFY` ใน SDK providers, citation ใน code block และแยก Matrix E2EE เป็น add-on+> **[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@@ -48,13 +50,13 @@> **[2026.4.27]** [v1.3.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.0) — ดัชนี KB แบบมีเวอร์ชันพร้อมเวิร์กโฟลว์ re-index, รีบิลด์ Knowledge workspace, embedding auto-discovery กับอะแดปเตอร์ใหม่, Space hub+<details>+<summary><b>รุ่นที่ผ่านมา (มากกว่า 2 สัปดาห์ที่แล้ว)</b></summary>+> **[2026.4.25]** [v1.2.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.5) — แนบไฟล์ในแชตถาวรพร้อมลิ้นชักพรีวิว, pipeline ความสามารถที่รับรู้แนบไฟล์, ส่งออก Markdown ของ TutorBot> **[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 ห้องสมุดหนังสือ, โหมดเต็มจอของการแสดงผลdiff --git a/assets/releases/ver1-3-10.md b/assets/releases/ver1-3-10.mdnew file mode 100644index 000000000..9ea91f17e--- /dev/null+++ b/assets/releases/ver1-3-10.md@@ -0,0 +1,93 @@+# DeepTutor v1.3.10 Release Notes++**Release Date:** 2026.05.10++v1.3.10 is a focused reliability release for the issues reported after v1.3.9.+It restores smoother remote Docker access, makes self-signed LLM endpoints work+consistently across SDK-backed providers, protects code snippets from citation+rewrites, and splits Matrix E2EE into an explicit opt-in dependency.++## Highlights++### Remote Docker and CORS Recovery++- **Remote single-user Docker works out of the box again** - when+ `AUTH_ENABLED=false`, DeepTutor now accepts browser origins over HTTP/HTTPS so+ LAN or remote-server frontends no longer hit the v1.3.8/v1.3.9 CORS+ regression reported in #463.+- **Authenticated deployments stay explicit** - when `AUTH_ENABLED=true`, CORS+ still requires a concrete allowlist through `CORS_ORIGIN` or `CORS_ORIGINS`,+ preserving the credentialed-auth safety boundary.+- **Multiple deployment origins are supported** - `CORS_ORIGINS` accepts comma+ or newline separated values, and both Docker Compose files pass the setting+ through to the backend container.+- **Settings no longer drop network flags** - `CORS_ORIGIN`, `CORS_ORIGINS`, and+ `DISABLE_SSL_VERIFY` are part of the canonical `.env` write order.++### Provider TLS and Rendering Fixes++- **`DISABLE_SSL_VERIFY` now reaches OpenAI SDK paths** - OpenAI-compatible,+ Azure OpenAI, executor, TutorBot, and legacy embedding SDK clients all receive+ a shared `httpx.AsyncClient(verify=False)` when the flag is enabled, fixing+ self-signed HTTPS LLM endpoints reported in #464.+- **Production still blocks unsafe TLS bypasses** - `ENVIRONMENT=prod` or+ `ENVIRONMENT=production` rejects `DISABLE_SSL_VERIFY`, with a single warning+ logged in non-production use.+- **Code blocks keep array indexes intact** - Markdown citation linkification now+ masks fenced and inline code before rewriting references, so `values[0]` stays+ code instead of becoming a `#references` citation link (#468).++### Matrix Install Compatibility++- **Matrix no longer installs E2EE by default** - the standard `matrix` extra and+ `requirements/matrix.txt` now use plain `matrix-nio`, avoiding the+ `python-olm` / `libolm` build failures seen on macOS Python 3.14 and Apple+ Clang 21 (#462).+- **Encrypted rooms are an explicit add-on** - install `deeptutor[matrix-e2e]`+ or `requirements/matrix-e2e.txt` when E2EE support is needed and libolm is+ available.+- **Runtime failures are clearer** - Matrix defaults to non-E2EE mode, and+ enabling E2EE without crypto dependencies now raises an actionable install+ message instead of failing at import time.++### Multi-User Runtime Compatibility++- **Default workspace paths stay stable outside user scope** - when no current+ multi-user context is active, path resolution falls back to the default data+ workspace rather than forcing an admin scope.+- **Legacy test and monkeypatch hooks remain available** - session and settings+ routers keep compatibility shims used by tests and older integrations.+- **Local agent artifacts are ignored** - `.claude/` is now excluded from Git so+ local worktrees and agent metadata do not accidentally enter releases.++## Tests++- Added CORS setting tests for unauthenticated remote origins and authenticated+ explicit allowlists.+- Added shared OpenAI SDK HTTP-client tests across provider-core, Azure,+ executors, TutorBot, and embedding adapters.+- Added Markdown display tests for prose citations, fenced code, inline code,+ and explicit backticked citations.+- Added Matrix dependency split tests to keep default installs free of+ `matrix-nio[e2e]`.+- Re-ran targeted Python tests, web node tests, Ruff checks, and diff whitespace+ validation for the release patch.++## Upgrade Notes++- If you run remote Docker with `AUTH_ENABLED=false`, no extra CORS setting is+ required for normal HTTP/HTTPS browser origins.+- If you run a shared or authenticated deployment with `AUTH_ENABLED=true`, set+ `CORS_ORIGIN` or `CORS_ORIGINS` to the exact frontend origin(s), for example+ `https://learn.example.com`.+- Use `DISABLE_SSL_VERIFY=true` only for local, self-signed, or air-gapped test+ LLM endpoints. It remains blocked in `ENVIRONMENT=prod` and+ `ENVIRONMENT=production`.+- Matrix installs are now non-E2EE by default. For encrypted Matrix rooms,+ install `.[matrix-e2e]` or `requirements/matrix-e2e.txt`, ensure libolm is+ present, and set `e2ee_enabled=true` in the Matrix channel config.+- If you previously installed `.[matrix]` only to get non-encrypted Matrix+ messaging, reinstalling after this release should no longer require native+ libolm build tooling.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.9...v1.3.10diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex c4689f844..ab87722f9 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -44,6 +44,7 @@ CONFIG_DRIFT_ERROR_TEMPLATE = ("registered in the runtime tool registry. Register the missing tools or ""remove the stale tool names from the capability manifests.")+TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}class SafeOutputStaticFiles(StaticFiles):@@ -87,6 +88,48 @@ def validate_tool_consistency():raise+def _env_truthy(value: str | None) -> bool:+ return str(value or "").strip().lower() in TRUTHY_ENV_VALUES+++def _split_origins(value: str | None) -> list[str]:+ if not value:+ return []+ origins: list[str] = []+ seen: set[str] = set()+ for raw in value.replace("\n", ",").split(","):+ origin = raw.strip().rstrip("/")+ if not origin or origin in seen:+ continue+ origins.append(origin)+ seen.add(origin)+ return origins+++def _build_cors_settings() -> dict[str, object]:+ """Build CORS settings for both localhost and remote Docker deployments."""+ frontend_port = os.getenv("FRONTEND_PORT", "3782").strip() or "3782"+ extra_origins = _split_origins(os.getenv("CORS_ORIGIN")) + _split_origins(+ os.getenv("CORS_ORIGINS")+ )+ origins = [+ f"http://localhost:{frontend_port}",+ f"http://127.0.0.1:{frontend_port}",+ "http://localhost:3000",+ "http://127.0.0.1:3000",+ ]+ for origin in extra_origins:+ if origin not in origins:+ origins.append(origin)++ # Auth is disabled by default. In that local/single-user mode, mirror the+ # pre-v1.3.8 behavior and allow remote Docker/LAN origins out of the box.+ # When auth is enabled, require explicit CORS_ORIGIN(S) for credentialed+ # cross-origin requests.+ allow_origin_regex = None if _env_truthy(os.getenv("AUTH_ENABLED")) else r"https?://.*"+ return {"allow_origins": origins, "allow_origin_regex": allow_origin_regex}++@asynccontextmanagerasync def lifespan(app: FastAPI):"""@@ -188,24 +231,11 @@ async def selective_access_log(request, call_next):return response-# Configure CORS.-# allow_origins=["*"] is incompatible with allow_credentials=True (browsers reject it).-# We build an explicit list that covers both localhost and 127.0.0.1 variants so the-# frontend works regardless of which loopback alias the browser resolves to.-_frontend_port = os.getenv("FRONTEND_PORT", "3782")-_extra_origin = os.getenv("CORS_ORIGIN", "") # optional extra origin for deployments-_cors_origins = [- f"http://localhost:{_frontend_port}",- f"http://127.0.0.1:{_frontend_port}",- "http://localhost:3000", # common Next.js default- "http://127.0.0.1:3000",-]-if _extra_origin:- _cors_origins.append(_extra_origin)-+_cors_settings = _build_cors_settings()app.add_middleware(CORSMiddleware,- allow_origins=_cors_origins,+ allow_origins=_cors_settings["allow_origins"],+ allow_origin_regex=_cors_settings["allow_origin_regex"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],diff --git a/deeptutor/services/config/env_store.py b/deeptutor/services/config/env_store.pyindex f02f7080a..ddaae505f 100644--- a/deeptutor/services/config/env_store.py+++ b/deeptutor/services/config/env_store.py@@ -15,6 +15,9 @@ ENV_KEY_ORDER = ("FRONTEND_PORT","NEXT_PUBLIC_API_BASE_EXTERNAL","NEXT_PUBLIC_API_BASE",+ "CORS_ORIGIN",+ "CORS_ORIGINS",+ "DISABLE_SSL_VERIFY","AUTH_ENABLED","AUTH_SECRET","AUTH_TOKEN_EXPIRE_HOURS",diff --git a/deeptutor/services/embedding/adapters/openai_sdk.py b/deeptutor/services/embedding/adapters/openai_sdk.pyindex e0b553dec..7dbf246ca 100644--- a/deeptutor/services/embedding/adapters/openai_sdk.py+++ b/deeptutor/services/embedding/adapters/openai_sdk.py@@ -12,6 +12,8 @@ from typing import Any, Dictfrom openai import APIConnectionError, APIError, APIStatusError, AsyncOpenAI+from deeptutor.services.llm.openai_http_client import openai_client_kwargs+from .base import (BaseEmbeddingAdapter,EmbeddingProviderError,@@ -57,6 +59,7 @@ class OpenAISDKEmbeddingAdapter(BaseEmbeddingAdapter):else None),max_retries=2,+ **openai_client_kwargs(timeout=max(self.request_timeout, 60)),)async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:diff --git a/deeptutor/services/llm/executors.py b/deeptutor/services/llm/executors.pyindex 3c90d3964..a93fb6c2b 100644--- a/deeptutor/services/llm/executors.py+++ b/deeptutor/services/llm/executors.py@@ -11,6 +11,7 @@ import uuidfrom openai import AsyncOpenAI, BadRequestErrorfrom deeptutor.services.llm.capabilities import disable_response_format_at_runtime+from deeptutor.services.llm.openai_http_client import openai_client_kwargsfrom deeptutor.services.llm.provider_registry import find_by_name, strip_provider_prefixfrom .config import get_token_limit_kwargs@@ -156,6 +157,7 @@ async def sdk_complete(base_url=effective_base,default_headers=default_headers,max_retries=0,+ **openai_client_kwargs(),)max_tokens_val = _coerce_int(kwargs.pop("max_tokens", 4096), 4096)@@ -222,6 +224,7 @@ async def sdk_stream(base_url=effective_base,default_headers=default_headers,max_retries=0,+ **openai_client_kwargs(),)max_tokens_val = _coerce_int(kwargs.pop("max_tokens", 4096), 4096)diff --git a/deeptutor/services/llm/openai_http_client.py b/deeptutor/services/llm/openai_http_client.pynew file mode 100644index 000000000..22e7aa6aa--- /dev/null+++ b/deeptutor/services/llm/openai_http_client.py@@ -0,0 +1,59 @@+"""HTTP client helpers for OpenAI-compatible SDK providers."""++from __future__ import annotations++import logging+import os+import threading+from typing import Any++import httpx++from deeptutor.services.llm.exceptions import LLMConfigError++logger = logging.getLogger(__name__)++_TRUTHY = {"1", "true", "yes", "on"}+_warning_lock = threading.Lock()+_warning_logged = False+++def _env_truthy(name: str) -> bool:+ return os.getenv(name, "").strip().lower() in _TRUTHY+++def disable_ssl_verify_enabled() -> bool:+ """Return whether outbound TLS verification should be disabled."""+ if not _env_truthy("DISABLE_SSL_VERIFY"):+ return False+ if os.getenv("ENVIRONMENT", "").strip().lower() in {"prod", "production"}:+ raise LLMConfigError("DISABLE_SSL_VERIFY is not allowed in production")+ global _warning_logged+ with _warning_lock:+ if not _warning_logged:+ logger.warning(+ "SSL verification is disabled via DISABLE_SSL_VERIFY. This is unsafe "+ "and must not be used in production environments."+ )+ _warning_logged = True+ return True+++def build_openai_http_client(**kwargs: Any) -> httpx.AsyncClient | None:+ """Build a custom SDK httpx client when DISABLE_SSL_VERIFY is enabled."""+ if not disable_ssl_verify_enabled():+ return None+ return httpx.AsyncClient(verify=False, **kwargs) # nosec B501+++def openai_client_kwargs(**httpx_kwargs: Any) -> dict[str, httpx.AsyncClient]:+ """Return kwargs to pass into ``AsyncOpenAI`` for custom HTTP behavior."""+ client = build_openai_http_client(**httpx_kwargs)+ return {"http_client": client} if client is not None else {}+++__all__ = [+ "build_openai_http_client",+ "disable_ssl_verify_enabled",+ "openai_client_kwargs",+]diff --git a/deeptutor/services/llm/provider_core/azure_openai_provider.py b/deeptutor/services/llm/provider_core/azure_openai_provider.pyindex 44517b173..2d4dd9878 100644--- a/deeptutor/services/llm/provider_core/azure_openai_provider.py+++ b/deeptutor/services/llm/provider_core/azure_openai_provider.py@@ -9,6 +9,7 @@ import uuidfrom openai import AsyncOpenAI+from deeptutor.services.llm.openai_http_client import openai_client_kwargsfrom deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponsefrom deeptutor.services.llm.provider_core.openai_responses import (adapt_chat_kwargs_to_responses,@@ -52,6 +53,7 @@ class AzureOpenAIProvider(LLMProvider):base_url=base_url,default_headers=headers,max_retries=0,+ **openai_client_kwargs(),)@staticmethoddiff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.pyindex b684a6fff..1b0cc7df3 100644--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py@@ -19,6 +19,7 @@ import json_repairfrom openai import AsyncOpenAIfrom deeptutor.services.llm.capabilities import disable_response_format_at_runtime+from deeptutor.services.llm.openai_http_client import openai_client_kwargsfrom deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse, ToolCallRequestfrom deeptutor.services.llm.provider_core.openai_responses import (adapt_chat_kwargs_to_responses,@@ -142,6 +143,7 @@ class OpenAICompatProvider(LLMProvider):base_url=effective_base,default_headers=default_headers,max_retries=0,+ **openai_client_kwargs(),)self._responses_failures: dict[str, int] = {}self._responses_tripped_at: dict[str, float] = {}diff --git a/deeptutor/tutorbot/channels/matrix.py b/deeptutor/tutorbot/channels/matrix.pyindex cb6a7508b..a962142ea 100644--- a/deeptutor/tutorbot/channels/matrix.py+++ b/deeptutor/tutorbot/channels/matrix.py@@ -29,13 +29,21 @@ try:SyncError,UploadError,)- from nio.crypto.attachments import decrypt_attachment- from nio.exceptions import EncryptionErrorexcept ImportError as e:raise ImportError("Matrix dependencies not installed. Run: pip install deeptutor[matrix]") from e+try:+ from nio.crypto.attachments import decrypt_attachment+ from nio.exceptions import EncryptionError+except ImportError:+ decrypt_attachment = None+ EncryptionError = Exception+ MATRIX_E2EE_AVAILABLE = False+else:+ MATRIX_E2EE_AVAILABLE = True+from deeptutor.tutorbot.bus.events import OutboundMessagefrom deeptutor.tutorbot.bus.queue import MessageBusfrom deeptutor.tutorbot.channels.base import BaseChannel@@ -185,7 +193,7 @@ class MatrixConfig(Base):access_token: str = ""user_id: str = ""device_id: str = ""- e2ee_enabled: bool = True+ e2ee_enabled: bool = Falsesync_stop_grace_seconds: int = 2max_media_bytes: int = 20 * 1024 * 1024allow_from: list[str] = Field(default_factory=list)@@ -229,6 +237,12 @@ class MatrixChannel(BaseChannel):"""Start Matrix client and begin sync loop."""self._running = True_configure_nio_logging_bridge()+ if self.config.e2ee_enabled and not MATRIX_E2EE_AVAILABLE:+ raise ImportError(+ "Matrix E2EE dependencies are not installed. Install "+ "`deeptutor[matrix-e2e]` or `requirements/matrix-e2e.txt`, and make "+ "sure libolm is available on your system."+ )store_path = get_data_dir() / "matrix-store"store_path.mkdir(parents=True, exist_ok=True)@@ -698,6 +712,12 @@ class MatrixChannel(BaseChannel):return Nonedef _decrypt_media_bytes(self, event: MatrixMediaEvent, ciphertext: bytes) -> bytes | None:+ if decrypt_attachment is None:+ logger.warning(+ "Matrix encrypted attachment received but E2EE dependencies are not installed. "+ "Install deeptutor[matrix-e2e] to decrypt encrypted media."+ )+ return Nonekey_obj, hashes, iv = (getattr(event, "key", None),getattr(event, "hashes", None),diff --git a/deeptutor/tutorbot/providers/openai_compat_provider.py b/deeptutor/tutorbot/providers/openai_compat_provider.pyindex 4a33e7ada..57cb6f37e 100644--- a/deeptutor/tutorbot/providers/openai_compat_provider.py+++ b/deeptutor/tutorbot/providers/openai_compat_provider.py@@ -17,6 +17,7 @@ import uuidimport json_repairfrom openai import AsyncOpenAI+from deeptutor.services.llm.openai_http_client import openai_client_kwargsfrom deeptutor.tutorbot.providers.base import LLMProvider, LLMResponse, ToolCallRequestif TYPE_CHECKING:@@ -108,6 +109,7 @@ class OpenAICompatProvider(LLMProvider):base_url=effective_base,default_headers=default_headers,max_retries=0,+ **openai_client_kwargs(),)def _setup_env(self, api_key: str, api_base: str | None) -> None:diff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.ymlindex 1d915db50..b914a4057 100644--- a/docker-compose.ghcr.yml+++ b/docker-compose.ghcr.yml@@ -76,6 +76,8 @@ services:# REMOTE: set to http://<your-server-ip>:8001 or https://your-domain.com:8001- NEXT_PUBLIC_API_BASE_EXTERNAL=${NEXT_PUBLIC_API_BASE_EXTERNAL:-}- NEXT_PUBLIC_API_BASE=${NEXT_PUBLIC_API_BASE:-}+ - CORS_ORIGIN=${CORS_ORIGIN:-}+ - CORS_ORIGINS=${CORS_ORIGINS:-}volumes:# Persistent data (created automatically on first start)diff --git a/docker-compose.yml b/docker-compose.ymlindex 63b4b4e66..f7c3e4a32 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -104,6 +104,9 @@ services:- NEXT_PUBLIC_API_BASE_EXTERNAL=${NEXT_PUBLIC_API_BASE_EXTERNAL:-}# Alternative: Direct API base URL (same priority as NEXT_PUBLIC_API_BASE_EXTERNAL)- NEXT_PUBLIC_API_BASE=${NEXT_PUBLIC_API_BASE:-}+ # Extra frontend origin(s) allowed by FastAPI CORS when auth is enabled.+ - CORS_ORIGIN=${CORS_ORIGIN:-}+ - CORS_ORIGINS=${CORS_ORIGINS:-}volumes:# Mount local data directory for persistence (read-write)diff --git a/pyproject.toml b/pyproject.tomlindex 7a0c203a4..33410bd78 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -96,13 +96,19 @@ tutorbot = []# Matrix (Element) channel for TutorBot. Mirrors requirements/matrix.txt.-# Kept as a separate extra because matrix-nio[e2e] requires libolm (native dep).+# Default Matrix install is non-E2EE so it works without libolm/python-olm.matrix = [- "matrix-nio[e2e]>=0.25.2,<1.0.0",+ "matrix-nio>=0.25.2,<1.0.0","mistune>=3.0.0,<4.0.0","nh3>=0.2.18,<1.0.0",]+# Optional Matrix E2EE addon. Mirrors requirements/matrix-e2e.txt and requires libolm.+matrix-e2e = [+ "deeptutor[matrix]",+ "matrix-nio[e2e]>=0.25.2,<1.0.0",+]+# Math Animator addon (Manim). Mirrors requirements/math-animator.txt.# System prerequisites (installed outside pip): LaTeX, pkg-config, cairo, cmake, ffmpeg.math-animator = ["manim>=0.19.0"]@@ -117,7 +123,7 @@ dev = ["bandit>=1.8.0",]-# Everything: server + tutorbot + matrix + math-animator + dev tools.+# Everything: server + tutorbot + non-E2EE matrix + math-animator + dev tools.all = ["deeptutor[tutorbot]","deeptutor[matrix]",diff --git a/requirements/matrix-e2e.txt b/requirements/matrix-e2e.txtnew file mode 100644index 000000000..22946ec6d--- /dev/null+++ b/requirements/matrix-e2e.txt@@ -0,0 +1,19 @@+# ============================================+# DeepTutor Matrix E2EE Add-on — Dependencies+# ============================================+# Mirrors pyproject.toml `[project.optional-dependencies].matrix-e2e`.+# Keep in sync with pyproject.toml when adding/updating dependencies.+#+# Preferred install (from a source clone): pip install -e ".[matrix-e2e]"+# Use this file for Docker/CI when pyproject.toml/source code aren't yet available.+#+# Note: matrix-nio[e2e] pulls python-olm, which requires the libolm native library.+# On macOS:+# brew install libolm+# On Debian/Ubuntu:+# apt-get install libolm-dev++-r matrix.txt++# --- Matrix E2EE support ---+matrix-nio[e2e]>=0.25.2,<1.0.0diff --git a/requirements/matrix.txt b/requirements/matrix.txtindex cac53517a..1696ce783 100644--- a/requirements/matrix.txt+++ b/requirements/matrix.txt@@ -7,14 +7,12 @@# Preferred install (from a source clone): pip install -e ".[matrix]"# Use this file for Docker/CI when pyproject.toml/source code aren't yet available.#-# Note: matrix-nio[e2e] requires the libolm native library. On macOS:-# brew install libolm-# On Debian/Ubuntu:-# apt-get install libolm-dev+# This default profile is non-E2EE and does not require libolm/python-olm.+# For encrypted rooms, install requirements/matrix-e2e.txt or `deeptutor[matrix-e2e]`.-r tutorbot.txt# --- Matrix channel ----matrix-nio[e2e]>=0.25.2,<1.0.0+matrix-nio>=0.25.2,<1.0.0mistune>=3.0.0,<4.0.0nh3>=0.2.18,<1.0.0diff --git a/scripts/start_tour.py b/scripts/start_tour.pyindex e41dd2ef1..8783f22b4 100644--- a/scripts/start_tour.py+++ b/scripts/start_tour.py@@ -282,7 +282,7 @@ MESSAGES: dict[str, dict[str, str]] = {"install_profile_tutorbot_label": "Web + TutorBot","install_profile_tutorbot_desc": "Adds TutorBot engine and common channel SDKs","install_profile_matrix_label": "Web + TutorBot + Matrix",- "install_profile_matrix_desc": "Also installs matrix-nio[e2e]; requires libolm on your system",+ "install_profile_matrix_desc": "Adds Matrix support without E2EE/libolm; install matrix-e2e for encrypted rooms","install_math_animator": "Install Math Animator add-on?","install_math_animator_hint": ("Optional: Manim can require LaTeX, Cairo, pkg-config, CMake, and ffmpeg."@@ -398,7 +398,7 @@ MESSAGES: dict[str, dict[str, str]] = {"install_profile_tutorbot_label": "Web + TutorBot","install_profile_tutorbot_desc": "增加 TutorBot 引擎和常用渠道 SDK","install_profile_matrix_label": "Web + TutorBot + Matrix",- "install_profile_matrix_desc": "额外安装 matrix-nio[e2e];系统需先安装 libolm",+ "install_profile_matrix_desc": "增加非 E2EE Matrix 支持;加密房间请另装 matrix-e2e/libolm","install_math_animator": "是否安装 Math Animator 附加能力?","install_math_animator_hint": "选填:Manim 可能需要 LaTeX、Cairo、pkg-config、CMake 和 ffmpeg。","install_selected": "已选择安装配置:{profile}",diff --git a/tests/api/test_cors_settings.py b/tests/api/test_cors_settings.pynew file mode 100644index 000000000..72d64261d--- /dev/null+++ b/tests/api/test_cors_settings.py@@ -0,0 +1,37 @@+"""Tests for FastAPI CORS settings."""++from __future__ import annotations++from deeptutor.api import main as api_main+++def test_cors_allows_remote_http_origins_when_auth_disabled(+ monkeypatch,+) -> None:+ monkeypatch.delenv("AUTH_ENABLED", raising=False)+ monkeypatch.delenv("CORS_ORIGIN", raising=False)+ monkeypatch.delenv("CORS_ORIGINS", raising=False)+ monkeypatch.setenv("FRONTEND_PORT", "3782")++ settings = api_main._build_cors_settings()++ assert settings["allow_origin_regex"] == r"https?://.*"+ assert "http://localhost:3782" in settings["allow_origins"]+ assert "http://127.0.0.1:3782" in settings["allow_origins"]+++def test_cors_requires_explicit_origins_when_auth_enabled(monkeypatch) -> None:+ monkeypatch.setenv("AUTH_ENABLED", "true")+ monkeypatch.setenv("CORS_ORIGIN", "https://app.example.com/")+ monkeypatch.setenv(+ "CORS_ORIGINS",+ "https://foo.example.com, https://bar.example.com\nhttps://foo.example.com",+ )++ settings = api_main._build_cors_settings()++ assert settings["allow_origin_regex"] is None+ assert "https://app.example.com" in settings["allow_origins"]+ assert "https://foo.example.com" in settings["allow_origins"]+ assert "https://bar.example.com" in settings["allow_origins"]+ assert settings["allow_origins"].count("https://foo.example.com") == 1diff --git a/tests/services/config/test_env_store_send_dimensions.py b/tests/services/config/test_env_store_send_dimensions.pyindex 81c0bd01c..7285eba0d 100644--- a/tests/services/config/test_env_store_send_dimensions.py+++ b/tests/services/config/test_env_store_send_dimensions.py@@ -15,30 +15,25 @@ from pathlib import Pathimport pytest-from deeptutor.services.config.env_store import EnvStore, _render_optional_bool+from deeptutor.services.config.env_store import ENV_KEY_ORDER, EnvStore, _render_optional_boolfrom deeptutor.services.config.provider_runtime import _coerce_optional_bool@pytest.fixture(autouse=True)-def _clean_send_dimensions_env(monkeypatch: pytest.MonkeyPatch) -> None:- """``EnvStore`` mutates ``os.environ`` on load/write — isolate each test.-- monkeypatch's ``delenv`` reverts only what it deleted; if the test then- has ``EnvStore.write()`` set ``EMBEDDING_SEND_DIMENSIONS`` again, that- value leaks into subsequent test files. Snapshot the current value here- and use a yield-style teardown to restore it.- """+def _clean_env_store_env(monkeypatch: pytest.MonkeyPatch) -> None:+ """``EnvStore`` mutates ``os.environ`` on load/write — isolate each test."""import ossentinel = object()- original = os.environ.get("EMBEDDING_SEND_DIMENSIONS", sentinel)- monkeypatch.delenv("EMBEDDING_SEND_DIMENSIONS", raising=False)+ original = {key: os.environ.get(key, sentinel) for key in ENV_KEY_ORDER}+ for key in ENV_KEY_ORDER:+ monkeypatch.delenv(key, raising=False)yield- # Restore the pre-test value so EnvStore.write() side-effects don't leak.- if original is sentinel:- os.environ.pop("EMBEDDING_SEND_DIMENSIONS", None)- else:- os.environ["EMBEDDING_SEND_DIMENSIONS"] = original # type: ignore[assignment]+ for key, value in original.items():+ if value is sentinel:+ os.environ.pop(key, None)+ else:+ os.environ[key] = value # type: ignore[assignment]def _embedding_catalog(send_dimensions: object | None) -> dict:@@ -172,6 +167,29 @@ def test_write_preserves_provider_specific_embedding_key(tmp_path: Path) -> Noneassert "GEMINI_API_KEY=gemini-existing" in text+def test_write_preserves_deployment_network_keys(tmp_path: Path) -> None:+ env_path = tmp_path / ".env"+ env_path.write_text(+ "\n".join(+ [+ "CORS_ORIGIN=https://app.example.com",+ "CORS_ORIGINS=https://foo.example.com,https://bar.example.com",+ "DISABLE_SSL_VERIFY=true",+ ]+ )+ + "\n",+ encoding="utf-8",+ )+ env = EnvStore(path=env_path)++ env.write(env.render_from_catalog(_embedding_catalog(send_dimensions=None)))++ text = env_path.read_text(encoding="utf-8")+ assert "CORS_ORIGIN=https://app.example.com" in text+ assert "CORS_ORIGINS=https://foo.example.com,https://bar.example.com" in text+ assert "DISABLE_SSL_VERIFY=true" in text++# ---------------------------------------------------------------------------# as_summary() — round-trip from .env back into the embedding dict# ---------------------------------------------------------------------------diff --git a/tests/services/llm/test_openai_http_client.py b/tests/services/llm/test_openai_http_client.pynew file mode 100644index 000000000..4139e2d19--- /dev/null+++ b/tests/services/llm/test_openai_http_client.py@@ -0,0 +1,200 @@+"""Tests for OpenAI SDK HTTP client options shared across providers."""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from deeptutor.services.llm import openai_http_client+from deeptutor.services.llm.exceptions import LLMConfigError++[email protected](autouse=True)+def _clean_ssl_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("DISABLE_SSL_VERIFY", raising=False)+ monkeypatch.delenv("ENVIRONMENT", raising=False)+ monkeypatch.setattr(openai_http_client, "_warning_logged", False)+++def _enable_ssl_override(monkeypatch: pytest.MonkeyPatch) -> list[Any]:+ clients: list[Any] = []++ class HTTPClientStub:+ def __init__(self, **kwargs: Any) -> None:+ self.kwargs = kwargs+ clients.append(self)++ monkeypatch.setenv("DISABLE_SSL_VERIFY", "1")+ monkeypatch.setattr(openai_http_client.httpx, "AsyncClient", HTTPClientStub)+ return clients+++def _capture_async_openai(monkeypatch: pytest.MonkeyPatch, module: Any) -> list[dict[str, Any]]:+ captured: list[dict[str, Any]] = []++ class AsyncOpenAIStub:+ def __init__(self, **kwargs: Any) -> None:+ captured.append(kwargs)++ monkeypatch.setattr(module, "AsyncOpenAI", AsyncOpenAIStub)+ return captured+++def test_openai_client_kwargs_disable_ssl_verify(monkeypatch: pytest.MonkeyPatch) -> None:+ clients = _enable_ssl_override(monkeypatch)++ kwargs = openai_http_client.openai_client_kwargs(timeout=60)++ assert kwargs["http_client"] is clients[0]+ assert clients[0].kwargs == {"verify": False, "timeout": 60}+++def test_openai_client_kwargs_rejects_production(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("DISABLE_SSL_VERIFY", "true")+ monkeypatch.setenv("ENVIRONMENT", "production")++ with pytest.raises(LLMConfigError, match="not allowed in production"):+ openai_http_client.openai_client_kwargs()+++def test_provider_core_passes_disable_ssl_http_client(monkeypatch: pytest.MonkeyPatch) -> None:+ from deeptutor.services.llm.provider_core import openai_compat_provider as provider_mod++ clients = _enable_ssl_override(monkeypatch)+ captured = _capture_async_openai(monkeypatch, provider_mod)++ provider_mod.OpenAICompatProvider(api_key="sk-test", api_base="https://example.com/v1")++ assert captured[0]["http_client"] is clients[0]+ assert clients[0].kwargs["verify"] is False+++def test_azure_provider_passes_disable_ssl_http_client(monkeypatch: pytest.MonkeyPatch) -> None:+ from deeptutor.services.llm.provider_core import azure_openai_provider as azure_mod++ clients = _enable_ssl_override(monkeypatch)+ captured = _capture_async_openai(monkeypatch, azure_mod)++ azure_mod.AzureOpenAIProvider(+ api_key="sk-test",+ api_base="https://example.openai.azure.com",+ default_model="gpt-test",+ )++ assert captured[0]["http_client"] is clients[0]+ assert clients[0].kwargs["verify"] is False+++def test_tutorbot_provider_passes_disable_ssl_http_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from deeptutor.tutorbot.providers import openai_compat_provider as tutorbot_mod++ clients = _enable_ssl_override(monkeypatch)+ captured = _capture_async_openai(monkeypatch, tutorbot_mod)++ tutorbot_mod.OpenAICompatProvider(api_key="sk-test", api_base="https://example.com/v1")++ assert captured[0]["http_client"] is clients[0]+ assert clients[0].kwargs["verify"] is False+++async def test_sdk_complete_passes_disable_ssl_http_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from deeptutor.services.llm import executors++ clients = _enable_ssl_override(monkeypatch)+ captured = _capture_async_openai(monkeypatch, executors)++ async def fake_create_with_format_fallback(*_args: Any, **_kwargs: Any) -> Any:+ return SimpleNamespace(+ choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))],+ )++ monkeypatch.setattr(executors, "_create_with_format_fallback", fake_create_with_format_fallback)++ result = await executors.sdk_complete(+ prompt="hi",+ system_prompt="system",+ provider_name="openai",+ model="gpt-test",+ api_key="sk-test",+ base_url="https://example.com/v1",+ )++ assert result == "ok"+ assert captured[0]["http_client"] is clients[0]+ assert clients[0].kwargs["verify"] is False+++async def test_sdk_stream_passes_disable_ssl_http_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from deeptutor.services.llm import executors++ clients = _enable_ssl_override(monkeypatch)+ captured = _capture_async_openai(monkeypatch, executors)++ class StreamStub:+ def __init__(self) -> None:+ self._chunks = [+ SimpleNamespace(+ choices=[SimpleNamespace(delta=SimpleNamespace(content="hi"))],+ )+ ]++ def __aiter__(self) -> "StreamStub":+ return self++ async def __anext__(self) -> Any:+ if not self._chunks:+ raise StopAsyncIteration+ return self._chunks.pop(0)++ async def fake_create_with_format_fallback(*_args: Any, **_kwargs: Any) -> StreamStub:+ return StreamStub()++ monkeypatch.setattr(executors, "_create_with_format_fallback", fake_create_with_format_fallback)++ chunks = [+ chunk+ async for chunk in executors.sdk_stream(+ prompt="hi",+ system_prompt="system",+ provider_name="openai",+ model="gpt-test",+ api_key="sk-test",+ base_url="https://example.com/v1",+ )+ ]++ assert chunks == ["hi"]+ assert captured[0]["http_client"] is clients[0]+ assert clients[0].kwargs["verify"] is False+++def test_embedding_sdk_passes_disable_ssl_http_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from deeptutor.services.embedding.adapters import openai_sdk as embedding_mod++ clients = _enable_ssl_override(monkeypatch)+ captured = _capture_async_openai(monkeypatch, embedding_mod)++ adapter = embedding_mod.OpenAISDKEmbeddingAdapter(+ {+ "api_key": "sk-test",+ "base_url": "https://example.com/v1",+ "model": "text-embedding-3-large",+ "request_timeout": 30,+ }+ )+ adapter._build_client()++ assert captured[0]["http_client"] is clients[0]+ assert clients[0].kwargs == {"verify": False, "timeout": 60}diff --git a/tests/test_matrix_requirements.py b/tests/test_matrix_requirements.pynew file mode 100644index 000000000..10c9ac24d--- /dev/null+++ b/tests/test_matrix_requirements.py@@ -0,0 +1,19 @@+"""Tests for Matrix dependency split."""++from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+++def test_matrix_default_requirements_do_not_install_e2e() -> None:+ text = (ROOT / "requirements" / "matrix.txt").read_text(encoding="utf-8")++ assert "matrix-nio[e2e]" not in text+ assert "matrix-nio>=0.25.2,<1.0.0" in text+++def test_matrix_e2e_requirements_are_separate() -> None:+ text = (ROOT / "requirements" / "matrix-e2e.txt").read_text(encoding="utf-8")++ assert "-r matrix.txt" in text+ assert "matrix-nio[e2e]>=0.25.2,<1.0.0" in textdiff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.tsindex 7205e2a66..7c6ad0ab3 100644--- a/web/lib/markdown-display.ts+++ b/web/lib/markdown-display.ts@@ -180,6 +180,8 @@ const ALLOWED_HTML_TAGS = new Set<string>([]);const HTML_LIKE_TAG_REGEX = /<\/?([A-Za-z][A-Za-z0-9_-]*)\b[^<>]*?\/?>/g;+const FENCED_CODE_BLOCK_REGEX = /```[\s\S]*?```/g;+const INLINE_CODE_SPAN_REGEX = /`[^`\n]*`/g;const PROTECTED_SPAN_REGEX = /```[\s\S]*?```|`[^`\n]*`/g;const PROTECTED_PLACEHOLDER_REGEX = /\u0000PROTECTED_(\d+)\u0000/g;@@ -374,6 +376,42 @@ function linkifyCitations(content: string): string {return linked + tail;}+function maskProtectedSpans(+ content: string,+ regex: RegExp,+ label: string,+): { masked: string; restore: (value: string) => string } {+ const protectedSpans: string[] = [];+ const masked = content.replace(regex, (match) => {+ protectedSpans.push(match);+ return `\u0000${label}_${protectedSpans.length - 1}\u0000`;+ });+ const placeholderRegex = new RegExp(`\\u0000${label}_(\\d+)\\u0000`, "g");+ return {+ masked,+ restore: (value: string) =>+ value.replace(+ placeholderRegex,+ (_match, idx: string) => protectedSpans[Number(idx)] ?? "",+ ),+ };+}++function linkifyCitationsOutsideCode(content: string): string {+ const fenced = maskProtectedSpans(+ content,+ FENCED_CODE_BLOCK_REGEX,+ "FENCED_CODE",+ );+ const unwrapped = unwrapBacktickedCitations(fenced.masked);+ const inline = maskProtectedSpans(+ unwrapped,+ INLINE_CODE_SPAN_REGEX,+ "INLINE_CODE",+ );+ return fenced.restore(inline.restore(linkifyCitations(inline.masked)));+}+export function normalizeMarkdownForDisplay(content: string): string {if (!content) return "";@@ -392,7 +430,7 @@ export function normalizeMarkdownForDisplay(content: string): string {removeEmptyHtmlTables(normalized),).replace(/\n{3,}/g, "\n\n");const safe = escapeUnknownHtmlTagsForDisplay(cleaned);- return linkifyCitations(unwrapBacktickedCitations(safe));+ return linkifyCitationsOutsideCode(safe);}export function hasVisibleMarkdownContent(content: string): boolean {diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.tsindex 16926c1ae..7d4259f14 100644--- a/web/tests/markdown-display.test.ts+++ b/web/tests/markdown-display.test.ts@@ -32,6 +32,30 @@ test("normalizeMarkdownForDisplay keeps meaningful tables", () => {assert.equal(normalizeMarkdownForDisplay(input), input);});+test("normalizeMarkdownForDisplay linkifies bare citations in prose", () => {+ assert.equal(+ normalizeMarkdownForDisplay("Reference [1]."),+ 'Reference [1](#references "citation").',+ );+});++test("normalizeMarkdownForDisplay keeps array indexes inside fenced code", () => {+ const input = "```js\nconst item = values[0];\n```";+ assert.equal(normalizeMarkdownForDisplay(input), input);+});++test("normalizeMarkdownForDisplay keeps array indexes inside inline code", () => {+ const input = "Use `values[0]` for the first item.";+ assert.equal(normalizeMarkdownForDisplay(input), input);+});++test("normalizeMarkdownForDisplay unwraps explicit citation code spans outside code", () => {+ assert.equal(+ normalizeMarkdownForDisplay("See `[web-1]` for details."),+ 'See [web-1](#references "citation") for details.',+ );+});+test("escapeUnknownHtmlTagsForDisplay escapes LLM pseudo tags", () => {const input = "Before\n<think>internal scratchpad</think>\nAfter";assert.equal(