DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
release: v1.5.17
Bingxi Zhao (Frank)bd80a4d28a20
diff --git a/Dockerfile b/Dockerfileindex 7476b9a12..5e793198a 100644--- a/Dockerfile+++ b/Dockerfile@@ -366,6 +366,42 @@ init_user_directories(Path('/app'))# owns it. Cheap on no-op; the only first-start cost is one stat per file.chown -R deeptutor:deeptutor /app/data 2>/dev/null || true+# Optional dependencies (#762). A container is disposable, so anything+# `docker exec … pip install`ed into a running one is gone at the next+# `compose down`. Declare them on the deployment instead and every container+# started from it has them:+#+# environment:+# DEEPTUTOR_EXTRAS: "math-animator,partners"+# DEEPTUTOR_APT_PACKAGES: "ffmpeg"+#+# Both steps are idempotent — a warm container only pays a check — and neither+# is allowed to be fatal: a missing wheel leaves that one feature unavailable,+# exactly as it was before, rather than taking the whole deployment down.+# The pip cache lives on the data volume so a rebuild reuses the downloads it+# already paid for instead of fetching them again.+export PIP_CACHE_DIR="${PIP_CACHE_DIR:-/app/data/.cache/pip}"+mkdir -p "$PIP_CACHE_DIR" 2>/dev/null || true++if [ -n "${DEEPTUTOR_APT_PACKAGES:-}" ]; then+ echo "🔧 Ensuring system packages: ${DEEPTUTOR_APT_PACKAGES}"+ apt_missing=""+ for pkg in $(echo "${DEEPTUTOR_APT_PACKAGES}" | tr ',' ' '); do+ dpkg -s "$pkg" >/dev/null 2>&1 || apt_missing="$apt_missing $pkg"+ done+ if [ -z "$apt_missing" ]; then+ echo " ✅ System packages already present"+ elif ! (apt-get update -qq && apt-get install -y --no-install-recommends $apt_missing); then+ echo " ⚠️ apt-get failed; these packages stay unavailable:$apt_missing"+ fi+fi++if [ -n "${DEEPTUTOR_EXTRAS:-}" ]; then+ echo "🔧 Ensuring Python extras: ${DEEPTUTOR_EXTRAS}"+ python /app/scripts/install_extras.py "${DEEPTUTOR_EXTRAS}" || true+ chown -R deeptutor:deeptutor "$PIP_CACHE_DIR" 2>/dev/null || true+fi+echo "⚙️ Loading runtime JSON settings..."eval "$(python - <<'PY'import shlexdiff --git a/README.md b/README.mdindex 18c904666..92d72de5f 100644--- a/README.md+++ b/README.md@@ -50,17 +50,19 @@### 📦 Releases+> **[2026.8.25]** [v1.5.17](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.17) — Partners each member owns with private conversations and linkable chat accounts, GitHub repos as a knowledge source, **Antigravity CLI**, browser WeChat QR login, and `deeptutor doctor`.+> **[2026.8.22]** [v1.5.16](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.16) — **MarginNote 4** libraries you connect and its add-on fills, Book pages that turn again, and tool-call ids, embeddings and temperature limits that stop breaking behind a gateway.> **[2026.8.20]** [v1.5.15](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.15) — **PageIndex OSS** you host yourself with reasoning retrieval, a question bank you can finally file into, third-party tool/capability plugins, and **Apache Tika** parsing.> **[2026.8.19]** [v1.5.14](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.14) — **Immersive Reading**: a document open beside the thread, cited page by page; DeepTutor configures itself from chat; IMA libraries you browse and write to; a notebook console.-> **[2026.8.17]** [v1.5.13](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.13) — Books stream while they compile, track your progress, and export to Markdown; a cost estimate before you approve a spine; and home starter suggestions drawn from memory.-<details><summary><b>Past releases (more than 1 week ago)</b></summary>+> **[2026.8.17]** [v1.5.13](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.13) — Books stream while they compile, track your progress, and export to Markdown; a cost estimate before you approve a spine; and home starter suggestions drawn from memory.+> **[2026.8.13]** [v1.5.12](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.12) — Web search rebuilt with six new providers (**Doubao**, **Bocha**, **Zhipu**, **Firecrawl**, **Qianfan**, **Aliyun IQS**), a **LiteParse** parsing engine, MCP servers that reconnect on credential change, and **CodeBuddy** + **OrcaRouter**.> **[2026.8.10]** [v1.5.11](https://github.com/HKUDS/DeepTutor/releases/tag/v1.5.11) — Prose around a DSML tool call stops vanishing, a truncated reply continues instead of ending, live memory usage in Settings, and LightRAG indexing off the event loop.@@ -318,7 +320,7 @@ docker run --rm --name deeptutor \> **Only `3782` needs to be published.** The browser talks exclusively to the frontend origin; the Next.js middleware (`web/proxy.ts`) forwards `/api/*` and `/ws/*` to the FastAPI backend **inside the container**. Publishing `8001` (`-p 127.0.0.1:8001:8001`) is optional — handy only for hitting the API directly with curl or scripts.-Open [http://127.0.0.1:3782](http://127.0.0.1:3782). The container creates `/app/data/user/settings/*.json` on first boot; configure model providers from the Web Settings page. Config, API keys, logs, workspace files, memory, and knowledge bases persist in the `deeptutor-data` volume.+Open [http://127.0.0.1:3782](http://127.0.0.1:3782). The container creates `/app/data/user/settings/*.json` on first boot; configure model providers from the Web Settings page. Config, API keys, logs, workspace files, memory, and knowledge bases persist in the `deeptutor-data` volume. Optional extras belong on the deployment, not in a shell: set `DEEPTUTOR_EXTRAS` (and `DEEPTUTOR_APT_PACKAGES` for system libraries) and every container started from it re-applies them, where a `docker exec … pip install` would be lost at the next `compose down`.- **Different host ports:** change the left side of each `-p host:container` mapping (e.g. `-p 127.0.0.1:8088:3782`). If you change container-side ports in `/app/data/user/settings/system.json`, restart and update the right side of each mapping to match.- **Detached:** add `-d`, then `docker logs -f deeptutor` to follow, `docker stop deeptutor` to stop, `docker rm deeptutor` before reusing the name. The `deeptutor-data` volume keeps your settings and workspace across restarts.@@ -522,7 +524,7 @@ Each partner has a `SOUL.md`, model selection, channels, tool policy, and assignThe channel layer is schema-driven and can connect to IM platforms such as Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat, and Microsoft Teams depending on installed extras and configured credentials. A partner can also be connected as a subagent and consulted from a normal chat turn — see **My Agents** below.-For faster setup, the Partner channel page can create a Feishu/Lark app or WeCom AI bot from a QR scan. Feishu/Lark detects the account domain and saves the scanning user as the initial allowed sender. WeCom keeps an existing allowlist and otherwise defaults to all users who can reach the bot, with a visible open-access warning; the manual channel forms remain available if a provider's scan protocol changes.+For faster setup, the Partner channel page can create a Feishu/Lark app or WeCom AI bot, or sign a personal WeChat account in, from a QR scan drawn in the browser rather than the server log. Feishu/Lark detects the account domain and saves the scanning user as the initial allowed sender. WeCom keeps an existing allowlist and otherwise defaults to all users who can reach the bot, with a visible open-access warning; the manual channel forms remain available if a provider's scan protocol changes.</details>@@ -533,7 +535,7 @@ For faster setup, the Partner channel page can create a Feishu/Lark app or WeCom<img src="assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agents workspace" width="900"></div>-My Agents turns other agents into context for DeepTutor, and does two distinct things. **Connect a live agent** — a Claude Code, Codex, Gemini, Kimi, opencode, or MiMo Code CLI on your machine, or one of your Partners — and consult it from inside a chat turn: DeepTutor actually *runs* the other agent and streams its work into the Activity panel via the `consult_subagent` tool. Select it with the Agent chip (or type `@`), and set how many rounds the consult may take.+My Agents turns other agents into context for DeepTutor, and does two distinct things. **Connect a live agent** — a Claude Code, Codex, Gemini, Antigravity, Kimi, opencode, or MiMo Code CLI on your machine, or one of your Partners — and consult it from inside a chat turn: DeepTutor actually *runs* the other agent and streams its work into the Activity panel via the `consult_subagent` tool. Select it with the Agent chip (or type `@`), and set how many rounds the consult may take.<div align="center"><img src="assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consulting a Claude Code subagent live" width="900">@@ -594,7 +596,7 @@ Knowledge bases are the document collections behind RAG — they ground Chat tur<img src="assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Create a knowledge base" width="900"></div>-Creating a KB, you either **create new** (upload documents and build a fresh index) or **link existing** (reuse an index built elsewhere, read in place with no re-index). Re-indexing writes a new flat `version-N` directory and keeps prior ones, so a working index is never destroyed mid-rebuild. A single document can be removed even from an **error**-state base — dropping a file that failed to parse without a full delete-and-rebuild. Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, or LiteParse — is chosen in **Settings → Knowledge Base**, with local model downloads off by default. Docling can also run in **remote** mode against a Docling Serve server (no local install or models needed), configured via **Settings → Document Parsing** (`mode=remote`, a server base URL, and an optional API key) or the `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables. Tika is remote-only and points at an Apache Tika server (`TIKA_SERVER_URL`). The CLI mirrors the lifecycle with `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, and `delete`.+Creating a KB, you either **create new** (upload documents and build a fresh index) or **link existing** (reuse an index built elsewhere, read in place with no re-index). A KB can also track **GitHub sources** — a repo, branch, and glob whose Markdown is pulled in and re-synced on demand, so documentation you follow stays current without re-uploading. Re-indexing writes a new flat `version-N` directory and keeps prior ones, so a working index is never destroyed mid-rebuild. A single document can be removed even from an **error**-state base — dropping a file that failed to parse without a full delete-and-rebuild. Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, or LiteParse — is chosen in **Settings → Knowledge Base**, with local model downloads off by default. Docling can also run in **remote** mode against a Docling Serve server (no local install or models needed), configured via **Settings → Document Parsing** (`mode=remote`, a server base URL, and an optional API key) or the `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables. Tika is remote-only and points at an Apache Tika server (`TIKA_SERVER_URL`). The CLI mirrors the lifecycle with `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, and `delete`.</details>@@ -740,6 +742,7 @@ The repo ships a root [`SKILL.md`](SKILL.md) — a ~150-line handover doc that t| Command | Description ||:---|:---|| `deeptutor init` | Create or update `data/user/settings` for the current workspace |+| `deeptutor doctor [--online]` | Check whether the workspace is ready to start a session; `--online` also probes the configured model provider, `--format json` prints the report || `deeptutor start [--home PATH] [--dev]` | Launch backend + frontend together; `--dev` enables frontend HMR || `deeptutor serve [--port PORT]` | Start only the FastAPI backend || `deeptutor run <capability> <message>` | Run a single capability turn (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); add `--format json` for NDJSON output |diff --git a/assets/README/README_AR.md b/assets/README/README_AR.mdindex 570fcd0ab..b6c0a7bf4 100644--- a/assets/README/README_AR.md+++ b/assets/README/README_AR.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **يكفي نشر `3782` فقط.** يتحدث المتصفح حصرياً إلى أصل الواجهة الأمامية؛ يقوم وسيط Next.js (`web/proxy.ts`) بإعادة توجيه `/api/*` و`/ws/*` إلى خلفية FastAPI **داخل الحاوية**. نشر `8001` (`-p 127.0.0.1:8001:8001`) اختياري — مفيد فقط لاستدعاء واجهة برمجة التطبيقات مباشرةً باستخدام curl أو نصوص.-افتح [http://127.0.0.1:3782](http://127.0.0.1:3782). تُنشئ الحاوية `/app/data/user/settings/*.json` عند الإقلاع الأول؛ قم بتهيئة مزودي النماذج من صفحة إعدادات الويب. تبقى التهيئة ومفاتيح API والسجلات وملفات مساحة العمل والذاكرة وقواعد المعرفة في وحدة تخزين `deeptutor-data`.+افتح [http://127.0.0.1:3782](http://127.0.0.1:3782). تُنشئ الحاوية `/app/data/user/settings/*.json` عند الإقلاع الأول؛ قم بتهيئة مزودي النماذج من صفحة إعدادات الويب. تبقى التهيئة ومفاتيح API والسجلات وملفات مساحة العمل والذاكرة وقواعد المعرفة في وحدة تخزين `deeptutor-data`. الإضافات الاختيارية تنتمي إلى بيئة النشر، لا إلى جلسة طرفية عابرة: اضبط `DEEPTUTOR_EXTRAS` (و`DEEPTUTOR_APT_PACKAGES` لمكتبات النظام) وستعيد كل حاوية تُشغَّل انطلاقاً منها تطبيقها تلقائياً، في حين أن أمر `docker exec … pip install` سيُفقَد عند `compose down` التالي.- **منافذ مضيف مختلفة:** غيّر الجانب الأيسر من كل تعيين `-p host:container` (مثلاً `-p 127.0.0.1:8088:3782`). إذا غيّرت المنافذ على جانب الحاوية في `/app/data/user/settings/system.json`، أعد التشغيل وحدّث الجانب الأيمن من كل تعيين ليطابق ذلك.- **وضع المنفصل:** أضف `-d`، ثم `docker logs -f deeptutor` للمتابعة، و`docker stop deeptutor` للإيقاف، و`docker rm deeptutor` قبل إعادة استخدام الاسم. تحتفظ وحدة تخزين `deeptutor-data` بإعداداتك ومساحة عملك عبر إعادات التشغيل.@@ -357,6 +357,8 @@ Chat هي أيضاً نقطة انطلاق للقدرات الأعمق: **Quiz**طبقة القناة مدفوعة بالمخطط ويمكنها الاتصال بمنصات IM مثل Feishu وTelegram وSlack وDiscord وDingTalk وQQ/NapCat وWeCom وWhatsApp وZulip وMattermost وMatrix وMochat وMicrosoft Teams بناءً على الإضافات المثبتة والبيانات الاعتمادية المهيأة. يمكن أيضاً توصيل الشريك كوكيل فرعي واستشارته من دور محادثة عادي — راجع **My Agents** أدناه.+لإعداد أسرع، يمكن لصفحة قناة الشريك إنشاء تطبيق Feishu/Lark أو بوت WeCom AI، أو تسجيل دخول حساب WeChat شخصي، من خلال مسح رمز QR يُرسَم في المتصفح بدلاً من سجل الخادم. يكتشف Feishu/Lark نطاق الحساب ويحفظ المستخدم الذي أجرى المسح كمُرسِل مسموح به أولي. يحتفظ WeCom بقائمة سماح موجودة، وإلا فإنه يفترض افتراضياً جميع المستخدمين القادرين على الوصول إلى البوت، مع تحذير وصول مفتوح ظاهر؛ وتبقى استمارات القناة اليدوية متاحة إذا تغيّر بروتوكول المسح الخاص بأحد المزودين.+</details><details>@@ -366,7 +368,7 @@ Chat هي أيضاً نقطة انطلاق للقدرات الأعمق: **Quiz**<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="مساحة عمل My Agents في DeepTutor" width="900"></div>-يحوّل My Agents الوكلاء الآخرين إلى سياق لـ DeepTutor، ويقوم بشيئين متمايزين. **توصيل وكيل مباشر** — واجهة CLI من Claude Code أو Codex أو Gemini أو Kimi أو opencode أو MiMo Code على جهازك، أو أحد شركائك — واستشارته من داخل دور محادثة: DeepTutor *يشغّل* الوكيل الآخر فعلاً ويبث عمله إلى لوحة Activity عبر أداة `consult_subagent`. اختره بشريحة الوكيل (أو اكتب `@`)، وحدد عدد الجولات التي يمكن للاستشارة أن تأخذها.+يحوّل My Agents الوكلاء الآخرين إلى سياق لـ DeepTutor، ويقوم بشيئين متمايزين. **توصيل وكيل مباشر** — واجهة CLI من Claude Code أو Codex أو Gemini أو Antigravity أو Kimi أو opencode أو MiMo Code على جهازك، أو أحد شركائك — واستشارته من داخل دور محادثة: DeepTutor *يشغّل* الوكيل الآخر فعلاً ويبث عمله إلى لوحة Activity عبر أداة `consult_subagent`. اختره بشريحة الوكيل (أو اكتب `@`)، وحدد عدد الجولات التي يمكن للاستشارة أن تأخذها.<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="استشارة وكيل Claude Code الفرعي مباشرةً" width="900">@@ -427,7 +429,7 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقا<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="إنشاء قاعدة معرفة" width="900"></div>-عند إنشاء قاعدة معرفة، إما أن **تنشئ جديدة** (تحميل مستندات وبناء فهرس جديد) أو **تربط موجودة** (إعادة استخدام فهرس مبني في مكان آخر، قراءة في مكانه بدون إعادة فهرسة). تكتب إعادة الفهرسة دليل `version-N` مسطحاً جديداً وتحتفظ بالسابقة، لذا لا يُدمَّر فهرس عامل أبداً أثناء إعادة البناء. يمكن إزالة مستند واحد حتى من قاعدة في حالة **خطأ** — إسقاط ملف فشل تحليله بدون حذف وإعادة بناء كاملين. تحليل المستندات — نص فقط أو MinerU أو Docling أو Tika أو markitdown أو PyMuPDF4LLM أو LiteParse — يُختار في **الإعدادات ← قاعدة المعرفة**، مع إيقاف تنزيلات النماذج المحلية افتراضياً. يمكن لـ Docling أيضاً العمل في وضع **بعيد** مقابل خادم Docling Serve (بلا حاجة إلى تثبيت محلي أو نماذج)، يُهيَّأ عبر **الإعدادات ← تحليل المستندات** (`mode=remote`، وعنوان URL أساسي للخادم، ومفتاح API اختياري) أو متغيرات البيئة `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. أما Tika فهو بعيد فقط ويشير إلى خادم Apache Tika (`TIKA_SERVER_URL`). تعكس واجهة CLI دورة الحياة مع `deeptutor kb list` و`info` و`create` و`add` و`search` و`set-default` و`delete`.+عند إنشاء قاعدة معرفة، إما أن **تنشئ جديدة** (تحميل مستندات وبناء فهرس جديد) أو **تربط موجودة** (إعادة استخدام فهرس مبني في مكان آخر، قراءة في مكانه بدون إعادة فهرسة). يمكن لقاعدة المعرفة أيضاً تتبُّع **مصادر GitHub** — مستودع وفرع ونمط تعبير (glob) يُسحَب Markdown الخاص به ويُعاد مزامنته عند الطلب، لذا تبقى الوثائق التي تتابعها محدَّثة دون إعادة رفع. تكتب إعادة الفهرسة دليل `version-N` مسطحاً جديداً وتحتفظ بالسابقة، لذا لا يُدمَّر فهرس عامل أبداً أثناء إعادة البناء. يمكن إزالة مستند واحد حتى من قاعدة في حالة **خطأ** — إسقاط ملف فشل تحليله بدون حذف وإعادة بناء كاملين. تحليل المستندات — نص فقط أو MinerU أو Docling أو Tika أو markitdown أو PyMuPDF4LLM أو LiteParse — يُختار في **الإعدادات ← قاعدة المعرفة**، مع إيقاف تنزيلات النماذج المحلية افتراضياً. يمكن لـ Docling أيضاً العمل في وضع **بعيد** مقابل خادم Docling Serve (بلا حاجة إلى تثبيت محلي أو نماذج)، يُهيَّأ عبر **الإعدادات ← تحليل المستندات** (`mode=remote`، وعنوان URL أساسي للخادم، ومفتاح API اختياري) أو متغيرات البيئة `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. أما Tika فهو بعيد فقط ويشير إلى خادم Apache Tika (`TIKA_SERVER_URL`). تعكس واجهة CLI دورة الحياة مع `deeptutor kb list` و`info` و`create` و`add` و`search` و`set-default` و`delete`.</details>@@ -573,6 +575,7 @@ deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format j| الأمر | الوصف ||:---|:---|| `deeptutor init` | إنشاء أو تحديث `data/user/settings` لمساحة العمل الحالية |+| `deeptutor doctor [--online]` | التحقق مما إذا كانت مساحة العمل جاهزة لبدء جلسة؛ `--online` يفحص أيضاً مزود النموذج المهيَّأ، و`--format json` يطبع التقرير || `deeptutor start [--home PATH] [--dev]` | تشغيل الخلفية + الواجهة الأمامية معاً || `deeptutor serve [--port PORT]` | تشغيل خلفية FastAPI فقط || `deeptutor run <capability> <message>` | تشغيل دور قدرة واحدة (`chat` و`deep_solve` و`deep_question` و`deep_research` و`visualize` و`math_animator` و`mastery_path`)؛ أضف `--format json` لإخراج NDJSON |diff --git a/assets/README/README_CN.md b/assets/README/README_CN.mdindex 52ac755e2..aa03243cf 100644--- a/assets/README/README_CN.md+++ b/assets/README/README_CN.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **只需发布 `3782` 端口。** 浏览器只与前端源通信;Next.js 中间件(`web/proxy.ts`)在**容器内部**将 `/api/*` 和 `/ws/*` 转发给 FastAPI 后端。发布 `8001`(`-p 127.0.0.1:8001:8001`)是可选的 — 仅在需要用 curl 或脚本直接访问 API 时才有用。-打开 [http://127.0.0.1:3782](http://127.0.0.1:3782)。容器首次启动时会创建 `/app/data/user/settings/*.json`;通过 Web Settings 页面配置模型提供商。配置、API Key、日志、工作区文件、记忆和知识库均持久化在 `deeptutor-data` 卷中。+打开 [http://127.0.0.1:3782](http://127.0.0.1:3782)。容器首次启动时会创建 `/app/data/user/settings/*.json`;通过 Web Settings 页面配置模型提供商。配置、API Key、日志、工作区文件、记忆和知识库均持久化在 `deeptutor-data` 卷中。可选的额外依赖应配置在部署层面,而不是在 shell 中临时安装:设置 `DEEPTUTOR_EXTRAS`(系统库则用 `DEEPTUTOR_APT_PACKAGES`),由此启动的每个容器都会重新应用这些依赖;而 `docker exec … pip install` 这类临时安装会在下一次 `compose down` 后丢失。- **不同宿主机端口:** 修改每个 `-p host:container` 映射的左侧(例如 `-p 127.0.0.1:8088:3782`)。如果修改了 `/app/data/user/settings/system.json` 中容器侧的端口,重启并更新映射右侧以匹配。- **后台运行:** 添加 `-d`,然后用 `docker logs -f deeptutor` 查看日志,`docker stop deeptutor` 停止,重用名称前执行 `docker rm deeptutor`。`deeptutor-data` 卷在重启之间保留设置和工作区。@@ -357,6 +357,8 @@ Partners 是拥有独立灵魂、模型策略、知识库、记忆和渠道的渠道层基于 Schema 驱动,根据已安装的额外依赖和配置的凭证,可连接飞书、Telegram、Slack、Discord、钉钉、QQ/NapCat、企业微信、WhatsApp、Zulip、Mattermost、Matrix、Mochat 和 Microsoft Teams 等 IM 平台。Partner 也可以作为子智能体连接,并从普通聊天轮次中调用 — 详见下方的**我的智能体**。+为加快配置,Partner 渠道页面可以直接在浏览器中绘制二维码(而非依赖服务器日志)来创建飞书/Lark 应用或企业微信 AI 机器人,或扫码登录个人微信账号。飞书/Lark 会检测账号所属域名,并将扫码用户保存为初始允许的发送者。企业微信会保留已有的白名单,否则默认允许所有能触达机器人的用户使用,并显示明显的开放访问警告;如果某个平台的扫码协议发生变化,手动渠道配置表单仍然可用。+</details><details>@@ -366,7 +368,7 @@ Partners 是拥有独立灵魂、模型策略、知识库、记忆和渠道的<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor 我的智能体工作区" width="900"></div>-"我的智能体"将其他智能体转化为 DeepTutor 的上下文,具备两种不同的功能。**连接实时智能体** — 连接你机器上的 Claude Code、Codex、Gemini、Kimi、opencode 或 MiMo Code CLI,或你的某个 Partner,在聊天轮次中调用它:DeepTutor 实际上会*运行*另一个智能体,并通过 `consult_subagent` 工具将其工作流式传输到 Activity 面板。通过智能体选项(或输入 `@`)选择它,并设置调用可进行的最大轮数。+"我的智能体"将其他智能体转化为 DeepTutor 的上下文,具备两种不同的功能。**连接实时智能体** — 连接你机器上的 Claude Code、Codex、Gemini、Antigravity、Kimi、opencode 或 MiMo Code CLI,或你的某个 Partner,在聊天轮次中调用它:DeepTutor 实际上会*运行*另一个智能体,并通过 `consult_subagent` 工具将其工作流式传输到 Activity 面板。通过智能体选项(或输入 `@`)选择它,并设置调用可进行的最大轮数。<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="实时调用 Claude Code 子智能体" width="900">@@ -427,7 +429,7 @@ Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="创建知识库" width="900"></div>-创建 KB 时,可以选择**新建**(上传文档并构建全新索引)或**链接已有**(复用在其他地方构建的索引,原位读取无需重新索引)。重新索引会写入新的平铺 `version-N` 目录并保留旧版本,因此重建过程中现有索引不会被破坏。即使知识库处于 **error** 状态,也可以单独移除其中一份文档 — 无需完整地删除重建,就能丢弃解析失败的文件。文档解析 — 纯文本、MinerU、Docling、Tika、markitdown、PyMuPDF4LLM 或 LiteParse — 在 **Settings → Knowledge Base** 中选择,本地模型下载默认关闭。Docling 也可以以 **remote** 模式运行,对接 Docling Serve 服务器(无需本地安装或模型),可在 **Settings → Document Parsing** 中配置(`mode=remote`、服务器 Base URL 和可选的 API Key),或通过 `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` 环境变量配置。Tika 仅支持远程模式,需指向 Apache Tika 服务器(`TIKA_SERVER_URL`)。CLI 通过 `deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 和 `delete` 来管理完整生命周期。+创建 KB 时,可以选择**新建**(上传文档并构建全新索引)或**链接已有**(复用在其他地方构建的索引,原位读取无需重新索引)。知识库还可以追踪 **GitHub 来源** — 一个仓库、分支和 glob 匹配模式,其中的 Markdown 文件会被拉取并可按需重新同步,让你关注的文档保持最新,无需重新上传。重新索引会写入新的平铺 `version-N` 目录并保留旧版本,因此重建过程中现有索引不会被破坏。即使知识库处于 **error** 状态,也可以单独移除其中一份文档 — 无需完整地删除重建,就能丢弃解析失败的文件。文档解析 — 纯文本、MinerU、Docling、Tika、markitdown、PyMuPDF4LLM 或 LiteParse — 在 **Settings → Knowledge Base** 中选择,本地模型下载默认关闭。Docling 也可以以 **remote** 模式运行,对接 Docling Serve 服务器(无需本地安装或模型),可在 **Settings → Document Parsing** 中配置(`mode=remote`、服务器 Base URL 和可选的 API Key),或通过 `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` 环境变量配置。Tika 仅支持远程模式,需指向 Apache Tika 服务器(`TIKA_SERVER_URL`)。CLI 通过 `deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 和 `delete` 来管理完整生命周期。</details>@@ -573,6 +575,7 @@ deeptutor run deep_question "就那篇调研测验我" --session "$SID" --format| 命令 | 说明 ||:---|:---|| `deeptutor init` | 为当前工作区创建或更新 `data/user/settings` |+| `deeptutor doctor [--online]` | 检查工作区是否已准备好启动会话;`--online` 还会探测已配置的模型提供商,`--format json` 打印报告 || `deeptutor start [--home PATH] [--dev]` | 同时启动后端 + 前端;`--dev` 启用前端热更新 || `deeptutor serve [--port PORT]` | 仅启动 FastAPI 后端 || `deeptutor run <capability> <message>` | 运行单次能力对话(`chat`、`deep_solve`、`deep_question`、`deep_research`、`visualize`、`math_animator`、`mastery_path`);添加 `--format json` 可获得 NDJSON 输出 |diff --git a/assets/README/README_ES.md b/assets/README/README_ES.mdindex cbb795d34..a4241db2a 100644--- a/assets/README/README_ES.md+++ b/assets/README/README_ES.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **Solo se necesita publicar `3782`.** El navegador habla exclusivamente con el origen del frontend; el middleware de Next.js (`web/proxy.ts`) reenvía `/api/*` y `/ws/*` al backend FastAPI **dentro del contenedor**. Publicar `8001` (`-p 127.0.0.1:8001:8001`) es opcional — útil solo para acceder a la API directamente con curl o scripts.-Abre [http://127.0.0.1:3782](http://127.0.0.1:3782). El contenedor crea `/app/data/user/settings/*.json` en el primer arranque; configura los proveedores de modelos desde la página de Settings web. La configuración, las claves API, los registros, los archivos del espacio de trabajo, la memoria y las bases de conocimiento persisten en el volumen `deeptutor-data`.+Abre [http://127.0.0.1:3782](http://127.0.0.1:3782). El contenedor crea `/app/data/user/settings/*.json` en el primer arranque; configura los proveedores de modelos desde la página de Settings web. La configuración, las claves API, los registros, los archivos del espacio de trabajo, la memoria y las bases de conocimiento persisten en el volumen `deeptutor-data`. Los extras opcionales pertenecen al despliegue, no a una shell: establece `DEEPTUTOR_EXTRAS` (y `DEEPTUTOR_APT_PACKAGES` para bibliotecas de sistema) y cada contenedor iniciado a partir de él los vuelve a aplicar, mientras que un `docker exec … pip install` se perdería en el siguiente `compose down`.- **Puertos de host diferentes:** cambia el lado izquierdo de cada mapeo `-p host:container` (ej. `-p 127.0.0.1:8088:3782`). Si cambias los puertos del lado del contenedor en `/app/data/user/settings/system.json`, reinicia y actualiza el lado derecho de cada mapeo para que coincida.- **Desconectado:** agrega `-d`, luego `docker logs -f deeptutor` para seguir, `docker stop deeptutor` para detener, `docker rm deeptutor` antes de reutilizar el nombre. El volumen `deeptutor-data` mantiene tu configuración y espacio de trabajo entre reinicios.@@ -369,6 +369,8 @@ Cada partner tiene un `SOUL.md`, selección de modelo, canales, política de herLa capa de canales está impulsada por esquema y puede conectarse a plataformas IM como Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat y Microsoft Teams dependiendo de los extras instalados y las credenciales configuradas. Un partner también puede conectarse como subagente y ser consultado desde un turno de chat normal — consulta **Mis Agentes** a continuación.+Para una configuración más rápida, la página de canales de Partner puede crear una app de Feishu/Lark o un bot IA de WeCom, o iniciar sesión con una cuenta personal de WeChat, a partir de un código QR dibujado en el navegador en lugar del registro del servidor. Feishu/Lark detecta el dominio de la cuenta y guarda al usuario que escanea como el remitente permitido inicial. WeCom conserva una lista blanca existente y de lo contrario predetermina a todos los usuarios que pueden alcanzar al bot, con una advertencia visible de acceso abierto; los formularios de canal manuales siguen disponibles si el protocolo de escaneo de un proveedor cambia.+</details><details>@@ -378,7 +380,7 @@ La capa de canales está impulsada por esquema y puede conectarse a plataformas<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Espacio de trabajo de Mis Agentes DeepTutor" width="900"></div>-Mis Agentes convierte a otros agentes en contexto para DeepTutor y hace dos cosas distintas. **Conectar un agente en vivo** — una CLI de Claude Code, Codex, Gemini, Kimi, opencode o MiMo Code en tu máquina, o uno de tus Partners — y consultarlo desde dentro de un turno de chat: DeepTutor realmente *ejecuta* el otro agente y transmite su trabajo al panel de Activity a través de la herramienta `consult_subagent`. Selecciónalo con el chip de Agente (o escribe `@`), y establece cuántas rondas puede tomar la consulta.+Mis Agentes convierte a otros agentes en contexto para DeepTutor y hace dos cosas distintas. **Conectar un agente en vivo** — una CLI de Claude Code, Codex, Gemini, Antigravity, Kimi, opencode o MiMo Code en tu máquina, o uno de tus Partners — y consultarlo desde dentro de un turno de chat: DeepTutor realmente *ejecuta* el otro agente y transmite su trabajo al panel de Activity a través de la herramienta `consult_subagent`. Selecciónalo con el chip de Agente (o escribe `@`), y establece cuántas rondas puede tomar la consulta.<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consultando un subagente Claude Code en vivo" width="900">@@ -439,7 +441,7 @@ Las bases de conocimiento son las colecciones de documentos detrás del RAG —<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Crear una base de conocimiento" width="900"></div>-Al crear una KB, puedes **crear nueva** (subir documentos y construir un índice nuevo) o **vincular existente** (reutilizar un índice construido en otro lugar, leer en el lugar sin re-indexar). La re-indexación escribe un nuevo directorio `version-N` plano y conserva los anteriores, de modo que un índice funcional nunca se destruye a mitad de la reconstrucción. Un solo documento puede eliminarse incluso de una base en estado de **error** — descartando un archivo que no se pudo analizar sin necesidad de borrar y reconstruir todo. El análisis de documentos — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM o LiteParse — se elige en **Settings → Knowledge Base**, con descargas de modelos locales desactivadas por defecto. Docling también puede ejecutarse en modo **remoto** contra un servidor Docling Serve (sin necesidad de instalación local ni modelos), configurado a través de **Settings → Document Parsing** (`mode=remote`, una URL base de servidor y una clave API opcional) o las variables de entorno `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika es solo remoto y apunta a un servidor Apache Tika (`TIKA_SERVER_URL`). La CLI refleja el ciclo de vida con `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` y `delete`.+Al crear una KB, puedes **crear nueva** (subir documentos y construir un índice nuevo) o **vincular existente** (reutilizar un índice construido en otro lugar, leer en el lugar sin re-indexar). Una KB también puede rastrear **fuentes de GitHub** — un repositorio, rama y patrón glob cuyo Markdown se trae y se resincroniza bajo demanda, de modo que la documentación que sigues se mantiene actualizada sin volver a subirla. La re-indexación escribe un nuevo directorio `version-N` plano y conserva los anteriores, de modo que un índice funcional nunca se destruye a mitad de la reconstrucción. Un solo documento puede eliminarse incluso de una base en estado de **error** — descartando un archivo que no se pudo analizar sin necesidad de borrar y reconstruir todo. El análisis de documentos — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM o LiteParse — se elige en **Settings → Knowledge Base**, con descargas de modelos locales desactivadas por defecto. Docling también puede ejecutarse en modo **remoto** contra un servidor Docling Serve (sin necesidad de instalación local ni modelos), configurado a través de **Settings → Document Parsing** (`mode=remote`, una URL base de servidor y una clave API opcional) o las variables de entorno `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika es solo remoto y apunta a un servidor Apache Tika (`TIKA_SERVER_URL`). La CLI refleja el ciclo de vida con `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` y `delete`.</details>@@ -585,6 +587,7 @@ El repo incluye un [`SKILL.md`](../../SKILL.md) raíz — un documento de traspa| Comando | Descripción ||:---|:---|| `deeptutor init` | Crear o actualizar `data/user/settings` para el espacio de trabajo actual |+| `deeptutor doctor [--online]` | Verificar si el espacio de trabajo está listo para iniciar una sesión; `--online` también sondea el proveedor de modelo configurado, `--format json` imprime el informe || `deeptutor start [--home PATH] [--dev]` | Lanzar backend + frontend juntos || `deeptutor serve [--port PORT]` | Iniciar solo el backend FastAPI || `deeptutor run <capability> <message>` | Ejecutar un turno de capacidad único (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); agrega `--format json` para salida NDJSON |diff --git a/assets/README/README_FR.md b/assets/README/README_FR.mdindex c5980310a..2b877adb8 100644--- a/assets/README/README_FR.md+++ b/assets/README/README_FR.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **Seul le port `3782` doit être publié.** Le navigateur parle exclusivement à l'origine frontend ; le middleware Next.js (`web/proxy.ts`) transmet `/api/*` et `/ws/*` au backend FastAPI **à l'intérieur du conteneur**. La publication de `8001` (`-p 127.0.0.1:8001:8001`) est optionnelle — utile uniquement pour accéder directement à l'API avec curl ou des scripts.-Ouvrez [http://127.0.0.1:3782](http://127.0.0.1:3782). Le conteneur crée `/app/data/user/settings/*.json` au premier démarrage ; configurez les fournisseurs de modèles depuis la page Paramètres Web. La configuration, les clés API, les journaux, les fichiers d'espace de travail, la mémoire et les bases de connaissances persistent dans le volume `deeptutor-data`.+Ouvrez [http://127.0.0.1:3782](http://127.0.0.1:3782). Le conteneur crée `/app/data/user/settings/*.json` au premier démarrage ; configurez les fournisseurs de modèles depuis la page Paramètres Web. La configuration, les clés API, les journaux, les fichiers d'espace de travail, la mémoire et les bases de connaissances persistent dans le volume `deeptutor-data`. Les extras optionnels appartiennent au déploiement, pas à un shell : définissez `DEEPTUTOR_EXTRAS` (et `DEEPTUTOR_APT_PACKAGES` pour les bibliothèques système) et chaque conteneur démarré à partir de celui-ci les réapplique, alors qu'un `docker exec … pip install` serait perdu au prochain `compose down`.- **Ports hôte différents :** modifiez le côté gauche de chaque correspondance `-p hôte:conteneur` (ex. `-p 127.0.0.1:8088:3782`). Si vous changez les ports côté conteneur dans `/app/data/user/settings/system.json`, redémarrez et mettez à jour le côté droit de chaque correspondance en conséquence.- **Détaché :** ajoutez `-d`, puis `docker logs -f deeptutor` pour suivre, `docker stop deeptutor` pour arrêter, `docker rm deeptutor` avant de réutiliser le nom. Le volume `deeptutor-data` conserve vos paramètres et votre espace de travail à travers les redémarrages.@@ -379,6 +379,8 @@ Chaque partner a un `SOUL.md`, une sélection de modèle, des canaux, une politiLa couche de canaux est pilotée par schéma et peut se connecter à des plateformes IM telles que Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat et Microsoft Teams selon les extras installés et les identifiants configurés. Un partner peut également être connecté comme sous-agent et consulté depuis un tour de chat normal — voir **My Agents** ci-dessous.+Pour une configuration plus rapide, la page de canal Partner peut créer une application Feishu/Lark ou un bot IA WeCom, ou connecter un compte WeChat personnel, à partir d'un scan QR dessiné dans le navigateur plutôt que dans le journal du serveur. Feishu/Lark détecte le domaine du compte et enregistre l'utilisateur qui scanne comme expéditeur autorisé initial. WeCom conserve une liste d'autorisation existante et, sinon, autorise par défaut tous les utilisateurs pouvant atteindre le bot, avec un avertissement visible d'accès ouvert ; les formulaires de canal manuels restent disponibles si le protocole de scan d'un fournisseur change.+</details><details>@@ -388,7 +390,7 @@ La couche de canaux est pilotée par schéma et peut se connecter à des platefo<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Espace de travail My Agents de DeepTutor" width="900"></div>-My Agents transforme d'autres agents en contexte pour DeepTutor, et fait deux choses distinctes. **Connectez un agent en direct** — une CLI Claude Code, Codex, Gemini, Kimi, opencode ou MiMo Code sur votre machine, ou l'un de vos Partners — et consultez-le depuis l'intérieur d'un tour de chat : DeepTutor *exécute* réellement l'autre agent et diffuse son travail dans le panneau d'Activité via l'outil `consult_subagent`. Sélectionnez-le avec la puce Agent (ou tapez `@`), et définissez combien de rounds la consultation peut prendre.+My Agents transforme d'autres agents en contexte pour DeepTutor, et fait deux choses distinctes. **Connectez un agent en direct** — une CLI Claude Code, Codex, Gemini, Antigravity, Kimi, opencode ou MiMo Code sur votre machine, ou l'un de vos Partners — et consultez-le depuis l'intérieur d'un tour de chat : DeepTutor *exécute* réellement l'autre agent et diffuse son travail dans le panneau d'Activité via l'outil `consult_subagent`. Sélectionnez-le avec la puce Agent (ou tapez `@`), et définissez combien de rounds la consultation peut prendre.<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consultation d'un sous-agent Claude Code en direct" width="900">@@ -449,7 +451,7 @@ Les bases de connaissances sont les collections de documents derrière le RAG<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Créer une base de connaissances" width="900"></div>-En créant une KB, vous choisissez soit de **créer nouvelle** (uploadez des documents et construisez un index frais) soit de **lier une existante** (réutilisez un index construit ailleurs, lu en place sans re-indexation). La re-indexation écrit un nouveau répertoire plat `version-N` et conserve les précédents, donc un index fonctionnel n'est jamais détruit en milieu de reconstruction. Un seul document peut être supprimé même d'une base en état d'**erreur** — retirer un fichier dont l'analyse a échoué sans devoir tout supprimer et reconstruire. L'analyse de documents — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM ou LiteParse — est choisie dans **Paramètres → Base de Connaissances**, avec les téléchargements de modèles locaux désactivés par défaut. Docling peut aussi fonctionner en mode **distant** contre un serveur Docling Serve (aucune installation ni modèle local nécessaire), configuré via **Paramètres → Analyse de Documents** (`mode=remote`, une URL de base de serveur, et une clé API optionnelle) ou les variables d'environnement `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika est distant uniquement et pointe vers un serveur Apache Tika (`TIKA_SERVER_URL`). La CLI reprend le cycle de vie avec `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` et `delete`.+En créant une KB, vous choisissez soit de **créer nouvelle** (uploadez des documents et construisez un index frais) soit de **lier une existante** (réutilisez un index construit ailleurs, lu en place sans re-indexation). Une KB peut aussi suivre des **sources GitHub** — un dépôt, une branche et un glob dont le Markdown est récupéré et resynchronisé à la demande, afin que la documentation que vous suivez reste à jour sans nouveau téléversement. La re-indexation écrit un nouveau répertoire plat `version-N` et conserve les précédents, donc un index fonctionnel n'est jamais détruit en milieu de reconstruction. Un seul document peut être supprimé même d'une base en état d'**erreur** — retirer un fichier dont l'analyse a échoué sans devoir tout supprimer et reconstruire. L'analyse de documents — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM ou LiteParse — est choisie dans **Paramètres → Base de Connaissances**, avec les téléchargements de modèles locaux désactivés par défaut. Docling peut aussi fonctionner en mode **distant** contre un serveur Docling Serve (aucune installation ni modèle local nécessaire), configuré via **Paramètres → Analyse de Documents** (`mode=remote`, une URL de base de serveur, et une clé API optionnelle) ou les variables d'environnement `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika est distant uniquement et pointe vers un serveur Apache Tika (`TIKA_SERVER_URL`). La CLI reprend le cycle de vie avec `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` et `delete`.</details>@@ -595,6 +597,7 @@ Le dépôt inclut un [`SKILL.md`](SKILL.md) racine — un document de passation| Commande | Description ||:---|:---|| `deeptutor init` | Créer ou mettre à jour `data/user/settings` pour l'espace de travail actuel |+| `deeptutor doctor [--online]` | Vérifier si l'espace de travail est prêt à démarrer une session ; `--online` sonde aussi le fournisseur de modèle configuré, `--format json` affiche le rapport || `deeptutor start [--home PATH] [--dev]` | Lancer le backend + frontend ensemble || `deeptutor serve [--port PORT]` | Démarrer uniquement le backend FastAPI || `deeptutor run <capacité> <message>` | Exécuter un seul tour de capacité (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`) ; ajoutez `--format json` pour la sortie NDJSON |diff --git a/assets/README/README_HI.md b/assets/README/README_HI.mdindex d761da521..e5528d7e9 100644--- a/assets/README/README_HI.md+++ b/assets/README/README_HI.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **केवल `3782` publish करना जरूरी है।** Browser exclusively frontend origin से बात करता है; Next.js middleware (`web/proxy.ts`) **container के अंदर** `/api/*` और `/ws/*` को FastAPI backend पर forward करता है। `8001` publish करना (`-p 127.0.0.1:8001:8001`) optional है — केवल curl या scripts से API directly hit करने के लिए उपयोगी।-[http://127.0.0.1:3782](http://127.0.0.1:3782) खोलें। Container पहले boot पर `/app/data/user/settings/*.json` बनाता है; Web Settings page से model providers configure करें। Config, API keys, logs, workspace files, memory, और knowledge bases `deeptutor-data` volume में persist करते हैं।+[http://127.0.0.1:3782](http://127.0.0.1:3782) खोलें। Container पहले boot पर `/app/data/user/settings/*.json` बनाता है; Web Settings page से model providers configure करें। Config, API keys, logs, workspace files, memory, और knowledge bases `deeptutor-data` volume में persist करते हैं। वैकल्पिक extras deployment पर belong करते हैं, किसी shell में नहीं: `DEEPTUTOR_EXTRAS` (और system libraries के लिए `DEEPTUTOR_APT_PACKAGES`) set करें, और उससे शुरू होने वाला हर container उन्हें फिर से apply करता है — जबकि एक `docker exec … pip install` अगले `compose down` पर खो जाता है।- **अलग host ports:** प्रत्येक `-p host:container` mapping के left side को बदलें (जैसे `-p 127.0.0.1:8088:3782`)। अगर आप `/app/data/user/settings/system.json` में container-side ports बदलते हैं, तो restart करें और match करने के लिए प्रत्येक mapping के right side को update करें।- **Detached:** `-d` add करें, फिर follow करने के लिए `docker logs -f deeptutor`, stop करने के लिए `docker stop deeptutor`, नाम reuse करने से पहले `docker rm deeptutor`। `deeptutor-data` volume आपकी settings और workspace को restarts के पार रखता है।@@ -357,6 +357,8 @@ Partners अपनी soul, model policy, library, memory, और channels वChannel layer schema-driven है और installed extras और configured credentials के आधार पर Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat, और Microsoft Teams जैसे IM platforms से connect हो सकती है। एक partner को subagent के रूप में भी connect किया जा सकता है और normal chat turn से consult किया जा सकता है — नीचे **My Agents** देखें।+तेज़ setup के लिए, Partner channel page एक Feishu/Lark app या WeCom AI bot create कर सकता है, या एक personal WeChat account को sign in करा सकता है, server log की बजाय browser में draw किए गए एक QR scan से। Feishu/Lark account domain detect करता है और scanning user को initial allowed sender के रूप में save करता है। WeCom एक existing allowlist रखता है और अन्यथा bot तक पहुंच सकने वाले सभी users को default करता है, एक visible open-access warning के साथ; अगर किसी provider का scan protocol बदलता है तो manual channel forms उपलब्ध रहते हैं।+</details><details>@@ -366,7 +368,7 @@ Channel layer schema-driven है और installed extras और configured cre<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agents workspace" width="900"></div>-My Agents दूसरे agents को DeepTutor के लिए context बनाता है, और दो अलग काम करता है। **लाइव एजेंट connect करें** — आपकी machine पर एक Claude Code, Codex, Gemini, Kimi, opencode, या MiMo Code CLI, या आपके Partners में से एक — और इसे chat turn के अंदर से consult करें: DeepTutor actually दूसरे agent को *run* करता है और इसके काम को `consult_subagent` tool के जरिए Activity panel में stream करता है। इसे Agent chip से select करें (या `@` type करें), और set करें कि consult कितने rounds ले सकता है।+My Agents दूसरे agents को DeepTutor के लिए context बनाता है, और दो अलग काम करता है। **लाइव एजेंट connect करें** — आपकी machine पर एक Claude Code, Codex, Gemini, Antigravity, Kimi, opencode, या MiMo Code CLI, या आपके Partners में से एक — और इसे chat turn के अंदर से consult करें: DeepTutor actually दूसरे agent को *run* करता है और इसके काम को `consult_subagent` tool के जरिए Activity panel में stream करता है। इसे Agent chip से select करें (या `@` type करें), और set करें कि consult कितने rounds ले सकता है।<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Claude Code subagent को live consult करना" width="900">@@ -427,7 +429,7 @@ Knowledge bases RAG के पीछे document collections हैं — व<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="एक knowledge base बनाएं" width="900"></div>-KB बनाते समय, आप either **नया create** करते हैं (documents upload करें और fresh index build करें) या **existing link** करते हैं (कहीं और बना index reuse करें, re-index के बिना in-place पढ़ें)। Re-indexing एक नई flat `version-N` directory लिखता है और prior ones रखता है, इसलिए एक working index rebuild के दौरान कभी destroy नहीं होता। एक single document को **error**-state base से भी remove किया जा सकता है — पूरी delete-and-rebuild के बिना parse होने में failed हुई file को drop करना। Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, या LiteParse — **Settings → Knowledge Base** में choose किया जाता है, local model downloads default रूप से off हैं। Docling को **remote** mode में भी एक Docling Serve server के विरुद्ध चलाया जा सकता है (कोई local install या models की जरूरत नहीं), जिसे **Settings → Document Parsing** (`mode=remote`, एक server base URL, और एक optional API key) या `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables के जरिए configure किया जाता है। Tika remote-only है और एक Apache Tika server (`TIKA_SERVER_URL`) पर point करता है। CLI lifecycle को `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, और `delete` से mirror करता है।+KB बनाते समय, आप either **नया create** करते हैं (documents upload करें और fresh index build करें) या **existing link** करते हैं (कहीं और बना index reuse करें, re-index के बिना in-place पढ़ें)। एक KB **GitHub sources** को भी track कर सकती है — एक repo, branch, और glob जिसका Markdown pull किया जाता है और demand पर re-sync किया जाता है, इसलिए जो documentation आप follow करते हैं वह re-upload किए बिना current बनी रहती है। Re-indexing एक नई flat `version-N` directory लिखता है और prior ones रखता है, इसलिए एक working index rebuild के दौरान कभी destroy नहीं होता। एक single document को **error**-state base से भी remove किया जा सकता है — पूरी delete-and-rebuild के बिना parse होने में failed हुई file को drop करना। Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, या LiteParse — **Settings → Knowledge Base** में choose किया जाता है, local model downloads default रूप से off हैं। Docling को **remote** mode में भी एक Docling Serve server के विरुद्ध चलाया जा सकता है (कोई local install या models की जरूरत नहीं), जिसे **Settings → Document Parsing** (`mode=remote`, एक server base URL, और एक optional API key) या `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables के जरिए configure किया जाता है। Tika remote-only है और एक Apache Tika server (`TIKA_SERVER_URL`) पर point करता है। CLI lifecycle को `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, और `delete` से mirror करता है।</details>@@ -573,6 +575,7 @@ Repo एक root [`SKILL.md`](../../SKILL.md) ship करता है — ए| Command | विवरण ||:---|:---|| `deeptutor init` | Current workspace के लिए `data/user/settings` create या update करें |+| `deeptutor doctor [--online]` | Check करें कि workspace session शुरू करने के लिए ready है या नहीं; `--online` configured model provider को भी probe करता है, `--format json` report print करता है || `deeptutor start [--home PATH] [--dev]` | Backend + frontend को एक साथ launch करें || `deeptutor serve [--port PORT]` | केवल FastAPI backend start करें || `deeptutor run <capability> <message>` | एक single capability turn run करें (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); NDJSON output के लिए `--format json` add करें |diff --git a/assets/README/README_JA.md b/assets/README/README_JA.mdindex 65110f1fa..f68891d42 100644--- a/assets/README/README_JA.md+++ b/assets/README/README_JA.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **公開が必要なのは`3782`のみです。** ブラウザはフロントエンドオリジンのみと通信し、Next.jsミドルウェア(`web/proxy.ts`)が`/api/*`と`/ws/*`をコンテナ**内部の**FastAPIバックエンドに転送します。`8001`を公開(`-p 127.0.0.1:8001:8001`)するのはオプションで、curlやスクリプトでAPIに直接アクセスする場合にのみ便利です。-[http://127.0.0.1:3782](http://127.0.0.1:3782)を開いてください。コンテナは初回起動時に`/app/data/user/settings/*.json`を作成します。Web Settingsページからモデルプロバイダーを設定してください。設定、APIキー、ログ、ワークスペースファイル、メモリ、知識ベースは`deeptutor-data`ボリュームに永続化されます。+[http://127.0.0.1:3782](http://127.0.0.1:3782)を開いてください。コンテナは初回起動時に`/app/data/user/settings/*.json`を作成します。Web Settingsページからモデルプロバイダーを設定してください。設定、APIキー、ログ、ワークスペースファイル、メモリ、知識ベースは`deeptutor-data`ボリュームに永続化されます。オプションのエクストラはシェルではなくデプロイメント自体に属します:`DEEPTUTOR_EXTRAS`(システムライブラリには`DEEPTUTOR_APT_PACKAGES`も)を設定すれば、そこから起動するすべてのコンテナがそれらを再適用します。一方`docker exec … pip install`は次の`compose down`で失われてしまいます。- **異なるホストポート:** 各`-p host:container`マッピングの左側を変更してください(例:`-p 127.0.0.1:8088:3782`)。`/app/data/user/settings/system.json`のコンテナ側ポートを変更する場合は、再起動して各マッピングの右側を一致するよう更新してください。- **デタッチ:** `-d`を追加し、`docker logs -f deeptutor`でログを追跡、`docker stop deeptutor`で停止、名前を再利用する前に`docker rm deeptutor`を実行。`deeptutor-data`ボリュームは再起動をまたいで設定とワークスペースを保持します。@@ -357,6 +357,8 @@ Partnersは独自のソウル、モデルポリシー、ライブラリ、メモチャンネル層はスキーマ駆動で、インストール済みエクストラと設定された認証情報に応じて、Feishu、Telegram、Slack、Discord、DingTalk、QQ/NapCat、WeCom、WhatsApp、Zulip、Mattermost、Matrix、Mochat、Microsoft Teamsなどのプラットフォームに接続できます。PartnerはサブエージェントとしてMy Agentsに接続でき、通常のチャットターンから相談できます。詳細は以下の**My Agents**を参照してください。+セットアップを高速化するため、Partnerチャンネルページはサーバーログではなくブラウザに描画されたQRコードのスキャンから、Feishu/Larkアプリの作成、WeCom AIボットの作成、または個人のWeChatアカウントのサインインを行えます。Feishu/Larkはアカウントドメインを検出し、スキャンしたユーザーを初期許可送信者として保存します。WeComは既存の許可リストを保持し、それ以外の場合はボットに到達できるすべてのユーザーをデフォルトで許可します(目に見えるオープンアクセス警告付き)。プロバイダーのスキャンプロトコルが変更された場合に備え、手動のチャンネルフォームも引き続き利用できます。+</details><details>@@ -366,7 +368,7 @@ Partnersは独自のソウル、モデルポリシー、ライブラリ、メモ<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agentsワークスペース" width="900"></div>-My Agentsは他のエージェントをDeepTutorのコンテキストにし、2つの異なることを行います。**ライブエージェントを接続** — マシン上のClaude Code、Codex、Gemini、Kimi、opencode、MiMo CodeいずれかのCLI、またはPartnerの1つ — してチャットターン内から相談できます。DeepTutorは実際に他のエージェントを*実行*し、`consult_subagent`ツールを介してその作業をActivityパネルにストリーミングします。Agentチップ(または`@`入力)で選択し、相談で取れるラウンド数を設定します。+My Agentsは他のエージェントをDeepTutorのコンテキストにし、2つの異なることを行います。**ライブエージェントを接続** — マシン上のClaude Code、Codex、Gemini、Antigravity、Kimi、opencode、MiMo CodeいずれかのCLI、またはPartnerの1つ — してチャットターン内から相談できます。DeepTutorは実際に他のエージェントを*実行*し、`consult_subagent`ツールを介してその作業をActivityパネルにストリーミングします。Agentチップ(または`@`入力)で選択し、相談で取れるラウンド数を設定します。<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Claude Codeサブエージェントをライブで相談" width="900">@@ -427,7 +429,7 @@ Bookは選択したソースをインタラクティブな**生きている本**<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="知識ベースの作成" width="900"></div>-KBを作成する際は、**新規作成**(ドキュメントをアップロードして新しいインデックスを構築)または**既存をリンク**(再インデックスなしで既に構築されたインデックスを再利用)を選択します。再インデックスは新しいフラットな`version-N`ディレクトリを書き込み、以前のものを保持するため、再構築中に作業中のインデックスが破壊されることはありません。解析に失敗したファイルを完全な削除・再構築なしで取り除けるよう、**error**状態のベースからでも単一のドキュメントを削除できます。ドキュメント解析(Text-only、MinerU、Docling、Tika、markitdown、PyMuPDF4LLM、LiteParse)は**Settings → Knowledge Base**で選択し、ローカルモデルのダウンロードはデフォルトでオフです。Docling は、Docling Serve サーバーに対して**remote**モードで実行することもできます(ローカルインストールやモデルは不要)。この設定は**Settings → Document Parsing**(`mode=remote`、サーバーのベースURL、オプションのAPIキー)または `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` 環境変数で行います。Tikaはリモート専用で、Apache Tikaサーバー(`TIKA_SERVER_URL`)を指定します。CLIは`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default`、`delete`でライフサイクルをミラーします。+KBを作成する際は、**新規作成**(ドキュメントをアップロードして新しいインデックスを構築)または**既存をリンク**(再インデックスなしで既に構築されたインデックスを再利用)を選択します。KBは**GitHubソース** — Markdownを取り込みオンデマンドで再同期するリポジトリ・ブランチ・globの組み合わせ — も追跡できるため、フォローしているドキュメントを再アップロードなしで最新の状態に保てます。再インデックスは新しいフラットな`version-N`ディレクトリを書き込み、以前のものを保持するため、再構築中に作業中のインデックスが破壊されることはありません。解析に失敗したファイルを完全な削除・再構築なしで取り除けるよう、**error**状態のベースからでも単一のドキュメントを削除できます。ドキュメント解析(Text-only、MinerU、Docling、Tika、markitdown、PyMuPDF4LLM、LiteParse)は**Settings → Knowledge Base**で選択し、ローカルモデルのダウンロードはデフォルトでオフです。Docling は、Docling Serve サーバーに対して**remote**モードで実行することもできます(ローカルインストールやモデルは不要)。この設定は**Settings → Document Parsing**(`mode=remote`、サーバーのベースURL、オプションのAPIキー)または `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` 環境変数で行います。Tikaはリモート専用で、Apache Tikaサーバー(`TIKA_SERVER_URL`)を指定します。CLIは`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default`、`delete`でライフサイクルをミラーします。</details>@@ -573,6 +575,7 @@ deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format j| コマンド | 説明 ||:---|:---|| `deeptutor init` | 現在のワークスペースの`data/user/settings`を作成または更新 |+| `deeptutor doctor [--online]` | ワークスペースがセッションを開始できる状態か確認;`--online`は設定済みのモデルプロバイダーもプローブし、`--format json`はレポートを出力 || `deeptutor start [--home PATH] [--dev]` | バックエンド + フロントエンドを一緒に起動 || `deeptutor serve [--port PORT]` | FastAPIバックエンドのみ起動 || `deeptutor run <capability> <message>` | 単一機能ターンを実行(`chat`、`deep_solve`、`deep_question`、`deep_research`、`visualize`、`math_animator`、`mastery_path`);`--format json`でNDJSON出力 |diff --git a/assets/README/README_PL.md b/assets/README/README_PL.mdindex fb2237cb6..31167b86e 100644--- a/assets/README/README_PL.md+++ b/assets/README/README_PL.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **Tylko `3782` musi być opublikowane.** Przeglądarka komunikuje się wyłącznie z serwerem frontendu; middleware Next.js (`web/proxy.ts`) przekazuje `/api/*` i `/ws/*` do backendu FastAPI **wewnątrz kontenera**. Opublikowanie `8001` (`-p 127.0.0.1:8001:8001`) jest opcjonalne — przydatne tylko do bezpośredniego uderzania w API z curl lub skryptów.-Otwórz [http://127.0.0.1:3782](http://127.0.0.1:3782). Kontener tworzy `/app/data/user/settings/*.json` przy pierwszym uruchomieniu; skonfiguruj dostawców modeli ze strony Web Settings. Konfiguracja, klucze API, dzienniki, pliki obszaru roboczego, pamięć i bazy wiedzy są przechowywane w woluminie `deeptutor-data`.+Otwórz [http://127.0.0.1:3782](http://127.0.0.1:3782). Kontener tworzy `/app/data/user/settings/*.json` przy pierwszym uruchomieniu; skonfiguruj dostawców modeli ze strony Web Settings. Konfiguracja, klucze API, dzienniki, pliki obszaru roboczego, pamięć i bazy wiedzy są przechowywane w woluminie `deeptutor-data`. Opcjonalne dodatki należą do wdrożenia, nie do powłoki: ustaw `DEEPTUTOR_EXTRAS` (oraz `DEEPTUTOR_APT_PACKAGES` dla bibliotek systemowych), a każdy kontener uruchomiony z tego wdrożenia ponownie je zastosuje, podczas gdy `docker exec … pip install` zostałby utracony przy kolejnym `compose down`.- **Różne porty hosta:** zmień lewą stronę każdego mapowania `-p host:kontener` (np. `-p 127.0.0.1:8088:3782`). Jeśli zmienisz porty po stronie kontenera w `/app/data/user/settings/system.json`, uruchom ponownie i zaktualizuj prawą stronę każdego mapowania, aby pasowała.- **Odłączony:** dodaj `-d`, następnie `docker logs -f deeptutor`, aby śledzić, `docker stop deeptutor`, aby zatrzymać, `docker rm deeptutor` przed ponownym użyciem nazwy. Wolumin `deeptutor-data` przechowuje ustawienia i obszar roboczy między restartami.@@ -357,6 +357,8 @@ Każdy partner ma `SOUL.md`, wybór modelu, kanały, politykę narzędzi i przypWarstwa kanałów jest sterowana schematem i może łączyć się z platformami IM takimi jak Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat i Microsoft Teams w zależności od zainstalowanych dodatków i skonfigurowanych danych uwierzytelniających. Partner może być również podłączony jako subagent i konsultowany z normalnej tury czatu — patrz **My Agents** poniżej.+Dla szybszej konfiguracji strona kanału Partner może utworzyć aplikację Feishu/Lark lub bota AI WeCom, albo zalogować osobiste konto WeChat, na podstawie kodu QR narysowanego w przeglądarce zamiast w dzienniku serwera. Feishu/Lark wykrywa domenę konta i zapisuje skanującego użytkownika jako początkowego dozwolonego nadawcę. WeCom zachowuje istniejącą listę dozwolonych, a w przeciwnym razie domyślnie zezwala wszystkim użytkownikom, którzy mogą dotrzeć do bota, z widocznym ostrzeżeniem o otwartym dostępie; ręczne formularze kanałów pozostają dostępne, jeśli protokół skanowania dostawcy się zmieni.+</details><details>@@ -366,7 +368,7 @@ Warstwa kanałów jest sterowana schematem i może łączyć się z platformami<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Obszar roboczy My Agents DeepTutor" width="900"></div>-My Agents zamienia innych agentów w kontekst dla DeepTutor i wykonuje dwie odrębne rzeczy. **Połącz żywego agenta** — CLI Claude Code, Codex, Gemini, Kimi, opencode lub MiMo Code na twoim komputerze, lub jednego z twoich Partners — i konsultuj go z wnętrza tury czatu: DeepTutor faktycznie *uruchamia* drugiego agenta i strumieniuje jego pracę do panelu Activity przez narzędzie `consult_subagent`. Wybierz go chipem Agent (lub wpisz `@`) i ustaw ile rund może trwać konsultacja.+My Agents zamienia innych agentów w kontekst dla DeepTutor i wykonuje dwie odrębne rzeczy. **Połącz żywego agenta** — CLI Claude Code, Codex, Gemini, Antigravity, Kimi, opencode lub MiMo Code na twoim komputerze, lub jednego z twoich Partners — i konsultuj go z wnętrza tury czatu: DeepTutor faktycznie *uruchamia* drugiego agenta i strumieniuje jego pracę do panelu Activity przez narzędzie `consult_subagent`. Wybierz go chipem Agent (lub wpisz `@`) i ustaw ile rund może trwać konsultacja.<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Konsultowanie subagenta Claude Code na żywo" width="900">@@ -427,7 +429,7 @@ Bazy wiedzy to kolekcje dokumentów za RAG — ugruntowują tury Chat, edycje Co<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Tworzenie bazy wiedzy" width="900"></div>-Tworząc KB, albo **tworzysz nową** (przesyłasz dokumenty i budujesz świeży indeks) albo **łączysz istniejącą** (ponownie używasz indeksu zbudowanego gdzie indziej, czytasz w miejscu bez ponownego indeksowania). Ponowne indeksowanie zapisuje nowy płaski katalog `version-N` i zachowuje poprzednie, więc działający indeks nigdy nie jest niszczony w trakcie przebudowy. Pojedynczy dokument można usunąć nawet z bazy w stanie **błędu** — usuwając plik, który nie sparsował się poprawnie, bez pełnego usuwania i przebudowy. Parsowanie dokumentów — Tylko tekst, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM lub LiteParse — jest wybierane w **Settings → Knowledge Base**, z domyślnie wyłączonymi pobieraniami lokalnego modelu. Docling może też działać w trybie **zdalnym** względem serwera Docling Serve (bez lokalnej instalacji czy modeli), konfigurowanym przez **Settings → Document Parsing** (`mode=remote`, bazowy URL serwera i opcjonalny klucz API) lub zmienne środowiskowe `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika jest wyłącznie zdalna i wskazuje na serwer Apache Tika (`TIKA_SERVER_URL`). CLI odzwierciedla cykl życia za pomocą `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` i `delete`.+Tworząc KB, albo **tworzysz nową** (przesyłasz dokumenty i budujesz świeży indeks) albo **łączysz istniejącą** (ponownie używasz indeksu zbudowanego gdzie indziej, czytasz w miejscu bez ponownego indeksowania). Baza wiedzy może też śledzić **źródła GitHub** — repozytorium, gałąź i wzorzec glob, których Markdown jest pobierany i ponownie synchronizowany na żądanie, dzięki czemu dokumentacja którą śledzisz pozostaje aktualna bez ponownego przesyłania. Ponowne indeksowanie zapisuje nowy płaski katalog `version-N` i zachowuje poprzednie, więc działający indeks nigdy nie jest niszczony w trakcie przebudowy. Pojedynczy dokument można usunąć nawet z bazy w stanie **błędu** — usuwając plik, który nie sparsował się poprawnie, bez pełnego usuwania i przebudowy. Parsowanie dokumentów — Tylko tekst, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM lub LiteParse — jest wybierane w **Settings → Knowledge Base**, z domyślnie wyłączonymi pobieraniami lokalnego modelu. Docling może też działać w trybie **zdalnym** względem serwera Docling Serve (bez lokalnej instalacji czy modeli), konfigurowanym przez **Settings → Document Parsing** (`mode=remote`, bazowy URL serwera i opcjonalny klucz API) lub zmienne środowiskowe `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika jest wyłącznie zdalna i wskazuje na serwer Apache Tika (`TIKA_SERVER_URL`). CLI odzwierciedla cykl życia za pomocą `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` i `delete`.</details>@@ -573,6 +575,7 @@ Repozytorium zawiera główny [`SKILL.md`](../../SKILL.md) — około 150-liniow| Polecenie | Opis ||:---|:---|| `deeptutor init` | Utwórz lub zaktualizuj `data/user/settings` dla bieżącego obszaru roboczego |+| `deeptutor doctor [--online]` | Sprawdź, czy obszar roboczy jest gotowy do rozpoczęcia sesji; `--online` sprawdza też skonfigurowanego dostawcę modelu, `--format json` wypisuje raport || `deeptutor start [--home PATH] [--dev]` | Uruchom backend + frontend razem || `deeptutor serve [--port PORT]` | Uruchom tylko backend FastAPI || `deeptutor run <capability> <message>` | Uruchom jedną turę możliwości (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); dodaj `--format json` dla wyjścia NDJSON |diff --git a/assets/README/README_PT.md b/assets/README/README_PT.mdindex 4af71555b..79c1d9c36 100644--- a/assets/README/README_PT.md+++ b/assets/README/README_PT.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **Apenas `3782` precisa de ser publicado.** O navegador comunica exclusivamente com a origem do frontend; o middleware Next.js (`web/proxy.ts`) reencaminha `/api/*` e `/ws/*` para o backend FastAPI **dentro do contentor**. Publicar `8001` (`-p 127.0.0.1:8001:8001`) é opcional — útil apenas para aceder à API diretamente com curl ou scripts.-Abra [http://127.0.0.1:3782](http://127.0.0.1:3782). O contentor cria `/app/data/user/settings/*.json` no primeiro arranque; configure os provedores de modelos a partir da página de Settings web. A configuração, as chaves API, os logs, os ficheiros do espaço de trabalho, a memória e as bases de conhecimento persistem no volume `deeptutor-data`.+Abra [http://127.0.0.1:3782](http://127.0.0.1:3782). O contentor cria `/app/data/user/settings/*.json` no primeiro arranque; configure os provedores de modelos a partir da página de Settings web. A configuração, as chaves API, os logs, os ficheiros do espaço de trabalho, a memória e as bases de conhecimento persistem no volume `deeptutor-data`. Extras opcionais pertencem à implementação, não a uma shell: defina `DEEPTUTOR_EXTRAS` (e `DEEPTUTOR_APT_PACKAGES` para bibliotecas de sistema) e cada contentor iniciado a partir dela reaplica-os, ao passo que um `docker exec … pip install` seria perdido no `compose down` seguinte.- **Portas de host diferentes:** altere o lado esquerdo de cada mapeamento `-p host:container` (ex. `-p 127.0.0.1:8088:3782`). Se alterar as portas do lado do contentor em `/app/data/user/settings/system.json`, reinicie e atualize o lado direito de cada mapeamento para corresponder.- **Desconectado:** adicione `-d`, depois `docker logs -f deeptutor` para seguir, `docker stop deeptutor` para parar, `docker rm deeptutor` antes de reutilizar o nome. O volume `deeptutor-data` mantém as suas configurações e espaço de trabalho entre reinicializações.@@ -369,6 +369,8 @@ Cada partner tem um `SOUL.md`, seleção de modelo, canais, política de ferrameA camada de canais é orientada por esquema e pode ligar-se a plataformas IM como Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat e Microsoft Teams dependendo dos extras instalados e das credenciais configuradas. Um partner também pode ser conectado como subagente e consultado a partir de um turno de chat normal — veja **Meus Agentes** abaixo.+Para uma configuração mais rápida, a página de canal do Partner pode criar uma aplicação Feishu/Lark ou um bot de IA WeCom, ou iniciar sessão numa conta pessoal de WeChat, a partir de um código QR desenhado no navegador em vez do log do servidor. O Feishu/Lark deteta o domínio da conta e guarda o utilizador que fez a leitura como o remetente permitido inicial. O WeCom mantém uma lista de permissões existente e, caso contrário, assume por predefinição todos os utilizadores que conseguem alcançar o bot, com um aviso visível de acesso aberto; os formulários de canal manuais permanecem disponíveis caso o protocolo de leitura de um provedor mude.+</details><details>@@ -378,7 +380,7 @@ A camada de canais é orientada por esquema e pode ligar-se a plataformas IM com<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Espaço de trabalho Meus Agentes DeepTutor" width="900"></div>-Meus Agentes transforma outros agentes em contexto para o DeepTutor, e faz duas coisas distintas. **Conectar um agente ao vivo** — um Claude Code, Codex, Gemini, Kimi, opencode ou MiMo Code CLI na sua máquina, ou um dos seus Partners — e consultá-lo a partir de dentro de um turno de chat: o DeepTutor *executa* mesmo o outro agente e transmite o seu trabalho para o painel de Atividade via a ferramenta `consult_subagent`. Selecione-o com o chip de Agente (ou escreva `@`), e defina quantas rondas a consulta pode ter.+Meus Agentes transforma outros agentes em contexto para o DeepTutor, e faz duas coisas distintas. **Conectar um agente ao vivo** — um Claude Code, Codex, Gemini, Antigravity, Kimi, opencode ou MiMo Code CLI na sua máquina, ou um dos seus Partners — e consultá-lo a partir de dentro de um turno de chat: o DeepTutor *executa* mesmo o outro agente e transmite o seu trabalho para o painel de Atividade via a ferramenta `consult_subagent`. Selecione-o com o chip de Agente (ou escreva `@`), e defina quantas rondas a consulta pode ter.<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consultar um subagente Claude Code ao vivo" width="900">@@ -439,7 +441,7 @@ As bases de conhecimento são as coleções de documentos por trás do RAG — f<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Criar uma base de conhecimento" width="900"></div>-Ao criar uma KB, pode **criar nova** (carregar documentos e construir um índice novo) ou **vincular existente** (reutilizar um índice construído noutro lugar, ler no lugar sem reindexação). A reindexação escreve um novo diretório plano `version-N` e mantém os anteriores, pelo que um índice funcional nunca é destruído a meio de uma reconstrução. Um único documento pode ser removido mesmo de uma base em estado de **erro** — descartando um ficheiro que falhou a análise sem uma eliminação e reconstrução completas. A análise de documentos — Somente Texto, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM ou LiteParse — é escolhida em **Settings → Knowledge Base**, com downloads de modelos locais desativados por predefinição. O Docling também pode correr em modo **remoto** contra um servidor Docling Serve (sem necessidade de instalação local nem de modelos), configurado através de **Settings → Document Parsing** (`mode=remote`, um URL base do servidor e uma chave API opcional) ou das variáveis de ambiente `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. O Tika é apenas remoto e aponta para um servidor Apache Tika (`TIKA_SERVER_URL`). A CLI espelha o ciclo de vida com `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` e `delete`.+Ao criar uma KB, pode **criar nova** (carregar documentos e construir um índice novo) ou **vincular existente** (reutilizar um índice construído noutro lugar, ler no lugar sem reindexação). Uma KB também pode rastrear **fontes GitHub** — um repositório, branch e glob cujo Markdown é obtido e ressincronizado a pedido, para que a documentação que segue se mantenha atual sem reenvio. A reindexação escreve um novo diretório plano `version-N` e mantém os anteriores, pelo que um índice funcional nunca é destruído a meio de uma reconstrução. Um único documento pode ser removido mesmo de uma base em estado de **erro** — descartando um ficheiro que falhou a análise sem uma eliminação e reconstrução completas. A análise de documentos — Somente Texto, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM ou LiteParse — é escolhida em **Settings → Knowledge Base**, com downloads de modelos locais desativados por predefinição. O Docling também pode correr em modo **remoto** contra um servidor Docling Serve (sem necessidade de instalação local nem de modelos), configurado através de **Settings → Document Parsing** (`mode=remote`, um URL base do servidor e uma chave API opcional) ou das variáveis de ambiente `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. O Tika é apenas remoto e aponta para um servidor Apache Tika (`TIKA_SERVER_URL`). A CLI espelha o ciclo de vida com `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` e `delete`.</details>@@ -585,6 +587,7 @@ O repositório inclui um [`SKILL.md`](../../SKILL.md) raiz — um documento de t| Comando | Descrição ||:---|:---|| `deeptutor init` | Criar ou atualizar `data/user/settings` para o espaço de trabalho atual |+| `deeptutor doctor [--online]` | Verificar se o espaço de trabalho está pronto para iniciar uma sessão; `--online` também sonda o provedor de modelo configurado, `--format json` imprime o relatório || `deeptutor start [--home PATH] [--dev]` | Lançar backend + frontend juntos || `deeptutor serve [--port PORT]` | Iniciar apenas o backend FastAPI || `deeptutor run <capability> <message>` | Executar um turno de capacidade único (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); adicionar `--format json` para saída NDJSON |diff --git a/assets/README/README_RU.md b/assets/README/README_RU.mdindex 51e7fb5d8..1d14d1c53 100644--- a/assets/README/README_RU.md+++ b/assets/README/README_RU.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **Публиковать нужно только порт `3782`.** Браузер обращается исключительно к источнику фронтенда; промежуточный слой Next.js (`web/proxy.ts`) перенаправляет `/api/*` и `/ws/*` на бэкенд FastAPI **внутри контейнера**. Публикация `8001` (`-p 127.0.0.1:8001:8001`) необязательна — полезна только при прямом обращении к API через curl или скрипты.-Откройте [http://127.0.0.1:3782](http://127.0.0.1:3782). Контейнер создаёт `/app/data/user/settings/*.json` при первом запуске; настройте провайдеров моделей на странице веб-настроек. Конфигурация, API-ключи, логи, файлы рабочего пространства, память и базы знаний сохраняются в томе `deeptutor-data`.+Откройте [http://127.0.0.1:3782](http://127.0.0.1:3782). Контейнер создаёт `/app/data/user/settings/*.json` при первом запуске; настройте провайдеров моделей на странице веб-настроек. Конфигурация, API-ключи, логи, файлы рабочего пространства, память и базы знаний сохраняются в томе `deeptutor-data`. Необязательные дополнения принадлежат развёртыванию, а не оболочке: задайте `DEEPTUTOR_EXTRAS` (и `DEEPTUTOR_APT_PACKAGES` для системных библиотек), и каждый контейнер, запущенный из него, будет повторно применять их, тогда как `docker exec … pip install` будет потерян при следующем `compose down`.- **Другие порты хоста:** измените левую часть каждого маппинга `-p host:container` (например, `-p 127.0.0.1:8088:3782`). Если вы измените порты на стороне контейнера в `/app/data/user/settings/system.json`, перезапустите и обновите правую часть каждого маппинга.- **Фоновый режим:** добавьте `-d`, затем `docker logs -f deeptutor` для слежения, `docker stop deeptutor` для остановки, `docker rm deeptutor` перед повторным использованием имени. Том `deeptutor-data` сохраняет ваши настройки и рабочее пространство между перезапусками.@@ -357,6 +357,8 @@ deeptutor config showСлой каналов управляется схемой и может подключаться к IM-платформам, таким как Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat и Microsoft Teams, в зависимости от установленных дополнений и настроенных учётных данных. Партнёр также может быть подключён как субагент и использован из обычного хода чата — см. **Мои Агенты** ниже.+Для более быстрой настройки страница канала Партнёра может создать приложение Feishu/Lark или AI-бота WeCom, либо войти с личной учётной записью WeChat — по QR-коду, отображаемому в браузере, а не в логе сервера. Feishu/Lark определяет домен учётной записи и сохраняет пользователя, выполнившего сканирование, как первого разрешённого отправителя. WeCom сохраняет существующий белый список, а иначе по умолчанию разрешает доступ всем пользователям, которые могут связаться с ботом, с заметным предупреждением об открытом доступе; ручные формы канала остаются доступны, если протокол сканирования провайдера изменится.+</details><details>@@ -366,7 +368,7 @@ deeptutor config show<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="Рабочее пространство «Мои Агенты» DeepTutor" width="900"></div>-Мои Агенты превращают других агентов в контекст для DeepTutor и делают две разные вещи. **Подключите живого агента** — Claude Code, Codex, Gemini, Kimi, opencode или MiMo Code CLI на вашей машине, или одного из ваших Партнёров — и обращайтесь к нему изнутри хода чата: DeepTutor фактически *запускает* другого агента и транслирует его работу в панель Activity через инструмент `consult_subagent`. Выберите его чипом агента (или введите `@`) и задайте, сколько раундов может занять обращение.+Мои Агенты превращают других агентов в контекст для DeepTutor и делают две разные вещи. **Подключите живого агента** — Claude Code, Codex, Gemini, Antigravity, Kimi, opencode или MiMo Code CLI на вашей машине, или одного из ваших Партнёров — и обращайтесь к нему изнутри хода чата: DeepTutor фактически *запускает* другого агента и транслирует его работу в панель Activity через инструмент `consult_subagent`. Выберите его чипом агента (или введите `@`) и задайте, сколько раундов может занять обращение.<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Обращение к субагенту Claude Code в реальном времени" width="900">@@ -427,7 +429,7 @@ Co-Writer — это разделённое рабочее пространст<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Создание базы знаний" width="900"></div>-При создании KB вы либо **создаёте новую** (загружаете документы и строите свежий индекс), либо **связываете существующую** (повторно используете индекс, построенный в другом месте, читаете на месте без переиндексирования). Переиндексирование записывает новую плоскую директорию `version-N` и сохраняет предыдущие, поэтому рабочий индекс никогда не уничтожается в процессе перестройки. Отдельный документ можно удалить даже из базы в состоянии **error** — убрав файл, который не удалось разобрать, без полного удаления и пересборки. Разбор документов — только текст, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM или LiteParse — выбирается в **Настройки → База знаний**, с отключёнными по умолчанию загрузками локальных моделей. Docling может также работать в **удалённом режиме**, обращаясь к серверу Docling Serve (без локальной установки и моделей), который настраивается в **Настройки → Разбор документов** (`mode=remote`, базовый URL сервера и необязательный API-ключ) или через переменные окружения `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika работает только в удалённом режиме и указывает на сервер Apache Tika (`TIKA_SERVER_URL`). CLI отражает жизненный цикл командами `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` и `delete`.+При создании KB вы либо **создаёте новую** (загружаете документы и строите свежий индекс), либо **связываете существующую** (повторно используете индекс, построенный в другом месте, читаете на месте без переиндексирования). База знаний также может отслеживать **GitHub-источники** — репозиторий, ветку и glob-шаблон, чей Markdown загружается и повторно синхронизируется по запросу, поэтому документация, за которой вы следите, остаётся актуальной без повторной загрузки. Переиндексирование записывает новую плоскую директорию `version-N` и сохраняет предыдущие, поэтому рабочий индекс никогда не уничтожается в процессе перестройки. Отдельный документ можно удалить даже из базы в состоянии **error** — убрав файл, который не удалось разобрать, без полного удаления и пересборки. Разбор документов — только текст, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM или LiteParse — выбирается в **Настройки → База знаний**, с отключёнными по умолчанию загрузками локальных моделей. Docling может также работать в **удалённом режиме**, обращаясь к серверу Docling Serve (без локальной установки и моделей), который настраивается в **Настройки → Разбор документов** (`mode=remote`, базовый URL сервера и необязательный API-ключ) или через переменные окружения `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN`. Tika работает только в удалённом режиме и указывает на сервер Apache Tika (`TIKA_SERVER_URL`). CLI отражает жизненный цикл командами `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` и `delete`.</details>@@ -573,6 +575,7 @@ deeptutor run deep_question "Quiz me on that survey" --session "$SID" --format j| Команда | Описание ||:---|:---|| `deeptutor init` | Создать или обновить `data/user/settings` для текущего рабочего пространства |+| `deeptutor doctor [--online]` | Проверить, готово ли рабочее пространство к запуску сессии; `--online` также проверяет настроенного провайдера модели, `--format json` выводит отчёт || `deeptutor start [--home PATH] [--dev]` | Запустить бэкенд + фронтенд вместе || `deeptutor serve [--port PORT]` | Запустить только бэкенд FastAPI || `deeptutor run <capability> <message>` | Запустить один ход возможности (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); добавьте `--format json` для вывода NDJSON |diff --git a/assets/README/README_TH.md b/assets/README/README_TH.mdindex 3a5f08f14..8c9f89c72 100644--- a/assets/README/README_TH.md+++ b/assets/README/README_TH.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **จำเป็นต้อง publish เฉพาะ `3782`** เบราว์เซอร์คุยกับ frontend origin เท่านั้น; Next.js middleware (`web/proxy.ts`) ส่งต่อ `/api/*` และ `/ws/*` ไปยัง FastAPI backend **ภายใน container** การ publish `8001` (`-p 127.0.0.1:8001:8001`) เป็นทางเลือก — มีประโยชน์เฉพาะเมื่อต้องการเรียก API โดยตรงด้วย curl หรือ scripts-เปิด [http://127.0.0.1:3782](http://127.0.0.1:3782) Container จะสร้าง `/app/data/user/settings/*.json` เมื่อบูตครั้งแรก กำหนดค่า model providers จากหน้า Web Settings Config, API keys, logs, ไฟล์ workspace, memory และ knowledge bases จะคงอยู่ใน volume `deeptutor-data`+เปิด [http://127.0.0.1:3782](http://127.0.0.1:3782) Container จะสร้าง `/app/data/user/settings/*.json` เมื่อบูตครั้งแรก กำหนดค่า model providers จากหน้า Web Settings Config, API keys, logs, ไฟล์ workspace, memory และ knowledge bases จะคงอยู่ใน volume `deeptutor-data` ส่วนเสริมที่เป็นทางเลือกควรอยู่ที่การปรับใช้ ไม่ใช่ใน shell: ตั้งค่า `DEEPTUTOR_EXTRAS` (และ `DEEPTUTOR_APT_PACKAGES` สำหรับ system libraries) แล้ว container ทุกตัวที่เริ่มจากมันจะ apply ส่วนเสริมเหล่านั้นซ้ำโดยอัตโนมัติ ในขณะที่ `docker exec … pip install` จะหายไปเมื่อ `compose down` ครั้งถัดไป- **พอร์ต host ที่แตกต่าง:** เปลี่ยนด้านซ้ายของการ mapping `-p host:container` แต่ละอัน (เช่น `-p 127.0.0.1:8088:3782`) หากคุณเปลี่ยนพอร์ตฝั่ง container ใน `/app/data/user/settings/system.json` ให้รีสตาร์ทและอัปเดตด้านขวาของการ mapping แต่ละอันให้ตรงกัน- **แบบ detached:** เพิ่ม `-d` จากนั้น `docker logs -f deeptutor` เพื่อติดตาม, `docker stop deeptutor` เพื่อหยุด, `docker rm deeptutor` ก่อนนำชื่อมาใช้ซ้ำ Volume `deeptutor-data` จะเก็บการตั้งค่าและ workspace ของคุณข้ามการรีสตาร์ท@@ -357,6 +357,8 @@ Partners คือเพื่อนถาวรที่มี soul, นโยชั้น channel ที่ขับเคลื่อนด้วย schema สามารถเชื่อมต่อกับแพลตฟอร์ม IM ได้แก่ Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat และ Microsoft Teams ขึ้นอยู่กับ extras ที่ติดตั้งและ credentials ที่กำหนดค่า partner ยังสามารถเชื่อมต่อเป็น subagent และปรึกษาได้จาก chat turn ปกติ — ดู **My Agents** ด้านล่าง+เพื่อการตั้งค่าที่รวดเร็วขึ้น หน้า channel ของ Partner สามารถสร้างแอป Feishu/Lark หรือ WeCom AI bot หรือลงชื่อเข้าใช้บัญชี WeChat ส่วนตัว ผ่านการสแกน QR ที่วาดในเบราว์เซอร์แทนที่จะอยู่ใน server log Feishu/Lark จะตรวจจับ account domain และบันทึกผู้ใช้ที่สแกนเป็นผู้ส่งที่ได้รับอนุญาตเริ่มต้น WeCom จะคง allowlist ที่มีอยู่ไว้ และหากไม่มีจะ default เป็นผู้ใช้ทุกคนที่เข้าถึง bot ได้ พร้อมคำเตือน open-access ที่มองเห็นได้ชัดเจน; ฟอร์ม channel แบบ manual ยังคงใช้งานได้หากโปรโตคอลการสแกนของ provider เปลี่ยนไป+</details><details>@@ -366,7 +368,7 @@ Partners คือเพื่อนถาวรที่มี soul, นโย<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor workspace My Agents" width="900"></div>-My Agents เปลี่ยน agent อื่น ๆ ให้กลายเป็นบริบทสำหรับ DeepTutor และทำสองสิ่งที่แตกต่างกัน **เชื่อมต่อ agent แบบสด** — Claude Code, Codex, Gemini, Kimi, opencode หรือ MiMo Code CLI บนเครื่องของคุณ หรือหนึ่งใน Partners ของคุณ — และปรึกษามันจากภายใน chat turn: DeepTutor จริง ๆ *รัน* agent อื่นและ stream งานเข้าสู่แผง Activity ผ่านเครื่องมือ `consult_subagent` เลือกด้วย Agent chip (หรือพิมพ์ `@`) และตั้งค่าจำนวนรอบที่การปรึกษาอาจทำได้+My Agents เปลี่ยน agent อื่น ๆ ให้กลายเป็นบริบทสำหรับ DeepTutor และทำสองสิ่งที่แตกต่างกัน **เชื่อมต่อ agent แบบสด** — Claude Code, Codex, Gemini, Antigravity, Kimi, opencode หรือ MiMo Code CLI บนเครื่องของคุณ หรือหนึ่งใน Partners ของคุณ — และปรึกษามันจากภายใน chat turn: DeepTutor จริง ๆ *รัน* agent อื่นและ stream งานเข้าสู่แผง Activity ผ่านเครื่องมือ `consult_subagent` เลือกด้วย Agent chip (หรือพิมพ์ `@`) และตั้งค่าจำนวนรอบที่การปรึกษาอาจทำได้<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="การปรึกษา subagent Claude Code แบบสด" width="900">@@ -427,7 +429,7 @@ Knowledge bases คือคอลเลกชันเอกสารที่<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="สร้าง knowledge base" width="900"></div>-เมื่อสร้าง KB คุณ **สร้างใหม่** (อัพโหลดเอกสารและสร้าง index ใหม่) หรือ **เชื่อมโยงที่มีอยู่** (นำ index ที่สร้างไว้มาใช้ซ้ำ อ่านในที่โดยไม่ต้อง re-index) การ re-indexing จะเขียน directory `version-N` ใหม่และเก็บอันก่อนหน้าไว้ ดังนั้น index ที่ทำงานอยู่จะไม่ถูกทำลายระหว่างการสร้างใหม่ การแยกวิเคราะห์เอกสาร — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM หรือ LiteParse — ถูกเลือกใน **Settings → Knowledge Base** โดยการดาวน์โหลด local model ปิดโดยค่าเริ่มต้น Docling ยังสามารถรันในโหมด **remote** กับเซิร์ฟเวอร์ Docling Serve ได้ (ไม่ต้องติดตั้ง local หรือใช้ model ใด ๆ) โดยถูกกำหนดค่าผ่าน **Settings → Document Parsing** (`mode=remote`, server base URL และ API key ที่เป็นทางเลือก) หรือผ่าน environment variables `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` Tika ทำงานในโหมด remote เท่านั้นและชี้ไปยังเซิร์ฟเวอร์ Apache Tika (`TIKA_SERVER_URL`) CLI ครอบคลุม lifecycle ด้วย `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` และ `delete`+เมื่อสร้าง KB คุณ **สร้างใหม่** (อัพโหลดเอกสารและสร้าง index ใหม่) หรือ **เชื่อมโยงที่มีอยู่** (นำ index ที่สร้างไว้มาใช้ซ้ำ อ่านในที่โดยไม่ต้อง re-index) KB ยังสามารถติดตาม **GitHub sources** ได้ — repo, branch และ glob ที่ Markdown ของมันจะถูกดึงเข้ามาและ re-sync ได้ตามต้องการ ดังนั้นเอกสารที่คุณติดตามจะทันสมัยอยู่เสมอโดยไม่ต้องอัพโหลดใหม่ การ re-indexing จะเขียน directory `version-N` ใหม่และเก็บอันก่อนหน้าไว้ ดังนั้น index ที่ทำงานอยู่จะไม่ถูกทำลายระหว่างการสร้างใหม่ การแยกวิเคราะห์เอกสาร — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM หรือ LiteParse — ถูกเลือกใน **Settings → Knowledge Base** โดยการดาวน์โหลด local model ปิดโดยค่าเริ่มต้น Docling ยังสามารถรันในโหมด **remote** กับเซิร์ฟเวอร์ Docling Serve ได้ (ไม่ต้องติดตั้ง local หรือใช้ model ใด ๆ) โดยถูกกำหนดค่าผ่าน **Settings → Document Parsing** (`mode=remote`, server base URL และ API key ที่เป็นทางเลือก) หรือผ่าน environment variables `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` Tika ทำงานในโหมด remote เท่านั้นและชี้ไปยังเซิร์ฟเวอร์ Apache Tika (`TIKA_SERVER_URL`) CLI ครอบคลุม lifecycle ด้วย `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default` และ `delete`</details>@@ -573,6 +575,7 @@ repo มี root [`SKILL.md`](../../SKILL.md) — เอกสาร handover ~1| คำสั่ง | คำอธิบาย ||:---|:---|| `deeptutor init` | สร้างหรืออัพเดต `data/user/settings` สำหรับ workspace ปัจจุบัน |+| `deeptutor doctor [--online]` | ตรวจสอบว่า workspace พร้อมเริ่ม session หรือไม่; `--online` ยังตรวจสอบ model provider ที่กำหนดค่าไว้ด้วย, `--format json` พิมพ์รายงานออกมา || `deeptutor start [--home PATH] [--dev]` | เปิดตัว backend + frontend ด้วยกัน || `deeptutor serve [--port PORT]` | เริ่มเฉพาะ FastAPI backend || `deeptutor run <capability> <message>` | รัน capability turn เดียว (`chat`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`); เพิ่ม `--format json` สำหรับ NDJSON output |diff --git a/assets/README/README_TW.md b/assets/README/README_TW.mdindex 1a089db88..05f6e75e6 100644--- a/assets/README/README_TW.md+++ b/assets/README/README_TW.md@@ -175,7 +175,7 @@ docker run --rm --name deeptutor \> **只需要發布 `3782`。** 瀏覽器只會與前端 origin 通訊;Next.js middleware(`web/proxy.ts`)會將 `/api/*` 與 `/ws/*` 轉送到容器**內部**的 FastAPI 後端。發布 `8001`(`-p 127.0.0.1:8001:8001`)並非必要;只有在你想直接以 curl 或指令碼呼叫 API 時才方便。-開啟 [http://127.0.0.1:3782](http://127.0.0.1:3782)。容器會在首次啟動時建立 `/app/data/user/settings/*.json`;請從 Web 設定頁面設定模型供應商。設定、API key、記錄、工作區檔案、記憶與知識庫都會保留在 `deeptutor-data` volume 中。+開啟 [http://127.0.0.1:3782](http://127.0.0.1:3782)。容器會在首次啟動時建立 `/app/data/user/settings/*.json`;請從 Web 設定頁面設定模型供應商。設定、API key、記錄、工作區檔案、記憶與知識庫都會保留在 `deeptutor-data` volume 中。選用的額外套件應設定在部署層級,而不是在 shell 裡:設定 `DEEPTUTOR_EXTRAS`(系統函式庫則另設 `DEEPTUTOR_APT_PACKAGES`),由它啟動的每個容器都會重新套用;相較之下,`docker exec … pip install` 這類做法會在下一次 `compose down` 時消失。- **不同的主機連接埠:** 變更各 `-p host:container` 對應左側的值(例如 `-p 127.0.0.1:8088:3782`)。若你在 `/app/data/user/settings/system.json` 變更容器側連接埠,請重新啟動,並同步更新各對應右側的值。- **背景執行:** 加上 `-d`;接著以 `docker logs -f deeptutor` 查看記錄、`docker stop deeptutor` 停止,並在重複使用名稱前執行 `docker rm deeptutor`。`deeptutor-data` volume 會在重新啟動後保留設定與工作區。@@ -357,6 +357,8 @@ Partners 是持續運作的夥伴,各自擁有 soul、模型政策、知識庫頻道層由結構描述驅動;依已安裝的額外套件與設定的憑證,可連接飛書、Telegram、Slack、Discord、釘釘、QQ/NapCat、企業微信、WhatsApp、Zulip、Mattermost、Matrix、Mochat 與 Microsoft Teams 等 IM 平台。Partner 也可以連接成子代理程式,並從一般聊天回合中接受諮詢;請參閱下方的 **My Agents**。+為了更快完成設定,Partner 頻道頁面可直接在瀏覽器中繪製 QR code(而非輸出到伺服器記錄),用來建立飛書/Lark 應用程式或企業微信 AI 機器人,或登入個人微信帳號。飛書/Lark 會偵測帳號網域,並將掃碼使用者存為初始允許發送者。企業微信會保留既有的允許清單,否則預設允許所有能觸及該機器人的使用者,並顯示明顯的開放存取警告;若供應商的掃碼協定有所變更,手動頻道表單仍可使用。+</details><details>@@ -366,7 +368,7 @@ Partners 是持續運作的夥伴,各自擁有 soul、模型政策、知識庫<img src="../../assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agents 工作區" width="900"></div>-My Agents 會將其他代理程式變成 DeepTutor 的情境,並提供兩項不同功能。**連接即時代理程式** — 連接電腦上的 Claude Code、Codex、Gemini、Kimi、opencode 或 MiMo Code CLI,或你自己的 Partner,並從聊天回合內諮詢它。DeepTutor 會實際*執行*其他代理程式,再透過 `consult_subagent` 工具將其工作即時串流至 Activity 面板。使用 Agent chip(或輸入 `@`)選取代理程式,並設定諮詢可進行的回合數。+My Agents 會將其他代理程式變成 DeepTutor 的情境,並提供兩項不同功能。**連接即時代理程式** — 連接電腦上的 Claude Code、Codex、Gemini、Antigravity、Kimi、opencode 或 MiMo Code CLI,或你自己的 Partner,並從聊天回合內諮詢它。DeepTutor 會實際*執行*其他代理程式,再透過 `consult_subagent` 工具將其工作即時串流至 Activity 面板。使用 Agent chip(或輸入 `@`)選取代理程式,並設定諮詢可進行的回合數。<div align="center"><img src="../../assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="即時諮詢 Claude Code 子代理程式" width="900">@@ -427,7 +429,7 @@ Book 會將選定來源轉換成互動式**活書**;它不是靜態 PDF,而<img src="../../assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="建立知識庫" width="900"></div>-建立知識庫時,可以選擇**建立新的知識庫**(上傳文件並建立全新索引),或**連結現有知識庫**(重複使用在其他位置建立的索引、就地讀取且不重新建立索引)。重新建立索引時,系統會寫入新的扁平 `version-N` 目錄並保留先前版本,因此可用索引不會在重建途中遭到破壞。即使知識庫處於 **error** 狀態,也能移除單一文件;可直接刪除解析失敗的檔案,無須刪除並重建全部內容。文件解析方式(Text-only、MinerU、Docling、Tika、markitdown 或 PyMuPDF4LLM)可在 **Settings → Knowledge Base** 選擇,預設不下載本機模型。Docling 也可以在**遠端(remote)**模式下運作,改連線至 Docling Serve 伺服器(無須本機安裝或下載模型),可透過 **Settings → Document Parsing**(設定 `mode=remote`、伺服器基礎 URL 與選用的 API 金鑰)或 `DOCLING_MODE`/`DOCLING_API_BASE_URL`/`DOCLING_API_TOKEN` 環境變數進行設定。Tika 僅支援遠端模式,會連線至 Apache Tika 伺服器(`TIKA_SERVER_URL`)。CLI 也提供對應的完整生命週期指令:`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 與 `delete`。+建立知識庫時,可以選擇**建立新的知識庫**(上傳文件並建立全新索引),或**連結現有知識庫**(重複使用在其他位置建立的索引、就地讀取且不重新建立索引)。知識庫也可以追蹤 **GitHub sources** — 一個 repo、branch 與 glob,其 Markdown 內容會被拉取並依需求重新同步,因此你所追蹤的文件能保持最新,無須重新上傳。重新建立索引時,系統會寫入新的扁平 `version-N` 目錄並保留先前版本,因此可用索引不會在重建途中遭到破壞。即使知識庫處於 **error** 狀態,也能移除單一文件;可直接刪除解析失敗的檔案,無須刪除並重建全部內容。文件解析方式(Text-only、MinerU、Docling、Tika、markitdown 或 PyMuPDF4LLM)可在 **Settings → Knowledge Base** 選擇,預設不下載本機模型。Docling 也可以在**遠端(remote)**模式下運作,改連線至 Docling Serve 伺服器(無須本機安裝或下載模型),可透過 **Settings → Document Parsing**(設定 `mode=remote`、伺服器基礎 URL 與選用的 API 金鑰)或 `DOCLING_MODE`/`DOCLING_API_BASE_URL`/`DOCLING_API_TOKEN` 環境變數進行設定。Tika 僅支援遠端模式,會連線至 Apache Tika 伺服器(`TIKA_SERVER_URL`)。CLI 也提供對應的完整生命週期指令:`deeptutor kb list`、`info`、`create`、`add`、`search`、`set-default` 與 `delete`。</details>@@ -573,6 +575,7 @@ repo 根目錄附有 [`SKILL.md`](../../SKILL.md),這份約 150 行的交接| 指令 | 說明 ||:---|:---|| `deeptutor init` | 為目前工作區建立或更新 `data/user/settings` |+| `deeptutor doctor [--online]` | 檢查工作區是否已就緒可開始工作階段;`--online` 也會探測目前設定的模型供應商,`--format json` 會輸出 JSON 格式報告 || `deeptutor start [--home PATH] [--dev]` | 同時啟動後端與前端;`--dev` 會啟用前端 HMR || `deeptutor serve [--port PORT]` | 只啟動 FastAPI 後端 || `deeptutor run <capability> <message>` | 執行單一能力回合(`chat`、`deep_solve`、`deep_question`、`deep_research`、`visualize`、`math_animator`、`mastery_path`);加上 `--format json` 可輸出 NDJSON |diff --git a/assets/releases/ver1-5-13.md b/assets/releases/past_releases/ver1-5-13.mdsimilarity index 100%rename from assets/releases/ver1-5-13.mdrename to assets/releases/past_releases/ver1-5-13.mddiff --git a/assets/releases/ver1-5-14.md b/assets/releases/ver1-5-14.mdindex ebda25d6f..74c183b34 100644--- a/assets/releases/ver1-5-14.md+++ b/assets/releases/ver1-5-14.md@@ -2,7 +2,7 @@**Release Date:** 2026.08.19-[v1.5.13](ver1-5-13.md) made a book something you read. This one puts the assistant next to what you are reading: a document opens beside the thread, and every claim comes back with the page it came from. Three other shifts sit around it — DeepTutor can configure itself from a chat turn, a Tencent IMA library becomes something you browse and write to rather than only search, and notebooks get a console of their own. Drop-in — no migrations, nothing to re-index.+[v1.5.13](past_releases/ver1-5-13.md) made a book something you read. This one puts the assistant next to what you are reading: a document opens beside the thread, and every claim comes back with the page it came from. Three other shifts sit around it — DeepTutor can configure itself from a chat turn, a Tencent IMA library becomes something you browse and write to rather than only search, and notebooks get a console of their own. Drop-in — no migrations, nothing to re-index.## What's Newdiff --git a/assets/releases/ver1-5-17.md b/assets/releases/ver1-5-17.mdnew file mode 100644index 000000000..988e46b89--- /dev/null+++ b/assets/releases/ver1-5-17.md@@ -0,0 +1,76 @@+# DeepTutor v1.5.17 Release Notes++**Release Date:** 2026.08.25++[v1.5.16](ver1-5-16.md) connected a MarginNote library and put a run of gateway failures to rest. This one changes who a **Partner** belongs to: they stop being a deployment-wide resource only an admin can touch and become something each member builds, owns, and holds their own private conversations with — an admin still lends theirs out through grants. Around that sit a knowledge base that tracks **GitHub repositories**, **Antigravity CLI** under My Agents, a WeChat QR code drawn in the browser instead of a log file, and a container that keeps the optional extras you declared. Existing partners keep working and migrate themselves; the one behavior change is scoped to non-admin users, who can now see a **Partners** page that used to be closed to them.++## What's New++### Partners belong to people, not to the deployment++Every `/api/v1/partners` route used to sit behind a blanket admin gate, so a member could talk to a partner an admin had assigned them and nothing else. Three rights now nest instead: **manage** (its creator, plus any admin) covers soul, channels, models, assets, lifecycle and deletion; **use** adds anyone an admin assigned it to, and means holding a conversation; anyone else cannot see that the partner exists — an unowned partner and an invisible one answer alike, so ids cannot be enumerated.++Conversations follow the human, not the partner. Two people talking to the same companion never see each other's threads, and each side reads back in the web app under its own account. Grants still exist and are unchanged in shape, but they now only offer *admin-managed* partners: one someone built for themselves is theirs to share or not, since its `SOUL.md` is usually written personally.++### A chat account can carry your DeepTutor identity++A partner reached over QQ or Telegram used to know only a channel-local sender id, so every inbound message was anonymous — it landed in the shared thread pool, and the partner answered out of the admin workspace rather than the sender's own library. Ask your partner for a code in the web app, send `/link <code>` to it from the chat account you want connected, and from then on that sender is you: the conversation is private to your account, readable back in the browser, and the partner reads your knowledge, notebooks and memory the way it would in a web turn.++### Two partners can share a channel++Channel runtime state — bot tokens, long-poll cursors, conversation references, E2EE device stores — lived in one directory per *channel*, not per partner, so two partners configured on the same channel read each other's credentials and overwrote each other's cursor. Only one of them could ever be online. State now lives under `data/partners/<id>/channels/<channel>/`, and the old tree is **copied** across on first start when its owner is certain — the saved token matches one partner's configured token, or only one partner has that channel enabled at all. A genuine tie re-authenticates once rather than being handed someone else's account.++### Personal WeChat signs in from the browser++The QR-code exchange has always worked, but it only ran from the channel's own `start()` and drew the code on the server's stdout — which on any container deployment is a supervisord log the person configuring the partner cannot reach ([#951](https://github.com/HKUDS/DeepTutor/issues/951)). The same exchange now runs for the web app: press **Scan to connect** on the partner's channel page, scan, and the bot token is written into the channel config server-side. A status reply says whether the login succeeded, never what it produced. The terminal still prints a code as a fallback.++### A knowledge base can track GitHub repositories++Register a repo, branch and glob as a **GitHub source** and its Markdown is pulled into the KB and re-synced on demand, so documentation you follow stays current without re-uploading it. Contributed as [#903](https://github.com/HKUDS/DeepTutor/pull/903); download destinations are contained inside the KB's `raw/` directory, since a `..` segment or an absolute path in a tree entry would otherwise have written — and, on the removal branch, deleted — outside the base.++### Antigravity CLI joins My Agents++Google retired Gemini CLI in June and pointed its users at Antigravity CLI, so anyone on a Google AI Pro/Ultra or Gemini Code Assist plan was left with a `gemini` backend that had no CLI to detect ([#828](https://github.com/HKUDS/DeepTutor/issues/828)). `agy` is now a backend of its own — connect it, consult it mid-turn, resume its conversations. The Gemini CLI backend stays: it still runs for anyone holding a Gemini API key, and a working connection must not break on upgrade.++### `deeptutor doctor`++One command that answers "is this workspace ready to start a session?" — settings, providers, dependencies, ports. `--online` also sends a small request to the configured model provider; `--format json` prints the same report for a script or an agent. Contributed as [#959](https://github.com/HKUDS/DeepTutor/pull/959).++### Containers keep the extras you declared++A container is disposable, so `docker exec … pip install ".[partners]"` survives exactly until the next `compose down` ([#762](https://github.com/HKUDS/DeepTutor/issues/762)). Declare them on the deployment instead — `DEEPTUTOR_EXTRAS: "math-animator,partners"`, and `DEEPTUTOR_APT_PACKAGES` for system libraries — and every container started from it re-applies them. A warm container pays one metadata lookup per requirement, the pip cache lives on the data volume, and a missing wheel leaves that one feature unavailable rather than taking the deployment down.++### Embeddings survive a rate-limited provider++Reindexing a large library against a low-RPM provider used to burn hours and then die on a 429. Three things changed: a key pool rotates across `provider × model` with per-key cooldown so one throttled key no longer poisons the run; a retry budget waits out `Retry-After` instead of exhausting itself on a sliding window; and a process-wide throttle serializes the interval-plus-post across concurrent reindexes, which is what made a request that succeeded by hand fail inside the app. Contributed as [#962](https://github.com/HKUDS/DeepTutor/pull/962).++### Windows++MinerU parsing decoded its subprocess output with the platform default — GBK on a zh-CN install — and died on the first non-ASCII byte; its multi-threaded PDF renderer separately corrupted the heap. Both are fixed, the render guard scoped to Windows only ([#844](https://github.com/HKUDS/DeepTutor/pull/844)). Atomic writes now retry a transient `PermissionError` from an antivirus or indexer holding the target, and code execution works on a Windows host ([#964](https://github.com/HKUDS/DeepTutor/pull/964)).++### Assorted++- **Reasoning effort is per conversation.** The model-level control from v1.5.9 can now be overridden for a single chat ([#641](https://github.com/HKUDS/DeepTutor/issues/641), contributed as [#958](https://github.com/HKUDS/DeepTutor/pull/958)).+- **Indexing fails bounded instead of hanging.** A provider that accepts an embedding request and never completes it stalled the executor future forever; a heartbeat guard now raises after a bounded window of no progress ([#946](https://github.com/HKUDS/DeepTutor/issues/946)).+- **MinerU page-layout blocks stop being indexed as content.** Headers, footers and page numbers are filtered before ingest; an unrecognized block type is indexed rather than failing the whole run, so a MinerU release that adds one cannot break indexing ([#949](https://github.com/HKUDS/DeepTutor/pull/949)).+- **Voice transcription accepts what Chrome records.** `audio/webm;codecs=opus` is normalized once, at the wire boundary, instead of being rejected as an unknown format ([#945](https://github.com/HKUDS/DeepTutor/issues/945)).+- **Mastery quiz cards no longer land below the fold.** The viewer mounts after the post-stream scroll window closed ([#960](https://github.com/HKUDS/DeepTutor/pull/960)), and a quiz whose options repeat a label or an answer is rejected at registration rather than shown as an unanswerable card ([#956](https://github.com/HKUDS/DeepTutor/pull/956)).+- **A learning path keeps its name.** Three surfaces each derived it from the first module, so rebuilding a map renamed the path and the three could disagree; one function answers now, and derivation is the fallback, never the record.+- **A tool that changes what the round operates on runs first.** Switching mastery path mid-round left the other calls bound to the state the round started with; the dispatcher now runs rebinding tools, re-binds everything else, then runs pausing tools last.+- **Local LightRAG answers cite their sources** ([#754](https://github.com/HKUDS/DeepTutor/pull/754)), and the local LlamaIndex pipeline no longer freezes its progress-bar decision at import time ([#864](https://github.com/HKUDS/DeepTutor/pull/864)).+- **Azure OpenAI accepts the endpoint the portal hands you.** A classic `…/openai/deployments/<name>/chat/completions` URL is reduced to the `/openai/v1` surface, so chat stops answering `404 Resource not found` while the settings probe passes.+- **Gemini embeds images where the model supports it**, and refuses `contents` for one that does not rather than posting parts the endpoint will reject ([#814](https://github.com/HKUDS/DeepTutor/issues/814)).+- **A page can ask whether a capability is installed.** Plugin-served capabilities such as the Whisper practice room were offered by a stock install that could not honour them, and the turn came back `Unknown capability` ([#963](https://github.com/HKUDS/DeepTutor/issues/963)).+- **The standalone CLI package declares what it actually imports** ([#954](https://github.com/HKUDS/DeepTutor/pull/954)).++## Upgrade Notes++`pip install -U deeptutor`; Docker users pull `ghcr.io/hkuds/deeptutor:latest`. No re-index and no manual migration.++- **Non-admin users gain a Partners page.** On a multi-user deployment members can now create and manage their own partners, and their conversations with any partner are private to their account. Existing partners have no `owner_id` and therefore read as admin-managed — exactly what they were — so nothing you have configured changes hands.+- **Channel state moves per partner, by copy.** On first start, state under `data/partners/<channel>/` is copied to `data/partners/<id>/channels/<channel>/` when its owner is unambiguous. The legacy tree is left untouched, so a bad outcome is recoverable by hand; a partner whose ownership was ambiguous simply re-authenticates once.+- **Grants only list admin-managed partners now.** A partner a member built for themselves will not appear in the assignable pool.+- **Container extras are opt-in.** Nothing changes until you set `DEEPTUTOR_EXTRAS` in your Compose file. Preview one with `python scripts/install_extras.py --dry-run "<name>"`.+- **Gemini CLI connections keep working.** Antigravity is an additional backend, not a replacement.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.5.16...v1.5.17diff --git a/deeptutor/__version__.py b/deeptutor/__version__.pyindex e5da75fbf..27a66b59f 100644--- a/deeptutor/__version__.py+++ b/deeptutor/__version__.py@@ -6,6 +6,6 @@ before publishing to PyPI; the web sidebar badge and CLI banner read from thisfile directly."""-__version__ = "1.5.16"+__version__ = "1.5.17"__all__ = ("__version__",)diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex c3562c799..3a5763642 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -669,6 +669,19 @@ class AgenticChatPipeline:names.extend(cap.owned_tools)return tuple(names)+ def _capability_rebinding_tools(self, context: UnifiedContext) -> frozenset[str]:+ """Tools that repoint the rest of the round at a different target.++ Optional, like ``pre_loop``: a capability declares the tools whose+ effect the round's other calls must see (``mastery_switch`` moves the+ turn onto another path), and the dispatcher runs them first and+ re-binds the rest against the result.+ """+ names: list[str] = []+ for cap in self._active_loop_capabilities(context):+ names.extend(getattr(cap, "rebinding_tools", ()) or ())+ return frozenset(names)+def _capability_system_blocks(self, context: UnifiedContext):blocks = []for cap in self._active_loop_capabilities(context):@@ -868,6 +881,7 @@ class AgenticChatPipeline:iteration_index=iteration_index,registry=self.tool_lookup,kwarg_augmenter=self._augment_tool_kwargs,+ rebinding_tools=self._capability_rebinding_tools(context),retrieve_meta_factory=lambda meta, tn, ta: self._retrieve_trace_metadata(meta, context=context, tool_name=tn, tool_args=ta),diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 3c5b8bfe7..0d7b50b46 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -361,6 +361,7 @@ from deeptutor.api.routers import (attachments,auth,book,+ capabilities,capabilities_settings,chat,co_writer,@@ -448,6 +449,12 @@ app.include_router(tags=["capabilities"],dependencies=_auth,)+app.include_router(+ capabilities.router,+ prefix="/api/v1/capabilities",+ tags=["capabilities"],+ dependencies=_auth,+)app.include_router(sessions.router, prefix="/api/v1/sessions", tags=["sessions"], dependencies=_auth)@@ -511,8 +518,13 @@ app.include_router(app.include_router(agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"], dependencies=_auth)+# Partners are per-user resources now: anyone may build their own, and an admin+# may assign theirs to others. Only ``_auth`` here — every route in the router+# declares whether it needs *use* or *manage* rights on the partner it names+# (see ``multi_user.partner_access``), which a blanket admin gate could not+# express.app.include_router(- partners.router, prefix="/api/v1/partners", tags=["partners"], dependencies=_admin+ partners.router, prefix="/api/v1/partners", tags=["partners"], dependencies=_auth)app.include_router(attachments.router,diff --git a/deeptutor/api/routers/capabilities.py b/deeptutor/api/routers/capabilities.pynew file mode 100644index 000000000..e30f1617b--- /dev/null+++ b/deeptutor/api/routers/capabilities.py@@ -0,0 +1,30 @@+"""What this deployment's capability registry actually resolved at boot.++Chat surfaces address a capability by name — ``mastery_path``,+``immersive_reading``, and so on — but not every name ships in this+repository. Capabilities also arrive from plugins, and the Whisper practice+room is one of those: its pages live here while ``whisper_visitor`` /+``whisper_trainee`` are served by an out-of-tree capability. A page had no way+to ask whether the backend could honour the name it was about to send, so a+stock install offered the entry, sent the turn anyway, and the learner got+``Unknown capability: whisper_visitor. Available: [...]`` (#963).++This endpoint is the missing fact, and deliberately nothing more: the names the+registry holds, built-ins and plugins alike. Callers that need a capability's+description or schema already have ``/api/v1/plugins/list``, which enumerates+every tool as well and is far too heavy to ask "is this feature installed?".+"""++from __future__ import annotations++from fastapi import APIRouter++router = APIRouter()++[email protected]("/registered")+async def list_registered_capabilities() -> dict[str, list[str]]:+ """Every capability name a turn can be started with, sorted."""+ from deeptutor.runtime.registry.capability_registry import get_capability_registry++ return {"capabilities": sorted(get_capability_registry().list_capabilities())}diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.pyindex 68c75a3ab..cad6148a0 100644--- a/deeptutor/api/routers/mastery_path.py+++ b/deeptutor/api/routers/mastery_path.py@@ -148,6 +148,12 @@ class InitModulesRequest(BaseModel):modules: list[dict] # list of LearningModule-compatible dicts+class RenamePathRequest(BaseModel):+ """An empty name is a valid request: it restores the derived display name."""++ name: str = ""++class ChapterImport(BaseModel):title: strknowledge_points: list[str] = []@@ -189,6 +195,7 @@ async def get_progress_map(book_id: str):progress = service.get_or_create(book_id)return {"book_id": book_id,+ "name": learning_policy.path_display_name(progress),"path_revision": progress.version,"next": learning_policy.next_objective(progress).to_dict(),"map": learning_policy.map_summary(progress),@@ -303,6 +310,27 @@ async def import_from_book(book_id: str, body: ImportFromBookRequest):}[email protected]("/progress/{book_id}")+async def rename_progress(book_id: str, body: RenamePathRequest):+ """Rename a path — the only edit that is the learner's rather than the tutor's.++ Guarded like every other path mutation so a rename cannot interleave with a+ tutoring turn's own commit, and emitted as an event so the activity feed+ records who called it what.+ """+ _validate_book_id(book_id)+ store = LearningStore()+ if not await asyncio.to_thread(store.exists, book_id):+ raise HTTPException(status_code=404, detail="Progress not found")+ async with _exclusive_path_mutation(book_id):+ progress = await asyncio.to_thread(LearningService(store).rename_path, book_id, body.name)+ return {+ "status": "ok",+ "name": learning_policy.path_display_name(progress),+ "path_revision": progress.version,+ }++@router.delete("/progress/{book_id}")async def delete_progress(book_id: str):_validate_book_id(book_id)diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.pyindex f4a555ce5..1e065f560 100644--- a/deeptutor/api/routers/partners.py+++ b/deeptutor/api/routers/partners.py@@ -17,11 +17,20 @@ import loggingfrom typing import Any, AsyncGenerator, Literalfrom uuid import uuid4-from fastapi import APIRouter, HTTPException, Query, WebSocket, WebSocketDisconnect+from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnectfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field, ValidationError+from deeptutor.api.routers.auth import require_adminfrom deeptutor.core.i18n import t+from deeptutor.multi_user.context import get_current_user+from deeptutor.multi_user.partner_access import (+ assert_partner_manageable,+ can_manage_partner,+ can_use_partner,+ identity_card,+ visible_partners,+)from deeptutor.partners.config.paths import get_partner_media_dirfrom deeptutor.partners.helpers import safe_filenamefrom deeptutor.services.partners import (@@ -53,6 +62,32 @@ logger = logging.getLogger(__name__)router = APIRouter()+# ── Access guards ──────────────────────────────────────────────+#+# The router is merely authenticated; each route declares what it needs of the+# caller. Two levels, matching ``multi_user.partner_access``: *use* (hold a+# conversation) and *manage* (configure, provision, delete). A partner the+# caller may not use reads as absent rather than forbidden, so nobody can+# enumerate other people's partners by probing ids.+++def usable_partner(partner_id: str) -> str:+ """Path dependency: the partner exists and the caller may talk to it."""+ if not get_partner_manager().partner_exists(partner_id) or not can_use_partner(partner_id):+ raise HTTPException(status_code=404, detail=t("api.partner_not_found"))+ return partner_id+++def manageable_partner(partner_id: str = Depends(usable_partner)) -> str:+ """Path dependency: the caller owns the partner (or is an admin)."""+ assert_partner_manageable(partner_id)+ return partner_id+++_USABLE = [Depends(usable_partner)]+_MANAGEABLE = [Depends(manageable_partner)]++# Per-partner async locks used to dedupe concurrent WebSocket-driven# auto-starts (start_partner short-circuits when running, but that check is# not async-safe under concurrent connections).@@ -280,6 +315,7 @@ def _validate_llm_selection_payload(value: dict[str, str] | None,) -> dict[str, str] | None:"""Validate a partner model selection against the shared LLM catalog."""+ from deeptutor.multi_user.model_access import apply_allowed_llm_selectionfrom deeptutor.services.config import get_model_catalog_servicefrom deeptutor.services.model_selection import apply_llm_selection_to_catalogfrom deeptutor.services.partners.model_runtime import normalize_partner_llm_selection@@ -288,11 +324,48 @@ def _validate_llm_selection_payload(selection = normalize_partner_llm_selection(value)if selection:apply_llm_selection_to_catalog(get_model_catalog_service().load(), selection)- return selection+ # A partner must not reach a model its creator cannot: the runtime+ # executes in the partner's synthetic scope, where the owner's grants+ # are no longer visible, so the check has to land here.+ return apply_allowed_llm_selection(selection)except ValueError as exc:raise HTTPException(status_code=422, detail=str(exc)) from None+def _caller_tool_reach() -> tuple[set[str] | None, set[str] | None]:+ """``(optional, mcp)`` tool whitelists for the caller; ``None`` = unrestricted."""+ from deeptutor.multi_user.tool_access import allowed_mcp_tools, allowed_optional_tools++ if get_current_user().is_admin:+ return None, None+ return allowed_optional_tools(), allowed_mcp_tools()+++def _clamp(chosen: list[str] | None, allowed: set[str] | None) -> list[str] | None:+ """Narrow a partner's tool whitelist to *allowed*.++ ``chosen is None`` means "every tool" in partner config, so an actual+ restriction has to spell the permitted set out rather than stay open.+ """+ if allowed is None:+ return chosen+ if chosen is None:+ return sorted(allowed)+ return [name for name in chosen if name in allowed]+++def clamp_to_caller_reach(config: PartnerConfig) -> None:+ """Hold a partner's tool surface inside its creator's own permissions.++ Ordinary chat enforces per-user tool grants at turn time, but a partner+ turn runs as the partner — by then nothing recalls whose partner it is. So+ the grant is applied once, here, where the human is still on the request.+ """+ optional, mcp = _caller_tool_reach()+ config.enabled_tools = _clamp(config.enabled_tools, optional)+ config.mcp_tools = _clamp(config.mcp_tools, mcp)++def _resolve_soul_content(soul: SoulSpec | None) -> tuple[str, dict[str, str]]:"""Resolve a SoulSpec into (markdown content, origin record)."""from deeptutor.services.partners.workspace import DEFAULT_SOUL@@ -328,7 +401,6 @@ def _resolve_soul_content(soul: SoulSpec | None) -> tuple[str, dict[str, str]]:def _load_persona_markdown(name: str) -> str:- from deeptutor.multi_user.context import get_current_userfrom deeptutor.multi_user.paths import get_admin_path_servicefrom deeptutor.services.persona import PersonaService, get_persona_service@@ -356,7 +428,7 @@ async def list_souls():return get_partner_manager().list_souls()[email protected]("/souls")[email protected]("/souls", dependencies=[Depends(require_admin)])async def create_soul(payload: SoulCreateRequest):mgr = get_partner_manager()# Slug the id server-side (authoritative): soul ids ride in ``/souls/<id>``@@ -376,7 +448,7 @@ async def get_soul(soul_id: str):return soul[email protected]("/souls/{soul_id}")[email protected]("/souls/{soul_id}", dependencies=[Depends(require_admin)])async def update_soul(soul_id: str, payload: SoulTemplateUpdateRequest):result = get_partner_manager().update_soul(soul_id, payload.name, payload.content)if not result:@@ -384,7 +456,7 @@ async def update_soul(soul_id: str, payload: SoulTemplateUpdateRequest):return result[email protected]("/souls/{soul_id}")[email protected]("/souls/{soul_id}", dependencies=[Depends(require_admin)])async def delete_soul(soul_id: str):if not get_partner_manager().delete_soul(soul_id):raise HTTPException(status_code=404, detail=t("api.soul_not_found"))@@ -394,7 +466,6 @@ async def delete_soul(soul_id: str):@router.get("/soul-sources")async def soul_sources():"""Everything the create-wizard's soul step can start from."""- from deeptutor.multi_user.context import get_current_userfrom deeptutor.multi_user.paths import get_admin_path_servicefrom deeptutor.services.persona import PersonaService, get_persona_service@@ -435,12 +506,14 @@ async def soul_sources():@router.get("")async def list_partners():- return get_partner_manager().list_partners()+ """Partners the caller may talk to — theirs in full, assigned ones as cards."""+ return visible_partners()@router.get("/recent")async def recent_partners(limit: int = 3):- return get_partner_manager().get_recent_active_partners(limit=limit)+ recent = get_partner_manager().get_recent_active_partners(limit=limit)+ return [item for item in recent if can_use_partner(str(item.get("partner_id") or ""))]@router.get("/channels/schema")@@ -451,6 +524,35 @@ async def list_channel_schemas():return {"channels": all_channel_schemas()}+# ── WeChat QR onboarding ───────────────────────────────────────+#+# The personal-WeChat channel authenticates by scanning a QR code, and until now+# it only ever drew that code on the server's stdout — unreachable on any+# container deployment (#951). These two endpoints run the same exchange for the+# browser. The bot token is written into the partner's channel config server-side+# and is never part of a response.++[email protected]("/{partner_id}/channels/weixin/qr", dependencies=_MANAGEABLE)+async def start_weixin_qr(partner_id: str):+ """Issue a QR code for this partner and return what to render."""+ from deeptutor.services.partners import weixin_onboarding++ try:+ return await weixin_onboarding.start_login(partner_id)+ except Exception as exc:+ logger.warning("weixin QR start failed for %s", partner_id, exc_info=True)+ raise HTTPException(status_code=502, detail=str(exc)) from exc++[email protected]("/{partner_id}/channels/weixin/qr/{session_id}", dependencies=_MANAGEABLE)+async def poll_weixin_qr(partner_id: str, session_id: str):+ """Advance the scan and report its state (never the token)."""+ from deeptutor.services.partners import weixin_onboarding++ return await weixin_onboarding.poll_login(partner_id, session_id)++@router.get("/tool-options")async def tool_options():"""The configurable tool surface for a partner.@@ -465,11 +567,24 @@ async def tool_options():"""from deeptutor.agents._shared.tool_composition import admin_enabled_optional_toolsfrom deeptutor.api.utils.tool_options import build_tool_options+ from deeptutor.multi_user.tool_access import combine_whitelists- return await build_tool_options(+ optional, mcp = _caller_tool_reach()+ options = await build_tool_options(exclude_builtin={"read_memory", "write_memory"},- optional_tools=admin_enabled_optional_tools(),+ optional_tools=sorted(+ combine_whitelists(set(admin_enabled_optional_tools()), optional) or ()+ ),)+ if mcp is not None:+ options["mcp_tools"] = [+ tool for tool in options.get("mcp_tools", []) if _tool_name(tool) in mcp+ ]+ return options+++def _tool_name(tool: Any) -> str:+ return str(tool.get("name") or "") if isinstance(tool, dict) else str(tool)# ── Create / read / update / lifecycle ─────────────────────────@@ -477,6 +592,12 @@ async def tool_options():@router.post("")async def create_partner(payload: CreatePartnerRequest):+ """Create a partner owned by the caller.++ Anyone may build their own companion; the assets it is provisioned with are+ resolved against the creator's own permissions (see ``provision_assets``),+ so this hands nobody access they did not already have.+ """mgr = get_partner_manager()partner_id = slugify_partner_id(payload.partner_id or payload.name)if mgr.partner_exists(partner_id):@@ -494,6 +615,7 @@ async def create_partner(payload: CreatePartnerRequest):config = PartnerConfig(name=payload.name.strip(),description=(payload.description or "").strip(),+ owner_id=get_current_user().id,channels=payload.channels or {},llm_selection=llm_selection,backup_llm_selection=backup_llm_selection,@@ -506,6 +628,7 @@ async def create_partner(payload: CreatePartnerRequest):builtin_tools=payload.builtin_tools,mcp_tools=payload.mcp_tools,)+ clamp_to_caller_reach(config)mgr.save_config(partner_id, config, auto_start=bool(payload.start))write_soul(partner_id, soul_content)@@ -565,7 +688,7 @@ def _stopped_partner_dict(}[email protected]("/{partner_id}")[email protected]("/{partner_id}", dependencies=_USABLE)async def get_partner(partner_id: str,include_secrets: bool = Query(@@ -576,17 +699,28 @@ async def get_partner(),),):+ """One partner, projected by what the caller may do with it.++ Someone who merely *uses* the partner gets its identity card — enough to+ render a conversation header — while its owner gets the configuration.+ """mgr = get_partner_manager()+ manageable = can_manage_partner(partner_id)+ include_secrets = include_secrets and manageableinstance = mgr.get_partner(partner_id)if instance:- return instance.to_dict(+ full = instance.to_dict(include_secrets=include_secrets,mask_secrets=not include_secrets,)- cfg = mgr.load_config(partner_id)- if cfg:- return _stopped_partner_dict(partner_id, cfg, include_secrets=include_secrets)- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))+ else:+ cfg = mgr.load_config(partner_id)+ if cfg is None:+ raise HTTPException(status_code=404, detail=t("api.partner_not_found"))+ full = _stopped_partner_dict(partner_id, cfg, include_secrets=include_secrets)+ if not manageable:+ return {**identity_card(full), "can_manage": False}+ return {**full, "can_manage": True}def _apply_update(cfg: PartnerConfig, payload: UpdatePartnerRequest) -> None:@@ -615,9 +749,10 @@ def _apply_update(cfg: PartnerConfig, payload: UpdatePartnerRequest) -> None:cfg.builtin_tools = payload.builtin_toolsif "mcp_tools" in payload.model_fields_set:cfg.mcp_tools = payload.mcp_tools+ clamp_to_caller_reach(cfg)[email protected]("/{partner_id}")[email protected]("/{partner_id}", dependencies=_MANAGEABLE)async def update_partner(partner_id: str, payload: UpdatePartnerRequest):if payload.channels is not None:_validate_channels_payload(payload.channels)@@ -651,7 +786,7 @@ async def update_partner(partner_id: str, payload: UpdatePartnerRequest):return _stopped_partner_dict(partner_id, cfg)[email protected]("/{partner_id}/start")[email protected]("/{partner_id}/start", dependencies=_MANAGEABLE)async def start_partner(partner_id: str):instance = await _ensure_running_partner(partner_id, allow_stopped=True)# An explicit start is a persisted "run on boot" intent — so the partner@@ -661,7 +796,7 @@ async def start_partner(partner_id: str):return instance.to_dict(mask_secrets=True)[email protected]("/{partner_id}/stop")[email protected]("/{partner_id}/stop", dependencies=_MANAGEABLE)async def stop_partner(partner_id: str):stopped = await get_partner_manager().stop_partner(partner_id)if not stopped:@@ -669,7 +804,7 @@ async def stop_partner(partner_id: str):return {"partner_id": partner_id, "stopped": True}[email protected]("/{partner_id}")[email protected]("/{partner_id}", dependencies=_MANAGEABLE)async def destroy_partner(partner_id: str):destroyed = await get_partner_manager().destroy_partner(partner_id)if not destroyed:@@ -677,7 +812,7 @@ async def destroy_partner(partner_id: str):return {"partner_id": partner_id, "destroyed": True}[email protected]("/{partner_id}/channels/reload")[email protected]("/{partner_id}/channels/reload", dependencies=_MANAGEABLE)async def reload_partner_channels(partner_id: str):mgr = get_partner_manager()instance = mgr.get_partner(partner_id)@@ -700,7 +835,7 @@ def _onboarding_manager_and_partner(partner_id: str):return get_channel_onboarding_manager(), mgr[email protected]("/{partner_id}/channel-onboarding/start")[email protected]("/{partner_id}/channel-onboarding/start", dependencies=_MANAGEABLE)async def start_partner_channel_onboarding(partner_id: str, payload: ChannelOnboardingStartRequest):onboarding, _ = _onboarding_manager_and_partner(partner_id)try:@@ -715,7 +850,7 @@ async def start_partner_channel_onboarding(partner_id: str, payload: ChannelOnbo) from exc[email protected]("/{partner_id}/channel-onboarding/{session_id}")[email protected]("/{partner_id}/channel-onboarding/{session_id}", dependencies=_MANAGEABLE)async def get_partner_channel_onboarding(partner_id: str, session_id: str):onboarding, _ = _onboarding_manager_and_partner(partner_id)try:@@ -730,7 +865,7 @@ async def get_partner_channel_onboarding(partner_id: str, session_id: str):) from exc[email protected]("/{partner_id}/channel-onboarding/{session_id}")[email protected]("/{partner_id}/channel-onboarding/{session_id}", dependencies=_MANAGEABLE)async def cancel_partner_channel_onboarding(partner_id: str, session_id: str):onboarding, _ = _onboarding_manager_and_partner(partner_id)try:@@ -739,7 +874,7 @@ async def cancel_partner_channel_onboarding(partner_id: str, session_id: str):raise HTTPException(status_code=exc.status_code, detail=str(exc)) from None[email protected]("/{partner_id}/channel-onboarding/{session_id}/apply")[email protected]("/{partner_id}/channel-onboarding/{session_id}/apply", dependencies=_MANAGEABLE)async def apply_partner_channel_onboarding(partner_id: str, session_id: str):onboarding, mgr = _onboarding_manager_and_partner(partner_id)try:@@ -760,19 +895,13 @@ async def apply_partner_channel_onboarding(partner_id: str, session_id: str):# ── Soul (the partner's own SOUL.md) ───────────────────────────[email protected]("/{partner_id}/soul")[email protected]("/{partner_id}/soul", dependencies=_MANAGEABLE)async def get_partner_soul(partner_id: str):- mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))return {"partner_id": partner_id, "content": read_soul(partner_id)}[email protected]("/{partner_id}/soul")[email protected]("/{partner_id}/soul", dependencies=_MANAGEABLE)async def put_partner_soul(partner_id: str, payload: SoulUpdateBody):- mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))write_soul(partner_id, payload.content)return {"partner_id": partner_id, "saved": True}@@ -780,19 +909,13 @@ async def put_partner_soul(partner_id: str, payload: SoulUpdateBody):# ── Assets ─────────────────────────────────────────────────────[email protected]("/{partner_id}/assets")[email protected]("/{partner_id}/assets", dependencies=_MANAGEABLE)async def get_partner_assets(partner_id: str):- mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))return list_assets(partner_id)[email protected]("/{partner_id}/assets")[email protected]("/{partner_id}/assets", dependencies=_MANAGEABLE)async def add_partner_assets(partner_id: str, payload: AssetAddRequest):- mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))report = provision_assets(partner_id,knowledge_bases=payload.knowledge_bases,@@ -802,11 +925,8 @@ async def add_partner_assets(partner_id: str, payload: AssetAddRequest):return {"partner_id": partner_id, **report, "assets": list_assets(partner_id)}[email protected]("/{partner_id}/assets/{asset_type}/{name}")[email protected]("/{partner_id}/assets/{asset_type}/{name}", dependencies=_MANAGEABLE)async def delete_partner_asset(partner_id: str, asset_type: str, name: str):- mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))try:removed = remove_asset(partner_id, asset_type, name)except ValueError as exc:@@ -816,10 +936,49 @@ async def delete_partner_asset(partner_id: str, asset_type: str, name: str):return {"partner_id": partner_id, "removed": True, "assets": list_assets(partner_id)}+# ── Channel account links ──────────────────────────────────────++[email protected]("/{partner_id}/links/code", dependencies=_USABLE)+async def create_partner_link_code(partner_id: str):+ """Mint a code for connecting one of your chat accounts to this partner.++ Send ``/link <code>`` to the partner as a direct message from the chat+ account you want connected; that account then speaks as you.+ """+ from deeptutor.services.partners.links import issue_link_code++ issued = issue_link_code(partner_id, get_current_user().id)+ return {+ "partner_id": partner_id,+ "code": issued.code,+ "expires_at": issued.expires_at,+ "command": f"/link {issued.code}",+ }++[email protected]("/{partner_id}/links", dependencies=_USABLE)+async def list_partner_links(partner_id: str):+ """Your own linked chat accounts for this partner — never anyone else's."""+ from deeptutor.services.partners.links import list_links++ return {"partner_id": partner_id, "links": list_links(partner_id, get_current_user().id)}++[email protected]("/{partner_id}/links/{key:path}", dependencies=_USABLE)+async def delete_partner_link(partner_id: str, key: str):+ """Disconnect one of your chat accounts; its past messages stay yours."""+ from deeptutor.services.partners.links import remove_link++ if not remove_link(partner_id, get_current_user().id, key):+ raise HTTPException(status_code=404, detail="No such linked account")+ return {"partner_id": partner_id, "removed": True, "key": key}++# ── History ────────────────────────────────────────────────────[email protected]("/{partner_id}/history")[email protected]("/{partner_id}/history", dependencies=_USABLE)async def get_partner_history(partner_id: str,session_key: str | None = None,@@ -835,53 +994,43 @@ async def get_partner_history(return mgr.get_history(partner_id, session_key=session_key, limit=limit)[email protected]("/{partner_id}/sessions")[email protected]("/{partner_id}/sessions", dependencies=_USABLE)async def get_partner_sessions(partner_id: str):mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))return mgr.session_store(partner_id).list_sessions()[email protected]("/{partner_id}/sessions/archive")[email protected]("/{partner_id}/sessions/archive", dependencies=_USABLE)async def archive_partner_session(partner_id: str, payload: SessionKeyBody):"""Soft-archive a session (web /new) — it stays resumable, file untouched."""mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))mgr.archive_session(partner_id, payload.session_key)return {"partner_id": partner_id, "archived": True, "session_key": payload.session_key}[email protected]("/{partner_id}/sessions/resume")[email protected]("/{partner_id}/sessions/resume", dependencies=_USABLE)async def resume_partner_session(partner_id: str, payload: SessionKeyBody):"""Clear a session's archived flag so the web app can continue it."""mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))summary = mgr.resume_session(partner_id, payload.session_key)if summary is None:raise HTTPException(status_code=404, detail="Session not found")return {"partner_id": partner_id, "resumed": True, "session": summary}[email protected]("/{partner_id}/sessions/delete")[email protected]("/{partner_id}/sessions/delete", dependencies=_USABLE)async def delete_partner_session(partner_id: str, payload: SessionKeyBody):mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))removed = mgr.delete_session(partner_id, payload.session_key)if not removed:raise HTTPException(status_code=404, detail="Session not found")return {"partner_id": partner_id, "deleted": True, "session_key": payload.session_key}[email protected]("/{partner_id}/sessions/branch")[email protected]("/{partner_id}/sessions/branch", dependencies=_USABLE)async def branch_partner_session(partner_id: str, payload: SessionBranchBody):"""Copy a session's full history into a new key and archive the source."""mgr = get_partner_manager()- if not mgr.partner_exists(partner_id):- raise HTTPException(status_code=404, detail=t("api.partner_not_found"))summary = mgr.branch_session(partner_id, payload.source_key, payload.new_key)if summary is None:raise HTTPException(status_code=400, detail="Nothing to branch (source is empty)")@@ -984,7 +1133,7 @@ def _materialize_partner_attachments(return media_paths[email protected]("/{partner_id}/chat")[email protected]("/{partner_id}/chat", dependencies=_USABLE)async def partner_chat_http(partner_id: str, payload: ChatMessageRequest) -> dict[str, Any]:"""Send one HTTP message to a partner with persistent session context."""content = payload.content.strip()@@ -1075,7 +1224,7 @@ async def _partner_chat_stream(task.cancel()[email protected]("/{partner_id}/chat/execute-stream")[email protected]("/{partner_id}/chat/execute-stream", dependencies=_USABLE)async def partner_chat_http_stream(partner_id: str, payload: ChatMessageRequest):"""Stream one HTTP message to a partner as server-sent events."""if not payload.content.strip() and not payload.attachments:@@ -1110,6 +1259,17 @@ async def partner_chat_ws(ws: WebSocket, partner_id: str):returnmgr = get_partner_manager()++ # The HTTP path dependencies can't run on a socket, so the same check is+ # made by hand: an unknown partner and one the caller may not talk to close+ # identically. ``ws_require_auth`` has already bound the current user, so+ # the token has to be released on this early exit too.+ if not mgr.partner_exists(partner_id) or not can_use_partner(partner_id):+ if user_token is not None:+ reset_current_user(user_token)+ await ws.close(code=4404)+ return+disconnected = asyncio.Event()async def _safe_send(payload: dict) -> bool:diff --git a/deeptutor/book/blocks/animation.py b/deeptutor/book/blocks/animation.pyindex 6e41de15a..e69c30879 100644--- a/deeptutor/book/blocks/animation.py+++ b/deeptutor/book/blocks/animation.py@@ -15,6 +15,8 @@ import importlib.utilimport loggingfrom typing import Any+from deeptutor.services.keypool import primary_api_key+from ..models import BlockType, SourceAnchorfrom ._prompts import get_book_prompt, load_book_promptsfrom .base import BlockContext, BlockGenerator, GenerationFailure@@ -80,7 +82,7 @@ class AnimationGenerator(BlockGenerator):style_hint=style_hint,)pipeline = MathAnimatorPipeline(- api_key=llm_config.api_key,+ api_key=primary_api_key(llm_config.api_key),base_url=llm_config.base_url,api_version=llm_config.api_version,language=ctx.language,diff --git a/deeptutor/book/blocks/figure.py b/deeptutor/book/blocks/figure.pyindex c7d89bd90..15951632a 100644--- a/deeptutor/book/blocks/figure.py+++ b/deeptutor/book/blocks/figure.py@@ -16,6 +16,8 @@ from __future__ import annotationsimport loggingfrom typing import Any+from deeptutor.services.keypool import primary_api_key+from ..models import BlockType, SourceAnchorfrom ._prompts import get_book_prompt, load_book_promptsfrom .base import BlockContext, BlockGenerator, GenerationFailure@@ -71,7 +73,7 @@ class FigureGenerator(BlockGenerator):llm_config = get_llm_config()pipeline = VisualizePipeline(- api_key=llm_config.api_key,+ api_key=primary_api_key(llm_config.api_key),base_url=llm_config.base_url,api_version=llm_config.api_version,language=ctx.language,diff --git a/deeptutor/book/blocks/interactive.py b/deeptutor/book/blocks/interactive.pyindex be11612e3..17a99bc26 100644--- a/deeptutor/book/blocks/interactive.py+++ b/deeptutor/book/blocks/interactive.py@@ -16,6 +16,8 @@ from __future__ import annotationsimport loggingfrom typing import Any+from deeptutor.services.keypool import primary_api_key+from ..models import BlockType, SourceAnchorfrom ._prompts import get_book_prompt, load_book_promptsfrom .base import BlockContext, BlockGenerator, GenerationFailure@@ -70,7 +72,7 @@ class InteractiveGenerator(BlockGenerator):llm_config = get_llm_config()pipeline = VisualizePipeline(- api_key=llm_config.api_key,+ api_key=primary_api_key(llm_config.api_key),base_url=llm_config.base_url,api_version=llm_config.api_version,language=ctx.language,diff --git a/deeptutor/capabilities/mastery/choices.py b/deeptutor/capabilities/mastery/choices.pyindex d0e7e5355..a5273ab16 100644--- a/deeptutor/capabilities/mastery/choices.py+++ b/deeptutor/capabilities/mastery/choices.py@@ -8,6 +8,8 @@ option text. This module owns the translation between those shapes so the toollayer (:mod:`deeptutor.capabilities.mastery.tools`) reads as orchestration:* :func:`parse_options` — option strings → a ``{label: body}`` map.+* :func:`option_label_intent` / :func:`canonical_labels` — were the options+ meant to be labelled A/B/C, and do those labels form a well-formed set?* :func:`has_option_bodies` — did the model send real bodies, not bare labels?* :func:`format_options` — a ``{label: body}`` map → canonical option strings.* :func:`resolve_answer` — a model-supplied answer → its stable option label.@@ -25,8 +27,10 @@ import loggingfrom typing import Anyfrom deeptutor.learning.pending import (+ canonical_labels,format_options,has_option_bodies,+ option_label_intent,parse_options,resolve_answer,resolve_choice_submission,@@ -84,8 +88,10 @@ async def recover_options_from_turn(store: Any, turn_id: str, question: str) ->__all__ = [+ "canonical_labels","format_options","has_option_bodies",+ "option_label_intent","parse_options","recover_options_from_turn","resolve_answer",diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.pyindex cdf31854c..2380ebb36 100644--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@ -119,6 +119,12 @@ class MasteryLoopCapability:name = "mastery"owned_tools = MASTERY_TOOL_NAMES+ # Declared to the dispatcher so a switch that shares a round with a write+ # runs first and the write lands on the path the model switched *to*. Every+ # call in a round is bound before any of them runs, so without this a+ # ``mastery_switch`` + ``mastery_build`` round rebuilt the map of the path+ # the conversation was leaving.+ rebinding_tools = tuple(_PATH_BINDING_TOOLS)def is_active(self, context: UnifiedContext) -> bool:return bool(context.metadata.get("mastery_mode"))diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex 30d44eb75..ca715a25a 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -22,8 +22,10 @@ from typing import TYPE_CHECKING, Anyimport uuidfrom deeptutor.capabilities.mastery.choices import (+ canonical_labels,format_options,has_option_bodies,+ option_label_intent,parse_options,recover_options_from_turn,resolve_answer,@@ -53,6 +55,7 @@ from deeptutor.learning.policy import (is_mastered,map_summary,next_objective,+ path_display_name,)if TYPE_CHECKING:@@ -118,6 +121,25 @@ def _question_bank_type(question_type: str) -> str:return "short_answer"+def _duplicate_option_body(options: dict[str, str]) -> str:+ """The first option body that appears twice, ignoring case and spacing.++ A model does occasionally emit the same answer under two labels, and a+ choice card with identical options is unanswerable: the learner picks the+ one they believe is right and is graded wrong for picking the twin. Better+ to reject the registration and let the model write a real distractor.+ """+ seen: set[str] = set()+ for body in options.values():+ key = "".join(str(body or "").split()).casefold()+ if not key:+ continue+ if key in seen:+ return body+ seen.add(key)+ return ""++def _normalize_quiz_contract(raw_question_type: Any,raw_options: Any,@@ -154,11 +176,22 @@ def _normalize_quiz_contract()return question_type, [], expected_answer+ intended_labels = option_label_intent(options)+ if intended_labels is not None and set(intended_labels) != canonical_labels(+ len(intended_labels)+ ):+ raise ValueError(+ f"Choice option labels must run A, B, C… with one option each; got "+ f"{intended_labels}. Retry mastery_quiz with one full body per label."+ )+choice_options = parse_options(options)- if len(choice_options) != len(options):+ duplicate = _duplicate_option_body(choice_options)+ if duplicate:raise ValueError(- "Choice option labels must be unique; retry mastery_quiz with one full body "- "for each label."+ f"Two or more choice options have the same answer ({duplicate!r}), so the "+ "learner would be shown identical choices. Retry mastery_quiz with one "+ "distinct body per option.")if not has_option_bodies(choice_options):raise ValueError(@@ -249,6 +282,25 @@ async def _sync_mastery_attempt_to_question_bank()+def _unreadable_choice_result(answer: str, options: dict[str, str]) -> ToolResult:+ """Ask for a definite choice rather than recording a guess as wrong."""+ shown = "; ".join(f"{label} = {body}" for label, body in options.items())+ blank = not str(answer or "").strip()+ return ToolResult(+ content=(+ (+ "The learner has not answered this question yet, so there is nothing to grade. "+ if blank+ else f"Could not tell which option {answer!r} picks, so it was NOT graded. "+ )+ + f"The options are: {shown}. Ask the learner which one they choose (or "+ "present the question again with ask_user), then call mastery_grade with "+ "the option label. Do not treat this as a wrong answer."+ ),+ success=False,+ )++def _json_result(payload: dict[str, Any], *, meta_key: str, success: bool = True) -> ToolResult:return ToolResult(content=json.dumps(payload, ensure_ascii=False),@@ -363,6 +415,17 @@ class MasteryStatusTool(BaseTool):# The answer is learner-authored state, not the hidden answer# key. Returning it lets a restart grade rather than ask twice.pending_interaction["learner_answer"] = interaction.user_answer+ else:+ # The card is not the only way in. A learner often answers the+ # question in the composer — that reply never reaches the+ # interaction, so without this the tutor re-posed the same+ # question forever and the path stalled on answer_pending.+ pending_interaction["instruction"] = (+ "A question is already open. If the learner has answered it "+ "anywhere in this conversation — on the card or in an ordinary "+ "message — call mastery_grade with their answer and this "+ "question_id instead of posing it again."+ )payload["pending_interaction"] = pending_interactionreturn _json_result(payload, meta_key="mastery_status")@@ -592,7 +655,18 @@ class MasteryGradeTool(BaseTool):choice_options, expected_answer = await _resolve_pending_choice(pending, _resolve_turn_id(kwargs))- answer_for_grading = resolve_choice_submission(answer, choice_options) or answer+ answer_for_grading = resolve_choice_submission(answer, choice_options)+ if not answer_for_grading:+ if has_option_bodies(choice_options):+ # Grading is a permanent, deterministic record. An answer+ # we cannot map onto exactly one option is not a wrong+ # answer — it is an unreadable one, and marking it wrong is+ # how a learner who typed their choice instead of tapping+ # the card lost mastery for being right.+ return _unreadable_choice_result(answer, choice_options)+ # Legacy question with no recoverable bodies: the raw reply is+ # the only thing there is to compare.+ answer_for_grading = answerfrom deeptutor.learning.service import MasteryInteractionErrortry:@@ -741,10 +815,11 @@ class MasteryBuildTool(BaseTool):"Create or extend the learner's mastery path. Design modules and ""their knowledge points from the learner's materials (use rag / ""read_source first when materials are attached) and pass them "- "here. Each knowledge point needs a 'type': memory (facts), "- "procedure (step-by-step skills), concept (ideas to understand), "- "or design (open-ended judgement). Use mode='replace' to start "- "fresh or 'append' to add to an existing path."+ "here, with a short path_name the learner will recognise. Each "+ "knowledge point needs a 'type': memory (facts), procedure "+ "(step-by-step skills), concept (ideas to understand), or design "+ "(open-ended judgement). Use mode='replace' to start fresh or "+ "'append' to add to an existing path."),parameters=[ToolParameter(@@ -776,6 +851,18 @@ class MasteryBuildTool(BaseTool):"required": ["name", "knowledge_points"],},),+ ToolParameter(+ name="path_name",+ type="string",+ description=(+ "What to call this path — a short course title the "+ "learner will recognise in their dashboard, such as "+ "'Quadratic equations'. Used only when the path has no "+ "name yet; rebuilding a named path keeps its name, and "+ "renaming one is the learner's own call."+ ),+ required=False,+ ),ToolParameter(name="mode",type="string",@@ -804,6 +891,7 @@ class MasteryBuildTool(BaseTool):path_id,new_modules,append=mode == "append",+ name=str(kwargs.get("path_name") or ""),event_type="path.built",session_id=_resolve_session_id(kwargs),turn_id=_resolve_turn_id(kwargs),@@ -814,6 +902,9 @@ class MasteryBuildTool(BaseTool):"status": "built","path_revision": progress.version,"mode": mode,+ # The name in effect, which is not necessarily the one passed:+ # an already-named path keeps the name the learner sees.+ "path_name": path_display_name(progress),"modules_added": len(new_modules),"knowledge_points_added": kp_count,"map": map_summary(progress),@@ -854,8 +945,9 @@ class MasteryPathsTool(BaseTool):"active_path_id": active,"paths": paths,"instruction": (- "Switch with mastery_switch(path_id=...) — it takes effect "- "from your next round, so call mastery_status afterwards."+ "Switch with mastery_switch(path_id=...); every later call "+ "in the turn — including ones issued alongside it — then "+ "acts on the new path. Call mastery_status after switching."),},meta_key="mastery_paths",@@ -914,7 +1006,8 @@ class MasterySwitchTool(BaseTool):"active_path_id": active,"instruction": ("This conversation now follows that path, on this turn and "- "later ones. Call mastery_status to see where it stands."+ "later ones — anything else you called in this round acted "+ "on it too. Call mastery_status to see where it stands."),},meta_key="mastery_switch",diff --git a/deeptutor/capabilities/protocol.py b/deeptutor/capabilities/protocol.pyindex a8a3cf137..02944537b 100644--- a/deeptutor/capabilities/protocol.py+++ b/deeptutor/capabilities/protocol.py@@ -78,6 +78,12 @@ class LoopCapability(Protocol):ask_user, *, reply_text, answers)`` hooks. The pipeline invokes them onthe two sides of an ``ask_user`` wait so state can be committed before adisconnect or another LLM round.++ A capability whose tools can repoint the turn at a different target MAY+ declare those tool names as ``rebinding_tools: tuple[str, ...]`` (read with+ a ``getattr`` default, like ``pre_loop``). The dispatcher runs them before+ the round's other calls and re-binds those calls afterwards, so a switch+ and a write issued in the same round cannot land on different targets."""name: strdiff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.pyindex 537c5e426..1c7870254 100644--- a/deeptutor/core/agentic/client.py+++ b/deeptutor/core/agentic/client.py@@ -23,7 +23,7 @@ import httpxfrom openai import AsyncAzureOpenAI, AsyncOpenAIfrom deeptutor.services.config import load_system_settings-from deeptutor.services.keypool import KeyPool+from deeptutor.services.keypool import KeyPool, primary_api_keyfrom deeptutor.services.llm import get_token_limit_kwargs, supports_toolsfrom deeptutor.services.llm.openai_http_client import sanitize_invalid_ssl_envfrom deeptutor.services.llm.reasoning_params import (@@ -244,7 +244,7 @@ def _build_anthropic_adapter(config: LLMClientConfig, spec: Any) -> Any:from deeptutor.services.llm.provider_core import AnthropicProvideranthropic_provider = AnthropicProvider(- api_key=config.api_key,+ api_key=primary_api_key(config.api_key),api_base=config.base_url or spec.default_api_base or None,default_model=config.model or "claude-sonnet-4-20250514",extra_headers=config.extra_headers,@@ -278,7 +278,7 @@ def _build_codebuddy_adapter(config: LLMClientConfig, spec: Any) -> Any:)codebuddy_provider = build_codebuddy_provider(- api_key=config.api_key,+ api_key=primary_api_key(config.api_key),default_model=config.model or "codebuddy/hy3",)return _ProviderOpenAIAdapter(codebuddy_provider)diff --git a/deeptutor/core/agentic/tool_dispatch.py b/deeptutor/core/agentic/tool_dispatch.pyindex 33146924f..2405b6fc3 100644--- a/deeptutor/core/agentic/tool_dispatch.py+++ b/deeptutor/core/agentic/tool_dispatch.py@@ -55,6 +55,10 @@ PAUSE_LAST_TOOLS = frozenset({"ask_user"})KwargAugmenter = Callable[[str, dict[str, Any], UnifiedContext], dict[str, Any]]+# Tool names whose whole job is to change what the *rest* of the round operates+# on (a mastery path, a workspace, …). Supplied per turn by the caller, since+# which tools rebind is a capability's knowledge, not the dispatcher's.+RebindingTools = frozenset[str]RetrieveMetaFactory = Callable[[dict[str, Any], str, dict[str, Any]], dict[str, Any] | None]UnknownErrorMessageFactory = Callable[[str], str]@@ -92,6 +96,7 @@ async def dispatch_tool_calls(iteration_index: int,registry: ToolLookup | None = None,kwarg_augmenter: KwargAugmenter | None = None,+ rebinding_tools: RebindingTools = frozenset(),retrieve_meta_factory: RetrieveMetaFactory | None = None,tool_call_label: str = "Tool call",retrieve_label: str = "Retrieve",@@ -201,27 +206,60 @@ async def dispatch_tool_calls(retrieve_label=retrieve_label,)- # Pausing tools go last, and re-bind first: their whole job is to show the- # user the state of the round, which does not exist until the round has- # run. Everything else still runs concurrently, and a pause costs no- # parallelism worth keeping — the turn is about to stop and wait anyway.- deferred = [index for index, (_, name, _) in enumerate(prepared) if name in PAUSE_LAST_TOOLS]- if deferred:- immediate = [index for index in range(len(prepared)) if index not in set(deferred)]- by_index = dict(- zip(immediate, await asyncio.gather(*[_run_one(i) for i in immediate]), strict=True)- )- for index in deferred:- if kwarg_augmenter is None or duplicate_of.get(index) is not None:+ def _rebind(indices: list[int]) -> None:+ """Re-bind server-owned args from the model's originals.++ As idempotent as the first bind, so a call can be re-bound at any+ stage boundary; a duplicate short-circuits before it executes and has+ nothing to re-bind.+ """+ if kwarg_augmenter is None:+ return+ for index in indices:+ if duplicate_of.get(index) is not None:continuecall_id, name, _stale = prepared[index]prepared[index] = (call_id, name, kwarg_augmenter(name, raw_args[index], context))++ # Three ordered stages around one concurrent middle. Every call in a round+ # has its args bound before any of them runs, so a tool that *changes what+ # the round operates on* has to run before the calls it affects — and those+ # calls have to be re-bound afterwards, or they would still be pointed at+ # the state the round started with.+ #+ # 1. rebinding tools (serial: two of them in one round are a handoff,+ # not a race), then everything else re-binds against the new target;+ # 2. everything else, concurrently;+ # 3. pausing tools, re-bound once more — their whole job is to show the+ # user the state of the round, which does not exist until it has run.+ # A pause costs no parallelism worth keeping: the turn is about to+ # stop and wait anyway.+ rebinding = [index for index, (_, name, _) in enumerate(prepared) if name in rebinding_tools]+ pausing = [+ index+ for index, (_, name, _) in enumerate(prepared)+ if name in PAUSE_LAST_TOOLS and index not in set(rebinding)+ ]+ ordinary = [+ index+ for index in range(len(prepared))+ if index not in set(rebinding) and index not in set(pausing)+ ]+ by_index: dict[int, dict[str, Any]] = {}+ if rebinding:+ for index in rebinding:+ by_index[index] = await _run_one(index)+ _rebind(ordinary)+ if ordinary:by_index.update(- zip(deferred, await asyncio.gather(*[_run_one(i) for i in deferred]), strict=True)+ zip(ordinary, await asyncio.gather(*[_run_one(i) for i in ordinary]), strict=True))- results = [by_index[index] for index in range(len(prepared))]- else:- results = await asyncio.gather(*[_run_one(i) for i in range(len(prepared))])+ if pausing:+ _rebind(pausing)+ by_index.update(+ zip(pausing, await asyncio.gather(*[_run_one(i) for i in pausing]), strict=True)+ )+ results = [by_index[index] for index in range(len(prepared))]return await _collect_outcome(prepared=prepared,diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.pyindex ee839a911..0ceaab1a4 100644--- a/deeptutor/learning/models.py+++ b/deeptutor/learning/models.py@@ -253,6 +253,11 @@ class LearningProgress(BaseModel):model_config = ConfigDict(extra="ignore")book_id: str+ # The learner-facing name of this path. Empty means "never named": the+ # display name is then derived (``policy.path_display_name``), which is how+ # every path behaved before this field existed — so an aggregate persisted+ # without it needs no migration.+ name: str = ""diagnostic: DiagnosticResult | None = Nonemodules: list[LearningModule] = Field(default_factory=list)current_module_id: str = ""diff --git a/deeptutor/learning/pending.py b/deeptutor/learning/pending.pyindex e27f3e59f..12c5d54b9 100644--- a/deeptutor/learning/pending.py+++ b/deeptutor/learning/pending.py@@ -9,6 +9,7 @@ and grading, so all three boundaries use the same immutable label/body map.from __future__ import annotations+from collections.abc import Iterablefrom dataclasses import dataclassimport refrom typing import TYPE_CHECKING, Any@@ -20,21 +21,68 @@ if TYPE_CHECKING:OPTION_PREFIX_RE = re.compile(r"^\s*([A-Z])\s*[.::、))-]\s*(.+)$", re.IGNORECASE | re.DOTALL)-def parse_options(options: list[str]) -> dict[str, str]:- """Map persisted option strings to their stable ``{label: body}`` form."""- result: dict[str, str] = {}- for idx, raw in enumerate(options):- text = str(raw or "").strip()- if not text:+def positional_label(index: int) -> str:+ """The label an option carries by its position: A, B, C, … then 27, 28, …"""+ return chr(ord("A") + index) if index < 26 else str(index + 1)+++def _option_texts(options: list[str]) -> list[str]:+ return [text for text in (str(raw or "").strip() for raw in options) if text]+++def _split_labelled(texts: list[str]) -> tuple[list[str], list[str]] | None:+ """``(labels, bodies)`` when every option carries a single-letter prefix."""+ labels: list[str] = []+ bodies: list[str] = []+ for text in texts:+ if len(text) == 1 and text.isalnum():+ # Legacy rows persisted the bare labels themselves.+ labels.append(text.upper())+ bodies.append(text)continuematch = OPTION_PREFIX_RE.match(text)- if match:- result[match.group(1).upper()] = match.group(2).strip()- elif len(text) == 1 and text.isalnum():- result[text.upper()] = text- else:- result[chr(ord("A") + idx) if idx < 26 else str(idx + 1)] = text- return result+ if match is None:+ return None+ labels.append(match.group(1).upper())+ bodies.append(match.group(2).strip())+ return labels, bodies+++def option_label_intent(options: list[str]) -> list[str] | None:+ """The A/B/C labels the caller *meant* to give, or ``None`` if unlabelled.++ "Meant to" is decided by two things together: every option carries a+ single-letter prefix, and the first one is ``A``. A leading letter alone is+ not evidence — ``"x - 1 = 0"`` matches the prefix pattern and would+ otherwise register as option ``X`` with the body ``"1 = 0"``, which is how+ a maths question ended up with mislabelled and (once two options collided+ on one letter) duplicated choices.++ The returned labels may still be malformed — repeated or skipping a letter.+ :func:`parse_options` reads those positionally so nothing is lost, and+ registration rejects them so the model fixes the question instead.+ """+ split = _split_labelled(_option_texts(options))+ if split is None:+ return None+ labels, _ = split+ return labels if labels and labels[0] == "A" else None+++def canonical_labels(count: int) -> set[str]:+ """The label set a well-formed *count*-option question must carry."""+ return {positional_label(index) for index in range(count)}+++def parse_options(options: list[str]) -> dict[str, str]:+ """Map persisted option strings to their stable ``{label: body}`` form."""+ texts = _option_texts(options)+ split = _split_labelled(texts)+ if split is not None:+ labels, bodies = split+ if labels[:1] == ["A"] and set(labels) == canonical_labels(len(labels)):+ return dict(zip(labels, bodies, strict=True))+ return {positional_label(index): text for index, text in enumerate(texts)}def has_option_bodies(options: dict[str, str]) -> bool:@@ -71,12 +119,38 @@ def resolve_answer(answer: str, options: dict[str, str]) -> str:return contained[0] if len(contained) == 1 else ""+def _squeezed(value: str) -> str:+ """Case-folded with all whitespace removed, for comparing formulas."""+ return "".join(str(value or "").split()).casefold()+++def _mentioned_labels(text: str, labels: Iterable[str]) -> list[str]:+ """Labels named in *text* as standalone tokens, not inside another word.++ ``\\b`` is useless here: Chinese is word-character too, so ``"选C"`` has no+ word boundary before the ``C``. The guard is therefore "not glued to+ another latin letter or digit", which accepts ``选C`` / ``答案是 C`` /+ ``C。`` and rejects the ``C`` inside ``ABC``.+ """+ return [+ label+ for label in labels+ if re.search(rf"(?<![0-9A-Za-z]){re.escape(label)}(?![0-9A-Za-z])", text, re.IGNORECASE)+ ]++def resolve_choice_submission(answer: str, options: dict[str, str]) -> str:- """Resolve a learner submission by label or one exact, unique option body.+ """Resolve a learner submission to the option label it picked, or ``""``.++ A learner typing into the composer instead of tapping the card writes+ ``"选C"``, ``"答案是 C"`` or the option body itself — none of which the+ label-only comparison could read, so a correct answer was graded wrong.+ Every form that identifies exactly ONE option is accepted; anything+ ambiguous (two labels named, a body fragment matching several) resolves to+ nothing, which the caller must treat as "unreadable", never as wrong.- Registration remains forgiving of a model-supplied body fragment through- :func:`resolve_answer`; grading is intentionally stricter so a partial word- cannot accidentally count as a correct learner answer.+ Registration stays separately forgiving of a model-supplied body fragment+ through :func:`resolve_answer`."""candidate = str(answer or "").strip()if not candidate:@@ -87,9 +161,12 @@ def resolve_choice_submission(answer: str, options: dict[str, str]) -> str:prefix_match = OPTION_PREFIX_RE.match(candidate)if prefix_match and prefix_match.group(1).upper() in options:return prefix_match.group(1).upper()- needle = candidate.casefold()- exact = [label for label, body in options.items() if body.casefold() == needle]- return exact[0] if len(exact) == 1 else ""+ needle = _squeezed(candidate)+ exact = [label for label, body in options.items() if _squeezed(body) == needle]+ if len(exact) == 1:+ return exact[0]+ mentioned = _mentioned_labels(candidate, options)+ return mentioned[0] if len(mentioned) == 1 else ""@dataclass(frozen=True, slots=True)@@ -155,11 +232,14 @@ def public_pending_question(pending: PendingQuestion) -> PublicPendingQuestion:__all__ = ["OPTION_PREFIX_RE",+ "canonical_labels","PublicPendingOption","PublicPendingQuestion","format_options","has_option_bodies",+ "option_label_intent","parse_options",+ "positional_label","public_pending_question","resolve_answer","resolve_choice_submission",diff --git a/deeptutor/learning/policy.py b/deeptutor/learning/policy.pyindex 93e8a1702..6fc156a9c 100644--- a/deeptutor/learning/policy.py+++ b/deeptutor/learning/policy.py@@ -50,6 +50,26 @@ QUALITATIVE_TYPES: frozenset[KnowledgeType] = frozenset(_QUALITATIVE_PASS_DISPLAY = 1.0+def path_display_name(progress: LearningProgress) -> str:+ """What to call this path, everywhere it is named.++ A path's own :attr:`~deeptutor.learning.models.LearningProgress.name` wins.+ Without one the first module's name stands in, and failing that the storage+ id — the behaviour every surface implemented separately before this+ function existed, which is why rebuilding a map used to rename the path+ (``mastery_build`` replaces module one) and why three surfaces could+ disagree about the same path.++ Derivation is the fallback, never the record: a named path keeps its name+ across every rebuild.+ """+ named = str(progress.name or "").strip()+ if named:+ return named+ first_module = progress.modules[0].name.strip() if progress.modules else ""+ return first_module or progress.book_id++def gate_threshold(kp_type: KnowledgeType) -> float:"""The quantitative mastery bar for *kp_type* (qualitative types reporttheir pass-display value so callers have a single number to show)."""@@ -273,6 +293,7 @@ def map_summary(progress: LearningProgress, *, now: float | None = None) -> dict})return {+ "name": path_display_name(progress),"counts": counts,"due_reviews": len(due_reviews(progress, now=now)),"complete": counts["total"] > 0 and counts["mastered"] == counts["total"],@@ -361,4 +382,5 @@ __all__ = ["find_knowledge_point","next_objective","map_summary",+ "path_display_name",]diff --git a/deeptutor/learning/service.py b/deeptutor/learning/service.pyindex d8ac93032..8e2c0ae00 100644--- a/deeptutor/learning/service.py+++ b/deeptutor/learning/service.py@@ -24,6 +24,11 @@ if TYPE_CHECKING:from deeptutor.learning.scheduler import SpacedRepetitionScheduler+# Long enough for a course title, short enough that a list row stays a row.+# Matches the cap module and objective names already use.+_MAX_PATH_NAME_LEN = 200++class MasteryInteractionError(RuntimeError):"""Base error for invalid durable question lifecycle transitions."""@@ -601,11 +606,23 @@ class LearningService:modules: list[LearningModule],*,append: bool = False,+ name: str = "",event_type: str = "path.modules_replaced",session_id: str = "",turn_id: str = "",) -> LearningProgress:+ """Install a module set, optionally naming a path that has no name yet.++ ``name`` is applied only when the path is still unnamed, in the same+ transaction as the modules so a built path is never briefly nameless.+ Replacing the map deliberately does NOT rename: the map is what the+ path teaches, the name is which path it is — deriving one from the+ other is what made a rebuild look like a different course.+ """+def replace(tx):+ if name.strip() and not tx.progress.name.strip():+ tx.progress.name = name.strip()[:_MAX_PATH_NAME_LEN]applied_modules = [module.model_copy(deep=True) for module in modules]if append:offset = len(tx.progress.modules)@@ -644,6 +661,26 @@ class LearningService:progress, _ = self._store.mutate(book_id, replace, create=True)return progress+ def rename_path(self, book_id: str, name: str) -> LearningProgress:+ """Set (or clear) the learner-facing name of a path.++ Clearing it is meaningful, not a no-op: an empty name hands the path+ back to the derived display name, which is the only way to undo a+ rename without inventing a second "auto" flag.+ """+ cleaned = str(name or "").strip()[:_MAX_PATH_NAME_LEN]++ def rename(tx):+ if tx.progress.name == cleaned:+ return cleaned+ tx.progress.name = cleaned+ tx.touch()+ tx.emit("path.renamed", {"name": cleaned})+ return cleaned++ progress, _ = self._store.mutate(book_id, rename)+ return progress+def abandon_active_question(self, book_id: str) -> tuple[LearningProgress, bool]:"""Drop the outstanding question so the path can move on.@@ -823,8 +860,7 @@ class LearningService:overviews.append({"path_id": progress.book_id,- "name": (progress.modules[0].name if progress.modules else "")- or progress.book_id,+ "name": policy.path_display_name(progress),"objectives": counts["total"],"mastered": counts["mastered"],"learning": counts["learning"],@@ -840,6 +876,8 @@ class LearningService:def list_progress(self) -> dict:"""Return summary of all book progress with per-book error info."""+ from deeptutor.learning import policy+logger = logging.getLogger(__name__)book_ids = self._store.list_all()@@ -856,14 +894,10 @@ class LearningService:total_mastery = sum(progress.mastery_levels.get(kp_id, 0) for kp_id in current_kp_ids)- # Derive display name from first module, fall back to book_id- display_name = ""- if progress.modules:- display_name = progress.modules[0].name or ""summaries.append({"book_id": progress.book_id,- "name": display_name or progress.book_id,+ "name": policy.path_display_name(progress),"modules_count": len(progress.modules),"kp_count": total_kps,"current_stage": progress.current_stage.valuediff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.pyindex 2f85e9564..6262ff737 100644--- a/deeptutor/learning/tests/test_api_endpoints.py+++ b/deeptutor/learning/tests/test_api_endpoints.py@@ -412,6 +412,54 @@ class TestSkipPendingQuestion:# -- POST /progress/{book_id}/redo ----------------------------------------+class TestRenamePath:+ """Renaming is the learner's edit: the tutor names, the learner decides."""++ def _built_path(self, client, book_id: str) -> None:+ client.post(+ f"/api/v1/learning/progress/{book_id}/init-modules",+ json={"modules": [_module_payload()]},+ )++ def test_rename_replaces_the_derived_name_everywhere(self, client):+ self._built_path(client, "renamed")+ assert client.get("/api/v1/learning/progress/renamed/map").json()["name"] == "M1"++ resp = client.patch(+ "/api/v1/learning/progress/renamed", json={"name": " Linear algebra "}+ )+ assert resp.status_code == 200+ assert resp.json()["name"] == "Linear algebra"++ assert (+ client.get("/api/v1/learning/progress/renamed/map").json()["name"] == "Linear algebra"+ )+ listed = client.get("/api/v1/learning/progress").json()["summaries"]+ assert [p["name"] for p in listed if p["book_id"] == "renamed"] == ["Linear algebra"]++ def test_an_empty_name_restores_the_derived_one(self, client):+ self._built_path(client, "cleared")+ client.patch("/api/v1/learning/progress/cleared", json={"name": "Temporary"})++ resp = client.patch("/api/v1/learning/progress/cleared", json={"name": ""})++ assert resp.status_code == 200+ assert resp.json()["name"] == "M1"++ def test_rename_is_recorded_in_the_activity_feed(self, client):+ self._built_path(client, "audited")+ client.patch("/api/v1/learning/progress/audited", json={"name": "Calculus"})++ events = client.get("/api/v1/learning/progress/audited/events").json()["events"]+ renames = [e for e in events if e["event_type"] == "path.renamed"]+ assert [e["payload"]["name"] for e in renames] == ["Calculus"]++ def test_rename_of_a_missing_path_is_404(self, client):+ assert (+ client.patch("/api/v1/learning/progress/ghost", json={"name": "x"}).status_code == 404+ )++class TestRedoProgress:def test_redo_resets_stage(self, client):client.post(diff --git a/deeptutor/learning/tests/test_mastery_choices.py b/deeptutor/learning/tests/test_mastery_choices.pyindex c4fb0f194..27876dbff 100644--- a/deeptutor/learning/tests/test_mastery_choices.py+++ b/deeptutor/learning/tests/test_mastery_choices.py@@ -10,8 +10,10 @@ from __future__ import annotationsimport pytestfrom deeptutor.capabilities.mastery.choices import (+ canonical_labels,format_options,has_option_bodies,+ option_label_intent,parse_options,recover_options_from_turn,resolve_answer,@@ -51,6 +53,39 @@ def test_parse_options_skips_blank_entries():assert parse_options(["A: keep", " ", ""]) == {"A": "keep"}+def test_parse_options_does_not_mistake_a_formula_for_a_label():+ """``"x - 1 = 0"`` matches the label pattern; it is still not labelled."""+ assert parse_options(["x - 1 = 0", "x - 2 = 0"]) == {+ "A": "x - 1 = 0",+ "B": "x - 2 = 0",+ }+++def test_parse_options_reads_malformed_labels_positionally():+ """Repeated labels keep every body — registration rejects them separately."""+ assert parse_options(["A: first", "A: second"]) == {+ "A": "A: first",+ "B": "A: second",+ }+++# ── option_label_intent ──────────────────────────────────────────────────────+++def test_option_label_intent_reads_labels_that_start_at_a():+ assert option_label_intent(["A: first", "B: second"]) == ["A", "B"]+ assert option_label_intent(["A: first", "A: second", "B: third"]) == ["A", "A", "B"]+++def test_option_label_intent_is_none_for_unlabelled_options():+ assert option_label_intent(["x - 1 = 0", "y - 2 = 0"]) is None+ assert option_label_intent(["first answer", "second answer"]) is None+++def test_canonical_labels_is_the_well_formed_set():+ assert canonical_labels(3) == {"A", "B", "C"}++# ── has_option_bodies ────────────────────────────────────────────────────────@@ -126,6 +161,23 @@ def test_resolve_choice_submission_accepts_label_or_exact_body_only():assert resolve_choice_submission("Step", options) == ""+def test_resolve_choice_submission_reads_a_typed_answer():+ """A learner who types instead of tapping the card still picks an option."""+ options = {"A": "3x² - 3x = 2x + 8", "B": "3x² - x - 8 = 0", "C": "3x² - 5x - 8 = 0"}+ assert resolve_choice_submission("选C", options) == "C"+ assert resolve_choice_submission("答案是 C", options) == "C"+ assert resolve_choice_submission("C。", options) == "C"+ # Spacing differences between the card and the stored body are not a+ # different answer.+ assert resolve_choice_submission("3x²-5x-8=0", options) == "C"+++def test_resolve_choice_submission_refuses_an_ambiguous_answer():+ options = {"A": "Step 2", "B": "Step 6"}+ assert resolve_choice_submission("A or B", options) == ""+ assert resolve_choice_submission("", options) == ""++# ── recover_options_from_turn ────────────────────────────────────────────────diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.pyindex 3ed3e87d1..9ed07e27d 100644--- a/deeptutor/learning/tests/test_mastery_tools.py+++ b/deeptutor/learning/tests/test_mastery_tools.py@@ -65,6 +65,65 @@ async def _build_basic(path_id):)+# ── naming ──────────────────────────────────────────────────────────────────+++async def test_build_names_the_path_and_a_rebuild_keeps_that_name(path_id):+ """A rebuild replaces the map, never the identity.++ Before paths had names, the display name was the first module's — so+ rebuilding renamed the course out from under the learner, and the tutor+ could no longer find "the quadratics path" they asked to switch back to.+ """+ build = MasteryBuildTool()+ first = await build.execute(+ _mastery_path_id=path_id,+ path_name="一元二次方程基础",+ modules=[{"name": "模块一:定义", "knowledge_points": [{"name": "标准形式"}]}],+ )+ assert json.loads(first.content)["path_name"] == "一元二次方程基础"++ rebuilt = await build.execute(+ _mastery_path_id=path_id,+ mode="replace",+ path_name="配方法",+ modules=[{"name": "模块一:配方法", "knowledge_points": [{"name": "配方法解方程"}]}],+ )+ payload = json.loads(rebuilt.content)+ assert payload["path_name"] == "一元二次方程基础"+ assert payload["map"]["modules"][0]["name"] == "模块一:配方法"+ assert LearningStore().load(path_id).name == "一元二次方程基础"+++async def test_build_without_a_name_still_reports_the_derived_one(path_id):+ result = await MasteryBuildTool().execute(+ _mastery_path_id=path_id,+ modules=[{"name": "Module 1", "knowledge_points": [{"name": "Truth tables"}]}],+ )+ assert json.loads(result.content)["path_name"] == "Module 1"+ assert LearningStore().load(path_id).name == ""+++async def test_paths_listing_shows_the_stable_name(path_id):+ """What the tutor matches against when the learner names a path."""+ await MasteryBuildTool().execute(+ _mastery_path_id=path_id,+ path_name="Quadratics",+ modules=[{"name": "Module 1", "knowledge_points": [{"name": "Standard form"}]}],+ )+ await MasteryBuildTool().execute(+ _mastery_path_id=path_id,+ mode="replace",+ modules=[{"name": "Completing the square", "knowledge_points": [{"name": "Method"}]}],+ )++ payload = json.loads((await MasteryPathsTool().execute(_mastery_path_id=path_id)).content)+ assert [p["name"] for p in payload["paths"]] == ["Quadratics"]++# ── build ───────────────────────────────────────────────────────────────────@@ -353,11 +412,12 @@ async def test_explicit_non_choice_rejects_options(path_id, question_type):("options", "error"),[("A: first, B: second", "must be an array"),- (["A: first", "A: second", "B: third"], "labels must be unique"),- (["A: repeated answer", "B: repeated answer"], "bodies must be unique"),- (["A: Repeated answer", "B: repeated answer"], "bodies must be unique"),- (["A: repeated\nanswer", "B: repeated answer"], "bodies must be unique"),- (["A: Straße", "B: STRASSE"], "bodies must be unique"),+ (["A: first", "A: second", "B: third"], "must run A, B, C"),+ (["A: repeated answer", "B: repeated answer"], "same answer"),+ (["A: Repeated answer", "B: repeated answer"], "same answer"),+ (["A: repeated\nanswer", "B: repeated answer"], "same answer"),+ (["A: Straße", "B: STRASSE"], "same answer"),+ (["A: first", "B: second", "C: first"], "same answer"),(["A: first", ""], "non-empty strings"),],)@@ -399,6 +459,57 @@ async def test_choice_quiz_requires_options_even_when_type_is_explicit(path_id):assert "full option bodies" in result.content+async def test_choice_grade_reads_an_answer_typed_in_the_composer(path_id):+ """The card is not the only way in: a typed answer must grade the same."""+ await _build_basic(path_id)+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Which is the general form?",+ expected_answer="C",+ question_type="choice",+ options=[+ "A: 3x² - 3x = 2x + 8",+ "B: 3x² - x - 8 = 0",+ "C: 3x² - 5x - 8 = 0",+ "D: 3x² - 5x + 8 = 0",+ ],+ )++ grade = await MasteryGradeTool().execute(_mastery_path_id=path_id, answer="选C")+ assert grade.success is True+ assert json.loads(grade.content)["is_correct"] is True+++async def test_choice_grade_refuses_an_unreadable_answer_instead_of_failing_it(path_id):+ """An answer we cannot map to one option is unreadable, not wrong."""+ await _build_basic(path_id)+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Which is the general form?",+ expected_answer="A",+ question_type="choice",+ options=["A: 3x² - 5x - 8 = 0", "B: 3x² - 5x + 8 = 0"],+ )++ grade = await MasteryGradeTool().execute(_mastery_path_id=path_id, answer="A or B")+ assert grade.success is False+ assert "NOT graded" in grade.content+ # Nothing was recorded, so the question is still open for a real answer.+ progress = LearningStore().load(path_id)+ assert progress.pending_question is not None+ assert progress.quiz_attempts == []++@pytest.mark.asyncioasync def test_choice_quiz_preserves_bodies_and_normalizes_answer(path_id, session_store):session = await session_store.create_session(title="Choice Mastery")diff --git a/deeptutor/learning/tests/test_policy.py b/deeptutor/learning/tests/test_policy.pyindex 506202bda..1267dd240 100644--- a/deeptutor/learning/tests/test_policy.py+++ b/deeptutor/learning/tests/test_policy.py@@ -295,3 +295,35 @@ def test_objective_report_carries_qualitative_evidence():def test_objective_report_is_none_for_an_unknown_objective():assert policy.objective_report(_progress(_kp("kp1", KnowledgeType.MEMORY)), "nope") is None+++# ── path_display_name ──────────────────────────────────────────────────────+++def test_path_display_name_prefers_the_paths_own_name():+ progress = _progress(_kp("kp1", KnowledgeType.MEMORY))+ progress.name = "一元二次方程基础"+ assert policy.path_display_name(progress) == "一元二次方程基础"+++def test_path_display_name_falls_back_to_the_first_module():+ """How every unnamed path was named before paths had names."""+ progress = _progress(_kp("kp1", KnowledgeType.MEMORY))+ assert policy.path_display_name(progress) == "M1"+++def test_path_display_name_falls_back_to_the_id_with_no_modules():+ assert policy.path_display_name(LearningProgress(book_id="b1")) == "b1"+++def test_path_display_name_ignores_a_blank_name():+ progress = _progress(_kp("kp1", KnowledgeType.MEMORY))+ progress.name = " "+ assert policy.path_display_name(progress) == "M1"+++def test_map_summary_carries_the_display_name():+ """So the dashboard and the composer strip read it instead of deriving it."""+ progress = _progress(_kp("kp1", KnowledgeType.MEMORY))+ progress.name = "Quadratics"+ assert policy.map_summary(progress)["name"] == "Quadratics"diff --git a/deeptutor/multi_user/grants.py b/deeptutor/multi_user/grants.pyindex 9846f77db..f859fee0e 100644--- a/deeptutor/multi_user/grants.py+++ b/deeptutor/multi_user/grants.py@@ -20,10 +20,11 @@ def empty_grant(user_id: str) -> dict[str, Any]:"models": {"llm": []},"knowledge_bases": [],"skills": [],- # Partners an admin has assigned to this user. Partners stay- # admin-managed (the /api/v1/partners CRUD router is admin-gated); a- # grant only lets the user *see and consult* the named partners — same- # shape as ``skills`` (``[{"partner_id": ...}]``).+ # Partners an admin has lent this user. People build their own partners+ # now, so a grant is only about someone *else's*: it lets the user talk+ # to the named partners — never configure them — and their side of each+ # conversation stays private to their account. Same shape as ``skills``+ # (``[{"partner_id": ...}]``)."partners": [],# Tool whitelists share the partner-config semantics for built-ins:# ``enabled_tools=None`` means "default" (every tool in the pool),diff --git a/deeptutor/multi_user/partner_access.py b/deeptutor/multi_user/partner_access.pyindex c74beb8d8..7966c0cae 100644--- a/deeptutor/multi_user/partner_access.py+++ b/deeptutor/multi_user/partner_access.py@@ -1,16 +1,24 @@-"""Partner visibility guards for non-admin users.--Partners are admin-managed, process-wide resources: the whole-``/api/v1/partners`` CRUD router is admin-gated, and a partner runs in its own-isolated workspace scope (``data/partners/{id}/``), never the caller's. A-non-admin can't create or manage partners, but an admin can *assign* specific-partners to specific users through the grant system — the same mechanism that-shares knowledge bases and skills.--An assigned user may then see the partner, connect it as a subagent, and-consult it in chat; the consult still drives the partner in its own scope, so-the user only ever exchanges messages with it — exactly as when an admin-consults it. This module is the read-side counterpart of ``skill_access``.+"""Who may see, use, and manage a Partner.++Three roles matter, and they nest:++* **Manage** — the human who created the partner (its ``owner_id``), plus any+ admin. Managing means the whole configuration surface: soul, channels,+ assets, models, lifecycle, deletion.+* **Use** — everyone who may manage it, plus any user an admin has *assigned*+ it to through the grant system (the same mechanism that shares knowledge+ bases and skills). Using means holding a conversation with it.+* **Neither** — the partner does not exist as far as that user is concerned.++A partner always runs in its own isolated workspace scope+(``data/partners/{id}/``), never the caller's, so "use" only ever exchanges+messages. Conversations, however, follow the human: each user's history and+learned preferences live under their own account+(:mod:`deeptutor.services.partners.interaction`), so two people talking to the+same partner never see each other's threads.++This module is the single source of truth for those three answers; routes and+backends ask it rather than re-deriving the rule."""from __future__ import annotations@@ -21,6 +29,24 @@ from fastapi import HTTPExceptionfrom .context import get_current_userfrom .grants import load_grant+from .models import CurrentUser+++def _manager() -> Any:+ # Imported lazily: the partner service pulls in the whole runtime stack,+ # which imports this module back.+ from deeptutor.services.partners import get_partner_manager++ return get_partner_manager()+++def partner_owner_id(partner_id: str) -> str:+ """The account that owns *partner_id*, or ``""`` when it is admin-managed.++ Partners created before ownership existed have no ``owner_id``; they read+ as admin-managed, which is exactly what they were.+ """+ return _manager().owner_id(partner_id)def assigned_partner_ids(user_id: str | None = None) -> set[str]:@@ -34,22 +60,50 @@ def assigned_partner_ids(user_id: str | None = None) -> set[str]:}+def can_manage_partner(partner_id: str, user: CurrentUser | None = None) -> bool:+ """Whether the user may configure *partner_id* — its owner, or any admin."""+ actor = user or get_current_user()+ if actor.is_admin:+ return True+ owner = partner_owner_id(partner_id)+ return bool(owner) and owner == actor.id+++def can_use_partner(partner_id: str, user: CurrentUser | None = None) -> bool:+ """Whether the user may talk to *partner_id* — manage it, or be assigned it."""+ actor = user or get_current_user()+ if can_manage_partner(partner_id, actor):+ return True+ return str(partner_id or "").strip() in assigned_partner_ids(actor.id)++def assert_partner_allowed(partner_id: str, user_id: str | None = None) -> None:- """Raise 403 when a non-admin tries to use a partner not assigned to them.+ """Raise 403 unless the current user may talk to *partner_id*.- Admins may use any partner; this is a no-op for them (and for single-user- deployments, where the current user resolves to the local admin).+ A no-op for admins, for the partner's owner, and for single-user+ deployments (where the current user resolves to the local admin)."""user = get_current_user()- if user.is_admin:+ if can_manage_partner(partner_id, user):+ return+ if str(partner_id or "").strip() in assigned_partner_ids(user_id or user.id):return- if str(partner_id or "").strip() not in assigned_partner_ids(user_id or user.id):- raise HTTPException(status_code=403, detail="Partner is not assigned to you")+ raise HTTPException(status_code=403, detail="Partner is not assigned to you")+++def assert_partner_manageable(partner_id: str) -> None:+ """Raise 403 unless the current user may configure *partner_id*.++ Deliberately the same 403 an unassigned partner gets: someone who may only+ talk to a partner learns nothing new about who owns it.+ """+ if not can_manage_partner(partner_id):+ raise HTTPException(status_code=403, detail="You cannot manage this partner")# Identity-only card fields a consumer needs (partner list page, connect modal).-# Deliberately excludes channels / llm_selection / tool config so a non-admin-# only ever sees a partner's face, never its wiring.+# Deliberately excludes channels / llm_selection / tool config so a user who was+# merely *assigned* a partner sees its face, never its wiring._CARD_FIELDS = ("partner_id","name",@@ -62,22 +116,39 @@ _CARD_FIELDS = ()-def _project_card(partner: dict[str, Any]) -> dict[str, Any]:+def identity_card(partner: dict[str, Any]) -> dict[str, Any]:+ """Reduce a partner dict to the fields a non-owner may see."""card = {field: partner.get(field) for field in _CARD_FIELDS}card["partner_id"] = str(partner.get("partner_id") or "")+ card["can_manage"] = Falsereturn card-def visible_partner_cards() -> list[dict[str, Any]]:- """Partners the current user may consult: all for an admin, or just the- assigned subset for a non-admin. Returns identity-only card dicts."""- from deeptutor.services.partners import get_partner_manager+def visible_partners() -> list[dict[str, Any]]:+ """Every partner the current user may talk to, projected by what they may do.- everything = get_partner_manager().list_partners()+ Partners they manage come through whole (the list page renders channel+ badges and drills into configuration); partners merely assigned to them are+ reduced to an identity card. ``can_manage`` tells the client which is which+ so it doesn't have to re-derive ownership.+ """user = get_current_user()- if user.is_admin:- return [_project_card(item) for item in everything]- allowed = assigned_partner_ids(user.id)+ out: list[dict[str, Any]] = []+ for partner in _manager().list_partners():+ pid = str(partner.get("partner_id") or "")+ if can_manage_partner(pid, user):+ out.append({**partner, "can_manage": True})+ elif can_use_partner(pid, user):+ out.append(identity_card(partner))+ return out+++def visible_partner_cards() -> list[dict[str, Any]]:+ """Identity-only cards for every partner the current user may talk to.++ The read surface behind the connect flow, where the wiring is never needed.+ """return [- _project_card(item) for item in everything if str(item.get("partner_id") or "") in allowed+ identity_card(partner) | {"can_manage": bool(partner.get("can_manage"))}+ for partner in visible_partners()]diff --git a/deeptutor/multi_user/router.py b/deeptutor/multi_user/router.pyindex e832d1c9e..e3142ae47 100644--- a/deeptutor/multi_user/router.py+++ b/deeptutor/multi_user/router.py@@ -14,6 +14,7 @@ from deeptutor.services.config.model_catalog import ModelCatalogServicefrom deeptutor.services.skill.service import SkillServicefrom .audit import log_admin_action+from .context import get_current_userfrom .grants import load_grant, save_grantfrom .identity import get_user_by_id, list_user_infofrom .knowledge_access import admin_kb_base_dir@@ -86,11 +87,17 @@ def _admin_skill_summary() -> list[dict[str, Any]]:def _admin_partner_summary() -> list[dict[str, Any]]:- """The partners an admin can assign. Partners are process-wide resources- anchored at the admin workspace, so this lists them all (identity only — no- channel wiring or model selection leaks into the assignable summary)."""+ """The partners an admin can hand to someone else.++ Admin-managed partners only — the ones with no owner, or that the admin+ created. A partner someone built for themselves is theirs to share or not;+ listing it here would let an admin lend out a private companion (and its+ soul, which people write personally) by a single click. Identity only: no+ channel wiring or model selection leaks into the assignable summary.+ """from deeptutor.services.partners import get_partner_manager+ admin_id = get_current_user().idreturn [{"partner_id": str(item.get("partner_id") or ""),@@ -99,6 +106,7 @@ def _admin_partner_summary() -> list[dict[str, Any]]:"emoji": item.get("emoji") or "",}for item in get_partner_manager().list_partners()+ if str(item.get("owner_id") or "") in ("", admin_id)]diff --git a/deeptutor/partners/channels/base.py b/deeptutor/partners/channels/base.pyindex 14008b957..1f45871fc 100644--- a/deeptutor/partners/channels/base.py+++ b/deeptutor/partners/channels/base.py@@ -3,12 +3,31 @@from __future__ import annotationsfrom abc import ABC, abstractmethod+from contextlib import contextmanager+from contextvars import ContextVarfrom pathlib import Pathfrom typing import Anyfrom deeptutor.partners.bus.events import InboundMessage, OutboundMessagefrom deeptutor.partners.bus.queue import MessageBus+#: Owning Partner of the channel currently being constructed. Channels that+#: resolve paths in ``__init__`` need the id *then*, but ``ChannelManager``+#: builds the instance before it can assign an attribute — and threading the+#: id through every subclass signature would break external plugins, which+#: are constructed the same way.+_constructing_for: ContextVar[str] = ContextVar("partner_channel_owner", default="")+++@contextmanager+def constructing_for(partner_id: str):+ """Mark whose channel is being built, so ``__init__`` can resolve paths."""+ token = _constructing_for.set(str(partner_id or ""))+ try:+ yield+ finally:+ _constructing_for.reset(token)+def _logger():from loguru import logger as _log@@ -44,6 +63,7 @@ class BaseChannel(ABC):self.config = configself.bus = busself._running = False+ self.partner_id = _constructing_for.get()def media_dir(self, channel: str | None = None) -> Path:"""Download directory isolated to this channel's owning Partner."""@@ -55,6 +75,21 @@ class BaseChannel(ABC):# the legacy location in that standalone case.return get_media_dir(channel or self.name)+ def state_dir(self) -> Path:+ """Runtime state directory isolated to this channel's owning Partner.++ Channel state is an *account identity* (bot tokens, poll cursors), so+ it must never be shared: two Partners on the same channel would read+ each other's credentials and overwrite each other's cursor. Resolve+ lazily — ``PartnerManager`` sets ``partner_id`` after construction.+ """+ from deeptutor.partners.config.paths import get_partner_channel_dir, get_runtime_subdir++ if self.partner_id:+ return get_partner_channel_dir(self.partner_id, self.name)+ # Standalone construction (plugins/tests): keep the legacy location.+ return get_runtime_subdir(self.name)+async def transcribe_audio(self, file_path: str | Path) -> str:"""Transcribe an audio file via Groq Whisper. Returns empty string on failure."""if not self.transcription_api_key:diff --git a/deeptutor/partners/channels/manager.py b/deeptutor/partners/channels/manager.pyindex 2d256c50e..e4a6bec9a 100644--- a/deeptutor/partners/channels/manager.py+++ b/deeptutor/partners/channels/manager.py@@ -9,7 +9,7 @@ from typing import Anyfrom deeptutor.partners.bus.events import OutboundMessagefrom deeptutor.partners.bus.queue import MessageBus-from deeptutor.partners.channels.base import BaseChannel+from deeptutor.partners.channels.base import BaseChannel, constructing_forfrom deeptutor.partners.config.schema import ChannelsConfig@@ -72,7 +72,8 @@ class ChannelManager:if not enabled:continuetry:- channel = cls(section, self.bus)+ with constructing_for(self._partner_id):+ channel = cls(section, self.bus)channel.partner_id = self._partner_idchannel.transcription_api_key = self._groq_api_key# Effective delivery flags are per-channel only. Historicaldiff --git a/deeptutor/partners/channels/matrix.py b/deeptutor/partners/channels/matrix.pyindex 4c3eb79fe..b1db432d5 100644--- a/deeptutor/partners/channels/matrix.py+++ b/deeptutor/partners/channels/matrix.py@@ -47,7 +47,6 @@ else:from deeptutor.partners.bus.events import OutboundMessagefrom deeptutor.partners.bus.queue import MessageBusfrom deeptutor.partners.channels.base import BaseChannel-from deeptutor.partners.config.paths import get_data_dirfrom deeptutor.partners.config.schema import DeliveryOverridesfrom deeptutor.partners.helpers import safe_filename@@ -244,7 +243,7 @@ class MatrixChannel(BaseChannel):"sure libolm is available on your system.")- store_path = get_data_dir() / "matrix-store"+ store_path = self.state_dir()store_path.mkdir(parents=True, exist_ok=True)self.client = AsyncClient(diff --git a/deeptutor/partners/channels/mochat.py b/deeptutor/partners/channels/mochat.pyindex 8e93dc363..aea048168 100644--- a/deeptutor/partners/channels/mochat.py+++ b/deeptutor/partners/channels/mochat.py@@ -16,7 +16,6 @@ from pydantic import Fieldfrom deeptutor.partners.bus.events import OutboundMessagefrom deeptutor.partners.bus.queue import MessageBusfrom deeptutor.partners.channels.base import BaseChannel-from deeptutor.partners.config.paths import get_runtime_subdirfrom deeptutor.partners.config.schema import Base, DeliveryOverridestry:@@ -293,7 +292,7 @@ class MochatChannel(BaseChannel):self._socket: Any = Noneself._ws_connected = self._ws_ready = False- self._state_dir = get_runtime_subdir("mochat")+ self._state_dir = self.state_dir()self._cursor_path = self._state_dir / "session_cursors.json"self._session_cursor: dict[str, int] = {}self._cursor_save_task: asyncio.Task | None = Nonediff --git a/deeptutor/partners/channels/msteams.py b/deeptutor/partners/channels/msteams.pyindex 4f7a28ce4..4aeb6d67d 100644--- a/deeptutor/partners/channels/msteams.py+++ b/deeptutor/partners/channels/msteams.py@@ -38,7 +38,6 @@ from pydantic import Fieldfrom deeptutor.partners.bus.events import OutboundMessagefrom deeptutor.partners.bus.queue import MessageBusfrom deeptutor.partners.channels.base import BaseChannel-from deeptutor.partners.config.paths import get_runtime_subdirfrom deeptutor.partners.config.schema import DeliveryOverridesMSTEAMS_AVAILABLE = (@@ -133,7 +132,7 @@ class MSTeamsChannel(BaseChannel):self._botframework_openid_config_expires_at: float = 0.0self._botframework_jwks: dict[str, Any] | None = Noneself._botframework_jwks_expires_at: float = 0.0- state_dir = get_runtime_subdir("msteams")+ state_dir = self.state_dir()self._refs_path = state_dir / MSTEAMS_REF_FILENAMEself._refs_meta_path = state_dir / MSTEAMS_REF_META_FILENAMEself._refs_lock_path = state_dir / MSTEAMS_REF_LOCK_FILENAMEdiff --git a/deeptutor/partners/channels/registry.py b/deeptutor/partners/channels/registry.pyindex 96a5e1305..25f457a8e 100644--- a/deeptutor/partners/channels/registry.py+++ b/deeptutor/partners/channels/registry.py@@ -14,6 +14,16 @@ if TYPE_CHECKING:_INTERNAL = frozenset({"base", "manager", "registry"})+class NotAChannelModule(Exception):+ """The module imported fine but defines no channel.++ Distinct from :class:`ImportError` on purpose. A channel whose *import*+ fails is a real channel with a missing optional dependency, and the UI+ should say so; a module with no channel in it is a helper (e.g. a shared+ protocol implementation) that was never meant to appear as one.+ """++def discover_channel_names() -> list[str]:"""Return all built-in channel module names by scanning the package (zero imports)."""import deeptutor.partners.channels as pkg@@ -34,7 +44,7 @@ def load_channel_class(module_name: str) -> type[BaseChannel]:obj = getattr(mod, attr)if isinstance(obj, type) and issubclass(obj, _Base) and obj is not _Base:return obj- raise ImportError(f"No BaseChannel subclass in deeptutor.partners.channels.{module_name}")+ raise NotAChannelModule(f"deeptutor.partners.channels.{module_name} defines no channel")def discover_plugins() -> dict[str, type[BaseChannel]]:@@ -73,6 +83,8 @@ def discover_all_with_errors() -> tuple[dict[str, type[BaseChannel]], dict[str,for modname in discover_channel_names():try:builtin[modname] = load_channel_class(modname)+ except NotAChannelModule:+ continue # A helper module, not a channel — never surface it.except ImportError as e:errors[modname] = str(e)logger.debug("Skipping built-in channel '{}': {}", modname, e)diff --git a/deeptutor/partners/channels/weixin.py b/deeptutor/partners/channels/weixin.pyindex 0502c6d90..42c5e7777 100644--- a/deeptutor/partners/channels/weixin.py+++ b/deeptutor/partners/channels/weixin.py@@ -31,7 +31,12 @@ from pydantic import Fieldfrom deeptutor.partners.bus.events import OutboundMessagefrom deeptutor.partners.bus.queue import MessageBusfrom deeptutor.partners.channels.base import BaseChannel-from deeptutor.partners.config.paths import get_runtime_subdir+from deeptutor.partners.channels.weixin_qr import (+ ILINK_APP_ID,+ fetch_qr_code,+ interpret_status,+ is_retryable_poll_error,+)from deeptutor.partners.config.schema import DeliveryOverridesfrom deeptutor.partners.helpers import safe_filename, split_message@@ -54,7 +59,6 @@ MESSAGE_STATE_FINISH = 2WEIXIN_MAX_MESSAGE_LEN = 4000WEIXIN_CHANNEL_VERSION = "2.1.1"-ILINK_APP_ID = "bot"def _build_client_version(version: str) -> int:@@ -131,7 +135,7 @@ class WeixinConfig(DeliveryOverrides):cdn_base_url: str = "https://novac2c.cdn.weixin.qq.com/c2c"route_tag: str | int | None = Nonetoken: str = "" # Manually set token, or obtained via QR login- state_dir: str = "" # Default: data/partners/weixin/+ state_dir: str = "" # Default: data/partners/{partner_id}/channels/weixin/poll_timeout: int = DEFAULT_LONG_POLL_TIMEOUT_S # seconds for long-poll@@ -183,19 +187,30 @@ class WeixinChannel(BaseChannel):if self.config.state_dir:d = Path(self.config.state_dir).expanduser()else:- d = get_runtime_subdir("weixin")+ d = self.state_dir()d.mkdir(parents=True, exist_ok=True)self._state_dir = dreturn ddef _load_state(self) -> bool:- """Load saved account state. Returns True if a valid token was found."""+ """Restore this partner's saved session. Returns True if a token was found.++ Identity (the bot token and the host it belongs to) comes from the+ channel config whenever that is set — the web QR onboarding writes it+ there, and an operator editing the config expects to win. The saved+ file is the fallback for a login that only ever landed here, and is+ always the source for *session* continuity: the long-poll cursor and+ the per-user context tokens, without which a restart re-reads whatever+ backlog the server still holds and cannot reply until each user speaks+ again.+ """state_file = self._get_state_dir() / "account.json"if not state_file.exists():return Falsetry:data = json.loads(state_file.read_text())- self._token = data.get("token", "")+ if not self.config.token:+ self._token = data.get("token", "")self._get_updates_buf = data.get("get_updates_buf", "")context_tokens = data.get("context_tokens", {})if isinstance(context_tokens, dict):@@ -216,7 +231,7 @@ class WeixinChannel(BaseChannel):else:self._typing_tickets = {}base_url = data.get("base_url", "")- if base_url:+ if base_url and not self.config.token:self.config.base_url = base_urlreturn bool(self._token)except Exception:@@ -331,16 +346,14 @@ class WeixinChannel(BaseChannel):async def _fetch_qr_code(self) -> tuple[str, str]:"""Fetch a fresh QR code. Returns (qrcode_id, scan_url)."""- data = await self._api_get(- "ilink/bot/get_bot_qrcode",- params={"bot_type": "3"},- auth=False,+ assert self._client is not None+ code = await fetch_qr_code(+ self._client,+ self.config.base_url,+ client_version=ILINK_APP_CLIENT_VERSION,+ route_tag=str(self.config.route_tag or ""),)- qrcode_img_content = data.get("qrcode_img_content", "")- qrcode_id = data.get("qrcode", "")- if not qrcode_id:- raise RuntimeError(f"Failed to get QR code from WeChat API: {data}")- return qrcode_id, (qrcode_img_content or qrcode_id)+ return code.qrcode_id, code.scan_payloadasync def _qr_login(self) -> bool:"""Perform QR code login flow. Returns True on success."""@@ -364,42 +377,25 @@ class WeixinChannel(BaseChannel):continueraise- if not isinstance(status_data, dict):- await asyncio.sleep(1)- continue-- status = status_data.get("status", "")- if status == "confirmed":- token = status_data.get("bot_token", "")- bot_id = status_data.get("ilink_bot_id", "")- base_url = status_data.get("baseurl", "")- user_id = status_data.get("ilink_user_id", "")- if token:- self._token = token- if base_url:- self.config.base_url = base_url- self._save_state()- self.logger.info(- "login successful! bot_id={} user_id={}",- bot_id,- user_id,- )- return True- else:- self.logger.error("Login confirmed but no bot_token in response")- return False- elif status == "scaned_but_redirect":- redirect_host = str(status_data.get("redirect_host", "") or "").strip()- if redirect_host:- if redirect_host.startswith("http://") or redirect_host.startswith(- "https://"- ):- redirected_base = redirect_host- else:- redirected_base = f"https://{redirect_host}"- if redirected_base != current_poll_base_url:- current_poll_base_url = redirected_base- elif status == "expired":+ outcome = interpret_status(status_data)+ if outcome.status == "confirmed":+ self._token = outcome.token+ if outcome.base_url:+ self.config.base_url = outcome.base_url+ self._save_state()+ self.logger.info(+ "login successful! bot_id={} user_id={}",+ outcome.bot_id,+ outcome.user_id,+ )+ return True+ elif outcome.status == "error":+ self.logger.error("Login confirmed but no bot_token in response")+ return False+ elif outcome.status == "scanned":+ if outcome.poll_base_url and outcome.poll_base_url != current_poll_base_url:+ current_poll_base_url = outcome.poll_base_url+ elif outcome.status == "expired":refresh_count += 1if refresh_count > MAX_QR_REFRESH_COUNT:self.logger.warning(@@ -421,15 +417,7 @@ class WeixinChannel(BaseChannel):return False- @staticmethod- def _is_retryable_qr_poll_error(err: Exception) -> bool:- if isinstance(err, httpx.TimeoutException | httpx.TransportError):- return True- if isinstance(err, httpx.HTTPStatusError):- status_code = err.response.status_code if err.response is not None else 0- if status_code >= 500:- return True- return False+ _is_retryable_qr_poll_error = staticmethod(is_retryable_poll_error)@staticmethoddef _print_qr_code(url: str) -> None:@@ -482,7 +470,8 @@ class WeixinChannel(BaseChannel):if self.config.token:self._token = self.config.token- elif not self._load_state():+ self._load_state()+ if not self._token:if not await self._qr_login():self.logger.error("login failed. open the Weixin channel and scan the QR code to authenticate."diff --git a/deeptutor/partners/channels/weixin_qr.py b/deeptutor/partners/channels/weixin_qr.pynew file mode 100644index 000000000..a276da854--- /dev/null+++ b/deeptutor/partners/channels/weixin_qr.py@@ -0,0 +1,202 @@+"""The personal-WeChat QR login exchange, with no channel attached.++The protocol itself already worked — :class:`WeixinChannel` has run it since the+channel landed — but it only ever ran from ``start()``, and the code it produces+was printed to the server's stdout. On any real deployment that is a supervisord+log file the person configuring the partner cannot see, so the channel's own+advice ("scan the QR code to authenticate") had nowhere to be followed (#951).++Lifting the exchange out of the channel is what lets the web app run it too:+same three calls, same status vocabulary, one implementation. Everything here is+stateless — the caller owns the HTTP client and whatever it does with the token.++The exchange is: ask for a code, then poll it until WeChat says what happened.+``interpret_status`` is the whole decision, in one testable place, because the+raw payload has five outcomes and two of them (an expiry that should be retried,+a redirect that changes the host you must poll next) are easy to mistake for+failure.+"""++from __future__ import annotations++import base64+from dataclasses import dataclass+import os+from typing import Any, Literal++import httpx++ILINK_APP_ID = "bot"++# Personal-WeChat bots are ``bot_type=3`` in the iLink API.+BOT_TYPE_PERSONAL = "3"++QR_ENDPOINT = "ilink/bot/get_bot_qrcode"+QR_STATUS_ENDPOINT = "ilink/bot/get_qrcode_status"++QrStatus = Literal["waiting", "scanned", "confirmed", "expired", "error", "unknown"]+++@dataclass(frozen=True, slots=True)+class QrCode:+ """A freshly issued login code: the id to poll, and what to render."""++ qrcode_id: str+ #: What the phone must scan. The API calls it ``qrcode_img_content``; it+ #: falls back to the id itself, which is what the channel has always drawn.+ scan_payload: str+++@dataclass(frozen=True, slots=True)+class QrOutcome:+ """What one poll of a login code means.++ ``base_url`` (on confirmation) and ``poll_base_url`` (on redirect) are+ separate on purpose: WeChat can move a *pending* login to another host+ mid-flight, and can also hand back a different host to use for the session+ once it succeeds. Collapsing them loses one or the other.+ """++ status: QrStatus+ token: str = ""+ base_url: str = ""+ poll_base_url: str = ""+ bot_id: str = ""+ user_id: str = ""+++def _random_wechat_uin() -> str:+ """``X-WECHAT-UIN``: random uint32 → decimal string → base64, per request."""+ uint32 = int.from_bytes(os.urandom(4), "big")+ return base64.b64encode(str(uint32).encode()).decode()+++def qr_headers(*, client_version: int, route_tag: str = "") -> dict[str, str]:+ """Headers for the unauthenticated half of the exchange.++ No ``Authorization``: obtaining the token is the point of these calls.+ """+ headers = {+ "X-WECHAT-UIN": _random_wechat_uin(),+ "Content-Type": "application/json",+ "AuthorizationType": "ilink_bot_token",+ "iLink-App-Id": ILINK_APP_ID,+ "iLink-App-ClientVersion": str(client_version),+ }+ if route_tag.strip():+ headers["SKRouteTag"] = route_tag.strip()+ return headers+++def normalize_host(value: str) -> str:+ """A redirect host as an absolute base URL (WeChat may omit the scheme)."""+ host = str(value or "").strip()+ if not host:+ return ""+ if host.startswith(("http://", "https://")):+ return host+ return f"https://{host}"+++def interpret_status(payload: Any) -> QrOutcome:+ """Read one ``get_qrcode_status`` body.++ Two non-obvious outcomes, kept apart because callers must act differently:++ * a confirmation carrying no token is ``error`` — the login is over and+ failed. Trusting ``status`` alone would store an empty token and fail+ later, far from the cause.+ * a status this function does not recognise is ``unknown``, which means+ "keep polling". A future status string must not end a working login.+ """+ if not isinstance(payload, dict):+ return QrOutcome(status="unknown")++ status = str(payload.get("status") or "")+ if status == "confirmed":+ token = str(payload.get("bot_token") or "")+ if not token:+ return QrOutcome(status="error")+ return QrOutcome(+ status="confirmed",+ token=token,+ base_url=str(payload.get("baseurl") or ""),+ bot_id=str(payload.get("ilink_bot_id") or ""),+ user_id=str(payload.get("ilink_user_id") or ""),+ )+ if status == "scaned_but_redirect":+ # Scanned, but the login moved hosts: keep waiting, poll elsewhere.+ return QrOutcome(+ status="scanned",+ poll_base_url=normalize_host(str(payload.get("redirect_host") or "")),+ )+ if status == "expired":+ return QrOutcome(status="expired")+ if status == "wait":+ return QrOutcome(status="waiting")+ return QrOutcome(status="unknown")+++async def fetch_qr_code(+ client: httpx.AsyncClient,+ base_url: str,+ *,+ client_version: int,+ route_tag: str = "",+) -> QrCode:+ """Ask WeChat for a login code to display."""+ response = await client.get(+ f"{base_url.rstrip('/')}/{QR_ENDPOINT}",+ params={"bot_type": BOT_TYPE_PERSONAL},+ headers=qr_headers(client_version=client_version, route_tag=route_tag),+ )+ response.raise_for_status()+ data = response.json()+ qrcode_id = str((data or {}).get("qrcode") or "") if isinstance(data, dict) else ""+ if not qrcode_id:+ raise RuntimeError(f"WeChat did not return a QR code: {data}")+ content = str(data.get("qrcode_img_content") or "")+ return QrCode(qrcode_id=qrcode_id, scan_payload=content or qrcode_id)+++async def poll_qr_code(+ client: httpx.AsyncClient,+ base_url: str,+ qrcode_id: str,+ *,+ client_version: int,+ route_tag: str = "",+) -> QrOutcome:+ """Poll a login code once and say what it means."""+ response = await client.get(+ f"{base_url.rstrip('/')}/{QR_STATUS_ENDPOINT}",+ params={"qrcode": qrcode_id},+ headers=qr_headers(client_version=client_version, route_tag=route_tag),+ )+ response.raise_for_status()+ return interpret_status(response.json())+++def is_retryable_poll_error(err: Exception) -> bool:+ """Transport hiccups and 5xx are worth another poll; 4xx are not."""+ if isinstance(err, httpx.TimeoutException | httpx.TransportError):+ return True+ if isinstance(err, httpx.HTTPStatusError):+ status_code = err.response.status_code if err.response is not None else 0+ return status_code >= 500+ return False+++__all__ = [+ "BOT_TYPE_PERSONAL",+ "ILINK_APP_ID",+ "QrCode",+ "QrOutcome",+ "QrStatus",+ "fetch_qr_code",+ "interpret_status",+ "is_retryable_poll_error",+ "normalize_host",+ "poll_qr_code",+ "qr_headers",+]diff --git a/deeptutor/partners/config/__init__.py b/deeptutor/partners/config/__init__.pyindex 4848444b1..5410f1229 100644--- a/deeptutor/partners/config/__init__.py+++ b/deeptutor/partners/config/__init__.py@@ -3,6 +3,7 @@from deeptutor.partners.config.paths import (get_data_dir,get_media_dir,+ get_partner_channel_dir,get_partner_dir,get_partner_media_dir,get_partner_sessions_dir,@@ -16,6 +17,7 @@ __all__ = ["ChannelsConfig","get_data_dir","get_media_dir",+ "get_partner_channel_dir","get_partner_dir","get_partner_media_dir","get_partner_sessions_dir",diff --git a/deeptutor/partners/config/paths.py b/deeptutor/partners/config/paths.pyindex 7c74f790e..90e742c8d 100644--- a/deeptutor/partners/config/paths.py+++ b/deeptutor/partners/config/paths.py@@ -54,6 +54,15 @@ def get_partner_media_dir(partner_id: str, channel: str | None = None) -> Path:return ensure_dir(base / channel) if channel else base+def get_partner_channel_dir(partner_id: str, channel: str) -> Path:+ """Private runtime state for one channel of one partner.++ Nested under ``channels/`` so a channel name can never collide with the+ partner dir's own entries (``workspace``, ``sessions``, ``users``, ...).+ """+ return ensure_dir(get_partner_dir(partner_id) / "channels" / channel)++_ACCOUNT_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")diff --git a/deeptutor/services/config/context_window_detection.py b/deeptutor/services/config/context_window_detection.pyindex 4f55d6c85..a54a1d007 100644--- a/deeptutor/services/config/context_window_detection.py+++ b/deeptutor/services/config/context_window_detection.py@@ -10,6 +10,7 @@ from typing import Anyimport aiohttp+from deeptutor.services.keypool import primary_api_keyfrom deeptutor.services.llm.config import LLMConfigfrom deeptutor.services.llm.context_window import (coerce_positive_int,@@ -151,7 +152,7 @@ async def _detect_from_models_endpoint(return Noneurl = f"{base_url.rstrip('/')}/models"- headers = build_auth_headers(llm_config.api_key, llm_config.binding)+ headers = build_auth_headers(primary_api_key(llm_config.api_key), llm_config.binding)headers.pop("Content-Type", None)timeout = aiohttp.ClientTimeout(total=12)diff --git a/deeptutor/services/embedding/adapters/gemini.py b/deeptutor/services/embedding/adapters/gemini.pyindex 52416a1ed..06499c194 100644--- a/deeptutor/services/embedding/adapters/gemini.py+++ b/deeptutor/services/embedding/adapters/gemini.py@@ -30,18 +30,25 @@ class GeminiEmbeddingAdapter(OpenAICompatibleEmbeddingAdapter):SUPPORTS_INPUT_TYPE = True+ # ``multimodal`` states what the model maps into its embedding space, and+ # is the single place that decides it: ``get_model_info`` reports it to+ # Settings, and ``_embed_native`` refuses ``contents`` for a model that+ # says False rather than posting parts the endpoint will reject (#814).MODELS_INFO: dict[str, object] = {"gemini-embedding-2": {"default": 3072,"dimensions": [128, 256, 512, 768, 1536, 3072],+ "multimodal": True,},"gemini-embedding-2-preview": {"default": 3072,"dimensions": [128, 256, 512, 768, 1536, 3072],+ "multimodal": True,},"gemini-embedding-001": {"default": 3072,"dimensions": [128, 256, 512, 768, 1536, 3072],+ "multimodal": False,},}@@ -135,6 +142,89 @@ class GeminiEmbeddingAdapter(OpenAICompatibleEmbeddingAdapter):redacted = redacted.replace(secret, "[REDACTED]")return redacted[:500]+ @classmethod+ def _model_info(cls, model_name: str | None) -> dict[str, Any] | None:+ """The MODELS_INFO row for a model, falling back across the 2.x line."""+ model_id = cls._model_id(model_name)+ info = cls.MODELS_INFO.get(model_id)+ if info is None and cls._is_embedding2(model_id):+ info = cls.MODELS_INFO["gemini-embedding-2"]+ return info if isinstance(info, dict) else None++ @classmethod+ def _supports_multimodal(cls, model_name: str | None) -> bool:+ info = cls._model_info(model_name)+ return bool(info.get("multimodal", False)) if info else False++ @staticmethod+ def _inline_data(value: str, kind: str) -> dict[str, Any]:+ """Turn one ``data:`` URI into Gemini's ``inlineData`` part.++ Only ``data:`` URIs are accepted. `batchEmbedContents` has no remote-URL+ part — the alternative to inline bytes is a File API upload — so an+ http(s) value could only be honoured by fetching it here, and this+ repository has already settled that question against doing so (see+ ``services/llm/multimodal._resolve_local_attachment_url``: sync network+ IO on an async path, and an SSRF footgun). Callers hand us bytes.+ """+ text = str(value or "").strip()+ if not text.startswith("data:"):+ raise ValueError(+ f"Gemini embeddings need inline bytes for '{kind}' content, but got "+ f"{'an http(s) URL' if text[:4].lower() == 'http' else 'an unsupported value'}. "+ "Pass a data: URI (base64) instead."+ )+ header, _, payload = text.partition(",")+ if not payload:+ raise ValueError(f"Malformed data: URI for '{kind}' content — no base64 payload.")+ mime_type = header[len("data:") :].split(";", 1)[0].strip()+ if not mime_type:+ raise ValueError(f"Malformed data: URI for '{kind}' content — no MIME type.")+ return {"inlineData": {"mimeType": mime_type, "data": payload}}++ @classmethod+ def _content_parts(cls, item: dict[str, Any]) -> list[dict[str, Any]]:+ """Map one ``{"text"|"image"|"video"|"audio": value}`` item to parts."""+ parts: list[dict[str, Any]] = []+ for kind, value in item.items():+ if kind == "text":+ parts.append({"text": str(value or "")})+ elif kind in {"image", "video", "audio", "document"}:+ parts.append(cls._inline_data(str(value or ""), kind))+ else:+ raise ValueError(f"Gemini embeddings do not support content type '{kind}'.")+ return parts++ def _native_multimodal_payload(+ self,+ request: EmbeddingRequest,+ model: str,+ ) -> dict[str, Any]:+ """Build ``batchEmbedContents`` requests from provider-agnostic contents.++ One vector per content item, matching the Cohere adapter's reading of+ the same contract — except that Gemini maps every modality into one+ shared space, so ``enable_fusion`` genuinely works here: it folds every+ item's parts into a single content and returns one vector for the lot.+ """+ model_id = self._model_id(model)+ items = [item for item in (request.contents or []) if isinstance(item, dict)]+ dimension = request.dimensions or self.dimensions++ def _request(parts: list[dict[str, Any]]) -> dict[str, Any]:+ entry: dict[str, Any] = {+ "model": f"models/{model_id}",+ "content": {"parts": parts},+ }+ if dimension and self.send_dimensions is not False:+ entry["outputDimensionality"] = dimension+ return entry++ if request.enable_fusion:+ fused = [part for item in items for part in self._content_parts(item)]+ return {"requests": [_request(fused)] if fused else []}+ return {"requests": [_request(self._content_parts(item)) for item in items]}+def _native_payload(self,request: EmbeddingRequest,@@ -175,13 +265,18 @@ class GeminiEmbeddingAdapter(OpenAICompatibleEmbeddingAdapter):f"Gemini endpoint model '{endpoint_model}' does not match selected "f"model '{model_id}'. Update the visible embedding Endpoint URL.")- if request.contents:+ if request.contents and not self._supports_multimodal(model_id):raise ValueError(- "DeepTutor's Gemini embedding adapter currently supports text only; "- "multimodal `contents` require a dedicated native content mapper."+ f"Gemini model '{model_id}' is text-only and cannot embed multimodal "+ "`contents`. Select gemini-embedding-2, which maps text, images, "+ "video, audio and documents into one space.")- payload = self._native_payload(request, model_id)+ payload = (+ self._native_multimodal_payload(request, model_id)+ if request.contents+ else self._native_payload(request, model_id)+ )headers = {"Content-Type": "application/json"}api_key = self._auth_api_key()explicit_auth = {str(key).lower() for key in self.extra_headers} & {@@ -302,10 +397,14 @@ class GeminiEmbeddingAdapter(OpenAICompatibleEmbeddingAdapter):not isinstance(vector, list) or not vector for vector in embeddings):raise ValueError("Gemini native embedding response contains no usable vectors.")- if len(embeddings) != len(request.texts):+ # Count against what was actually posted, not against `request.texts`:+ # a multimodal turn carries no texts at all, and a fused one collapses+ # many items into a single vector.+ expected = len(payload.get("requests", []))+ if len(embeddings) != expected:raise ValueError("Gemini native embedding response count does not match the request: "- f"expected {len(request.texts)}, got {len(embeddings)}."+ f"expected {expected}, got {len(embeddings)}.")requested_dimension = request.dimensions or self.dimensions@@ -343,10 +442,8 @@ class GeminiEmbeddingAdapter(OpenAICompatibleEmbeddingAdapter):def get_model_info(self) -> Dict[str, Any]:"""Return Gemini embedding dimensions exposed to Settings diagnostics."""model_name = self._model_id(self.model)- model_info = self.MODELS_INFO.get(model_name)- if model_info is None and self._is_embedding2(model_name):- model_info = self.MODELS_INFO["gemini-embedding-2"]- if not isinstance(model_info, dict):+ model_info = self._model_info(model_name)+ if model_info is None:return {"model": model_name,"dimensions": self.dimensions,@@ -360,8 +457,6 @@ class GeminiEmbeddingAdapter(OpenAICompatibleEmbeddingAdapter):"dimensions": model_info["default"],"supported_dimensions": list(model_info["dimensions"]),"supports_variable_dimensions": True,- # The current DeepTutor content contract is text-only. Advertising- # multimodal here would route images into an unsupported payload.- "multimodal": False,+ "multimodal": bool(model_info.get("multimodal", False)),"provider": "gemini",}diff --git a/deeptutor/services/keypool.py b/deeptutor/services/keypool.pyindex b043cbbd9..e6bb2d00e 100644--- a/deeptutor/services/keypool.py+++ b/deeptutor/services/keypool.py@@ -56,4 +56,19 @@ class KeyPool:self._cooldown_until[key] = monotonic() + self._cooldown_s-__all__ = ["KeyPool"]+def primary_api_key(value: str | list[str] | None) -> str | None:+ """The one key to use where a pool cannot be rotated.++ A configured credential became ``str | list[str]`` when key rotation+ landed, but most consumers take a single key: an auth header, an SDK+ client built once, a pipeline handed a credential. Passing the list+ through would render as ``"['sk-a', 'sk-b']"`` in an ``Authorization``+ header — a 401 whose cause is invisible. Reduce at the boundary instead,+ and reduce in one place so every such boundary agrees which key is first.+ """+ if isinstance(value, list):+ return value[0] if value else None+ return value or None+++__all__ = ["KeyPool", "primary_api_key"]diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.pyindex 97b5d1c7c..9b093c278 100644--- a/deeptutor/services/llm/config.py+++ b/deeptutor/services/llm/config.py@@ -17,6 +17,7 @@ import refrom typing import TYPE_CHECKING, TypedDictfrom deeptutor.services.config import resolve_llm_runtime_config+from deeptutor.services.keypool import primary_api_keyfrom deeptutor.services.provider_registry import canonical_provider_name, find_by_namefrom .exceptions import LLMConfigError@@ -62,7 +63,7 @@ def _is_openai_compatible_binding(binding: str | None) -> bool:def _set_openai_env_vars(api_key: str | list[str] | None, base_url: str | None, *, source: str) -> None:- primary_key = api_key[0] if isinstance(api_key, list) and api_key else api_key+ primary_key = primary_api_key(api_key)if primary_key:os.environ["OPENAI_API_KEY"] = primary_keylogger.debug("Set OPENAI_API_KEY env var (%s)", source)diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 757bc25d0..8d0818eec 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -9,6 +9,7 @@ from types import SimpleNamespacefrom typing import Any, TypedDictfrom deeptutor.config.settings import settings+from deeptutor.services.keypool import primary_api_keyfrom deeptutor.services.provider_registry import (PROVIDERS,canonical_provider_name,@@ -85,7 +86,7 @@ def _resolve_provider_spec(explicit = find_by_name(binding)gateway = find_gateway(provider_name=explicit.name if explicit else None,- api_key=(api_key[0] if isinstance(api_key, list) and api_key else api_key) or None,+ api_key=primary_api_key(api_key),api_base=base_url or None,)if explicit and gateway and explicit.name == "openai":diff --git a/deeptutor/services/llm/provider_core/azure_openai_provider.py b/deeptutor/services/llm/provider_core/azure_openai_provider.pyindex 2d4dd9878..8060dae97 100644--- a/deeptutor/services/llm/provider_core/azure_openai_provider.py+++ b/deeptutor/services/llm/provider_core/azure_openai_provider.py@@ -4,7 +4,9 @@ from __future__ import annotationsimport asynciofrom collections.abc import Awaitable, Callable+import refrom typing import Any+from urllib.parse import urlsplit, urlunsplitimport uuidfrom openai import AsyncOpenAI@@ -19,6 +21,49 @@ from deeptutor.services.llm.provider_core.openai_responses import (parse_response_output,)+_ENDPOINT_SUFFIXES = (+ "/chat/completions",+ "/completions",+ "/responses",+ "/embeddings",+)+_DEPLOYMENT_SEGMENT = re.compile(r"/deployments/[^/]+")+++def normalize_azure_base_url(api_base: str) -> str:+ """Reduce any Azure OpenAI endpoint spelling to the ``/openai/v1`` surface.++ The portal hands out classic endpoints such as+ ``https://res.openai.azure.com/openai/deployments/<name>/chat/completions``+ (often with ``?api-version=``). Appending ``/openai/v1`` to those verbatim+ yields an unreachable path, so chat answered ``404 Resource not found``+ while the settings probe — which builds classic URLs — kept passing.+ """+ raw = (api_base or "").strip()+ if not raw:+ return raw+ if not re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", raw):+ raw = f"https://{raw}"++ parsed = urlsplit(raw)+ path = parsed.path.rstrip("/")++ stripped = True+ while stripped:+ stripped = False+ for suffix in _ENDPOINT_SUFFIXES:+ if path.endswith(suffix):+ path = path[: -len(suffix)].rstrip("/")+ stripped = True++ path = _DEPLOYMENT_SEGMENT.sub("", path).rstrip("/")+ for surface in ("/openai/v1", "/openai"):+ if path.endswith(surface):+ path = path[: -len(surface)].rstrip("/")+ break++ return urlunsplit((parsed.scheme, parsed.netloc, f"{path}/openai/v1/", "", ""))+class AzureOpenAIProvider(LLMProvider):"""Azure OpenAI provider using the Responses API."""@@ -29,6 +74,7 @@ class AzureOpenAIProvider(LLMProvider):api_base: str = "",default_model: str = "gpt-5.2-chat",extra_headers: dict[str, str] | None = None,+ api_version: str | None = None,):super().__init__(api_key, api_base)self.default_model = default_model@@ -39,19 +85,27 @@ class AzureOpenAIProvider(LLMProvider):if not api_base:raise ValueError("Azure OpenAI api_base is required")- base_url = api_base.rstrip("/")- if not base_url.endswith("/openai/v1"):- base_url = f"{base_url}/openai/v1"- base_url = f"{base_url.rstrip('/')}/"+ base_url = normalize_azure_base_url(api_base)- headers = {"x-session-affinity": uuid.uuid4().hex}+ # Azure authenticates API keys through ``api-key``; the SDK only sends+ # ``Authorization: Bearer``, which the service reserves for Entra tokens.+ headers = {"x-session-affinity": uuid.uuid4().hex, "api-key": api_key}if extra_headers:headers.update(extra_headers)+ # The ``/openai/v1`` surface supersedes ``?api-version=``, so a classic+ # dated version configured for the probe's URL would be rejected here.+ # Only ``preview`` is forwarded, since Azure still gates preview-only+ # Responses features behind it.+ default_query = (+ {"api-version": "preview"} if (api_version or "").strip().lower() == "preview" else None+ )+self._client = AsyncOpenAI(api_key=api_key,base_url=base_url,default_headers=headers,+ default_query=default_query,max_retries=0,**openai_client_kwargs(),)diff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.pyindex bd13bd4e0..97181b057 100644--- a/deeptutor/services/llm/provider_factory.py+++ b/deeptutor/services/llm/provider_factory.py@@ -68,7 +68,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:)provider = build_codebuddy_provider(- api_key=llm_config.api_key or None,+ api_key=primary_api_key or None,default_model=llm_config.model,)elif backend == "azure_openai":@@ -79,6 +79,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:api_base=llm_config.effective_url or llm_config.base_url or "",default_model=llm_config.model,extra_headers=llm_config.extra_headers or None,+ api_version=llm_config.api_version,)elif backend == "anthropic":from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProviderdiff --git a/deeptutor/services/partners/channel_state_migration.py b/deeptutor/services/partners/channel_state_migration.pynew file mode 100644index 000000000..2cea6114f--- /dev/null+++ b/deeptutor/services/partners/channel_state_migration.py@@ -0,0 +1,127 @@+"""One-shot rehoming of channel state that used to be shared by all partners.++Channel runtime state — bot tokens, long-poll cursors, conversation+references, E2EE device stores — used to live in one directory per *channel*+(``data/partners/weixin/``), not per partner. Two partners on the same channel+therefore read each other's credentials and overwrote each other's cursor,+which is why only one of them could ever be online. It now lives under+``data/partners/{partner_id}/channels/{channel}/``.++That move would log the working partner out, so the old state is copied across+first — but only when its owner is certain. Two kinds of certainty:++* the state *names* its owner (a saved bot token that matches one partner's+ configured token), or+* only one partner has the channel enabled at all.++Anything else is a genuine tie, and guessing would hand one partner another's+account — the very bug this fixes. Those re-authenticate once instead.++Copies rather than moves, like the TutorBot migration before it: the legacy+tree is left untouched, so a bad outcome is always recoverable by hand.+"""++from __future__ import annotations++import json+import logging+from pathlib import Path+import shutil+from typing import Any, Callable, Mapping++from deeptutor.partners.config.paths import get_data_dir, get_partner_channel_dir++logger = logging.getLogger(__name__)++#: Channel name → the directory it used to share, under ``data/partners/``.+LEGACY_STATE_DIRS: dict[str, str] = {+ "weixin": "weixin",+ "mochat": "mochat",+ "msteams": "msteams",+ "matrix": "matrix-store",+}+++def _has_content(path: Path) -> bool:+ return path.is_dir() and any(path.iterdir())+++def _weixin_claims(legacy: Path, channel_config: Mapping[str, Any]) -> bool:+ """True when the legacy ``account.json`` holds *this* partner's bot token.++ The web onboarding writes the token it wins into the partner's own config,+ so for every partner set up that way the saved state proves whose it is.+ """+ token = str(channel_config.get("token") or "").strip()+ if not token:+ return False+ try:+ data = json.loads((legacy / "account.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return False+ return isinstance(data, dict) and str(data.get("token") or "").strip() == token+++#: Channels whose stored state can identify its own owner.+_CLAIMS: dict[str, Callable[[Path, Mapping[str, Any]], bool]] = {"weixin": _weixin_claims}+++def _resolve_owner(+ channel: str,+ legacy: Path,+ candidates: Mapping[str, Mapping[str, Any]],+) -> str | None:+ """Which partner the legacy state belongs to, or ``None`` if undecidable."""+ enabled = [+ partner_id+ for partner_id, channels in candidates.items()+ if isinstance(channels.get(channel), Mapping) and channels[channel].get("enabled")+ ]+ if not enabled:+ return None++ claims = _CLAIMS.get(channel)+ if claims:+ proven = [pid for pid in enabled if claims(legacy, candidates[pid][channel])]+ if len(proven) == 1:+ return proven[0]+ if len(proven) > 1:+ return None # Two partners configured with one token: not ours to split.++ return enabled[0] if len(enabled) == 1 else None+++def rehome_shared_channel_state(candidates: Mapping[str, Mapping[str, Any]]) -> None:+ """Copy each legacy shared channel state dir to the partner that owns it.++ ``candidates`` maps partner id → that partner's ``channels`` config dict.+ Safe to call repeatedly: a partner that already has its own state is left+ alone, which is also what stops the copy from happening twice.+ """+ base = get_data_dir()+ for channel, dirname in LEGACY_STATE_DIRS.items():+ legacy = base / dirname+ if not _has_content(legacy):+ continue+ if (legacy / "config.yaml").exists():+ continue # A partner that happens to be named after a channel.++ owner = _resolve_owner(channel, legacy, candidates)+ if owner is None:+ logger.info(+ "Legacy %s state in %s has no unambiguous owner; leaving it in place "+ "(affected partners re-authenticate once)",+ channel,+ legacy,+ )+ continue++ target = get_partner_channel_dir(owner, channel)+ if _has_content(target):+ continue+ try:+ shutil.copytree(legacy, target, dirs_exist_ok=True)+ except OSError:+ logger.exception("Failed to rehome legacy %s state to partner '%s'", channel, owner)+ continue+ logger.info("Rehomed legacy %s state to partner '%s'", channel, owner)diff --git a/deeptutor/services/partners/commands.py b/deeptutor/services/partners/commands.pyindex 7847224f7..260369401 100644--- a/deeptutor/services/partners/commands.py+++ b/deeptutor/services/partners/commands.py@@ -34,6 +34,11 @@ BUILTIN_PARTNER_COMMANDS: tuple[PartnerCommandSpec, ...] = (PartnerCommandSpec("/status", "Show partner, session, model, and tool status."),PartnerCommandSpec("/history", "Show recent messages in this conversation.", "[n]"),PartnerCommandSpec("/tool", "Show or change enabled tools.", "[on|off <name>|reset]"),+ PartnerCommandSpec(+ "/link",+ "Connect this chat account to your DeepTutor account.",+ "<code from the web app>",+ ),)@@ -109,8 +114,44 @@ class PartnerCommandHandler:return self._history(msg, args)if command == "/tool":return self._tool(args)+ if command == "/link":+ return self._link(msg, args)return PartnerCommandResult(f"Unknown command: {parts[0]}\n\n{build_partner_help_text()}")+ def _link(self, msg: InboundMessage, args: list[str]) -> PartnerCommandResult:+ """Claim a link code, so this chat account speaks as its owner from now on."""+ from deeptutor.services.partners.interaction import actor_for_account+ from deeptutor.services.partners.links import redeem_link_code++ if msg.channel == "web":+ return PartnerCommandResult("You're already signed in here — nothing to link.")+ if (msg.metadata or {}).get("is_group"):+ return PartnerCommandResult(+ "Send /link in a direct message instead — group chats stay shared, "+ "and a code posted in one would be visible to everyone."+ )+ if not args:+ return PartnerCommandResult(+ "Usage: /link <code>. Open this partner in DeepTutor and choose "+ "“Link this chat account” to get a code."+ )+ user_id = redeem_link_code(+ self.partner_id, args[0], channel=msg.channel, sender_id=msg.sender_id+ )+ if not user_id:+ return PartnerCommandResult(+ "That code is not valid — it may have expired or already been used. "+ "Generate a fresh one in DeepTutor and try again."+ )+ actor = actor_for_account(user_id)+ if actor is None:+ return PartnerCommandResult("That code belongs to an account that no longer exists.")+ return PartnerCommandResult(+ f"Linked — I'll talk to you as {actor.username} from now on. "+ "This conversation is private to your account, and I can reach your "+ "library and notes here just like in the app."+ )+def _new(self, msg: InboundMessage) -> PartnerCommandResult:archived = self.store.archive(msg.session_key)if archived:diff --git a/deeptutor/services/partners/interaction.py b/deeptutor/services/partners/interaction.pyindex 063554856..560d9bff4 100644--- a/deeptutor/services/partners/interaction.py+++ b/deeptutor/services/partners/interaction.py@@ -12,7 +12,8 @@ from __future__ import annotationsfrom contextlib import contextmanagerfrom contextvars import ContextVar, Tokenfrom dataclasses import dataclass-from typing import Iterator+from pathlib import Path+from typing import Iterator, Literalfrom deeptutor.multi_user.models import CurrentUserfrom deeptutor.multi_user.paths import (@@ -20,13 +21,45 @@ from deeptutor.multi_user.paths import (get_admin_path_service,get_path_service_for_scope,)-from deeptutor.partners.config.paths import get_partner_user_workspace+from deeptutor.partners.config.paths import (+ get_partner_sessions_dir,+ get_partner_user_sessions_dir,+ get_partner_user_workspace,+)from deeptutor.services.path_service import PathServicefrom .scope import is_partner_user_idfrom .sessions import PartnerSessionStore+def actor_for_account(user_id: str) -> CurrentUser | None:+ """Rebuild the ``CurrentUser`` for a stored account id, or None if it is gone.++ Channel traffic carries no session, so an identity established earlier (by+ linking a chat account) has to be reconstituted from the account store on+ every turn — and a user who has since been deleted must resolve to nobody+ rather than to a scope that no longer belongs to anyone.+ """+ from deeptutor.multi_user.identity import get_user_by_id+ from deeptutor.multi_user.paths import scope_for_user++ found = get_user_by_id(user_id)+ if found is None:+ return None+ username, record = found+ if record.get("disabled"):+ return None+ role: Literal["admin", "user"] = (+ "admin" if str(record.get("role") or "user") == "admin" else "user"+ )+ return CurrentUser(+ id=user_id,+ username=username,+ role=role,+ scope=scope_for_user(user_id, is_admin=role == "admin"),+ )++def personal_actor_id(actor: CurrentUser | None) -> str | None:"""Account id requiring private Partner state, or ``None`` for legacy scope."""if actor is None or actor.is_admin or is_partner_user_id(actor.id):@@ -34,6 +67,47 @@ def personal_actor_id(actor: CurrentUser | None) -> str | None:return actor.id+# One store instance per directory, process-wide. Sharing matters: the store+# serialises writes through an instance-level lock, so two objects over the same+# directory would not exclude each other.+_STORES: dict[Path, PartnerSessionStore] = {}+++def session_sessions_dir(partner_id: str, actor: CurrentUser | None) -> Path:+ """Where *actor*'s conversations with *partner_id* live.++ Each human gets their own directory under the partner; the partner's own+ top-level ``sessions/`` holds the shared, un-attributed threads — admin+ turns and channel traffic from senders who have not linked an account.+ """+ actor_id = personal_actor_id(actor)+ if actor_id is None:+ return get_partner_sessions_dir(partner_id)+ return get_partner_user_sessions_dir(partner_id, actor_id)+++def session_store_for(partner_id: str, actor: CurrentUser | None) -> PartnerSessionStore:+ """The single store that owns *actor*'s conversations with *partner_id*.++ Every reader and writer resolves through here — the runner persisting a+ turn, and the history/session endpoints reading it back — so a message is+ never written to one place and looked for in another.+ """+ directory = session_sessions_dir(partner_id, actor)+ store = _STORES.get(directory)+ if store is None:+ store = PartnerSessionStore(directory)+ _STORES[directory] = store+ return store+++def forget_partner_stores(partner_id: str) -> None:+ """Drop cached stores for a deleted partner."""+ root = get_partner_sessions_dir(partner_id).parent.resolve()+ for directory in [d for d in _STORES if root in d.resolve().parents or d.resolve() == root]:+ _STORES.pop(directory, None)++@dataclass(frozen=True, slots=True)class PartnerTurnContext:partner_id: str@@ -98,8 +172,12 @@ def partner_turn_context(context: PartnerTurnContext) -> Iterator[None]:__all__ = ["PartnerTurnContext",+ "actor_for_account","build_partner_turn_context",+ "forget_partner_stores","get_partner_turn_context","partner_turn_context","personal_actor_id",+ "session_sessions_dir",+ "session_store_for",]diff --git a/deeptutor/services/partners/links.py b/deeptutor/services/partners/links.pynew file mode 100644index 000000000..ee641cb14--- /dev/null+++ b/deeptutor/services/partners/links.py@@ -0,0 +1,197 @@+"""Linking a chat-channel account to a DeepTutor account.++A partner reached over QQ or Telegram knows only a channel-local sender id.+Nothing connects that to the person's DeepTutor account, so without a link+every channel message is anonymous: it lands in the partner's shared thread+pool, which only admins can read, and the partner answers it out of the admin+workspace rather than the sender's own library and memory.++A link closes that gap. The person asks their partner for a code in the web+app, sends ``/link <code>`` to it from the chat account they want connected,+and from then on that sender id carries their identity: their conversations are+private to them and readable back in the web app, and the partner reads their+knowledge, notebooks and memory the same way it would in a browser turn.++State lives beside the partner it belongs to, in+``data/partners/<id>/channel_links.json``, and is rewritten whole under a+per-file lock so two channels redeeming at once cannot lose each other's work.+"""++from __future__ import annotations++from dataclasses import dataclass+from datetime import datetime, timedelta, timezone+import json+from pathlib import Path+import secrets+import threading+from typing import Any++from deeptutor.partners.config.paths import get_partner_dir+from deeptutor.services.file_io import atomic_write_json++# Unambiguous when read aloud or retyped: no O/0, I/1, or similar look-alikes.+_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"+_CODE_LENGTH = 6+_CODE_TTL = timedelta(minutes=15)++_locks: dict[Path, threading.Lock] = {}+_locks_mutex = threading.Lock()+++@dataclass(frozen=True, slots=True)+class LinkCode:+ code: str+ expires_at: str+++def link_key(channel: str, sender_id: str) -> str:+ """The stable identifier for one account on one channel."""+ return f"{channel}:{sender_id}"+++def _path(partner_id: str) -> Path:+ return get_partner_dir(partner_id) / "channel_links.json"+++def _lock(path: Path) -> threading.Lock:+ with _locks_mutex:+ lock = _locks.get(path)+ if lock is None:+ lock = threading.Lock()+ _locks[path] = lock+ return lock+++def _now() -> datetime:+ return datetime.now(timezone.utc)+++def _read(path: Path) -> dict[str, Any]:+ if not path.exists():+ return {"links": {}, "codes": {}}+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return {"links": {}, "codes": {}}+ if not isinstance(data, dict):+ return {"links": {}, "codes": {}}+ links = data.get("links")+ codes = data.get("codes")+ return {+ "links": links if isinstance(links, dict) else {},+ "codes": codes if isinstance(codes, dict) else {},+ }+++def _drop_expired(state: dict[str, Any]) -> dict[str, Any]:+ now = _now()+ state["codes"] = {+ code: record+ for code, record in state["codes"].items()+ if isinstance(record, dict) and _expiry(record) > now+ }+ return state+++def _expiry(record: dict[str, Any]) -> datetime:+ try:+ return datetime.fromisoformat(str(record.get("expires_at") or ""))+ except ValueError:+ return datetime.min.replace(tzinfo=timezone.utc)+++def _update(partner_id: str, mutate: Any) -> Any:+ """Read, mutate and rewrite the file as one indivisible step."""+ path = _path(partner_id)+ with _lock(path):+ state = _drop_expired(_read(path))+ result = mutate(state)+ atomic_write_json(path, state)+ return result+++def issue_link_code(partner_id: str, user_id: str) -> LinkCode:+ """Mint a single-use code for *user_id*, replacing any code they still hold.++ One live code per person: a second request invalidates the first, so a code+ read off a stale screen cannot link an account the user has moved on from.+ """+ code = "".join(secrets.choice(_CODE_ALPHABET) for _ in range(_CODE_LENGTH))+ expires_at = (_now() + _CODE_TTL).isoformat()++ def mutate(state: dict[str, Any]) -> None:+ state["codes"] = {+ existing: record+ for existing, record in state["codes"].items()+ if record.get("user_id") != user_id+ }+ state["codes"][code] = {"user_id": user_id, "expires_at": expires_at}++ _update(partner_id, mutate)+ return LinkCode(code=code, expires_at=expires_at)+++def redeem_link_code(partner_id: str, code: str, *, channel: str, sender_id: str) -> str | None:+ """Bind *channel*/*sender_id* to whoever holds *code*; the account id, or None.++ The code is spent whether or not the sender was already linked, and a+ sender that was linked to someone else is re-pointed — the person holding+ the code is by definition the one at the keyboard.+ """+ wanted = (code or "").strip().upper()+ if not wanted:+ return None++ def mutate(state: dict[str, Any]) -> str | None:+ record = state["codes"].pop(wanted, None)+ if not isinstance(record, dict):+ return None+ user_id = str(record.get("user_id") or "")+ if not user_id:+ return None+ state["links"][link_key(channel, sender_id)] = {+ "user_id": user_id,+ "channel": channel,+ "sender_id": sender_id,+ "linked_at": _now().isoformat(),+ }+ return user_id++ return _update(partner_id, mutate)+++def linked_user_id(partner_id: str, channel: str, sender_id: str) -> str | None:+ """The account behind a channel sender, or None when it is unlinked."""+ record = _read(_path(partner_id))["links"].get(link_key(channel, sender_id))+ if not isinstance(record, dict):+ return None+ return str(record.get("user_id") or "") or None+++def list_links(partner_id: str, user_id: str) -> list[dict[str, Any]]:+ """Every channel account *user_id* has linked to this partner."""+ return [+ {"key": key, **record}+ for key, record in sorted(_read(_path(partner_id))["links"].items())+ if isinstance(record, dict) and record.get("user_id") == user_id+ ]+++def remove_link(partner_id: str, user_id: str, key: str) -> bool:+ """Unlink one channel account. Only its own owner may."""++ def mutate(state: dict[str, Any]) -> bool:+ record = state["links"].get(key)+ if not isinstance(record, dict) or record.get("user_id") != user_id:+ return False+ del state["links"][key]+ return True++ return bool(_update(partner_id, mutate))+++def forget_partner_links(partner_id: str) -> None:+ """Drop the cached lock for a deleted partner (its file goes with it)."""+ with _locks_mutex:+ _locks.pop(_path(partner_id), None)diff --git a/deeptutor/services/partners/manager.py b/deeptutor/services/partners/manager.pyindex deca04937..dee36fce8 100644--- a/deeptutor/services/partners/manager.py+++ b/deeptutor/services/partners/manager.py@@ -20,11 +20,14 @@ from typing import Any, Awaitable, Callableimport yaml+from deeptutor.multi_user.models import CurrentUserfrom deeptutor.partners.config.paths import (get_data_dir,get_partner_dir,get_partner_sessions_dir,)+from deeptutor.services.partners.interaction import forget_partner_stores+from deeptutor.services.partners.links import forget_partner_linksfrom deeptutor.services.partners.runtime import PartnerRunnerfrom deeptutor.services.partners.sessions import PartnerSessionStorefrom deeptutor.services.partners.workspace import (@@ -166,12 +169,21 @@ def _mcp_tools_setting(data: dict[str, Any]) -> list[str] | None:return None if MCP_TOOLS_UNRESTRICTED in names else names+# Distinguishes "use the authenticated caller" (the default) from an explicit+# ``actor=None``, which selects the partner's shared, un-attributed store.+_CURRENT_ACTOR: Any = object()++@dataclassclass PartnerConfig:"""Configuration for a single partner."""name: strdescription: str = ""+ # Account id of the human who created the partner. Empty for partners that+ # predate ownership (and for anything an admin created before this field+ # existed) — those stay admin-managed, which is what they always were.+ owner_id: str = ""channels: dict[str, Any] = field(default_factory=dict)llm_selection: dict[str, str] | None = None# Fallback model: when a turn fails outright on the primary selection@@ -297,6 +309,7 @@ class PartnerInstance:"partner_id": self.partner_id,"name": self.config.name,"description": self.config.description,+ "owner_id": self.config.owner_id,"channels": channels,"llm_selection": self.config.llm_selection,"backup_llm_selection": self.config.backup_llm_selection,@@ -320,8 +333,8 @@ class PartnerManager:def __init__(self) -> None:self._partners: dict[str, PartnerInstance] = {}- self._stores: dict[str, PartnerSessionStore] = {}self._migrated_legacy = False+ self._rehomed_channel_state = False# ── Path helpers ──────────────────────────────────────────────@@ -332,12 +345,35 @@ class PartnerManager:def _partner_dir(self, partner_id: str) -> Path:return self._partners_dir / partner_id- def session_store(self, partner_id: str) -> PartnerSessionStore:- store = self._stores.get(partner_id)- if store is None:- store = PartnerSessionStore(get_partner_sessions_dir(partner_id))- self._stores[partner_id] = store- return store+ def owner_id(self, partner_id: str) -> str:+ """The account that created *partner_id*, or ``""`` when admin-managed.++ Reads the live instance when the partner is running and falls back to+ disk, so ownership is answerable whether or not it has been started.+ """+ instance = self._partners.get(partner_id)+ if instance is not None:+ return instance.config.owner_id+ config = self.load_config(partner_id)+ return config.owner_id if config else ""++ def session_store(+ self, partner_id: str, *, actor: CurrentUser | None = _CURRENT_ACTOR+ ) -> PartnerSessionStore:+ """The session store holding *actor*'s conversations with the partner.++ Defaults to the authenticated caller, so every history / session+ endpoint reads back exactly what that person's turns wrote. Pass+ ``actor=None`` for the partner's shared thread pool (admin turns and+ un-linked channel traffic).+ """+ from deeptutor.services.partners.interaction import session_store_for++ if actor is _CURRENT_ACTOR:+ from deeptutor.multi_user.context import get_current_user_or_none++ actor = get_current_user_or_none()+ return session_store_for(partner_id, actor)def _ensure_partner_dirs(self, partner_id: str) -> None:get_partner_dir(partner_id)@@ -354,6 +390,7 @@ class PartnerManager:_MERGEABLE_FIELDS = ("name","description",+ "owner_id","channels","llm_selection","backup_llm_selection",@@ -377,6 +414,7 @@ class PartnerManager:return PartnerConfig(name=data.get("name", partner_id),description=data.get("description", ""),+ owner_id=str(data.get("owner_id", "") or ""),channels=strip_legacy_global_delivery(data.get("channels", {}) or {}),llm_selection=data.get("llm_selection"),backup_llm_selection=data.get("backup_llm_selection"),@@ -411,6 +449,7 @@ class PartnerManager:data: dict[str, Any] = {"name": config.name,"description": config.description,+ "owner_id": config.owner_id,"channels": strip_legacy_global_delivery(config.channels),"language": config.language,"emoji": config.emoji,@@ -486,8 +525,7 @@ class PartnerManager:from deeptutor.partners.bus.queue import MessageBusbus = MessageBus()- store = self.session_store(partner_id)- runner = PartnerRunner(partner_id, config, bus, store, save_config=self.save_config)+ runner = PartnerRunner(partner_id, config, bus, save_config=self.save_config)try:channel_manager = self._build_channel_manager(config, bus, partner_id=partner_id)@@ -614,6 +652,7 @@ class PartnerManager:from deeptutor.partners.channels.manager import ChannelManagerfrom deeptutor.partners.config.schema import ChannelsConfig+ self._rehome_shared_channel_state()channels_config = ChannelsConfig(**config.channels)manager = ChannelManager(channels_config, bus, partner_id=partner_id)if not manager.channels:@@ -722,6 +761,7 @@ class PartnerManager:"partner_id": pid,"name": cfg.name if cfg else pid,"description": cfg.description if cfg else "",+ "owner_id": cfg.owner_id if cfg else "","channels": list(cfg.channels.keys()) if cfg else [],"llm_selection": cfg.llm_selection if cfg else None,"backup_llm_selection": cfg.backup_llm_selection if cfg else None,@@ -957,7 +997,8 @@ class PartnerManager:async def destroy_partner(self, partner_id: str) -> bool:await self.stop_partner(partner_id, preserve_auto_start=False)- self._stores.pop(partner_id, None)+ forget_partner_stores(partner_id)+ forget_partner_links(partner_id)try:from deeptutor.services.cron import get_cron_service@@ -971,6 +1012,29 @@ class PartnerManager:logger.info("Partner '%s' destroyed (data deleted)", partner_id)return True+ def _rehome_shared_channel_state(self) -> None:+ """One-shot: give each channel's formerly shared state to its owner.++ Runs before any channel is constructed — a channel resolves its state+ dir while starting, so the copy has to already be there.+ """+ if self._rehomed_channel_state:+ return+ self._rehomed_channel_state = True+ try:+ from deeptutor.services.partners.channel_state_migration import (+ rehome_shared_channel_state,+ )++ candidates: dict[str, dict[str, Any]] = {}+ for pid in self._discover_partner_ids():+ cfg = self.load_config(pid)+ if cfg and cfg.channels:+ candidates[pid] = cfg.channels+ rehome_shared_channel_state(candidates)+ except Exception:+ logger.exception("Failed to rehome legacy channel state")+# ── Legacy TutorBot migration ─────────────────────────────────def _migrate_legacy_tutorbot(self) -> None:diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.pyindex 3db63083a..146afc16d 100644--- a/deeptutor/services/partners/runtime.py+++ b/deeptutor/services/partners/runtime.py@@ -35,14 +35,16 @@ from deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.multi_user.paths import get_current_path_service, user_contextfrom deeptutor.partners.bus.events import InboundMessage, OutboundMessagefrom deeptutor.partners.bus.queue import MessageBus-from deeptutor.partners.config.paths import get_partner_user_sessions_dirfrom deeptutor.partners.helpers import detect_image_mimefrom deeptutor.services.partners.commands import PartnerCommandHandlerfrom deeptutor.services.partners.interaction import (+ actor_for_account,build_partner_turn_context,partner_turn_context,personal_actor_id,+ session_store_for,)+from deeptutor.services.partners.links import linked_user_idfrom deeptutor.services.partners.scope import partner_userfrom deeptutor.services.partners.sessions import PartnerSessionStorefrom deeptutor.services.partners.workspace import ensure_partner_workspace, read_soul@@ -83,16 +85,13 @@ class PartnerRunner:partner_id: str,config: Any,bus: MessageBus,- store: PartnerSessionStore,save_config: Callable[[str, Any], None] | None = None,) -> None:self.partner_id = partner_idself.config = configself.bus = bus- self.store = storeself.save_config = save_configself._session_locks: dict[str, asyncio.Lock] = {}- self._personal_stores: dict[str, PartnerSessionStore] = {}self._tasks: set[asyncio.Task] = set()# ── inbound loop ──────────────────────────────────────────────@@ -134,15 +133,26 @@ class PartnerRunner:# ── one turn ──────────────────────────────────────────────────+ def _identify(self, msg: InboundMessage) -> None:+ """Attach the sender's DeepTutor identity to a channel message, if any.++ In-app turns arrive with an actor already set. A channel message+ carries only a sender id, which counts as an identity once that account+ has been linked (``/link``). Group traffic deliberately stays+ un-attributed: a group thread is a shared conversation, and splitting it+ per speaker would leave the partner answering each person out of a+ history nobody else in the room can see.+ """+ if msg.actor is not None or (msg.metadata or {}).get("is_group"):+ return+ user_id = linked_user_id(self.partner_id, msg.channel, msg.sender_id)+ if user_id:+ msg.actor = actor_for_account(user_id)+def _store_for(self, msg: InboundMessage) -> PartnerSessionStore:- actor_id = personal_actor_id(msg.actor)- if actor_id is None:- return self.store- store = self._personal_stores.get(actor_id)- if store is None:- store = PartnerSessionStore(get_partner_user_sessions_dir(self.partner_id, actor_id))- self._personal_stores[actor_id] = store- return store+ """Where this message's turn is persisted — the sender's own thread pool+ when the message carries an identity, the partner's shared one otherwise."""+ return session_store_for(self.partner_id, msg.actor)def _lock_for(self, session_key: str, *, actor_id: str | None) -> asyncio.Lock:lock_key = f"{actor_id or 'legacy'}:{session_key}"@@ -165,6 +175,7 @@ class PartnerRunner:should attach to the final outbound message (e.g. ``_streamed``when the reply was already delivered live via stream deltas)."""+ self._identify(msg)session_key = msg.session_keystore = self._store_for(msg)async with self._lock_for(session_key, actor_id=personal_actor_id(msg.actor)):diff --git a/deeptutor/services/partners/weixin_onboarding.py b/deeptutor/services/partners/weixin_onboarding.pynew file mode 100644index 000000000..e3c18fa32--- /dev/null+++ b/deeptutor/services/partners/weixin_onboarding.py@@ -0,0 +1,310 @@+"""Run the personal-WeChat QR login from the web app instead of the terminal.++Configuring a WeChat partner used to mean starting it and then finding the QR+code the channel printed to stdout — which on a container deployment is a+supervisord log the admin has no access to, so the channel's own "scan the QR+code to authenticate" was un-followable (#951).++This drives the same exchange (:mod:`deeptutor.partners.channels.weixin_qr`) on+behalf of a browser: start an attempt, poll it, and on success write the bot+token straight into the partner's channel config.++Two properties this owes the caller:++* **The token never leaves the server.** A status reply says *whether* the login+ succeeded, never what it produced. It is written to the partner config, which+ is already where channel secrets live and is already masked on read.+* **Attempts expire.** Sessions are in-process and short-lived, so a browser tab+ left open overnight cannot hold a pending login, and a restarted backend+ simply has none — the admin starts a new scan, which is what they would do+ anyway.+"""++from __future__ import annotations++from dataclasses import dataclass, field+import logging+import secrets+import threading+import time+from typing import Any++import httpx++from deeptutor.partners.channels.weixin_qr import (+ QrOutcome,+ fetch_qr_code,+ is_retryable_poll_error,+ poll_qr_code,+)++logger = logging.getLogger(__name__)++CHANNEL = "weixin"++#: WeChat's own codes expire in well under this; the ceiling exists so an+#: abandoned tab cannot pin a session forever.+_SESSION_TTL_SECONDS = 10 * 60+#: A code that expired mid-scan is re-issued this many times before the attempt+#: is declared over, mirroring the channel's own MAX_QR_REFRESH_COUNT.+_MAX_REFRESHES = 3++_DEFAULT_BASE_URL = "https://ilinkai.weixin.qq.com"+++@dataclass+class _Attempt:+ partner_id: str+ qrcode_id: str+ scan_payload: str+ poll_base_url: str+ route_tag: str+ client_version: int+ created_at: float+ status: str = "waiting"+ error: str = ""+ refreshes: int = 0+ #: Set once, on success. Never rendered into a response.+ token: str = field(default="", repr=False)+++_attempts: dict[str, _Attempt] = {}+_lock = threading.Lock()+++def _now() -> float:+ return time.monotonic()+++def _prune(now: float) -> None:+ stale = [key for key, a in _attempts.items() if now - a.created_at > _SESSION_TTL_SECONDS]+ for key in stale:+ _attempts.pop(key, None)+++def _client_version() -> int:+ from deeptutor.partners.channels.weixin import ILINK_APP_CLIENT_VERSION++ return ILINK_APP_CLIENT_VERSION+++def _channel_config(partner_id: str) -> dict[str, Any]:+ from deeptutor.services.partners.manager import get_partner_manager++ config = get_partner_manager().load_config(partner_id)+ channels = getattr(config, "channels", None) if config else None+ entry = (channels or {}).get(CHANNEL) if isinstance(channels, dict) else None+ return entry if isinstance(entry, dict) else {}+++def render_qr_svg(payload: str) -> str:+ """The code as an inline SVG, or ``""`` when it cannot be drawn here.++ SVG rather than PNG so no imaging library is pulled in, and server-side+ rather than in the browser so the web bundle needs no QR dependency at all.+ ``qrcode`` ships with the ``partners`` extra — the same extra this channel+ needs — but a deployment missing it should still get a usable page, so the+ caller also receives the raw payload to fall back on.+ """+ if not payload:+ return ""+ try:+ import io++ import qrcode+ import qrcode.image.svg++ image = qrcode.make(+ payload, image_factory=qrcode.image.svg.SvgPathImage, box_size=10, border=2+ )+ buffer = io.BytesIO()+ image.save(buffer)+ return buffer.getvalue().decode("utf-8")+ except Exception:+ logger.debug("qrcode unavailable; returning the raw scan payload", exc_info=True)+ return ""+++def _public(attempt: _Attempt, session_id: str) -> dict[str, Any]:+ """The wire view — deliberately without the token."""+ return {+ "session_id": session_id,+ "status": attempt.status,+ "error": attempt.error,+ "expires_in": max(0, int(_SESSION_TTL_SECONDS - (_now() - attempt.created_at))),+ # Carried on every reply because an expired code is silently replaced:+ # the browser must redraw, and polling is the only time it hears about it.+ "scan_payload": attempt.scan_payload,+ }+++async def start_login(partner_id: str) -> dict[str, Any]:+ """Issue a QR code for this partner and return what the browser must draw."""+ entry = _channel_config(partner_id)+ base_url = str(entry.get("base_url") or "") or _DEFAULT_BASE_URL+ route_tag = str(entry.get("route_tag") or "")+ client_version = _client_version()++ async with httpx.AsyncClient(timeout=httpx.Timeout(30, connect=15)) as client:+ code = await fetch_qr_code(+ client, base_url, client_version=client_version, route_tag=route_tag+ )++ session_id = secrets.token_urlsafe(16)+ attempt = _Attempt(+ partner_id=partner_id,+ qrcode_id=code.qrcode_id,+ scan_payload=code.scan_payload,+ poll_base_url=base_url,+ route_tag=route_tag,+ client_version=client_version,+ created_at=_now(),+ )+ with _lock:+ _prune(_now())+ _attempts[session_id] = attempt+ return {+ **_public(attempt, session_id),+ "scan_payload": code.scan_payload,+ "qr_svg": render_qr_svg(code.scan_payload),+ }+++async def poll_login(partner_id: str, session_id: str) -> dict[str, Any]:+ """Advance one attempt and report its state.++ Terminal states stay put: once an attempt is confirmed or dead, polling it+ again returns the same answer rather than re-running the exchange.+ """+ with _lock:+ _prune(_now())+ attempt = _attempts.get(session_id)+ if attempt is None or attempt.partner_id != partner_id:+ return {"session_id": session_id, "status": "expired", "error": "", "expires_in": 0}+ if attempt.status in {"confirmed", "expired", "error"}:+ return _public(attempt, session_id)++ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(30, connect=15)) as client:+ outcome = await poll_qr_code(+ client,+ attempt.poll_base_url,+ attempt.qrcode_id,+ client_version=attempt.client_version,+ route_tag=attempt.route_tag,+ )+ except Exception as exc:+ if is_retryable_poll_error(exc):+ # Not a verdict — the browser polls again in a moment.+ return _public(attempt, session_id)+ logger.warning("weixin QR poll failed for %s: %s", partner_id, exc, exc_info=True)+ attempt.status = "error"+ attempt.error = str(exc)+ return _public(attempt, session_id)++ previous = attempt.scan_payload+ await _apply_outcome(attempt, outcome)+ reply = _public(attempt, session_id)+ if attempt.scan_payload != previous:+ reply["qr_svg"] = render_qr_svg(attempt.scan_payload)+ return reply+++async def _apply_outcome(attempt: _Attempt, outcome: QrOutcome) -> None:+ if outcome.status == "scanned":+ attempt.status = "scanned"+ if outcome.poll_base_url:+ attempt.poll_base_url = outcome.poll_base_url+ return+ if outcome.status in {"waiting", "unknown"}:+ # `unknown` is a status this build does not recognise, not a failure:+ # keep the attempt alive so a new WeChat status string cannot end a+ # login that is actually still in progress.+ attempt.status = "waiting"+ return+ if outcome.status == "expired":+ attempt.refreshes += 1+ if attempt.refreshes > _MAX_REFRESHES:+ attempt.status = "expired"+ return+ await _reissue(attempt)+ return+ if outcome.status == "confirmed":+ attempt.token = outcome.token+ try:+ _persist_token(attempt.partner_id, outcome)+ except Exception as exc:+ logger.warning(+ "weixin login succeeded but the token could not be saved for %s: %s",+ attempt.partner_id,+ exc,+ exc_info=True,+ )+ attempt.status = "error"+ attempt.error = "The login succeeded but the token could not be saved."+ return+ attempt.status = "confirmed"+ return+ # `error` — WeChat confirmed the scan but handed back no token.+ attempt.status = "error"+ attempt.error = "WeChat confirmed the scan but returned no bot token."+++async def _reissue(attempt: _Attempt) -> None:+ """Swap in a fresh code so a slow scan is not a dead end."""+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(30, connect=15)) as client:+ code = await fetch_qr_code(+ client,+ attempt.poll_base_url,+ client_version=attempt.client_version,+ route_tag=attempt.route_tag,+ )+ except Exception as exc:+ logger.warning("weixin QR re-issue failed: %s", exc, exc_info=True)+ attempt.status = "expired"+ return+ attempt.qrcode_id = code.qrcode_id+ attempt.scan_payload = code.scan_payload+ attempt.status = "waiting"+++def current_scan_payload(partner_id: str, session_id: str) -> str:+ """What to draw right now — it changes when an expired code is re-issued."""+ with _lock:+ attempt = _attempts.get(session_id)+ if attempt is None or attempt.partner_id != partner_id:+ return ""+ return attempt.scan_payload+++def _persist_token(partner_id: str, outcome: QrOutcome) -> None:+ """Write the bot token into the partner's ``weixin`` channel config."""+ from deeptutor.services.partners.manager import get_partner_manager++ manager = get_partner_manager()+ existing = manager.load_config(partner_id)+ channels = dict(getattr(existing, "channels", None) or {})+ entry = dict(channels.get(CHANNEL) or {})+ entry["token"] = outcome.token+ if outcome.base_url:+ entry["base_url"] = outcome.base_url+ entry.setdefault("enabled", True)+ channels[CHANNEL] = entry+ # merge_config overlays and returns; save_config is what writes it down.+ merged = manager.merge_config(partner_id, {"channels": channels})+ manager.save_config(partner_id, merged)+++def forget(session_id: str) -> None:+ with _lock:+ _attempts.pop(session_id, None)+++__all__ = [+ "CHANNEL",+ "current_scan_payload",+ "forget",+ "poll_login",+ "start_login",+]diff --git a/deeptutor/services/persona/service.py b/deeptutor/services/persona/service.pyindex 01d6576b2..7c875dd88 100644--- a/deeptutor/services/persona/service.py+++ b/deeptutor/services/persona/service.py@@ -205,10 +205,17 @@ class PersonaService:body = body.strip()if not body:return ""+ # The scope sentence has to name capability playbooks, because they are+ # what a persona actually competes with. Mastery Path's playbook runs+ # 600 words and prescribes its own tone ("be warm and encouraging"),+ # sits above this block, and is plainly not a "generic style default" —+ # so a persona claiming only those was read as the weaker instruction+ # and the tutor stayed a stock teacher no matter what was written (#793).return ("## Active Persona\n"- "Embody the persona below for this entire conversation. "- "It overrides generic style defaults.\n\n"+ "Embody the persona below for this entire conversation. It sets your "+ "voice and outranks any tone a mode above prescribes; carry out that "+ "mode's steps in this voice.\n\n"f"### Persona: {detail.name}\n\n{body}")diff --git a/deeptutor/services/subagent/antigravity.py b/deeptutor/services/subagent/antigravity.pynew file mode 100644index 000000000..db31a5782--- /dev/null+++ b/deeptutor/services/subagent/antigravity.py@@ -0,0 +1,314 @@+"""Antigravity CLI backend — drive the local ``agy`` CLI in headless mode.++Google retired Gemini CLI on 2026-06-18 and pointed its users at Antigravity+CLI, so for anyone on a Google AI Pro/Ultra or Gemini Code Assist plan the+``gemini`` backend simply stopped having a CLI to detect (#828). This backend is+the replacement path. The old one is deliberately kept: Gemini CLI still runs+for anyone holding a Gemini API key, and a working connection must not break on+upgrade.++Invocation is ``agy -p <question> --output-format stream-json``. The event+vocabulary is the CLI's own and is *not* Gemini CLI's, despite the shared+lineage — events are tagged with ``event`` (not ``type``) and carry their body+in a same-named field:++* ``init`` — ``conversation_id`` plus ``init.{cwd,tools,permission_mode,model}``+* ``step_update`` — ``step_update.{step_index,state,step_type,text_delta,+ tool_name,tool_info,usage}``; assistant text arrives as ``text_delta`` chunks+ with no aggregate, so we accumulate per step index+* ``result`` — ``result.{status,response,num_turns,usage}``++Sessions resume with ``--conversation <conversation_id>`` (the id the ``init``+event hands back), the model is pinned with ``--model`` and reasoning depth with+``--effort low|medium|high``.++Permissions differ from Gemini CLI in a way worth stating: headless ``agy``+*soft-denies* tools that would need approval rather than blocking on them, so an+unattended run degrades instead of hanging. That makes the cautious mapping the+correct default — only the explicitly permissive modes pass+``--dangerously-skip-permissions``.++⚠️ Upstream issue google-antigravity/antigravity-cli#76: ``-p`` has been+reported to emit nothing at all when stdout is not a TTY, which is exactly how+this backend runs it. It is a plain-print bug and ``--output-format stream-json``+takes a different output path, but if a build regresses the whole stream, a+consult would otherwise look like the agent answering with silence. So an empty+stream is reported as a failure that names the cause — see ``_EMPTY_STREAM_HINT``.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.process import (+ not_found_detail,+ probe_version,+ stream_process_lines,+)+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++logger = logging.getLogger(__name__)++_NOT_FOUND_DETAIL = (+ "Antigravity CLI (agy) not found on PATH. Install it from https://antigravity.google/docs/cli."+)++_MAX_FIELD_CHARS = 4000+_TOOL_HEADER_CHARS = 160++# Stored permission modes use Claude Code's spellings as the shared vocabulary.+# Only the two permissive ones waive approval; `default` and `plan` leave the+# CLI's soft-deny in place, which is safe here precisely because soft-deny does+# not stall a headless run.+_SKIP_PERMISSION_MODES = frozenset({"bypassPermissions", "acceptEdits"})++# `--effort` accepts exactly these; anything else is dropped rather than passed+# through to a non-zero exit on an unknown value.+_EFFORTS = frozenset({"low", "medium", "high"})++# Terminal statuses the CLI reports in its `result` event.+_FAILED_STATUSES = frozenset({"ERROR", "CANCELED", "INTERRUPTED", "INVALID"})++_EMPTY_STREAM_HINT = (+ "agy produced no output. If it answers normally in a terminal but not here, "+ "this is antigravity-cli#76 (stdout suppressed when not a TTY); upgrade the CLI."+)++# The salient argument to put in a tool header — `Shell(cmd …)` rather than raw+# JSON, matching how the other CLI backends render their tool rows.+_TOOL_PRIMARY_ARGS = (+ "command",+ "file_path",+ "path",+ "pattern",+ "query",+ "url",+ "prompt",+ "description",+)+++def _parse_json(line: str) -> dict[str, Any] | None:+ try:+ parsed = json.loads(line)+ except (json.JSONDecodeError, ValueError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def _clip(text: str, limit: int = _MAX_FIELD_CHARS) -> str:+ return text if len(text) <= limit else f"{text[:limit]}…"+++def _tool_header(name: str, info: Any) -> str:+ """``name(salient arg)`` for the sidebar row."""+ if not isinstance(info, dict):+ return name+ args = info.get("args") if isinstance(info.get("args"), dict) else info+ for key in _TOOL_PRIMARY_ARGS:+ value = args.get(key) if isinstance(args, dict) else None+ if isinstance(value, str) and value.strip():+ return f"{name}({_clip(value.strip(), _TOOL_HEADER_CHARS)})"+ return name+++class AntigravityBackend(SubagentBackend):+ """Consult Google's Antigravity CLI (``agy``) as a subagent."""++ kind = "antigravity"+ display_name = "Antigravity CLI"+ cli_command = "agy"++ async def detect(self) -> DetectResult:+ ok, text = await probe_version([self.cli_command, "--version"])+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=ok,+ version=text if ok else "",+ detail="" if ok else not_found_detail(text, _NOT_FOUND_DETAIL),+ )++ def _build_command(+ self,+ question: str,+ *,+ session_id: str | None,+ config: BackendConfig,+ images: list[str] | None = None,+ ) -> list[str]:+ prompt = question+ # No system-prompt flag, so the delegate instruction is prepended once on+ # the session-creating consult; a resumed conversation already carries it.+ if config.system_prompt.strip() and not session_id:+ prompt = f"{config.system_prompt.strip()}\n\n{question}"+ # Headless `agy` documents no attachment flag, so images are named as+ # paths and left to the agent's own file-reading tools — the same+ # arrangement Claude Code uses.+ if images:+ listing = "\n".join(images)+ prompt = f"{prompt}\n\nAttached image files (read them from disk):\n{listing}"+ cmd = [+ self.cli_command,+ "-p",+ prompt,+ "--output-format",+ "stream-json",+ ]+ if config.permission_mode in _SKIP_PERMISSION_MODES:+ cmd.append("--dangerously-skip-permissions")+ if session_id:+ cmd += ["--conversation", session_id]+ if config.model:+ cmd += ["--model", config.model]+ if config.effort in _EFFORTS:+ cmd += ["--effort", config.effort]+ cmd += list(config.extra_args)+ return cmd++ async def consult(+ self,+ question: str,+ *,+ on_event: OnEvent,+ cwd: str | None = None,+ session_id: str | None = None,+ config: BackendConfig | None = None,+ images: list[str] | None = None,+ partner_id: str | None = None, # noqa: ARG002 — partner-only; ignored here+ ) -> ConsultResult:+ config = config or BackendConfig()+ cmd = self._build_command(question, session_id=session_id, config=config, images=images)+ result = ConsultResult(session_id=session_id)+ # Assistant text arrives as `text_delta` chunks with no aggregate, so+ # accumulate per step index; a step that is not text closes the current+ # block, letting post-tool prose stream as its own row.+ stream: dict[str, Any] = {"blocks": [], "open_step": None}+ saw_stream_event = False++ async def emit(+ kind: str, text: str, raw: dict[str, Any], meta: dict[str, Any] | None = None+ ) -> None:+ result.event_count += 1+ await on_event(SubagentEvent(kind=kind, text=text, raw=raw, meta=meta or {}))++ try:+ async for channel, line in stream_process_lines(cmd, cwd=cwd):+ if channel == "exit":+ if line != "0" and result.success and not result.final_text:+ result.success = False+ result.error = f"agy exited with code {line}"+ await emit(EVENT_ERROR, result.error, {"returncode": line})+ continue+ if channel == "stderr":+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stderr"})+ continue+ event = _parse_json(line)+ if event is None:+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stdout"})+ continue+ saw_stream_event = True+ await self._handle_event(event, result, stream, emit)+ except Exception as exc: # pragma: no cover - defensive: surface, don't crash the turn+ logger.warning("antigravity consult failed: %s", exc, exc_info=True)+ result.success = False+ result.error = str(exc)+ await emit(EVENT_ERROR, str(exc), {})++ if not result.final_text:+ result.final_text = "\n\n".join(b for b in stream["blocks"] if b.strip()).strip()+ # Silence is not an answer: name the known cause rather than handing the+ # caller an empty reply that reads like the agent had nothing to say.+ if result.success and not result.final_text and not saw_stream_event:+ result.success = False+ result.error = _EMPTY_STREAM_HINT+ await emit(EVENT_ERROR, result.error, {})+ return result++ async def _handle_event(+ self,+ event: dict[str, Any],+ result: ConsultResult,+ stream: dict[str, Any],+ emit: Any,+ ) -> None:+ name = str(event.get("event") or "")+ body = event.get(name)+ body = body if isinstance(body, dict) else {}++ # Every event carries the conversation id; the `init` one is simply the+ # first, and taking it wherever it appears keeps resume working even if a+ # build stops emitting `init`.+ conversation = str(event.get("conversation_id") or body.get("conversation_id") or "")+ if conversation:+ result.session_id = conversation++ if name == "init":+ model = str(body.get("model") or "")+ await emit(EVENT_LOG, f"Session started{f' · {model}' if model else ''}", event)+ return++ if name == "step_update":+ await self._handle_step(body, stream, emit, event)+ return++ if name == "result":+ status = str(body.get("status") or "").upper()+ response = str(body.get("response") or "")+ if response:+ result.final_text = response+ if status in _FAILED_STATUSES:+ result.success = False+ result.error = str(body.get("error") or "") or f"agy reported status {status}"+ await emit(EVENT_ERROR, result.error, event)+ return++ async def _handle_step(+ self,+ step: dict[str, Any],+ stream: dict[str, Any],+ emit: Any,+ raw: dict[str, Any],+ ) -> None:+ index = step.get("step_index")+ delta = str(step.get("text_delta") or "")+ tool_name = str(step.get("tool_name") or "")++ if delta:+ if stream["open_step"] != index:+ stream["blocks"].append("")+ stream["open_step"] = index+ stream["blocks"][-1] += delta+ await emit(EVENT_TEXT, delta, raw, {"partial": True, "step": index})+ return++ if tool_name:+ # A tool ends the current text block so later prose starts a new row.+ stream["open_step"] = None+ info = step.get("tool_info")+ state = str(step.get("state") or "").upper()+ if state == "DONE":+ output = ""+ if isinstance(info, dict):+ output = str(info.get("result") or info.get("output") or "")+ await emit(EVENT_TOOL_RESULT, _clip(output), raw, {"tool": tool_name})+ else:+ await emit(EVENT_TOOL, _tool_header(tool_name, info), raw, {"tool": tool_name})+++__all__ = ["AntigravityBackend"]diff --git a/deeptutor/services/subagent/gemini.py b/deeptutor/services/subagent/gemini.pyindex b01154f6d..cdccf3584 100644--- a/deeptutor/services/subagent/gemini.py+++ b/deeptutor/services/subagent/gemini.py@@ -29,7 +29,11 @@ from typing import Anyfrom deeptutor.services.subagent.base import OnEvent, SubagentBackendfrom deeptutor.services.subagent.config import BackendConfig-from deeptutor.services.subagent.process import probe_version, stream_process_lines+from deeptutor.services.subagent.process import (+ not_found_detail,+ probe_version,+ stream_process_lines,+)from deeptutor.services.subagent.types import (EVENT_ERROR,EVENT_LOG,@@ -43,6 +47,16 @@ from deeptutor.services.subagent.types import (logger = logging.getLogger(__name__)+# Google retired Gemini CLI on 2026-06-18 for Google AI Pro/Ultra and Gemini+# Code Assist users, so "not found" is now the expected state for most people+# rather than a mistake. Say where the CLI went instead of leaving them to work+# out why a CLI they used to have stopped being detected (#828).+GEMINI_NOT_FOUND_DETAIL = (+ "gemini CLI not found on PATH. Google retired Gemini CLI on 2026-06-18 for "+ "plan-based accounts — connect Antigravity CLI (agy) instead. Gemini CLI "+ "still works with a Gemini API key."+)+_MAX_FIELD_CHARS = 4000_TOOL_HEADER_CHARS = 160@@ -83,7 +97,7 @@ class GeminiBackend(SubagentBackend):display_name=self.display_name,available=ok,version=text if ok else "",- detail="" if ok else (text or "gemini CLI not found on PATH"),+ detail="" if ok else not_found_detail(text, GEMINI_NOT_FOUND_DETAIL),)def _build_command(diff --git a/deeptutor/services/subagent/models.py b/deeptutor/services/subagent/models.pyindex b2217ba0b..2bf067101 100644--- a/deeptutor/services/subagent/models.py+++ b/deeptutor/services/subagent/models.py@@ -34,7 +34,11 @@ from pathlib import Pathimport refrom typing import Any-from deeptutor.services.subagent.process import probe_version, resolve_cli_command+from deeptutor.services.subagent.process import (+ not_found_detail,+ probe_version,+ resolve_cli_command,+)from deeptutor.services.subagent.registry import get_backendlogger = logging.getLogger(__name__)@@ -59,6 +63,9 @@ _GEMINI_MODELS = (("flash-lite", "Gemini Flash-Lite"),)+# Antigravity CLI: ``--effort`` accepts exactly these three.+_ANTIGRAVITY_EFFORTS = ("low", "medium", "high")+# opencode family: ``--variant`` — provider-relative reasoning effort._OPENCODE_EFFORTS = ("minimal", "high", "max")@@ -209,6 +216,8 @@ async def _probe(kind: str) -> tuple[bool, str]:async def _gemini_options() -> BackendOptions:+ from deeptutor.services.subagent.gemini import GEMINI_NOT_FOUND_DETAIL+ok, version = await _probe("gemini")return BackendOptions(kind="gemini",@@ -218,7 +227,28 @@ async def _gemini_options() -> BackendOptions:models=[ModelOption(slug=slug, display_name=name) for slug, name in _GEMINI_MODELS],efforts=[], # no reasoning-effort flagallow_custom_model=True,- detail="" if ok else (version or "gemini CLI not found on PATH"),+ detail="" if ok else not_found_detail(version, GEMINI_NOT_FOUND_DETAIL),+ )+++async def _antigravity_options() -> BackendOptions:+ from deeptutor.services.subagent.antigravity import (+ _NOT_FOUND_DETAIL as _ANTIGRAVITY_NOT_FOUND,+ )++ ok, version = await _probe("antigravity")+ return BackendOptions(+ kind="antigravity",+ display_name="Antigravity CLI",+ available=ok,+ version=version if ok else "",+ # `agy models` prints the live list, and the slugs move with the Gemini+ # releases behind them; naming a stale set here would be worse than+ # letting the operator paste the one they ran.+ models=[],+ efforts=list(_ANTIGRAVITY_EFFORTS),+ allow_custom_model=True,+ detail="" if ok else not_found_detail(version, _ANTIGRAVITY_NOT_FOUND),)@@ -299,6 +329,7 @@ _PROVIDERS: dict[str, Callable[..., Awaitable[BackendOptions]]] = {"claude_code": _claude_options,"codex": _codex_options,"gemini": _gemini_options,+ "antigravity": _antigravity_options,"kimi": _kimi_options,"opencode": _opencode_options,"mimo": _mimo_options,diff --git a/deeptutor/services/subagent/process.py b/deeptutor/services/subagent/process.pyindex 605d089a1..af8938fb8 100644--- a/deeptutor/services/subagent/process.py+++ b/deeptutor/services/subagent/process.py@@ -138,6 +138,19 @@ async def _terminate(process: asyncio.subprocess.Process) -> None:await process.wait()+def not_found_detail(probe_text: str, fallback: str) -> str:+ """What to show a reader when a CLI probe failed.++ :func:`probe_version` reports a bare ``"not installed"`` for a missing+ binary, which repeats what the status chip already says and crowds out the+ backend's own guidance — every caller writing ``version or "<cli> not found+ on PATH"`` was in fact unreachable for the common case. Real probe output (a+ version banner, a permission error) is more informative and still wins.+ """+ text = (probe_text or "").strip()+ return fallback if text in ("", "not installed") else text++async def probe_version(cmd: Sequence[str], *, timeout: float = 8.0) -> tuple[bool, str]:"""Run a fast ``--version``-style probe; return ``(ok, stdout-or-error)``.@@ -165,4 +178,10 @@ async def probe_version(cmd: Sequence[str], *, timeout: float = 8.0) -> tuple[boreturn process.returncode == 0, text-__all__ = ["ProcessLine", "resolve_cli_command", "stream_process_lines", "probe_version"]+__all__ = [+ "ProcessLine",+ "not_found_detail",+ "probe_version",+ "resolve_cli_command",+ "stream_process_lines",+]diff --git a/deeptutor/services/subagent/registry.py b/deeptutor/services/subagent/registry.pyindex 42decad81..1c1e8100f 100644--- a/deeptutor/services/subagent/registry.py+++ b/deeptutor/services/subagent/registry.py@@ -2,7 +2,8 @@Add a new subagent by writing a :class:`SubagentBackend` and listing it here;the capability, API and UI all discover it through these helpers. Local-CLI-backends (Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code) and+backends (Claude Code, Codex, Gemini CLI, Antigravity CLI, Kimi CLI, opencode,+MiMo Code) andthe in-process partner backend live in the same registry but are told apart by``local_cli`` — only CLIs are detected on the machine and offered in theconnect-CLI modal.@@ -12,6 +13,7 @@ from __future__ import annotationsimport asyncio+from deeptutor.services.subagent.antigravity import AntigravityBackendfrom deeptutor.services.subagent.base import SubagentBackendfrom deeptutor.services.subagent.claude_code import ClaudeCodeBackendfrom deeptutor.services.subagent.codex import CodexBackend@@ -27,6 +29,7 @@ _BACKENDS: dict[str, SubagentBackend] = {ClaudeCodeBackend(),CodexBackend(),GeminiBackend(),+ AntigravityBackend(),KimiBackend(),OpencodeBackend(),MimoBackend(),diff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.ymlindex c73df472b..a3bca69ab 100644--- a/docker-compose.ghcr.yml+++ b/docker-compose.ghcr.yml@@ -56,6 +56,22 @@ services:# CONTAINERIZATION.md → "One-time migration".- ./data:/app/data+ # Optional dependencies, re-applied on every start (#762). This image+ # ships the base install; anything added with `docker exec … pip install`+ # or `apt-get install` lives in the container's writable layer and is+ # discarded on the next `compose down`. Declaring it here instead makes it+ # a property of the deployment, so every container started from this file+ # has it. Both steps are idempotent (a warm container only pays a check)+ # and neither is fatal — a package that fails to install leaves that one+ # feature unavailable rather than stopping the app. The pip cache lives on+ # the data volume above, so a recreate reuses the downloads it already+ # paid for. Preview an extra with+ # `python scripts/install_extras.py --dry-run "<name>"`. Uncomment the+ # `environment:` key together with the entries under it.+ # environment:+ # - DEEPTUTOR_EXTRAS=math-animator,partners+ # - DEEPTUTOR_APT_PACKAGES=ffmpeg+healthcheck:test: ["CMD", "curl", "-f", "http://localhost:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}/"]interval: 30sdiff --git a/docker-compose.yml b/docker-compose.ymlindex e4a048349..4c2b228e1 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -82,6 +82,15 @@ services:# DEEPTUTOR_SANDBOX_ALLOW_SUBPROCESS=1, a restricted subprocess.- DEEPTUTOR_SANDBOX_RUNNER_URL=http://sandbox-runner:8900+ # Optional dependencies, re-applied on every start (#762). Installing+ # these with `docker exec` does not survive `compose down`, so declare+ # them here instead. Both are idempotent and never fatal; the pip cache+ # lives on the data volume, so a rebuild reuses what it already fetched.+ # Extras come from pyproject.toml — preview one with+ # `python scripts/install_extras.py --dry-run "<name>"`.+ # - DEEPTUTOR_EXTRAS=math-animator,partners+ # - DEEPTUTOR_APT_PACKAGES=ffmpeg+healthcheck:test: ["CMD", "curl", "-f", "http://localhost:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}/"]interval: 30sdiff --git a/scripts/install_extras.py b/scripts/install_extras.pynew file mode 100644index 000000000..3b8afabd4--- /dev/null+++ b/scripts/install_extras.py@@ -0,0 +1,150 @@+"""Make a container's declared optional dependencies true again at every start.++A Docker container is disposable, so `docker exec … pip install ".[partners]"`+survives exactly until the next `docker compose down` (#762). The fix is to+stop treating extras as something you *do* to a running container and make them+something the deployment *declares*: set ``DEEPTUTOR_EXTRAS`` in the Compose+file, and every container that starts from it has them.++Two things keep this cheap enough to run on the startup path:++* it reads the extra's requirement list out of ``pyproject.toml`` and installs+ those, rather than reinstalling ``deeptutor`` itself to pull them in;+* an extra whose requirements are already importable-and-satisfied costs one+ metadata lookup per requirement, so a warm container starts as fast as it did+ before.++Never fatal. A missing wheel or an offline registry degrades the same feature+that was already unavailable — it must not take a working deployment offline+with it, so failures are reported and the process still exits 0.+"""++from __future__ import annotations++import argparse+from pathlib import Path+import re+import subprocess+import sys+import tomllib++# Compose values arrive as one string; accept the spellings people actually+# write ("a,b", "a, b", "a b") rather than making the separator a gotcha.+_SPLIT_RE = re.compile(r"[,\s]+")+++def parse_names(raw: str) -> list[str]:+ """Split a declaration into names, de-duplicated and order-preserving."""+ seen: dict[str, None] = {}+ for name in _SPLIT_RE.split(raw or ""):+ cleaned = name.strip()+ if cleaned:+ seen.setdefault(cleaned, None)+ return list(seen)+++def load_extras(pyproject: Path) -> dict[str, list[str]]:+ """``{extra: [requirement, …]}`` as declared by the project."""+ with open(pyproject, "rb") as handle:+ data = tomllib.load(handle)+ optional = data.get("project", {}).get("optional-dependencies", {})+ return {+ str(name): [str(req) for req in reqs]+ for name, reqs in optional.items()+ if isinstance(reqs, list)+ }+++def missing_requirements(requirements: list[str]) -> list[str]:+ """The subset not already satisfied in this interpreter.++ A requirement we cannot parse counts as missing: handing it to pip and+ letting pip decide is right more often than silently skipping it.+ """+ from importlib.metadata import PackageNotFoundError, version++ from packaging.requirements import Requirement++ missing: list[str] = []+ for raw in requirements:+ try:+ requirement = Requirement(raw)+ except Exception:+ missing.append(raw)+ continue+ if requirement.marker is not None and not requirement.marker.evaluate():+ continue+ try:+ installed = version(requirement.name)+ except PackageNotFoundError:+ missing.append(raw)+ continue+ if requirement.specifier and installed not in requirement.specifier:+ missing.append(raw)+ return missing+++def resolve(extras: dict[str, list[str]], names: list[str]) -> tuple[list[str], list[str]]:+ """``(requirements to install, unknown extra names)``."""+ wanted: list[str] = []+ unknown: list[str] = []+ for name in names:+ # Extras normalise dashes and underscores; accept either spelling.+ key = next((k for k in extras if k.replace("_", "-") == name.replace("_", "-")), None)+ if key is None:+ unknown.append(name)+ continue+ wanted.extend(extras[key])+ return wanted, unknown+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("names", nargs="?", default="", help="extras, comma- or space-separated")+ parser.add_argument("--pyproject", default="pyproject.toml", type=Path)+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="report what would be installed and change nothing",+ )+ args = parser.parse_args(argv)++ names = parse_names(args.names)+ if not names:+ return 0++ try:+ extras = load_extras(args.pyproject)+ except Exception as exc:+ print(f" ⚠️ Could not read {args.pyproject}: {exc}")+ return 0++ requirements, unknown = resolve(extras, names)+ for name in unknown:+ print(f" ⚠️ Unknown extra '{name}'. Available: {', '.join(sorted(extras))}")+ if not requirements:+ return 0++ missing = missing_requirements(requirements)+ if not missing:+ print(f" ✅ Extras already satisfied: {', '.join(names)}")+ return 0++ if args.dry_run:+ print(f" 📦 Would install {len(missing)} package(s) for {', '.join(names)}:")+ for requirement in missing:+ print(f" {requirement}")+ return 0++ print(f" 📦 Installing {len(missing)} package(s) for: {', '.join(names)}")+ result = subprocess.run(+ [sys.executable, "-m", "pip", "install", "--no-input", *missing],+ check=False,+ )+ if result.returncode != 0:+ print(f" ⚠️ pip exited {result.returncode}; the extras above stay unavailable.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/api/test_capabilities_router.py b/tests/api/test_capabilities_router.pynew file mode 100644index 000000000..cd868ca5b--- /dev/null+++ b/tests/api/test_capabilities_router.py@@ -0,0 +1,70 @@+"""API surface tests for /api/v1/capabilities/registered.++The endpoint exists so a page can ask whether the capability it is about to+send actually exists here (#963): Whisper ships its pages in this repository+but its ``whisper_visitor`` / ``whisper_trainee`` capability comes from an+out-of-tree plugin, and a stock install used to offer the room anyway.+"""++from __future__ import annotations++import pytest++try:+ from fastapi import FastAPI+ from fastapi.testclient import TestClient+except Exception: # pragma: no cover+ FastAPI = None+ TestClient = None++pytestmark = pytest.mark.skipif(+ FastAPI is None or TestClient is None, reason="fastapi not installed"+)+++def client() -> TestClient:+ from deeptutor.api.routers import capabilities++ app = FastAPI()+ app.include_router(capabilities.router, prefix="/api/v1/capabilities")+ return TestClient(app)+++def test_registered_lists_the_builtin_capabilities(client) -> None:+ """The names a turn can be started with, sorted and de-duplicated."""+ from deeptutor.runtime.bootstrap.builtin_capabilities import BUILTIN_CAPABILITY_CLASSES++ body = client.get("/api/v1/capabilities/registered").json()+ names = body["capabilities"]++ assert names == sorted(names)+ assert set(BUILTIN_CAPABILITY_CLASSES) <= set(names)+++def test_a_stock_install_reports_whisper_missing(client) -> None:+ """#963: without the psych-academy plugin the seats are not startable.++ The page gates its entry on exactly this answer, so if Whisper ever moves+ in-tree this test failing is the signal to drop the gate — not to loosen+ the assertion.+ """+ names = client.get("/api/v1/capabilities/registered").json()["capabilities"]++ assert "whisper_visitor" not in names+ assert "whisper_trainee" not in names+++def test_plugin_capabilities_are_reported(client, monkeypatch) -> None:+ """A registered plugin capability is visible, which is what un-gates a page."""+ from deeptutor.runtime.registry import capability_registry as registry_module++ class _StubCapability:+ name = "whisper_visitor"++ registry = registry_module.get_capability_registry()+ monkeypatch.setitem(registry._capabilities, "whisper_visitor", _StubCapability())++ names = client.get("/api/v1/capabilities/registered").json()["capabilities"]++ assert "whisper_visitor" in namesdiff --git a/tests/api/test_partners_router.py b/tests/api/test_partners_router.pyindex 7947d125f..34e014dd6 100644--- a/tests/api/test_partners_router.py+++ b/tests/api/test_partners_router.py@@ -204,23 +204,36 @@ class TestChannelOnboarding:)assert cancelled.json()["status"] == "cancelled"- def test_onboarding_routes_inherit_the_full_partners_admin_gate(self, monkeypatch):- """The real app must gate the onboarding routes on *admin*, not just auth.-- The ``client`` fixture above mounts the partners router *without* the- admin dependency so the endpoint tests can drive it directly, so- nothing else in this file would notice if ``main.py`` stopped applying- the gate.-- Asserted by sending a valid **non-admin** token and requiring 403,- rather than by inspecting ``app.routes``: FastAPI 0.141 stopped- flattening ``include_router`` into the parent app (it keeps the- sub-router nested behind ``include_context``), so every structural- assertion available here holds on only one side of this project's own- ``fastapi>=0.100.0`` range. A response code does not care how the- router is represented. An unauthenticated request would not do:- ``require_auth`` alone answers that with 401, so downgrading the- router from ``_admin`` to ``_auth`` would still look gated.+ def test_onboarding_routes_carry_the_partner_manage_gate(self, monkeypatch):+ """The real app must gate the onboarding routes on *manage*, not just auth.++ These routes write a channel bot token into the partner's config, so+ they belong to whoever may configure the partner — its owner or an+ admin — never to any signed-in account that knows the id. Partners+ stopped being a blanket admin resource in v1.5.17: ``main.py`` mounts+ the router under ``_auth`` and each route declares ``_USABLE`` or+ ``_MANAGEABLE`` for the partner it names. That per-route declaration is+ easy to forget on a new route, and this is what notices.++ The ``client`` fixture above mounts the partners router *without* those+ dependencies so the endpoint tests can drive it directly, so nothing+ else in this file would notice if the gate went missing.++ Asserted by sending a valid **non-admin** token, rather than by+ inspecting ``app.routes``: FastAPI 0.141 stopped flattening+ ``include_router`` into the parent app (it keeps the sub-router nested+ behind ``include_context``), so every structural assertion available+ here holds on only one side of this project's own ``fastapi>=0.100.0``+ range. A response code does not care how the router is represented.++ The body is deliberately invalid, which is what makes the assertion+ sharp. A gated route rejects the caller in a dependency, before the+ body is ever validated — 404 when the partner is unknown *or* invisible+ (``usable_partner`` answers both alike so ids cannot be enumerated),+ 403 when it is visible but not theirs. An **ungated** route would reach+ body validation and answer 422, and an unauthenticated request would+ not discriminate at all: ``require_auth`` alone answers 401, so a route+ that had lost its partner gate would still look protected."""from deeptutor.api import main as api_mainfrom deeptutor.api.routers import auth as auth_module@@ -232,27 +245,71 @@ class TestChannelOnboarding:for route in partners_module.router.routes)- # ``require_admin`` waves everything through when auth is disabled,- # which is the default in tests — turn it on so the gate is observable.+ # The gates wave everything through when auth is disabled, which is the+ # default in tests — turn it on so they are observable.monkeypatch.setattr(auth_module, "AUTH_ENABLED", True)# ``decode_token`` refuses every token when no secret is configured,# which is the state of a bare test environment — without this the- # request would 401 and the assertion below could not tell an- # admin-only route from a merely authenticated one.+ # request would 401 and the assertion below could not tell a gated+ # route from a merely authenticated one.monkeypatch.setattr(auth_service, "AUTH_SECRET", "test-secret")monkeypatch.setattr(auth_service, "POCKETBASE_ENABLED", False)token = auth_service.create_token("not-an-admin", role="user", user_id="u-1")# No context manager: this must not run the app's lifespan.client = TestClient(api_main.app)response = client.post(- "/api/v1/partners/ada/channel-onboarding/start",+ "/api/v1/partners/no-such-partner/channel-onboarding/start",json={},headers={"Authorization": f"Bearer {token}"},)- assert response.status_code == 403, (- f"onboarding start is not admin-gated (a role=user token got {response.status_code})"+ assert response.status_code in (403, 404), (+ "onboarding start is not manage-gated (a role=user token got "+ f"{response.status_code}; 422 means the request reached body validation, "+ "so the route is mounted without _MANAGEABLE)")+ def test_every_route_naming_a_partner_declares_its_rights(self):+ """No ``{partner_id}`` route may be left to the router's bare ``_auth``.++ The test above cannot tell ``_USABLE`` from ``_MANAGEABLE``: both+ answer an outsider with 404. This one can, and it sweeps the whole+ router rather than the routes someone remembered to test — which is+ the shape the mistake actually takes. When partners stopped being+ admin-only, six credential routes kept the ``_auth``-only mount they+ had inherited from the blanket gate, and any signed-in account could+ write a channel bot token into anyone's partner.++ Introspection is safe here because it reads the router's *own*+ ``routes``, not the mounted app's: the FastAPI 0.141 nesting change+ that rules out asserting against ``api_main.app`` does not touch this.+ """+ from deeptutor.api.routers import partners as partners_module++ # Writing or reading channel credentials is configuration, so these+ # must be manage-gated specifically; use rights are not enough.+ manage_only = ("/channel-onboarding", "/channels/weixin/qr", "/soul", "/assets")++ ungated: list[str] = []+ under_gated: list[str] = []+ for route in partners_module.router.routes:+ path = getattr(route, "path", "")+ if "{partner_id}" not in path:+ continue+ # The socket cannot run HTTP dependencies; it checks by hand.+ if not getattr(route, "methods", None):+ continue+ names = {+ getattr(dep.dependency, "__name__", "")+ for dep in getattr(route, "dependencies", [])+ }+ if not names & {"usable_partner", "manageable_partner"}:+ ungated.append(path)+ elif any(part in path for part in manage_only) and "manageable_partner" not in names:+ under_gated.append(path)++ assert not ungated, f"partner routes with no use/manage gate: {ungated}"+ assert not under_gated, f"configuration routes gated on use, not manage: {under_gated}"+def test_duplicate_id_conflicts(self, client):assert _create(client).status_code == 200assert _create(client).status_code == 409diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.pyindex a20a3a54d..022f2a08d 100644--- a/tests/capabilities/test_mastery_capability.py+++ b/tests/capabilities/test_mastery_capability.py@@ -411,3 +411,61 @@ async def test_recording_tools_refuse_an_unbuilt_path_without_creating_it(tmp_paassert result.success is Falseassert "mastery_paths" in result.contentassert LearningStore().list_all() == []+++async def test_a_switch_and_a_build_in_one_round_land_on_the_switched_path(tmp_path, monkeypatch):+ """The regression behind "my paths contaminate each other".++ Every tool call in a round has its arguments bound before any of them runs,+ so a ``mastery_switch`` + ``mastery_build`` round used to rebuild the map of+ the path the conversation was *leaving*: the learner edited path B's map and+ watched path A's map change instead. Driven through the real dispatcher so+ the ordering contract, not just the tool, is under test.+ """+ from deeptutor.core.agentic.tool_dispatch import dispatch_tool_calls++ _use_store_root(monkeypatch, tmp_path)+ LearningStore().save(_built_path("path-a", name="Path A"))+ LearningStore().save(_built_path("path-b", name="Path B"))++ context = UnifiedContext(+ user_message="switch to path B and rebuild its map",+ session_id="session-1",+ metadata={"mastery_mode": True, "mastery_path_id": "path-a", "turn_id": "turn-1"},+ )+ capability = MasteryLoopCapability()+ pipeline = AgenticChatPipeline(language="en")++ await dispatch_tool_calls(+ tool_calls=[+ {+ "id": "c1",+ "name": "mastery_build",+ "arguments": json.dumps(+ {+ "mode": "replace",+ "modules": [+ {+ "name": "Rebuilt module",+ "knowledge_points": [{"name": "New objective"}],+ }+ ],+ }+ ),+ },+ {"id": "c2", "name": "mastery_switch", "arguments": '{"path_id": "path-b"}'},+ ],+ context=context,+ stream=StreamBus(),+ source="chat",+ stage="responding",+ iteration_index=0,+ kwarg_augmenter=pipeline._augment_tool_kwargs,+ rebinding_tools=frozenset(capability.rebinding_tools),+ )++ store = LearningStore()+ assert [m.name for m in store.load("path-b").modules] == ["Rebuilt module"]+ # The path the turn started on is untouched.+ assert [m.name for m in store.load("path-a").modules] == ["Path A"]diff --git a/tests/core/agentic/test_tool_dispatch_pause_ordering.py b/tests/core/agentic/test_tool_dispatch_pause_ordering.pyindex 62ca10117..0b2652fa4 100644--- a/tests/core/agentic/test_tool_dispatch_pause_ordering.py+++ b/tests/core/agentic/test_tool_dispatch_pause_ordering.py@@ -117,3 +117,94 @@ async def test_results_stay_paired_with_their_tool_calls() -> None:("c2", "rag-done"),("c3", "web_search-done"),]+++class _PathRegistry:+ """Stands in for the mastery path binding: switch moves it, writes follow it."""++ def __init__(self) -> None:+ self.order: list[str] = []+ self.active = "path-a"+ self.written_to: list[str] = []++ async def execute(self, name: str, **kwargs: Any) -> ToolResult:+ self.order.append(name)+ if name == "mastery_switch":+ self.active = str(kwargs.get("path_id") or self.active)+ if name == "mastery_build":+ self.written_to.append(str(kwargs.get("_mastery_path_id") or ""))+ return ToolResult(content="ok", success=True)+++async def _dispatch_with_rebinding(+ registry: _PathRegistry, tool_calls: list[dict[str, Any]]+) -> None:+ def augment(tool_name: str, tool_args: dict[str, Any], _ctx: UnifiedContext) -> dict[str, Any]:+ if tool_name.startswith("mastery_"):+ return {**tool_args, "_mastery_path_id": registry.active}+ return dict(tool_args)++ await dispatch_tool_calls(+ tool_calls=tool_calls,+ context=UnifiedContext(session_id="s1", user_message="hi"),+ stream=StreamBus(),+ source="chat",+ stage="responding",+ iteration_index=0,+ registry=registry,+ kwarg_augmenter=augment,+ rebinding_tools=frozenset({"mastery_switch"}),+ )+++async def test_a_rebinding_tool_runs_first_and_its_round_mates_follow_it() -> None:+ """A switch + build round must build the path it switched TO, not FROM."""+ registry = _PathRegistry()++ await _dispatch_with_rebinding(+ registry,+ [+ {"id": "c1", "name": "mastery_build", "arguments": "{}"},+ {"id": "c2", "name": "mastery_switch", "arguments": '{"path_id": "path-b"}'},+ ],+ )++ assert registry.order == ["mastery_switch", "mastery_build"]+ assert registry.written_to == ["path-b"]+++async def test_a_pausing_tool_still_runs_after_a_rebound_round() -> None:+ registry = _PathRegistry()++ await _dispatch_with_rebinding(+ registry,+ [+ {"id": "c1", "name": "ask_user", "arguments": "{}"},+ {"id": "c2", "name": "mastery_build", "arguments": "{}"},+ {"id": "c3", "name": "mastery_switch", "arguments": '{"path_id": "path-b"}'},+ ],+ )++ assert registry.order == ["mastery_switch", "mastery_build", "ask_user"]+++async def test_declaring_no_rebinding_tools_leaves_the_round_concurrent() -> None:+ registry = _PathRegistry()++ await dispatch_tool_calls(+ tool_calls=[+ {"id": "c1", "name": "mastery_build", "arguments": "{}"},+ {"id": "c2", "name": "mastery_switch", "arguments": '{"path_id": "path-b"}'},+ ],+ context=UnifiedContext(session_id="s1", user_message="hi"),+ stream=StreamBus(),+ source="chat",+ stage="responding",+ iteration_index=0,+ registry=registry,+ )++ assert sorted(registry.order) == ["mastery_build", "mastery_switch"]diff --git a/tests/multi_user/test_partner_access.py b/tests/multi_user/test_partner_access.pyindex 77eaa5904..5cd1852d1 100644--- a/tests/multi_user/test_partner_access.py+++ b/tests/multi_user/test_partner_access.py@@ -16,6 +16,12 @@ class _FakeManager:def list_partners(self) -> list[dict]:return self._partners+ def owner_id(self, partner_id: str) -> str:+ for partner in self._partners:+ if partner.get("partner_id") == partner_id:+ return str(partner.get("owner_id") or "")+ return ""+def _patch_manager(monkeypatch, partners: list[dict]) -> None:import deeptutor.services.partners as pkg@@ -119,6 +125,74 @@ def test_non_admin_with_no_grant_sees_nothing(as_user, monkeypatch):assert partner_access.visible_partner_cards() == []+# ── ownership ─────────────────────────────────────────────────+++def test_owner_may_manage_and_use_their_own_partner(as_user, monkeypatch):+ _patch_manager(monkeypatch, [{"partner_id": "p1", "name": "P1", "owner_id": "u_alice"}])+ monkeypatch.setattr(partner_access, "load_grant", lambda uid: empty_grant(uid))+ with as_user("u_alice", role="user"):+ assert partner_access.can_manage_partner("p1")+ assert partner_access.can_use_partner("p1")+ partner_access.assert_partner_manageable("p1") # no raise+ partner_access.assert_partner_allowed("p1") # no raise+++def test_a_partner_someone_else_owns_is_not_manageable(as_user, monkeypatch):+ _patch_manager(monkeypatch, [{"partner_id": "p1", "name": "P1", "owner_id": "u_bob"}])+ monkeypatch.setattr(partner_access, "load_grant", lambda uid: empty_grant(uid))+ with as_user("u_alice", role="user"):+ assert not partner_access.can_manage_partner("p1")+ with pytest.raises(HTTPException) as exc:+ partner_access.assert_partner_manageable("p1")+ assert exc.value.status_code == 403+++def test_assigned_partner_is_usable_but_not_manageable(as_user, monkeypatch):+ _patch_manager(monkeypatch, [{"partner_id": "p1", "name": "P1", "owner_id": "u_bob"}])+ monkeypatch.setattr(+ partner_access, "load_grant", lambda uid: {"partners": [{"partner_id": "p1"}]}+ )+ with as_user("u_alice", role="user"):+ assert partner_access.can_use_partner("p1")+ assert not partner_access.can_manage_partner("p1")+++def test_ownerless_partners_stay_admin_managed(as_user, monkeypatch):+ # Partners that predate ownership carry no owner_id; nobody inherits them+ # just by having an empty id themselves.+ _patch_manager(monkeypatch, [{"partner_id": "legacy", "name": "Legacy", "owner_id": ""}])+ monkeypatch.setattr(partner_access, "load_grant", lambda uid: empty_grant(uid))+ with as_user("", role="user"):+ assert not partner_access.can_manage_partner("legacy")+ with as_user("u_admin", role="admin"):+ assert partner_access.can_manage_partner("legacy")+++def test_visible_partners_projects_by_what_the_caller_may_do(as_user, monkeypatch):+ _patch_manager(+ monkeypatch,+ [+ {"partner_id": "mine", "name": "Mine", "owner_id": "u_alice", "channels": ["qq"]},+ {"partner_id": "lent", "name": "Lent", "owner_id": "u_bob", "channels": ["telegram"]},+ {"partner_id": "hidden", "name": "Hidden", "owner_id": "u_bob"},+ ],+ )+ monkeypatch.setattr(+ partner_access, "load_grant", lambda uid: {"partners": [{"partner_id": "lent"}]}+ )+ with as_user("u_alice", role="user"):+ visible = {p["partner_id"]: p for p in partner_access.visible_partners()}++ assert set(visible) == {"mine", "lent"}+ # Their own partner comes through whole, with its wiring and a manage flag.+ assert visible["mine"]["can_manage"] is True+ assert visible["mine"]["channels"] == ["qq"]+ # A partner merely lent to them is reduced to a face.+ assert visible["lent"]["can_manage"] is False+ assert "channels" not in visible["lent"]++# ── assignable pool (admin side) ──────────────────────────────diff --git a/tests/scripts/test_install_extras.py b/tests/scripts/test_install_extras.pynew file mode 100644index 000000000..1ec3a93b5--- /dev/null+++ b/tests/scripts/test_install_extras.py@@ -0,0 +1,159 @@+"""Tests for the container's declared-extras installer (#762).++The reporter's scenario is the one that matters: extras installed by hand into+a running container vanish on `compose down`, so the deployment declares them+and every start re-applies them — cheaply when they are already there, and+never fatally when they cannot be had.+"""++from __future__ import annotations++import importlib.util+from pathlib import Path+import sys++import pytest+++def _load():+ module_path = Path(__file__).resolve().parents[2] / "scripts" / "install_extras.py"+ module_name = "install_extras_under_test"+ sys.modules.pop(module_name, None)+ spec = importlib.util.spec_from_file_location(module_name, module_path)+ assert spec and spec.loader+ module = importlib.util.module_from_spec(spec)+ sys.modules[module_name] = module+ spec.loader.exec_module(module)+ return module+++install_extras = _load()+++def pyproject(tmp_path: Path) -> Path:+ path = tmp_path / "pyproject.toml"+ path.write_text(+ "[project.optional-dependencies]\n"+ 'math-animator = ["manim>=0.19.0"]\n'+ 'matrix-e2e = ["matrix-nio[e2e]>=0.25.2"]\n',+ encoding="utf-8",+ )+ return path+++ "raw,expected",+ [+ ("a,b", ["a", "b"]),+ ("a, b", ["a", "b"]),+ ("a b", ["a", "b"]),+ (" a ,, b ", ["a", "b"]),+ ("a,a,b", ["a", "b"]),+ ("", []),+ ],+)+def test_parse_names_accepts_the_spellings_people_write(raw, expected) -> None:+ """A Compose value is one string; the separator must not be a gotcha."""+ assert install_extras.parse_names(raw) == expected+++def test_underscore_and_dash_spellings_resolve_to_the_same_extra(pyproject) -> None:+ extras = install_extras.load_extras(pyproject)++ dashed, _ = install_extras.resolve(extras, ["matrix-e2e"])+ underscored, _ = install_extras.resolve(extras, ["matrix_e2e"])++ assert dashed == underscored == ["matrix-nio[e2e]>=0.25.2"]+++def test_unknown_extra_is_reported_without_dropping_the_valid_ones(pyproject) -> None:+ """One typo must not cost the operator the extras they spelled correctly."""+ extras = install_extras.load_extras(pyproject)++ requirements, unknown = install_extras.resolve(extras, ["nope", "math-animator"])++ assert unknown == ["nope"]+ assert requirements == ["manim>=0.19.0"]+++def test_satisfied_requirements_are_not_reinstalled() -> None:+ """The warm-container path: already-present packages cost a lookup, not a pip run."""+ assert install_extras.missing_requirements(["pytest"]) == []+ assert install_extras.missing_requirements(["pytest>=9999"]) == ["pytest>=9999"]+ assert install_extras.missing_requirements(["definitely-not-a-real-package"]) == [+ "definitely-not-a-real-package"+ ]+++def test_requirements_for_other_platforms_are_skipped() -> None:+ """An environment marker that excludes this interpreter is not 'missing'."""+ assert install_extras.missing_requirements(['nonexistent-pkg; python_version < "3.0"']) == []+++def test_unparseable_requirement_is_left_for_pip_to_judge() -> None:+ assert install_extras.missing_requirements(["=not a requirement="]) == ["=not a requirement="]+++def test_dry_run_installs_nothing(pyproject, monkeypatch, capsys) -> None:+ def _fail(*args, **kwargs):+ raise AssertionError("--dry-run must not shell out to pip")++ monkeypatch.setattr(install_extras.subprocess, "run", _fail)+ # Pin the resolver: this asserts the *install* path, and whether manim+ # happens to be present in the runner's environment must not decide+ # which branch runs. The real resolver is covered on its own above.+ monkeypatch.setattr(install_extras, "missing_requirements", lambda reqs: list(reqs))++ code = install_extras.main(["math-animator", "--pyproject", str(pyproject), "--dry-run"])++ assert code == 0+ assert "manim>=0.19.0" in capsys.readouterr().out+++def test_pip_failure_does_not_fail_the_start(pyproject, monkeypatch, capsys) -> None:+ """A wheel that will not install leaves one feature off, not the app down."""+ from types import SimpleNamespace++ monkeypatch.setattr(+ install_extras.subprocess,+ "run",+ lambda *a, **k: SimpleNamespace(returncode=1),+ )+ # Pin the resolver: this asserts the *install* path, and whether manim+ # happens to be present in the runner's environment must not decide+ # which branch runs. The real resolver is covered on its own above.+ monkeypatch.setattr(install_extras, "missing_requirements", lambda reqs: list(reqs))++ code = install_extras.main(["math-animator", "--pyproject", str(pyproject)])++ assert code == 0+ assert "stay unavailable" in capsys.readouterr().out+++def test_unreadable_pyproject_does_not_fail_the_start(tmp_path, capsys) -> None:+ code = install_extras.main(["math-animator", "--pyproject", str(tmp_path / "gone.toml")])++ assert code == 0+ assert "Could not read" in capsys.readouterr().out+++def test_no_declaration_is_a_no_op(monkeypatch) -> None:+ """The default deployment declares nothing and must not pay for the feature."""++ def _fail(*args, **kwargs):+ raise AssertionError("nothing declared; must not read pyproject or run pip")++ monkeypatch.setattr(install_extras, "load_extras", _fail)++ assert install_extras.main([""]) == 0+++def test_every_extra_the_project_declares_resolves() -> None:+ """Guards the docs: the names suggested in docker-compose must be real."""+ root = Path(__file__).resolve().parents[2]+ extras = install_extras.load_extras(root / "pyproject.toml")++ _, unknown = install_extras.resolve(extras, ["math-animator", "partners"])++ assert unknown == []diff --git a/tests/services/embedding/test_gemini_adapter.py b/tests/services/embedding/test_gemini_adapter.pyindex 2ac7111d2..0eb6deb6c 100644--- a/tests/services/embedding/test_gemini_adapter.py+++ b/tests/services/embedding/test_gemini_adapter.py@@ -310,4 +310,148 @@ def test_gemini2_model_info_advertises_matryoshka_dimensions() -> None:assert info["dimensions"] == 3072assert 768 in info["supported_dimensions"]assert info["supports_variable_dimensions"] is True- assert info["multimodal"] is False+ # Was False while the adapter was text-only; Embedding 2 maps text, images,+ # video and audio into one space and the adapter now sends them (#814).+ assert info["multimodal"] is True+++# ── Multimodal contents (#814) ──────────────────────────────────────────────+#+# The reporter's scenario: a textbook knowledge base whose image nodes should be+# retrievable by a natural-language query. That needs the parsed image to reach+# the model as an embedding, which the adapter used to refuse outright.++_PNG_DATA_URI = "data:image/png;base64,iVBORw0KGgo="+_INLINE_PNG = {"inlineData": {"mimeType": "image/png", "data": "iVBORw0KGgo="}}+++def _multimodal_request(contents: list[dict[str, Any]], **kwargs: Any) -> EmbeddingRequest:+ return EmbeddingRequest(+ texts=[],+ model="gemini-embedding-2",+ contents=contents,+ **kwargs,+ )+++def test_image_content_becomes_an_inline_data_part() -> None:+ payload = _adapter()._native_multimodal_payload(+ _multimodal_request([{"image": _PNG_DATA_URI}]),+ "gemini-embedding-2",+ )++ (request,) = payload["requests"]+ assert request["content"]["parts"] == [_INLINE_PNG]+ assert request["model"] == "models/gemini-embedding-2"+++def test_each_content_item_gets_its_own_vector() -> None:+ """One vector per node is what makes an image node independently retrievable."""+ payload = _adapter()._native_multimodal_payload(+ _multimodal_request([{"text": "a number line"}, {"image": _PNG_DATA_URI}]),+ "gemini-embedding-2",+ )++ assert [r["content"]["parts"][0] for r in payload["requests"]] == [+ {"text": "a number line"},+ _INLINE_PNG,+ ]+++def test_fusion_folds_every_item_into_one_vector() -> None:+ payload = _adapter()._native_multimodal_payload(+ _multimodal_request(+ [{"text": "caption"}, {"image": _PNG_DATA_URI}],+ enable_fusion=True,+ ),+ "gemini-embedding-2",+ )++ (request,) = payload["requests"]+ assert request["content"]["parts"] == [{"text": "caption"}, _INLINE_PNG]+++def test_multimodal_payload_carries_output_dimensionality() -> None:+ payload = _adapter(dimensions=768)._native_multimodal_payload(+ _multimodal_request([{"image": _PNG_DATA_URI}]),+ "gemini-embedding-2",+ )++ assert payload["requests"][0]["outputDimensionality"] == 768+++def test_remote_urls_are_refused_with_an_actionable_message() -> None:+ """batchEmbedContents has no remote-URL part, and this path must not fetch."""+ with pytest.raises(ValueError) as caught:+ _adapter()._native_multimodal_payload(+ _multimodal_request([{"image": "https://example.com/x.png"}]),+ "gemini-embedding-2",+ )++ assert "http(s) URL" in str(caught.value)+ assert "data: URI" in str(caught.value)++[email protected]("value", ["data:image/png;base64,", "data:;base64,abc", "not-a-uri"])+def test_malformed_inline_values_are_refused(value: str) -> None:+ with pytest.raises(ValueError):+ _adapter()._native_multimodal_payload(+ _multimodal_request([{"image": value}]),+ "gemini-embedding-2",+ )+++def test_unknown_content_kind_is_refused() -> None:+ with pytest.raises(ValueError, match="content type 'hologram'"):+ _adapter()._native_multimodal_payload(+ _multimodal_request([{"hologram": _PNG_DATA_URI}]),+ "gemini-embedding-2",+ )+++async def test_text_only_model_refuses_contents_naming_the_alternative() -> None:+ adapter = _adapter(model="gemini-embedding-001", base_url=NATIVE_GEMINI001_ENDPOINT)++ with pytest.raises(ValueError) as caught:+ await adapter._embed_native(+ EmbeddingRequest(+ texts=[],+ model="gemini-embedding-001",+ contents=[{"image": _PNG_DATA_URI}],+ ),+ "gemini-embedding-001",+ )++ assert "text-only" in str(caught.value)+ assert "gemini-embedding-2" in str(caught.value)+++async def test_multimodal_contents_reach_the_provider(+ capturing_httpx: _CapturingTransport,+) -> None:+ """End to end: the image survives into the posted body, one vector per item."""+ response = await _adapter().embed(+ _multimodal_request([{"text": "a number line"}, {"image": _PNG_DATA_URI}])+ )++ posted = capturing_httpx.requests[-1]["json"]["requests"]+ assert posted[1]["content"]["parts"] == [_INLINE_PNG]+ assert len(response.embeddings) == 2+++def test_text_only_path_is_unchanged_by_the_multimodal_addition() -> None:+ """No `contents` must produce byte-identical requests to before."""+ payload = _adapter()._native_payload(+ EmbeddingRequest(+ texts=["hello"],+ model="gemini-embedding-2",+ input_type="search_document",+ ),+ "gemini-embedding-2",+ )++ (request,) = payload["requests"]+ assert request["content"]["parts"] == [{"text": "title: none | text: hello"}]+ assert "taskType" not in requestdiff --git a/tests/services/llm/test_azure_openai_provider.py b/tests/services/llm/test_azure_openai_provider.pynew file mode 100644index 000000000..8e37bb79a--- /dev/null+++ b/tests/services/llm/test_azure_openai_provider.py@@ -0,0 +1,132 @@+"""Tests for Azure OpenAI endpoint normalization and client wiring."""++from __future__ import annotations++from typing import Any++import pytest++from deeptutor.services.llm.provider_core import azure_openai_provider as azure_mod+from deeptutor.services.llm.provider_core.azure_openai_provider import normalize_azure_base_url++V1_SURFACE = "https://res.openai.azure.com/openai/v1/"+++ "api_base",+ [+ "https://res.openai.azure.com",+ "https://res.openai.azure.com/",+ "https://res.openai.azure.com/openai",+ "https://res.openai.azure.com/openai/",+ "https://res.openai.azure.com/openai/v1",+ "https://res.openai.azure.com/openai/v1/",+ "https://res.openai.azure.com/openai/v1/responses",+ "https://res.openai.azure.com/openai/deployments/gpt-4o",+ "https://res.openai.azure.com/openai/deployments/gpt-4o/chat/completions",+ "https://res.openai.azure.com/openai/deployments/my.dep-01/chat/completions?api-version=2024-10-21",+ "res.openai.azure.com/openai/deployments/gpt-4o",+ " https://res.openai.azure.com/openai/deployments/gpt-4o ",+ ],+)+def test_every_endpoint_spelling_collapses_to_one_surface(api_base: str) -> None:+ """Portal endpoints and hand-written bases must land on the same URL.++ Appending ``/openai/v1`` verbatim used to turn a classic deployment+ endpoint into ``.../deployments/gpt-4o/openai/v1/responses``, which Azure+ answers with ``404 Resource not found`` even though the settings probe —+ which builds classic URLs — succeeds against the same configuration.+ """+ assert normalize_azure_base_url(api_base) == V1_SURFACE+++def test_reverse_proxy_prefix_survives_normalization() -> None:+ assert (+ normalize_azure_base_url("https://gw.corp/azure/openai/deployments/gpt-4o/chat/completions")+ == "https://gw.corp/azure/openai/v1/"+ )+++def test_blank_base_is_left_untouched() -> None:+ assert normalize_azure_base_url("") == ""+++def _capture(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:+ captured: list[dict[str, Any]] = []++ class AsyncOpenAIStub:+ def __init__(self, **kwargs: Any) -> None:+ captured.append(kwargs)++ monkeypatch.setattr(azure_mod, "AsyncOpenAI", AsyncOpenAIStub)+ return captured+++def test_client_gets_normalized_base_and_api_key_header(monkeypatch: pytest.MonkeyPatch) -> None:+ captured = _capture(monkeypatch)++ azure_mod.AzureOpenAIProvider(+ api_key="sk-test",+ api_base="https://res.openai.azure.com/openai/deployments/gpt-4o/chat/completions",+ default_model="gpt-4o",+ )++ kwargs = captured[0]+ assert kwargs["base_url"] == V1_SURFACE+ # Azure reserves ``Authorization: Bearer`` for Entra tokens; API keys are+ # authenticated through ``api-key``, which the SDK never sends on its own.+ assert kwargs["default_headers"]["api-key"] == "sk-test"+++def test_extra_headers_override_defaults(monkeypatch: pytest.MonkeyPatch) -> None:+ captured = _capture(monkeypatch)++ azure_mod.AzureOpenAIProvider(+ api_key="sk-test",+ api_base="https://res.openai.azure.com",+ extra_headers={"api-key": "override", "x-custom": "1"},+ )++ headers = captured[0]["default_headers"]+ assert headers["api-key"] == "override"+ assert headers["x-custom"] == "1"+++ ("api_version", "expected"),+ [+ ("preview", {"api-version": "preview"}),+ ("PREVIEW", {"api-version": "preview"}),+ # A dated version belongs to the classic surface and would be rejected+ # against ``/openai/v1``, so it must not be forwarded.+ ("2024-10-21", None),+ ("", None),+ (None, None),+ ],+)+def test_only_preview_api_version_reaches_the_v1_surface(+ monkeypatch: pytest.MonkeyPatch,+ api_version: str | None,+ expected: dict[str, str] | None,+) -> None:+ captured = _capture(monkeypatch)++ azure_mod.AzureOpenAIProvider(+ api_key="sk-test",+ api_base="https://res.openai.azure.com",+ api_version=api_version,+ )++ assert captured[0]["default_query"] == expected+++ ("api_key", "api_base", "match"),+ [+ ("", "https://res.openai.azure.com", "api_key is required"),+ ("sk-test", "", "api_base is required"),+ ],+)+def test_missing_credentials_are_rejected(api_key: str, api_base: str, match: str) -> None:+ with pytest.raises(ValueError, match=match):+ azure_mod.AzureOpenAIProvider(api_key=api_key, api_base=api_base)diff --git a/tests/services/partners/conftest.py b/tests/services/partners/conftest.pyindex 5de95ef2b..78608efc5 100644--- a/tests/services/partners/conftest.py+++ b/tests/services/partners/conftest.py@@ -1,11 +1,19 @@-"""Fixtures for the partners service suite — isolate all paths under tmp_path."""+"""Fixtures for the partners service suite — isolate all paths under tmp_path.++Also holds the scripted-orchestrator scaffolding every runtime-level test+needs: a partner turn is a chat-loop run, and the tests care about what the+runner does with the loop's events, not about the loop itself.+"""from __future__ import annotationsfrom pathlib import Path+from typing import Anyimport pytest+from deeptutor.core.stream import StreamEvent+@pytest.fixturedef partners_root(tmp_path, monkeypatch) -> Path:@@ -28,3 +36,50 @@ def partners_root(tmp_path, monkeypatch) -> Path:admin_root.mkdir(parents=True, exist_ok=True)return admin_root / "partners"+++class _FakeOrchestrator:+ """Yields a scripted event sequence instead of running the chat loop."""++ script: list[StreamEvent] = []+ # Optional queue of per-turn scripts; when non-empty, each handle() call+ # pops the next one (lets tests model a failed turn + a backup retry).+ scripts: list[list[StreamEvent]] = []+ seen_contexts: list[Any] = []+ activated_selections: list[Any] = []+ # The memory root in effect while the turn runs — proves the partner reads+ # the owner's (admin) memory via memory_path_service_override, not its own.+ seen_memory_roots: list[Any] = []++ def __init__(self) -> None:+ pass++ async def handle(self, context):+ from deeptutor.services.memory.paths import memory_root++ type(self).seen_contexts.append(context)+ type(self).seen_memory_roots.append(memory_root())+ script = type(self).scripts.pop(0) if type(self).scripts else type(self).script+ for event in script:+ yield event+++def fake_orchestrator(monkeypatch):+ import deeptutor.runtime.orchestrator as orch_mod+ from deeptutor.services.model_selection import runtime as selection_runtime++ _FakeOrchestrator.script = []+ _FakeOrchestrator.scripts = []+ _FakeOrchestrator.seen_contexts = []+ _FakeOrchestrator.activated_selections = []+ _FakeOrchestrator.seen_memory_roots = []+ monkeypatch.setattr(orch_mod, "ChatOrchestrator", _FakeOrchestrator)++ def _record_activate(selection):+ _FakeOrchestrator.activated_selections.append(selection)+ return (None, None)++ monkeypatch.setattr(selection_runtime, "activate_llm_selection", _record_activate)+ monkeypatch.setattr(selection_runtime, "reset_llm_selection", lambda token: None)+ return _FakeOrchestratordiff --git a/tests/services/partners/scripts.py b/tests/services/partners/scripts.pynew file mode 100644index 000000000..7f52c5134--- /dev/null+++ b/tests/services/partners/scripts.py@@ -0,0 +1,60 @@+"""Scripted chat-loop event sequences for partner runtime tests.++A partner turn is a chat-loop run; these build the event streams a real+loop would emit so tests can assert on what the runner makes of them.+"""++from __future__ import annotations++from typing import Any++from deeptutor.core.stream import StreamEvent, StreamEventType+++def event(+ event_type: StreamEventType,+ *,+ content: str = "",+ source: str = "chat",+ metadata: dict[str, Any] | None = None,+) -> StreamEvent:+ return StreamEvent(type=event_type, source=source, content=content, metadata=metadata or {})+++def narration_round(call_id: str, text: str) -> list[StreamEvent]:+ return [+ event(StreamEventType.CONTENT, content=text, metadata={"call_id": call_id}),+ event(+ StreamEventType.PROGRESS,+ metadata={+ "trace_kind": "call_status",+ "call_state": "complete",+ "call_role": "narration",+ "call_id": call_id,+ },+ ),+ ]+++def finish(text: str) -> list[StreamEvent]:+ return [+ event(StreamEventType.CONTENT, content=text, metadata={"call_id": "c-finish"}),+ event(StreamEventType.RESULT, metadata={"response": text}),+ event(StreamEventType.DONE),+ ]+++def answer_visible_narration(call_id: str, text: str) -> list[StreamEvent]:+ return [+ event(StreamEventType.CONTENT, content=text, metadata={"call_id": call_id}),+ event(+ StreamEventType.PROGRESS,+ metadata={+ "trace_kind": "call_status",+ "call_state": "complete",+ "call_role": "narration",+ "answer_visible": True,+ "call_id": call_id,+ },+ ),+ ]diff --git a/tests/services/partners/test_channel_links.py b/tests/services/partners/test_channel_links.pynew file mode 100644index 000000000..7657476e0--- /dev/null+++ b/tests/services/partners/test_channel_links.py@@ -0,0 +1,233 @@+"""Linking a chat-channel account to a DeepTutor account.++The point of a link is that a channel message stops being anonymous: it lands+in the sender's own thread pool instead of the partner's shared one, and the+partner answers out of that person's workspace.+"""++from __future__ import annotations++from datetime import datetime, timedelta, timezone++import pytest++from deeptutor.partners.bus.events import InboundMessage+from deeptutor.partners.bus.queue import MessageBus+from deeptutor.services.partners import links+from deeptutor.services.partners.interaction import session_store_for+from deeptutor.services.partners.manager import PartnerConfig+from deeptutor.services.partners.runtime import PartnerRunner+from tests.services.partners.scripts import finish+++def alice(partners_root):+ """A real account — identity is re-read from the user store on every turn."""+ from deeptutor.multi_user import identity+ from deeptutor.services.partners.interaction import actor_for_account++ identity.save_user("alice", "hash", "user")+ return actor_for_account(identity.get_user("alice")["id"])+++# ── code lifecycle ────────────────────────────────────────────+++def test_redeeming_a_code_links_the_sender(partners_root):+ issued = links.issue_link_code("ada", "u_alice")++ claimed = links.redeem_link_code("ada", issued.code, channel="qq", sender_id="90210")++ assert claimed == "u_alice"+ assert links.linked_user_id("ada", "qq", "90210") == "u_alice"+++def test_codes_are_single_use(partners_root):+ issued = links.issue_link_code("ada", "u_alice")+ links.redeem_link_code("ada", issued.code, channel="qq", sender_id="90210")++ again = links.redeem_link_code("ada", issued.code, channel="qq", sender_id="55555")++ assert again is None+ assert links.linked_user_id("ada", "qq", "55555") is None+++def test_codes_are_case_insensitive_and_trimmed(partners_root):+ issued = links.issue_link_code("ada", "u_alice")++ claimed = links.redeem_link_code(+ "ada", f" {issued.code.lower()} ", channel="qq", sender_id="90210"+ )++ assert claimed == "u_alice"+++def test_issuing_again_invalidates_the_previous_code(partners_root):+ stale = links.issue_link_code("ada", "u_alice")+ links.issue_link_code("ada", "u_alice")++ assert links.redeem_link_code("ada", stale.code, channel="qq", sender_id="1") is None+++def test_expired_codes_are_refused(partners_root, monkeypatch):+ issued = links.issue_link_code("ada", "u_alice")+ later = datetime.now(timezone.utc) + timedelta(hours=1)+ monkeypatch.setattr(links, "_now", lambda: later)++ assert links.redeem_link_code("ada", issued.code, channel="qq", sender_id="1") is None+++def test_unknown_and_empty_codes_are_refused(partners_root):+ assert links.redeem_link_code("ada", "ZZZZZZ", channel="qq", sender_id="1") is None+ assert links.redeem_link_code("ada", "", channel="qq", sender_id="1") is None+++def test_links_are_scoped_to_one_partner(partners_root):+ issued = links.issue_link_code("ada", "u_alice")+ links.redeem_link_code("ada", issued.code, channel="qq", sender_id="90210")++ assert links.linked_user_id("bo", "qq", "90210") is None+++# ── managing your own links ───────────────────────────────────+++def test_a_user_only_sees_and_removes_their_own_links(partners_root):+ for user, sender in (("u_alice", "1"), ("u_bob", "2")):+ code = links.issue_link_code("ada", user).code+ links.redeem_link_code("ada", code, channel="qq", sender_id=sender)++ listed = links.list_links("ada", "u_alice")+ assert [item["key"] for item in listed] == ["qq:1"]++ assert links.remove_link("ada", "u_alice", "qq:2") is False # not hers to unlink+ assert links.linked_user_id("ada", "qq", "2") == "u_bob"++ assert links.remove_link("ada", "u_alice", "qq:1") is True+ assert links.linked_user_id("ada", "qq", "1") is None+++def test_a_corrupt_store_reads_as_empty_rather_than_raising(partners_root):+ path = links._path("ada")+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("{ not json", encoding="utf-8")++ assert links.linked_user_id("ada", "qq", "1") is None+ issued = links.issue_link_code("ada", "u_alice")+ assert links.redeem_link_code("ada", issued.code, channel="qq", sender_id="1") == "u_alice"+++# ── what a link changes for a turn ────────────────────────────+++def _dm(content: str = "hello", *, sender: str = "90210") -> InboundMessage:+ return InboundMessage(+ channel="qq", sender_id=sender, chat_id=f"private:{sender}", content=content+ )+++def _group(content: str = "hello", *, sender: str = "90210") -> InboundMessage:+ return InboundMessage(+ channel="qq",+ sender_id=sender,+ chat_id="group:777",+ content=content,+ metadata={"is_group": True},+ )+++async def test_a_linked_sender_gets_their_own_private_history(+ partners_root, fake_orchestrator, alice+):+ from deeptutor.services.partners.manager import PartnerConfig++ fake_orchestrator.script = finish("ok")+ runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())+ code = links.issue_link_code("ada", alice.id).code+ links.redeem_link_code("ada", code, channel="qq", sender_id="90210")++ await runner.process_message(_dm("what did we say?"))++ assert [m["content"] for m in session_store_for("ada", alice).messages("qq:private:90210")] == [+ "what did we say?",+ "ok",+ ]+ # Nothing lands in the shared pool the admin reads.+ assert session_store_for("ada", None).messages("qq:private:90210") == []+++async def test_an_unlinked_sender_stays_in_the_shared_pool(partners_root, fake_orchestrator):+ from deeptutor.services.partners.manager import PartnerConfig++ fake_orchestrator.script = finish("ok")+ runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())++ await runner.process_message(_dm("hi"))++ assert [m["content"] for m in session_store_for("ada", None).messages("qq:private:90210")] == [+ "hi",+ "ok",+ ]+++async def test_group_traffic_stays_shared_even_from_a_linked_sender(+ partners_root, fake_orchestrator, alice+):+ from deeptutor.services.partners.manager import PartnerConfig++ fake_orchestrator.script = finish("ok")+ runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())+ code = links.issue_link_code("ada", alice.id).code+ links.redeem_link_code("ada", code, channel="qq", sender_id="90210")++ await runner.process_message(_group("morning everyone"))++ # A group thread is one shared conversation; splitting it per speaker would+ # leave the partner replying out of a history the room cannot see.+ assert session_store_for("ada", alice).list_sessions() == []+ assert session_store_for("ada", None).messages("qq:group:777")+++async def test_link_command_binds_the_sender_mid_conversation(partners_root, fake_orchestrator):+ from deeptutor.multi_user import identity++ identity.save_user("alice", "hash", "user")+ user_id = identity.get_user("alice")["id"]+ runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())+ code = links.issue_link_code("ada", user_id).code++ reply = await runner.process_message(_dm(f"/link {code}"))++ assert "alice" in reply+ assert links.linked_user_id("ada", "qq", "90210") == user_id+++async def test_link_command_refuses_a_group_chat(partners_root, fake_orchestrator):++ runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())+ code = links.issue_link_code("ada", "u_alice").code++ reply = await runner.process_message(_group(f"/link {code}"))++ assert "direct message" in reply+ assert links.linked_user_id("ada", "qq", "90210") is None+++async def test_a_deleted_account_does_not_speak_for_anyone(partners_root, fake_orchestrator):+ from deeptutor.services.partners.manager import PartnerConfig++ fake_orchestrator.script = finish("ok")+ runner = PartnerRunner("ada", PartnerConfig(name="Ada"), MessageBus())+ code = links.issue_link_code("ada", "u_ghost").code+ links.redeem_link_code("ada", code, channel="qq", sender_id="90210")++ await runner.process_message(_dm("hi"))++ # The link survives but resolves to nobody, so the turn falls back to shared.+ assert session_store_for("ada", None).messages("qq:private:90210")diff --git a/tests/services/partners/test_channel_manager.py b/tests/services/partners/test_channel_manager.pyindex 561f7bd93..a8bbaa773 100644--- a/tests/services/partners/test_channel_manager.py+++ b/tests/services/partners/test_channel_manager.py@@ -78,6 +78,64 @@ def test_channel_media_is_scoped_to_owning_partner(partners_root):assert channel.media_dir() == partners_root / "ada" / "media" / "telegram"+def test_channel_state_is_scoped_to_owning_partner(partners_root):+ from deeptutor.partners.bus.queue import MessageBus+ from deeptutor.partners.channels.base import BaseChannel++ class _StatefulChannel(BaseChannel):+ name = "telegram"++ async def start(self):+ pass++ async def stop(self):+ pass++ async def send(self, msg):+ pass++ channel = _StatefulChannel({}, MessageBus())+ channel.partner_id = "ada"++ assert channel.state_dir() == partners_root / "ada" / "channels" / "telegram"+++def test_partner_id_is_available_while_the_channel_is_constructed(partners_root, monkeypatch):+ """Channels that resolve paths in ``__init__`` must not see an empty owner."""+ from deeptutor.partners.bus.queue import MessageBus+ from deeptutor.partners.channels.base import BaseChannel++ class _EagerChannel(BaseChannel):+ name = "telegram"+ display_name = "Eager"++ def __init__(self, config, bus):+ super().__init__(config, bus)+ self.resolved_at_init = self.state_dir()++ async def start(self):+ pass++ async def stop(self):+ pass++ async def send(self, msg):+ pass++ monkeypatch.setattr(+ "deeptutor.partners.channels.registry.discover_all",+ lambda: {"telegram": _EagerChannel},+ )+ manager = ChannelManager(+ ChannelsConfig(telegram={"enabled": True}),+ MessageBus(),+ partner_id="ada",+ )++ channel = manager.channels["telegram"]+ assert channel.resolved_at_init == partners_root / "ada" / "channels" / "telegram"++async def _dispatch_one(msg: OutboundMessage,*,diff --git a/tests/services/partners/test_channel_state_migration.py b/tests/services/partners/test_channel_state_migration.pynew file mode 100644index 000000000..ccd95f8a1--- /dev/null+++ b/tests/services/partners/test_channel_state_migration.py@@ -0,0 +1,119 @@+"""The one-shot rehoming of channel state that used to be shared by all partners."""++from __future__ import annotations++import json++import pytest++from deeptutor.partners.config import paths as partner_paths+from deeptutor.partners.helpers import ensure_dir+from deeptutor.services.partners.channel_state_migration import rehome_shared_channel_state+++def partners_root(tmp_path, monkeypatch):+ root = ensure_dir(tmp_path / "partners")+ monkeypatch.setattr(partner_paths, "_base_dir", lambda: root)+ return root+++def _legacy_weixin(partners_root, token: str, cursor: str = "cursor-1"):+ legacy = ensure_dir(partners_root / "weixin")+ (legacy / "account.json").write_text(+ json.dumps({"token": token, "get_updates_buf": cursor}), encoding="utf-8"+ )+ return legacy+++def _adopted(partners_root, partner_id: str, channel: str = "weixin"):+ return partners_root / partner_id / "channels" / channel / "account.json"+++class TestRehomeSharedChannelState:+ def test_sole_partner_on_the_channel_keeps_working(self, partners_root):+ _legacy_weixin(partners_root, "token-a")++ rehome_shared_channel_state({"alice": {"weixin": {"enabled": True}}})++ saved = json.loads(_adopted(partners_root, "alice").read_text())+ assert saved["token"] == "token-a"+ assert saved["get_updates_buf"] == "cursor-1"++ def test_token_match_decides_between_two_partners(self, partners_root):+ """The reported case: a second partner was added, so both are candidates."""+ _legacy_weixin(partners_root, "token-b")++ rehome_shared_channel_state(+ {+ "alice": {"weixin": {"enabled": True, "token": "token-a"}},+ "bob": {"weixin": {"enabled": True, "token": "token-b"}},+ }+ )++ assert _adopted(partners_root, "bob").exists()+ assert not _adopted(partners_root, "alice").exists()++ def test_ambiguous_owner_is_left_alone(self, partners_root):+ """Two candidates and no proof: guessing would repeat the bug."""+ _legacy_weixin(partners_root, "token-unknown")++ rehome_shared_channel_state(+ {+ "alice": {"weixin": {"enabled": True}},+ "bob": {"weixin": {"enabled": True}},+ }+ )++ assert not _adopted(partners_root, "alice").exists()+ assert not _adopted(partners_root, "bob").exists()+ assert (partners_root / "weixin" / "account.json").exists()++ def test_disabled_partners_are_not_candidates(self, partners_root):+ _legacy_weixin(partners_root, "token-a")++ rehome_shared_channel_state(+ {+ "alice": {"weixin": {"enabled": True}},+ "bob": {"weixin": {"enabled": False}},+ }+ )++ assert _adopted(partners_root, "alice").exists()+ assert not _adopted(partners_root, "bob").exists()++ def test_existing_state_is_never_overwritten(self, partners_root):+ _legacy_weixin(partners_root, "token-legacy")+ own = ensure_dir(partners_root / "alice" / "channels" / "weixin") / "account.json"+ own.write_text(json.dumps({"token": "token-own"}), encoding="utf-8")++ rehome_shared_channel_state({"alice": {"weixin": {"enabled": True}}})++ assert json.loads(own.read_text())["token"] == "token-own"++ def test_is_idempotent_and_non_destructive(self, partners_root):+ legacy = _legacy_weixin(partners_root, "token-a")++ rehome_shared_channel_state({"alice": {"weixin": {"enabled": True}}})+ rehome_shared_channel_state({"alice": {"weixin": {"enabled": True}}})++ assert (legacy / "account.json").exists()+ assert json.loads(_adopted(partners_root, "alice").read_text())["token"] == "token-a"++ def test_partner_named_after_a_channel_is_not_treated_as_state(self, partners_root):+ impostor = ensure_dir(partners_root / "weixin")+ (impostor / "config.yaml").write_text("name: weixin\n", encoding="utf-8")++ rehome_shared_channel_state({"alice": {"weixin": {"enabled": True}}})++ assert not _adopted(partners_root, "alice").exists()++ def test_other_channels_rehome_by_their_legacy_dir_name(self, partners_root):+ store = ensure_dir(partners_root / "matrix-store")+ (store / "nio.db").write_text("device-keys", encoding="utf-8")++ rehome_shared_channel_state({"alice": {"matrix": {"enabled": True}}})++ assert (+ partners_root / "alice" / "channels" / "matrix" / "nio.db"+ ).read_text() == "device-keys"diff --git a/tests/services/partners/test_msteams_channel.py b/tests/services/partners/test_msteams_channel.pyindex 3aec12f2c..6831306cd 100644--- a/tests/services/partners/test_msteams_channel.py+++ b/tests/services/partners/test_msteams_channel.py@@ -18,12 +18,13 @@ from deeptutor.partners.channels.msteams import (MSTeamsChannel,MSTeamsConfig,)+from deeptutor.partners.config import paths as partner_paths@pytest.fixturedef state_dir(tmp_path, monkeypatch):"""Redirect the channel's runtime state dir to a temp directory."""- monkeypatch.setattr(msteams_mod, "get_runtime_subdir", lambda name: tmp_path)+ monkeypatch.setattr(partner_paths, "get_runtime_subdir", lambda name: tmp_path)return tmp_pathdiff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.pyindex b3164f306..48eae488c 100644--- a/tests/services/partners/test_partner_runtime.py+++ b/tests/services/partners/test_partner_runtime.py@@ -10,114 +10,26 @@ import pytestfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.partners.bus.events import InboundMessagefrom deeptutor.partners.bus.queue import MessageBus+from deeptutor.services.partners.interaction import session_store_forfrom deeptutor.services.partners.manager import PartnerConfigfrom deeptutor.services.partners.runtime import PartnerRunnerfrom deeptutor.services.partners.sessions import PartnerSessionStore---def _event(- event_type: StreamEventType,- *,- content: str = "",- source: str = "chat",- metadata: dict[str, Any] | None = None,-) -> StreamEvent:- return StreamEvent(type=event_type, source=source, content=content, metadata=metadata or {})---def _narration_round(call_id: str, text: str) -> list[StreamEvent]:- return [- _event(StreamEventType.CONTENT, content=text, metadata={"call_id": call_id}),- _event(- StreamEventType.PROGRESS,- metadata={- "trace_kind": "call_status",- "call_state": "complete",- "call_role": "narration",- "call_id": call_id,- },- ),- ]---def _finish(text: str) -> list[StreamEvent]:- return [- _event(StreamEventType.CONTENT, content=text, metadata={"call_id": "c-finish"}),- _event(StreamEventType.RESULT, metadata={"response": text}),- _event(StreamEventType.DONE),- ]---def _answer_visible_narration(call_id: str, text: str) -> list[StreamEvent]:- return [- _event(StreamEventType.CONTENT, content=text, metadata={"call_id": call_id}),- _event(- StreamEventType.PROGRESS,- metadata={- "trace_kind": "call_status",- "call_state": "complete",- "call_role": "narration",- "answer_visible": True,- "call_id": call_id,- },- ),- ]---class _FakeOrchestrator:- """Yields a scripted event sequence instead of running the chat loop."""-- script: list[StreamEvent] = []- # Optional queue of per-turn scripts; when non-empty, each handle() call- # pops the next one (lets tests model a failed turn + a backup retry).- scripts: list[list[StreamEvent]] = []- seen_contexts: list[Any] = []- activated_selections: list[Any] = []- # The memory root in effect while the turn runs — proves the partner reads- # the owner's (admin) memory via memory_path_service_override, not its own.- seen_memory_roots: list[Any] = []-- def __init__(self) -> None:- pass-- async def handle(self, context):- from deeptutor.services.memory.paths import memory_root-- type(self).seen_contexts.append(context)- type(self).seen_memory_roots.append(memory_root())- script = type(self).scripts.pop(0) if type(self).scripts else type(self).script- for event in script:- yield event---def fake_orchestrator(monkeypatch):- import deeptutor.runtime.orchestrator as orch_mod- from deeptutor.services.model_selection import runtime as selection_runtime-- _FakeOrchestrator.script = []- _FakeOrchestrator.scripts = []- _FakeOrchestrator.seen_contexts = []- _FakeOrchestrator.activated_selections = []- _FakeOrchestrator.seen_memory_roots = []- monkeypatch.setattr(orch_mod, "ChatOrchestrator", _FakeOrchestrator)-- def _record_activate(selection):- _FakeOrchestrator.activated_selections.append(selection)- return (None, None)-- monkeypatch.setattr(selection_runtime, "activate_llm_selection", _record_activate)- monkeypatch.setattr(selection_runtime, "reset_llm_selection", lambda token: None)- return _FakeOrchestrator+from tests.services.partners.scripts import (+ answer_visible_narration,+ event,+ finish,+ narration_round,+)def _runner(partners_root, config: PartnerConfig | None = None) -> PartnerRunner:- from deeptutor.partners.config.paths import get_partner_sessions_dir-config = config or PartnerConfig(name="Ada")- bus = MessageBus()- store = PartnerSessionStore(get_partner_sessions_dir("ada"))- return PartnerRunner("ada", config, bus, store)+ return PartnerRunner("ada", config, MessageBus())+++def _shared_store(partner_id: str = "ada") -> PartnerSessionStore:+ """The partner's shared thread pool — where un-attributed turns land."""+ return session_store_for(partner_id, None)def _msg(content: str = "hello", channel: str = "telegram") -> InboundMessage:@@ -127,7 +39,7 @@ def _msg(content: str = "hello", channel: str = "telegram") -> InboundMessage:class TestTurnExecution:@pytest.mark.asyncioasync def test_returns_finish_text_and_persists_session(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _narration_round("c1", "let me check") + _finish(+ fake_orchestrator.script = narration_round("c1", "let me check") + finish("The answer is 4.")runner = _runner(partners_root)@@ -135,7 +47,7 @@ class TestTurnExecution:final = await runner.process_message(_msg("what is 2+2?"))assert final == "The answer is 4."- history = runner.store.conversation_history("telegram:42")+ history = _shared_store().conversation_history("telegram:42")assert history == [{"role": "user", "content": "what is 2+2?"},{"role": "assistant", "content": "The answer is 4."},@@ -143,7 +55,7 @@ class TestTurnExecution:@pytest.mark.asyncioasync def test_narration_streams_as_progress_outbound(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _narration_round("c1", "exploring…") + _finish("done")+ fake_orchestrator.script = narration_round("c1", "exploring…") + finish("done")runner = _runner(partners_root)await runner.process_message(_msg())@@ -154,9 +66,9 @@ class TestTurnExecution:@pytest.mark.asyncioasync def test_answer_visible_narration_stays_in_reply(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _answer_visible_narration(+ fake_orchestrator.script = answer_visible_narration("c1", "Great job on that answer."- ) + _finish("Choose the next topic.")+ ) + finish("Choose the next topic.")runner = _runner(partners_root)final = await runner.process_message(_msg())@@ -168,9 +80,9 @@ class TestTurnExecution:async def test_answer_visible_prefix_is_not_duplicated_when_result_is_canonical(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _answer_visible_narration("c1", "Part one. ") + [- _event(StreamEventType.CONTENT, content="Part two.", metadata={"call_id": "c2"}),- _event(+ fake_orchestrator.script = answer_visible_narration("c1", "Part one. ") + [+ event(StreamEventType.CONTENT, content="Part two.", metadata={"call_id": "c2"}),+ event(StreamEventType.PROGRESS,metadata={"trace_kind": "call_status",@@ -179,7 +91,7 @@ class TestTurnExecution:"call_id": "c2",},),- _event(+ event(StreamEventType.RESULT,metadata={"response": "Part one. Part two."},),@@ -194,12 +106,12 @@ class TestTurnExecution:@pytest.mark.asyncioasync def test_tool_calls_stream_as_hints_by_default(self, partners_root, fake_orchestrator):fake_orchestrator.script = [- _event(+ event(StreamEventType.TOOL_CALL,content="rag",metadata={"args": {"query": "hello world", "_internal": "x"}},),- *_finish("done"),+ *finish("done"),]runner = _runner(partners_root)@@ -214,7 +126,7 @@ class TestTurnExecution:async def test_send_progress_flag_off_suppresses_narration(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _narration_round("c1", "exploring…") + _finish("done")+ fake_orchestrator.script = narration_round("c1", "exploring…") + finish("done")config = PartnerConfig(name="Ada", channels={"telegram": {"send_progress": False}})runner = _runner(partners_root, config)@@ -225,7 +137,7 @@ class TestTurnExecution:async def test_web_channel_never_emits_progress_outbound(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _narration_round("c1", "exploring…") + _finish("done")+ fake_orchestrator.script = narration_round("c1", "exploring…") + finish("done")runner = _runner(partners_root)await runner.process_message(_msg(channel="web"))@@ -238,13 +150,13 @@ class TestTurnExecution:# An unresolved ask_user pause emits the question as a final-response# CONTENT event while RESULT carries an empty response.fake_orchestrator.script = [- _event(+ event(StreamEventType.CONTENT,content="Which topic do you mean?",metadata={"call_id": "f1", "call_kind": "llm_final_response"},),- _event(StreamEventType.RESULT, metadata={"response": ""}),- _event(StreamEventType.DONE),+ event(StreamEventType.RESULT, metadata={"response": ""}),+ event(StreamEventType.DONE),]runner = _runner(partners_root)@@ -258,12 +170,12 @@ class TestTurnExecution:fake_orchestrator.scripts = [# Turn 1 (primary): hard failure, no answer.[- _event(StreamEventType.ERROR, content="rate limited"),- _event(StreamEventType.RESULT, metadata={"response": ""}),- _event(StreamEventType.DONE),+ event(StreamEventType.ERROR, content="rate limited"),+ event(StreamEventType.RESULT, metadata={"response": ""}),+ event(StreamEventType.DONE),],# Turn 2 (backup): succeeds.- _finish("backup answer"),+ finish("backup answer"),]config = PartnerConfig(name="Ada", llm_selection=primary, backup_llm_selection=backup)runner = _runner(partners_root, config)@@ -275,9 +187,9 @@ class TestTurnExecution:@pytest.mark.asyncioasync def test_no_backup_returns_error_text(self, partners_root, fake_orchestrator):fake_orchestrator.script = [- _event(StreamEventType.ERROR, content="rate limited"),- _event(StreamEventType.RESULT, metadata={"response": ""}),- _event(StreamEventType.DONE),+ event(StreamEventType.ERROR, content="rate limited"),+ event(StreamEventType.RESULT, metadata={"response": ""}),+ event(StreamEventType.DONE),]runner = _runner(partners_root)@@ -327,7 +239,7 @@ class TestTurnExecution:return (None, None)monkeypatch.setattr(selection_runtime, "activate_llm_selection", _activate)- fake_orchestrator.script = _finish("backup answer")+ fake_orchestrator.script = finish("backup answer")config = PartnerConfig(name="Ada", llm_selection=primary, backup_llm_selection=backup)runner = _runner(partners_root, config)@@ -338,7 +250,7 @@ class TestTurnExecution:@pytest.mark.asyncioasync def test_successful_turn_never_touches_backup(self, partners_root, fake_orchestrator):backup = {"profile_id": "p2", "model_id": "m2"}- fake_orchestrator.script = _finish("first try works")+ fake_orchestrator.script = finish("first try works")config = PartnerConfig(name="Ada", backup_llm_selection=backup)runner = _runner(partners_root, config)@@ -348,7 +260,7 @@ class TestTurnExecution:@pytest.mark.asyncioasync def test_inbound_handler_publishes_reply_outbound(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _finish("reply text")+ fake_orchestrator.script = finish("reply text")runner = _runner(partners_root)await runner._handle_inbound(_msg())@@ -364,7 +276,7 @@ class TestContextAssembly:from deeptutor.services.partners.workspace import write_soulwrite_soul("ada", "# Soul\nBe kind.")- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")config = PartnerConfig(name="Ada",language="zh",@@ -408,7 +320,7 @@ class TestContextAssembly:):from deeptutor.agents._shared.tool_composition import default_optional_tools- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")runner = _runner(partners_root) # enabled_tools=Noneawait runner.process_message(_msg())@@ -460,7 +372,7 @@ class TestContextAssembly:async def test_owner_can_opt_partner_into_all_mcp_tools(self, partners_root, fake_orchestrator):"""``mcp_tools=None`` is still the deliberate unrestricted state: itemits no filter, which the chat pipeline reads as no MCP narrowing."""- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")runner = _runner(partners_root, PartnerConfig(name="Ada", mcp_tools=None))await runner.process_message(_msg())@@ -469,11 +381,11 @@ class TestContextAssembly:@pytest.mark.asyncioasync def test_history_feeds_next_turn(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _finish("first reply")+ fake_orchestrator.script = finish("first reply")runner = _runner(partners_root)await runner.process_message(_msg("first question"))- fake_orchestrator.script = _finish("second reply")+ fake_orchestrator.script = finish("second reply")await runner.process_message(_msg("second question"))context = fake_orchestrator.seen_contexts[-1]@@ -490,7 +402,7 @@ class TestContextAssembly:image_path = partners_root / "image.png"image_path.parent.mkdir(parents=True, exist_ok=True)image_path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"0" * 32)- fake_orchestrator.script = _finish("saw it")+ fake_orchestrator.script = finish("saw it")runner = _runner(partners_root)msg = _msg("what is in this image?")msg.media = [str(image_path)]@@ -501,7 +413,7 @@ class TestContextAssembly:assert len(context.attachments) == 1assert context.attachments[0].type == "image"assert context.attachments[0].filename == "image.png"- records = runner.store.messages("telegram:42")+ records = _shared_store().messages("telegram:42")assert records[0]["attachments"][0]["type"] == "image"assert records[0]["attachments"][0]["filename"] == "image.png"@@ -510,7 +422,7 @@ class TestContextAssembly:doc_path = partners_root / "notes.txt"doc_path.parent.mkdir(parents=True, exist_ok=True)doc_path.write_text("Gradient descent uses a learning rate.", encoding="utf-8")- fake_orchestrator.script = _finish("noted")+ fake_orchestrator.script = finish("noted")runner = _runner(partners_root)msg = _msg("summarize this")msg.media = [str(doc_path)]@@ -522,7 +434,7 @@ class TestContextAssembly:source_index = context.metadata["source_index"]assert len(source_index) == 1assert "Gradient descent" in next(iter(source_index.values()))- records = runner.store.messages("telegram:42")+ records = _shared_store().messages("telegram:42")attachment = records[0]["attachments"][0]assert attachment["filename"] == "notes.txt"assert "Gradient descent" in attachment["extracted_text"]@@ -531,7 +443,7 @@ class TestContextAssembly:class TestBuiltinToolsAndMemory:@pytest.mark.asyncioasync def test_builtin_tools_default_to_no_gating(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")runner = _runner(partners_root) # builtin_tools=Noneawait runner.process_message(_msg())@@ -542,7 +454,7 @@ class TestBuiltinToolsAndMemory:@pytest.mark.asyncioasync def test_builtin_tools_whitelist_flows_to_context(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")config = PartnerConfig(name="Ada", builtin_tools=["rag", "web_fetch"])runner = _runner(partners_root, config)@@ -559,7 +471,7 @@ class TestBuiltinToolsAndMemory:partner_memorize writes only the partner's own scope."""from deeptutor.partners.config.paths import get_partner_workspace- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")runner = _runner(partners_root)await runner.process_message(_msg())@@ -573,7 +485,7 @@ class TestBuiltinToolsAndMemory:async def test_memory_override_is_reset_after_turn(self, partners_root, fake_orchestrator):from deeptutor.services.memory.paths import memory_root- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")runner = _runner(partners_root)before = memory_root()@@ -592,7 +504,7 @@ class TestBuiltinToolsAndMemory:alice = CurrentUser("u_alice", "alice", "user", scope_for_user("u_alice", is_admin=False))bob = CurrentUser("u_bob", "bob", "user", scope_for_user("u_bob", is_admin=False))- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")runner = _runner(partners_root)first = _msg("alice one")@@ -612,8 +524,8 @@ class TestBuiltinToolsAndMemory:{"role": "user", "content": "alice one"},{"role": "assistant", "content": "ok"},]- alice_store = PartnerSessionStore(get_partner_user_sessions_dir("ada", alice.id))- bob_store = PartnerSessionStore(get_partner_user_sessions_dir("ada", bob.id))+ alice_store = session_store_for("ada", alice)+ bob_store = session_store_for("ada", bob)assert [m["content"] for m in alice_store.messages("telegram:42")] == ["alice one","ok",@@ -621,16 +533,16 @@ class TestBuiltinToolsAndMemory:"ok",]assert [m["content"] for m in bob_store.messages("telegram:42")] == ["bob one", "ok"]- assert runner.store.list_sessions() == []+ assert _shared_store().list_sessions() == []@pytest.mark.asyncioasync def test_turn_trace_persisted_for_rehydration(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _narration_round("c1", "let me check") + _finish("4.")+ fake_orchestrator.script = narration_round("c1", "let me check") + finish("4.")runner = _runner(partners_root)await runner.process_message(_msg("what is 2+2?"))- records = runner.store.messages("telegram:42")+ records = _shared_store().messages("telegram:42")assistant = next(r for r in records if r["role"] == "assistant")events = assistant.get("events")assert events, "assistant turn must persist its trace events"@@ -640,18 +552,18 @@ class TestBuiltinToolsAndMemory:@pytest.mark.asyncioasync def test_session_title_is_first_user_message(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _finish("the answer is 4")+ fake_orchestrator.script = finish("the answer is 4")runner = _runner(partners_root)await runner.process_message(_msg("what is two plus two?"))- session = runner.store.list_sessions()[0]+ session = _shared_store().list_sessions()[0]assert session["title"] == "what is two plus two?"class TestSessionStoreOps:def test_archive_flag_is_soft_and_reversible(self, partners_root):- store = PartnerSessionStore(_runner(partners_root).store._dir)+ store = _shared_store()store.append("web-a", "user", "hi")assert store.is_archived("web-a") is Falsestore.set_archived("web-a", True)@@ -663,7 +575,7 @@ class TestSessionStoreOps:assert store.is_archived("web-a") is Falsedef test_branch_copies_history_and_archives_source(self, partners_root):- store = PartnerSessionStore(_runner(partners_root).store._dir)+ store = _shared_store()store.append("web-a", "user", "q1")store.append("web-a", "assistant", "a1", events=[{"type": "content"}])summary = store.branch("web-a", "web-b")@@ -674,7 +586,7 @@ class TestSessionStoreOps:assert store.messages("web-b")[1].get("events")def test_delete_removes_file_and_index(self, partners_root):- store = PartnerSessionStore(_runner(partners_root).store._dir)+ store = _shared_store()store.append("web-a", "user", "hi")store.set_archived("web-a", True)assert store.delete_session("web-a") is True@@ -716,7 +628,7 @@ class TestLiveTurn:):from deeptutor.services.partners.manager import PartnerManager- fake_orchestrator.script = _narration_round("c1", "working") + _finish("done!")+ fake_orchestrator.script = narration_round("c1", "working") + finish("done!")mgr = PartnerManager()mgr.save_config("ada", PartnerConfig(name="Ada"), auto_start=True)await mgr.start_partner("ada")@@ -748,7 +660,7 @@ class TestLiveTurn:from deeptutor.partners.config.paths import get_partner_user_sessions_dirfrom deeptutor.services.partners.manager import PartnerManager- fake_orchestrator.script = _finish("private reply")+ fake_orchestrator.script = finish("private reply")mgr = PartnerManager()mgr.save_config("ada", PartnerConfig(name="Ada"), auto_start=True)await mgr.start_partner("ada")@@ -756,7 +668,7 @@ class TestLiveTurn:try:with user_context(actor):assert await mgr.send_message("ada", "private question") == "private reply"- private = PartnerSessionStore(get_partner_user_sessions_dir("ada", actor.id))+ private = session_store_for("ada", actor)assert [item["content"] for item in private.merged_messages()] == ["private question","private reply",@@ -772,17 +684,19 @@ class TestPartnerCommands:from deeptutor.services.partners.commands import PartnerCommandHandlerrunner = _runner(partners_root)- fake_orchestrator.script = _finish("ok")+ fake_orchestrator.script = finish("ok")await runner.process_message(_msg("hello")) # creates telegram:42- handler = PartnerCommandHandler(partner_id="ada", config=runner.config, store=runner.store)+ handler = PartnerCommandHandler(+ partner_id="ada", config=runner.config, store=_shared_store()+ )listed = handler.dispatch(_msg("/sessions"))assert listed is not None and "telegram_42" in listed.content# /delete an existing key, /resume clears an archived flag.- runner.store.set_archived("telegram:42", True)+ _shared_store().set_archived("telegram:42", True)resumed = handler.dispatch(_msg("/resume telegram:42"))- assert resumed is not None and not runner.store.is_archived("telegram:42")+ assert resumed is not None and not _shared_store().is_archived("telegram:42")deleted = handler.dispatch(_msg("/delete telegram:42"))assert deleted is not None and "Deleted" in deleted.contentassert handler.dispatch(_msg("/delete telegram:42")).content.startswith("No conversation")@@ -792,7 +706,9 @@ class TestPartnerCommands:from deeptutor.services.partners.commands import PartnerCommandHandlerrunner = _runner(partners_root)- handler = PartnerCommandHandler(partner_id="ada", config=runner.config, store=runner.store)+ handler = PartnerCommandHandler(+ partner_id="ada", config=runner.config, store=_shared_store()+ )result = handler.dispatch(_msg("/stop"))assert result is not None and "nothing" in result.content.lower()@@ -800,7 +716,7 @@ class TestPartnerCommands:async def test_new_archives_current_session_without_calling_orchestrator(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _finish("first reply")+ fake_orchestrator.script = finish("first reply")runner = _runner(partners_root)await runner.process_message(_msg("first question"))assert len(fake_orchestrator.seen_contexts) == 1@@ -809,8 +725,8 @@ class TestPartnerCommands:assert "Started a new conversation" in replyassert len(fake_orchestrator.seen_contexts) == 1- assert runner.store.conversation_history("telegram:42") == []- archived = [session for session in runner.store.list_sessions() if session["archived"]]+ assert _shared_store().conversation_history("telegram:42") == []+ archived = [session for session in _shared_store().list_sessions() if session["archived"]]assert len(archived) == 1assert archived[0]["message_count"] == 2assert archived[0]["session_key"].startswith("_archived_")@@ -818,11 +734,11 @@ class TestPartnerCommands:@pytest.mark.asyncioasync def test_archived_session_does_not_feed_next_turn(self, partners_root, fake_orchestrator):runner = _runner(partners_root)- fake_orchestrator.script = _finish("old reply")+ fake_orchestrator.script = finish("old reply")await runner.process_message(_msg("old question"))await runner.process_message(_msg("/new"))- fake_orchestrator.script = _finish("fresh reply")+ fake_orchestrator.script = finish("fresh reply")await runner.process_message(_msg("fresh question"))context = fake_orchestrator.seen_contexts[-1]@@ -830,7 +746,7 @@ class TestPartnerCommands:@pytest.mark.asyncioasync def test_telegram_bot_command_suffix_is_supported(self, partners_root, fake_orchestrator):- fake_orchestrator.script = _finish("first reply")+ fake_orchestrator.script = finish("first reply")runner = _runner(partners_root)await runner.process_message(_msg("first question"))diff --git a/tests/services/partners/test_weixin_channel.py b/tests/services/partners/test_weixin_channel.pyindex 441098b25..df6e7110b 100644--- a/tests/services/partners/test_weixin_channel.py+++ b/tests/services/partners/test_weixin_channel.py@@ -23,13 +23,17 @@ from deeptutor.partners.channels.weixin import (_parse_aes_key,_pkcs7_unpad_safe,)+from deeptutor.partners.config import paths as partner_paths+from deeptutor.partners.helpers import ensure_dir@pytest.fixturedef state_dir(tmp_path, monkeypatch):"""Redirect default Weixin runtime state to a temp directory."""- monkeypatch.setattr(weixin_mod, "get_runtime_subdir", lambda name: tmp_path / name)+ monkeypatch.setattr(+ partner_paths, "get_runtime_subdir", lambda name: ensure_dir(tmp_path / name)+ )return tmp_path / "weixin"@@ -119,6 +123,12 @@ class TestDefaultAndDiscovery:assert "weixin" in discover_channel_names()assert discover_all()["weixin"] is WeixinChannel+ def test_qr_helper_module_is_not_offered_as_a_channel(self, state_dir):+ """``weixin_qr`` holds the login protocol, not a channel."""+ assert "weixin_qr" in discover_channel_names()+ assert "weixin_qr" not in discover_all()+ assert "weixin_qr" not in all_channel_schemas()+def test_schema_exposes_weixin_and_delivery_fields(self, state_dir):payload = all_channel_schemas()["weixin"]assert payload["display_name"] == "WeChat"@@ -144,6 +154,52 @@ class TestStateAndHeaders:assert loaded._context_tokens == {"wx-user-1": "ctx"}assert loaded._typing_tickets["wx-user-1"]["ticket"] == "typing"+ def test_state_is_isolated_per_partner(self, tmp_path, monkeypatch):+ """Two Partners on WeChat must not share one bot identity."""+ monkeypatch.setattr(partner_paths, "_base_dir", lambda: ensure_dir(tmp_path / "partners"))++ alice = _make_channel(token="")+ alice.partner_id = "alice-tutor"+ bob = _make_channel(token="")+ bob.partner_id = "bob-tutor"++ assert alice._get_state_dir() != bob._get_state_dir()++ alice._token = "token-alice"+ alice._get_updates_buf = "cursor-alice"+ alice._save_state()++ # Bob has no identity of his own: he must NOT inherit Alice's.+ assert bob._load_state() is False+ assert bob._token == ""++ # And Bob logging in must not overwrite Alice's stored identity.+ bob._token = "token-bob"+ bob._get_updates_buf = "cursor-bob"+ bob._save_state()++ reloaded = _make_channel(token="")+ reloaded.partner_id = "alice-tutor"+ assert reloaded._load_state() is True+ assert reloaded._token == "token-alice"+ assert reloaded._get_updates_buf == "cursor-alice"++ def test_configured_token_wins_but_session_still_loads(self, state_dir):+ """Config owns identity; the file owns cursor and context tokens."""+ seeded = _make_channel(token="", state_dir=str(state_dir))+ seeded._token = "token-from-file"+ seeded._get_updates_buf = "cursor"+ seeded._context_tokens = {"wx-user-1": "ctx"}+ seeded._save_state()++ ch = _make_channel(token="token-from-config", state_dir=str(state_dir))+ ch._token = ch.config.token+ ch._load_state()++ assert ch._token == "token-from-config"+ assert ch._get_updates_buf == "cursor"+ assert ch._context_tokens == {"wx-user-1": "ctx"}+def test_headers_include_auth_and_route_tag(self):ch = _make_channel(route_tag="r1")ch._token = "secret-token"diff --git a/tests/services/partners/test_weixin_onboarding.py b/tests/services/partners/test_weixin_onboarding.pynew file mode 100644index 000000000..261cbadbb--- /dev/null+++ b/tests/services/partners/test_weixin_onboarding.py@@ -0,0 +1,329 @@+"""Web-driven personal-WeChat QR login (#951).++The reporter's problem, in the WeChat case: the channel already knew how to log+in by QR, but drew the code on the server's stdout — a supervisord log on any+container deployment, so nobody configuring a partner could ever scan it.++These cover the two things that decides: reading WeChat's status payload+correctly, and never letting the bot token out of the server.+"""++from __future__ import annotations++from typing import Any++import httpx+import pytest++from deeptutor.partners.channels.weixin_qr import (+ QrCode,+ QrOutcome,+ interpret_status,+ is_retryable_poll_error,+ normalize_host,+)+from deeptutor.services.partners import weixin_onboarding++[email protected](autouse=True)+def _clean_attempts():+ weixin_onboarding._attempts.clear()+ yield+ weixin_onboarding._attempts.clear()+++def stub_partner(monkeypatch) -> dict[str, Any]:+ """A partner whose channel config we can read back after a login."""+ saved: dict[str, Any] = {"channels": {"weixin": {}}}++ class _Config:+ channels = saved["channels"]++ class _Manager:+ def load_config(self, partner_id: str): # noqa: ARG002+ return _Config()++ def merge_config(self, partner_id: str, overrides): # noqa: ARG002+ saved["channels"] = overrides["channels"]+ return _Config()++ def save_config(self, partner_id: str, config, **kwargs): # noqa: ARG002+ saved["written"] = True++ monkeypatch.setattr(+ "deeptutor.services.partners.manager.get_partner_manager", lambda: _Manager()+ )+ return saved+++def _stub_exchange(monkeypatch, *, code: str = "qr-1", outcomes: list[QrOutcome] | None = None):+ calls = {"fetched": 0}++ async def _fetch(client, base_url, **kwargs): # noqa: ARG001+ calls["fetched"] += 1+ # A re-issued code is a different code: distinct payload each time.+ return QrCode(+ qrcode_id=f"{code}-{calls['fetched']}",+ scan_payload=f"scan-{code}-{calls['fetched']}",+ )++ queue = list(outcomes or [])++ async def _poll(client, base_url, qrcode_id, **kwargs): # noqa: ARG001+ return queue.pop(0) if queue else QrOutcome(status="waiting")++ monkeypatch.setattr(weixin_onboarding, "fetch_qr_code", _fetch)+ monkeypatch.setattr(weixin_onboarding, "poll_qr_code", _poll)+ return calls+++# ---- reading WeChat's answers ------------------------------------------------+++def test_confirmed_without_a_token_is_a_failure_not_a_success() -> None:+ """Storing an empty token would fail later, far from the cause."""+ assert interpret_status({"status": "confirmed"}).status == "error"+++def test_an_unrecognised_status_means_keep_waiting() -> None:+ """A future WeChat status string must not end a login that is still live."""+ assert interpret_status({"status": "something_new"}).status == "unknown"+ assert interpret_status("not a dict").status == "unknown"+++def test_redirect_is_a_scan_in_progress_carrying_a_new_host() -> None:+ outcome = interpret_status(+ {"status": "scaned_but_redirect", "redirect_host": "other.weixin.qq.com"}+ )++ assert outcome.status == "scanned"+ assert outcome.poll_base_url == "https://other.weixin.qq.com"+++ "raw,expected",+ [+ ("host.qq.com", "https://host.qq.com"),+ ("https://host.qq.com", "https://host.qq.com"),+ ("http://host.qq.com", "http://host.qq.com"),+ ("", ""),+ ],+)+def test_redirect_hosts_are_normalised(raw: str, expected: str) -> None:+ assert normalize_host(raw) == expected+++def test_only_transient_failures_are_worth_another_poll() -> None:+ assert is_retryable_poll_error(httpx.ConnectTimeout("x")) is True+ assert (+ is_retryable_poll_error(+ httpx.HTTPStatusError(+ "x", request=httpx.Request("GET", "https://x"), response=httpx.Response(503)+ )+ )+ is True+ )+ assert (+ is_retryable_poll_error(+ httpx.HTTPStatusError(+ "x", request=httpx.Request("GET", "https://x"), response=httpx.Response(403)+ )+ )+ is False+ )+++# ---- the web-driven attempt --------------------------------------------------+++async def test_start_returns_something_the_browser_can_draw(monkeypatch, stub_partner) -> None:+ _stub_exchange(monkeypatch)++ started = await weixin_onboarding.start_login("p1")++ assert started["scan_payload"] == "scan-qr-1-1"+ assert started["status"] == "waiting"+ assert started["session_id"]+++async def test_a_confirmed_scan_writes_the_token_into_the_channel_config(+ monkeypatch, stub_partner+) -> None:+ _stub_exchange(+ monkeypatch,+ outcomes=[QrOutcome(status="confirmed", token="bot-token", base_url="https://edge")],+ )+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "confirmed"+ assert stub_partner["channels"]["weixin"]["token"] == "bot-token"+ assert stub_partner["channels"]["weixin"]["base_url"] == "https://edge"+ assert stub_partner["written"] is True+++async def test_the_token_never_appears_in_a_response(monkeypatch, stub_partner) -> None:+ """A status reply says whether it worked, never what it produced."""+ _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="confirmed", token="s3cret")])+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert "s3cret" not in str(started)+ assert "s3cret" not in str(status)+ assert "token" not in status+++async def test_a_redirect_moves_where_the_attempt_polls_next(monkeypatch, stub_partner) -> None:+ _stub_exchange(+ monkeypatch,+ outcomes=[QrOutcome(status="scanned", poll_base_url="https://edge-2")],+ )+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "scanned"+ assert weixin_onboarding._attempts[started["session_id"]].poll_base_url == "https://edge-2"+++async def test_an_expired_code_is_reissued_so_a_slow_scan_is_not_a_dead_end(+ monkeypatch, stub_partner+) -> None:+ calls = _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="expired")])+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "waiting"+ assert calls["fetched"] == 2 # the original, plus the replacement+++async def test_repeated_expiry_eventually_ends_the_attempt(monkeypatch, stub_partner) -> None:+ _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="expired")] * 6)+ started = await weixin_onboarding.start_login("p1")++ for _ in range(5):+ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "expired"+++async def test_an_unknown_status_keeps_the_attempt_alive(monkeypatch, stub_partner) -> None:+ _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="unknown")])+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "waiting"+++async def test_confirmed_without_token_is_reported_as_an_error(monkeypatch, stub_partner) -> None:+ _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="error")])+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "error"+ assert status["error"]+ assert "token" not in stub_partner["channels"]["weixin"]+++async def test_a_transient_poll_failure_is_not_a_verdict(monkeypatch, stub_partner) -> None:+ _stub_exchange(monkeypatch)+ started = await weixin_onboarding.start_login("p1")++ async def _boom(*args, **kwargs):+ raise httpx.ConnectTimeout("network blip")++ monkeypatch.setattr(weixin_onboarding, "poll_qr_code", _boom)+ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "waiting"+++async def test_a_session_belonging_to_another_partner_is_not_readable(+ monkeypatch, stub_partner+) -> None:+ _stub_exchange(monkeypatch)+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p2", started["session_id"])++ assert status["status"] == "expired"+++async def test_a_settled_attempt_stops_re_running_the_exchange(monkeypatch, stub_partner) -> None:+ _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="confirmed", token="t")])+ started = await weixin_onboarding.start_login("p1")+ await weixin_onboarding.poll_login("p1", started["session_id"])++ async def _boom(*args, **kwargs):+ raise AssertionError("a confirmed attempt must not poll again")++ monkeypatch.setattr(weixin_onboarding, "poll_qr_code", _boom)+ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "confirmed"+++async def test_start_renders_the_code_server_side(monkeypatch, stub_partner) -> None:+ """The web bundle carries no QR library, so the SVG is drawn here."""+ _stub_exchange(monkeypatch)++ started = await weixin_onboarding.start_login("p1")++ assert started["qr_svg"].lstrip().startswith("<?xml")+ assert "<svg" in started["qr_svg"]+++async def test_a_reissued_code_ships_a_fresh_image_to_redraw(monkeypatch, stub_partner) -> None:+ """Expiry silently swaps the code; polling is the browser's only notice."""+ _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="expired")])+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert status["status"] == "waiting"+ assert "<svg" in status["qr_svg"]+++async def test_an_unchanged_code_does_not_resend_the_image(monkeypatch, stub_partner) -> None:+ _stub_exchange(monkeypatch, outcomes=[QrOutcome(status="waiting")])+ started = await weixin_onboarding.start_login("p1")++ status = await weixin_onboarding.poll_login("p1", started["session_id"])++ assert "qr_svg" not in status+++def test_a_deployment_without_the_qrcode_library_still_gets_a_page(monkeypatch) -> None:+ """`qrcode` rides on the partners extra; missing it must degrade, not fail."""+ import builtins++ real_import = builtins.__import__++ def _no_qrcode(name, *args, **kwargs):+ if name.startswith("qrcode"):+ raise ImportError("no qrcode here")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _no_qrcode)++ assert weixin_onboarding.render_qr_svg("payload") == ""diff --git a/tests/services/test_antigravity_backend.py b/tests/services/test_antigravity_backend.pynew file mode 100644index 000000000..d017e6dae--- /dev/null+++ b/tests/services/test_antigravity_backend.py@@ -0,0 +1,294 @@+"""Antigravity CLI (``agy``) subagent backend (#828).++Google retired Gemini CLI on 2026-06-18, so for plan-based users the `gemini`+backend has no CLI left to detect. These tests pin the replacement's wire+contract: the `agy` command line, and its stream-json event vocabulary — which+is *not* Gemini CLI's despite the shared lineage.+"""++from __future__ import annotations++import json+from typing import Any++import pytest++from deeptutor.services.subagent.antigravity import AntigravityBackend+from deeptutor.services.subagent.config import BackendConfig+++def _stream(*events: dict[str, Any], exit_code: str = "0"):+ """Replay a canned stdout stream in stream_process_lines' shape."""++ async def _fake(cmd, cwd=None, **kwargs): # noqa: ARG001+ for event in events:+ yield "stdout", json.dumps(event)+ yield "exit", exit_code++ return _fake+++async def _consult(backend: AntigravityBackend, monkeypatch, *events, exit_code: str = "0"):+ monkeypatch.setattr(+ "deeptutor.services.subagent.antigravity.stream_process_lines",+ _stream(*events, exit_code=exit_code),+ )+ seen: list[Any] = []++ async def on_event(event):+ seen.append(event)++ result = await backend.consult("q", on_event=on_event)+ return result, seen+++# ---- command line ------------------------------------------------------------+++def test_fresh_command_carries_prompt_stream_format_model_and_effort() -> None:+ cmd = AntigravityBackend()._build_command(+ "hi",+ session_id=None,+ config=BackendConfig(system_prompt="be brief", model="gemini-3-pro", effort="high"),+ )++ assert cmd[:3] == ["agy", "-p", "be brief\n\nhi"]+ assert cmd[cmd.index("--output-format") + 1] == "stream-json"+ assert cmd[cmd.index("--model") + 1] == "gemini-3-pro"+ assert cmd[cmd.index("--effort") + 1] == "high"+ assert "--conversation" not in cmd+++def test_resume_uses_conversation_and_drops_the_system_prompt() -> None:+ """The resumed conversation already carries the delegate instruction."""+ cmd = AntigravityBackend()._build_command(+ "again",+ session_id="conv-1",+ config=BackendConfig(system_prompt="be brief"),+ )++ assert cmd[:3] == ["agy", "-p", "again"]+ assert cmd[cmd.index("--conversation") + 1] == "conv-1"++[email protected]("mode", ["bypassPermissions", "acceptEdits"])+def test_permissive_modes_waive_approval(mode: str) -> None:+ cmd = AntigravityBackend()._build_command(+ "hi", session_id=None, config=BackendConfig(permission_mode=mode)+ )++ assert "--dangerously-skip-permissions" in cmd++[email protected]("mode", ["default", "plan"])+def test_cautious_modes_keep_the_clis_soft_deny(mode: str) -> None:+ """Headless `agy` soft-denies rather than blocking, so this cannot stall."""+ cmd = AntigravityBackend()._build_command(+ "hi", session_id=None, config=BackendConfig(permission_mode=mode)+ )++ assert "--dangerously-skip-permissions" not in cmd+++def test_unknown_effort_is_dropped_rather_than_passed_through() -> None:+ """`--effort` only accepts low/medium/high; anything else exits non-zero."""+ cmd = AntigravityBackend()._build_command(+ "hi", session_id=None, config=BackendConfig(effort="ultra")+ )++ assert "--effort" not in cmd+++def test_images_are_named_as_paths_for_the_agents_own_read_tools() -> None:+ cmd = AntigravityBackend()._build_command(+ "describe", session_id=None, config=BackendConfig(), images=["/tmp/a.png"]+ )++ assert "/tmp/a.png" in cmd[2]+++# ---- event stream ------------------------------------------------------------+++async def test_text_deltas_accumulate_into_the_final_answer(monkeypatch) -> None:+ """`step_update.text_delta` chunks have no aggregate event to fall back on."""+ result, _ = await _consult(+ AntigravityBackend(),+ monkeypatch,+ {"event": "init", "conversation_id": "c1", "init": {"model": "gemini-3-pro"}},+ {"event": "step_update", "step_update": {"step_index": 0, "text_delta": "4 is "}},+ {"event": "step_update", "step_update": {"step_index": 0, "text_delta": "the answer."}},+ )++ assert result.final_text == "4 is the answer."+ assert result.success is True+++async def test_conversation_id_is_captured_for_resume(monkeypatch) -> None:+ result, _ = await _consult(+ AntigravityBackend(),+ monkeypatch,+ {"event": "init", "conversation_id": "conv-42", "init": {}},+ {"event": "step_update", "step_update": {"step_index": 0, "text_delta": "hi"}},+ )++ assert result.session_id == "conv-42"+++async def test_result_event_response_wins_over_accumulated_deltas(monkeypatch) -> None:+ result, _ = await _consult(+ AntigravityBackend(),+ monkeypatch,+ {"event": "step_update", "step_update": {"step_index": 0, "text_delta": "partial"}},+ {"event": "result", "result": {"status": "SUCCESS", "response": "the whole answer"}},+ )++ assert result.final_text == "the whole answer"++[email protected]("status", ["ERROR", "CANCELED", "INTERRUPTED", "INVALID"])+async def test_failing_result_status_marks_the_consult_failed(monkeypatch, status: str) -> None:+ result, _ = await _consult(+ AntigravityBackend(),+ monkeypatch,+ {"event": "result", "result": {"status": status, "error": "boom"}},+ )++ assert result.success is False+ assert "boom" in result.error+++async def test_tool_steps_surface_with_a_readable_header(monkeypatch) -> None:+ _, seen = await _consult(+ AntigravityBackend(),+ monkeypatch,+ {+ "event": "step_update",+ "step_update": {+ "step_index": 1,+ "state": "ACTIVE",+ "tool_name": "Shell",+ "tool_info": {"args": {"command": "ls -la"}},+ },+ },+ )++ assert any(e.kind == "tool" and e.text == "Shell(ls -la)" for e in seen)+++async def test_a_tool_starts_a_new_text_block(monkeypatch) -> None:+ """Prose after a tool call reads as its own row, not glued to the earlier one."""+ result, _ = await _consult(+ AntigravityBackend(),+ monkeypatch,+ {"event": "step_update", "step_update": {"step_index": 0, "text_delta": "Looking…"}},+ {"event": "step_update", "step_update": {"step_index": 1, "tool_name": "Shell"}},+ {"event": "step_update", "step_update": {"step_index": 2, "text_delta": "Found it."}},+ )++ assert result.final_text == "Looking…\n\nFound it."+++async def test_empty_stream_is_reported_not_returned_as_a_blank_answer(monkeypatch) -> None:+ """antigravity-cli#76: `-p` can emit nothing when stdout is not a TTY.++ Silence must not reach the caller as the agent having nothing to say — the+ model in the sidebar would look like it answered with an empty message.+ """+ result, seen = await _consult(AntigravityBackend(), monkeypatch)++ assert result.success is False+ assert "#76" in result.error+ assert any(e.kind == "error" for e in seen)+++async def test_nonzero_exit_without_output_is_surfaced(monkeypatch) -> None:+ result, _ = await _consult(AntigravityBackend(), monkeypatch, exit_code="1")++ assert result.success is False+++async def test_non_json_stdout_becomes_a_log_line_not_a_crash(monkeypatch) -> None:+ async def _fake(cmd, cwd=None, **kwargs): # noqa: ARG001+ yield "stdout", "warning: something plain"+ yield (+ "stdout",+ json.dumps({"event": "result", "result": {"status": "SUCCESS", "response": "ok"}}),+ )+ yield "exit", "0"++ monkeypatch.setattr("deeptutor.services.subagent.antigravity.stream_process_lines", _fake)+ seen: list[Any] = []++ async def on_event(event):+ seen.append(event)++ result = await AntigravityBackend().consult("q", on_event=on_event)++ assert result.final_text == "ok"+ assert any(e.kind == "log" for e in seen)+++# ---- registry ----------------------------------------------------------------+++def test_backend_is_registered_as_a_local_cli() -> None:+ from deeptutor.services.subagent import get_backend++ backend = get_backend("antigravity")++ assert backend is not None+ assert backend.cli_command == "agy"+ assert backend.local_cli is True+++def test_gemini_cli_is_kept_alongside_it() -> None:+ """#828 asked to replace Gemini CLI; API-key users still have a working one."""+ from deeptutor.services.subagent import get_backend++ assert get_backend("gemini") is not None+++async def test_options_expose_the_effort_flag_and_free_text_models() -> None:+ from deeptutor.services.subagent.models import sync_backend_options++ options = await sync_backend_options("antigravity")++ assert options.kind == "antigravity"+ assert [e for e in options.efforts] == ["low", "medium", "high"]+ assert options.allow_custom_model is True+++def test_missing_cli_detail_says_something_the_status_chip_does_not() -> None:+ """`probe_version` returns a bare "not installed", which told the reader nothing.++ The Gemini CLI page in #828 showed exactly that, leaving the reporter to work+ out on their own that Google had retired the CLI.+ """+ from deeptutor.services.subagent.process import not_found_detail++ assert not_found_detail("not installed", "go install it") == "go install it"+ assert not_found_detail("", "go install it") == "go install it"+ # Real probe output is more informative and still wins.+ assert not_found_detail("permission denied", "go install it") == "permission denied"+++async def test_retired_gemini_cli_points_at_its_successor() -> None:+ from deeptutor.services.subagent.models import sync_backend_options++ detail = (await sync_backend_options("gemini")).detail++ # Skipped where a Gemini CLI really is installed — then there is no detail.+ if detail:+ assert "Antigravity" in detaildiff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.pyindex 132a08851..7b12fc3ff 100644--- a/tests/services/test_subagent_backends.py+++ b/tests/services/test_subagent_backends.py@@ -683,7 +683,15 @@ async def test_detect_all_excludes_partner_backend() -> None:kinds = {d.kind for d in await detect_all()}assert "partner" not in kinds- assert kinds <= {"claude_code", "codex", "gemini", "kimi", "opencode", "mimo"}+ assert kinds <= {+ "claude_code",+ "codex",+ "gemini",+ "antigravity",+ "kimi",+ "opencode",+ "mimo",+ }# ---- partner backend: drive a partner as a subagent --------------------------@@ -707,6 +715,11 @@ class _FakePartnerManager:self.sent: list[dict] = []self._trace: list = []+ def owner_id(self, partner_id: str) -> str:+ # These partners are admin-created, so the access check falls through+ # to the grant rather than short-circuiting on ownership.+ return ""+def script_trace(self, events: list) -> None:self._trace = eventsdiff --git a/web/app/(utility)/settings/agents/antigravity/page.tsx b/web/app/(utility)/settings/agents/antigravity/page.tsxnew file mode 100644index 000000000..848352d35--- /dev/null+++ b/web/app/(utility)/settings/agents/antigravity/page.tsx@@ -0,0 +1,7 @@+"use client";++import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++export default function AntigravityAgentSettingsPage() {+ return <SubagentSettingsEditor kind="antigravity" />;+}diff --git a/web/app/(utility)/space/learning/page.tsx b/web/app/(utility)/space/learning/page.tsxindex 689283b79..f02524584 100644--- a/web/app/(utility)/space/learning/page.tsx+++ b/web/app/(utility)/space/learning/page.tsx@@ -16,6 +16,7 @@ import {fetchMasteryMap,deleteProgress,redoProgress,+ renameProgress,skipPendingQuestion,type ProgressSummary,type MasteryMapResult,@@ -24,6 +25,7 @@ import { newMasteryPathChatUrl } from "@/lib/chat-launch-intent";import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";import { ActivityTimeline } from "@/components/space/learning/ActivityTimeline";import { PathMap } from "@/components/space/learning/PathMap";+import { PathTitle } from "@/components/space/learning/PathTitle";import { formatRelative } from "@/components/space/learning/format";/**@@ -139,6 +141,27 @@ export default function MasteryPathPage() {[afterMutation, tr],);+ const handleRename = useCallback(+ async (pathId: string, name: string) => {+ const { name: applied } = await renameProgress(pathId, name);+ // Show it at once. Everything else on this page refreshes by noticing a+ // new revision in the event feed, which is right for changes made by a+ // tutoring turn elsewhere and wrong for an edit made right here: the+ // title would stay stale for up to one poll interval.+ setDetail((previous) =>+ previous && previous.book_id === pathId+ ? {+ ...previous,+ name: applied,+ map: { ...previous.map, name: applied },+ }+ : previous,+ );+ await afterMutation();+ },+ [afterMutation],+ );+const handleSkipQuestion = useCallback(async (pathId: string) => {if (@@ -239,6 +262,7 @@ export default function MasteryPathPage() {<PathViewpathId={selected}result={detail}+ onRename={(name) => handleRename(selected, name)}revision={revision}events={events}objectiveNames={objectiveNames}@@ -280,6 +304,7 @@ function PathView({zh,tr,onContinue,+ onRename,onSkipQuestion,onRedo,onDelete,@@ -294,6 +319,7 @@ function PathView({zh: boolean;tr: (cn: string, en: string) => string;onContinue: () => void;+ onRename: (name: string) => Promise<void>;onSkipQuestion: () => void;onRedo: () => void;onDelete: () => void;@@ -313,7 +339,15 @@ function PathView({{/* Header: progress + actions */}<div className="flex items-start justify-between gap-4"><div className="min-w-0 flex-1">- <div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">+ {/* Keyed by path: an open editor belongs to the path it was+ opened on, and its draft must not follow a switch. */}+ <PathTitle+ key={pathId}+ name={result.name}+ onRename={onRename}+ tr={tr}+ />+ <div className="mt-1 flex items-center gap-2 text-sm text-[var(--muted-foreground)]"><span>{map.counts.mastered}/{map.counts.total}{" "}{tr("已掌握", "mastered")}diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 3960e56ea..6dd2d08ae 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -80,6 +80,7 @@ import {import { classifyFile, isSvgFilename } from "@/lib/doc-attachments";import { readChatLaunchIntent } from "@/lib/chat-launch-intent";import { useAttachmentLimits } from "@/lib/attachment-limits";+import { hasPendingAskUser } from "@/lib/ask-user-state";import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";import { useSetupSync } from "@/hooks/useSetupSync";@@ -1033,6 +1034,25 @@ export default function ChatPage() {scrollToBottom("instant");}, [scrollToBottom, shouldAutoScrollRef]);+ /* A card waiting on the user is the one thing that MUST be on screen: the+ turn cannot continue until they act on it. Reading the question that+ precedes it normally scrolls up, which releases the streaming pin — so a+ quiz card would appear below the fold, under the composer, and the+ conversation looked stalled. Re-arm the pin and land on the card. */+ const awaitingUserReply = hasPendingAskUser(lastMessage?.events);+ // Read inside ``handleSend`` without adding a dependency that would rebuild+ // the callback (and so the composer) on every streamed event.+ const awaitingUserReplyRef = useRef(awaitingUserReply);+ awaitingUserReplyRef.current = awaitingUserReply;+ useEffect(() => {+ if (!awaitingUserReply) return;+ shouldAutoScrollRef.current = true;+ // One frame later: the card has to be laid out before the bottom it+ // defines exists.+ const frame = requestAnimationFrame(() => scrollToBottom("instant"));+ return () => cancelAnimationFrame(frame);+ }, [awaitingUserReply, scrollToBottom, shouldAutoScrollRef]);+const copyAssistantMessage = useCallback(async (content: string) => {if (!content.trim()) return;try {@@ -1687,6 +1707,14 @@ export default function ChatPage() {const handleSend = useCallback(async (content: string) => {+ // A turn paused on a question: what the user typed is their answer, not+ // a new message. Routing it here means the card is one way to answer,+ // not the only one — and a card that never rendered no longer strands+ // the learner with a turn they can only cancel.+ if (awaitingUserReplyRef.current) {+ if (content.trim()) submitUserReply({ text: content });+ return;+ }if ((!content &&!attachments.length &&@@ -1797,6 +1825,7 @@ export default function ChatPage() {shouldAutoScrollRef,state.isStreaming,subagentBudget,+ submitUserReply,t,visualizeConfig,],@@ -2309,6 +2338,7 @@ export default function ChatPage() {onPersonaSelectorOpenChange={setPersonaSelectorOpen}onToggleMemoryFile={handleToggleMemoryFile}onSend={handleSend}+ awaitingUserReply={awaitingUserReply}onRemoveAttachment={removeAttachment}onPreviewAttachment={handlePreviewPendingAttachment}onRemoveHistory={handleRemoveHistory}diff --git a/web/app/(workspace)/partners/[partnerId]/page.tsx b/web/app/(workspace)/partners/[partnerId]/page.tsxindex edf28fefa..edf5088c9 100644--- a/web/app/(workspace)/partners/[partnerId]/page.tsx+++ b/web/app/(workspace)/partners/[partnerId]/page.tsx@@ -13,6 +13,7 @@ import {Archive,BookmarkPlus,Download,+ Link2,Loader2,MessageCircle,Play,@@ -42,6 +43,7 @@ import PartnerChat from "@/components/partners/PartnerChat";import PartnerChannels from "@/components/partners/PartnerChannels";import PartnerConfigure from "@/components/partners/PartnerConfigure";import PartnerArchives from "@/components/partners/PartnerArchives";+import PartnerLinkModal from "@/components/partners/PartnerLinkModal";import SaveToNotebookModal, {type NotebookSaveMessage,type NotebookSavePayload,@@ -63,6 +65,14 @@ function PartnerDetail() {: "chat",);const [partner, setPartner] = useState<PartnerInfo | null>(null);+ const [showLinkModal, setShowLinkModal] = useState(false);+ // A partner shared with you is a companion, not a project: you talk to it and+ // read your own history, but its soul, channels and library stay its owner's.+ const canManage = partner?.can_manage !== false;+ // ``?tab=`` is user-supplied, so a management tab on a shared partner (or+ // before the partner has loaded) resolves to Chat rather than an empty pane.+ const activeTab: Tab =+ !canManage && (tab === "configure" || tab === "channels") ? "chat" : tab;const [loading, setLoading] = useState(true);const [lifecycleBusy, setLifecycleBusy] = useState(false);const [toast, setToast] = useState("");@@ -94,10 +104,10 @@ function PartnerDetail() {}, [toast]);const exportMessages = useMemo<ExportableMessage[]>(() => {- if (tab === "chat") return chatMessages;- if (tab === "archive") return archiveMessages;+ if (activeTab === "chat") return chatMessages;+ if (activeTab === "archive") return archiveMessages;return [];- }, [tab, chatMessages, archiveMessages]);+ }, [activeTab, chatMessages, archiveMessages]);const canExport = exportMessages.length > 0;@@ -222,8 +232,12 @@ function PartnerDetail() {const tabs: { key: Tab; label: string; icon: typeof MessageCircle }[] = [{ key: "chat", label: t("Chat"), icon: MessageCircle },- { key: "configure", label: t("Configure"), icon: Settings2 },- { key: "channels", label: t("Channels"), icon: Radio },+ ...(canManage+ ? ([+ { key: "configure", label: t("Configure"), icon: Settings2 },+ { key: "channels", label: t("Channels"), icon: Radio },+ ] as const)+ : []),{ key: "archive", label: t("Archive"), icon: Archive },];@@ -271,7 +285,7 @@ function PartnerDetail() {type="button"onClick={() => setTab(key)}className={`inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[12px] transition-colors ${- tab === key+ activeTab === key? "bg-[var(--background)] font-medium text-[var(--foreground)] shadow-sm": "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}@@ -282,7 +296,7 @@ function PartnerDetail() {))}</nav>- {(tab === "chat" || tab === "archive") && (+ {(activeTab === "chat" || activeTab === "archive") && (<><buttontype="button"@@ -308,33 +322,54 @@ function PartnerDetail() {)}<buttontype="button"- onClick={() => void toggleRunning()}- disabled={lifecycleBusy}- title={partner.running ? t("Stop") : t("Start")}- className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40"- >- {lifecycleBusy ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : partner.running ? (- <Square className="h-4 w-4" />- ) : (- <Play className="h-4 w-4" />- )}- </button>- <button- type="button"- onClick={() => void handleDestroy()}- title={t("Delete partner")}- className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-red-500"+ onClick={() => setShowLinkModal(true)}+ title={t("Link a chat account")}+ aria-label={t("Link a chat account")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]">- <Trash2 className="h-4 w-4" />+ <Link2 className="h-4 w-4" /></button>+ {canManage ? (+ <>+ <button+ type="button"+ onClick={() => void toggleRunning()}+ disabled={lifecycleBusy}+ title={partner.running ? t("Stop") : t("Start")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {lifecycleBusy ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : partner.running ? (+ <Square className="h-4 w-4" />+ ) : (+ <Play className="h-4 w-4" />+ )}+ </button>+ <button+ type="button"+ onClick={() => void handleDestroy()}+ title={t("Delete partner")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-red-500"+ >+ <Trash2 className="h-4 w-4" />+ </button>+ </>+ ) : null}</div>+ {showLinkModal ? (+ <PartnerLinkModal+ partnerId={partnerId}+ partnerName={partner.name}+ onClose={() => setShowLinkModal(false)}+ />+ ) : null}+{/* Body. Chat stays mounted (hidden off-tab) so an in-progress turn —its WebSocket and live trace — survives switching to another tab. */}<div className="min-h-0 flex-1">- <div className={tab === "chat" ? "h-full" : "hidden"}>+ <div className={activeTab === "chat" ? "h-full" : "hidden"}><div className="mx-auto h-full max-w-3xl px-5"><PartnerChatpartnerId={partnerId}@@ -350,7 +385,7 @@ function PartnerDetail() {/></div></div>- {tab === "archive" ? (+ {activeTab === "archive" ? (<div className="mx-auto h-full max-w-5xl overflow-hidden px-5 py-5"><PartnerArchivespartnerId={partnerId}@@ -362,7 +397,7 @@ function PartnerDetail() {}}/></div>- ) : tab === "configure" ? (+ ) : activeTab === "configure" ? (<div className="mx-auto h-full max-w-3xl overflow-y-auto px-5 py-5"><PartnerConfigurepartner={partner}@@ -370,7 +405,7 @@ function PartnerDetail() {onUpdated={() => void load()}/></div>- ) : tab === "channels" ? (+ ) : activeTab === "channels" ? (<div className="mx-auto h-full max-w-3xl overflow-y-auto px-5 py-5"><PartnerChannels partnerId={partnerId} onToast={setToast} /></div>diff --git a/web/app/(workspace)/partners/page.tsx b/web/app/(workspace)/partners/page.tsxindex 6ef54c3ae..ab64088ad 100644--- a/web/app/(workspace)/partners/page.tsx+++ b/web/app/(workspace)/partners/page.tsx@@ -7,17 +7,9 @@import { useCallback, useEffect, useState } from "react";import Link from "next/link";-import { useRouter } from "next/navigation";import { HeartHandshake, Loader2, Plus } from "lucide-react";import { useTranslation } from "react-i18next";import { listPartners, type PartnerInfo } from "@/lib/partners-api";-import {- connectSubagent,- listConnectablePartners,- listSubagentConnections,- type ConnectablePartner,-} from "@/lib/subagents-api";-import { useAuthStatus } from "@/hooks/useAuthStatus";import ChannelIcon from "@/components/partners/ChannelIcon";import PartnerAvatar from "@/components/partners/PartnerAvatar";@@ -30,97 +22,29 @@ function channelNames(partner: PartnerInfo): string[] {return [];}-function asPartnerInfo(card: ConnectablePartner): PartnerInfo {- // A non-admin only ever sees identity cards (no channel wiring); normalize- // into the shape the card grid renders, with no channels.- return {- partner_id: card.partner_id,- name: card.name,- description: card.description || "",- channels: [],- emoji: card.emoji,- color: card.color,- avatar: card.avatar,- language: card.language,- running: Boolean(card.running),- started_at: null,- };-}-export default function PartnersPage() {- const router = useRouter();const { t } = useTranslation();- // Partners are admin-managed: an admin sees & manages every partner, while a- // non-admin sees only the partners assigned to them, read-only (creation and- // editing stay admin-only). The list source differs accordingly.- const { isAdmin, loading: authLoading } = useAuthStatus();+ // Anyone may build partners of their own; an admin may also assign theirs to+ // other people. The list returns both — the caller's own partners in full and+ // assigned ones as identity cards — so there is one source either way.const [partners, setPartners] = useState<PartnerInfo[]>([]);const [loading, setLoading] = useState(true);- const [busyId, setBusyId] = useState<string | null>(null);-- // Clicking a partner card. An admin drills into the management page; a- // non-admin can't manage partners — for them a partner is consulted as a- // connected agent, so we reuse (or create) that partner's subagent- // connection and drop them straight into a fresh chat with it preselected.- const openPartner = useCallback(- async (partner: PartnerInfo) => {- if (isAdmin) {- router.push(`/partners/${partner.partner_id}`);- return;- }- setBusyId(partner.partner_id);- try {- const conns = await listSubagentConnections();- const existing = conns.find(- (c) =>- c.agent_kind === "partner" && c.partner_id === partner.partner_id,- );- let name = existing?.name;- if (!name) {- const taken = new Set(conns.map((c) => c.name));- const base = partner.name?.trim() || partner.partner_id;- let candidate = base;- for (let i = 2; taken.has(candidate); i++)- candidate = `${base} (${i})`;- name = (- await connectSubagent({- name: candidate,- agent_kind: "partner",- partner_id: partner.partner_id,- })- ).name;- }- router.push(`/home?agent=${encodeURIComponent(name)}`);- } catch {- // Couldn't auto-connect (e.g. the name clashes with an existing KB) —- // fall back to My Agents, where the partner can be connected by hand.- router.push("/agents");- } finally {- setBusyId(null);- }- },- [isAdmin, router],- );+ const anyAssigned = partners.some((partner) => partner.can_manage === false);const load = useCallback(async () => {setLoading(true);try {- if (isAdmin) {- setPartners(await listPartners());- } else {- setPartners((await listConnectablePartners()).map(asPartnerInfo));- }+ setPartners(await listPartners());} catch {setPartners([]);} finally {setLoading(false);}- }, [isAdmin]);+ }, []);useEffect(() => {- if (authLoading) return;void load();- }, [authLoading, load]);+ }, [load]);return (<div className="mx-auto h-full max-w-4xl overflow-y-auto px-6 py-8">@@ -130,24 +54,22 @@ export default function PartnersPage() {{t("Partners")}</h1><p className="mt-1 text-[12.5px] text-[var(--muted-foreground)]">- {isAdmin+ {anyAssigned? t(- "Companions with their own soul, library, and channels — reachable from your IM apps.",+ "Your companions, plus the ones shared with you — each with its own soul, library, and channels.",): t(- "Partners your administrator has assigned to you. Click one to start chatting with it.",+ "Companions with their own soul, library, and channels — reachable from your IM apps.",)}</p></div>- {isAdmin ? (- <Link- href="/partners/new"- className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)] hover:opacity-90"- >- <Plus className="h-3.5 w-3.5" />- {t("New partner")}- </Link>- ) : null}+ <Link+ href="/partners/new"+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)] hover:opacity-90"+ >+ <Plus className="h-3.5 w-3.5" />+ {t("New partner")}+ </Link></header>{loading ? (@@ -161,38 +83,30 @@ export default function PartnersPage() {strokeWidth={1.5}/><p className="text-[14px] font-medium text-[var(--foreground)]">- {isAdmin ? t("No partners yet") : t("No partners assigned yet")}+ {t("No partners yet")}</p><p className="mt-1.5 max-w-sm text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">- {isAdmin- ? t(- "Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.",- )- : t(- "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.",- )}+ {t(+ "Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.",+ )}</p>- {isAdmin ? (- <Link- href="/partners/new"- className="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)]"- >- <Plus className="h-3.5 w-3.5" />- {t("Create your first partner")}- </Link>- ) : null}+ <Link+ href="/partners/new"+ className="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2 text-[12.5px] font-medium text-[var(--primary-foreground)]"+ >+ <Plus className="h-3.5 w-3.5" />+ {t("Create your first partner")}+ </Link></div>) : (<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">{partners.map((partner) => {const channels = channelNames(partner);return (- <button+ <Linkkey={partner.partner_id}- type="button"- onClick={() => void openPartner(partner)}- disabled={busyId === partner.partner_id}- className="group flex items-start gap-3 rounded-2xl border border-[var(--border)] p-4 text-left transition-colors hover:border-[var(--ring)] disabled:opacity-60"+ href={`/partners/${encodeURIComponent(partner.partner_id)}`}+ className="group flex items-start gap-3 rounded-2xl border border-[var(--border)] p-4 text-left transition-colors hover:border-[var(--ring)]"><PartnerAvatarname={partner.name}@@ -206,18 +120,19 @@ export default function PartnersPage() {<span className="truncate text-[14px] font-medium text-[var(--foreground)]">{partner.name}</span>- {busyId === partner.partner_id ? (- <Loader2 className="h-3 w-3 shrink-0 animate-spin text-[var(--muted-foreground)]" />- ) : (- <span- title={partner.running ? t("Running") : t("Stopped")}- className={`h-1.5 w-1.5 shrink-0 rounded-full ${- partner.running- ? "bg-emerald-500"- : "bg-[var(--border)]"- }`}- />- )}+ <span+ title={partner.running ? t("Running") : t("Stopped")}+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${+ partner.running+ ? "bg-emerald-500"+ : "bg-[var(--border)]"+ }`}+ />+ {partner.can_manage === false ? (+ <span className="shrink-0 rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10.5px] text-[var(--muted-foreground)]">+ {t("Shared with you")}+ </span>+ ) : null}</div>{partner.description ? (<p className="mt-0.5 line-clamp-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">@@ -242,7 +157,7 @@ export default function PartnersPage() {)}</div></div>- </button>+ </Link>);})}</div>diff --git a/web/app/(workspace)/whisper/page.tsx b/web/app/(workspace)/whisper/page.tsxindex f2948f262..705887adf 100644--- a/web/app/(workspace)/whisper/page.tsx+++ b/web/app/(workspace)/whisper/page.tsx@@ -6,6 +6,7 @@ import { Ear, Loader2 } from "lucide-react";import WhisperComposer from "@/components/whisper/WhisperComposer";import WhisperMessageList from "@/components/whisper/WhisperMessageList";import WhisperRoomChip from "@/components/whisper/WhisperRoomChip";+import { useCapabilityFilter } from "@/lib/capabilities-api";import {UnifiedWSClient,type StartTurnMessage,@@ -281,6 +282,33 @@ export default function WhisperPage() {const canNewRoom = Boolean(roomId || roomClosed || crisisHit);+ // Whisper's seats are served by the out-of-tree psych-academy capability, not+ // by this repository. Where it was never installed every send comes back as+ // `Unknown capability: whisper_visitor` (#963), so say so here rather than+ // letting the learner find out one message in. Still loading (`null`) renders+ // the room as usual, so an install that does have the plugin never waits.+ const capabilityAvailable = useCapabilityFilter();+ if (capabilityAvailable && !capabilityAvailable("whisper_visitor")) {+ return (+ <div className="flex h-full min-h-0 flex-col items-center justify-center px-6">+ <div className="max-w-md text-center">+ <Ear+ className="mx-auto h-6 w-6 text-[var(--muted-foreground)]"+ aria-hidden+ />+ <h1 className="mt-3 text-sm font-medium text-[var(--foreground)]">+ {t("Whisper is not installed on this server")}+ </h1>+ <p className="mt-1.5 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "The practice room runs on a separate capability plugin that this deployment does not have. Ask your administrator to install it to use this page.",+ )}+ </p>+ </div>+ </div>+ );+ }+return (<div className="flex h-full min-h-0 flex-col"><header className="flex flex-wrap items-center justify-between gap-3 border-b border-[var(--border)] px-4 py-3">diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsxindex 975293ea1..24e0fdd6c 100644--- a/web/components/agents/ConnectedAgents.tsx+++ b/web/components/agents/ConnectedAgents.tsx@@ -36,6 +36,7 @@ function backendLabel(kind: string, tr: (l: Lang) => string): string {if (kind === "claude_code") return "Claude Code";if (kind === "codex") return "Codex";if (kind === "gemini") return "Gemini CLI";+ if (kind === "antigravity") return "Antigravity CLI";if (kind === "kimi") return "Kimi CLI";if (kind === "opencode") return "opencode";if (kind === "mimo") return "MiMo Code";diff --git a/web/components/agents/agent-icons.tsx b/web/components/agents/agent-icons.tsxindex a56ad4a98..82cd36b39 100644--- a/web/components/agents/agent-icons.tsx+++ b/web/components/agents/agent-icons.tsx@@ -197,6 +197,8 @@ export function agentGlyph(kind: string | undefined): AgentGlyph | null {if (kind === "claude_code") return ClaudeGlyph;if (kind === "codex") return CodexGlyph;if (kind === "gemini") return GeminiGlyph;+ // Google's own successor to Gemini CLI, and it carries the same mark.+ if (kind === "antigravity") return GeminiGlyph;if (kind === "kimi") return KimiGlyph;if (kind === "opencode") return OpencodeGlyph;if (kind === "mimo") return MimoGlyph;diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsxindex 22e2589cb..15fc5cf2e 100644--- a/web/components/chat/home/AskUserOptions.tsx+++ b/web/components/chat/home/AskUserOptions.tsx@@ -183,7 +183,16 @@ export type MessageSegment =data: AskUserCardData;toolCallId: string | null;key: string;- };+ }+ /**+ * The trace of the round(s) that ran AFTER a card — the reasoning the+ * resumed turn produced once the user answered. It renders below the+ * card it followed, because the message's activity block is pinned to+ * the top: everything emitted after a submit used to land back up+ * there, above content the user had already scrolled past, so the+ * turn looked frozen after they picked an option.+ */+ | { kind: "trace"; events: StreamEvent[]; key: string };export function extractMessageSegments(events: StreamEvent[] | undefined,@@ -197,6 +206,8 @@ export function extractMessageSegments(const byToolCall = new Map<string, number>();const seenAskUserCards = new Set<string>();let pendingTextIdx: number | null = null;+ let pendingTraceIdx: number | null = null;+ let sawAskUser = false;let seq = 0;// Narration rounds (chat-loop preamble alongside a tool call) stream as// content but belong in the trace, not the answer — keep them out of the@@ -204,6 +215,7 @@ export function extractMessageSegments(const narrationCallIds = collectNarrationCallIds(events);const ensureTextSegment = () => {+ pendingTraceIdx = null;if (pendingTextIdx === null) {pendingTextIdx = segments.length;segments.push({ kind: "text", text: "", key: `t${seq++}` });@@ -211,10 +223,24 @@ export function extractMessageSegments(return pendingTextIdx;};+ /** Collect one post-card trace event; a no-op before the first card. */+ const appendTraceEvent = (event: StreamEvent) => {+ if (!sawAskUser) return;+ if (pendingTraceIdx === null) {+ pendingTraceIdx = segments.length;+ segments.push({ kind: "trace", events: [], key: `r${seq++}` });+ }+ const seg = segments[pendingTraceIdx];+ if (seg.kind === "trace") seg.events.push(event);+ };+for (const event of events) {if (shouldAppendEventContent(event)) {const callId = ((event.metadata ?? {}) as { call_id?: string }).call_id;- if (callId && narrationCallIds.has(callId)) continue;+ if (callId && narrationCallIds.has(callId)) {+ appendTraceEvent(event);+ continue;+ }const idx = ensureTextSegment();const seg = segments[idx];if (seg.kind === "text") {@@ -225,10 +251,16 @@ export function extractMessageSegments(const meta = (event.metadata ?? {}) as Record<string, unknown>;if (event.type === "tool_result") {const toolMetadata = meta.tool_metadata;- if (!toolMetadata || typeof toolMetadata !== "object") continue;- const askUser = (toolMetadata as Record<string, unknown>).ask_user;+ const askUser =+ toolMetadata && typeof toolMetadata === "object"+ ? (toolMetadata as Record<string, unknown>).ask_user+ : null;const normalised = normaliseAskUserPayload(askUser);- if (!normalised) continue;+ if (!normalised) {+ // Any other tool's result is trace material for the region.+ appendTraceEvent(event);+ continue;+ }const toolCallId =(event as { tool_call_id?: string }).tool_call_id ??(typeof meta.tool_call_id === "string" ? meta.tool_call_id : null);@@ -237,9 +269,11 @@ export function extractMessageSegments(: `payload:${JSON.stringify(normalised)}`;if (seenAskUserCards.has(cardKey)) continue;seenAskUserCards.add(cardKey);- // Close the current text run so the next text chunk starts a new- // segment after this card.+ // Close the current text and trace runs so what the resumed round+ // emits starts fresh segments below this card.pendingTextIdx = null;+ pendingTraceIdx = null;+ sawAskUser = true;const idx = segments.length;segments.push({kind: "ask_user",@@ -306,12 +340,39 @@ export function extractMessageSegments(resolved: true,},};+ // The resolution belongs to the card, not to the trace below it.+ continue;}+ appendTraceEvent(event);}// Drop empty trailing/leading text segments so the renderer doesn't- // emit blank ``<AssistantResponse>`` nodes.- return segments.filter((s) => s.kind !== "text" || s.text.length > 0);+ // emit blank ``<AssistantResponse>`` nodes, and trace regions whose+ // events all turned out to be unrenderable.+ return segments.filter((s) =>+ s.kind === "text"+ ? s.text.length > 0+ : s.kind !== "trace" || s.events.length > 0,+ );+}++/**+ * The events whose trace rows still belong to the message's top activity+ * block: everything the segments did not claim for a post-card region.+ * Pass it as ``AssistantActivity``'s ``traceEvents`` (or to a bare+ * ``TraceFlow``) so a resumed round's reasoning is not shown twice — once+ * where the user is looking, and once back above the card.+ */+export function leadingTraceEvents(+ events: StreamEvent[] | undefined,+ segments: MessageSegment[],+): StreamEvent[] {+ const claimed = new Set<StreamEvent>();+ for (const segment of segments) {+ if (segment.kind !== "trace") continue;+ for (const event of segment.events) claimed.add(event);+ }+ return (events ?? []).filter((event) => !claimed.has(event));}/**diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex b0948b662..8bbcc5af3 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -208,6 +208,7 @@ export default memo(function ChatComposer({selectedMemoryFiles,selectedKnowledgeBases,isStreaming,+ awaitingUserReply = false,isVisualizeMode,capabilityNeedsConfig,capabilityConfigConfirmed,@@ -298,6 +299,8 @@ export default memo(function ChatComposer({selectedMemoryFiles: SpaceMemoryFile[];selectedKnowledgeBases: string[];isStreaming: boolean;+ /** The live turn is paused on an ask_user card and needs an answer. */+ awaitingUserReply?: boolean;isVisualizeMode: boolean;/*** True when the active capability (e.g. Quiz / Visualize / Research)@@ -511,13 +514,18 @@ export default memo(function ChatComposer({// (via `onRequestConfigConfirm`) instead of silently doing nothing.const isConfigBlocked = capabilityNeedsConfig && !capabilityConfigConfirmed;const hasIntent = hasContent || hasReferences;- const canSend = hasIntent && !isStreaming && !isConfigBlocked;+ // A turn paused on a question is technically still streaming, but the only+ // thing that can move it forward is the user's answer. Locking the composer+ // there made the interactive card the ONLY way to answer — and left the+ // learner with no way out at all if the card failed to render.+ const streamingBlocksSend = isStreaming && !awaitingUserReply;+ const canSend = hasIntent && !streamingBlocksSend && !isConfigBlocked;// `blocked` only exists once there is intent: without it the button stays// `idle` so an empty composer doesn't present a live send affordance. That// makes intent — not `canSend` — the thing that decides interactivity, so// the `blocked` state can stay clickable and surface the config card.- const sendState: SendState = isStreaming+ const sendState: SendState = streamingBlocksSend? "streaming": !hasIntent? "idle"@@ -637,17 +645,22 @@ export default memo(function ChatComposer({doSend(content);}, [canSend, doSend, isConfigBlocked, onRequestConfigConfirm]);- // One button, so one handler: mid-turn the same control cancels.+ // One button, so one handler: mid-turn the same control cancels — except+ // while the turn is waiting on the user, where sending IS how it continues.const handleSendButtonClick = useCallback(() => {- if (isStreaming) {+ if (streamingBlocksSend) {onCancelStreaming();return;}handleManualSend();- }, [handleManualSend, isStreaming, onCancelStreaming]);+ }, [handleManualSend, streamingBlocksSend, onCancelStreaming]);const sendLabel =- sendState === "streaming" ? t("Stop generating") : t("Send");+ sendState === "streaming"+ ? t("Stop generating")+ : awaitingUserReply+ ? t("Send answer")+ : t("Send");const sendTitle =sendState === "blocked"? t("Confirm settings on the right to send.")diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex 15733a0cf..89acde006 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -60,13 +60,14 @@ import {AskUserOptions,extractAskUserPayload,extractMessageSegments,+ leadingTraceEvents,} from "./AskUserOptions";import { SetupCredentialCard } from "./SetupCredentialCard";import { extractSetupCredential } from "@/lib/setup-signals";import ContextReferenceTree, {type ContextTreeItem,} from "./ContextReferenceTree";-import { AssistantActivity } from "./TracePanels";+import { AssistantActivity, NestedTraceFlow } from "./TracePanels";import { agentGlyph } from "@/components/agents/agent-icons";import { useConnectedAgentKinds } from "@/hooks/useConnectedAgentKinds";@@ -404,6 +405,16 @@ const AssistantMessage = memo(function AssistantMessage({const hasInlineAskUser =useInlineAskUserSegments &&messageSegments.some((seg) => seg.kind === "ask_user");+ // The activity block is pinned to the top of the message, so it can only+ // show the rounds that ran BEFORE the first card. What the resumed rounds+ // reason about renders below the card they answer, in stream order.+ const headerTraceEvents = useMemo(+ () =>+ hasInlineAskUser+ ? leadingTraceEvents(events, messageSegments)+ : undefined,+ [hasInlineAskUser, messageSegments, events],+ );const researchInProgress =outlineStatus === "researching" || outlineStatus === "done";@@ -418,6 +429,7 @@ const AssistantMessage = memo(function AssistantMessage({still working, collapsed once it settles into the final answer. */}<AssistantActivityevents={events}+ traceEvents={headerTraceEvents}isStreaming={isStreaming}content={msg.content}className="mb-3"@@ -503,6 +515,14 @@ const AssistantMessage = memo(function AssistantMessage({content={seg.text}isStreaming={isStreaming}/>+ ) : seg.kind === "trace" ? (+ // What DeepTutor worked out after the user answered — shown+ // where they are looking, not back up in the header block.+ <NestedTraceFlow+ key={seg.key}+ events={seg.events}+ isStreaming={isStreaming}+ />) : (<AskUserOptionskey={seg.key}diff --git a/web/components/chat/home/MasteryPathStrip.tsx b/web/components/chat/home/MasteryPathStrip.tsxindex 0920e1bb4..4525f6fd6 100644--- a/web/components/chat/home/MasteryPathStrip.tsx+++ b/web/components/chat/home/MasteryPathStrip.tsx@@ -56,7 +56,7 @@ export default function MasteryPathStrip({ pathId }: { pathId: string }) {<div className="mx-auto mb-2 flex w-full max-w-[760px] items-center gap-2.5 px-1 text-xs text-[var(--muted-foreground)]"><GraduationCap className="h-3.5 w-3.5 shrink-0" /><span className="shrink-0 font-medium text-[var(--foreground)]">- {map.modules[0]?.name || tr("精通之路", "Mastery Path")}+ {result.name || tr("精通之路", "Mastery Path")}</span><span className="h-1 w-16 shrink-0 overflow-hidden rounded-full bg-[var(--accent)]"><spandiff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsxindex 4fba7737b..40b6cfe8a 100644--- a/web/components/chat/home/TracePanels.tsx+++ b/web/components/chat/home/TracePanels.tsx@@ -2453,6 +2453,26 @@ export function TraceFlow({return <CallTracePanel events={events} isStreaming={isStreaming} />;}+/**+ * Trace rows hanging from the guide line that aligns them under the activity+ * mark, so they read as "nested below" whatever they belong to. Shared by the+ * status header's own trace and by the resumed-round trace the chat surface+ * renders under an ``ask_user`` card.+ */+export function NestedTraceFlow({+ events,+ isStreaming,+}: {+ events: StreamEvent[];+ isStreaming?: boolean;+}) {+ return (+ <div className="ml-[11px] border-l border-[var(--border)]/45 pl-[13px] pt-2 [&>div]:mb-0">+ <TraceFlow events={events} isStreaming={isStreaming} />+ </div>+ );+}+/*** Has the turn entered its final-answer phase? Used to auto-collapse the* reasoning trace once DeepTutor stops working and starts (or has finished)@@ -2520,6 +2540,7 @@ function isFinalAnswerPhase(*/export function AssistantActivity({events,+ traceEvents,isStreaming,content,className = "",@@ -2528,6 +2549,15 @@ export function AssistantActivity({headerClassName = "",}: {events: StreamEvent[];+ /**+ * The subset of ``events`` whose trace rows belong under this header.+ * Defaults to all of them. The chat surface narrows it to the rounds+ * before the first ``ask_user`` card, because the rounds after one render+ * below that card instead — this block is pinned to the top of the+ * message, so anything appended here after the user answers lands above+ * content they have already read.+ */+ traceEvents?: StreamEvent[];isStreaming?: boolean;content?: string;className?: string;@@ -2539,7 +2569,11 @@ export function AssistantActivity({* vertically centers against an adjacent avatar). */headerClassName?: string;}) {- const hasTrace = useMemo(() => hasRenderableCallTrace(events), [events]);+ const shownTraceEvents = traceEvents ?? events;+ const hasTrace = useMemo(+ () => hasRenderableCallTrace(shownTraceEvents),+ [shownTraceEvents],+ );const hasFinalContent = Boolean(content && content.trim().length > 0);const finalPhase = useMemo(() => isFinalAnswerPhase(events, Boolean(isStreaming), hasFinalContent),@@ -2580,9 +2614,10 @@ export function AssistantActivity({below the header when open; [&>div]:mb-0 stripsCallTracePanel's own bottom margin so the single gap to thebody comes from this block's outer ``mb-3`` in both states. */}- <div className="ml-[11px] border-l border-[var(--border)]/45 pl-[13px] pt-2 [&>div]:mb-0">- <TraceFlow events={events} isStreaming={isStreaming} />- </div>+ <NestedTraceFlow+ events={shownTraceEvents}+ isStreaming={isStreaming}+ /></div></div>) : null}diff --git a/web/components/knowledge/KbGitHubSourcesSection.tsx b/web/components/knowledge/KbGitHubSourcesSection.tsxindex e838252fb..d70aabe31 100644--- a/web/components/knowledge/KbGitHubSourcesSection.tsx+++ b/web/components/knowledge/KbGitHubSourcesSection.tsx@@ -2,13 +2,7 @@import { useCallback, useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import {- Github,- Loader2,- Plus,- RefreshCw,- Trash2,-} from "lucide-react";+import { Github, Loader2, Plus, RefreshCw, Trash2 } from "lucide-react";import {addGitHubSource,listGitHubSources,@@ -99,7 +93,9 @@ export default function KbGitHubSourcesSection({const failed = results.filter((r) => !r.ok);if (failed.length > 0) {setError(- failed.map((r) => `${r.repo}: ${r.error ?? "unknown error"}`).join("\n"),+ failed+ .map((r) => `${r.repo}: ${r.error ?? "unknown error"}`)+ .join("\n"),);}await refresh();@@ -186,7 +182,10 @@ export default function KbGitHubSourcesSection({className="w-full rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]"/></FormField>- <FormField label={t("Path prefix")} help={t("e.g. docs/ — leave empty for root")}>+ <FormField+ label={t("Path prefix")}+ help={t("e.g. docs/ — leave empty for root")}+ ><inputtype="text"value={pathInput}@@ -231,7 +230,7 @@ export default function KbGitHubSourcesSection({<div className="rounded-lg border border-dashed border-[var(--border)] py-8 text-center"><Github className="mx-auto mb-2 h-6 w-6 text-[var(--muted-foreground)]" /><p className="text-[12px] text-[var(--muted-foreground)]">- {t("No GitHub sources yet. Click \"Add source\" to track a repo.")}+ {t('No GitHub sources yet. Click "Add source" to track a repo.')}</p></div>) : (diff --git a/web/components/partners/PartnerChannels.tsx b/web/components/partners/PartnerChannels.tsxindex 3b4824d24..7dcd5a063 100644--- a/web/components/partners/PartnerChannels.tsx+++ b/web/components/partners/PartnerChannels.tsx@@ -20,6 +20,7 @@ import {defaultFor,type JsonSchema,} from "@/components/partners/schema-form";+import WeixinQrLogin from "@/components/partners/WeixinQrLogin";import ChannelIcon from "@/components/partners/ChannelIcon";import ChannelOnboardingPanel from "@/components/partners/ChannelOnboardingPanel";@@ -107,6 +108,13 @@ export default function PartnerChannels({setActiveChannel(enabled ?? names[0] ?? null);}, [schemaCatalog, channels, activeChannel]);+ // A confirmed WeChat scan wrote the token into the config server-side;+ // re-read so the form shows what is actually stored.+ const onWeixinConnected = useCallback(() => {+ onToast(t("WeChat connected."));+ void loadDetail();+ }, [loadDetail, onToast, t]);+const toggleSecret = useCallback((path: string) => {setRevealed((prev) => {const next = new Set(prev);@@ -289,6 +297,14 @@ export default function PartnerChannels({{(activeEntry.json_schema as JsonSchema).description}</p>)}+ {/* Personal WeChat authenticates by scanning, not by pasting+ a secret; the fields below stay as the manual fallback. */}+ {activeChannel === "weixin" && partnerId && (+ <WeixinQrLogin+ partnerId={partnerId}+ onConfirmed={onWeixinConnected}+ />+ )}{Object.entries((activeEntry.json_schema as JsonSchema).properties ?? {},).map(([k, child]) => (diff --git a/web/components/partners/PartnerLinkModal.tsx b/web/components/partners/PartnerLinkModal.tsxnew file mode 100644index 000000000..d706647ed--- /dev/null+++ b/web/components/partners/PartnerLinkModal.tsx@@ -0,0 +1,209 @@+"use client";++/**+ * Connect a chat account (QQ, Telegram, …) to your DeepTutor account.+ *+ * Without a link, a partner reached over a channel sees only a channel-local+ * sender id: the conversation lands in a shared pool you cannot read back here,+ * and the partner answers without your library or memory. Claiming a code from+ * that chat account closes the gap — and the code is deliberately short-lived+ * and single-use, since whoever sends it becomes you for that partner.+ */++import { useCallback, useEffect, useState } from "react";+import { Check, Copy, Link2, Loader2, X } from "lucide-react";+import { useTranslation } from "react-i18next";+import {+ createPartnerLinkCode,+ listPartnerLinks,+ removePartnerLink,+ type PartnerLink,+ type PartnerLinkCode,+} from "@/lib/partners-api";+import ChannelIcon from "@/components/partners/ChannelIcon";++export default function PartnerLinkModal({+ partnerId,+ partnerName,+ onClose,+}: {+ partnerId: string;+ partnerName: string;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const [links, setLinks] = useState<PartnerLink[]>([]);+ const [code, setCode] = useState<PartnerLinkCode | null>(null);+ const [loading, setLoading] = useState(true);+ const [issuing, setIssuing] = useState(false);+ const [copied, setCopied] = useState(false);+ const [error, setError] = useState("");++ const load = useCallback(async () => {+ setLoading(true);+ try {+ setLinks(await listPartnerLinks(partnerId));+ } catch {+ setLinks([]);+ } finally {+ setLoading(false);+ }+ }, [partnerId]);++ useEffect(() => {+ void load();+ }, [load]);++ const issue = useCallback(async () => {+ setIssuing(true);+ setError("");+ setCopied(false);+ try {+ setCode(await createPartnerLinkCode(partnerId));+ } catch {+ setError(t("Couldn't create a code. Try again."));+ } finally {+ setIssuing(false);+ }+ }, [partnerId, t]);++ const copy = useCallback(async () => {+ if (!code) return;+ try {+ await navigator.clipboard.writeText(code.command);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch {+ setError(t("Couldn't copy — select the command and copy it by hand."));+ }+ }, [code, t]);++ const unlink = useCallback(+ async (key: string) => {+ try {+ await removePartnerLink(partnerId, key);+ await load();+ } catch {+ setError(t("Couldn't disconnect that account. Try again."));+ }+ },+ [partnerId, load, t],+ );++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"+ onClick={onClose}+ >+ <div+ className="w-full max-w-md rounded-2xl border border-[var(--border)] bg-[var(--background)] p-5 shadow-xl"+ onClick={(event) => event.stopPropagation()}+ >+ <div className="mb-3 flex items-start justify-between gap-3">+ <div>+ <h2 className="text-[15px] font-semibold text-[var(--foreground)]">+ {t("Link a chat account")}+ </h2>+ <p className="mt-1 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Connect the account you message {{name}} from, so those conversations are private to you and it can reach your library and notes there.",+ { name: partnerName },+ )}+ </p>+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label={t("Close")}+ className="rounded-md p-1 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <X className="h-4 w-4" />+ </button>+ </div>++ {code ? (+ <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)] p-3.5">+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {t(+ "Send this to {{name}} as a direct message from the chat account you want to connect:",+ { name: partnerName },+ )}+ </p>+ <div className="mt-2 flex items-center gap-2">+ <code className="flex-1 select-all rounded-lg bg-[var(--background)] px-3 py-2 font-mono text-[13.5px] text-[var(--foreground)]">+ {code.command}+ </code>+ <button+ type="button"+ onClick={() => void copy()}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-2 text-[12px] text-[var(--foreground)] hover:bg-[var(--background)]"+ >+ {copied ? (+ <Check className="h-3.5 w-3.5 text-emerald-500" />+ ) : (+ <Copy className="h-3.5 w-3.5" />+ )}+ {copied ? t("Copied") : t("Copy")}+ </button>+ </div>+ <p className="mt-2 text-[11.5px] text-[var(--muted-foreground)]">+ {t("Valid for 15 minutes, and usable once.")}+ </p>+ </div>+ ) : (+ <button+ type="button"+ onClick={() => void issue()}+ disabled={issuing}+ className="inline-flex w-full items-center justify-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-2.5 text-[12.5px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-60"+ >+ {issuing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Link2 className="h-3.5 w-3.5" />+ )}+ {t("Get a link code")}+ </button>+ )}++ {error ? (+ <p className="mt-2 text-[12px] text-red-500">{error}</p>+ ) : null}++ <div className="mt-4">+ <h3 className="text-[12px] font-medium text-[var(--foreground)]">+ {t("Connected accounts")}+ </h3>+ {loading ? (+ <Loader2 className="mt-2 h-4 w-4 animate-spin text-[var(--muted-foreground)]" />+ ) : links.length === 0 ? (+ <p className="mt-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("No chat accounts connected yet.")}+ </p>+ ) : (+ <ul className="mt-2 space-y-1.5">+ {links.map((link) => (+ <li+ key={link.key}+ className="flex items-center gap-2 rounded-lg border border-[var(--border)] px-3 py-2"+ >+ <ChannelIcon name={link.channel} size={13} />+ <span className="flex-1 truncate text-[12.5px] text-[var(--foreground)]">+ {link.channel} · {link.sender_id}+ </span>+ <button+ type="button"+ onClick={() => void unlink(link.key)}+ className="text-[11.5px] text-[var(--muted-foreground)] hover:text-red-500"+ >+ {t("Disconnect")}+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/web/components/partners/SoulPicker.tsx b/web/components/partners/SoulPicker.tsxindex c3e639a7e..9fcc17310 100644--- a/web/components/partners/SoulPicker.tsx+++ b/web/components/partners/SoulPicker.tsx@@ -10,6 +10,7 @@import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";+import { useAuthStatus } from "@/hooks/useAuthStatus";import {BookHeart,Check,@@ -50,6 +51,8 @@ export default function SoulPicker({onChange: (next: SoulSpec) => void;}) {const { t } = useTranslation();+ // The soul library is shared deployment-wide; only an admin may add to it.+ const { isAdmin } = useAuthStatus();const [sources, setSources] = useState<SoulSources | null>(null);const [tab, setTab] = useState<SourceTab>(value.source === "persona"@@ -229,7 +232,7 @@ export default function SoulPicker({</div>)}- {tab === "custom" && (value.content ?? "").trim() && (+ {isAdmin && tab === "custom" && (value.content ?? "").trim() && (<div className="flex flex-wrap items-center gap-2"><inputvalue={saveName}diff --git a/web/components/partners/WeixinQrLogin.tsx b/web/components/partners/WeixinQrLogin.tsxnew file mode 100644index 000000000..a2ea046d0--- /dev/null+++ b/web/components/partners/WeixinQrLogin.tsx@@ -0,0 +1,161 @@+"use client";++/**+ * Scan-to-connect for the personal-WeChat channel (#951).+ *+ * The channel authenticates by QR and always has — but it drew the code on the+ * server's stdout, which on a container deployment is a supervisord log the+ * admin cannot read. So its own advice, "scan the QR code to authenticate", had+ * nowhere to be followed. This panel is that missing surface.+ *+ * The token is never in flight here: the server writes it into the partner's+ * channel config and these replies only ever say whether the scan succeeded.+ */++import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Loader2, QrCode, RefreshCw } from "lucide-react";+import {+ pollWeixinQr,+ startWeixinQr,+ type WeixinQrSession,+} from "@/lib/partners-api";++const POLL_INTERVAL_MS = 2000;++export default function WeixinQrLogin({+ partnerId,+ onConfirmed,+}: {+ partnerId: string;+ /** The config now holds a token — the caller reloads to show it masked. */+ onConfirmed?: () => void;+}) {+ const { t } = useTranslation();+ const [session, setSession] = useState<WeixinQrSession | null>(null);+ const [svg, setSvg] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ // Polling closes over the session it started with; a ref keeps the timer+ // pointed at the current attempt when the admin restarts the scan.+ const sessionRef = useRef<string>("");++ const settled =+ session?.status === "confirmed" ||+ session?.status === "expired" ||+ session?.status === "error";++ const start = useCallback(async () => {+ setBusy(true);+ setError("");+ try {+ const started = await startWeixinQr(partnerId);+ sessionRef.current = started.session_id;+ setSession(started);+ setSvg(started.qr_svg ?? "");+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setBusy(false);+ }+ }, [partnerId]);++ useEffect(() => {+ if (!session || settled) return;+ let cancelled = false;+ const timer = setTimeout(async () => {+ try {+ const next = await pollWeixinQr(partnerId, sessionRef.current);+ if (cancelled || next.session_id !== sessionRef.current) return;+ setSession(next);+ // Only sent when the code actually changed, so an unchanged reply must+ // not blank the image already on screen.+ if (next.qr_svg) setSvg(next.qr_svg);+ if (next.status === "confirmed") onConfirmed?.();+ } catch (e) {+ if (!cancelled) setError(e instanceof Error ? e.message : String(e));+ }+ }, POLL_INTERVAL_MS);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [session, settled, partnerId, onConfirmed]);++ const statusLine = () => {+ switch (session?.status) {+ case "waiting":+ return t("Waiting for a scan…");+ case "scanned":+ return t("Scanned — confirm on your phone.");+ case "confirmed":+ return t("Connected. The bot token has been saved.");+ case "expired":+ return t("This code expired. Start a new scan.");+ case "error":+ return session.error || t("The scan failed.");+ default:+ return "";+ }+ };++ return (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--card)] p-3">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]">+ <QrCode className="h-3.5 w-3.5 text-[var(--primary)]" aria-hidden />+ {t("Scan to connect")}+ </div>+ <button+ type="button"+ onClick={() => void start()}+ disabled={busy}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--ring)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {busy ? (+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ ) : (+ <RefreshCw className="h-3 w-3" aria-hidden />+ )}+ {session ? t("New code") : t("Get a code")}+ </button>+ </div>++ <p className="mt-1.5 text-[11px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Sign in with the WeChat account this partner should speak as. The bot token is saved on the server.",+ )}+ </p>++ {error && (+ <p className="mt-2 text-[11px] text-red-600 dark:text-red-400">+ {error}+ </p>+ )}++ {session && !error && (+ <div className="mt-3 flex items-center gap-3">+ {svg && session.status !== "confirmed" ? (+ <div+ className="h-[132px] w-[132px] shrink-0 rounded-md bg-white p-1.5 [&_svg]:h-full [&_svg]:w-full"+ // Server-rendered from the scan payload: a QR path, no scripting.+ dangerouslySetInnerHTML={{ __html: svg }}+ role="img"+ aria-label={t("WeChat login QR code")}+ />+ ) : null}+ <div className="min-w-0 text-[11px] text-[var(--muted-foreground)]">+ <p>{statusLine()}</p>+ {/* Without the server-side `qrcode` library there is no image to+ draw, so show the payload rather than an empty box. */}+ {!svg && session.scan_payload && session.status !== "confirmed" && (+ <p className="mt-1 break-all font-mono text-[10px] opacity-80">+ {session.scan_payload}+ </p>+ )}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/web/components/quiz/QuizFollowupTabBody.tsx b/web/components/quiz/QuizFollowupTabBody.tsxindex 85f38c96c..104f27e69 100644--- a/web/components/quiz/QuizFollowupTabBody.tsx+++ b/web/components/quiz/QuizFollowupTabBody.tsx@@ -28,6 +28,7 @@ import FollowupChatComposer from "@/components/quiz/FollowupChatComposer";import {AskUserOptions,extractMessageSegments,+ leadingTraceEvents,} from "@/components/chat/home/AskUserOptions";import { StreamingStatus, TraceFlow } from "@/components/chat/home/TracePanels";import { useSmoothStreamText } from "@/hooks/useSmoothStreamText";@@ -323,6 +324,12 @@ function AssistantThreadMessage({[message.events],);const hasInlineAskUser = segments.some((s) => s.kind === "ask_user");+ // Same split as the main chat surface: rounds that ran after a card+ // render below it, so this top trace keeps only what came before.+ const headerTraceEvents = useMemo(+ () => leadingTraceEvents(message.events, segments),+ [message.events, segments],+ );// Smooth the trailing-text growth via the shared rAF typewriter so// the markdown renderer sees a steadily-growing string instead of// bursty deltas. Off when ``isStreaming`` is false — the hook@@ -331,7 +338,7 @@ function AssistantThreadMessage({return (<div className="flex flex-col gap-1.5">- <TraceFlow events={message.events ?? []} isStreaming={isStreaming} />+ <TraceFlow events={headerTraceEvents} isStreaming={isStreaming} />{hasInlineAskUser ? (segments.map((seg) =>seg.kind === "text" ? (@@ -343,6 +350,12 @@ function AssistantThreadMessage({<MarkdownRenderer content={seg.text} variant="compact" /></div>) : null+ ) : seg.kind === "trace" ? (+ <TraceFlow+ key={seg.key}+ events={seg.events}+ isStreaming={isStreaming}+ />) : (<AskUserOptionskey={seg.key}diff --git a/web/components/settings/SubagentSettingsEditor.tsx b/web/components/settings/SubagentSettingsEditor.tsxindex b3dd90801..e07cb9cd0 100644--- a/web/components/settings/SubagentSettingsEditor.tsx+++ b/web/components/settings/SubagentSettingsEditor.tsx@@ -104,6 +104,17 @@ const KIND_FEATURES: Record<string, KindFeatures> = {thinking: false,forwardImages: true, // @path syntax},+ antigravity: {+ effort: true, // --effort low|medium|high+ systemPrompt: true,+ permissionMode: true, // permissive modes map onto --dangerously-skip-permissions+ codexSandbox: false,+ autoApprove: false,+ thinking: false,+ // Headless `agy` documents no attachment flag; images are named as paths+ // in the prompt for the agent's own file-reading tools instead.+ forwardImages: false,+ },kimi: {effort: false,systemPrompt: true,diff --git a/web/components/space/SpaceDashboard.tsx b/web/components/space/SpaceDashboard.tsxindex 305a15c9b..54bec4160 100644--- a/web/components/space/SpaceDashboard.tsx+++ b/web/components/space/SpaceDashboard.tsx@@ -3,6 +3,7 @@import { useCallback, useEffect, useMemo, useState } from "react";import Link from "next/link";import { useTranslation } from "react-i18next";+import { useCapabilityFilter } from "@/lib/capabilities-api";import {ArrowUpRight,ClipboardList,@@ -69,6 +70,13 @@ interface DashboardItem {load?: () => Promise<number>;/** GitHub handle of the contributor this surface came from. */credit?: string;+ /**+ * Turn capability this surface needs, when it is not served by this+ * repository. The tile is withheld unless the backend registry actually+ * holds the name, so a stock install never offers a room whose capability+ * was never installed (#963).+ */+ requiresCapability?: string;}interface DashboardGroup {@@ -214,6 +222,8 @@ const GROUPS: DashboardGroup[] = [},tile: "bg-fuchsia-500/10 text-fuchsia-600 dark:text-fuchsia-400",credit: "alanguan73",+ // Served by the out-of-tree psych-academy plugin, not by this repo.+ requiresCapability: "whisper_visitor",},],},@@ -221,6 +231,33 @@ const GROUPS: DashboardGroup[] = [const ALL_ITEMS = GROUPS.flatMap((g) => g.items);+/**+ * The groups to render, given what the backend can actually serve.+ *+ * `isAvailable` is null while the probe is in flight: gated tiles stay hidden+ * until then, so a surface whose capability was never installed does not flash+ * into view and out again — an ungated tile is never affected. A group left+ * with no tiles is dropped along with its heading, or "More Projects" would+ * render as a title over nothing (#963).+ */+export function visibleGroups(+ groups: DashboardGroup[],+ isAvailable: ((name: string) => boolean) | null,+): DashboardGroup[] {+ return groups+ .map((group) => ({+ ...group,+ items: group.items.filter(+ (item) =>+ !item.requiresCapability ||+ (isAvailable?.(item.requiresCapability) ?? false),+ ),+ }))+ .filter((group) => group.items.length > 0);+}++export { GROUPS as DASHBOARD_GROUPS };+export default function SpaceDashboard() {const { i18n } = useTranslation();const zh = i18n.language?.toLowerCase().startsWith("zh");@@ -228,6 +265,12 @@ export default function SpaceDashboard() {const [counts, setCounts] = useState<Partial<Record<DashKey, number>>>({});+ const capabilityAvailable = useCapabilityFilter();+ const groups = useMemo(+ () => visibleGroups(GROUPS, capabilityAvailable),+ [capabilityAvailable],+ );+useEffect(() => {let cancelled = false;// Each tile loads independently so one slow/failed endpoint never blanks@@ -263,7 +306,7 @@ export default function SpaceDashboard() {</header><div className="space-y-9">- {GROUPS.map((group) => (+ {groups.map((group) => (<section key={group.label.en}><h2 className="mb-3 px-0.5 font-serif text-[16px] font-semibold tracking-tight text-[var(--foreground)]">{tr(group.label)}diff --git a/web/components/space/learning/ActivityTimeline.tsx b/web/components/space/learning/ActivityTimeline.tsxindex 3c773f4d9..a7df13ad7 100644--- a/web/components/space/learning/ActivityTimeline.tsx+++ b/web/components/space/learning/ActivityTimeline.tsx@@ -83,6 +83,12 @@ function describe(}case "path.reset":return tr("重置了进度", "Progress reset");+ case "path.renamed": {+ const renamed = String(event.payload?.name ?? "").trim();+ return renamed+ ? tr(`改名为「${renamed}」`, `Renamed to "${renamed}"`)+ : tr("恢复了自动命名", "Restored the derived name");+ }case "interaction.registered":return tr(`出了一道题:${name}`, `Posed a question on ${name}`);case "interaction.awaiting_input":diff --git a/web/components/space/learning/PathTitle.tsx b/web/components/space/learning/PathTitle.tsxnew file mode 100644index 000000000..f74d14673--- /dev/null+++ b/web/components/space/learning/PathTitle.tsx@@ -0,0 +1,136 @@+"use client";++import { Check, Pencil, X } from "lucide-react";+import { useEffect, useRef, useState } from "react";++import type { Translate } from "./format";++/**+ * The path's name, and the only place it can be changed.+ *+ * A path is named by the tutor when it is built, which makes that name a good+ * default and a poor final answer — it is the learner's course, so the learner+ * gets to say what it is called. Editing happens in place rather than through a+ * dialog: the title is one line, and a modal for one line reads as a bigger+ * commitment than renaming actually is.+ *+ * Submitting an empty name is allowed and meaningful — it hands the path back+ * to its derived name (the tutor's, or the first module's) instead of pinning+ * an empty string.+ *+ * Losing focus does NOT save. A rename is a deliberate act, and committing on+ * blur turns "clicked somewhere else" into a silent rename — while also racing+ * whatever focus the field was given when it opened. Blur only closes an+ * editor the learner never changed.+ */+export function PathTitle({+ name,+ onRename,+ tr,+}: {+ name: string;+ /** Resolves once the new name is committed; may reject. */+ onRename: (name: string) => Promise<void>;+ tr: Translate;+}) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(name);+ const [saving, setSaving] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);++ // Reopen on a different path (or after a rename lands) with that path's name,+ // never with whatever was half-typed for the previous one.+ useEffect(() => {+ if (!editing) setDraft(name);+ }, [name, editing]);++ useEffect(() => {+ if (editing) inputRef.current?.select();+ }, [editing]);++ const commit = async () => {+ if (saving) return;+ const next = draft.trim();+ if (next === name.trim()) {+ setEditing(false);+ return;+ }+ setSaving(true);+ try {+ await onRename(next);+ setEditing(false);+ } catch {+ // Keep the editor open with the text still in it — the alternative is+ // silently discarding what they typed.+ } finally {+ setSaving(false);+ }+ };++ const cancel = () => {+ setDraft(name);+ setEditing(false);+ };++ if (!editing) {+ return (+ <div className="flex min-w-0 items-center gap-1.5">+ <h2 className="truncate text-sm font-semibold text-[var(--foreground)]">+ {name}+ </h2>+ {/* Always present, like the reset/delete controls beside it. A+ hover-revealed affordance does not exist on a touch screen. */}+ <button+ onClick={() => setEditing(true)}+ title={tr("重命名", "Rename")}+ className="shrink-0 cursor-pointer rounded p-1 text-[var(--muted-foreground)]/60 transition-colors hover:bg-[var(--accent)] hover:text-[var(--foreground)]"+ >+ <Pencil className="h-3 w-3" />+ </button>+ </div>+ );+ }++ return (+ <div className="flex min-w-0 items-center gap-1.5">+ <input+ ref={inputRef}+ value={draft}+ autoFocus+ disabled={saving}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") void commit();+ if (event.key === "Escape") cancel();+ }}+ onBlur={() => {+ if (draft.trim() === name.trim()) setEditing(false);+ }}+ maxLength={200}+ placeholder={tr("这条路叫什么?", "What is this path called?")}+ className="min-w-0 flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-sm text-[var(--foreground)] outline-none focus:border-[var(--primary)] disabled:opacity-60"+ />+ {/* mousedown, not click: blur fires first and would commit-then-cancel. */}+ <button+ onMouseDown={(event) => {+ event.preventDefault();+ void commit();+ }}+ title={tr("保存", "Save")}+ className="shrink-0 cursor-pointer rounded p-1 text-[var(--muted-foreground)] hover:bg-[var(--accent)] hover:text-[var(--foreground)]"+ >+ <Check className="h-3.5 w-3.5" />+ </button>+ <button+ onMouseDown={(event) => {+ event.preventDefault();+ cancel();+ }}+ title={tr("取消", "Cancel")}+ className="shrink-0 cursor-pointer rounded p-1 text-[var(--muted-foreground)] hover:bg-[var(--accent)] hover:text-[var(--foreground)]"+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </div>+ );+}diff --git a/web/lib/capabilities-api.ts b/web/lib/capabilities-api.tsnew file mode 100644index 000000000..b8a204cee--- /dev/null+++ b/web/lib/capabilities-api.ts@@ -0,0 +1,72 @@+"use client";++import { useEffect, useState } from "react";+import { apiFetch, apiUrl } from "@/lib/api";+import { withClientCache } from "@/lib/client-cache";++/**+ * Which capabilities the backend can actually start a turn with.+ *+ * Not every capability ships in this repository: the Whisper practice room+ * keeps its pages here while `whisper_visitor` / `whisper_trainee` come from an+ * out-of-tree plugin. A surface offering such a feature has to ask before it+ * sends, or the learner gets a raw `Unknown capability: whisper_visitor` from+ * the turn runtime (#963).+ *+ * The registry is fixed for the life of a backend process — installing a+ * plugin needs a restart — so the answer is cached and shared by every caller+ * rather than re-fetched per surface.+ */+export async function listRegisteredCapabilities(): Promise<string[]> {+ return withClientCache(+ "capabilities:registered",+ async () => {+ const res = await apiFetch(apiUrl("/api/v1/capabilities/registered"));+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = (await res.json()) as { capabilities?: unknown };+ return Array.isArray(data.capabilities)+ ? data.capabilities.filter((n): n is string => typeof n === "string")+ : [];+ },+ { ttlMs: 300_000 },+ );+}++/** Answers "is this capability installed?" — see {@link useCapabilityFilter}. */+export type CapabilityFilter = (name: string) => boolean;++/**+ * A predicate for gating entry points on whether their capability exists, or+ * `null` while the answer is still in flight.+ *+ * Callers should treat `null` as "not yet" and withhold the gated surface: the+ * probe is a cached local call, so a feature that is installed appears the same+ * way a tile's count does, while one that is missing never flashes into view+ * and out again.+ *+ * The settled predicate fails **open**. An unreachable or older backend answers+ * `true` for everything, so a web bundle newer than its API keeps the pre-#963+ * behaviour instead of hiding features that are really there; only a successful+ * reply that omits a name hides anything.+ */+export function useCapabilityFilter(): CapabilityFilter | null {+ const [filter, setFilter] = useState<CapabilityFilter | null>(null);++ useEffect(() => {+ let cancelled = false;+ listRegisteredCapabilities()+ .then((names) => {+ // Stored through the updater form: a bare `setFilter(fn)` would run+ // `fn` as a state reducer instead of storing it.+ if (!cancelled) setFilter(() => (name: string) => names.includes(name));+ })+ .catch(() => {+ if (!cancelled) setFilter(() => () => true);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ return filter;+}diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsindex 732ab9b37..31c7e79a7 100644--- a/web/lib/knowledge-api.ts+++ b/web/lib/knowledge-api.ts@@ -199,7 +199,9 @@ export async function listKnowledgeBases(options?: { force?: boolean }) {cache: "no-store",});if (!response.ok) {- throw new Error(await readErrorDetail(response, "Failed to list knowledge bases"));+ throw new Error(+ await readErrorDetail(response, "Failed to list knowledge bases"),+ );}const data = await response.json();return Array.isArray(data)@@ -225,7 +227,9 @@ export async function listRagProviders(options?: { force?: boolean }) {},);if (!response.ok) {- throw new Error(await readErrorDetail(response, "Failed to list RAG providers"));+ throw new Error(+ await readErrorDetail(response, "Failed to list RAG providers"),+ );}const data = await response.json();return Array.isArray(data?.providers) ? data.providers : [];@@ -247,7 +251,9 @@ export async function getKnowledgeUploadPolicy(options?: { force?: boolean }) {},);if (!response.ok) {- throw new Error(await readErrorDetail(response, "Failed to load upload policy"));+ throw new Error(+ await readErrorDetail(response, "Failed to load upload policy"),+ );}const data = await response.json();return normalizeUploadPolicy(data);@@ -1134,13 +1140,14 @@ export async function listGitHubSources(kbName: string,): Promise<GitHubSource[]> {const res = await apiFetch(- apiUrl(- `/api/v1/knowledge/${encodeURIComponent(kbName)}/github-sources`,- ),+ apiUrl(`/api/v1/knowledge/${encodeURIComponent(kbName)}/github-sources`),);if (!res.ok) {throw new Error(- await readErrorDetail(res, `Failed to list GitHub sources (${res.status})`),+ await readErrorDetail(+ res,+ `Failed to list GitHub sources (${res.status})`,+ ),);}return (await res.json()) as GitHubSource[];@@ -1151,9 +1158,7 @@ export async function addGitHubSource(payload: AddGitHubSourcePayload,): Promise<GitHubSource> {const res = await apiFetch(- apiUrl(- `/api/v1/knowledge/${encodeURIComponent(kbName)}/github-source`,- ),+ apiUrl(`/api/v1/knowledge/${encodeURIComponent(kbName)}/github-source`),{method: "POST",headers: { "Content-Type": "application/json" },@@ -1186,7 +1191,10 @@ export async function removeGitHubSource();if (!res.ok) {throw new Error(- await readErrorDetail(res, `Failed to remove GitHub source (${res.status})`),+ await readErrorDetail(+ res,+ `Failed to remove GitHub source (${res.status})`,+ ),);}invalidateKnowledgeCaches();@@ -1196,9 +1204,7 @@ export async function syncGitHubSources(kbName: string,): Promise<GitHubSyncResult[]> {const res = await apiFetch(- apiUrl(- `/api/v1/knowledge/${encodeURIComponent(kbName)}/sync-github`,- ),+ apiUrl(`/api/v1/knowledge/${encodeURIComponent(kbName)}/sync-github`),{ method: "POST" },);if (!res.ok) {diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex 217148760..7e1408072 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -116,7 +116,7 @@ export interface KnowledgeBase {vault_path?: string;/** SQLite store of a connected MarginNote 4 library (when type === "marginnote4"). */db_path?: string;- /** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex" | "gemini" | "kimi" | "opencode" | "mimo" | "partner". */+ /** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex" | "gemini" | "antigravity" | "kimi" | "opencode" | "mimo" | "partner". */agent_kind?: string;/** Bound partner id when agent_kind === "partner". */partner_id?: string;diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.tsindex 8897ec3f7..657d7f994 100644--- a/web/lib/learning-api.ts+++ b/web/lib/learning-api.ts@@ -78,6 +78,8 @@ export interface MapModule {}export interface MasteryMap {+ /** What to call this path — see policy.path_display_name. */+ name: string;counts: { mastered: number; learning: number; new: number; total: number };due_reviews: number;complete: boolean;@@ -100,6 +102,7 @@ export interface NextStep {export interface MasteryMapResult {book_id: string;+ name: string;path_revision: number;next: NextStep;map: MasteryMap;@@ -117,6 +120,20 @@ export async function fetchMasteryMap(return res.json() as Promise<MasteryMapResult>;}+/** Rename a path. An empty name restores the derived display name. */+export async function renameProgress(pathId: string, name: string) {+ const res = await apiFetch(+ apiUrl(`/api/v1/learning/progress/${encodeURIComponent(pathId)}`),+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name }),+ },+ );+ if (!res.ok) throw new Error(`Failed to rename path: ${res.status}`);+ return res.json() as Promise<{ status: string; name: string }>;+}+// ── Activity feed ─────────────────────────────────────────────────────────// Mirrors deeptutor/learning/models.py MasteryEvent. Every committed change to// a path emits one, numbered by the path's revision — which is what lets thediff --git a/web/lib/partners-api.ts b/web/lib/partners-api.tsindex d8af6205b..63f56a040 100644--- a/web/lib/partners-api.ts+++ b/web/lib/partners-api.ts@@ -7,6 +7,14 @@ export interface PartnerInfo {partner_id: string;name: string;description: string;+ /** Account that created the partner; empty for admin-managed ones. */+ owner_id?: string;+ /**+ * Whether the signed-in user may configure this partner (its owner, or an+ * admin). False for a partner merely assigned to them, whose response is+ * reduced to identity fields — so read this rather than re-deriving it.+ */+ can_manage?: boolean;/** List endpoints: channel name keys only. Detail: full (masked) dict. */channels: string[] | Record<string, unknown>;llm_selection?: LLMSelection | null;@@ -508,3 +516,108 @@ export async function branchPartnerSession(),);}++// ── Channel account links ─────────────────────────────────────+//+// Connecting a chat account (QQ, Telegram, …) to your DeepTutor account, so+// messages you send the partner there are yours: private history you can read+// back here, answered out of your own library and memory.++export interface PartnerLink {+ key: string;+ channel: string;+ sender_id: string;+ linked_at: string;+}++export interface PartnerLinkCode {+ code: string;+ expires_at: string;+ /** Ready-to-send command, e.g. "/link A1B2C3". */+ command: string;+}++export async function createPartnerLinkCode(+ partnerId: string,+): Promise<PartnerLinkCode> {+ return json(+ await apiFetch(+ apiUrl(`/api/v1/partners/${encodeURIComponent(partnerId)}/links/code`),+ { method: "POST" },+ ),+ );+}++export async function listPartnerLinks(+ partnerId: string,+): Promise<PartnerLink[]> {+ const data = await json<{ links: PartnerLink[] }>(+ await apiFetch(+ apiUrl(`/api/v1/partners/${encodeURIComponent(partnerId)}/links`),+ ),+ );+ return data.links ?? [];+}++export async function removePartnerLink(+ partnerId: string,+ key: string,+): Promise<void> {+ await json(+ await apiFetch(+ apiUrl(+ `/api/v1/partners/${encodeURIComponent(partnerId)}/links/${encodeURIComponent(key)}`,+ ),+ { method: "DELETE" },+ ),+ );+}++// ── WeChat QR onboarding (#951) ───────────────────────────────────────────────+//+// The personal-WeChat channel authenticates by scanning a QR code. The channel+// has always known how to run that exchange, but drew the code on the server's+// stdout — unreachable on a container deployment — so these drive it from the+// browser instead. The bot token is written into the partner's channel config+// server-side; nothing here ever sees it.++export interface WeixinQrSession {+ session_id: string;+ /** waiting | scanned | confirmed | expired | error */+ status: string;+ error: string;+ expires_in: number;+ /** What the phone scans. Present on start, and again whenever it changes. */+ scan_payload?: string;+ /** Inline SVG of `scan_payload`, rendered server-side (no QR lib in the web+ * bundle). Absent when unchanged since the last reply, or when the server+ * lacks the `qrcode` library — fall back to showing `scan_payload`. */+ qr_svg?: string;+}++export async function startWeixinQr(+ partnerId: string,+): Promise<WeixinQrSession> {+ return json(+ await apiFetch(+ apiUrl(+ `/api/v1/partners/${encodeURIComponent(partnerId)}/channels/weixin/qr`,+ ),+ { method: "POST" },+ ),+ );+}++export async function pollWeixinQr(+ partnerId: string,+ sessionId: string,+): Promise<WeixinQrSession> {+ return json(+ await apiFetch(+ apiUrl(+ `/api/v1/partners/${encodeURIComponent(partnerId)}/channels/weixin/qr/${encodeURIComponent(sessionId)}`,+ ),+ { cache: "no-store" },+ ),+ );+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 85997f275..10023c40c 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -890,6 +890,7 @@"Create & Start": "Create & Start","Stop": "Stop","Stop generating": "Stop generating",+ "Send answer": "Send answer","Answer now": "Answer now","Answering…": "Answering…","Skip reasoning and answer now": "Skip reasoning and answer now",@@ -2423,9 +2424,6 @@"Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.": "Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.","Create your first partner": "Create your first partner","No channels connected": "No channels connected",- "Partners your administrator has assigned to you. Click one to start chatting with it.": "Partners your administrator has assigned to you. Click one to start chatting with it.",- "No partners assigned yet": "No partners assigned yet",- "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.": "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.","A companion that lives on your channels and works from its own library.": "A companion that lives on your channels and works from its own library.","Identity": "Identity","e.g. Ada": "e.g. Ada",@@ -2527,6 +2525,16 @@"That file is too large.": "That file is too large.","Could not read that image.": "Could not read that image.","Please use the attached file(s).": "Please use the attached file(s).",+ "Get a code": "Get a code",+ "New code": "New code",+ "Waiting for a scan…": "Waiting for a scan…",+ "Scanned — confirm on your phone.": "Scanned — confirm on your phone.",+ "Connected. The bot token has been saved.": "Connected. The bot token has been saved.",+ "This code expired. Start a new scan.": "This code expired. Start a new scan.",+ "The scan failed.": "The scan failed.",+ "Sign in with the WeChat account this partner should speak as. The bot token is saved on the server.": "Sign in with the WeChat account this partner should speak as. The bot token is saved on the server.",+ "WeChat login QR code": "WeChat login QR code",+ "WeChat connected.": "WeChat connected.","This channel is not available on the server.": "This channel is not available on the server.","Partner": "Partner","Edited — your version becomes this partner's soul. The original template is untouched.": "Edited — your version becomes this partner's soul. The original template is untouched.",@@ -3280,6 +3288,8 @@"Open the room as Visitor first.": "Open the room as Visitor first.","Reconnecting…": "Reconnecting…","Seat": "Seat",+ "Whisper is not installed on this server": "Whisper is not installed on this server",+ "The practice room runs on a separate capability plugin that this deployment does not have. Ask your administrator to install it to use this page.": "The practice room runs on a separate capability plugin that this deployment does not have. Ask your administrator to install it to use this page.","This whisper room has ended. Sending is disabled.": "This whisper room has ended. Sending is disabled.","Trainee": "Trainee","Trainee message": "Trainee message",@@ -3301,5 +3311,18 @@"main": "main","docs/": "docs/","*.md": "*.md",- "Session {{id}}": "Session {{id}}"+ "Session {{id}}": "Session {{id}}",+ "Link a chat account": "Link a chat account",+ "Connect the account you message {{name}} from, so those conversations are private to you and it can reach your library and notes there.": "Connect the account you message {{name}} from, so those conversations are private to you and it can reach your library and notes there.",+ "Send this to {{name}} as a direct message from the chat account you want to connect:": "Send this to {{name}} as a direct message from the chat account you want to connect:",+ "Valid for 15 minutes, and usable once.": "Valid for 15 minutes, and usable once.",+ "Get a link code": "Get a link code",+ "Couldn't create a code. Try again.": "Couldn't create a code. Try again.",+ "Couldn't copy — select the command and copy it by hand.": "Couldn't copy — select the command and copy it by hand.",+ "Couldn't disconnect that account. Try again.": "Couldn't disconnect that account. Try again.",+ "Connected accounts": "Connected accounts",+ "No chat accounts connected yet.": "No chat accounts connected yet.",+ "Disconnect": "Disconnect",+ "Shared with you": "Shared with you",+ "Your companions, plus the ones shared with you — each with its own soul, library, and channels.": "Your companions, plus the ones shared with you — each with its own soul, library, and channels."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 9e3368062..f3343d60f 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -825,6 +825,7 @@"Create & Start": "创建并启动","Stop": "停止","Stop generating": "停止生成",+ "Send answer": "提交回答","Answer now": "直接回答","Answering…": "正在回答…","Skip reasoning and answer now": "跳过推理,直接回答",@@ -2423,9 +2424,6 @@"Create a partner, give it a soul and a slice of your library, then talk to it here or from Feishu, Telegram, Slack and more.": "创建一个伙伴,赋予它灵魂和一部分资料库,然后在这里或飞书、Telegram、Slack 等 IM 中与它对话。","Create your first partner": "创建第一个伙伴","No channels connected": "未接入频道",- "Partners your administrator has assigned to you. Click one to start chatting with it.": "管理员分配给你的伙伴。点击任意一个即可开始与它对话。",- "No partners assigned yet": "还没有分配给你的伙伴",- "Your administrator hasn't assigned you any partners yet. Once they do, they'll appear here.": "管理员还没有给你分配任何伙伴。一旦分配,它们就会显示在这里。","A companion that lives on your channels and works from its own library.": "一个常驻于你频道里的伙伴,用属于它自己的资料库工作。","Identity": "身份","e.g. Ada": "例如 Ada",@@ -2527,6 +2525,16 @@"That file is too large.": "文件太大了。","Could not read that image.": "无法读取该图片。","Please use the attached file(s).": "请结合附件文件回答。",+ "Get a code": "获取二维码",+ "New code": "换一张",+ "Waiting for a scan…": "等待扫码…",+ "Scanned — confirm on your phone.": "已扫码,请在手机上确认。",+ "Connected. The bot token has been saved.": "已连接,令牌已保存。",+ "This code expired. Start a new scan.": "二维码已过期,请重新获取。",+ "The scan failed.": "扫码失败。",+ "Sign in with the WeChat account this partner should speak as. The bot token is saved on the server.": "用你希望该伙伴对外使用的微信账号登录。令牌保存在服务器上。",+ "WeChat login QR code": "微信登录二维码",+ "WeChat connected.": "微信已连接。","This channel is not available on the server.": "该频道在此服务器上不可用。","Partner": "伙伴","Edited — your version becomes this partner's soul. The original template is untouched.": "已编辑——你的版本将成为这个伙伴的 soul,原模板保持不变。",@@ -3280,6 +3288,8 @@"Open the room as Visitor first.": "请先以来访者身份开启房间。","Reconnecting…": "重新连接中…","Seat": "席位",+ "Whisper is not installed on this server": "本服务器未安装密语",+ "The practice room runs on a separate capability plugin that this deployment does not have. Ask your administrator to install it to use this page.": "该练习房间由一个独立的能力插件提供,当前部署没有安装它。请联系管理员安装后再使用本页面。","This whisper room has ended. Sending is disabled.": "该密语房间已结束,无法继续发送。","Trainee": "受训者","Trainee message": "受训者消息",@@ -3301,5 +3311,18 @@"main": "main","docs/": "docs/","*.md": "*.md",- "Session {{id}}": "会话 {{id}}"+ "Session {{id}}": "会话 {{id}}",+ "Link a chat account": "关联聊天账号",+ "Connect the account you message {{name}} from, so those conversations are private to you and it can reach your library and notes there.": "把你用来给「{{name}}」发消息的账号关联过来——那些对话就只属于你,它在那边也能读到你的资料库和笔记。",+ "Send this to {{name}} as a direct message from the chat account you want to connect:": "用你想关联的聊天账号,私聊发送这条给「{{name}}」:",+ "Valid for 15 minutes, and usable once.": "15 分钟内有效,只能用一次。",+ "Get a link code": "获取关联码",+ "Couldn't create a code. Try again.": "没能生成关联码,请重试。",+ "Couldn't copy — select the command and copy it by hand.": "复制失败,请手动选中命令复制。",+ "Couldn't disconnect that account. Try again.": "没能解除关联,请重试。",+ "Connected accounts": "已关联的账号",+ "No chat accounts connected yet.": "还没有关联任何聊天账号。",+ "Disconnect": "解除关联",+ "Shared with you": "共享给你",+ "Your companions, plus the ones shared with you — each with its own soul, library, and channels.": "你的伙伴,以及共享给你的伙伴——每个都有自己的灵魂、资料库和频道。"}diff --git a/web/tests/ask-user-segments.test.ts b/web/tests/ask-user-segments.test.tsnew file mode 100644index 000000000..ad50235f5--- /dev/null+++ b/web/tests/ask-user-segments.test.ts@@ -0,0 +1,116 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ extractMessageSegments,+ leadingTraceEvents,+} from "../components/chat/home/AskUserOptions";+import type { StreamEvent } from "../lib/unified-ws";++function event(+ type: StreamEvent["type"],+ metadata: Record<string, unknown> = {},+ content = "",+): StreamEvent {+ return {+ type,+ source: "chat",+ stage: "responding",+ content,+ metadata,+ session_id: "session-1",+ turn_id: "turn-1",+ seq: 1,+ timestamp: 0,+ };+}++const askUserCard = (toolCallId: string) =>+ event("tool_result", {+ tool_call_id: toolCallId,+ tool_metadata: {+ ask_user: {+ questions: [+ {+ id: "q1",+ prompt: "Which is the general form?",+ options: [{ label: "A" }, { label: "B" }],+ },+ ],+ },+ },+ });++const resolved = (toolCallId: string) =>+ event("progress", {+ ask_user_resolved: true,+ ask_user_tool_call_id: toolCallId,+ answers: [{ questionId: "q1", text: "B" }],+ });++test("reasoning produced after a card becomes its own segment below it", () => {+ const before = event("thinking", { call_id: "round-1" }, "planning a question");+ const after = event("thinking", { call_id: "round-2" }, "grading their answer");++ const segments = extractMessageSegments([+ before,+ askUserCard("call-1"),+ resolved("call-1"),+ after,+ event("content", { call_id: "round-2", call_kind: "agent_loop_round" }, "Correct!"),+ ]);++ assert.deepEqual(+ segments.map((segment) => segment.kind),+ ["ask_user", "trace", "text"],+ );+ const traceSegment = segments[1];+ assert.equal(traceSegment.kind === "trace" && traceSegment.events.length, 1);+ assert.equal(+ traceSegment.kind === "trace" && traceSegment.events[0].content,+ "grading their answer",+ );+});++test("the pre-card rounds stay with the top activity block", () => {+ const before = event("thinking", { call_id: "round-1" }, "planning");+ const after = event("thinking", { call_id: "round-2" }, "grading");+ const events = [before, askUserCard("call-1"), resolved("call-1"), after];++ const leading = leadingTraceEvents(events, extractMessageSegments(events));++ assert.deepEqual(leading, [before, askUserCard("call-1"), resolved("call-1")]);+});++test("a turn with no card keeps every event in the top block", () => {+ const events = [+ event("thinking", { call_id: "round-1" }, "thinking"),+ event(+ "content",+ { call_id: "round-1", call_kind: "agent_loop_round" },+ "answer",+ ),+ ];+ const segments = extractMessageSegments(events);++ assert.deepEqual(+ segments.map((segment) => segment.kind),+ ["text"],+ );+ assert.deepEqual(leadingTraceEvents(events, segments), events);+});++test("each card gets the rounds that followed it", () => {+ const segments = extractMessageSegments([+ askUserCard("call-1"),+ resolved("call-1"),+ event("thinking", { call_id: "round-2" }, "first follow-up"),+ askUserCard("call-2"),+ resolved("call-2"),+ event("thinking", { call_id: "round-3" }, "second follow-up"),+ ]);++ assert.deepEqual(+ segments.map((segment) => segment.kind),+ ["ask_user", "trace", "ask_user", "trace"],+ );+});diff --git a/web/tests/space-dashboard-capability-gate.test.ts b/web/tests/space-dashboard-capability-gate.test.tsnew file mode 100644index 000000000..b770edd8a--- /dev/null+++ b/web/tests/space-dashboard-capability-gate.test.ts@@ -0,0 +1,74 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ DASHBOARD_GROUPS,+ visibleGroups,+} from "../components/space/SpaceDashboard";++// #963: /whisper ships its pages here but its capability comes from an+// out-of-tree plugin, so a stock install offered a room the backend could not+// start and answered "Unknown capability: whisper_visitor".++const groups = [+ {+ label: { zh: "常规", en: "Regular" },+ items: [{ key: "a", href: "/a" }],+ },+ {+ label: { zh: "更多项目", en: "More Projects" },+ items: [{ key: "w", href: "/w", requiresCapability: "whisper_visitor" }],+ },+] as unknown as typeof DASHBOARD_GROUPS;++test("an installed capability shows its tile", () => {+ const shown = visibleGroups(groups, (name) => name === "whisper_visitor");++ assert.equal(shown.length, 2);+ assert.equal(shown[1].items.length, 1);+});++test("a missing capability hides its tile", () => {+ const shown = visibleGroups(groups, () => false);++ assert.equal(shown.length, 1);+ assert.equal(shown[0].label.en, "Regular");+});++test("a group emptied by the gate loses its heading too", () => {+ // Otherwise "More Projects" renders as a title with nothing under it.+ const shown = visibleGroups(groups, () => false);++ assert.ok(!shown.some((g) => g.label.en === "More Projects"));+});++test("ungated tiles are never affected by the gate", () => {+ for (const gate of [null, () => false, () => true] as const) {+ const shown = visibleGroups(groups, gate);+ assert.equal(shown[0].items[0].key, "a");+ }+});++test("gated tiles stay hidden while the probe is still in flight", () => {+ // Showing them first and removing them a moment later reads as a glitch.+ const shown = visibleGroups(groups, null);++ assert.equal(shown.length, 1);+});++test("the real dashboard gates whisper and nothing else", () => {+ const gated = DASHBOARD_GROUPS.flatMap((g) => g.items).filter(+ (i) => i.requiresCapability,+ );++ assert.deepEqual(+ gated.map((i) => i.requiresCapability),+ ["whisper_visitor"],+ );+});++test("with whisper absent the real dashboard drops More Projects entirely", () => {+ const shown = visibleGroups(DASHBOARD_GROUPS, () => false);++ assert.ok(!shown.some((g) => g.items.some((i) => i.key === "whisper")));+ assert.ok(shown.length > 0, "the ungated groups must survive");+});diff --git a/web/tests/voice-mime.test.ts b/web/tests/voice-mime.test.tsindex a7c183345..a8e074d94 100644--- a/web/tests/voice-mime.test.ts+++ b/web/tests/voice-mime.test.ts@@ -8,10 +8,7 @@ test("stripAudioMimeParameters drops MediaRecorder codec parameters", () => {stripAudioMimeParameters("audio/webm;codecs=opus"),"audio/webm",);- assert.equal(- stripAudioMimeParameters("audio/ogg; codecs=opus"),- "audio/ogg",- );+ assert.equal(stripAudioMimeParameters("audio/ogg; codecs=opus"), "audio/ogg");});test("stripAudioMimeParameters keeps a clean type and falls back", () => {