DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
release: v1.1.0 — LaTeX parsing overhaul, LLM probe config, extra_headers fix, notebook UUID fix
Bingxi Zhao (Frank)727d49cf8bda
diff --git a/.env.example b/.env.exampleindex 0cb750aa2..a2f24bfc1 100644--- a/.env.example+++ b/.env.example@@ -14,15 +14,13 @@ FRONTEND_PORT=3782# --------------------------------------------# LLM (Required)# --------------------------------------------+# Supported bindings: openai, lm_studio, ollama, azure_openai, deepseek, ...+# For a full list run: deeptutor provider list // READMELLM_BINDING=openaiLLM_MODEL=gpt-4o-miniLLM_API_KEY=sk-xxxLLM_HOST=https://api.openai.com/v1LLM_API_VERSION=-# Max completion tokens used by the Settings → LLM diagnostic probe.-# Bump this if you point the probe at a reasoning model (thinking tokens-# eat into the budget and empty out the visible response otherwise).-LLM_TEST_MAX_TOKENS=1024# --------------------------------------------# Embedding (Required for knowledge base features)@@ -34,6 +32,21 @@ EMBEDDING_HOST=https://api.openai.com/v1EMBEDDING_DIMENSION=3072EMBEDDING_API_VERSION=+# ⚠️ Docker + local LLM (LM Studio / Ollama / vLLM)+# ─────────────────────────────────────────────────────+# When running DeepTutor in Docker and your LLM runs on the HOST machine:+# - Do NOT use "localhost" or "127.0.0.1" — inside the container these+# refer to the container itself, not the host.+# - macOS / Windows Docker Desktop: use http://host.docker.internal:<port>/v1+# - Linux: use the host's LAN IP, e.g. http://192.168.1.100:<port>/v1+# (or run Docker with --network=host)+#+# Example (LM Studio on port 1234):+# LLM_BINDING=lm_studio+# LLM_HOST=http://host.docker.internal:1234/v1+# EMBEDDING_BINDING=lm_studio+# EMBEDDING_HOST=http://host.docker.internal:1234/v1+# --------------------------------------------# Web Search (Optional)# --------------------------------------------diff --git a/.env.example_CN b/.env.example_CNindex 14120f86c..f4a83067f 100644--- a/.env.example_CN+++ b/.env.example_CN@@ -14,6 +14,8 @@ FRONTEND_PORT=3782# --------------------------------------------# LLM(必填)# --------------------------------------------+# 支持的 binding: openai, lm_studio, ollama, azure_openai, deepseek, ...+# 完整列表请运行: deeptutor provider listLLM_BINDING=openaiLLM_MODEL=gpt-4o-miniLLM_API_KEY=sk-xxx@@ -30,6 +32,21 @@ EMBEDDING_HOST=https://api.openai.com/v1EMBEDDING_DIMENSION=3072EMBEDDING_API_VERSION=+# ⚠️ Docker + 本地模型(LM Studio / Ollama / vLLM)+# ─────────────────────────────────────────────────────+# 当 DeepTutor 以 Docker 方式运行、而 LLM 运行在宿主机上时:+# - 不要使用 "localhost" 或 "127.0.0.1"——容器内这些地址指向容器自身,+# 而不是宿主机。+# - macOS / Windows (Docker Desktop): 使用 http://host.docker.internal:<端口>/v1+# - Linux: 使用宿主机的局域网 IP,例如 http://192.168.1.100:<端口>/v1+# (或使用 --network=host 模式启动 Docker)+#+# 示例(LM Studio 运行在 1234 端口):+# LLM_BINDING=lm_studio+# LLM_HOST=http://host.docker.internal:1234/v1+# EMBEDDING_BINDING=lm_studio+# EMBEDDING_HOST=http://host.docker.internal:1234/v1+# --------------------------------------------# 搜索(可选)# --------------------------------------------diff --git a/README.md b/README.mdindex 9ae39cb21..3b0f2c94f 100644--- a/README.md+++ b/README.md@@ -26,6 +26,8 @@### 📦 Releases+> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX block math parsing overhaul, LLM diagnostic probe agents.yaml configuration, extra headers forwarding in LLM factory, SaveToNotebookModal UUID fix, Docker + local LLM guidance, and expanded test suite.+> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — URL-based chat routing with bookmarkable sessions, Snow theme, WebSocket heartbeat & auto-reconnect with resume, ChatComposer performance optimization, embedding provider registry overhaul, Serper search provider, streaming idle timeout, and expanded test suite.> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) — Question Notebook for unified quiz review with bookmarks & categories, Mermaid diagram support in Visualize, embedding model mismatch detection, system message merging for Qwen/vLLM compatibility, LM Studio & llama.cpp provider support, and Glass theme.diff --git a/assets/releases/ver1-1-0.md b/assets/releases/ver1-1-0.mdnew file mode 100644index 000000000..87ff44b02--- /dev/null+++ b/assets/releases/ver1-1-0.md@@ -0,0 +1,30 @@+# DeepTutor v1.1.0 Release Notes++**Release Date:** 2026.04.15++## Highlights++### LaTeX Block Math Parsing Overhaul+Rewrote the `normalizeEditorMdInlineMath` pipeline to correctly handle loose block math — content wrapped in single `$` delimiters on separate lines (e.g. `$\n\\frac{a}{b}\n$`). A new `looksLikeLatexBlock` heuristic scans the enclosed lines for LaTeX-specific tokens (`\\command`, `\\\\`, `_`, `^`, `&`) and promotes the delimiters to `$$…$$` when appropriate, while leaving non-LaTeX dollar-sign usage untouched. Also tightened the one-line `$$…$$` regex to require a trailing `$` anchor, preventing over-eager matching.++### LLM Diagnostic Probe — `agents.yaml` Configuration+Moved the LLM probe `max_tokens` setting from the `LLM_TEST_MAX_TOKENS` environment variable to `diagnostics.llm_probe.max_tokens` in `agents.yaml`, aligning it with the existing agent-parameter system. The env-var approach and its Docker/`.env.example` entries have been removed in favour of the unified config loader (`get_agent_params("llm_probe")`).++### Extra Headers Forwarding in LLM Factory+Both `llm_complete` and `llm_stream` now accept caller-supplied `extra_headers` via kwargs and merge them with provider-level headers, instead of silently dropping or double-passing them. This fixes a `TypeError: multiple values for keyword argument 'extra_headers'` crash when agents (e.g. `NotebookSummarizeAgent`) forwarded custom gateway headers.++### SaveToNotebookModal UUID Fix+The modal now fetches notebooks from `/api/v1/notebook/list` (UUID-based) instead of `listCategories()` (integer category IDs from the legacy question-notebook API). This resolves issue #301 where Co-Writer and other non-quiz saves silently failed because numeric category IDs never matched any notebook UUID.++### Docker + Local LLM Guidance+Added a prominent documentation block to `.env.example`, `.env.example_CN`, `docker-compose.yml`, and `docker-compose.ghcr.yml` explaining `host.docker.internal` usage when the LLM/embedding server runs on the host machine — covering macOS/Windows Docker Desktop and Linux LAN-IP / `--network=host` alternatives.++### Test Suite Expansion+Added 5 new test modules (153 + 107 + 114 + 193 + 102 lines) covering LaTeX delimiter conversion and block-math promotion (`web/tests/latex.test.ts`), notebook router UUID validation (`tests/api/test_main_notebook_router.py`), `NotebookSummarizeAgent` extra-headers forwarding (`tests/agents/notebook/`), LLM probe `agents.yaml` integration (`tests/services/config/test_llm_probe_config.py`), and `extra_headers` dedup/merge in the LLM factory (`tests/services/llm/test_factory_provider_exec.py`).++## Community Contributions++- **@DarkGenius** — Make LLM probe `max_tokens` configurable (#321)+- **@sagnikonly** — Improve robust parsing for LaTeX block math (#323)++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.1.0-beta...v1.1.0diff --git a/deeptutor/agents/notebook/summarize_agent.py b/deeptutor/agents/notebook/summarize_agent.pyindex c50a89fa9..d5a4d260e 100644--- a/deeptutor/agents/notebook/summarize_agent.py+++ b/deeptutor/agents/notebook/summarize_agent.py@@ -26,6 +26,7 @@ class NotebookSummarizeAgent:self.base_url = getattr(self.llm_config, "base_url", None)self.api_version = getattr(self.llm_config, "api_version", None)self.binding = getattr(self.llm_config, "binding", None) or "openai"+ self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}async def summarize(self,@@ -68,6 +69,9 @@ class NotebookSummarizeAgent:if self.model:kwargs.update(get_token_limit_kwargs(self.model, 300))+ if self.extra_headers:+ kwargs["extra_headers"] = self.extra_headers+async for chunk in llm_stream(prompt=prompt,system_prompt=self._system_prompt(),diff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.pyindex 30e46f996..3e458e81e 100644--- a/deeptutor/services/config/loader.py+++ b/deeptutor/services/config/loader.py@@ -216,6 +216,7 @@ def get_agent_params(module_name: str) -> dict:- "brainstorm": Brainstorm tool settings- "co_writer": CoWriter module agents- "narrator": Narrator agent (independent, for TTS)+ - "llm_probe": Settings → LLM diagnostic probeReturns:dict: Dictionary containing:@@ -240,6 +241,7 @@ def get_agent_params(module_name: str) -> dict:"brainstorm": ("tools", "brainstorm"),"vision_solver": ("plugins", "vision_solver"),"math_animator": ("plugins", "math_animator"),+ "llm_probe": ("diagnostics", "llm_probe"),}path = get_runtime_settings_dir(PROJECT_ROOT) / "agents.yaml"if not path.exists():diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.pyindex f72c73f75..d067a17f3 100644--- a/deeptutor/services/config/test_runner.py+++ b/deeptutor/services/config/test_runner.py@@ -156,12 +156,11 @@ class ConfigTestRunner:run.emit("info", f"Resolved model `{llm_config.model}` with binding `{llm_config.binding}`.")run.emit("info", f"Request target: {llm_config.base_url}")# Reasoning models spend part of the budget on internal thinking;- # too tight a cap makes them return empty content. Override via- # LLM_TEST_MAX_TOKENS when the default (1024) isn't enough.- try:- max_tokens = max(1, int(os.getenv("LLM_TEST_MAX_TOKENS", "1024")))- except ValueError:- max_tokens = 1024+ # too tight a cap makes them return empty content. Configurable+ # via diagnostics.llm_probe.max_tokens in agents.yaml.+ from .loader import get_agent_params+ probe_params = get_agent_params("llm_probe")+ max_tokens = max(1, int(probe_params.get("max_tokens", 1024)))token_kwargs = get_token_limit_kwargs(llm_config.model, max_tokens=max_tokens)run.emit("info", f"Token options: {json.dumps(token_kwargs)}")response = await llm_complete(diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 8b8fd85af..677620fd6 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -177,6 +177,7 @@ async def complete(provider_name = binding or "openai"provider_mode = "standard"extra_headers: dict[str, str] = {}+ caller_extra_headers = kwargs.pop("extra_headers", None) or {}reasoning_effort = kwargs.pop("reasoning_effort", None)if not model or not base_url or api_key is None or not binding:@@ -199,6 +200,9 @@ async def complete(if spec is not None:provider_mode = spec.mode+ if caller_extra_headers:+ extra_headers.update(caller_extra_headers)+use_local_fallback = _should_use_local(base_url)def _is_retriable_llm_api_error(exc: BaseException) -> bool:@@ -320,6 +324,7 @@ async def complete(extra_kwargs: CallKwargs = dict(kwargs)extra_kwargs.pop("messages", None)+ extra_kwargs.pop("extra_headers", None)return await _do_complete(prompt_value=prompt,@@ -352,6 +357,7 @@ async def stream(provider_name = binding or "openai"provider_mode = "standard"extra_headers: dict[str, str] = {}+ caller_extra_headers = kwargs.pop("extra_headers", None) or {}reasoning_effort = kwargs.pop("reasoning_effort", None)if not model or not base_url or api_key is None or not binding:@@ -374,9 +380,13 @@ async def stream(if spec is not None:provider_mode = spec.mode+ if caller_extra_headers:+ extra_headers.update(caller_extra_headers)+use_local_fallback = _should_use_local(base_url)extra_kwargs: CallKwargs = dict(kwargs)extra_kwargs.pop("messages", None)+ extra_kwargs.pop("extra_headers", None)total_attempts = max_retries + 1last_exception: Exception | None = Nonediff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.ymlindex e8e30acc0..6e4620264 100644--- a/docker-compose.ghcr.yml+++ b/docker-compose.ghcr.yml@@ -14,6 +14,10 @@# 1. Copy .env.example to .env and fill in your API keys# 2. Read the API URL note below before starting#+# Local LLM (LM Studio / Ollama / vLLM):+# Use "host.docker.internal" instead of "localhost" for LLM_HOST / EMBEDDING_HOST.+# See .env.example for details.+## ============================================# IMPORTANT: Frontend-to-Backend API URL# ============================================diff --git a/docker-compose.yml b/docker-compose.ymlindex 509721eb6..0d010f570 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -11,6 +11,10 @@# Prerequisites:# 1. Copy .env.example to .env and configure your API keys# 2. Runtime settings are stored in ./data/user/settings (created automatically)+#+# Local LLM (LM Studio / Ollama / vLLM):+# Use "host.docker.internal" instead of "localhost" for LLM_HOST / EMBEDDING_HOST.+# See .env.example for details.# ============================================services:@@ -42,7 +46,6 @@ services:- LLM_API_KEY=${LLM_API_KEY}- LLM_HOST=${LLM_HOST}- LLM_API_VERSION=${LLM_API_VERSION:-}- - LLM_TEST_MAX_TOKENS=${LLM_TEST_MAX_TOKENS:-1024}- DISABLE_SSL_VERIFY=${DISABLE_SSL_VERIFY:-false}# Embedding Configuration (Required for Knowledge Base)- EMBEDDING_BINDING=${EMBEDDING_BINDING:-openai}diff --git a/tests/agents/notebook/__init__.py b/tests/agents/notebook/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/agents/notebook/test_summarize_agent.py b/tests/agents/notebook/test_summarize_agent.pynew file mode 100644index 000000000..19c18ffe8--- /dev/null+++ b/tests/agents/notebook/test_summarize_agent.py@@ -0,0 +1,107 @@+"""Tests for NotebookSummarizeAgent — extra_headers forwarding."""++from __future__ import annotations++import pytest++from deeptutor.services.llm.config import LLMConfig+++def _make_cfg(**overrides):+ defaults = dict(+ model="gpt-4o-mini",+ api_key="test-key",+ base_url="https://api.example.com/v1",+ binding="openai",+ provider_name="openai",+ provider_mode="standard",+ )+ defaults.update(overrides)+ return LLMConfig(**defaults)+++def test_summarize_agent_stores_extra_headers(monkeypatch) -> None:+ """Agent should pick up extra_headers from LLMConfig."""+ cfg = _make_cfg(extra_headers={"X-Gateway": "prod"})+ monkeypatch.setattr(+ "deeptutor.agents.notebook.summarize_agent.get_llm_config", lambda: cfg,+ )++ from deeptutor.agents.notebook.summarize_agent import NotebookSummarizeAgent++ agent = NotebookSummarizeAgent(language="en")+ assert agent.extra_headers == {"X-Gateway": "prod"}+++def test_summarize_agent_empty_extra_headers(monkeypatch) -> None:+ """Agent should default to empty dict when config has no extra_headers."""+ cfg = _make_cfg()+ monkeypatch.setattr(+ "deeptutor.agents.notebook.summarize_agent.get_llm_config", lambda: cfg,+ )++ from deeptutor.agents.notebook.summarize_agent import NotebookSummarizeAgent++ agent = NotebookSummarizeAgent(language="en")+ assert agent.extra_headers == {}+++async def test_summarize_agent_forwards_extra_headers(monkeypatch) -> None:+ """extra_headers must reach the underlying llm_stream call."""+ cfg = _make_cfg(extra_headers={"X-Gateway": "prod"})+ monkeypatch.setattr(+ "deeptutor.agents.notebook.summarize_agent.get_llm_config", lambda: cfg,+ )+ captured: dict[str, object] = {}++ async def _fake_llm_stream(**kwargs):+ captured.update(kwargs)+ yield "summary text"++ monkeypatch.setattr(+ "deeptutor.agents.notebook.summarize_agent.llm_stream", _fake_llm_stream,+ )++ from deeptutor.agents.notebook.summarize_agent import NotebookSummarizeAgent++ agent = NotebookSummarizeAgent(language="en")+ chunks: list[str] = []+ async for c in agent.stream_summary(+ title="Test",+ record_type="chat",+ user_query="What is X?",+ output="X is Y.",+ ):+ chunks.append(c)++ assert "".join(chunks) == "summary text"+ assert captured.get("extra_headers") == {"X-Gateway": "prod"}+++async def test_summarize_agent_omits_extra_headers_when_empty(monkeypatch) -> None:+ """When no extra_headers configured, they should not appear in kwargs."""+ cfg = _make_cfg()+ monkeypatch.setattr(+ "deeptutor.agents.notebook.summarize_agent.get_llm_config", lambda: cfg,+ )+ captured: dict[str, object] = {}++ async def _fake_llm_stream(**kwargs):+ captured.update(kwargs)+ yield "ok"++ monkeypatch.setattr(+ "deeptutor.agents.notebook.summarize_agent.llm_stream", _fake_llm_stream,+ )++ from deeptutor.agents.notebook.summarize_agent import NotebookSummarizeAgent++ agent = NotebookSummarizeAgent(language="en")+ async for _ in agent.stream_summary(+ title="T", record_type="chat", user_query="q", output="o",+ ):+ pass++ assert "extra_headers" not in captureddiff --git a/tests/api/test_main_notebook_router.py b/tests/api/test_main_notebook_router.pynew file mode 100644index 000000000..646dabc04--- /dev/null+++ b/tests/api/test_main_notebook_router.py@@ -0,0 +1,114 @@+"""Tests for the main notebook router (/api/v1/notebook).++Verifies that records can only be saved using real notebook UUIDs+(from /api/v1/notebook/list), not question-notebook category integer IDs.+Regression test for issue #301 (Co-Writer save to notebook).+"""++from __future__ import annotations++import importlib++import pytest++pytest.importorskip("fastapi")++FastAPI = pytest.importorskip("fastapi").FastAPI+TestClient = pytest.importorskip("fastapi.testclient").TestClient++notebook_router = importlib.import_module("deeptutor.api.routers.notebook").router++from deeptutor.services.notebook.service import NotebookManager+++def _build_app(manager: NotebookManager) -> FastAPI:+ app = FastAPI()+ app.include_router(notebook_router, prefix="/api/v1/notebook")+ return app+++def manager(tmp_path, monkeypatch) -> NotebookManager:+ instance = NotebookManager(base_dir=str(tmp_path / "notebooks"))+ monkeypatch.setattr(+ "deeptutor.api.routers.notebook.notebook_manager", instance,+ )+ return instance+++def test_list_notebooks_empty(manager: NotebookManager) -> None:+ with TestClient(_build_app(manager)) as client:+ resp = client.get("/api/v1/notebook/list")+ assert resp.status_code == 200+ data = resp.json()+ assert data["notebooks"] == []+ assert data["total"] == 0+++def test_create_and_list_notebook(manager: NotebookManager) -> None:+ with TestClient(_build_app(manager)) as client:+ create_resp = client.post(+ "/api/v1/notebook/create",+ json={"name": "Study Notes", "description": "Physics"},+ )+ assert create_resp.status_code == 200+ nb = create_resp.json()["notebook"]+ assert nb["name"] == "Study Notes"+ nb_id = nb["id"]++ listing = client.get("/api/v1/notebook/list").json()+ assert listing["total"] == 1+ assert listing["notebooks"][0]["id"] == nb_id+++def test_add_record_with_valid_notebook_id(manager: NotebookManager) -> None:+ """Records saved with a real notebook UUID must appear in that notebook."""+ nb = manager.create_notebook(name="My Notes")+ nb_id = nb["id"]++ with TestClient(_build_app(manager)) as client:+ resp = client.post(+ "/api/v1/notebook/add_record",+ json={+ "notebook_ids": [nb_id],+ "record_type": "co_writer",+ "title": "Draft on Fourier",+ "summary": "Existing summary",+ "user_query": "Explain Fourier",+ "output": "Fourier transform is...",+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["success"] is True+ assert nb_id in body["added_to_notebooks"]++ detail = client.get(f"/api/v1/notebook/{nb_id}").json()+ assert len(detail["records"]) == 1+ assert detail["records"][0]["title"] == "Draft on Fourier"+++def test_add_record_with_numeric_category_id_saves_nothing(manager: NotebookManager) -> None:+ """Using a question-notebook integer category ID must NOT match any notebook.++ This is the root cause of issue #301: the old SaveToNotebookModal sent+ numeric category IDs from /api/v1/question-notebook/categories instead of+ UUID notebook IDs from /api/v1/notebook/list.+ """+ manager.create_notebook(name="My Notes")++ with TestClient(_build_app(manager)) as client:+ resp = client.post(+ "/api/v1/notebook/add_record",+ json={+ "notebook_ids": ["1", "42"],+ "record_type": "co_writer",+ "title": "Lost draft",+ "summary": "This should not be saved anywhere",+ "user_query": "...",+ "output": "...",+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["added_to_notebooks"] == []diff --git a/tests/services/config/__init__.py b/tests/services/config/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/services/config/test_llm_probe_config.py b/tests/services/config/test_llm_probe_config.pynew file mode 100644index 000000000..14f7b5903--- /dev/null+++ b/tests/services/config/test_llm_probe_config.py@@ -0,0 +1,193 @@+"""Tests for LLM diagnostic probe max_tokens configuration via agents.yaml."""++from __future__ import annotations++import textwrap+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock, patch++import pytest+import yaml++from deeptutor.services.config.loader import get_agent_params+++# ---------------------------------------------------------------------------+# get_agent_params("llm_probe") — reads diagnostics.llm_probe from agents.yaml+# ---------------------------------------------------------------------------+++def _write_agents_yaml(tmp_path: Path, content: dict[str, Any]) -> Path:+ settings_dir = tmp_path / "data" / "user" / "settings"+ settings_dir.mkdir(parents=True, exist_ok=True)+ agents_file = settings_dir / "agents.yaml"+ agents_file.write_text(yaml.dump(content), encoding="utf-8")+ return tmp_path+++class TestGetAgentParamsLlmProbe:+ """Verify get_agent_params correctly resolves ``diagnostics.llm_probe``."""++ def test_reads_configured_max_tokens(self, tmp_path: Path, monkeypatch):+ project_root = _write_agents_yaml(tmp_path, {+ "diagnostics": {"llm_probe": {"max_tokens": 2048}},+ })+ monkeypatch.setattr(+ "deeptutor.services.config.loader.PROJECT_ROOT", project_root,+ )+ params = get_agent_params("llm_probe")+ assert params["max_tokens"] == 2048++ def test_uses_default_when_section_absent(self, tmp_path: Path, monkeypatch):+ project_root = _write_agents_yaml(tmp_path, {+ "capabilities": {"solve": {"temperature": 0.3}},+ })+ monkeypatch.setattr(+ "deeptutor.services.config.loader.PROJECT_ROOT", project_root,+ )+ params = get_agent_params("llm_probe")+ assert params["max_tokens"] == 4096+ assert params["temperature"] == 0.5++ def test_uses_default_when_max_tokens_key_absent(self, tmp_path: Path, monkeypatch):+ project_root = _write_agents_yaml(tmp_path, {+ "diagnostics": {"llm_probe": {"temperature": 0.1}},+ })+ monkeypatch.setattr(+ "deeptutor.services.config.loader.PROJECT_ROOT", project_root,+ )+ params = get_agent_params("llm_probe")+ assert params["max_tokens"] == 4096+ assert params["temperature"] == 0.1++ def test_custom_value_overrides_default(self, tmp_path: Path, monkeypatch):+ project_root = _write_agents_yaml(tmp_path, {+ "diagnostics": {"llm_probe": {"max_tokens": 512, "temperature": 0.2}},+ })+ monkeypatch.setattr(+ "deeptutor.services.config.loader.PROJECT_ROOT", project_root,+ )+ params = get_agent_params("llm_probe")+ assert params["max_tokens"] == 512+ assert params["temperature"] == 0.2+++# ---------------------------------------------------------------------------+# _test_llm integration: verify probe picks up max_tokens from agents.yaml+# ---------------------------------------------------------------------------+++def _patch_project_root(tmp_path: Path, monkeypatch):+ """Create a minimal agents.yaml and point PROJECT_ROOT at tmp_path."""+ project_root = _write_agents_yaml(tmp_path, {+ "diagnostics": {"llm_probe": {"max_tokens": 768}},+ })+ monkeypatch.setattr(+ "deeptutor.services.config.loader.PROJECT_ROOT", project_root,+ )+ return project_root+++class TestLlmProbeUsesAgentsYaml:+ """End-to-end: ConfigTestRunner._test_llm reads max_tokens from agents.yaml."""++ @pytest.mark.asyncio+ @pytest.mark.usefixtures("_patch_project_root")+ async def test_probe_passes_configured_max_tokens(self, monkeypatch):+ from deeptutor.services.config.test_runner import ConfigTestRunner, TestRun++ captured_kwargs: dict[str, Any] = {}++ async def _fake_llm_complete(**kwargs):+ captured_kwargs.update(kwargs)+ return "OK I am gpt-4o-mini"++ monkeypatch.setattr(+ "deeptutor.services.config.test_runner.resolve_llm_runtime_config",+ lambda catalog: _stub_resolved_llm(),+ )+ monkeypatch.setattr(+ "deeptutor.services.llm.get_token_limit_kwargs",+ _real_get_token_limit_kwargs,+ )+ monkeypatch.setattr(+ "deeptutor.services.llm.complete", _fake_llm_complete,+ )+ monkeypatch.setattr(+ "deeptutor.services.llm.clear_llm_config_cache", lambda: None,+ )++ runner = ConfigTestRunner()+ run = TestRun(id="test-llm-probe", service="llm")+ await runner._test_llm(run, catalog={})++ assert captured_kwargs.get("max_tokens") == 768 or captured_kwargs.get("max_completion_tokens") == 768++ @pytest.mark.asyncio+ async def test_probe_defaults_when_no_diagnostics_section(self, tmp_path, monkeypatch):+ """When diagnostics section is absent, falls back to get_agent_params default (4096)."""+ project_root = _write_agents_yaml(tmp_path, {"capabilities": {}})+ monkeypatch.setattr(+ "deeptutor.services.config.loader.PROJECT_ROOT", project_root,+ )++ from deeptutor.services.config.test_runner import ConfigTestRunner, TestRun++ captured_kwargs: dict[str, Any] = {}++ async def _fake_llm_complete(**kwargs):+ captured_kwargs.update(kwargs)+ return "OK I am gpt-4o-mini"++ monkeypatch.setattr(+ "deeptutor.services.config.test_runner.resolve_llm_runtime_config",+ lambda catalog: _stub_resolved_llm(),+ )+ monkeypatch.setattr(+ "deeptutor.services.llm.get_token_limit_kwargs",+ _real_get_token_limit_kwargs,+ )+ monkeypatch.setattr(+ "deeptutor.services.llm.complete", _fake_llm_complete,+ )+ monkeypatch.setattr(+ "deeptutor.services.llm.clear_llm_config_cache", lambda: None,+ )++ runner = ConfigTestRunner()+ run = TestRun(id="test-llm-probe-default", service="llm")+ await runner._test_llm(run, catalog={})++ assert captured_kwargs.get("max_tokens") == 4096 or captured_kwargs.get("max_completion_tokens") == 4096+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _stub_resolved_llm():+ """Return a minimal resolved LLM config stub."""+ from deeptutor.services.config.provider_runtime import ResolvedLLMConfig+ return ResolvedLLMConfig(+ model="gpt-4o-mini",+ api_key="sk-test",+ base_url="https://api.example.com/v1",+ effective_url="https://api.example.com/v1",+ binding="openai",+ provider_name="openai",+ provider_mode="standard",+ api_version="",+ extra_headers={},+ reasoning_effort=None,+ )+++def _real_get_token_limit_kwargs(model: str, max_tokens: int) -> dict[str, int]:+ """Inline reimplementation to avoid importing the full LLM stack in tests."""+ from deeptutor.services.llm.config import uses_max_completion_tokens+ if uses_max_completion_tokens(model):+ return {"max_completion_tokens": max_tokens}+ return {"max_tokens": max_tokens}diff --git a/tests/services/llm/test_factory_provider_exec.py b/tests/services/llm/test_factory_provider_exec.pyindex e1f33d787..32987b84e 100644--- a/tests/services/llm/test_factory_provider_exec.py+++ b/tests/services/llm/test_factory_provider_exec.py@@ -8,6 +8,108 @@ from deeptutor.services.llm.config import LLMConfigfrom deeptutor.services.llm.factory import complete, stream+# ---------------------------------------------------------------------------+# extra_headers dedup / merge (regression for #324)+# ---------------------------------------------------------------------------+++def _make_cfg(**overrides):+ defaults = dict(+ model="gpt-4o-mini",+ api_key="test-key",+ base_url="https://api.example.com/v1",+ binding="openai",+ provider_name="openai",+ provider_mode="standard",+ )+ defaults.update(overrides)+ return LLMConfig(**defaults)+++async def test_complete_extra_headers_from_kwargs_no_duplicate(monkeypatch) -> None:+ """Passing extra_headers via kwargs must not cause 'multiple values' TypeError."""+ cfg = _make_cfg(extra_headers={})+ captured: dict[str, object] = {}++ async def _fake_sdk_complete(**kwargs):+ captured.update(kwargs)+ return "ok"++ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)+ monkeypatch.setattr("deeptutor.services.llm.executors.sdk_complete", _fake_sdk_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.sdk_complete", _fake_sdk_complete)++ result = await complete("hello", extra_headers={"X-Custom": "val"})+ assert result == "ok"+ assert captured["extra_headers"] == {"X-Custom": "val"}+++async def test_complete_merges_config_and_caller_extra_headers(monkeypatch) -> None:+ """Caller extra_headers should be merged with config-level headers."""+ cfg = _make_cfg(extra_headers={"X-Config": "from-config"})+ captured: dict[str, object] = {}++ async def _fake_sdk_complete(**kwargs):+ captured.update(kwargs)+ return "ok"++ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)+ monkeypatch.setattr("deeptutor.services.llm.executors.sdk_complete", _fake_sdk_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.sdk_complete", _fake_sdk_complete)++ result = await complete("hello", extra_headers={"X-Caller": "from-caller"})+ assert result == "ok"+ headers = captured["extra_headers"]+ assert headers["X-Config"] == "from-config"+ assert headers["X-Caller"] == "from-caller"+++async def test_stream_extra_headers_from_kwargs_no_duplicate(monkeypatch) -> None:+ """Passing extra_headers via kwargs to stream must not cause 'multiple values' TypeError."""+ cfg = _make_cfg(extra_headers={})+ captured: dict[str, object] = {}++ async def _fake_sdk_stream(**kwargs):+ captured.update(kwargs)+ yield "chunk"++ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)+ monkeypatch.setattr("deeptutor.services.llm.executors.sdk_stream", _fake_sdk_stream)+ monkeypatch.setattr("deeptutor.services.llm.factory.sdk_stream", _fake_sdk_stream)++ chunks = []+ async for c in stream("hello", extra_headers={"X-Custom": "val"}):+ chunks.append(c)+ assert chunks == ["chunk"]+ assert captured["extra_headers"] == {"X-Custom": "val"}+++async def test_stream_merges_config_and_caller_extra_headers(monkeypatch) -> None:+ """Caller extra_headers should be merged with config-level headers in stream."""+ cfg = _make_cfg(extra_headers={"X-Config": "cfg"})+ captured: dict[str, object] = {}++ async def _fake_sdk_stream(**kwargs):+ captured.update(kwargs)+ yield "chunk"++ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)+ monkeypatch.setattr("deeptutor.services.llm.executors.sdk_stream", _fake_sdk_stream)+ monkeypatch.setattr("deeptutor.services.llm.factory.sdk_stream", _fake_sdk_stream)++ chunks = []+ async for c in stream("hello", extra_headers={"X-Caller": "clr"}):+ chunks.append(c)+ assert chunks == ["chunk"]+ headers = captured["extra_headers"]+ assert headers["X-Config"] == "cfg"+ assert headers["X-Caller"] == "clr"++@pytest.mark.asyncioasync def test_factory_complete_uses_litellm(monkeypatch) -> None:cfg = LLMConfig(diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsxindex 7cf0cf80a..9201cbd70 100644--- a/web/components/notebook/SaveToNotebookModal.tsx+++ b/web/components/notebook/SaveToNotebookModal.tsx@@ -4,7 +4,6 @@ import { useEffect, useMemo, useRef, useState } from "react";import { Loader2, X } from "lucide-react";import { useTranslation } from "react-i18next";import { apiUrl } from "@/lib/api";-import { listCategories } from "@/lib/notebook-api";type RecordType =| "solve"@@ -83,8 +82,12 @@ export default function SaveToNotebookModal({setSelectedIds([]);void (async () => {try {- const cats = await listCategories();- setNotebooks(cats.map((c) => ({ id: String(c.id), name: c.name })));+ const res = await fetch(apiUrl("/api/v1/notebook/list"), { cache: "no-store" });+ if (!res.ok) throw new Error("Failed to fetch notebooks");+ const data = (await res.json()) as {+ notebooks: Array<{ id: string; name: string; color?: string; description?: string }>;+ };+ setNotebooks(data.notebooks.map((nb) => ({ id: nb.id, name: nb.name, color: nb.color, description: nb.description })));} catch {setNotebooks([]);}diff --git a/web/lib/latex.ts b/web/lib/latex.tsindex 5c0c2ae73..c1f5b407c 100644--- a/web/lib/latex.ts+++ b/web/lib/latex.ts@@ -90,16 +90,13 @@ function normalizeEditorMdInlineMath(content: string): string {}}- // Preserve block math on its own line, but normalize one-line block math.if (- /^\$\$[\s\S]+\$\$/.test(trimmed) &&+ /^\$\$[\s\S]+\$\$$/.test(trimmed) &&(trimmed.match(/\$\$/g)?.length ?? 0) === 2) {- if (line.trim() === trimmed) {- const inner = trimmed.slice(2, -2).trim();- result.push(`$$\n${inner}\n$$`);- continue;- }+ const inner = trimmed.slice(2, -2).trim();+ result.push(`$$\n${inner}\n$$`);+ continue;}// editor.md commonly uses $...$ for inline math.diff --git a/web/tests/latex.test.ts b/web/tests/latex.test.tsnew file mode 100644index 000000000..13c62dcd3--- /dev/null+++ b/web/tests/latex.test.ts@@ -0,0 +1,152 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ convertLatexDelimiters,+ processLatexContent,+ processMarkdownContent,+} from "../lib/latex";++// ---------------------------------------------------------------------------+// convertLatexDelimiters+// ---------------------------------------------------------------------------++test("convertLatexDelimiters: \\\\[...\\\\] → block $$...$$", () => {+ const input = "Before \\[x^2 + 1\\] after";+ const result = convertLatexDelimiters(input);+ assert.ok(result.includes("$$\nx^2 + 1\n$$"));+});++test("convertLatexDelimiters: \\\\(...\\\\) → inline $...$", () => {+ const input = "Solve \\(x = 2\\) now";+ const result = convertLatexDelimiters(input);+ assert.ok(result.includes("$x = 2$"));+});++test("convertLatexDelimiters: strips \\\\(\\\\) inside $$...$$", () => {+ const input = "$$\\(x^2\\)$$";+ const result = convertLatexDelimiters(input);+ assert.ok(result.includes("$$\nx^2\n$$"));+ assert.ok(!result.includes("\\("));+});++test("convertLatexDelimiters: multiline \\\\[...\\\\]", () => {+ const input = "\\[\n\\frac{a}{b}\n\\]";+ const result = convertLatexDelimiters(input);+ assert.ok(result.includes("$$"));+ assert.ok(result.includes("\\frac{a}{b}"));+});++test("convertLatexDelimiters: preserves expr containing $& replacement char", () => {+ const input = "\\[x \\$\\& y\\]";+ const result = convertLatexDelimiters(input);+ assert.ok(result.includes("x \\$\\& y"), "special regex replacement char $& must be preserved");+});++test("convertLatexDelimiters: returns empty-ish input unchanged", () => {+ assert.equal(convertLatexDelimiters(""), "");+ assert.equal(convertLatexDelimiters(null as unknown as string), null);+});++test("convertLatexDelimiters: collapses triple+ newlines", () => {+ const input = "a\n\n\n\nb";+ const result = convertLatexDelimiters(input);+ assert.ok(!result.includes("\n\n\n"));+});++// ---------------------------------------------------------------------------+// processLatexContent (thin wrapper)+// ---------------------------------------------------------------------------++test("processLatexContent: delegates to convertLatexDelimiters", () => {+ assert.equal(processLatexContent(""), "");+ const out = processLatexContent("\\(x\\)");+ assert.ok(out.includes("$x$"));+});++// ---------------------------------------------------------------------------+// processMarkdownContent — heading normalisation+// ---------------------------------------------------------------------------++test("headings: inserts space when missing", () => {+ const result = processMarkdownContent("##Title");+ assert.ok(result.includes("## Title"));+});++test("headings: leaves properly-spaced headings alone", () => {+ const result = processMarkdownContent("## Title");+ assert.ok(result.includes("## Title"));+});++test("headings: does not split 7+ consecutive hashes", () => {+ const result = processMarkdownContent("#######");+ assert.equal(result.trim(), "#######");+});++// ---------------------------------------------------------------------------+// processMarkdownContent — inline math normalisation ($$...$$ → $...$)+// ---------------------------------------------------------------------------++test("inline math: $$x$$ on a line with other text → $x$", () => {+ const result = processMarkdownContent("Compute $$x^2$$ now");+ assert.ok(result.includes("$x^2$"));+ assert.ok(!result.includes("$$x^2$$"));+});++test("inline math: standalone one-line $$...$$ → split to block", () => {+ const result = processMarkdownContent("$$\\frac{a}{b}$$");+ const lines = result.trim().split("\n");+ assert.equal(lines[0], "$$");+ assert.ok(lines[1].includes("\\frac{a}{b}"));+ assert.equal(lines[2], "$$");+});++// ---------------------------------------------------------------------------+// processMarkdownContent — loose block math ($...\n...\n$) promotion+// ---------------------------------------------------------------------------++test("loose block math: single-$ lines wrapping LaTeX → promoted to $$", () => {+ const input = "$\n\\frac{a}{b}\n$";+ const result = processMarkdownContent(input);+ const lines = result.trim().split("\n");+ assert.equal(lines[0], "$$");+ assert.ok(lines.some((l) => l.includes("\\frac{a}{b}")));+ assert.equal(lines[lines.length - 1], "$$");+});++test("loose block math: single-$ lines with non-LaTeX content → not promoted", () => {+ const input = "$\nhello world\n$";+ const result = processMarkdownContent(input);+ assert.ok(!result.startsWith("$$"));+});++test("loose block math: recognises \\\\ (line break) as LaTeX", () => {+ const input = "$\na \\\\\nb\n$";+ const result = processMarkdownContent(input);+ const lines = result.trim().split("\n");+ assert.equal(lines[0], "$$");+});++test("loose block math: recognises _ and ^ as LaTeX", () => {+ const input = "$\nx_1 + y^2\n$";+ const result = processMarkdownContent(input);+ const lines = result.trim().split("\n");+ assert.equal(lines[0], "$$");+});++// ---------------------------------------------------------------------------+// processMarkdownContent — end-to-end pipeline+// ---------------------------------------------------------------------------++test("pipeline: combined heading + inline math + delimiter conversion", () => {+ const input = "##Heading\n\nSolve \\(x=1\\) and $$y$$";+ const result = processMarkdownContent(input);+ assert.ok(result.includes("## Heading"), "heading should be normalised");+ assert.ok(result.includes("$x=1$"), "\\\\(...\\\\) should become $...$");+ assert.ok(result.includes("$y$"), "$$y$$ inline should become $y$");+});++test("pipeline: preserves fenced code blocks", () => {+ const input = "```python\nprint('hello')\n```";+ const result = processMarkdownContent(input);+ assert.ok(result.includes("print('hello')"));+});