DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
prepare v1.3.5 release
Bingxi Zhao (Frank)49661211cee5
diff --git a/.env.example b/.env.exampleindex e72460ed7..0769353d8 100644--- a/.env.example+++ b/.env.example@@ -15,7 +15,7 @@ FRONTEND_PORT=3782# LLM (Required)# --------------------------------------------# Supported bindings: openai, lm_studio, ollama, azure_openai, deepseek, ...-# For a full list run: deeptutor provider list // README+# For a full list run: deeptutor provider listLLM_BINDING=openaiLLM_MODEL=gpt-4o-miniLLM_API_KEY=sk-xxx@@ -29,7 +29,8 @@ LLM_API_VERSION=# siliconflow, aliyun, custom.## IMPORTANT (v1.3.0+): EMBEDDING_HOST is the FULL endpoint URL, not a base.-# What you set here is exactly what gets called — no path appending. Examples:+# LLM_HOST above remains a chat-completions base URL; this embedding value is+# exactly what gets called — no path appending. Examples:# OpenAI: https://api.openai.com/v1/embeddings# Gemini: https://generativelanguage.googleapis.com/v1beta/openai/embeddings# Cohere v4: https://api.cohere.com/v2/embeddiff --git a/.env.example_CN b/.env.example_CNindex 2cd50bcc6..aa2e9e041 100644--- a/.env.example_CN+++ b/.env.example_CN@@ -25,19 +25,42 @@ LLM_API_VERSION=# --------------------------------------------# Embedding(知识库能力必填)# --------------------------------------------+# 支持的 binding: openai, azure_openai, cohere, jina, ollama, vllm,+# siliconflow, aliyun, custom.+#+# 重要(v1.3.0+):EMBEDDING_HOST 必须填写“完整 endpoint URL”,+# 不是基础 URL。上面的 LLM_HOST 仍然是聊天接口 base URL;这里填写的+# embedding 地址会被原样调用,不会自动追加路径。例如:+# OpenAI: https://api.openai.com/v1/embeddings+# Gemini: https://generativelanguage.googleapis.com/v1beta/openai/embeddings+# Cohere v4: https://api.cohere.com/v2/embed+# Jina: https://api.jina.ai/v1/embeddings+# Ollama: http://localhost:11434/api/embed+# SiliconFlow: https://api.siliconflow.cn/v1/embeddings+# Aliyun: https://dashscope.aliyuncs.com/api/v1/services/embeddings/multimodal-embedding/multimodal-embeddingEMBEDDING_BINDING=openaiEMBEDDING_MODEL=text-embedding-3-largeEMBEDDING_API_KEY=sk-xxx-EMBEDDING_HOST=https://api.openai.com/v1-EMBEDDING_DIMENSION=3072+EMBEDDING_HOST=https://api.openai.com/v1/embeddings+# 建议留空,让 DeepTutor 在首次 “Test connection” 成功后自动识别维度。+# 只有在需要强制指定 Matryoshka 维度时才手动填写,例如 Qwen3-Embedding+# 的 1024/1536/2048/2560/4096,或 OpenAI text-embedding-3-large 的 3072。+EMBEDDING_DIMENSION=EMBEDDING_API_VERSION=# 是否在请求体中携带 `dimensions` 参数:-# true -> 总是发送(仅 OpenAI text-embedding-3* 系列官方支持该参数)-# false -> 永不发送(Qwen text-embedding-v4 等模型必须设为 false,-# 否则会返回 HTTP 400)-# 留空或不设置 -> 自动:仅对 OpenAI text-embedding-3* 系列发送+# true -> 总是发送(OpenAI text-embedding-3*, Qwen3-Embedding, Qwen3-VL-Embedding)+# false -> 永不发送(如果提供商在收到 dimensions 参数时返回 HTTP 400,请设为 false)+# 留空或不设置 -> 自动:根据模型家族判断EMBEDDING_SEND_DIMENSIONS=+# 各 embedding 提供商的 API Key 兜底值。当当前 embedding profile 没有+# 单独配置 api_key 时会使用这些值;设置页首次打开时也会读取它们,避免重复输入。+SILICONFLOW_API_KEY=+DASHSCOPE_API_KEY=+COHERE_API_KEY=+JINA_API_KEY=+GEMINI_API_KEY=+# ⚠️ Docker + 本地模型(LM Studio / Ollama / vLLM)# ─────────────────────────────────────────────────────# 当 DeepTutor 以 Docker 方式运行、而 LLM 运行在宿主机上时:@@ -51,7 +74,7 @@ EMBEDDING_SEND_DIMENSIONS=# LLM_BINDING=lm_studio# LLM_HOST=http://host.docker.internal:1234/v1# EMBEDDING_BINDING=lm_studio-# EMBEDDING_HOST=http://host.docker.internal:1234/v1+# EMBEDDING_HOST=http://host.docker.internal:1234/v1/embeddings# --------------------------------------------# 搜索(可选)@@ -73,3 +96,14 @@ NEXT_PUBLIC_API_BASE=# --------------------------------------------# 生产环境请保持 falseDISABLE_SSL_VERIFY=false++# --------------------------------------------+# 聊天附件(可选)+# --------------------------------------------+# 聊天运行时会把用户上传的 PDF、DOCX、图片等文件持久化到这里,+# 方便预览抽屉在内存中的 base64 被释放后仍能重新读取原文件。+#+# 默认路径为 <project>/data/user/workspace/chat/attachments;docker-compose.yml+# 已经把对应目录挂载为持久化 volume。普通 Docker / Linux 部署请留空。+# 只有在多后端实例共用共享存储(例如 NFS)时才需要覆盖。+CHAT_ATTACHMENT_DIR=diff --git a/README.md b/README.mdindex 1b515cc50..b1e413bf5 100644--- a/README.md+++ b/README.md@@ -28,6 +28,8 @@### 📦 Releases+> **[2026.5.2]** [v1.3.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.5) — Smoother local launch settings, safer RAG queries, cleaner local embedding auth, and Settings dark-mode polish.+> **[2026.5.1]** [v1.3.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.4) — Book page chat persistence and rebuild flows, chat-to-book references, stronger language/reasoning handling, RAG document extraction hardening.> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — NVIDIA NIM + Gemini embedding support, unified Space context for chat history/skills/memory, session snapshots, RAG re-index resilience.@@ -126,8 +128,8 @@ Before you begin, make sure the following are installed on your system:|:---|:---|:---|:---|| [Git](https://git-scm.com/) | Any | `git --version` | For cloning the repository || [Python](https://www.python.org/downloads/) | 3.11+ | `python --version` | Backend runtime |-| [Node.js](https://nodejs.org/) | 18+ | `node --version` | Frontend build (not needed for CLI-only or Docker) |-| [npm](https://www.npmjs.com/) | 9+ | `npm --version` | Bundled with Node.js |+| [Node.js](https://nodejs.org/) | 20.9+ | `node --version` | Frontend runtime for local Web installs |+| [npm](https://www.npmjs.com/) | Bundled with Node.js | `npm --version` | Installed with Node.js |> **Windows only (missing compiler fix):** If you do not have Visual Studio, install [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) and ensure the **Desktop development with C++** workload is selected.@@ -135,79 +137,149 @@ You'll also need an **API key** from at least one LLM provider (e.g. [OpenAI](ht### Option A — Setup Tour (Recommended)-A **single interactive CLI script** that takes you from a fresh clone to a running app — no manual `pip install`, no `npm install`, no `.env` editing. Everything is detected, installed, and configured for you in a guided 7-step flow.+A guided CLI wizard for first-time local Web setup. It checks your environment, installs Python and Node.js dependencies, writes `.env`, and lets you choose optional add-ons such as TutorBot, Matrix, and Math Animator.++**1. Clone the repository**```bashgit clone https://github.com/HKUDS/DeepTutor.gitcd DeepTutor+```++**2. Create and activate a Python environment**++Pick **one** of the following based on your system.++macOS / Linux with `venv`:++```bash+python3 -m venv .venv+source .venv/bin/activate+python -m pip install --upgrade pip+```-# Create a Python virtual environment (pick one):-conda create -n deeptutor python=3.11 && conda activate deeptutor # Anaconda/Miniconda-python -m venv .venv && source .venv/bin/activate # macOS/Linux-python -m venv .venv && .venv\Scripts\activate # Windows+Windows PowerShell with `venv`:-# Launch the guided tour+```powershell+py -3.11 -m venv .venv+.\.venv\Scripts\Activate.ps1+python -m pip install --upgrade pip+```++Anaconda / Miniconda:++```bash+conda create -n deeptutor python=3.11+conda activate deeptutor+python -m pip install --upgrade pip+```++**3. Launch the guided tour**++```bashpython scripts/start_tour.py```+During the install step, the tour asks which dependency profile you want:++| Choice | What it installs | When to choose it |+|:---|:---|:---|+| Web app (recommended) | CLI + API server + RAG/document parsing | Most first-time users |+| Web + TutorBot | Adds TutorBot engine and common channel SDKs | If you want autonomous tutor bots or channel integrations |+| Web + TutorBot + Matrix | Adds Matrix / Element channel support | Only if you already have `libolm` installed or are ready to install it |+| Math Animator add-on | Installs Manim separately | Only if you need animation generation and have LaTeX/ffmpeg/system build tools ready |+Once the wizard finishes:```bashpython scripts/start_web.py```-> **Daily launch** — The tour is only needed once. From now on, just run `python scripts/start_web.py` to boot both the backend and frontend in a single command (the frontend URL is printed in the terminal). Re-run `start_tour.py` only if you want to reconfigure providers, change ports, or install missing extras. Inside the web **Settings** page you can also click **Run Tour** to replay the highlight-based UI walkthrough.+> **Daily launch** — The tour is only needed once. From now on, keep that Python environment activated and run `python scripts/start_web.py` to boot both the backend and frontend. The frontend URL is printed in the terminal. Re-run `start_tour.py` only if you want to reconfigure providers, change ports, or install optional add-ons.> **Updating a local install** — If you installed with Option A or Option B from a git clone, run `python scripts/update.py`. The updater fetches the remote for your current branch, shows the local-vs-remote commit gap, asks you to confirm the detected branch mapping, then performs a safe fast-forward pull.### Option B — Manual Local Install-If you prefer full control, install and configure everything yourself.+Use this path if you prefer to run each setup command yourself.-**1. Install dependencies**+**1. Clone the repository**```bashgit clone https://github.com/HKUDS/DeepTutor.gitcd DeepTutor+```-# Create & activate a Python virtual environment (same as Option A)-conda create -n deeptutor python=3.11 && conda activate deeptutor+**2. Create and activate a Python environment**-# Install DeepTutor with backend + web server dependencies-# (includes RAG, document parsing, and all built-in LLM provider SDKs)-pip install -e ".[server]"+Pick **one** of the following.-# Optional add-ons — install only the ones you need:-# pip install -e ".[tutorbot]" # TutorBot agent engine + channel SDKs-# pip install -e ".[matrix]" # Matrix channel for TutorBot (requires libolm)-# pip install -e ".[math-animator]" # Manim (also requires LaTeX & ffmpeg)-# pip install -e ".[all]" # Everything above + dev tools+macOS / Linux with `venv`:++```bash+python3 -m venv .venv+source .venv/bin/activate+python -m pip install --upgrade pip+```++Windows PowerShell with `venv`:++```powershell+py -3.11 -m venv .venv+.\.venv\Scripts\Activate.ps1+python -m pip install --upgrade pip+```++Anaconda / Miniconda:++```bash+conda create -n deeptutor python=3.11+conda activate deeptutor+python -m pip install --upgrade pip+```-# Install frontend dependencies (requires Node.js 18+)-cd web && npm install && cd ..+**3. Install dependencies**++```bash+# Backend + Web server dependencies. Includes CLI, RAG, document parsing,+# and built-in LLM provider SDKs.+python -m pip install -e ".[server]"++# Optional add-ons — install only the ones you need:+# python -m pip install -e ".[tutorbot]" # TutorBot engine + channel SDKs+# python -m pip install -e ".[tutorbot,matrix]" # TutorBot + Matrix channel; requires libolm+# python -m pip install -e ".[math-animator]" # Manim; also requires LaTeX/ffmpeg/system build tools+# python -m pip install -e ".[all]" # Everything above + dev tools++# Frontend dependencies. Requires Node.js 20.9+.+cd web+npm install+cd ..```-**2. Configure environment**+**4. Configure environment**```bashcp .env.example .env```-Edit `.env` and fill in at least the required fields:+Edit `.env` and fill in at least the LLM fields. Embedding fields are needed for Knowledge Base features and can be left for later if you only want to try chat first.```dotenv-# LLM (Required)+# LLM (required for chat)LLM_BINDING=openaiLLM_MODEL=gpt-4o-miniLLM_API_KEY=sk-xxxLLM_HOST=https://api.openai.com/v1-# Embedding (Required for Knowledge Base)+# Embedding (required for Knowledge Base / RAG)EMBEDDING_BINDING=openaiEMBEDDING_MODEL=text-embedding-3-largeEMBEDDING_API_KEY=sk-xxx-EMBEDDING_HOST=https://api.openai.com/v1-EMBEDDING_DIMENSION=3072+# v1.3.0+: use the full endpoint URL, not just https://api.openai.com/v1+EMBEDDING_HOST=https://api.openai.com/v1/embeddings+# Leave empty unless you need to force a specific dimension.+EMBEDDING_DIMENSION=```<details>@@ -281,7 +353,7 @@ OpenAI-compatible providers (DashScope, SiliconFlow, etc.) work via the `custom`</details>-**3. Start services**+**5. Start services**The quickest way to launch everything:@@ -289,7 +361,7 @@ The quickest way to launch everything:python scripts/start_web.py```-This starts both the backend and frontend and opens the browser automatically.+This starts both the backend and frontend. Keep the terminal open, then open the frontend URL printed in the terminal.Alternatively, start each service manually in separate terminals:@@ -333,7 +405,7 @@ docker compose -f docker-compose.ghcr.yml up -dTo pin a specific version, edit the image tag in `docker-compose.ghcr.yml`:```yaml-image: ghcr.io/hkuds/deeptutor:1.0.0 # or :latest+image: ghcr.io/hkuds/deeptutor:1.3.4 # or :latest```**2b. Build from source**@@ -422,11 +494,11 @@ These directories survive `docker compose down` and are reused on the next `dock| `LLM_MODEL` | **Yes** | Model name (e.g. `gpt-4o`) || `LLM_API_KEY` | **Yes** | Your LLM API key || `LLM_HOST` | **Yes** | API endpoint URL |-| `EMBEDDING_BINDING` | **Yes** | Embedding provider |-| `EMBEDDING_MODEL` | **Yes** | Embedding model name |-| `EMBEDDING_API_KEY` | **Yes** | Embedding API key |-| `EMBEDDING_HOST` | **Yes** | Embedding endpoint |-| `EMBEDDING_DIMENSION` | **Yes** | Vector dimension |+| `EMBEDDING_BINDING` | Knowledge Base only | Embedding provider |+| `EMBEDDING_MODEL` | Knowledge Base only | Embedding model name |+| `EMBEDDING_API_KEY` | Knowledge Base only | Embedding API key |+| `EMBEDDING_HOST` | Knowledge Base only | Full embedding endpoint URL |+| `EMBEDDING_DIMENSION` | No | Vector dimension; leave empty for auto-detection || `SEARCH_PROVIDER` | No | Search provider (`tavily`, `jina`, `serper`, `perplexity`, etc.) || `SEARCH_API_KEY` | No | Search API key || `BACKEND_PORT` | No | Backend port (default `8001`) |@@ -443,7 +515,7 @@ If you just want the CLI without the web frontend:```bash# Includes RAG, document parsing, and all built-in LLM provider SDKs.# Same set as Option B minus FastAPI/uvicorn.-pip install -e ".[cli]"+python -m pip install -e ".[cli]"```You still need to configure your LLM provider. The quickest way:diff --git a/assets/releases/ver1-3-5.md b/assets/releases/ver1-3-5.mdnew file mode 100644index 000000000..7e5fbda89--- /dev/null+++ b/assets/releases/ver1-3-5.md@@ -0,0 +1,81 @@+# DeepTutor v1.3.5 Release Notes++**Release Date:** 2026.05.02++v1.3.5 focuses on making local setup and knowledge-base chat more reliable. The+launcher now follows the same runtime settings users configure in the web app,+RAG tool calls are stricter about real search queries, and local embedding+servers no longer receive placeholder auth headers.++## Highlights++### Smoother Local Launch++- **Setup Tour writes launch ports** - the guided installer now records backend+ and frontend ports in `data/user/settings/env.json`, so later launches can use+ the same choices.+- **`start_web.py` reads runtime settings first** - backend/frontend ports and UI+ language come from web settings when available, with `.env` kept as fallback.+- **Cleaner process handling** - the launcher records started processes, detects+ port conflicts, waits for readiness, and exposes `scripts/stop_web.py` for+ cleaning up recorded backend/frontend processes.+- **Setup requirements are clearer** - README and environment examples now align+ around Node.js 20.9+, install profiles, complete embedding endpoint URLs, and+ optional attachment storage.++### More Reliable RAG Tool Calls++- **RAG queries must be non-empty** - tool schemas, prompts, and built-in checks+ now reject blank queries early instead of passing empty input into retrieval.+- **Chat-side fallback is safer** - when a model omits the RAG query, the agentic+ pipeline can reuse the user's actual question as the retrieval query.+- **ReAct calls accept simple string input** - `rag` actions that provide a+ string are normalized to `{"query": ...}`, reducing fragile tool-call failures.++### Local Embedding Compatibility++- **No fake API key for local embedding providers** - runtime config no longer+ injects `sk-no-key-required` for local embedding servers.+- **Placeholder keys are not sent as auth headers** - OpenAI-compatible+ embedding requests suppress `Authorization` and `api-key` when the configured+ key is the local placeholder, which helps LM Studio, Ollama, vLLM, and similar+ servers.+- **Embedding examples are easier to follow** - English and Chinese sample env+ files now explain that `EMBEDDING_HOST` is the exact endpoint DeepTutor calls.++### Web UX Polish++- **Dark-mode provider dropdown is readable** - the Settings provider selector+ now uses the theme background token, fixing the white native dropdown popover+ reported on Edge/Chromium.+- **Settings controls are more consistent** - select fields and setup tour+ spotlight behavior were tightened for a steadier settings experience.+- **Book reference payloads are normalized more defensively** - selected book+ references keep the same behavior with cleaner filtering and deduplication.++## Tests++- Added launch settings tests for runtime settings precedence, `.env` fallback,+ and invalid-port handling.+- Added `start_web.py` tests for translation, state persistence, and recorded+ process matching.+- Added Setup Tour coverage for dependency profiles, Math Animator selection,+ Node.js version validation, and saved launch ports.+- Added RAG/tool tests for non-empty query schemas, blank-query rejection, and+ fallback query behavior.+- Added embedding runtime and adapter tests for local providers, placeholder API+ keys, and auth header suppression.++## Upgrade Notes++- Local web installs now require Node.js 20.9 or newer.+- `start_web.py` and setup helpers prefer `data/user/settings/env.json` and+ `interface.json` over `.env`; edit the web Settings page or rerun+ `start_tour.py` when changing launch ports.+- Local OpenAI-compatible embedding servers should use an empty API key unless a+ real key is required. Avoid relying on `sk-no-key-required` as a transmitted+ credential.+- Custom RAG callers should always provide a non-empty `query`; blank queries now+ fail fast by design.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.4...v1.3.5diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex 54140d573..da2406476 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -683,6 +683,8 @@ class AgenticChatPipeline:context,thinking_text,)+ if tool_name == "rag":+ display_args = self._llm_visible_tool_args(tool_name, execution_args)pending_calls.append((tool_call.id, tool_name, display_args, execution_args))for tool_index, (tool_call_id, tool_name, display_args, _execution_args) in enumerate(@@ -841,8 +843,12 @@ class AgenticChatPipeline:payload = {}action = str(payload.get("action") or "done").strip()- action_input = payload.get("action_input") or {}- if not isinstance(action_input, dict):+ raw_action_input = payload.get("action_input")+ if isinstance(raw_action_input, dict):+ action_input = raw_action_input+ elif action == "rag" and isinstance(raw_action_input, str):+ action_input = {"query": raw_action_input}+ else:action_input = {}if action == "done":@@ -872,6 +878,8 @@ class AgenticChatPipeline:display_args = self._llm_visible_tool_args(action, action_input)tool_args = self._augment_tool_kwargs(action, display_args, context, thinking_text)+ if action == "rag":+ display_args = self._llm_visible_tool_args(action, tool_args)if response:await stream.thinking(response,@@ -1073,6 +1081,9 @@ class AgenticChatPipeline:properties = parameters.get("properties")if isinstance(properties, dict):properties.pop("kb_name", None)+ query_schema = properties.get("query")+ if isinstance(query_schema, dict):+ query_schema.setdefault("minLength", 1)required = parameters.get("required")if isinstance(required, list):parameters["required"] = [name for name in required if name != "kb_name"]@@ -1264,6 +1275,10 @@ class AgenticChatPipeline:task_dir = get_path_service().get_task_workspace("chat", turn_id)if tool_name == "rag":selected_kbs = self._selected_kbs(context)+ if not str(kwargs.get("query") or "").strip():+ fallback_query = self._fallback_rag_query(context)+ if fallback_query:+ kwargs["query"] = fallback_querykwargs["kb_name"] = selected_kbs[0] if selected_kbs else ""kwargs.setdefault("mode", "hybrid")elif tool_name == "code_execution":@@ -1286,6 +1301,14 @@ class AgenticChatPipeline:kwargs.setdefault("output_dir", str(task_dir / "web_search"))return kwargs+ @staticmethod+ def _fallback_rag_query(context: UnifiedContext) -> str:+ message = str(context.user_message or "")+ marker = "[User Question]\n"+ if marker in message:+ message = message.rsplit(marker, 1)[-1]+ return " ".join(message.split())[:800]+def _acting_system_prompt(self, enabled_tools: list[str], context: UnifiedContext) -> str:kb_name = context.knowledge_bases[0] if context.knowledge_bases else ""tool_list = self.registry.build_prompt_text(@@ -1342,14 +1365,14 @@ class AgenticChatPipeline:return ""if getattr(self, "language", "en") == "zh":return (- "本轮已有系统态选中的知识库。如果需要知识库检索,只需调用 RAG 并提供 query;"- "不要输出、猜测或沿用任何知识库名称。系统会把 query 发到当前选中的知识库。"+ "本轮已有系统态选中的知识库。如果需要知识库检索,只需调用 RAG 并提供非空 query;"+ "不要输出、猜测或沿用任何知识库名称,也不要传 kb_name。系统会把 query 发到当前选中的知识库。")return ("A knowledge base is selected in system state for this turn. "- "If retrieval is useful, call RAG with only a query; do not output, "- "guess, or reuse any knowledge-base name. The system will route the "- "query to the currently selected knowledge base."+ "If retrieval is useful, call RAG with only a non-empty query; do not output, "+ "guess, reuse, or pass any knowledge-base name. The system will route "+ "the query to the currently selected knowledge base.")def _rag_without_kb_message(self) -> str:diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yamlindex f825579a5..15e82c873 100644--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml@@ -55,9 +55,10 @@ acting:2. For complex questions that need definitions, grounding, outside evidence, papers, calculation, or deeper reasoning, prefer calling multiple complementary tools in parallel so each one covers a distinct information need.3. Call tools only when they add value, but when they materially improve answer quality you should use them fully.4. Use concrete, executable arguments grounded in the user's request, and adapt the wording when different tools need different query styles.- 5. If enough evidence already exists, you may skip tool use.- 6. Do not produce the final student-facing answer here; this stage is only for tool use.- 7. At most {max_parallel_tools} tools may run in parallel in one turn; if several complementary tools are relevant, prefer issuing them together in the same turn.+ 5. When calling RAG, you MUST provide a non-empty query field. The query should be a natural-language retrieval sentence extracted or rewritten from the user request or thinking. Do not pass an empty object, an empty string, or kb_name.+ 6. If enough evidence already exists, you may skip tool use.+ 7. Do not produce the final student-facing answer here; this stage is only for tool use.+ 8. At most {max_parallel_tools} tools may run in parallel in one turn; if several complementary tools are relevant, prefer issuing them together in the same turn.Enabled tools:{tool_list}@@ -138,7 +139,7 @@ react_fallback:Available actions:{tool_table}- Decide from the user request and the full enabled tool list whether tool use is truly needed; if it is, choose the single tool that best closes the most important information gap. If no tool is needed, set action=done.+ Decide from the user request and the full enabled tool list whether tool use is truly needed; if it is, choose the single tool that best closes the most important information gap. If you call rag, action_input MUST be {{"query": "non-empty retrieval query"}}; do not pass an empty object, an empty string, or kb_name. If no tool is needed, set action=done.done_when_to_use: "Use when the available information is sufficient and no more tools are needed."done_input_format: "Empty string."diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yamlindex 68074b8c1..4c12bbea6 100644--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml@@ -55,9 +55,10 @@ acting:2. 对于需要定义、事实核验、外部资料、论文、计算、推理等不同信息面的复杂问题,优先并行调用多个互补工具来覆盖这些信息面。3. 只调用真正有帮助的工具,但只要工具能显著提升答案质量,就应充分调用。4. 参数要具体、可执行,优先使用用户原问题中的关键信息,必要时针对不同工具改写成最适合它的查询。- 5. 如果信息已经足够,可以不调用工具。- 6. 不要输出最终回答给学生;这里只负责工具选择与调用。- 7. 单轮最多并行调用 {max_parallel_tools} 个工具;如果有多个互补工具都相关,优先在同一轮一起调用。+ 5. 调用 RAG 时,必须提供非空的 query 字段;query 应是从用户问题或 thinking 中抽取/改写出的自然语言检索句。不要传空对象、空字符串或 kb_name。+ 6. 如果信息已经足够,可以不调用工具。+ 7. 不要输出最终回答给学生;这里只负责工具选择与调用。+ 8. 单轮最多并行调用 {max_parallel_tools} 个工具;如果有多个互补工具都相关,优先在同一轮一起调用。当前可用工具:{tool_list}@@ -138,7 +139,7 @@ react_fallback:可选动作如下:{tool_table}- 先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。如果不需要工具,请输出 action=done。+ 先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。如果调用 rag,action_input 必须是 {{"query": "非空检索句"}},不要传空对象、空字符串或 kb_name。如果不需要工具,请输出 action=done。done_when_to_use: "当已有信息足够,且不需要继续调用工具时使用。"done_input_format: "空字符串。"diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.pyindex e6d99c1d6..1dce55752 100644--- a/deeptutor/services/config/__init__.py+++ b/deeptutor/services/config/__init__.py@@ -18,6 +18,7 @@ from .loader import (parse_language,resolve_config_path,)+from .launch_settings import LaunchSettings, load_launch_settingsfrom .model_catalog import ModelCatalogService, get_model_catalog_service# Re-export the loader module itself for code paths that monkeypatch via the@@ -28,6 +29,8 @@ __all__ = ["ConfigSummary","EnvStore","get_env_store",+ "LaunchSettings",+ "load_launch_settings",# From loader.py"PROJECT_ROOT","get_runtime_settings_dir",diff --git a/deeptutor/services/config/launch_settings.py b/deeptutor/services/config/launch_settings.pynew file mode 100644index 000000000..8406e7069--- /dev/null+++ b/deeptutor/services/config/launch_settings.py@@ -0,0 +1,131 @@+from __future__ import annotations++from dataclasses import dataclass+import json+import os+from pathlib import Path+from typing import Any++from .env_store import EnvStore++PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent+DEFAULT_BACKEND_PORT = 8001+DEFAULT_FRONTEND_PORT = 3782+DEFAULT_LANGUAGE = "en"+++@dataclass(frozen=True, slots=True)+class LaunchSettings:+ backend_port: int+ frontend_port: int+ language: str+ source: str+ settings_dir: Path+ env_json_path: Path+ interface_json_path: Path+ env_path: Path+++def _load_json_object(path: Path) -> dict[str, Any]:+ if not path.exists() or path.stat().st_size == 0:+ return {}+ try:+ loaded = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ return {}+ return loaded if isinstance(loaded, dict) else {}+++def _coerce_port(value: Any) -> int | None:+ try:+ port = int(value)+ except (TypeError, ValueError):+ return None+ if 1 <= port <= 65535:+ return port+ return None+++def _normalize_language(value: Any) -> str | None:+ if not isinstance(value, str):+ return None+ language = value.strip().lower()+ if language in {"en", "english"} or language.startswith("en_"):+ return "en"+ if language in {"zh", "cn", "chinese"} or language.startswith("zh_"):+ return "zh"+ return None+++def load_launch_settings(project_root: Path | None = None) -> LaunchSettings:+ """Load ports and UI language for launcher-style entry points.++ Runtime settings under ``data/user/settings`` are preferred because they+ reflect the web Settings flow. When that directory or the relevant files+ are absent/empty/invalid, the project ``.env`` remains the compatibility+ fallback used by older installs and manual setups.+ """++ root = project_root or PROJECT_ROOT+ settings_dir = root / "data" / "user" / "settings"+ env_json_path = settings_dir / "env.json"+ interface_json_path = settings_dir / "interface.json"+ env_path = root / ".env"++ settings_env = _load_json_object(env_json_path)+ interface_settings = _load_json_object(interface_json_path)+ env_store = EnvStore(env_path)+ env_values = env_store.load()++ settings_ports = settings_env.get("ports") if isinstance(settings_env.get("ports"), dict) else {}+ settings_backend_port = _coerce_port(settings_ports.get("backend"))+ settings_frontend_port = _coerce_port(settings_ports.get("frontend"))+ interface_language = _normalize_language(interface_settings.get("language"))+ backend_port = (+ settings_backend_port+ or _coerce_port(env_values.get("BACKEND_PORT"))+ or _coerce_port(os.getenv("BACKEND_PORT"))+ or DEFAULT_BACKEND_PORT+ )+ frontend_port = (+ settings_frontend_port+ or _coerce_port(env_values.get("FRONTEND_PORT"))+ or _coerce_port(os.getenv("FRONTEND_PORT"))+ or DEFAULT_FRONTEND_PORT+ )+ language = (+ interface_language+ or _normalize_language(env_values.get("UI_LANGUAGE"))+ or _normalize_language(env_values.get("LANGUAGE"))+ or _normalize_language(os.getenv("UI_LANGUAGE"))+ or _normalize_language(os.getenv("LANGUAGE"))+ or DEFAULT_LANGUAGE+ )++ sources: list[str] = []+ if settings_backend_port is not None or settings_frontend_port is not None:+ sources.append("data/user/settings/env.json")+ if interface_language is not None:+ sources.append("data/user/settings/interface.json")+ if not sources:+ sources.append(".env")++ return LaunchSettings(+ backend_port=backend_port,+ frontend_port=frontend_port,+ language=language,+ source=" + ".join(sources),+ settings_dir=settings_dir,+ env_json_path=env_json_path,+ interface_json_path=interface_json_path,+ env_path=env_path,+ )+++__all__ = [+ "DEFAULT_BACKEND_PORT",+ "DEFAULT_FRONTEND_PORT",+ "DEFAULT_LANGUAGE",+ "LaunchSettings",+ "load_launch_settings",+]diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex 2c9321d56..39317f91f 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -659,9 +659,6 @@ def resolve_embedding_runtime_config(api_version = active_api_version or ((mapped.api_version or "") if mapped else "")extra_headers = active_extra_headers or ((mapped.extra_headers or {}) if mapped else {})- if spec.is_local and not api_key:- api_key = "sk-no-key-required"-return ResolvedEmbeddingConfig(model=resolved_model,provider_name=provider_name,diff --git a/deeptutor/services/embedding/.env.example b/deeptutor/services/embedding/.env.exampleindex c7e521fbb..3fa64f5b6 100644--- a/deeptutor/services/embedding/.env.example+++ b/deeptutor/services/embedding/.env.example@@ -96,7 +96,8 @@ EMBEDDING_DIMENSION=1024# ============================================EMBEDDING_BINDING=vllmEMBEDDING_MODEL=text-embedding-model-EMBEDDING_API_KEY=sk-no-key-required+# Leave blank for local servers like LM Studio that reject auth headers.+EMBEDDING_API_KEY=EMBEDDING_HOST=http://localhost:8000/v1/embeddingsEMBEDDING_DIMENSION=1024diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.pyindex 3c00bff77..8360d38db 100644--- a/deeptutor/services/embedding/adapters/openai_compatible.py+++ b/deeptutor/services/embedding/adapters/openai_compatible.py@@ -17,12 +17,21 @@ logger = logging.getLogger(__name__)class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):+ NO_KEY_SENTINEL = "sk-no-key-required"+MODELS_INFO = {"text-embedding-3-large": {"default": 3072, "dimensions": [256, 512, 1024, 3072]},"text-embedding-3-small": {"default": 1536, "dimensions": [512, 1536]},"text-embedding-ada-002": 1536,}+ def _auth_api_key(self) -> str:+ """Return a real API key, suppressing local-provider placeholder keys."""+ key = str(self.api_key or "").strip()+ if key == self.NO_KEY_SENTINEL:+ return ""+ return key+@staticmethoddef _extract_embeddings_from_response(data: Any) -> list[list[float]]:"""@@ -132,11 +141,12 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):import asyncioheaders = {"Content-Type": "application/json"}+ api_key = self._auth_api_key()if self.api_version:- if self.api_key:- headers["api-key"] = self.api_key- elif self.api_key:- headers["Authorization"] = f"Bearer {self.api_key}"+ if api_key:+ headers["api-key"] = api_key+ elif api_key:+ headers["Authorization"] = f"Bearer {api_key}"headers.update({str(k): str(v) for k, v in self.extra_headers.items()})# Multimodal: pass `contents` through as `input` when set. SiliconFlow'sdiff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.pyindex 808cc7ecd..fe58af5da 100644--- a/deeptutor/services/setup/init.py+++ b/deeptutor/services/setup/init.py@@ -217,13 +217,22 @@ def _write_yaml_if_missing(file_path: Path, payload: dict) -> None:def get_backend_port(project_root: Path | None = None) -> int:"""- Get backend port from environment variable.+ Get backend port from runtime settings, falling back to environment.- Configure in .env file: BACKEND_PORT=8001+ Preferred source: data/user/settings/env.json -> ports.backend+ Fallback source: .env -> BACKEND_PORTReturns:Backend port number (default: 8001)"""+ try:+ from deeptutor.services.config.launch_settings import load_launch_settings++ return load_launch_settings(project_root).backend_port+ except Exception:+ # Preserve the historical .env fallback if runtime settings cannot load.+ pass+env_port = get_env_store().get("BACKEND_PORT", "8001")try:return int(env_port)@@ -235,13 +244,22 @@ def get_backend_port(project_root: Path | None = None) -> int:def get_frontend_port(project_root: Path | None = None) -> int:"""- Get frontend port from environment variable.+ Get frontend port from runtime settings, falling back to environment.- Configure in .env file: FRONTEND_PORT=3782+ Preferred source: data/user/settings/env.json -> ports.frontend+ Fallback source: .env -> FRONTEND_PORTReturns:Frontend port number (default: 3782)"""+ try:+ from deeptutor.services.config.launch_settings import load_launch_settings++ return load_launch_settings(project_root).frontend_port+ except Exception:+ # Preserve the historical .env fallback if runtime settings cannot load.+ pass+env_port = get_env_store().get("FRONTEND_PORT", "3782")try:return int(env_port)diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex 0bfd9f29b..86e26dc8c 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -77,7 +77,9 @@ class RAGTool(_PromptHintsMixin, BaseTool):async def execute(self, **kwargs: Any) -> ToolResult:from deeptutor.tools.rag_tool import rag_search- query = kwargs.get("query", "")+ query = str(kwargs.get("query") or "").strip()+ if not query:+ raise ValueError("RAG query must be a non-empty string.")kb_name = kwargs.get("kb_name")event_sink = kwargs.get("event_sink")extra_kwargs = {diff --git a/deeptutor/tools/prompting/hints/en/rag.yaml b/deeptutor/tools/prompting/hints/en/rag.yamlindex 322bc9348..bfd4cfa1b 100644--- a/deeptutor/tools/prompting/hints/en/rag.yaml+++ b/deeptutor/tools/prompting/hints/en/rag.yaml@@ -1,6 +1,6 @@short_description: "Search the knowledge base for relevant passages and grounded answers."when_to_use: "Use when the answer is likely covered by the uploaded knowledge base, such as definitions, formulas, concepts, or textbook explanations."-input_format: "Natural-language query."+input_format: "{\"query\": \"non-empty natural-language query\"}. Do not pass an empty query or kb_name."guideline: "Prefer RAG before external search when the task is course-aligned or knowledge-base-specific."-note: "If the first retrieval is weak, revise the query from another angle instead of giving up immediately."+note: "The query must be non-empty; if the first retrieval is weak, revise the query from another angle instead of giving up immediately."phase: "exploration"diff --git a/deeptutor/tools/prompting/hints/zh/rag.yaml b/deeptutor/tools/prompting/hints/zh/rag.yamlindex c82963d34..950acdbd5 100644--- a/deeptutor/tools/prompting/hints/zh/rag.yaml+++ b/deeptutor/tools/prompting/hints/zh/rag.yaml@@ -1,6 +1,6 @@short_description: "在知识库中检索相关内容,并生成有依据的回答。"when_to_use: "当答案大概率来自已上传知识库,例如定义、公式、概念解释或教材内容时使用。"-input_format: "自然语言查询。"+input_format: "{\"query\": \"非空自然语言查询\"}。不要传空 query 或 kb_name。"guideline: "如果任务与课程材料强相关,优先使用 RAG,而不是直接转向外部搜索。"-note: "第一次检索效果不佳时,应先换一个查询角度再判断是否无结果。"+note: "query 不能为空;若第一次检索效果不佳,应先换一个查询角度再判断是否无结果。"phase: "exploration"diff --git a/deeptutor/tools/rag_tool.py b/deeptutor/tools/rag_tool.pyindex bacc52d38..e9a449728 100644--- a/deeptutor/tools/rag_tool.py+++ b/deeptutor/tools/rag_tool.py@@ -64,6 +64,10 @@ async def rag_search("provider": str}"""+ query = str(query or "").strip()+ if not query:+ raise ValueError("RAG query must be a non-empty string.")+service = RAGService(kb_base_dir=kb_base_dir, provider=provider)resolved_kb_name = _resolve_kb_name(kb_name, kb_base_dir=kb_base_dir)if not resolved_kb_name:diff --git a/scripts/start_tour.py b/scripts/start_tour.pyindex 6cf744183..f528d9a27 100644--- a/scripts/start_tour.py+++ b/scripts/start_tour.py@@ -24,6 +24,7 @@ configure_text_streams()ENV_PATH = PROJECT_ROOT / ".env"ENV_EXAMPLE_PATH = PROJECT_ROOT / ".env.example"INTERFACE_SETTINGS_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "interface.json"+ENV_SETTINGS_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "env.json"LEGACY_TOUR_CACHE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / ".tour_cache.json"@@ -169,6 +170,8 @@ PROFILE_COMMANDS: dict[str, list[str]] = {"cli-rag": ["requirements/cli.txt"],"web-basic": ["requirements/server.txt"],"web-rag": ["requirements/server.txt"],+ "web-tutorbot": ["requirements/tutorbot.txt"],+ "web-matrix": ["requirements/matrix.txt"],}PROFILE_ALIASES: dict[str, str] = {@@ -179,6 +182,7 @@ PROFILE_ALIASES: dict[str, str] = {}MATH_ANIMATOR_REQUIREMENTS = "requirements/math-animator.txt"+NODE_MIN_VERSION = (20, 9, 0)MESSAGES: dict[str, dict[str, str]] = {@@ -272,8 +276,22 @@ MESSAGES: dict[str, dict[str, str]] = {"install_node_hint_winget": "Install with: winget install OpenJS.NodeJS","install_node_hint_manual": "Download from https://nodejs.org","install_node_abort": "Node.js is required for the frontend. Please install it and re-run this script.",+ "install_node_too_old": "Node.js {version} is too old. DeepTutor web requires Node.js >=20.9.0.",+ "install_profile_prompt": "Choose installation profile",+ "install_profile_web_label": "Web app (recommended)",+ "install_profile_web_desc": "CLI + API server + RAG/document parsing",+ "install_profile_tutorbot_label": "Web + TutorBot",+ "install_profile_tutorbot_desc": "Adds TutorBot engine and common channel SDKs",+ "install_profile_matrix_label": "Web + TutorBot + Matrix",+ "install_profile_matrix_desc": "Also installs matrix-nio[e2e]; requires libolm on your system",+ "install_math_animator": "Install Math Animator add-on?",+ "install_math_animator_hint": (+ "Optional: Manim can require LaTeX, Cairo, pkg-config, CMake, and ffmpeg."+ ),+ "install_selected": "Selected install profile: {profile}","install_confirm": "Install dependencies now?","install_backend": "Installing Python dependencies ...",+ "install_requirement": "Installing {requirement} ...","install_backend_done": "Python dependencies installed.","install_frontend": "Installing frontend dependencies (npm install) ...","install_frontend_done": "Frontend dependencies installed.",@@ -374,8 +392,20 @@ MESSAGES: dict[str, dict[str, str]] = {"install_node_hint_winget": "请运行: winget install OpenJS.NodeJS","install_node_hint_manual": "请前往 https://nodejs.org 下载安装","install_node_abort": "前端运行需要 Node.js,请安装后重新运行本脚本。",+ "install_node_too_old": "当前 Node.js {version} 版本过低。DeepTutor Web 需要 Node.js >=20.9.0。",+ "install_profile_prompt": "选择安装配置",+ "install_profile_web_label": "Web 应用(推荐)",+ "install_profile_web_desc": "CLI + API 服务 + RAG/文档解析",+ "install_profile_tutorbot_label": "Web + TutorBot",+ "install_profile_tutorbot_desc": "增加 TutorBot 引擎和常用渠道 SDK",+ "install_profile_matrix_label": "Web + TutorBot + Matrix",+ "install_profile_matrix_desc": "额外安装 matrix-nio[e2e];系统需先安装 libolm",+ "install_math_animator": "是否安装 Math Animator 附加能力?",+ "install_math_animator_hint": "选填:Manim 可能需要 LaTeX、Cairo、pkg-config、CMake 和 ffmpeg。",+ "install_selected": "已选择安装配置:{profile}","install_confirm": "现在安装依赖?","install_backend": "正在安装 Python 依赖 ...",+ "install_requirement": "正在安装 {requirement} ...","install_backend_done": "Python 依赖安装完成。","install_frontend": "正在安装前端依赖(npm install)...","install_frontend_done": "前端依赖安装完成。",@@ -496,6 +526,16 @@ def _install_commands(return cmds+def _requirements_for_install(profile: str, *, include_math_animator: bool = False) -> list[str]:+ profile = PROFILE_ALIASES.get(profile, profile)+ if profile not in PROFILE_COMMANDS:+ raise ValueError(f"Unknown install profile: {profile}")+ requirements = list(PROFILE_COMMANDS[profile])+ if include_math_animator:+ requirements.append(MATH_ANIMATOR_REQUIREMENTS)+ return requirements++def _run_cmd(cmd: list[str], cwd: Path) -> None:log_info(f"{dim(str(cwd))} {' '.join(cmd)}")use_shell = platform.system().lower() == "windows"@@ -552,6 +592,35 @@ def _save_ui_language(language: str, path: Path = INTERFACE_SETTINGS_PATH) -> Nopath.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")+def _save_launch_ports(values: dict[str, str], path: Path = ENV_SETTINGS_PATH) -> None:+ """Keep launcher ports in runtime settings without rewriting provider data."""+ backend = values.get("BACKEND_PORT")+ frontend = values.get("FRONTEND_PORT")+ if backend is None and frontend is None:+ return++ payload: dict[str, Any] = {}+ if path.exists() and path.stat().st_size > 0:+ try:+ loaded = json.loads(path.read_text(encoding="utf-8"))+ if isinstance(loaded, dict):+ payload = loaded+ except Exception:+ payload = {}++ payload.setdefault("version", 1)+ ports = payload.get("ports")+ if not isinstance(ports, dict):+ ports = {}+ if backend is not None:+ ports["backend"] = int(backend)+ if frontend is not None:+ ports["frontend"] = int(frontend)+ payload["ports"] = ports+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")++def _ensure_env_file(env_path: Path = ENV_PATH, template_path: Path = ENV_EXAMPLE_PATH) -> bool:if env_path.exists():return False@@ -753,6 +822,69 @@ def _send_dimensions_choice(current_value: str) -> str:)+def _install_profile_options() -> list[tuple[str, str, str]]:+ return [+ (+ "web-basic",+ _t("install_profile_web_label"),+ _t("install_profile_web_desc"),+ ),+ (+ "web-tutorbot",+ _t("install_profile_tutorbot_label"),+ _t("install_profile_tutorbot_desc"),+ ),+ (+ "web-matrix",+ _t("install_profile_matrix_label"),+ _t("install_profile_matrix_desc"),+ ),+ ]+++def _install_profile_label(profile: str) -> str:+ for value, label, _desc in _install_profile_options():+ if value == profile:+ return label+ return profile+++def _select_install_profile() -> str:+ profile = select(_t("install_profile_prompt"), _install_profile_options())+ log_info(_t("install_selected", profile=_install_profile_label(profile)))+ return profile+++def _select_math_animator() -> bool:+ log_info(dim(_t("install_math_animator_hint")))+ return confirm(_t("install_math_animator"), default=False)+++def _parse_version_tuple(version: str | None) -> tuple[int, int, int] | None:+ if not version:+ return None+ token = version.strip().split()[0].lstrip("v")+ parts: list[int] = []+ for raw_part in token.split(".")[:3]:+ digits = ""+ for char in raw_part:+ if char.isdigit():+ digits += char+ else:+ break+ if not digits:+ return None+ parts.append(int(digits))+ while len(parts) < 3:+ parts.append(0)+ return tuple(parts[:3])+++def _node_version_supported(version: str | None) -> bool:+ parsed = _parse_version_tuple(version)+ return parsed is None or parsed >= NODE_MIN_VERSION++# ---------------------------------------------------------------------------# Wizard steps# ---------------------------------------------------------------------------@@ -912,11 +1044,14 @@ def _install_dependencies() -> None:node_version = _detect_command_version("node")npm_version = _detect_command_version("npm")- if node_version and npm_version:+ if node_version and npm_version and _node_version_supported(node_version):log_success(_t("install_node_ok", version=node_version))log_success(_t("install_npm_ok", version=npm_version))else:- log_warn(_t("install_node_missing"))+ if node_version and not _node_version_supported(node_version):+ log_warn(_t("install_node_too_old", version=node_version))+ else:+ log_warn(_t("install_node_missing"))strategy = _node_strategy()hint_key = f"install_node_hint_{strategy}"if hint_key in MESSAGES[_LANG]:@@ -933,11 +1068,18 @@ def _install_dependencies() -> None:if not (node_version and npm_version):log_error(_t("install_node_abort"))raise SystemExit(1)+ if not _node_version_supported(node_version):+ log_error(_t("install_node_too_old", version=node_version))+ raise SystemExit(1)log_success(_t("install_node_ok", version=node_version))log_success(_t("install_npm_ok", version=npm_version))print()+ profile = _select_install_profile()+ include_math_animator = _select_math_animator()+ print()+if not confirm(_t("install_confirm"), default=True):log_warn(_t("install_skipped"))print()@@ -947,13 +1089,17 @@ def _install_dependencies() -> None:uv = _uv()- # --- uv pip install -r requirements/server.txt ---+ # --- uv pip install -r requirements/*.txt ---try:- _run_live(- [uv, "pip", "install", "-r", "requirements/server.txt", "--python", _PYTHON],- PROJECT_ROOT,- _t("install_backend"),- )+ for requirement in _requirements_for_install(+ profile,+ include_math_animator=include_math_animator,+ ):+ _run_live(+ [uv, "pip", "install", "-r", requirement, "--python", _PYTHON],+ PROJECT_ROOT,+ _t("install_requirement", requirement=requirement),+ )log_success(_t("install_backend_done"))except RuntimeError as exc:log_error(_t("install_failed", error=str(exc)))@@ -1159,6 +1305,7 @@ def _print_review(values: dict[str, str]) -> None:def _write_env(values: dict[str, str]) -> None:get_env_store().write(values)+ _save_launch_ports(values)def _tour_banner() -> None:diff --git a/scripts/start_web.py b/scripts/start_web.pyindex 0df7c8e06..d76b17ac2 100644--- a/scripts/start_web.py+++ b/scripts/start_web.py@@ -1,16 +1,24 @@#!/usr/bin/env python-"""DeepTutor Web Launcher — starts backend + frontend from the active .env."""+"""DeepTutor Web Launcher — starts backend + frontend from user settings."""from __future__ import annotations+import atexit+from dataclasses import dataclass+from datetime import datetime, timezone+import jsonimport osfrom pathlib import Pathimport shutilimport signal+import socketimport subprocessimport sysimport threadingimport time+from typing import Any, Callable+from urllib import error as urlerror+from urllib import request as urlrequestPROJECT_ROOT = Path(__file__).resolve().parent.parentif str(PROJECT_ROOT) not in sys.path:@@ -18,20 +26,106 @@ if str(PROJECT_ROOT) not in sys.path:def _load_runtime_deps():- from _cli_kit import accent, banner, bold, dim, log_error, log_info, log_success, warn+ from _cli_kit import banner, bold, dim, log_error, log_info, log_success, log_warn- from deeptutor.services.config import get_env_store+ from deeptutor.services.config.launch_settings import load_launch_settings- return accent, banner, bold, dim, log_error, log_info, log_success, warn, get_env_store+ return banner, bold, dim, log_error, log_info, log_success, log_warn, load_launch_settings-accent, banner, bold, dim, log_error, log_info, log_success, warn, get_env_store = (+banner, bold, dim, log_error, log_info, log_success, log_warn, load_launch_settings = (_load_runtime_deps())+STATE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "start_web_state.json"+BACKEND_READY_TIMEOUT = 60+FRONTEND_READY_TIMEOUT = 120+KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)++MESSAGES = {+ "en": {+ "backend": "Backend",+ "frontend": "Frontend",+ "config_source": "Config source: {source}",+ "npm_missing": "npm not found. Run `python scripts/start_tour.py` first.",+ "port_conflict": "{name} port {port} is already in use.",+ "port_owner": "owner: {command} (PID {pid})",+ "port_owner_unknown": "owner: unknown process",+ "port_hint": "Stop the existing process or run `python scripts/stop_web.py` if it is a stale DeepTutor launch.",+ "cleanup_previous": "Found a stale DeepTutor launch state; cleaning it up first ...",+ "starting_backend": "Starting backend ...",+ "starting_frontend": "Starting frontend ...",+ "waiting_backend": "Waiting for backend at {url} ...",+ "waiting_frontend": "Waiting for frontend at {url} ...",+ "ready_backend": "Backend is ready.",+ "ready_frontend": "Frontend is ready.",+ "ready_timeout": "{name} did not become ready within {seconds}s.",+ "process_exited": "{name} exited with code {code}.",+ "open_url": "Open {url} in your browser.",+ "shutdown_signal": "Received {signal}; shutting down ...",+ "shutdown": "Shutting down ...",+ "stopping": "Stopping {name} (PID {pid})",+ "state_missing": "No DeepTutor launcher state found.",+ "state_stopped": "Stopped recorded DeepTutor processes.",+ "state_invalid": "Ignoring unreadable launcher state.",+ },+ "zh": {+ "backend": "后端",+ "frontend": "前端",+ "config_source": "配置来源:{source}",+ "npm_missing": "未找到 npm。请先运行 `python scripts/start_tour.py`。",+ "port_conflict": "{name}端口 {port} 已被占用。",+ "port_owner": "占用进程:{command} (PID {pid})",+ "port_owner_unknown": "占用进程:未知",+ "port_hint": "请先停止已有进程;如果是上次 DeepTutor 异常退出残留,可运行 `python scripts/stop_web.py`。",+ "cleanup_previous": "发现上次 DeepTutor 启动状态,正在先清理残留进程 ...",+ "starting_backend": "正在启动后端 ...",+ "starting_frontend": "正在启动前端 ...",+ "waiting_backend": "正在等待后端就绪:{url} ...",+ "waiting_frontend": "正在等待前端就绪:{url} ...",+ "ready_backend": "后端已就绪。",+ "ready_frontend": "前端已就绪。",+ "ready_timeout": "{name}在 {seconds}s 内未就绪。",+ "process_exited": "{name}已退出,退出码 {code}。",+ "open_url": "请在浏览器中打开 {url}。",+ "shutdown_signal": "收到 {signal},正在关闭 ...",+ "shutdown": "正在关闭 ...",+ "stopping": "正在停止 {name} (PID {pid})",+ "state_missing": "未找到 DeepTutor 启动状态。",+ "state_stopped": "已停止记录中的 DeepTutor 进程。",+ "state_invalid": "启动状态文件不可读,已忽略。",+ },+}+++@dataclass(slots=True)+class ManagedProcess:+ name: str+ process: subprocess.Popen[str]+ pgid: int | None+++@dataclass(frozen=True, slots=True)+class PortOwner:+ command: str+ pid: int | None+++@dataclass(frozen=True, slots=True)+class PortConflict:+ name: str+ port: int+ owners: list[PortOwner]+++def _t(language: str, key: str, **kwargs: Any) -> str:+ catalog = MESSAGES.get(language, MESSAGES["en"])+ template = catalog.get(key, MESSAGES["en"][key])+ return template.format(**kwargs)+# ----------------------------------------------------------------------------# Process management (unchanged logic)+# Process and state management# ---------------------------------------------------------------------------@@ -41,27 +135,23 @@ def _stream_output(prefix: str, process: subprocess.Popen[str]) -> None:print(f" {dim(prefix)} {line.rstrip()}", flush=True)-def _terminate(process: subprocess.Popen[str] | None, name: str) -> None:- if process is None or process.poll() is not None:- return- log_info(f"Stopping {name} (PID {process.pid})")+def _get_pgid(pid: int | None) -> int | None:+ if pid is None or os.name == "nt":+ return Nonetry:- if os.name == "nt":- process.send_signal(signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined]- try:- process.wait(timeout=5)- return- except subprocess.TimeoutExpired:- process.kill()- else:- os.killpg(os.getpgid(process.pid), signal.SIGTERM)- try:- process.wait(timeout=5)- return- except subprocess.TimeoutExpired:- os.killpg(os.getpgid(process.pid), signal.SIGKILL)- except Exception:- process.kill()+ return os.getpgid(pid)+ except OSError:+ return None+++def _is_pid_alive(pid: int | None) -> bool:+ if pid is None:+ return False+ try:+ os.kill(pid, 0)+ except OSError:+ return False+ return Truedef _spawn(@@ -70,7 +160,7 @@ def _spawn(cwd: Path,env: dict[str, str],name: str,-) -> subprocess.Popen[str]:+) -> ManagedProcess:kwargs: dict[str, object] = {"cwd": str(cwd),"env": env,@@ -89,7 +179,313 @@ def _spawn(process = subprocess.Popen(command, **kwargs) # type: ignore[arg-type]thread = threading.Thread(target=_stream_output, args=(name, process), daemon=True)thread.start()- return process+ return ManagedProcess(name=name, process=process, pgid=_get_pgid(process.pid))+++def _send_tree_signal(pid: int | None, pgid: int | None, sig: int) -> None:+ if pid is None:+ return+ if os.name == "nt":+ # taskkill is the most reliable way to include npm/node child processes.+ cmd = ["taskkill", "/PID", str(pid), "/T"]+ if sig == KILL_SIGNAL:+ cmd.append("/F")+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)+ return+ if pgid is not None:+ os.killpg(pgid, sig)+ else:+ os.kill(pid, sig)+++def _terminate(process: ManagedProcess | None, language: str) -> None:+ if process is None:+ return++ pid = process.process.pid+ log_info(_t(language, "stopping", name=process.name, pid=pid))+ try:+ if os.name == "nt" and process.process.poll() is None:+ process.process.send_signal(signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined]+ else:+ _send_tree_signal(pid, process.pgid, signal.SIGTERM)+ except Exception:+ pass++ try:+ process.process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ try:+ _send_tree_signal(pid, process.pgid, KILL_SIGNAL)+ except Exception:+ try:+ process.process.kill()+ except Exception:+ pass+ except Exception:+ try:+ _send_tree_signal(pid, process.pgid, KILL_SIGNAL)+ except Exception:+ pass+++def _read_state(path: Path = STATE_PATH) -> dict[str, Any] | None:+ if not path.exists():+ return None+ try:+ loaded = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ return None+ return loaded if isinstance(loaded, dict) else None+++def _write_state(+ processes: list[ManagedProcess],+ *,+ backend_port: int,+ frontend_port: int,+ path: Path = STATE_PATH,+) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ state = {+ "version": 1,+ "created_at": datetime.now(timezone.utc).isoformat(),+ "backend_port": backend_port,+ "frontend_port": frontend_port,+ "processes": {+ item.name: {"pid": item.process.pid, "pgid": item.pgid} for item in processes+ },+ }+ tmp_path = path.with_suffix(".tmp")+ tmp_path.write_text(json.dumps(state, indent=2), encoding="utf-8")+ tmp_path.replace(path)+++def _remove_state(path: Path = STATE_PATH) -> None:+ try:+ path.unlink(missing_ok=True)+ except OSError:+ pass+++def _state_process_records(state: dict[str, Any]) -> list[tuple[int | None, int | None]]:+ processes = state.get("processes")+ if not isinstance(processes, dict):+ return []+ records: list[tuple[int | None, int | None]] = []+ for raw in processes.values():+ if not isinstance(raw, dict):+ continue+ pid = raw.get("pid")+ pgid = raw.get("pgid")+ records.append((pid if isinstance(pid, int) else None, pgid if isinstance(pgid, int) else None))+ return records+++def _terminate_state_processes(state: dict[str, Any]) -> None:+ seen: set[tuple[int | None, int | None]] = set()+ for pid, pgid in _state_process_records(state):+ key = (pid, pgid)+ if key in seen:+ continue+ seen.add(key)+ try:+ _send_tree_signal(pid, pgid, signal.SIGTERM)+ except Exception:+ pass+ time.sleep(1)+ for pid, pgid in seen:+ if _is_pid_alive(pid):+ try:+ _send_tree_signal(pid, pgid, KILL_SIGNAL)+ except Exception:+ pass+++def stop_recorded_processes(language: str | None = None) -> bool:+ settings = load_launch_settings(PROJECT_ROOT)+ lang = language or settings.language+ state = _read_state()+ if state is None:+ log_info(_t(lang, "state_missing"))+ return False+ _terminate_state_processes(state)+ _remove_state()+ log_success(_t(lang, "state_stopped"))+ return True+++# ---------------------------------------------------------------------------+# Port checks and readiness+# ---------------------------------------------------------------------------+++def _port_accepts_connection(port: int) -> bool:+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=0.25):+ return True+ except OSError:+ return False+++def _listening_owners(port: int) -> list[PortOwner]:+ lsof = shutil.which("lsof")+ if not lsof:+ return []+ try:+ result = subprocess.run(+ [lsof, "-n", "-P", f"-iTCP:{port}", "-sTCP:LISTEN"],+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=2,+ check=False,+ )+ except Exception:+ return []+ owners: list[PortOwner] = []+ for line in result.stdout.splitlines()[1:]:+ parts = line.split()+ if len(parts) < 2:+ continue+ try:+ pid = int(parts[1])+ except ValueError:+ pid = None+ owners.append(PortOwner(command=parts[0], pid=pid))+ return owners+++def _collect_port_conflicts(ports: dict[str, int]) -> list[PortConflict]:+ conflicts: list[PortConflict] = []+ for name, port in ports.items():+ owners = _listening_owners(port)+ if owners or _port_accepts_connection(port):+ conflicts.append(PortConflict(name=name, port=port, owners=owners))+ return conflicts+++def _conflicts_match_state(conflicts: list[PortConflict], state: dict[str, Any]) -> bool:+ records = _state_process_records(state)+ state_pids = {pid for pid, _pgid in records if pid is not None}+ state_pgids = {pgid for _pid, pgid in records if pgid is not None}+ if not state_pids and not state_pgids:+ return False+ for conflict in conflicts:+ for owner in conflict.owners:+ if owner.pid in state_pids:+ return True+ owner_pgid = _get_pgid(owner.pid)+ if owner_pgid is not None and owner_pgid in state_pgids:+ return True+ return False+++def _state_has_live_process(state: dict[str, Any]) -> bool:+ return any(_is_pid_alive(pid) for pid, _pgid in _state_process_records(state))+++def _cleanup_previous_launch_if_safe(ports: dict[str, int], language: str) -> None:+ state = _read_state()+ if state is None:+ return++ state_ports = {+ "backend": state.get("backend_port"),+ "frontend": state.get("frontend_port"),+ }+ conflicts = _collect_port_conflicts(ports)+ ports_match_state = all(state_ports.get(name) == port for name, port in ports.items())+ if conflicts and (+ _conflicts_match_state(conflicts, state)+ or (ports_match_state and _state_has_live_process(state))+ ):+ log_warn(_t(language, "cleanup_previous"))+ _terminate_state_processes(state)+ _remove_state()+ return+ if not conflicts and _state_has_live_process(state):+ log_warn(_t(language, "cleanup_previous"))+ _terminate_state_processes(state)+ _remove_state()+ return+ if not conflicts and not _state_has_live_process(state):+ _remove_state()+++def _ensure_ports_available(backend_port: int, frontend_port: int, language: str) -> None:+ ports = {+ _t(language, "backend"): backend_port,+ _t(language, "frontend"): frontend_port,+ }+ state_ports = {"backend": backend_port, "frontend": frontend_port}+ _cleanup_previous_launch_if_safe(state_ports, language)++ conflicts = _collect_port_conflicts(ports)+ if not conflicts:+ return+ for conflict in conflicts:+ log_error(_t(language, "port_conflict", name=conflict.name, port=conflict.port))+ if conflict.owners:+ for owner in conflict.owners:+ log_info(_t(language, "port_owner", command=owner.command, pid=owner.pid))+ else:+ log_info(_t(language, "port_owner_unknown"))+ log_info(_t(language, "port_hint"))+ raise SystemExit(1)+++def _wait_for_http(+ *,+ name: str,+ url: str,+ process: ManagedProcess,+ timeout: int,+ language: str,+ waiting_key: str,+ ready_key: str,+ should_stop: Callable[[], bool] | None = None,+) -> None:+ log_info(_t(language, waiting_key, url=url))+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if should_stop is not None and should_stop():+ raise SystemExit(0)+ if process.process.poll() is not None:+ log_error(+ _t(language, "process_exited", name=name, code=process.process.returncode)+ )+ raise SystemExit(1)+ try:+ with urlrequest.urlopen(url, timeout=1):+ log_success(_t(language, ready_key))+ return+ except urlerror.HTTPError as exc:+ if exc.code < 500:+ log_success(_t(language, ready_key))+ return+ except (OSError, urlerror.URLError, TimeoutError):+ pass+ time.sleep(0.5)+ log_error(_t(language, "ready_timeout", name=name, seconds=timeout))+ raise SystemExit(1)+++def _install_signal_handlers(request_shutdown: Callable[[str], None]) -> None:+ def _handler(signum: int, _frame: object) -> None:+ signal_name = signal.Signals(signum).name+ request_shutdown(signal_name)++ for sig_name in ("SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"):+ sig = getattr(signal, sig_name, None)+ if sig is None:+ continue+ try:+ signal.signal(sig, _handler)+ except (OSError, ValueError):+ continue# ---------------------------------------------------------------------------@@ -98,23 +494,26 @@ def _spawn(def main() -> None:- summary = get_env_store().as_summary()- backend_port = summary.backend_port- frontend_port = summary.frontend_port+ settings = load_launch_settings(PROJECT_ROOT)+ language = settings.language+ backend_port = settings.backend_port+ frontend_port = settings.frontend_portnpm = shutil.which("npm")if not npm:- log_error("npm not found. Run `python scripts/start_tour.py` first.")+ log_error(_t(language, "npm_missing"))raise SystemExit(1)- # Bannerbanner("DeepTutor",[- f"Backend http://localhost:{backend_port}",- f"Frontend http://localhost:{frontend_port}",+ f"{_t(language, 'backend')} http://localhost:{backend_port}",+ f"{_t(language, 'frontend')} http://localhost:{frontend_port}",],)+ log_info(_t(language, "config_source", source=settings.source))++ _ensure_ports_available(backend_port, frontend_port, language)api_base = f"http://localhost:{backend_port}"@@ -122,47 +521,115 @@ def main() -> None:# even when started independently (e.g. `npm run dev` without this launcher).env_local_path = PROJECT_ROOT / "web" / ".env.local"env_local_path.write_text(- f"# Auto-generated by start_web.py — do not edit manually\n"+ f"# Auto-generated by start_web.py - do not edit manually\n"f"NEXT_PUBLIC_API_BASE={api_base}\n",encoding="utf-8",)backend_env = os.environ.copy()+ backend_env["BACKEND_PORT"] = str(backend_port)+ backend_env["FRONTEND_PORT"] = str(frontend_port)backend_env["PYTHONUNBUFFERED"] = "1"backend_env["PYTHONIOENCODING"] = "utf-8:replace"frontend_env = os.environ.copy()+ frontend_env["BACKEND_PORT"] = str(backend_port)+ frontend_env["FRONTEND_PORT"] = str(frontend_port)frontend_env["NEXT_PUBLIC_API_BASE"] = api_basefrontend_env["PYTHONIOENCODING"] = "utf-8:replace"backend_cmd = [sys.executable, "-m", "deeptutor.api.run_server"]frontend_cmd = [npm, "run", "dev", "--", "--port", str(frontend_port)]- log_info("Starting backend ...")- backend = _spawn(backend_cmd, cwd=PROJECT_ROOT, env=backend_env, name="backend")- time.sleep(1.5)-- log_info("Starting frontend ...")- frontend = _spawn(frontend_cmd, cwd=PROJECT_ROOT / "web", env=frontend_env, name="frontend")-- log_success(f"Open {bold(f'http://localhost:{frontend_port}')} in your browser.")- print()+ processes: list[ManagedProcess] = []+ frontend: ManagedProcess | None = None+ backend: ManagedProcess | None = None+ shutdown_requested = False+ cleanup_started = False+ exit_code = 0++ def request_shutdown(signal_name: str | None = None) -> None:+ nonlocal shutdown_requested+ if shutdown_requested:+ return+ shutdown_requested = True+ if signal_name:+ print()+ log_info(_t(language, "shutdown_signal", signal=signal_name))++ def cleanup() -> None:+ nonlocal cleanup_started+ if cleanup_started:+ return+ cleanup_started = True+ _terminate(frontend, language)+ _terminate(backend, language)+ _remove_state()++ _install_signal_handlers(request_shutdown)+ atexit.register(cleanup)try:- while True:- if backend.poll() is not None:- log_error(f"Backend exited with code {backend.returncode}")- raise SystemExit(1)- if frontend.poll() is not None:- log_error(f"Frontend exited with code {frontend.returncode}")- raise SystemExit(1)+ log_info(_t(language, "starting_backend"))+ backend = _spawn(backend_cmd, cwd=PROJECT_ROOT, env=backend_env, name="backend")+ processes.append(backend)+ _write_state(processes, backend_port=backend_port, frontend_port=frontend_port)+ _wait_for_http(+ name=_t(language, "backend"),+ url=f"http://127.0.0.1:{backend_port}/",+ process=backend,+ timeout=BACKEND_READY_TIMEOUT,+ language=language,+ waiting_key="waiting_backend",+ ready_key="ready_backend",+ should_stop=lambda: shutdown_requested,+ )++ log_info(_t(language, "starting_frontend"))+ frontend = _spawn(frontend_cmd, cwd=PROJECT_ROOT / "web", env=frontend_env, name="frontend")+ processes.append(frontend)+ _write_state(processes, backend_port=backend_port, frontend_port=frontend_port)+ _wait_for_http(+ name=_t(language, "frontend"),+ url=f"http://127.0.0.1:{frontend_port}/",+ process=frontend,+ timeout=FRONTEND_READY_TIMEOUT,+ language=language,+ waiting_key="waiting_frontend",+ ready_key="ready_frontend",+ should_stop=lambda: shutdown_requested,+ )++ log_success(_t(language, "open_url", url=bold(f"http://localhost:{frontend_port}")))+ print()++ while not shutdown_requested:+ if backend.process.poll() is not None:+ log_error(+ _t(language, "process_exited", name=backend.name, code=backend.process.returncode)+ )+ exit_code = 1+ break+ if frontend.process.poll() is not None:+ log_error(+ _t(+ language,+ "process_exited",+ name=frontend.name,+ code=frontend.process.returncode,+ )+ )+ exit_code = 1+ breaktime.sleep(1)except KeyboardInterrupt:print()- log_info("Shutting down ...")+ log_info(_t(language, "shutdown"))finally:- _terminate(frontend, "frontend")- _terminate(backend, "backend")+ cleanup()++ if exit_code:+ raise SystemExit(exit_code)if __name__ == "__main__":diff --git a/scripts/stop_web.py b/scripts/stop_web.pynew file mode 100644index 000000000..095ae06ce--- /dev/null+++ b/scripts/stop_web.py@@ -0,0 +1,24 @@+#!/usr/bin/env python+"""Stop processes recorded by scripts/start_web.py."""++from __future__ import annotations++from pathlib import Path+import sys++PROJECT_ROOT = Path(__file__).resolve().parent.parent+SCRIPTS_DIR = PROJECT_ROOT / "scripts"+if str(SCRIPTS_DIR) not in sys.path:+ sys.path.insert(0, str(SCRIPTS_DIR))+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++from start_web import stop_recorded_processes # noqa: E402+++def main() -> None:+ stop_recorded_processes()+++if __name__ == "__main__":+ main()diff --git a/tests/agents/chat/test_agentic_parallel_tools.py b/tests/agents/chat/test_agentic_parallel_tools.pyindex 85a0d430b..76516fc6a 100644--- a/tests/agents/chat/test_agentic_parallel_tools.py+++ b/tests/agents/chat/test_agentic_parallel_tools.py@@ -357,7 +357,7 @@ def test_chat_messages_tell_llm_to_call_rag_without_kb_name() -> None:)system_content = messages[0]["content"]- assert "call RAG with only a query" in system_content+ assert "call RAG with only a non-empty query" in system_contentassert "currently selected knowledge base" in system_contentassert "new-kb" not in system_content@@ -390,7 +390,7 @@ def test_chat_rag_schema_exposes_only_query_to_llm() -> None:[schema] = pipeline._build_llm_tool_schemas(["rag"])parameters = schema["function"]["parameters"]- assert parameters["properties"] == {"query": {"type": "string"}}+ assert parameters["properties"] == {"query": {"type": "string", "minLength": 1}}assert parameters["required"] == ["query"]assert parameters["additionalProperties"] is False@@ -515,6 +515,105 @@ async def test_native_rag_call_uses_system_selected_kb_not_llm_args(assert tool_call_events[0].content+async def test_native_rag_call_falls_back_to_user_message_when_query_is_empty(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",+ lambda: SimpleNamespace(+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None+ ),+ )++ class FakeRegistry:+ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []++ def build_openai_schemas(self, _enabled_tools):+ return [+ {+ "type": "function",+ "function": {+ "name": "rag",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ },+ }+ ]++ def build_prompt_text(self, enabled_tools, **_kwargs):+ return "\n".join(enabled_tools)++ async def execute(self, name: str, **kwargs):+ self.calls.append({"name": name, **kwargs})+ return ToolResult(content="grounded result", metadata={}, success=True)++ registry = FakeRegistry()+ monkeypatch.setattr(+ "deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry+ )++ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry++ async def fake_create(**_kwargs):+ return SimpleNamespace(+ choices=[+ SimpleNamespace(+ message=SimpleNamespace(+ content="",+ tool_calls=[+ SimpleNamespace(+ id="tool-call-rag",+ function=SimpleNamespace(name="rag", arguments="{}"),+ )+ ],+ )+ )+ ]+ )++ monkeypatch.setattr(+ pipeline,+ "_build_openai_client",+ lambda: SimpleNamespace(+ chat=SimpleNamespace(completions=SimpleNamespace(create=fake_create)),+ ),+ )++ bus = StreamBus()+ events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="session-1",+ user_message="Summarize chapter 3 from the selected knowledge base.",+ enabled_tools=["rag"],+ knowledge_bases=["current-kb"],+ language="en",+ )++ traces = await pipeline._run_native_tool_loop(+ context=context,+ enabled_tools=["rag"],+ thinking_text="RAG would help.",+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ expected_query = "Summarize chapter 3 from the selected knowledge base."+ assert registry.calls[0]["query"] == expected_query+ assert registry.calls[0]["kb_name"] == "current-kb"+ assert traces[0].arguments == {"query": expected_query}++ tool_call_events = [event for event in events if event.type == StreamEventType.TOOL_CALL]+ assert tool_call_events[0].metadata.get("args", {}) == {"query": expected_query}++@pytest.mark.asyncioasync def test_native_tool_loop_caps_parallel_tool_calls_at_eight(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/core/test_builtin_tools.py b/tests/core/test_builtin_tools.pyindex 86f3bae70..0e2725023 100644--- a/tests/core/test_builtin_tools.py+++ b/tests/core/test_builtin_tools.py@@ -93,6 +93,23 @@ async def test_rag_tool_forwards_query_and_extra_kwargs(monkeypatch: pytest.Monkassert captured["only_need_context"] is True+async def test_rag_tool_rejects_empty_query(monkeypatch: pytest.MonkeyPatch) -> None:+ called = False++ async def fake_rag_search(**_kwargs: Any) -> dict[str, Any]:+ nonlocal called+ called = True+ return {"answer": "should not run"}++ _install_module(monkeypatch, "deeptutor.tools.rag_tool", rag_search=fake_rag_search)++ with pytest.raises(ValueError, match="RAG query must be a non-empty string"):+ await RAGTool().execute(query=" ", kb_name="demo-kb")++ assert called is False++@pytest.mark.asyncioasync def test_web_search_tool_wraps_sync_function(monkeypatch: pytest.MonkeyPatch) -> None:captured: dict[str, Any] = {}diff --git a/tests/scripts/test_start_tour.py b/tests/scripts/test_start_tour.pyindex c803a1ab2..c3a0b4eef 100644--- a/tests/scripts/test_start_tour.py+++ b/tests/scripts/test_start_tour.py@@ -144,6 +144,37 @@ class TestResolvePython:f"Expected resolved python {python_used!r}, got {cmd[0]!r}")+ def test_install_commands_support_web_addon_profiles(self) -> None:+ start_tour = _load_start_tour_module()+ catalog: dict = {"services": {}}++ tutorbot_cmds = start_tour._install_commands("web-tutorbot", catalog)+ matrix_cmds = start_tour._install_commands("web-matrix", catalog)++ assert any("requirements/tutorbot.txt" in cmd for cmd, _cwd in tutorbot_cmds)+ assert any(cmd[0].startswith("npm") or cmd[0].endswith("npm") for cmd, _cwd in tutorbot_cmds)+ assert any("requirements/matrix.txt" in cmd for cmd, _cwd in matrix_cmds)++ def test_requirements_for_install_can_include_math_animator(self) -> None:+ start_tour = _load_start_tour_module()++ requirements = start_tour._requirements_for_install(+ "web-tutorbot",+ include_math_animator=True,+ )++ assert requirements == [+ "requirements/tutorbot.txt",+ "requirements/math-animator.txt",+ ]++ def test_node_version_requires_next_compatible_runtime(self) -> None:+ start_tour = _load_start_tour_module()++ assert start_tour._node_version_supported("v20.9.0")+ assert start_tour._node_version_supported("v22.1.0")+ assert not start_tour._node_version_supported("v18.20.0")+def test_ensure_env_file_copies_template_when_missing(tmp_path: Path) -> None:start_tour = _load_start_tour_module()@@ -169,6 +200,26 @@ def test_save_ui_language_preserves_existing_theme(tmp_path: Path) -> None:assert '"language": "zh"' in saved+def test_save_launch_ports_preserves_existing_env_settings(tmp_path: Path) -> None:+ start_tour = _load_start_tour_module()+ settings_path = tmp_path / "env.json"+ settings_path.write_text(+ '{"version":1,"profile":"web-basic","llm":{"binding":"openai"}}',+ encoding="utf-8",+ )++ start_tour._save_launch_ports(+ {"BACKEND_PORT": "9101", "FRONTEND_PORT": "4200"},+ path=settings_path,+ )++ saved = settings_path.read_text(encoding="utf-8")+ assert '"profile": "web-basic"' in saved+ assert '"binding": "openai"' in saved+ assert '"backend": 9101' in saved+ assert '"frontend": 4200' in saved++def test_embedding_model_suggestions_include_gemini() -> None:start_tour = _load_start_tour_module()assert start_tour.EMBEDDING_MODEL_SUGGESTIONS["gemini"] == "gemini-embedding-001"diff --git a/tests/scripts/test_start_web.py b/tests/scripts/test_start_web.pynew file mode 100644index 000000000..0bd78b414--- /dev/null+++ b/tests/scripts/test_start_web.py@@ -0,0 +1,65 @@+from __future__ import annotations++import importlib.util+from pathlib import Path+import sys+import types+++def _load_start_web_module():+ project_root = Path(__file__).resolve().parents[2]+ scripts_dir = project_root / "scripts"+ module_path = scripts_dir / "start_web.py"+ sys.path.insert(0, str(scripts_dir))+ try:+ spec = importlib.util.spec_from_file_location("start_web_under_test", module_path)+ assert spec and spec.loader+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+ finally:+ sys.modules.pop("start_web_under_test", None)+ try:+ sys.path.remove(str(scripts_dir))+ except ValueError:+ pass+++def test_start_web_translation_uses_interface_language() -> None:+ start_web = _load_start_web_module()++ assert start_web._t("zh", "backend") == "后端"+ assert start_web._t("en", "frontend") == "Frontend"+++def test_state_round_trip(tmp_path: Path) -> None:+ start_web = _load_start_web_module()+ state_path = tmp_path / "start_web_state.json"+ fake_process = types.SimpleNamespace(pid=12345)+ managed = start_web.ManagedProcess(name="backend", process=fake_process, pgid=67890)++ start_web._write_state(+ [managed],+ backend_port=8101,+ frontend_port=4100,+ path=state_path,+ )++ state = start_web._read_state(state_path)+ assert state["backend_port"] == 8101+ assert state["frontend_port"] == 4100+ assert state["processes"]["backend"]["pid"] == 12345+ assert state["processes"]["backend"]["pgid"] == 67890+++def test_conflict_matches_recorded_state_by_pid() -> None:+ start_web = _load_start_web_module()+ state = {"processes": {"backend": {"pid": 12345, "pgid": None}}}+ conflict = start_web.PortConflict(+ name="Backend",+ port=8101,+ owners=[start_web.PortOwner(command="python", pid=12345)],+ )++ assert start_web._conflicts_match_state([conflict], state) is Truediff --git a/tests/services/config/test_embedding_runtime.py b/tests/services/config/test_embedding_runtime.pyindex 4a6a7242f..0f25f60d8 100644--- a/tests/services/config/test_embedding_runtime.py+++ b/tests/services/config/test_embedding_runtime.py@@ -175,7 +175,29 @@ def test_embedding_local_fallback_from_base_url(tmp_path: Path) -> None:resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))assert resolved.provider_name == "ollama"assert resolved.provider_mode == "local"- assert resolved.api_key == "sk-no-key-required"+ assert resolved.api_key == ""+++def test_embedding_local_vllm_keeps_explicit_env_key(tmp_path: Path) -> None:+ catalog = _build_catalog(+ embedding_profile={+ "id": "embedding-p",+ "name": "Embedding",+ "binding": "vllm",+ "base_url": "http://localhost:1234/v1/embeddings",+ "api_key": "",+ "api_version": "",+ "extra_headers": {},+ "models": [{"id": "embedding-m", "name": "m", "model": "text-embedding-model"}],+ }+ )+ resolved = resolve_embedding_runtime_config(+ catalog=catalog,+ env_store=_env(tmp_path, ["HOSTED_VLLM_API_KEY=local-secret"]),+ )+ assert resolved.provider_name == "vllm"+ assert resolved.provider_mode == "local"+ assert resolved.api_key == "local-secret"def test_embedding_openai_default_base_injected(tmp_path: Path) -> None:diff --git a/tests/services/config/test_launch_settings.py b/tests/services/config/test_launch_settings.pynew file mode 100644index 000000000..c421e2526--- /dev/null+++ b/tests/services/config/test_launch_settings.py@@ -0,0 +1,79 @@+from __future__ import annotations++import json+from pathlib import Path++from deeptutor.services.config.launch_settings import load_launch_settings+++def _settings_dir(root: Path) -> Path:+ path = root / "data" / "user" / "settings"+ path.mkdir(parents=True, exist_ok=True)+ return path+++def test_launch_settings_prefer_runtime_settings(monkeypatch, tmp_path: Path) -> None:+ for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):+ monkeypatch.delenv(key, raising=False)++ (tmp_path / ".env").write_text(+ "BACKEND_PORT=9001\nFRONTEND_PORT=4000\nUI_LANGUAGE=en\n",+ encoding="utf-8",+ )+ settings_dir = _settings_dir(tmp_path)+ (settings_dir / "env.json").write_text(+ json.dumps({"ports": {"backend": 8101, "frontend": 4100}}),+ encoding="utf-8",+ )+ (settings_dir / "interface.json").write_text(+ json.dumps({"language": "zh"}),+ encoding="utf-8",+ )++ settings = load_launch_settings(tmp_path)++ assert settings.backend_port == 8101+ assert settings.frontend_port == 4100+ assert settings.language == "zh"+ assert "env.json" in settings.source+ assert "interface.json" in settings.source+++def test_launch_settings_fall_back_to_env_when_settings_missing(+ monkeypatch, tmp_path: Path+) -> None:+ for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):+ monkeypatch.delenv(key, raising=False)++ (tmp_path / ".env").write_text(+ "BACKEND_PORT=9101\nFRONTEND_PORT=4200\nUI_LANGUAGE=zh\n",+ encoding="utf-8",+ )++ settings = load_launch_settings(tmp_path)++ assert settings.backend_port == 9101+ assert settings.frontend_port == 4200+ assert settings.source == ".env"+ assert settings.language == "zh"+ assert settings.source == ".env"+++def test_launch_settings_fall_back_per_invalid_port(monkeypatch, tmp_path: Path) -> None:+ for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):+ monkeypatch.delenv(key, raising=False)++ (tmp_path / ".env").write_text(+ "BACKEND_PORT=9101\nFRONTEND_PORT=4200\n",+ encoding="utf-8",+ )+ settings_dir = _settings_dir(tmp_path)+ (settings_dir / "env.json").write_text(+ json.dumps({"ports": {"backend": "not-a-port", "frontend": 70000}}),+ encoding="utf-8",+ )++ settings = load_launch_settings(tmp_path)++ assert settings.backend_port == 9101+ assert settings.frontend_port == 4200diff --git a/tests/services/embedding/test_url_transparency.py b/tests/services/embedding/test_url_transparency.pyindex 4c6dacb8d..85e1ec570 100644--- a/tests/services/embedding/test_url_transparency.py+++ b/tests/services/embedding/test_url_transparency.py@@ -35,6 +35,7 @@ def _capture_url(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:async def fake_post(self: httpx.AsyncClient, url: str, **kwargs: Any) -> httpx.Response:captured["url"] = urlcaptured["json"] = kwargs.get("json")+ captured["headers"] = kwargs.get("headers")request = httpx.Request("POST", url)# Different adapters expect different response shapes.return httpx.Response(@@ -78,6 +79,45 @@ async def test_openai_compat_url_verbatim(monkeypatch: pytest.MonkeyPatch) -> Noassert captured["url"] == CUSTOM_URL+async def test_openai_compat_forwards_real_authorization_header(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured = _capture_url(monkeypatch)+ adapter = OpenAICompatibleEmbeddingAdapter(+ {+ "api_key": "sk-real",+ "base_url": CUSTOM_URL,+ "model": "test-model",+ "dimensions": 0,+ "send_dimensions": False,+ "request_timeout": 5,+ }+ )+ await adapter.embed(EmbeddingRequest(texts=["hello"], model="test-model"))+ assert captured["headers"]["Authorization"] == "Bearer sk-real"+++async def test_openai_compat_suppresses_no_key_placeholder_header(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured = _capture_url(monkeypatch)+ adapter = OpenAICompatibleEmbeddingAdapter(+ {+ "api_key": "sk-no-key-required",+ "base_url": CUSTOM_URL,+ "model": "test-model",+ "dimensions": 0,+ "send_dimensions": False,+ "request_timeout": 5,+ }+ )+ await adapter.embed(EmbeddingRequest(texts=["hello"], model="test-model"))+ assert "Authorization" not in captured["headers"]+ assert "api-key" not in captured["headers"]++@pytest.mark.asyncioasync def test_jina_url_verbatim(monkeypatch: pytest.MonkeyPatch) -> None:captured = _capture_url(monkeypatch)diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsxindex 202da7739..de9779c3f 100644--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@ -201,11 +201,19 @@ function defaultCatalog(): Catalog {};}+const fieldControlClass =+ "w-full rounded-lg border border-[var(--border)] px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)]";+const inputClass =- "w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40";+ `${fieldControlClass} bg-transparent placeholder:text-[var(--muted-foreground)]/40`;++const nativeSelectClass =+ `${fieldControlClass} bg-[var(--background)] cursor-pointer disabled:cursor-not-allowed disabled:opacity-60`;const selectClass =- "w-full appearance-none rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] cursor-pointer";+ `${nativeSelectClass} appearance-none`;++const selectOptionClass = "bg-[var(--background)] text-[var(--foreground)]";function stringifyExtraHeaders(value: CatalogProfile["extra_headers"]): string {if (!value) return "";@@ -309,11 +317,11 @@ function SpotlightOverlay({useEffect(() => {if (!guideStep) return;- const el = document.querySelector(`[data-tour="${guideStep.target}"]`);- if (el) {- const r = el.getBoundingClientRect();- setRect(r);- }+ const frame = window.requestAnimationFrame(() => {+ const el = document.querySelector(`[data-tour="${guideStep.target}"]`);+ setRect(el ? el.getBoundingClientRect() : null);+ });+ return () => window.cancelAnimationFrame(frame);}, [guideStep]);if (!guideStep || !rect) return null;@@ -489,20 +497,26 @@ function DimensionField({<div className="space-y-1.5">{useDropdown && !customMode ? (<select- className={inputClass}+ className={nativeSelectClass}value={dropdownValue}onChange={(e) => handleSelect(e.target.value)}disabled={disabled}>- <option value={AUTO_DIM_SENTINEL}>+ <option className={selectOptionClass} value={AUTO_DIM_SENTINEL}>{t("Auto (probe on next test)")}</option>{supported.map((dim) => (- <option key={dim} value={String(dim)}>+ <option+ className={selectOptionClass}+ key={dim}+ value={String(dim)}+ >{dim}</option>))}- <option value={CUSTOM_DIM_SENTINEL}>{t("Custom…")}</option>+ <option className={selectOptionClass} value={CUSTOM_DIM_SENTINEL}>+ {t("Custom…")}+ </option></select>) : (<input@@ -1125,7 +1139,9 @@ function SettingsPageContent() {false,)}`}/>- <span className={`${labelClass("md")} text-[var(--muted-foreground)]`}>+ <span+ className={`${labelClass("md")} text-[var(--muted-foreground)]`}+ >{t("Backend")}</span></div>@@ -1405,9 +1421,15 @@ function SettingsPageContent() {}}}>- <option value="">{t("Select provider...")}</option>+ <option className={selectOptionClass} value="">+ {t("Select provider...")}+ </option>{(providers[activeService] || []).map((p) => (- <option key={p.value} value={p.value}>+ <option+ className={selectOptionClass}+ key={p.value}+ value={p.value}+ >{p.label}</option>))}diff --git a/web/components/chat/BookReferencePicker.tsx b/web/components/chat/BookReferencePicker.tsxindex e298a382f..c934e727f 100644--- a/web/components/chat/BookReferencePicker.tsx+++ b/web/components/chat/BookReferencePicker.tsx@@ -149,18 +149,30 @@ export default function BookReferencePicker({}if (existing) {return prev.map((ref) =>- ref.bookId === book.id ? { ...ref, pages: [...ref.pages, nextPage] } : ref,+ ref.bookId === book.id+ ? { ...ref, pages: [...ref.pages, nextPage] }+ : ref,);}return [...prev,- { bookId: book.id, bookTitle: book.title || t("Untitled book"), pages: [nextPage] },+ {+ bookId: book.id,+ bookTitle: book.title || t("Untitled book"),+ pages: [nextPage],+ },];});};- const toggleChapter = (book: Book, chapter: Chapter | null, pages: Page[]) => {- const allSelected = pages.every((page) => selectedKeys.has(pageKey(book.id, page.id)));+ const toggleChapter = (+ book: Book,+ chapter: Chapter | null,+ pages: Page[],+ ) => {+ const allSelected = pages.every((page) =>+ selectedKeys.has(pageKey(book.id, page.id)),+ );setSelected((prev) => {const existing = prev.find((ref) => ref.bookId === book.id);const existingPages = existing?.pages || [];@@ -170,14 +182,17 @@ export default function BookReferencePicker({: [...existingPages,...pages- .filter((page) => !existingPages.some((p) => p.pageId === page.id))+ .filter(+ (page) => !existingPages.some((p) => p.pageId === page.id),+ ).map((page) => ({bookId: book.id,bookTitle: book.title || t("Untitled book"),pageId: page.id,pageTitle: page.title || t("Untitled chapter"),chapterId: chapter?.id || page.chapter_id,- chapterTitle: chapter?.title || page.title || t("Untitled chapter"),+ chapterTitle:+ chapter?.title || page.title || t("Untitled chapter"),})),];const nextRef = {@@ -190,7 +205,10 @@ export default function BookReferencePicker({});};- const selectedCount = selected.reduce((total, ref) => total + ref.pages.length, 0);+ const selectedCount = selected.reduce(+ (total, ref) => total + ref.pages.length,+ 0,+ );if (!open) return null;@@ -240,13 +258,16 @@ export default function BookReferencePicker({{filteredBooks.map((book) => {const active = book.id === activeBookId;const selectedPages =- selected.find((ref) => ref.bookId === book.id)?.pages.length || 0;+ selected.find((ref) => ref.bookId === book.id)?.pages+ .length || 0;return (<buttonkey={book.id}onClick={() => setActiveBookId(book.id)}className={`flex w-full items-center gap-3 px-3 py-3 text-left transition-colors ${- active ? "bg-[var(--primary)]/8" : "hover:bg-[var(--muted)]/40"+ active+ ? "bg-[var(--primary)]/8"+ : "hover:bg-[var(--muted)]/40"}`}><BookOpen className="h-4 w-4 shrink-0 text-[var(--muted-foreground)]" />@@ -309,7 +330,9 @@ export default function BookReferencePicker({className="overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--background)]/35"><button- onClick={() => toggleChapter(activeBook, chapter, pages)}+ onClick={() =>+ toggleChapter(activeBook, chapter, pages)+ }className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-[var(--muted)]/35 ${showPageRows ? "border-b border-[var(--border)]" : ""}`}@@ -326,12 +349,15 @@ export default function BookReferencePicker({<Layers3 className="mt-0.5 h-4 w-4 shrink-0 text-[var(--muted-foreground)]" /><span className="min-w-0 flex-1"><span className="block truncate text-[13px] font-medium text-[var(--foreground)]">- {chapter?.title || firstPage?.title || t("Unassigned pages")}+ {chapter?.title ||+ firstPage?.title ||+ t("Unassigned pages")}</span><span className="text-[11px] text-[var(--muted-foreground)]">{pages.length} {t("pages")}</span>- {!showPageRows && firstPage?.learning_objectives?.length ? (+ {!showPageRows &&+ firstPage?.learning_objectives?.length ? (<span className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">{firstPage.learning_objectives.join("; ")}</span>@@ -340,38 +366,44 @@ export default function BookReferencePicker({</button>{showPageRows && (<div className="divide-y divide-[var(--border)]">- {pages.map((page) => {- const checked = selectedKeys.has(pageKey(activeBook.id, page.id));- return (- <button- key={page.id}- onClick={() => togglePage(activeBook, page, chapter)}- className={`flex w-full items-start gap-3 px-5 py-3 text-left transition-colors ${- checked ? "bg-[var(--primary)]/8" : "hover:bg-[var(--muted)]/30"- }`}- >- <span- className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${+ {pages.map((page) => {+ const checked = selectedKeys.has(+ pageKey(activeBook.id, page.id),+ );+ return (+ <button+ key={page.id}+ onClick={() =>+ togglePage(activeBook, page, chapter)+ }+ className={`flex w-full items-start gap-3 px-5 py-3 text-left transition-colors ${checked- ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"- : "border-[var(--border)] text-transparent"+ ? "bg-[var(--primary)]/8"+ : "hover:bg-[var(--muted)]/30"}`}>- <Check size={12} />- </span>- <span className="min-w-0 flex-1">- <span className="block text-[13px] font-medium text-[var(--foreground)]">- {page.title || t("Untitled chapter")}+ <span+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${+ checked+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"+ : "border-[var(--border)] text-transparent"+ }`}+ >+ <Check size={12} /></span>- {page.learning_objectives?.length ? (- <span className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">- {page.learning_objectives.join("; ")}+ <span className="min-w-0 flex-1">+ <span className="block text-[13px] font-medium text-[var(--foreground)]">+ {page.title || t("Untitled chapter")}</span>- ) : null}- </span>- </button>- );- })}+ {page.learning_objectives?.length ? (+ <span className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">+ {page.learning_objectives.join("; ")}+ </span>+ ) : null}+ </span>+ </button>+ );+ })}</div>)}</div>diff --git a/web/lib/book-references.ts b/web/lib/book-references.tsindex 1b6e18874..70c1e3cdd 100644--- a/web/lib/book-references.ts+++ b/web/lib/book-references.ts@@ -26,9 +26,9 @@ export function selectedBooksToPayload(return refs.map((ref) => ({book_id: ref.bookId,- page_ids: Array.from(new Set(ref.pages.map((page) => page.pageId))).filter(- Boolean,- ),+ page_ids: Array.from(+ new Set(ref.pages.map((page) => page.pageId)),+ ).filter(Boolean),})).filter((ref) => ref.book_id && ref.page_ids.length > 0);}@@ -37,22 +37,23 @@ export function countSelectedBookPages(refs: SelectedBookReference[]): number {return refs.reduce((total, ref) => total + ref.pages.length, 0);}-export function normalizeBookReferences(value: unknown): BookReferencePayload[] {+export function normalizeBookReferences(+ value: unknown,+): BookReferencePayload[] {if (!Array.isArray(value)) return [];return value.map((item) => {const record: Record<string, unknown> =- item && typeof item === "object" ? (item as Record<string, unknown>) : {};- const bookId =- typeof record.book_id === "string"- ? record.book_id- : "";- const pageIds =- Array.isArray(record.page_ids)- ? record.page_ids.filter(- (pageId): pageId is string => typeof pageId === "string" && !!pageId,- )- : [];+ item && typeof item === "object"+ ? (item as Record<string, unknown>)+ : {};+ const bookId = typeof record.book_id === "string" ? record.book_id : "";+ const pageIds = Array.isArray(record.page_ids)+ ? record.page_ids.filter(+ (pageId): pageId is string =>+ typeof pageId === "string" && !!pageId,+ )+ : [];return bookId && pageIds.length? { book_id: bookId, page_ids: Array.from(new Set(pageIds)) }: null;diff --git a/web/next-env.d.ts b/web/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/web/next-env.d.ts+++ b/web/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.