DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(book/session/zulip): post-merge hardening of #493/#529/#484
Bingxi Zhao (Frank)1946ae818289
diff --git a/PATCHES.md b/PATCHES.mddeleted file mode 100644index 13269be00..000000000--- a/PATCHES.md+++ /dev/null@@ -1,163 +0,0 @@-# DeepTutor Local Patch Notes--> Local fixes applied on top of mainstream v1.1.0.-> Re-apply these after syncing from upstream (https://github.com/HKUDS/DeepTutor).-------## Fix 1: Deep Research — "settings are incomplete" guard--**Problem:** When Deep Research mode is active but the research config hasn't been fully initialized yet, `buildResearchWSConfig()` throws and the message gets swallowed — the user sees nothing happen when they hit send.--**Root cause:** `handleSend()` unconditionally called `buildResearchWSConfig(researchConfig)` even when `researchConfig` fields like `depth` were empty strings. The validation check existed in the UI (composer shows disabled state) but was not enforced at send time — a race condition / edge case.--**Files affected:**--| File | Change |-|---|---|-| `web/app/(workspace)/chat/[[...sessionId]]/page.tsx` | Added `if (!researchValidation.valid) return;` guard before `buildResearchWSConfig(researchConfig)` call (line ~555) |-| `web/app/(workspace)/chat/[[...sessionId]]/page.tsx` | Added `researchValidation` to the `useCallback` dependency array (line ~570) |--**Diff snippet:**--```typescript-// BEFORE-if (isResearchMode) config = buildResearchWSConfig(researchConfig);--// AFTER-if (isResearchMode) {- if (!researchValidation.valid) return;- config = buildResearchWSConfig(researchConfig);-}-```--**Re-apply after sync:** Search for `isResearchMode` in `page.tsx` — the guard must be placed before `buildResearchWSConfig`. If the upstream changed the variable name (`researchValidation` / `researchConfig`), adapt accordingly.-------## Fix 2: Windows GBK encoding crash (emoji in print())--**Problem:** Backend crashes with `'gbk' codec can't encode character '\U0001f500'` when running on Windows (Chinese/Japanese locale). The emoji characters in `decompose_agent.py` `print()` statements cannot be encoded to the Windows default GBK code page.--**Root cause:** `sys.stdout` on Windows defaults to the system locale encoding (e.g. `gbk` on zh-CN Windows). Emoji characters (🔄, ✅, ❌, etc.) are outside the GBK character set. When `print()` tries to write them to stdout, Python throws `UnicodeEncodeError`.--**Files affected:**--| File | Change |-|---|---|-| `deeptutor/api/run_server.py` | Added `encoding="utf-8"` to both `sys.stdout.reconfigure()` and `sys.stderr.reconfigure()` calls |-| `start_backend.bat` | Added `set PYTHONIOENCODING=utf-8` and `set PYTHONUTF8=1` before launching Python |--**Diff snippet (`run_server.py`):**--```python-# BEFORE-if hasattr(sys.stdout, "reconfigure"):- sys.stdout.reconfigure(line_buffering=True)-if hasattr(sys.stderr, "reconfigure"):- sys.stderr.reconfigure(line_buffering=True)--# AFTER-if hasattr(sys.stdout, "reconfigure"):- sys.stdout.reconfigure(line_buffering=True, encoding="utf-8")-if hasattr(sys.stderr, "reconfigure"):- sys.stderr.reconfigure(line_buffering=True, encoding="utf-8")-```--**Diff snippet (`start_backend.bat`):**--```batch-@echo off-cd /d "%~dp0"--REM Set UTF-8 encoding for stdout to support emoji characters-set PYTHONIOENCODING=utf-8-set PYTHONUTF8=1--call .venv\Scripts\activate.bat-python -m deeptutor.api.run_server-pause-```--**Source of the emoji:** `deeptutor/agents/research/agents/decompose_agent.py` line ~131 has `print()` calls with emoji characters. On Linux/Mac these work fine (UTF-8 by default); on Windows they fail.--**Re-apply after sync:** Two changes needed:-1. Add `encoding="utf-8"` to `sys.stdout.reconfigure()` and `sys.stderr.reconfigure()` in `run_server.py`-2. Add `PYTHONIOENCODING=utf-8` and `PYTHONUTF8=1` in the startup script-------## Fix 3: Notebook service module not importable--**Problem:** Frontend "Save to Notebook" modal shows "No Notebooks found" even though notebooks exist. The `/api/v1/notebook/list` API endpoint either returns empty or errors silently.--**Root cause discovered so far:** The `deeptutor/services/notebook/` directory was missing from the working tree (possibly deleted or not checked out properly). Restored from git HEAD. Also, the `deeptutor/services/__init__.py` was missing a lazy import for `notebook_manager`, so `from deeptutor.services import notebook_manager` would fail at runtime if the directory existed but the import wasn't wired.--**Files affected:**--| File | Change |-|---|---|-| `deeptutor/services/notebook/` | Restored entire directory from git HEAD (service.py, __init__.py) |-| `deeptutor/services/__init__.py` | Added lazy import for `notebook_manager` and added `"notebook"` to `__all__` |--**Diff snippet (`services/__init__.py`):**--```python-# In __all__ — added "notebook"-__all__ = [- ...- "notebook", # NEW- ...-]--# In __getattr__ — added notebook_manager lazy import-if name == "notebook_manager":- from .notebook import notebook_manager- return notebook_manager-```--**Re-apply after sync:**-1. Verify `deeptutor/services/notebook/` exists with `service.py` and `__init__.py`-2. Add the `notebook_manager` lazy import in `deeptutor/services/__init__.py` (and `"notebook"` to `__all__`)-3. Test with: `python -c "from deeptutor.services import notebook_manager; print(notebook_manager)"`-------## Fix 4 (Unconfirmed): SaveToNotebookModal — image model crash--**Problem (reported but root cause not yet confirmed):** When using "Save to Notebook" from a chat record that includes an image attachment, the `NotebookSummarizeAgent` tries to generate a summary. The agent uses the LLM model (likely `gpt-4o-mini`), and if the model doesn't support image input, it fails with an error like "Cannot read image.png (this model does not support image input)".--**Speculative:** The `_build_record_summary` function in `deeptutor/api/routers/notebook.py` passes the record to `NotebookSummarizeAgent.summarize()`, which sends the raw `output` (which may include image references) to the LLM. If the output contains image URLs/data that the LLM cannot process, it throws.--**No fix applied yet** — needs investigation.-------## Startup scripts (new files)--These are convenience scripts created for local use, not in the upstream repo:--| File | Description |-|---|---|-| `start_backend.bat` | Activates venv, sets UTF-8 encoding, starts `python -m deeptutor.api.run_server` |-| `start_frontend.bat` | Runs `npm run dev -- -p 3782` in the `web/` directory |-------## Verification checklist--After re-syncing from upstream, run these checks:--```bash-# 1. Check Deep Research guard-grep -n "isResearchMode" web/app/(workspace)/chat/[[...sessionId]]/page.tsx--# 2. Check UTF-8 encoding in run_server.py-grep -n "encoding" deeptutor/api/run_server.py--# 3. Check notebook import-python -c "from deeptutor.services import notebook_manager; print('OK:', notebook_manager)"--# 4. Test notebook list API-curl -s http://localhost:8001/api/v1/notebook/list | python -m json.tool-```diff --git a/PR_DESCRIPTION.md b/PR_DESCRIPTION.mddeleted file mode 100644index 8b586c668..000000000--- a/PR_DESCRIPTION.md+++ /dev/null@@ -1,91 +0,0 @@-# feat: Guided Learning — structured mastery-based tutoring system--## Summary--This PR introduces **Guided Learning**, a structured, mastery-based tutoring subsystem that transforms DeepTutor from a free-form chat tool into a pedagogical learning system with persistent progress tracking, spaced repetition, and adaptive stage progression.--**Upstream status**: This is a complete new subsystem. `upstream/dev` has no `deeptutor/learning/`, no `guided_learning.py` capability, and no learning-related frontend pages or components.--**Scope**: 71 files changed, +7,284 / -99 lines across 114 commits. All changes are additive except for minor hook points in existing chat/stream infrastructure. The branch was merged with `upstream/dev` (a merge commit at the tip) so it applies cleanly on top of the current dev base.-------## What's included--### Backend--| Component | Files | Description |-|-----------|-------|-------------|-| **Models** | `deeptutor/learning/models.py` | 4 enums + 9 Pydantic models: `LearningProgress`, `LearningModule`, `KnowledgePoint`, `QuizAttempt`, `ErrorRecord`, etc. |-| **Storage** | `deeptutor/learning/storage.py` | JSON persistence with CAS (compare-and-swap) semantics and path-traversal guards |-| **Service** | `deeptutor/learning/service.py` | Business logic: module lifecycle, mastery calculation (weighted recent accuracy), quiz attempt recording, error tracking |-| **Scheduler** | `deeptutor/learning/scheduler.py` | Spaced repetition scheduler with per-knowledge-type initial states |-| **Grading** | `deeptutor/learning/grading.py` | Server-side answer evaluation with normalization and stripping |-| **Capability** | `deeptutor/capabilities/guided_learning.py` | 12-stage state machine: diagnostic → plan → pretest → explain → Feynman check → practice → error diagnosis → module test → review → completed |-| **API Router** | `deeptutor/api/routers/guided_learning.py` | 10 REST endpoints: progress CRUD, module generation, notebook import, `/redo`, `/answer`, etc. |-| **Tests** | `deeptutor/learning/tests/` (13 files) | 164 tests covering models, storage, scheduler, service, API endpoints, LLM integration, timeout degradation, error diagnosis, E2E flow |--### Frontend--| Component | Files | Description |-|-----------|-------|-------------|-| **Learning Pages** | `web/app/(workspace)/learning/` | Module list, book-based learning session, WebSocket-driven stage streaming |-| **Learning Components** | `web/components/learning/` | `ModuleTree` (sidebar + mastery indicator), `CreateModuleDialog` (4-tab module creation), `StructuredStageContent` (JSON content rendering) |-| **API Client** | `web/lib/learning-api.ts` | Typed API client for all learning endpoints |-| **i18n** | `web/locales/en/app.json`, `zh/app.json` | Full English + Chinese localization |--### Infrastructure hooks--- `deeptutor/core/stream_bus.py`: added `wait_for_input()` for interactive stage turns-- `deeptutor/api/routers/unified_ws.py`: wired Guided Learning into WebSocket routing-- `deeptutor/api/main.py`: registered learning router-- `deeptutor/runtime/bootstrap/builtin_capabilities.py`: registered `guided_learning` capability-------## Key design decisions--1. **Fail-closed + degradation**: Every LLM call has bounded retry + timeout. If a stage fails repeatedly, it degrades gracefully (skips with user-visible notice) rather than blocking the learner.-2. **Cross-turn persistence**: `LearningProgress` is saved after every interactive step, so reconnects, cancellations, and backend restarts never lose student attempts.-3. **Server-side grading**: All answer evaluation happens server-side with stripped comparisons, preventing client-side manipulation.-4. **Prompt injection hardening**: Notebook-to-module generation uses XML tag boundaries (`<notebook_records>`), system-prompt constraints, input escaping (`html.escape` on user fields), and output validation (type whitelist + length truncation).-------## Testing--```bash-pytest deeptutor/learning/tests/ -q-# 164 passed-```--Test categories:-- Unit: models, storage, scheduler, grading-- Integration: service replace/merge, mastery updates, timeout degradation-- API: all 10 endpoints with success + error paths-- E2E: complete `PRETEST → EXPLAIN → FEYNMAN_CHECK → PRACTICE_QUIZ → ERROR_DIAGNOSIS → MODULE_TEST → REVIEW → COMPLETED` flow--Frontend type check:--```bash-cd web && npx tsc --noEmit-# clean-```-------## Checklist--- [x] 164 backend tests pass-- [x] Frontend `tsc --noEmit` clean-- [x] No breaking changes to existing chat / solve / research capabilities-- [x] i18n parity verified (`npm run i18n:parity`)-- [x] No secrets or local configs committed-- [x] All user-facing strings localized-- [x] Branch merged with `upstream/dev` at HEAD (clean three-way merge)-------## Related--Closes the gap identified in community discussions around structured learning workflows (see Discord #feature-requests, Feishu group).diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.pyindex d1a8c3a9e..8cb47d846 100644--- a/deeptutor/book/blocks/_llm_writer.py+++ b/deeptutor/book/blocks/_llm_writer.py@@ -7,6 +7,7 @@ Avoids subclassing BaseAgent for these tiny calls; instead usesfrom __future__ import annotations+import jsonfrom typing import Anyfrom deeptutor.services.llm import (@@ -101,20 +102,21 @@ def _strip_thinking_preamble(text: str) -> str:"""if not text:return text+ if "{" not in text:+ # No JSON object present (refusal / plain prose) — return as-is so the+ # caller's json-repair fallback can decide, instead of raising here.+ return text# Find the last '{' — that's where the actual JSON object startsbrace = text.rindex("{")if brace > 0:candidate = text[brace:]# Quick check: can json.loads parse it?- import jsontry:json.loads(candidate)return candidate # Valid JSON -> use itexcept (json.JSONDecodeError, ValueError):pass # Not valid JSON, fall through to original approach# Fallback: try the first '{' with the thinking-heuristic check- if "{" not in text:- return textbrace = text.index("{")if brace > 0:before = text[:brace].strip()@@ -129,7 +131,7 @@ async def llm_json(*,user_prompt: str,system_prompt: str,- max_tokens: int = 1200,+ max_tokens: int = 2600,temperature: float = 0.4,language: str | None = None,expected_key: str | None = None,@@ -138,8 +140,10 @@ async def llm_json(Reasoning models can spend the whole response budget on hidden/scratchpadtokens and leave the visible JSON object empty. For structured book blocks- we first honor the configured reasoning mode, then retry once with minimal- reasoning if parsing fails or the expected top-level key is missing.+ we first honor the configured reasoning mode, then retry once with low+ reasoning effort if parsing fails or the expected top-level key is missing.+ ("low" rather than "minimal": local/Qwen models served via vLLM reject+ "minimal", and "minimal" disables thinking entirely.)Also strips thinking/reasoning preamble text (common with local models)before JSON parsing.@@ -149,7 +153,8 @@ async def llm_json(raw = await llm_text(user_prompt=user_prompt,system_prompt=system_prompt,- max_tokens=2600, # generous budget: thinking + actual JSON+ # Floor of 2600: room for thinking + JSON, but let callers raise it.+ max_tokens=max(max_tokens, 2600),temperature=temperature,language=language,reasoning_effort=reasoning_effort,diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.pyindex 696a2673a..11f395920 100644--- a/deeptutor/book/engine.py+++ b/deeptutor/book/engine.py@@ -712,6 +712,21 @@ class BookEngine:raise ValueError(f"Cannot compile page – missing book/spine/page ({book_id}/{page_id})")if page.status == PageStatus.READY and not force:return page++ # Overview pages are built deterministically from the spine (intro,+ # concept graph, chapter index). Never run the generic LLM compiler over+ # their hand-built blocks — that would overwrite the deterministic+ # "How to read this book" intro and chapter index with hallucinated+ # prose. Reaching here means force=True or the page is not yet READY, so+ # rebuild deterministically (this also refreshes a changed spine).+ if page.content_type == ContentType.OVERVIEW:+ page.status = PageStatus.PENDING+ self.storage.save_page(page)+ await self._materialize_overview_page(spine, [page], book, stream=stream)+ page = self.storage.load_page(book_id, page_id) or page+ await self._maybe_finalize_book(book_id)+ return page+if force:self._reset_page_for_force_compile(page)self.storage.save_page(page)diff --git a/deeptutor/book/kb_health.py b/deeptutor/book/kb_health.pyindex 561adb2dc..2972777c6 100644--- a/deeptutor/book/kb_health.py+++ b/deeptutor/book/kb_health.py@@ -259,7 +259,7 @@ def scan_log_health(book_id: str, storage: BookStorage | None = None) -> LogHealif not log_path.exists():return report- counter: dict[str, int] = {}+ counter: dict[tuple[str, str], int] = {}try:with open(log_path, encoding="utf-8") as f:for line in f:@@ -277,17 +277,19 @@ def scan_log_health(book_id: str, storage: BookStorage | None = None) -> LogHealreport.last_error_at = tsif op == "block_error":report.block_failures += 1- key = f"{op}:{msg[:80]}"- counter[key] = counter.get(key, 0) + 1+ counter[(op, msg[:80])] = counter.get((op, msg[:80]), 0) + 1except OSError as exc:logger.warning(f"Could not read log {log_path}: {exc}")return report- # Only report repeated entries that are actual errors/failures.+ # Only report repeated entries whose *operation* denotes a failure. Keying+ # the failure test on the op (not the free-text message) avoids both false+ # positives (a success whose message mentions "error"/"failure") and false+ # negatives (a failure op whose message happens not to).repeated: list[dict[str, str | int]] = [- {"signature": k, "count": v}- for k, v in counter.items()- if v >= 3 and ("error" in k.lower() or "fail" in k.lower())+ {"signature": f"{op}:{msg}", "count": v}+ for (op, msg), v in counter.items()+ if v >= 3 and ("error" in op.lower() or "fail" in op.lower())]repeated.sort(key=lambda r: r["count"] if isinstance(r["count"], int) else 0, reverse=True)report.repeated_failures = repeated[:10]diff --git a/deeptutor/services/__init__.py b/deeptutor/services/__init__.pyindex 749dd2691..4529ea427 100644--- a/deeptutor/services/__init__.py+++ b/deeptutor/services/__init__.py@@ -53,7 +53,6 @@ __all__ = ["setup","session","config",- "notebook","PathService","get_path_service","BaseSessionManager",@@ -80,10 +79,6 @@ def __getattr__(name: str):return importlib.import_module(f"{__name__}.rag")if name == "embedding":return importlib.import_module(f"{__name__}.embedding")- if name == "notebook_manager":- from .notebook import notebook_manager-- return notebook_managerif name == "BaseSessionManager":from .session import BaseSessionManagerdiff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex 03f621bca..798b3f250 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -95,8 +95,7 @@ class SQLiteSessionStore:passdef _initialize(self) -> None:- with sqlite3.connect(self.db_path) as conn:- conn.execute("PRAGMA foreign_keys = ON")+ with self._connect() as conn:conn.executescript("""CREATE TABLE IF NOT EXISTS sessions (@@ -383,7 +382,9 @@ class SQLiteSessionStore:# sqlite3.Connection's own context manager commits/rolls back but does# NOT close the connection — so naked `with sqlite3.connect(...)` leaks# one FD per call until GC. Wrap it so each call site gets both- # transaction semantics and deterministic close.+ # transaction semantics and deterministic close. The inner `with conn`+ # commits on clean exit and rolls back on exception, so call sites do+ # NOT need an explicit conn.commit() (any remaining ones are no-ops).conn = sqlite3.connect(self.db_path)conn.row_factory = sqlite3.Rowconn.execute("PRAGMA foreign_keys = ON")diff --git a/deeptutor/tutorbot/channels/zulip.py b/deeptutor/tutorbot/channels/zulip.pyindex f1220b51f..5a32b17df 100644--- a/deeptutor/tutorbot/channels/zulip.py+++ b/deeptutor/tutorbot/channels/zulip.py@@ -523,13 +523,18 @@ class ZulipChannel(BaseChannel):return True# 2. Content fallback — Generic bot + Event Queue API often returns an- # empty ``flags`` array, so scan the message body for the literal- # ``@**Bot Full Name**`` mention syntax Zulip renders.+ # empty ``flags`` array, so scan the message body for the mention+ # syntax Zulip renders: ``@**Bot Full Name**`` and, when names are+ # ambiguous, the disambiguated ``@**Bot Full Name|user_id**``.if self._bot_full_name:- mention_pattern = f"@**{self._bot_full_name}**"- if mention_pattern in message.get("content", ""):- logger.debug("Zulip _is_mentioned: matched content pattern {}", mention_pattern)- return True+ content = message.get("content", "")+ patterns = [f"@**{self._bot_full_name}**"]+ if self._bot_user_id is not None:+ patterns.append(f"@**{self._bot_full_name}|{self._bot_user_id}**")+ for mention_pattern in patterns:+ if mention_pattern in content:+ logger.debug("Zulip _is_mentioned: matched content pattern {}", mention_pattern)+ return Truelogger.debug("Zulip _is_mentioned: no mention flags or content match, flags={}",diff --git a/tests/services/tutorbot/test_zulip_channel.py b/tests/services/tutorbot/test_zulip_channel.pyindex 6e2f4a902..45c6b9c79 100644--- a/tests/services/tutorbot/test_zulip_channel.py+++ b/tests/services/tutorbot/test_zulip_channel.py@@ -233,6 +233,14 @@ class TestIsMentioned:ch._bot_full_name = "DeepTutor Bot"assert ch._is_mentioned({"flags": [], "content": "no mention here"}) is False+ def test_content_fallback_disambiguated_mention(self):+ # Zulip renders @**Name|user_id** when names are ambiguous; this string+ # does not contain @**Name** as a substring, so it needs its own pattern.+ ch = _make_channel()+ ch._bot_user_id = 100+ ch._bot_full_name = "DeepTutor Bot"+ assert ch._is_mentioned({"flags": [], "content": "hi @**DeepTutor Bot|100** help"}) is True+class TestExtractUploadLinks:def test_markdown_image(self):diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsxindex f77d04d47..00ed7496d 100644--- a/web/app/(workspace)/book/components/PageReader.tsx+++ b/web/app/(workspace)/book/components/PageReader.tsx@@ -165,7 +165,7 @@ export default function PageReader({) : (<RefreshCcw className="h-3.5 w-3.5" />)}- {loading ? "Regenerating…" : "Force regenerate"}+ {loading ? t("Regenerating…") : t("Force regenerate")}</button>)}<button@@ -222,7 +222,7 @@ export default function PageReader({) : (<RefreshCcw className="h-3.5 w-3.5" />)}- {loading ? "Regenerating…" : "Regenerate page"}+ {loading ? t("Regenerating…") : t("Regenerate page")}</button>)}</div>diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex fa890c5b3..fa11203f3 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1501,6 +1501,7 @@"Collapse header": "Collapse header","Untitled chapter": "Untitled chapter","Force regenerate": "Force regenerate",+ "Regenerating…": "Regenerating…","{{count}} block failed": "{{count}} block failed","{{count}} blocks failed": "{{count}} blocks failed","Regenerate page": "Regenerate page",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 3757394fa..e0b4ca257 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1600,6 +1600,7 @@"Collapse header": "折叠标题栏","Untitled chapter": "未命名章节","Force regenerate": "强制重新生成",+ "Regenerating…": "正在重新生成…","{{count}} block failed": "{{count}} 个内容块生成失败","{{count}} blocks failed": "{{count}} 个内容块生成失败","Regenerate page": "重新生成本页",