From bd80a4d28a2093347ef080f98ae7cf8e3eee488e Mon Sep 17 00:00:00 2001
From: "Bingxi Zhao (Frank)" <13051345080@163.com>
Date: Tue, 25 Aug 2026 02:24:35 +0800
Subject: [PATCH] release: v1.5.17
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Partners stop being a deployment-wide admin resource and become
per-user: three nested rights (manage / use / neither) replace the
blanket admin gate on the router, each member can build and own their
own, and every person's conversations with a partner stay private to
their account. Grants keep working and now offer only admin-managed
partners. Channel runtime state moves from one directory per channel to
one per partner — copied, not moved, and only when its owner is
unambiguous — so two partners can finally run the same channel.
Around that: a knowledge base can track GitHub repositories and re-sync
their Markdown (#903); Antigravity CLI joins My Agents now that Gemini
CLI is retired (#828); personal WeChat signs in from a QR code drawn in
the browser instead of the server log (#951); a chat account can be
linked to a DeepTutor account with /link; containers re-apply the extras
they declare instead of losing them at compose down (#762); and
`deeptutor doctor` answers whether a workspace is ready to run (#959).
Reliability, largely from community PRs: embeddings survive a
rate-limited provider through key rotation, a retry budget and a global
throttle (#962); MinerU parsing and code execution work on Windows
(#844, #964); indexing fails bounded instead of hanging (#946); MinerU
page-layout blocks stop being indexed as content (#949); voice uploads
carry a MIME the transcription API accepts (#945); and reasoning effort
can be overridden per conversation (#641).
Release plumbing: notes in assets/releases/ver1-5-17.md, v1.5.13
archived, __version__ 1.5.17, README Releases row and all eleven
translations synced.
Two defects found by the release gate and fixed here:
- Six partner routes — the four channel-onboarding endpoints and both
WeChat QR endpoints — kept the _auth-only mount they had inherited
from the blanket admin gate, so any signed-in account could start a
QR login for someone else's partner and write a bot token into its
channel config. All six now declare _MANAGEABLE, and a sweep test
asserts no {partner_id} route is left ungated.
- A configured api_key became `str | list[str]` when key rotation
landed, but ten call sites pass it somewhere that takes one key; a
list would have rendered into an Authorization header verbatim.
keypool.primary_api_key reduces at each boundary.
Gates: pre-commit (all 15 hooks), ruff check + format, pytest
5276 passed, web 605 node tests, docs build.
---
Dockerfile | 36 ++
README.md | 15 +-
assets/README/README_AR.md | 9 +-
assets/README/README_CN.md | 9 +-
assets/README/README_ES.md | 9 +-
assets/README/README_FR.md | 9 +-
assets/README/README_HI.md | 9 +-
assets/README/README_JA.md | 9 +-
assets/README/README_PL.md | 9 +-
assets/README/README_PT.md | 9 +-
assets/README/README_RU.md | 9 +-
assets/README/README_TH.md | 9 +-
assets/README/README_TW.md | 9 +-
.../releases/{ => past_releases}/ver1-5-13.md | 0
assets/releases/ver1-5-14.md | 2 +-
assets/releases/ver1-5-17.md | 76 ++++
deeptutor/__version__.py | 2 +-
deeptutor/agents/chat/agentic_pipeline.py | 14 +
deeptutor/api/main.py | 14 +-
deeptutor/api/routers/capabilities.py | 30 ++
deeptutor/api/routers/mastery_path.py | 28 ++
deeptutor/api/routers/partners.py | 288 +++++++++++----
deeptutor/book/blocks/animation.py | 4 +-
deeptutor/book/blocks/figure.py | 4 +-
deeptutor/book/blocks/interactive.py | 4 +-
deeptutor/capabilities/mastery/choices.py | 6 +
deeptutor/capabilities/mastery/loop.py | 6 +
deeptutor/capabilities/mastery/tools.py | 117 ++++++-
deeptutor/capabilities/protocol.py | 6 +
deeptutor/core/agentic/client.py | 6 +-
deeptutor/core/agentic/tool_dispatch.py | 70 +++-
deeptutor/learning/models.py | 5 +
deeptutor/learning/pending.py | 122 +++++--
deeptutor/learning/policy.py | 22 ++
deeptutor/learning/service.py | 48 ++-
.../learning/tests/test_api_endpoints.py | 48 +++
.../learning/tests/test_mastery_choices.py | 52 +++
.../learning/tests/test_mastery_tools.py | 121 ++++++-
deeptutor/learning/tests/test_policy.py | 32 ++
deeptutor/multi_user/grants.py | 9 +-
deeptutor/multi_user/partner_access.py | 131 +++++--
deeptutor/multi_user/router.py | 14 +-
deeptutor/partners/channels/base.py | 35 ++
deeptutor/partners/channels/manager.py | 5 +-
deeptutor/partners/channels/matrix.py | 3 +-
deeptutor/partners/channels/mochat.py | 3 +-
deeptutor/partners/channels/msteams.py | 3 +-
deeptutor/partners/channels/registry.py | 14 +-
deeptutor/partners/channels/weixin.py | 113 +++---
deeptutor/partners/channels/weixin_qr.py | 202 +++++++++++
deeptutor/partners/config/__init__.py | 2 +
deeptutor/partners/config/paths.py | 9 +
.../config/context_window_detection.py | 3 +-
.../services/embedding/adapters/gemini.py | 121 ++++++-
deeptutor/services/keypool.py | 17 +-
deeptutor/services/llm/config.py | 3 +-
deeptutor/services/llm/factory.py | 3 +-
.../provider_core/azure_openai_provider.py | 64 +++-
deeptutor/services/llm/provider_factory.py | 3 +-
.../partners/channel_state_migration.py | 127 +++++++
deeptutor/services/partners/commands.py | 41 +++
deeptutor/services/partners/interaction.py | 82 ++++-
deeptutor/services/partners/links.py | 197 +++++++++++
deeptutor/services/partners/manager.py | 84 ++++-
deeptutor/services/partners/runtime.py | 35 +-
.../services/partners/weixin_onboarding.py | 310 +++++++++++++++++
deeptutor/services/persona/service.py | 11 +-
deeptutor/services/subagent/antigravity.py | 314 +++++++++++++++++
deeptutor/services/subagent/gemini.py | 18 +-
deeptutor/services/subagent/models.py | 35 +-
deeptutor/services/subagent/process.py | 21 +-
deeptutor/services/subagent/registry.py | 5 +-
docker-compose.ghcr.yml | 16 +
docker-compose.yml | 9 +
scripts/install_extras.py | 150 ++++++++
tests/api/test_capabilities_router.py | 70 ++++
tests/api/test_partners_router.py | 101 ++++--
tests/capabilities/test_mastery_capability.py | 58 +++
.../test_tool_dispatch_pause_ordering.py | 91 +++++
tests/multi_user/test_partner_access.py | 74 ++++
tests/scripts/test_install_extras.py | 159 +++++++++
.../services/embedding/test_gemini_adapter.py | 146 +++++++-
.../llm/test_azure_openai_provider.py | 132 +++++++
tests/services/partners/conftest.py | 57 ++-
tests/services/partners/scripts.py | 60 ++++
tests/services/partners/test_channel_links.py | 233 +++++++++++++
.../services/partners/test_channel_manager.py | 58 +++
.../partners/test_channel_state_migration.py | 119 +++++++
.../services/partners/test_msteams_channel.py | 3 +-
.../services/partners/test_partner_runtime.py | 246 +++++--------
.../services/partners/test_weixin_channel.py | 58 ++-
.../partners/test_weixin_onboarding.py | 329 ++++++++++++++++++
tests/services/test_antigravity_backend.py | 294 ++++++++++++++++
tests/services/test_subagent_backends.py | 15 +-
.../settings/agents/antigravity/page.tsx | 7 +
web/app/(utility)/space/learning/page.tsx | 36 +-
.../home/[[...sessionId]]/page.tsx | 30 ++
.../(workspace)/partners/[partnerId]/page.tsx | 95 +++--
web/app/(workspace)/partners/page.tsx | 175 +++-------
web/app/(workspace)/whisper/page.tsx | 28 ++
web/components/agents/ConnectedAgents.tsx | 1 +
web/components/agents/agent-icons.tsx | 2 +
web/components/chat/home/AskUserOptions.tsx | 79 ++++-
web/components/chat/home/ChatComposer.tsx | 25 +-
web/components/chat/home/ChatMessages.tsx | 22 +-
web/components/chat/home/MasteryPathStrip.tsx | 2 +-
web/components/chat/home/TracePanels.tsx | 43 ++-
.../knowledge/KbGitHubSourcesSection.tsx | 19 +-
web/components/partners/PartnerChannels.tsx | 16 +
web/components/partners/PartnerLinkModal.tsx | 209 +++++++++++
web/components/partners/SoulPicker.tsx | 5 +-
web/components/partners/WeixinQrLogin.tsx | 161 +++++++++
web/components/quiz/QuizFollowupTabBody.tsx | 15 +-
.../settings/SubagentSettingsEditor.tsx | 11 +
web/components/space/SpaceDashboard.tsx | 45 ++-
.../space/learning/ActivityTimeline.tsx | 6 +
web/components/space/learning/PathTitle.tsx | 136 ++++++++
web/lib/capabilities-api.ts | 72 ++++
web/lib/knowledge-api.ts | 34 +-
web/lib/knowledge-helpers.ts | 2 +-
web/lib/learning-api.ts | 17 +
web/lib/partners-api.ts | 113 ++++++
web/locales/en/app.json | 31 +-
web/locales/zh/app.json | 31 +-
web/tests/ask-user-segments.test.ts | 116 ++++++
.../space-dashboard-capability-gate.test.ts | 74 ++++
web/tests/voice-mime.test.ts | 5 +-
127 files changed, 6705 insertions(+), 750 deletions(-)
rename assets/releases/{ => past_releases}/ver1-5-13.md (100%)
create mode 100644 assets/releases/ver1-5-17.md
create mode 100644 deeptutor/api/routers/capabilities.py
create mode 100644 deeptutor/partners/channels/weixin_qr.py
create mode 100644 deeptutor/services/partners/channel_state_migration.py
create mode 100644 deeptutor/services/partners/links.py
create mode 100644 deeptutor/services/partners/weixin_onboarding.py
create mode 100644 deeptutor/services/subagent/antigravity.py
create mode 100644 scripts/install_extras.py
create mode 100644 tests/api/test_capabilities_router.py
create mode 100644 tests/scripts/test_install_extras.py
create mode 100644 tests/services/llm/test_azure_openai_provider.py
create mode 100644 tests/services/partners/scripts.py
create mode 100644 tests/services/partners/test_channel_links.py
create mode 100644 tests/services/partners/test_channel_state_migration.py
create mode 100644 tests/services/partners/test_weixin_onboarding.py
create mode 100644 tests/services/test_antigravity_backend.py
create mode 100644 web/app/(utility)/settings/agents/antigravity/page.tsx
create mode 100644 web/components/partners/PartnerLinkModal.tsx
create mode 100644 web/components/partners/WeixinQrLogin.tsx
create mode 100644 web/components/space/learning/PathTitle.tsx
create mode 100644 web/lib/capabilities-api.ts
create mode 100644 web/tests/ask-user-segments.test.ts
create mode 100644 web/tests/space-dashboard-capability-gate.test.ts
diff --git a/Dockerfile b/Dockerfile
index 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 shlex
diff --git a/README.md b/README.md
index 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.
-
Past releases (more than 1 week ago)
+> **[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 assign
The 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.
-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.
@@ -594,7 +596,7 @@ Knowledge bases are the document collections behind RAG — they ground Chat tur
-يحوّل 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`. اختره بشريحة الوكيل (أو اكتب `@`)، وحدد عدد الجولات التي يمكن للاستشارة أن تأخذها.
@@ -427,7 +429,7 @@ Co-Writer هو مساحة عمل Markdown ذات عرض مقسَّم للتقا
-"我的智能体"将其他智能体转化为 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 面板。通过智能体选项(或输入 `@`)选择它,并设置调用可进行的最大轮数。
@@ -427,7 +429,7 @@ Book 将选定的来源转化为交互式**活书** — 不是静态 PDF,而
-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.
@@ -439,7 +441,7 @@ Las bases de conocimiento son las colecciones de documentos detrás del RAG —
-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.
@@ -449,7 +451,7 @@ Les bases de connaissances sont les collections de documents derrière le RAG
-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 ले सकता है।
@@ -427,7 +429,7 @@ Knowledge bases RAG के पीछे document collections हैं — व
-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チップ(または`@`入力)で選択し、相談で取れるラウンド数を設定します。
@@ -427,7 +429,7 @@ Bookは選択したソースをインタラクティブな**生きている本**
-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.
@@ -427,7 +429,7 @@ Bazy wiedzy to kolekcje dokumentów za RAG — ugruntowują tury Chat, edycje Co
-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.
@@ -439,7 +441,7 @@ As bases de conhecimento são as coleções de documentos por trás do RAG — f
-Мои Агенты превращают других агентов в контекст для 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`. Выберите его чипом агента (или введите `@`) и задайте, сколько раундов может занять обращение.
@@ -427,7 +429,7 @@ Co-Writer — это разделённое рабочее пространст
-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 (หรือพิมพ์ `@`) และตั้งค่าจำนวนรอบที่การปรึกษาอาจทำได้
@@ -427,7 +429,7 @@ Knowledge bases คือคอลเลกชันเอกสารที่
-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(或輸入 `@`)選取代理程式,並設定諮詢可進行的回合數。
@@ -427,7 +429,7 @@ Book 會將選定來源轉換成互動式**活書**;它不是靜態 PDF,而
` 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//channels//`, 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//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//` is copied to `data/partners//channels//` 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 ""`.
+- **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.17
diff --git a/deeptutor/__version__.py b/deeptutor/__version__.py
index 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 this
file 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.py
index 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.py
index 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.py
new file mode 100644
index 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()
+
+
+@router.get("/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.py
index 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: str
knowledge_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):
}
+@router.patch("/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.py
index f4a555ce5..1e065f560 100644
--- a/deeptutor/api/routers/partners.py
+++ b/deeptutor/api/routers/partners.py
@@ -17,11 +17,20 @@ import logging
from typing import Any, AsyncGenerator, Literal
from uuid import uuid4
-from fastapi import APIRouter, HTTPException, Query, WebSocket, WebSocketDisconnect
+from fastapi import APIRouter, Depends, HTTPException, Query, WebSocket, WebSocketDisconnect
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, ValidationError
+from deeptutor.api.routers.auth import require_admin
from 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_dir
from deeptutor.partners.helpers import safe_filename
from 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_selection
from deeptutor.services.config import get_model_catalog_service
from deeptutor.services.model_selection import apply_llm_selection_to_catalog
from 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_user
from deeptutor.multi_user.paths import get_admin_path_service
from deeptutor.services.persona import PersonaService, get_persona_service
@@ -356,7 +428,7 @@ async def list_souls():
return get_partner_manager().list_souls()
-@router.post("/souls")
+@router.post("/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/``
@@ -376,7 +448,7 @@ async def get_soul(soul_id: str):
return soul
-@router.put("/souls/{soul_id}")
+@router.put("/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
-@router.delete("/souls/{soul_id}")
+@router.delete("/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_user
from deeptutor.multi_user.paths import get_admin_path_service
from 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.
+
+
+@router.post("/{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
+
+
+@router.get("/{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_tools
from 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(
}
-@router.get("/{partner_id}")
+@router.get("/{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 manageable
instance = 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_tools
if "mcp_tools" in payload.model_fields_set:
cfg.mcp_tools = payload.mcp_tools
+ clamp_to_caller_reach(cfg)
-@router.patch("/{partner_id}")
+@router.patch("/{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)
-@router.post("/{partner_id}/start")
+@router.post("/{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)
-@router.post("/{partner_id}/stop")
+@router.post("/{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}
-@router.delete("/{partner_id}")
+@router.delete("/{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}
-@router.post("/{partner_id}/channels/reload")
+@router.post("/{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
-@router.post("/{partner_id}/channel-onboarding/start")
+@router.post("/{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
-@router.get("/{partner_id}/channel-onboarding/{session_id}")
+@router.get("/{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
-@router.delete("/{partner_id}/channel-onboarding/{session_id}")
+@router.delete("/{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
-@router.post("/{partner_id}/channel-onboarding/{session_id}/apply")
+@router.post("/{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) ───────────────────────────
-@router.get("/{partner_id}/soul")
+@router.get("/{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)}
-@router.put("/{partner_id}/soul")
+@router.put("/{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 ─────────────────────────────────────────────────────
-@router.get("/{partner_id}/assets")
+@router.get("/{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)
-@router.post("/{partner_id}/assets")
+@router.post("/{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)}
-@router.delete("/{partner_id}/assets/{asset_type}/{name}")
+@router.delete("/{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 ──────────────────────────────────────
+
+
+@router.post("/{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 `` 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}",
+ }
+
+
+@router.get("/{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)}
+
+
+@router.delete("/{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 ────────────────────────────────────────────────────
-@router.get("/{partner_id}/history")
+@router.get("/{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)
-@router.get("/{partner_id}/sessions")
+@router.get("/{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()
-@router.post("/{partner_id}/sessions/archive")
+@router.post("/{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}
-@router.post("/{partner_id}/sessions/resume")
+@router.post("/{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}
-@router.post("/{partner_id}/sessions/delete")
+@router.post("/{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}
-@router.post("/{partner_id}/sessions/branch")
+@router.post("/{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
-@router.post("/{partner_id}/chat")
+@router.post("/{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()
-@router.post("/{partner_id}/chat/execute-stream")
+@router.post("/{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):
return
mgr = 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.py
index 6e41de15a..e69c30879 100644
--- a/deeptutor/book/blocks/animation.py
+++ b/deeptutor/book/blocks/animation.py
@@ -15,6 +15,8 @@ import importlib.util
import logging
from typing import Any
+from deeptutor.services.keypool import primary_api_key
+
from ..models import BlockType, SourceAnchor
from ._prompts import get_book_prompt, load_book_prompts
from .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.py
index c7d89bd90..15951632a 100644
--- a/deeptutor/book/blocks/figure.py
+++ b/deeptutor/book/blocks/figure.py
@@ -16,6 +16,8 @@ from __future__ import annotations
import logging
from typing import Any
+from deeptutor.services.keypool import primary_api_key
+
from ..models import BlockType, SourceAnchor
from ._prompts import get_book_prompt, load_book_prompts
from .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.py
index be11612e3..17a99bc26 100644
--- a/deeptutor/book/blocks/interactive.py
+++ b/deeptutor/book/blocks/interactive.py
@@ -16,6 +16,8 @@ from __future__ import annotations
import logging
from typing import Any
+from deeptutor.services.keypool import primary_api_key
+
from ..models import BlockType, SourceAnchor
from ._prompts import get_book_prompt, load_book_prompts
from .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.py
index 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 tool
layer (: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 logging
from typing import Any
from 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.py
index 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.py
index 30d44eb75..ca715a25a 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -22,8 +22,10 @@ from typing import TYPE_CHECKING, Any
import uuid
from 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
- choice_options = parse_options(options)
- if len(choice_options) != len(options):
+ intended_labels = option_label_intent(options)
+ if intended_labels is not None and set(intended_labels) != canonical_labels(
+ len(intended_labels)
+ ):
raise ValueError(
- "Choice option labels must be unique; retry mastery_quiz with one full body "
- "for each label."
+ 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)
+ duplicate = _duplicate_option_body(choice_options)
+ if duplicate:
+ raise ValueError(
+ 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_interaction
return _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 = answer
from deeptutor.learning.service import MasteryInteractionError
try:
@@ -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.py
index 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 on
the two sides of an ``ask_user`` wait so state can be committed before a
disconnect 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: str
diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.py
index 537c5e426..1c7870254 100644
--- a/deeptutor/core/agentic/client.py
+++ b/deeptutor/core/agentic/client.py
@@ -23,7 +23,7 @@ import httpx
from openai import AsyncAzureOpenAI, AsyncOpenAI
from deeptutor.services.config import load_system_settings
-from deeptutor.services.keypool import KeyPool
+from deeptutor.services.keypool import KeyPool, primary_api_key
from deeptutor.services.llm import get_token_limit_kwargs, supports_tools
from deeptutor.services.llm.openai_http_client import sanitize_invalid_ssl_env
from 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 AnthropicProvider
anthropic_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.py
index 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:
continue
call_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.py
index 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 = None
modules: list[LearningModule] = Field(default_factory=list)
current_module_id: str = ""
diff --git a/deeptutor/learning/pending.py b/deeptutor/learning/pending.py
index 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 Iterable
from dataclasses import dataclass
import re
from 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)
continue
match = 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 resolve_choice_submission(answer: str, options: dict[str, str]) -> str:
- """Resolve a learner submission by label or one exact, unique option body.
+def _squeezed(value: str) -> str:
+ """Case-folded with all whitespace removed, for comparing formulas."""
+ return "".join(str(value or "").split()).casefold()
- 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.
+
+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"(? str:
+ """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 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.py
index 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 report
their 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.py
index 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.value
diff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.py
index 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.py
index 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 annotations
import pytest
from 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.py
index 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 ──────────────────────────────────────────────────────────────────
+
+
+@pytest.mark.asyncio
+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 == "一元二次方程基础"
+
+
+@pytest.mark.asyncio
+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 == ""
+
+
+@pytest.mark.asyncio
+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
+@pytest.mark.asyncio
+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
+
+
+@pytest.mark.asyncio
+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.asyncio
async 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.py
index 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.py
index 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.py
index 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.
+"""Who may see, use, and manage a Partner.
-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.
+Three roles matter, and they nest:
-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``.
+* **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 HTTPException
from .context import get_current_user
from .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 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.
+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
- 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).
+
+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 unless the current user may talk to *partner_id*.
+
+ 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() not in assigned_partner_ids(user_id or user.id):
- raise HTTPException(status_code=403, detail="Partner is not assigned to you")
+ if str(partner_id or "").strip() in assigned_partner_ids(user_id or user.id):
+ return
+ 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"] = False
return 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.py
index 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 ModelCatalogService
from deeptutor.services.skill.service import SkillService
from .audit import log_admin_action
+from .context import get_current_user
from .grants import load_grant, save_grant
from .identity import get_user_by_id, list_user_info
from .knowledge_access import admin_kb_base_dir
@@ -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().id
return [
{
"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.py
index 14008b957..1f45871fc 100644
--- a/deeptutor/partners/channels/base.py
+++ b/deeptutor/partners/channels/base.py
@@ -3,12 +3,31 @@
from __future__ import annotations
from abc import ABC, abstractmethod
+from contextlib import contextmanager
+from contextvars import ContextVar
from pathlib import Path
from typing import Any
from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
from 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 = config
self.bus = bus
self._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.py
index 2d256c50e..e4a6bec9a 100644
--- a/deeptutor/partners/channels/manager.py
+++ b/deeptutor/partners/channels/manager.py
@@ -9,7 +9,7 @@ from typing import Any
from deeptutor.partners.bus.events import OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
-from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.channels.base import BaseChannel, constructing_for
from deeptutor.partners.config.schema import ChannelsConfig
@@ -72,7 +72,8 @@ class ChannelManager:
if not enabled:
continue
try:
- channel = cls(section, self.bus)
+ with constructing_for(self._partner_id):
+ channel = cls(section, self.bus)
channel.partner_id = self._partner_id
channel.transcription_api_key = self._groq_api_key
# Effective delivery flags are per-channel only. Historical
diff --git a/deeptutor/partners/channels/matrix.py b/deeptutor/partners/channels/matrix.py
index 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 OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
from deeptutor.partners.channels.base import BaseChannel
-from deeptutor.partners.config.paths import get_data_dir
from deeptutor.partners.config.schema import DeliveryOverrides
from 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.py
index 8e93dc363..aea048168 100644
--- a/deeptutor/partners/channels/mochat.py
+++ b/deeptutor/partners/channels/mochat.py
@@ -16,7 +16,6 @@ from pydantic import Field
from deeptutor.partners.bus.events import OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
from deeptutor.partners.channels.base import BaseChannel
-from deeptutor.partners.config.paths import get_runtime_subdir
from deeptutor.partners.config.schema import Base, DeliveryOverrides
try:
@@ -293,7 +292,7 @@ class MochatChannel(BaseChannel):
self._socket: Any = None
self._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 = None
diff --git a/deeptutor/partners/channels/msteams.py b/deeptutor/partners/channels/msteams.py
index 4f7a28ce4..4aeb6d67d 100644
--- a/deeptutor/partners/channels/msteams.py
+++ b/deeptutor/partners/channels/msteams.py
@@ -38,7 +38,6 @@ from pydantic import Field
from deeptutor.partners.bus.events import OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
from deeptutor.partners.channels.base import BaseChannel
-from deeptutor.partners.config.paths import get_runtime_subdir
from deeptutor.partners.config.schema import DeliveryOverrides
MSTEAMS_AVAILABLE = (
@@ -133,7 +132,7 @@ class MSTeamsChannel(BaseChannel):
self._botframework_openid_config_expires_at: float = 0.0
self._botframework_jwks: dict[str, Any] | None = None
self._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_FILENAME
self._refs_meta_path = state_dir / MSTEAMS_REF_META_FILENAME
self._refs_lock_path = state_dir / MSTEAMS_REF_LOCK_FILENAME
diff --git a/deeptutor/partners/channels/registry.py b/deeptutor/partners/channels/registry.py
index 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.py
index 0502c6d90..42c5e7777 100644
--- a/deeptutor/partners/channels/weixin.py
+++ b/deeptutor/partners/channels/weixin.py
@@ -31,7 +31,12 @@ from pydantic import Field
from deeptutor.partners.bus.events import OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
from 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 DeliveryOverrides
from deeptutor.partners.helpers import safe_filename, split_message
@@ -54,7 +59,6 @@ MESSAGE_STATE_FINISH = 2
WEIXIN_MAX_MESSAGE_LEN = 4000
WEIXIN_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 = None
token: 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 = d
return d
def _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 False
try:
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_url
return 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_payload
async def _qr_login(self) -> bool:
"""Perform QR code login flow. Returns True on success."""
@@ -364,42 +377,25 @@ class WeixinChannel(BaseChannel):
continue
raise
- 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 += 1
if 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)
@staticmethod
def _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.py
new file mode 100644
index 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__.py
index 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.py
index 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.py
index 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 Any
import aiohttp
+from deeptutor.services.keypool import primary_api_key
from deeptutor.services.llm.config import LLMConfig
from deeptutor.services.llm.context_window import (
coerce_positive_int,
@@ -151,7 +152,7 @@ async def _detect_from_models_endpoint(
return None
url = 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.py
index 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.py
index 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.py
index 97b5d1c7c..9b093c278 100644
--- a/deeptutor/services/llm/config.py
+++ b/deeptutor/services/llm/config.py
@@ -17,6 +17,7 @@ import re
from typing import TYPE_CHECKING, TypedDict
from deeptutor.services.config import resolve_llm_runtime_config
+from deeptutor.services.keypool import primary_api_key
from deeptutor.services.provider_registry import canonical_provider_name, find_by_name
from .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_key
logger.debug("Set OPENAI_API_KEY env var (%s)", source)
diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.py
index 757bc25d0..8d0818eec 100644
--- a/deeptutor/services/llm/factory.py
+++ b/deeptutor/services/llm/factory.py
@@ -9,6 +9,7 @@ from types import SimpleNamespace
from typing import Any, TypedDict
from deeptutor.config.settings import settings
+from deeptutor.services.keypool import primary_api_key
from 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.py
index 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 annotations
import asyncio
from collections.abc import Awaitable, Callable
+import re
from typing import Any
+from urllib.parse import urlsplit, urlunsplit
import uuid
from 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//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.py
index 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 AnthropicProvider
diff --git a/deeptutor/services/partners/channel_state_migration.py b/deeptutor/services/partners/channel_state_migration.py
new file mode 100644
index 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.py
index 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 |reset]"),
+ PartnerCommandSpec(
+ "/link",
+ "Connect this chat account to your DeepTutor account.",
+ "",
+ ),
)
@@ -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 . 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.py
index 063554856..560d9bff4 100644
--- a/deeptutor/services/partners/interaction.py
+++ b/deeptutor/services/partners/interaction.py
@@ -12,7 +12,8 @@ from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar, Token
from dataclasses import dataclass
-from typing import Iterator
+from pathlib import Path
+from typing import Iterator, Literal
from deeptutor.multi_user.models import CurrentUser
from 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 PathService
from .scope import is_partner_user_id
from .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.py
new file mode 100644
index 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 `` 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//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.py
index deca04937..dee36fce8 100644
--- a/deeptutor/services/partners/manager.py
+++ b/deeptutor/services/partners/manager.py
@@ -20,11 +20,14 @@ from typing import Any, Awaitable, Callable
import yaml
+from deeptutor.multi_user.models import CurrentUser
from 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_links
from deeptutor.services.partners.runtime import PartnerRunner
from deeptutor.services.partners.sessions import PartnerSessionStore
from 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()
+
+
@dataclass
class PartnerConfig:
"""Configuration for a single partner."""
name: str
description: 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 MessageBus
bus = 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 ChannelManager
from 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.py
index 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, StreamEventType
from deeptutor.multi_user.paths import get_current_path_service, user_context
from deeptutor.partners.bus.events import InboundMessage, OutboundMessage
from deeptutor.partners.bus.queue import MessageBus
-from deeptutor.partners.config.paths import get_partner_user_sessions_dir
from deeptutor.partners.helpers import detect_image_mime
from deeptutor.services.partners.commands import PartnerCommandHandler
from 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_id
from deeptutor.services.partners.scope import partner_user
from deeptutor.services.partners.sessions import PartnerSessionStore
from 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_id
self.config = config
self.bus = bus
- self.store = store
self.save_config = save_config
self._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_key
store = 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.py
new file mode 100644
index 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.py
index 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.py
new file mode 100644
index 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 --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 `` (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.py
index b01154f6d..cdccf3584 100644
--- a/deeptutor/services/subagent/gemini.py
+++ b/deeptutor/services/subagent/gemini.py
@@ -29,7 +29,11 @@ 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 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.py
index b2217ba0b..2bf067101 100644
--- a/deeptutor/services/subagent/models.py
+++ b/deeptutor/services/subagent/models.py
@@ -34,7 +34,11 @@ from pathlib import Path
import re
from 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_backend
logger = 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 flag
allow_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.py
index 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 " 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[bo
return 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.py
index 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) and
the 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 the
connect-CLI modal.
@@ -12,6 +13,7 @@ from __future__ import annotations
import asyncio
+from deeptutor.services.subagent.antigravity import AntigravityBackend
from deeptutor.services.subagent.base import SubagentBackend
from deeptutor.services.subagent.claude_code import ClaudeCodeBackend
from 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.yml
index 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 ""`. 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: 30s
diff --git a/docker-compose.yml b/docker-compose.yml
index 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 ""`.
+ # - DEEPTUTOR_EXTRAS=math-animator,partners
+ # - DEEPTUTOR_APT_PACKAGES=ffmpeg
+
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}/"]
interval: 30s
diff --git a/scripts/install_extras.py b/scripts/install_extras.py
new file mode 100644
index 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.py
new file mode 100644
index 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"
+)
+
+
+@pytest.fixture
+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 names
diff --git a/tests/api/test_partners_router.py b/tests/api/test_partners_router.py
index 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.
+ def test_onboarding_routes_carry_the_partner_manage_gate(self, monkeypatch):
+ """The real app must gate the onboarding routes on *manage*, 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.
+ 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.
- 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.
+ 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_main
from 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 == 200
assert _create(client).status_code == 409
diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.py
index 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_pa
assert result.success is False
assert "mastery_paths" in result.content
assert LearningStore().list_all() == []
+
+
+@pytest.mark.asyncio
+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.py
index 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"}),
+ )
+
+
+@pytest.mark.asyncio
+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"]
+
+
+@pytest.mark.asyncio
+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"]
+
+
+@pytest.mark.asyncio
+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.py
index 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.py
new file mode 100644
index 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()
+
+
+@pytest.fixture
+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
+
+
+@pytest.mark.parametrize(
+ "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.py
index 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"] == 3072
assert 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)
+
+
+@pytest.mark.parametrize("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",
+ )
+
+
+@pytest.mark.asyncio
+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)
+
+
+@pytest.mark.asyncio
+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 request
diff --git a/tests/services/llm/test_azure_openai_provider.py b/tests/services/llm/test_azure_openai_provider.py
new file mode 100644
index 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/"
+
+
+@pytest.mark.parametrize(
+ "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"
+
+
+@pytest.mark.parametrize(
+ ("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
+
+
+@pytest.mark.parametrize(
+ ("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.py
index 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 annotations
from pathlib import Path
+from typing import Any
import pytest
+from deeptutor.core.stream import StreamEvent
+
@pytest.fixture
def 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
+
+
+@pytest.fixture
+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
diff --git a/tests/services/partners/scripts.py b/tests/services/partners/scripts.py
new file mode 100644
index 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.py
new file mode 100644
index 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
+
+
+@pytest.fixture
+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},
+ )
+
+
+@pytest.mark.asyncio
+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") == []
+
+
+@pytest.mark.asyncio
+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",
+ ]
+
+
+@pytest.mark.asyncio
+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")
+
+
+@pytest.mark.asyncio
+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
+
+
+@pytest.mark.asyncio
+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
+
+
+@pytest.mark.asyncio
+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.py
index 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.py
new file mode 100644
index 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
+
+
+@pytest.fixture
+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.py
index 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.fixture
def 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_path
diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.py
index b3164f306..48eae488c 100644
--- a/tests/services/partners/test_partner_runtime.py
+++ b/tests/services/partners/test_partner_runtime.py
@@ -10,114 +10,26 @@ import pytest
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.partners.bus.events import InboundMessage
from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.services.partners.interaction import session_store_for
from deeptutor.services.partners.manager import PartnerConfig
from deeptutor.services.partners.runtime import PartnerRunner
from 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
-
-
-@pytest.fixture
-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.asyncio
async 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.asyncio
async 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.asyncio
async 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.asyncio
async 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.asyncio
async 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.asyncio
async 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.asyncio
async 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_soul
write_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=None
await 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: it
emits 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.asyncio
async 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) == 1
assert 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) == 1
assert "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.asyncio
async 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=None
await runner.process_message(_msg())
@@ -542,7 +454,7 @@ class TestBuiltinToolsAndMemory:
@pytest.mark.asyncio
async 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.asyncio
async 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.asyncio
async 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 False
store.set_archived("web-a", True)
@@ -663,7 +575,7 @@ class TestSessionStoreOps:
assert store.is_archived("web-a") is False
def 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_dir
from 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 PartnerCommandHandler
runner = _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.content
assert handler.dispatch(_msg("/delete telegram:42")).content.startswith("No conversation")
@@ -792,7 +706,9 @@ class TestPartnerCommands:
from deeptutor.services.partners.commands import PartnerCommandHandler
runner = _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 reply
assert 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) == 1
assert archived[0]["message_count"] == 2
assert archived[0]["session_key"].startswith("_archived_")
@@ -818,11 +734,11 @@ class TestPartnerCommands:
@pytest.mark.asyncio
async 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.asyncio
async 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.py
index 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.fixture
def 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.py
new file mode 100644
index 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
+
+
+@pytest.fixture(autouse=True)
+def _clean_attempts():
+ weixin_onboarding._attempts.clear()
+ yield
+ weixin_onboarding._attempts.clear()
+
+
+@pytest.fixture
+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"
+
+
+@pytest.mark.parametrize(
+ "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 --------------------------------------------------
+
+
+@pytest.mark.asyncio
+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"]
+
+
+@pytest.mark.asyncio
+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
+
+
+@pytest.mark.asyncio
+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
+
+
+@pytest.mark.asyncio
+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"
+
+
+@pytest.mark.asyncio
+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
+
+
+@pytest.mark.asyncio
+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"
+
+
+@pytest.mark.asyncio
+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"
+
+
+@pytest.mark.asyncio
+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"]
+
+
+@pytest.mark.asyncio
+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"
+
+
+@pytest.mark.asyncio
+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"
+
+
+@pytest.mark.asyncio
+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"
+
+
+@pytest.mark.asyncio
+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(" 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 "