DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(book): introduce book capability and restructure guide/co_writer modules
Bingxi Zhao (Frank)2745e8bde916
diff --git a/Dockerfile b/Dockerfileindex 4991652f5..ce079fbae 100644--- a/Dockerfile+++ b/Dockerfile@@ -161,7 +161,6 @@ RUN mkdir -p \data/user/workspace/notebook \data/user/workspace/co-writer/audio \data/user/workspace/co-writer/tool_calls \- data/user/workspace/guide \data/user/workspace/chat/chat \data/user/workspace/chat/deep_solve \data/user/workspace/chat/deep_question \diff --git a/deeptutor/agents/__init__.py b/deeptutor/agents/__init__.pyindex 63c9c1e3f..72965381b 100644--- a/deeptutor/agents/__init__.py+++ b/deeptutor/agents/__init__.py@@ -4,11 +4,14 @@ Agents Module - Unified agent system for OpenTutor.This module provides a unified BaseAgent class and module-specific agents:- solve: Question solving agents (MainSolver, SolveAgent, etc.)- research: Deep research agents (DecomposeAgent, ResearchAgent, etc.)-- guide: Guided learning agents (ChatAgent, DesignAgent, etc.)-- co_writer: Co-writing agents (EditAgent, NarratorAgent)- question: Question generation agents (ReAct architecture, separate base)- chat: Lightweight conversational agent with session management+Note: ``co_writer`` and ``book`` are independent top-level modules under+``deeptutor/`` (e.g. ``deeptutor.co_writer``, ``deeptutor.book``). They+still inherit from :class:`BaseAgent` defined here but are not part of+the ``deeptutor.agents`` package.+Usage:from deeptutor.agents.base_agent import BaseAgentdiff --git a/deeptutor/agents/base_agent.py b/deeptutor/agents/base_agent.pyindex d08de9400..128d40f25 100644--- a/deeptutor/agents/base_agent.py+++ b/deeptutor/agents/base_agent.py@@ -5,7 +5,6 @@ Unified BaseAgent - Base class for all module agents.This is the single source of truth for agent base functionality across:- solve module- research module-- guide module- co_writer module- question module (unified in Jan 2026 refactor)"""@@ -63,7 +62,7 @@ class BaseAgent(ABC):Initialize base Agent.Args:- module_name: Module name (solve/research/guide/co_writer/question)+ module_name: Module name (solve/research/co_writer/question)agent_name: Agent name (e.g., "solve_agent", "note_agent")api_key: API key (optional, defaults to environment variable)base_url: API endpoint (optional, defaults to environment variable)diff --git a/deeptutor/agents/guide/__init__.py b/deeptutor/agents/guide/__init__.pydeleted file mode 100644index 0ebd431b3..000000000--- a/deeptutor/agents/guide/__init__.py+++ /dev/null@@ -1,16 +0,0 @@-"""-Guided Learning Module-Generates personalized knowledge point learning plans based on user notebook content-"""--from .agents import ChatAgent, DesignAgent, InteractiveAgent, SummaryAgent-from .guide_manager import GuidedSession, GuideManager--__all__ = [- "ChatAgent",- "DesignAgent",- "GuideManager",- "GuidedSession",- "InteractiveAgent",- "SummaryAgent",-]diff --git a/deeptutor/agents/guide/agents/__init__.py b/deeptutor/agents/guide/agents/__init__.pydeleted file mode 100644index e6fda8cdb..000000000--- a/deeptutor/agents/guide/agents/__init__.py+++ /dev/null@@ -1,11 +0,0 @@-"""-Guided Learning Agents-Agent modules for guided learning-"""--from .chat_agent import ChatAgent-from .design_agent import DesignAgent-from .interactive_agent import InteractiveAgent-from .summary_agent import SummaryAgent--__all__ = ["ChatAgent", "DesignAgent", "InteractiveAgent", "SummaryAgent"]diff --git a/deeptutor/agents/guide/agents/chat_agent.py b/deeptutor/agents/guide/agents/chat_agent.pydeleted file mode 100644index 4c6595034..000000000--- a/deeptutor/agents/guide/agents/chat_agent.py+++ /dev/null@@ -1,116 +0,0 @@-#!/usr/bin/env python-"""-ChatAgent - Q&A Agent during learning process-Answers user questions while learning specific knowledge points-"""--from typing import Any--from deeptutor.agents.base_agent import BaseAgent---class ChatAgent(BaseAgent):- """Learning Q&A agent"""-- def __init__(- self,- api_key: str,- base_url: str,- language: str = "zh",- api_version: str | None = None,- binding: str = "openai",- ):- super().__init__(- module_name="guide",- agent_name="chat_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- binding=binding,- )-- def _format_chat_history(self, history: list[dict[str, str]]) -> str:- """Format chat history"""- if not history:- return "(No chat history)"-- formatted = []- for msg in history[-10:]:- role = msg.get("role", "user")- content = msg.get("content", "")-- if role == "user":- formatted.append(f"**User**: {content}")- elif role == "assistant":- formatted.append(f"**Assistant**: {content}")- elif role == "system":- formatted.append(f"_System: {content}_")-- return "\n\n".join(formatted)-- async def process(- self,- knowledge: dict[str, Any],- chat_history: list[dict[str, str]],- user_question: str,- current_html: str = "",- ) -> dict[str, Any]:- """- Answer user questions about current knowledge point-- Args:- knowledge: Current knowledge point information- chat_history: Chat history- user_question: User question- current_html: Current interactive page HTML-- Returns:- Dictionary containing answer- """- if not user_question.strip():- return {"success": False, "error": "Question cannot be empty", "answer": ""}-- system_prompt = self.get_prompt("system")- if not system_prompt:- raise ValueError(- "ChatAgent missing system prompt, please configure system in prompts/{lang}/chat_agent.yaml"- )-- user_template = self.get_prompt("user_template")- if not user_template:- raise ValueError(- "ChatAgent missing user_template, please configure user_template in prompts/{lang}/chat_agent.yaml"- )-- formatted_history = self._format_chat_history(chat_history)- interactive_page_context = (- current_html[:3000] if current_html else "(Interactive page is still generating or unavailable)"- )-- user_prompt = user_template.format(- knowledge_title=knowledge.get("knowledge_title", ""),- knowledge_summary=knowledge.get("knowledge_summary", ""),- user_difficulty=knowledge.get("user_difficulty", ""),- interactive_page_context=interactive_page_context,- chat_history=formatted_history,- user_question=user_question,- )-- try:- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- ):- _chunks.append(_c)- response = "".join(_chunks)-- return {"success": True, "answer": response.strip()}-- except Exception as e:- return {- "success": False,- "error": str(e),- "answer": "Sorry, an error occurred while answering the question. Please try again later.",- }diff --git a/deeptutor/agents/guide/agents/design_agent.py b/deeptutor/agents/guide/agents/design_agent.pydeleted file mode 100644index 5945a501c..000000000--- a/deeptutor/agents/guide/agents/design_agent.py+++ /dev/null@@ -1,119 +0,0 @@-#!/usr/bin/env python-"""-DesignAgent - Agent for designing guided learning plans-Generates progressive knowledge point plans from plain user input-"""--import json-from typing import Optional--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.utils.json_parser import parse_json_response---class DesignAgent(BaseAgent):- """Learning plan design agent"""-- def __init__(- self,- api_key: str,- base_url: str,- language: str = "zh",- api_version: Optional[str] = None,- binding: str = "openai",- ):- super().__init__(- module_name="guide",- agent_name="design_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- binding=binding,- )-- async def process(self, user_input: str) -> dict[str, object]:- """- Design a progressive guided learning plan from user input.-- Args:- user_input: User's learning request-- Returns:- Dictionary containing knowledge point list- """- if not user_input.strip():- return {- "success": False,- "error": "User input cannot be empty",- "knowledge_points": [],- }-- system_prompt = self.get_prompt("system")- if not system_prompt:- raise ValueError(- "DesignAgent missing system prompt, please configure system in prompts/{lang}/design_agent.yaml"- )-- user_template = self.get_prompt("user_template")- if not user_template:- raise ValueError(- "DesignAgent missing user_template, please configure user_template in prompts/{lang}/design_agent.yaml"- )-- user_prompt = user_template.format(user_input=user_input.strip())-- try:- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- ):- _chunks.append(_c)- response = "".join(_chunks)-- try:- result = parse_json_response(response, logger_instance=self.logger)-- if isinstance(result, list):- knowledge_points = result- elif isinstance(result, dict):- knowledge_points = (- result.get("knowledge_points")- or result.get("points")- or result.get("data")- or []- )- else:- knowledge_points = []-- validated_points = []- for point in knowledge_points:- if isinstance(point, dict):- validated_points.append(- {- "knowledge_title": point.get(- "knowledge_title", "Unnamed knowledge point"- ),- "knowledge_summary": point.get("knowledge_summary", ""),- "user_difficulty": point.get("user_difficulty", ""),- }- )-- return {- "success": True,- "knowledge_points": validated_points,- "total_points": len(validated_points),- }-- except json.JSONDecodeError as e:- return {- "success": False,- "error": f"JSON parsing failed: {e!s}",- "raw_response": response,- "knowledge_points": [],- }-- except Exception as e:- return {"success": False, "error": str(e), "knowledge_points": []}diff --git a/deeptutor/agents/guide/agents/interactive_agent.py b/deeptutor/agents/guide/agents/interactive_agent.pydeleted file mode 100644index 56f9be6c3..000000000--- a/deeptutor/agents/guide/agents/interactive_agent.py+++ /dev/null@@ -1,249 +0,0 @@-#!/usr/bin/env python-"""-InteractiveAgent - Agent for generating interactive HTML pages-Converts knowledge points into visual, interactive learning pages-"""--import re-from typing import Any--from deeptutor.agents.base_agent import BaseAgent---class InteractiveAgent(BaseAgent):- """Interactive page generation agent"""-- def __init__(- self,- api_key: str,- base_url: str,- language: str = "zh",- api_version: str | None = None,- binding: str = "openai",- ):- super().__init__(- module_name="guide",- agent_name="interactive_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- )-- def _extract_html(self, response: str) -> str:- """Extract HTML code from LLM response"""- html_pattern = r"```html\s*([\s\S]*?)\s*```"- match = re.search(html_pattern, response)- if match:- return match.group(1).strip()-- code_pattern = r"```\s*([\s\S]*?)\s*```"- match = re.search(code_pattern, response)- if match:- content = match.group(1).strip()- if content.startswith("<!DOCTYPE") or content.startswith("<html"):- return content-- if response.strip().startswith("<!DOCTYPE") or response.strip().startswith("<html"):- return response.strip()-- return response.strip()-- def _validate_html(self, html: str) -> bool:- """Validate if HTML is basically valid"""- return (- "<html" in html.lower()- or "<!doctype" in html.lower()- or "<body" in html.lower()- or "<div" in html.lower()- )-- def _is_retryable_error(self, error: str) -> bool:- lowered = error.lower()- return any(- marker in lowered- for marker in (- "429",- "rate limit",- "rate_limit",- "too many requests",- "resource exhausted",- "resource has been exhausted",- "quota",- )- )-- def _generate_fallback_html(self, knowledge: dict[str, Any]) -> str:- """Generate fallback HTML page"""- title = knowledge.get("knowledge_title", "Knowledge Point")- summary = knowledge.get("knowledge_summary", "").replace("\n", "<br>")- difficulty = knowledge.get("user_difficulty", "").replace("\n", "<br>")-- return f"""<!DOCTYPE html>-<html lang="zh">-<head>- <meta charset="UTF-8">- <meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>{title}</title>- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">- <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>- <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117n7w6ODWgRrA7TlVzRsFtwW3ZxUo8h4w20Z5J3d3xjfcw" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>- <style>- * {{- margin: 0;- padding: 0;- box-sizing: border-box;- }}- body {{- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;- background: linear-gradient(135deg, #F8FAFC 0%, #EFF6FF 100%);- min-height: 100vh;- padding: 2rem;- color: #1E293B;- }}- .container {{- max-width: 800px;- margin: 0 auto;- }}- .card {{- background: white;- border-radius: 16px;- padding: 2rem;- margin-bottom: 1.5rem;- box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);- transition: transform 0.2s, box-shadow 0.2s;- }}- .card:hover {{- transform: translateY(-2px);- box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1);- }}- h1 {{- color: #1E40AF;- font-size: 1.75rem;- margin-bottom: 1rem;- display: flex;- align-items: center;- gap: 0.5rem;- }}- h2 {{- color: #3B82F6;- font-size: 1.25rem;- margin-bottom: 1rem;- }}- .content {{- line-height: 1.8;- color: #475569;- }}- .difficulty {{- background: #FEF3C7;- border-left: 4px solid #F59E0B;- padding: 1rem;- border-radius: 0 8px 8px 0;- margin-top: 1rem;- }}- .difficulty h3 {{- color: #B45309;- margin-bottom: 0.5rem;- }}- </style>-</head>-<body>- <div class="container">- <div class="card">- <h1>📚 {title}</h1>- </div>- <div class="card">- <h2>Knowledge Content</h2>- <div class="content">{summary}</div>- </div>- <div class="card">- <h2>💡 Notes</h2>- <div class="difficulty">- <h3>Possible Difficulties</h3>- <p>{difficulty}</p>- </div>- </div>- </div>-</body>-</html>"""-- async def process(- self, knowledge: dict[str, Any], retry_with_bug: str | None = None- ) -> dict[str, Any]:- """- Generate interactive HTML learning page-- Args:- knowledge: Knowledge point information (knowledge_title, knowledge_summary, user_difficulty)- retry_with_bug: If provided, it's a bug fix request-- Returns:- Dictionary containing HTML code- """- system_prompt = self.get_prompt("system")- if not system_prompt:- raise ValueError(- "InteractiveAgent missing system prompt, please configure system in prompts/{lang}/interactive_agent.yaml"- )-- user_template = self.get_prompt("user_template")- if not user_template:- raise ValueError(- "InteractiveAgent missing user_template, please configure user_template in prompts/{lang}/interactive_agent.yaml"- )-- if retry_with_bug:- user_prompt = f"""The previously generated HTML page has the following issues:-{retry_with_bug}--Please fix these issues and regenerate the HTML page.--Original knowledge point information:-{user_template.format(**knowledge)}"""- else:- user_prompt = user_template.format(- knowledge_title=knowledge.get("knowledge_title", ""),- knowledge_summary=knowledge.get("knowledge_summary", ""),- user_difficulty=knowledge.get("user_difficulty", ""),- )-- try:- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- ):- _chunks.append(_c)- response = "".join(_chunks)-- html_code = self._extract_html(response)-- if not self._validate_html(html_code):- html_code = self._generate_fallback_html(knowledge)- return {- "success": True,- "html": html_code,- "is_fallback": True,- "message": "Used fallback template",- }-- return {"success": True, "html": html_code, "is_fallback": False}-- except Exception as e:- error_message = str(e)- if self._is_retryable_error(error_message):- return {- "success": False,- "retryable": True,- "error": error_message,- "html": "",- }-- html_code = self._generate_fallback_html(knowledge)- return {- "success": True,- "html": html_code,- "is_fallback": True,- "error": error_message,- "message": "Error occurred, used fallback template",- }diff --git a/deeptutor/agents/guide/agents/summary_agent.py b/deeptutor/agents/guide/agents/summary_agent.pydeleted file mode 100644index 86c2a135c..000000000--- a/deeptutor/agents/guide/agents/summary_agent.py+++ /dev/null@@ -1,152 +0,0 @@-#!/usr/bin/env python-"""-SummaryAgent - Learning Summary Generation Agent-Generates personalized learning summary reports after users complete learning-"""--from typing import Any--from deeptutor.agents.base_agent import BaseAgent---class SummaryAgent(BaseAgent):- """Learning summary agent"""-- def __init__(- self,- api_key: str,- base_url: str,- language: str = "zh",- api_version: str | None = None,- binding: str = "openai",- ):- super().__init__(- module_name="guide",- agent_name="summary_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- )-- def _format_knowledge_points(self, points: list[dict[str, Any]]) -> str:- """Format knowledge point list"""- formatted = []- for i, point in enumerate(points, 1):- formatted.append(- f"""-### Knowledge Point {i}: {point.get("knowledge_title", "Unnamed")}-**Content Summary**: {point.get("knowledge_summary", "")}-**Potential Difficulty**: {point.get("user_difficulty", "")}-"""- )- return "\n".join(formatted)-- def _format_chat_history(self, history: list[dict[str, str]]) -> str:- """Format complete chat history"""- if not history:- return "(User did not ask questions during learning)"-- formatted = []- current_knowledge = None-- for msg in history:- role = msg.get("role", "user")- content = msg.get("content", "")- knowledge_index = msg.get("knowledge_index")-- if knowledge_index is not None and knowledge_index != current_knowledge:- current_knowledge = knowledge_index- formatted.append(- f"\n--- During learning knowledge point {knowledge_index + 1} ---\n"- )-- if role == "user":- formatted.append(f"**User Question**: {content}")- elif role == "assistant":- formatted.append(f"**Assistant Answer**: {content}")- elif role == "system":- formatted.append(f"_System Message: {content}_")-- return "\n\n".join(formatted)-- async def process(- self,- notebook_name: str,- knowledge_points: list[dict[str, Any]],- chat_history: list[dict[str, str]],- ) -> dict[str, Any]:- """- Generate learning summary report-- Args:- notebook_name: Notebook name- knowledge_points: All knowledge point list- chat_history: Complete chat history-- Returns:- Dictionary containing summary report- """- system_prompt = self.get_prompt("system")- if not system_prompt:- raise ValueError(- "SummaryAgent missing system prompt, please configure system in prompts/{lang}/summary_agent.yaml"- )-- user_template = self.get_prompt("user_template")- if not user_template:- raise ValueError(- "SummaryAgent missing user_template, please configure user_template in prompts/{lang}/summary_agent.yaml"- )-- formatted_points = self._format_knowledge_points(knowledge_points)- formatted_history = self._format_chat_history(chat_history)-- user_prompt = user_template.format(- notebook_name=notebook_name,- total_points=len(knowledge_points),- all_knowledge_points=formatted_points,- full_chat_history=formatted_history,- )-- try:- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- ):- _chunks.append(_c)- response = "".join(_chunks)-- cleaned_summary = response.strip()-- import re-- markdown_pattern = r"```(?:markdown)?\s*([\s\S]*?)\s*```"- match = re.search(markdown_pattern, cleaned_summary)- if match:- cleaned_summary = match.group(1).strip()-- return {- "success": True,- "summary": cleaned_summary,- "notebook_name": notebook_name,- "total_points": len(knowledge_points),- "total_interactions": len([m for m in chat_history if m.get("role") == "user"]),- }-- except Exception as e:- return {- "success": False,- "error": str(e),- "summary": f"""# 📊 Learning Summary--Congratulations on completing learning **{notebook_name}**!--## Learning Overview-- Learned {len(knowledge_points)} knowledge points-- Had {len([m for m in chat_history if m.get("role") == "user"])} interactions during learning--Thank you for your hard work! Keep up this learning enthusiasm! 🎉-""",- }diff --git a/deeptutor/agents/guide/guide_manager.py b/deeptutor/agents/guide/guide_manager.pydeleted file mode 100644index eb319fb2f..000000000--- a/deeptutor/agents/guide/guide_manager.py+++ /dev/null@@ -1,753 +0,0 @@-#!/usr/bin/env python-"""-GuideManager - Guided Learning Session Manager-Manages the complete lifecycle of learning sessions-"""--import asyncio-from dataclasses import asdict, dataclass, field-import json-from pathlib import Path-import time-from typing import Any-import uuid--import yaml--from deeptutor.logging import get_logger-from deeptutor.services.config import load_config_with_main, parse_language-from deeptutor.services.path_service import get_path_service--from .agents import ChatAgent, DesignAgent, InteractiveAgent, SummaryAgent---@dataclass-class GuidedSession:- """Guided learning session"""-- session_id: str- notebook_id: str- notebook_name: str- created_at: float- knowledge_points: list[dict[str, Any]] = field(default_factory=list)- current_index: int = -1- chat_history: list[dict[str, Any]] = field(default_factory=list)- status: str = "initialized" # initialized, learning, completed- html_pages: dict[str, str] = field(default_factory=dict)- page_statuses: dict[str, str] = field(default_factory=dict)- page_errors: dict[str, str] = field(default_factory=dict)- summary: str = ""- notebook_context: str = ""-- def to_dict(self) -> dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> "GuidedSession":- session_data = dict(data)-- current_html = str(session_data.pop("current_html", "") or "")- current_index = int(session_data.get("current_index", -1))- html_pages = dict(session_data.get("html_pages") or {})- page_statuses = dict(session_data.get("page_statuses") or {})- page_errors = dict(session_data.get("page_errors") or {})-- if current_html and not html_pages and current_index >= 0:- html_pages[str(current_index)] = current_html- page_statuses[str(current_index)] = "ready"-- session_data.setdefault("current_index", current_index)- session_data.setdefault("chat_history", [])- session_data.setdefault("status", "initialized")- session_data.setdefault("summary", "")- session_data["html_pages"] = html_pages- session_data["page_statuses"] = page_statuses- session_data["page_errors"] = page_errors- return cls(**session_data)---class GuideManager:- """Guided learning manager"""-- def __init__(- self,- api_key: str,- base_url: str,- api_version: str | None = None,- language: str | None = None,- output_dir: str | None = None,- config_path: str | None = None,- binding: str = "openai",- ):- """- Initialize manager-- Args:- api_key: API key- base_url: API endpoint- api_version: API version (for Azure OpenAI)- language: Language setting (if None, read from config file)- output_dir: Output directory- config_path: Configuration file path (if None, use default path)- binding: LLM provider binding- """- self.api_key = api_key- self.base_url = base_url- self.api_version = api_version- self.binding = binding-- if config_path is None:- from deeptutor.services.config import PROJECT_ROOT-- config = load_config_with_main("main.yaml", PROJECT_ROOT)- else:- config_path = Path(config_path)- if config_path.exists():- try:- with open(config_path, encoding="utf-8") as f:- config = yaml.safe_load(f) or {}- except Exception:- config = {}- else:- config = {}-- # Initialize logger (from config)- log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(- "log_dir"- )- self.logger = get_logger("Guide", log_dir=log_dir)-- if language is None:- # Get language config (unified in config/main.yaml system.language)- lang_config = config.get("system", {}).get("language", "zh")- self.language = parse_language(lang_config)- self.logger.info(f"Language setting loaded from config: {self.language}")- else:- # If explicitly specified, also parse it to ensure consistency- self.language = parse_language(language)- self.logger.info(f"Using explicitly specified language setting: {self.language}")-- if output_dir:- self.output_dir = Path(output_dir)- else:- # Get output_dir from config (already loaded above)- output_dir_from_config = config.get("system", {}).get("output_dir")- if output_dir_from_config:- self.output_dir = Path(output_dir_from_config)- else:- # Fallback to default path using PathService- path_service = get_path_service()- self.output_dir = path_service.get_guide_dir()- self.output_dir.mkdir(parents=True, exist_ok=True)-- self.design_agent = DesignAgent(- api_key,- base_url,- language=self.language,- api_version=self.api_version,- binding=self.binding,- )- self.interactive_agent = InteractiveAgent(- api_key,- base_url,- language=self.language,- api_version=self.api_version,- binding=self.binding,- )- self.chat_agent = ChatAgent(- api_key,- base_url,- language=self.language,- api_version=self.api_version,- binding=self.binding,- )- self.summary_agent = SummaryAgent(- api_key,- base_url,- language=self.language,- api_version=self.api_version,- binding=self.binding,- )-- self._sessions: dict[str, GuidedSession] = {}- self._generation_tasks: dict[str, asyncio.Task[None]] = {}- self.max_parallel_generations = 2-- def _get_session_file(self, session_id: str) -> Path:- """Get session file path"""- return self.output_dir / f"session_{session_id}.json"-- def _save_session(self, session: GuidedSession):- """Save session to file"""- filepath = self._get_session_file(session.session_id)- with open(filepath, "w", encoding="utf-8") as f:- json.dump(session.to_dict(), f, indent=2, ensure_ascii=False)- self._sessions[session.session_id] = session-- def _delete_session(self, session_id: str):- """Delete a session from memory and disk."""- self._sessions.pop(session_id, None)- filepath = self._get_session_file(session_id)- if filepath.exists():- filepath.unlink()-- def _load_session(self, session_id: str) -> GuidedSession | None:- """Load session from file"""- if session_id in self._sessions:- return self._sessions[session_id]-- filepath = self._get_session_file(session_id)- if filepath.exists():- with open(filepath, encoding="utf-8") as f:- data = json.load(f)- session = GuidedSession.from_dict(data)- self._sessions[session_id] = session- return session- return None-- def _initialize_page_statuses(self, session: GuidedSession):- """Ensure every knowledge point has an initial page status."""- for index, _knowledge in enumerate(session.knowledge_points):- key = str(index)- session.page_statuses.setdefault(key, "pending")- session.page_errors.setdefault(key, "")-- def _count_ready_pages(self, session: GuidedSession) -> int:- return sum(1 for status in session.page_statuses.values() if status == "ready")-- def _calculate_progress(self, session: GuidedSession) -> int:- total_points = len(session.knowledge_points)- if total_points == 0:- return 0- return int((self._count_ready_pages(session) / total_points) * 100)-- def _has_active_generation_task(self, session_id: str) -> bool:- task = self._generation_tasks.get(session_id)- return bool(task and not task.done())-- def _clear_generation_task(self, session_id: str):- task = self._generation_tasks.pop(session_id, None)- if task and not task.done():- task.cancel()-- async def _generate_single_page(self, session_id: str, knowledge_index: int) -> dict[str, Any]:- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- if knowledge_index < 0 or knowledge_index >= len(session.knowledge_points):- return {"success": False, "error": "Knowledge point does not exist"}-- key = str(knowledge_index)- knowledge = session.knowledge_points[knowledge_index]- session.page_statuses[key] = "generating"- session.page_errors[key] = ""- self._save_session(session)-- result = await self.interactive_agent.process(knowledge=knowledge)- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- if result.get("success"):- html = result.get("html", "")- if html:- session.html_pages[key] = html- session.page_statuses[key] = "ready"- session.page_errors[key] = result.get("error", "")- self._save_session(session)- return result-- retryable = bool(result.get("retryable"))- session.page_statuses[key] = "pending" if retryable else "failed"- session.page_errors[key] = result.get("error", "Failed to generate page")- self._save_session(session)- return result-- async def _generate_all_pages_background(- self, session_id: str, indices: list[int] | None = None- ) -> None:- session = self._load_session(session_id)- if not session:- return-- if indices is None:- page_indices = list(range(len(session.knowledge_points)))- else:- page_indices = sorted({index for index in indices if 0 <= index < len(session.knowledge_points)})-- if not page_indices:- return-- queue: asyncio.PriorityQueue[tuple[int, int]] = asyncio.PriorityQueue()- for index in page_indices:- await queue.put((index, 0))-- shared_state = {"backoff_until": 0.0}-- async def worker():- while True:- index, attempt = await queue.get()- try:- delay = shared_state["backoff_until"] - time.time()- if delay > 0:- await asyncio.sleep(delay)-- result = await self._generate_single_page(session_id, index)- if result.get("retryable") and attempt < 2:- backoff_seconds = 2**attempt- shared_state["backoff_until"] = max(- shared_state["backoff_until"], time.time() + backoff_seconds- )- await queue.put((index, attempt + 1))- elif result.get("retryable"):- failed_session = self._load_session(session_id)- if failed_session:- key = str(index)- failed_session.page_statuses[key] = "failed"- failed_session.page_errors[key] = result.get(- "error", "Failed after retries"- )- self._save_session(failed_session)- finally:- queue.task_done()-- workers = [- asyncio.create_task(worker()) for _ in range(min(self.max_parallel_generations, len(page_indices)))- ]-- try:- await queue.join()- finally:- for worker_task in workers:- worker_task.cancel()- await asyncio.gather(*workers, return_exceptions=True)-- def _schedule_generation_task(self, session_id: str, indices: list[int] | None = None):- if self._has_active_generation_task(session_id):- return-- task = asyncio.create_task(self._generate_all_pages_background(session_id, indices))- self._generation_tasks[session_id] = task-- def _cleanup(_task: asyncio.Task[None]):- self._generation_tasks.pop(session_id, None)-- task.add_done_callback(_cleanup)-- async def create_session(- self,- user_input: str,- display_title: str | None = None,- notebook_context: str = "",- ) -> dict[str, Any]:- """- Create new learning session-- Args:- user_input: User's learning request-- Returns:- Session creation result- """- if not user_input.strip():- return {- "success": False,- "error": "User input cannot be empty",- "session_id": None,- }-- session_id = str(uuid.uuid4())[:8]-- design_result = await self.design_agent.process(user_input=user_input)-- if not design_result.get("success"):- return {- "success": False,- "error": design_result.get("error", "Failed to design learning plan"),- "session_id": None,- }-- knowledge_points = design_result.get("knowledge_points", [])-- if not knowledge_points:- return {- "success": False,- "error": "No knowledge points identified from user input",- "session_id": None,- }-- session_title = (display_title or user_input).strip().replace("\n", " ")[:50]-- session = GuidedSession(- session_id=session_id,- notebook_id="user_input",- notebook_name=session_title or "Guided Learning",- created_at=time.time(),- knowledge_points=knowledge_points,- current_index=-1,- status="initialized",- notebook_context=notebook_context,- )- self._initialize_page_statuses(session)-- self._save_session(session)-- return {- "success": True,- "session_id": session_id,- "knowledge_points": knowledge_points,- "total_points": len(knowledge_points),- "message": f"Learning plan created with {len(knowledge_points)} knowledge points",- }-- def _get_learning_state(- self, knowledge_points: list[dict[str, Any]], current_index: int- ) -> dict[str, Any]:- """- Get learning state information (internal helper method)-- Args:- knowledge_points: Knowledge point list- current_index: Current knowledge point index-- Returns:- Learning state information- """- total_points = len(knowledge_points)-- if total_points == 0:- return {"success": False, "error": "No knowledge points to learn", "status": "empty"}-- if current_index >= total_points:- return {- "success": True,- "current_index": current_index,- "current_knowledge": None,- "status": "completed",- "progress_percentage": 100,- "total_points": total_points,- "message": "🎉 Congratulations! You have completed learning all knowledge points!",- }-- current_knowledge = knowledge_points[current_index]- progress = int((current_index / total_points) * 100)-- message = f"📚 Starting to learn knowledge point {current_index + 1}: {current_knowledge.get('knowledge_title', '')}"-- return {- "success": True,- "current_index": current_index,- "current_knowledge": current_knowledge,- "status": "learning",- "progress_percentage": progress,- "total_points": total_points,- "remaining_points": total_points - current_index - 1,- "message": message,- }-- async def start_learning(self, session_id: str) -> dict[str, Any]:- """- Start learning the first knowledge point-- Args:- session_id: Session ID-- Returns:- First knowledge point information and interactive page- """- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- session.current_index = 0- session.status = "learning"- self._initialize_page_statuses(session)-- session.chat_history.append(- {- "role": "system",- "content": "Started guided learning. Interactive pages are now generating in parallel.",- "knowledge_index": 0,- "timestamp": time.time(),- }- )-- self._save_session(session)- self._schedule_generation_task(session_id)-- return {- "success": True,- "current_index": 0,- "current_knowledge": session.knowledge_points[0] if session.knowledge_points else None,- "html": session.html_pages.get("0", ""),- "page_statuses": session.page_statuses,- "progress": self._calculate_progress(session),- "total_points": len(session.knowledge_points),- "message": "Interactive pages are generating in parallel. Open any page as soon as it is ready.",- }-- async def navigate_to_knowledge(self, session_id: str, knowledge_index: int) -> dict[str, Any]:- """Navigate to any knowledge point."""- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- if knowledge_index < 0 or knowledge_index >= len(session.knowledge_points):- return {"success": False, "error": "Knowledge point does not exist"}-- self._initialize_page_statuses(session)- session.current_index = knowledge_index- self._save_session(session)-- if not self._has_active_generation_task(session_id):- pending_indices = [- index- for index, _knowledge in enumerate(session.knowledge_points)- if session.page_statuses.get(str(index)) in {"pending", "generating"}- ]- if pending_indices:- self._schedule_generation_task(session_id, pending_indices)-- key = str(knowledge_index)- return {- "success": True,- "current_index": knowledge_index,- "current_knowledge": session.knowledge_points[knowledge_index],- "html": session.html_pages.get(key, ""),- "page_status": session.page_statuses.get(key, "pending"),- "page_error": session.page_errors.get(key, ""),- "progress": self._calculate_progress(session),- "total_points": len(session.knowledge_points),- "message": f"Viewing knowledge point {knowledge_index + 1}.",- }-- async def complete_learning(self, session_id: str) -> dict[str, Any]:- """Generate the final learning summary."""- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- summary_result = await self.summary_agent.process(- notebook_name=session.notebook_name,- knowledge_points=session.knowledge_points,- chat_history=session.chat_history,- )-- session.status = "completed"- session.summary = summary_result.get("summary", "")- session.chat_history.append(- {- "role": "system",- "content": "Congratulations on completing guided learning!",- "timestamp": time.time(),- }- )- self._save_session(session)-- return {- "success": True,- "status": "completed",- "summary": session.summary,- "progress": 100,- "message": "Guided learning completed.",- }-- async def chat(- self, session_id: str, user_message: str, knowledge_index: int | None = None- ) -> dict[str, Any]:- """- Process user chat message-- Args:- session_id: Session ID- user_message: User message-- Returns:- Assistant's answer- """- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- if session.status != "learning":- return {"success": False, "error": "Not currently in learning state"}-- current_index = session.current_index if knowledge_index is None else knowledge_index- if current_index < 0 or current_index >= len(session.knowledge_points):- return {"success": False, "error": "Knowledge point does not exist"}-- current_knowledge = session.knowledge_points[current_index]- current_html = session.html_pages.get(str(current_index), "")-- current_history = [- msg- for msg in session.chat_history- if msg.get("knowledge_index") == current_index- ]-- user_msg = {- "role": "user",- "content": user_message,- "knowledge_index": current_index,- "timestamp": time.time(),- }- session.chat_history.append(user_msg)-- chat_result = await self.chat_agent.process(- knowledge=current_knowledge,- chat_history=current_history,- user_question=user_message,- current_html=current_html,- )-- assistant_msg = {- "role": "assistant",- "content": chat_result.get("answer", ""),- "knowledge_index": current_index,- "timestamp": time.time(),- }- session.chat_history.append(assistant_msg)-- self._save_session(session)-- return {- "success": True,- "answer": chat_result.get("answer", ""),- "knowledge_index": current_index,- }-- async def fix_html(self, session_id: str, bug_description: str) -> dict[str, Any]:- """- Fix HTML page bug-- Args:- session_id: Session ID- bug_description: Bug description-- Returns:- Fixed HTML- """- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- if session.current_index < 0:- return {"success": False, "error": "No active knowledge point selected"}-- current_knowledge = session.knowledge_points[session.current_index]-- result = await self.interactive_agent.process(- knowledge=current_knowledge, retry_with_bug=bug_description- )-- if result.get("success"):- session.html_pages[str(session.current_index)] = result.get("html", "")- session.page_statuses[str(session.current_index)] = "ready"- self._save_session(session)-- return result-- def get_session(self, session_id: str) -> dict[str, Any] | None:- """Get session information"""- session = self._load_session(session_id)- if session:- self._initialize_page_statuses(session)- self._save_session(session)- return session.to_dict()- return None-- def get_session_pages(self, session_id: str) -> dict[str, Any] | None:- """Get page generation status for a session."""- session = self._load_session(session_id)- if not session:- return None-- self._initialize_page_statuses(session)- if session.status == "learning" and not self._has_active_generation_task(session_id):- pending_indices = [- index- for index, _knowledge in enumerate(session.knowledge_points)- if session.page_statuses.get(str(index)) in {"pending", "generating"}- ]- if pending_indices:- self._schedule_generation_task(session_id, pending_indices)-- return {- "session_id": session.session_id,- "current_index": session.current_index,- "status": session.status,- "page_statuses": session.page_statuses,- "page_errors": session.page_errors,- "html_pages": session.html_pages,- "progress": self._calculate_progress(session),- "total_points": len(session.knowledge_points),- }-- def get_current_html(self, session_id: str) -> str | None:- """Get current HTML page"""- session = self._load_session(session_id)- if not session or session.current_index < 0:- return None- return session.html_pages.get(str(session.current_index))-- async def retry_page(self, session_id: str, page_index: int) -> dict[str, Any]:- """Retry a failed or pending page generation."""- session = self._load_session(session_id)- if not session:- return {"success": False, "error": "Session does not exist"}-- if page_index < 0 or page_index >= len(session.knowledge_points):- return {"success": False, "error": "Knowledge point does not exist"}-- key = str(page_index)- session.page_statuses[key] = "pending"- session.page_errors[key] = ""- self._save_session(session)- self._schedule_generation_task(session_id, [page_index])-- return {- "success": True,- "page_index": page_index,- "page_status": session.page_statuses.get(key, "pending"),- "message": f"Retrying knowledge point {page_index + 1}.",- }-- def list_sessions(self) -> list[dict[str, Any]]:- """List all sessions with summary metadata (no html_pages / chat_history)."""- summaries: list[dict[str, Any]] = []- for filepath in self.output_dir.glob("session_*.json"):- try:- with open(filepath, encoding="utf-8") as f:- data = json.load(f)- page_statuses = data.get("page_statuses") or {}- ready_count = sum(1 for v in page_statuses.values() if v == "ready")- total_points = len(data.get("knowledge_points") or [])- progress = int((ready_count / total_points) * 100) if total_points else 0- summaries.append(- {- "session_id": data.get("session_id", ""),- "topic": data.get("notebook_name", ""),- "status": data.get("status", "initialized"),- "created_at": data.get("created_at", 0),- "total_points": total_points,- "ready_count": ready_count,- "progress": progress,- }- )- except Exception:- continue- summaries.sort(key=lambda s: s["created_at"], reverse=True)- return summaries-- async def reset_session(self, session_id: str) -> dict[str, Any]:- """Detach from a session (cancel tasks, clear cache, but keep the file for history)."""- self._clear_generation_task(session_id)- self._sessions.pop(session_id, None)- return {"success": True, "message": "Session reset"}-- async def delete_session(self, session_id: str) -> dict[str, Any]:- """Permanently delete a session from memory and disk."""- self._clear_generation_task(session_id)- self._delete_session(session_id)- return {"success": True, "message": "Session deleted"}diff --git a/deeptutor/agents/guide/prompts/en/chat_agent.yaml b/deeptutor/agents/guide/prompts/en/chat_agent.yamldeleted file mode 100644index 9ba8d5b75..000000000--- a/deeptutor/agents/guide/prompts/en/chat_agent.yaml+++ /dev/null@@ -1,45 +0,0 @@-system: |- # Role Positioning- You are an **Intelligent Learning Assistant**. Your responsibility is to answer users' questions, resolve their doubts, and provide additional explanations and examples while they are learning specific knowledge points.-- # Core Principles- 1. **Focus on Current Knowledge Point**: Answers should revolve around the knowledge point the user is currently learning- 2. **Progressive**: Provide explanations at an appropriate level based on the depth of the user's questions- 3. **Encourage Thinking**: While directly providing answers, guide users to think- 4. **Address Difficulties**: Consider potential difficulties users may have and proactively provide relevant clarifications-- # Answer Style- - Use clear, easy-to-understand language- - Use examples and analogies appropriately- - For complex concepts, explain step by step- - Use Markdown format to enhance readability- - Maintain a friendly, encouraging tone-- # Output Format- Directly output answers in Markdown format, with clear structure and highlighted key points.--user_template: |- ## Currently Learning Knowledge Point- **Title**: {knowledge_title}-- **Content Summary**:- {knowledge_summary}-- **User's Potential Difficulties**:- {user_difficulty}-- ## Current Interactive Page Context- {interactive_page_context}-- ## Conversation History- {chat_history}-- ## User's Current Question- {user_question}-- ## Task- Please answer the user's question based on the content of the current knowledge point and context.- - Ensure the answer is relevant to the current knowledge point- - If the question refers to the current interactive page, include its structure, content, visuals, or behavior in your answer- - If the question involves the user's potential difficulties, give special attention- - The answer should be clear and well-organizeddiff --git a/deeptutor/agents/guide/prompts/en/design_agent.yaml b/deeptutor/agents/guide/prompts/en/design_agent.yamldeleted file mode 100644index 7d051ac45..000000000--- a/deeptutor/agents/guide/prompts/en/design_agent.yaml+++ /dev/null@@ -1,19 +0,0 @@-system: |- You are a learning plan designer. Given a user's learning request, design a progressive guided learning plan.-- Output a JSON object with key `knowledge_points`. Each item must include:- - knowledge_title: a concise title- - knowledge_summary: a thorough explanation of concepts, principles, methods, formulas, examples, or applications- - user_difficulty: realistic difficulties, misconceptions, or sticking points a learner may face-- Requirements:- - Arrange points from foundational to advanced- - Prefer fewer, richer points, usually 2-5 knowledge points- - Make each point a meaningful learning unit- - Stay close to the user's actual request instead of expanding too broadly--user_template: |- User's learning request:- {user_input}-- Design a progressive learning plan and return it as JSON.diff --git a/deeptutor/agents/guide/prompts/en/interactive_agent.yaml b/deeptutor/agents/guide/prompts/en/interactive_agent.yamldeleted file mode 100644index dbea00fd4..000000000--- a/deeptutor/agents/guide/prompts/en/interactive_agent.yaml+++ /dev/null@@ -1,28 +0,0 @@-system: |- You are an interactive learning page designer. Turn a knowledge point into a single self-contained HTML file that teaches the concept through visuals and interaction.-- Technical constraints:- - Output a complete standalone HTML file from DOCTYPE through </html>- - Put all CSS in <style> and all JavaScript in a <script> tag before </body>- - Do not rely on external CDNs, fonts, or other resources- - The page will run inside an iframe, so it must be responsive: use max-width: 100%, box-sizing: border-box, and avoid fixed widths- - Handle long content safely, using overflow-x: auto when needed, and avoid clipping expanded content- - Wrap interactive JavaScript in DOMContentLoaded and use addEventListener instead of inline handlers- - Check that DOM elements exist before using them- - KaTeX is injected by the host page, so use $...$ for inline math and $$...$$ for block math-- Design freely. Choose the layout, colors, visual style, and interaction patterns that best fit the knowledge content. The result should be clear, beautiful, and educational.-- Output raw HTML only, with no markdown fences or explanation.--user_template: |- Knowledge point title:- {knowledge_title}-- Knowledge content:- {knowledge_summary}-- Learner's likely difficulties:- {user_difficulty}-- Generate an interactive HTML learning page for this knowledge point.diff --git a/deeptutor/agents/guide/prompts/en/summary_agent.yaml b/deeptutor/agents/guide/prompts/en/summary_agent.yamldeleted file mode 100644index 5348e6d91..000000000--- a/deeptutor/agents/guide/prompts/en/summary_agent.yaml+++ /dev/null@@ -1,157 +0,0 @@-system: |- # Role Positioning- You are a **Learning Summary Expert**. Your responsibility is to generate a comprehensive, specific, and personalized learning summary report after users complete a round of guided learning.-- # Core Principles- 1. **Concretization First**: All analysis must be based on actual learning data, citing specific knowledge points, specific questions, and specific interaction content- 2. **Data-Driven**: Analyze based on users' actual questions and interaction situations, avoid generalizations- 3. **Personalization**: Provide personalized analysis based on users' learning characteristics, difficulties, and interaction patterns- 4. **Actionability**: All suggestions must be specific and executable, avoid using vague expressions-- # Summary Dimensions (Must Be Specific)- 1. **Learning Content Review**:- - Must list the specific title of each knowledge point- - Briefly explain the core content of each knowledge point (1-2 sentences)- - Explain the progressive relationship between knowledge points- - Don't just say "learned X knowledge points", specifically list each knowledge point-- 2. **Learning Process Analysis**:- - Must cite users' specific questions (if users have asked questions)- - Analyze the frequency, depth, and focus of users' questions- - Identify users' learning patterns (active questioning type/passive acceptance type/deep exploration type, etc.)- - If users haven't asked questions, explain users' learning approach and analyze possible reasons- - Don't use vague expressions like "users asked several questions", specifically explain the question content-- 3. **Mastery Assessment**:- - Based on users' specific question content, assess the understanding level of each knowledge point- - If users asked questions about a certain knowledge point, explain the type of question (concept understanding/application practice/deep exploration, etc.)- - Identify users' potential weak areas (based on question content or knowledge points without questions)- - Don't use vague evaluations like "good mastery", specifically explain the evidence of mastery-- 4. **Improvement Suggestions**:- - Provide suggestions for users' specific weak areas- - Suggestions must be specific and actionable, don't use vague suggestions like "practice more", "think more"- - Can suggest specific review priorities, expansion directions, practice methods- - If users asked few questions, can suggest how to learn more actively-- # Report Style- - Write as a mentor, with a friendly and professional tone- - Use encouraging language, affirm users' learning efforts- - Provide specific, actionable suggestions- - Use Markdown format with clear structure- - **Important**: Directly output Markdown content, don't wrap it in code blocks (```markdown)- - **Important**: Output pure Markdown text, don't add any markdown markers or explanations- - **Important**: All analysis must be specific, cite actual learning data, avoid vague expressions-- # Report Structure (Must Include Specific Content)- ```markdown- # 📊 Learning Summary Report-- ## 🎯 Learning Overview- [Specifically explain: which knowledge points were learned, learning duration/interaction count, overall learning characteristics]-- For example:- - This learning session covered 3 knowledge points: XXX, XXX, XXX- - During the learning process, you asked X questions, mainly focused on XXX aspects- - Your learning approach shows XXX characteristics-- ## 📚 Knowledge Point Review- [Review one by one, each knowledge point must be specifically explained]-- ### Knowledge Point 1: XXX- - Core Content: [Specifically explain the core content of this knowledge point]- - Learning Situation: [Based on interaction situation, explain your learning performance on this knowledge point]-- ### Knowledge Point 2: XXX- - Core Content: [Specifically explain]- - Learning Situation: [Specifically analyze]-- ## 💬 Learning Interaction Analysis- [Must cite specific question content, specifically analyze]-- - Question Frequency: [Specific numbers and distribution]- - Question Characteristics: [Analyze based on specific question content, e.g., "You focus on concept understanding or practical application"]- - Specific Question Review: [List 1-2 typical questions, explain what these questions reflect]- - Learning Pattern: [Based on interaction situation, determine user's learning pattern]-- ## 📈 Mastery Assessment- [Based on specific data, specifically assess each knowledge point]-- - Knowledge Point 1: XXX- - Mastery Evidence: [Specifically explain, e.g., "You asked a question about XXX, indicating you understood..."]- - Weak Areas: [If any, specifically explain]-- - Knowledge Point 2: XXX- - Mastery Evidence: [Specifically explain]- - Weak Areas: [If any, specifically explain]-- ## 🚀 Follow-up Learning Suggestions- [Must be specific and actionable]-- - Review Priorities: [Specifically list knowledge points or concepts that need focused review]- - Expansion Directions: [Specifically suggest what related content can be learned]- - Practice Suggestions: [Specifically suggest how to practice and apply]- - Learning Methods: [Based on your learning characteristics, provide specific learning method suggestions]-- ## 🌟 Conclusion- [Encouraging closing remarks, can summarize the highlights of this learning session]- ```-- # Output Requirements- - All analysis must be based on the provided actual data (knowledge points, conversation history)- - Must cite specific knowledge point titles, specific question content- - Avoid using vague evaluations like "very good", "not bad", "needs strengthening"- - Use specific data, specific examples, specific suggestions- - If users haven't asked questions, analyze the reasons and provide specific suggestions- - Directly output Markdown format text content, don't wrap in code blocks--user_template: |- ## Learning Plan Overview- Notebook Name: {notebook_name}- Number of Knowledge Points: {total_points}-- ## All Knowledge Points- {all_knowledge_points}-- ## Complete Conversation History- {full_chat_history}-- ## Task- Please generate a **specific and detailed** learning summary report based on the above **actual learning data**.-- ### Requirements (Must Strictly Follow):-- 1. **Concretize All Content**:- - Must list the specific title and core content of each knowledge point- - Must cite users' specific questions (if any)- - Must analyze based on actual interaction situations- - Don't use vague expressions like "learned several knowledge points"-- 2. **Data-Driven Analysis**:- - Count the number and distribution of users' questions (which knowledge points have more questions)- - Analyze the types of users' questions (concept understanding/application/deep exploration)- - Judge users' understanding level based on question content- - If users haven't asked questions, analyze possible reasons (quick understanding/needs guidance, etc.)-- 3. **Personalized Assessment**:- - For each knowledge point, provide specific assessment based on actual interaction situations- - Identify users' specific weak areas (if any)- - Explain the basis of assessment (e.g., "You asked a question about XXX, indicating you understood...")-- 4. **Actionable Suggestions**:- - Suggestions must be specific, don't use vague expressions like "practice more", "think more"- - Can suggest specific review priorities, expansion directions, practice methods- - Provide personalized learning method suggestions based on users' learning characteristics-- 5. **Cite Actual Data**:- - Cite specific knowledge point titles in the report- - Cite users' specific questions (if any)- - Use specific numbers (question count, number of knowledge points, etc.)- - Avoid vague expressions-- **Output Format Requirements**:- - Directly output Markdown format text content- - Don't wrap in ```markdown or ``` code blocks- - Don't add any explanations or descriptive text- - Directly output renderable Markdown content- - Ensure all content is specific and based on actual datadiff --git a/deeptutor/agents/guide/prompts/zh/chat_agent.yaml b/deeptutor/agents/guide/prompts/zh/chat_agent.yamldeleted file mode 100644index 4884ab16e..000000000--- a/deeptutor/agents/guide/prompts/zh/chat_agent.yaml+++ /dev/null@@ -1,45 +0,0 @@-system: |- # 角色定位- 你是一位**智能学习助教 (Learning Assistant)**。你的职责是在用户学习特定知识点的过程中,回答他们的问题,解答疑惑,提供额外的解释和例子。-- # 核心原则- 1. **聚焦当前知识点**:回答应该围绕用户正在学习的知识点展开- 2. **循序渐进**:根据用户的问题深度,提供适当级别的解释- 3. **鼓励思考**:在直接给出答案的同时,引导用户思考- 4. **关联困难**:考虑用户可能存在的困难点,主动提供相关澄清-- # 回答风格- - 使用清晰、易懂的语言- - 适当使用例子和类比- - 对于复杂概念,分步骤解释- - 使用Markdown格式增强可读性- - 保持友好、鼓励的语气-- # 输出格式- 直接输出Markdown格式的回答,结构清晰,重点突出。--user_template: |- ## 当前学习的知识点- **标题**: {knowledge_title}-- **内容摘要**:- {knowledge_summary}-- **用户可能的困难**:- {user_difficulty}-- ## 当前交互页面上下文- {interactive_page_context}-- ## 对话历史- {chat_history}-- ## 用户当前问题- {user_question}-- ## 任务- 请根据当前知识点的内容和上下文,回答用户的问题。- - 确保回答与当前知识点相关- - 如果问题和当前交互页面的结构、内容、视觉元素或交互行为有关,也要结合页面上下文回答- - 如果问题涉及到用户可能的困难点,给予特别关注- - 回答应该清晰、有条理diff --git a/deeptutor/agents/guide/prompts/zh/design_agent.yaml b/deeptutor/agents/guide/prompts/zh/design_agent.yamldeleted file mode 100644index 86b3633e5..000000000--- a/deeptutor/agents/guide/prompts/zh/design_agent.yaml+++ /dev/null@@ -1,19 +0,0 @@-system: |- 你是一位学习路径设计师。给定用户的一段学习需求,请设计一套循序渐进的学习计划。-- 输出一个 JSON 对象,包含键 `knowledge_points`,每个知识点都必须包含:- - knowledge_title:简洁明确的标题- - knowledge_summary:完整讲清核心概念、原理、方法、公式、例子或应用场景- - user_difficulty:学习者可能遇到的真实困难、误区或卡点-- 设计要求:- - 按照从基础到进阶的顺序组织知识点- - 优先少而精,通常设计 2-5 个知识点- - 每个知识点都应是独立且有价值的学习单元- - 内容要贴近用户需求,不要空泛展开--user_template: |- 用户的学习需求:- {user_input}-- 请据此设计一套渐进式学习计划,并以 JSON 输出。diff --git a/deeptutor/agents/guide/prompts/zh/interactive_agent.yaml b/deeptutor/agents/guide/prompts/zh/interactive_agent.yamldeleted file mode 100644index 5bb9abe84..000000000--- a/deeptutor/agents/guide/prompts/zh/interactive_agent.yaml+++ /dev/null@@ -1,28 +0,0 @@-system: |- 你是一位交互式学习页面设计师。请把一个知识点转化为单文件、可独立运行的 HTML 学习页面,让用户能通过视觉化与交互理解内容。-- 技术约束:- - 直接输出完整 HTML 文件(从 DOCTYPE 到 </html>)- - 所有 CSS 写在 <style> 中,所有 JavaScript 写在 </body> 前的 <script> 中- - 不依赖外部 CDN、字体或其他资源- - 页面会渲染在 iframe 中,必须响应式适配:使用 max-width: 100%、box-sizing: border-box,避免固定宽度- - 需要处理长内容溢出,必要时使用 overflow-x: auto,并避免让展开内容被截断- - 所有交互都必须包在 DOMContentLoaded 中,并使用 addEventListener,禁止 onclick- - 在操作 DOM 前检查元素是否存在- - KaTeX 会由宿主页面自动注入;行内公式用 $...$,块级公式用 $$...$$-- 你可以自由决定布局、配色、视觉风格和交互形式,只要它适合当前知识内容,且页面清晰、美观、易学。-- 只输出原始 HTML,不要输出 Markdown 标记或解释。--user_template: |- 知识点标题:- {knowledge_title}-- 知识内容:- {knowledge_summary}-- 学习者可能遇到的困难:- {user_difficulty}-- 请基于以上内容生成一个可交互的 HTML 学习页面。diff --git a/deeptutor/agents/guide/prompts/zh/summary_agent.yaml b/deeptutor/agents/guide/prompts/zh/summary_agent.yamldeleted file mode 100644index 5bd17e57e..000000000--- a/deeptutor/agents/guide/prompts/zh/summary_agent.yaml+++ /dev/null@@ -1,157 +0,0 @@-system: |- # 角色定位- 你是一位**学习总结专家 (Learning Summary Expert)**。你的职责是在用户完成一轮引导式学习后,生成一份全面、具体、个性化的学习总结报告。-- # 核心原则- 1. **具体化优先**:所有分析必须基于实际的学习数据,引用具体的知识点、具体的问题、具体的互动内容- 2. **数据驱动**:基于用户的实际提问和互动情况进行分析,不要泛泛而谈- 3. **个性化**:针对用户的学习特点、困难点、互动模式提供个性化分析- 4. **可操作性**:所有建议必须具体、可执行,不要使用空泛的表述-- # 总结维度(必须具体化)- 1. **学习内容回顾**:- - 必须列出每个知识点的具体标题- - 简要说明每个知识点的核心内容(1-2句话)- - 说明知识点之间的递进关系- - 不要只说"学习了X个知识点",要具体列出每个知识点-- 2. **学习过程分析**:- - 必须引用用户的具体问题(如果用户有提问)- - 分析用户提问的频率、深度、关注点- - 识别用户的学习模式(主动提问型/被动接受型/深入探索型等)- - 如果用户没有提问,说明用户的学习方式,并分析可能的原因- - 不要使用"用户提出了几个问题"这样的泛泛表述,要具体说明问题内容-- 3. **掌握程度评估**:- - 基于用户的具体问题内容,评估对每个知识点的理解程度- - 如果用户针对某个知识点提问,说明提问的类型(概念理解/应用实践/深入探索等)- - 识别用户可能存在的薄弱环节(基于提问内容或没有提问的知识点)- - 不要使用"掌握良好"这样的空泛评价,要具体说明掌握的证据-- 4. **改进建议**:- - 针对用户的具体薄弱环节提供建议- - 建议必须具体、可操作,不要使用"多练习"、"多思考"这样的空泛建议- - 可以建议具体的复习重点、拓展方向、实践方法- - 如果用户提问较少,可以建议如何更主动地学习-- # 报告风格- - 以导师的身份撰写,语气亲切专业- - 使用鼓励性的语言,肯定用户的学习努力- - 提供具体、可操作的建议- - 使用Markdown格式,结构清晰- - **重要**:直接输出Markdown内容,不要用代码块(```markdown)包裹- - **重要**:输出纯Markdown文本,不要添加任何markdown标记或解释- - **重要**:所有分析必须具体,引用实际的学习数据,避免空泛的表述-- # 报告结构(必须包含具体内容)- ```markdown- # 📊 学习总结报告-- ## 🎯 学习概览- [具体说明:学习了哪些知识点,学习时长/互动次数,整体学习特点]-- 例如:- - 本次学习共涵盖3个知识点:XXX、XXX、XXX- - 在学习过程中,你提出了X个问题,主要集中在XXX方面- - 你的学习方式表现出XXX特点-- ## 📚 知识点回顾- [逐一回顾,每个知识点都要具体说明]-- ### 知识点1:XXX- - 核心内容:[具体说明这个知识点的核心内容]- - 学习情况:[基于互动情况,说明你在这个知识点上的学习表现]-- ### 知识点2:XXX- - 核心内容:[具体说明]- - 学习情况:[具体分析]-- ## 💬 学习互动分析- [必须引用具体的提问内容,具体分析]-- - 提问频率:[具体数字和分布]- - 提问特点:[基于具体问题内容分析,例如"你关注的是概念理解还是实际应用"]- - 具体问题回顾:[列出1-2个典型问题,说明这些问题反映了什么]- - 学习模式:[基于互动情况,判断用户的学习模式]-- ## 📈 掌握程度评估- [基于具体数据,对每个知识点进行具体评估]-- - 知识点1:XXX- - 掌握证据:[具体说明,例如"你提出了关于XXX的问题,说明你理解了..."]- - 薄弱环节:[如果有,具体说明]-- - 知识点2:XXX- - 掌握证据:[具体说明]- - 薄弱环节:[如果有,具体说明]-- ## 🚀 后续学习建议- [必须具体、可操作]-- - 复习重点:[具体列出需要重点复习的知识点或概念]- - 拓展方向:[具体建议可以学习哪些相关内容]- - 实践建议:[具体建议如何实践应用]- - 学习方法:[基于你的学习特点,给出具体的学习方法建议]-- ## 🌟 结语- [鼓励性的结束语,可以总结本次学习的亮点]- ```-- # 输出要求- - 所有分析必须基于提供的实际数据(知识点、对话历史)- - 必须引用具体的知识点标题、具体的问题内容- - 避免使用"很好"、"不错"、"需要加强"这样的空泛评价- - 使用具体的数据、具体的例子、具体的建议- - 如果用户没有提问,要分析原因并给出具体建议- - 直接输出Markdown格式的文本内容,不要用代码块包裹--user_template: |- ## 学习计划概览- 笔记本名称: {notebook_name}- 知识点数量: {total_points}-- ## 所有知识点- {all_knowledge_points}-- ## 完整对话历史- {full_chat_history}-- ## 任务- 请基于以上**实际的学习数据**,生成一份**具体、详细**的学习总结报告。-- ### 要求(必须严格遵守):-- 1. **具体化所有内容**:- - 必须列出每个知识点的具体标题和核心内容- - 必须引用用户的具体问题(如果有)- - 必须基于实际互动情况进行分析- - 不要使用"学习了几个知识点"这样的泛泛表述-- 2. **数据驱动分析**:- - 统计用户提问的次数、分布(哪个知识点提问多)- - 分析用户问题的类型(概念理解/应用/深入探索)- - 基于问题内容判断用户的理解程度- - 如果用户没有提问,分析可能的原因(快速理解/需要引导等)-- 3. **个性化评估**:- - 对每个知识点,基于实际互动情况给出具体评估- - 识别用户的具体薄弱环节(如果有)- - 说明评估的依据(例如"你提出了关于XXX的问题,说明你理解了...")-- 4. **可操作建议**:- - 建议必须具体,不要使用"多练习"、"多思考"这样的空泛表述- - 可以建议具体的复习重点、拓展方向、实践方法- - 基于用户的学习特点给出个性化的学习方法建议-- 5. **引用实际数据**:- - 在报告中引用具体的知识点标题- - 引用用户的具体问题(如果有)- - 使用具体数字(提问次数、知识点数量等)- - 避免空泛的表述-- **输出格式要求**:- - 直接输出Markdown格式的文本内容- - 不要用 ```markdown 或 ``` 代码块包裹- - 不要添加任何解释或说明文字- - 直接输出可渲染的Markdown内容- - 确保所有内容都是具体的、基于实际数据的diff --git a/deeptutor/agents/notebook/summarize_agent.py b/deeptutor/agents/notebook/summarize_agent.pyindex d5a4d260e..be53a15e6 100644--- a/deeptutor/agents/notebook/summarize_agent.py+++ b/deeptutor/agents/notebook/summarize_agent.py@@ -147,10 +147,6 @@ class NotebookSummarizeAgent:"zh": "一份写作草稿,重点提炼主题、结构、当前完成度与可继续扩展方向。","en": "A writing draft; focus on theme, structure, current completeness, and expansion paths.",},- "guided_learning": {- "zh": "一段引导式学习记录,重点提炼学习主题、知识点结构与阶段性产出。",- "en": "A guided learning record; focus on topic, knowledge structure, and partial/final output.",- },}localized = hints.get(record_type, {})return localized.get(self.language, "Summarize the most reusable information in this record.")diff --git a/deeptutor/agents/visualize/agents/analysis_agent.py b/deeptutor/agents/visualize/agents/analysis_agent.pyindex 0fd457b69..f25b2f174 100644--- a/deeptutor/agents/visualize/agents/analysis_agent.py+++ b/deeptutor/agents/visualize/agents/analysis_agent.py@@ -33,9 +33,14 @@ class AnalysisAgent(BaseAgent):history_context: str,render_mode: str = "auto",) -> VisualizationAnalysis:- if render_mode in ("svg", "chartjs", "mermaid"):+ if render_mode in ("svg", "chartjs", "mermaid", "html"):system_prompt = self.get_prompt("system_fixed")user_template = self.get_prompt("user_template_fixed")+ elif render_mode == "figure":+ # Constrained-auto mode: LLM picks one of svg/chartjs/mermaid+ # (html is excluded). Used by the Book figure block.+ system_prompt = self.get_prompt("system_figure")+ user_template = self.get_prompt("user_template_figure")else:system_prompt = self.get_prompt("system")user_template = self.get_prompt("user_template")@@ -46,7 +51,7 @@ class AnalysisAgent(BaseAgent):"user_input": user_input.strip(),"history_context": history_context.strip() or "(none)",}- if render_mode in ("svg", "chartjs", "mermaid"):+ if render_mode in ("svg", "chartjs", "mermaid", "html"):format_kwargs["render_type"] = render_modeuser_prompt = user_template.format(**format_kwargs)@@ -69,6 +74,13 @@ class AnalysisAgent(BaseAgent):chunks.append(chunk)response = "".join(chunks)result = VisualizationAnalysis.model_validate(extract_json_object(response))- if render_mode in ("svg", "chartjs", "mermaid"):+ if render_mode in ("svg", "chartjs", "mermaid", "html"):result.render_type = render_mode # type: ignore[assignment]+ elif render_mode == "figure" and result.render_type not in (+ "svg",+ "chartjs",+ "mermaid",+ ):+ # Defensive: if the LLM ignored the constraint, force a safe default.+ result.render_type = "svg" # type: ignore[assignment]return resultdiff --git a/deeptutor/agents/visualize/agents/code_generator_agent.py b/deeptutor/agents/visualize/agents/code_generator_agent.pyindex c26be402a..9110e4089 100644--- a/deeptutor/agents/visualize/agents/code_generator_agent.py+++ b/deeptutor/agents/visualize/agents/code_generator_agent.py@@ -68,6 +68,20 @@ class CodeGeneratorAgent(BaseAgent):lang_hint = "svg"elif analysis.render_type == "mermaid":lang_hint = "mermaid"+ elif analysis.render_type == "html":+ lang_hint = "html"else:lang_hint = "javascript"- return extract_code_block(response, lang_hint) or extract_code_block(response)++ extracted = extract_code_block(response, lang_hint) or extract_code_block(response)++ # For html, the model sometimes returns the full document with no fence.+ # `extract_code_block` will then return the trimmed raw response — accept+ # it as long as it looks like an HTML document.+ if analysis.render_type == "html" and not extracted:+ stripped = (response or "").strip()+ lowered = stripped.lower()+ if lowered.startswith("<!doctype") or lowered.startswith("<html"):+ return stripped++ return extracteddiff --git a/deeptutor/agents/visualize/agents/review_agent.py b/deeptutor/agents/visualize/agents/review_agent.pyindex 6391c4aed..95c2a617a 100644--- a/deeptutor/agents/visualize/agents/review_agent.py+++ b/deeptutor/agents/visualize/agents/review_agent.py@@ -35,6 +35,16 @@ class ReviewAgent(BaseAgent):analysis: VisualizationAnalysis,code: str,) -> ReviewResult:+ # HTML pages are 8-16k tokens of full single-file documents; a second+ # LLM pass to "review" them costs another 30-60s with negligible+ # quality gain. Skip the LLM review for html and return the code as-is.+ if analysis.render_type == "html":+ return ReviewResult(+ optimized_code=code,+ changed=False,+ review_notes="Skipped LLM review for html render_type.",+ )+system_prompt = self.get_prompt("system")user_template = self.get_prompt("user_template")if not system_prompt or not user_template:diff --git a/deeptutor/agents/visualize/models.py b/deeptutor/agents/visualize/models.pyindex 9345f6391..d0963f692 100644--- a/deeptutor/agents/visualize/models.py+++ b/deeptutor/agents/visualize/models.py@@ -10,8 +10,11 @@ from pydantic import BaseModel, Fieldclass VisualizationAnalysis(BaseModel):"""Output of the analysis stage."""- render_type: Literal["svg", "chartjs", "mermaid"] = Field(- description="Whether to render as raw SVG, a Chart.js configuration, or Mermaid diagram code.",+ render_type: Literal["svg", "chartjs", "mermaid", "html"] = Field(+ description=(+ "Whether to render as raw SVG, a Chart.js configuration, a Mermaid "+ "diagram, or a self-contained interactive HTML page."+ ),)description: str = Field(default="",@@ -25,8 +28,9 @@ class VisualizationAnalysis(BaseModel):default="",description=("Chart.js chart type (bar, line, pie, doughnut, radar, etc.) when render_type is chartjs, "- "or Mermaid diagram type (flowchart, sequenceDiagram, mindmap, classDiagram, stateDiagram, etc.) "- "when render_type is mermaid."+ "Mermaid diagram type (flowchart, sequenceDiagram, mindmap, classDiagram, stateDiagram, etc.) "+ "when render_type is mermaid, or a short interaction tag (e.g. 'interactive', 'animation', "+ "'walkthrough') when render_type is html."),)visual_elements: list[str] = Field(diff --git a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/en/analysis_agent.yamlindex dd292bb8d..bf9310164 100644--- a/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml+++ b/deeptutor/agents/visualize/prompts/en/analysis_agent.yaml@@ -2,7 +2,7 @@ system: |You are a visualization analyst. Given a user request and conversation history,decide the best rendering approach and produce a structured analysis.- Choose between three render types:+ Choose between four render types:- "svg": Use when the visualization is a custom illustration, schematic, or anyfree-form graphic that requires precise coordinate-level control and does notfit a standard chart or structured diagram.@@ -12,6 +12,11 @@ system: |sequence diagram, class diagram, state diagram, entity-relationship diagram,Gantt chart, mindmap, or any graph that can be expressed with Mermaid.js syntax.Prefer mermaid over svg for these structured diagram types.+ - "html": Use when the user wants an interactive learning/explanation page —+ e.g. a draggable demo, an animation with controls, a step-by-step walkthrough,+ clickable practice exercises, or a concept visualization. Prefer the static+ options (svg/chartjs/mermaid) when they are sufficient. Choose html only when+ "user interaction + state changes + mixed text/graphics" is the core experience.Return your analysis as a single JSON object. Do not include any text outside the JSON.@@ -24,11 +29,11 @@ user_template: |Return JSON:{{- "render_type": "svg" or "chartjs" or "mermaid",+ "render_type": "svg" or "chartjs" or "mermaid" or "html","description": "High-level description of what the visualization should show","data_description": "Description of the data or elements to be visualized",- "chart_type": "Chart.js chart type if chartjs, Mermaid diagram type if mermaid, otherwise empty string",- "visual_elements": ["key visual elements to include"],+ "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (e.g. interactive / animation / walkthrough / quiz) if html; otherwise empty string",+ "visual_elements": ["key visual elements or interactive modules to include"],"rationale": "Why this render_type was chosen"}}@@ -53,7 +58,42 @@ user_template_fixed: |"render_type": "{render_type}","description": "High-level description of what the visualization should show","data_description": "Description of the data or elements to be visualized",- "chart_type": "Chart.js chart type if chartjs, Mermaid diagram type if mermaid, otherwise empty string",- "visual_elements": ["key visual elements to include"],+ "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; an interaction tag (e.g. interactive / animation / walkthrough / quiz) if html; otherwise empty string",+ "visual_elements": ["key visual elements or interactive modules to include"],"rationale": "Analysis notes"}}++system_figure: |+ You are a visualization analyst. The user wants a STATIC figure (no+ interactivity). Choose between three render types ONLY:+ - "svg": Use when the visualization is a custom illustration, schematic, or any+ free-form graphic that requires precise coordinate-level control and does not+ fit a standard chart or structured diagram.+ - "chartjs": Use when the visualization involves quantitative data that fits a+ standard chart type (bar, line, pie, doughnut, radar, scatter, bubble, polar area).+ - "mermaid": Use when the visualization is a structured diagram such as a flowchart,+ sequence diagram, class diagram, state diagram, entity-relationship diagram,+ Gantt chart, mindmap, or any graph that can be expressed with Mermaid.js syntax.+ Prefer mermaid over svg for these structured diagram types.++ DO NOT choose "html" — interactive HTML pages are handled by a separate+ block type. Pick exactly one of svg / chartjs / mermaid.++ Return your analysis as a single JSON object. Do not include any text outside the JSON.++user_template_figure: |+ User request:+ {user_input}++ Conversation history:+ {history_context}++ Return JSON (render_type MUST be one of "svg", "chartjs", or "mermaid"):+ {{+ "render_type": "svg" or "chartjs" or "mermaid",+ "description": "High-level description of what the figure should show",+ "data_description": "Description of the data or elements to be visualized",+ "chart_type": "Chart.js chart type if chartjs; Mermaid diagram type if mermaid; otherwise empty string",+ "visual_elements": ["key visual elements to include"],+ "rationale": "Why this render_type was chosen"+ }}diff --git a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yamlindex 5b0ebbf92..0a7d331fb 100644--- a/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml+++ b/deeptutor/agents/visualize/prompts/en/code_generator_agent.yaml@@ -16,9 +16,25 @@ system: |sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, gantt, mindmap, etc.).Use clear node labels and readable edge descriptions. Do NOT use spaces innode IDs — use camelCase or underscores. Avoid reserved keywords as node IDs.+ - If render_type is "html", output one complete, self-contained single-file HTML+ learning page.+ Technical constraints:+ * Must include everything from <!DOCTYPE html> to </html>.+ * Put all CSS inside <style>; put all JavaScript inside <script> before </body>.+ * Do NOT rely on external CDNs, fonts, or other resources (KaTeX is injected+ by the host page; use $...$ for inline math, $$...$$ for block math).+ * The page will render inside an iframe — use max-width: 100% and+ box-sizing: border-box, avoid fixed widths.+ * For long content use overflow-x: auto when needed; never let content be+ clipped.+ * Wrap all interactions inside DOMContentLoaded and use addEventListener;+ do NOT use inline onclick handlers.+ * Always check that an element exists before manipulating it.+ Within these constraints, freely choose layout, colors, visual style, and+ interaction patterns to make the page clear, beautiful, and easy to learn from.- Do NOT include any explanation outside the code fence.- Wrap the code in a fenced code block with the appropriate language tag- (```svg, ```javascript, or ```mermaid).+ (```svg, ```javascript, ```mermaid, or ```html).user_template: |User request:@@ -36,3 +52,4 @@ user_template: |- For SVG: ```svg ... ```- For Chart.js: ```javascript ... ```- For Mermaid: ```mermaid ... ```+ - For HTML: ```html ... ```diff --git a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yamlindex bd369688b..8fa19e8fa 100644--- a/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml+++ b/deeptutor/agents/visualize/prompts/zh/analysis_agent.yaml@@ -1,10 +1,11 @@system: |你是一个可视化分析师。根据用户请求和对话历史,决定最佳的渲染方式并生成结构化分析。- 在三种渲染类型中选择:+ 在四种渲染类型中选择:- "svg":当可视化是自定义插图、示意图或任何需要精确坐标控制的自由图形,且不适合标准图表或结构化图形时使用。- "chartjs":当可视化涉及可以用标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、气泡图、极坐标图)表示的定量数据时使用。- "mermaid":当可视化是结构化图形时使用,如流程图、序列图、类图、状态图、实体关系图、甘特图、思维导图或任何可以用 Mermaid.js 语法表达的图形。对于这些结构化图形类型,优先使用 mermaid 而非 svg。+ - "html":当用户需要一个交互式学习/讲解页面,例如可拖动的演示、带控件的动画、分步走读、可点击的练习题、概念可视化页面等。如果一个静态图(svg/chartjs/mermaid)足够表达用户需求,请优先使用前三种;只有当"用户操作 + 状态变化 + 图文混排"是核心体验时才选 html。返回一个 JSON 对象,不要包含 JSON 以外的任何文本。@@ -17,11 +18,11 @@ user_template: |返回 JSON:{{- "render_type": "svg" 或 "chartjs" 或 "mermaid",+ "render_type": "svg" 或 "chartjs" 或 "mermaid" 或 "html","description": "可视化应展示的内容的高层描述","data_description": "要可视化的数据或元素的描述",- "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型,如果是 mermaid 则填写 Mermaid 图表类型,否则为空字符串",- "visual_elements": ["需要包含的关键视觉元素"],+ "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;如果是 html 则填写交互形式(如 interactive / animation / walkthrough / quiz);否则为空字符串",+ "visual_elements": ["需要包含的关键视觉元素或交互模块"],"rationale": "为什么选择这种 render_type"}}@@ -46,7 +47,34 @@ user_template_fixed: |"render_type": "{render_type}","description": "可视化应展示的内容的高层描述","data_description": "要可视化的数据或元素的描述",- "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型,如果是 mermaid 则填写 Mermaid 图表类型,否则为空字符串",- "visual_elements": ["需要包含的关键视觉元素"],+ "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;如果是 html 则填写交互形式(如 interactive / animation / walkthrough / quiz);否则为空字符串",+ "visual_elements": ["需要包含的关键视觉元素或交互模块"],"rationale": "分析说明"}}++system_figure: |+ 你是一个可视化分析师。用户需要一张静态图(不需要交互)。请仅在以下三种渲染类型中选择:+ - "svg":当可视化是自定义插图、示意图或任何需要精确坐标控制的自由图形,且不适合标准图表或结构化图形时使用。+ - "chartjs":当可视化涉及可以用标准图表类型(柱状图、折线图、饼图、环形图、雷达图、散点图、气泡图、极坐标图)表示的定量数据时使用。+ - "mermaid":当可视化是结构化图形时使用,如流程图、序列图、类图、状态图、实体关系图、甘特图、思维导图或任何可以用 Mermaid.js 语法表达的图形。对于这些结构化图形类型,优先使用 mermaid 而非 svg。++ 禁止选择 "html":交互式 HTML 页面由另一种独立的 block 类型处理。请从 svg / chartjs / mermaid 三者中选择其一。++ 返回一个 JSON 对象,不要包含 JSON 以外的任何文本。++user_template_figure: |+ 用户请求:+ {user_input}++ 对话历史:+ {history_context}++ 返回 JSON(render_type 必须是 "svg" / "chartjs" / "mermaid" 之一):+ {{+ "render_type": "svg" 或 "chartjs" 或 "mermaid",+ "description": "图示应展示的内容的高层描述",+ "data_description": "要可视化的数据或元素的描述",+ "chart_type": "如果是 chartjs 则填写 Chart.js 图表类型;如果是 mermaid 则填写 Mermaid 图表类型;否则为空字符串",+ "visual_elements": ["需要包含的关键视觉元素"],+ "rationale": "为什么选择这种 render_type"+ }}diff --git a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yamlindex 41d95b941..aba8ae9ac 100644--- a/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml+++ b/deeptutor/agents/visualize/prompts/zh/code_generator_agent.yaml@@ -15,8 +15,20 @@ system: |classDiagram、stateDiagram-v2、erDiagram、gantt、mindmap 等)。使用清晰的节点标签和可读的边描述。节点 ID 不要使用空格——使用camelCase 或下划线。避免使用保留关键词作为节点 ID。+ - 如果 render_type 是 "html",输出一个完整的、自包含的单文件 HTML 学习页面。+ 技术约束:+ * 必须从 <!DOCTYPE html> 写到 </html>+ * 所有 CSS 写在 <style> 中,所有 JavaScript 写在 </body> 前的 <script> 中+ * 不依赖外部 CDN、字体或其他资源(KaTeX 会由宿主页面自动注入;行内公式用+ $...$,块级公式用 $$...$$)+ * 页面会渲染在 iframe 中,必须响应式适配:使用 max-width: 100%、+ box-sizing: border-box,避免固定宽度+ * 长内容必要时用 overflow-x: auto,避免被截断+ * 所有交互必须包在 DOMContentLoaded 中,使用 addEventListener,禁止 onclick+ * 操作 DOM 前检查元素是否存在+ 在以上约束内自由决定布局、配色、视觉风格和交互形式,让页面清晰、美观、易学。- 不要在代码块之外包含任何解释。- - 用带有适当语言标签的代码块包裹代码(```svg、```javascript 或 ```mermaid)。+ - 用带有适当语言标签的代码块包裹代码(```svg、```javascript、```mermaid 或 ```html)。user_template: |用户请求:@@ -34,3 +46,4 @@ user_template: |- SVG 使用:```svg ... ```- Chart.js 使用:```javascript ... ```- Mermaid 使用:```mermaid ... ```+ - HTML 使用:```html ... ```diff --git a/deeptutor/agents/visualize/utils.py b/deeptutor/agents/visualize/utils.pyindex 722d56ad4..b0d8aaa81 100644--- a/deeptutor/agents/visualize/utils.py+++ b/deeptutor/agents/visualize/utils.py@@ -77,7 +77,69 @@ def extract_code_block(text: str, language: str = "") -> str:return (text or "").strip()+def is_valid_html_document(html: str) -> bool:+ """Heuristic check that *html* looks like a renderable HTML fragment."""+ if not html:+ return False+ lowered = html.lower()+ return (+ "<html" in lowered+ or "<!doctype" in lowered+ or "<body" in lowered+ or "<div" in lowered+ )+++def build_fallback_html(*, title: str, summary: str = "", note: str = "") -> str:+ """Build a minimal, self-contained fallback HTML page.++ Used when the model fails to produce a renderable HTML document, so the+ user still gets *something* shown in the iframe instead of a blank panel.+ """+ safe_title = (title or "Visualization").strip() or "Visualization"+ safe_summary = (summary or "").replace("\n", "<br>") or (+ "The model did not return a renderable HTML document."+ )+ safe_note = (note or "").replace("\n", "<br>")++ note_block = (+ f'<div class="note"><strong>Note:</strong><br>{safe_note}</div>'+ if safe_note+ else ""+ )++ return f"""<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1.0">+<title>{safe_title}</title>+<style>+ *{{margin:0;padding:0;box-sizing:border-box;}}+ body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;+ background:linear-gradient(135deg,#F8FAFC 0%,#EFF6FF 100%);+ min-height:100vh;padding:2rem;color:#1E293B;}}+ .card{{max-width:760px;margin:0 auto;background:#fff;border-radius:16px;+ padding:1.75rem 2rem;box-shadow:0 4px 6px -1px rgba(0,0,0,.08);}}+ h1{{color:#1E40AF;font-size:1.4rem;margin-bottom:1rem;}}+ .summary{{line-height:1.7;color:#475569;}}+ .note{{margin-top:1rem;padding:0.9rem 1rem;background:#FEF3C7;+ border-left:4px solid #F59E0B;border-radius:0 8px 8px 0;color:#92400E;}}+</style>+</head>+<body>+ <div class="card">+ <h1>{safe_title}</h1>+ <div class="summary">{safe_summary}</div>+ {note_block}+ </div>+</body>+</html>"""++__all__ = [+ "build_fallback_html","extract_code_block","extract_json_object",+ "is_valid_html_document",]diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 5e8dded9e..1f83cfda3 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -199,10 +199,10 @@ app.mount(# Some router modules load YAML settings at import time.from deeptutor.api.routers import (agent_config,+ book,chat,co_writer,dashboard,- guide,knowledge,memory,notebook,@@ -226,7 +226,7 @@ app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledgapp.include_router(dashboard.router, prefix="/api/v1/dashboard", tags=["dashboard"])app.include_router(co_writer.router, prefix="/api/v1/co_writer", tags=["co_writer"])app.include_router(notebook.router, prefix="/api/v1/notebook", tags=["notebook"])-app.include_router(guide.router, prefix="/api/v1/guide", tags=["guide"])+app.include_router(book.router, prefix="/api/v1/book", tags=["book"])app.include_router(memory.router, prefix="/api/v1/memory", tags=["memory"])app.include_router(sessions.router, prefix="/api/v1/sessions", tags=["sessions"])app.include_router(diff --git a/deeptutor/api/routers/agent_config.py b/deeptutor/api/routers/agent_config.pyindex 76cc7a3df..b8647f113 100644--- a/deeptutor/api/routers/agent_config.py+++ b/deeptutor/api/routers/agent_config.py@@ -29,11 +29,6 @@ AGENT_REGISTRY = {"color": "amber","label_key": "Co-Writer",},- "guide": {- "icon": "BookOpen",- "color": "indigo",- "label_key": "Guided Learning",- },}diff --git a/deeptutor/api/routers/book.py b/deeptutor/api/routers/book.pynew file mode 100644index 000000000..89d7ec495--- /dev/null+++ b/deeptutor/api/routers/book.py@@ -0,0 +1,627 @@+"""+Book Engine API Router+======================++REST + WebSocket endpoints for the ``BookEngine``. Phase 1 surface:+create / confirm / compile / read / delete + a per-book event stream.+"""++from __future__ import annotations++import asyncio+from typing import Any++from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect+from pydantic import BaseModel, Field++from deeptutor.book import (+ BlockType,+ BookProposal,+ Spine,+ get_book_engine,+)+from deeptutor.book.models import ContentType+from deeptutor.book.streaming import SOURCE as BOOK_SOURCE+from deeptutor.core.stream import StreamEventType+from deeptutor.core.stream_bus import StreamBus+from deeptutor.logging import get_logger++router = APIRouter()+logger = get_logger("book.router")+++# ─────────────────────────────────────────────────────────────────────────────+# Request / response models+# ─────────────────────────────────────────────────────────────────────────────+++class CreateBookRequest(BaseModel):+ user_intent: str = Field(default="")+ chat_session_id: str = Field(default="")+ chat_selections: list[dict[str, Any]] = Field(default_factory=list)+ notebook_refs: list[dict[str, Any]] = Field(default_factory=list)+ knowledge_bases: list[str] = Field(default_factory=list)+ question_categories: list[int] = Field(default_factory=list)+ question_entries: list[int] = Field(default_factory=list)+ language: str = Field(default="en")+++class ConfirmProposalRequest(BaseModel):+ book_id: str+ proposal: dict[str, Any] | None = None # full edited BookProposal payload+++class ConfirmSpineRequest(BaseModel):+ book_id: str+ spine: dict[str, Any] | None = None+ auto_compile: bool = True+++class CompilePageRequest(BaseModel):+ book_id: str+ page_id: str+ force: bool = False+++class RegenerateBlockRequest(BaseModel):+ book_id: str+ page_id: str+ block_id: str+ params_override: dict[str, Any] | None = None+++class InsertBlockRequest(BaseModel):+ book_id: str+ page_id: str+ block_type: str+ params: dict[str, Any] | None = None+ position: int | None = None+ compile_now: bool = True+++class DeleteBlockRequest(BaseModel):+ book_id: str+ page_id: str+ block_id: str+++class MoveBlockRequest(BaseModel):+ book_id: str+ page_id: str+ block_id: str+ new_position: int+++class ChangeBlockTypeRequest(BaseModel):+ book_id: str+ page_id: str+ block_id: str+ new_type: str+ params_override: dict[str, Any] | None = None+++class DeepDiveRequest(BaseModel):+ book_id: str+ parent_page_id: str+ topic: str+ block_id: str | None = None+ content_type: str = "concept"+++class QuizAttemptRequest(BaseModel):+ book_id: str+ page_id: str+ block_id: str+ question_id: str = ""+ user_answer: str = ""+ is_correct: bool = False+ request_remediation: bool = False+++class SupplementRequest(BaseModel):+ book_id: str+ page_id: str+ topic: str+++# ─────────────────────────────────────────────────────────────────────────────+# REST endpoints+# ─────────────────────────────────────────────────────────────────────────────++[email protected]("/health")+async def health_check() -> dict[str, str]:+ return {"status": "healthy", "service": "book"}++[email protected]("/books")+async def list_books() -> dict[str, Any]:+ engine = get_book_engine()+ return {"books": [b.model_dump(mode="json") for b in engine.list_books()]}++[email protected]("/books/{book_id}")+async def get_book(book_id: str) -> dict[str, Any]:+ engine = get_book_engine()+ book = engine.load_book(book_id)+ if book is None:+ raise HTTPException(status_code=404, detail="Book not found")+ spine = engine.load_spine(book_id)+ pages = engine.list_pages(book_id)+ progress = engine.load_progress(book_id)+ return {+ "book": book.model_dump(mode="json"),+ "spine": spine.model_dump(mode="json") if spine else None,+ "pages": [p.model_dump(mode="json") for p in pages],+ "progress": progress.model_dump(mode="json"),+ }++[email protected]("/books/{book_id}/spine")+async def get_spine(book_id: str) -> dict[str, Any]:+ engine = get_book_engine()+ spine = engine.load_spine(book_id)+ if spine is None:+ raise HTTPException(status_code=404, detail="Spine not found")+ return {"spine": spine.model_dump(mode="json")}++[email protected]("/books/{book_id}/pages/{page_id}")+async def get_page(book_id: str, page_id: str) -> dict[str, Any]:+ engine = get_book_engine()+ page = engine.load_page(book_id, page_id)+ if page is None:+ raise HTTPException(status_code=404, detail="Page not found")+ return {"page": page.model_dump(mode="json")}++[email protected]("/books/{book_id}")+async def delete_book(book_id: str) -> dict[str, Any]:+ engine = get_book_engine()+ ok = engine.delete_book(book_id)+ if not ok:+ raise HTTPException(status_code=404, detail="Book not found")+ return {"deleted": True, "book_id": book_id}++[email protected]("/books")+async def create_book(req: CreateBookRequest) -> dict[str, Any]:+ """Stage 1: capture inputs + run IdeationAgent."""+ if not req.user_intent.strip():+ raise HTTPException(status_code=400, detail="user_intent is required")+ engine = get_book_engine()+ try:+ book, proposal = await engine.create_book(+ user_intent=req.user_intent,+ chat_session_id=req.chat_session_id,+ chat_selections=req.chat_selections,+ notebook_refs=req.notebook_refs,+ knowledge_bases=req.knowledge_bases,+ question_categories=req.question_categories,+ question_entries=req.question_entries,+ language=req.language,+ )+ except Exception as exc: # noqa: BLE001+ logger.error(f"create_book failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ return {+ "book": book.model_dump(mode="json"),+ "proposal": proposal.model_dump(mode="json"),+ }++[email protected]("/books/confirm-proposal")+async def confirm_proposal(req: ConfirmProposalRequest) -> dict[str, Any]:+ """Stage 2: user confirms (and possibly edits) the proposal → SpineAgent."""+ engine = get_book_engine()+ edited: BookProposal | None = None+ if req.proposal:+ try:+ edited = BookProposal.model_validate(req.proposal)+ except Exception as exc:+ raise HTTPException(status_code=400, detail=f"Invalid proposal: {exc}")+ try:+ book, spine = await engine.confirm_proposal(+ book_id=req.book_id, edited_proposal=edited+ )+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc))+ except Exception as exc: # noqa: BLE001+ logger.error(f"confirm_proposal failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ return {+ "book": book.model_dump(mode="json"),+ "spine": spine.model_dump(mode="json"),+ }++[email protected]("/books/confirm-spine")+async def confirm_spine(req: ConfirmSpineRequest) -> dict[str, Any]:+ """Stage 3: user confirms the spine → create pending page shells."""+ engine = get_book_engine()+ edited: Spine | None = None+ if req.spine:+ try:+ edited = Spine.model_validate(req.spine)+ except Exception as exc:+ raise HTTPException(status_code=400, detail=f"Invalid spine: {exc}")+ try:+ pages = await engine.confirm_spine(+ book_id=req.book_id,+ edited_spine=edited,+ auto_compile=req.auto_compile,+ )+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc))+ except Exception as exc: # noqa: BLE001+ logger.error(f"confirm_spine failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ return {"pages": [p.model_dump(mode="json") for p in pages]}++[email protected]("/books/compile-page")+async def compile_page(req: CompilePageRequest) -> dict[str, Any]:+ """Drive the compiler for the page the user just opened (current-page priority)."""+ engine = get_book_engine()+ try:+ page = await engine.compile_page(+ book_id=req.book_id, page_id=req.page_id, force=req.force+ )+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc))+ except Exception as exc: # noqa: BLE001+ logger.error(f"compile_page failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ return {"page": page.model_dump(mode="json")}++[email protected]("/books/regenerate-block")+async def regenerate_block(req: RegenerateBlockRequest) -> dict[str, Any]:+ engine = get_book_engine()+ try:+ block = await engine.regenerate_block(+ book_id=req.book_id,+ page_id=req.page_id,+ block_id=req.block_id,+ params_override=req.params_override,+ )+ except Exception as exc: # noqa: BLE001+ logger.error(f"regenerate_block failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ if block is None:+ raise HTTPException(status_code=404, detail="Block not found")+ return {"block": block.model_dump(mode="json")}+++def _coerce_block_type(name: str) -> BlockType:+ try:+ return BlockType(name)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=f"Unknown block type: {name}") from exc+++def _coerce_content_type(name: str) -> ContentType:+ try:+ return ContentType(name)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=f"Unknown content type: {name}") from exc++[email protected]("/books/insert-block")+async def insert_block(req: InsertBlockRequest) -> dict[str, Any]:+ engine = get_book_engine()+ block_type = _coerce_block_type(req.block_type)+ try:+ block = await engine.insert_block(+ book_id=req.book_id,+ page_id=req.page_id,+ block_type=block_type,+ params=req.params,+ position=req.position,+ compile_now=req.compile_now,+ )+ except Exception as exc: # noqa: BLE001+ logger.error(f"insert_block failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ if block is None:+ raise HTTPException(status_code=404, detail="Page or chapter not found")+ return {"block": block.model_dump(mode="json")}++[email protected]("/books/delete-block")+async def delete_block(req: DeleteBlockRequest) -> dict[str, Any]:+ engine = get_book_engine()+ ok = await engine.delete_block(+ book_id=req.book_id, page_id=req.page_id, block_id=req.block_id+ )+ if not ok:+ raise HTTPException(status_code=404, detail="Block not found")+ return {"ok": True}++[email protected]("/books/move-block")+async def move_block(req: MoveBlockRequest) -> dict[str, Any]:+ engine = get_book_engine()+ ok = await engine.move_block(+ book_id=req.book_id,+ page_id=req.page_id,+ block_id=req.block_id,+ new_position=req.new_position,+ )+ if not ok:+ raise HTTPException(status_code=404, detail="Block not found")+ return {"ok": True}++[email protected]("/books/change-block-type")+async def change_block_type(req: ChangeBlockTypeRequest) -> dict[str, Any]:+ engine = get_book_engine()+ new_type = _coerce_block_type(req.new_type)+ try:+ block = await engine.change_block_type(+ book_id=req.book_id,+ page_id=req.page_id,+ block_id=req.block_id,+ new_type=new_type,+ params_override=req.params_override,+ )+ except Exception as exc: # noqa: BLE001+ logger.error(f"change_block_type failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ if block is None:+ raise HTTPException(status_code=404, detail="Block not found")+ return {"block": block.model_dump(mode="json")}++[email protected]("/books/deep-dive")+async def deep_dive(req: DeepDiveRequest) -> dict[str, Any]:+ engine = get_book_engine()+ content_type = _coerce_content_type(req.content_type)+ try:+ page = await engine.create_deep_dive_subpage(+ book_id=req.book_id,+ parent_page_id=req.parent_page_id,+ topic=req.topic,+ block_id=req.block_id,+ content_type=content_type,+ )+ except Exception as exc: # noqa: BLE001+ logger.error(f"deep_dive failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ if page is None:+ raise HTTPException(status_code=404, detail="Parent page not found")+ return {"page": page.model_dump(mode="json")}++[email protected]("/books/quiz-attempt")+async def quiz_attempt(req: QuizAttemptRequest) -> dict[str, Any]:+ engine = get_book_engine()+ progress = await engine.record_quiz_attempt(+ book_id=req.book_id,+ page_id=req.page_id,+ block_id=req.block_id,+ question_id=req.question_id,+ user_answer=req.user_answer,+ is_correct=req.is_correct,+ )+ return {"progress": progress.model_dump(mode="json")}++[email protected]("/books/{book_id}/health")+async def book_health(book_id: str) -> dict[str, Any]:+ engine = get_book_engine()+ drift = engine.kb_drift_report(book_id)+ log = engine.log_health(book_id)+ return {"kb_drift": drift, "log_health": log}++[email protected]("/books/{book_id}/refresh-fingerprints")+async def refresh_fingerprints(book_id: str) -> dict[str, Any]:+ engine = get_book_engine()+ result = engine.refresh_kb_fingerprints(book_id)+ if result is None:+ raise HTTPException(status_code=404, detail="Book not found")+ return result++[email protected]("/books/supplement")+async def supplement(req: SupplementRequest) -> dict[str, Any]:+ engine = get_book_engine()+ try:+ block = await engine.supplement_for_weakness(+ book_id=req.book_id,+ page_id=req.page_id,+ topic=req.topic,+ )+ except Exception as exc: # noqa: BLE001+ logger.error(f"supplement failed: {exc}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(exc))+ if block is None:+ raise HTTPException(status_code=404, detail="Page not found")+ return {"block": block.model_dump(mode="json")}+++# ─────────────────────────────────────────────────────────────────────────────+# WebSocket – streamed Book events+# ─────────────────────────────────────────────────────────────────────────────+++def _serialize_event(event) -> dict[str, Any]:+ return {+ "type": event.type.value if hasattr(event.type, "value") else str(event.type),+ "source": event.source,+ "stage": event.stage,+ "content": event.content,+ "metadata": event.metadata or {},+ }++[email protected]("/ws")+async def book_websocket(ws: WebSocket) -> None:+ """Streaming endpoint.++ Client message protocol::++ {"type": "create", ...CreateBookRequest fields}+ {"type": "confirm_proposal", "book_id": "...", "proposal": {...}}+ {"type": "confirm_spine", "book_id": "...", "spine": {...}, "auto_compile": true}+ {"type": "compile_page", "book_id": "...", "page_id": "..."}+ {"type": "regenerate_block", "book_id": "...", "page_id": "...", "block_id": "...", "params_override": {}}+ """+ await ws.accept()+ closed = False++ async def send(data: dict[str, Any]) -> None:+ nonlocal closed+ if closed:+ return+ try:+ await ws.send_json(data)+ except Exception:+ closed = True++ async def stream_into_socket(bus: StreamBus) -> asyncio.Task:+ async def _forward() -> None:+ async for event in bus.subscribe():+ if event.source != BOOK_SOURCE:+ continue+ await send(_serialize_event(event))+ if event.type == StreamEventType.STAGE_END and event.stage in {+ "ideation", "spine", "compilation"+ }:+ pass # keep streaming – multiple stages per task+ return asyncio.create_task(_forward())++ try:+ engine = get_book_engine()+ while not closed:+ try:+ data = await ws.receive_json()+ except WebSocketDisconnect:+ break+ except Exception as exc:+ await send({"type": "error", "content": f"Bad message: {exc}"})+ continue++ msg_type = str(data.get("type") or "").strip()+ if not msg_type:+ await send({"type": "error", "content": "Missing 'type' field"})+ continue++ bus = StreamBus()+ forward_task = await stream_into_socket(bus)++ try:+ if msg_type == "create":+ book, proposal = await engine.create_book(+ user_intent=str(data.get("user_intent") or ""),+ chat_session_id=str(data.get("chat_session_id") or ""),+ chat_selections=data.get("chat_selections") or [],+ notebook_refs=data.get("notebook_refs") or [],+ knowledge_bases=data.get("knowledge_bases") or [],+ question_categories=[+ int(c) for c in (data.get("question_categories") or [])+ ],+ question_entries=[+ int(e) for e in (data.get("question_entries") or [])+ ],+ language=str(data.get("language") or "en"),+ stream=bus,+ )+ await send(+ {+ "type": "create_result",+ "book": book.model_dump(mode="json"),+ "proposal": proposal.model_dump(mode="json"),+ }+ )++ elif msg_type == "confirm_proposal":+ edited: BookProposal | None = None+ if data.get("proposal"):+ edited = BookProposal.model_validate(data["proposal"])+ book, spine = await engine.confirm_proposal(+ book_id=str(data.get("book_id") or ""),+ edited_proposal=edited,+ stream=bus,+ )+ await send(+ {+ "type": "confirm_proposal_result",+ "book": book.model_dump(mode="json"),+ "spine": spine.model_dump(mode="json"),+ }+ )++ elif msg_type == "confirm_spine":+ edited_spine: Spine | None = None+ if data.get("spine"):+ edited_spine = Spine.model_validate(data["spine"])+ pages = await engine.confirm_spine(+ book_id=str(data.get("book_id") or ""),+ edited_spine=edited_spine,+ auto_compile=bool(data.get("auto_compile", True)),+ stream=bus,+ )+ await send(+ {+ "type": "confirm_spine_result",+ "pages": [p.model_dump(mode="json") for p in pages],+ }+ )++ elif msg_type == "compile_page":+ page = await engine.compile_page(+ book_id=str(data.get("book_id") or ""),+ page_id=str(data.get("page_id") or ""),+ stream=bus,+ force=bool(data.get("force", False)),+ )+ await send(+ {+ "type": "compile_page_result",+ "page": page.model_dump(mode="json"),+ }+ )++ elif msg_type == "regenerate_block":+ block = await engine.regenerate_block(+ book_id=str(data.get("book_id") or ""),+ page_id=str(data.get("page_id") or ""),+ block_id=str(data.get("block_id") or ""),+ params_override=data.get("params_override"),+ stream=bus,+ )+ await send(+ {+ "type": "regenerate_block_result",+ "block": block.model_dump(mode="json") if block else None,+ }+ )++ else:+ await send(+ {"type": "error", "content": f"Unknown message type: {msg_type}"}+ )++ except Exception as exc:+ logger.error(f"book ws action {msg_type} failed: {exc}", exc_info=True)+ await send({"type": "error", "content": str(exc)})+ finally:+ await bus.close()+ forward_task.cancel()+ try:+ await forward_task+ except (asyncio.CancelledError, Exception):+ pass++ except WebSocketDisconnect:+ pass+ except Exception as exc:+ logger.error(f"Book WS connection error: {exc}", exc_info=True)+ finally:+ closed = True+ try:+ await ws.close()+ except Exception:+ passdiff --git a/deeptutor/api/routers/co_writer.py b/deeptutor/api/routers/co_writer.pyindex 6c3d2223b..e2d47a74c 100644--- a/deeptutor/api/routers/co_writer.py+++ b/deeptutor/api/routers/co_writer.py@@ -11,7 +11,7 @@ from pydantic import BaseModelimport json-from deeptutor.agents.co_writer.edit_agent import (+from deeptutor.co_writer.edit_agent import (TOOL_CALLS_DIR,EditAgent,load_history,diff --git a/deeptutor/api/routers/guide.py b/deeptutor/api/routers/guide.pydeleted file mode 100644index 39b748db7..000000000--- a/deeptutor/api/routers/guide.py+++ /dev/null@@ -1,485 +0,0 @@-"""-Guided Learning API Router-==========================--Provides session creation, learning progress management, and chat interaction.-"""--from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect-from pydantic import BaseModel--from deeptutor.agents.notebook import NotebookAnalysisAgent-from deeptutor.agents.base_agent import BaseAgent-from deeptutor.agents.guide.guide_manager import GuideManager-from deeptutor.api.utils.task_id_manager import TaskIDManager-from deeptutor.logging import get_logger-from deeptutor.services.config import PROJECT_ROOT, load_config_with_main-from deeptutor.services.llm import get_llm_config-from deeptutor.services.notebook import notebook_manager-from deeptutor.services.settings.interface_settings import get_ui_language--router = APIRouter()-_guide_manager: GuideManager | None = None--# Initialize logger with config-config = load_config_with_main("main.yaml", PROJECT_ROOT)-log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")-logger = get_logger("Guide", level="INFO", log_dir=log_dir)---# === Request/Response Models ===---class CreateSessionRequest(BaseModel):- """Create session request"""-- user_input: str = ""- notebook_id: str | None = None # Optional, single notebook mode- records: list[dict] | None = None # Optional, cross-notebook mode with direct records- notebook_references: list[dict] | None = None---class ChatRequest(BaseModel):- """Chat request"""-- session_id: str- message: str- knowledge_index: int | None = None---class FixHtmlRequest(BaseModel):- """Fix HTML request"""-- session_id: str- bug_description: str---class SessionActionRequest(BaseModel):- """Session action request"""-- session_id: str---class NavigateRequest(BaseModel):- """Navigate to a knowledge point."""-- session_id: str- knowledge_index: int---class RetryPageRequest(BaseModel):- """Retry a failed page generation."""-- session_id: str- page_index: int---# === Helper Functions ===---def get_guide_manager():- """Get GuideManager instance"""- global _guide_manager- if _guide_manager is not None:- return _guide_manager-- try:- llm_config = get_llm_config()- api_key = llm_config.api_key- base_url = llm_config.base_url- api_version = getattr(llm_config, "api_version", None)- binding = llm_config.binding- except Exception as e:- raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")-- ui_language = get_ui_language(default=config.get("system", {}).get("language", "en"))- _guide_manager = GuideManager(- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=ui_language,- binding=binding,- ) # Read from config file- return _guide_manager---def _build_user_input_from_records(records: list[dict]) -> str:- """Build a compact user input string from legacy record payloads."""- parts: list[str] = []- for record in records:- user_query = str(record.get("user_query", "")).strip()- if user_query:- parts.append(user_query)-- if not parts:- return ""-- joined = "\n".join(f"- {part}" for part in parts)- return f"Please design a guided learning plan based on these learner requests:\n{joined}"---# === REST API Endpoints ===--[email protected]("/create_session")-async def create_session(request: CreateSessionRequest):- """- Create a new guided learning session.-- Returns:- Session creation result with knowledge point list.- """- task_manager = TaskIDManager.get_instance()-- try:- user_input = request.user_input.strip()-- if not user_input and request.records and isinstance(request.records, list):- user_input = _build_user_input_from_records(request.records)- elif not user_input and request.notebook_id:- notebook = notebook_manager.get_notebook(request.notebook_id)- if not notebook:- raise HTTPException(status_code=404, detail="Notebook not found")- user_input = _build_user_input_from_records(notebook.get("records", []))-- if not user_input:- raise HTTPException(- status_code=400, detail="Must provide user_input, notebook_id, or records"- )-- raw_user_input = user_input- notebook_context = ""- if request.notebook_references:- selected_records = notebook_manager.get_records_by_references(request.notebook_references)- if selected_records:- analysis_agent = NotebookAnalysisAgent(language=get_ui_language(default="en"))- notebook_context = await analysis_agent.analyze(- user_question=raw_user_input,- records=selected_records,- )- user_input = (- f"[Notebook Context]\n{notebook_context}\n\n"- f"[User Question]\n{raw_user_input}"- )-- # Reset LLM stats for new session- BaseAgent.reset_stats("guide")-- manager = get_guide_manager()- result = await manager.create_session(- user_input=user_input,- display_title=raw_user_input,- notebook_context=notebook_context,- )-- if result and "session_id" in result:- session_id = result["session_id"]- task_id = task_manager.generate_task_id("guide", session_id)- logger.info(f"[{task_id}] Session created: {session_id}")-- return result-- except HTTPException:- raise- except Exception as e:- logger.error(f"Create session failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/start")-async def start_learning(request: SessionActionRequest):- """- Start learning (get the first knowledge point).- """- try:- manager = get_guide_manager()- result = await manager.start_learning(request.session_id)- return result- except Exception as e:- logger.error(f"Start learning failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/navigate")-async def navigate_to_knowledge(request: NavigateRequest):- """- Navigate to any knowledge point.- """- try:- manager = get_guide_manager()- result = await manager.navigate_to_knowledge(request.session_id, request.knowledge_index)- return result- except Exception as e:- logger.error(f"Navigate knowledge failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/complete")-async def complete_learning(request: SessionActionRequest):- """- Complete guided learning and generate a summary.- """- try:- manager = get_guide_manager()- result = await manager.complete_learning(request.session_id)- BaseAgent.print_stats("guide")- return result- except Exception as e:- logger.error(f"Complete learning failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/chat")-async def chat(request: ChatRequest):- """- Send a chat message.- """- try:- manager = get_guide_manager()- result = await manager.chat(request.session_id, request.message, request.knowledge_index)- return result- except Exception as e:- logger.error(f"Chat failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/fix_html")-async def fix_html(request: FixHtmlRequest):- """- Fix HTML page bugs.- """- try:- manager = get_guide_manager()- result = await manager.fix_html(request.session_id, request.bug_description)- return result- except Exception as e:- logger.error(f"Fix HTML failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/retry_page")-async def retry_page(request: RetryPageRequest):- """- Retry a failed page generation.- """- try:- manager = get_guide_manager()- result = await manager.retry_page(request.session_id, request.page_index)- return result- except Exception as e:- logger.error(f"Retry page failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/reset")-async def reset_session(request: SessionActionRequest):- """- Reset the current guided learning session.- """- try:- manager = get_guide_manager()- result = await manager.reset_session(request.session_id)- return result- except Exception as e:- logger.error(f"Reset session failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/session/{session_id}")-async def delete_session(session_id: str):- """- Permanently delete a guided learning session.- """- try:- manager = get_guide_manager()- result = await manager.delete_session(session_id)- return result- except Exception as e:- logger.error(f"Delete session failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/sessions")-async def list_sessions():- """- List all guided learning sessions (summary only, no HTML).- """- try:- manager = get_guide_manager()- sessions = manager.list_sessions()- return {"sessions": sessions}- except Exception as e:- logger.error(f"List sessions failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/session/{session_id}")-async def get_session(session_id: str):- """- Get session information.- """- try:- manager = get_guide_manager()- session = manager.get_session(session_id)- if not session:- raise HTTPException(status_code=404, detail="Session not found")- return session- except HTTPException:- raise- except Exception as e:- logger.error(f"Get session failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/session/{session_id}/html")-async def get_current_html(session_id: str):- """- Get the current HTML page.- """- try:- manager = get_guide_manager()- html = manager.get_current_html(session_id)- if html is None:- raise HTTPException(status_code=404, detail="Session not found or no HTML content")- return {"html": html}- except HTTPException:- raise- except Exception as e:- logger.error(f"Get HTML failed: {e}")- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/session/{session_id}/pages")-async def get_session_pages(session_id: str):- """- Get page generation status and ready HTML pages.- """- try:- manager = get_guide_manager()- pages = manager.get_session_pages(session_id)- if not pages:- raise HTTPException(status_code=404, detail="Session not found")- return pages- except HTTPException:- raise- except Exception as e:- logger.error(f"Get session pages failed: {e}")- raise HTTPException(status_code=500, detail=str(e))---# === WebSocket Endpoint ===--[email protected]("/ws/{session_id}")-async def websocket_guide(websocket: WebSocket, session_id: str):- """- WebSocket endpoint for real-time interaction.-- Message types:- - start: Start learning- - next: Next knowledge point- - chat: Send chat message- - fix_html: Fix HTML- - get_session: Get session state- """- await websocket.accept()-- task_manager = TaskIDManager.get_instance()- task_id = task_manager.generate_task_id("guide", session_id)-- try:- await websocket.send_json({"type": "task_id", "task_id": task_id})- except (RuntimeError, WebSocketDisconnect, ConnectionError) as e:- logger.debug(f"Failed to send task_id: {e}")-- try:- manager = get_guide_manager()-- session = manager.get_session(session_id)- if not session:- await websocket.send_json({"type": "error", "content": "Session not found"})- await websocket.close()- return-- logger.info(f"[{task_id}] Guide session started: {session_id}")-- await websocket.send_json({"type": "session_info", "data": session})-- while True:- try:- data = await websocket.receive_json()- msg_type = data.get("type", "")-- if msg_type == "start":- logger.debug(f"[{task_id}] Start learning")- result = await manager.start_learning(session_id)- await websocket.send_json({"type": "start_result", "data": result})-- elif msg_type == "navigate":- knowledge_index = int(data.get("knowledge_index", 0))- logger.debug(f"[{task_id}] Navigate to knowledge point {knowledge_index}")- result = await manager.navigate_to_knowledge(session_id, knowledge_index)- await websocket.send_json({"type": "navigate_result", "data": result})-- elif msg_type == "complete":- logger.debug(f"[{task_id}] Complete learning")- result = await manager.complete_learning(session_id)- await websocket.send_json({"type": "complete_result", "data": result})-- elif msg_type == "chat":- message = data.get("message", "")- knowledge_index = data.get("knowledge_index")- if message:- logger.debug(f"[{task_id}] User message: {message[:50]}...")- result = await manager.chat(session_id, message, knowledge_index)- await websocket.send_json({"type": "chat_result", "data": result})-- elif msg_type == "fix_html":- bug_desc = data.get("bug_description", "")- logger.debug(f"[{task_id}] Fix HTML: {bug_desc[:50]}...")- result = await manager.fix_html(session_id, bug_desc)- await websocket.send_json({"type": "fix_result", "data": result})-- elif msg_type == "get_session":- session = manager.get_session(session_id)- await websocket.send_json({"type": "session_info", "data": session})-- elif msg_type == "get_pages":- pages = manager.get_session_pages(session_id)- await websocket.send_json({"type": "pages_info", "data": pages})-- elif msg_type == "retry_page":- page_index = int(data.get("page_index", 0))- result = await manager.retry_page(session_id, page_index)- await websocket.send_json({"type": "retry_result", "data": result})-- elif msg_type == "reset":- result = await manager.reset_session(session_id)- await websocket.send_json({"type": "reset_result", "data": result})- await websocket.close()- return-- else:- await websocket.send_json(- {"type": "error", "content": f"Unknown message type: {msg_type}"}- )-- except WebSocketDisconnect:- logger.debug(f"WebSocket disconnected: {session_id}")- break- except Exception as e:- logger.error(f"WebSocket error: {e}")- await websocket.send_json({"type": "error", "content": str(e)})-- except Exception as e:- logger.error(f"WebSocket connection error: {e}")- try:- await websocket.close()- except (RuntimeError, WebSocketDisconnect, ConnectionError):- pass # Connection already closed--[email protected]("/health")-async def health_check():- """Health check"""- return {"status": "healthy", "service": "guide"}diff --git a/deeptutor/api/routers/notebook.py b/deeptutor/api/routers/notebook.pyindex 48fcb7a8d..b0ae77a15 100644--- a/deeptutor/api/routers/notebook.py+++ b/deeptutor/api/routers/notebook.py@@ -41,7 +41,7 @@ class AddRecordRequest(BaseModel):"""Add record request"""notebook_ids: list[str]- record_type: Literal["solve", "question", "research", "co_writer", "chat", "guided_learning"]+ record_type: Literal["solve", "question", "research", "co_writer", "chat"]title: strsummary: str = ""user_query: strdiff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 34ab91c30..fdc0a01f4 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -29,7 +29,7 @@ SETTINGS_FILE = _path_service.get_settings_file("interface")DEFAULT_SIDEBAR_NAV_ORDER = {"start": ["/", "/history", "/knowledge", "/notebook"],- "learnResearch": ["/question", "/solver", "/guide", "/research", "/co_writer"],+ "learnResearch": ["/question", "/solver", "/research", "/co_writer"],}DEFAULT_UI_SETTINGS = {diff --git a/deeptutor/api/routers/system.py b/deeptutor/api/routers/system.pyindex bfe061b05..b89e60df1 100644--- a/deeptutor/api/routers/system.py+++ b/deeptutor/api/routers/system.py@@ -51,7 +51,6 @@ async def get_runtime_topology():{"router": "research", "mode": "legacy_specialized"},],"isolated_subsystems": [- {"router": "guide", "mode": "independent_subsystem"},{"router": "co_writer", "mode": "independent_subsystem"},{"router": "plugins_api", "mode": "playground_transport"},],diff --git a/deeptutor/book/__init__.py b/deeptutor/book/__init__.pynew file mode 100644index 000000000..e5d8b26ff--- /dev/null+++ b/deeptutor/book/__init__.py@@ -0,0 +1,42 @@+"""+Book Engine+===========++Independent runtime engine that compiles user inputs (chat history, notebooks,+knowledge bases, intent) into structured, block-based, interactive "living+books". Sits parallel to ``ChatOrchestrator`` and reuses the existing+``ToolRegistry`` / ``CapabilityRegistry`` / ``StreamBus`` plumbing.+"""++from .engine import BookEngine, get_book_engine+from .models import (+ Block,+ BlockStatus,+ BlockType,+ Book,+ BookInputs,+ BookProposal,+ BookStatus,+ Chapter,+ Page,+ PageStatus,+ Progress,+ Spine,+)++__all__ = [+ "BookEngine",+ "get_book_engine",+ "Book",+ "BookInputs",+ "BookProposal",+ "BookStatus",+ "Spine",+ "Chapter",+ "Page",+ "PageStatus",+ "Block",+ "BlockType",+ "BlockStatus",+ "Progress",+]diff --git a/deeptutor/book/agents/__init__.py b/deeptutor/book/agents/__init__.pynew file mode 100644index 000000000..85f8457a1--- /dev/null+++ b/deeptutor/book/agents/__init__.py@@ -0,0 +1,15 @@+"""BookEngine agents: Ideation, SourceExplorer, Spine, PagePlanner."""++from .ideation_agent import IdeationAgent+from .page_planner import PagePlanner+from .source_explorer import SourceExplorer+from .spine_agent import SpineAgent+from .spine_synthesizer import SpineSynthesizer++__all__ = [+ "IdeationAgent",+ "SourceExplorer",+ "SpineAgent",+ "SpineSynthesizer",+ "PagePlanner",+]diff --git a/deeptutor/book/agents/ideation_agent.py b/deeptutor/book/agents/ideation_agent.pynew file mode 100644index 000000000..aae75fffc--- /dev/null+++ b/deeptutor/book/agents/ideation_agent.py@@ -0,0 +1,98 @@+"""+IdeationAgent+=============++Stage 1 of the BookEngine pipeline: turn an ``IdeationContext`` into a+``BookProposal`` that the user can confirm or edit before Spine generation.+"""++from __future__ import annotations++from typing import Any++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.utils.json_parser import parse_json_response++from ..inputs import IdeationContext+from ..models import BookProposal+++class IdeationAgent(BaseAgent):+ """LLM call that proposes a book given the four-source IdeationContext."""++ def __init__(+ self,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ language: str = "en",+ binding: str = "openai",+ ) -> None:+ super().__init__(+ module_name="book",+ agent_name="ideation_agent",+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ binding=binding,+ )++ async def process(+ self,+ *,+ ideation_context: IdeationContext,+ ) -> BookProposal:+ from ..blocks._language import language_directive++ system_prompt = self.get_prompt("system") or _FALLBACK_SYSTEM+ system_prompt = system_prompt.rstrip() + language_directive(self.language)+ user_template = self.get_prompt("user_template") or _FALLBACK_USER+ user_prompt = user_template.format(ideation_context=ideation_context.render())++ chunks: list[str] = []+ async for chunk in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="ideation",+ ):+ chunks.append(chunk)+ raw = "".join(chunks)++ payload = parse_json_response(raw, logger_instance=self.logger, fallback={})+ if not isinstance(payload, dict):+ payload = {}++ return self._coerce_proposal(payload, ideation_context)++ @staticmethod+ def _coerce_proposal(+ data: dict[str, Any], ctx: IdeationContext+ ) -> BookProposal:+ chapters_raw = data.get("estimated_chapters", 0) or 0+ try:+ estimated = max(2, min(8, int(chapters_raw)))+ except (TypeError, ValueError):+ estimated = 4++ title = str(data.get("title") or "Untitled Book").strip() or "Untitled Book"+ return BookProposal(+ title=title[:120],+ description=str(data.get("description") or "").strip(),+ scope=str(data.get("scope") or "").strip(),+ target_level=str(data.get("target_level") or "mixed").strip(),+ estimated_chapters=estimated,+ rationale=str(data.get("rationale") or "").strip(),+ )+++_FALLBACK_SYSTEM = (+ "Propose ONE coherent book that satisfies the learner's intent. "+ 'Output JSON: {"title", "description", "scope", "target_level", '+ '"estimated_chapters", "rationale"}.'+)+_FALLBACK_USER = "{ideation_context}\n\nRespond with the JSON object only."+++__all__ = ["IdeationAgent"]diff --git a/deeptutor/book/agents/page_planner.py b/deeptutor/book/agents/page_planner.pynew file mode 100644index 000000000..0f895f236--- /dev/null+++ b/deeptutor/book/agents/page_planner.py@@ -0,0 +1,335 @@+"""+Section Architect (formerly PagePlanner)+========================================++Stage 3 of the BookEngine pipeline. Translate a ``Chapter`` into a concrete+ordered list of ``Block`` shells (type + params + dependencies) ready for the+``BookCompiler`` to fill in.++BookEngine v2 architecture+--------------------------++The architect runs in two layers:++1. **LLM layer (``SectionArchitect.plan_blocks_async``)** — best effort. Calls+ one LLM with the chapter spec and (optionally) the cached+ ``ExplorationReport`` summary. The LLM returns a JSON ``blocks`` list with+ ``type``, ``focus``, ``transition_in``, and free-form ``params``. We+ validate / clip / coerce, then return.++2. **Static layer (``SectionArchitect.plan_blocks``)** — always available.+ Deterministic templates keyed on ``ContentType`` that *already* include+ ``SECTION`` blocks for chapter-grade prose plus optional ``transition_in``+ strings that the compiler turns into a short ``payload['bridge_text']``+ on the target block. Used as fallback when the LLM call is disabled or+ fails.++The legacy class name ``PagePlanner`` is kept as an alias to avoid touching+every importer in the codebase.+"""++from __future__ import annotations++from typing import Any++from deeptutor.logging import get_logger+from deeptutor.utils.json_parser import parse_json_response++from ..blocks._llm_writer import llm_text+from ..blocks._prompts import get_book_prompt, load_book_prompts+from ..models import (+ Block,+ BlockStatus,+ BlockType,+ Chapter,+ ContentType,+ ExplorationReport,+)++logger = get_logger("book.section_architect")+++# ─────────────────────────────────────────────────────────────────────────────+# Static templates (v2). Each entry is (BlockType, params overrides). SECTION+# blocks carry the long-form chapter content; supporting blocks may declare a+# ``transition_in`` so the compiler attaches a short ``bridge_text`` paragraph+# onto that block's payload.+# ─────────────────────────────────────────────────────────────────────────────+++_PHASE1_TYPES = {+ BlockType.TEXT,+ BlockType.CALLOUT,+ BlockType.QUIZ,+ BlockType.SECTION,+ BlockType.FIGURE,+ BlockType.INTERACTIVE,+ BlockType.CODE,+ BlockType.FLASH_CARDS,+ BlockType.TIMELINE,+ BlockType.ANIMATION,+}+++_TEMPLATES_V2: dict[ContentType, list[tuple[BlockType, dict[str, Any]]]] = {+ ContentType.THEORY: [+ (BlockType.SECTION, {"role": "introduction", "target_words": 1200}),+ (BlockType.FIGURE, {"variant": "diagram", "transition_in": "Visualising the core structure"}),+ (BlockType.SECTION, {"role": "deep_dive", "target_words": 1600}),+ (BlockType.CALLOUT, {"variant": "key_idea", "transition_in": "A key idea to remember"}),+ (BlockType.CODE, {"language": "python", "intent": "example", "transition_in": "A concrete example in code"}),+ (BlockType.SECTION, {"role": "synthesis", "target_words": 800}),+ (BlockType.QUIZ, {"num_questions": 3, "transition_in": "Check your understanding"}),+ (BlockType.FLASH_CARDS, {"count": 5, "transition_in": "Quick mental hooks"}),+ ],+ ContentType.DERIVATION: [+ (BlockType.SECTION, {"role": "setup", "target_words": 1400}),+ (BlockType.ANIMATION, {"focus": "core derivation", "transition_in": "Step through the derivation visually"}),+ (BlockType.SECTION, {"role": "formal_proof", "target_words": 1200}),+ (BlockType.CODE, {"language": "python", "intent": "verify", "transition_in": "Verify the result numerically"}),+ (BlockType.CALLOUT, {"variant": "insight", "transition_in": "What this result really means"}),+ (BlockType.SECTION, {"role": "interpretation", "target_words": 1000}),+ (BlockType.QUIZ, {"num_questions": 2, "transition_in": "Test your derivation skills"}),+ ],+ ContentType.HISTORY: [+ (BlockType.SECTION, {"role": "context", "target_words": 1200}),+ (BlockType.TIMELINE, {"transition_in": "The key milestones"}),+ (BlockType.SECTION, {"role": "narrative", "target_words": 1500}),+ (BlockType.FIGURE, {"variant": "illustration", "transition_in": "A period illustration"}),+ (BlockType.CALLOUT, {"variant": "connection", "transition_in": "Why this matters today"}),+ (BlockType.SECTION, {"role": "analysis", "target_words": 1000}),+ (BlockType.QUIZ, {"num_questions": 2, "transition_in": "Quick recap quiz"}),+ ],+ ContentType.PRACTICE: [+ (BlockType.SECTION, {"role": "brief", "target_words": 1000}),+ (BlockType.QUIZ, {"num_questions": 3, "difficulty": "easy", "transition_in": "Warm up"}),+ (BlockType.CODE, {"language": "python", "intent": "scaffold", "transition_in": "Try it yourself"}),+ (BlockType.SECTION, {"role": "walkthrough", "target_words": 1200}),+ (BlockType.INTERACTIVE, {"interaction": "guided exercise", "transition_in": "Practise interactively"}),+ (BlockType.QUIZ, {"num_questions": 3, "difficulty": "hard", "transition_in": "Now push further"}),+ (BlockType.CALLOUT, {"variant": "common_pitfall", "transition_in": "Watch out for these traps"}),+ ],+ ContentType.CONCEPT: [+ (BlockType.SECTION, {"role": "definition", "target_words": 1400}),+ (BlockType.FIGURE, {"variant": "mindmap", "transition_in": "Map the related concepts"}),+ (BlockType.SECTION, {"role": "examples", "target_words": 1200}),+ (BlockType.FLASH_CARDS, {"count": 5, "transition_in": "Hooks for recall"}),+ (BlockType.CALLOUT, {"variant": "common_pitfall", "transition_in": "Watch out for these"}),+ (BlockType.FIGURE, {"variant": "comparison", "transition_in": "Side-by-side comparison"}),+ (BlockType.QUIZ, {"num_questions": 3, "transition_in": "Self-check"}),+ ],+}+++_PHASE1_SUBSTITUTES: dict[BlockType, tuple[BlockType, dict[str, Any]]] = {}+++# ─────────────────────────────────────────────────────────────────────────────+# Static fallback planner+# ─────────────────────────────────────────────────────────────────────────────+++def _build_block(+ block_type: BlockType,+ params: dict[str, Any],+ chapter: Chapter,+) -> Block:+ transition_in = params.pop("transition_in", "")+ full_params: dict[str, Any] = {+ "chapter_title": chapter.title,+ "chapter_summary": chapter.summary,+ "objectives": chapter.learning_objectives,+ "anchors": [a.model_dump() for a in chapter.source_anchors],+ **params,+ }+ metadata: dict[str, Any] = {}+ if transition_in:+ metadata["transition_in"] = transition_in+ return Block(+ type=block_type,+ status=BlockStatus.PENDING,+ params=full_params,+ metadata=metadata,+ )+++def _static_plan(+ chapter: Chapter,+ *,+ phase: int,+) -> list[Block]:+ template = _TEMPLATES_V2.get(chapter.content_type) or _TEMPLATES_V2[+ ContentType.THEORY+ ]+ return [_build_block(bt, dict(params), chapter) for bt, params in template]+++# ─────────────────────────────────────────────────────────────────────────────+# LLM layer+# ─────────────────────────────────────────────────────────────────────────────+++_ALLOWED_LLM_TYPES = {+ BlockType.SECTION,+ BlockType.TEXT,+ BlockType.CALLOUT,+ BlockType.QUIZ,+ BlockType.FLASH_CARDS,+ BlockType.FIGURE,+ BlockType.INTERACTIVE,+ BlockType.ANIMATION,+ BlockType.CODE,+ BlockType.TIMELINE,+}+++def _architect_prompts(language: str) -> tuple[str, str]:+ """Return (system_prompt, user_template) for the SectionArchitect.++ The catalog block list and design principles live in+ ``deeptutor/book/prompts/{en,zh}/page_planner.yaml`` so they can be+ iterated on without touching python.+ """+ bundle = load_book_prompts("page_planner", language)+ catalog = get_book_prompt(bundle, "block_catalog")+ system_prompt = get_book_prompt(bundle, "architect_system").replace(+ "{block_catalog}", catalog+ )+ user_template = get_book_prompt(bundle, "architect_user")+ return system_prompt, user_template+++def _architect_user_prompt(+ *,+ chapter: Chapter,+ language: str,+ exploration_summary: str,+ user_template: str,+) -> str:+ none_label = "(无)" if language == "zh" else "(none)"+ objs = (+ "\n".join(f"- {o}" for o in chapter.learning_objectives) or none_label+ )+ return user_template.format(+ chapter_title=chapter.title,+ chapter_summary=chapter.summary or none_label,+ content_type=chapter.content_type.value,+ objectives_block=objs,+ exploration_summary=exploration_summary or none_label,+ )+++# ─────────────────────────────────────────────────────────────────────────────+# Public class+# ─────────────────────────────────────────────────────────────────────────────+++class SectionArchitect:+ """Pick block sequence for a chapter / page (LLM-aware, with fallback)."""++ def __init__(self, *, phase: int = 1, llm_enabled: bool = True) -> None:+ """+ Args:+ phase: 1 → only emit text/callout/quiz/section blocks; 2+ → use the+ full template (includes figure/interactive/animation/etc.).+ llm_enabled: When True, ``plan_blocks_async`` will try the LLM+ layer first and only fall back on failure. ``plan_blocks``+ (sync) always uses the static layer.+ """+ self.phase = phase+ self.llm_enabled = llm_enabled++ # ── Sync (legacy) ────────────────────────────────────────────────+ def plan_blocks(self, chapter: Chapter) -> list[Block]:+ """Static-template plan. Always succeeds."""+ return _static_plan(chapter, phase=self.phase)++ # ── Async (LLM-first) ────────────────────────────────────────────+ async def plan_blocks_async(+ self,+ chapter: Chapter,+ *,+ exploration: ExplorationReport | None = None,+ language: str = "en",+ ) -> list[Block]:+ if not self.llm_enabled:+ return self.plan_blocks(chapter)++ try:+ system_prompt, user_template = _architect_prompts(language)+ raw = await llm_text(+ user_prompt=_architect_user_prompt(+ chapter=chapter,+ language=language,+ exploration_summary=(exploration.summary if exploration else ""),+ user_template=user_template,+ ),+ system_prompt=system_prompt,+ max_tokens=1200,+ temperature=0.6,+ response_format={"type": "json_object"},+ language=language,+ )+ except Exception as exc:+ logger.warning(f"SectionArchitect LLM failed → fallback static: {exc}")+ return self.plan_blocks(chapter)++ payload = parse_json_response(raw, logger_instance=logger, fallback={})+ if not isinstance(payload, dict):+ return self.plan_blocks(chapter)++ items = payload.get("blocks")+ if not isinstance(items, list) or not items:+ return self.plan_blocks(chapter)++ blocks: list[Block] = []+ for raw_item in items[:12]:+ if not isinstance(raw_item, dict):+ continue+ type_str = str(raw_item.get("type") or "").strip().lower()+ try:+ block_type = BlockType(type_str)+ except ValueError:+ continue+ if block_type not in _ALLOWED_LLM_TYPES:+ continue++ params = _safe_dict(raw_item.get("params"))+ if raw_item.get("transition_in"):+ params["transition_in"] = str(raw_item["transition_in"])[:240]+ if raw_item.get("focus"):+ params["focus"] = str(raw_item["focus"])[:240]+ blocks.append(_build_block(block_type, params, chapter))++ if not blocks:+ return self.plan_blocks(chapter)++ # Coverage guarantee: ensure at least one SECTION block, otherwise we+ # silently lose chapter prose. Inject one at the front if missing.+ if self.phase >= 1 and not any(b.type == BlockType.SECTION for b in blocks):+ blocks.insert(+ 0,+ _build_block(+ BlockType.SECTION,+ {"role": "core", "target_words": 1700},+ chapter,+ ),+ )++ return blocks+++def _safe_dict(value: Any) -> dict[str, Any]:+ return value.copy() if isinstance(value, dict) else {}+++# Legacy alias used by existing callers (``compiler.py`` historically imported+# ``PagePlanner``). Calling ``.plan_blocks(chapter)`` keeps the old contract.+class PagePlanner(SectionArchitect):+ """Backward-compatible alias for :class:`SectionArchitect`."""++ def __init__(self, *, phase: int = 1) -> None:+ super().__init__(phase=phase, llm_enabled=False)+++__all__ = ["PagePlanner", "SectionArchitect"]diff --git a/deeptutor/book/agents/source_explorer.py b/deeptutor/book/agents/source_explorer.pynew file mode 100644index 000000000..4f486d210--- /dev/null+++ b/deeptutor/book/agents/source_explorer.py@@ -0,0 +1,510 @@+"""+SourceExplorer+==============++Stage 2 prep of the BookEngine pipeline.++Given the user's confirmed ``BookProposal`` plus the four-source ``BookInputs``+snapshot, ``SourceExplorer`` performs a *parallel multi-query sweep* over the+attached knowledge bases and additional sources (notebook records, recent chat+history, quiz entries) to produce an ``ExplorationReport``.++The report drives every subsequent stage of the pipeline:++- ``SpineSynthesizer`` reads ``summary`` + ``candidate_concepts`` to draft an+ evidence-grounded chapter spine and concept graph.+- ``SectionArchitect`` and individual ``BlockGenerator`` instances read+ ``chunks`` to avoid re-running RAG for the same query in later stages.++Two LLM calls happen here:++1. Query design (``queries_system`` / ``queries_user``) — turns the proposal+ into a small, diverse set of search queries.+2. Synthesis (``summary_system`` / ``summary_user``) — distils the retrieved+ chunks into a short summary, candidate concepts, and notes.++In between, RAG retrievals are executed *in parallel* across queries × KBs+via ``asyncio.gather``.+"""++from __future__ import annotations++import asyncio+from typing import Any++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.logging import get_logger+from deeptutor.utils.json_parser import parse_json_response++from ..models import (+ BookInputs,+ BookProposal,+ ExplorationReport,+ SourceChunk,+)++logger = get_logger("book.source_explorer")+++def _clip(text: str, limit: int) -> str:+ text = (text or "").strip()+ if len(text) <= limit:+ return text+ return text[:limit].rstrip() + "…"+++# ─────────────────────────────────────────────────────────────────────────────+# Defaults / fallbacks+# ─────────────────────────────────────────────────────────────────────────────+++_DEFAULT_QUERIES = [+ "overview and definition",+ "core mechanisms and theory",+ "representative examples and case studies",+ "common pitfalls and edge cases",+ "applications and use cases",+ "comparisons and history",+]+++_FALLBACK_QUERIES_SYSTEM = (+ "Design 4-8 short, diverse search queries that, run against the user's "+ "knowledge bases, will surface useful evidence for the proposed book. "+ 'Output JSON: {"queries": ["..."]}'+)+_FALLBACK_QUERIES_USER = (+ "Intent:\n{user_intent}\n\nProposal:\n{proposal_block}\n\n"+ "KBs: {kb_list}\n\nExtra context:\n{extra_context}\n\n"+ "Respond with the JSON object only."+)+_FALLBACK_SUMMARY_SYSTEM = (+ "Summarise the retrieved chunks. Output JSON: "+ '{"summary": str, "candidate_concepts": [str], "notes": [str]}.'+)+_FALLBACK_SUMMARY_USER = (+ "Intent:\n{user_intent}\n\nProposal title: {proposal_title}\n\n"+ "Coverage:\n{coverage_block}\n\nChunks:\n{chunks_block}\n\n"+ "Respond with the JSON object only."+)+++# ─────────────────────────────────────────────────────────────────────────────+# Agent+# ─────────────────────────────────────────────────────────────────────────────+++class SourceExplorer(BaseAgent):+ """Two-LLM-call agent that produces an ``ExplorationReport``."""++ def __init__(+ self,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ language: str = "en",+ binding: str = "openai",+ *,+ max_queries: int = 8,+ chunks_per_query: int = 4,+ ) -> None:+ super().__init__(+ module_name="book",+ agent_name="source_explorer",+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ binding=binding,+ )+ self.max_queries = max_queries+ self.chunks_per_query = chunks_per_query++ # ------------------------------------------------------------------ #+ # Public API+ # ------------------------------------------------------------------ #++ async def process(self, *args: Any, **kwargs: Any) -> Any:+ """``BaseAgent.process`` adapter — forwards to :meth:`explore`."""+ return await self.explore(*args, **kwargs)++ async def explore(+ self,+ *,+ book_id: str,+ proposal: BookProposal,+ inputs: BookInputs,+ ) -> ExplorationReport:+ """Run the full design → retrieve → summarise pipeline."""++ intent = (inputs.user_intent or proposal.description or "").strip()+ kb_list = list(inputs.knowledge_bases or [])++ queries = await self._design_queries(proposal=proposal, inputs=inputs)+ if not queries:+ queries = list(_DEFAULT_QUERIES)+ queries = queries[: self.max_queries]++ chunks: list[SourceChunk] = []+ if kb_list:+ chunks.extend(await self._retrieve_kb_chunks(queries, kb_list))++ chunks.extend(self._collect_non_kb_chunks(inputs))++ chunks = self._dedupe_and_clip(chunks)++ coverage: dict[str, int] = {}+ for ch in chunks:+ coverage[ch.source] = coverage.get(ch.source, 0) + 1++ summary, concepts, notes = await self._summarise(+ proposal=proposal,+ intent=intent,+ chunks=chunks,+ coverage=coverage,+ )++ return ExplorationReport(+ book_id=book_id,+ queries=queries,+ chunks=chunks,+ summary=summary,+ coverage=coverage,+ candidate_concepts=concepts,+ notes=notes,+ )++ # ------------------------------------------------------------------ #+ # Step 1 — query design+ # ------------------------------------------------------------------ #++ async def _design_queries(+ self,+ *,+ proposal: BookProposal,+ inputs: BookInputs,+ ) -> list[str]:+ from ..blocks._language import language_directive++ system_prompt = self.get_prompt("queries_system") or _FALLBACK_QUERIES_SYSTEM+ system_prompt = system_prompt.rstrip() + language_directive(self.language)+ user_template = self.get_prompt("queries_user") or _FALLBACK_QUERIES_USER++ intent = (inputs.user_intent or proposal.description or "").strip() or "(empty)"+ kb_list = ", ".join(inputs.knowledge_bases) or "(none)"+ proposal_block = (+ f"title: {proposal.title}\n"+ f"description: {proposal.description}\n"+ f"scope: {proposal.scope}\n"+ f"target_level: {proposal.target_level}\n"+ f"estimated_chapters: {proposal.estimated_chapters}"+ )+ extra_context_lines: list[str] = []+ if inputs.notebook_refs:+ extra_context_lines.append(+ f"- Notebook records selected: "+ f"{sum(len(r.record_ids) for r in inputs.notebook_refs) or 'all'}"+ )+ if inputs.chat_history:+ recent = inputs.chat_history[-4:]+ extra_context_lines.append(+ "- Recent chat highlights: "+ + " | ".join(_clip(m.content, 120) for m in recent)+ )+ if inputs.question_categories or inputs.question_entries:+ extra_context_lines.append(+ f"- Quiz items: cats={len(inputs.question_categories)} "+ f"entries={len(inputs.question_entries)}"+ )+ extra_context = "\n".join(extra_context_lines) or "(none)"++ user_prompt = user_template.format(+ user_intent=intent,+ proposal_block=proposal_block,+ kb_list=kb_list,+ extra_context=extra_context,+ )++ try:+ chunks: list[str] = []+ async for piece in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="explore_queries",+ ):+ chunks.append(piece)+ raw = "".join(chunks)+ except Exception as exc:+ logger.warning(f"SourceExplorer query LLM failed: {exc}")+ return []++ payload = parse_json_response(raw, logger_instance=self.logger, fallback={})+ if not isinstance(payload, dict):+ return []+ queries_raw = payload.get("queries")+ if not isinstance(queries_raw, list):+ return []++ seen: set[str] = set()+ result: list[str] = []+ for q in queries_raw:+ text = str(q or "").strip()+ if not text:+ continue+ key = text.lower()+ if key in seen:+ continue+ seen.add(key)+ result.append(text[:160])+ if len(result) >= self.max_queries:+ break+ return result++ # ------------------------------------------------------------------ #+ # Step 2 — parallel RAG retrieval+ # ------------------------------------------------------------------ #++ async def _retrieve_kb_chunks(+ self,+ queries: list[str],+ kb_list: list[str],+ ) -> list[SourceChunk]:+ try:+ from deeptutor.tools.rag_tool import rag_search+ except Exception as exc: # pragma: no cover - import guard+ logger.warning(f"rag_tool unavailable: {exc}")+ return []++ async def _one_query(kb: str, query: str) -> list[SourceChunk]:+ try:+ result = await rag_search(query=query, kb_name=kb)+ except Exception as exc:+ logger.debug(f"rag_search({kb}, {query!r}) failed: {exc}")+ return []+ if not isinstance(result, dict):+ return []+ sources = result.get("sources")+ if not isinstance(sources, list):+ return []++ answer = str(result.get("answer") or result.get("content") or "").strip()+ out: list[SourceChunk] = []+ for idx, src in enumerate(sources[: self.chunks_per_query]):+ if not isinstance(src, dict):+ continue+ ref = (+ src.get("id")+ or src.get("doc_id")+ or src.get("path")+ or src.get("source")+ or f"{kb}#{idx}"+ )+ text = (+ src.get("text")+ or src.get("snippet")+ or src.get("content")+ or ""+ )+ score = src.get("score") or src.get("similarity") or 0.0+ try:+ score_f = float(score)+ except (TypeError, ValueError):+ score_f = 0.0+ out.append(+ SourceChunk(+ chunk_id=str(ref)[:200],+ kb_name=kb,+ source="kb",+ ref=str(ref)[:200],+ text=_clip(str(text), 1200),+ score=score_f,+ query=query,+ )+ )+ # If RAG returned an answer but no usable sources, surface it as+ # a synthesised chunk so the spine still has something to chew on.+ if not out and answer:+ out.append(+ SourceChunk(+ chunk_id=f"{kb}::synth::{abs(hash(query)) % 10_000}",+ kb_name=kb,+ source="kb",+ ref=f"synthesised::{kb}",+ text=_clip(answer, 1200),+ score=0.0,+ query=query,+ metadata={"synthesised": True},+ )+ )+ return out++ coros = [_one_query(kb, q) for kb in kb_list for q in queries]+ if not coros:+ return []+ gathered = await asyncio.gather(*coros, return_exceptions=False)+ chunks: list[SourceChunk] = []+ for batch in gathered:+ chunks.extend(batch)+ return chunks++ # ------------------------------------------------------------------ #+ # Step 3 — non-KB sources (notebooks, chat, questions)+ # ------------------------------------------------------------------ #++ def _collect_non_kb_chunks(self, inputs: BookInputs) -> list[SourceChunk]:+ chunks: list[SourceChunk] = []++ # Notebook records+ try:+ if inputs.notebook_refs:+ from deeptutor.services.notebook import notebook_manager++ records = notebook_manager.get_records_by_references(+ [r.model_dump() for r in inputs.notebook_refs]+ )+ for rec in records[:24]:+ text = str(+ rec.get("summary")+ or rec.get("output")+ or rec.get("content")+ or rec.get("title")+ or ""+ ).strip()+ if not text:+ continue+ rid = str(rec.get("id") or rec.get("title") or "notebook")+ chunks.append(+ SourceChunk(+ chunk_id=f"nb::{rid}",+ source="notebook",+ ref=rid[:200],+ text=_clip(text, 1200),+ metadata={+ "notebook_name": rec.get("notebook_name") or "",+ "title": rec.get("title") or "",+ },+ )+ )+ except Exception as exc:+ logger.debug(f"Notebook chunk collection skipped: {exc}")++ # Chat snapshots+ for msg in (inputs.chat_history or [])[-24:]:+ text = (msg.content or "").strip()+ if len(text) < 20:+ continue+ chunks.append(+ SourceChunk(+ chunk_id=f"chat::{int(msg.created_at) or len(chunks)}",+ source="chat",+ ref=msg.role or "chat",+ text=_clip(text, 1200),+ metadata={+ "role": msg.role,+ "capability": msg.capability or "",+ },+ )+ )++ return chunks++ # ------------------------------------------------------------------ #+ # Step 4 — dedupe + clip+ # ------------------------------------------------------------------ #++ @staticmethod+ def _dedupe_and_clip(chunks: list[SourceChunk]) -> list[SourceChunk]:+ seen: set[str] = set()+ deduped: list[SourceChunk] = []+ for ch in chunks:+ key = f"{ch.source}::{ch.ref}::{ch.text[:200]}"+ if key in seen:+ continue+ seen.add(key)+ deduped.append(ch)+ return deduped[:96]++ # ------------------------------------------------------------------ #+ # Step 5 — synthesis LLM call+ # ------------------------------------------------------------------ #++ async def _summarise(+ self,+ *,+ proposal: BookProposal,+ intent: str,+ chunks: list[SourceChunk],+ coverage: dict[str, int],+ ) -> tuple[str, list[str], list[str]]:+ if not chunks:+ return ("", [], [])++ from ..blocks._language import language_directive++ system_prompt = self.get_prompt("summary_system") or _FALLBACK_SUMMARY_SYSTEM+ system_prompt = system_prompt.rstrip() + language_directive(self.language)+ user_template = self.get_prompt("summary_user") or _FALLBACK_SUMMARY_USER++ # Send only the most informative slice to the synthesiser.+ slice_chunks = sorted(chunks, key=lambda c: -c.score)[:24]+ chunks_block = "\n".join(+ f"- [{c.source}/{c.kb_name or 'n/a'}] (q={c.query!r}) {_clip(c.text, 320)}"+ for c in slice_chunks+ )+ coverage_block = ", ".join(f"{k}={v}" for k, v in coverage.items()) or "(none)"++ user_prompt = user_template.format(+ user_intent=intent or "(empty)",+ proposal_title=proposal.title,+ proposal_scope=proposal.scope,+ coverage_block=coverage_block,+ chunks_block=chunks_block,+ )++ try:+ buf: list[str] = []+ async for piece in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="explore_summary",+ ):+ buf.append(piece)+ raw = "".join(buf)+ except Exception as exc:+ logger.warning(f"SourceExplorer summary LLM failed: {exc}")+ return ("", [], [])++ payload = parse_json_response(raw, logger_instance=self.logger, fallback={})+ if not isinstance(payload, dict):+ return ("", [], [])++ summary = _clip(str(payload.get("summary") or ""), 2400)+ concepts_raw = payload.get("candidate_concepts")+ notes_raw = payload.get("notes")+ concepts = _coerce_str_list(concepts_raw, max_items=24, max_len=80)+ notes = _coerce_str_list(notes_raw, max_items=8, max_len=240)+ return summary, concepts, notes+++def _coerce_str_list(raw: Any, *, max_items: int, max_len: int) -> list[str]:+ if not isinstance(raw, list):+ return []+ out: list[str] = []+ seen: set[str] = set()+ for item in raw:+ text = str(item or "").strip()+ if not text:+ continue+ key = text.lower()+ if key in seen:+ continue+ seen.add(key)+ out.append(_clip(text, max_len))+ if len(out) >= max_items:+ break+ return out+++__all__ = ["SourceExplorer"]diff --git a/deeptutor/book/agents/spine_agent.py b/deeptutor/book/agents/spine_agent.pynew file mode 100644index 000000000..c411db71e--- /dev/null+++ b/deeptutor/book/agents/spine_agent.py@@ -0,0 +1,188 @@+"""+SpineAgent+==========++Stage 2 of the BookEngine pipeline. Given an approved ``BookProposal`` and+optional source material from the learner's knowledge bases, produce a+``Spine`` of chapters that the user can review and edit before compilation.+"""++from __future__ import annotations++from typing import Any++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.utils.json_parser import parse_json_response++from ..models import BookProposal, Chapter, ContentType, Spine, SourceAnchor+++def _clip(text: str, limit: int) -> str:+ text = (text or "").strip()+ if len(text) <= limit:+ return text+ return text[:limit].rstrip() + "…"+++class SpineAgent(BaseAgent):+ """LLM call that designs the chapter tree of a book."""++ def __init__(+ self,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ language: str = "en",+ binding: str = "openai",+ ) -> None:+ super().__init__(+ module_name="book",+ agent_name="spine_agent",+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ binding=binding,+ )++ async def process(+ self,+ *,+ book_id: str,+ proposal: BookProposal,+ source_material: str = "",+ ) -> Spine:+ system_prompt = self.get_prompt("system") or _FALLBACK_SYSTEM+ user_template = self.get_prompt("user_template") or _FALLBACK_USER+ proposal_block = (+ f"title: {proposal.title}\n"+ f"description: {proposal.description}\n"+ f"scope: {proposal.scope}\n"+ f"target_level: {proposal.target_level}\n"+ f"estimated_chapters: {proposal.estimated_chapters}\n"+ f"rationale: {proposal.rationale}"+ )+ user_prompt = user_template.format(+ proposal_block=proposal_block,+ source_material=source_material.strip() or "(no extra material provided)",+ )++ chunks: list[str] = []+ async for chunk in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="spine",+ ):+ chunks.append(chunk)+ raw = "".join(chunks)++ payload = parse_json_response(raw, logger_instance=self.logger, fallback={})+ if not isinstance(payload, dict):+ payload = {}++ chapters = self._coerce_chapters(payload.get("chapters"))+ if not chapters:+ # Fallback: fabricate a minimal spine so the pipeline can keep going+ chapters = [+ Chapter(+ title=f"{proposal.title} – Overview",+ learning_objectives=[+ "Understand the scope of this book",+ "Identify the key topics it will cover",+ ],+ content_type=ContentType.THEORY,+ summary=proposal.description or "Overview chapter.",+ order=0,+ )+ ]++ # Guarantee deterministic order field+ for idx, chapter in enumerate(chapters):+ chapter.order = idx++ return Spine(book_id=book_id, chapters=chapters)++ # ------------------------------------------------------------------ #+ # JSON → models+ # ------------------------------------------------------------------ #++ def _coerce_chapters(self, raw: Any) -> list[Chapter]:+ if not isinstance(raw, list):+ return []+ chapters: list[Chapter] = []+ seen_titles: set[str] = set()+ for item in raw:+ if not isinstance(item, dict):+ continue+ title = _clip(str(item.get("title") or ""), 160)+ if not title or title.lower() in seen_titles:+ continue+ seen_titles.add(title.lower())++ objectives_raw = item.get("learning_objectives") or []+ if not isinstance(objectives_raw, list):+ objectives_raw = []+ objectives = [+ _clip(str(o), 200) for o in objectives_raw if str(o or "").strip()+ ][:6]++ anchors = self._coerce_anchors(item.get("source_anchors"))+ content_type = self._coerce_content_type(item.get("content_type"))++ prereq_raw = item.get("prerequisites") or []+ if not isinstance(prereq_raw, list):+ prereq_raw = []+ prerequisites = [+ _clip(str(p), 160) for p in prereq_raw if str(p or "").strip()+ ][:4]++ chapters.append(+ Chapter(+ title=title,+ learning_objectives=objectives,+ content_type=content_type,+ source_anchors=anchors,+ prerequisites=prerequisites,+ summary=_clip(str(item.get("summary") or ""), 400),+ )+ )+ return chapters++ @staticmethod+ def _coerce_content_type(raw: Any) -> ContentType:+ try:+ return ContentType(str(raw or "theory").strip().lower())+ except ValueError:+ return ContentType.THEORY++ @staticmethod+ def _coerce_anchors(raw: Any) -> list[SourceAnchor]:+ if not isinstance(raw, list):+ return []+ anchors: list[SourceAnchor] = []+ for item in raw:+ if not isinstance(item, dict):+ continue+ anchors.append(+ SourceAnchor(+ kind=_clip(str(item.get("kind") or "manual"), 32),+ ref=_clip(str(item.get("ref") or ""), 200),+ snippet=_clip(str(item.get("snippet") or ""), 300),+ )+ )+ return anchors[:6]+++_FALLBACK_SYSTEM = (+ "Design a chapter tree for the approved BookProposal. "+ 'Output JSON: {"chapters": [{"title", "learning_objectives", "content_type", '+ '"source_anchors", "prerequisites", "summary"}]}.'+)+_FALLBACK_USER = (+ "Proposal:\n{proposal_block}\n\n"+ "Material:\n{source_material}\n\nRespond with the JSON object only."+)+++__all__ = ["SpineAgent"]diff --git a/deeptutor/book/agents/spine_synthesizer.py b/deeptutor/book/agents/spine_synthesizer.pynew file mode 100644index 000000000..b26892e01--- /dev/null+++ b/deeptutor/book/agents/spine_synthesizer.py@@ -0,0 +1,798 @@+"""+SpineSynthesizer+================++Stage 2 of the BookEngine pipeline (replaces the legacy ``SpineAgent``).++Implements a multi-round **Draft → Critique → Revise** reasoning loop driven+by an ``ExplorationReport`` produced by ``SourceExplorer``. The synthesiser+emits *both* a chapter ``Spine`` AND a directed ``ConceptGraph`` in a single+shot so the two stay in sync.++Pipeline (default ``max_rounds=2``):++1. **Draft** — one LLM call that produces ``{concept_graph, chapters}``.+2. **Critique** — second LLM call that checks coverage / ordering / cycles+ and returns ``{issues, verdict}``.+3. **Revise** — third LLM call that incorporates the critique.++If any LLM call fails, the synthesiser returns the last valid draft (or a+minimal fallback) so the pipeline never blocks.++After the LLM rounds, deterministic post-processing applies:++- **Topological sort** of chapters by ``covers`` + concept-graph dependencies.+- **Cycle removal** in the concept graph (drops the lowest-rationale edge).+- **Coverage padding** — concepts with no covering chapter are attached to+ the most relevant existing chapter (Jaccard over labels).+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Awaitable, Callable+from typing import Any++from deeptutor.agents.base_agent import BaseAgent+from deeptutor.logging import get_logger+from deeptutor.utils.json_parser import parse_json_response++from ..models import (+ BookProposal,+ Chapter,+ ConceptEdge,+ ConceptGraph,+ ConceptNode,+ ContentType,+ ExplorationReport,+ SourceAnchor,+ Spine,+)++logger = get_logger("book.spine_synthesizer")+++def _clip(text: str, limit: int) -> str:+ text = (text or "").strip()+ if len(text) <= limit:+ return text+ return text[:limit].rstrip() + "…"+++def _slug(text: str) -> str:+ cleaned = "".join(+ ch.lower() if ch.isalnum() else "_" for ch in (text or "").strip()+ )+ while "__" in cleaned:+ cleaned = cleaned.replace("__", "_")+ return cleaned.strip("_")[:48] or "concept"+++_FALLBACK_SYSTEM = (+ "Design BOTH a concept_graph and a chapter spine. "+ 'Output JSON with keys {"concept_graph": {"nodes":[...], "edges":[...]}, '+ '"chapters": [...]}.'+)+_FALLBACK_USER = "Proposal:\n{proposal_block}\n\nExploration:\n{exploration_summary}"+++# ─────────────────────────────────────────────────────────────────────────────+# Agent+# ─────────────────────────────────────────────────────────────────────────────+++class SpineSynthesizer(BaseAgent):+ """Draft → Critique → Revise spine designer with concept-graph output."""++ def __init__(+ self,+ api_key: str | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ language: str = "en",+ binding: str = "openai",+ *,+ max_rounds: int = 2,+ ) -> None:+ super().__init__(+ module_name="book",+ agent_name="spine_synthesizer",+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ language=language,+ binding=binding,+ )+ self.max_rounds = max(1, max_rounds)++ # ------------------------------------------------------------------ #+ # Public API+ # ------------------------------------------------------------------ #++ async def process(self, *args: Any, **kwargs: Any) -> Spine:+ """``BaseAgent.process`` adapter — forwards to :meth:`synthesize`."""+ return await self.synthesize(*args, **kwargs)++ async def synthesize(+ self,+ *,+ book_id: str,+ proposal: BookProposal,+ exploration: ExplorationReport | None,+ on_round: Callable[[str, dict[str, Any]], Awaitable[None] | None] | None = None,+ ) -> Spine:+ proposal_block = self._render_proposal(proposal)+ exploration_summary = (exploration.summary if exploration else "") or "(none)"+ candidate_concepts_text = (+ ", ".join(exploration.candidate_concepts)+ if exploration and exploration.candidate_concepts+ else "(none)"+ )+ chunks_block = self._render_chunks(exploration)++ # ── Round 1: Draft ─────────────────────────────────────────────+ draft = await self._draft(+ proposal_block=proposal_block,+ exploration_summary=exploration_summary,+ candidate_concepts_text=candidate_concepts_text,+ chunks_block=chunks_block,+ )+ if on_round:+ await _maybe_await(on_round("draft", draft))++ current = draft++ # ── Round 2+: Critique → Revise ───────────────────────────────+ for round_idx in range(1, self.max_rounds):+ critique = await self._critique(+ proposal_block=proposal_block,+ exploration_summary=exploration_summary,+ draft=current,+ )+ if on_round:+ await _maybe_await(on_round(f"critique_{round_idx}", critique))++ verdict = str(critique.get("verdict") or "").lower()+ issues = critique.get("issues") or []+ if verdict == "ok" or not issues:+ break++ revised = await self._revise(+ proposal_block=proposal_block,+ draft=current,+ critique=critique,+ )+ if revised:+ current = revised+ if on_round:+ await _maybe_await(on_round(f"revise_{round_idx}", current))++ spine = self._materialise(+ book_id=book_id,+ proposal=proposal,+ payload=current,+ exploration=exploration,+ )+ return spine++ # ------------------------------------------------------------------ #+ # Round helpers+ # ------------------------------------------------------------------ #++ async def _draft(+ self,+ *,+ proposal_block: str,+ exploration_summary: str,+ candidate_concepts_text: str,+ chunks_block: str,+ ) -> dict[str, Any]:+ system_prompt = self.get_prompt("draft_system") or _FALLBACK_SYSTEM+ user_template = self.get_prompt("draft_user") or _FALLBACK_USER+ user_prompt = user_template.format(+ proposal_block=proposal_block,+ exploration_summary=exploration_summary,+ candidate_concepts=candidate_concepts_text,+ chunks_block=chunks_block,+ )+ return await self._call_json(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ stage="spine_draft",+ )++ async def _critique(+ self,+ *,+ proposal_block: str,+ exploration_summary: str,+ draft: dict[str, Any],+ ) -> dict[str, Any]:+ system_prompt = self.get_prompt("critique_system")+ user_template = self.get_prompt("critique_user")+ if not system_prompt or not user_template:+ return {"issues": [], "verdict": "ok"}+ user_prompt = user_template.format(+ proposal_block=proposal_block,+ exploration_summary=exploration_summary,+ draft_block=_clip(_safe_json(draft), 4500),+ )+ result = await self._call_json(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ stage="spine_critique",+ )+ if not isinstance(result, dict):+ result = {"issues": [], "verdict": "ok"}+ return result++ async def _revise(+ self,+ *,+ proposal_block: str,+ draft: dict[str, Any],+ critique: dict[str, Any],+ ) -> dict[str, Any]:+ system_prompt = self.get_prompt("revise_system")+ user_template = self.get_prompt("revise_user")+ if not system_prompt or not user_template:+ return {}+ user_prompt = user_template.format(+ proposal_block=proposal_block,+ critique_block=_clip(_safe_json(critique), 2400),+ draft_block=_clip(_safe_json(draft), 4500),+ )+ return await self._call_json(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ stage="spine_revise",+ )++ async def _call_json(+ self,+ *,+ system_prompt: str,+ user_prompt: str,+ stage: str,+ ) -> dict[str, Any]:+ from ..blocks._language import language_directive++ system_prompt = system_prompt.rstrip() + language_directive(self.language)+ try:+ buf: list[str] = []+ async for piece in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage=stage,+ ):+ buf.append(piece)+ raw = "".join(buf)+ except Exception as exc:+ logger.warning(f"SpineSynthesizer LLM call ({stage}) failed: {exc}")+ return {}+ payload = parse_json_response(raw, logger_instance=self.logger, fallback={})+ return payload if isinstance(payload, dict) else {}++ # ------------------------------------------------------------------ #+ # Materialise: payload → Spine + ConceptGraph (with validation)+ # ------------------------------------------------------------------ #++ def _materialise(+ self,+ *,+ book_id: str,+ proposal: BookProposal,+ payload: dict[str, Any],+ exploration: ExplorationReport | None,+ ) -> Spine:+ raw_graph = self._coerce_graph(payload.get("concept_graph"))+ chapters_raw = payload.get("chapters")+ chapters = self._coerce_chapters(chapters_raw, raw_graph)++ if not chapters:+ chapters = [+ Chapter(+ title=f"{proposal.title} – Overview",+ learning_objectives=[+ "Understand the scope of this book",+ "Identify the key topics it will cover",+ ],+ content_type=ContentType.THEORY,+ summary=proposal.description or "Overview chapter.",+ order=0,+ )+ ]++ # ── Validation passes (uses the raw LLM concept graph) ────────+ raw_graph = _remove_cycles(raw_graph)+ chapters = _topological_sort(chapters, raw_graph)+ raw_graph = _ensure_full_coverage(chapters, raw_graph)++ for idx, chapter in enumerate(chapters):+ chapter.order = idx++ # ── Build a chapter-level mind map for the Overview page ──────+ # The raw concept graph served its purpose (topological ordering).+ # The user-facing graph should map 1-to-1 with chapters so the+ # Overview concept map reads like a mind map of the book.+ chapter_map = _build_chapter_map(+ chapters, raw_graph, book_title=proposal.title,+ )++ return Spine(+ book_id=book_id,+ chapters=chapters,+ concept_graph=chapter_map,+ exploration_summary=(exploration.summary if exploration else ""),+ )++ # ------------------------------------------------------------------ #+ # Coercers+ # ------------------------------------------------------------------ #++ @staticmethod+ def _coerce_graph(raw: Any) -> ConceptGraph:+ if not isinstance(raw, dict):+ return ConceptGraph()+ nodes_raw = raw.get("nodes") or []+ edges_raw = raw.get("edges") or []++ nodes: list[ConceptNode] = []+ seen_ids: set[str] = set()+ for item in nodes_raw if isinstance(nodes_raw, list) else []:+ if not isinstance(item, dict):+ continue+ label = _clip(str(item.get("label") or ""), 80)+ if not label:+ continue+ nid = _slug(str(item.get("id") or label))+ if not nid or nid in seen_ids:+ continue+ seen_ids.add(nid)+ try:+ weight = float(item.get("weight", 1.0))+ except (TypeError, ValueError):+ weight = 1.0+ nodes.append(+ ConceptNode(+ id=nid,+ label=label,+ description=_clip(str(item.get("description") or ""), 240),+ weight=max(0.05, min(1.0, weight)),+ )+ )++ edges: list[ConceptEdge] = []+ seen_edges: set[tuple[str, str, str]] = set()+ for item in edges_raw if isinstance(edges_raw, list) else []:+ if not isinstance(item, dict):+ continue+ src = _slug(str(item.get("src") or ""))+ dst = _slug(str(item.get("dst") or ""))+ if not src or not dst or src == dst:+ continue+ if src not in seen_ids or dst not in seen_ids:+ continue+ relation = str(item.get("relation") or "depends_on").strip().lower()+ if relation not in {"depends_on", "extends", "related"}:+ relation = "depends_on"+ key = (src, dst, relation)+ if key in seen_edges:+ continue+ seen_edges.add(key)+ edges.append(+ ConceptEdge(+ src=src,+ dst=dst,+ relation=relation,+ rationale=_clip(str(item.get("rationale") or ""), 240),+ )+ )++ return ConceptGraph(nodes=nodes, edges=edges)++ @staticmethod+ def _coerce_chapters(raw: Any, graph: ConceptGraph) -> list[Chapter]:+ if not isinstance(raw, list):+ return []+ node_ids = {n.id for n in graph.nodes}+ chapters: list[Chapter] = []+ seen_titles: set[str] = set()+ for item in raw:+ if not isinstance(item, dict):+ continue+ title = _clip(str(item.get("title") or ""), 160)+ if not title or title.lower() in seen_titles:+ continue+ seen_titles.add(title.lower())++ objectives_raw = item.get("learning_objectives") or []+ if not isinstance(objectives_raw, list):+ objectives_raw = []+ objectives = [+ _clip(str(o), 200) for o in objectives_raw if str(o or "").strip()+ ][:6]++ anchors_raw = item.get("source_anchors") or []+ anchors: list[SourceAnchor] = []+ if isinstance(anchors_raw, list):+ for anchor_item in anchors_raw[:6]:+ if not isinstance(anchor_item, dict):+ continue+ anchors.append(+ SourceAnchor(+ kind=_clip(str(anchor_item.get("kind") or "manual"), 32),+ ref=_clip(str(anchor_item.get("ref") or ""), 200),+ snippet=_clip(str(anchor_item.get("snippet") or ""), 300),+ )+ )++ content_type = ContentType.THEORY+ try:+ content_type = ContentType(+ str(item.get("content_type") or "theory").strip().lower()+ )+ except ValueError:+ content_type = ContentType.THEORY+ if content_type == ContentType.OVERVIEW:+ # Overview is reserved for engine-injected first chapter.+ content_type = ContentType.THEORY++ prereq_raw = item.get("prerequisites") or []+ prerequisites = (+ [_clip(str(p), 160) for p in prereq_raw if str(p or "").strip()][:4]+ if isinstance(prereq_raw, list)+ else []+ )++ covers_raw = item.get("covers") or []+ covers = []+ if isinstance(covers_raw, list):+ for c in covers_raw:+ cid = _slug(str(c or ""))+ if cid and cid in node_ids and cid not in covers:+ covers.append(cid)++ chapter = Chapter(+ title=title,+ learning_objectives=objectives,+ content_type=content_type,+ source_anchors=anchors,+ prerequisites=prerequisites,+ summary=_clip(str(item.get("summary") or ""), 400),+ )+ # Stash covered concept ids on the chapter (extra="allow" enabled).+ chapter.__pydantic_extra__ = chapter.__pydantic_extra__ or {}+ chapter.__pydantic_extra__["covers"] = covers+ chapters.append(chapter)+ return chapters++ # ------------------------------------------------------------------ #+ # Renderers+ # ------------------------------------------------------------------ #++ @staticmethod+ def _render_proposal(proposal: BookProposal) -> str:+ return (+ f"title: {proposal.title}\n"+ f"description: {proposal.description}\n"+ f"scope: {proposal.scope}\n"+ f"target_level: {proposal.target_level}\n"+ f"estimated_chapters: {proposal.estimated_chapters}\n"+ f"rationale: {proposal.rationale}"+ )++ @staticmethod+ def _render_chunks(exploration: ExplorationReport | None) -> str:+ if not exploration or not exploration.chunks:+ return "(no exploration evidence)"+ slice_chunks = sorted(exploration.chunks, key=lambda c: -c.score)[:18]+ lines = []+ for ch in slice_chunks:+ tag = ch.kb_name or ch.source+ lines.append(f"- [{tag}] {_clip(ch.text, 280)}")+ return "\n".join(lines)+++# ─────────────────────────────────────────────────────────────────────────────+# Validation helpers+# ─────────────────────────────────────────────────────────────────────────────+++def _build_chapter_map(+ chapters: list[Chapter],+ raw_graph: ConceptGraph,+ *,+ book_title: str = "",+) -> ConceptGraph:+ """Derive a chapter-level mind map where each node IS a chapter.++ Edges come from two sources (merged, deduplicated):+ 1. Concept-graph ``depends_on`` edges — lifted to chapter level via the+ ``covers`` mapping (chapter A covers prerequisite concept, chapter B+ covers dependent concept → edge A→B).+ 2. Explicit ``prerequisites`` on each chapter (matched by title).++ If multiple root chapters exist (no incoming edges) and a *book_title* is+ given, a virtual root node is added to form a connected tree, giving the+ rendered Mermaid diagram a clear mind-map shape.+ """++ # ── Node per chapter ──────────────────────────────────────────────+ slug_of: dict[str, str] = {} # chapter.id → slug+ title_to_slug: dict[str, str] = {} # chapter.title.lower() → slug+ concept_to_slug: dict[str, str] = {} # concept_id → owning chapter slug+ nodes: list[ConceptNode] = []++ for idx, ch in enumerate(chapters):+ slug = _slug(ch.title) or f"ch_{idx}"+ # Ensure uniqueness+ base = slug+ counter = 2+ while slug in {n.id for n in nodes}:+ slug = f"{base}_{counter}"+ counter += 1++ slug_of[ch.id] = slug+ title_to_slug[ch.title.strip().lower()] = slug+ for cid in (ch.__pydantic_extra__ or {}).get("covers") or []:+ concept_to_slug.setdefault(cid, slug)++ nodes.append(+ ConceptNode(+ id=slug,+ label=ch.title,+ description=ch.summary or "",+ weight=1.0,+ chapter_id=ch.id,+ )+ )++ # ── Edges: concept-graph dependencies lifted to chapter level ─────+ seen_edges: set[tuple[str, str]] = set()+ edges: list[ConceptEdge] = []++ for edge in raw_graph.edges:+ if edge.relation != "depends_on":+ continue+ src_slug = concept_to_slug.get(edge.src)+ dst_slug = concept_to_slug.get(edge.dst)+ if not src_slug or not dst_slug or src_slug == dst_slug:+ continue+ pair = (src_slug, dst_slug)+ if pair in seen_edges:+ continue+ seen_edges.add(pair)+ edges.append(+ ConceptEdge(src=src_slug, dst=dst_slug, relation="depends_on",+ rationale=edge.rationale)+ )++ # ── Edges: explicit prerequisite titles ───────────────────────────+ for ch in chapters:+ dst_slug = slug_of.get(ch.id)+ if not dst_slug:+ continue+ for prereq_title in ch.prerequisites:+ src_slug = title_to_slug.get(prereq_title.strip().lower())+ if not src_slug or src_slug == dst_slug:+ continue+ pair = (src_slug, dst_slug)+ if pair in seen_edges:+ continue+ seen_edges.add(pair)+ edges.append(+ ConceptEdge(src=src_slug, dst=dst_slug, relation="depends_on",+ rationale="")+ )++ # ── Virtual root for disconnected graphs ──────────────────────────+ incoming = {e.dst for e in edges}+ roots = [n for n in nodes if n.id not in incoming]+ if len(roots) > 1 and book_title:+ root_slug = _slug(book_title) or "book"+ if root_slug in {n.id for n in nodes}:+ root_slug = f"{root_slug}_root"+ root_node = ConceptNode(+ id=root_slug, label=book_title, description="", weight=1.0,+ )+ nodes.insert(0, root_node)+ for rn in roots:+ edges.append(+ ConceptEdge(src=root_slug, dst=rn.id, relation="related",+ rationale="")+ )++ return ConceptGraph(nodes=nodes, edges=edges)+++def _remove_cycles(graph: ConceptGraph) -> ConceptGraph:+ """Drop the weakest ``depends_on`` edge in any detected cycle."""+ if not graph.edges:+ return graph++ edges = [e for e in graph.edges]+ node_ids = {n.id for n in graph.nodes}++ def _find_cycle(active_edges: list[ConceptEdge]) -> list[str] | None:+ adj: dict[str, list[str]] = defaultdict(list)+ for e in active_edges:+ if e.relation == "depends_on":+ adj[e.src].append(e.dst)+ color: dict[str, int] = {n: 0 for n in node_ids}+ stack: list[str] = []++ def dfs(node: str) -> list[str] | None:+ color[node] = 1+ stack.append(node)+ for nxt in adj.get(node, []):+ if color.get(nxt) == 1:+ idx = stack.index(nxt)+ return stack[idx:] + [nxt]+ if color.get(nxt) == 0:+ cyc = dfs(nxt)+ if cyc:+ return cyc+ stack.pop()+ color[node] = 2+ return None++ for n in list(node_ids):+ if color.get(n) == 0:+ cyc = dfs(n)+ if cyc:+ return cyc+ return None++ safety = 0+ while safety < 20:+ cycle = _find_cycle(edges)+ if cycle is None:+ break+ cycle_pairs = set(zip(cycle, cycle[1:]))+ candidates = [e for e in edges if (e.src, e.dst) in cycle_pairs]+ if not candidates:+ break+ # Drop the edge with the least rationale (proxy for confidence).+ weakest = min(candidates, key=lambda e: len(e.rationale or ""))+ edges.remove(weakest)+ logger.debug(f"SpineSynthesizer dropped cycle edge {weakest.src}→{weakest.dst}")+ safety += 1++ return ConceptGraph(nodes=graph.nodes, edges=edges)+++def _topological_sort(chapters: list[Chapter], graph: ConceptGraph) -> list[Chapter]:+ """Re-order chapters so that ``covers`` follow concept-graph dependencies.++ Falls back to original order on any inconsistency.+ """+ if not chapters or not graph.nodes:+ return chapters++ # Map each concept id → first chapter index that covers it.+ chapter_of: dict[str, int] = {}+ for idx, chapter in enumerate(chapters):+ covers = (chapter.__pydantic_extra__ or {}).get("covers") or []+ for nid in covers:+ chapter_of.setdefault(nid, idx)++ # Build chapter-level dependency graph.+ n = len(chapters)+ chapter_adj: dict[int, set[int]] = defaultdict(set)+ indeg: dict[int, int] = {i: 0 for i in range(n)}+ for edge in graph.edges:+ if edge.relation != "depends_on":+ continue+ src_idx = chapter_of.get(edge.src)+ dst_idx = chapter_of.get(edge.dst)+ if src_idx is None or dst_idx is None or src_idx == dst_idx:+ continue+ if dst_idx in chapter_adj[src_idx]:+ continue+ chapter_adj[src_idx].add(dst_idx)+ indeg[dst_idx] += 1++ # Kahn — break ties by original order to keep author intent.+ ready = sorted([i for i in range(n) if indeg[i] == 0])+ ordered: list[int] = []+ while ready:+ i = ready.pop(0)+ ordered.append(i)+ for j in sorted(chapter_adj[i]):+ indeg[j] -= 1+ if indeg[j] == 0:+ ready.append(j)+ ready.sort()++ if len(ordered) != n:+ # Cycle in chapter graph → bail out, keep original order.+ return chapters+ return [chapters[i] for i in ordered]+++def _ensure_full_coverage(+ chapters: list[Chapter], graph: ConceptGraph+) -> ConceptGraph:+ """Attach uncovered concept nodes to the most relevant chapter (Jaccard)."""+ if not graph.nodes or not chapters:+ return graph++ covered: set[str] = set()+ for ch in chapters:+ for nid in (ch.__pydantic_extra__ or {}).get("covers") or []:+ covered.add(nid)++ def _tokenize(text: str) -> set[str]:+ return {+ t for t in (text or "").lower().replace("_", " ").split() if len(t) > 1+ }++ chapter_tokens = [+ _tokenize(f"{ch.title} {ch.summary} {' '.join(ch.learning_objectives)}")+ for ch in chapters+ ]++ for node in graph.nodes:+ if node.id in covered:+ continue+ node_tokens = _tokenize(f"{node.label} {node.description}")+ if not node_tokens:+ target_idx = 0+ else:+ best_idx = 0+ best_score = -1.0+ for idx, ctoks in enumerate(chapter_tokens):+ if not ctoks:+ score = 0.0+ else:+ inter = len(node_tokens & ctoks)+ union = len(node_tokens | ctoks)+ score = inter / union if union else 0.0+ if score > best_score:+ best_idx = idx+ best_score = score+ target_idx = best_idx++ target = chapters[target_idx]+ target.__pydantic_extra__ = target.__pydantic_extra__ or {}+ covers = list(target.__pydantic_extra__.get("covers") or [])+ if node.id not in covers:+ covers.append(node.id)+ target.__pydantic_extra__["covers"] = covers+ node.chapter_id = target.id+ covered.add(node.id)++ # Fill chapter_id for nodes already covered.+ for ch in chapters:+ for nid in (ch.__pydantic_extra__ or {}).get("covers") or []:+ node = graph.node_by_id(nid)+ if node and not node.chapter_id:+ node.chapter_id = ch.id++ return graph+++# ─────────────────────────────────────────────────────────────────────────────+# Misc helpers+# ─────────────────────────────────────────────────────────────────────────────+++def _safe_json(payload: Any) -> str:+ import json++ try:+ return json.dumps(payload, ensure_ascii=False)+ except Exception:+ return str(payload)+++async def _maybe_await(value: Any) -> None:+ import inspect++ if inspect.isawaitable(value):+ await value+++__all__ = ["SpineSynthesizer"]diff --git a/deeptutor/book/blocks/__init__.py b/deeptutor/book/blocks/__init__.pynew file mode 100644index 000000000..85a2d533c--- /dev/null+++ b/deeptutor/book/blocks/__init__.py@@ -0,0 +1,42 @@+"""Block generators – one per ``BlockType``."""++from .base import (+ BlockContext,+ BlockGenerator,+ BlockGeneratorRegistry,+ GenerationFailure,+ get_block_registry,+)+from .callout import CalloutGenerator+from .quiz import QuizGenerator+from .text import TextGenerator, generate_bridge_text+from .user_note import UserNoteGenerator++# Phase 2+ generators+from .animation import AnimationGenerator+from .code import CodeGenerator+from .deep_dive import DeepDiveGenerator+from .figure import FigureGenerator+from .flash_cards import FlashCardsGenerator+from .interactive import InteractiveGenerator+from .timeline import TimelineGenerator++__all__ = [+ "BlockContext",+ "BlockGenerator",+ "BlockGeneratorRegistry",+ "GenerationFailure",+ "get_block_registry",+ "TextGenerator",+ "generate_bridge_text",+ "CalloutGenerator",+ "QuizGenerator",+ "UserNoteGenerator",+ "FigureGenerator",+ "InteractiveGenerator",+ "AnimationGenerator",+ "CodeGenerator",+ "TimelineGenerator",+ "FlashCardsGenerator",+ "DeepDiveGenerator",+]diff --git a/deeptutor/book/blocks/_language.py b/deeptutor/book/blocks/_language.pynew file mode 100644index 000000000..98131b32b--- /dev/null+++ b/deeptutor/book/blocks/_language.py@@ -0,0 +1,74 @@+"""Shared language directive for BookEngine LLM prompts.++Every block generator and agent that writes user-facing prose should append+``language_directive(language)`` to its **system prompt**. This guarantees the+output stays in the book's chosen language even when the rest of the prompt+contains English token names (block types, role hints, JSON keys, etc.) or+when the underlying source material is in a different language.+"""++from __future__ import annotations+++_LANGUAGE_LABELS: dict[str, str] = {+ "zh": "中文(简体)",+ "zh-cn": "中文(简体)",+ "zh-tw": "繁體中文",+ "en": "English",+ "ja": "日本語",+ "ko": "한국어",+ "es": "Español",+ "fr": "Français",+ "de": "Deutsch",+ "ru": "Русский",+ "pt": "Português",+ "it": "Italiano",+}+++def normalize_language(language: str | None) -> str:+ return (language or "en").strip().lower() or "en"+++def language_label(language: str | None) -> str:+ code = normalize_language(language)+ if code in _LANGUAGE_LABELS:+ return _LANGUAGE_LABELS[code]+ base = code.split("-", 1)[0]+ return _LANGUAGE_LABELS.get(base, language or "English")+++def language_directive(language: str | None) -> str:+ """Strict instruction that forces the LLM to respond in *language*.++ The directive is intentionally repetitive — empirically that's what gets+ LLMs to stop drifting back to English when the prompt mixes languages.+ """+ code = normalize_language(language)+ label = language_label(code)+ if code.startswith("zh"):+ return (+ "\n\n[语言要求 / Language] "+ f"请严格使用{label}撰写所有面向读者的文本(标题、正文、解释、提示、过渡句、"+ "题干、选项等),即使参考资料、JSON 字段名或英文术语出现在 prompt 中也"+ "不得切换语言;保留必要的专有名词原文(如人名、产品名、公式中的变量符号"+ f"等)即可,其余一律使用{label}。"+ )+ if code == "en":+ return (+ "\n\n[Language] Write ALL reader-facing text (titles, prose, "+ "explanations, hints, transitions, quiz stems, options, etc.) in "+ "English. Do NOT switch languages even if the source material, "+ "JSON keys, or examples in this prompt are in another language. "+ "Keep proper nouns (people, products, formula symbols) in their "+ "original form."+ )+ return (+ f"\n\n[Language] Write ALL reader-facing text strictly in {label}. "+ "Do NOT switch languages even if the source material, JSON keys, or "+ "examples in this prompt are in a different language. Keep proper "+ "nouns (people, products, formula symbols) in their original form."+ )+++__all__ = ["language_directive", "language_label", "normalize_language"]diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.pynew file mode 100644index 000000000..16c6f47f2--- /dev/null+++ b/deeptutor/book/blocks/_llm_writer.py@@ -0,0 +1,62 @@+"""+Shared LLM helper for text-flavoured block generators.++Avoids subclassing BaseAgent for these tiny calls; instead uses+``deeptutor.services.llm.complete`` directly with a sane default config.+"""++from __future__ import annotations++from typing import Any++from deeptutor.services.llm import (+ clean_thinking_tags,+ complete as llm_complete,+ get_llm_config,+ get_token_limit_kwargs,+)++from ._language import language_directive+++async def llm_text(+ *,+ user_prompt: str,+ system_prompt: str,+ max_tokens: int = 1200,+ temperature: float = 0.4,+ response_format: dict[str, Any] | None = None,+ language: str | None = None,+) -> str:+ """Run an LLM completion for a Book block / agent.++ Pass ``language`` (the book's chosen language code, e.g. ``"zh"`` or+ ``"en"``) and the helper appends a strict language directive to the+ system prompt. This is the single chokepoint that prevents the LLM from+ drifting between languages when prompts contain English token names,+ JSON keys, or non-matching source material.+ """+ if language:+ system_prompt = system_prompt.rstrip() + language_directive(language)++ config = get_llm_config()+ model = config.model+ binding = getattr(config, "binding", None) or "openai"+ kwargs: dict[str, Any] = {"temperature": temperature}+ kwargs.update(get_token_limit_kwargs(model, max_tokens))+ if response_format:+ kwargs["response_format"] = response_format+ response = await llm_complete(+ prompt=user_prompt,+ system_prompt=system_prompt,+ model=model,+ api_key=config.api_key,+ base_url=config.base_url,+ api_version=getattr(config, "api_version", None),+ binding=binding,+ **kwargs,+ )+ return clean_thinking_tags(response, binding, model).strip()+++__all__ = ["llm_text"]diff --git a/deeptutor/book/blocks/_prompts.py b/deeptutor/book/blocks/_prompts.pynew file mode 100644index 000000000..8d8ed0224--- /dev/null+++ b/deeptutor/book/blocks/_prompts.py@@ -0,0 +1,69 @@+"""+Shared prompt loader for non-BaseAgent call sites in ``deeptutor/book``.++All LLM-facing prompts inside this module live as YAML under+``deeptutor/book/prompts/{en,zh}/<name>.yaml`` and are loaded through the+unified :class:`~deeptutor.services.prompt.PromptManager`. This helper is the+thin wrapper that block generators and the SectionArchitect use, since they+call ``llm_text`` directly instead of inheriting :class:`BaseAgent`.++Conventions+-----------+* One YAML file per logical writer (block generator, planner stage…), named+ after the python module (``text.py`` → ``text.yaml``).+* Top-level keys are short identifiers (``system``, ``user_template``,+ ``bridge_system``, ``outline_system``…) and contain plain strings.+* Variable interpolation uses ``str.format`` placeholders (``{chapter_title}``).++Missing files / keys raise :class:`RuntimeError` so the failure surfaces at+the call site instead of silently producing degenerate prompts.+"""++from __future__ import annotations++from typing import Any++from deeptutor.services.prompt import get_prompt_manager+++def load_book_prompts(name: str, language: str) -> dict[str, Any]:+ """Load a YAML prompt bundle for the ``book`` module.++ Args:+ name: File stem under ``deeptutor/book/prompts/{lang}/``+ (e.g. ``"text"``, ``"section"``, ``"page_planner"``).+ language: ``"en"`` or ``"zh"``.++ Returns:+ Parsed YAML as a dictionary.++ Raises:+ RuntimeError: When the bundle is missing or empty.+ """+ prompts = get_prompt_manager().load_prompts(+ module_name="book",+ agent_name=name,+ language=language,+ )+ if not prompts:+ raise RuntimeError(+ f"Missing prompt bundle for book/{name} (language={language}). "+ f"Expected deeptutor/book/prompts/{{en,zh}}/{name}.yaml."+ )+ return prompts+++def get_book_prompt(prompts: dict[str, Any], key: str) -> str:+ """Return the prompt string under ``key`` from a loaded bundle.++ Raises ``RuntimeError`` if the key is missing or not a non-empty string.+ """+ value = prompts.get(key)+ if not isinstance(value, str) or not value.strip():+ raise RuntimeError(+ f"Prompt key '{key}' missing or empty in loaded book prompt bundle."+ )+ return value+++__all__ = ["load_book_prompts", "get_book_prompt"]diff --git a/deeptutor/book/blocks/_rag_helpers.py b/deeptutor/book/blocks/_rag_helpers.pynew file mode 100644index 000000000..75b8af286--- /dev/null+++ b/deeptutor/book/blocks/_rag_helpers.py@@ -0,0 +1,117 @@+"""+Optional RAG lookup helper for block generators.++If the block context has a primary KB and ``rag_enabled``, run a single+``rag_search`` call and return both the synthesised text and a list of+``SourceAnchor`` objects. Failures are swallowed silently – RAG is treated as+"nice to have" by every generator.+"""++from __future__ import annotations++from dataclasses import dataclass, field++from deeptutor.logging import get_logger++from ..models import SourceAnchor++logger = get_logger("book.rag_helpers")+++@dataclass+class RagLookup:+ text: str = ""+ anchors: list[SourceAnchor] = field(default_factory=list)+ used: bool = False+++def _coerce_anchors(sources: list[dict] | None) -> list[SourceAnchor]:+ if not sources:+ return []+ anchors: list[SourceAnchor] = []+ for src in sources[:6]:+ if not isinstance(src, dict):+ continue+ ref = (+ src.get("id")+ or src.get("doc_id")+ or src.get("path")+ or src.get("source")+ or ""+ )+ snippet = src.get("text") or src.get("snippet") or src.get("content") or ""+ anchors.append(+ SourceAnchor(+ kind="kb",+ ref=str(ref)[:200],+ snippet=str(snippet)[:300],+ )+ )+ return anchors+++async def optional_rag_lookup(*, query: str, ctx) -> RagLookup:+ """Cheap, best-effort retrieval helper for block generators.++ Lookup order (BookEngine v2):++ 1. Local exploration chunks attached to ``ctx`` (free, deterministic).+ 2. Live ``rag_search`` against ``ctx.primary_kb`` (network round-trip).++ Returns an empty ``RagLookup`` if neither path produced anything; failures+ are swallowed silently because every generator treats RAG as optional.+ """+ if not query.strip():+ return RagLookup()++ # ── Step 1: try the cached exploration sweep first ───────────────+ local_chunks = []+ try:+ local_chunks = ctx.relevant_chunks(query, limit=4)+ except AttributeError:+ local_chunks = []+ except Exception as exc: # noqa: BLE001+ logger.debug(f"relevant_chunks failed: {exc}")+ local_chunks = []++ if local_chunks:+ text = "\n\n".join(+ f"- {(c.text or '').strip()}" for c in local_chunks if (c.text or "").strip()+ )+ anchors = [+ SourceAnchor(+ kind=c.source or "kb",+ ref=str(c.ref or c.chunk_id or "")[:200],+ snippet=str(c.text or "")[:300],+ )+ for c in local_chunks+ if (c.text or "").strip()+ ]+ if text or anchors:+ return RagLookup(text=text, anchors=anchors, used=True)++ # ── Step 2: fall back to a live RAG call ─────────────────────────+ if not ctx.rag_enabled or not ctx.primary_kb:+ return RagLookup()++ try:+ from deeptutor.tools.rag_tool import rag_search++ result = await rag_search(query=query, kb_name=ctx.primary_kb)+ except Exception as exc:+ logger.debug(f"RAG lookup skipped ({ctx.primary_kb}): {exc}")+ return RagLookup()++ if not isinstance(result, dict):+ return RagLookup()++ answer = str(result.get("answer") or result.get("content") or "").strip()+ sources = result.get("sources")+ return RagLookup(+ text=answer,+ anchors=_coerce_anchors(sources if isinstance(sources, list) else None),+ used=bool(answer or sources),+ )+++__all__ = ["RagLookup", "optional_rag_lookup"]diff --git a/deeptutor/book/blocks/animation.py b/deeptutor/book/blocks/animation.pynew file mode 100644index 000000000..7df7c8f73--- /dev/null+++ b/deeptutor/book/blocks/animation.py@@ -0,0 +1,123 @@+"""Animation block – Manim-rendered math animation.++Calls :class:`deeptutor.agents.math_animator.pipeline.MathAnimatorPipeline`+to generate a video clip explaining the chapter. The payload exposes the+rendered artifact URL(s) plus a short summary.++This block requires the optional ``math-animator`` extras (LaTeX, ffmpeg,+manim, …). When those packages are missing the generator raises+:class:`GenerationFailure` with a clear install hint.+"""++from __future__ import annotations++import importlib.util+from typing import Any++from deeptutor.logging import get_logger++from ..models import BlockType, SourceAnchor+from .base import BlockContext, BlockGenerator, GenerationFailure++logger = get_logger("book.blocks.animation")+++class AnimationGenerator(BlockGenerator):+ block_type = BlockType.ANIMATION++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ if importlib.util.find_spec("manim") is None:+ raise GenerationFailure(+ "AnimationGenerator requires the optional math-animator extras. "+ "Install with `pip install -r requirements/math-animator.txt`."+ )++ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives = params.get("objectives") or ctx.chapter.learning_objectives+ focus = str(params.get("focus") or "")+ quality = str(params.get("quality") or "medium")+ style_hint = str(params.get("style_hint") or "")++ history_lines: list[str] = []+ if chapter_summary:+ history_lines.append(f"Chapter summary: {chapter_summary}")+ if objectives:+ history_lines.append("Learning objectives:")+ for obj in objectives:+ history_lines.append(f"- {obj}")+ history_context = "\n".join(history_lines)++ focus_clause = f" focusing on {focus}" if focus else ""+ user_input = (+ f"Create a short Manim animation that walks through the core "+ f"derivation of \"{chapter_title}\"{focus_clause}. Aim for a "+ "clear, step-by-step explanation a learner can follow."+ )++ try:+ from deeptutor.agents.math_animator.pipeline import MathAnimatorPipeline+ from deeptutor.agents.math_animator.request_config import (+ MathAnimatorRequestConfig,+ )+ from deeptutor.services.llm.config import get_llm_config++ llm_config = get_llm_config()+ request_config = MathAnimatorRequestConfig(+ output_mode="video",+ quality=quality if quality in ("low", "medium", "high") else "medium",+ style_hint=style_hint,+ )+ pipeline = MathAnimatorPipeline(+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ api_version=llm_config.api_version,+ language=ctx.language,+ )+ turn_id = f"book-{ctx.book_id}-{ctx.block.id}"+ result = await pipeline.run(+ turn_id=turn_id,+ user_input=user_input,+ history_context=history_context,+ request_config=request_config,+ attachments=[],+ )+ except Exception as exc:+ logger.warning(f"AnimationGenerator failed: {exc}", exc_info=True)+ raise GenerationFailure(f"animation generation failed: {exc}") from exc++ render_result = result["render_result"]+ summary_payload = result["summary"]+ analysis = result["analysis"]+ artifacts = [artifact.model_dump() for artifact in render_result.artifacts]+ primary = next(+ (+ a+ for a in artifacts+ if a.get("type") == "video" or "video" in (a.get("content_type") or "")+ ),+ artifacts[0] if artifacts else None,+ )++ return (+ {+ "render_type": "video",+ "artifacts": artifacts,+ "video_url": (primary or {}).get("url", ""),+ "filename": (primary or {}).get("filename", ""),+ "summary": getattr(summary_payload, "summary_text", "") or "",+ "key_points": list(getattr(summary_payload, "key_points", []) or []),+ "description": getattr(analysis, "learning_goal", "") or "",+ },+ [],+ {+ "retry_attempts": render_result.retry_attempts,+ "quality": request_config.quality,+ },+ )+++__all__ = ["AnimationGenerator"]diff --git a/deeptutor/book/blocks/base.py b/deeptutor/book/blocks/base.pynew file mode 100644index 000000000..1bbc18c3c--- /dev/null+++ b/deeptutor/book/blocks/base.py@@ -0,0 +1,192 @@+"""+BlockGenerator base class+=========================++A BlockGenerator turns a ``Block`` (with ``params``) plus some shared context+(book / chapter / page / KB) into a populated ``Block`` (``payload`` filled,+``status`` set to READY/ERROR).++Generators are stateless and are looked up by ``BlockType`` via+``get_block_registry()``.+"""++from __future__ import annotations++import asyncio+from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from typing import Any++from deeptutor.logging import get_logger++from ..models import (+ Block,+ BlockStatus,+ BlockType,+ Chapter,+ ExplorationReport,+ Page,+ SourceAnchor,+)++logger = get_logger("book.blocks")+++class GenerationFailure(Exception):+ """Raised by a generator to mark the block as ERROR."""+++@dataclass+class BlockContext:+ """Everything a generator might need outside the block itself."""++ book_id: str+ chapter: Chapter+ page: Page+ block: Block+ language: str = "en"+ knowledge_bases: list[str] = field(default_factory=list)+ rag_enabled: bool = True+ extra: dict[str, Any] = field(default_factory=dict)+ # BookEngine v2 — fed in by ``BookCompiler`` so generators can reuse the+ # exploration sweep instead of re-issuing RAG calls.+ exploration: ExplorationReport | None = None++ @property+ def primary_kb(self) -> str | None:+ return self.knowledge_bases[0] if self.knowledge_bases else None++ def relevant_chunks(self, query: str, *, limit: int = 6) -> list:+ """Return ``SourceChunk`` objects from ``self.exploration`` that look+ relevant to *query* (cheap keyword overlap heuristic). Empty list when+ no exploration is attached."""+ if self.exploration is None or not self.exploration.chunks:+ return []+ tokens = {+ t for t in (query or "").lower().split() if len(t) > 2+ }+ if not tokens:+ return self.exploration.chunks[:limit]++ scored: list[tuple[float, Any]] = []+ for ch in self.exploration.chunks:+ text = (ch.text or "").lower()+ q = (ch.query or "").lower()+ hits = sum(1 for tok in tokens if tok in text or tok in q)+ if hits == 0:+ continue+ scored.append((hits + 0.01 * (ch.score or 0.0), ch))+ scored.sort(key=lambda pair: -pair[0])+ return [ch for _, ch in scored[:limit]]+++class BlockGenerator(ABC):+ """Base class for all block generators."""++ block_type: BlockType # subclasses MUST override++ async def generate(self, ctx: BlockContext) -> Block:+ """Public entry point. Wraps ``_generate`` with status book-keeping."""+ block = ctx.block+ block.status = BlockStatus.GENERATING+ block.error = ""+ try:+ payload, anchors, metadata = await self._generate(ctx)+ except GenerationFailure as exc:+ block.status = BlockStatus.ERROR+ block.error = str(exc)+ return block+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ logger.warning(+ f"Generator {self.__class__.__name__} raised: {exc}", exc_info=True+ )+ block.status = BlockStatus.ERROR+ block.error = str(exc)+ return block++ block.payload = payload or {}+ if anchors:+ block.source_anchors = anchors+ if metadata:+ block.metadata = {**block.metadata, **metadata}+ block.status = BlockStatus.READY+ return block++ @abstractmethod+ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ """Subclasses return (payload, source_anchors, metadata)."""+++class BlockGeneratorRegistry:+ """In-memory registry mapping ``BlockType`` → generator instance."""++ def __init__(self) -> None:+ self._registry: dict[BlockType, BlockGenerator] = {}++ def register(self, generator: BlockGenerator) -> None:+ self._registry[generator.block_type] = generator++ def get(self, block_type: BlockType) -> BlockGenerator | None:+ return self._registry.get(block_type)++ def types(self) -> list[BlockType]:+ return list(self._registry.keys())+++_REGISTRY: BlockGeneratorRegistry | None = None+++def get_block_registry() -> BlockGeneratorRegistry:+ global _REGISTRY+ if _REGISTRY is None:+ _REGISTRY = _build_default_registry()+ return _REGISTRY+++def _build_default_registry() -> BlockGeneratorRegistry:+ registry = BlockGeneratorRegistry()+ # Lazy imports to avoid circular deps+ from .animation import AnimationGenerator+ from .callout import CalloutGenerator+ from .code import CodeGenerator+ from .concept_graph import ConceptGraphGenerator+ from .deep_dive import DeepDiveGenerator+ from .figure import FigureGenerator+ from .flash_cards import FlashCardsGenerator+ from .interactive import InteractiveGenerator+ from .quiz import QuizGenerator+ from .section import SectionGenerator+ from .text import TextGenerator+ from .timeline import TimelineGenerator+ from .user_note import UserNoteGenerator++ for cls in (+ TextGenerator,+ CalloutGenerator,+ QuizGenerator,+ UserNoteGenerator,+ FigureGenerator,+ InteractiveGenerator,+ AnimationGenerator,+ CodeGenerator,+ TimelineGenerator,+ FlashCardsGenerator,+ DeepDiveGenerator,+ ConceptGraphGenerator,+ SectionGenerator,+ ):+ registry.register(cls())+ return registry+++__all__ = [+ "BlockContext",+ "BlockGenerator",+ "BlockGeneratorRegistry",+ "GenerationFailure",+ "get_block_registry",+]diff --git a/deeptutor/book/blocks/callout.py b/deeptutor/book/blocks/callout.pynew file mode 100644index 000000000..6e61ba9f8--- /dev/null+++ b/deeptutor/book/blocks/callout.py@@ -0,0 +1,62 @@+"""Callout block – key idea / common pitfall / summary highlight.++Prompts live in ``deeptutor/book/prompts/{en,zh}/callout.yaml``.+"""++from __future__ import annotations++from typing import Any++from ..models import BlockType, SourceAnchor+from ._llm_writer import llm_text+from ._prompts import get_book_prompt, load_book_prompts+from .base import BlockContext, BlockGenerator+++_VARIANT_LABELS = {+ "key_idea": ("Key Idea", "核心要点"),+ "common_pitfall": ("Watch Out", "常见误区"),+ "summary": ("Summary", "小结"),+ "tip": ("Tip", "小提示"),+}+++class CalloutGenerator(BlockGenerator):+ block_type = BlockType.CALLOUT++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ variant = str(params.get("variant") or "key_idea")+ labels = _VARIANT_LABELS.get(variant, _VARIANT_LABELS["key_idea"])+ label = labels[1] if ctx.language == "zh" else labels[0]++ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives = params.get("objectives") or ctx.chapter.learning_objectives++ prompts = load_book_prompts("callout", ctx.language)+ none_label = "(无)" if ctx.language == "zh" else "(none)"+ user_prompt = get_book_prompt(prompts, "user_template").format(+ chapter_title=chapter_title,+ chapter_summary=chapter_summary or none_label,+ objectives_inline="; ".join(objectives) or none_label,+ variant=variant,+ label=label,+ )+ body = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "system"),+ max_tokens=250,+ temperature=0.5,+ language=ctx.language,+ )+ return (+ {"variant": variant, "label": label, "body": body},+ [],+ {},+ )+++__all__ = ["CalloutGenerator"]diff --git a/deeptutor/book/blocks/code.py b/deeptutor/book/blocks/code.pynew file mode 100644index 000000000..4f4a23558--- /dev/null+++ b/deeptutor/book/blocks/code.py@@ -0,0 +1,83 @@+"""Code block – generates a runnable code snippet plus brief explanation.++Phase 2 implementation. Uses the unified LLM service with a strict JSON+response. The frontend ``CodeBlock`` component renders the code and the+explanation side-by-side; the playground "code_execution" tool can be+hooked in later for live runs.++Prompts live in ``deeptutor/book/prompts/{en,zh}/code.yaml``.+"""++from __future__ import annotations++import json+from typing import Any++from ..models import BlockType, SourceAnchor+from ._llm_writer import llm_text+from ._prompts import get_book_prompt, load_book_prompts+from .base import BlockContext, BlockGenerator, GenerationFailure+++class CodeGenerator(BlockGenerator):+ block_type = BlockType.CODE++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives = params.get("objectives") or ctx.chapter.learning_objectives+ language = str(params.get("language") or "python")+ intent = str(params.get("intent") or "demonstrate")++ prompts = load_book_prompts("code", ctx.language)+ none_label = "(无)" if ctx.language == "zh" else "(none)"+ user_prompt = get_book_prompt(prompts, "user_template").format(+ chapter_title=chapter_title,+ chapter_summary=chapter_summary or none_label,+ objectives_inline="; ".join(objectives) or none_label,+ intent=intent,+ language=language,+ )+ raw = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "system"),+ max_tokens=900,+ temperature=0.3,+ response_format={"type": "json_object"},+ language=ctx.language,+ )++ data = _safe_json(raw)+ code = str(data.get("code") or "").strip()+ if not code:+ raise GenerationFailure("LLM did not return any code.")+ return (+ {+ "language": str(data.get("language") or language).strip() or language,+ "code": code,+ "explanation": str(data.get("explanation") or "").strip(),+ "intent": intent,+ },+ [],+ {},+ )+++def _safe_json(raw: str) -> dict[str, Any]:+ raw = raw.strip()+ if raw.startswith("```"):+ raw = raw.strip("`")+ idx = raw.find("\n")+ if idx > 0 and not raw[:idx].strip().startswith("{"):+ raw = raw[idx + 1 :]+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ return {}+ return data if isinstance(data, dict) else {}+++__all__ = ["CodeGenerator"]diff --git a/deeptutor/book/blocks/concept_graph.py b/deeptutor/book/blocks/concept_graph.pynew file mode 100644index 000000000..cb062288e--- /dev/null+++ b/deeptutor/book/blocks/concept_graph.py@@ -0,0 +1,137 @@+"""Concept-graph block — deterministically rendered from the spine's graph.++This generator never calls an LLM. It reads ``ctx.extra['concept_graph']`` (a+``ConceptGraph`` model dump injected by the engine) and emits both:++- A Mermaid ``graph TD`` source the frontend can render with its existing+ Mermaid pipeline.+- A structured ``index`` payload (chapter list + concept ↔ chapter mapping)+ the frontend can use for an interactive sidebar in the Overview chapter.+"""++from __future__ import annotations++from typing import Any++from ..models import BlockType, ConceptGraph, SourceAnchor+from .base import BlockContext, BlockGenerator, GenerationFailure+++def _safe_id(node_id: str, used: set[str]) -> str:+ cleaned = "".join(ch if ch.isalnum() else "_" for ch in (node_id or "n"))+ cleaned = cleaned.strip("_") or "n"+ candidate = cleaned[:32]+ suffix = 1+ while candidate in used:+ suffix += 1+ candidate = f"{cleaned[:30]}_{suffix}"+ used.add(candidate)+ return candidate+++def _escape_label(text: str, *, max_len: int = 48) -> str:+ """Mermaid-safe label: collapse whitespace and escape quotes."""+ cleaned = " ".join((text or "").split())+ cleaned = cleaned.replace('"', "'")+ if len(cleaned) > max_len:+ cleaned = cleaned[: max_len - 1] + "…"+ return cleaned or "concept"+++def render_mermaid(graph: ConceptGraph) -> str:+ """Render a ``ConceptGraph`` as a Mermaid ``graph TD`` source.++ When nodes carry ``chapter_id`` (chapter-level mind map produced by+ ``_build_chapter_map``), each node is rendered with a chapter number+ prefix and a slightly shorter label to keep the diagram readable.+ The virtual book-title root (no ``chapter_id``) gets a stadium shape+ ``(["..."])`` to stand out visually.+ """+ if not graph.nodes:+ return "graph TD\n empty[\"(no concepts yet)\"]"++ chapter_mode = any(n.chapter_id for n in graph.nodes)++ used: set[str] = set()+ id_map: dict[str, str] = {}+ lines = ["graph TD"]+ chapter_seq = 0+ for node in graph.nodes:+ sid = _safe_id(node.id or node.label, used)+ id_map[node.id] = sid++ if chapter_mode and node.chapter_id:+ chapter_seq += 1+ num = str(chapter_seq).zfill(2)+ label = _escape_label(node.label, max_len=28)+ lines.append(f' {sid}["{num} · {label}"]')+ elif chapter_mode and not node.chapter_id:+ label = _escape_label(node.label, max_len=36)+ lines.append(f' {sid}(["{label}"])')+ else:+ lines.append(f' {sid}["{_escape_label(node.label)}"]')++ arrow_for = {"depends_on": "-->", "extends": "==>", "related": "-.->"}+ for edge in graph.edges:+ if edge.src not in id_map or edge.dst not in id_map:+ continue+ arrow = arrow_for.get(edge.relation, "-->")+ lines.append(f" {id_map[edge.src]} {arrow} {id_map[edge.dst]}")++ return "\n".join(lines)+++class ConceptGraphGenerator(BlockGenerator):+ block_type = BlockType.CONCEPT_GRAPH++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ raw = ctx.extra.get("concept_graph") or ctx.block.params.get("concept_graph")+ if raw is None:+ raise GenerationFailure(+ "concept_graph payload missing from BlockContext.extra"+ )+ if isinstance(raw, ConceptGraph):+ graph = raw+ elif isinstance(raw, dict):+ try:+ graph = ConceptGraph.model_validate(raw)+ except Exception as exc:+ raise GenerationFailure(f"invalid concept_graph payload: {exc}") from exc+ else:+ raise GenerationFailure(+ f"unexpected concept_graph payload type: {type(raw).__name__}"+ )++ chapters_index = ctx.extra.get("chapter_index") or []+ if not isinstance(chapters_index, list):+ chapters_index = []++ mermaid_src = render_mermaid(graph)++ # Build a node→chapter lookup for the interactive sidebar.+ node_to_chapter: dict[str, str] = {}+ for n in graph.nodes:+ if n.chapter_id:+ node_to_chapter[n.id] = n.chapter_id++ return (+ {+ "render_type": "concept_graph",+ "code": {"language": "mermaid", "content": mermaid_src},+ "graph": graph.model_dump(),+ "index": {+ "chapters": chapters_index,+ "node_to_chapter": node_to_chapter,+ },+ },+ [],+ {+ "node_count": len(graph.nodes),+ "edge_count": len(graph.edges),+ },+ )+++__all__ = ["ConceptGraphGenerator", "render_mermaid"]diff --git a/deeptutor/book/blocks/deep_dive.py b/deeptutor/book/blocks/deep_dive.pynew file mode 100644index 000000000..d247b9f99--- /dev/null+++ b/deeptutor/book/blocks/deep_dive.py@@ -0,0 +1,70 @@+"""Deep-dive block – Phase 3 implementation.++Renders a "Go deeper" call-to-action card. The actual sub-page is created on+demand by the BookEngine (``create_deep_dive_subpage``) when the user clicks+the card; we only emit suggested topics here so the page reader can render+the affordance.++Prompts live in ``deeptutor/book/prompts/{en,zh}/deep_dive.yaml``.+"""++from __future__ import annotations++import json+from typing import Any++from ..models import BlockType, SourceAnchor+from ._llm_writer import llm_text+from ._prompts import get_book_prompt, load_book_prompts+from .base import BlockContext, BlockGenerator, GenerationFailure+++class DeepDiveGenerator(BlockGenerator):+ block_type = BlockType.DEEP_DIVE++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)++ prompts = load_book_prompts("deep_dive", ctx.language)+ none_label = "(无)" if ctx.language == "zh" else "(none)"+ user_prompt = get_book_prompt(prompts, "user_template").format(+ chapter_title=chapter_title,+ chapter_summary=chapter_summary or none_label,+ )+ raw = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "system"),+ max_tokens=500,+ temperature=0.4,+ response_format={"type": "json_object"},+ language=ctx.language,+ )+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ data = {}+ suggestions_raw = data.get("suggestions") if isinstance(data, dict) else None+ suggestions: list[dict[str, str]] = []+ if isinstance(suggestions_raw, list):+ for item in suggestions_raw[:5]:+ if not isinstance(item, dict):+ continue+ topic = str(item.get("topic") or "").strip()+ if not topic:+ continue+ suggestions.append(+ {+ "topic": topic[:160],+ "rationale": str(item.get("rationale") or "").strip()[:300],+ }+ )+ if not suggestions:+ raise GenerationFailure("LLM returned no deep-dive suggestions.")+ return ({"suggestions": suggestions}, [], {})+++__all__ = ["DeepDiveGenerator"]diff --git a/deeptutor/book/blocks/figure.py b/deeptutor/book/blocks/figure.pynew file mode 100644index 000000000..a754e7f08--- /dev/null+++ b/deeptutor/book/blocks/figure.py@@ -0,0 +1,103 @@+"""Figure block – static visual figure (svg / chartjs / mermaid).++Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with+``render_mode="figure"`` so the LLM picks the best static rendering for the+chapter, but never falls back to interactive HTML (handled by the+``interactive`` block type).+"""++from __future__ import annotations++from typing import Any++from deeptutor.logging import get_logger++from ..models import BlockType, SourceAnchor+from .base import BlockContext, BlockGenerator, GenerationFailure++logger = get_logger("book.blocks.figure")+++class FigureGenerator(BlockGenerator):+ block_type = BlockType.FIGURE++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives = params.get("objectives") or ctx.chapter.learning_objectives+ variant = str(params.get("variant") or "diagram")+ focus = str(params.get("focus") or "")++ history_lines: list[str] = []+ if chapter_summary:+ history_lines.append(f"Chapter summary: {chapter_summary}")+ if objectives:+ history_lines.append("Learning objectives:")+ for obj in objectives:+ history_lines.append(f"- {obj}")+ history_context = "\n".join(history_lines)++ focus_clause = f" focusing on {focus}" if focus else ""+ user_input = (+ f"Create a {variant} figure for the chapter "+ f"\"{chapter_title}\"{focus_clause}. The figure should help a "+ "learner build intuition about the core relationships covered above."+ )++ try:+ from deeptutor.agents.visualize.pipeline import VisualizePipeline+ from deeptutor.services.llm.config import get_llm_config++ llm_config = get_llm_config()+ pipeline = VisualizePipeline(+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ api_version=llm_config.api_version,+ language=ctx.language,+ )+ analysis = await pipeline.run_analysis(+ user_input=user_input,+ history_context=history_context,+ render_mode="figure",+ )+ code = await pipeline.run_code_generation(+ user_input=user_input,+ history_context=history_context,+ analysis=analysis,+ )+ review = await pipeline.run_review(+ user_input=user_input,+ analysis=analysis,+ code=code,+ )+ except Exception as exc:+ logger.warning(f"FigureGenerator failed: {exc}", exc_info=True)+ raise GenerationFailure(f"figure generation failed: {exc}") from exc++ final_code = review.optimized_code or code+ render_type = analysis.render_type+ lang_tag = {+ "svg": "svg",+ "mermaid": "mermaid",+ "chartjs": "javascript",+ }.get(render_type, "svg")++ return (+ {+ "render_type": render_type,+ "code": {"language": lang_tag, "content": final_code},+ "description": analysis.description,+ "chart_type": analysis.chart_type,+ },+ [],+ {+ "review_changed": review.changed,+ "review_notes": review.review_notes,+ },+ )+++__all__ = ["FigureGenerator"]diff --git a/deeptutor/book/blocks/flash_cards.py b/deeptutor/book/blocks/flash_cards.pynew file mode 100644index 000000000..11009964f--- /dev/null+++ b/deeptutor/book/blocks/flash_cards.py@@ -0,0 +1,74 @@+"""Flash-cards block – LLM-generated study cards.++Returns ``cards: [{front, back, hint}]`` ready for the frontend+``FlashCardsBlock`` component.++Prompts live in ``deeptutor/book/prompts/{en,zh}/flash_cards.yaml``.+"""++from __future__ import annotations++import json+from typing import Any++from ..models import BlockType, SourceAnchor+from ._llm_writer import llm_text+from ._prompts import get_book_prompt, load_book_prompts+from .base import BlockContext, BlockGenerator, GenerationFailure+++class FlashCardsGenerator(BlockGenerator):+ block_type = BlockType.FLASH_CARDS++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives = params.get("objectives") or ctx.chapter.learning_objectives+ count = max(3, min(8, int(params.get("count") or 5)))++ prompts = load_book_prompts("flash_cards", ctx.language)+ none_label = "(无)" if ctx.language == "zh" else "(none)"+ system_prompt = get_book_prompt(prompts, "system_template").format(count=count)+ user_prompt = get_book_prompt(prompts, "user_template").format(+ chapter_title=chapter_title,+ chapter_summary=chapter_summary or none_label,+ objectives_inline="; ".join(objectives) or none_label,+ )+ raw = await llm_text(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ max_tokens=900,+ temperature=0.4,+ response_format={"type": "json_object"},+ language=ctx.language,+ )+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ data = {}+ cards_raw = data.get("cards") if isinstance(data, dict) else None+ cards: list[dict[str, str]] = []+ if isinstance(cards_raw, list):+ for item in cards_raw[:count]:+ if not isinstance(item, dict):+ continue+ front = str(item.get("front") or "").strip()+ back = str(item.get("back") or "").strip()+ if not front or not back:+ continue+ cards.append(+ {+ "front": front[:300],+ "back": back[:600],+ "hint": str(item.get("hint") or "").strip()[:200],+ }+ )+ if not cards:+ raise GenerationFailure("LLM did not return any flashcards.")+ return ({"cards": cards}, [], {})+++__all__ = ["FlashCardsGenerator"]diff --git a/deeptutor/book/blocks/interactive.py b/deeptutor/book/blocks/interactive.pynew file mode 100644index 000000000..b1942b205--- /dev/null+++ b/deeptutor/book/blocks/interactive.py@@ -0,0 +1,97 @@+"""Interactive block – self-contained interactive HTML widget.++Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with+``render_mode="html"``. The payload carries an HTML document the frontend+renders in an isolated iframe.+"""++from __future__ import annotations++from typing import Any++from deeptutor.logging import get_logger++from ..models import BlockType, SourceAnchor+from .base import BlockContext, BlockGenerator, GenerationFailure++logger = get_logger("book.blocks.interactive")+++class InteractiveGenerator(BlockGenerator):+ block_type = BlockType.INTERACTIVE++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives = params.get("objectives") or ctx.chapter.learning_objectives+ focus = str(params.get("focus") or "")+ interaction = str(params.get("interaction") or "interactive")++ history_lines: list[str] = []+ if chapter_summary:+ history_lines.append(f"Chapter summary: {chapter_summary}")+ if objectives:+ history_lines.append("Learning objectives:")+ for obj in objectives:+ history_lines.append(f"- {obj}")+ history_context = "\n".join(history_lines)++ focus_clause = f" focusing on {focus}" if focus else ""+ user_input = (+ f"Build an {interaction} HTML page for the chapter "+ f"\"{chapter_title}\"{focus_clause}. The page should let the learner "+ "manipulate state, drag/click controls, or step through a guided "+ "demo to internalise the concept."+ )++ try:+ from deeptutor.agents.visualize.pipeline import VisualizePipeline+ from deeptutor.services.llm.config import get_llm_config++ llm_config = get_llm_config()+ pipeline = VisualizePipeline(+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ api_version=llm_config.api_version,+ language=ctx.language,+ )+ analysis = await pipeline.run_analysis(+ user_input=user_input,+ history_context=history_context,+ render_mode="html",+ )+ code = await pipeline.run_code_generation(+ user_input=user_input,+ history_context=history_context,+ analysis=analysis,+ )+ review = await pipeline.run_review(+ user_input=user_input,+ analysis=analysis,+ code=code,+ )+ except Exception as exc:+ logger.warning(f"InteractiveGenerator failed: {exc}", exc_info=True)+ raise GenerationFailure(f"interactive generation failed: {exc}") from exc++ final_code = review.optimized_code or code++ return (+ {+ "render_type": "html",+ "code": {"language": "html", "content": final_code},+ "description": analysis.description,+ "chart_type": analysis.chart_type,+ },+ [],+ {+ "review_changed": review.changed,+ "review_notes": review.review_notes,+ },+ )+++__all__ = ["InteractiveGenerator"]diff --git a/deeptutor/book/blocks/quiz.py b/deeptutor/book/blocks/quiz.pynew file mode 100644index 000000000..fe89bb96f--- /dev/null+++ b/deeptutor/book/blocks/quiz.py@@ -0,0 +1,92 @@+"""Quiz block – delegates to the existing question generation coordinator."""++from __future__ import annotations++from typing import Any++from deeptutor.logging import get_logger++from ..models import BlockType, SourceAnchor+from .base import BlockContext, BlockGenerator, GenerationFailure++logger = get_logger("book.blocks.quiz")+++class QuizGenerator(BlockGenerator):+ block_type = BlockType.QUIZ++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives = params.get("objectives") or ctx.chapter.learning_objectives+ num_questions = max(1, min(8, int(params.get("num_questions") or 3)))+ difficulty = str(params.get("difficulty") or "medium")+ question_type = str(params.get("question_type") or "")++ topic = chapter_title.strip() or ctx.book_id+ preference = "; ".join(filter(None, [chapter_summary, *objectives]))++ try:+ from deeptutor.agents.question.coordinator import AgentCoordinator++ coordinator = AgentCoordinator(+ kb_name=ctx.primary_kb,+ language=ctx.language,+ enable_idea_rag=ctx.rag_enabled and bool(ctx.primary_kb),+ )+ summary = await coordinator.generate_from_topic(+ user_topic=topic,+ preference=preference,+ num_questions=num_questions,+ difficulty=difficulty,+ question_type=question_type,+ )+ except Exception as exc:+ logger.warning(f"QuizGenerator failed: {exc}", exc_info=True)+ raise GenerationFailure(f"quiz generation failed: {exc}") from exc++ questions = self._extract_questions(summary)+ if not questions:+ raise GenerationFailure("no questions generated")++ return (+ {"questions": questions, "topic": topic},+ [],+ {+ "completed": summary.get("completed", 0),+ "failed": summary.get("failed", 0),+ "kb": ctx.primary_kb,+ },+ )++ @staticmethod+ def _extract_questions(summary: dict[str, Any]) -> list[dict[str, Any]]:+ results = summary.get("results") or []+ if not isinstance(results, list):+ return []+ out: list[dict[str, Any]] = []+ for item in results:+ if not isinstance(item, dict) or not item.get("success"):+ continue+ qa = item.get("qa_pair") or {}+ if not isinstance(qa, dict):+ continue+ out.append(+ {+ "question_id": qa.get("question_id", ""),+ "question": qa.get("question", ""),+ "question_type": qa.get("question_type", "written"),+ "options": qa.get("options") or {},+ "correct_answer": qa.get("correct_answer", ""),+ "explanation": qa.get("explanation", ""),+ "difficulty": qa.get("difficulty", ""),+ "concentration": qa.get("concentration", ""),+ }+ )+ return out+++__all__ = ["QuizGenerator"]diff --git a/deeptutor/book/blocks/section.py b/deeptutor/book/blocks/section.pynew file mode 100644index 000000000..eada1a5fc--- /dev/null+++ b/deeptutor/book/blocks/section.py@@ -0,0 +1,374 @@+"""+Section block generator+=======================++Long-form section block (1500-2500 words) introduced in BookEngine v2.++Generation is a *two-pass* pipeline:++1. **Outline pass** — single LLM call returns a JSON ``{intro, subsections,+ key_takeaway}`` plan. ``subsections`` is a list of+ ``{heading, role, focus, target_words}`` items. The pass is grounded by+ ``ExplorationReport`` chunks (no extra RAG round-trip when chunks are+ already cached).+2. **Fill pass** — every subsection is materialised in parallel with+ ``asyncio.gather`` using ``llm_text``. Each subsection LLM call sees only+ its own slot prompt + the relevant local chunks.++The final payload combines intro + filled subsections + key takeaway, ready+for ``SectionBlock.tsx`` on the frontend (see Phase 4.d).+"""++from __future__ import annotations++import asyncio+import json+from typing import Any++from deeptutor.logging import get_logger+from deeptutor.utils.json_parser import parse_json_response++from ..models import BlockType, SourceAnchor, SourceChunk+from ._llm_writer import llm_text+from ._prompts import get_book_prompt, load_book_prompts+from ._rag_helpers import optional_rag_lookup+from .base import BlockContext, BlockGenerator, GenerationFailure++logger = get_logger("book.blocks.section")+++_DEFAULT_SUBSECTION_WORDS = 320+++def _clip(text: str, limit: int) -> str:+ text = (text or "").strip()+ if len(text) <= limit:+ return text+ return text[:limit].rstrip() + "…"+++def _none_label(language: str) -> str:+ return "(无)" if language == "zh" else "(none)"+++# ─────────────────────────────────────────────────────────────────────────────+# Generator+# ─────────────────────────────────────────────────────────────────────────────+++class SectionGenerator(BlockGenerator):+ block_type = BlockType.SECTION++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives: list[str] = (+ params.get("objectives") or ctx.chapter.learning_objectives or []+ )+ focus_topic: str = str(params.get("focus") or chapter_title)+ section_role: str = str(params.get("role") or "core")+ target_words: int = int(params.get("target_words") or 1800)++ # Pull local evidence first; fall back to a single live RAG call only+ # when the cached sweep returned nothing.+ rag = await optional_rag_lookup(+ query=f"{chapter_title}: {focus_topic}",+ ctx=ctx,+ )++ # ── Pass 1: outline ───────────────────────────────────────────+ outline = await self._make_outline(+ ctx=ctx,+ chapter_title=chapter_title,+ chapter_summary=chapter_summary,+ objectives=objectives,+ focus_topic=focus_topic,+ section_role=section_role,+ target_words=target_words,+ rag_context=rag.text,+ )+ if not outline.get("subsections"):+ raise GenerationFailure(+ "SectionArchitect produced no subsections in outline pass."+ )++ # ── Pass 2: fill subsections in parallel ─────────────────────+ relevant_chunks: list[SourceChunk] = []+ try:+ relevant_chunks = ctx.relevant_chunks(focus_topic, limit=8)+ except Exception: # noqa: BLE001+ relevant_chunks = []++ subs = outline["subsections"]+ coros = [+ self._fill_subsection(+ ctx=ctx,+ chapter_title=chapter_title,+ section_focus=focus_topic,+ outline_intro=outline.get("intro", ""),+ sub=sub,+ chunks=relevant_chunks,+ )+ for sub in subs+ ]+ bodies = await asyncio.gather(*coros, return_exceptions=False)++ filled: list[dict[str, Any]] = []+ for sub, body in zip(subs, bodies):+ filled.append(+ {+ "heading": sub.get("heading") or "",+ "role": sub.get("role") or "core",+ "focus": sub.get("focus") or "",+ "body": body or "",+ "target_words": sub.get("target_words")+ or _DEFAULT_SUBSECTION_WORDS,+ }+ )++ payload = {+ "format": "section",+ "intro": outline.get("intro") or "",+ "subsections": filled,+ "key_takeaway": outline.get("key_takeaway") or "",+ "focus": focus_topic,+ "role": section_role,+ }++ anchors = list(rag.anchors)+ # Add anchors for any per-subsection chunks not yet covered.+ seen_refs = {(a.kind, a.ref) for a in anchors}+ for ch in relevant_chunks:+ key = (ch.source or "kb", str(ch.ref or ch.chunk_id or ""))+ if key in seen_refs:+ continue+ seen_refs.add(key)+ anchors.append(+ SourceAnchor(+ kind=ch.source or "kb",+ ref=str(ch.ref or ch.chunk_id or "")[:200],+ snippet=_clip(ch.text or "", 300),+ )+ )++ metadata = {+ "subsection_count": len(filled),+ "outline_target_words": target_words,+ "used_rag": rag.used,+ "kb": ctx.primary_kb,+ }+ return payload, anchors[:8], metadata++ # ------------------------------------------------------------------ #+ # Pass 1+ # ------------------------------------------------------------------ #++ async def _make_outline(+ self,+ *,+ ctx: BlockContext,+ chapter_title: str,+ chapter_summary: str,+ objectives: list[str],+ focus_topic: str,+ section_role: str,+ target_words: int,+ rag_context: str,+ ) -> dict[str, Any]:+ prompts = load_book_prompts("section", ctx.language)+ none_label = _none_label(ctx.language)+ obj_block = "\n".join(f"- {o}" for o in objectives) or none_label+ rag_section = (+ f"\n[Relevant source evidence]\n{_clip(rag_context, 1800)}\n"+ if rag_context+ else ""+ )+ user_prompt = get_book_prompt(prompts, "outline_user").format(+ chapter_title=chapter_title,+ chapter_summary=chapter_summary or none_label,+ objectives_block=obj_block,+ focus_topic=focus_topic,+ section_role=section_role,+ target_words=target_words,+ rag_section=rag_section,+ )+ try:+ raw = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "outline_system"),+ max_tokens=900,+ temperature=0.4,+ response_format={"type": "json_object"},+ language=ctx.language,+ )+ except Exception as exc:+ logger.warning(f"SectionGenerator outline LLM failed: {exc}")+ return _fallback_outline(focus_topic, objectives, target_words, ctx.language)++ payload = parse_json_response(raw, logger_instance=logger, fallback={})+ if not isinstance(payload, dict):+ return _fallback_outline(focus_topic, objectives, target_words, ctx.language)++ subs_raw = payload.get("subsections")+ if not isinstance(subs_raw, list) or not subs_raw:+ return _fallback_outline(focus_topic, objectives, target_words, ctx.language)++ subs: list[dict[str, Any]] = []+ for item in subs_raw[:6]:+ if not isinstance(item, dict):+ continue+ heading = _clip(str(item.get("heading") or ""), 80)+ if not heading:+ continue+ role = str(item.get("role") or "core").strip().lower()+ try:+ tw = int(item.get("target_words") or _DEFAULT_SUBSECTION_WORDS)+ except (TypeError, ValueError):+ tw = _DEFAULT_SUBSECTION_WORDS+ tw = max(160, min(520, tw))+ subs.append(+ {+ "heading": heading,+ "role": role,+ "focus": _clip(str(item.get("focus") or ""), 240),+ "target_words": tw,+ }+ )+ if not subs:+ return _fallback_outline(focus_topic, objectives, target_words, ctx.language)++ return {+ "intro": _clip(str(payload.get("intro") or ""), 600),+ "subsections": subs,+ "key_takeaway": _clip(str(payload.get("key_takeaway") or ""), 400),+ }++ # ------------------------------------------------------------------ #+ # Pass 2+ # ------------------------------------------------------------------ #++ async def _fill_subsection(+ self,+ *,+ ctx: BlockContext,+ chapter_title: str,+ section_focus: str,+ outline_intro: str,+ sub: dict[str, Any],+ chunks: list[SourceChunk],+ ) -> str:+ heading = sub.get("heading") or ""+ role = sub.get("role") or "core"+ focus = sub.get("focus") or ""+ target_words = int(sub.get("target_words") or _DEFAULT_SUBSECTION_WORDS)++ # Pick chunks whose query / text overlaps the heading or focus.+ haystack = f"{heading} {focus}".lower()+ slice_chunks: list[SourceChunk] = []+ for ch in chunks:+ text = (ch.text or "").lower()+ tokens_match = sum(+ 1+ for tok in haystack.split()+ if len(tok) > 3 and tok in text+ )+ if tokens_match:+ slice_chunks.append(ch)+ if len(slice_chunks) >= 3:+ break+ if not slice_chunks:+ slice_chunks = chunks[:2]++ evidence_block = ""+ if slice_chunks:+ evidence_block = "\n".join(+ f"- {_clip(c.text or '', 320)}" for c in slice_chunks+ )++ prompts = load_book_prompts("section", ctx.language)+ none_label = _none_label(ctx.language)+ same_as_heading = "(同标题)" if ctx.language == "zh" else "(same as heading)"+ evidence_section = (+ f"\nReference evidence:\n{evidence_block}\n" if evidence_block else ""+ )+ user_prompt = get_book_prompt(prompts, "subsection_user").format(+ chapter_title=chapter_title,+ section_focus=section_focus,+ outline_intro=outline_intro or none_label,+ heading=heading,+ role=role,+ focus=focus or same_as_heading,+ target_words=target_words,+ evidence_section=evidence_section,+ )+ try:+ body = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "subsection_system"),+ max_tokens=1200,+ temperature=0.5,+ language=ctx.language,+ )+ except Exception as exc:+ logger.warning(f"SectionGenerator subsection LLM failed: {exc}")+ return f"### {heading}\n\n_(generation failed: {exc})_"+ body = body.strip()+ if not body.startswith("###"):+ body = f"### {heading}\n\n{body}"+ return body+++# ─────────────────────────────────────────────────────────────────────────────+# Fallback outline when the LLM call fails+# ─────────────────────────────────────────────────────────────────────────────+++def _fallback_outline(+ focus_topic: str,+ objectives: list[str],+ target_words: int,+ language: str,+) -> dict[str, Any]:+ if language == "zh":+ roles = [+ ("核心定义", "core"),+ ("典型例子", "example"),+ ("应用 / 比较", "application"),+ ]+ intro = f"本节围绕“{focus_topic}”展开。"+ takeaway = "记住核心定义,并能在例子中识别其应用。"+ else:+ roles = [+ ("Core idea", "core"),+ ("Worked example", "example"),+ ("Applications & contrasts", "application"),+ ]+ intro = f"This section unpacks **{focus_topic}** in three steps."+ takeaway = "Hold on to the definition, then recognise it in real cases."++ per = max(220, target_words // len(roles))+ subs = [+ {+ "heading": h,+ "role": r,+ "focus": (objectives[i] if i < len(objectives) else focus_topic),+ "target_words": per,+ }+ for i, (h, r) in enumerate(roles)+ ]+ return {+ "intro": intro,+ "subsections": subs,+ "key_takeaway": takeaway,+ }+++__all__ = ["SectionGenerator"]+++# Tiny safety net — keep ``json`` import in use even when only the+# ``parse_json_response`` path runs (avoids ``F401`` in some lint setups).+_unused = json # noqa: F841diff --git a/deeptutor/book/blocks/text.py b/deeptutor/book/blocks/text.pynew file mode 100644index 000000000..900e2eb27--- /dev/null+++ b/deeptutor/book/blocks/text.py@@ -0,0 +1,116 @@+"""Text block generator – Markdown body.++Also exposes :func:`generate_bridge_text` so the compiler can attach a short+1-2 sentence transition to *any* block's payload (not as a separate block).++Prompts live in ``deeptutor/book/prompts/{en,zh}/text.yaml``.+"""++from __future__ import annotations++from typing import Any++from ..models import BlockType, SourceAnchor+from ._llm_writer import llm_text+from ._prompts import get_book_prompt, load_book_prompts+from ._rag_helpers import optional_rag_lookup+from .base import BlockContext, BlockGenerator+++_NONE_LABEL = {"zh": "(无)", "en": "(none)"}+++def _format_objectives(objectives: list[str]) -> str:+ return "\n".join(f"- {o}" for o in objectives) or "(none)"+++def _none_label(language: str) -> str:+ return _NONE_LABEL.get(language, _NONE_LABEL["en"])+++class TextGenerator(BlockGenerator):+ block_type = BlockType.TEXT++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)+ objectives: list[str] = params.get("objectives") or ctx.chapter.learning_objectives+ role: str = str(params.get("role") or "explanation")+ previous_block_summary: str = str(params.get("previous_block_summary") or "")++ rag = await optional_rag_lookup(+ query=f"{chapter_title}: {role}. Objectives: {'; '.join(objectives)}",+ ctx=ctx,+ )++ prompts = load_book_prompts("text", ctx.language)+ none_label = _none_label(ctx.language)+ rag_section = (+ f"\n[Relevant source material]\n{rag.text}\n" if rag.text else ""+ )+ prev_section = (+ f"\n[Previous block recap]\n{previous_block_summary}\n"+ if previous_block_summary+ else ""+ )+ user_prompt = get_book_prompt(prompts, "user_template").format(+ chapter_title=chapter_title,+ chapter_summary=chapter_summary or none_label,+ objectives_block=_format_objectives(objectives),+ role=role,+ previous_section=prev_section,+ rag_section=rag_section,+ )+ body = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "system"),+ max_tokens=1400,+ temperature=0.45,+ language=ctx.language,+ )++ return (+ {+ "format": "markdown",+ "body": body,+ "role": role,+ },+ rag.anchors,+ {"used_rag": rag.used, "kb": ctx.primary_kb},+ )+++async def generate_bridge_text(+ *,+ chapter_title: str,+ previous_block_summary: str,+ next_block_hint: str,+ language: str,+) -> str:+ """Produce 1-2 short Markdown sentences that bridge two adjacent blocks.++ Used by :class:`deeptutor.book.compiler.BookCompiler` to attach a plain+ transition paragraph onto a target block's ``payload['bridge_text']``,+ instead of materialising a dedicated bridge block.+ """+ prompts = load_book_prompts("text", language)+ none_label = _none_label(language)+ user_prompt = get_book_prompt(prompts, "bridge_user_template").format(+ chapter_title=chapter_title,+ previous_block_summary=previous_block_summary or none_label,+ next_block_hint=next_block_hint or none_label,+ )+ body = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "bridge_system"),+ max_tokens=300,+ temperature=0.5,+ language=language,+ )+ return body.strip()+++__all__ = ["TextGenerator", "generate_bridge_text"]diff --git a/deeptutor/book/blocks/timeline.py b/deeptutor/book/blocks/timeline.pynew file mode 100644index 000000000..34ba9fd85--- /dev/null+++ b/deeptutor/book/blocks/timeline.py@@ -0,0 +1,66 @@+"""Timeline block – LLM-generated chronological events list.++Phase 2 implementation. Returns a structured list of events the frontend+renders as a vertical timeline.++Prompts live in ``deeptutor/book/prompts/{en,zh}/timeline.yaml``.+"""++from __future__ import annotations++import json+from typing import Any++from ..models import BlockType, SourceAnchor+from ._llm_writer import llm_text+from ._prompts import get_book_prompt, load_book_prompts+from .base import BlockContext, BlockGenerator, GenerationFailure+++class TimelineGenerator(BlockGenerator):+ block_type = BlockType.TIMELINE++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ chapter_title = params.get("chapter_title", ctx.chapter.title)+ chapter_summary = params.get("chapter_summary", ctx.chapter.summary)++ prompts = load_book_prompts("timeline", ctx.language)+ none_label = "(无)" if ctx.language == "zh" else "(none)"+ user_prompt = get_book_prompt(prompts, "user_template").format(+ chapter_title=chapter_title,+ chapter_summary=chapter_summary or none_label,+ )+ raw = await llm_text(+ user_prompt=user_prompt,+ system_prompt=get_book_prompt(prompts, "system"),+ max_tokens=800,+ temperature=0.4,+ response_format={"type": "json_object"},+ language=ctx.language,+ )+ try:+ data = json.loads(raw)+ except json.JSONDecodeError:+ data = {}+ events_raw = data.get("events") if isinstance(data, dict) else None+ events: list[dict[str, str]] = []+ if isinstance(events_raw, list):+ for item in events_raw[:8]:+ if not isinstance(item, dict):+ continue+ events.append(+ {+ "date": str(item.get("date") or "")[:80],+ "title": str(item.get("title") or "")[:160],+ "description": str(item.get("description") or "")[:600],+ }+ )+ if not events:+ raise GenerationFailure("LLM did not return any timeline events.")+ return ({"events": events}, [], {})+++__all__ = ["TimelineGenerator"]diff --git a/deeptutor/book/blocks/user_note.py b/deeptutor/book/blocks/user_note.pynew file mode 100644index 000000000..c8ebbed20--- /dev/null+++ b/deeptutor/book/blocks/user_note.py@@ -0,0 +1,26 @@+"""User note block – passthrough; user-authored content has no LLM step."""++from __future__ import annotations++from typing import Any++from ..models import BlockType, SourceAnchor+from .base import BlockContext, BlockGenerator+++class UserNoteGenerator(BlockGenerator):+ block_type = BlockType.USER_NOTE++ async def _generate(+ self, ctx: BlockContext+ ) -> tuple[dict[str, Any], list[SourceAnchor], dict[str, Any]]:+ params = ctx.block.params+ body = str(params.get("body") or "").strip()+ return (+ {"format": "markdown", "body": body, "author": "user"},+ [],+ {},+ )+++__all__ = ["UserNoteGenerator"]diff --git a/deeptutor/book/compiler.py b/deeptutor/book/compiler.pynew file mode 100644index 000000000..39da94288--- /dev/null+++ b/deeptutor/book/compiler.py@@ -0,0 +1,370 @@+"""+BookCompiler+============++Drives the per-page block-generation pipeline.++Responsibilities+----------------+1. Plan a page (call :class:`PagePlanner`) if it has no blocks yet.+2. For each block, look up the right :class:`BlockGenerator` and run it.+3. Persist the page after every block (atomic incremental progress).+4. Emit fine-grained ``BookStream`` events so the frontend can stream+ blocks as they become ready.+5. Aggregate page status (READY / PARTIAL / ERROR).++The compiler is intentionally isolated from the orchestrator (``BookEngine``)+so it can be reused by background workers, recovery flows, and ad-hoc+re-generation requests.+"""++from __future__ import annotations++import asyncio+import time+from dataclasses import dataclass++from deeptutor.logging import get_logger++from .agents.page_planner import SectionArchitect+from .blocks.base import BlockContext, get_block_registry+from .blocks.text import generate_bridge_text+from .models import (+ Block,+ BlockStatus,+ Chapter,+ ExplorationReport,+ Page,+ PageStatus,+)+from .storage import BookStorage, get_book_storage+from .streaming import STAGE_BLOCK, STAGE_COMPILATION, STAGE_PAGE_PLAN, BookStream++logger = get_logger("book.compiler")+++@dataclass+class CompilerOptions:+ """Knobs that influence how a page is compiled."""++ phase: int = 1+ """1 → only emit text/callout/quiz blocks (Phase 1 substitution)."""++ rag_enabled: bool = True+ """Whether block generators may call the RAG tool."""++ block_concurrency: int = 1+ """Maximum number of blocks generated in parallel for a single page.++ Phase 1 uses sequential (1) for predictable streaming order; later phases+ can crank this up for faster compilation.+ """++ persist_after_each_block: bool = True+ """Save the page JSON to disk after every block completes."""++ architect_llm_enabled: bool = True+ """When True, ``SectionArchitect`` may use the LLM layer to plan blocks."""+++class BookCompiler:+ """Compile a single page (or list of pages) end-to-end."""++ def __init__(+ self,+ *,+ storage: BookStorage | None = None,+ options: CompilerOptions | None = None,+ ) -> None:+ self.storage = storage or get_book_storage()+ self.options = options or CompilerOptions()+ self.registry = get_block_registry()+ self.architect = SectionArchitect(+ phase=self.options.phase,+ llm_enabled=self.options.architect_llm_enabled,+ )++ # ── Public API ───────────────────────────────────────────────────────++ async def compile_page(+ self,+ *,+ book_id: str,+ chapter: Chapter,+ page: Page,+ stream: BookStream,+ knowledge_bases: list[str] | None = None,+ language: str = "en",+ exploration: ExplorationReport | None = None,+ ) -> Page:+ """Plan (if needed) and generate every block on *page*."""+ await stream.book_event(+ "page_compile_started",+ {"page_id": page.id, "chapter_id": chapter.id, "title": page.title},+ stage=STAGE_COMPILATION,+ )++ # Lazy-load the exploration report from disk if the caller didn't pass+ # one in. This keeps the compiler usable from background workers.+ if exploration is None:+ try:+ exploration = self.storage.load_exploration(book_id)+ except Exception as exc: # noqa: BLE001+ logger.debug(f"load_exploration({book_id}) skipped: {exc}")++ await self._plan_if_needed(+ book_id, chapter, page, stream, language=language, exploration=exploration+ )++ page.status = PageStatus.GENERATING+ page.updated_at = time.time()+ self.storage.save_page(page)++ ctx_factory = lambda block: BlockContext( # noqa: E731+ book_id=book_id,+ chapter=chapter,+ page=page,+ block=block,+ language=language,+ knowledge_bases=knowledge_bases or [],+ rag_enabled=self.options.rag_enabled,+ exploration=exploration,+ )++ sem = asyncio.Semaphore(max(1, self.options.block_concurrency))++ async def _run(block: Block, prev: Block | None) -> None:+ async with sem:+ await self._generate_block(+ book_id,+ page,+ block,+ ctx_factory(block),+ stream,+ chapter=chapter,+ language=language,+ previous_block=prev,+ )++ # Sequential keeps streaming order; concurrent if requested.+ if self.options.block_concurrency <= 1:+ prev: Block | None = None+ for block in page.blocks:+ if block.status == BlockStatus.READY:+ prev = block+ continue+ await _run(block, prev)+ prev = block+ else:+ # Concurrent path uses planning order to derive prev pointers.+ pending: list[tuple[Block, Block | None]] = []+ prev = None+ for block in page.blocks:+ if block.status != BlockStatus.READY:+ pending.append((block, prev))+ prev = block+ await asyncio.gather(*(_run(b, p) for b, p in pending))++ self._finalize_page_status(page)+ page.updated_at = time.time()+ self.storage.save_page(page)+ self.storage.append_log(+ book_id,+ f"page {page.id} → {page.status.value} "+ f"({sum(1 for b in page.blocks if b.status == BlockStatus.READY)}/{len(page.blocks)} blocks ready)",+ op="compile_page",+ )++ await stream.book_event(+ "page_compiled",+ {+ "page_id": page.id,+ "chapter_id": chapter.id,+ "status": page.status.value,+ "blocks": [+ {"id": b.id, "type": b.type.value, "status": b.status.value}+ for b in page.blocks+ ],+ },+ stage=STAGE_COMPILATION,+ )+ return page++ # ── Block-level helpers ──────────────────────────────────────────────++ async def _generate_block(+ self,+ book_id: str,+ page: Page,+ block: Block,+ ctx: BlockContext,+ stream: BookStream,+ *,+ chapter: Chapter,+ language: str,+ previous_block: Block | None,+ ) -> None:+ await stream.book_event(+ "block_started",+ {+ "page_id": page.id,+ "block_id": block.id,+ "block_type": block.type.value,+ },+ stage=STAGE_BLOCK,+ )++ generator = self.registry.get(block.type)+ if generator is None:+ block.status = BlockStatus.ERROR+ block.error = f"No generator registered for block type {block.type.value}"+ logger.warning(block.error)+ else:+ t0 = time.time()+ await generator.generate(ctx)+ block.metadata.setdefault("generation_ms", int((time.time() - t0) * 1000))++ if block.status == BlockStatus.READY:+ await self._attach_bridge_text(+ block, chapter=chapter, previous_block=previous_block, language=language+ )++ block.updated_at = time.time()++ if self.options.persist_after_each_block:+ self.storage.save_page(page)++ kind = "block_ready" if block.status == BlockStatus.READY else "block_error"+ await stream.book_event(+ kind,+ {+ "page_id": page.id,+ "block_id": block.id,+ "block_type": block.type.value,+ "status": block.status.value,+ "error": block.error,+ "payload_keys": list(block.payload.keys()),+ },+ stage=STAGE_BLOCK,+ )++ # ── Bridge text attachment ─────────────────────────────────────────++ async def attach_bridge_text(+ self,+ block: Block,+ *,+ chapter: Chapter,+ previous_block: Block | None,+ language: str,+ ) -> None:+ """If the block carries a ``transition_in`` hint, generate a short+ plain-text bridge paragraph and store it on the block's payload as+ ``bridge_text``. The hint stays on ``metadata`` so the bridge can be+ regenerated when the target block is replaced or refreshed.+ """+ hint = str((block.metadata or {}).get("transition_in") or "").strip()+ if not hint or previous_block is None:+ block.payload.pop("bridge_text", None)+ return++ previous_summary = (+ f"{previous_block.type.value} block on {chapter.title}"+ )+ try:+ text = await generate_bridge_text(+ chapter_title=chapter.title,+ previous_block_summary=previous_summary,+ next_block_hint=hint,+ language=language,+ )+ except Exception as exc: # noqa: BLE001+ logger.warning(f"bridge_text generation failed: {exc}")+ text = ""++ if text:+ block.payload["bridge_text"] = text+ else:+ block.payload.pop("bridge_text", None)++ async def _attach_bridge_text(+ self,+ block: Block,+ *,+ chapter: Chapter,+ previous_block: Block | None,+ language: str,+ ) -> None:+ await self.attach_bridge_text(+ block,+ chapter=chapter,+ previous_block=previous_block,+ language=language,+ )++ # ── Planning ─────────────────────────────────────────────────────────++ async def _plan_if_needed(+ self,+ book_id: str,+ chapter: Chapter,+ page: Page,+ stream: BookStream,+ *,+ language: str = "en",+ exploration: ExplorationReport | None = None,+ ) -> None:+ if page.blocks:+ return+ page.status = PageStatus.PLANNING+ self.storage.save_page(page)+ await stream.book_event(+ "page_planning",+ {"page_id": page.id, "chapter_id": chapter.id, "title": page.title},+ stage=STAGE_PAGE_PLAN,+ )++ planned = await self.architect.plan_blocks_async(+ chapter, exploration=exploration, language=language+ )+ page.blocks = planned+ if not page.content_type:+ page.content_type = chapter.content_type+ if not page.learning_objectives:+ page.learning_objectives = list(chapter.learning_objectives)+ page.updated_at = time.time()+ self.storage.save_page(page)++ await stream.book_event(+ "page_planned",+ {+ "page_id": page.id,+ "chapter_id": chapter.id,+ "block_types": [b.type.value for b in page.blocks],+ },+ stage=STAGE_PAGE_PLAN,+ )++ # ── Status aggregation ─────────────────────────────────────────────++ @staticmethod+ def _finalize_page_status(page: Page) -> None:+ if not page.blocks:+ page.status = PageStatus.ERROR+ page.error = "No blocks were planned for this page."+ return++ ready = sum(1 for b in page.blocks if b.status == BlockStatus.READY)+ errored = sum(1 for b in page.blocks if b.status == BlockStatus.ERROR)+ if ready == len(page.blocks):+ page.status = PageStatus.READY+ page.error = ""+ elif ready == 0:+ page.status = PageStatus.ERROR+ page.error = f"All {errored} blocks failed to generate."+ else:+ page.status = PageStatus.PARTIAL+ page.error = f"{errored}/{len(page.blocks)} blocks failed."+++__all__ = ["BookCompiler", "CompilerOptions"]diff --git a/deeptutor/book/engine.py b/deeptutor/book/engine.pynew file mode 100644index 000000000..d2c5e4cfc--- /dev/null+++ b/deeptutor/book/engine.py@@ -0,0 +1,1155 @@+"""+BookEngine+==========++Top-level orchestrator for the Book Engine. Sits **parallel** to+``ChatOrchestrator`` (i.e. it is **not** a ``BaseCapability``) and is the+single public entry point used by the API router, CLI, and SDK.++Lifecycle+---------++::++ create_book(...) → BookProposal (Stage 1, requires user confirm)+ confirm_proposal(...) → Spine (Stage 2, requires user confirm)+ confirm_spine(...) → page shells + queued compilation+ compile_page(book, page) → Page (Stage 3-4, drives BookCompiler)+ list_books(), load_book(), delete_book(), resume_book()++Compilation queue+-----------------++For each book a per-book ``asyncio.Queue`` schedules pages with priority:+- Highest priority: page the user just opened (handled inline).+- Background: remaining unfinished pages, processed by a single worker.++The engine emits all progress over a ``StreamBus`` (wrapped by ``BookStream``)+which the WebSocket router fans out to clients.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+from typing import Any++from deeptutor.core.stream_bus import StreamBus+from deeptutor.logging import get_logger++from .agents.ideation_agent import IdeationAgent+from .agents.source_explorer import SourceExplorer+from .agents.spine_synthesizer import SpineSynthesizer+from .compiler import BookCompiler, CompilerOptions+from .inputs import IdeationContext, build_book_inputs+from .models import (+ Block,+ BlockStatus,+ BlockType,+ Book,+ BookInputs,+ BookProposal,+ BookStatus,+ Chapter,+ ContentType,+ ExplorationReport,+ Page,+ PageLink,+ PageStatus,+ Progress,+ QuizAttempt,+ Spine,+)+from .storage import BookStorage, get_book_storage+from .streaming import (+ STAGE_COMPILATION,+ STAGE_CRITIQUE,+ STAGE_EXPLORATION,+ STAGE_IDEATION,+ STAGE_OVERVIEW,+ STAGE_SPINE,+ STAGE_SYNTHESIS,+ BookStream,+)++logger = get_logger("book.engine")+++# ─────────────────────────────────────────────────────────────────────────────+# Per-book runtime state (queues, workers)+# ─────────────────────────────────────────────────────────────────────────────+++@dataclass+class _BookRuntime:+ """In-process per-book scheduling state."""++ queue: asyncio.Queue[str] = field(default_factory=asyncio.Queue)+ queued: set[str] = field(default_factory=set)+ worker: asyncio.Task[None] | None = None+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ stream: BookStream | None = None # default stream for background work+++# ─────────────────────────────────────────────────────────────────────────────+# Engine+# ─────────────────────────────────────────────────────────────────────────────+++class BookEngine:+ """Process-wide orchestrator for the Book Engine."""++ def __init__(+ self,+ *,+ storage: BookStorage | None = None,+ compiler_options: CompilerOptions | None = None,+ ) -> None:+ self.storage = storage or get_book_storage()+ self.compiler = BookCompiler(+ storage=self.storage,+ options=compiler_options or CompilerOptions(phase=2),+ )+ self._runtimes: dict[str, _BookRuntime] = {}+ self._global_lock = asyncio.Lock()++ # ── Discovery / lifecycle ────────────────────────────────────────────++ def list_books(self) -> list[Book]:+ books: list[Book] = []+ for book_id in self.storage.list_book_ids():+ book = self.storage.load_book(book_id)+ if book is not None:+ books.append(book)+ books.sort(key=lambda b: b.updated_at, reverse=True)+ return books++ def load_book(self, book_id: str) -> Book | None:+ return self.storage.load_book(book_id)++ def load_spine(self, book_id: str) -> Spine | None:+ return self.storage.load_spine(book_id)++ def list_pages(self, book_id: str) -> list[Page]:+ return self.storage.list_pages(book_id)++ def load_page(self, book_id: str, page_id: str) -> Page | None:+ return self.storage.load_page(book_id, page_id)++ def load_progress(self, book_id: str) -> Progress:+ progress = self.storage.load_progress(book_id)+ if progress is None:+ progress = Progress(book_id=book_id)+ self.storage.save_progress(progress)+ return progress++ def delete_book(self, book_id: str) -> bool:+ runtime = self._runtimes.pop(book_id, None)+ if runtime and runtime.worker and not runtime.worker.done():+ runtime.worker.cancel()+ return self.storage.delete_book(book_id)++ # ── Stage 1: Ideation ────────────────────────────────────────────────++ async def create_book(+ self,+ *,+ user_intent: str,+ chat_session_id: str = "",+ chat_selections: list[dict[str, Any]] | None = None,+ notebook_refs: list[dict[str, Any]] | None = None,+ knowledge_bases: list[str] | None = None,+ question_categories: list[int] | None = None,+ question_entries: list[int] | None = None,+ language: str = "en",+ stream: StreamBus | None = None,+ ) -> tuple[Book, BookProposal]:+ """Capture inputs, run IdeationAgent, persist DRAFT book + proposal."""+ bus = stream or StreamBus()+ bstream = BookStream(bus)++ async with bstream.stage(STAGE_IDEATION):+ await bstream.progress("Capturing inputs…", stage=STAGE_IDEATION)+ book_inputs, ideation_ctx = await build_book_inputs(+ user_intent=user_intent,+ chat_session_id=chat_session_id,+ chat_selections=chat_selections,+ notebook_refs=notebook_refs,+ knowledge_bases=knowledge_bases,+ question_categories=question_categories,+ question_entries=question_entries,+ language=language,+ )++ await bstream.progress(+ "Generating book proposal…", stage=STAGE_IDEATION,+ )+ proposal = await self._run_ideation(ideation_ctx, language)++ book = Book(+ title=proposal.title,+ description=proposal.description,+ status=BookStatus.DRAFT,+ proposal=proposal,+ knowledge_bases=book_inputs.knowledge_bases,+ language=language,+ chapter_count=proposal.estimated_chapters,+ )+ # Capture baseline KB fingerprints immediately so subsequent drift+ # checks have something to compare against. Without this the very+ # first health-check run treats every selected KB as "newly added"+ # and surfaces a spurious drift warning.+ try:+ from .kb_health import fingerprint_kbs++ if book.knowledge_bases:+ book.kb_fingerprints = fingerprint_kbs(book.knowledge_bases)+ except Exception as exc: # noqa: BLE001+ logger.debug(f"baseline fingerprint capture skipped: {exc}")+ self.storage.save_book(book)+ self.storage.save_inputs(book.id, book_inputs)+ self.storage.save_progress(Progress(book_id=book.id))+ self.storage.append_log(+ book.id, f"created (status=draft, title='{book.title}')", op="create"+ )++ await bstream.book_event(+ "proposal_ready",+ {+ "book_id": book.id,+ "title": book.title,+ "proposal": proposal.model_dump(),+ },+ stage=STAGE_IDEATION,+ )++ return book, proposal++ async def _run_ideation(+ self, ctx: IdeationContext, language: str+ ) -> BookProposal:+ agent = IdeationAgent(language=language)+ return await agent.process(ideation_context=ctx)++ # ── Stage 2: Spine ───────────────────────────────────────────────────++ async def confirm_proposal(+ self,+ *,+ book_id: str,+ edited_proposal: BookProposal | None = None,+ stream: StreamBus | None = None,+ ) -> tuple[Book, Spine]:+ """User confirms (and optionally edits) the proposal → run SpineAgent."""+ book = self.storage.load_book(book_id)+ if book is None:+ raise ValueError(f"Book {book_id} not found")++ if edited_proposal is not None:+ book.proposal = edited_proposal+ book.title = edited_proposal.title or book.title+ book.description = edited_proposal.description or book.description++ bus = stream or StreamBus()+ bstream = BookStream(bus)++ proposal = book.proposal or BookProposal(title=book.title)+ inputs = self.storage.load_inputs(book.id) or BookInputs(+ user_intent=book.title or "",+ knowledge_bases=list(book.knowledge_bases),+ language=book.language,+ )++ async with bstream.stage(STAGE_SPINE):+ # ── Sub-stage 1: Source exploration ──────────────────────+ exploration: ExplorationReport | None = None+ try:+ async with bstream.stage(STAGE_EXPLORATION):+ await bstream.progress(+ "Exploring your sources in parallel…",+ stage=STAGE_EXPLORATION,+ )+ explorer = SourceExplorer(language=book.language)+ exploration = await explorer.explore(+ book_id=book.id,+ proposal=proposal,+ inputs=inputs,+ )+ self.storage.save_exploration(book.id, exploration)+ await bstream.book_event(+ "exploration_ready",+ {+ "book_id": book.id,+ "queries": exploration.queries,+ "coverage": exploration.coverage,+ "candidate_concepts": exploration.candidate_concepts,+ "summary": exploration.summary,+ },+ stage=STAGE_EXPLORATION,+ )+ except Exception as exc:+ logger.warning(f"SourceExplorer failed for {book.id}: {exc}")+ exploration = None+ await bstream.progress(+ "Source exploration unavailable — falling back to proposal-only spine.",+ stage=STAGE_EXPLORATION,+ )++ # ── Sub-stage 2: Synthesise spine + concept graph ────────+ synthesizer = SpineSynthesizer(language=book.language)++ async def _on_round(label: str, payload: dict[str, Any]) -> None:+ stage = STAGE_CRITIQUE if label.startswith("critique") else STAGE_SYNTHESIS+ # Don't push the full payload; just enough to drive the timeline.+ summary = {+ "round": label,+ "chapter_count": len(payload.get("chapters") or [])+ if isinstance(payload.get("chapters"), list)+ else 0,+ "issue_count": len(payload.get("issues") or [])+ if isinstance(payload.get("issues"), list)+ else 0,+ "verdict": payload.get("verdict") or "",+ }+ await bstream.book_event(+ "spine_round", {"book_id": book.id, **summary}, stage=stage+ )++ async with bstream.stage(STAGE_SYNTHESIS):+ await bstream.progress(+ "Synthesising spine + concept graph…", stage=STAGE_SYNTHESIS+ )+ spine = await synthesizer.synthesize(+ book_id=book.id,+ proposal=proposal,+ exploration=exploration,+ on_round=_on_round,+ )++ book.chapter_count = len(spine.chapters)+ book.status = BookStatus.SPINE_READY+ self.storage.save_book(book)+ self.storage.save_spine(spine)+ self.storage.append_log(+ book.id,+ f"spine generated ({len(spine.chapters)} chapters, "+ f"{len(spine.concept_graph.nodes)} concepts)",+ op="spine",+ )++ await bstream.book_event(+ "spine_ready",+ {+ "book_id": book.id,+ "chapter_count": len(spine.chapters),+ "concept_node_count": len(spine.concept_graph.nodes),+ "concept_edge_count": len(spine.concept_graph.edges),+ "spine": spine.model_dump(),+ },+ stage=STAGE_SPINE,+ )+ return book, spine++ # ── Stage 2.5: Overview chapter injection ───────────────────────────++ async def _ensure_overview_chapter(+ self,+ spine: Spine,+ book: Book,+ *,+ stream: StreamBus | None,+ ) -> Spine:+ """Insert an Overview chapter at position 0 (idempotent)."""+ # Idempotent guard — already injected?+ first = spine.chapters[0] if spine.chapters else None+ already = bool(+ first+ and (+ first.content_type == ContentType.OVERVIEW+ or (first.__pydantic_extra__ or {}).get("auto_overview") is True+ )+ )+ if already:+ return spine++ overview_title = (+ "本书导览" if book.language == "zh" else "How to read this book"+ )+ objectives = (+ [+ "了解整本书的章节脉络",+ "掌握各章之间的概念依赖关系",+ "选择最合适的阅读顺序",+ ]+ if book.language == "zh"+ else [+ "See the full chapter map at a glance",+ "Understand how concepts depend on each other",+ "Pick the reading path that fits your goals",+ ]+ )+ overview = Chapter(+ title=overview_title,+ learning_objectives=objectives,+ content_type=ContentType.OVERVIEW,+ summary=(+ "Auto-generated overview of the book's concept graph and chapter index."+ if book.language != "zh"+ else "自动生成的概念图与章节索引,作为本书的入口。"+ ),+ order=0,+ )+ # Mark for idempotency on subsequent runs.+ overview.__pydantic_extra__ = overview.__pydantic_extra__ or {}+ overview.__pydantic_extra__["auto_overview"] = True++ # Re-number existing chapters down by one.+ for ch in spine.chapters:+ ch.order = ch.order + 1+ spine.chapters = [overview, *spine.chapters]+ return spine++ async def _materialize_overview_page(+ self,+ spine: Spine,+ pages: list[Page],+ book: Book,+ *,+ stream: StreamBus | None,+ ) -> None:+ """Build the Overview page's blocks deterministically."""+ if not spine.chapters:+ return+ overview_chapter = spine.chapters[0]+ if overview_chapter.content_type != ContentType.OVERVIEW:+ return++ overview_page = next(+ (p for p in pages if p.chapter_id == overview_chapter.id), None+ )+ if overview_page is None or overview_page.status == PageStatus.READY:+ return++ zh = book.language == "zh"+ chapter_index = [+ {+ "id": ch.id,+ "title": ch.title,+ "summary": ch.summary,+ "objectives": list(ch.learning_objectives),+ "order": ch.order,+ "content_type": ch.content_type.value,+ "page_id": (ch.page_ids[0] if ch.page_ids else ""),+ }+ for ch in spine.chapters+ if ch.content_type != ContentType.OVERVIEW+ ]++ # 1) Intro text block (pre-rendered, status=READY)+ intro_md = (+ (+ f"# {book.title or '本书'}\n\n"+ f"{(book.proposal.description if book.proposal else '') or ''}\n\n"+ f"下方的概念图展示了本书 {len(spine.concept_graph.nodes)} 个核心概念以及"+ f"它们之间的依赖关系;再下方是 {len(chapter_index)} 个章节的入口。"+ f"你可以按从上到下的顺序阅读,也可以根据自己的兴趣或先验知识选择切入点。"+ )+ if zh+ else (+ f"# {book.title or 'This book'}\n\n"+ f"{(book.proposal.description if book.proposal else '') or ''}\n\n"+ f"The diagram below maps the {len(spine.concept_graph.nodes)} core "+ f"concepts in this book and how they depend on each other. The "+ f"chapter index that follows lists all {len(chapter_index)} "+ f"chapters — read top-to-bottom for the recommended path, or jump "+ f"straight to whatever you're most curious about."+ )+ )+ intro_block = Block(+ type=BlockType.TEXT,+ status=BlockStatus.READY,+ title=("如何阅读这本书" if zh else "How to read this book"),+ params={"role": "overview_intro"},+ payload={"content": intro_md, "format": "markdown"},+ )++ # 2) Concept graph block — render deterministically+ from .blocks.concept_graph import render_mermaid++ graph_block = Block(+ type=BlockType.CONCEPT_GRAPH,+ status=BlockStatus.READY,+ title=("概念图" if zh else "Concept map"),+ params={+ "concept_graph": spine.concept_graph.model_dump(),+ "chapter_index": chapter_index,+ },+ payload={+ "render_type": "concept_graph",+ "code": {+ "language": "mermaid",+ "content": render_mermaid(spine.concept_graph),+ },+ "graph": spine.concept_graph.model_dump(),+ "index": {+ "chapters": chapter_index,+ "node_to_chapter": {+ n.id: n.chapter_id+ for n in spine.concept_graph.nodes+ if n.chapter_id+ },+ },+ },+ metadata={+ "node_count": len(spine.concept_graph.nodes),+ "edge_count": len(spine.concept_graph.edges),+ },+ )++ # 3) Chapter index callout — also rendered deterministically+ index_lines = []+ for entry in chapter_index:+ line = f"- **{entry['title']}**"+ if entry.get("summary"):+ line += f" — {entry['summary']}"+ index_lines.append(line)+ index_md = (+ ("## 章节索引\n\n" if zh else "## Chapter index\n\n") + "\n".join(index_lines)+ )+ index_block = Block(+ type=BlockType.TEXT,+ status=BlockStatus.READY,+ title=("章节索引" if zh else "Chapter index"),+ params={"role": "chapter_index"},+ payload={"content": index_md, "format": "markdown"},+ )++ overview_page.blocks = [intro_block, graph_block, index_block]+ overview_page.status = PageStatus.READY+ overview_page.content_type = ContentType.OVERVIEW+ self.storage.save_page(overview_page)++ if stream is not None:+ bstream = BookStream(stream)+ await bstream.book_event(+ "overview_ready",+ {+ "book_id": book.id,+ "page_id": overview_page.id,+ "node_count": len(spine.concept_graph.nodes),+ "chapter_count": len(chapter_index),+ },+ stage=STAGE_OVERVIEW,+ )++ # ── Stage 3: confirm spine + create page shells ─────────────────────++ async def confirm_spine(+ self,+ *,+ book_id: str,+ edited_spine: Spine | None = None,+ stream: StreamBus | None = None,+ auto_compile: bool = True,+ ) -> list[Page]:+ """User confirms (or edits) the spine → create pending page shells.++ BookEngine v2: automatically injects an **Overview** chapter at order 0+ whose page is fully pre-built (deterministic concept-graph render ++ intro text + chapter index). The rest of the chapters are queued for+ normal compilation.+ """+ book = self.storage.load_book(book_id)+ if book is None:+ raise ValueError(f"Book {book_id} not found")++ spine = edited_spine or self.storage.load_spine(book_id)+ if spine is None:+ raise ValueError(f"No spine for book {book_id}")+ if edited_spine is not None:+ spine.book_id = book_id+ self.storage.save_spine(spine)++ # ── Inject Overview chapter (idempotent) ─────────────────────+ spine = await self._ensure_overview_chapter(spine, book, stream=stream)+ self.storage.save_spine(spine)++ existing = {p.chapter_id: p for p in self.storage.list_pages(book_id)}+ pages: list[Page] = []+ for chapter in spine.chapters:+ page = existing.get(chapter.id)+ if page is None:+ page = Page(+ book_id=book_id,+ chapter_id=chapter.id,+ title=chapter.title,+ learning_objectives=list(chapter.learning_objectives),+ content_type=chapter.content_type,+ order=chapter.order,+ status=PageStatus.PENDING,+ )+ self.storage.save_page(page)+ chapter.page_ids = [page.id]+ self.storage.save_spine(spine)+ pages.append(page)++ # Build the Overview page eagerly (no LLM, no queue).+ await self._materialize_overview_page(spine, pages, book, stream=stream)++ book.page_count = len(pages)+ book.status = BookStatus.COMPILING if auto_compile else BookStatus.SPINE_READY+ self.storage.save_book(book)+ self.storage.append_log(+ book_id,+ f"spine confirmed ({len(pages)} page shells, auto_compile={auto_compile})",+ op="confirm_spine",+ )++ if auto_compile:+ await self._enqueue_pending_pages(book_id, pages, stream=stream)+ return pages++ # ── Stage 3-4: compile a single page (current page) ──────────────────++ async def compile_page(+ self,+ *,+ book_id: str,+ page_id: str,+ stream: StreamBus | None = None,+ force: bool = False,+ ) -> Page:+ """Drive the compiler for one page (used when a user opens it)."""+ book = self.storage.load_book(book_id)+ spine = self.storage.load_spine(book_id)+ page = self.storage.load_page(book_id, page_id)+ if book is None or spine is None or page is None:+ raise ValueError(+ f"Cannot compile page – missing book/spine/page "+ f"({book_id}/{page_id})"+ )+ if page.status == PageStatus.READY and not force:+ return page++ chapter = spine.chapter_by_id(page.chapter_id)+ if chapter is None:+ raise ValueError(+ f"Page {page_id} references unknown chapter {page.chapter_id}"+ )++ bus = stream or StreamBus()+ bstream = BookStream(bus)++ async with bstream.stage(STAGE_COMPILATION):+ page = await self.compiler.compile_page(+ book_id=book_id,+ chapter=chapter,+ page=page,+ stream=bstream,+ knowledge_bases=book.knowledge_bases,+ language=book.language,+ )++ # Refresh KB fingerprints once we successfully ship a READY page.+ # We capture them lazily so a brand-new book gets its baseline as+ # soon as the very first page is compiled.+ if page.status == PageStatus.READY:+ try:+ from .kb_health import refresh_book_fingerprints++ refreshed = self.storage.load_book(book_id)+ if refreshed is not None and not refreshed.kb_fingerprints:+ refresh_book_fingerprints(book_id, storage=self.storage)+ except Exception as exc: # noqa: BLE001+ logger.debug(f"fingerprint refresh skipped: {exc}")++ await self._maybe_finalize_book(book_id)+ return page++ # ── Background compilation queue ─────────────────────────────────────++ async def _enqueue_pending_pages(+ self,+ book_id: str,+ pages: list[Page],+ *,+ stream: StreamBus | None = None,+ ) -> None:+ runtime = await self._get_or_create_runtime(book_id, stream)+ async with runtime.lock:+ for page in pages:+ if page.status == PageStatus.READY:+ continue+ if page.id in runtime.queued:+ continue+ runtime.queued.add(page.id)+ await runtime.queue.put(page.id)+ self._ensure_worker(book_id)++ async def _get_or_create_runtime(+ self, book_id: str, stream: StreamBus | None+ ) -> _BookRuntime:+ async with self._global_lock:+ runtime = self._runtimes.get(book_id)+ if runtime is None:+ runtime = _BookRuntime()+ self._runtimes[book_id] = runtime+ if stream is not None and runtime.stream is None:+ runtime.stream = BookStream(stream)+ elif runtime.stream is None:+ runtime.stream = BookStream(StreamBus())+ return runtime++ def _ensure_worker(self, book_id: str) -> None:+ runtime = self._runtimes.get(book_id)+ if runtime is None:+ return+ if runtime.worker is not None and not runtime.worker.done():+ return+ runtime.worker = asyncio.create_task(self._worker_loop(book_id))++ async def _worker_loop(self, book_id: str) -> None:+ runtime = self._runtimes.get(book_id)+ if runtime is None:+ return+ bstream = runtime.stream or BookStream(StreamBus())+ while True:+ try:+ page_id = await asyncio.wait_for(runtime.queue.get(), timeout=2.0)+ except asyncio.TimeoutError:+ async with runtime.lock:+ if runtime.queue.empty():+ runtime.worker = None+ return+ continue++ try:+ book = self.storage.load_book(book_id)+ spine = self.storage.load_spine(book_id)+ page = self.storage.load_page(book_id, page_id)+ if book is None or spine is None or page is None:+ continue+ if page.status == PageStatus.READY:+ continue+ chapter = spine.chapter_by_id(page.chapter_id)+ if chapter is None:+ continue+ await self.compiler.compile_page(+ book_id=book_id,+ chapter=chapter,+ page=page,+ stream=bstream,+ knowledge_bases=book.knowledge_bases,+ language=book.language,+ )+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ logger.warning(+ f"Background compilation failed for {book_id}/{page_id}: {exc}",+ exc_info=True,+ )+ self.storage.append_log(+ book_id,+ f"background compile failed for page {page_id}: {exc}",+ op="compile_error",+ )+ finally:+ runtime.queued.discard(page_id)++ await self._maybe_finalize_book(book_id)++ async def _maybe_finalize_book(self, book_id: str) -> None:+ book = self.storage.load_book(book_id)+ if book is None:+ return+ pages = self.storage.list_pages(book_id)+ if not pages:+ return+ if all(p.status == PageStatus.READY for p in pages):+ if book.status != BookStatus.READY:+ book.status = BookStatus.READY+ self.storage.save_book(book)+ self.storage.append_log(+ book_id, "all pages ready → status=READY", op="finalize"+ )++ # ── Block-level controls (Phase 1: regenerate single block) ─────────++ async def regenerate_block(+ self,+ *,+ book_id: str,+ page_id: str,+ block_id: str,+ params_override: dict[str, Any] | None = None,+ stream: StreamBus | None = None,+ ) -> Block | None:+ """Re-run a single block generator (e.g. user clicked 'regenerate')."""+ book = self.storage.load_book(book_id)+ spine = self.storage.load_spine(book_id)+ page = self.storage.load_page(book_id, page_id)+ if book is None or spine is None or page is None:+ return None+ chapter = spine.chapter_by_id(page.chapter_id)+ if chapter is None:+ return None+ block = page.block_by_id(block_id)+ if block is None:+ return None+ if params_override:+ block.params = {**block.params, **params_override}++ bus = stream or StreamBus()+ bstream = BookStream(bus)++ from .blocks.base import BlockContext, get_block_registry++ registry = get_block_registry()+ generator = registry.get(block.type)+ if generator is None:+ block.error = f"No generator for {block.type.value}"+ self.storage.save_page(page)+ return block++ ctx = BlockContext(+ book_id=book_id,+ chapter=chapter,+ page=page,+ block=block,+ language=book.language,+ knowledge_bases=book.knowledge_bases,+ )+ # Resolve previous block by planning order so the bridge text can be+ # refreshed alongside the block itself.+ prev_block: Block | None = None+ for candidate in page.blocks:+ if candidate.id == block.id:+ break+ prev_block = candidate++ async with bstream.stage(STAGE_COMPILATION):+ await generator.generate(ctx)+ if block.status.value == "ready":+ await self.compiler.attach_bridge_text(+ block,+ chapter=chapter,+ previous_block=prev_block,+ language=book.language,+ )+ self.storage.save_page(page)+ self.compiler._finalize_page_status(page)+ self.storage.save_page(page)+ return block+++ # ── Maintenance / health (Phase 4) ─────────────────────────────────++ def kb_drift_report(self, book_id: str) -> dict[str, Any]:+ """Compute and persist the current KB drift report for *book_id*."""+ from .kb_health import mark_drift_on_book++ report = mark_drift_on_book(book_id, storage=self.storage)+ if report is None:+ return {"book_id": book_id, "has_drift": False, "missing": True}+ return report.to_dict()++ def refresh_kb_fingerprints(self, book_id: str) -> dict[str, Any] | None:+ from .kb_health import refresh_book_fingerprints++ book = refresh_book_fingerprints(book_id, storage=self.storage)+ if book is None:+ return None+ return {+ "book_id": book.id,+ "kb_fingerprints": book.kb_fingerprints,+ "stale_page_ids": book.stale_page_ids,+ }++ def log_health(self, book_id: str) -> dict[str, Any]:+ from .kb_health import scan_log_health++ return scan_log_health(book_id, storage=self.storage).to_dict()++ # ── Block CRUD operations (Phase 3) ────────────────────────────────++ async def insert_block(+ self,+ *,+ book_id: str,+ page_id: str,+ block_type: BlockType,+ params: dict[str, Any] | None = None,+ position: int | None = None,+ stream: StreamBus | None = None,+ compile_now: bool = True,+ ) -> Block | None:+ """Insert a fresh PENDING block at *position* (default: end)."""+ spine = self.storage.load_spine(book_id)+ page = self.storage.load_page(book_id, page_id)+ if spine is None or page is None:+ return None+ chapter = spine.chapter_by_id(page.chapter_id)+ if chapter is None:+ return None++ merged_params: dict[str, Any] = {+ "chapter_title": chapter.title,+ "chapter_summary": chapter.summary,+ "objectives": chapter.learning_objectives,+ **(params or {}),+ }+ block = Block(type=block_type, status=BlockStatus.PENDING, params=merged_params)+ if position is None or position >= len(page.blocks) or position < 0:+ page.blocks.append(block)+ else:+ page.blocks.insert(position, block)+ self.storage.save_page(page)++ if compile_now and block_type != BlockType.USER_NOTE:+ from .blocks.base import BlockContext, get_block_registry++ generator = get_block_registry().get(block_type)+ if generator is not None:+ ctx = BlockContext(+ book_id=book_id,+ chapter=chapter,+ page=page,+ block=block,+ language=self.storage.load_book(book_id).language+ if self.storage.load_book(book_id) else "en",+ knowledge_bases=self.storage.load_book(book_id).knowledge_bases+ if self.storage.load_book(book_id) else [],+ )+ bus = stream or StreamBus()+ bstream = BookStream(bus)+ async with bstream.stage(STAGE_COMPILATION):+ await generator.generate(ctx)+ self.compiler._finalize_page_status(page)+ self.storage.save_page(page)+ elif block_type == BlockType.USER_NOTE:+ block.status = BlockStatus.READY+ block.payload = {+ "format": "markdown",+ "body": str(merged_params.get("body") or ""),+ "author": "user",+ }+ self.storage.save_page(page)+ self.storage.append_log(+ book_id,+ f"inserted {block_type.value} block on page {page_id} (pos={position})",+ op="insert_block",+ )+ return block++ async def delete_block(+ self, *, book_id: str, page_id: str, block_id: str+ ) -> bool:+ page = self.storage.load_page(book_id, page_id)+ if page is None:+ return False+ before = len(page.blocks)+ page.blocks = [b for b in page.blocks if b.id != block_id]+ if len(page.blocks) == before:+ return False+ self.compiler._finalize_page_status(page)+ self.storage.save_page(page)+ self.storage.append_log(+ book_id, f"deleted block {block_id} from page {page_id}", op="delete_block"+ )+ return True++ async def move_block(+ self, *, book_id: str, page_id: str, block_id: str, new_position: int+ ) -> bool:+ page = self.storage.load_page(book_id, page_id)+ if page is None:+ return False+ idx = next((i for i, b in enumerate(page.blocks) if b.id == block_id), -1)+ if idx < 0:+ return False+ new_position = max(0, min(len(page.blocks) - 1, new_position))+ block = page.blocks.pop(idx)+ page.blocks.insert(new_position, block)+ self.storage.save_page(page)+ self.storage.append_log(+ book_id,+ f"moved block {block_id} on page {page_id} → pos {new_position}",+ op="move_block",+ )+ return True++ async def change_block_type(+ self,+ *,+ book_id: str,+ page_id: str,+ block_id: str,+ new_type: BlockType,+ params_override: dict[str, Any] | None = None,+ stream: StreamBus | None = None,+ ) -> Block | None:+ spine = self.storage.load_spine(book_id)+ page = self.storage.load_page(book_id, page_id)+ if spine is None or page is None:+ return None+ chapter = spine.chapter_by_id(page.chapter_id)+ if chapter is None:+ return None+ block = page.block_by_id(block_id)+ if block is None:+ return None+ block.type = new_type+ block.status = BlockStatus.PENDING+ block.payload = {}+ block.error = ""+ if params_override:+ block.params = {**block.params, **params_override}+ self.storage.save_page(page)+ # Re-run generator immediately+ return await self.regenerate_block(+ book_id=book_id, page_id=page_id, block_id=block_id, stream=stream+ )++ # ── Deep-dive sub-page (Phase 3) ──────────────────────────────────++ async def create_deep_dive_subpage(+ self,+ *,+ book_id: str,+ parent_page_id: str,+ topic: str,+ block_id: str | None = None,+ content_type: ContentType = ContentType.CONCEPT,+ stream: StreamBus | None = None,+ ) -> Page | None:+ """Spawn a child Page that deepens *topic* and link it from the parent."""+ book = self.storage.load_book(book_id)+ spine = self.storage.load_spine(book_id)+ parent = self.storage.load_page(book_id, parent_page_id)+ if book is None or spine is None or parent is None:+ return None++ # Add a synthetic chapter so the planner has a target+ chapter = Chapter(+ title=f"{topic} (deep dive)",+ learning_objectives=[f"Go deeper into {topic}"],+ content_type=content_type,+ summary=f"Sub-chapter spawned from {parent.title}.",+ order=len(spine.chapters),+ )+ spine.chapters.append(chapter)+ self.storage.save_spine(spine)++ sub = Page(+ book_id=book_id,+ chapter_id=chapter.id,+ title=topic,+ learning_objectives=list(chapter.learning_objectives),+ content_type=content_type,+ status=PageStatus.PENDING,+ order=len(self.storage.list_pages(book_id)),+ parent_page_id=parent.id,+ )+ self.storage.save_page(sub)+ chapter.page_ids = [sub.id]+ self.storage.save_spine(spine)++ # Add link from parent → sub+ parent.links.append(+ PageLink(target_page_id=sub.id, relation="deepens", label=topic)+ )+ if block_id:+ block = parent.block_by_id(block_id)+ if block is not None:+ block.metadata = {**block.metadata, "deep_dive_page_id": sub.id}+ self.storage.save_page(parent)++ # Compile the new page now (blocking, so caller gets ready content)+ await self.compile_page(book_id=book_id, page_id=sub.id, stream=stream)+ self.storage.append_log(+ book_id,+ f"deep-dive page {sub.id} spawned from {parent_page_id}: {topic}",+ op="deep_dive",+ )+ return self.storage.load_page(book_id, sub.id)++ # ── Quiz attempts (Phase 3) ────────────────────────────────────────++ async def record_quiz_attempt(+ self,+ *,+ book_id: str,+ page_id: str,+ block_id: str,+ question_id: str,+ user_answer: str,+ is_correct: bool,+ ) -> Progress:+ progress = self.load_progress(book_id)+ progress.quiz_attempts.append(+ QuizAttempt(+ block_id=block_id,+ page_id=page_id,+ question_id=question_id,+ user_answer=user_answer,+ is_correct=is_correct,+ )+ )+ if not is_correct:+ page = self.storage.load_page(book_id, page_id)+ if page and page.chapter_id and page.chapter_id not in progress.weak_chapters:+ progress.weak_chapters.append(page.chapter_id)+ else:+ progress.score += 1+ self.storage.save_progress(progress)+ return progress++ async def supplement_for_weakness(+ self,+ *,+ book_id: str,+ page_id: str,+ topic: str,+ stream: StreamBus | None = None,+ ) -> Block | None:+ """Append an extra TEXT + QUIZ block when the user struggles."""+ await self.insert_block(+ book_id=book_id,+ page_id=page_id,+ block_type=BlockType.CALLOUT,+ params={"variant": "common_pitfall", "topic": topic},+ stream=stream,+ )+ await self.insert_block(+ book_id=book_id,+ page_id=page_id,+ block_type=BlockType.TEXT,+ params={"role": "remediation", "topic": topic},+ stream=stream,+ )+ return await self.insert_block(+ book_id=book_id,+ page_id=page_id,+ block_type=BlockType.QUIZ,+ params={"num_questions": 2, "difficulty": "easy", "topic": topic},+ stream=stream,+ )+++# ─────────────────────────────────────────────────────────────────────────────+# Singleton accessor+# ─────────────────────────────────────────────────────────────────────────────+++_engine: BookEngine | None = None+++def get_book_engine() -> BookEngine:+ global _engine+ if _engine is None:+ _engine = BookEngine()+ return _engine+++__all__ = ["BookEngine", "get_book_engine"]diff --git a/deeptutor/book/inputs.py b/deeptutor/book/inputs.pynew file mode 100644index 000000000..c9fca6bf1--- /dev/null+++ b/deeptutor/book/inputs.py@@ -0,0 +1,376 @@+"""+BookInputs Fusion+=================++Merges the four input sources (user intent, chat history, notebook references,+knowledge bases) into a structured ``IdeationContext`` text block consumed by+``IdeationAgent``.++Reuses:+- ``deeptutor.services.session.get_sqlite_session_store`` for chat history+- ``deeptutor.services.notebook.notebook_manager`` for notebook records+- ``deeptutor.agents.notebook.NotebookAnalysisAgent`` for context distillation+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++from deeptutor.logging import get_logger++from .models import (+ BookInputs,+ ChatMessageSnapshot,+ ChatSelection,+ NotebookRef,+)++logger = get_logger("book.inputs")+++# ─────────────────────────────────────────────────────────────────────────────+# Output container+# ─────────────────────────────────────────────────────────────────────────────+++@dataclass+class IdeationContext:+ """Structured text+metadata bundle consumed by Stage 1 (Ideation)."""++ user_intent: str = ""+ chat_history_text: str = ""+ notebook_context: str = ""+ question_notebook_text: str = ""+ knowledge_bases: list[str] = field(default_factory=list)+ notebook_record_count: int = 0+ chat_message_count: int = 0+ question_entry_count: int = 0++ def render(self) -> str:+ """Render as a single multi-section prompt block."""+ sections: list[str] = []+ sections.append(f"[User Intent]\n{(self.user_intent or '(empty)').strip()}")++ if self.notebook_context.strip():+ sections.append(f"[Notebook Context]\n{self.notebook_context.strip()}")+ elif self.notebook_record_count == 0:+ sections.append("[Notebook Context]\n(no notebook records selected)")++ if self.question_notebook_text.strip():+ sections.append(+ f"[Question Notebook]\n{self.question_notebook_text.strip()}"+ )+ elif self.question_entry_count == 0:+ sections.append("[Question Notebook]\n(no quiz entries selected)")++ if self.chat_history_text.strip():+ sections.append(f"[Past Conversations]\n{self.chat_history_text.strip()}")+ elif self.chat_message_count == 0:+ sections.append("[Past Conversations]\n(none)")++ if self.knowledge_bases:+ sections.append(+ "[Knowledge Sources]\n"+ + "\n".join(f"- {name}" for name in self.knowledge_bases)+ )+ else:+ sections.append("[Knowledge Sources]\n(no knowledge bases attached)")++ return "\n\n".join(sections)+++# ─────────────────────────────────────────────────────────────────────────────+# Helpers+# ─────────────────────────────────────────────────────────────────────────────+++def _clip_text(value: str, limit: int) -> str:+ text = (value or "").strip()+ if len(text) <= limit:+ return text+ return text[:limit].rstrip() + "…"+++async def _resolve_chat_selections(+ selections: list[ChatSelection],+ *,+ limit_per_session: int = 60,+) -> list[ChatMessageSnapshot]:+ """Pull messages for one or more sessions, optionally filtered by id."""+ if not selections:+ return []+ try:+ from deeptutor.services.session import get_sqlite_session_store++ store = get_sqlite_session_store()+ except Exception as exc:+ logger.warning(f"Chat session store unavailable: {exc}")+ return []++ snapshots: list[ChatMessageSnapshot] = []+ for sel in selections:+ sid = (sel.session_id or "").strip()+ if not sid:+ continue+ try:+ messages = await store.get_messages(sid)+ except Exception as exc:+ logger.warning(f"Failed to fetch chat history for {sid}: {exc}")+ continue++ wanted_ids = {int(mid) for mid in sel.message_ids if mid is not None}+ candidates: list[dict[str, Any]]+ if wanted_ids:+ candidates = [+ m+ for m in messages+ if isinstance(m, dict) and int(m.get("id") or -1) in wanted_ids+ ]+ else:+ candidates = list(messages[-limit_per_session:])++ for msg in candidates:+ if not isinstance(msg, dict):+ continue+ role = str(msg.get("role") or "").strip()+ if role not in {"user", "assistant", "system"}:+ continue+ content = str(msg.get("content") or "").strip()+ if not content:+ continue+ snapshots.append(+ ChatMessageSnapshot(+ role=role,+ content=content,+ capability=str(msg.get("capability") or ""),+ created_at=float(msg.get("created_at") or 0.0),+ )+ )++ snapshots.sort(key=lambda m: m.created_at)+ return snapshots+++def _format_chat_history(messages: list[ChatMessageSnapshot]) -> str:+ if not messages:+ return ""+ lines = []+ for msg in messages:+ snippet = _clip_text(msg.content, 600)+ prefix = msg.role.capitalize()+ if msg.capability:+ prefix = f"{prefix}/{msg.capability}"+ lines.append(f"- {prefix}: {snippet}")+ return "\n".join(lines)+++def _normalize_notebook_refs(raw: list[dict[str, Any]] | None) -> list[NotebookRef]:+ refs: list[NotebookRef] = []+ if not raw:+ return refs+ for item in raw:+ if not isinstance(item, dict):+ continue+ try:+ refs.append(NotebookRef.model_validate(item))+ except Exception as exc:+ logger.warning(f"Invalid notebook reference {item}: {exc}")+ return refs+++async def _resolve_notebook_context(+ user_intent: str,+ notebook_refs: list[NotebookRef],+ *,+ language: str,+) -> tuple[str, int]:+ """Return (context_text, record_count). 0 records → empty context."""+ if not notebook_refs:+ return "", 0+ try:+ from deeptutor.services.notebook import notebook_manager++ records = notebook_manager.get_records_by_references(+ [ref.model_dump() for ref in notebook_refs]+ )+ except Exception as exc:+ logger.warning(f"Failed to resolve notebook records: {exc}")+ return "", 0++ if not records:+ return "", 0++ try:+ from deeptutor.agents.notebook import NotebookAnalysisAgent++ agent = NotebookAnalysisAgent(language=language)+ context = await agent.analyze(user_question=user_intent, records=records)+ except Exception as exc:+ logger.warning(f"NotebookAnalysisAgent failed: {exc}; using raw record summary fallback")+ # Fallback: list titles/summaries so we still inject *something*+ lines = []+ for record in records[:8]:+ title = str(record.get("title") or record.get("id") or "(untitled)")+ summary = _clip_text(str(record.get("summary") or record.get("output") or ""), 400)+ notebook = str(record.get("notebook_name") or "")+ lines.append(f"- [{notebook}] {title}: {summary}")+ context = "\n".join(lines)++ return context, len(records)+++def _format_quiz_entry(item: dict[str, Any]) -> str:+ q = _clip_text(str(item.get("question") or ""), 240)+ ans = _clip_text(str(item.get("correct_answer") or ""), 80)+ user_ans = _clip_text(str(item.get("user_answer") or ""), 80)+ mark = "✓" if item.get("is_correct") else "✗"+ return f"- [{mark}] Q: {q}\n A: {ans}\n User: {user_ans or '(no attempt)'}"+++async def _resolve_question_notebook(+ category_ids: list[int] | None,+ entry_ids: list[int] | None,+ *,+ limit_per_category: int = 50,+) -> tuple[str, int]:+ """Pull quiz entries by category and/or by entry id, render a digest."""+ if not category_ids and not entry_ids:+ return "", 0+ try:+ from deeptutor.services.session import get_sqlite_session_store++ store = get_sqlite_session_store()+ except Exception as exc:+ logger.warning(f"Question notebook unavailable: {exc}")+ return "", 0++ blocks: list[str] = []+ seen: set[int] = set()++ for cat_id in category_ids or []:+ try:+ result = await store.list_notebook_entries(+ category_id=int(cat_id), limit=limit_per_category+ )+ except Exception as exc:+ logger.warning(f"list_notebook_entries({cat_id}) failed: {exc}")+ continue+ items = result.get("items") or []+ if not items:+ continue+ lines = [f"## Category {cat_id}"]+ for item in items[:limit_per_category]:+ eid = int(item.get("id") or 0)+ if eid in seen:+ continue+ seen.add(eid)+ lines.append(_format_quiz_entry(item))+ blocks.append("\n".join(lines))++ if entry_ids:+ loose: list[str] = []+ for eid in entry_ids:+ if int(eid) in seen:+ continue+ try:+ item = await store.get_notebook_entry(int(eid))+ except Exception as exc:+ logger.warning(f"get_notebook_entry({eid}) failed: {exc}")+ continue+ if not item:+ continue+ seen.add(int(eid))+ loose.append(_format_quiz_entry(item))+ if loose:+ blocks.append("## Picked entries\n" + "\n".join(loose))++ return "\n\n".join(blocks), len(seen)+++# ─────────────────────────────────────────────────────────────────────────────+# Public API+# ─────────────────────────────────────────────────────────────────────────────+++def _normalize_chat_selections(+ raw: list[dict[str, Any]] | None,+ legacy_session_id: str = "",+) -> list[ChatSelection]:+ sels: list[ChatSelection] = []+ if raw:+ for item in raw:+ if not isinstance(item, dict):+ continue+ try:+ sels.append(ChatSelection.model_validate(item))+ except Exception as exc:+ logger.warning(f"Invalid chat selection {item}: {exc}")+ if not sels and legacy_session_id:+ sels.append(ChatSelection(session_id=legacy_session_id, message_ids=[]))+ return sels+++async def build_book_inputs(+ *,+ user_intent: str,+ chat_session_id: str = "",+ chat_selections: list[dict[str, Any]] | None = None,+ notebook_refs: list[dict[str, Any]] | None = None,+ knowledge_bases: list[str] | None = None,+ question_categories: list[int] | None = None,+ question_entries: list[int] | None = None,+ language: str = "en",+ chat_history_limit: int = 60,+) -> tuple[BookInputs, IdeationContext]:+ """Capture the four-source snapshot and produce the IdeationContext."""++ intent = (user_intent or "").strip()+ refs = _normalize_notebook_refs(notebook_refs)+ kb_list = [+ kb.strip()+ for kb in (knowledge_bases or [])+ if isinstance(kb, str) and kb.strip()+ ]+ cat_ids = [int(c) for c in (question_categories or []) if c is not None]+ entry_ids = [int(e) for e in (question_entries or []) if e is not None]+ sels = _normalize_chat_selections(chat_selections, chat_session_id)++ chat_messages = await _resolve_chat_selections(+ sels, limit_per_session=chat_history_limit+ )+ chat_history_text = _format_chat_history(chat_messages)++ notebook_context, record_count = await _resolve_notebook_context(+ intent, refs, language=language+ )+ question_text, question_count = await _resolve_question_notebook(+ cat_ids, entry_ids+ )++ book_inputs = BookInputs(+ user_intent=intent,+ chat_session_id=chat_session_id,+ chat_selections=sels,+ chat_history=chat_messages,+ notebook_refs=refs,+ knowledge_bases=kb_list,+ question_categories=cat_ids,+ question_entries=entry_ids,+ language=language,+ )+ ideation_ctx = IdeationContext(+ user_intent=intent,+ chat_history_text=chat_history_text,+ notebook_context=notebook_context,+ question_notebook_text=question_text,+ knowledge_bases=kb_list,+ notebook_record_count=record_count,+ chat_message_count=len(chat_messages),+ question_entry_count=question_count,+ )++ return book_inputs, ideation_ctx+++__all__ = ["IdeationContext", "build_book_inputs"]diff --git a/deeptutor/book/kb_health.py b/deeptutor/book/kb_health.pynew file mode 100644index 000000000..31b2a0c8c--- /dev/null+++ b/deeptutor/book/kb_health.py@@ -0,0 +1,313 @@+"""KB drift detection & log.md health checks for the Book Engine.++This module is intentionally side-effect-free: it inspects the on-disk+representation of a knowledge base (the ``raw/`` documents folder) to derive a+deterministic fingerprint, compares it to the fingerprint snapshot stored on+the Book manifest, and surfaces a structured impact report. The Book Engine+calls this module after compilation to mark stale pages, and the API exposes+it so the frontend can show a "this book is out-of-date" banner.++A second helper (`scan_log_health`) parses the per-book ``log.md`` to detect+recurring failures – useful for maintenance dashboards.+"""++from __future__ import annotations++import hashlib+import re+from dataclasses import dataclass, field+from datetime import datetime+from pathlib import Path++from deeptutor.knowledge import KnowledgeBaseManager+from deeptutor.logging import get_logger++from .models import Book+from .storage import BookStorage, get_book_storage++logger = get_logger("book.kb_health")+++# ─────────────────────────────────────────────────────────────────────────────+# Fingerprints+# ─────────────────────────────────────────────────────────────────────────────+++def _hash_file(path: Path) -> str:+ """Cheap, change-sensitive fingerprint: name + mtime + size."""+ try:+ stat = path.stat()+ except OSError:+ return ""+ return f"{path.name}:{int(stat.st_mtime)}:{stat.st_size}"+++def fingerprint_kb(kb_name: str, manager: KnowledgeBaseManager | None = None) -> str:+ """Return a deterministic fingerprint for the *raw* docs of a KB.++ Returns ``""`` when the KB does not exist (so callers can detect deletion).+ """+ mgr = manager or KnowledgeBaseManager()+ if kb_name not in mgr.list_knowledge_bases():+ return ""+ base_dir: Path = mgr.base_dir / kb_name / "raw"+ if not base_dir.exists():+ return ""+ parts: list[str] = []+ for child in sorted(base_dir.rglob("*")):+ if not child.is_file():+ continue+ token = _hash_file(child)+ if token:+ parts.append(token)+ if not parts:+ return ""+ digest = hashlib.sha1("|".join(parts).encode("utf-8")).hexdigest()+ return digest+++def fingerprint_kbs(+ kb_names: list[str], manager: KnowledgeBaseManager | None = None+) -> dict[str, str]:+ mgr = manager or KnowledgeBaseManager()+ return {name: fingerprint_kb(name, manager=mgr) for name in kb_names}+++# ─────────────────────────────────────────────────────────────────────────────+# Drift report+# ─────────────────────────────────────────────────────────────────────────────+++@dataclass+class KBDriftReport:+ book_id: str+ has_drift: bool = False+ new_kbs: list[str] = field(default_factory=list)+ removed_kbs: list[str] = field(default_factory=list)+ changed_kbs: list[str] = field(default_factory=list)+ current_fingerprints: dict[str, str] = field(default_factory=dict)+ stale_page_ids: list[str] = field(default_factory=list)++ def to_dict(self) -> dict:+ return {+ "book_id": self.book_id,+ "has_drift": self.has_drift,+ "new_kbs": self.new_kbs,+ "removed_kbs": self.removed_kbs,+ "changed_kbs": self.changed_kbs,+ "current_fingerprints": self.current_fingerprints,+ "stale_page_ids": self.stale_page_ids,+ }+++def detect_kb_drift(+ book: Book,+ storage: BookStorage | None = None,+ manager: KnowledgeBaseManager | None = None,+) -> KBDriftReport:+ """Compare ``book.kb_fingerprints`` against current KB state.++ If the book has no stored fingerprints yet (brand-new book that hasn't+ completed its first compile, or a legacy book created before fingerprinting+ was wired up) we treat the *current* state as the baseline rather than+ flagging every selected KB as "newly added". Without this guard the+ health-check would surface a spurious drift warning the moment the user+ opens a freshly-created book.+ """+ store = storage or get_book_storage()+ current = fingerprint_kbs(book.knowledge_bases, manager=manager)+ stored = dict(book.kb_fingerprints or {})++ if not stored:+ return KBDriftReport(+ book_id=book.id,+ has_drift=False,+ current_fingerprints=current,+ )++ # Only flag *new* KBs that were actually selected for this book — we do+ # not care about KBs the user added to their workspace but never linked+ # to the book.+ new_kbs = [+ k for k in current if k not in stored and k in book.knowledge_bases+ ]+ removed_kbs = [k for k in stored if k not in current and k in book.knowledge_bases]+ changed_kbs = [+ k+ for k, v in current.items()+ if k in stored and stored[k] and v and stored[k] != v+ ]++ has_drift = bool(new_kbs or removed_kbs or changed_kbs)+ stale_pages: list[str] = []+ if has_drift:+ # Any READY page that referenced this KB is stale.+ for page in store.list_pages(book.id):+ if page.status.value == "ready":+ stale_pages.append(page.id)++ return KBDriftReport(+ book_id=book.id,+ has_drift=has_drift,+ new_kbs=new_kbs,+ removed_kbs=removed_kbs,+ changed_kbs=changed_kbs,+ current_fingerprints=current,+ stale_page_ids=stale_pages,+ )+++def refresh_book_fingerprints(+ book_id: str,+ storage: BookStorage | None = None,+ manager: KnowledgeBaseManager | None = None,+) -> Book | None:+ """Re-compute and persist KB fingerprints on the book manifest."""+ store = storage or get_book_storage()+ book = store.load_book(book_id)+ if book is None:+ return None+ book.kb_fingerprints = fingerprint_kbs(book.knowledge_bases, manager=manager)+ book.stale_page_ids = []+ store.save_book(book)+ store.append_log(+ book_id, f"refreshed kb fingerprints ({len(book.kb_fingerprints)} kbs)",+ op="kb_health",+ )+ return book+++def mark_drift_on_book(+ book_id: str,+ storage: BookStorage | None = None,+ manager: KnowledgeBaseManager | None = None,+) -> KBDriftReport | None:+ store = storage or get_book_storage()+ book = store.load_book(book_id)+ if book is None:+ return None+ report = detect_kb_drift(book, storage=store, manager=manager)+ dirty = False++ # Self-heal: when there's no drift but the book is missing a baseline+ # fingerprint (legacy book / new book whose first compile hasn't finished)+ # capture the baseline now so future runs have something to compare to.+ if not report.has_drift and not book.kb_fingerprints and book.knowledge_bases:+ book.kb_fingerprints = report.current_fingerprints or fingerprint_kbs(+ book.knowledge_bases, manager=manager+ )+ dirty = True++ if report.has_drift:+ book.stale_page_ids = report.stale_page_ids+ dirty = True+ store.append_log(+ book_id,+ (+ f"detected kb drift: changed={report.changed_kbs} "+ f"new={report.new_kbs} removed={report.removed_kbs} "+ f"→ {len(report.stale_page_ids)} stale pages"+ ),+ op="kb_health",+ )+ elif book.stale_page_ids:+ # No drift any more (e.g. a previous false-positive was just fixed) →+ # clear the leftover stale markers so the UI banner disappears.+ book.stale_page_ids = []+ dirty = True+ store.append_log(+ book_id,+ "cleared stale page markers (no drift detected)",+ op="kb_health",+ )++ if dirty:+ store.save_book(book)+ return report+++# ─────────────────────────────────────────────────────────────────────────────+# log.md health check+# ─────────────────────────────────────────────────────────────────────────────+++_LOG_LINE = re.compile(+ r"^- `(?P<ts>[^`]+)` \*\*(?P<op>[^*]+)\*\* — (?P<msg>.+)$"+)+++@dataclass+class LogHealthReport:+ book_id: str+ total_entries: int = 0+ error_entries: int = 0+ block_failures: int = 0+ last_compile_at: str = ""+ last_error_at: str = ""+ repeated_failures: list[dict] = field(default_factory=list)++ def to_dict(self) -> dict:+ return {+ "book_id": self.book_id,+ "total_entries": self.total_entries,+ "error_entries": self.error_entries,+ "block_failures": self.block_failures,+ "last_compile_at": self.last_compile_at,+ "last_error_at": self.last_error_at,+ "repeated_failures": self.repeated_failures,+ }+++def scan_log_health(+ book_id: str, storage: BookStorage | None = None+) -> LogHealthReport:+ store = storage or get_book_storage()+ log_path: Path = store.path_service.get_book_log_file(book_id)+ report = LogHealthReport(book_id=book_id)+ if not log_path.exists():+ return report++ counter: dict[str, int] = {}+ try:+ with open(log_path, encoding="utf-8") as f:+ for line in f:+ m = _LOG_LINE.match(line.strip())+ if not m:+ continue+ report.total_entries += 1+ ts = m.group("ts")+ op = m.group("op").strip()+ msg = m.group("msg").strip()+ if op in {"compile_page", "page_compiled", "page_planned"}:+ report.last_compile_at = ts+ if "error" in op.lower() or "fail" in op.lower():+ report.error_entries += 1+ report.last_error_at = ts+ if op == "block_error":+ report.block_failures += 1+ key = f"{op}:{msg[:80]}"+ counter[key] = counter.get(key, 0) + 1+ except OSError as exc:+ logger.warning(f"Could not read log {log_path}: {exc}")+ return report++ repeated = [+ {"signature": k, "count": v}+ for k, v in counter.items()+ if v >= 3+ ]+ repeated.sort(key=lambda r: r["count"], reverse=True)+ report.repeated_failures = repeated[:10]+ return report+++__all__ = [+ "KBDriftReport",+ "LogHealthReport",+ "detect_kb_drift",+ "fingerprint_kb",+ "fingerprint_kbs",+ "mark_drift_on_book",+ "refresh_book_fingerprints",+ "scan_log_health",+]diff --git a/deeptutor/book/models.py b/deeptutor/book/models.pynew file mode 100644index 000000000..b358645a2--- /dev/null+++ b/deeptutor/book/models.py@@ -0,0 +1,468 @@+"""+Book Engine data models+=======================++Pydantic models that describe the persistent state of a Book:++- ``BookInputs`` snapshot of the four sources captured at creation.+- ``BookProposal`` LLM-generated proposal (Stage 1 output).+- ``Spine`` / ``Chapter`` chapter tree (Stage 2 output).+- ``Page`` / ``Block`` content units (Stage 3-4 output).+- ``Progress`` user progress + quiz stats (Stage 5).+- ``Book`` aggregate metadata persisted in ``manifest.json``.+"""++from __future__ import annotations++import time+import uuid+from enum import Enum+from typing import Any++from pydantic import BaseModel, ConfigDict, Field+++# ─────────────────────────────────────────────────────────────────────────────+# Enums+# ─────────────────────────────────────────────────────────────────────────────+++class BookStatus(str, Enum):+ DRAFT = "draft" # ideation only, no spine yet+ SPINE_READY = "spine_ready" # spine confirmed, compilation pending+ COMPILING = "compiling"+ READY = "ready"+ ERROR = "error"+ ARCHIVED = "archived"+++class PageStatus(str, Enum):+ PENDING = "pending"+ PLANNING = "planning"+ GENERATING = "generating"+ READY = "ready"+ PARTIAL = "partial" # some blocks ok, some failed+ ERROR = "error"+++class BlockStatus(str, Enum):+ PENDING = "pending"+ GENERATING = "generating"+ READY = "ready"+ ERROR = "error"+ HIDDEN = "hidden"+++class BlockType(str, Enum):+ # Phase 1+ TEXT = "text"+ CALLOUT = "callout"+ QUIZ = "quiz"+ USER_NOTE = "user_note"+ # Phase 2 — visual taxonomy: figure (svg/chartjs/mermaid) | interactive (html) | animation (video)+ FIGURE = "figure"+ INTERACTIVE = "interactive"+ ANIMATION = "animation"+ CODE = "code"+ TIMELINE = "timeline"+ FLASH_CARDS = "flash_cards"+ # Phase 3+ DEEP_DIVE = "deep_dive"+ # Phase 4 (BookEngine v2)+ SECTION = "section" # long-form chapter section (multi-subsection)+ CONCEPT_GRAPH = "concept_graph" # rendered overview / TOC graph+++class ContentType(str, Enum):+ """Hint that drives Page Planner template selection."""++ THEORY = "theory" # text + figure + quiz + flash_cards+ DERIVATION = "derivation" # text + animation + code + quiz+ HISTORY = "history" # text + timeline + figure + quiz+ PRACTICE = "practice" # quiz + code + text(explanation)+ CONCEPT = "concept" # text + figure + flash_cards + quiz+ OVERVIEW = "overview" # auto-generated TOC / concept-graph chapter+++# ─────────────────────────────────────────────────────────────────────────────+# Helpers+# ─────────────────────────────────────────────────────────────────────────────+++def _new_id(prefix: str) -> str:+ return f"{prefix}_{uuid.uuid4().hex[:10]}"+++def _now() -> float:+ return time.time()+++# ─────────────────────────────────────────────────────────────────────────────+# Inputs (Stage 0)+# ─────────────────────────────────────────────────────────────────────────────+++class NotebookRef(BaseModel):+ """Reference to one notebook with selected record ids."""++ model_config = ConfigDict(extra="ignore")++ notebook_id: str+ record_ids: list[str] = Field(default_factory=list)+++class ChatSelection(BaseModel):+ """Reference to one chat session with optional message-id filter.++ ``message_ids`` empty → use all (recent) messages of that session.+ """++ model_config = ConfigDict(extra="ignore")++ session_id: str+ message_ids: list[int] = Field(default_factory=list)+++class ChatMessageSnapshot(BaseModel):+ """Lightweight snapshot of a chat message captured at book creation."""++ model_config = ConfigDict(extra="ignore")++ role: str = ""+ content: str = ""+ capability: str = ""+ created_at: float = 0.0+++class BookInputs(BaseModel):+ """Four-source input snapshot captured when the book is created."""++ model_config = ConfigDict(extra="ignore")++ user_intent: str = ""+ chat_session_id: str = "" # legacy single-session shorthand+ chat_selections: list[ChatSelection] = Field(default_factory=list)+ chat_history: list[ChatMessageSnapshot] = Field(default_factory=list)+ notebook_refs: list[NotebookRef] = Field(default_factory=list)+ knowledge_bases: list[str] = Field(default_factory=list)+ question_categories: list[int] = Field(default_factory=list)+ question_entries: list[int] = Field(default_factory=list)+ language: str = "en"+ captured_at: float = Field(default_factory=_now)+++# ─────────────────────────────────────────────────────────────────────────────+# Stage 1: Proposal+# ─────────────────────────────────────────────────────────────────────────────+++class BookProposal(BaseModel):+ """LLM-generated proposal returned at the end of Stage 1 (Ideation)."""++ model_config = ConfigDict(extra="allow")++ title: str = ""+ description: str = ""+ scope: str = ""+ target_level: str = ""+ estimated_chapters: int = 0+ rationale: str = ""+++# ─────────────────────────────────────────────────────────────────────────────+# Stage 2: Spine+# ─────────────────────────────────────────────────────────────────────────────+++class SourceAnchor(BaseModel):+ """Pointer back to the raw source(s) that anchor a chapter or block."""++ model_config = ConfigDict(extra="ignore")++ kind: str = "" # 'kb' | 'notebook' | 'chat' | 'web' | 'manual'+ ref: str = "" # KB doc id, notebook record id, message id…+ snippet: str = "" # short preview (≤300 chars)+++class Chapter(BaseModel):+ """A chapter in the spine. May be expanded into one or more pages."""++ model_config = ConfigDict(extra="allow")++ id: str = Field(default_factory=lambda: _new_id("ch"))+ title: str = ""+ learning_objectives: list[str] = Field(default_factory=list)+ content_type: ContentType = ContentType.THEORY+ source_anchors: list[SourceAnchor] = Field(default_factory=list)+ prerequisites: list[str] = Field(default_factory=list) # other chapter ids+ page_ids: list[str] = Field(default_factory=list)+ summary: str = ""+ order: int = 0+++# ─────────────────────────────────────────────────────────────────────────────+# Concept graph (Stage 2 — Spine companion)+# ─────────────────────────────────────────────────────────────────────────────+++class ConceptNode(BaseModel):+ """One concept in the directed concept graph behind the spine."""++ model_config = ConfigDict(extra="ignore")++ id: str = "" # short slug, e.g. "fourier_basis"+ label: str = "" # human-readable concept name+ chapter_id: str = "" # chapter that primarily covers this concept+ description: str = "" # 1-sentence description (optional)+ weight: float = 1.0 # importance / centrality hint+++class ConceptEdge(BaseModel):+ """Directed edge ``from`` → ``to`` in the concept graph."""++ model_config = ConfigDict(extra="ignore")++ src: str = "" # ConceptNode.id+ dst: str = "" # ConceptNode.id+ relation: str = "depends_on" # 'depends_on' | 'extends' | 'related'+ rationale: str = ""+++class ConceptGraph(BaseModel):+ """Directed graph of concepts that grounds the spine."""++ model_config = ConfigDict(extra="ignore")++ nodes: list[ConceptNode] = Field(default_factory=list)+ edges: list[ConceptEdge] = Field(default_factory=list)++ def node_by_id(self, node_id: str) -> ConceptNode | None:+ for n in self.nodes:+ if n.id == node_id:+ return n+ return None++ def has_edge(self, src: str, dst: str) -> bool:+ return any(e.src == src and e.dst == dst for e in self.edges)+++class Spine(BaseModel):+ """Full chapter tree of a book."""++ model_config = ConfigDict(extra="allow")++ book_id: str+ chapters: list[Chapter] = Field(default_factory=list)+ version: int = 1+ updated_at: float = Field(default_factory=_now)+ # New (BookEngine v2): structural / source-grounding companions+ concept_graph: ConceptGraph = Field(default_factory=ConceptGraph)+ exploration_summary: str = ""++ def chapter_by_id(self, chapter_id: str) -> Chapter | None:+ for chapter in self.chapters:+ if chapter.id == chapter_id:+ return chapter+ return None+++# ─────────────────────────────────────────────────────────────────────────────+# Source exploration (Stage 2 prep — fed into SpineSynthesizer & compiler)+# ─────────────────────────────────────────────────────────────────────────────+++class SourceChunk(BaseModel):+ """A retrieved chunk that grounds spine / block generation.++ Persisted alongside the book so subsequent stages can reuse retrievals+ without re-hitting the RAG pipeline.+ """++ model_config = ConfigDict(extra="ignore")++ chunk_id: str = ""+ kb_name: str = "" # empty for non-KB sources (chat / notebook…)+ source: str = "" # 'kb' | 'notebook' | 'chat' | 'questions' | 'web'+ ref: str = "" # doc id / record id / message id …+ text: str = ""+ score: float = 0.0+ query: str = "" # the query that surfaced this chunk+ metadata: dict[str, Any] = Field(default_factory=dict)+++class ExplorationReport(BaseModel):+ """Structured artefact produced by ``SourceExplorer``.++ Captures the multi-query parallel sweep across the user-provided sources+ (KBs, notebooks, chat selections, question entries…). Down-stream stages+ (SpineSynthesizer, SectionArchitect, BlockGenerators) read from this report+ instead of re-issuing retrievals — making generation deterministic and far+ cheaper after the first sweep.+ """++ model_config = ConfigDict(extra="ignore")++ book_id: str = ""+ queries: list[str] = Field(default_factory=list)+ chunks: list[SourceChunk] = Field(default_factory=list)+ summary: str = "" # short LLM summary of recurring themes+ coverage: dict[str, int] = Field(default_factory=dict) # source → chunk count+ candidate_concepts: list[str] = Field(default_factory=list)+ notes: list[str] = Field(default_factory=list)+ created_at: float = Field(default_factory=_now)+++# ─────────────────────────────────────────────────────────────────────────────+# Blocks+# ─────────────────────────────────────────────────────────────────────────────+++class Block(BaseModel):+ """Atomic content unit on a page. Rendered natively by the frontend."""++ model_config = ConfigDict(extra="allow")++ id: str = Field(default_factory=lambda: _new_id("blk"))+ type: BlockType+ status: BlockStatus = BlockStatus.PENDING+ title: str = ""+ # Generator inputs (kept after generation for retry / regenerate)+ params: dict[str, Any] = Field(default_factory=dict)+ # Generated payload (shape depends on `type`)+ payload: dict[str, Any] = Field(default_factory=dict)+ # Source anchors that grounded the block+ source_anchors: list[SourceAnchor] = Field(default_factory=list)+ # Free-form metadata (timing, model, retries…)+ metadata: dict[str, Any] = Field(default_factory=dict)+ error: str = ""+ created_at: float = Field(default_factory=_now)+ updated_at: float = Field(default_factory=_now)+++# ─────────────────────────────────────────────────────────────────────────────+# Pages+# ─────────────────────────────────────────────────────────────────────────────+++class PageLink(BaseModel):+ """Cross-page relationship (deepens, references, prereq…)."""++ model_config = ConfigDict(extra="ignore")++ target_page_id: str+ relation: str = "references" # 'deepens' | 'prereq' | 'references'+ label: str = ""+++class Page(BaseModel):+ """A single page = ordered sequence of Blocks + state."""++ model_config = ConfigDict(extra="allow")++ id: str = Field(default_factory=lambda: _new_id("pg"))+ book_id: str = ""+ chapter_id: str = ""+ title: str = ""+ learning_objectives: list[str] = Field(default_factory=list)+ content_type: ContentType = ContentType.THEORY+ status: PageStatus = PageStatus.PENDING+ order: int = 0+ blocks: list[Block] = Field(default_factory=list)+ links: list[PageLink] = Field(default_factory=list)+ parent_page_id: str = "" # for deep_dive sub-pages+ error: str = ""+ created_at: float = Field(default_factory=_now)+ updated_at: float = Field(default_factory=_now)++ def block_by_id(self, block_id: str) -> Block | None:+ for block in self.blocks:+ if block.id == block_id:+ return block+ return None+++# ─────────────────────────────────────────────────────────────────────────────+# Stage 5: Progress+# ─────────────────────────────────────────────────────────────────────────────+++class QuizAttempt(BaseModel):+ model_config = ConfigDict(extra="ignore")++ block_id: str+ page_id: str+ question_id: str = ""+ user_answer: str = ""+ is_correct: bool = False+ timestamp: float = Field(default_factory=_now)+++class Progress(BaseModel):+ """Per-user progress through the book."""++ model_config = ConfigDict(extra="ignore")++ book_id: str+ current_page_id: str = ""+ visited_page_ids: list[str] = Field(default_factory=list)+ bookmarked_page_ids: list[str] = Field(default_factory=list)+ quiz_attempts: list[QuizAttempt] = Field(default_factory=list)+ weak_chapters: list[str] = Field(default_factory=list)+ score: int = 0+ updated_at: float = Field(default_factory=_now)+++# ─────────────────────────────────────────────────────────────────────────────+# Aggregate manifest+# ─────────────────────────────────────────────────────────────────────────────+++class Book(BaseModel):+ """Top-level book metadata persisted in ``manifest.json``."""++ model_config = ConfigDict(extra="allow")++ id: str = Field(default_factory=lambda: _new_id("bk"))+ title: str = ""+ description: str = ""+ status: BookStatus = BookStatus.DRAFT+ proposal: BookProposal | None = None+ knowledge_bases: list[str] = Field(default_factory=list)+ language: str = "en"+ page_count: int = 0+ chapter_count: int = 0+ created_at: float = Field(default_factory=_now)+ updated_at: float = Field(default_factory=_now)+ metadata: dict[str, Any] = Field(default_factory=dict)+ # KB fingerprints captured at compile-time. Used to detect KB drift.+ kb_fingerprints: dict[str, str] = Field(default_factory=dict)+ # Pages whose KB content has changed since they were last compiled.+ stale_page_ids: list[str] = Field(default_factory=list)+++__all__ = [+ "BookStatus",+ "PageStatus",+ "BlockStatus",+ "BlockType",+ "ContentType",+ "NotebookRef",+ "ChatSelection",+ "ChatMessageSnapshot",+ "BookInputs",+ "BookProposal",+ "SourceAnchor",+ "Chapter",+ "ConceptNode",+ "ConceptEdge",+ "ConceptGraph",+ "Spine",+ "SourceChunk",+ "ExplorationReport",+ "Block",+ "Page",+ "PageLink",+ "QuizAttempt",+ "Progress",+ "Book",+]diff --git a/deeptutor/book/prompts/en/callout.yaml b/deeptutor/book/prompts/en/callout.yamlnew file mode 100644index 000000000..46f2eb2e6--- /dev/null+++ b/deeptutor/book/prompts/en/callout.yaml@@ -0,0 +1,12 @@+system: |+ You are the Callout writer for DeepTutor's BookEngine. Produce a single+ short (<=60 words) sticky-note style insight. No JSON, no title, no lists –+ just the body text.++user_template: |+ Chapter: {chapter_title}+ Summary: {chapter_summary}+ Objectives: {objectives_inline}+ Callout variant: {variant} ({label})++ Write the callout body.diff --git a/deeptutor/book/prompts/en/code.yaml b/deeptutor/book/prompts/en/code.yamlnew file mode 100644index 000000000..46543ea70--- /dev/null+++ b/deeptutor/book/prompts/en/code.yaml@@ -0,0 +1,14 @@+system: |+ You are the Code Block generator for DeepTutor's BookEngine. Produce a+ minimal, self-contained, runnable example that fits the chapter slot, plus+ a short (1-2 sentence) English explanation. Strictly output JSON:+ {"language": "...", "code": "...", "explanation": "..."}.++user_template: |+ Chapter: {chapter_title}+ Summary: {chapter_summary}+ Objectives: {objectives_inline}+ Slot intent: {intent}+ Preferred language: {language}++ Output the JSON now.diff --git a/deeptutor/book/prompts/en/deep_dive.yaml b/deeptutor/book/prompts/en/deep_dive.yamlnew file mode 100644index 000000000..be68bff77--- /dev/null+++ b/deeptutor/book/prompts/en/deep_dive.yaml@@ -0,0 +1,10 @@+system: |+ You are the Deep Dive recommender for DeepTutor's BookEngine. Output JSON:+ {"suggestions": [{"topic": "...", "rationale": "..."}]}+ with 3 sub-topics that deserve a deeper sub-page.++user_template: |+ Chapter: {chapter_title}+ Summary: {chapter_summary}++ Output the JSON now.diff --git a/deeptutor/book/prompts/en/flash_cards.yaml b/deeptutor/book/prompts/en/flash_cards.yamlnew file mode 100644index 000000000..9333e3119--- /dev/null+++ b/deeptutor/book/prompts/en/flash_cards.yaml@@ -0,0 +1,12 @@+system_template: |+ You are the Flashcard generator for DeepTutor's BookEngine. Output JSON:+ {{"cards": [{{"front": "...", "back": "...", "hint": "..."}}]}}+ with {count} high-signal cards. ``front`` is the prompt, ``back`` is a+ concise answer.++user_template: |+ Chapter: {chapter_title}+ Summary: {chapter_summary}+ Objectives: {objectives_inline}++ Output the JSON now.diff --git a/deeptutor/book/prompts/en/ideation_agent.yaml b/deeptutor/book/prompts/en/ideation_agent.yamlnew file mode 100644index 000000000..1dc16ae8a--- /dev/null+++ b/deeptutor/book/prompts/en/ideation_agent.yaml@@ -0,0 +1,30 @@+system: |+ You are the Ideation stage of DeepTutor's BookEngine. Given a learner's+ intent together with optional context (past conversations, notebook+ highlights, knowledge bases), propose ONE coherent "living book" the system+ should compile.++ Your output is a single JSON object (no prose, no markdown fences) shaped+ exactly like:+ {+ "title": "<= 80 chars title",+ "description": "1-3 sentence elevator pitch for the book",+ "scope": "what is in / out of scope, in 1-2 sentences",+ "target_level": "introductory | intermediate | advanced | mixed",+ "estimated_chapters": <integer 3-8>,+ "rationale": "1-2 sentences justifying the structure based on the inputs"+ }++ Guidelines:+ - Stay tightly anchored to the learner's intent; do not blow up the scope.+ - Prefer fewer, richer chapters over many shallow ones.+ - All knowledge bases listed under [Knowledge Sources] will be used as+ grounding material in later stages; do not re-select among them.+ - Use the same language as the learner's intent.++user_template: |+ Below are the four input sources captured for this book.++ {ideation_context}++ Propose the book now. Respond with the JSON object only.diff --git a/deeptutor/book/prompts/en/page_planner.yaml b/deeptutor/book/prompts/en/page_planner.yamlnew file mode 100644index 000000000..097287353--- /dev/null+++ b/deeptutor/book/prompts/en/page_planner.yaml@@ -0,0 +1,57 @@+block_catalog: |+ Available block types — use ANY combination that serves the chapter best:++ - **section**: Long-form prose (1000-2500 words). Core chapter content.+ params: {"role": "<intro|core|deep_dive|analysis|synthesis|...>", "target_words": <int>}+ - **text**: Short text (100-400 words). Transitions, summaries, brief notes.+ - **callout**: Highlighted box — key idea, warning, tip, common pitfall, insight.+ params: {"variant": "<key_idea|warning|tip|common_pitfall|insight|connection>"}+ - **quiz**: Interactive questions. params: {"num_questions": <int>, "difficulty": "<easy|mixed|hard>"}+ - **flash_cards**: Flashcards for spaced retention. params: {"count": <int 3-8>}+ - **figure**: Static figure — SVG diagram, Chart.js chart, or Mermaid graph+ (flowchart / mindmap / class / sequence / state / ER / Gantt). The renderer+ picks the best of svg / chartjs / mermaid automatically.+ params: {"variant": "<diagram|comparison|flowchart|mindmap|illustration|schematic>",+ "focus": "<what to highlight>"}+ - **interactive**: Self-contained interactive HTML widget — draggable demo,+ guided walkthrough, clickable exercise, animation with controls.+ params: {"interaction": "<interactive|walkthrough|simulation|guided exercise>",+ "focus": "<what the learner manipulates>"}+ - **animation**: Manim-rendered video explanation (mathematical processes,+ derivations, algorithms). Heavyweight; use sparingly.+ params: {"focus": "<what the animation shows>", "quality": "low|medium|high"}+ - **code**: Runnable code example. params: {"language": "<python|js|...>", "intent": "<example|verify|scaffold>"}+ - **timeline**: Chronological event sequence.++architect_system: |+ You are the SectionArchitect of DeepTutor's BookEngine.+ Design a rich, engaging reading sequence for the given chapter. Return+ STRICT JSON:+ {"blocks": [{"type": "<block_type>", "focus": "<focus>",+ "transition_in": "<1-sentence bridge from previous block>", "params": { ... }}]}++ {block_catalog}+ Design principles:+ - 5-10 blocks. Prefer variety — avoid repeating the same type.+ - **Interleave** different block types naturally: explanation → example →+ practice → deeper insight → another angle, like a great textbook.+ - Each block should connect logically to the previous one via transition_in.+ - At least 1 section for core prose, but you may scatter multiple sections+ at different points in the sequence.+ - Match block types to the content's nature: derivations need animation/code,+ concepts need figure (svg/chartjs/mermaid), interactive exploration needs+ interactive, practice needs quiz/code.+ - Do NOT emit deep_dive / user_note / concept_graph.++architect_user: |+ Chapter title: {chapter_title}+ Chapter summary: {chapter_summary}+ Content type hint: {content_type} (for reference only — freely choose the+ best block mix)+ Learning objectives:+ {objectives_block}++ [Source exploration summary]+ {exploration_summary}++ Design a rich, interleaved block sequence. Respond with JSON only.diff --git a/deeptutor/book/prompts/en/section.yaml b/deeptutor/book/prompts/en/section.yamlnew file mode 100644index 000000000..cd54ea8a1--- /dev/null+++ b/deeptutor/book/prompts/en/section.yaml@@ -0,0 +1,44 @@+outline_system: |+ You are the Section Architect of DeepTutor's BookEngine. Plan ONE long-form+ section based on the chapter info and retrieved evidence. Output STRICT+ JSON of the shape:+ {+ "intro": "<= 70 words opening paragraph",+ "subsections": [+ {"heading": "H3 heading", "role": "core | example | derivation | application | comparison",+ "focus": "1-sentence focus", "target_words": 280-360}+ ],+ "key_takeaway": "<= 40 words crisp takeaway"+ }+ Rules: 3-5 subsections; total target 1500-2500 words; concise headings;+ align with the chapter's learning objectives; do NOT write the body —+ only the plan.++outline_user: |+ Chapter: {chapter_title}+ Chapter summary: {chapter_summary}+ Learning objectives:+ {objectives_block}+ Section focus: {focus_topic}+ Section role: {section_role}+ Target total words: {target_words}+ {rag_section}+ Respond with the JSON outline only.++subsection_system: |+ You are the Subsection writer of DeepTutor's BookEngine. Produce one+ tightly written Markdown subsection that matches the given heading, role,+ and word target. You may use lists, `code`, and $math$. Do not emit any+ H1/H2 headings (start from H3 / ### only); do not repeat the full chapter+ title; do not wrap output in JSON or code fences.++subsection_user: |+ Chapter: {chapter_title}+ Section focus: {section_focus}+ Section opener (style reference): {outline_intro}+ Subsection heading: {heading}+ Subsection role: {role}+ Focus: {focus}+ Target words: {target_words}+ {evidence_section}+ Write the Markdown body now (start with the H3 heading).diff --git a/deeptutor/book/prompts/en/source_explorer.yaml b/deeptutor/book/prompts/en/source_explorer.yamlnew file mode 100644index 000000000..144c38212--- /dev/null+++ b/deeptutor/book/prompts/en/source_explorer.yaml@@ -0,0 +1,74 @@+queries_system: |+ You are the SourceExplorer of DeepTutor's BookEngine. Given a confirmed+ ``BookProposal`` and the learner's intent, design a set of 4-8 short,+ diverse search queries that, when run against the learner's knowledge+ bases (and other sources), will surface the most useful, structurally+ diverse evidence to help design a good book about the topic.++ Guidelines:+ - Cover BREADTH: include queries about overview/definitions, mechanisms,+ representative examples/cases, edge cases or pitfalls, applications, and+ historical/comparative context.+ - Use the SAME language as the learner's intent.+ - Each query should be standalone (3-12 words), specific enough to retrieve+ something concrete, but not so narrow it duplicates another query.+ - Avoid duplicating queries; ensure conceptual coverage.++ Output ONLY a JSON object of the form:+ {+ "queries": ["...", "...", ...]+ }++queries_user: |+ Learner intent:+ {user_intent}++ Approved proposal:+ {proposal_block}++ Knowledge bases available:+ {kb_list}++ Other context (notebook / chat highlights):+ {extra_context}++ Design the search queries now. Respond with the JSON object only.++summary_system: |+ You are summarising an exploration over the learner's source materials+ (knowledge bases, notebook records, prior chats, quiz history) for+ DeepTutor's BookEngine.++ Read the chunks and produce:+ - ``summary``: 4-8 sentences describing the recurring themes, the strongest+ evidence the sources offer, and gaps or weak spots that the spine should+ address.+ - ``candidate_concepts``: 8-20 short concept labels (≤ 5 words each) that+ will become candidate nodes in the concept graph. Prefer atomic, reusable+ terms over long phrases.+ - ``notes``: optional bullet list (≤ 5) of caveats / contradictions /+ follow-up questions worth surfacing.++ Use the same language as the learner's intent.++ Output ONLY a JSON object:+ {+ "summary": "...",+ "candidate_concepts": ["...", "..."],+ "notes": ["..."]+ }++summary_user: |+ Learner intent:+ {user_intent}++ Proposal title: {proposal_title}+ Proposal scope: {proposal_scope}++ Coverage by source:+ {coverage_block}++ Top retrieved chunks (truncated):+ {chunks_block}++ Produce the JSON object now.diff --git a/deeptutor/book/prompts/en/spine_agent.yaml b/deeptutor/book/prompts/en/spine_agent.yamlnew file mode 100644index 000000000..b239e511e--- /dev/null+++ b/deeptutor/book/prompts/en/spine_agent.yaml@@ -0,0 +1,43 @@+system: |+ You are the Spine stage of DeepTutor's BookEngine. Given the approved+ BookProposal plus optional source material from the learner's knowledge+ bases, design the chapter tree (the "spine") of the book.++ Output a single JSON object (no prose, no markdown fences):+ {+ "chapters": [+ {+ "title": "concise chapter title",+ "learning_objectives": ["bullet 1", "bullet 2", ...],+ "content_type": "theory | derivation | history | practice | concept",+ "source_anchors": [+ {"kind": "kb|notebook|chat|manual", "ref": "<id or short ref>", "snippet": "<=200 chars"}+ ],+ "prerequisites": ["<title of an earlier chapter>"],+ "summary": "1-2 sentence chapter abstract"+ }+ ]+ }++ Guidelines:+ - Number of chapters should match the proposal's estimated_chapters (±1).+ - Order chapters from foundational to advanced; declare prerequisites+ using earlier chapter titles only.+ - Pick a content_type that maximally fits each chapter:+ * theory – conceptual explanation + visual aids+ * derivation – math/formula heavy, benefits from animation+ * history – timeline / case-study material+ * practice – exercise-driven+ * concept – definition / vocabulary heavy+ - source_anchors must reference the SUPPLIED material when available.+ - Each chapter should be a meaningful, self-contained learning unit.+ - Use the same language as the proposal title.++user_template: |+ Approved Book Proposal:+ {proposal_block}++ Material available from the learner's knowledge bases / notebooks:+ {source_material}++ Design the spine now. Respond with the JSON object only.diff --git a/deeptutor/book/prompts/en/spine_synthesizer.yaml b/deeptutor/book/prompts/en/spine_synthesizer.yamlnew file mode 100644index 000000000..57db6fe9a--- /dev/null+++ b/deeptutor/book/prompts/en/spine_synthesizer.yaml@@ -0,0 +1,126 @@+draft_system: |+ You are the **draft** step of DeepTutor's SpineSynthesizer. Given the+ approved ``BookProposal``, the ``ExplorationReport`` (source summary + key+ evidence chunks + candidate concepts), design TWO things in a single JSON+ object:++ 1. ``concept_graph`` – an evidence-grounded directed graph of concepts that+ the book should teach. Use the exploration's ``candidate_concepts`` as a+ seed but feel free to add / drop / merge. Edges point from prerequisite to+ dependent concept ("depends_on") or "extends" / "related" where relevant.+ 2. ``chapters`` – a chapter spine that *covers* the concept graph. Each+ chapter should pick up one or more nodes (``covers`` field). Order should+ follow a topological order of concept dependencies.++ Output ONLY this JSON shape (no prose, no markdown fences):+ {+ "concept_graph": {+ "nodes": [+ {"id": "<slug>", "label": "<human label>", "description": "<= 1 sentence",+ "weight": <0.1-1.0>}+ ],+ "edges": [+ {"src": "<node id>", "dst": "<node id>",+ "relation": "depends_on | extends | related",+ "rationale": "<= 1 sentence"}+ ]+ },+ "chapters": [+ {+ "title": "concise chapter title",+ "learning_objectives": ["bullet 1", "bullet 2", ...],+ "content_type": "theory | derivation | history | practice | concept",+ "covers": ["<concept node id>", ...],+ "source_anchors": [+ {"kind": "kb|notebook|chat|manual", "ref": "<id>", "snippet": "<=200 chars"}+ ],+ "prerequisites": ["<earlier chapter title>"],+ "summary": "1-2 sentence chapter abstract"+ }+ ]+ }++ Guidelines:+ - Number of chapters should match the proposal's ``estimated_chapters`` (±1).+ - Every chapter should ``cover`` at least one concept node; every concept+ node should be covered by at least one chapter.+ - Use ``snake_case`` ids for concept nodes; keep them short and reusable.+ - Avoid circular dependencies in the concept graph.+ - Use the same language as the proposal title.++draft_user: |+ Approved BookProposal:+ {proposal_block}++ Exploration summary:+ {exploration_summary}++ Candidate concepts (seed):+ {candidate_concepts}++ Evidence highlights:+ {chunks_block}++ Design the JSON object now.++critique_system: |+ You are the **critique** step of DeepTutor's SpineSynthesizer. Given a+ draft spine + concept graph, identify concrete weaknesses. Be terse and+ specific.++ Output ONLY a JSON object:+ {+ "issues": [+ {"category": "coverage | ordering | granularity | redundancy | missing_anchor | cycle | other",+ "detail": "<= 2 sentences explaining the issue",+ "fix_hint": "<= 1 sentence suggesting a concrete fix"}+ ],+ "verdict": "ok | revise"+ }++ Look for:+ - Concept nodes never covered by any chapter (or vice versa).+ - Chapters whose prerequisites are inconsistent with the concept graph.+ - Cycles or contradictions among ``depends_on`` edges.+ - Chapters that are too broad / too narrow relative to the proposal scope.+ - Redundant chapters or near-duplicate concept nodes.+ - Empty source_anchors when relevant exploration evidence exists.++ If there are no real issues, return ``"verdict": "ok"`` with an empty+ ``issues`` list.++critique_user: |+ Approved BookProposal:+ {proposal_block}++ Draft (spine + concept graph):+ {draft_block}++ Exploration summary:+ {exploration_summary}++ Critique now.++revise_system: |+ You are the **revise** step of DeepTutor's SpineSynthesizer. Given the+ prior draft and a structured critique, produce a corrected JSON object+ with the SAME schema as the draft step (``concept_graph`` + ``chapters``).++ Apply the fix hints faithfully. If a critique entry is unclear or+ conflicting, prefer the option that increases concept-graph coverage and+ topological consistency. Do not introduce new chapters that were not+ hinted at unless coverage clearly demands it.++ Output ONLY the JSON object.++revise_user: |+ Approved BookProposal:+ {proposal_block}++ Critique:+ {critique_block}++ Prior draft:+ {draft_block}++ Produce the revised JSON now.diff --git a/deeptutor/book/prompts/en/text.yaml b/deeptutor/book/prompts/en/text.yamlnew file mode 100644index 000000000..5b16d0f12--- /dev/null+++ b/deeptutor/book/prompts/en/text.yaml@@ -0,0 +1,29 @@+system: |+ You are the Text Block writer of DeepTutor's BookEngine. Produce a compact,+ well-structured Markdown explanation that fits the given chapter slot. You+ may use ###, lists, `code`, and inline math ($...$). Do not repeat the full+ chapter title and do not output JSON or code-fence wrappers.++user_template: |+ Chapter: {chapter_title}+ Chapter summary: {chapter_summary}+ Learning objectives:+ {objectives_block}+ Slot role: {role}+ {previous_section}{rag_section}+ Write 150-300 words of Markdown explanation.++bridge_system: |+ You are the Bridge / Transition writer of DeepTutor's BookEngine. Given a+ short summary of the previous block and a hint about the next block, write+ 1-2 short Markdown sentences that smoothly carry the reader forward. Use a+ plain, natural tone — like a connecting paragraph inside a textbook+ chapter. No headings, no bullet lists, no code fences, no JSON, and do not+ repeat the full chapter title.++bridge_user_template: |+ Chapter: {chapter_title}+ Previous block summary: {previous_block_summary}+ Next block hint: {next_block_hint}++ Write 1-2 short Markdown sentences that bridge the two.diff --git a/deeptutor/book/prompts/en/timeline.yaml b/deeptutor/book/prompts/en/timeline.yamlnew file mode 100644index 000000000..0bbe56205--- /dev/null+++ b/deeptutor/book/prompts/en/timeline.yaml@@ -0,0 +1,10 @@+system: |+ You are the Timeline generator for DeepTutor's BookEngine. Output a JSON+ object: {"events": [{"date": "...", "title": "...", "description": "..."}]}+ with 4-8 key events sorted chronologically (oldest first).++user_template: |+ Chapter: {chapter_title}+ Summary: {chapter_summary}++ Output the JSON now.diff --git a/deeptutor/book/prompts/zh/callout.yaml b/deeptutor/book/prompts/zh/callout.yamlnew file mode 100644index 000000000..dd3195031--- /dev/null+++ b/deeptutor/book/prompts/zh/callout.yaml@@ -0,0 +1,12 @@+system: |+ 你是 DeepTutor BookEngine 的 Callout 写作者。请输出一个简短(≤80 字)、+ 清晰、有强烈记忆点的提示,用于 Markdown 卡片展示。不要 JSON、不要标题、+ 不要列表。++user_template: |+ 章节:{chapter_title}+ 摘要:{chapter_summary}+ 目标:{objectives_inline}+ Callout 变体:{variant}({label})++ 请输出该 callout 的正文。diff --git a/deeptutor/book/prompts/zh/code.yaml b/deeptutor/book/prompts/zh/code.yamlnew file mode 100644index 000000000..0db5b5a41--- /dev/null+++ b/deeptutor/book/prompts/zh/code.yaml@@ -0,0 +1,13 @@+system: |+ 你是 DeepTutor BookEngine 的 Code Block 生成器。请生成与章节配套的、+ 可独立运行的最小代码示例,并配上 1-2 句中文解释。严格输出 JSON:+ {"language": "...", "code": "...", "explanation": "..."}。++user_template: |+ 章节:{chapter_title}+ 摘要:{chapter_summary}+ 目标:{objectives_inline}+ 槽位意图:{intent}+ 首选语言:{language}++ 请直接输出 JSON。diff --git a/deeptutor/book/prompts/zh/deep_dive.yaml b/deeptutor/book/prompts/zh/deep_dive.yamlnew file mode 100644index 000000000..ca6f32be7--- /dev/null+++ b/deeptutor/book/prompts/zh/deep_dive.yaml@@ -0,0 +1,10 @@+system: |+ 你是 DeepTutor BookEngine 的 Deep Dive 推荐器。请输出 JSON:+ {"suggestions": [{"topic": "...", "rationale": "..."}]}。+ 建议 3 个最值得深入展开的子话题。++user_template: |+ 章节:{chapter_title}+ 摘要:{chapter_summary}++ 请直接输出 JSON。diff --git a/deeptutor/book/prompts/zh/flash_cards.yaml b/deeptutor/book/prompts/zh/flash_cards.yamlnew file mode 100644index 000000000..1e411697d--- /dev/null+++ b/deeptutor/book/prompts/zh/flash_cards.yaml@@ -0,0 +1,11 @@+system_template: |+ 你是 DeepTutor BookEngine 的 Flashcard 生成器。请输出 JSON:+ {{"cards": [{{"front": "...", "back": "...", "hint": "..."}}]}}。+ 生成 {count} 张高质量记忆卡,front 是问题/概念,back 是简洁答案。++user_template: |+ 章节:{chapter_title}+ 摘要:{chapter_summary}+ 目标:{objectives_inline}++ 请直接输出 JSON。diff --git a/deeptutor/book/prompts/zh/ideation_agent.yaml b/deeptutor/book/prompts/zh/ideation_agent.yamlnew file mode 100644index 000000000..0e09b422b--- /dev/null+++ b/deeptutor/book/prompts/zh/ideation_agent.yaml@@ -0,0 +1,27 @@+system: |+ 你是 DeepTutor BookEngine 的 Ideation 阶段。基于学习者的目标,结合可选的+ 上下文(历史对话、笔记本要点、知识库),为系统提出 **一本** 连贯的+ 「活的书」(living book) 的方案。++ 你的输出必须是一个 JSON 对象(不要散文,不要 markdown 代码块),结构如下:+ {+ "title": "标题,不超过 80 字符",+ "description": "1-3 句话的电梯描述",+ "scope": "1-2 句话说明涵盖与不涵盖的内容",+ "target_level": "introductory | intermediate | advanced | mixed",+ "estimated_chapters": <3 到 8 的整数>,+ "rationale": "1-2 句话解释结构选择"+ }++ 原则:+ - 紧扣学习者意图,不要无限扩展范围+ - 偏好少而精的章节,而不是多而浅+ - [Knowledge Sources] 中列出的所有知识库都会在后续阶段作为素材使用,无需在此再做选择+ - 使用与学习者意图一致的语言++user_template: |+ 以下是为本书捕获的四源输入:++ {ideation_context}++ 请立即输出书的方案,仅返回 JSON 对象。diff --git a/deeptutor/book/prompts/zh/page_planner.yaml b/deeptutor/book/prompts/zh/page_planner.yamlnew file mode 100644index 000000000..44addde60--- /dev/null+++ b/deeptutor/book/prompts/zh/page_planner.yaml@@ -0,0 +1,52 @@+block_catalog: |+ 可用 block 类型 —— 自由组合最适合本章节的搭配:++ - **section**:长文 prose(1000-2500 字),章节核心内容。+ params: {"role": "<intro|core|deep_dive|analysis|synthesis|...>", "target_words": <int>}+ - **text**:短文(100-400 字),用于过渡、小结、简短笔记。+ - **callout**:高亮卡片 —— 核心要点、警示、技巧、常见误区、洞见。+ params: {"variant": "<key_idea|warning|tip|common_pitfall|insight|connection>"}+ - **quiz**:交互题。params: {"num_questions": <int>, "difficulty": "<easy|mixed|hard>"}+ - **flash_cards**:用于记忆的闪卡。params: {"count": <int 3-8>}+ - **figure**:静态图 —— SVG 图、Chart.js 图表,或 Mermaid 图(flowchart /+ mindmap / class / sequence / state / ER / Gantt)。渲染器会自动在+ svg / chartjs / mermaid 中挑选最合适的形式。+ params: {"variant": "<diagram|comparison|flowchart|mindmap|illustration|schematic>",+ "focus": "<想突出的重点>"}+ - **interactive**:独立的交互 HTML 小部件 —— 可拖拽演示、引导式走查、+ 可点击练习、带控件的动画。+ params: {"interaction": "<interactive|walkthrough|simulation|guided exercise>",+ "focus": "<学习者要操作的对象>"}+ - **animation**:Manim 渲染的视频讲解(数学过程、推导、算法)。较重,慎用。+ params: {"focus": "<动画要展示的内容>", "quality": "low|medium|high"}+ - **code**:可运行代码示例。params: {"language": "<python|js|...>", "intent": "<example|verify|scaffold>"}+ - **timeline**:按时间顺序的事件序列。++architect_system: |+ 你是 DeepTutor BookEngine 的 SectionArchitect。+ 为给定章节设计一个丰富、引人入胜的阅读序列,返回严格 JSON:+ {"blocks": [{"type": "<block_type>", "focus": "<本块聚焦点>",+ "transition_in": "<1 句过渡句,连接上一块>", "params": { ... }}]}++ {block_catalog}+ 设计原则:+ - 5-10 个 block;追求多样性,不要重复同类型+ - 围绕计划讲解的内容,**穿插排列**不同类型的 block,像一个优秀教科书一样+ - 每个 block 之间应该有自然的逻辑衔接,通过 transition_in 体现+ - 至少 1 个 section 承担核心讲解,但可以把多个 section 分散在不同位置+ - 根据内容本身的需要选择 block 类型:推导需要 animation/code,概念需要+ figure(svg/chartjs/mermaid),交互探索需要 interactive,实践需要+ quiz/code+ - 不要返回 deep_dive / user_note / concept_graph++architect_user: |+ 章节标题:{chapter_title}+ 章节摘要:{chapter_summary}+ 内容类型提示:{content_type}(仅供参考,自由选择最合适的 block 组合)+ 学习目标:+ {objectives_block}++ [资料探索摘要]+ {exploration_summary}++ 请设计一个丰富多样、穿插排列的 block 序列。直接输出 JSON。diff --git a/deeptutor/book/prompts/zh/section.yaml b/deeptutor/book/prompts/zh/section.yamlnew file mode 100644index 000000000..8ecbccb52--- /dev/null+++ b/deeptutor/book/prompts/zh/section.yaml@@ -0,0 +1,41 @@+outline_system: |+ 你是 DeepTutor BookEngine 的 Section Architect。请基于章节信息以及检索证据,+ 规划 1 个 section 的结构。输出严格 JSON:+ {+ "intro": "≤ 80 字的开场短段",+ "subsections": [+ {"heading": "二级标题", "role": "core | example | derivation | application | comparison",+ "focus": "本段聚焦点 ≤ 1 句", "target_words": 280-360}+ ],+ "key_takeaway": "≤ 50 字的核心要点提炼"+ }+ 原则:3-5 个 subsection;总字数 1500-2500;标题精炼;与章节学习目标对齐;+ 不要在 outline 内写正文,只列 plan。++outline_user: |+ 章节:{chapter_title}+ 章节摘要:{chapter_summary}+ 学习目标:+ {objectives_block}+ 本 section 焦点:{focus_topic}+ Section 定位:{section_role}+ 目标总字数:{target_words}+ {rag_section}+ 请直接输出 JSON outline。++subsection_system: |+ 你是 DeepTutor 的 Section Subsection 写作者。请输出一段紧凑、有信息密度的+ Markdown 讲解,符合给定的标题、定位、字数目标。可以使用列表/`代码`/$math$。+ 不要再输出任何 H1/H2 标题,只能从 H3 (###) 开始;不要重复整章标题;不要+ 输出 JSON 或代码块包裹。++subsection_user: |+ 所属章节:{chapter_title}+ Section 焦点:{section_focus}+ Section 开场(仅供风格参考):{outline_intro}+ 本子节标题:{heading}+ 本子节定位:{role}+ 聚焦点:{focus}+ 目标字数:{target_words}+ {evidence_section}+ 请直接输出 Markdown 正文(以 ### 开头的子节标题)。diff --git a/deeptutor/book/prompts/zh/source_explorer.yaml b/deeptutor/book/prompts/zh/source_explorer.yamlnew file mode 100644index 000000000..29b91dce5--- /dev/null+++ b/deeptutor/book/prompts/zh/source_explorer.yaml@@ -0,0 +1,67 @@+queries_system: |+ 你是 DeepTutor BookEngine 的 SourceExplorer。给定一个已确认的+ BookProposal 与用户意图,请设计 4-8 个简短、多样的检索查询。+ 这些查询会在用户提供的知识库(以及其他来源)上运行,目的是为后续+ 章节设计提供结构上多样、信息密度高的证据。++ 原则:+ - 覆盖广度:包含概述/定义、机制原理、代表性案例、易错点/边界条件、+ 实际应用、历史/对比背景等不同角度。+ - 与用户意图保持同一语言。+ - 每个 query 长度 3-12 个词,足够具体能召回真实片段,但不要互相重复。+ - 避免冗余,注重概念覆盖。++ 仅输出 JSON:+ {+ "queries": ["...", "..."]+ }++queries_user: |+ 用户意图:+ {user_intent}++ 已批准的 proposal:+ {proposal_block}++ 可用知识库:+ {kb_list}++ 其他上下文(笔记 / 历史对话亮点):+ {extra_context}++ 请直接输出 JSON。++summary_system: |+ 你正在为 DeepTutor BookEngine 总结一次源材料探索结果(知识库、笔记+ 记录、历史对话、错题本等)。++ 阅读这些 chunk 并输出:+ - ``summary``: 4-8 句话,归纳反复出现的主题、证据强弱以及 spine 需要+ 弥补的薄弱点。+ - ``candidate_concepts``: 8-20 个 ≤ 5 个词的概念标签,作为概念图的候选+ 节点。偏好原子化、可复用的术语。+ - ``notes``: 可选的 ≤ 5 条注意事项 / 矛盾 / 待跟进问题。++ 使用与用户意图一致的语言。++ 仅输出 JSON:+ {+ "summary": "...",+ "candidate_concepts": ["...", "..."],+ "notes": ["..."]+ }++summary_user: |+ 用户意图:+ {user_intent}++ Proposal 标题:{proposal_title}+ Proposal 范围:{proposal_scope}++ 各来源覆盖情况:+ {coverage_block}++ 代表性 chunk(已截断):+ {chunks_block}++ 请直接输出 JSON。diff --git a/deeptutor/book/prompts/zh/spine_agent.yaml b/deeptutor/book/prompts/zh/spine_agent.yamlnew file mode 100644index 000000000..8ee39b1ac--- /dev/null+++ b/deeptutor/book/prompts/zh/spine_agent.yaml@@ -0,0 +1,41 @@+system: |+ 你是 DeepTutor BookEngine 的 Spine 阶段。基于已确认的 BookProposal 与+ 来自学习者知识库的可选素材,设计本书的章节树("骨架")。++ 输出一个 JSON 对象(无散文、无 markdown 代码块):+ {+ "chapters": [+ {+ "title": "简洁的章节标题",+ "learning_objectives": ["目标 1", "目标 2"],+ "content_type": "theory | derivation | history | practice | concept",+ "source_anchors": [+ {"kind": "kb|notebook|chat|manual", "ref": "<id 或简短引用>", "snippet": "≤200 字符片段"}+ ],+ "prerequisites": ["<前置章节的标题>"],+ "summary": "1-2 句章节摘要"+ }+ ]+ }++ 原则:+ - 章节数量应与 proposal 的 estimated_chapters 接近(±1)+ - 按由浅入深排序;prerequisites 仅引用前面已出现的章节标题+ - 为每章选择最合适的 content_type:+ * theory – 概念讲解 + 视觉化+ * derivation – 公式推导,适合配合动画+ * history – 时间线 / 案例研究+ * practice – 练习驱动+ * concept – 定义 / 术语密集+ - 当有素材时,source_anchors 必须引用所给素材+ - 每章都应是自包含、有意义的学习单元+ - 使用与 proposal 标题一致的语言++user_template: |+ 已确认的 BookProposal:+ {proposal_block}++ 来自学习者知识库 / 笔记本的可用素材:+ {source_material}++ 请输出 spine,仅返回 JSON 对象。diff --git a/deeptutor/book/prompts/zh/spine_synthesizer.yaml b/deeptutor/book/prompts/zh/spine_synthesizer.yamlnew file mode 100644index 000000000..caac2844a--- /dev/null+++ b/deeptutor/book/prompts/zh/spine_synthesizer.yaml@@ -0,0 +1,118 @@+draft_system: |+ 你是 DeepTutor SpineSynthesizer 的 **draft** 阶段。基于已批准的+ BookProposal、ExplorationReport(摘要 + 关键证据 + 候选概念),在一个+ JSON 对象里同时设计:++ 1. ``concept_graph`` —— 一张以证据为依托的概念有向图。可以以+ ``candidate_concepts`` 为种子,自由增加/删除/合并。边的方向:+ 从前置概念指向依赖它的概念(``depends_on``),或在合适时使用+ ``extends`` / ``related``。+ 2. ``chapters`` —— 覆盖整张概念图的章节 spine。每章必须用 ``covers``+ 字段绑定一个或多个节点;章节顺序应基本符合概念依赖的拓扑顺序。++ 仅输出此 JSON:+ {+ "concept_graph": {+ "nodes": [+ {"id": "<slug>", "label": "<可读标签>", "description": "≤ 1 句",+ "weight": <0.1-1.0>}+ ],+ "edges": [+ {"src": "<节点 id>", "dst": "<节点 id>",+ "relation": "depends_on | extends | related",+ "rationale": "≤ 1 句"}+ ]+ },+ "chapters": [+ {+ "title": "简洁章节标题",+ "learning_objectives": ["bullet 1", "bullet 2"],+ "content_type": "theory | derivation | history | practice | concept",+ "covers": ["<concept node id>", ...],+ "source_anchors": [+ {"kind": "kb|notebook|chat|manual", "ref": "<id>", "snippet": "≤200 字符"}+ ],+ "prerequisites": ["<更早一章的标题>"],+ "summary": "1-2 句章节摘要"+ }+ ]+ }++ 原则:+ - 章节数应贴近 ``estimated_chapters``(±1)。+ - 每章必须 cover 至少一个节点;每个节点必须被至少一章覆盖。+ - 概念节点 id 使用 ``snake_case``,简短且可复用。+ - 概念图中不得出现循环依赖。+ - 与 proposal 标题保持同一语言。++draft_user: |+ 已批准的 BookProposal:+ {proposal_block}++ 探索摘要:+ {exploration_summary}++ 候选概念(seed):+ {candidate_concepts}++ 证据片段:+ {chunks_block}++ 请直接输出 JSON。++critique_system: |+ 你是 DeepTutor SpineSynthesizer 的 **critique** 阶段。基于 draft 的+ spine + concept_graph,找出真实存在的问题,措辞简洁、具体。++ 仅输出 JSON:+ {+ "issues": [+ {"category": "coverage | ordering | granularity | redundancy | missing_anchor | cycle | other",+ "detail": "≤ 2 句问题说明",+ "fix_hint": "≤ 1 句具体修复建议"}+ ],+ "verdict": "ok | revise"+ }++ 关注:+ - 没有任何章节覆盖的概念节点(或反之)。+ - 章节 prerequisite 与 concept_graph 不一致。+ - depends_on 边出现循环或自相矛盾。+ - 章节相对 proposal 范围过宽 / 过窄。+ - 章节冗余、概念节点近似重复。+ - 探索证据明显存在但章节 source_anchors 为空。++ 若不存在实质问题,输出 ``"verdict": "ok"`` 并保持 issues 为空数组。++critique_user: |+ 已批准的 BookProposal:+ {proposal_block}++ 当前 draft(spine + concept_graph):+ {draft_block}++ 探索摘要:+ {exploration_summary}++ 请输出 JSON。++revise_system: |+ 你是 DeepTutor SpineSynthesizer 的 **revise** 阶段。基于上一轮 draft+ 与 critique,输出与 draft 阶段同样 schema 的 JSON(``concept_graph`` ++ ``chapters``)。请忠实应用 fix_hint。当 critique 含糊或冲突时,优先+ 保证概念图覆盖度与拓扑一致性。除非覆盖明显要求,不要引入未被提示+ 的新章节。++ 仅输出 JSON。++revise_user: |+ 已批准的 BookProposal:+ {proposal_block}++ Critique:+ {critique_block}++ 上一轮 draft:+ {draft_block}++ 请输出修订后的 JSON。diff --git a/deeptutor/book/prompts/zh/text.yaml b/deeptutor/book/prompts/zh/text.yamlnew file mode 100644index 000000000..97d4a793b--- /dev/null+++ b/deeptutor/book/prompts/zh/text.yaml@@ -0,0 +1,26 @@+system: |+ 你是 DeepTutor BookEngine 的 Text Block 写作者。请输出一段紧凑、结构清晰的+ Markdown 讲解文本,配合给定的章节信息。可以使用 ###/列表/`代码`/数学公式+ ($...$)。不要重复完整的章节标题,不要输出 JSON 或代码块标记。++user_template: |+ 章节:{chapter_title}+ 章节摘要:{chapter_summary}+ 学习目标:+ {objectives_block}+ 本段定位:{role}+ {previous_section}{rag_section}+ 请生成 200-400 字的讲解 Markdown。++bridge_system: |+ 你是 DeepTutor BookEngine 的过渡句写作者。请基于上一段内容与下一段提示,+ 写 1-2 句简短自然的过渡 Markdown,用于把读者从前一块内容平滑引导到下一块。+ 语气朴素自然,就像教科书里章节内的衔接段落。不要写小标题,不要使用列表/+ 代码块/JSON,不要重复整章标题。++bridge_user_template: |+ 章节:{chapter_title}+ 上一块摘要:{previous_block_summary}+ 下一块提示:{next_block_hint}++ 请用 1-2 句话写一个简短自然的过渡 Markdown。diff --git a/deeptutor/book/prompts/zh/timeline.yaml b/deeptutor/book/prompts/zh/timeline.yamlnew file mode 100644index 000000000..311d160ba--- /dev/null+++ b/deeptutor/book/prompts/zh/timeline.yaml@@ -0,0 +1,10 @@+system: |+ 你是 DeepTutor BookEngine 的 Timeline 生成器。请输出与章节相关的时间线,+ 严格 JSON:{"events": [{"date": "...", "title": "...", "description": "..."}]}。+ 包含 4-8 条关键事件,按时间升序排列。++user_template: |+ 章节:{chapter_title}+ 摘要:{chapter_summary}++ 请直接输出 JSON。diff --git a/deeptutor/book/storage.py b/deeptutor/book/storage.pynew file mode 100644index 000000000..9a8481ea7--- /dev/null+++ b/deeptutor/book/storage.py@@ -0,0 +1,277 @@+"""+Book Storage+============++Per-book directory + per-page file persistence with atomic writes.++Layout (relative to ``data/user/workspace/book/``)::++ book_{book_id}/+ ├── manifest.json # Book metadata+ ├── spine.json # Spine+ ├── progress.json # Progress+ ├── inputs.json # Captured BookInputs+ ├── log.md # Append-only operation log+ ├── pages/+ │ └── {page_id}.json+ └── assets/+ └── ...+"""++from __future__ import annotations++import asyncio+import json+import os+import shutil+from datetime import datetime+from pathlib import Path+from typing import Any++from deeptutor.logging import get_logger+from deeptutor.services.path_service import get_path_service++from .models import Book, BookInputs, ExplorationReport, Page, Progress, Spine++logger = get_logger("book.storage")+++# ─────────────────────────────────────────────────────────────────────────────+# Atomic JSON helpers+# ─────────────────────────────────────────────────────────────────────────────+++def _atomic_write_text(path: Path, text: str) -> None:+ """Write *text* to *path* atomically (write-temp + rename)."""+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(path.suffix + ".tmp")+ with open(tmp, "w", encoding="utf-8") as f:+ f.write(text)+ f.flush()+ try:+ os.fsync(f.fileno())+ except OSError:+ pass+ os.replace(tmp, path)+++def _atomic_write_json(path: Path, payload: Any) -> None:+ text = json.dumps(payload, ensure_ascii=False, indent=2, default=str)+ _atomic_write_text(path, text)+++def _read_json(path: Path) -> Any | None:+ if not path.exists():+ return None+ try:+ with open(path, encoding="utf-8") as f:+ return json.load(f)+ except (OSError, json.JSONDecodeError) as exc:+ logger.warning(f"Failed to read JSON {path}: {exc}")+ return None+++# ─────────────────────────────────────────────────────────────────────────────+# Public API+# ─────────────────────────────────────────────────────────────────────────────+++class BookStorage:+ """Async-friendly wrapper around the on-disk book layout."""++ def __init__(self) -> None:+ self.path_service = get_path_service()+ self._lock = asyncio.Lock()++ # ── Path helpers ─────────────────────────────────────────────────────++ def book_root(self, book_id: str) -> Path:+ return self.path_service.get_book_root(book_id)++ def ensure_book_root(self, book_id: str) -> Path:+ return self.path_service.ensure_book_root(book_id)++ def list_book_ids(self) -> list[str]:+ root = self.path_service.get_book_dir()+ if not root.exists():+ return []+ ids = []+ for child in root.iterdir():+ if child.is_dir() and child.name.startswith("book_"):+ ids.append(child.name[len("book_"):])+ return ids++ def book_exists(self, book_id: str) -> bool:+ return self.book_root(book_id).exists()++ # ── Manifest ─────────────────────────────────────────────────────────++ def save_book(self, book: Book) -> None:+ self.ensure_book_root(book.id)+ _atomic_write_json(+ self.path_service.get_book_manifest_file(book.id), book.model_dump(mode="json")+ )++ def load_book(self, book_id: str) -> Book | None:+ data = _read_json(self.path_service.get_book_manifest_file(book_id))+ if data is None:+ return None+ try:+ return Book.model_validate(data)+ except Exception as exc:+ logger.warning(f"Failed to validate Book {book_id}: {exc}")+ return None++ # ── Inputs (immutable snapshot) ─────────────────────────────────────++ def save_inputs(self, book_id: str, inputs: BookInputs) -> None:+ self.ensure_book_root(book_id)+ _atomic_write_json(+ self.path_service.get_book_inputs_file(book_id), inputs.model_dump(mode="json")+ )++ def load_inputs(self, book_id: str) -> BookInputs | None:+ data = _read_json(self.path_service.get_book_inputs_file(book_id))+ if data is None:+ return None+ try:+ return BookInputs.model_validate(data)+ except Exception as exc:+ logger.warning(f"Failed to validate BookInputs {book_id}: {exc}")+ return None++ # ── Spine ────────────────────────────────────────────────────────────++ def save_spine(self, spine: Spine) -> None:+ self.ensure_book_root(spine.book_id)+ _atomic_write_json(+ self.path_service.get_book_spine_file(spine.book_id),+ spine.model_dump(mode="json"),+ )++ def load_spine(self, book_id: str) -> Spine | None:+ data = _read_json(self.path_service.get_book_spine_file(book_id))+ if data is None:+ return None+ try:+ return Spine.model_validate(data)+ except Exception as exc:+ logger.warning(f"Failed to validate Spine {book_id}: {exc}")+ return None++ # ── Exploration report (Stage 2 — Source sweep) ────────────────────++ def _exploration_path(self, book_id: str) -> Path:+ return self.book_root(book_id) / "exploration.json"++ def save_exploration(self, book_id: str, report: ExplorationReport) -> None:+ self.ensure_book_root(book_id)+ report.book_id = report.book_id or book_id+ _atomic_write_json(+ self._exploration_path(book_id), report.model_dump(mode="json")+ )++ def load_exploration(self, book_id: str) -> ExplorationReport | None:+ data = _read_json(self._exploration_path(book_id))+ if data is None:+ return None+ try:+ return ExplorationReport.model_validate(data)+ except Exception as exc:+ logger.warning(f"Failed to validate ExplorationReport {book_id}: {exc}")+ return None++ # ── Progress ─────────────────────────────────────────────────────────++ def save_progress(self, progress: Progress) -> None:+ self.ensure_book_root(progress.book_id)+ _atomic_write_json(+ self.path_service.get_book_progress_file(progress.book_id),+ progress.model_dump(mode="json"),+ )++ def load_progress(self, book_id: str) -> Progress | None:+ data = _read_json(self.path_service.get_book_progress_file(book_id))+ if data is None:+ return None+ try:+ return Progress.model_validate(data)+ except Exception as exc:+ logger.warning(f"Failed to validate Progress {book_id}: {exc}")+ return None++ # ── Pages ────────────────────────────────────────────────────────────++ def save_page(self, page: Page) -> None:+ self.ensure_book_root(page.book_id)+ _atomic_write_json(+ self.path_service.get_book_page_file(page.book_id, page.id),+ page.model_dump(mode="json"),+ )++ def load_page(self, book_id: str, page_id: str) -> Page | None:+ data = _read_json(self.path_service.get_book_page_file(book_id, page_id))+ if data is None:+ return None+ try:+ return Page.model_validate(data)+ except Exception as exc:+ logger.warning(f"Failed to validate Page {page_id}: {exc}")+ return None++ def list_pages(self, book_id: str) -> list[Page]:+ pages_dir = self.path_service.get_book_pages_dir(book_id)+ if not pages_dir.exists():+ return []+ result: list[Page] = []+ for child in pages_dir.iterdir():+ if child.suffix != ".json":+ continue+ data = _read_json(child)+ if data is None:+ continue+ try:+ result.append(Page.model_validate(data))+ except Exception as exc:+ logger.warning(f"Skipping invalid page file {child}: {exc}")+ result.sort(key=lambda p: (p.order, p.created_at))+ return result++ def delete_page(self, book_id: str, page_id: str) -> bool:+ path = self.path_service.get_book_page_file(book_id, page_id)+ if path.exists():+ path.unlink()+ return True+ return False++ # ── Log (append-only) ────────────────────────────────────────────────++ def append_log(self, book_id: str, message: str, *, op: str = "info") -> None:+ path = self.path_service.get_book_log_file(book_id)+ path.parent.mkdir(parents=True, exist_ok=True)+ ts = datetime.utcnow().isoformat(timespec="seconds")+ line = f"- `{ts}Z` **{op}** — {message.strip()}\n"+ with open(path, "a", encoding="utf-8") as f:+ f.write(line)++ # ── Delete ───────────────────────────────────────────────────────────++ def delete_book(self, book_id: str) -> bool:+ root = self.book_root(book_id)+ if not root.exists():+ return False+ shutil.rmtree(root, ignore_errors=True)+ return not root.exists()+++_storage: BookStorage | None = None+++def get_book_storage() -> BookStorage:+ global _storage+ if _storage is None:+ _storage = BookStorage()+ return _storage+++__all__ = ["BookStorage", "get_book_storage"]diff --git a/deeptutor/book/streaming.py b/deeptutor/book/streaming.pynew file mode 100644index 000000000..8cde3ddea--- /dev/null+++ b/deeptutor/book/streaming.py@@ -0,0 +1,134 @@+"""+Book Engine streaming helpers+=============================++Thin wrapper around ``StreamBus`` that fixes ``source="book_engine"`` and+defines book-specific event metadata schemas.+"""++from __future__ import annotations++from contextlib import asynccontextmanager+from typing import Any++from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.stream_bus import StreamBus++SOURCE = "book_engine"+++# Stage names used across the pipeline+STAGE_IDEATION = "ideation"+STAGE_EXPLORATION = "exploration" # SourceExplorer (Stage 2 prep)+STAGE_SYNTHESIS = "synthesis" # SpineSynthesizer draft / revise+STAGE_CRITIQUE = "critique" # SpineSynthesizer critique round+STAGE_OVERVIEW = "overview" # Engine-injected Overview chapter+STAGE_SPINE = "spine" # Outer wrapper for the spine stage+STAGE_PAGE_PLAN = "page_plan"+STAGE_COMPILATION = "compilation"+STAGE_BLOCK = "block"+STAGE_INTERACTION = "interaction"+++class BookStream:+ """High-level helpers around a ``StreamBus`` for the BookEngine."""++ def __init__(self, bus: StreamBus) -> None:+ self.bus = bus++ @asynccontextmanager+ async def stage(self, name: str, metadata: dict[str, Any] | None = None):+ async with self.bus.stage(name, source=SOURCE, metadata=metadata or {}):+ yield++ async def content(+ self,+ text: str,+ stage: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ await self.bus.content(text, source=SOURCE, stage=stage, metadata=metadata)++ async def thinking(+ self,+ text: str,+ stage: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ await self.bus.thinking(text, source=SOURCE, stage=stage, metadata=metadata)++ async def progress(+ self,+ message: str,+ current: int = 0,+ total: int = 0,+ stage: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ await self.bus.progress(+ message,+ current=current,+ total=total,+ source=SOURCE,+ stage=stage,+ metadata=metadata,+ )++ async def result(self, data: dict[str, Any], metadata: dict[str, Any] | None = None) -> None:+ await self.bus.result(data, source=SOURCE, metadata=metadata)++ async def error(+ self,+ message: str,+ stage: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ await self.bus.error(message, source=SOURCE, stage=stage, metadata=metadata)++ async def emit(self, event_type: StreamEventType, **kwargs: Any) -> None:+ kwargs.setdefault("source", SOURCE)+ await self.bus.emit(StreamEvent(type=event_type, **kwargs))++ # ── Book-specific events ────────────────────────────────────────────++ async def book_event(+ self,+ kind: str,+ data: dict[str, Any],+ stage: str = "",+ ) -> None:+ """Emit a custom 'book' progress event using the PROGRESS channel.++ Frontend distinguishes by ``metadata.kind``::++ kind ∈ {+ "proposal_ready", "spine_ready", "page_planned",+ "block_ready", "block_error", "page_ready",+ "compilation_complete", ...+ }+ """+ await self.bus.emit(+ StreamEvent(+ type=StreamEventType.PROGRESS,+ source=SOURCE,+ stage=stage,+ content=kind,+ metadata={"kind": kind, **data},+ )+ )+++__all__ = [+ "BookStream",+ "SOURCE",+ "STAGE_IDEATION",+ "STAGE_EXPLORATION",+ "STAGE_SYNTHESIS",+ "STAGE_CRITIQUE",+ "STAGE_OVERVIEW",+ "STAGE_SPINE",+ "STAGE_PAGE_PLAN",+ "STAGE_COMPILATION",+ "STAGE_BLOCK",+ "STAGE_INTERACTION",+]diff --git a/deeptutor/capabilities/request_contracts.py b/deeptutor/capabilities/request_contracts.pyindex ef615ed3f..fbb8774e5 100644--- a/deeptutor/capabilities/request_contracts.py+++ b/deeptutor/capabilities/request_contracts.py@@ -52,7 +52,7 @@ class DeepQuestionRequestConfig(BaseModel):class VisualizeRequestConfig(BaseModel):model_config = ConfigDict(extra="forbid")- render_mode: Literal["auto", "svg", "chartjs", "mermaid"] = "auto"+ render_mode: Literal["auto", "svg", "chartjs", "mermaid", "html"] = "auto"def _clean_public_config(raw_config: dict[str, Any] | None) -> dict[str, Any]:diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.pyindex f962ae698..9c7dc7c6a 100644--- a/deeptutor/capabilities/visualize.py+++ b/deeptutor/capabilities/visualize.py@@ -20,7 +20,7 @@ from deeptutor.core.trace import merge_trace_metadataclass VisualizeCapability(BaseCapability):manifest = CapabilityManifest(name="visualize",- description="Generate SVG, Chart.js, or Mermaid visualizations.",+ description="Generate SVG, Chart.js, Mermaid, or interactive HTML visualizations.",stages=["analyzing", "generating", "reviewing"],tools_used=[],cli_aliases=["visualize", "viz"],@@ -29,6 +29,10 @@ class VisualizeCapability(BaseCapability):async def run(self, context: UnifiedContext, stream: StreamBus) -> None:from deeptutor.agents.visualize.pipeline import VisualizePipeline+ from deeptutor.agents.visualize.utils import (+ build_fallback_html,+ is_valid_html_document,+ )from deeptutor.capabilities._answer_now import extract_answer_now_contextfrom deeptutor.services.llm.config import get_llm_config@@ -91,35 +95,73 @@ class VisualizeCapability(BaseCapability):# Stage 3: Review & optimiseasync with stream.stage("reviewing", source=self.name):- await stream.thinking(- "Reviewing and optimizing code...",- source=self.name,- stage="reviewing",- )- review = await pipeline.run_review(- user_input=context.user_message,- analysis=analysis,- code=code,- )- final_code = review.optimized_code- if review.changed:- await stream.progress(- message=f"Code optimized: {review.review_notes}",- source=self.name,- stage="reviewing",- )+ if analysis.render_type == "html":+ # Skip the LLM review pass for html — it would cost another+ # 30-60s on a 10k-token document with negligible quality gain.+ # Instead, do a local sanity check and fall back to a minimal+ # template if the model returned something unrenderable.+ from deeptutor.agents.visualize.models import ReviewResult++ if is_valid_html_document(code):+ final_code = code+ review = ReviewResult(+ optimized_code=final_code,+ changed=False,+ review_notes="Skipped LLM review for html render_type.",+ )+ await stream.progress(+ message="HTML page ready (review skipped).",+ source=self.name,+ stage="reviewing",+ )+ else:+ final_code = build_fallback_html(+ title=analysis.description or "Visualization",+ summary=analysis.data_description,+ note="The model did not return a renderable HTML document.",+ )+ review = ReviewResult(+ optimized_code=final_code,+ changed=True,+ review_notes="Used fallback HTML template.",+ )+ await stream.progress(+ message="HTML did not validate; using fallback template.",+ source=self.name,+ stage="reviewing",+ )else:- await stream.progress(- message="Code looks good — no changes needed.",+ await stream.thinking(+ "Reviewing and optimizing code...",source=self.name,stage="reviewing",)+ review = await pipeline.run_review(+ user_input=context.user_message,+ analysis=analysis,+ code=code,+ )+ final_code = review.optimized_code+ if review.changed:+ await stream.progress(+ message=f"Code optimized: {review.review_notes}",+ source=self.name,+ stage="reviewing",+ )+ else:+ await stream.progress(+ message="Code looks good — no changes needed.",+ source=self.name,+ stage="reviewing",+ )# Emit final content as a fenced code block for the chat areaif analysis.render_type == "svg":lang_tag = "svg"elif analysis.render_type == "mermaid":lang_tag = "mermaid"+ elif analysis.render_type == "html":+ lang_tag = "html"else:lang_tag = "javascript"content_md = f"```{lang_tag}\n{final_code}\n```"@@ -177,9 +219,13 @@ class VisualizeCapability(BaseCapability):system_prompt = ("你是 DeepTutor 的可视化代码生成器。用户已经在等待,""请直接输出最终可渲染的代码。"- "严格输出 JSON:{\"render_type\": \"svg|chartjs|mermaid\", "+ "严格输出 JSON:{\"render_type\": \"svg|chartjs|mermaid|html\", ""\"code\": \"...\"}。"- "code 字段是可直接渲染的源代码(SVG 标签 / Chart.js JS 代码 / Mermaid 文本)。"+ "code 字段是可直接渲染的源代码:"+ "SVG 标签 / Chart.js JS 配置 / Mermaid 文本 / "+ "完整的单文件 HTML(从 <!DOCTYPE> 到 </html>,"+ "CSS 内联在 <style>,JS 内联在 <script>,不依赖外部资源,"+ "页面会渲染在 iframe 中,KaTeX 由宿主注入)。")user_prompt = (f"用户请求:{original}\n\n"@@ -193,9 +239,12 @@ class VisualizeCapability(BaseCapability):"You are DeepTutor's visualization code generator. The user ""is waiting, so emit the final renderable code in one shot. ""Output strictly the JSON {\"render_type\": "- "\"svg|chartjs|mermaid\", \"code\": \"...\"}, where ``code`` "- "is the renderable source (SVG markup, Chart.js JS, or "- "Mermaid DSL)."+ "\"svg|chartjs|mermaid|html\", \"code\": \"...\"}, where ``code`` "+ "is the renderable source: SVG markup / Chart.js JS config / "+ "Mermaid DSL / a complete single-file HTML document "+ "(from <!DOCTYPE> to </html>, CSS inlined in <style>, JS in "+ "<script>, no external resources; the page renders inside an "+ "iframe and KaTeX is injected by the host).")user_prompt = (f"User request: {original}\n\n"@@ -214,6 +263,10 @@ class VisualizeCapability(BaseCapability):stages_skipped=["analyzing", "reviewing"],)+ # html pages are larger; bump the answer-now budget for that mode.+ is_html_mode = render_mode == "html"+ max_tokens = 16000 if is_html_mode else 2400+chunks: list[str] = []async with stream.stage("generating", source=self.name, metadata=trace_meta):async for chunk in stream_synthesis(@@ -223,7 +276,7 @@ class VisualizeCapability(BaseCapability):trace_meta=trace_meta,system_prompt=system_prompt,user_prompt=user_prompt,- max_tokens=2400,+ max_tokens=max_tokens,push_content=False,response_format={"type": "json_object"},):@@ -238,18 +291,27 @@ class VisualizeCapability(BaseCapability):try:parsed = json.loads(raw)except json.JSONDecodeError:- parsed = {"render_type": "svg", "code": raw}+ parsed = {"render_type": "html" if is_html_mode else "svg", "code": raw}if not isinstance(parsed, dict):- parsed = {"render_type": "svg", "code": str(parsed)}+ parsed = {+ "render_type": "html" if is_html_mode else "svg",+ "code": str(parsed),+ }- render_type = str(parsed.get("render_type") or "svg").strip().lower()- if render_type not in {"svg", "chartjs", "mermaid"}:- render_type = "svg"+ default_type = "html" if is_html_mode else "svg"+ render_type = str(parsed.get("render_type") or default_type).strip().lower()+ if render_type not in {"svg", "chartjs", "mermaid", "html"}:+ render_type = default_typefinal_code = str(parsed.get("code") or "").strip()- lang_tag = "svg" if render_type == "svg" else (- "mermaid" if render_type == "mermaid" else "javascript"- )+ if render_type == "html":+ lang_tag = "html"+ elif render_type == "svg":+ lang_tag = "svg"+ elif render_type == "mermaid":+ lang_tag = "mermaid"+ else:+ lang_tag = "javascript"content_md = f"```{lang_tag}\n{final_code}\n```"body = (notice + "\n\n" + content_md).strip() if notice else content_mdawait stream.content(body, source=self.name, stage="generating")diff --git a/deeptutor/agents/co_writer/__init__.py b/deeptutor/co_writer/__init__.pysimilarity index 100%rename from deeptutor/agents/co_writer/__init__.pyrename to deeptutor/co_writer/__init__.pydiff --git a/deeptutor/agents/co_writer/edit_agent.py b/deeptutor/co_writer/edit_agent.pysimilarity index 100%rename from deeptutor/agents/co_writer/edit_agent.pyrename to deeptutor/co_writer/edit_agent.pydiff --git a/deeptutor/agents/co_writer/prompts/en/edit_agent.yaml b/deeptutor/co_writer/prompts/en/edit_agent.yamlsimilarity index 100%rename from deeptutor/agents/co_writer/prompts/en/edit_agent.yamlrename to deeptutor/co_writer/prompts/en/edit_agent.yamldiff --git a/deeptutor/agents/co_writer/prompts/en/narrator_agent.yaml b/deeptutor/co_writer/prompts/en/narrator_agent.yamlsimilarity index 100%rename from deeptutor/agents/co_writer/prompts/en/narrator_agent.yamlrename to deeptutor/co_writer/prompts/en/narrator_agent.yamldiff --git a/deeptutor/agents/co_writer/prompts/zh/edit_agent.yaml b/deeptutor/co_writer/prompts/zh/edit_agent.yamlsimilarity index 100%rename from deeptutor/agents/co_writer/prompts/zh/edit_agent.yamlrename to deeptutor/co_writer/prompts/zh/edit_agent.yamldiff --git a/deeptutor/agents/co_writer/prompts/zh/narrator_agent.yaml b/deeptutor/co_writer/prompts/zh/narrator_agent.yamlsimilarity index 100%rename from deeptutor/agents/co_writer/prompts/zh/narrator_agent.yamlrename to deeptutor/co_writer/prompts/zh/narrator_agent.yamldiff --git a/deeptutor/logging/logger.py b/deeptutor/logging/logger.pyindex 193c23dad..a9e7a28f0 100644--- a/deeptutor/logging/logger.py+++ b/deeptutor/logging/logger.py@@ -8,7 +8,6 @@ Format: [LEVEL] [Module] MessageExample outputs:[INFO] [Solver] Ready in 2.3s[INFO] [Research] Starting deep research...- [INFO] [Guide] Compiling knowledge points[INFO] [Knowledge] Indexed 150 documents[ERROR] [EmbeddingClient] Embedding request failed"""@@ -160,7 +159,7 @@ class Logger:Initialize logger.Args:- name: Module name (e.g., "Solver", "Research", "Guide")+ name: Module name (e.g., "Solver", "Research", "Book")level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)console_output: Whether to output to consolefile_output: Whether to output to filediff --git a/deeptutor/services/__init__.py b/deeptutor/services/__init__.pyindex 0d903e45f..4529ea427 100644--- a/deeptutor/services/__init__.py+++ b/deeptutor/services/__init__.py@@ -34,7 +34,7 @@ Usage:# Promptpm = get_prompt_manager()- prompts = pm.load_prompts("guide", "tutor_agent")+ prompts = pm.load_prompts("solve", "solve_agent")# Searchresult = web_search("What is AI?")diff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.pyindex 3e458e81e..46cba5723 100644--- a/deeptutor/services/config/loader.py+++ b/deeptutor/services/config/loader.py@@ -73,7 +73,6 @@ def _inject_runtime_paths(config: dict[str, Any]) -> dict[str, Any]:"knowledge_bases_dir": str(path_service.project_root / "data" / "knowledge_bases"),"user_log_dir": str(path_service.get_logs_dir()),"performance_log_dir": str(path_service.get_logs_dir() / "performance"),- "guide_output_dir": str(path_service.get_guide_dir()),"question_output_dir": str(path_service.get_chat_feature_dir("deep_question")),"research_output_dir": str(path_service.get_research_dir()),"research_reports_dir": str(path_service.get_research_reports_dir()),@@ -209,7 +208,6 @@ def get_agent_params(module_name: str) -> dict:Args:module_name: Module name, one of:- - "guide": Guide module agents- "solve": Solve module agents- "research": Research module agents- "question": Question module agents@@ -224,8 +222,8 @@ def get_agent_params(module_name: str) -> dict:- max_tokens: int, default 4096Example:- >>> params = get_agent_params("guide")- >>> params["temperature"] # 0.5+ >>> params = get_agent_params("solve")+ >>> params["temperature"] # 0.3>>> params["max_tokens"] # 8192"""defaults = {@@ -236,7 +234,6 @@ def get_agent_params(module_name: str) -> dict:"solve": ("capabilities", "solve"),"research": ("capabilities", "research"),"question": ("capabilities", "question"),- "guide": ("capabilities", "guide"),"co_writer": ("capabilities", "co_writer"),"brainstorm": ("tools", "brainstorm"),"vision_solver": ("plugins", "vision_solver"),diff --git a/deeptutor/services/llm/__init__.py b/deeptutor/services/llm/__init__.pyindex ef4a347b6..84917338e 100644--- a/deeptutor/services/llm/__init__.py+++ b/deeptutor/services/llm/__init__.py@@ -5,7 +5,7 @@ LLM ServiceUnified LLM service for all DeepTutor modules.Architecture:- Agents (ChatAgent, GuideAgent, etc.)+ Agents (ChatAgent, SolveAgent, etc.)↓BaseAgent.call_llm() / stream_llm()↓diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 677620fd6..f4ad0eba0 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -13,7 +13,7 @@ Compatibility:directly, this wrapper can be removed.Architecture:- Agents (ChatAgent, GuideAgent, etc.)+ Agents (ChatAgent, SolveAgent, etc.)↓BaseAgent.call_llm() / stream_llm()↓diff --git a/deeptutor/services/notebook/service.py b/deeptutor/services/notebook/service.pyindex c35a04b5a..9bd9eb330 100644--- a/deeptutor/services/notebook/service.py+++ b/deeptutor/services/notebook/service.py@@ -27,7 +27,6 @@ class RecordType(str, Enum):RESEARCH = "research"CO_WRITER = "co_writer"CHAT = "chat"- GUIDED_LEARNING = "guided_learning"class NotebookRecord(BaseModel):@@ -380,7 +379,6 @@ class NotebookManager:"research": 0,"co_writer": 0,"chat": 0,- "guided_learning": 0,}for nb_info in notebooks:diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.pyindex c3f7cd2b4..9e18fad45 100644--- a/deeptutor/services/path_service.py+++ b/deeptutor/services/path_service.py@@ -12,7 +12,7 @@ data/user/├── memory/├── notebook/├── co-writer/- ├── guide/+ ├── book/└── chat/├── chat/├── deep_solve/@@ -31,7 +31,6 @@ AgentModule = Literal["question","research","co-writer",- "guide","run_code_workspace","logs","math_animator",@@ -50,8 +49,8 @@ WorkspaceFeature = Literal["memory","notebook","co-writer",- "guide","chat",+ "book",]@@ -67,7 +66,6 @@ class PathService:"research": ("chat", "deep_research"),"math_animator": ("chat", "math_animator"),"co-writer": ("co-writer", None),- "guide": ("guide", None),"run_code_workspace": ("chat", "_detached_code_execution"),}_PRIVATE_SUFFIXES = {".json", ".sqlite", ".db", ".md", ".yaml", ".yml", ".py", ".log"}@@ -185,7 +183,7 @@ class PathService:def _resolve_feature_root(self, feature: str) -> Path:if feature in {"chat", "deep_solve", "deep_question", "deep_research", "math_animator", "_detached_code_execution"}:return self.get_chat_feature_dir(feature) # type: ignore[arg-type]- if feature in {"memory", "notebook", "co-writer", "guide"}:+ if feature in {"memory", "notebook", "co-writer", "book"}:return self.get_workspace_feature_dir(feature) # type: ignore[arg-type]raise ValueError(f"Unknown workspace feature: {feature}")@@ -266,11 +264,46 @@ class PathService:def get_co_writer_audio_dir(self) -> Path:return self.get_co_writer_dir() / "audio"- def get_guide_dir(self) -> Path:- return self.get_workspace_feature_dir("guide")+ # ── Book Engine paths ────────────────────────────────────────────────- def get_guide_session_file(self, session_id: str) -> Path:- return self.get_guide_dir() / f"session_{session_id}.json"+ def get_book_dir(self) -> Path:+ """Root directory holding all books (one sub-directory per book)."""+ return self.get_workspace_feature_dir("book")++ def get_book_root(self, book_id: str) -> Path:+ """Per-book root directory."""+ return self.get_book_dir() / f"book_{book_id}"++ def get_book_manifest_file(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "manifest.json"++ def get_book_spine_file(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "spine.json"++ def get_book_progress_file(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "progress.json"++ def get_book_inputs_file(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "inputs.json"++ def get_book_log_file(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "log.md"++ def get_book_pages_dir(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "pages"++ def get_book_page_file(self, book_id: str, page_id: str) -> Path:+ return self.get_book_pages_dir(book_id) / f"{page_id}.json"++ def get_book_assets_dir(self, book_id: str) -> Path:+ return self.get_book_root(book_id) / "assets"++ def ensure_book_root(self, book_id: str) -> Path:+ root = self.get_book_root(book_id)+ root.mkdir(parents=True, exist_ok=True)+ (root / "pages").mkdir(parents=True, exist_ok=True)+ (root / "assets").mkdir(parents=True, exist_ok=True)+ return rootdef get_run_code_workspace_dir(self) -> Path:return self.get_chat_feature_dir("_detached_code_execution")@@ -314,7 +347,7 @@ class PathService:self.ensure_memory_dir()self.ensure_notebook_dir()self.get_logs_dir().mkdir(parents=True, exist_ok=True)- for feature in ("co-writer", "guide"):+ for feature in ("co-writer", "book"):self.get_workspace_feature_dir(feature).mkdir(parents=True, exist_ok=True)for feature in ("chat",diff --git a/deeptutor/services/prompt/__init__.py b/deeptutor/services/prompt/__init__.pyindex 1d5652771..ce5ea644f 100644--- a/deeptutor/services/prompt/__init__.py+++ b/deeptutor/services/prompt/__init__.py@@ -11,7 +11,7 @@ Usage:pm = get_prompt_manager()# Load prompts for an agent- prompts = pm.load_prompts("guide", "tutor_agent", language="en")+ prompts = pm.load_prompts("solve", "solve_agent", language="en")# Get specific promptsystem_prompt = pm.get_prompt(prompts, "system", "base")diff --git a/deeptutor/services/prompt/manager.py b/deeptutor/services/prompt/manager.pyindex c1820554a..ee1ef9e87 100644--- a/deeptutor/services/prompt/manager.py+++ b/deeptutor/services/prompt/manager.py@@ -25,10 +25,14 @@ class PromptManager:}# Supported modules- MODULES = ["research", "solve", "guide", "question", "co_writer", "math_animator"]+ MODULES = ["research", "solve", "question", "co_writer", "math_animator", "book"]# Modules that are not under deeptutor/agents/ directory- NON_AGENT_MODULES: dict[str, str] = {}+ # Map module_name → on-disk path component under deeptutor/+ NON_AGENT_MODULES: dict[str, str] = {+ "book": "book",+ "co_writer": "co_writer",+ }def __new__(cls) -> "PromptManager":if cls._instance is None:@@ -46,7 +50,7 @@ class PromptManager:Load prompts for an agent.Args:- module_name: Module name (research, solve, guide, question, co_writer)+ module_name: Module name (research, solve, question, co_writer)agent_name: Agent name (filename without .yaml)language: Language code ('zh' or 'en')subdirectory: Optional subdirectory (e.g., 'solve_loop' for solve module)diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex c928251ff..a63a425a4 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -36,6 +36,74 @@ def _clip_text(value: str, limit: int = 4000) -> str:return text[:limit].rstrip() + "\n...[truncated]"+def _format_question_bank_entry(entry: dict[str, Any]) -> str:+ """Render a single Question Bank entry as a structured Markdown block."""+ lines: list[str] = []+ title = str(entry.get("session_title", "") or "Untitled session")+ difficulty = str(entry.get("difficulty", "") or "").strip()+ qtype = str(entry.get("question_type", "") or "").strip()+ is_correct = bool(entry.get("is_correct"))++ badges: list[str] = []+ if qtype:+ badges.append(qtype)+ if difficulty:+ badges.append(difficulty)+ badges.append("correct" if is_correct else "incorrect")+ badge_text = " · ".join(badges)++ lines.append(f"### Question (from {title}) [{badge_text}]")+ lines.append(_clip_text(str(entry.get("question", "") or ""), limit=2000))++ options = entry.get("options") or {}+ if isinstance(options, dict) and options:+ lines.append("")+ lines.append("**Options:**")+ for key in sorted(options.keys()):+ lines.append(f"- {key}. {options[key]}")++ user_answer = str(entry.get("user_answer", "") or "").strip()+ correct_answer = str(entry.get("correct_answer", "") or "").strip()+ if user_answer:+ lines.append("")+ lines.append(f"**User's Answer:** {_clip_text(user_answer, limit=1000)}")+ if correct_answer:+ lines.append(f"**Reference Answer:** {_clip_text(correct_answer, limit=1500)}")++ explanation = str(entry.get("explanation", "") or "").strip()+ if explanation:+ lines.append("")+ lines.append("**Explanation:**")+ lines.append(_clip_text(explanation, limit=2000))++ return "\n".join(lines)+++async def _build_question_bank_context(+ store: SQLiteSessionStore,+ entry_ids: list[Any],+) -> str:+ """Fetch the requested Question Bank entries and render them as context."""+ seen: set[int] = set()+ blocks: list[str] = []+ for raw in entry_ids:+ try:+ entry_id = int(raw)+ except (TypeError, ValueError):+ continue+ if entry_id in seen:+ continue+ seen.add(entry_id)+ try:+ entry = await store.get_notebook_entry(entry_id)+ except Exception:+ entry = None+ if not entry:+ continue+ blocks.append(_format_question_bank_entry(entry))+ return "\n\n---\n\n".join(blocks)++def _extract_followup_question_context(config: dict[str, Any] | None,) -> dict[str, Any] | None:@@ -355,8 +423,12 @@ class TurnRuntimeManager:raw_user_content = str(payload.get("content", "") or "")notebook_references = payload.get("notebook_references", []) or []history_references = payload.get("history_references", []) or []+ question_notebook_references = (+ payload.get("question_notebook_references", []) or []+ )notebook_context = ""history_context = ""+ question_bank_context = ""for item in payload.get("attachments", []):record = {@@ -480,12 +552,21 @@ class TurnRuntimeManager:total += len(part)history_context = "\n\n".join(parts)+ if question_notebook_references:+ question_bank_context = await _build_question_bank_context(+ self.store, question_notebook_references+ )+effective_user_message = raw_user_contentcontext_parts: list[str] = []if notebook_context:context_parts.append(f"[Notebook Context]\n{notebook_context}")if history_context:context_parts.append(f"[History Context]\n{history_context}")+ if question_bank_context:+ context_parts.append(+ f"[Question Bank Context]\n{question_bank_context}"+ )if context_parts:context_parts.append(f"[User Question]\n{raw_user_content}")effective_user_message = "\n\n".join(context_parts)@@ -524,6 +605,8 @@ class TurnRuntimeManager:"question_followup_context": followup_question_context or {},"notebook_references": notebook_references,"history_references": history_references,+ "question_notebook_references": question_notebook_references,+ "question_bank_context": question_bank_context,"memory_context": memory_context,},)diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.pyindex 2713185b5..7f6869c12 100644--- a/deeptutor/services/setup/init.py+++ b/deeptutor/services/setup/init.py@@ -22,7 +22,7 @@ DEFAULT_INTERFACE_SETTINGS = {"sidebar_description": "✨ Data Intelligence Lab @ HKU","sidebar_nav_order": {"start": ["/", "/history", "/knowledge", "/notebook"],- "learnResearch": ["/question", "/solver", "/guide", "/research", "/co_writer"],+ "learnResearch": ["/question", "/solver", "/research", "/co_writer"],},}@@ -83,7 +83,6 @@ DEFAULT_AGENTS_SETTINGS = {"solve": {"temperature": 0.3, "max_tokens": 8192},"research": {"temperature": 0.5, "max_tokens": 12000},"question": {"temperature": 0.7, "max_tokens": 4096},- "guide": {"temperature": 0.5, "max_tokens": 16192},"co_writer": {"temperature": 0.7, "max_tokens": 4096},},"tools": {@@ -134,7 +133,7 @@ def init_user_directories(project_root: Path | None = None) -> None:├── notebook/├── memory/├── co-writer/- ├── guide/+ ├── book/└── chat/├── chat/├── deep_solve/diff --git a/deeptutor_cli/book.py b/deeptutor_cli/book.pynew file mode 100644index 000000000..27cb5283f--- /dev/null+++ b/deeptutor_cli/book.py@@ -0,0 +1,61 @@+"""``deeptutor book ...`` CLI commands for the new BookEngine.++Currently exposes maintenance commands. (Authoring/reading still goes through+the API + web frontend.)+"""++from __future__ import annotations++import json++import typer++from .common import console+++def register(app: typer.Typer) -> None:+ @app.command("list")+ def list_books() -> None:+ """List all books in the local workspace."""+ from deeptutor.book import get_book_engine++ engine = get_book_engine()+ books = engine.list_books()+ if not books:+ console.print("[yellow]No books yet.[/yellow]")+ return+ for book in books:+ stale = len(book.stale_page_ids or [])+ stale_label = f" [red]({stale} stale)[/red]" if stale else ""+ console.print(+ f"[bold]{book.title or '(untitled)'}[/bold] "+ f"[dim]{book.id}[/dim] "+ f"[cyan]{book.status.value}[/cyan]"+ f"{stale_label}"+ )++ @app.command("health")+ def health(+ book_id: str = typer.Argument(..., help="Book id."),+ ) -> None:+ """Inspect KB drift + log.md health for a book."""+ from deeptutor.book import get_book_engine++ engine = get_book_engine()+ drift = engine.kb_drift_report(book_id)+ log = engine.log_health(book_id)+ console.print_json(json.dumps({"kb_drift": drift, "log_health": log}))++ @app.command("refresh-fingerprints")+ def refresh_fingerprints(+ book_id: str = typer.Argument(..., help="Book id."),+ ) -> None:+ """Re-snapshot KB fingerprints; clears the stale-page list."""+ from deeptutor.book import get_book_engine++ engine = get_book_engine()+ result = engine.refresh_kb_fingerprints(book_id)+ if result is None:+ console.print(f"[red]Book {book_id} not found.[/red]")+ raise typer.Exit(code=1)+ console.print_json(json.dumps(result))diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.pyindex 392de636e..2c43374cb 100644--- a/deeptutor_cli/main.py+++ b/deeptutor_cli/main.py@@ -6,6 +6,7 @@ import typerfrom deeptutor.runtime.mode import RunMode, set_modefrom deeptutor.services.setup import get_backend_port+from .book import register as register_bookfrom .bot import register as register_botfrom .chat import register as register_chatfrom .common import build_turn_request, console, maybe_run@@ -35,6 +36,7 @@ config_app = typer.Typer(help="Inspect configuration.")session_app = typer.Typer(help="Manage shared sessions.")notebook_app = typer.Typer(help="Manage notebooks and imported markdown records.")provider_app = typer.Typer(help="Manage provider OAuth login.")+book_app = typer.Typer(help="Manage interactive Books (BookEngine).")app.add_typer(bot_app, name="bot")app.add_typer(chat_app, name="chat")@@ -45,6 +47,7 @@ app.add_typer(config_app, name="config")app.add_typer(session_app, name="session")app.add_typer(notebook_app, name="notebook")app.add_typer(provider_app, name="provider")+app.add_typer(book_app, name="book")register_bot(bot_app)register_chat(chat_app)@@ -55,6 +58,7 @@ register_config(config_app)register_session(session_app)register_notebook(notebook_app)register_provider(provider_app)+register_book(book_app)@app.command("run")diff --git a/scripts/migrate_user_data.py b/scripts/migrate_user_data.pyindex 5cae49d8d..7303651dc 100644--- a/scripts/migrate_user_data.py+++ b/scripts/migrate_user_data.py@@ -67,7 +67,6 @@ def create_structure(user_dir: Path) -> None:user_dir / "workspace" / "notebook",user_dir / "workspace" / "co-writer" / "audio",user_dir / "workspace" / "co-writer" / "tool_calls",- user_dir / "workspace" / "guide",user_dir / "workspace" / "chat" / "chat",user_dir / "workspace" / "chat" / "deep_solve",user_dir / "workspace" / "chat" / "deep_question",@@ -125,8 +124,6 @@ def migrate() -> None:(user_dir / "agent" / "research", user_dir / "workspace" / "chat" / "deep_research"),(user_dir / "co-writer", user_dir / "workspace" / "co-writer"),(user_dir / "agent" / "co-writer", user_dir / "workspace" / "co-writer"),- (user_dir / "guide", user_dir / "workspace" / "guide"),- (user_dir / "agent" / "guide", user_dir / "workspace" / "guide"),(user_dir / "workspace" / "logs", user_dir / "logs"),(user_dir / "logs", user_dir / "logs"),(user_dir / "agent" / "logs", user_dir / "logs"),@@ -170,7 +167,6 @@ data/user/├── memory/├── notebook/├── co-writer/- ├── guide/├── logs/└── chat/├── chat/@@ -194,7 +190,6 @@ def verify_migration() -> bool:"workspace/notebook","workspace/co-writer/audio","workspace/co-writer/tool_calls",- "workspace/guide","workspace/chat/chat","workspace/chat/deep_solve","workspace/chat/deep_question",diff --git a/tests/core/test_prompt_manager.py b/tests/core/test_prompt_manager.pyindex 3689b08be..33dcf3496 100644--- a/tests/core/test_prompt_manager.py+++ b/tests/core/test_prompt_manager.py@@ -50,16 +50,6 @@ class TestPromptManager:)assert isinstance(prompts, dict)- def test_load_prompts_guide_module(self):- """Test loading prompts for guide module."""- pm = get_prompt_manager()- prompts = pm.load_prompts(- module_name="guide",- agent_name="chat_agent",- language="en",- )- assert isinstance(prompts, dict)-def test_load_prompts_with_subdirectory(self):"""Test loading prompts with subdirectory (e.g., solve_loop)."""pm = get_prompt_manager()@@ -89,7 +79,7 @@ class TestPromptManager:# Load some promptspm.load_prompts("research", "research_agent", "en")- pm.load_prompts("guide", "chat_agent", "en")+ pm.load_prompts("solve", "solve_agent", "en")assert len(pm._cache) >= 2@@ -102,15 +92,13 @@ class TestPromptManager:# Load prompts for multiple modulespm.load_prompts("research", "research_agent", "en")- pm.load_prompts("guide", "chat_agent", "en")-- initial_count = len(pm._cache)+ pm.load_prompts("solve", "solve_agent", "en")# Clear only research cachepm.clear_cache("research")- # Guide prompts should still be cached- assert any("guide" in k for k in pm._cache)+ # Solve prompts should still be cached+ assert any("solve" in k for k in pm._cache)assert not any("research" in k for k in pm._cache)def test_get_prompt_helper(self):@@ -172,13 +160,13 @@ class TestPromptManagerLanguages:def test_english_prompts(self):"""Test loading English prompts."""pm = get_prompt_manager()- prompts = pm.load_prompts("guide", "chat_agent", "en")+ prompts = pm.load_prompts("solve", "solve_agent", "en")assert isinstance(prompts, dict)def test_chinese_prompts(self):"""Test loading Chinese prompts."""pm = get_prompt_manager()- prompts = pm.load_prompts("guide", "chat_agent", "zh")+ prompts = pm.load_prompts("solve", "solve_agent", "zh")assert isinstance(prompts, dict)def test_invalid_language_falls_back(self):diff --git a/tests/services/test_runtime_storage_guard.py b/tests/services/test_runtime_storage_guard.pyindex 068505b60..8c14cb08e 100644--- a/tests/services/test_runtime_storage_guard.py+++ b/tests/services/test_runtime_storage_guard.py@@ -17,7 +17,6 @@ def test_runtime_config_paths_are_confined_to_data_user() -> None:assert Path(paths["question_output_dir"]).resolve().is_relative_to(user_root)assert Path(paths["research_output_dir"]).resolve().is_relative_to(user_root)assert Path(paths["research_reports_dir"]).resolve().is_relative_to(user_root)- assert Path(paths["guide_output_dir"]).resolve().is_relative_to(user_root)assert Path(paths["user_log_dir"]).resolve() == user_root / "logs"assert Path(config["tools"]["run_code"]["workspace"]).resolve().is_relative_to(user_root)diff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsxindex 099de534b..0af27f6c6 100644--- a/web/app/(utility)/knowledge/page.tsx+++ b/web/app/(utility)/knowledge/page.tsx@@ -17,7 +17,6 @@ import {ExternalLink,FileUp,FolderOpen,- GraduationCap,Loader2,MessageSquare,NotebookPen,@@ -716,10 +715,6 @@ function KnowledgePageContent() {if (!sessionId) return;if (record.type === "chat") {router.push(`/?session=${encodeURIComponent(sessionId)}`);- return;- }- if (record.type === "guided_learning") {- router.push(`/guide?session=${encodeURIComponent(sessionId)}`);}};@@ -732,8 +727,6 @@ function KnowledgePageContent() {switch (type) {case "chat":return { label: t("Chat"), color: "bg-sky-100 text-sky-700 dark:bg-sky-900/40 dark:text-sky-300", icon: MessageSquare };- case "guided_learning":- return { label: t("Guided Learning"), color: "bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300", icon: GraduationCap };case "co_writer":return { label: t("Co-Writer"), color: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300", icon: PenLine };case "research":@@ -796,7 +789,7 @@ function KnowledgePageContent() {{[{ key: "knowledge", label: t("Knowledge Bases"), icon: Database },{ key: "notebooks", label: t("Notebooks"), icon: NotebookPen },- { key: "questions", label: t("Question Notebook"), icon: ClipboardList },+ { key: "questions", label: t("Question Bank"), icon: ClipboardList },].map((item) => (<buttonkey={item.key}@@ -1289,10 +1282,8 @@ function KnowledgePageContent() {const BadgeIcon = badge.icon;const expanded = expandedRecordId === record.id;const canOpenSession =- (record.type === "chat" || record.type === "guided_learning") &&- Boolean(record.metadata?.session_id);- const sessionLabel =- record.type === "chat" ? t("Open chat session") : t("Open guided learning session");+ record.type === "chat" && Boolean(record.metadata?.session_id);+ const sessionLabel = t("Open chat session");return (<div key={record.id} className="group">diff --git a/web/app/(utility)/notebook/page.tsx b/web/app/(utility)/notebook/page.tsxindex b97860b3a..41e4d6b90 100644--- a/web/app/(utility)/notebook/page.tsx+++ b/web/app/(utility)/notebook/page.tsx@@ -177,7 +177,7 @@ export default function NotebookPage() {<div className="mb-6 flex items-start justify-between"><div><h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">- {t("Question Notebook")}+ {t("Question Bank")}</h1><p className="mt-1 text-[13px] text-[var(--muted-foreground)]">{t("Review and organize quiz questions across sessions.")}diff --git a/web/app/(workspace)/book/components/BookChatPanel.tsx b/web/app/(workspace)/book/components/BookChatPanel.tsxnew file mode 100644index 000000000..66d7e39e1--- /dev/null+++ b/web/app/(workspace)/book/components/BookChatPanel.tsx@@ -0,0 +1,245 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Send, Loader2, MessageSquare, X } from "lucide-react";+import { wsUrl } from "@/lib/api";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Page, Book } from "@/lib/book-types";++interface ChatMessage {+ role: "user" | "assistant";+ content: string;+ streaming?: boolean;+}++export interface BookChatPanelProps {+ book: Book | null;+ page: Page | null;+ open: boolean;+ onClose: () => void;+}++export default function BookChatPanel({+ book,+ page,+ open,+ onClose,+}: BookChatPanelProps) {+ const [messages, setMessages] = useState<ChatMessage[]>([]);+ const [input, setInput] = useState("");+ const [busy, setBusy] = useState(false);+ const sessionIdRef = useRef<string | null>(null);+ const socketRef = useRef<WebSocket | null>(null);+ const scrollerRef = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ return () => {+ socketRef.current?.close();+ socketRef.current = null;+ };+ }, []);++ useEffect(() => {+ sessionIdRef.current = null;+ setMessages([]);+ }, [book?.id]);++ useEffect(() => {+ if (scrollerRef.current) {+ scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;+ }+ }, [messages]);++ function ensureSocket(): WebSocket {+ const existing = socketRef.current;+ if (existing && existing.readyState === WebSocket.OPEN) {+ return existing;+ }+ if (existing && existing.readyState === WebSocket.CONNECTING) {+ return existing;+ }+ const ws = new WebSocket(wsUrl("/api/v1/chat"));+ socketRef.current = ws;+ ws.onmessage = (event) => {+ try {+ const data = JSON.parse(event.data);+ switch (data.type) {+ case "session":+ sessionIdRef.current = data.session_id;+ break;+ case "stream":+ setMessages((prev) => {+ const next = [...prev];+ const last = next[next.length - 1];+ if (last && last.role === "assistant" && last.streaming) {+ next[next.length - 1] = {+ ...last,+ content: last.content + String(data.content || ""),+ };+ } else {+ next.push({+ role: "assistant",+ content: String(data.content || ""),+ streaming: true,+ });+ }+ return next;+ });+ break;+ case "result":+ setMessages((prev) => {+ const next = [...prev];+ const last = next[next.length - 1];+ if (last && last.role === "assistant") {+ next[next.length - 1] = {+ ...last,+ content: data.content || last.content,+ streaming: false,+ };+ } else {+ next.push({+ role: "assistant",+ content: String(data.content || ""),+ });+ }+ return next;+ });+ setBusy(false);+ break;+ case "error":+ setMessages((prev) => [+ ...prev,+ { role: "assistant", content: `❌ ${data.message || "error"}` },+ ]);+ setBusy(false);+ break;+ default:+ break;+ }+ } catch {+ // ignore+ }+ };+ ws.onclose = () => {+ socketRef.current = null;+ setBusy(false);+ };+ ws.onerror = () => setBusy(false);+ return ws;+ }++ function buildContextPreface(): string {+ const lines: string[] = [];+ if (book?.title) lines.push(`Book: ${book.title}`);+ if (page?.title) lines.push(`Current page: ${page.title}`);+ if (page?.learning_objectives?.length) {+ lines.push(`Objectives: ${page.learning_objectives.join("; ")}`);+ }+ return lines.join("\n");+ }++ async function send() {+ const text = input.trim();+ if (!text || busy) return;+ setMessages((prev) => [...prev, { role: "user", content: text }]);+ setInput("");+ setBusy(true);+ const ws = ensureSocket();+ const payload = {+ message: text,+ session_id: sessionIdRef.current,+ kb_name: book?.knowledge_bases?.[0] || "",+ enable_rag: !!(book?.knowledge_bases && book.knowledge_bases.length > 0),+ enable_web_search: false,+ context: buildContextPreface(),+ };+ const dispatch = () => ws.send(JSON.stringify(payload));+ if (ws.readyState === WebSocket.OPEN) {+ dispatch();+ } else {+ ws.addEventListener("open", dispatch, { once: true });+ }+ }++ if (!open) return null;++ return (+ <aside className="flex h-full w-[360px] shrink-0 flex-col border-l border-[var(--border)] bg-[var(--card)]/40 backdrop-blur">+ <header className="flex items-center justify-between border-b border-[var(--border)] px-4 py-3">+ <div className="flex items-center gap-2 text-sm font-medium text-[var(--foreground)]">+ <MessageSquare className="h-4 w-4 text-[var(--primary)]" />+ Page Chat+ </div>+ <button+ onClick={onClose}+ className="rounded p-1 text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ >+ <X className="h-4 w-4" />+ </button>+ </header>++ <div ref={scrollerRef} className="flex-1 overflow-y-auto px-4 py-3">+ {messages.length === 0 ? (+ <div className="text-xs text-[var(--muted-foreground)]">+ Ask a question about this page. Context (book + chapter) is sent+ automatically.+ </div>+ ) : (+ <div className="space-y-3">+ {messages.map((m, i) => (+ <div+ key={i}+ className={+ m.role === "user"+ ? "ml-6 rounded-2xl rounded-tr-sm bg-[var(--primary)]/10 px-3 py-2 text-sm text-[var(--foreground)]"+ : "mr-6 rounded-2xl rounded-tl-sm bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)]"+ }+ >+ {m.role === "assistant" ? (+ <MarkdownRenderer content={m.content} variant="compact" />+ ) : (+ m.content+ )}+ </div>+ ))}+ </div>+ )}+ </div>++ <form+ onSubmit={(e) => {+ e.preventDefault();+ send();+ }}+ className="border-t border-[var(--border)] p-3"+ >+ <div className="flex items-end gap-2">+ <textarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ placeholder="Ask about this page…"+ rows={2}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ send();+ }+ }}+ className="flex-1 resize-none rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-sm text-[var(--foreground)] focus:border-[var(--primary)] focus:outline-none"+ />+ <button+ type="submit"+ disabled={busy || !input.trim()}+ className="inline-flex h-9 items-center justify-center rounded-md bg-[var(--primary)] px-3 text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {busy ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Send className="h-4 w-4" />+ )}+ </button>+ </div>+ </form>+ </aside>+ );+}diff --git a/web/app/(workspace)/book/components/BookCreator.tsx b/web/app/(workspace)/book/components/BookCreator.tsxnew file mode 100644index 000000000..422d04d6e--- /dev/null+++ b/web/app/(workspace)/book/components/BookCreator.tsx@@ -0,0 +1,1071 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import {+ ChevronDown,+ ChevronRight,+ ChevronUp,+ ClipboardList,+ Database,+ Loader2,+ MessagesSquare,+ NotebookPen,+ Pencil,+ RefreshCw,+ Sparkles,+} from "lucide-react";+import type { BookProposal } from "@/lib/book-types";+import {+ listKnowledgeBases,+ type KnowledgeBaseSummary,+} from "@/lib/knowledge-api";+import {+ getNotebook,+ listCategories,+ listNotebookEntries,+ listNotebooks,+ type NotebookCategory,+ type NotebookEntry,+ type NotebookRecordItem,+ type NotebookSummary,+} from "@/lib/notebook-api";+import {+ getSession,+ listSessions,+ type SessionMessage,+ type SessionSummary,+} from "@/lib/session-api";++type SourceTab = "knowledge" | "notebooks" | "questions" | "chats";++type ParentSelection<TChild extends string | number> =+ | { mode: "all" }+ | { mode: "subset"; ids: Set<TChild> };++type ParentMap<TParent extends string | number, TChild extends string | number> = Map<+ TParent,+ ParentSelection<TChild>+>;++export interface BookCreatorProps {+ onCreate: (payload: {+ user_intent: string;+ chat_session_id: string;+ chat_selections: Array<{ session_id: string; message_ids: number[] }>;+ knowledge_bases: string[];+ notebook_refs: Array<Record<string, unknown>>;+ question_categories: number[];+ question_entries: number[];+ language: string;+ }) => void | Promise<void>;+ loading?: boolean;+ proposal?: BookProposal | null;+ onConfirmProposal?: (edited: BookProposal) => void | Promise<void>;+ confirmLoading?: boolean;+}++export default function BookCreator({+ onCreate,+ loading = false,+ proposal = null,+ onConfirmProposal,+ confirmLoading = false,+}: BookCreatorProps) {+ const [intent, setIntent] = useState("");+ const [language, setLanguage] = useState("en");+ const [tab, setTab] = useState<SourceTab>("knowledge");++ // Knowledge bases (flat selection)+ const [kbs, setKbs] = useState<KnowledgeBaseSummary[]>([]);+ const [kbsLoading, setKbsLoading] = useState(false);+ const [selectedKbs, setSelectedKbs] = useState<Set<string>>(new Set());++ // Notebooks → records (tree selection)+ const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);+ const [notebooksLoading, setNotebooksLoading] = useState(false);+ const [notebookSelection, setNotebookSelection] = useState<+ ParentMap<string, string>+ >(new Map());+ const [notebookExpanded, setNotebookExpanded] = useState<Set<string>>(new Set());+ const [notebookRecords, setNotebookRecords] = useState<+ Record<string, NotebookRecordItem[]>+ >({});+ const [notebookRecordsLoading, setNotebookRecordsLoading] = useState<+ Record<string, boolean>+ >({});++ // Question bank: categories → entries+ const [categories, setCategories] = useState<NotebookCategory[]>([]);+ const [categoriesLoading, setCategoriesLoading] = useState(false);+ const [questionSelection, setQuestionSelection] = useState<+ ParentMap<number, number>+ >(new Map());+ const [questionExpanded, setQuestionExpanded] = useState<Set<number>>(new Set());+ const [questionEntries, setQuestionEntries] = useState<+ Record<number, NotebookEntry[]>+ >({});+ const [questionEntriesLoading, setQuestionEntriesLoading] = useState<+ Record<number, boolean>+ >({});++ // Chat history: sessions → messages+ const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [sessionsLoading, setSessionsLoading] = useState(false);+ const [chatSelection, setChatSelection] = useState<ParentMap<string, number>>(+ new Map(),+ );+ const [chatExpanded, setChatExpanded] = useState<Set<string>>(new Set());+ const [chatMessages, setChatMessages] = useState<+ Record<string, SessionMessage[]>+ >({});+ const [chatMessagesLoading, setChatMessagesLoading] = useState<+ Record<string, boolean>+ >({});++ const [editProposal, setEditProposal] = useState<BookProposal | null>(null);+ const [formCollapsed, setFormCollapsed] = useState(false);+ const lastSeenProposalIdRef = useRef<string | null>(null);++ // Auto-collapse the form once the proposal first arrives (never overwrites+ // a manual expand later because we only fire on identity change).+ useEffect(() => {+ const id = proposal ? proposal.title || "_proposal_" : null;+ if (id && id !== lastSeenProposalIdRef.current) {+ setFormCollapsed(true);+ }+ lastSeenProposalIdRef.current = id;+ }, [proposal]);++ const refreshKbs = async () => {+ setKbsLoading(true);+ try {+ setKbs(await listKnowledgeBases({ force: true }));+ } catch {+ setKbs([]);+ } finally {+ setKbsLoading(false);+ }+ };+ const refreshNotebooks = async () => {+ setNotebooksLoading(true);+ try {+ setNotebooks(await listNotebooks());+ } catch {+ setNotebooks([]);+ } finally {+ setNotebooksLoading(false);+ }+ };+ const refreshCategories = async () => {+ setCategoriesLoading(true);+ try {+ setCategories(await listCategories());+ } catch {+ setCategories([]);+ } finally {+ setCategoriesLoading(false);+ }+ };+ const refreshSessions = async () => {+ setSessionsLoading(true);+ try {+ setSessions(await listSessions(50, 0, { force: true }));+ } catch {+ setSessions([]);+ } finally {+ setSessionsLoading(false);+ }+ };++ useEffect(() => {+ void refreshKbs();+ void refreshNotebooks();+ void refreshCategories();+ void refreshSessions();+ }, []);++ // ── selection counts ─────────────────────────────────────────────+ const countSelection = <P extends string | number, C extends string | number>(+ map: ParentMap<P, C>,+ ): number => {+ let n = 0;+ map.forEach((sel) => {+ n += sel.mode === "all" ? 1 : sel.ids.size;+ });+ return n;+ };+ const nbCount = countSelection(notebookSelection);+ const qCount = countSelection(questionSelection);+ const chatCount = countSelection(chatSelection);+ const totalSelected = selectedKbs.size + nbCount + qCount + chatCount;++ // ── generic tree-selection helpers ───────────────────────────────+ const toggleParent = <P extends string | number, C extends string | number>(+ map: ParentMap<P, C>,+ parent: P,+ ): ParentMap<P, C> => {+ const next = new Map(map);+ if (next.has(parent)) next.delete(parent);+ else next.set(parent, { mode: "all" });+ return next;+ };+ const toggleChild = <P extends string | number, C extends string | number>(+ map: ParentMap<P, C>,+ parent: P,+ child: C,+ knownChildren: C[],+ ): ParentMap<P, C> => {+ const next = new Map(map);+ const current = next.get(parent);+ let ids: Set<C>;+ if (!current) {+ ids = new Set([child]);+ } else if (current.mode === "all") {+ // materialize: all known children except the one being unchecked+ ids = new Set(knownChildren.filter((c) => c !== child));+ } else {+ ids = new Set(current.ids);+ if (ids.has(child)) ids.delete(child);+ else ids.add(child);+ }+ if (ids.size === 0) next.delete(parent);+ else next.set(parent, { mode: "subset", ids });+ return next;+ };++ const toggleKb = (name: string) => {+ setSelectedKbs((prev) => {+ const next = new Set(prev);+ if (next.has(name)) next.delete(name);+ else next.add(name);+ return next;+ });+ };++ // ── lazy children loaders ────────────────────────────────────────+ const ensureNotebookRecords = async (id: string) => {+ if (notebookRecords[id] || notebookRecordsLoading[id]) return;+ setNotebookRecordsLoading((p) => ({ ...p, [id]: true }));+ try {+ const detail = await getNotebook(id);+ setNotebookRecords((p) => ({ ...p, [id]: detail.records ?? [] }));+ } catch {+ setNotebookRecords((p) => ({ ...p, [id]: [] }));+ } finally {+ setNotebookRecordsLoading((p) => ({ ...p, [id]: false }));+ }+ };+ const ensureQuestionEntries = async (id: number) => {+ if (questionEntries[id] || questionEntriesLoading[id]) return;+ setQuestionEntriesLoading((p) => ({ ...p, [id]: true }));+ try {+ const result = await listNotebookEntries({ category_id: id, limit: 200 });+ setQuestionEntries((p) => ({ ...p, [id]: result.items }));+ } catch {+ setQuestionEntries((p) => ({ ...p, [id]: [] }));+ } finally {+ setQuestionEntriesLoading((p) => ({ ...p, [id]: false }));+ }+ };+ const ensureChatMessages = async (sid: string) => {+ if (chatMessages[sid] || chatMessagesLoading[sid]) return;+ setChatMessagesLoading((p) => ({ ...p, [sid]: true }));+ try {+ const detail = await getSession(sid);+ setChatMessages((p) => ({ ...p, [sid]: detail.messages ?? [] }));+ } catch {+ setChatMessages((p) => ({ ...p, [sid]: [] }));+ } finally {+ setChatMessagesLoading((p) => ({ ...p, [sid]: false }));+ }+ };++ // ── submit ───────────────────────────────────────────────────────+ const handleCreate = async () => {+ if (!intent.trim()) return;++ const notebook_refs: Array<{ notebook_id: string; record_ids: string[] }> = [];+ notebookSelection.forEach((sel, id) => {+ notebook_refs.push({+ notebook_id: id,+ record_ids: sel.mode === "all" ? [] : Array.from(sel.ids),+ });+ });++ const question_categories: number[] = [];+ const question_entries: number[] = [];+ questionSelection.forEach((sel, id) => {+ if (sel.mode === "all") question_categories.push(id);+ else sel.ids.forEach((eid) => question_entries.push(eid));+ });++ const chat_selections: Array<{ session_id: string; message_ids: number[] }> = [];+ chatSelection.forEach((sel, sid) => {+ chat_selections.push({+ session_id: sid,+ message_ids: sel.mode === "all" ? [] : Array.from(sel.ids),+ });+ });++ await onCreate({+ user_intent: intent,+ chat_session_id: "",+ chat_selections,+ knowledge_bases: Array.from(selectedKbs),+ notebook_refs,+ question_categories,+ question_entries,+ language,+ });+ };++ const currentProposal = editProposal || proposal;++ const tabConfig: Array<{+ key: SourceTab;+ label: string;+ icon: typeof Database;+ count: number;+ }> = [+ { key: "knowledge", label: "KB", icon: Database, count: selectedKbs.size },+ { key: "notebooks", label: "Notebooks", icon: NotebookPen, count: nbCount },+ { key: "questions", label: "Questions", icon: ClipboardList, count: qCount },+ { key: "chats", label: "Chats", icon: MessagesSquare, count: chatCount },+ ];++ // Summary chips shown in the collapsed form header so users always see what+ // sources their proposal was generated from (even after collapsing).+ const summaryChips: Array<{ icon: typeof Database; label: string }> = [];+ if (selectedKbs.size > 0) {+ summaryChips.push({+ icon: Database,+ label: `${selectedKbs.size} KB`,+ });+ }+ if (nbCount > 0) {+ summaryChips.push({+ icon: NotebookPen,+ label: `${nbCount} notebook record${nbCount === 1 ? "" : "s"}`,+ });+ }+ if (qCount > 0) {+ summaryChips.push({+ icon: ClipboardList,+ label: `${qCount} quiz item${qCount === 1 ? "" : "s"}`,+ });+ }+ if (chatCount > 0) {+ summaryChips.push({+ icon: MessagesSquare,+ label: `${chatCount} chat item${chatCount === 1 ? "" : "s"}`,+ });+ }++ return (+ <div className="mx-auto w-full max-w-2xl space-y-5 p-6">+ <div className="space-y-1.5">+ <h1 className="text-2xl font-semibold text-[var(--foreground)]">Create a new book</h1>+ <p className="text-sm text-[var(--muted-foreground)]">+ Describe what you want to learn, then pick the knowledge sources to fuse+ into a structured, interactive book.+ </p>+ </div>++ <div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] shadow-sm">+ <button+ type="button"+ onClick={() => setFormCollapsed((v) => !v)}+ className="flex w-full items-center justify-between gap-3 rounded-t-2xl px-5 py-3 text-left hover:bg-[var(--muted)]/40"+ >+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-semibold text-[var(--foreground)]">+ {formCollapsed ? "Inputs" : "Configure inputs"}+ </span>+ {formCollapsed && intent.trim() && (+ <span className="truncate text-xs text-[var(--muted-foreground)]">+ · {clip(intent, 90)}+ </span>+ )}+ </div>+ {formCollapsed && (+ <div className="mt-1 flex flex-wrap items-center gap-1.5">+ {summaryChips.length === 0 ? (+ <span className="text-[11px] text-[var(--muted-foreground)]">+ No knowledge sources selected+ </span>+ ) : (+ summaryChips.map((chip, i) => (+ <span+ key={i}+ className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/10 px-2 py-0.5 text-[11px] font-medium text-[var(--primary)]"+ >+ <chip.icon className="h-3 w-3" />+ {chip.label}+ </span>+ ))+ )}+ </div>+ )}+ </div>+ <span className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] text-[var(--muted-foreground)]">+ {formCollapsed ? (+ <>+ <Pencil className="h-3 w-3" />+ Edit+ </>+ ) : (+ <ChevronUp className="h-3.5 w-3.5" />+ )}+ </span>+ </button>++ {!formCollapsed && (+ <div className="space-y-4 px-5 pb-5">+ <label className="block">+ <span className="text-xs font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ Learning intent+ </span>+ <textarea+ value={intent}+ onChange={(e) => setIntent(e.target.value)}+ rows={5}+ placeholder="e.g. Build intuition for transformer attention with derivations and exercises."+ className="mt-1.5 w-full resize-none rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--primary)]/50"+ />+ </label>++ <div className="space-y-3">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ Knowledge sources+ {totalSelected > 0 && (+ <span className="ml-2 rounded-full bg-[var(--primary)]/15 px-2 py-0.5 text-[10px] font-semibold text-[var(--primary)]">+ {totalSelected} selected+ </span>+ )}+ </span>+ <button+ type="button"+ onClick={() => {+ if (tab === "knowledge") void refreshKbs();+ else if (tab === "notebooks") void refreshNotebooks();+ else if (tab === "questions") void refreshCategories();+ else void refreshSessions();+ }}+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ <RefreshCw className="h-3 w-3" />+ Refresh+ </button>+ </div>++ <div className="inline-flex w-full rounded-lg border border-[var(--border)] bg-[var(--muted)] p-0.5">+ {tabConfig.map((item) => (+ <button+ key={item.key}+ type="button"+ onClick={() => setTab(item.key)}+ className={`flex flex-1 items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-[12px] font-medium transition-all ${+ tab === item.key+ ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ <item.icon size={13} />+ {item.label}+ {item.count > 0 && (+ <span+ className={`ml-0.5 rounded-full px-1.5 text-[10px] font-semibold ${+ tab === item.key+ ? "bg-[var(--primary)]/15 text-[var(--primary)]"+ : "bg-[var(--border)]/70 text-[var(--muted-foreground)]"+ }`}+ >+ {item.count}+ </span>+ )}+ </button>+ ))}+ </div>++ <div className="max-h-72 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--background)] p-1.5">+ {tab === "knowledge" && (+ <FlatList+ loading={kbsLoading}+ emptyHint="No knowledge bases yet. Create one in the Knowledge page first."+ items={kbs.map((kb) => ({+ key: kb.name,+ primary: kb.name,+ secondary: kb.is_default ? "default" : kb.status || "",+ checked: selectedKbs.has(kb.name),+ onToggle: () => toggleKb(kb.name),+ }))}+ />+ )}++ {tab === "notebooks" && (+ <TreeList+ loading={notebooksLoading}+ emptyHint="No notebooks yet. Save chat outputs into a notebook first."+ parents={notebooks.map((nb) => {+ const records = notebookRecords[nb.id];+ return {+ id: nb.id,+ title: nb.name,+ subtitle: parentSubtitle(+ notebookSelection.get(nb.id),+ records?.length ?? nb.record_count ?? 0,+ "record",+ ),+ expanded: notebookExpanded.has(nb.id),+ childrenLoading: !!notebookRecordsLoading[nb.id],+ children: (records ?? []).map((rec) => ({+ id: rec.id,+ title: rec.title || "(untitled)",+ subtitle: rec.summary || "",+ })),+ selection: notebookSelection.get(nb.id),+ };+ })}+ onToggleParent={(id) =>+ setNotebookSelection((prev) => toggleParent(prev, id))+ }+ onToggleChild={(parentId, childId, knownChildren) =>+ setNotebookSelection((prev) =>+ toggleChild(prev, parentId, childId, knownChildren),+ )+ }+ onToggleExpand={(id) => {+ setNotebookExpanded((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else {+ next.add(id);+ void ensureNotebookRecords(id);+ }+ return next;+ });+ }}+ />+ )}++ {tab === "questions" && (+ <TreeList<number, number>+ loading={categoriesLoading}+ emptyHint="No quiz categories yet. Bookmark questions into a category first."+ parents={categories.map((cat) => {+ const entries = questionEntries[cat.id];+ return {+ id: cat.id,+ title: cat.name,+ subtitle: parentSubtitle(+ questionSelection.get(cat.id),+ entries?.length ?? cat.entry_count ?? 0,+ "entry",+ "entries",+ ),+ expanded: questionExpanded.has(cat.id),+ childrenLoading: !!questionEntriesLoading[cat.id],+ children: (entries ?? []).map((e) => ({+ id: e.id,+ title: e.question || "(no question)",+ subtitle: `${e.is_correct ? "✓" : "✗"} ${+ e.user_answer ? `your: ${e.user_answer}` : "no attempt"+ } · correct: ${e.correct_answer}`,+ })),+ selection: questionSelection.get(cat.id),+ };+ })}+ onToggleParent={(id) =>+ setQuestionSelection((prev) => toggleParent(prev, id))+ }+ onToggleChild={(parentId, childId, knownChildren) =>+ setQuestionSelection((prev) =>+ toggleChild(prev, parentId, childId, knownChildren),+ )+ }+ onToggleExpand={(id) => {+ setQuestionExpanded((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else {+ next.add(id);+ void ensureQuestionEntries(id);+ }+ return next;+ });+ }}+ />+ )}++ {tab === "chats" && (+ <TreeList<string, number>+ loading={sessionsLoading}+ emptyHint="No chat sessions yet."+ parents={sessions.map((s) => {+ const msgs = chatMessages[s.session_id];+ return {+ id: s.session_id,+ title: s.title || "(untitled chat)",+ subtitle: parentSubtitle(+ chatSelection.get(s.session_id),+ msgs?.length ?? s.message_count ?? 0,+ "message",+ ),+ expanded: chatExpanded.has(s.session_id),+ childrenLoading: !!chatMessagesLoading[s.session_id],+ children: (msgs ?? []).map((m) => ({+ id: m.id,+ title: `${m.role}${m.capability ? ` · ${m.capability}` : ""}`,+ subtitle: clip(m.content, 140),+ })),+ selection: chatSelection.get(s.session_id),+ };+ })}+ onToggleParent={(id) =>+ setChatSelection((prev) => toggleParent(prev, id))+ }+ onToggleChild={(parentId, childId, knownChildren) =>+ setChatSelection((prev) =>+ toggleChild(prev, parentId, childId, knownChildren),+ )+ }+ onToggleExpand={(id) => {+ setChatExpanded((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else {+ next.add(id);+ void ensureChatMessages(id);+ }+ return next;+ });+ }}+ />+ )}+ </div>+ </div>++ <div className="flex items-center justify-between gap-3">+ <label className="text-xs text-[var(--muted-foreground)]">+ Language{" "}+ <select+ value={language}+ onChange={(e) => setLanguage(e.target.value)}+ className="ml-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-xs text-[var(--foreground)]"+ >+ <option value="en">English</option>+ <option value="zh">中文</option>+ </select>+ </label>+ <button+ onClick={handleCreate}+ disabled={loading || !intent.trim()}+ className="inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"+ >+ {loading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Sparkles className="h-4 w-4" />+ )}+ Generate proposal+ </button>+ </div>+ </div>+ )}+ </div>++ {currentProposal && onConfirmProposal && (+ <div className="space-y-4 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">+ <div>+ <h2 className="text-base font-semibold text-[var(--foreground)]">+ Proposal+ </h2>+ <p className="text-xs text-[var(--muted-foreground)]">+ Edit anything below, then confirm to generate the chapter spine.+ </p>+ </div>+ <ProposalForm+ proposal={currentProposal}+ onChange={setEditProposal}+ selectedKbs={Array.from(selectedKbs)}+ />+ <div className="flex justify-end">+ <button+ onClick={() =>+ editProposal+ ? onConfirmProposal(editProposal)+ : onConfirmProposal(currentProposal)+ }+ disabled={confirmLoading}+ className="inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"+ >+ {confirmLoading && <Loader2 className="h-4 w-4 animate-spin" />}+ Confirm proposal & build spine+ </button>+ </div>+ </div>+ )}+ </div>+ );+}++// ─── helpers ───────────────────────────────────────────────────────────++function clip(text: string, n: number): string {+ if (!text) return "";+ const t = text.replace(/\s+/g, " ").trim();+ return t.length <= n ? t : t.slice(0, n) + "…";+}++function parentSubtitle<C extends string | number>(+ sel: ParentSelection<C> | undefined,+ total: number,+ unit: string,+ unitPlural?: string,+): string {+ const plural = unitPlural || `${unit}s`;+ const fmt = (n: number) => `${n} ${n === 1 ? unit : plural}`;+ if (!sel) return total > 0 ? fmt(total) : `0 ${plural}`;+ if (sel.mode === "all") {+ return total > 0 ? `All ${fmt(total)}` : "All";+ }+ return total > 0 ? `${sel.ids.size} of ${fmt(total)}` : `${sel.ids.size} selected`;+}++// ─── checkbox icon ─────────────────────────────────────────────────────++function CheckBox({+ state,+}: {+ state: "off" | "on" | "indeterminate";+}) {+ if (state === "off") {+ return (+ <span className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-[var(--border)] bg-[var(--background)]" />+ );+ }+ if (state === "indeterminate") {+ return (+ <span className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-[var(--primary)] bg-[var(--primary)]">+ <span className="h-[2px] w-2 rounded bg-[var(--primary-foreground)]" />+ </span>+ );+ }+ return (+ <span className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]">+ <svg width="10" height="10" viewBox="0 0 12 12" fill="none">+ <path+ d="M2.5 6.5L5 9L9.5 3.5"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ </span>+ );+}++// ─── flat list (for KB tab) ────────────────────────────────────────────++function FlatList({+ loading,+ emptyHint,+ items,+}: {+ loading: boolean;+ emptyHint: string;+ items: Array<{+ key: string;+ primary: string;+ secondary?: string;+ checked: boolean;+ onToggle: () => void;+ }>;+}) {+ if (loading)+ return (+ <div className="flex items-center justify-center gap-2 py-6 text-xs text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ Loading…+ </div>+ );+ if (items.length === 0)+ return (+ <div className="flex items-center justify-center px-3 py-6 text-center text-xs text-[var(--muted-foreground)]">+ {emptyHint}+ </div>+ );+ return (+ <ul className="space-y-0.5">+ {items.map((item) => (+ <li key={item.key}>+ <button+ type="button"+ onClick={item.onToggle}+ className={`flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left text-[13px] transition-colors ${+ item.checked+ ? "bg-[var(--primary)]/10"+ : "hover:bg-[var(--muted)]/60"+ }`}+ >+ <CheckBox state={item.checked ? "on" : "off"} />+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium text-[var(--foreground)]">+ {item.primary}+ </div>+ {item.secondary && (+ <div className="truncate text-[11px] text-[var(--muted-foreground)]">+ {item.secondary}+ </div>+ )}+ </div>+ </button>+ </li>+ ))}+ </ul>+ );+}++// ─── tree list (for notebooks / questions / chats) ─────────────────────++interface TreeChild<C extends string | number> {+ id: C;+ title: string;+ subtitle?: string;+}++interface TreeParent<P extends string | number, C extends string | number> {+ id: P;+ title: string;+ subtitle?: string;+ expanded: boolean;+ childrenLoading: boolean;+ children: TreeChild<C>[];+ selection: ParentSelection<C> | undefined;+}++function TreeList<+ P extends string | number = string,+ C extends string | number = string,+>({+ loading,+ emptyHint,+ parents,+ onToggleParent,+ onToggleChild,+ onToggleExpand,+}: {+ loading: boolean;+ emptyHint: string;+ parents: TreeParent<P, C>[];+ onToggleParent: (id: P) => void;+ onToggleChild: (parentId: P, childId: C, knownChildren: C[]) => void;+ onToggleExpand: (id: P) => void;+}) {+ if (loading)+ return (+ <div className="flex items-center justify-center gap-2 py-6 text-xs text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ Loading…+ </div>+ );+ if (parents.length === 0)+ return (+ <div className="flex items-center justify-center px-3 py-6 text-center text-xs text-[var(--muted-foreground)]">+ {emptyHint}+ </div>+ );++ return (+ <ul className="space-y-0.5">+ {parents.map((p) => {+ const sel = p.selection;+ const parentState: "on" | "off" | "indeterminate" = !sel+ ? "off"+ : sel.mode === "all"+ ? "on"+ : "indeterminate";++ return (+ <li key={String(p.id)}>+ <div+ className={`group flex items-center gap-1 rounded-md pr-2 transition-colors ${+ sel ? "bg-[var(--primary)]/8" : "hover:bg-[var(--muted)]/60"+ }`}+ >+ <button+ type="button"+ onClick={() => onToggleExpand(p.id)}+ className="flex h-7 w-6 shrink-0 items-center justify-center text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ aria-label={p.expanded ? "Collapse" : "Expand"}+ >+ {p.expanded ? (+ <ChevronDown className="h-3.5 w-3.5" />+ ) : (+ <ChevronRight className="h-3.5 w-3.5" />+ )}+ </button>+ <button+ type="button"+ onClick={() => onToggleParent(p.id)}+ className="flex min-w-0 flex-1 items-center gap-2.5 py-1.5 text-left text-[13px]"+ >+ <CheckBox state={parentState} />+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium text-[var(--foreground)]">+ {p.title}+ </div>+ {p.subtitle && (+ <div className="truncate text-[11px] text-[var(--muted-foreground)]">+ {p.subtitle}+ </div>+ )}+ </div>+ </button>+ </div>++ {p.expanded && (+ <div className="ml-6 mt-0.5 border-l border-[var(--border)] pl-1.5">+ {p.childrenLoading ? (+ <div className="flex items-center gap-2 px-2 py-2 text-[11px] text-[var(--muted-foreground)]">+ <Loader2 className="h-3 w-3 animate-spin" />+ Loading…+ </div>+ ) : p.children.length === 0 ? (+ <div className="px-2 py-2 text-[11px] text-[var(--muted-foreground)]">+ Nothing inside.+ </div>+ ) : (+ <ul className="max-h-56 space-y-0.5 overflow-y-auto pr-0.5">+ {p.children.map((c) => {+ const checked = !!sel && (sel.mode === "all" || sel.ids.has(c.id));+ const knownChildren = p.children.map((x) => x.id);+ return (+ <li key={String(c.id)}>+ <button+ type="button"+ onClick={() =>+ onToggleChild(p.id, c.id, knownChildren)+ }+ className={`flex w-full items-start gap-2.5 rounded px-2 py-1 text-left text-[12px] transition-colors ${+ checked+ ? "bg-[var(--primary)]/10"+ : "hover:bg-[var(--muted)]/60"+ }`}+ >+ <span className="pt-0.5">+ <CheckBox state={checked ? "on" : "off"} />+ </span>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[var(--foreground)]">+ {c.title}+ </div>+ {c.subtitle && (+ <div className="truncate text-[10.5px] text-[var(--muted-foreground)]">+ {c.subtitle}+ </div>+ )}+ </div>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ )}+ </li>+ );+ })}+ </ul>+ );+}++// ─── proposal form (unchanged) ─────────────────────────────────────────++function ProposalForm({+ proposal,+ onChange,+ selectedKbs,+}: {+ proposal: BookProposal;+ onChange: (p: BookProposal) => void;+ selectedKbs: string[];+}) {+ const update = (patch: Partial<BookProposal>) =>+ onChange({ ...proposal, ...patch });+ return (+ <div className="grid gap-3 sm:grid-cols-2">+ <label className="block sm:col-span-2">+ <span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">Title</span>+ <input+ value={proposal.title}+ onChange={(e) => update({ title: e.target.value })}+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ <label className="block sm:col-span-2">+ <span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">Description</span>+ <textarea+ value={proposal.description}+ onChange={(e) => update({ description: e.target.value })}+ rows={3}+ className="mt-1 w-full resize-none rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ <label className="block">+ <span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">Scope</span>+ <input+ value={proposal.scope}+ onChange={(e) => update({ scope: e.target.value })}+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ <label className="block">+ <span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">Target level</span>+ <input+ value={proposal.target_level}+ onChange={(e) => update({ target_level: e.target.value })}+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ <label className="block">+ <span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">Estimated chapters</span>+ <input+ type="number"+ min={2}+ max={12}+ value={proposal.estimated_chapters}+ onChange={(e) =>+ update({ estimated_chapters: Number(e.target.value) || 0 })+ }+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ <div className="block sm:col-span-2">+ <span className="text-xs uppercase tracking-wider text-[var(--muted-foreground)]">+ Knowledge bases used+ </span>+ <div className="mt-1.5 flex flex-wrap gap-1.5">+ {selectedKbs.length === 0 ? (+ <span className="text-xs italic text-[var(--muted-foreground)]">+ No knowledge bases selected. The book will rely on general knowledge.+ </span>+ ) : (+ selectedKbs.map((kb) => (+ <span+ key={kb}+ className="inline-flex items-center rounded-full border border-[var(--border)] bg-[var(--muted)]/40 px-2.5 py-0.5 text-[11px] text-[var(--foreground)]"+ >+ {kb}+ </span>+ ))+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/BookHealthBanner.tsx b/web/app/(workspace)/book/components/BookHealthBanner.tsxnew file mode 100644index 000000000..0b752242e--- /dev/null+++ b/web/app/(workspace)/book/components/BookHealthBanner.tsx@@ -0,0 +1,195 @@+"use client";++import { useEffect, useState } from "react";+import { AlertTriangle, RefreshCcw, X, ScrollText } from "lucide-react";+import { bookApi } from "@/lib/book-api";++export interface BookHealthBannerProps {+ bookId: string | null;+ refreshKey?: number;+ onRecompile?: (pageId: string) => void;+}++interface KbDrift {+ has_drift: boolean;+ new_kbs?: string[];+ removed_kbs?: string[];+ changed_kbs?: string[];+ stale_page_ids?: string[];+}++interface LogHealth {+ total_entries: number;+ error_entries: number;+ block_failures: number;+ repeated_failures?: { signature: string; count: number }[];+}++export default function BookHealthBanner({+ bookId,+ refreshKey,+ onRecompile,+}: BookHealthBannerProps) {+ const [kbDrift, setKbDrift] = useState<KbDrift | null>(null);+ const [logHealth, setLogHealth] = useState<LogHealth | null>(null);+ const [dismissed, setDismissed] = useState(false);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ let cancelled = false;+ if (!bookId) {+ setKbDrift(null);+ setLogHealth(null);+ return;+ }+ setDismissed(false);+ (async () => {+ try {+ const data = await bookApi.health(bookId);+ if (cancelled) return;+ setKbDrift(data.kb_drift);+ setLogHealth(data.log_health);+ } catch {+ // ignore – health is non-critical+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [bookId, refreshKey]);++ if (!bookId || dismissed) return null;++ const hasDrift = !!kbDrift?.has_drift;+ // Filter out repeated failures that are already represented elsewhere+ // (kb_health drift logs are surfaced via the kb-drift section above).+ const repeated = (logHealth?.repeated_failures || [])+ .filter((r) => {+ const sig = (r.signature || "").toLowerCase();+ if (sig.includes("kb_health")) return false;+ if (sig.includes("kb drift")) return false;+ return true;+ })+ .slice(0, 3);+ const blockFailures = logHealth?.block_failures || 0;+ const hasLogIssues = blockFailures >= 3 || repeated.length > 0;++ if (!hasDrift && !hasLogIssues) return null;++ // Convert technical signatures into a short human label.+ const humanizeSignature = (sig: string): string => {+ if (!sig) return "unknown failure";+ const stripped = sig.replace(/^[a-z_]+:/i, "").trim();+ return stripped.length > 80 ? `${stripped.slice(0, 80)}…` : stripped;+ };++ const acknowledge = async () => {+ if (!bookId) return;+ setBusy(true);+ try {+ await bookApi.refreshFingerprints(bookId);+ setKbDrift({ has_drift: false });+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="mx-6 mt-4 rounded-xl border border-amber-300/60 bg-amber-50 px-4 py-3 text-sm text-amber-900 shadow-sm dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-100">+ <div className="flex items-start gap-3">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />+ <div className="flex-1 space-y-1.5">+ {hasDrift && (+ <div>+ <strong>Your knowledge bases changed since this book was generated.</strong>{" "}+ <span className="opacity-90">+ {kbDrift?.new_kbs?.length ? (+ <>+ Newly added:{" "}+ <code className="rounded bg-white/40 px-1 text-[11px] dark:bg-white/10">+ {kbDrift.new_kbs.join(", ")}+ </code>+ .{" "}+ </>+ ) : null}+ {kbDrift?.changed_kbs?.length ? (+ <>+ Updated:{" "}+ <code className="rounded bg-white/40 px-1 text-[11px] dark:bg-white/10">+ {kbDrift.changed_kbs.join(", ")}+ </code>+ .{" "}+ </>+ ) : null}+ {kbDrift?.removed_kbs?.length ? (+ <>+ Removed:{" "}+ <code className="rounded bg-white/40 px-1 text-[11px] dark:bg-white/10">+ {kbDrift.removed_kbs.join(", ")}+ </code>+ .{" "}+ </>+ ) : null}+ </span>+ {kbDrift?.stale_page_ids?.length ? (+ <div className="mt-1.5 text-xs opacity-90">+ {kbDrift.stale_page_ids.length} previously-compiled page+ {kbDrift.stale_page_ids.length === 1 ? "" : "s"} may be out+ of date.{" "}+ {onRecompile && kbDrift.stale_page_ids[0] && (+ <button+ onClick={() => onRecompile(kbDrift.stale_page_ids![0])}+ className="ml-1 inline-flex items-center gap-1 rounded border border-current px-1.5 py-0.5 text-xs hover:bg-white/40"+ >+ <RefreshCcw className="h-3 w-3" /> Recompile first stale+ page+ </button>+ )}+ </div>+ ) : null}+ </div>+ )}+ {hasLogIssues && (+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <ScrollText className="h-3.5 w-3.5" />+ {blockFailures > 0 && (+ <span>+ {blockFailures} block generation{" "}+ {blockFailures === 1 ? "failure" : "failures"} recorded.+ </span>+ )}+ {repeated.length > 0 && (+ <span>+ Recurring issue+ {repeated.length === 1 ? "" : "s"}:{" "}+ {repeated+ .map((r) => `${humanizeSignature(r.signature)} (×${r.count})`)+ .join("; ")}+ .+ </span>+ )}+ </div>+ )}+ </div>+ <div className="flex items-center gap-1">+ {hasDrift && (+ <button+ onClick={acknowledge}+ disabled={busy}+ title="Mark the current KB state as the new baseline (won't recompile pages — use the recompile button above for that)."+ className="whitespace-nowrap rounded-md border border-current px-2 py-1 text-xs font-medium hover:bg-white/40 disabled:opacity-60"+ >+ {busy ? "…" : "Mark as seen"}+ </button>+ )}+ <button+ onClick={() => setDismissed(true)}+ className="rounded p-1 text-amber-700 hover:bg-white/40 dark:text-amber-200"+ >+ <X className="h-4 w-4" />+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/BookProgressTimeline.tsx b/web/app/(workspace)/book/components/BookProgressTimeline.tsxnew file mode 100644index 000000000..1db0620d5--- /dev/null+++ b/web/app/(workspace)/book/components/BookProgressTimeline.tsx@@ -0,0 +1,332 @@+"use client";++import {+ Check,+ Loader2,+ AlertTriangle,+ Lightbulb,+ Search,+ Network,+ ScanSearch,+ BookMarked,+ LayoutList,+} from "lucide-react";+import type { BookProgress, StageId, StageView } from "@/lib/book-progress";++export interface BookProgressTimelineProps {+ progress: BookProgress;+ /** Compact mode — single-line horizontal pill strip (for reader header). */+ compact?: boolean;+ /** Mini mode — extra-thin floating chip (line + circles) for top-right. */+ mini?: boolean;+ className?: string;+}++const STAGE_ICONS: Record<StageId, React.ComponentType<{ className?: string }>> = {+ ideation: Lightbulb,+ exploration: Search,+ synthesis: Network,+ critique: ScanSearch,+ overview: BookMarked,+ compilation: LayoutList,+};++// State → tailwind tokens. Uses theme css vars so it follows light/dark mode.+const STATE_TONE = {+ pending: {+ fg: "text-[var(--muted-foreground)]",+ bg: "bg-[var(--muted)]/40",+ ring: "ring-[var(--border)]",+ bar: "bg-[var(--border)]",+ },+ running: {+ fg: "text-sky-700 dark:text-sky-200",+ bg: "bg-gradient-to-br from-sky-400/20 to-indigo-400/15",+ ring: "ring-sky-400/60",+ bar: "bg-gradient-to-r from-sky-400 to-indigo-400",+ },+ completed: {+ fg: "text-emerald-700 dark:text-emerald-200",+ bg: "bg-emerald-500/10",+ ring: "ring-emerald-400/50",+ bar: "bg-gradient-to-r from-emerald-400 to-teal-400",+ },+ error: {+ fg: "text-rose-700 dark:text-rose-200",+ bg: "bg-rose-500/10",+ ring: "ring-rose-400/60",+ bar: "bg-rose-400",+ },+} as const;++function stageProgressFraction(progress: BookProgress): number {+ const { ordered, stages } = progress;+ let value = 0;+ for (const id of ordered) {+ const s = stages[id].state;+ if (s === "completed") value += 1;+ else if (s === "running") value += 0.5;+ else if (s === "error") value += 1;+ }+ return Math.min(1, value / ordered.length);+}++function StageIcon({+ id,+ state,+}: {+ id: StageId;+ state: StageView["state"];+}) {+ const cls = "h-3.5 w-3.5";+ if (state === "running") return <Loader2 className={`${cls} animate-spin`} />;+ if (state === "completed") return <Check className={cls} />;+ if (state === "error") return <AlertTriangle className={cls} />;+ const Icon = STAGE_ICONS[id];+ return <Icon className={cls} />;+}++export default function BookProgressTimeline({+ progress,+ compact = false,+ mini = false,+ className = "",+}: BookProgressTimelineProps) {+ const { ordered, stages, message } = progress;+ const fraction = stageProgressFraction(progress);+ const activeStage =+ ordered.find((id) => stages[id].state === "running") ||+ [...ordered].reverse().find((id) => stages[id].state === "completed") ||+ ordered[0];+ const activeView = stages[activeStage];+ const counters = collectCounters(progress);++ // ── Mini mode: thin floating chip (top-right) ───────────────────────+ if (mini) {+ const allDone = fraction >= 1;+ const tooltip = `${activeView.label}${+ activeView.detail ? ` · ${activeView.detail}` : ""+ }${message && message !== activeView.label ? ` · ${message}` : ""}`;+ return (+ <div+ className={`pointer-events-auto inline-flex items-center gap-2 rounded-full border border-[var(--border)] bg-[var(--card)]/90 px-2.5 py-1 text-[11px] shadow-sm backdrop-blur ${className}`}+ title={tooltip}+ aria-label={tooltip}+ >+ <Loader2+ className={`h-3 w-3 text-[var(--muted-foreground)] ${+ allDone ? "opacity-0" : "animate-spin"+ }`}+ />+ {/* line + circles strip */}+ <div className="relative flex items-center gap-1">+ {/* connector line behind the dots */}+ <div className="pointer-events-none absolute left-1.5 right-1.5 top-1/2 -z-0 h-px -translate-y-1/2 bg-[var(--border)]" />+ {ordered.map((id) => {+ const s = stages[id].state;+ const tone = STATE_TONE[s];+ return (+ <span+ key={id}+ title={`${stages[id].label} · ${s}`}+ className={`relative z-10 inline-flex h-3 w-3 items-center justify-center rounded-full ring-1 ${tone.ring} ${tone.bg}`}+ >+ {s === "running" && (+ <span className="absolute inset-0 animate-ping rounded-full bg-sky-400/40" />+ )}+ {s === "completed" && (+ <Check className="h-2 w-2 text-emerald-600 dark:text-emerald-300" />+ )}+ {s === "error" && (+ <AlertTriangle className="h-2 w-2 text-rose-600 dark:text-rose-300" />+ )}+ </span>+ );+ })}+ </div>+ <span className="max-w-[160px] truncate text-[10.5px] text-[var(--muted-foreground)]">+ {activeView.label}+ </span>+ <span className="tabular-nums text-[10px] font-medium text-[var(--muted-foreground)]">+ {Math.round(fraction * 100)}%+ </span>+ </div>+ );+ }++ if (compact) {+ return (+ <div+ className={`flex items-center gap-3 ${className}`}+ title={message || activeView.label}+ >+ {/* Icon strip */}+ <div className="flex items-center gap-0.5">+ {ordered.map((id) => {+ const s = stages[id].state;+ const tone = STATE_TONE[s];+ return (+ <span+ key={id}+ title={`${stages[id].label} · ${s}`}+ className={`inline-flex h-5 w-5 items-center justify-center rounded-full ${tone.bg} ${tone.fg}`}+ >+ <StageIcon id={id} state={s} />+ </span>+ );+ })}+ </div>++ {/* Live caption */}+ <div className="min-w-0 flex-1 truncate text-[11px] text-[var(--muted-foreground)]">+ <span className="font-medium text-[var(--foreground)]">+ {activeView.label}+ </span>+ {activeView.detail && (+ <span className="ml-1.5 opacity-70">· {activeView.detail}</span>+ )}+ {message && message !== activeView.label && (+ <span className="ml-1.5 opacity-70">· {message}</span>+ )}+ </div>+ </div>+ );+ }++ return (+ <div+ className={`overflow-hidden rounded-2xl border border-[var(--border)] bg-gradient-to-br from-[var(--card)] to-[var(--card)]/60 shadow-sm ${className}`}+ >+ {/* ── Top hero row: animated progress bar + live caption ───────── */}+ <div className="px-4 pt-3.5">+ <div className="flex items-baseline justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ <Loader2+ className={`h-3 w-3 ${+ fraction < 1 ? "animate-spin" : "opacity-0"+ }`}+ />+ Generating book+ </div>+ <div className="mt-0.5 truncate text-sm font-medium text-[var(--foreground)]">+ {activeView.label}+ {activeView.detail && (+ <span className="ml-1.5 text-[12px] font-normal text-[var(--muted-foreground)]">+ · {activeView.detail}+ </span>+ )}+ </div>+ {message && message !== activeView.label && (+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">+ {message}+ </div>+ )}+ </div>+ <div className="text-right text-[11px] font-medium text-[var(--muted-foreground)] tabular-nums">+ {Math.round(fraction * 100)}%+ </div>+ </div>++ {/* Continuous gradient progress bar */}+ <div className="mt-3 h-1.5 w-full overflow-hidden rounded-full bg-[var(--muted)]/60">+ <div+ className="h-full rounded-full bg-gradient-to-r from-sky-400 via-indigo-400 to-emerald-400 transition-all duration-700 ease-out"+ style={{ width: `${Math.max(2, fraction * 100)}%` }}+ />+ </div>+ </div>++ {/* ── Segmented stage strip ──────────────────────────────────── */}+ <div className="px-3 pb-3 pt-3">+ <div className="grid grid-cols-6 gap-1.5">+ {ordered.map((id) => {+ const stage = stages[id];+ const tone = STATE_TONE[stage.state];+ const isActive = stage.state === "running";+ return (+ <div+ key={id}+ title={`${stage.label} — ${stage.description}`}+ className={`group relative flex items-center gap-1.5 rounded-lg px-1.5 py-1.5 ring-1 transition-all ${+ isActive+ ? `${tone.bg} ${tone.ring}`+ : `${tone.bg} ${tone.ring} opacity-90`+ }`}+ >+ <span+ className={`inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full ${tone.bg} ${tone.fg}`}+ >+ <StageIcon id={id} state={stage.state} />+ </span>+ <div className="min-w-0 flex-1">+ <div+ className={`truncate text-[11px] font-medium ${tone.fg}`}+ >+ {stage.label}+ </div>+ </div>+ </div>+ );+ })}+ </div>++ {counters.length > 0 && (+ <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-[var(--border)] pt-2.5 text-[11px]">+ {counters.map((item) => (+ <div+ key={item.label}+ className="inline-flex items-baseline gap-1 text-[var(--muted-foreground)]"+ >+ <span className="font-semibold tabular-nums text-[var(--foreground)]">+ {item.value}+ </span>+ <span className="opacity-80">{item.label}</span>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}++function collectCounters(+ progress: BookProgress,+): { label: string; value: string | number }[] {+ const items: { label: string; value: string | number }[] = [];+ if (progress.exploration.queryCount > 0) {+ items.push({ label: "queries", value: progress.exploration.queryCount });+ }+ if (progress.exploration.chunkCount > 0) {+ items.push({ label: "chunks", value: progress.exploration.chunkCount });+ }+ if (progress.synthesis.chapterCount > 0) {+ items.push({ label: "chapters", value: progress.synthesis.chapterCount });+ }+ if (progress.synthesis.conceptNodes > 0) {+ items.push({+ label: "concepts",+ value: `${progress.synthesis.conceptNodes}/${progress.synthesis.conceptEdges}`,+ });+ }+ if (progress.compilation.blocksReady > 0) {+ items.push({+ label: "blocks ready",+ value: progress.compilation.blocksReady,+ });+ }+ if (progress.compilation.pagesReady > 0) {+ items.push({+ label: "pages ready",+ value: progress.compilation.pagesReady,+ });+ }+ if (progress.compilation.blocksError > 0) {+ items.push({+ label: "block errors",+ value: progress.compilation.blocksError,+ });+ }+ return items;+}diff --git a/web/app/(workspace)/book/components/BookSidebar.tsx b/web/app/(workspace)/book/components/BookSidebar.tsxnew file mode 100644index 000000000..3162a45eb--- /dev/null+++ b/web/app/(workspace)/book/components/BookSidebar.tsx@@ -0,0 +1,138 @@+"use client";++import { Plus, Library, Loader2, Trash2, Compass } from "lucide-react";+import type { Book, Page } from "@/lib/book-types";++const STATUS_LABEL: Record<string, string> = {+ pending: "Queued",+ planning: "Planning",+ generating: "Compiling",+ ready: "Ready",+ partial: "Partial",+ error: "Failed",+};++export interface BookSidebarProps {+ books: Book[];+ loadingBooks: boolean;+ selectedBookId: string | null;+ onSelectBook: (id: string | null) => void;+ onNewBook: () => void;+ onDeleteBook: (id: string) => void;+ pages?: Page[];+ selectedPageId?: string | null;+ onSelectPage?: (id: string) => void;+}++export default function BookSidebar({+ books,+ loadingBooks,+ selectedBookId,+ onSelectBook,+ onNewBook,+ onDeleteBook,+ pages = [],+ selectedPageId = null,+ onSelectPage,+}: BookSidebarProps) {+ return (+ <aside className="flex h-full w-[232px] flex-col gap-3 border-r border-[var(--border)] bg-[var(--card)]/40 px-3 py-4">+ <button+ onClick={onNewBook}+ className="inline-flex items-center justify-center gap-2 rounded-xl bg-[var(--primary)] px-3 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90"+ >+ <Plus className="h-4 w-4" /> New book+ </button>++ <section className="flex-1 overflow-y-auto">+ <div className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ <Library className="h-3.5 w-3.5" /> My Books+ </div>+ {loadingBooks ? (+ <div className="flex items-center gap-2 px-2 py-3 text-xs text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" /> Loading…+ </div>+ ) : books.length === 0 ? (+ <div className="rounded-md border border-dashed border-[var(--border)] px-2 py-3 text-xs text-[var(--muted-foreground)]">+ No books yet. Create one to get started.+ </div>+ ) : (+ <ul className="space-y-1">+ {books.map((book) => {+ const active = book.id === selectedBookId;+ return (+ <li key={book.id}>+ <div+ className={`group flex items-start gap-2 rounded-lg px-2 py-2 text-sm ${+ active+ ? "bg-[var(--primary)]/10 text-[var(--foreground)]"+ : "hover:bg-[var(--muted)]/40 text-[var(--foreground)]"+ }`}+ >+ <button+ onClick={() => onSelectBook(book.id)}+ className="flex flex-1 flex-col gap-0.5 text-left"+ >+ <span className="truncate font-medium">{book.title || "Untitled book"}</span>+ <span className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {book.status} · {book.chapter_count || 0} chapters+ </span>+ </button>+ <button+ onClick={() => onDeleteBook(book.id)}+ className="invisible rounded-md p-1 text-rose-500 hover:bg-rose-50 group-hover:visible dark:hover:bg-rose-500/10"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </div>+ </li>+ );+ })}+ </ul>+ )}+ </section>++ {selectedBookId && pages.length > 0 && (+ <section>+ <div className="mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ Chapters+ </div>+ <ul className="space-y-1">+ {pages.map((page) => {+ const active = page.id === selectedPageId;+ const isOverview = page.content_type === "overview";+ return (+ <li key={page.id}>+ <button+ onClick={() => onSelectPage?.(page.id)}+ className={`flex w-full items-start justify-between gap-2 rounded-md px-2 py-1.5 text-left text-xs ${+ active+ ? "bg-[var(--primary)]/15 text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"+ } ${+ isOverview+ ? "border border-dashed border-[var(--border)]"+ : ""+ }`}+ >+ <span className="flex min-w-0 items-start gap-1.5">+ {isOverview && (+ <Compass className="mt-[1px] h-3 w-3 shrink-0 text-[var(--primary)]" />+ )}+ <span className="line-clamp-2">+ {page.title || "Untitled"}+ </span>+ </span>+ <span className="shrink-0 rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {STATUS_LABEL[page.status] || page.status}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ </section>+ )}+ </aside>+ );+}diff --git a/web/app/(workspace)/book/components/PageOutlineNav.tsx b/web/app/(workspace)/book/components/PageOutlineNav.tsxnew file mode 100644index 000000000..9db3f73e6--- /dev/null+++ b/web/app/(workspace)/book/components/PageOutlineNav.tsx@@ -0,0 +1,334 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import {+ AlertCircle,+ AlignLeft,+ BookOpen,+ ChevronRight,+ Code2,+ FileText,+ Film,+ Image as ImageIcon,+ Layers,+ ListChecks,+ Loader2,+ type LucideIcon,+ MessageCircle,+ MousePointerClick,+ Sparkles,+ Sticker,+} from "lucide-react";++import type { Block, BlockType, BlockStatus } from "@/lib/book-types";++const TYPE_ICON: Record<BlockType, LucideIcon> = {+ text: AlignLeft,+ section: BookOpen,+ callout: Sparkles,+ quiz: ListChecks,+ user_note: FileText,+ figure: ImageIcon,+ interactive: MousePointerClick,+ animation: Film,+ code: Code2,+ timeline: Layers,+ flash_cards: Sticker,+ deep_dive: MessageCircle,+ concept_graph: Layers,+};++const TYPE_LABEL_EN: Record<BlockType, string> = {+ text: "Text",+ section: "Section",+ callout: "Callout",+ quiz: "Quiz",+ user_note: "Note",+ figure: "Figure",+ interactive: "Interactive",+ animation: "Animation",+ code: "Code",+ timeline: "Timeline",+ flash_cards: "Flash cards",+ deep_dive: "Deep dive",+ concept_graph: "Concept graph",+};++const TYPE_LABEL_ZH: Record<BlockType, string> = {+ text: "文本",+ section: "章节",+ callout: "要点",+ quiz: "测验",+ user_note: "笔记",+ figure: "图示",+ interactive: "交互",+ animation: "动画",+ code: "代码",+ timeline: "时间线",+ flash_cards: "闪卡",+ deep_dive: "深入",+ concept_graph: "概念图",+};++const HEADER_EN = "On this page";+const HEADER_ZH = "本页内容";++const COLLAPSE_TIP_EN = "Hide outline";+const COLLAPSE_TIP_ZH = "隐藏目录";+const EXPAND_TIP_EN = "Show outline";+const EXPAND_TIP_ZH = "展开目录";++function shortLabel(block: Block, fallback: string): string {+ const title = (block.title || "").trim();+ if (title) return title;+ const params = (block.params || {}) as Record<string, unknown>;+ const focus = typeof params.focus === "string" ? params.focus.trim() : "";+ if (focus) return focus;+ const role = typeof params.role === "string" ? params.role.trim() : "";+ if (role) return `${fallback} · ${role}`;+ const variant = typeof params.variant === "string" ? params.variant.trim() : "";+ if (variant) return `${fallback} · ${variant}`;+ return fallback;+}++function statusDotClass(status: BlockStatus): string {+ switch (status) {+ case "ready":+ return "bg-emerald-500";+ case "generating":+ return "bg-amber-400 animate-pulse";+ case "pending":+ return "bg-[var(--muted-foreground)]/40";+ case "error":+ return "bg-rose-500";+ case "hidden":+ return "bg-[var(--muted-foreground)]/20";+ default:+ return "bg-[var(--muted-foreground)]/40";+ }+}++export interface PageOutlineNavProps {+ blocks: Block[];+ scrollContainer?: HTMLElement | null;+ language?: string;+ /** Stable identifier (e.g. page id) used to reset collapsed state when the page changes. */+ resetKey?: string;+}++export default function PageOutlineNav({+ blocks,+ scrollContainer,+ language,+ resetKey,+}: PageOutlineNavProps) {+ const isZh = (language || "").toLowerCase().startsWith("zh");+ const labelMap = isZh ? TYPE_LABEL_ZH : TYPE_LABEL_EN;+ const headerText = isZh ? HEADER_ZH : HEADER_EN;+ const collapseTip = isZh ? COLLAPSE_TIP_ZH : COLLAPSE_TIP_EN;+ const expandTip = isZh ? EXPAND_TIP_ZH : EXPAND_TIP_EN;++ // Default: expanded. Reset whenever the page changes.+ const [collapsed, setCollapsed] = useState(false);+ useEffect(() => {+ setCollapsed(false);+ }, [resetKey]);++ // Track which block is currently in view for active highlight.+ const [activeId, setActiveId] = useState<string | null>(null);+ const visibleBlocks = useMemo(+ () => blocks.filter((b) => b.status !== "hidden"),+ [blocks],+ );++ useEffect(() => {+ if (!scrollContainer || visibleBlocks.length === 0) return;+ const ids = visibleBlocks.map((b) => `block-${b.id}`);+ const elements = ids+ .map((id) => document.getElementById(id))+ .filter((el): el is HTMLElement => !!el);+ if (elements.length === 0) return;++ const observer = new IntersectionObserver(+ (entries) => {+ // Pick the entry closest to the top of the viewport that is intersecting.+ const intersecting = entries+ .filter((e) => e.isIntersecting)+ .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);+ if (intersecting.length > 0) {+ const id = intersecting[0].target.id.replace(/^block-/, "");+ setActiveId(id);+ }+ },+ {+ root: scrollContainer,+ rootMargin: "-20% 0px -65% 0px",+ threshold: 0,+ },+ );+ elements.forEach((el) => observer.observe(el));+ return () => observer.disconnect();+ }, [scrollContainer, visibleBlocks]);++ const handleJump = (blockId: string) => {+ const el = document.getElementById(`block-${blockId}`);+ if (!el) return;+ setActiveId(blockId);+ el.scrollIntoView({ behavior: "smooth", block: "start" });+ };++ if (visibleBlocks.length === 0) return null;++ // Smooth easing tuned to feel natural — same curve framer-motion uses for+ // its `easeOut` token, just expressed as a CSS bezier.+ const EASE = "cubic-bezier(0.22, 1, 0.36, 1)";++ return (+ <div+ className="pointer-events-none absolute right-0 top-1/2 z-20 -translate-y-1/2"+ style={{ transition: `transform 320ms ${EASE}` }}+ >+ {/* Single morphing card. Width / border-radius / x-translate transition+ between slim-handle and full-nav, while the inner nav drives the+ card's height naturally via max-height (so it never balloons past+ its own content). */}+ <div+ className={[+ "pointer-events-auto relative overflow-hidden border border-[var(--border)] bg-[var(--card)]/85 shadow-md backdrop-blur",+ collapsed ? "w-6 rounded-l-md border-r-0" : "w-56 rounded-xl",+ ].join(" ")}+ style={{+ transition: [+ `width 320ms ${EASE}`,+ `border-radius 320ms ${EASE}`,+ `transform 320ms ${EASE}`,+ `box-shadow 200ms ease-out`,+ ].join(", "),+ transform: collapsed ? "translateX(0)" : "translateX(-12px)",+ }}+ >+ {/* ── Expanded content: full outline list. Stays in flow so its+ height drives the parent card; collapses to 64px (matches+ handle height) via max-height when hidden. The fixed inner+ width keeps content laid out during the width transition; the+ parent overflow:hidden clips it cleanly. */}+ <nav+ aria-label={headerText}+ aria-hidden={collapsed}+ className={[+ "flex w-56 flex-col text-[12.5px]",+ collapsed ? "pointer-events-none" : "pointer-events-auto",+ ].join(" ")}+ style={{+ maxHeight: collapsed ? "64px" : "min(70vh, 520px)",+ opacity: collapsed ? 0 : 1,+ transform: collapsed ? "translateX(8px)" : "translateX(0)",+ transition: collapsed+ ? `max-height 320ms ${EASE}, opacity 140ms ease-out, transform 220ms ${EASE}`+ : `max-height 320ms ${EASE}, opacity 220ms ease-out 100ms, transform 320ms ${EASE} 60ms`,+ }}+ >+ <div className="flex items-center justify-between gap-2 border-b border-[var(--border)] px-3 py-2">+ <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">+ <Layers className="h-3 w-3" />+ <span>{headerText}</span>+ </div>+ <button+ type="button"+ onClick={() => setCollapsed(true)}+ title={collapseTip}+ aria-label={collapseTip}+ className="rounded p-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ >+ <ChevronRight className="h-3.5 w-3.5" />+ </button>+ </div>++ <ol className="flex-1 overflow-y-auto px-1.5 py-1.5">+ {visibleBlocks.map((block, idx) => {+ const Icon = TYPE_ICON[block.type] || FileText;+ const fallbackLabel = labelMap[block.type] || block.type;+ const label = shortLabel(block, fallbackLabel);+ const isActive = block.id === activeId;+ const isError = block.status === "error";+ const isLoading =+ block.status === "pending" || block.status === "generating";++ return (+ <li key={block.id}>+ <button+ type="button"+ onClick={() => handleJump(block.id)}+ className={[+ "group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150",+ isActive+ ? "bg-[var(--primary)]/10 text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)]",+ ].join(" ")}+ >+ <span+ className={[+ "shrink-0 transition-colors",+ isActive+ ? "text-[var(--primary)]"+ : "text-[var(--muted-foreground)] group-hover:text-[var(--foreground)]",+ ].join(" ")}+ >+ {isLoading ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : isError ? (+ <AlertCircle className="h-3.5 w-3.5 text-rose-500" />+ ) : (+ <Icon className="h-3.5 w-3.5" />+ )}+ </span>+ <span className="flex min-w-0 flex-1 items-center gap-1.5">+ <span className="shrink-0 text-[10.5px] tabular-nums text-[var(--muted-foreground)]/70">+ {String(idx + 1).padStart(2, "0")}+ </span>+ <span+ className="truncate"+ title={`${fallbackLabel} · ${label}`}+ >+ {label}+ </span>+ </span>+ <span+ className={[+ "shrink-0 h-1.5 w-1.5 rounded-full",+ statusDotClass(block.status),+ ].join(" ")}+ />+ </button>+ </li>+ );+ })}+ </ol>+ </nav>++ {/* ── Collapsed handle: chevron-only button overlays the same card */}+ <button+ type="button"+ onClick={() => setCollapsed(false)}+ title={expandTip}+ aria-label={expandTip}+ aria-hidden={!collapsed}+ tabIndex={collapsed ? 0 : -1}+ className={[+ "group absolute inset-0 flex items-center justify-center text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]",+ collapsed ? "pointer-events-auto" : "pointer-events-none",+ ].join(" ")}+ style={{+ opacity: collapsed ? 1 : 0,+ transform: collapsed ? "translateX(0)" : "translateX(-6px)",+ transition: collapsed+ ? `opacity 220ms ease-out 120ms, transform 320ms ${EASE} 80ms`+ : `opacity 140ms ease-out, transform 220ms ${EASE}`,+ }}+ >+ <ChevronRight className="h-3.5 w-3.5 rotate-180 transition-transform duration-200 group-hover:-translate-x-0.5" />+ </button>+ </div>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/PageReader.tsx b/web/app/(workspace)/book/components/PageReader.tsxnew file mode 100644index 000000000..24f2902f9--- /dev/null+++ b/web/app/(workspace)/book/components/PageReader.tsx@@ -0,0 +1,265 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Loader2, RefreshCcw, Plus, ChevronDown, ChevronUp } from "lucide-react";+import type { Block, BlockType, Page } from "@/lib/book-types";+import BlockRenderer from "./blocks/BlockRenderer";+import PageOutlineNav from "./PageOutlineNav";++const INSERTABLE_TYPES: BlockType[] = [+ "text",+ "callout",+ "quiz",+ "code",+ "timeline",+ "flash_cards",+ "figure",+ "interactive",+ "animation",+ "deep_dive",+ "user_note",+];++export interface PageReaderProps {+ page: Page | null;+ onRegenerateBlock?: (block: Block) => void;+ onDeleteBlock?: (block: Block) => void;+ onMoveBlock?: (block: Block, direction: "up" | "down") => void;+ onChangeBlockType?: (block: Block, newType: BlockType) => void;+ onInsertBlock?: (block_type: BlockType) => Promise<void> | void;+ onDeepDive?: (topic: string, blockId: string) => Promise<void> | void;+ onQuizAttempt?: (+ block: Block,+ args: { questionId?: string; userAnswer?: string; isCorrect: boolean },+ ) => void;+ onRecompile?: () => void;+ pendingDeepDiveTopic?: string | null;+ loading?: boolean;+ bookId?: string;+ bookLanguage?: string;+}++export default function PageReader({+ page,+ onRegenerateBlock,+ onDeleteBlock,+ onMoveBlock,+ onChangeBlockType,+ onInsertBlock,+ onDeepDive,+ onQuizAttempt,+ onRecompile,+ pendingDeepDiveTopic,+ loading = false,+ bookId,+ bookLanguage,+}: PageReaderProps) {+ const [showInsertMenu, setShowInsertMenu] = useState(false);+ const [inserting, setInserting] = useState(false);+ const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(+ null,+ );++ // ── Collapsible header ──────────────────────────────────────────────+ // Default expanded; collapse on user-initiated scroll-down past threshold;+ // re-expand when user returns to the very top. Manual toggle via button.+ const [headerCollapsed, setHeaderCollapsed] = useState(false);+ const [userToggled, setUserToggled] = useState(false);+ const lastScrollTopRef = useRef(0);++ // Reset header + scroll bookkeeping whenever we load a new page.+ useEffect(() => {+ setHeaderCollapsed(false);+ setUserToggled(false);+ lastScrollTopRef.current = 0;+ }, [page?.id]);++ useEffect(() => {+ if (!scrollContainer) return;+ const handler = () => {+ const top = scrollContainer.scrollTop;+ const last = lastScrollTopRef.current;+ lastScrollTopRef.current = top;+ // Snap back to expanded when user scrolls all the way to the top,+ // even if they previously toggled manually.+ if (top <= 8) {+ setHeaderCollapsed(false);+ setUserToggled(false);+ return;+ }+ if (userToggled) return;+ // Collapse on downward scroll past a small threshold.+ if (top > last && top > 80) {+ setHeaderCollapsed(true);+ }+ };+ scrollContainer.addEventListener("scroll", handler, { passive: true });+ return () => scrollContainer.removeEventListener("scroll", handler);+ }, [scrollContainer, userToggled]);++ if (!page) {+ return (+ <div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">+ Select a chapter to start reading.+ </div>+ );+ }++ const isZh = (bookLanguage || "").toLowerCase().startsWith("zh");+ const expandTip = isZh ? "展开标题栏" : "Expand header";+ const collapseTip = isZh ? "折叠标题栏" : "Collapse header";++ return (+ // The outer container is `relative` so the floating outline nav can+ // anchor to the viewport-stable column instead of being trapped inside+ // the scrollable inner div.+ <div className="relative flex h-full flex-col">+ <header+ className={[+ "border-b border-[var(--border)] bg-[var(--card)]/60 backdrop-blur transition-all duration-200 ease-out",+ headerCollapsed ? "px-8 py-2" : "px-8 py-5",+ ].join(" ")}+ >+ <div className="mx-auto flex w-full max-w-[78ch] items-start justify-between gap-3">+ <div className="min-w-0 flex-1">+ <h1+ className={[+ "font-semibold leading-tight tracking-tight text-[var(--foreground)] transition-all duration-200",+ headerCollapsed ? "truncate text-[15px]" : "text-[26px]",+ ].join(" ")}+ title={page.title || "Untitled chapter"}+ >+ {page.title || "Untitled chapter"}+ </h1>+ {!headerCollapsed && page.learning_objectives.length > 0 && (+ <ul className="mt-3 space-y-0.5 text-[12.5px] text-[var(--muted-foreground)]">+ {page.learning_objectives.map((obj, idx) => (+ <li key={idx}>• {obj}</li>+ ))}+ </ul>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {!headerCollapsed && (+ <span className="rounded-full bg-[var(--muted)] px-2.5 py-0.5 text-[11px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {page.status}+ </span>+ )}+ {!headerCollapsed && onRecompile && (+ <button+ onClick={onRecompile}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"+ >+ <RefreshCcw className="h-3.5 w-3.5" /> Recompile+ </button>+ )}+ <button+ type="button"+ onClick={() => {+ setHeaderCollapsed((v) => !v);+ setUserToggled(true);+ }}+ title={headerCollapsed ? expandTip : collapseTip}+ aria-label={headerCollapsed ? expandTip : collapseTip}+ className="inline-flex h-6 w-6 items-center justify-center rounded-md text-[var(--muted-foreground)] hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ >+ {headerCollapsed ? (+ <ChevronDown className="h-3.5 w-3.5" />+ ) : (+ <ChevronUp className="h-3.5 w-3.5" />+ )}+ </button>+ </div>+ </div>+ </header>++ <div+ ref={setScrollContainer}+ className="flex-1 overflow-y-auto px-8 py-8"+ >+ {loading && page.blocks.length === 0 ? (+ <div className="mx-auto flex w-full max-w-[78ch] items-center gap-2 text-sm text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ Compiling page…+ </div>+ ) : (+ <article className="mx-auto flex w-full max-w-[78ch] flex-col gap-6 [&>:first-child]:mt-0">+ {page.blocks.map((block) => (+ <div+ key={block.id}+ id={`block-${block.id}`}+ className="scroll-mt-6"+ >+ <BlockRenderer+ block={block}+ onRegenerate={onRegenerateBlock}+ onDelete={onDeleteBlock}+ onMove={onMoveBlock}+ onChangeType={onChangeBlockType}+ onDeepDive={onDeepDive}+ onQuizAttempt={onQuizAttempt}+ pendingDeepDiveTopic={pendingDeepDiveTopic}+ bookId={bookId}+ currentPageId={page.id}+ bookLanguage={bookLanguage}+ />+ </div>+ ))}+ {page.blocks.length === 0 && (+ <div className="text-sm text-[var(--muted-foreground)]">+ This page has no blocks yet.+ </div>+ )}++ {onInsertBlock && (+ <div className="relative mt-2 flex justify-center">+ <button+ onClick={() => setShowInsertMenu((v) => !v)}+ disabled={inserting}+ className="inline-flex items-center gap-1.5 rounded-full border border-dashed border-[var(--border)] bg-[var(--card)] px-3 py-1.5 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/50 hover:text-[var(--primary)] disabled:opacity-60"+ >+ {inserting ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Plus className="h-3.5 w-3.5" />+ )}+ Insert block+ </button>+ {showInsertMenu && (+ <div className="absolute top-full mt-1 z-10 grid w-72 grid-cols-2 gap-1 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 shadow-lg">+ {INSERTABLE_TYPES.map((t) => (+ <button+ key={t}+ onClick={async () => {+ setShowInsertMenu(false);+ setInserting(true);+ try {+ await onInsertBlock(t);+ } finally {+ setInserting(false);+ }+ }}+ className="rounded px-2 py-1 text-left text-xs text-[var(--foreground)] hover:bg-[var(--background)]"+ >+ {t}+ </button>+ ))}+ </div>+ )}+ </div>+ )}+ </article>+ )}+ </div>++ {/* Floating outline lives outside the scroll container so it stays+ pinned to the viewport regardless of page scrolling. */}+ <PageOutlineNav+ blocks={page.blocks}+ scrollContainer={scrollContainer}+ language={bookLanguage}+ resetKey={page.id}+ />+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/SpineEditor.tsx b/web/app/(workspace)/book/components/SpineEditor.tsxnew file mode 100644index 000000000..b924fa906--- /dev/null+++ b/web/app/(workspace)/book/components/SpineEditor.tsx@@ -0,0 +1,230 @@+"use client";++import { ArrowDown, ArrowUp, Plus, Trash2, CheckCircle2, Loader2 } from "lucide-react";+import { useState } from "react";+import type { Chapter, ContentType, Spine } from "@/lib/book-types";++/**+ * Each chapter declares a *content type* — a hint to the SectionArchitect+ * about what kind of block sequence to plan (e.g. theory chapters get+ * Section + Figure + Quiz; practice chapters get more Quiz + Code).+ *+ * `overview` is intentionally excluded — it's reserved for the engine-injected+ * first chapter (the table of contents + concept map).+ */+interface ContentTypeOption {+ value: ContentType;+ label: string;+ description: string;+}++const CONTENT_TYPE_OPTIONS: ContentTypeOption[] = [+ {+ value: "theory",+ label: "Theory",+ description: "Long-form explanation with diagrams + flash cards + a quiz.",+ },+ {+ value: "derivation",+ label: "Derivation",+ description: "Step-by-step derivation, often with animation + verifying code.",+ },+ {+ value: "history",+ label: "History",+ description: "Narrative + timeline + period image, ends with a recap quiz.",+ },+ {+ value: "practice",+ label: "Practice",+ description: "Quiz-heavy chapter with a runnable code scaffold + explanation.",+ },+ {+ value: "concept",+ label: "Concept",+ description: "Definition + figure + flash cards + common-pitfall callout.",+ },+];++export interface SpineEditorProps {+ spine: Spine;+ onConfirm: (spine: Spine) => void | Promise<void>;+ loading?: boolean;+}++export default function SpineEditor({ spine, onConfirm, loading = false }: SpineEditorProps) {+ const [chapters, setChapters] = useState<Chapter[]>(spine.chapters);++ const updateChapter = (idx: number, patch: Partial<Chapter>) => {+ setChapters((prev) =>+ prev.map((c, i) => (i === idx ? { ...c, ...patch } : c)),+ );+ };++ const move = (idx: number, dir: -1 | 1) => {+ setChapters((prev) => {+ const next = [...prev];+ const target = idx + dir;+ if (target < 0 || target >= next.length) return prev;+ [next[idx], next[target]] = [next[target], next[idx]];+ return next.map((c, i) => ({ ...c, order: i }));+ });+ };++ const remove = (idx: number) => {+ setChapters((prev) => prev.filter((_, i) => i !== idx).map((c, i) => ({ ...c, order: i })));+ };++ const addChapter = () => {+ setChapters((prev) => [+ ...prev,+ {+ id: `ch_new_${prev.length + 1}_${Date.now().toString(36)}`,+ title: "New chapter",+ learning_objectives: [],+ content_type: "theory",+ source_anchors: [],+ prerequisites: [],+ page_ids: [],+ summary: "",+ order: prev.length,+ },+ ]);+ };++ const handleConfirm = async () => {+ const cleaned = chapters+ .filter((c) => c.title.trim())+ .map((c, i) => ({ ...c, order: i }));+ await onConfirm({ ...spine, chapters: cleaned });+ };++ return (+ <div className="flex h-full flex-col">+ <header className="border-b border-[var(--border)] bg-[var(--card)]/60 px-6 py-4">+ <h2 className="text-lg font-semibold text-[var(--foreground)]">Review the chapter spine</h2>+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">+ Reorder, rename, or remove chapters before the book starts compiling.+ </p>+ </header>++ <div className="flex-1 overflow-y-auto px-6 py-4">+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-3">+ {chapters.map((chapter, idx) => (+ <div+ key={chapter.id}+ className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm"+ >+ <div className="flex items-start justify-between gap-2">+ <input+ value={chapter.title}+ onChange={(e) => updateChapter(idx, { title: e.target.value })}+ className="flex-1 rounded-lg border border-transparent bg-transparent px-2 py-1 text-base font-semibold text-[var(--foreground)] outline-none focus:border-[var(--border)]"+ />+ <div className="flex items-center gap-1">+ <button+ onClick={() => move(idx, -1)}+ disabled={idx === 0}+ className="rounded-md border border-[var(--border)] p-1 text-[var(--muted-foreground)] disabled:opacity-30"+ >+ <ArrowUp className="h-3.5 w-3.5" />+ </button>+ <button+ onClick={() => move(idx, 1)}+ disabled={idx === chapters.length - 1}+ className="rounded-md border border-[var(--border)] p-1 text-[var(--muted-foreground)] disabled:opacity-30"+ >+ <ArrowDown className="h-3.5 w-3.5" />+ </button>+ <button+ onClick={() => remove(idx)}+ className="rounded-md border border-rose-300/60 p-1 text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </div>+ </div>++ <div className="mt-3 grid gap-3 sm:grid-cols-2">+ <label className="text-xs text-[var(--muted-foreground)]">+ <span className="flex items-center gap-1">+ Content type+ <span+ className="cursor-help text-[10px] opacity-60"+ title="Hint that drives the chapter's block plan (text length, whether to include diagrams / quizzes / code, etc.)."+ >+ ⓘ+ </span>+ </span>+ <select+ value={chapter.content_type}+ onChange={(e) =>+ updateChapter(idx, { content_type: e.target.value as ContentType })+ }+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-sm text-[var(--foreground)]"+ >+ {CONTENT_TYPE_OPTIONS.map((opt) => (+ <option key={opt.value} value={opt.value}>+ {opt.label}+ </option>+ ))}+ </select>+ <span className="mt-1 block text-[11px] leading-snug text-[var(--muted-foreground)]/80">+ {CONTENT_TYPE_OPTIONS.find(+ (o) => o.value === chapter.content_type,+ )?.description ||+ "Hint for the architect about what blocks to plan."}+ </span>+ </label>+ <label className="text-xs text-[var(--muted-foreground)]">+ Summary+ <input+ value={chapter.summary}+ onChange={(e) => updateChapter(idx, { summary: e.target.value })}+ placeholder="Optional one-line description"+ className="mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ </div>++ <label className="mt-3 block text-xs text-[var(--muted-foreground)]">+ Learning objectives (one per line)+ <textarea+ value={chapter.learning_objectives.join("\n")}+ onChange={(e) =>+ updateChapter(idx, {+ learning_objectives: e.target.value+ .split("\n")+ .map((s) => s.trim())+ .filter(Boolean),+ })+ }+ rows={3}+ className="mt-1 w-full resize-none rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-sm text-[var(--foreground)]"+ />+ </label>+ </div>+ ))}++ <button+ onClick={addChapter}+ className="inline-flex items-center justify-center gap-1.5 rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)] px-3 py-2 text-sm font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"+ >+ <Plus className="h-4 w-4" /> Add chapter+ </button>+ </div>+ </div>++ <footer className="flex items-center justify-end gap-3 border-t border-[var(--border)] bg-[var(--card)]/60 px-6 py-3">+ <button+ onClick={handleConfirm}+ disabled={loading}+ className="inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"+ >+ {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle2 className="h-4 w-4" />}+ Confirm spine & start compiling+ </button>+ </footer>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx b/web/app/(workspace)/book/components/blocks/AnimationBlock.tsxnew file mode 100644index 000000000..d4fdd9eb3--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx@@ -0,0 +1,60 @@+"use client";++import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";++export interface AnimationBlockProps {+ block: Block;+}++interface Artifact {+ type?: string;+ url?: string;+ filename?: string;+ content_type?: string;+ label?: string;+}++export default function AnimationBlock({ block }: AnimationBlockProps) {+ const payload = (block.payload || {}) as Record<string, unknown>;+ const videoUrl = String(payload.video_url || "");+ const summary = String(payload.summary || "");+ const description = String(payload.description || "");+ const artifacts = (payload.artifacts as Artifact[] | undefined) || [];++ if (!videoUrl && artifacts.length === 0) {+ return (+ <div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 p-4 text-xs italic text-[var(--muted-foreground)]">+ (Animation payload is empty)+ </div>+ );+ }++ const primary = videoUrl || artifacts[0]?.url || "";+ const isVideo =+ primary.endsWith(".mp4") ||+ primary.endsWith(".webm") ||+ artifacts.some((a) => (a.content_type || "").startsWith("video/"));++ return (+ <figure className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-3 shadow-sm">+ <div className="overflow-hidden rounded-xl bg-black">+ {isVideo ? (+ <video+ src={primary}+ controls+ className="h-auto w-full"+ preload="metadata"+ />+ ) : (+ <img src={primary} alt={description || "Animation frame"} className="h-auto w-full" />+ )}+ </div>+ {(summary || description) && (+ <figcaption className="mt-3 text-xs leading-snug text-[var(--muted-foreground)]">+ <MarkdownRenderer content={summary || description} variant="default" />+ </figcaption>+ )}+ </figure>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsxnew file mode 100644index 000000000..d11b152fa--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/BlockRenderer.tsx@@ -0,0 +1,248 @@+"use client";++import { useState } from "react";+import {+ AlertTriangle,+ Loader2,+ RefreshCw,+ Trash2,+ ArrowUp,+ ArrowDown,+ Replace,+} from "lucide-react";+import type { Block, BlockType } from "@/lib/book-types";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";++import TextBlock from "./TextBlock";+import CalloutBlock from "./CalloutBlock";+import QuizBlock from "./QuizBlock";+import UserNoteBlock from "./UserNoteBlock";+import FigureBlock from "./FigureBlock";+import InteractiveBlock from "./InteractiveBlock";+import AnimationBlock from "./AnimationBlock";+import CodeBlock from "./CodeBlock";+import TimelineBlock from "./TimelineBlock";+import FlashCardsBlock from "./FlashCardsBlock";+import DeepDiveBlock from "./DeepDiveBlock";+import ConceptGraphBlock from "./ConceptGraphBlock";+import SectionBlock from "./SectionBlock";+import PlaceholderBlock from "./PlaceholderBlock";++const CHANGEABLE_TYPES: BlockType[] = [+ "text",+ "section",+ "callout",+ "quiz",+ "code",+ "timeline",+ "flash_cards",+ "figure",+ "interactive",+ "animation",+ "deep_dive",+];++export interface BlockRendererProps {+ block: Block;+ onRegenerate?: (block: Block) => void;+ onDelete?: (block: Block) => void;+ onMove?: (block: Block, direction: "up" | "down") => void;+ onChangeType?: (block: Block, newType: BlockType) => void;+ onDeepDive?: (topic: string, blockId: string) => Promise<void> | void;+ onQuizAttempt?: (+ block: Block,+ args: { questionId?: string; userAnswer?: string; isCorrect: boolean },+ ) => void;+ pendingDeepDiveTopic?: string | null;+ bookId?: string;+ currentPageId?: string;+ bookLanguage?: string;+}++export default function BlockRenderer({+ block,+ onRegenerate,+ onDelete,+ onMove,+ onChangeType,+ onDeepDive,+ onQuizAttempt,+ pendingDeepDiveTopic,+ bookId,+ currentPageId,+ bookLanguage,+}: BlockRendererProps) {+ const [showTypeMenu, setShowTypeMenu] = useState(false);++ if (block.status === "pending" || block.status === "generating") {+ return (+ <div className="flex items-center gap-2 rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)] px-4 py-3 text-sm text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ <span>Generating {block.type}…</span>+ </div>+ );+ }+ if (block.status === "error") {+ return (+ <div className="rounded-2xl border border-rose-300/60 bg-rose-50 px-4 py-3 text-sm text-rose-900 dark:border-rose-500/40 dark:bg-rose-500/10 dark:text-rose-100">+ <div className="mb-1 flex items-center gap-2 font-medium">+ <AlertTriangle className="h-4 w-4" />+ {block.type} block failed+ </div>+ <div className="text-xs opacity-80">{block.error || "Unknown error"}</div>+ {onRegenerate && (+ <button+ onClick={() => onRegenerate(block)}+ className="mt-2 inline-flex rounded-md border border-rose-400/60 bg-white/40 px-2 py-1 text-xs font-medium hover:bg-white/60 dark:bg-white/10"+ >+ Retry+ </button>+ )}+ </div>+ );+ }++ let body: React.ReactNode;+ switch (block.type) {+ case "text":+ body = <TextBlock block={block} />;+ break;+ case "section":+ body = <SectionBlock block={block} />;+ break;+ case "callout":+ body = <CalloutBlock block={block} />;+ break;+ case "quiz":+ body = <QuizBlock block={block} onAttempt={onQuizAttempt} />;+ break;+ case "user_note":+ body = <UserNoteBlock block={block} />;+ break;+ case "figure":+ body = <FigureBlock block={block} />;+ break;+ case "interactive":+ body = <InteractiveBlock block={block} />;+ break;+ case "animation":+ body = <AnimationBlock block={block} />;+ break;+ case "code":+ body = <CodeBlock block={block} />;+ break;+ case "timeline":+ body = <TimelineBlock block={block} />;+ break;+ case "flash_cards":+ body = <FlashCardsBlock block={block} />;+ break;+ case "deep_dive":+ body = (+ <DeepDiveBlock+ block={block}+ onDeepDive={onDeepDive}+ pendingTopic={pendingDeepDiveTopic}+ />+ );+ break;+ case "concept_graph":+ body = (+ <ConceptGraphBlock+ block={block}+ bookId={bookId}+ currentPageId={currentPageId}+ language={bookLanguage}+ />+ );+ break;+ default:+ body = <PlaceholderBlock block={block} />;+ }++ const hasActions =+ !!onRegenerate || !!onDelete || !!onMove || !!onChangeType;++ const bridgeText = String(+ (block.payload as Record<string, unknown> | undefined)?.bridge_text ?? "",+ ).trim();+ const showBridge = bridgeText.length > 0;++ return (+ <div className="group relative">+ {showBridge && (+ <div className="mb-3 text-[var(--foreground)]">+ <MarkdownRenderer content={bridgeText} variant="prose" />+ </div>+ )}+ {hasActions && (+ <div className="pointer-events-none absolute -top-3 right-2 z-10 flex translate-y-1 items-center gap-1 rounded-md border border-[var(--border)] bg-[var(--card)] px-1 py-0.5 text-[var(--muted-foreground)] opacity-0 shadow-sm transition group-hover:translate-y-0 group-hover:opacity-100">+ {onMove && (+ <>+ <button+ onClick={() => onMove(block, "up")}+ className="pointer-events-auto rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ title="Move up"+ >+ <ArrowUp className="h-3.5 w-3.5" />+ </button>+ <button+ onClick={() => onMove(block, "down")}+ className="pointer-events-auto rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ title="Move down"+ >+ <ArrowDown className="h-3.5 w-3.5" />+ </button>+ </>+ )}+ {onChangeType && (+ <div className="relative pointer-events-auto">+ <button+ onClick={() => setShowTypeMenu((v) => !v)}+ className="rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ title="Change type"+ >+ <Replace className="h-3.5 w-3.5" />+ </button>+ {showTypeMenu && (+ <div className="absolute right-0 top-full mt-1 max-h-60 w-44 overflow-y-auto rounded-md border border-[var(--border)] bg-[var(--card)] p-1 shadow-lg">+ {CHANGEABLE_TYPES.filter((t) => t !== block.type).map((t) => (+ <button+ key={t}+ onClick={() => {+ setShowTypeMenu(false);+ onChangeType(block, t);+ }}+ className="block w-full rounded px-2 py-1 text-left text-xs hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ >+ {t}+ </button>+ ))}+ </div>+ )}+ </div>+ )}+ {onRegenerate && (+ <button+ onClick={() => onRegenerate(block)}+ className="pointer-events-auto rounded p-1 hover:bg-[var(--background)] hover:text-[var(--foreground)]"+ title="Regenerate"+ >+ <RefreshCw className="h-3.5 w-3.5" />+ </button>+ )}+ {onDelete && (+ <button+ onClick={() => onDelete(block)}+ className="pointer-events-auto rounded p-1 hover:bg-rose-100 hover:text-rose-700 dark:hover:bg-rose-500/10 dark:hover:text-rose-200"+ title="Delete"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ )}+ </div>+ )}+ {body}+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/CalloutBlock.tsx b/web/app/(workspace)/book/components/blocks/CalloutBlock.tsxnew file mode 100644index 000000000..960de2f73--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/CalloutBlock.tsx@@ -0,0 +1,61 @@+"use client";++import { Lightbulb, AlertTriangle, BookmarkCheck, Sparkles } from "lucide-react";+import type { Block } from "@/lib/book-types";++const VARIANT_STYLES: Record<+ string,+ { icon: typeof Lightbulb; rule: string; tint: string; accent: string }+> = {+ key_idea: {+ icon: Lightbulb,+ rule: "border-amber-400/70 dark:border-amber-300/60",+ tint: "bg-amber-50/60 text-amber-950 dark:bg-amber-500/[0.06] dark:text-amber-100",+ accent: "text-amber-700 dark:text-amber-300",+ },+ common_pitfall: {+ icon: AlertTriangle,+ rule: "border-rose-400/70 dark:border-rose-300/60",+ tint: "bg-rose-50/60 text-rose-950 dark:bg-rose-500/[0.06] dark:text-rose-100",+ accent: "text-rose-700 dark:text-rose-300",+ },+ summary: {+ icon: BookmarkCheck,+ rule: "border-sky-400/70 dark:border-sky-300/60",+ tint: "bg-sky-50/60 text-sky-950 dark:bg-sky-500/[0.06] dark:text-sky-100",+ accent: "text-sky-700 dark:text-sky-300",+ },+ tip: {+ icon: Sparkles,+ rule: "border-emerald-400/70 dark:border-emerald-300/60",+ tint: "bg-emerald-50/60 text-emerald-950 dark:bg-emerald-500/[0.06] dark:text-emerald-100",+ accent: "text-emerald-700 dark:text-emerald-300",+ },+};++export interface CalloutBlockProps {+ block: Block;+}++export default function CalloutBlock({ block }: CalloutBlockProps) {+ const variant = String(block.payload?.variant || "key_idea");+ const label = String(block.payload?.label || variant.replace(/_/g, " "));+ const body = String(block.payload?.body || "");+ const style = VARIANT_STYLES[variant] || VARIANT_STYLES.key_idea;+ const Icon = style.icon;+ return (+ <aside+ className={`relative flex gap-3 border-l-[3px] ${style.rule} ${style.tint} py-2 pl-4 pr-3`}+ >+ <Icon className={`mt-[3px] h-4 w-4 shrink-0 ${style.accent}`} />+ <div className="min-w-0 space-y-1">+ <div+ className={`text-[11px] font-semibold uppercase tracking-[0.16em] ${style.accent}`}+ >+ {label}+ </div>+ <div className="text-[14.5px] leading-relaxed">{body}</div>+ </div>+ </aside>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/CodeBlock.tsx b/web/app/(workspace)/book/components/blocks/CodeBlock.tsxnew file mode 100644index 000000000..024744f63--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/CodeBlock.tsx@@ -0,0 +1,23 @@+"use client";++import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";++export interface CodeBlockProps {+ block: Block;+}++export default function CodeBlock({ block }: CodeBlockProps) {+ const language = String(block.payload?.language || "python");+ const code = String(block.payload?.code || "");+ const explanation = String(block.payload?.explanation || "");+ const fenced = `\`\`\`${language}\n${code}\n\`\`\``;+ return (+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">+ <MarkdownRenderer content={fenced} variant="default" />+ {explanation && (+ <p className="mt-2 text-xs text-[var(--muted-foreground)]">{explanation}</p>+ )}+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx b/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsxnew file mode 100644index 000000000..537cceacf--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/ConceptGraphBlock.tsx@@ -0,0 +1,168 @@+"use client";++import { useMemo } from "react";+import Link from "next/link";+import { Compass } from "lucide-react";++import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block, ConceptGraph } from "@/lib/book-types";++export interface ConceptGraphBlockProps {+ block: Block;+ bookId?: string;+ currentPageId?: string;+ language?: string;+}++const LABELS: Record<string, {+ chapterMap: (n: number, e: number) => string;+ conceptMap: (n: number, e: number) => string;+ chapterIndex: string;+ noChapters: string;+}> = {+ zh: {+ chapterMap: (n, e) => `章节图谱 · ${n} 章 · ${e} 条依赖`,+ conceptMap: (n, e) => `概念图 · ${n} 个概念 · ${e} 条关系`,+ chapterIndex: "章节索引",+ noChapters: "(暂无章节)",+ },+ en: {+ chapterMap: (n, e) => `Chapter map · ${n} chapters · ${e} dependencies`,+ conceptMap: (n, e) => `Concept map · ${n} concepts · ${e} relations`,+ chapterIndex: "Chapter index",+ noChapters: "(No chapters yet)",+ },+};++function pickLabels(language?: string) {+ const code = (language || "en").toLowerCase().split("-")[0];+ return LABELS[code] ?? LABELS.en;+}++interface ChapterIndexEntry {+ id: string;+ title: string;+ summary?: string;+ objectives?: string[];+ order?: number;+ content_type?: string;+ page_id?: string;+}++interface IndexPayload {+ chapters: ChapterIndexEntry[];+ node_to_chapter: Record<string, string>;+}++function asGraph(payload: unknown): ConceptGraph | null {+ if (!payload || typeof payload !== "object") return null;+ const candidate = payload as Partial<ConceptGraph>;+ if (!Array.isArray(candidate.nodes) || !Array.isArray(candidate.edges)) {+ return null;+ }+ return candidate as ConceptGraph;+}++function asIndex(payload: unknown): IndexPayload {+ if (!payload || typeof payload !== "object") {+ return { chapters: [], node_to_chapter: {} };+ }+ const candidate = payload as Partial<IndexPayload>;+ return {+ chapters: Array.isArray(candidate.chapters) ? candidate.chapters : [],+ node_to_chapter:+ candidate.node_to_chapter && typeof candidate.node_to_chapter === "object"+ ? candidate.node_to_chapter+ : {},+ };+}++export default function ConceptGraphBlock({+ block,+ bookId,+ currentPageId: _currentPageId,+ language,+}: ConceptGraphBlockProps) {+ const labels = pickLabels(language);+ const code =+ (block.payload?.code as { language?: string; content?: string } | undefined) || {};+ const mermaidSrc = String(code.content || "").trim();+ const graph = asGraph(block.payload?.graph);+ const index = asIndex(block.payload?.index);++ const fenced = useMemo(+ () =>+ mermaidSrc+ ? `\`\`\`mermaid\n${mermaidSrc}\n\`\`\``+ : "```mermaid\ngraph TD\n empty[\"(no concepts yet)\"]\n```",+ [mermaidSrc],+ );++ const chapterNodes = graph?.nodes.filter((n) => n.chapter_id) ?? [];+ const isChapterMap = chapterNodes.length > 0;+ const nodeCount = graph?.nodes.length ?? 0;+ const edgeCount = graph?.edges.length ?? 0;++ return (+ <section className="grid gap-4 md:grid-cols-[minmax(0,1fr)_minmax(0,260px)]">+ <figure className="overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] p-3 shadow-sm">+ <header className="mb-2 flex items-center gap-2 text-xs text-[var(--muted-foreground)]">+ <Compass className="h-3.5 w-3.5" />+ <span>+ {isChapterMap+ ? labels.chapterMap(chapterNodes.length, edgeCount)+ : labels.conceptMap(nodeCount, edgeCount)}+ </span>+ </header>+ <div className="max-h-[60vh] overflow-auto">+ <MarkdownRenderer content={fenced} variant="default" />+ </div>+ </figure>++ <aside className="rounded-2xl border border-[var(--border)] bg-[var(--card)]/60 p-3 shadow-sm">+ <h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ {labels.chapterIndex}+ </h3>+ <ol className="space-y-1.5">+ {index.chapters.length === 0 && (+ <li className="text-xs italic text-[var(--muted-foreground)]">+ {labels.noChapters}+ </li>+ )}+ {index.chapters.map((chapter, idx) => {+ const label = (+ <span className="flex items-baseline gap-2">+ <span className="text-[10px] font-mono text-[var(--muted-foreground)]">+ {String(idx + 1).padStart(2, "0")}+ </span>+ <span className="line-clamp-2 text-xs font-medium leading-snug text-[var(--foreground)]">+ {chapter.title}+ </span>+ </span>+ );+ if (bookId && chapter.page_id) {+ return (+ <li key={chapter.id}>+ <Link+ href={`/book/${bookId}?page=${chapter.page_id}`}+ className="block rounded-md px-2 py-1.5 hover:bg-[var(--background)]"+ >+ {label}+ </Link>+ </li>+ );+ }+ return (+ <li+ key={chapter.id}+ className="rounded-md px-2 py-1.5 text-[var(--foreground)]"+ >+ {label}+ </li>+ );+ })}+ </ol>+ </aside>+ </section>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx b/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsxnew file mode 100644index 000000000..680c5d7e4--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/DeepDiveBlock.tsx@@ -0,0 +1,84 @@+"use client";++import { useState } from "react";+import { ChevronRight, Sparkles, Loader2 } from "lucide-react";+import type { Block } from "@/lib/book-types";++interface Suggestion {+ topic?: string;+ rationale?: string;+}++export interface DeepDiveBlockProps {+ block: Block;+ onDeepDive?: (topic: string, blockId: string) => Promise<void> | void;+ pendingTopic?: string | null;+}++export default function DeepDiveBlock({+ block,+ onDeepDive,+ pendingTopic,+}: DeepDiveBlockProps) {+ const suggestions =+ (block.payload?.suggestions as Suggestion[] | undefined) || [];+ const linkedPageId = block.metadata?.deep_dive_page_id as string | undefined;+ const [busy, setBusy] = useState<string | null>(null);++ if (suggestions.length === 0) return null;++ return (+ <div className="rounded-2xl border border-[var(--primary)]/30 bg-gradient-to-br from-[var(--primary)]/5 to-transparent p-4 shadow-sm">+ <div className="mb-3 flex items-center gap-2">+ <Sparkles className="h-4 w-4 text-[var(--primary)]" />+ <span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">+ Go Deeper+ </span>+ </div>+ <ul className="space-y-2">+ {suggestions.map((s, i) => {+ const topic = s.topic || "";+ const isPending = busy === topic || pendingTopic === topic;+ return (+ <li key={i}>+ <button+ onClick={async () => {+ if (!onDeepDive || !topic) return;+ setBusy(topic);+ try {+ await onDeepDive(topic, block.id);+ } finally {+ setBusy(null);+ }+ }}+ disabled={isPending || !!linkedPageId}+ className="group flex w-full items-start justify-between gap-3 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-left transition hover:border-[var(--primary)]/40 disabled:opacity-60"+ >+ <div className="flex-1">+ <div className="text-sm font-medium text-[var(--foreground)]">+ {topic}+ </div>+ {s.rationale && (+ <div className="mt-0.5 text-xs leading-relaxed text-[var(--muted-foreground)]">+ {s.rationale}+ </div>+ )}+ </div>+ {isPending ? (+ <Loader2 className="h-4 w-4 shrink-0 animate-spin text-[var(--primary)]" />+ ) : (+ <ChevronRight className="h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition group-hover:translate-x-0.5 group-hover:text-[var(--primary)]" />+ )}+ </button>+ </li>+ );+ })}+ </ul>+ {linkedPageId && (+ <p className="mt-2 text-[11px] text-[var(--muted-foreground)]">+ Linked sub-page already exists.+ </p>+ )}+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/FigureBlock.tsx b/web/app/(workspace)/book/components/blocks/FigureBlock.tsxnew file mode 100644index 000000000..40405ddbc--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/FigureBlock.tsx@@ -0,0 +1,79 @@+"use client";++import VisualizationViewer from "@/components/visualize/VisualizationViewer";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";+import type { VisualizeRenderType, VisualizeResult } from "@/lib/visualize-types";++export interface FigureBlockProps {+ block: Block;+}++const FIGURE_RENDER_TYPES: ReadonlySet<VisualizeRenderType> = new Set([+ "svg",+ "chartjs",+ "mermaid",+]);++function coerceRenderType(value: unknown, language: string): VisualizeRenderType {+ if (typeof value === "string" && (FIGURE_RENDER_TYPES as Set<string>).has(value)) {+ return value as VisualizeRenderType;+ }+ if (language === "javascript" || language === "js") return "chartjs";+ if (language === "mermaid") return "mermaid";+ return "svg";+}++export default function FigureBlock({ block }: FigureBlockProps) {+ const code =+ (block.payload?.code as { language?: string; content?: string } | undefined) ||+ {};+ const language = String(code.language || "svg");+ const content = String(code.content || "");+ const description = block.payload?.description+ ? String(block.payload.description)+ : "";+ const chartType = block.payload?.chart_type+ ? String(block.payload.chart_type)+ : "";++ if (!content.trim()) {+ return (+ <div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 p-4 text-xs italic text-[var(--muted-foreground)]">+ (Figure payload is empty)+ </div>+ );+ }++ const renderType = coerceRenderType(block.payload?.render_type, language);++ const result: VisualizeResult = {+ response: description,+ render_type: renderType,+ code: { language, content },+ analysis: {+ render_type: renderType,+ description,+ data_description: "",+ chart_type: chartType,+ visual_elements: [],+ rationale: "",+ },+ review: {+ optimized_code: "",+ changed: false,+ review_notes: "",+ },+ };++ return (+ <figure className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-3 shadow-sm">+ <VisualizationViewer result={result} />+ {description && (+ <figcaption className="mt-3 text-xs leading-snug text-[var(--muted-foreground)]">+ <MarkdownRenderer content={description} variant="default" />+ </figcaption>+ )}+ </figure>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/FlashCardsBlock.tsx b/web/app/(workspace)/book/components/blocks/FlashCardsBlock.tsxnew file mode 100644index 000000000..e99a14ccd--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/FlashCardsBlock.tsx@@ -0,0 +1,80 @@+"use client";++import { useState } from "react";+import { ChevronLeft, ChevronRight, RotateCcw } from "lucide-react";+import type { Block } from "@/lib/book-types";++interface Card {+ front?: string;+ back?: string;+ hint?: string;+}++export interface FlashCardsBlockProps {+ block: Block;+}++export default function FlashCardsBlock({ block }: FlashCardsBlockProps) {+ const cards = (block.payload?.cards as Card[] | undefined) || [];+ const [idx, setIdx] = useState(0);+ const [showBack, setShowBack] = useState(false);+ if (cards.length === 0) return null;+ const card = cards[Math.min(idx, cards.length - 1)] || {};++ return (+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">+ <div className="flex items-center justify-between">+ <span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">+ Flash Cards+ </span>+ <span className="text-xs text-[var(--muted-foreground)]">+ {idx + 1} / {cards.length}+ </span>+ </div>+ <button+ onClick={() => setShowBack((v) => !v)}+ className="mt-3 flex h-40 w-full flex-col items-center justify-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--background)] px-6 text-center transition hover:border-[var(--primary)]/40"+ >+ <span className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {showBack ? "Answer" : "Question"}+ </span>+ <span className="text-base font-medium text-[var(--foreground)]">+ {showBack ? card.back : card.front}+ </span>+ {!showBack && card.hint && (+ <span className="text-xs italic text-[var(--muted-foreground)]">+ Hint: {card.hint}+ </span>+ )}+ </button>+ <div className="mt-3 flex items-center justify-between">+ <button+ onClick={() => {+ setShowBack(false);+ setIdx((i) => Math.max(0, i - 1));+ }}+ disabled={idx === 0}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-xs disabled:opacity-30"+ >+ <ChevronLeft className="h-3.5 w-3.5" /> Prev+ </button>+ <button+ onClick={() => setShowBack((v) => !v)}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-xs hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"+ >+ <RotateCcw className="h-3.5 w-3.5" /> Flip+ </button>+ <button+ onClick={() => {+ setShowBack(false);+ setIdx((i) => Math.min(cards.length - 1, i + 1));+ }}+ disabled={idx >= cards.length - 1}+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] px-2 py-1 text-xs disabled:opacity-30"+ >+ Next <ChevronRight className="h-3.5 w-3.5" />+ </button>+ </div>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/InteractiveBlock.tsx b/web/app/(workspace)/book/components/blocks/InteractiveBlock.tsxnew file mode 100644index 000000000..90e50b347--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/InteractiveBlock.tsx@@ -0,0 +1,61 @@+"use client";++import VisualizationViewer from "@/components/visualize/VisualizationViewer";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";+import type { VisualizeResult } from "@/lib/visualize-types";++export interface InteractiveBlockProps {+ block: Block;+}++export default function InteractiveBlock({ block }: InteractiveBlockProps) {+ const code =+ (block.payload?.code as { language?: string; content?: string } | undefined) ||+ {};+ const content = String(code.content || "");+ const description = block.payload?.description+ ? String(block.payload.description)+ : "";+ const chartType = block.payload?.chart_type+ ? String(block.payload.chart_type)+ : "interactive";++ if (!content.trim()) {+ return (+ <div className="rounded-2xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 p-4 text-xs italic text-[var(--muted-foreground)]">+ (Interactive payload is empty)+ </div>+ );+ }++ const result: VisualizeResult = {+ response: description,+ render_type: "html",+ code: { language: "html", content },+ analysis: {+ render_type: "html",+ description,+ data_description: "",+ chart_type: chartType,+ visual_elements: [],+ rationale: "",+ },+ review: {+ optimized_code: "",+ changed: false,+ review_notes: "",+ },+ };++ return (+ <figure className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-3 shadow-sm">+ <VisualizationViewer result={result} />+ {description && (+ <figcaption className="mt-3 text-xs leading-snug text-[var(--muted-foreground)]">+ <MarkdownRenderer content={description} variant="default" />+ </figcaption>+ )}+ </figure>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/PlaceholderBlock.tsx b/web/app/(workspace)/book/components/blocks/PlaceholderBlock.tsxnew file mode 100644index 000000000..a64359d85--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/PlaceholderBlock.tsx@@ -0,0 +1,37 @@+"use client";++import { Sparkles } from "lucide-react";+import type { Block } from "@/lib/book-types";++export interface PlaceholderBlockProps {+ block: Block;+}++const LABELS: Record<string, string> = {+ figure: "Figure",+ interactive: "Interactive",+ animation: "Animation",+ code: "Code Sandbox",+ timeline: "Timeline",+ flash_cards: "Flash Cards",+ deep_dive: "Deep Dive",+};++export default function PlaceholderBlock({ block }: PlaceholderBlockProps) {+ const label = LABELS[block.type] || block.type;+ const intended = block.params?.intended_block_type+ ? String(block.params.intended_block_type)+ : block.type;+ return (+ <div className="flex items-center gap-3 rounded-2xl border border-dashed border-[var(--border)] bg-[var(--muted)]/30 px-4 py-3 text-sm text-[var(--muted-foreground)]">+ <Sparkles className="h-4 w-4 text-[var(--primary)]" />+ <div>+ <div className="font-medium text-[var(--foreground)]">{label}</div>+ <div className="text-xs">+ Coming in Phase 2 – {intended} block will appear here once the+ generator is wired.+ </div>+ </div>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/QuizBlock.tsx b/web/app/(workspace)/book/components/blocks/QuizBlock.tsxnew file mode 100644index 000000000..81ee7d352--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/QuizBlock.tsx@@ -0,0 +1,167 @@+"use client";++import { useEffect, useState } from "react";+import { CheckCircle2, XCircle, Eye, EyeOff } from "lucide-react";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";++export interface QuizAttemptArgs {+ questionId?: string;+ userAnswer?: string;+ isCorrect: boolean;+}++interface QuizQuestion {+ question_id?: string;+ question?: string;+ question_type?: string;+ options?: Record<string, string> | null;+ correct_answer?: string;+ explanation?: string;+ difficulty?: string;+}++export interface QuizBlockProps {+ block: Block;+ onAttempt?: (block: Block, args: QuizAttemptArgs) => void;+}++export default function QuizBlock({ block, onAttempt }: QuizBlockProps) {+ const questions = (block.payload?.questions as QuizQuestion[] | undefined) || [];+ if (questions.length === 0) {+ return (+ <div className="text-sm text-[var(--muted-foreground)]">+ No quiz questions generated.+ </div>+ );+ }+ return (+ <section>+ <div className="mb-3 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">+ <span className="h-px flex-1 bg-[var(--primary)]/20" />+ Quick Check+ <span className="h-px flex-1 bg-[var(--primary)]/20" />+ </div>+ <div className="space-y-3">+ {questions.map((q, idx) => (+ <QuizQuestionCard+ key={q.question_id || idx}+ index={idx}+ question={q}+ onAttempt={(args) => onAttempt?.(block, args)}+ />+ ))}+ </div>+ </section>+ );+}++function QuizQuestionCard({+ index,+ question,+ onAttempt,+}: {+ index: number;+ question: QuizQuestion;+ onAttempt?: (args: QuizAttemptArgs) => void;+}) {+ const [selected, setSelected] = useState<string | null>(null);+ const [revealed, setRevealed] = useState(false);+ const [reported, setReported] = useState(false);+ const isMultiple =+ (question.question_type || "").toLowerCase() === "multiple_choice";+ const correct = String(question.correct_answer || "").trim();+ const options = question.options || {};++ useEffect(() => {+ if (revealed && selected && !reported && onAttempt) {+ onAttempt({+ questionId: question.question_id,+ userAnswer: selected,+ isCorrect: selected === correct,+ });+ setReported(true);+ }+ }, [revealed, selected, reported, onAttempt, question.question_id, correct]);++ return (+ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">+ <div className="flex items-baseline justify-between gap-2">+ <div className="text-sm font-medium text-[var(--foreground)]">+ {index + 1}. {question.question || "(missing)"}+ </div>+ {question.difficulty && (+ <span className="rounded-full bg-[var(--muted)] px-2 py-0.5 text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {question.difficulty}+ </span>+ )}+ </div>++ {isMultiple && Object.keys(options).length > 0 ? (+ <div className="mt-3 space-y-1.5">+ {Object.entries(options).map(([key, label]) => {+ const isSelected = selected === key;+ const isCorrect = revealed && key === correct;+ const isWrongPick = revealed && isSelected && key !== correct;+ return (+ <button+ key={key}+ onClick={() => setSelected(key)}+ className={`flex w-full items-start gap-2 rounded-lg border px-3 py-2 text-left text-sm transition-colors ${+ isCorrect+ ? "border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-500/40 dark:bg-emerald-500/10 dark:text-emerald-100"+ : isWrongPick+ ? "border-rose-300 bg-rose-50 text-rose-900 dark:border-rose-500/40 dark:bg-rose-500/10 dark:text-rose-100"+ : isSelected+ ? "border-[var(--primary)] bg-[var(--primary)]/8 text-[var(--foreground)]"+ : "border-[var(--border)] bg-[var(--card)] text-[var(--foreground)] hover:border-[var(--primary)]/40"+ }`}+ >+ <span className="font-mono text-xs uppercase text-[var(--muted-foreground)]">+ {key}.+ </span>+ <span className="flex-1">{label}</span>+ {isCorrect && <CheckCircle2 className="mt-0.5 h-4 w-4" />}+ {isWrongPick && <XCircle className="mt-0.5 h-4 w-4" />}+ </button>+ );+ })}+ </div>+ ) : (+ <div className="mt-2 text-xs text-[var(--muted-foreground)]">+ {question.question_type === "fill_in_blank"+ ? "Think about your answer, then reveal the solution."+ : "Open response — click reveal to see the model answer."}+ </div>+ )}++ <div className="mt-3 flex items-center justify-between gap-2">+ <button+ onClick={() => setRevealed((v) => !v)}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1 text-xs font-medium text-[var(--muted-foreground)] hover:border-[var(--primary)]/40 hover:text-[var(--primary)]"+ >+ {revealed ? (+ <EyeOff className="h-3.5 w-3.5" />+ ) : (+ <Eye className="h-3.5 w-3.5" />+ )}+ {revealed ? "Hide answer" : "Reveal answer"}+ </button>+ {revealed && correct && (+ <span className="text-xs text-[var(--muted-foreground)]">+ Answer: <span className="font-mono text-[var(--foreground)]">{correct}</span>+ </span>+ )}+ </div>++ {revealed && question.explanation && (+ <div className="mt-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 p-2">+ <MarkdownRenderer+ content={String(question.explanation)}+ variant="compact"+ />+ </div>+ )}+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/SectionBlock.tsx b/web/app/(workspace)/book/components/blocks/SectionBlock.tsxnew file mode 100644index 000000000..eb8b4d85b--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/SectionBlock.tsx@@ -0,0 +1,64 @@+"use client";++import { Sparkles } from "lucide-react";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";++export interface SectionBlockProps {+ block: Block;+}++interface Subsection {+ heading?: string;+ role?: string;+ focus?: string;+ body?: string;+ target_words?: number;+}++export default function SectionBlock({ block }: SectionBlockProps) {+ const payload = block.payload || {};+ const intro = String(payload.intro ?? "").trim();+ const keyTakeaway = String(payload.key_takeaway ?? "").trim();+ const focus = String(payload.focus ?? "").trim();+ const rawSubs = Array.isArray(payload.subsections) ? payload.subsections : [];+ const subsections: Subsection[] = rawSubs as Subsection[];++ return (+ <section className="text-[var(--foreground)]">+ {intro && (+ <div className="mb-5 text-[1.02em] leading-relaxed">+ <MarkdownRenderer content={intro} variant="prose" />+ </div>+ )}++ {focus && (+ <div className="mb-4 text-[11px] uppercase tracking-wider text-[var(--muted-foreground)]">+ Section focus · {focus}+ </div>+ )}++ <div className="space-y-6">+ {subsections.map((sub, idx) => {+ const body = (sub.body || "").trim();+ if (!body) return null;+ return (+ <div key={idx} className="leading-relaxed">+ <MarkdownRenderer content={body} variant="prose" />+ </div>+ );+ })}+ </div>++ {keyTakeaway && (+ <div className="mt-6 flex items-start gap-2 rounded-xl border border-[var(--border)] bg-[var(--muted)]/30 px-3 py-2 text-sm">+ <Sparkles className="mt-0.5 h-4 w-4 flex-shrink-0 text-[var(--muted-foreground)]" />+ <div className="flex-1">+ <span className="mr-1 font-medium">Key takeaway:</span>+ <span className="text-[var(--foreground)]">{keyTakeaway}</span>+ </div>+ </div>+ )}+ </section>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/TextBlock.tsx b/web/app/(workspace)/book/components/blocks/TextBlock.tsxnew file mode 100644index 000000000..df2e50856--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/TextBlock.tsx@@ -0,0 +1,18 @@+"use client";++import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";++export interface TextBlockProps {+ block: Block;+}++export default function TextBlock({ block }: TextBlockProps) {+ const body = String(block.payload?.body ?? "");++ return (+ <div className="text-[var(--foreground)]">+ <MarkdownRenderer content={body} variant="prose" />+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/TimelineBlock.tsx b/web/app/(workspace)/book/components/blocks/TimelineBlock.tsxnew file mode 100644index 000000000..247346708--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/TimelineBlock.tsx@@ -0,0 +1,40 @@+"use client";++import type { Block } from "@/lib/book-types";++interface TimelineEvent {+ date?: string;+ title?: string;+ description?: string;+}++export interface TimelineBlockProps {+ block: Block;+}++export default function TimelineBlock({ block }: TimelineBlockProps) {+ const events = (block.payload?.events as TimelineEvent[] | undefined) || [];+ if (events.length === 0) return null;+ return (+ <div className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">+ <ol className="relative ml-3 space-y-4 border-l border-[var(--border)] pl-4">+ {events.map((ev, idx) => (+ <li key={idx} className="relative">+ <span className="absolute -left-[19px] top-1 inline-flex h-3 w-3 rounded-full border-2 border-[var(--card)] bg-[var(--primary)]" />+ <div className="text-xs font-mono uppercase tracking-wider text-[var(--muted-foreground)]">+ {ev.date || ""}+ </div>+ <div className="text-sm font-semibold text-[var(--foreground)]">+ {ev.title}+ </div>+ {ev.description && (+ <div className="mt-0.5 text-xs leading-relaxed text-[var(--muted-foreground)]">+ {ev.description}+ </div>+ )}+ </li>+ ))}+ </ol>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx b/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsxnew file mode 100644index 000000000..58626b6d3--- /dev/null+++ b/web/app/(workspace)/book/components/blocks/UserNoteBlock.tsx@@ -0,0 +1,30 @@+"use client";++import { StickyNote } from "lucide-react";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import type { Block } from "@/lib/book-types";++export interface UserNoteBlockProps {+ block: Block;+}++export default function UserNoteBlock({ block }: UserNoteBlockProps) {+ const body = String(block.payload?.body || "");+ return (+ <aside className="flex gap-3 border-l-[3px] border-dashed border-[var(--primary)]/50 bg-[var(--primary)]/[0.04] py-2 pl-4 pr-3">+ <StickyNote className="mt-[3px] h-4 w-4 shrink-0 text-[var(--primary)]" />+ <div className="min-w-0 space-y-1">+ <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--primary)]">+ Your note+ </div>+ {body ? (+ <MarkdownRenderer content={body} variant="compact" />+ ) : (+ <div className="text-xs text-[var(--muted-foreground)]">+ Empty note – start writing your own annotation.+ </div>+ )}+ </div>+ </aside>+ );+}diff --git a/web/app/(workspace)/book/page.tsx b/web/app/(workspace)/book/page.tsxnew file mode 100644index 000000000..fe82be296--- /dev/null+++ b/web/app/(workspace)/book/page.tsx@@ -0,0 +1,479 @@+"use client";++import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";+import { useSearchParams } from "next/navigation";+import { Loader2, MessageSquare } from "lucide-react";++import { bookApi, openBookSocket } from "@/lib/book-api";+import type {+ Block,+ BlockType,+ Book,+ BookDetail,+ BookProposal,+ Page,+ Spine,+} from "@/lib/book-types";+import {+ emptyBookProgress,+ progressHasActivity,+ progressIsComplete,+ reduceBookEvent,+} from "@/lib/book-progress";++import BookChatPanel from "./components/BookChatPanel";+import BookCreator from "./components/BookCreator";+import BookHealthBanner from "./components/BookHealthBanner";+import BookProgressTimeline from "./components/BookProgressTimeline";+import BookSidebar from "./components/BookSidebar";+import PageReader from "./components/PageReader";+import SpineEditor from "./components/SpineEditor";++type View = "list" | "creator" | "spine" | "reader";++export default function BookPage() {+ const [books, setBooks] = useState<Book[]>([]);+ const [loadingBooks, setLoadingBooks] = useState(false);+ const [view, setView] = useState<View>("list");++ const [selectedBookId, setSelectedBookId] = useState<string | null>(null);+ const [detail, setDetail] = useState<BookDetail | null>(null);+ const [selectedPageId, setSelectedPageId] = useState<string | null>(null);++ // Creator-stage state+ const [creating, setCreating] = useState(false);+ const [confirmingProposal, setConfirmingProposal] = useState(false);+ const [pendingProposal, setPendingProposal] = useState<BookProposal | null>(null);+ const [pendingBook, setPendingBook] = useState<Book | null>(null);++ // Spine-stage state+ const [confirmingSpine, setConfirmingSpine] = useState(false);++ // Page compile state+ const [compilingPageId, setCompilingPageId] = useState<string | null>(null);++ // Phase 3 state+ const [pendingDeepDiveTopic, setPendingDeepDiveTopic] = useState<string | null>(null);+ const [chatOpen, setChatOpen] = useState(false);++ // Phase 5 — live BookEngine progress timeline state.+ const [progress, dispatchProgress] = useReducer(+ reduceBookEvent,+ null,+ emptyBookProgress,+ );++ // ── Data loaders ───────────────────────────────────────────────────++ const refreshBooks = useCallback(async () => {+ setLoadingBooks(true);+ try {+ const data = await bookApi.list();+ setBooks(data.books);+ } finally {+ setLoadingBooks(false);+ }+ }, []);++ const loadBookDetail = useCallback(async (id: string) => {+ const data = await bookApi.get(id);+ setDetail(data);+ return data;+ }, []);++ useEffect(() => {+ void refreshBooks();+ }, [refreshBooks]);++ // ── Live WS event subscription ─────────────────────────────────────++ useEffect(() => {+ if (!selectedBookId) return;+ const socket = openBookSocket((event) => {+ // Always feed the progress reducer so the timeline updates live.+ dispatchProgress(event);++ const meta = (event.metadata as Record<string, unknown> | undefined) || {};+ const kind = String((event.content as string) || (meta.kind as string) || "");+ if (+ kind === "block_ready" ||+ kind === "block_error" ||+ kind === "page_compiled" ||+ kind === "page_planned" ||+ kind === "spine_ready"+ ) {+ void loadBookDetail(selectedBookId);+ }+ });+ return () => {+ try {+ socket.close();+ } catch {+ // ignore+ }+ };+ }, [selectedBookId, loadBookDetail]);++ // ── Selectors ──────────────────────────────────────────────────────++ const selectedPage: Page | null = useMemo(() => {+ if (!detail || !selectedPageId) return null;+ return detail.pages.find((p) => p.id === selectedPageId) || null;+ }, [detail, selectedPageId]);++ // ── Handlers ───────────────────────────────────────────────────────++ const handleNewBook = () => {+ setSelectedBookId(null);+ setDetail(null);+ setPendingBook(null);+ setPendingProposal(null);+ setSelectedPageId(null);+ setView("creator");+ };++ // Defined after handleSelectBook below.+ const lastDeepLinkedBookId = useRef<string | null>(null);++ const handleSelectBook = useCallback(+ async (id: string | null) => {+ if (!id) {+ setSelectedBookId(null);+ setDetail(null);+ setView("list");+ return;+ }+ setSelectedBookId(id);+ const data = await loadBookDetail(id);+ if (data.book.status === "draft" && data.book.proposal) {+ setPendingBook(data.book);+ setPendingProposal(data.book.proposal);+ setView("creator");+ } else if (data.book.status === "spine_ready" && data.spine) {+ setView("spine");+ } else {+ const firstReady = data.pages.find((p) => p.status === "ready");+ const firstAny = data.pages[0] || null;+ setSelectedPageId((firstReady || firstAny)?.id || null);+ setView("reader");+ }+ },+ [loadBookDetail],+ );++ // Allow deep-linking via /book?book=<id> (e.g. from the global sidebar).+ const searchParams = useSearchParams();+ const requestedBookId = searchParams?.get("book") || null;+ useEffect(() => {+ if (!requestedBookId) return;+ if (requestedBookId === selectedBookId) return;+ if (requestedBookId === lastDeepLinkedBookId.current) return;+ lastDeepLinkedBookId.current = requestedBookId;+ void handleSelectBook(requestedBookId);+ }, [requestedBookId, selectedBookId, handleSelectBook]);++ const handleDeleteBook = async (id: string) => {+ if (!confirm("Delete this book? This cannot be undone.")) return;+ await bookApi.delete(id);+ if (selectedBookId === id) {+ setSelectedBookId(null);+ setDetail(null);+ setView("list");+ }+ await refreshBooks();+ };++ const handleCreate = async (payload: {+ user_intent: string;+ chat_session_id: string;+ chat_selections: Array<{ session_id: string; message_ids: number[] }>;+ knowledge_bases: string[];+ notebook_refs: Array<Record<string, unknown>>;+ question_categories: number[];+ question_entries: number[];+ language: string;+ }) => {+ setCreating(true);+ try {+ const result = await bookApi.create(payload);+ setPendingBook(result.book);+ setPendingProposal(result.proposal);+ setSelectedBookId(result.book.id);+ await refreshBooks();+ } finally {+ setCreating(false);+ }+ };++ const handleConfirmProposal = async (edited: BookProposal) => {+ if (!pendingBook) return;+ setConfirmingProposal(true);+ try {+ const result = await bookApi.confirmProposal(pendingBook.id, edited);+ setPendingBook(result.book);+ setPendingProposal(null);+ await loadBookDetail(result.book.id);+ setView("spine");+ await refreshBooks();+ } finally {+ setConfirmingProposal(false);+ }+ };++ const handleConfirmSpine = async (spine: Spine) => {+ if (!detail) return;+ setConfirmingSpine(true);+ try {+ await bookApi.confirmSpine(detail.book.id, spine, true);+ const refreshed = await loadBookDetail(detail.book.id);+ const firstPage = refreshed.pages[0] || null;+ setSelectedPageId(firstPage?.id || null);+ setView("reader");+ if (firstPage) {+ void compilePage(firstPage.id);+ }+ await refreshBooks();+ } finally {+ setConfirmingSpine(false);+ }+ };++ const compilePage = useCallback(+ async (pageId: string, force = false) => {+ if (!selectedBookId) return;+ setCompilingPageId(pageId);+ try {+ await bookApi.compilePage(selectedBookId, pageId, force);+ } finally {+ setCompilingPageId((current) => (current === pageId ? null : current));+ await loadBookDetail(selectedBookId);+ }+ },+ [selectedBookId, loadBookDetail],+ );++ const handleSelectPage = (pageId: string) => {+ setSelectedPageId(pageId);+ if (!detail) return;+ const page = detail.pages.find((p) => p.id === pageId);+ if (page && page.status !== "ready" && page.status !== "generating") {+ void compilePage(pageId);+ }+ };++ const handleRegenerateBlock = async (block: Block) => {+ if (!detail || !selectedPage) return;+ await bookApi.regenerateBlock(detail.book.id, selectedPage.id, block.id);+ await loadBookDetail(detail.book.id);+ };++ const handleDeleteBlock = async (block: Block) => {+ if (!detail || !selectedPage) return;+ if (!confirm(`Delete this ${block.type} block?`)) return;+ await bookApi.deleteBlock(detail.book.id, selectedPage.id, block.id);+ await loadBookDetail(detail.book.id);+ };++ const handleMoveBlock = async (+ block: Block,+ direction: "up" | "down",+ ) => {+ if (!detail || !selectedPage) return;+ const idx = selectedPage.blocks.findIndex((b) => b.id === block.id);+ if (idx < 0) return;+ const newPos = direction === "up" ? idx - 1 : idx + 1;+ if (newPos < 0 || newPos >= selectedPage.blocks.length) return;+ await bookApi.moveBlock(detail.book.id, selectedPage.id, block.id, newPos);+ await loadBookDetail(detail.book.id);+ };++ const handleChangeBlockType = async (block: Block, newType: BlockType) => {+ if (!detail || !selectedPage) return;+ await bookApi.changeBlockType({+ book_id: detail.book.id,+ page_id: selectedPage.id,+ block_id: block.id,+ new_type: newType,+ });+ await loadBookDetail(detail.book.id);+ };++ const handleInsertBlock = async (block_type: BlockType) => {+ if (!detail || !selectedPage) return;+ await bookApi.insertBlock({+ book_id: detail.book.id,+ page_id: selectedPage.id,+ block_type,+ });+ await loadBookDetail(detail.book.id);+ };++ const handleDeepDive = async (topic: string, blockId: string) => {+ if (!detail || !selectedPage) return;+ setPendingDeepDiveTopic(topic);+ try {+ const result = await bookApi.deepDive({+ book_id: detail.book.id,+ parent_page_id: selectedPage.id,+ topic,+ block_id: blockId,+ });+ const refreshed = await loadBookDetail(detail.book.id);+ const newPage = refreshed.pages.find((p) => p.id === result.page.id);+ if (newPage) {+ setSelectedPageId(newPage.id);+ }+ } finally {+ setPendingDeepDiveTopic(null);+ }+ };++ const handleQuizAttempt = async (+ block: Block,+ args: { questionId?: string; userAnswer?: string; isCorrect: boolean },+ ) => {+ if (!detail || !selectedPage) return;+ await bookApi.recordQuizAttempt({+ book_id: detail.book.id,+ page_id: selectedPage.id,+ block_id: block.id,+ question_id: args.questionId,+ user_answer: args.userAnswer,+ is_correct: args.isCorrect,+ });+ if (!args.isCorrect) {+ const topic =+ (block.params?.topic as string | undefined) ||+ selectedPage.title ||+ "this topic";+ try {+ await bookApi.supplement(detail.book.id, selectedPage.id, topic);+ } catch {+ // best-effort+ }+ await loadBookDetail(detail.book.id);+ }+ };++ // ── Render ─────────────────────────────────────────────────────────++ return (+ <div className="flex h-screen w-full">+ <BookSidebar+ books={books}+ loadingBooks={loadingBooks}+ selectedBookId={selectedBookId}+ onSelectBook={(id) => void handleSelectBook(id)}+ onNewBook={handleNewBook}+ onDeleteBook={(id) => void handleDeleteBook(id)}+ pages={detail?.pages || []}+ selectedPageId={selectedPageId}+ onSelectPage={handleSelectPage}+ />++ <main className="relative flex flex-1 overflow-hidden bg-[var(--background)]">+ {/* Persistent mini progress chip — floats top-right of the workspace+ across creator/spine/reader views as long as generation activity+ exists and isn't fully complete. */}+ {progressHasActivity(progress) && !progressIsComplete(progress) && (+ <div className="pointer-events-none absolute right-3 top-3 z-30">+ <BookProgressTimeline progress={progress} mini />+ </div>+ )}+ <div className="flex-1 overflow-hidden">+ {view === "list" && (+ <div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">+ Select a book or click <span className="mx-1 font-semibold text-[var(--foreground)]">New book</span> to get started.+ </div>+ )}++ {view === "creator" && (+ <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">+ {(confirmingProposal || progressHasActivity(progress)) && (+ <div className="mx-auto mt-4 max-w-4xl px-4">+ <BookProgressTimeline progress={progress} />+ </div>+ )}+ <BookCreator+ onCreate={handleCreate}+ loading={creating}+ proposal={pendingProposal}+ onConfirmProposal={handleConfirmProposal}+ confirmLoading={confirmingProposal}+ />+ </div>+ )}++ {view === "spine" && detail?.spine && (+ <div className="flex h-full flex-col overflow-hidden">+ <div className="flex-1 overflow-hidden">+ <SpineEditor+ spine={detail.spine}+ onConfirm={handleConfirmSpine}+ loading={confirmingSpine}+ />+ </div>+ </div>+ )}++ {view === "reader" && (+ <>+ <BookHealthBanner+ bookId={selectedBookId}+ refreshKey={detail?.book.updated_at}+ onRecompile={(pageId) => {+ setSelectedPageId(pageId);+ void compilePage(pageId, true);+ }}+ />+ <PageReader+ page={selectedPage}+ bookId={detail?.book.id}+ bookLanguage={detail?.book.language}+ loading={!!compilingPageId && compilingPageId === selectedPage?.id}+ onRegenerateBlock={(block) => void handleRegenerateBlock(block)}+ onDeleteBlock={(block) => void handleDeleteBlock(block)}+ onMoveBlock={(block, dir) => void handleMoveBlock(block, dir)}+ onChangeBlockType={(block, t) => void handleChangeBlockType(block, t)}+ onInsertBlock={(t) => handleInsertBlock(t)}+ onDeepDive={(topic, blockId) => handleDeepDive(topic, blockId)}+ onQuizAttempt={(block, args) => void handleQuizAttempt(block, args)}+ pendingDeepDiveTopic={pendingDeepDiveTopic}+ onRecompile={+ selectedPage+ ? () => void compilePage(selectedPage.id, true)+ : undefined+ }+ />+ </>+ )}++ {view === "spine" && !detail?.spine && (+ <div className="flex h-full items-center justify-center text-[var(--muted-foreground)]">+ <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Loading spine…+ </div>+ )}+ </div>++ {view === "reader" && !chatOpen && (+ <button+ onClick={() => setChatOpen(true)}+ className="absolute bottom-4 right-4 inline-flex items-center gap-2 rounded-full bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] shadow-lg hover:opacity-90"+ >+ <MessageSquare className="h-4 w-4" />+ Chat+ </button>+ )}++ {view === "reader" && chatOpen && (+ <BookChatPanel+ book={detail?.book || null}+ page={selectedPage}+ open={chatOpen}+ onClose={() => setChatOpen(false)}+ />+ )}+ </main>+ </div>+ );+}diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex 119f61288..f9746ee45 100644--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@ -20,8 +20,9 @@ import {type LucideIcon,} from "lucide-react";import { useTranslation } from "react-i18next";-import type { SelectedRecord } from "@/app/(workspace)/guide/types";+import type { SelectedRecord } from "@/lib/notebook-selection-types";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";+import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";import ChatComposer from "@/components/chat/home/ChatComposer";import { ChatMessageList } from "@/components/chat/home/ChatMessages";import { useUnifiedChat, type MessageRequestSnapshot } from "@/context/UnifiedChatContext";@@ -65,6 +66,9 @@ const NotebookRecordPicker = dynamic(() => import("@/components/notebook/Notebooconst HistorySessionPicker = dynamic(() => import("@/components/chat/HistorySessionPicker"), {ssr: false,});+const QuestionBankPicker = dynamic(() => import("@/components/chat/QuestionBankPicker"), {+ ssr: false,+});const SaveToNotebookModal = dynamic(() => import("@/components/notebook/SaveToNotebookModal"), {ssr: false,});@@ -230,10 +234,12 @@ export default function ChatPage() {const [showSaveModal, setShowSaveModal] = useState(false);const [showNotebookPicker, setShowNotebookPicker] = useState(false);const [showHistoryPicker, setShowHistoryPicker] = useState(false);+ const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);const [toolMenuOpen, setToolMenuOpen] = useState(false);const [refMenuOpen, setRefMenuOpen] = useState(false);const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<SelectedRecord[]>([]);const [selectedHistorySessions, setSelectedHistorySessions] = useState<SelectedHistorySession[]>([]);+ const [selectedQuestionEntries, setSelectedQuestionEntries] = useState<SelectedQuestionEntry[]>([]);const dragCounter = useRef(0);const capMenuRef = useRef<HTMLDivElement>(null);const capBtnRef = useRef<HTMLButtonElement>(null);@@ -285,6 +291,10 @@ export default function ChatPage() {() => selectedHistorySessions.map((session) => session.sessionId),[selectedHistorySessions],);+ const questionNotebookReferencesPayload = useMemo(+ () => selectedQuestionEntries.map((entry) => entry.id),+ [selectedQuestionEntries],+ );const chatSaveMessages = useMemo(() =>state.messages.map((msg) => ({@@ -342,6 +352,7 @@ export default function ChatPage() {snapshot.content, snapshot.attachments, configOverride ?? snapshot.config,snapshot.notebookReferences, snapshot.historyReferences,{ displayUserMessage: false, persistUserMessage: false, requestSnapshotOverride: snapshot },+ snapshot.questionNotebookReferences,);shouldAutoScrollRef.current = true;},@@ -385,6 +396,7 @@ export default function ChatPage() {persistUserMessage: false,requestSnapshotOverride: answerNowSnapshot,},+ answerNowSnapshot.questionNotebookReferences,);shouldAutoScrollRef.current = true;}, 0);@@ -567,7 +579,7 @@ export default function ChatPage() {}, [fileToAttachment]);const handleSend = useCallback(async (content: string) => {- if ((!content && !attachments.length && !selectedNotebookRecords.length && !selectedHistorySessions.length) || state.isStreaming) return;+ if ((!content && !attachments.length && !selectedNotebookRecords.length && !selectedHistorySessions.length && !selectedQuestionEntries.length) || state.isStreaming) return;let extraAttachments = attachments.map((a) => ({ type: a.type, filename: a.filename, base64: a.base64 }));let config: Record<string, unknown> | undefined;@@ -585,11 +597,20 @@ export default function ChatPage() {sendMessage(content ||- (selectedNotebookRecords.length || selectedHistorySessions.length ? "Please use the selected context to help with this request." : "") ||+ (selectedNotebookRecords.length ||+ selectedHistorySessions.length ||+ selectedQuestionEntries.length+ ? "Please use the selected context to help with this request."+ : "") ||(isMathAnimatorMode? attachments.some((a) => a.type === "image") ? "Generate a math animation from the attached reference image(s)." : "": attachments.some((a) => a.type === "image") ? "Please analyze the attached image(s)." : ""),- extraAttachments, config, notebookReferencesPayload, historyReferencesPayload,+ extraAttachments,+ config,+ notebookReferencesPayload,+ historyReferencesPayload,+ undefined,+ questionNotebookReferencesPayload,);shouldAutoScrollRef.current = true;// Auto-collapse the per-capability settings panel after sending so the@@ -598,7 +619,8 @@ export default function ChatPage() {setAttachments([]);setSelectedNotebookRecords([]);setSelectedHistorySessions([]);- }, [attachments, historyReferencesPayload, isMathAnimatorMode, isQuizMode, isResearchMode, isVisualizeMode, mathAnimatorConfig, notebookReferencesPayload, quizConfig, quizPdf, researchConfig, selectedHistorySessions.length, selectedNotebookRecords.length, sendMessage, shouldAutoScrollRef, state.isStreaming, visualizeConfig]);+ setSelectedQuestionEntries([]);+ }, [attachments, historyReferencesPayload, isMathAnimatorMode, isQuizMode, isResearchMode, isVisualizeMode, mathAnimatorConfig, notebookReferencesPayload, questionNotebookReferencesPayload, quizConfig, quizPdf, researchConfig, selectedHistorySessions.length, selectedNotebookRecords.length, selectedQuestionEntries.length, sendMessage, shouldAutoScrollRef, state.isStreaming, visualizeConfig]);const handleConfirmOutline = useCallback((outline: OutlineItem[], _topic: string, originalConfig?: Record<string, unknown> | null) => {@@ -619,17 +641,23 @@ export default function ChatPage() {const handleSetKB = useCallback((kb: string) => { setKBs(kb ? [kb] : []); }, [setKBs]);const handleSelectNotebookPicker = useCallback(() => { setShowNotebookPicker(true); }, []);const handleSelectHistoryPicker = useCallback(() => { setShowHistoryPicker(true); }, []);+ const handleSelectQuestionBankPicker = useCallback(() => { setShowQuestionBankPicker(true); }, []);const handleRemoveHistory = useCallback((sessionId: string) => {setSelectedHistorySessions((prev) => prev.filter((item) => item.sessionId !== sessionId));}, []);const handleRemoveNotebook = useCallback((notebookId: string) => {setSelectedNotebookRecords((prev) => prev.filter((record) => record.notebookId !== notebookId));}, []);+ const handleRemoveQuestion = useCallback((entryId: number) => {+ setSelectedQuestionEntries((prev) => prev.filter((entry) => entry.id !== entryId));+ }, []);const handleTogglePanelCollapsed = useCallback(() => { setPanelCollapsed((prev) => !prev); }, []);const handleCloseNotebookPicker = useCallback(() => { setShowNotebookPicker(false); }, []);const handleApplyNotebookRecords = useCallback((records: SelectedRecord[]) => { setSelectedNotebookRecords(records); }, []);const handleCloseHistoryPicker = useCallback(() => { setShowHistoryPicker(false); }, []);const handleApplyHistorySessions = useCallback((sessions: SelectedHistorySession[]) => { setSelectedHistorySessions(sessions); }, []);+ const handleCloseQuestionBankPicker = useCallback(() => { setShowQuestionBankPicker(false); }, []);+ const handleApplyQuestionEntries = useCallback((entries: SelectedQuestionEntry[]) => { setSelectedQuestionEntries(entries); }, []);const handleCloseSaveModal = useCallback(() => { setShowSaveModal(false); }, []);const handleNewChat = useCallback(() => {@@ -725,6 +753,7 @@ export default function ChatPage() {knowledgeBases={knowledgeBases}selectedNotebookRecords={selectedNotebookRecords}selectedHistorySessions={selectedHistorySessions}+ selectedQuestionEntries={selectedQuestionEntries}notebookReferenceGroups={notebookReferenceGroups}stateKnowledgeBase={state.knowledgeBases[0] || ""}isStreaming={state.isStreaming}@@ -747,12 +776,14 @@ export default function ChatPage() {onSetKB={handleSetKB}onSelectNotebookPicker={handleSelectNotebookPicker}onSelectHistoryPicker={handleSelectHistoryPicker}+ onSelectQuestionBankPicker={handleSelectQuestionBankPicker}onToggleTool={toggleTool}onToggleResearchSource={toggleResearchSource}onSend={handleSend}onRemoveAttachment={removeAttachment}onRemoveHistory={handleRemoveHistory}onRemoveNotebook={handleRemoveNotebook}+ onRemoveQuestion={handleRemoveQuestion}onDragEnter={handleDragEnter}onDragLeave={handleDragLeave}onDragOver={handleDragOver}@@ -778,6 +809,11 @@ export default function ChatPage() {onClose={handleCloseHistoryPicker}onApply={handleApplyHistorySessions}/>+ <QuestionBankPicker+ open={showQuestionBankPicker}+ onClose={handleCloseQuestionBankPicker}+ onApply={handleApplyQuestionEntries}+ /><SaveToNotebookModalopen={showSaveModal}payload={chatSavePayload}diff --git a/web/app/(workspace)/guide/components/ChatPanel.tsx b/web/app/(workspace)/guide/components/ChatPanel.tsxdeleted file mode 100644index 100a085ac..000000000--- a/web/app/(workspace)/guide/components/ChatPanel.tsx+++ /dev/null@@ -1,137 +0,0 @@-"use client";--import { useRef, useEffect, useState } from "react";-import { MessageSquare, Send, Loader2 } from "lucide-react";-import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import "katex/dist/katex.min.css";-import { useTranslation } from "react-i18next";-import { ChatMessage } from "../types";--interface ChatPanelProps {- messages: ChatMessage[];- isLearning: boolean;- currentKnowledgeTitle?: string;- currentKnowledgeIndex?: number;- onSendMessage: (message: string) => void;-}--export default function ChatPanel({- messages,- isLearning,- currentKnowledgeTitle,- currentKnowledgeIndex,- onSendMessage,-}: ChatPanelProps) {- const { t } = useTranslation();- const [inputMessage, setInputMessage] = useState("");- const [sendingMessage, setSendingMessage] = useState(false);- const chatContainerRef = useRef<HTMLDivElement>(null);-- useEffect(() => {- if (chatContainerRef.current) {- chatContainerRef.current.scrollTo({- top: chatContainerRef.current.scrollHeight,- behavior: "smooth",- });- }- }, [messages]);-- const handleSendMessage = async () => {- if (!inputMessage.trim() || sendingMessage) return;-- setSendingMessage(true);- const message = inputMessage;- setInputMessage("");-- try {- await onSendMessage(message);- } finally {- setSendingMessage(false);- }- };-- return (- <div className="surface-card flex flex-1 flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">- <div className="flex items-center gap-2 border-b border-[var(--border)] bg-[var(--muted)]/35 p-3 text-xs font-bold uppercase tracking-wider text-[var(--muted-foreground)]">- <MessageSquare className="h-4 w-4" />- {t("Learning Assistant")}- </div>-- {isLearning && currentKnowledgeTitle && (- <div className="border-b border-[var(--border)] bg-[var(--primary)]/8 px-4 py-2 text-xs text-[var(--primary)]">- {t("Current page")}: {currentKnowledgeIndex !== undefined ? currentKnowledgeIndex + 1 : ""}- {currentKnowledgeIndex !== undefined ? ". " : ""}- {currentKnowledgeTitle}- </div>- )}-- <div- ref={chatContainerRef}- className="flex-1 space-y-4 overflow-y-auto bg-[var(--background)]/30 p-4"- >- {messages.map((msg) => (- <div- key={msg.id}- className={`flex flex-col ${msg.role === "user" ? "items-end" : "items-start"}`}- >- <div- className={`max-w-[90%] rounded-2xl px-4 py-3 text-sm ${- msg.role === "user"- ? "rounded-tr-none bg-[var(--primary)] text-[var(--primary-foreground)] shadow-sm"- : msg.role === "system" && msg.content.includes("⏳")- ? "rounded-tl-none border border-amber-300/50 bg-amber-500/10 text-amber-900 dark:text-amber-200"- : msg.role === "system"- ? "rounded-tl-none border border-sky-300/50 bg-sky-500/10 text-sky-900 dark:text-sky-200"- : "rounded-tl-none border border-[var(--border)] bg-[var(--card)] text-[var(--foreground)] shadow-sm"- }`}- >- {typeof msg.knowledge_index === "number" && (- <div className="mb-2 text-[11px] font-semibold opacity-70">- {t("Knowledge Point")} {msg.knowledge_index + 1}- </div>- )}- {msg.role === "system" || msg.role === "assistant" ? (- <MarkdownRenderer- content={msg.content}- variant="compact"- className="text-sm"- />- ) : (- <p>{msg.content}</p>- )}- </div>- </div>- ))}- </div>-- {isLearning && (- <div className="border-t border-[var(--border)] bg-[var(--card)] p-3">- <div className="relative flex items-center gap-2">- <input- type="text"- value={inputMessage}- onChange={(e) => setInputMessage(e.target.value)}- onKeyDown={(e) =>- e.key === "Enter" && !e.shiftKey && handleSendMessage()- }- placeholder={t("Have any questions? Feel free to ask...")}- disabled={sendingMessage}- className="flex-1 rounded-xl border border-transparent bg-[var(--muted)]/60 py-2.5 pl-4 pr-10 text-sm text-[var(--foreground)] outline-none transition placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/50 focus:bg-[var(--card)] focus:ring-2 focus:ring-[var(--primary)]/15 disabled:cursor-not-allowed disabled:opacity-50"- />- <button- onClick={handleSendMessage}- disabled={!inputMessage.trim() || sendingMessage}- className="btn-primary rounded-xl bg-[var(--primary)] p-2.5 text-[var(--primary-foreground)] transition-opacity hover:opacity-90 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"- >- {sendingMessage ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Send className="h-4 w-4" />- )}- </button>- </div>- </div>- )}- </div>- );-}diff --git a/web/app/(workspace)/guide/components/CompletionSummary.tsx b/web/app/(workspace)/guide/components/CompletionSummary.tsxdeleted file mode 100644index e11032dd1..000000000--- a/web/app/(workspace)/guide/components/CompletionSummary.tsx+++ /dev/null@@ -1,28 +0,0 @@-"use client";--import { CheckCircle2 } from "lucide-react";-import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import "katex/dist/katex.min.css";-import { useTranslation } from "react-i18next";--interface CompletionSummaryProps {- summary: string;-}--export default function CompletionSummary({ summary }: CompletionSummaryProps) {- const { t } = useTranslation();-- return (- <div className="surface-card relative flex flex-1 flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">- <div className="flex shrink-0 items-center justify-between border-b border-[var(--border)] bg-gradient-to-r from-emerald-500/10 to-[var(--primary)]/10 p-4">- <h2 className="flex items-center gap-2 font-semibold text-[var(--foreground)]">- <CheckCircle2 className="h-5 w-5 text-emerald-600 dark:text-emerald-400" />- {t("Learning Summary")}- </h2>- </div>- <div className="flex-1 overflow-y-auto bg-[var(--card)] p-8">- <MarkdownRenderer content={summary || ""} variant="prose" />- </div>- </div>- );-}diff --git a/web/app/(workspace)/guide/components/DebugModal.tsx b/web/app/(workspace)/guide/components/DebugModal.tsxdeleted file mode 100644index 83d38db21..000000000--- a/web/app/(workspace)/guide/components/DebugModal.tsx+++ /dev/null@@ -1,102 +0,0 @@-"use client";--import { useState } from "react";-import { Bug, X, Loader2 } from "lucide-react";-import { useTranslation } from "react-i18next";--interface DebugModalProps {- isOpen: boolean;- onClose: () => void;- onFix: (description: string) => Promise<boolean>;-}--export default function DebugModal({- isOpen,- onClose,- onFix,-}: DebugModalProps) {- const { t } = useTranslation();- const [description, setDescription] = useState("");- const [fixing, setFixing] = useState(false);-- if (!isOpen) return null;-- const handleFix = async () => {- if (!description.trim() || fixing) return;-- setFixing(true);- const success = await onFix(description);- setFixing(false);-- if (success) {- setDescription("");- onClose();- }- };-- const handleClose = () => {- setDescription("");- onClose();- };-- return (- <div className="fixed inset-0 z-[80] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">- <div className="surface-card w-[500px] max-w-full overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">- <div className="flex items-center justify-between border-b border-[var(--border)] p-4">- <h3 className="flex items-center gap-2 font-semibold text-[var(--foreground)]">- <Bug className="h-5 w-5 text-amber-600 dark:text-amber-400" />- {t("Fix HTML Issue")}- </h3>- <button- onClick={handleClose}- className="rounded-lg p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- aria-label={t("Close")}- >- <X className="h-5 w-5" />- </button>- </div>- <div className="space-y-4 p-6">- <div>- <label className="mb-2 block text-xs font-bold uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Issue Description")}- </label>- <textarea- value={description}- onChange={(e) => setDescription(e.target.value)}- placeholder={t(- "Describe the HTML issue, e.g.: button not clickable, style display error, interaction not working...",- )}- rows={6}- className="w-full resize-none rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-2 text-[var(--foreground)] outline-none transition placeholder:text-[var(--muted-foreground)] focus:border-amber-500/60 focus:ring-2 focus:ring-amber-500/15"- />- </div>- </div>- <div className="flex justify-end gap-2 border-t border-[var(--border)] p-4">- <button- onClick={handleClose}- className="rounded-lg px-4 py-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- >- {t("Cancel")}- </button>- <button- onClick={handleFix}- disabled={!description.trim() || fixing}- className="flex items-center gap-2 rounded-lg bg-amber-600 px-4 py-2 text-white transition-colors hover:bg-amber-700 disabled:opacity-50 dark:bg-amber-500 dark:hover:bg-amber-400"- >- {fixing ? (- <>- <Loader2 className="h-4 w-4 animate-spin" />- {t("Fixing...")}- </>- ) : (- <>- <Bug className="h-4 w-4" />- {t("Fix")}- </>- )}- </button>- </div>- </div>- </div>- );-}diff --git a/web/app/(workspace)/guide/components/HTMLViewer.tsx b/web/app/(workspace)/guide/components/HTMLViewer.tsxdeleted file mode 100644index 90021cdce..000000000--- a/web/app/(workspace)/guide/components/HTMLViewer.tsx+++ /dev/null@@ -1,188 +0,0 @@-"use client";--import { useRef, useEffect } from "react";-import { Bug, Loader2 } from "lucide-react";-import { useKaTeXInjection } from "../hooks";-import { useTranslation } from "react-i18next";--interface HTMLViewerProps {- html: string;- currentIndex: number;- loadingMessage: string;- onOpenDebugModal: () => void;-}--/**- * Regex that matches common LaTeX patterns NOT already wrapped in $..$ or $$..$$.- * Used to detect bare LaTeX commands in text nodes.- */-const BARE_LATEX_RE =- /(?<![\\$])(?:\\(?:underbrace|mathbb|frac|text|sqrt|subseteq|supseteq|notsubset|mid|pmod|leq|geq|Rightarrow|Leftarrow|Rightarrow|neq|approx|infty|partial|nabla|forall|exists|emptyset|varnothing|in|notin|alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega|vec|hat|bar|dot|tilde|overline|overbrace|boldsymbol|mathrm|mathit|mathbf|mathcal|mathfrak|mathscr|mathsf|mathtt|quad|qquad|ldots|cdots|vdots|ddots|prime|limits|sum|int|prod|oint|bigcup|bigcap|bigvee|bigwedge|bigoplus|bigotimes|binom|choose)[\s{])|\{[^}]*\\(?:underbrace|mathbb|frac|text|sqrt)/;--export default function HTMLViewer({- html,- currentIndex,- loadingMessage,- onOpenDebugModal,-}: HTMLViewerProps) {- const { t } = useTranslation();- const htmlFrameRef = useRef<HTMLIFrameElement>(null);- const lastWrittenRef = useRef<string>("");- const lastIndexRef = useRef<number>(currentIndex);- const { injectKaTeX } = useKaTeXInjection();-- const sanitizeHtml = (rawHtml: string) =>- rawHtml- .replace(/<script(?![^>]*katex)[\s\S]*?>[\s\S]*?<\/script>/gi, "")- .replace(/\son[a-z]+\s*=\s*(['"]).*?\1/gi, (match) => {- if (/onload\s*=\s*(['"])renderMathInElement/i.test(match)) return match;- return "";- })- .replace(/\s(href|src)\s*=\s*(['"])javascript:[\s\S]*?\2/gi, "");-- useEffect(() => {- if (currentIndex !== lastIndexRef.current) {- lastWrittenRef.current = "";- lastIndexRef.current = currentIndex;- }- }, [currentIndex]);-- useEffect(() => {- if (!html) return;-- const injected = injectKaTeX(html);- const htmlWithKaTeX = sanitizeHtml(injected);-- if (lastWrittenRef.current === htmlWithKaTeX) {- return;- }-- const timer = setTimeout(() => {- if (htmlFrameRef.current) {- const iframe = htmlFrameRef.current;- // Set srcdoc- iframe.srcdoc = htmlWithKaTeX;- lastWrittenRef.current = htmlWithKaTeX;-- /**- * Fallback rendering strategy:- * 1. Wait for CDN scripts to load- * 2. Find text nodes with bare LaTeX (no $ wrapping)- * 3. Wrap them in $...$ delimiters- * 4. Call renderMathInElement to render everything- */- const fallbackDelays = [1500, 3000];- const fallbackTimers = fallbackDelays.map((delay) =>- setTimeout(() => {- try {- const doc = iframe.contentDocument;- if (!doc || !doc.body) return;- const win = doc.defaultView as Window & {- renderMathInElement?: (el: HTMLElement, opts: Record<string, unknown>) => void;- };- if (typeof win?.renderMathInElement !== "function") return;-- let wrappedCount = 0;-- // Step 1: Find text nodes with bare LaTeX and fix them- const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT);- const nodesToProcess: Text[] = [];- let node: Text | null;- while ((node = walker.nextNode() as Text | null)) {- // Skip if inside a .katex element (already rendered)- const parent = node.parentElement;- if (parent && parent.closest(".katex")) continue;-- const text = node.textContent || "";- // Check for bare LaTeX patterns not already delimited- if (BARE_LATEX_RE.test(text) && !/^\$.*\$$/.test(text.trim())) {- nodesToProcess.push(node);- }- }-- // Process each bare LaTeX text node- for (const textNode of nodesToProcess) {- const originalText = textNode.textContent || "";- const trimmed = originalText.trim();- // Skip already-delimited content- if (- trimmed.startsWith("$") ||- trimmed.endsWith("$") ||- trimmed.startsWith("\\(") ||- trimmed.startsWith("\\[")- )- continue;-- // Wrap the entire text node content in $...$- // KaTeX handles non-math parts gracefully (renders them as \text{})- const span = doc.createElement("span");- span.textContent = `$${originalText}$`;- textNode.parentNode?.replaceChild(span, textNode);- wrappedCount++;- }-- // Step 2: Render all math (including newly wrapped)- win.renderMathInElement(doc.body, {- delimiters: [- { left: "$$", right: "$$", display: true },- { left: "$", right: "$", display: false },- { left: "\\(", right: "\\)", display: false },- { left: "\\[", right: "\\]", display: true },- ],- throwOnError: false,- });-- if (wrappedCount > 0) {- console.log(`[KaTeX] Auto-wrapped ${wrappedCount} bare LaTeX nodes`);- }- } catch (_e) {- // Silently ignore fallback errors- }- }, delay),- );-- // Store cleanup refs- (iframe as unknown as Record<string, unknown>).__fallbackTimers = fallbackTimers;- }- }, 100);-- return () => {- clearTimeout(timer);- // Clear any pending fallback timers from previous render- const prev = htmlFrameRef.current as unknown as Record<string, unknown> | null;- if (prev?.__fallbackTimers) {- (prev.__fallbackTimers as ReturnType<typeof setTimeout>[]).forEach(clearTimeout);- }- };- }, [html, currentIndex, injectKaTeX]);-- if (!html) {- return (- <div className="flex flex-1 flex-col items-center justify-center rounded-b-2xl border border-t-0 border-[var(--border)] bg-[var(--card)]">- <Loader2 className="mb-4 h-12 w-12 animate-spin text-[var(--primary)]" />- <p className="text-[var(--muted-foreground)]">- {loadingMessage || t("Loading learning content...")}- </p>- </div>- );- }-- return (- <div className="surface-card relative flex flex-1 flex-col overflow-hidden rounded-b-2xl rounded-t-none border border-t-0 border-[var(--border)] bg-[var(--card)]">- <button- onClick={onOpenDebugModal}- className="absolute right-4 top-4 z-10 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 text-[var(--muted-foreground)] shadow-sm transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- title={t("Fix HTML")}- >- <Bug className="h-4 w-4" />- </button>-- <iframe- ref={htmlFrameRef}- className="w-full flex-1 border-0"- title={t("Interactive Learning Content")}- sandbox="allow-scripts allow-same-origin"- />- </div>- );-}diff --git a/web/app/(workspace)/guide/components/KnowledgeTabBar.tsx b/web/app/(workspace)/guide/components/KnowledgeTabBar.tsxdeleted file mode 100644index 7c6c50be9..000000000--- a/web/app/(workspace)/guide/components/KnowledgeTabBar.tsx+++ /dev/null@@ -1,176 +0,0 @@-"use client";--import { useRef, useEffect } from "react";-import {- AlertCircle,- CheckCircle2,- Loader2,- Play,- RotateCcw,- XCircle,-} from "lucide-react";-import { SessionState } from "../types";-import { useTranslation } from "react-i18next";--interface KnowledgeTabBarProps {- sessionState: SessionState;- isLoading: boolean;- canStart: boolean;- readyCount: number;- allPagesReady: boolean;- isCompleted: boolean;- onStartLearning: () => void;- onNavigate: (knowledgeIndex: number) => void;- onRetryPage: (knowledgeIndex: number) => void;- onCompleteLearning: () => void;- onResetSession: () => void;- onShowSummary: () => void;-}--export default function KnowledgeTabBar({- sessionState,- isLoading,- canStart,- readyCount,- allPagesReady,- isCompleted,- onStartLearning,- onNavigate,- onRetryPage,- onCompleteLearning,- onResetSession,- onShowSummary,-}: KnowledgeTabBarProps) {- const { t } = useTranslation();- const scrollRef = useRef<HTMLDivElement>(null);- const activeRef = useRef<HTMLButtonElement>(null);- const totalCount = sessionState.knowledge_points.length;-- useEffect(() => {- if (activeRef.current) {- activeRef.current.scrollIntoView({- behavior: "smooth",- block: "nearest",- inline: "center",- });- }- }, [sessionState.current_index]);-- const renderStatusIcon = (index: number) => {- const status = sessionState.page_statuses[index];- if (status === "ready")- return <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />;- if (status === "generating")- return <Loader2 className="h-3.5 w-3.5 animate-spin text-[var(--primary)]" />;- if (status === "failed")- return <XCircle className="h-3.5 w-3.5 text-rose-500" />;- return <AlertCircle className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />;- };-- return (- <div className="flex shrink-0 flex-col rounded-t-2xl border border-b-0 border-[var(--border)] bg-[var(--card)]">- <div className="flex items-center gap-2 px-3 pb-1 pt-2">- <div- ref={scrollRef}- className="scrollbar-hide flex flex-1 items-center gap-1 overflow-x-auto"- >- {sessionState.knowledge_points.map((knowledge, index) => {- const isCurrent = sessionState.current_index === index;- const status = sessionState.page_statuses[index] || "pending";- const isReady = status === "ready";- const isFailed = status === "failed";-- return (- <button- key={`tab-${index}`}- ref={isCurrent && !isCompleted ? activeRef : null}- onClick={() => {- if (isFailed) {- onRetryPage(index);- } else {- onNavigate(index);- }- }}- disabled={!isReady && !isFailed}- title={knowledge.knowledge_title}- className={`inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors ${- isCurrent && !isCompleted- ? "bg-[var(--primary)]/12 text-[var(--primary)]"- : isReady- ? "bg-[var(--muted)] text-[var(--foreground)] hover:bg-[var(--muted)]/80"- : "cursor-default bg-[var(--muted)]/40 text-[var(--muted-foreground)]"- }`}- >- {renderStatusIcon(index)}- <span>{index + 1}</span>- </button>- );- })}- {sessionState.status === "completed" && (- <button- ref={isCompleted ? activeRef : null}- onClick={onShowSummary}- className={`inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors ${- isCompleted- ? "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"- : "bg-[var(--muted)] text-[var(--foreground)] hover:bg-[var(--muted)]/80"- }`}- >- <CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />- <span>{t("Summary")}</span>- </button>- )}- </div>-- <div className="flex shrink-0 items-center gap-1.5 border-l border-[var(--border)] pl-2">- {canStart && (- <button- onClick={onStartLearning}- disabled={isLoading}- className="btn-primary inline-flex items-center gap-1 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-50"- >- {isLoading ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Play className="h-3.5 w-3.5" />- )}- {t("Start")}- </button>- )}-- {!canStart && sessionState.status !== "completed" && (- <button- onClick={onCompleteLearning}- disabled={isLoading || !allPagesReady}- className="inline-flex items-center gap-1 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-emerald-700 disabled:opacity-50 dark:bg-emerald-500 dark:hover:bg-emerald-400"- >- {isLoading ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <CheckCircle2 className="h-3.5 w-3.5" />- )}- {t("Complete")}- </button>- )}-- <button- onClick={onResetSession}- className="inline-flex items-center gap-1 rounded-lg bg-[var(--muted)] px-2.5 py-1.5 text-xs font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/70"- title={t("Reset session")}- >- <RotateCcw className="h-3.5 w-3.5" />- </button>- </div>- </div>-- <div className="mx-3 mb-1 h-1 overflow-hidden rounded-full bg-[var(--muted)]">- <div- className="h-full rounded-full bg-[var(--primary)] transition-all duration-500"- style={{- width: `${totalCount > 0 ? (readyCount / totalCount) * 100 : 0}%`,- }}- />- </div>- </div>- );-}diff --git a/web/app/(workspace)/guide/components/ProgressPanel.tsx b/web/app/(workspace)/guide/components/ProgressPanel.tsxdeleted file mode 100644index bb6d3d896..000000000--- a/web/app/(workspace)/guide/components/ProgressPanel.tsx+++ /dev/null@@ -1,195 +0,0 @@-"use client";--import {- AlertCircle,- CheckCircle2,- Loader2,- Play,- RotateCcw,- Sparkles,- XCircle,-} from "lucide-react";-import { SessionState } from "../types";-import { useTranslation } from "react-i18next";--interface ProgressPanelProps {- sessionState: SessionState;- isLoading: boolean;- canStart: boolean;- readyCount: number;- allPagesReady: boolean;- onStartLearning: () => void;- onNavigate: (knowledgeIndex: number) => void;- onRetryPage: (knowledgeIndex: number) => void;- onCompleteLearning: () => void;- onResetSession: () => void;-}--export default function ProgressPanel({- sessionState,- isLoading,- canStart,- readyCount,- allPagesReady,- onStartLearning,- onNavigate,- onRetryPage,- onCompleteLearning,- onResetSession,-}: ProgressPanelProps) {- const { t } = useTranslation();-- const totalCount = sessionState.knowledge_points.length;-- const renderStatusIcon = (knowledgeIndex: number) => {- const status = sessionState.page_statuses[knowledgeIndex];-- if (status === "ready") {- return <CheckCircle2 className="h-4 w-4 text-emerald-500" />;- }- if (status === "generating") {- return <Loader2 className="h-4 w-4 animate-spin text-[var(--primary)]" />;- }- if (status === "failed") {- return <XCircle className="h-4 w-4 text-rose-500" />;- }- return <AlertCircle className="h-4 w-4 text-[var(--muted-foreground)]" />;- };-- return (- <div className="surface-card border border-[var(--border)] bg-[var(--card)] p-4 text-[var(--card-foreground)]">- <div className="mb-2 flex items-center justify-between gap-3">- <span className="text-xs font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Learning Progress")}- </span>- <span className="text-xs text-[var(--muted-foreground)]">- {readyCount}/{totalCount} {t("pages ready")}- </span>- </div>- <div className="mb-4 h-2 overflow-hidden rounded-full bg-[var(--muted)]">- <div- className="h-full rounded-full bg-[var(--primary)] transition-all duration-500"- style={{ width: `${sessionState.progress}%` }}- />- </div>- {totalCount > 0 && (- <p className="mb-4 text-xs text-[var(--muted-foreground)]">- {t("Open any page once it is ready. Early stages are prioritized.")}- </p>- )}-- <div className="mb-4 space-y-2">- {sessionState.knowledge_points.map((knowledge, index) => {- const status = sessionState.page_statuses[index] || "pending";- const isCurrent = sessionState.current_index === index;- const isReady = status === "ready";- const isFailed = status === "failed";-- return (- <div- key={`${knowledge.knowledge_title}-${index}`}- className={`rounded-xl border px-3 py-3 transition-colors ${- isCurrent- ? "border-[var(--primary)]/40 bg-[var(--primary)]/8"- : "border-[var(--border)] bg-[var(--muted)]/30"- }`}- >- <div className="flex items-start justify-between gap-3">- <button- onClick={() => onNavigate(index)}- className="flex-1 text-left"- >- <div className="flex items-center gap-2 text-sm font-medium text-[var(--foreground)]">- {renderStatusIcon(index)}- <span>{index + 1}.</span>- <span className="line-clamp-2">{knowledge.knowledge_title}</span>- </div>- <p className="mt-1 text-xs text-[var(--muted-foreground)]">- {status === "ready"- ? t("Ready to open")- : status === "generating"- ? t("Generating interactive page...")- : status === "failed"- ? t("Generation failed")- : t("Waiting in queue")}- </p>- </button>-- {isFailed && (- <button- onClick={() => onRetryPage(index)}- className="inline-flex items-center gap-1 rounded-lg border border-rose-300/50 bg-rose-500/8 px-2 py-1 text-xs text-rose-600 hover:bg-rose-500/15 dark:text-rose-300"- >- <RotateCcw className="h-3 w-3" />- {t("Retry")}- </button>- )}- {isReady && (- <button- onClick={() => onNavigate(index)}- className="inline-flex items-center gap-1 rounded-lg border border-emerald-300/50 bg-emerald-500/8 px-2 py-1 text-xs text-emerald-600 hover:bg-emerald-500/15 dark:text-emerald-300"- >- <Sparkles className="h-3 w-3" />- {t("Open")}- </button>- )}- </div>- </div>- );- })}- </div>-- <div className="flex flex-wrap gap-2">- {canStart && (- <button- onClick={onStartLearning}- disabled={isLoading}- className="btn-primary flex flex-1 items-center justify-center gap-2 rounded-lg bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"- >- {isLoading ? (- <>- <Loader2 className="h-4 w-4 animate-spin" />- {t("Starting...")}- </>- ) : (- <>- <Play className="h-4 w-4" />- {t("Start Learning")}- </>- )}- </button>- )}-- {!canStart && (- <button- onClick={onResetSession}- className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-[var(--muted)] px-4 py-2 text-sm font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/70"- >- <RotateCcw className="h-4 w-4" />- {t("New Session")}- </button>- )}-- {!canStart && sessionState.status !== "completed" && (- <button- onClick={onCompleteLearning}- disabled={isLoading || !allPagesReady}- className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-emerald-500 dark:hover:bg-emerald-400"- >- {isLoading ? (- <>- <Loader2 className="h-4 w-4 animate-spin" />- {t("Generating Summary...")}- </>- ) : (- <>- <CheckCircle2 className="h-4 w-4" />- {t("Complete Learning")}- </>- )}- </button>- )}- </div>- </div>- );-}diff --git a/web/app/(workspace)/guide/components/SessionHistoryList.tsx b/web/app/(workspace)/guide/components/SessionHistoryList.tsxdeleted file mode 100644index c4d85fad0..000000000--- a/web/app/(workspace)/guide/components/SessionHistoryList.tsx+++ /dev/null@@ -1,116 +0,0 @@-"use client";--import {- BookOpen,- CheckCircle2,- Clock,- FileText,- GraduationCap,- Loader2,-} from "lucide-react";-import { SessionSummary } from "../types";-import { useTranslation } from "react-i18next";--interface SessionHistoryListProps {- sessions: SessionSummary[];- loading: boolean;- onLoadSession: (sessionId: string) => void;-}--function StatusBadge({ status }: { status: string }) {- const { t } = useTranslation();- if (status === "completed") {- return (- <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/15 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 dark:text-emerald-300">- <CheckCircle2 className="h-3 w-3" />- {t("Completed")}- </span>- );- }- if (status === "learning") {- return (- <span className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/12 px-2 py-0.5 text-[11px] font-semibold text-[var(--primary)]">- <BookOpen className="h-3 w-3" />- {t("In Progress")}- </span>- );- }- return (- <span className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-2 py-0.5 text-[11px] font-semibold text-[var(--muted-foreground)]">- <FileText className="h-3 w-3" />- {t("Planned")}- </span>- );-}--export default function SessionHistoryList({- sessions,- loading,- onLoadSession,-}: SessionHistoryListProps) {- const { t } = useTranslation();-- if (loading) {- return (- <div className="flex flex-1 flex-col items-center justify-center p-8 text-[var(--muted-foreground)]">- <Loader2 className="mb-3 h-8 w-8 animate-spin" />- <p className="text-sm">{t("Loading history...")}</p>- </div>- );- }-- if (sessions.length === 0) {- return (- <div className="flex flex-1 flex-col items-center justify-center p-8 text-[var(--muted-foreground)]">- <GraduationCap className="mb-4 h-20 w-20 text-[var(--muted-foreground)]/40" />- <h3 className="mb-1 text-base font-medium text-[var(--foreground)]">- {t("No learning history yet")}- </h3>- <p className="max-w-sm text-center text-sm">- {t(- "Describe what you want to learn on the left, and your guided learning sessions will appear here.",- )}- </p>- </div>- );- }-- return (- <div className="flex-1 overflow-y-auto p-4">- <h3 className="mb-3 text-xs font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Learning History")}- </h3>- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">- {sessions.map((session) => (- <button- key={session.session_id}- onClick={() => onLoadSession(session.session_id)}- className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 text-left shadow-sm transition-all hover:-translate-y-0.5 hover:border-[var(--primary)]/40 hover:shadow-md"- >- <p className="mb-2 line-clamp-2 text-sm font-medium text-[var(--foreground)]">- {session.topic || t("Untitled")}- </p>- <div className="mb-2 flex items-center gap-2">- <StatusBadge status={session.status} />- <span className="flex items-center gap-0.5 text-[10px] text-[var(--muted-foreground)]">- <Clock className="h-3 w-3" />- {new Date(session.created_at * 1000).toLocaleDateString()}- </span>- </div>- <div className="flex items-center gap-2">- <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--muted)]">- <div- className="h-full rounded-full bg-[var(--primary)] transition-all"- style={{ width: `${session.progress}%` }}- />- </div>- <span className="shrink-0 text-[10px] text-[var(--muted-foreground)]">- {session.ready_count}/{session.total_points}- </span>- </div>- </button>- ))}- </div>- </div>- );-}diff --git a/web/app/(workspace)/guide/components/SessionSwitcher.tsx b/web/app/(workspace)/guide/components/SessionSwitcher.tsxdeleted file mode 100644index e2ed786ca..000000000--- a/web/app/(workspace)/guide/components/SessionSwitcher.tsx+++ /dev/null@@ -1,141 +0,0 @@-"use client";--import { useState, useRef, useEffect } from "react";-import {- ChevronDown,- Plus,- Clock,- CheckCircle2,- BookOpen,- FileText,-} from "lucide-react";-import { SessionSummary } from "../types";-import { useTranslation } from "react-i18next";--interface SessionSwitcherProps {- currentSessionId: string | null;- currentTopic: string;- currentStatus: string;- sessions: SessionSummary[];- onLoadSession: (sessionId: string) => void;- onNewSession: () => void;-}--function StatusBadge({ status }: { status: string }) {- const { t } = useTranslation();- if (status === "completed") {- return (- <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/15 px-2 py-0.5 text-[10px] font-semibold text-emerald-700 dark:text-emerald-300">- <CheckCircle2 className="h-3 w-3" />- {t("Completed")}- </span>- );- }- if (status === "learning") {- return (- <span className="inline-flex items-center gap-1 rounded-full bg-[var(--primary)]/12 px-2 py-0.5 text-[10px] font-semibold text-[var(--primary)]">- <BookOpen className="h-3 w-3" />- {t("In Progress")}- </span>- );- }- return (- <span className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-2 py-0.5 text-[10px] font-semibold text-[var(--muted-foreground)]">- <FileText className="h-3 w-3" />- {t("Planned")}- </span>- );-}--export default function SessionSwitcher({- currentSessionId,- currentTopic,- currentStatus,- sessions,- onLoadSession,- onNewSession,-}: SessionSwitcherProps) {- const { t } = useTranslation();- const [open, setOpen] = useState(false);- const containerRef = useRef<HTMLDivElement>(null);-- useEffect(() => {- const handleClickOutside = (e: MouseEvent) => {- if (- containerRef.current &&- !containerRef.current.contains(e.target as Node)- ) {- setOpen(false);- }- };- document.addEventListener("mousedown", handleClickOutside);- return () => document.removeEventListener("mousedown", handleClickOutside);- }, []);-- const otherSessions = sessions.filter(- (s) => s.session_id !== currentSessionId,- );-- return (- <div ref={containerRef} className="relative shrink-0">- <button- onClick={() => setOpen(!open)}- className="flex w-full items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-left transition-colors hover:bg-[var(--muted)]/40"- >- <div className="min-w-0 flex-1">- <p className="truncate text-sm font-medium text-[var(--foreground)]">- {currentTopic || t("Untitled Session")}- </p>- <StatusBadge status={currentStatus} />- </div>- <ChevronDown- className={`h-4 w-4 shrink-0 text-[var(--muted-foreground)] transition-transform ${open ? "rotate-180" : ""}`}- />- </button>-- {open && (- <div className="absolute left-0 right-0 top-full z-30 mt-1 max-h-64 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--popover)] text-[var(--popover-foreground)] shadow-lg">- {otherSessions.length > 0 && (- <div className="py-1">- {otherSessions.map((session) => (- <button- key={session.session_id}- onClick={() => {- onLoadSession(session.session_id);- setOpen(false);- }}- className="flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-[var(--muted)]/60"- >- <div className="min-w-0 flex-1">- <p className="truncate text-xs font-medium text-[var(--foreground)]">- {session.topic || t("Untitled")}- </p>- <div className="mt-0.5 flex items-center gap-2">- <StatusBadge status={session.status} />- <span className="flex items-center gap-0.5 text-[10px] text-[var(--muted-foreground)]">- <Clock className="h-3 w-3" />- {new Date(session.created_at * 1000).toLocaleDateString()}- </span>- </div>- </div>- </button>- ))}- </div>- )}- <div className="border-t border-[var(--border)] p-2">- <button- onClick={() => {- onNewSession();- setOpen(false);- }}- className="flex w-full items-center justify-center gap-1.5 rounded-lg bg-[var(--primary)]/10 px-3 py-2 text-xs font-medium text-[var(--primary)] transition-colors hover:bg-[var(--primary)]/18"- >- <Plus className="h-3.5 w-3.5" />- {t("New Session")}- </button>- </div>- </div>- )}- </div>- );-}diff --git a/web/app/(workspace)/guide/components/index.ts b/web/app/(workspace)/guide/components/index.tsdeleted file mode 100644index 3364bdc53..000000000--- a/web/app/(workspace)/guide/components/index.ts+++ /dev/null@@ -1,9 +0,0 @@-export { default as NotebookSelector } from "./NotebookSelector";-export { default as ProgressPanel } from "./ProgressPanel";-export { default as KnowledgeTabBar } from "./KnowledgeTabBar";-export { default as SessionSwitcher } from "./SessionSwitcher";-export { default as SessionHistoryList } from "./SessionHistoryList";-export { default as ChatPanel } from "./ChatPanel";-export { default as HTMLViewer } from "./HTMLViewer";-export { default as DebugModal } from "./DebugModal";-export { default as CompletionSummary } from "./CompletionSummary";diff --git a/web/app/(workspace)/guide/hooks/index.ts b/web/app/(workspace)/guide/hooks/index.tsdeleted file mode 100644index b22a27d0a..000000000--- a/web/app/(workspace)/guide/hooks/index.ts+++ /dev/null@@ -1,4 +0,0 @@-export { useGuideSession } from "./useGuideSession";-export { useGuideHistory } from "./useGuideHistory";-export { useNotebookSelection } from "./useNotebookSelection";-export { useKaTeXInjection } from "./useKaTeXInjection";diff --git a/web/app/(workspace)/guide/hooks/useGuideHistory.ts b/web/app/(workspace)/guide/hooks/useGuideHistory.tsdeleted file mode 100644index 8da073d6d..000000000--- a/web/app/(workspace)/guide/hooks/useGuideHistory.ts+++ /dev/null@@ -1,33 +0,0 @@-import { useState, useCallback, useEffect } from "react";-import { apiUrl } from "@/lib/api";-import { SessionSummary } from "../types";--export function useGuideHistory() {- const [sessions, setSessions] = useState<SessionSummary[]>([]);- const [loading, setLoading] = useState(false);-- const fetchHistory = useCallback(async () => {- setLoading(true);- try {- const res = await fetch(apiUrl("/api/v1/guide/sessions"));- if (!res.ok) {- setSessions([]);- return;- }- const data = await res.json();- setSessions(- Array.isArray(data.sessions) ? (data.sessions as SessionSummary[]) : [],- );- } catch {- setSessions([]);- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- void fetchHistory();- }, [fetchHistory]);-- return { sessions, loading, refresh: fetchHistory };-}diff --git a/web/app/(workspace)/guide/hooks/useGuideSession.ts b/web/app/(workspace)/guide/hooks/useGuideSession.tsdeleted file mode 100644index 2b8c8dbde..000000000--- a/web/app/(workspace)/guide/hooks/useGuideSession.ts+++ /dev/null@@ -1,1021 +0,0 @@-import { useState, useCallback, useEffect, useRef, useMemo } from "react";-import { apiUrl } from "@/lib/api";-import {- SessionState,- ChatMessage,- KnowledgePoint,- INITIAL_SESSION_STATE,- PageStatus,-} from "../types";-import {- loadFromStorage,- removeFromStorage,- saveToStorage,- persistState,- mergeWithDefaults,- STORAGE_KEYS,-} from "@/lib/persistence";-import { debounce } from "@/lib/debounce";--const GUIDE_CHAT_KEY = "guide_chat_messages";-const GUIDE_SESSION_EXCLUDE: (keyof SessionState)[] = ["html_pages"];--type PagePayload = {- page_statuses?: Record<number, PageStatus>;- page_errors?: Record<number, string>;- html_pages?: Record<number, string>;- progress?: number;- current_index?: number;- status?: SessionState["status"];-};--export function useGuideSession() {- const isHydrated = useRef(false);- const pollingRef = useRef<number | null>(null);-- const [sessionState, setSessionState] = useState<SessionState>(- INITIAL_SESSION_STATE,- );- const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);- const [isLoading, setIsLoading] = useState(false);- const [loadingMessage, setLoadingMessage] = useState("");- const hasUnresolvedPages = Object.values(sessionState.page_statuses).some(- (status) => status === "pending" || status === "generating",- );-- const stopPolling = useCallback(() => {- if (pollingRef.current !== null) {- window.clearInterval(pollingRef.current);- pollingRef.current = null;- }- }, []);-- const clearPersistedGuideState = useCallback(() => {- removeFromStorage(STORAGE_KEYS.GUIDE_SESSION);- removeFromStorage(GUIDE_CHAT_KEY);- }, []);-- const resetGuideState = useCallback(- (message?: string) => {- stopPolling();- clearPersistedGuideState();- setSessionState(INITIAL_SESSION_STATE);- setIsLoading(false);- setLoadingMessage("");- setChatMessages(- message- ? [- {- id: `reset-${Date.now()}`,- role: "system",- content: message,- timestamp: Date.now(),- },- ]- : [],- );- },- [clearPersistedGuideState, stopPolling],- );-- const isSessionMissingResponse = useCallback(- (status: number, data: unknown) => {- if (status === 404) return true;- if (!data || typeof data !== "object") return false;-- const payload = data as Record<string, unknown>;- const error = typeof payload.error === "string" ? payload.error : "";- const detail = typeof payload.detail === "string" ? payload.detail : "";-- return (- error === "Session does not exist" ||- detail === "Session not found" ||- detail === "Session not found or no HTML content"- );- },- [],- );-- const saveSessionState = useMemo(- () =>- debounce((state: SessionState) => {- const toSave = persistState(state, GUIDE_SESSION_EXCLUDE);- saveToStorage(STORAGE_KEYS.GUIDE_SESSION, toSave);- }, 500),- [],- );-- const saveChatMessages = useMemo(- () =>- debounce((messages: ChatMessage[]) => {- saveToStorage(GUIDE_CHAT_KEY, messages);- }, 500),- [],- );-- const addLoadingMessage = useCallback((message: string) => {- const loadingMsg: ChatMessage = {- id: `loading-${Date.now()}`,- role: "system",- content: `⏳ ${message}`,- timestamp: Date.now(),- };- setChatMessages((prev) => [...prev, loadingMsg]);- return loadingMsg.id;- }, []);-- const removeLoadingMessage = useCallback((id: string) => {- setChatMessages((prev) => prev.filter((msg) => msg.id !== id));- }, []);-- const addChatMessage = useCallback(- (- role: "user" | "assistant" | "system",- content: string,- id?: string,- knowledge_index?: number | null,- ) => {- setChatMessages((prev) => [- ...prev,- {- id: id || `${role}-${Date.now()}`,- role,- content,- timestamp: Date.now(),- knowledge_index,- },- ]);- },- [],- );-- const mergePageState = useCallback((payload: PagePayload) => {- setSessionState((prev) => {- const mergedHtmlPages = {- ...prev.html_pages,- ...(payload.html_pages || {}),- };- const mergedStatuses = {- ...prev.page_statuses,- ...(payload.page_statuses || {}),- };- const mergedErrors = {- ...prev.page_errors,- ...(payload.page_errors || {}),- };-- let currentIndex = prev.current_index;- // Only accept current_index from server/payload if user hasn't navigated yet.- // This prevents polling from overwriting the user's tab selection.- if (typeof payload.current_index === "number" && prev.current_index < 0) {- currentIndex = payload.current_index;- }-- if (currentIndex < 0) {- const firstReadyKey = Object.keys(mergedStatuses).find(- (key) => mergedStatuses[Number(key)] === "ready",- );- if (firstReadyKey !== undefined) {- currentIndex = Number(firstReadyKey);- }- }-- return {- ...prev,- html_pages: mergedHtmlPages,- page_statuses: mergedStatuses,- page_errors: mergedErrors,- current_index: currentIndex,- progress: payload.progress ?? prev.progress,- status: payload.status ?? prev.status,- };- });- }, []);-- const fetchPageStatuses = useCallback(async () => {- if (!sessionState.session_id) return;-- try {- const res = await fetch(- apiUrl(`/api/v1/guide/session/${sessionState.session_id}/pages`),- );- let data: unknown = null;- try {- data = await res.json();- } catch {- data = null;- }-- if (!res.ok && isSessionMissingResponse(res.status, data)) {- resetGuideState(- "⚠️ Guided learning session expired. Please generate a new learning plan.",- );- return;- }-- if (!res.ok || !data || typeof data !== "object") {- return;- }-- const payload = data as Record<string, unknown>;- const pageStatuses =- (payload.page_statuses as Record<number, PageStatus> | undefined) || {};- const allStatuses = Object.values(pageStatuses);- const resolved =- allStatuses.length > 0 &&- allStatuses.every((status) => status === "ready" || status === "failed");-- mergePageState({- page_statuses: pageStatuses,- page_errors:- (payload.page_errors as Record<number, string> | undefined) || {},- html_pages:- (payload.html_pages as Record<number, string> | undefined) || {},- progress: typeof payload.progress === "number" ? payload.progress : 0,- current_index:- typeof payload.current_index === "number"- ? payload.current_index- : undefined,- status:- typeof payload.status === "string"- ? (payload.status as SessionState["status"])- : undefined,- });-- if (resolved) {- stopPolling();- }- } catch (err) {- console.error("Failed to fetch page statuses:", err);- }- }, [- isSessionMissingResponse,- mergePageState,- resetGuideState,- sessionState.session_id,- stopPolling,- ]);-- useEffect(() => {- if (typeof window === "undefined") return;- let cancelled = false;-- const restoreSession = async () => {- const persistedSession = loadFromStorage<Partial<SessionState>>(- STORAGE_KEYS.GUIDE_SESSION,- {},- );- const persistedChat = loadFromStorage<ChatMessage[]>(GUIDE_CHAT_KEY, []);- const persistedSessionId =- typeof persistedSession.session_id === "string"- ? persistedSession.session_id- : null;-- if (!persistedSessionId) {- if (- Object.keys(persistedSession).length > 0 ||- persistedChat.length > 0- ) {- clearPersistedGuideState();- }- isHydrated.current = true;- return;- }-- try {- const res = await fetch(- apiUrl(`/api/v1/guide/session/${persistedSessionId}`),- );- let data: unknown = null;- try {- data = await res.json();- } catch {- data = null;- }-- if (!res.ok && isSessionMissingResponse(res.status, data)) {- if (!cancelled) {- resetGuideState(- "⚠️ Previous guided learning session expired. Please generate a new learning plan.",- );- }- return;- }-- if (!cancelled) {- setSessionState((prev) =>- mergeWithDefaults(persistedSession, prev, GUIDE_SESSION_EXCLUDE),- );- if (persistedChat.length > 0) {- setChatMessages(persistedChat);- }- }- } catch {- if (!cancelled) {- setSessionState((prev) =>- mergeWithDefaults(persistedSession, prev, GUIDE_SESSION_EXCLUDE),- );- if (persistedChat.length > 0) {- setChatMessages(persistedChat);- }- }- } finally {- isHydrated.current = true;- }- };-- void restoreSession();-- return () => {- cancelled = true;- };- }, [clearPersistedGuideState, isSessionMissingResponse, resetGuideState]);-- useEffect(() => {- if (isHydrated.current) {- saveSessionState(sessionState);- }- }, [sessionState, saveSessionState]);-- useEffect(() => {- if (isHydrated.current) {- saveChatMessages(chatMessages);- }- }, [chatMessages, saveChatMessages]);-- useEffect(() => {- if (- sessionState.status !== "learning" ||- !sessionState.session_id ||- !hasUnresolvedPages- ) {- stopPolling();- return;- }-- void fetchPageStatuses();- if (pollingRef.current === null) {- pollingRef.current = window.setInterval(() => {- void fetchPageStatuses();- }, 2000);- }-- return () => {- stopPolling();- };- }, [- fetchPageStatuses,- hasUnresolvedPages,- sessionState.session_id,- sessionState.status,- stopPolling,- ]);-- const createSession = useCallback(- async (- userInput: string,- notebookReferences?: Array<{ notebook_id: string; record_ids: string[] }>,- ) => {- const trimmedInput = userInput.trim();- if (!trimmedInput) return;-- stopPolling();- setIsLoading(true);- setLoadingMessage("Designing your guided learning plan...");- const loadingId = addLoadingMessage(- "Designing your guided learning plan...",- );-- try {- const res = await fetch(apiUrl("/api/v1/guide/create_session"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- user_input: trimmedInput,- ...(notebookReferences?.length- ? { notebook_references: notebookReferences }- : {}),- }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");-- if (data.success) {- const initialStatuses: Record<number, PageStatus> = {};- (data.knowledge_points || []).forEach(- (_kp: KnowledgePoint, idx: number) => {- initialStatuses[idx] = "pending";- },- );-- setSessionState({- session_id: data.session_id,- topic: trimmedInput,- knowledge_points: data.knowledge_points || [],- current_index: -1,- html_pages: {},- page_statuses: initialStatuses,- page_errors: {},- status: "initialized",- progress: 0,- summary: "",- });-- const planMessage = `📚 Learning plan generated with **${data.total_points}** knowledge points:\n\n${data.knowledge_points.map((kp: KnowledgePoint, idx: number) => `${idx + 1}. ${kp.knowledge_title}`).join("\n")}\n\nClick "Start Learning" to generate all interactive pages in parallel.`;- setChatMessages([- {- id: "plan",- role: "system",- content: planMessage,- timestamp: Date.now(),- },- ]);- } else {- addChatMessage(- "system",- `❌ Failed to create session: ${data.error}`,- `error-${Date.now()}`,- );- }- } catch (err) {- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");- console.error("Failed to create session:", err);- addChatMessage(- "system",- "❌ Failed to create session, please try again later",- `error-${Date.now()}`,- );- }- },- [addChatMessage, addLoadingMessage, removeLoadingMessage, stopPolling],- );-- const startLearning = useCallback(async () => {- if (!sessionState.session_id) return;-- setIsLoading(true);- setLoadingMessage("Generating interactive learning pages...");- const loadingId = addLoadingMessage(- "Generating interactive learning pages...",- );-- try {- const res = await fetch(apiUrl("/api/v1/guide/start"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ session_id: sessionState.session_id }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);-- if (isSessionMissingResponse(res.status, data)) {- resetGuideState(- "⚠️ Guided learning session expired. Please generate a new learning plan.",- );- return;- }-- setIsLoading(false);- setLoadingMessage("");-- if (data.success) {- setSessionState((prev) => ({- ...prev,- current_index: typeof data.current_index === "number" ? data.current_index : 0,- html_pages: data.html- ? { ...prev.html_pages, 0: data.html as string }- : prev.html_pages,- page_statuses: {- ...prev.page_statuses,- ...(data.page_statuses || {}),- },- status: "learning",- progress: data.progress || 0,- }));-- addChatMessage(- "system",- data.message ||- "Interactive pages are generating in parallel. Open any page once it becomes ready.",- `start-${Date.now()}`,- );- } else {- addChatMessage(- "system",- `❌ Failed to start learning: ${data.error || "Unknown error"}`,- `error-${Date.now()}`,- );- }- } catch (err) {- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");- console.error("Failed to start learning:", err);- addChatMessage(- "system",- "❌ Failed to start learning, please try again later",- `error-${Date.now()}`,- );- }- }, [- addChatMessage,- addLoadingMessage,- isSessionMissingResponse,- removeLoadingMessage,- resetGuideState,- sessionState.session_id,- ]);-- const navigateTo = useCallback(- async (knowledgeIndex: number) => {- if (!sessionState.session_id) return;-- setSessionState((prev) => ({- ...prev,- current_index: knowledgeIndex,- }));-- if (- sessionState.page_statuses[knowledgeIndex] === "ready" &&- sessionState.html_pages[knowledgeIndex]- ) {- return;- }-- try {- const res = await fetch(apiUrl("/api/v1/guide/navigate"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- session_id: sessionState.session_id,- knowledge_index: knowledgeIndex,- }),- });- const data = await res.json();-- if (isSessionMissingResponse(res.status, data)) {- resetGuideState(- "⚠️ Guided learning session expired. Please generate a new learning plan.",- );- return;- }-- if (data.success) {- mergePageState({- current_index: knowledgeIndex,- html_pages: data.html ? { [knowledgeIndex]: data.html as string } : {},- page_statuses: data.page_status- ? { [knowledgeIndex]: data.page_status as PageStatus }- : {},- page_errors: data.page_error ? { [knowledgeIndex]: data.page_error as string } : {},- progress: typeof data.progress === "number" ? data.progress : undefined,- });- } else {- addChatMessage(- "system",- `❌ Failed to open page: ${data.error || "Unknown error"}`,- `error-${Date.now()}`,- );- }- } catch (err) {- console.error("Failed to navigate knowledge point:", err);- }- },- [- addChatMessage,- isSessionMissingResponse,- mergePageState,- resetGuideState,- sessionState.html_pages,- sessionState.page_statuses,- sessionState.session_id,- ],- );-- const retryPage = useCallback(- async (pageIndex: number) => {- if (!sessionState.session_id) return;-- try {- const res = await fetch(apiUrl("/api/v1/guide/retry_page"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- session_id: sessionState.session_id,- page_index: pageIndex,- }),- });- const data = await res.json();-- if (isSessionMissingResponse(res.status, data)) {- resetGuideState(- "⚠️ Guided learning session expired. Please generate a new learning plan.",- );- return;- }-- if (data.success) {- mergePageState({- page_statuses: { [pageIndex]: "pending" },- page_errors: { [pageIndex]: "" },- });- addChatMessage(- "system",- data.message || `Retrying page ${pageIndex + 1}.`,- `retry-${Date.now()}`,- pageIndex,- );- }- } catch (err) {- console.error("Failed to retry page:", err);- }- },- [- addChatMessage,- isSessionMissingResponse,- mergePageState,- resetGuideState,- sessionState.session_id,- ],- );-- const completeLearning = useCallback(async () => {- if (!sessionState.session_id) return;-- setIsLoading(true);- setLoadingMessage("Generating learning summary...");- const loadingId = addLoadingMessage("Generating learning summary...");-- try {- const res = await fetch(apiUrl("/api/v1/guide/complete"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ session_id: sessionState.session_id }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");-- if (isSessionMissingResponse(res.status, data)) {- resetGuideState(- "⚠️ Guided learning session expired. Please generate a new learning plan.",- );- return;- }-- if (data.success) {- stopPolling();- setSessionState((prev) => ({- ...prev,- status: "completed",- summary: data.summary || "",- progress: 100,- }));- addChatMessage(- "system",- data.message || "Guided learning completed.",- `complete-${Date.now()}`,- );- }- } catch (err) {- removeLoadingMessage(loadingId);- setIsLoading(false);- setLoadingMessage("");- console.error("Failed to complete learning:", err);- }- }, [- addChatMessage,- addLoadingMessage,- isSessionMissingResponse,- removeLoadingMessage,- resetGuideState,- sessionState.session_id,- stopPolling,- ]);-- const sendMessage = useCallback(- async (message: string) => {- if (- !message.trim() ||- !sessionState.session_id ||- sessionState.current_index < 0 ||- sessionState.page_statuses[sessionState.current_index] !== "ready"- ) {- return;- }-- const knowledgeIndex = sessionState.current_index;- addChatMessage(- "user",- message,- `user-${Date.now()}`,- knowledgeIndex,- );- const loadingId = addLoadingMessage("Thinking...");-- try {- const res = await fetch(apiUrl("/api/v1/guide/chat"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- session_id: sessionState.session_id,- message,- knowledge_index: knowledgeIndex,- }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);-- if (isSessionMissingResponse(res.status, data)) {- resetGuideState(- "⚠️ Guided learning session expired. Please generate a new learning plan.",- );- return;- }-- if (data.success) {- addChatMessage(- "assistant",- data.answer || "",- `assistant-${Date.now()}`,- typeof data.knowledge_index === "number"- ? data.knowledge_index- : knowledgeIndex,- );- } else {- addChatMessage(- "assistant",- `❌ Error: ${data.error || "Failed to respond"}`,- `error-${Date.now()}`,- knowledgeIndex,- );- }- } catch (err) {- removeLoadingMessage(loadingId);- console.error("Failed to send message:", err);- addChatMessage(- "assistant",- "❌ Failed to send message, please try again later",- `error-${Date.now()}`,- knowledgeIndex,- );- }- },- [- addChatMessage,- addLoadingMessage,- isSessionMissingResponse,- removeLoadingMessage,- resetGuideState,- sessionState.current_index,- sessionState.page_statuses,- sessionState.session_id,- ],- );-- const fixHtml = useCallback(- async (bugDescription: string) => {- if (- !sessionState.session_id ||- !bugDescription.trim() ||- sessionState.current_index < 0- ) {- return false;- }-- const currentIndex = sessionState.current_index;- const loadingId = addLoadingMessage("Fixing HTML page...");-- try {- const res = await fetch(apiUrl("/api/v1/guide/fix_html"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- session_id: sessionState.session_id,- bug_description: bugDescription,- }),- });- const data = await res.json();-- removeLoadingMessage(loadingId);-- if (isSessionMissingResponse(res.status, data)) {- resetGuideState(- "⚠️ Guided learning session expired. Please generate a new learning plan.",- );- return false;- }-- if (data.success) {- mergePageState({- html_pages: {- [currentIndex]:- (data.html as string) || sessionState.html_pages[currentIndex],- },- page_statuses: { [currentIndex]: "ready" },- });- addChatMessage(- "system",- "✅ HTML page has been fixed!",- `fix-${Date.now()}`,- currentIndex,- );- return true;- }-- addChatMessage(- "system",- `❌ Fix failed: ${data.error || "Unknown error"}`,- `error-${Date.now()}`,- currentIndex,- );- return false;- } catch (err) {- removeLoadingMessage(loadingId);- console.error("Failed to fix HTML:", err);- addChatMessage(- "system",- "❌ Fix failed, please try again later",- `error-${Date.now()}`,- currentIndex,- );- return false;- }- },- [- addChatMessage,- addLoadingMessage,- isSessionMissingResponse,- mergePageState,- removeLoadingMessage,- resetGuideState,- sessionState.current_index,- sessionState.html_pages,- sessionState.session_id,- ],- );-- const resetSession = useCallback(async () => {- const sessionId = sessionState.session_id;- resetGuideState();-- if (!sessionId) return;- try {- await fetch(apiUrl("/api/v1/guide/reset"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ session_id: sessionId }),- });- } catch (err) {- console.error("Failed to reset session on backend:", err);- }- }, [resetGuideState, sessionState.session_id]);-- const loadSession = useCallback(- async (sessionId: string) => {- stopPolling();- setIsLoading(true);- setLoadingMessage("Loading session...");-- try {- const res = await fetch(apiUrl(`/api/v1/guide/session/${sessionId}`));- if (!res.ok) {- setIsLoading(false);- setLoadingMessage("");- addChatMessage(- "system",- "Failed to load session.",- `error-${Date.now()}`,- );- return;- }-- const data = await res.json();- const knowledgePoints: KnowledgePoint[] =- data.knowledge_points || [];- const htmlPages: Record<number, string> = {};- const pageStatuses: Record<number, PageStatus> = {};- const pageErrors: Record<number, string> = {};-- if (data.html_pages && typeof data.html_pages === "object") {- for (const [key, val] of Object.entries(data.html_pages)) {- htmlPages[Number(key)] = val as string;- }- }- if (data.page_statuses && typeof data.page_statuses === "object") {- for (const [key, val] of Object.entries(data.page_statuses)) {- pageStatuses[Number(key)] = val as PageStatus;- }- }- if (data.page_errors && typeof data.page_errors === "object") {- for (const [key, val] of Object.entries(data.page_errors)) {- pageErrors[Number(key)] = val as string;- }- }-- const restoredMessages: ChatMessage[] = [];- if (Array.isArray(data.chat_history)) {- for (const msg of data.chat_history) {- if (msg.role && msg.content) {- restoredMessages.push({- id: `restored-${msg.timestamp || Date.now()}-${Math.random()}`,- role: msg.role as ChatMessage["role"],- content: msg.content,- timestamp: msg.timestamp ? msg.timestamp * 1000 : Date.now(),- knowledge_index:- typeof msg.knowledge_index === "number"- ? msg.knowledge_index- : undefined,- });- }- }- }-- setSessionState({- session_id: data.session_id || sessionId,- topic: data.notebook_name || "",- knowledge_points: knowledgePoints,- current_index:- typeof data.current_index === "number" ? data.current_index : -1,- html_pages: htmlPages,- page_statuses: pageStatuses,- page_errors: pageErrors,- status: data.status || "initialized",- progress:- typeof data.progress === "number"- ? data.progress- : knowledgePoints.length > 0- ? Math.round(- (Object.values(pageStatuses).filter((s) => s === "ready")- .length /- knowledgePoints.length) *- 100,- )- : 0,- summary: data.summary || "",- });-- setChatMessages(restoredMessages);- setIsLoading(false);- setLoadingMessage("");- } catch (err) {- console.error("Failed to load session:", err);- setIsLoading(false);- setLoadingMessage("");- addChatMessage(- "system",- "Failed to load session, please try again later.",- `error-${Date.now()}`,- );- }- },- [addChatMessage, stopPolling],- );-- const canStart =- sessionState.status === "initialized" &&- sessionState.knowledge_points.length > 0;- const isCompleted = sessionState.status === "completed";- const readyCount = Object.values(sessionState.page_statuses).filter(- (status) => status === "ready",- ).length;- const allPagesReady =- sessionState.knowledge_points.length > 0 &&- readyCount === sessionState.knowledge_points.length;- const currentPageStatus =- sessionState.current_index >= 0- ? sessionState.page_statuses[sessionState.current_index]- : undefined;- const currentPageReady = currentPageStatus === "ready";-- return {- sessionState,- chatMessages,- isLoading,- loadingMessage,- canStart,- isCompleted,- readyCount,- allPagesReady,- currentPageStatus,- currentPageReady,- createSession,- startLearning,- navigateTo,- retryPage,- completeLearning,- sendMessage,- fixHtml,- resetSession,- loadSession,- };-}diff --git a/web/app/(workspace)/guide/hooks/useKaTeXInjection.ts b/web/app/(workspace)/guide/hooks/useKaTeXInjection.tsdeleted file mode 100644index e90cd63ca..000000000--- a/web/app/(workspace)/guide/hooks/useKaTeXInjection.ts+++ /dev/null@@ -1,67 +0,0 @@-/**- * Hook for injecting KaTeX resources + render script into HTML content.- *- * Strategy: inject CDN resources into <head> + a small inline init script- * that polls for renderMathInElement availability. HTMLViewer also has- * a parent-window fallback in case the inline script gets corrupted by- * page content containing "</script>" strings.- */-export function useKaTeXInjection() {- const injectKaTeX = (html: string): string => {- const htmlLower = html.toLowerCase();- const hasKaTeX =- htmlLower.includes("katex.min.css") ||- htmlLower.includes("katex.min.js") ||- htmlLower.includes("katex@") ||- htmlLower.includes("cdn.jsdelivr.net/npm/katex") ||- htmlLower.includes("unpkg.com/katex");-- if (hasKaTeX) {- console.log("[KaTeX] Already included, skipping injection");- return html;- }-- // CDN resources (no SRI hash to avoid mismatch)- const katexResources = [- '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" crossorigin="anonymous">',- '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" crossorigin="anonymous"><' + "/script>",- '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" crossorigin="anonymous"><' + "/script>",- ].join("\n ");-- // Inline render script — placed in <head> with DOMContentLoaded listener.- // Uses data-katex-init attr so sanitizer preserves it (contains "katex").- // Polls every 100ms up to 5s for auto-render to load via defer.- // eslint-disable-next-line no-template-curly-in-string- const katexInit =- '<script data-katex-init>' +- 'document.addEventListener("DOMContentLoaded",function(){var t=0,i=setInterval(function(){if(typeof renderMathInElement==="function"){clearInterval(i);try{renderMathInElement(document.body,{delimiters:[{left:"$$",right:"$$",display:true},{left:"$",right:"$",display:false},{left:"\\\\(",right:"\\\\)",display:false},{left:"\\\\[",right:"\\\\]",display:true}],throwOnError:false});console.log("[KaTeX] Rendered "+document.querySelectorAll(".katex").length+" formulas")}catch(e){console.error("[KaTeX] Error:",e)}}else if(++t>50){clearInterval(i);console.warn("[KaTeX] Timeout")}},100)});' +- "<" + "/script>";-- const headContent = katexResources + "\n " + katexInit;-- // Inject into <head>- if (html.includes("</head>")) {- return html.replace("</head>", headContent + "\n</head>");- }- if (html.includes("<head>")) {- return html.replace(/<head([^>]*)>/i, "<head$1>\n" + headContent);- }- if (html.includes("<html")) {- return html.replace(- /(<html[^>]*>)/i,- "$1\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + headContent + "\n</head>",- );- }-- // Wrap bare content- return (- "<!DOCTYPE html>\n<html lang=\"zh\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +- headContent +- "\n</head>\n<body>\n" +- html +- "\n</body>\n</html>"- );- };-- return { injectKaTeX };-}diff --git a/web/app/(workspace)/guide/page.tsx b/web/app/(workspace)/guide/page.tsxdeleted file mode 100644index d6309c2b1..000000000--- a/web/app/(workspace)/guide/page.tsx+++ /dev/null@@ -1,428 +0,0 @@-"use client";--import { useEffect, useMemo, useState } from "react";-import {- BookOpen,- ChevronRight,- ChevronLeft,- ArrowRight,- Loader2,- Sparkles,-} from "lucide-react";-import "katex/dist/katex.min.css";--import type { SelectedRecord } from "./types";-import NotebookRecordPicker from "@/components/notebook/NotebookRecordPicker";-import SaveToNotebookModal from "@/components/notebook/SaveToNotebookModal";-import {- ChatPanel,- HTMLViewer,- DebugModal,- CompletionSummary,- KnowledgeTabBar,- SessionSwitcher,- SessionHistoryList,-} from "./components";-import { useGuideSession, useGuideHistory } from "./hooks";-import { useTranslation } from "react-i18next";--export default function GuidePage() {- const { t } = useTranslation();-- const {- sessionState,- chatMessages,- isLoading,- loadingMessage,- canStart,- isCompleted,- readyCount,- allPagesReady,- currentPageReady,- createSession,- startLearning,- navigateTo,- retryPage,- completeLearning,- sendMessage,- fixHtml,- resetSession,- loadSession,- } = useGuideSession();-- const { sessions, loading: historyLoading, refresh: refreshHistory } = useGuideHistory();-- const [showDebugModal, setShowDebugModal] = useState(false);- const [sidebarCollapsed, setSidebarCollapsed] = useState(false);- const [sidebarWide, setSidebarWide] = useState(false);- const [topicInput, setTopicInput] = useState("");- const [showNotebookPicker, setShowNotebookPicker] = useState(false);- const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<- SelectedRecord[]- >([]);- const [showSaveModal, setShowSaveModal] = useState(false);-- const [hiddenSummaryBySession, setHiddenSummaryBySession] = useState<- Record<string, boolean>- >({});-- const leftWidthPercent = sidebarCollapsed ? 0 : sidebarWide ? 75 : 25;- const rightWidthPercent = sidebarCollapsed ? 100 : sidebarWide ? 25 : 75;- const isIdle = sessionState.status === "idle";- const currentSessionKey = sessionState.session_id || "__guide__";- const showingSummary =- sessionState.status === "completed" &&- Boolean(sessionState.summary) &&- !hiddenSummaryBySession[currentSessionKey];- const notebookReferenceGroups = useMemo(() => {- const groups = new Map<string, { notebookName: string; count: number }>();- selectedNotebookRecords.forEach((record) => {- const existing = groups.get(record.notebookId);- if (existing) {- existing.count += 1;- } else {- groups.set(record.notebookId, {- notebookName: record.notebookName,- count: 1,- });- }- });- return Array.from(groups.entries()).map(([notebookId, value]) => ({- notebookId,- ...value,- }));- }, [selectedNotebookRecords]);- const notebookReferencesPayload = useMemo(() => {- const grouped = new Map<string, string[]>();- selectedNotebookRecords.forEach((record) => {- const current = grouped.get(record.notebookId) || [];- current.push(record.id);- grouped.set(record.notebookId, current);- });- return Array.from(grouped.entries()).map(([notebook_id, record_ids]) => ({- notebook_id,- record_ids,- }));- }, [selectedNotebookRecords]);- const guideSavePayload = useMemo(() => {- if (sessionState.status === "idle" || !sessionState.session_id) return null;- return {- recordType: "guided_learning" as const,- title: sessionState.topic || "Guided Learning Session",- userQuery: sessionState.topic || "",- output: JSON.stringify(- {- topic: sessionState.topic,- status: sessionState.status,- knowledge_points: sessionState.knowledge_points,- current_index: sessionState.current_index,- html_pages: sessionState.html_pages,- page_statuses: sessionState.page_statuses,- summary: sessionState.summary,- },- null,- 2,- ),- metadata: {- source: "guided_learning",- progress: sessionState.progress,- session_id: sessionState.session_id,- },- };- }, [sessionState]);-- const handleCreateSession = () => {- createSession(topicInput, notebookReferencesPayload);- };-- const handleResetSession = async () => {- await resetSession();- refreshHistory();- };-- const handleLoadSession = async (sessionId: string) => {- await loadSession(sessionId);- };-- const handleFixHtml = async (description: string) => {- return await fixHtml(description);- };-- useEffect(() => {- if (typeof window === "undefined") return;- const params = new URLSearchParams(window.location.search);- const session = params.get("session");- if (session) {- void loadSession(session);- }- }, [loadSession]);-- return (- <div className="h-screen flex gap-0 p-4 animate-fade-in relative">- {/* LEFT PANEL */}- <div- className={`flex flex-col gap-3 h-full transition-all duration-300 flex-shrink-0 mr-4 ${sidebarCollapsed ? "overflow-hidden" : ""}`}- style={{- width: sidebarCollapsed ? 0 : `${leftWidthPercent}%`,- minWidth: sidebarCollapsed- ? 0- : `${Math.max(leftWidthPercent * 0.01 * 1200, 300)}px`,- maxWidth: sidebarCollapsed ? 0 : `${leftWidthPercent}%`,- }}- >- {isIdle ? (- <div className="surface-card flex flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">- <div className="border-b border-[var(--border)] bg-[var(--muted)]/35 p-3">- <h2 className="flex items-center gap-2 font-semibold text-[var(--foreground)]">- <Sparkles className="h-5 w-5 text-[var(--primary)]" />- {t("Describe what you want to learn")}- </h2>- <p className="mt-2 text-sm text-[var(--muted-foreground)]">- {t(- "Write a short learning request, and the system will design a progressive guided learning plan for you.",- )}- </p>- </div>-- <div className="space-y-4 p-4">- <textarea- value={topicInput}- onChange={(e) => setTopicInput(e.target.value)}- placeholder={t(- "For example: Teach me linear algebra from the basics, with intuition, key formulas, and common mistakes.",- )}- rows={8}- className="w-full resize-none rounded-xl border border-[var(--border)] bg-[var(--card)] px-4 py-3 text-sm text-[var(--foreground)] outline-none transition placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"- />-- <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/30 p-3.5">- <div className="flex items-center justify-between gap-2">- <div className="inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">- <BookOpen className="h-3 w-3" />- {t("Notebook Context")}- </div>- <span className="rounded-full bg-[var(--muted)] px-2 py-0.5 text-[9px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Optional")}- </span>- </div>- <p className="mt-1.5 text-xs leading-relaxed text-[var(--muted-foreground)]">- {t("Ground the plan with saved notebook records.")}- </p>- <button- onClick={() => setShowNotebookPicker(true)}- className="mt-3 inline-flex w-full items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-dashed border-[var(--border)] bg-[var(--card)] px-3 py-2 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/50 hover:bg-[var(--primary)]/8 hover:text-[var(--primary)]"- >- <BookOpen className="h-3.5 w-3.5" />- {selectedNotebookRecords.length > 0- ? t("Update selection ({n})", {- n: selectedNotebookRecords.length,- })- : t("Select records")}- </button>- {notebookReferenceGroups.length > 0 && (- <div className="mt-2.5 flex flex-wrap gap-1.5">- {notebookReferenceGroups.map((group) => (- <span- key={group.notebookId}- className="inline-flex max-w-full items-center gap-1.5 truncate rounded-full border border-[var(--border)] bg-[var(--card)] px-2.5 py-0.5 text-[11px] text-[var(--foreground)]"- title={`${group.notebookName} (${group.count})`}- >- <span className="truncate">{group.notebookName}</span>- <span className="shrink-0 text-[var(--muted-foreground)]">- {group.count}- </span>- </span>- ))}- </div>- )}- </div>-- <button- onClick={handleCreateSession}- disabled={isLoading || !topicInput.trim()}- className="btn-primary inline-flex items-center gap-2 rounded-xl bg-[var(--primary)] px-4 py-2.5 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"- >- {isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <Sparkles className="h-4 w-4" />- )}- {t("Generate learning plan")}- </button>- </div>- </div>- ) : (- <>- <div className="flex items-center justify-end">- <button- onClick={() => setShowSaveModal(true)}- className="inline-flex items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-sm font-medium text-[var(--foreground)] transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/8 hover:text-[var(--primary)]"- >- <BookOpen className="h-4 w-4" />- {t("Add to Notebook")}- </button>- </div>- <SessionSwitcher- currentSessionId={sessionState.session_id}- currentTopic={sessionState.topic}- currentStatus={sessionState.status}- sessions={sessions}- onLoadSession={handleLoadSession}- onNewSession={handleResetSession}- />- <ChatPanel- messages={chatMessages}- isLearning={sessionState.status === "learning" && currentPageReady}- currentKnowledgeTitle={- sessionState.current_index >= 0- ? sessionState.knowledge_points[sessionState.current_index]- ?.knowledge_title- : undefined- }- currentKnowledgeIndex={- sessionState.current_index >= 0- ? sessionState.current_index- : undefined- }- onSendMessage={sendMessage}- />- </>- )}- </div>-- {/* RIGHT PANEL */}- <div- className="flex flex-col h-full overflow-hidden transition-all duration-300 flex-1 relative"- style={{ width: `${rightWidthPercent}%` }}- >- {/* Collapse/Expand buttons */}- {isIdle && (- <div className="absolute top-4 left-4 z-20 flex gap-2">- <button- onClick={() => setSidebarCollapsed(!sidebarCollapsed)}- className="rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 text-[var(--muted-foreground)] shadow-sm transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- title={- sidebarCollapsed ? t("Expand sidebar") : t("Collapse sidebar")- }- >- {sidebarCollapsed ? (- <ChevronRight className="h-4 w-4" />- ) : (- <ChevronLeft className="h-4 w-4" />- )}- </button>- {!sidebarCollapsed && (- <button- onClick={() => setSidebarWide(!sidebarWide)}- className="rounded-lg border border-[var(--border)] bg-[var(--card)] p-2 text-[var(--muted-foreground)] shadow-sm transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"- title={- sidebarWide- ? t("Switch to narrow sidebar (1:3)")- : t("Switch to wide sidebar (3:1)")- }- >- <ArrowRight- className={`h-4 w-4 transition-transform ${sidebarWide ? "rotate-180" : ""}`}- />- </button>- )}- </div>- )}-- {isIdle ? (- <div className="surface-card flex flex-1 flex-col overflow-hidden border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]">- <SessionHistoryList- sessions={sessions}- loading={historyLoading}- onLoadSession={handleLoadSession}- />- </div>- ) : (- <>- {/* Knowledge tab bar */}- <KnowledgeTabBar- sessionState={sessionState}- isLoading={isLoading}- canStart={canStart}- readyCount={readyCount}- allPagesReady={allPagesReady}- isCompleted={showingSummary}- onStartLearning={startLearning}- onNavigate={(index) => {- setHiddenSummaryBySession((prev) => ({- ...prev,- [currentSessionKey]: true,- }));- navigateTo(index);- }}- onRetryPage={retryPage}- onCompleteLearning={() => {- completeLearning();- setHiddenSummaryBySession((prev) => ({- ...prev,- [currentSessionKey]: false,- }));- }}- onResetSession={handleResetSession}- onShowSummary={() =>- setHiddenSummaryBySession((prev) => ({- ...prev,- [currentSessionKey]: false,- }))- }- />-- {/* Main content */}- <div className="flex-1 min-h-0 flex flex-col">- {showingSummary && sessionState.summary ? (- <CompletionSummary summary={sessionState.summary} />- ) : sessionState.status === "learning" || (isCompleted && !showingSummary) ? (- <HTMLViewer- html={- sessionState.current_index >= 0- ? sessionState.html_pages[sessionState.current_index] ||- ""- : ""- }- currentIndex={sessionState.current_index}- loadingMessage={- sessionState.current_index >= 0 &&- sessionState.page_statuses[sessionState.current_index] ===- "failed"- ? t(- "This page failed to generate. You can retry it from the tab bar.",- )- : loadingMessage ||- t("Waiting for the selected interactive page...")- }- onOpenDebugModal={() => setShowDebugModal(true)}- />- ) : (- <div className="flex h-full flex-col items-center justify-center rounded-b-2xl border border-t-0 border-[var(--border)] bg-[var(--card)] p-8 text-[var(--muted-foreground)]">- <Loader2 className="mb-4 h-12 w-12 animate-spin text-[var(--primary)]" />- <p>{loadingMessage || t("Loading learning content...")}</p>- </div>- )}- </div>- </>- )}- </div>-- <DebugModal- isOpen={showDebugModal}- onClose={() => setShowDebugModal(false)}- onFix={handleFixHtml}- />- <NotebookRecordPicker- open={showNotebookPicker}- onClose={() => setShowNotebookPicker(false)}- onApply={(records) => setSelectedNotebookRecords(records)}- />- <SaveToNotebookModal- open={showSaveModal}- payload={guideSavePayload}- onClose={() => setShowSaveModal(false)}- />- </div>- );-}diff --git a/web/app/(workspace)/guide/types.ts b/web/app/(workspace)/guide/types.tsdeleted file mode 100644index c70b1144e..000000000--- a/web/app/(workspace)/guide/types.ts+++ /dev/null@@ -1,95 +0,0 @@-// Guide page types--export interface Notebook {- id: string;- name: string;- description: string;- record_count: number;- color: string;-}--export interface NotebookRecord {- id: string;- title: string;- summary?: string;- user_query: string;- output: string;- type: string;-}--export interface SelectedRecord extends NotebookRecord {- notebookId: string;- notebookName: string;-}--export interface KnowledgePoint {- knowledge_title: string;- knowledge_summary: string;- user_difficulty: string;-}--export interface ChatMessage {- id: string;- role: "user" | "assistant" | "system";- content: string;- timestamp?: number;- knowledge_index?: number | null;-}--export type PageStatus = "pending" | "generating" | "ready" | "failed";--export interface SessionSummary {- session_id: string;- topic: string;- status: "initialized" | "learning" | "completed";- created_at: number;- total_points: number;- ready_count: number;- progress: number;-}--export interface SessionState {- session_id: string | null;- topic: string;- knowledge_points: KnowledgePoint[];- current_index: number;- html_pages: Record<number, string>;- page_statuses: Record<number, PageStatus>;- page_errors: Record<number, string>;- status: "idle" | "initialized" | "learning" | "completed";- progress: number;- summary: string;-}--export const INITIAL_SESSION_STATE: SessionState = {- session_id: null,- topic: "",- knowledge_points: [],- current_index: -1,- html_pages: {},- page_statuses: {},- page_errors: {},- status: "idle",- progress: 0,- summary: "",-};--// Helper to get record type color-export function getTypeColor(type: string): string {- switch (type) {- case "solve":- return "bg-blue-100 text-blue-700 border-blue-200";- case "question":- return "bg-purple-100 text-purple-700 border-purple-200";- case "research":- return "bg-emerald-100 text-emerald-700 border-emerald-200";- case "co_writer":- return "bg-amber-100 text-amber-700 border-amber-200";- case "chat":- return "bg-cyan-100 text-cyan-700 border-cyan-200";- case "guided_learning":- return "bg-rose-100 text-rose-700 border-rose-200";- default:- return "bg-slate-100 text-slate-700 border-slate-200";- }-}diff --git a/web/components/chat/AtMentionPopup.tsx b/web/components/chat/AtMentionPopup.tsxindex 29069b49c..30f0b4fce 100644--- a/web/components/chat/AtMentionPopup.tsx+++ b/web/components/chat/AtMentionPopup.tsx@@ -6,12 +6,14 @@ interface AtMentionPopupProps {open: boolean;onSelectNotebook: () => void;onSelectHistory: () => void;+ onSelectQuestionBank: () => void;}export default function AtMentionPopup({open,onSelectNotebook,onSelectHistory,+ onSelectQuestionBank,}: AtMentionPopupProps) {const { t } = useTranslation();@@ -31,6 +33,12 @@ export default function AtMentionPopup({>{t("Chat History")}</button>+ <button+ onClick={onSelectQuestionBank}+ className="w-full rounded-xl px-3 py-2.5 text-left text-[14px] font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)]/70"+ >+ {t("Question Bank")}+ </button></div>);}diff --git a/web/components/chat/QuestionBankPicker.tsx b/web/components/chat/QuestionBankPicker.tsxnew file mode 100644index 000000000..ea09806b4--- /dev/null+++ b/web/components/chat/QuestionBankPicker.tsx@@ -0,0 +1,328 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import {+ Bookmark,+ Check,+ ClipboardList,+ FolderOpen,+ Loader2,+ Search,+ X,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import {+ listCategories,+ listNotebookEntries,+ type NotebookCategory,+ type NotebookEntry,+} from "@/lib/notebook-api";++export interface SelectedQuestionEntry {+ id: number;+ question: string;+ session_title: string;+ is_correct: boolean;+ difficulty: string;+}++interface QuestionBankPickerProps {+ open: boolean;+ onClose: () => void;+ onApply: (entries: SelectedQuestionEntry[]) => void;+}++type FilterMode = "all" | "bookmarked" | "wrong";++const FILTER_MODES: { value: FilterMode; label: string }[] = [+ { value: "all", label: "All" },+ { value: "bookmarked", label: "Bookmarked" },+ { value: "wrong", label: "Wrong Only" },+];++export default function QuestionBankPicker({+ open,+ onClose,+ onApply,+}: QuestionBankPickerProps) {+ const { t } = useTranslation();+ const [entries, setEntries] = useState<NotebookEntry[]>([]);+ const [categories, setCategories] = useState<NotebookCategory[]>([]);+ const [filter, setFilter] = useState<FilterMode>("all");+ const [activeCategoryId, setActiveCategoryId] = useState<number | null>(null);+ const [selectedIds, setSelectedIds] = useState<number[]>([]);+ const [query, setQuery] = useState("");+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ if (!open) return;+ let mounted = true;+ void (async () => {+ try {+ setCategories(await listCategories());+ } catch {+ if (mounted) setCategories([]);+ }+ })();+ return () => {+ mounted = false;+ };+ }, [open]);++ useEffect(() => {+ if (!open) return;+ let mounted = true;+ setLoading(true);+ void (async () => {+ try {+ const result = await listNotebookEntries({+ bookmarked: filter === "bookmarked" ? true : undefined,+ is_correct: filter === "wrong" ? false : undefined,+ category_id: activeCategoryId ?? undefined,+ limit: 200,+ });+ if (!mounted) return;+ setEntries(result.items);+ } catch {+ if (!mounted) return;+ setEntries([]);+ } finally {+ if (mounted) setLoading(false);+ }+ })();+ return () => {+ mounted = false;+ };+ }, [open, filter, activeCategoryId]);++ const filteredEntries = useMemo(() => {+ const keyword = query.trim().toLowerCase();+ if (!keyword) return entries;+ return entries.filter((entry) => {+ const question = String(entry.question || "").toLowerCase();+ const session = String(entry.session_title || "").toLowerCase();+ return question.includes(keyword) || session.includes(keyword);+ });+ }, [entries, query]);++ const toggleEntry = (entryId: number) => {+ setSelectedIds((prev) =>+ prev.includes(entryId)+ ? prev.filter((id) => id !== entryId)+ : [...prev, entryId],+ );+ };++ const handleApply = () => {+ const selectedSet = new Set(selectedIds);+ const selectedEntries = entries+ .filter((entry) => selectedSet.has(entry.id))+ .map((entry) => ({+ id: entry.id,+ question: entry.question,+ session_title: entry.session_title,+ is_correct: entry.is_correct,+ difficulty: entry.difficulty || "",+ }));+ onApply(selectedEntries);+ onClose();+ };++ if (!open) return null;++ return (+ <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">+ <div className="surface-card w-full max-w-4xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">+ <div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">+ <div className="min-w-0">+ <div className="mb-1 inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">+ <ClipboardList className="h-3 w-3" />+ {t("Question Bank Reference")}+ </div>+ <h2 className="text-lg font-semibold text-[var(--foreground)]">+ {t("Select Question Bank Entries")}+ </h2>+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">+ {t("Choose quiz questions to ground the next request.")}+ </p>+ </div>+ <button+ onClick={onClose}+ className="rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ aria-label={t("Close")}+ >+ <X size={18} />+ </button>+ </div>++ <div className="bg-[var(--background)]/40 p-5">+ {/* Filter row */}+ <div className="mb-3 flex flex-wrap items-center gap-1">+ {FILTER_MODES.map(({ value, label }) => {+ const active = filter === value && activeCategoryId === null;+ return (+ <button+ key={value}+ onClick={() => {+ setFilter(value);+ setActiveCategoryId(null);+ }}+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] transition-colors ${+ active+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {t(label)}+ </button>+ );+ })}+ {categories.length > 0 && (+ <span className="mx-1 text-[var(--border)]">|</span>+ )}+ {categories.map((cat) => {+ const active = activeCategoryId === cat.id;+ return (+ <button+ key={cat.id}+ onClick={() => {+ setActiveCategoryId(cat.id);+ setFilter("all");+ }}+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] transition-colors ${+ active+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ <FolderOpen size={11} />+ {cat.name}+ </button>+ );+ })}+ </div>++ <div className="mb-4 flex items-center gap-2">+ <div className="relative flex-1">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />+ <input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t("Search questions by content")}+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"+ />+ </div>+ <button+ onClick={() => setSelectedIds([])}+ className="rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {t("Clear")}+ </button>+ </div>++ <div className="max-h-[56vh] overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)]">+ {loading ? (+ <div className="flex min-h-[280px] items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : filteredEntries.length ? (+ <div className="divide-y divide-[var(--border)]">+ {filteredEntries.map((entry) => {+ const selected = selectedIds.includes(entry.id);+ return (+ <button+ key={entry.id}+ onClick={() => toggleEntry(entry.id)}+ className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors ${+ selected+ ? "bg-[var(--primary)]/8"+ : "hover:bg-[var(--muted)]/40"+ }`}+ >+ <div+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${+ selected+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"+ : "border-[var(--border)] text-transparent"+ }`}+ >+ <Check size={12} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-1.5">+ {entry.difficulty && (+ <span+ className={`rounded-md px-1.5 py-0.5 text-[10px] font-medium uppercase ${+ entry.difficulty === "hard"+ ? "bg-red-50 text-red-600 dark:bg-red-950/30 dark:text-red-400"+ : entry.difficulty === "medium"+ ? "bg-amber-50 text-amber-600 dark:bg-amber-950/30 dark:text-amber-400"+ : "bg-green-50 text-green-600 dark:bg-green-950/30 dark:text-green-400"+ }`}+ >+ {entry.difficulty}+ </span>+ )}+ {entry.question_type && (+ <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">+ {entry.question_type}+ </span>+ )}+ <span+ className={`rounded-md px-1.5 py-0.5 text-[10px] font-semibold ${+ entry.is_correct+ ? "bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400"+ : "bg-red-100 text-red-700 dark:bg-red-950/30 dark:text-red-400"+ }`}+ >+ {entry.is_correct ? t("Correct") : t("Incorrect")}+ </span>+ {entry.bookmarked && (+ <Bookmark+ size={11}+ className="text-[var(--primary)]"+ fill="currentColor"+ />+ )}+ </div>+ <p className="mt-1 line-clamp-2 text-[13px] leading-5 text-[var(--foreground)]">+ {entry.question}+ </p>+ {entry.session_title && (+ <div className="mt-1 truncate text-[11px] text-[var(--muted-foreground)]/85">+ {entry.session_title}+ </div>+ )}+ </div>+ </button>+ );+ })}+ </div>+ ) : (+ <div className="px-6 py-14 text-center text-[13px] text-[var(--muted-foreground)]">+ {entries.length === 0+ ? t("No quiz entries yet.")+ : t("No matching questions found.")}+ </div>+ )}+ </div>++ <div className="mt-4 flex items-center justify-between gap-3">+ <div className="text-[12px] text-[var(--muted-foreground)]">+ {selectedIds.length === 1+ ? t("1 question selected")+ : t("{n} questions selected", { n: selectedIds.length })}+ </div>+ <button+ onClick={handleApply}+ disabled={!selectedIds.length}+ className="btn-primary rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {t("Use Selected Questions ({n})", { n: selectedIds.length })}+ </button>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex e97ea5182..9ec69dbb5 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -8,6 +8,7 @@ import {AtSign,BookOpen,ChevronDown,+ ClipboardList,FilePlus2,Layers,MessageSquare,@@ -19,8 +20,9 @@ import {} from "lucide-react";import { useTranslation } from "react-i18next";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";+import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";import AtMentionPopup from "@/components/chat/AtMentionPopup";-import type { SelectedRecord } from "@/app/(workspace)/guide/types";+import type { SelectedRecord } from "@/lib/notebook-selection-types";import type { DeepQuestionFormConfig } from "@/lib/quiz-types";import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";import type { VisualizeFormConfig } from "@/lib/visualize-types";@@ -105,6 +107,7 @@ export default memo(function ChatComposer({knowledgeBases,selectedNotebookRecords,selectedHistorySessions,+ selectedQuestionEntries,notebookReferenceGroups,stateKnowledgeBase,isStreaming,@@ -127,12 +130,14 @@ export default memo(function ChatComposer({onSetKB,onSelectNotebookPicker,onSelectHistoryPicker,+ onSelectQuestionBankPicker,onToggleTool,onToggleResearchSource,onSend,onRemoveAttachment,onRemoveHistory,onRemoveNotebook,+ onRemoveQuestion,onDragEnter,onDragLeave,onDragOver,@@ -168,6 +173,7 @@ export default memo(function ChatComposer({knowledgeBases: KnowledgeBase[];selectedNotebookRecords: SelectedRecord[];selectedHistorySessions: SelectedHistorySession[];+ selectedQuestionEntries: SelectedQuestionEntry[];notebookReferenceGroups: Array<{ notebookId: string; notebookName: string; count: number }>;stateKnowledgeBase: string;isStreaming: boolean;@@ -190,12 +196,14 @@ export default memo(function ChatComposer({onSetKB: (kb: string) => void;onSelectNotebookPicker: () => void;onSelectHistoryPicker: () => void;+ onSelectQuestionBankPicker: () => void;onToggleTool: (tool: ToolDef["name"]) => void;onToggleResearchSource: (source: ResearchSource) => void;onSend: (content: string) => void;onRemoveAttachment: (index: number) => void;onRemoveHistory: (sessionId: string) => void;onRemoveNotebook: (notebookId: string) => void;+ onRemoveQuestion: (entryId: number) => void;onDragEnter: (event: React.DragEvent) => void;onDragLeave: (event: React.DragEvent) => void;onDragOver: (event: React.DragEvent) => void;@@ -273,8 +281,18 @@ export default memo(function ChatComposer({onSelectHistoryPicker();}, [onSelectHistoryPicker]);+ const handleSelectQuestionBank = useCallback(() => {+ setInput((prev) => stripTrailingAtMention(prev));+ setShowAtPopup(false);+ onSelectQuestionBankPicker();+ }, [onSelectQuestionBankPicker]);+const canSend =- (!!input.trim() || !!attachments.length || !!selectedNotebookRecords.length || !!selectedHistorySessions.length) &&+ (!!input.trim() ||+ !!attachments.length ||+ !!selectedNotebookRecords.length ||+ !!selectedHistorySessions.length ||+ !!selectedQuestionEntries.length) &&!isStreaming &&!(isResearchMode && Object.keys(researchValidationErrors).length > 0);@@ -328,6 +346,7 @@ export default memo(function ChatComposer({open={showAtPopup}onSelectNotebook={handleSelectNotebook}onSelectHistory={handleSelectHistory}+ onSelectQuestionBank={handleSelectQuestionBank}/><div@@ -355,8 +374,10 @@ export default memo(function ChatComposer({<ReferenceChipshistorySessions={selectedHistorySessions}notebookGroups={notebookReferenceGroups}+ questionEntries={selectedQuestionEntries}onRemoveHistory={onRemoveHistory}onRemoveNotebook={onRemoveNotebook}+ onRemoveQuestion={onRemoveQuestion}/><textarearef={textareaRef}@@ -541,9 +562,13 @@ export default memo(function ChatComposer({{t("Reference")}<ChevronDown size={10} className={`transition-transform ${refMenuOpen ? "rotate-180" : ""}`} /></button>- {(selectedNotebookRecords.length > 0 || selectedHistorySessions.length > 0) && (+ {(selectedNotebookRecords.length > 0 ||+ selectedHistorySessions.length > 0 ||+ selectedQuestionEntries.length > 0) && (<span className="shrink-0 rounded-full bg-[var(--primary)]/10 px-1.5 py-px text-[9px] font-semibold text-[var(--primary)]">- {selectedNotebookRecords.length + selectedHistorySessions.length}+ {selectedNotebookRecords.length ++ selectedHistorySessions.length ++ selectedQuestionEntries.length}</span>)}{refMenuOpen && (@@ -577,6 +602,19 @@ export default memo(function ChatComposer({<span className="text-[10px] text-[var(--primary)]">{selectedHistorySessions.length}</span>)}</button>+ <button+ onClick={() => {+ onSetRefMenuOpen(false);+ onSelectQuestionBankPicker();+ }}+ className="flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] hover:bg-[var(--muted)]/40"+ >+ <ClipboardList size={13} strokeWidth={1.7} />+ <span className="flex-1 font-medium">{t("Question Bank")}</span>+ {selectedQuestionEntries.length > 0 && (+ <span className="text-[10px] text-[var(--primary)]">{selectedQuestionEntries.length}</span>+ )}+ </button></div>)}</div>diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex ffa13de92..c06adb854 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -5,6 +5,7 @@ import { memo, useCallback, useMemo, useState } from "react";import Image from "next/image";import {BookOpen,+ ClipboardList,Coins,Copy,MessageSquare,@@ -15,6 +16,7 @@ import {} from "lucide-react";import { useTranslation } from "react-i18next";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";+import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";import AssistantResponse from "@/components/common/AssistantResponse";import type { MessageRequestSnapshot } from "@/context/UnifiedChatContext";import { extractMathAnimatorResult } from "@/lib/math-animator-types";@@ -317,16 +319,25 @@ UserMessage.displayName = "UserMessage";export const ReferenceChips = memo(function ReferenceChips({historySessions,notebookGroups,+ questionEntries,onRemoveHistory,onRemoveNotebook,+ onRemoveQuestion,}: {historySessions: SelectedHistorySession[];notebookGroups: NotebookReferenceGroup[];+ questionEntries: SelectedQuestionEntry[];onRemoveHistory: (sessionId: string) => void;onRemoveNotebook: (notebookId: string) => void;+ onRemoveQuestion: (entryId: number) => void;}) {const { t } = useTranslation();- if (historySessions.length === 0 && notebookGroups.length === 0) return null;+ if (+ historySessions.length === 0 &&+ notebookGroups.length === 0 &&+ questionEntries.length === 0+ )+ return null;return (<div className="mb-3 flex flex-wrap gap-2">@@ -364,6 +375,26 @@ export const ReferenceChips = memo(function ReferenceChips({</button></span>))}+ {questionEntries.map((entry) => (+ <span+ key={entry.id}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-1.5 text-[12px] text-amber-800 shadow-sm dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200"+ >+ <ClipboardList size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Question Bank")}</span>+ <span className="truncate text-amber-700/90 dark:text-amber-200/90">+ {entry.question.length > 40+ ? `${entry.question.slice(0, 40)}…`+ : entry.question}+ </span>+ <button+ onClick={() => onRemoveQuestion(entry.id)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}</div>);});diff --git a/web/components/notebook/NotebookRecordPicker.tsx b/web/components/notebook/NotebookRecordPicker.tsxindex f8e5dbb2e..2bcd5565e 100644--- a/web/components/notebook/NotebookRecordPicker.tsx+++ b/web/components/notebook/NotebookRecordPicker.tsx@@ -3,9 +3,9 @@import { useEffect } from "react";import { Layers, X } from "lucide-react";import { useTranslation } from "react-i18next";-import NotebookSelector from "@/app/(workspace)/guide/components/NotebookSelector";-import { useNotebookSelection } from "@/app/(workspace)/guide/hooks/useNotebookSelection";-import type { SelectedRecord } from "@/app/(workspace)/guide/types";+import NotebookSelector from "@/components/notebook/NotebookSelector";+import { useNotebookSelection } from "@/components/notebook/useNotebookSelection";+import type { SelectedRecord } from "@/lib/notebook-selection-types";interface NotebookRecordPickerProps {open: boolean;diff --git a/web/app/(workspace)/guide/components/NotebookSelector.tsx b/web/components/notebook/NotebookSelector.tsxsimilarity index 97%rename from web/app/(workspace)/guide/components/NotebookSelector.tsxrename to web/components/notebook/NotebookSelector.tsxindex f46a90b5b..9f114bef2 100644--- a/web/app/(workspace)/guide/components/NotebookSelector.tsx+++ b/web/components/notebook/NotebookSelector.tsx@@ -12,7 +12,7 @@ import {NotebookRecord,SelectedRecord,getTypeColor,-} from "../types";+} from "@/lib/notebook-selection-types";import { useTranslation } from "react-i18next";interface NotebookSelectorProps {@@ -81,7 +81,7 @@ export default function NotebookSelector({<NotebookPen className="h-5 w-5 text-[var(--muted-foreground)]/60" /><span>{t("No notebooks with records found")}</span><span className="text-[11px] text-[var(--muted-foreground)]/80">- {t("Save a chat or guided learning result first to populate a notebook.")}+ {t("Save a chat result first to populate a notebook.")}</span></div>) : (@@ -225,7 +225,7 @@ export default function NotebookSelector({)}</div>- {/* Generate / Apply Button */}+ {/* Apply Button */}<div className="border-t border-[var(--border)] bg-[var(--card)] p-4"><buttononClick={onCreateSession}@@ -238,7 +238,7 @@ export default function NotebookSelector({{t("Generating...")}</>) : (- (actionLabel || t("Generate Learning Plan ({n} items)")).replace(+ (actionLabel || t("Use Selected Records ({n})")).replace("{n}",String(selectedRecords.size),)diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsxindex aa1b9b844..3ce82dd37 100644--- a/web/components/notebook/SaveToNotebookModal.tsx+++ b/web/components/notebook/SaveToNotebookModal.tsx@@ -14,8 +14,7 @@ type RecordType =| "question"| "research"| "co_writer"- | "chat"- | "guided_learning";+ | "chat";export interface NotebookSavePayload {recordType: RecordType;diff --git a/web/app/(workspace)/guide/hooks/useNotebookSelection.ts b/web/components/notebook/useNotebookSelection.tssimilarity index 96%rename from web/app/(workspace)/guide/hooks/useNotebookSelection.tsrename to web/components/notebook/useNotebookSelection.tsindex eae25e87d..85236e9f9 100644--- a/web/app/(workspace)/guide/hooks/useNotebookSelection.ts+++ b/web/components/notebook/useNotebookSelection.ts@@ -1,9 +1,13 @@import { useState, useCallback } from "react";import { listNotebooks, getNotebook } from "@/lib/notebook-api";-import { Notebook, NotebookRecord, SelectedRecord } from "../types";+import {+ Notebook,+ NotebookRecord,+ SelectedRecord,+} from "@/lib/notebook-selection-types";/**- * Hook for managing notebook and record selection.+ * Hook for managing notebook and record selection across notebook pickers.** Backed by the real notebook system (`/api/v1/notebook/*`) so that records* saved via Save-to-Notebook from any surface are immediately discoverablediff --git a/web/components/sidebar/BookRecent.tsx b/web/components/sidebar/BookRecent.tsxnew file mode 100644index 000000000..45f174278--- /dev/null+++ b/web/components/sidebar/BookRecent.tsx@@ -0,0 +1,116 @@+"use client";++import Link from "next/link";+import { useEffect, useState } from "react";+import { Library } from "lucide-react";+import { apiUrl } from "@/lib/api";++interface RecentBook {+ id: string;+ title: string;+ status: string;+ chapter_count: number;+ page_count: number;+ updated_at: number;+}++const STATUS_DOT: Record<string, string> = {+ ready: "bg-emerald-400",+ partial: "bg-amber-400",+ generating: "bg-sky-400",+ planning: "bg-sky-400",+ pending: "bg-[var(--muted-foreground)]/30",+ draft: "bg-[var(--muted-foreground)]/30",+ spine_ready: "bg-violet-400",+ error: "bg-rose-400",+};++function relativeTime(seconds: number): string {+ if (!seconds || Number.isNaN(seconds)) return "";+ const diff = Date.now() / 1000 - seconds;+ if (diff < 60) return "now";+ const mins = Math.floor(diff / 60);+ if (mins < 60) return `${mins}m`;+ const hrs = Math.floor(mins / 60);+ if (hrs < 24) return `${hrs}h`;+ const days = Math.floor(hrs / 24);+ return `${days}d`;+}++interface BookRecentProps {+ collapsed?: boolean;+ limit?: number;+}++export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {+ const [books, setBooks] = useState<RecentBook[]>([]);++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ const res = await fetch(apiUrl("/api/v1/book/books"));+ if (!res.ok) return;+ const data = await res.json();+ const items: RecentBook[] = Array.isArray(data?.books) ? data.books : [];+ items.sort(+ (a, b) => (Number(b.updated_at) || 0) - (Number(a.updated_at) || 0),+ );+ if (!cancelled) setBooks(items.slice(0, limit));+ } catch {+ /* ignore */+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [limit]);++ if (books.length === 0) return null;++ if (collapsed) {+ return (+ <div className="flex flex-col items-center gap-0.5 pb-0.5 pt-px">+ {books.map((book) => {+ const dot = STATUS_DOT[book.status] || "bg-[var(--muted-foreground)]/30";+ return (+ <Link+ key={book.id}+ href={`/book?book=${encodeURIComponent(book.id)}`}+ title={book.title || "Untitled book"}+ className="relative rounded-md p-1.5 text-[var(--muted-foreground)]/70 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"+ >+ <Library size={12} strokeWidth={1.5} />+ <span+ className={`absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full ${dot} ring-1 ring-[var(--secondary)]`}+ />+ </Link>+ );+ })}+ </div>+ );+ }++ return (+ <div className="ml-5 border-l border-[var(--border)]/30 py-1">+ {books.map((book) => {+ const dot = STATUS_DOT[book.status] || "bg-[var(--muted-foreground)]/30";+ return (+ <Link+ key={book.id}+ href={`/book?book=${encodeURIComponent(book.id)}`}+ className="group flex items-center gap-2 rounded-r-lg py-1 pl-3 pr-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"+ >+ <span className={`block h-1.5 w-1.5 shrink-0 rounded-full ${dot}`} />+ <span className="min-w-0 flex-1 truncate text-[13px]">+ {book.title || "Untitled book"}+ </span>+ <span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">+ {relativeTime(Number(book.updated_at) || 0)}+ </span>+ </Link>+ );+ })}+ </div>+ );+}diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsxindex c5e1b6083..172e64a29 100644--- a/web/components/sidebar/SidebarShell.tsx+++ b/web/components/sidebar/SidebarShell.tsx@@ -8,7 +8,7 @@ import {BookOpen,Bot,Brain,- GraduationCap,+ Library,MessageSquare,PanelLeftClose,PanelLeftOpen,@@ -20,6 +20,7 @@ import {import { useTranslation } from "react-i18next";import SessionList from "@/components/SessionList";import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";+import { BookRecent } from "@/components/sidebar/BookRecent";import type { SessionSummary } from "@/lib/session-api";interface NavEntry {@@ -32,7 +33,7 @@ const PRIMARY_NAV: NavEntry[] = [{ href: "/chat", label: "Chat", icon: MessageSquare },{ href: "/agents", label: "TutorBot", icon: Bot },{ href: "/co-writer", label: "Co-Writer", icon: PenLine },- { href: "/guide", label: "Guided Learning", icon: GraduationCap },+ { href: "/book", label: "Book", icon: Library },{ href: "/knowledge", label: "Knowledge", icon: BookOpen },{ href: "/memory", label: "Memory", icon: Brain },];@@ -114,6 +115,7 @@ export function SidebarShell({<item.icon size={16} strokeWidth={active ? 1.9 : 1.5} /></Link>{item.href === "/agents" && <TutorBotRecent collapsed />}+ {item.href === "/book" && <BookRecent collapsed />}</div>);@@ -187,6 +189,7 @@ export function SidebarShell({const active = pathname.startsWith(item.href);const hasSessionsBelow = item.href === "/chat" && showSessions && onSelectSession && onRenameSession && onDeleteSession;const hasBots = item.href === "/agents";+ const hasBooks = item.href === "/book";return (<div key={item.href}><Link@@ -214,6 +217,7 @@ export function SidebarShell({</div>)}{hasBots && <TutorBotRecent />}+ {hasBooks && <BookRecent />}</div>);})}diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsxindex 7899ed079..1778eb08f 100644--- a/web/components/visualize/VisualizationViewer.tsx+++ b/web/components/visualize/VisualizationViewer.tsx@@ -1,9 +1,10 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { Code2, Copy, Check } from "lucide-react";+import { Code2, Copy, Check, ExternalLink } from "lucide-react";import { useTranslation } from "react-i18next";import { Mermaid } from "@/components/Mermaid";+import { prepareIframeHtml } from "@/lib/iframe-html";import type { VisualizeResult } from "@/lib/visualize-types";function ChartJsRenderer({ config }: { config: string }) {@@ -69,6 +70,51 @@ function ChartJsRenderer({ config }: { config: string }) {);}+function HtmlRenderer({ html }: { html: string }) {+ const iframeRef = useRef<HTMLIFrameElement>(null);++ const prepared = useMemo(() => prepareIframeHtml(html || ""), [html]);++ useEffect(() => {+ const iframe = iframeRef.current;+ if (!iframe) return;+ iframe.srcdoc = prepared;+ }, [prepared]);++ const handleOpenInNewTab = () => {+ try {+ const blob = new Blob([prepared], { type: "text/html" });+ const url = URL.createObjectURL(blob);+ window.open(url, "_blank", "noopener,noreferrer");+ // Best-effort cleanup; the new tab keeps its own reference.+ setTimeout(() => URL.revokeObjectURL(url), 60_000);+ } catch {+ /* no-op */+ }+ };++ return (+ <div className="relative w-full">+ <button+ type="button"+ onClick={handleOpenInNewTab}+ className="absolute right-2 top-2 z-10 inline-flex items-center gap-1 rounded-md border border-[var(--border)] bg-[var(--background)]/90 px-2 py-1 text-[10px] font-medium text-[var(--muted-foreground)] backdrop-blur transition-colors hover:text-[var(--foreground)]"+ title="Open in new tab"+ >+ <ExternalLink size={10} strokeWidth={1.8} />+ Open+ </button>+ <iframe+ ref={iframeRef}+ title="HTML visualization"+ sandbox="allow-scripts"+ className="w-full rounded-lg border border-[var(--border)] bg-white"+ style={{ minHeight: 480, height: 560 }}+ />+ </div>+ );+}+function SvgRenderer({ svg }: { svg: string }) {const containerRef = useRef<HTMLDivElement>(null);const [error, setError] = useState<string | null>(null);@@ -125,11 +171,19 @@ export default function VisualizationViewer({return (<div className="space-y-3">{/* Visualization area */}- <div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)] p-4">+ <div+ className={+ result.render_type === "html"+ ? "overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)]"+ : "overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--background)] p-4"+ }+ >{result.render_type === "svg" ? (<SvgRenderer svg={result.code.content} />) : result.render_type === "mermaid" ? (<Mermaid chart={result.code.content} />+ ) : result.render_type === "html" ? (+ <HtmlRenderer html={result.code.content} />) : (<ChartJsRenderer config={result.code.content} />)}@@ -160,7 +214,9 @@ export default function VisualizationViewer({? "SVG": result.render_type === "mermaid"? `Mermaid · ${result.analysis.chart_type || "diagram"}`- : `Chart.js · ${result.analysis.chart_type || "chart"}`}+ : result.render_type === "html"+ ? `HTML · ${result.analysis.chart_type || "interactive"}`+ : `Chart.js · ${result.analysis.chart_type || "chart"}`}</span></div>diff --git a/web/components/visualize/VisualizeConfigPanel.tsx b/web/components/visualize/VisualizeConfigPanel.tsxindex a57e4aa3a..f7168f06b 100644--- a/web/components/visualize/VisualizeConfigPanel.tsx+++ b/web/components/visualize/VisualizeConfigPanel.tsx@@ -45,6 +45,7 @@ export default function VisualizeConfigPanel({<option value="chartjs">{t("Chart.js")}</option><option value="svg">{t("SVG")}</option><option value="mermaid">{t("Mermaid")}</option>+ <option value="html">{t("HTML")}</option></select></Field></CollapsibleConfigSection>diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex 7046f13b6..b8826a0e8 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -42,6 +42,8 @@ interface NotebookReferencePayload {type HistoryReferencePayload = string[];+type QuestionNotebookReferencePayload = number[];+export interface SendMessageOptions {displayUserMessage?: boolean;persistUserMessage?: boolean;@@ -84,6 +86,7 @@ export interface MessageRequestSnapshot {config?: Record<string, unknown>;notebookReferences?: NotebookReferencePayload[];historyReferences?: HistoryReferencePayload;+ questionNotebookReferences?: QuestionNotebookReferencePayload;}export interface MessageItem {@@ -387,6 +390,7 @@ interface ChatContextValue {notebookReferences?: NotebookReferencePayload[],historyReferences?: HistoryReferencePayload,options?: SendMessageOptions,+ questionNotebookReferences?: QuestionNotebookReferencePayload,) => void;cancelStreamingTurn: () => void;newSession: () => void;@@ -659,6 +663,7 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })notebookReferences?: NotebookReferencePayload[],historyReferences?: HistoryReferencePayload,options?: SendMessageOptions,+ questionNotebookReferences?: QuestionNotebookReferencePayload,) => {const msgAttachments = attachments?.map((a) => ({type: a.type,@@ -695,6 +700,9 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })...(config && Object.keys(config).length > 0 ? { config } : {}),...(notebookReferences?.length ? { notebookReferences } : {}),...(historyReferences?.length ? { historyReferences: [...historyReferences] } : {}),+ ...(questionNotebookReferences?.length+ ? { questionNotebookReferences: [...questionNotebookReferences] }+ : {}),};if (options?.displayUserMessage !== false) {dispatch({@@ -726,6 +734,9 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })...(historyReferences?.length? { history_references: historyReferences }: {}),+ ...(questionNotebookReferences?.length+ ? { question_notebook_references: questionNotebookReferences }+ : {}),...(effectiveConfig && Object.keys(effectiveConfig).length > 0? { config: effectiveConfig }: {}),diff --git a/web/lib/book-api.ts b/web/lib/book-api.tsnew file mode 100644index 000000000..90fa03b53--- /dev/null+++ b/web/lib/book-api.ts@@ -0,0 +1,221 @@+import { apiUrl, wsUrl } from "@/lib/api";+import type {+ Book,+ BookDetail,+ BookProposal,+ Page,+ Spine,+ Block,+} from "@/lib/book-types";++const BASE = "/api/v1/book";++async function request<T>(path: string, init?: RequestInit): Promise<T> {+ const res = await fetch(apiUrl(`${BASE}${path}`), {+ headers: { "Content-Type": "application/json", ...(init?.headers || {}) },+ ...init,+ });+ if (!res.ok) {+ let detail: string;+ try {+ const data = await res.json();+ detail = (data && (data.detail || data.message)) || res.statusText;+ } catch {+ detail = res.statusText;+ }+ throw new Error(`book api ${path} → ${res.status}: ${detail}`);+ }+ return (await res.json()) as T;+}++export interface CreateBookPayload {+ user_intent: string;+ chat_session_id?: string;+ chat_selections?: Array<{ session_id: string; message_ids: number[] }>;+ notebook_refs?: Array<Record<string, unknown>>;+ knowledge_bases?: string[];+ question_categories?: number[];+ question_entries?: number[];+ language?: string;+}++export const bookApi = {+ list: () => request<{ books: Book[] }>("/books"),+ get: (book_id: string) =>+ request<BookDetail>(`/books/${encodeURIComponent(book_id)}`),+ delete: (book_id: string) =>+ request<{ deleted: boolean; book_id: string }>(+ `/books/${encodeURIComponent(book_id)}`,+ { method: "DELETE" },+ ),+ getSpine: (book_id: string) =>+ request<{ spine: Spine }>(+ `/books/${encodeURIComponent(book_id)}/spine`,+ ),+ getPage: (book_id: string, page_id: string) =>+ request<{ page: Page }>(+ `/books/${encodeURIComponent(book_id)}/pages/${encodeURIComponent(page_id)}`,+ ),+ create: (payload: CreateBookPayload) =>+ request<{ book: Book; proposal: BookProposal }>("/books", {+ method: "POST",+ body: JSON.stringify(payload),+ }),+ confirmProposal: (book_id: string, proposal?: BookProposal) =>+ request<{ book: Book; spine: Spine }>("/books/confirm-proposal", {+ method: "POST",+ body: JSON.stringify({ book_id, proposal: proposal ?? null }),+ }),+ confirmSpine: (book_id: string, spine?: Spine, auto_compile = true) =>+ request<{ pages: Page[] }>("/books/confirm-spine", {+ method: "POST",+ body: JSON.stringify({ book_id, spine: spine ?? null, auto_compile }),+ }),+ compilePage: (book_id: string, page_id: string, force = false) =>+ request<{ page: Page }>("/books/compile-page", {+ method: "POST",+ body: JSON.stringify({ book_id, page_id, force }),+ }),+ regenerateBlock: (+ book_id: string,+ page_id: string,+ block_id: string,+ params_override?: Record<string, unknown>,+ ) =>+ request<{ block: Block | null }>("/books/regenerate-block", {+ method: "POST",+ body: JSON.stringify({+ book_id,+ page_id,+ block_id,+ params_override: params_override ?? null,+ }),+ }),++ insertBlock: (params: {+ book_id: string;+ page_id: string;+ block_type: string;+ params?: Record<string, unknown>;+ position?: number;+ compile_now?: boolean;+ }) =>+ request<{ block: Block }>("/books/insert-block", {+ method: "POST",+ body: JSON.stringify({+ compile_now: true,+ ...params,+ }),+ }),++ deleteBlock: (book_id: string, page_id: string, block_id: string) =>+ request<{ ok: boolean }>("/books/delete-block", {+ method: "POST",+ body: JSON.stringify({ book_id, page_id, block_id }),+ }),++ moveBlock: (+ book_id: string,+ page_id: string,+ block_id: string,+ new_position: number,+ ) =>+ request<{ ok: boolean }>("/books/move-block", {+ method: "POST",+ body: JSON.stringify({ book_id, page_id, block_id, new_position }),+ }),++ changeBlockType: (params: {+ book_id: string;+ page_id: string;+ block_id: string;+ new_type: string;+ params_override?: Record<string, unknown>;+ }) =>+ request<{ block: Block }>("/books/change-block-type", {+ method: "POST",+ body: JSON.stringify(params),+ }),++ deepDive: (params: {+ book_id: string;+ parent_page_id: string;+ topic: string;+ block_id?: string;+ content_type?: string;+ }) =>+ request<{ page: Page }>("/books/deep-dive", {+ method: "POST",+ body: JSON.stringify({ content_type: "concept", ...params }),+ }),++ recordQuizAttempt: (params: {+ book_id: string;+ page_id: string;+ block_id: string;+ question_id?: string;+ user_answer?: string;+ is_correct: boolean;+ }) =>+ request<{ progress: Record<string, unknown> }>("/books/quiz-attempt", {+ method: "POST",+ body: JSON.stringify(params),+ }),++ supplement: (book_id: string, page_id: string, topic: string) =>+ request<{ block: Block }>("/books/supplement", {+ method: "POST",+ body: JSON.stringify({ book_id, page_id, topic }),+ }),++ health: (book_id: string) =>+ request<{+ kb_drift: {+ book_id: string;+ has_drift: boolean;+ new_kbs?: string[];+ removed_kbs?: string[];+ changed_kbs?: string[];+ stale_page_ids?: string[];+ };+ log_health: {+ book_id: string;+ total_entries: number;+ error_entries: number;+ block_failures: number;+ last_compile_at?: string;+ last_error_at?: string;+ repeated_failures?: { signature: string; count: number }[];+ };+ }>(`/books/${encodeURIComponent(book_id)}/health`),++ refreshFingerprints: (book_id: string) =>+ request<{+ book_id: string;+ kb_fingerprints: Record<string, string>;+ stale_page_ids: string[];+ }>(`/books/${encodeURIComponent(book_id)}/refresh-fingerprints`, {+ method: "POST",+ }),+};++// ── WebSocket helper ─────────────────────────────────────────────────++export type BookWsEvent =+ | { type: string; [key: string]: unknown };++export function openBookSocket(+ onEvent: (event: BookWsEvent) => void,+ onError?: (error: Event) => void,+): WebSocket {+ const socket = new WebSocket(wsUrl(`${BASE}/ws`));+ socket.onmessage = (event) => {+ try {+ onEvent(JSON.parse(event.data));+ } catch {+ // ignore malformed frames+ }+ };+ if (onError) socket.onerror = onError;+ return socket;+}diff --git a/web/lib/book-progress.ts b/web/lib/book-progress.tsnew file mode 100644index 000000000..4e801e52b--- /dev/null+++ b/web/lib/book-progress.ts@@ -0,0 +1,442 @@+/**+ * Book Engine progress model+ * ==========================+ *+ * A pure reducer that turns the raw `BookWsEvent` stream coming out of the+ * BookEngine into a cleaned-up `BookProgress` snapshot. The `BookProgressTimeline`+ * component renders this snapshot — the reducer keeps the UI presentational.+ *+ * Stage order matches the actual pipeline:+ *+ * ideation → exploration → synthesis (with critique sub-rounds) →+ * overview (engine-injected) → compilation (per-page block stream)+ */++import type { BookWsEvent } from "@/lib/book-api";++export type StageId =+ | "ideation"+ | "exploration"+ | "synthesis"+ | "critique"+ | "overview"+ | "compilation";++export type StageState = "pending" | "running" | "completed" | "error";++export interface StageView {+ id: StageId;+ label: string;+ description: string;+ state: StageState;+ detail?: string;+ startedAt?: number;+ endedAt?: number;+}++export interface BookProgress {+ bookId: string | null;+ stages: Record<StageId, StageView>;+ ordered: StageId[];+ // Aggregated counters+ exploration: {+ queryCount: number;+ chunkCount: number;+ candidateConcepts: number;+ summary: string;+ };+ synthesis: {+ rounds: number;+ chapterCount: number;+ conceptNodes: number;+ conceptEdges: number;+ lastVerdict: string;+ };+ critique: {+ rounds: number;+ issues: number;+ };+ compilation: {+ pagesPlanned: number;+ pagesReady: number;+ blocksReady: number;+ blocksError: number;+ };+ // Latest progress message — useful as a single-line live caption.+ message: string;+ updatedAt: number;+}++export const STAGE_ORDER: StageId[] = [+ "ideation",+ "exploration",+ "synthesis",+ "critique",+ "overview",+ "compilation",+];++const STAGE_LABELS: Record<StageId, { label: string; description: string }> = {+ ideation: {+ label: "Ideation",+ description: "Drafting the proposal from your inputs.",+ },+ exploration: {+ label: "Source sweep",+ description: "Parallel multi-query retrieval across your KBs.",+ },+ synthesis: {+ label: "Synthesis",+ description: "Spine + concept graph (draft → revise).",+ },+ critique: {+ label: "Critique",+ description: "Self-review rounds tightening the spine.",+ },+ overview: {+ label: "Overview chapter",+ description: "Auto-built table of contents + concept map.",+ },+ compilation: {+ label: "Compilation",+ description: "Per-page block planning + generation.",+ },+};++export function emptyBookProgress(): BookProgress {+ const stages = Object.fromEntries(+ STAGE_ORDER.map((id) => [+ id,+ {+ id,+ label: STAGE_LABELS[id].label,+ description: STAGE_LABELS[id].description,+ state: "pending" as StageState,+ },+ ]),+ ) as Record<StageId, StageView>;+ return {+ bookId: null,+ stages,+ ordered: STAGE_ORDER,+ exploration: {+ queryCount: 0,+ chunkCount: 0,+ candidateConcepts: 0,+ summary: "",+ },+ synthesis: {+ rounds: 0,+ chapterCount: 0,+ conceptNodes: 0,+ conceptEdges: 0,+ lastVerdict: "",+ },+ critique: { rounds: 0, issues: 0 },+ compilation: {+ pagesPlanned: 0,+ pagesReady: 0,+ blocksReady: 0,+ blocksError: 0,+ },+ message: "",+ updatedAt: 0,+ };+}++function patchStage(+ state: BookProgress,+ id: StageId,+ patch: Partial<StageView>,+): BookProgress {+ const next = { ...state.stages[id], ...patch };+ return {+ ...state,+ stages: { ...state.stages, [id]: next },+ };+}++function startStage(state: BookProgress, id: StageId): BookProgress {+ // Mark earlier stages completed if they're still pending/running so the+ // timeline always reads left-to-right cleanly even when we miss an event.+ let next = state;+ for (const sid of STAGE_ORDER) {+ if (sid === id) break;+ const s = next.stages[sid];+ if (s.state === "pending" || s.state === "running") {+ next = patchStage(next, sid, { state: "completed", endedAt: Date.now() });+ }+ }+ return patchStage(next, id, {+ state: "running",+ startedAt: next.stages[id].startedAt ?? Date.now(),+ });+}++function completeStage(state: BookProgress, id: StageId): BookProgress {+ return patchStage(state, id, { state: "completed", endedAt: Date.now() });+}++function asNumber(value: unknown): number {+ if (typeof value === "number") return value;+ if (Array.isArray(value)) return value.length;+ if (value && typeof value === "object") return Object.keys(value).length;+ return 0;+}++function asString(value: unknown): string {+ return value == null ? "" : String(value);+}++/** Reducer: ingest a single WS event and return the next snapshot. */+export function reduceBookEvent(+ state: BookProgress,+ event: BookWsEvent,+): BookProgress {+ const meta = (event.metadata as Record<string, unknown> | undefined) || {};+ const stage = String((event as { stage?: string }).stage || "");+ const rawKind = String(+ (event.content as string) || (meta.kind as string) || "",+ );+ const eventType = String(event.type || "");++ // Track book id once.+ let next: BookProgress = { ...state, updatedAt: Date.now() };+ const bookIdFromMeta = asString(meta.book_id);+ if (bookIdFromMeta && next.bookId == null) {+ next = { ...next, bookId: bookIdFromMeta };+ }++ // Pick up STAGE_BEGIN / STAGE_END from generic stream events.+ if (eventType === "stage_begin" && stage) {+ if ((STAGE_ORDER as string[]).includes(stage)) {+ next = startStage(next, stage as StageId);+ }+ }+ if (eventType === "stage_end" && stage) {+ if ((STAGE_ORDER as string[]).includes(stage)) {+ next = completeStage(next, stage as StageId);+ }+ }++ // Generic progress message for the live caption.+ if (eventType === "progress" && typeof event.content === "string") {+ next = { ...next, message: event.content as string };+ }++ // Book-specific kinds.+ switch (rawKind) {+ case "proposal_ready": {+ next = startStage(next, "ideation");+ next = completeStage(next, "ideation");+ next = { ...next, message: "Proposal ready" };+ break;+ }+ case "exploration_ready": {+ const queries = asNumber(meta.queries);+ const coverage = meta.coverage as Record<string, unknown> | undefined;+ const chunkCount = coverage+ ? Object.values(coverage).reduce<number>((acc, v) => acc + asNumber(v), 0)+ : 0;+ next = startStage(next, "exploration");+ next = completeStage(next, "exploration");+ next = {+ ...next,+ exploration: {+ queryCount: queries,+ chunkCount,+ candidateConcepts: asNumber(meta.candidate_concepts),+ summary: asString(meta.summary).slice(0, 220),+ },+ message: `Source sweep done — ${queries} queries, ${chunkCount} chunks`,+ };+ next = patchStage(next, "exploration", {+ detail: `${queries} queries · ${chunkCount} chunks`,+ });+ break;+ }+ case "spine_round": {+ const round = asString(meta.round);+ const isCritique = round.startsWith("critique");+ const targetStage: StageId = isCritique ? "critique" : "synthesis";+ next = startStage(next, targetStage);+ const issueCount = asNumber(meta.issue_count);+ const chapterCount = asNumber(meta.chapter_count);+ const verdict = asString(meta.verdict);+ if (isCritique) {+ next = {+ ...next,+ critique: {+ rounds: next.critique.rounds + 1,+ issues: issueCount,+ },+ };+ next = patchStage(next, "critique", {+ detail: `${next.critique.rounds} round${+ next.critique.rounds === 1 ? "" : "s"+ } · ${issueCount} issue${issueCount === 1 ? "" : "s"}`,+ });+ } else {+ next = {+ ...next,+ synthesis: {+ ...next.synthesis,+ rounds: next.synthesis.rounds + 1,+ chapterCount: chapterCount || next.synthesis.chapterCount,+ lastVerdict: verdict,+ },+ };+ next = patchStage(next, "synthesis", {+ detail: `${next.synthesis.rounds} round${+ next.synthesis.rounds === 1 ? "" : "s"+ } · ${next.synthesis.chapterCount || 0} chapter${+ next.synthesis.chapterCount === 1 ? "" : "s"+ }`,+ });+ }+ next = {+ ...next,+ message: `${round}${verdict ? ` · ${verdict}` : ""}`,+ };+ break;+ }+ case "spine_ready": {+ const chapterCount = asNumber(meta.chapter_count);+ const nodes = asNumber(meta.concept_node_count);+ const edges = asNumber(meta.concept_edge_count);+ // Both synthesis + critique are done when the spine is ready.+ next = startStage(next, "synthesis");+ next = completeStage(next, "synthesis");+ if (next.critique.rounds > 0) {+ next = completeStage(next, "critique");+ } else {+ next = patchStage(next, "critique", { state: "completed" });+ }+ next = {+ ...next,+ synthesis: {+ ...next.synthesis,+ chapterCount,+ conceptNodes: nodes,+ conceptEdges: edges,+ },+ message: `Spine ready — ${chapterCount} chapters · ${nodes} concepts`,+ };+ next = patchStage(next, "synthesis", {+ detail: `${chapterCount} chapters · ${nodes} concepts`,+ });+ break;+ }+ case "page_planning": {+ next = startStage(next, "compilation");+ next = {+ ...next,+ compilation: {+ ...next.compilation,+ pagesPlanned: next.compilation.pagesPlanned + 1,+ },+ };+ break;+ }+ case "page_planned":+ next = startStage(next, "compilation");+ break;+ case "block_ready": {+ next = {+ ...next,+ compilation: {+ ...next.compilation,+ blocksReady: next.compilation.blocksReady + 1,+ },+ };+ break;+ }+ case "block_error": {+ next = {+ ...next,+ compilation: {+ ...next.compilation,+ blocksError: next.compilation.blocksError + 1,+ },+ };+ break;+ }+ case "page_compiled":+ case "page_ready": {+ next = startStage(next, "compilation");+ next = {+ ...next,+ compilation: {+ ...next.compilation,+ pagesReady: next.compilation.pagesReady + 1,+ },+ };+ next = patchStage(next, "compilation", {+ detail: `${next.compilation.pagesReady} page${+ next.compilation.pagesReady === 1 ? "" : "s"+ } · ${next.compilation.blocksReady} blocks`,+ });+ // Treat the overview as completed once the very first page is ready —+ // the engine pre-materialises the overview before any normal page+ // compilation.+ if (next.stages.overview.state !== "completed") {+ next = patchStage(next, "overview", {+ state: "completed",+ endedAt: Date.now(),+ });+ }+ break;+ }+ case "overview_ready": {+ next = startStage(next, "overview");+ next = completeStage(next, "overview");+ break;+ }+ case "compilation_complete": {+ next = completeStage(next, "compilation");+ next = { ...next, message: "Book compilation complete" };+ break;+ }+ default:+ break;+ }++ // Stream-level error → mark the *currently running* stage as errored.+ if (eventType === "error") {+ const running = STAGE_ORDER.find(+ (id) => next.stages[id].state === "running",+ );+ if (running) {+ next = patchStage(next, running, {+ state: "error",+ detail: asString(event.content) || "error",+ });+ }+ }++ return next;+}++/** True when at least one stage is no longer pending — useful for hiding the+ * timeline on a freshly-loaded existing book where no events arrive. */+export function progressHasActivity(progress: BookProgress): boolean {+ return STAGE_ORDER.some((id) => progress.stages[id].state !== "pending");+}++/** True when every stage is either completed or errored (or skipped). */+export function progressIsTerminal(progress: BookProgress): boolean {+ return STAGE_ORDER.every((id) => {+ const s = progress.stages[id].state;+ return s === "completed" || s === "error" || s === "pending";+ });+}++/** True when generation is fully done — every stage has completed or+ * errored. Implies activity (compilation must have advanced past pending). */+export function progressIsComplete(progress: BookProgress): boolean {+ if (!progressHasActivity(progress)) return false;+ return STAGE_ORDER.every((id) => {+ const s = progress.stages[id].state;+ return s === "completed" || s === "error";+ });+}diff --git a/web/lib/book-types.ts b/web/lib/book-types.tsnew file mode 100644index 000000000..3d5dc57f0--- /dev/null+++ b/web/lib/book-types.ts@@ -0,0 +1,176 @@+// Type definitions mirroring deeptutor.book.models on the backend.+// Kept loose (Record<string, unknown>) where the payload is block-type+// specific so we don't have to keep these in lock-step.++export type BookStatus =+ | "draft"+ | "spine_ready"+ | "compiling"+ | "ready"+ | "error"+ | "archived";++export type PageStatus =+ | "pending"+ | "planning"+ | "generating"+ | "ready"+ | "partial"+ | "error";++export type BlockStatus =+ | "pending"+ | "generating"+ | "ready"+ | "error"+ | "hidden";++export type BlockType =+ | "text"+ | "callout"+ | "quiz"+ | "user_note"+ | "figure"+ | "interactive"+ | "animation"+ | "code"+ | "timeline"+ | "flash_cards"+ | "deep_dive"+ | "section"+ | "concept_graph";++export type ContentType =+ | "theory"+ | "derivation"+ | "history"+ | "practice"+ | "concept"+ | "overview";++export interface ConceptNode {+ id: string;+ label: string;+ chapter_id: string;+ description: string;+ weight: number;+}++export interface ConceptEdge {+ src: string;+ dst: string;+ relation: "depends_on" | "extends" | "related" | string;+ rationale: string;+}++export interface ConceptGraph {+ nodes: ConceptNode[];+ edges: ConceptEdge[];+}++export interface SourceAnchor {+ kind: string;+ ref: string;+ snippet: string;+}++export interface Block {+ id: string;+ type: BlockType;+ status: BlockStatus;+ title: string;+ params: Record<string, unknown>;+ payload: Record<string, unknown>;+ source_anchors: SourceAnchor[];+ metadata: Record<string, unknown>;+ error: string;+ created_at: number;+ updated_at: number;+}++export interface Page {+ id: string;+ book_id: string;+ chapter_id: string;+ title: string;+ learning_objectives: string[];+ content_type: ContentType;+ status: PageStatus;+ order: number;+ blocks: Block[];+ links: Array<{ target_page_id: string; relation: string; label: string }>;+ parent_page_id: string;+ error: string;+ created_at: number;+ updated_at: number;+}++export interface Chapter {+ id: string;+ title: string;+ learning_objectives: string[];+ content_type: ContentType;+ source_anchors: SourceAnchor[];+ prerequisites: string[];+ page_ids: string[];+ summary: string;+ order: number;+}++export interface Spine {+ book_id: string;+ chapters: Chapter[];+ version: number;+ updated_at: number;+ concept_graph?: ConceptGraph;+ exploration_summary?: string;+}++export interface BookProposal {+ title: string;+ description: string;+ scope: string;+ target_level: string;+ estimated_chapters: number;+ rationale: string;+}++export interface Book {+ id: string;+ title: string;+ description: string;+ status: BookStatus;+ proposal: BookProposal | null;+ knowledge_bases: string[];+ language: string;+ page_count: number;+ chapter_count: number;+ created_at: number;+ updated_at: number;+ metadata: Record<string, unknown>;+}++export interface Progress {+ book_id: string;+ current_page_id: string;+ visited_page_ids: string[];+ bookmarked_page_ids: string[];+ quiz_attempts: Array<{+ block_id: string;+ page_id: string;+ question_id: string;+ user_answer: string;+ is_correct: boolean;+ timestamp: number;+ }>;+ weak_chapters: string[];+ score: number;+ updated_at: number;+}++export interface BookDetail {+ book: Book;+ spine: Spine | null;+ pages: Page[];+ progress: Progress;+}diff --git a/web/lib/iframe-html.ts b/web/lib/iframe-html.tsnew file mode 100644index 000000000..5cd094d05--- /dev/null+++ b/web/lib/iframe-html.ts@@ -0,0 +1,89 @@+/**+ * Helpers for rendering AI-generated HTML inside a sandboxed `<iframe>`:+ * - {@link injectKaTeX} ensures the page can render `$...$` / `$$...$$`+ * even if the model didn't include KaTeX itself.+ * - {@link sanitizeIframeHtml} strips bare `<script>` blocks (except the+ * KaTeX init shim) and any inline event handlers / `javascript:` URLs.+ *+ * These were originally written for the (now-deprecated) Guided Learning+ * page; the visualize capability now reuses them for `render_mode=html`.+ */++const KATEX_RESOURCES = [+ '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" crossorigin="anonymous">',+ '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" crossorigin="anonymous"><' ++ "/script>",+ '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" crossorigin="anonymous"><' ++ "/script>",+].join("\n ");++// eslint-disable-next-line no-template-curly-in-string+const KATEX_INIT_SCRIPT =+ "<script data-katex-init>" ++ 'document.addEventListener("DOMContentLoaded",function(){var t=0,i=setInterval(function(){if(typeof renderMathInElement==="function"){clearInterval(i);try{renderMathInElement(document.body,{delimiters:[{left:"$$",right:"$$",display:true},{left:"$",right:"$",display:false},{left:"\\\\(",right:"\\\\)",display:false},{left:"\\\\[",right:"\\\\]",display:true}],throwOnError:false})}catch(e){console.error("[KaTeX] Error:",e)}}else if(++t>50){clearInterval(i);console.warn("[KaTeX] Timeout")}},100)});' ++ "<" ++ "/script>";++const KATEX_HEAD = KATEX_RESOURCES + "\n " + KATEX_INIT_SCRIPT;++/**+ * Inject KaTeX (CSS + JS + auto-render init) into the document's `<head>`.+ * No-op if the document already references KaTeX.+ */+export function injectKaTeX(html: string): string {+ const lower = html.toLowerCase();+ const hasKaTeX =+ lower.includes("katex.min.css") ||+ lower.includes("katex.min.js") ||+ lower.includes("katex@") ||+ lower.includes("cdn.jsdelivr.net/npm/katex") ||+ lower.includes("unpkg.com/katex");++ if (hasKaTeX) return html;++ if (html.includes("</head>")) {+ return html.replace("</head>", KATEX_HEAD + "\n</head>");+ }+ if (html.includes("<head>")) {+ return html.replace(/<head([^>]*)>/i, "<head$1>\n" + KATEX_HEAD);+ }+ if (html.includes("<html")) {+ return html.replace(+ /(<html[^>]*>)/i,+ '$1\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n' ++ KATEX_HEAD ++ "\n</head>",+ );+ }++ return (+ '<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n' ++ KATEX_HEAD ++ "\n</head>\n<body>\n" ++ html ++ "\n</body>\n</html>"+ );+}++/**+ * Light defense-in-depth on top of `sandbox="allow-scripts"` (without+ * `allow-same-origin`): strip `javascript:` URLs and (best-effort) any+ * `<a target="_top">` / `target="_parent"` so a misbehaving model cannot+ * navigate the parent frame. We deliberately keep `<script>` tags and+ * inline `on*=` handlers because the model is *expected* to ship+ * interactive JS — and the sandbox already isolates it in a null origin+ * with no access to the host page.+ */+export function sanitizeIframeHtml(html: string): string {+ return html+ .replace(/\s(href|src|formaction)\s*=\s*(['"])\s*javascript:[\s\S]*?\2/gi, "")+ .replace(/\starget\s*=\s*(['"])_(top|parent)\1/gi, ' target="_self"');+}++/**+ * Convenience: inject KaTeX, then sanitize. Suitable for a one-shot iframe+ * `srcdoc` write.+ */+export function prepareIframeHtml(html: string): string {+ return sanitizeIframeHtml(injectKaTeX(html));+}diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.tsindex 57f517551..1c73dc9e8 100644--- a/web/lib/markdown-display.ts+++ b/web/lib/markdown-display.ts@@ -19,6 +19,74 @@ function stripInvisibleCharacters(value: string): string {return value.replace(ZERO_WIDTH_REGEX, "");}+// Tags that the renderer (rehype-raw + react-markdown) is allowed to render+// as actual HTML/SVG/MathML elements. Any other `<word>` looking token+// (e.g. LLM-pseudo-tags like <mem>, <think>, <tool_call>, <answer>, <search>)+// is escaped into inline code so the browser does not warn about unknown+// custom elements with lowercase names.+const ALLOWED_HTML_TAGS = new Set<string>([+ // structural+ "p", "div", "span", "section", "article", "aside", "header", "footer",+ "main", "nav", "address", "dialog",+ // text-level+ "a", "em", "strong", "b", "i", "u", "s", "del", "ins", "small", "sub",+ "sup", "mark", "kbd", "code", "samp", "var", "q", "cite", "abbr", "time",+ "wbr", "ruby", "rt", "rp", "bdi", "bdo",+ // line-level+ "br", "hr",+ // lists+ "ol", "ul", "li", "dl", "dt", "dd",+ // headings+ "h1", "h2", "h3", "h4", "h5", "h6",+ // block quotes / pre+ "blockquote", "pre", "figure", "figcaption",+ // tables+ "table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "col",+ "colgroup",+ // media+ "img", "video", "audio", "source", "picture", "track", "iframe", "canvas",+ "embed", "object", "param", "map", "area",+ // disclosure / forms (we keep these even if they are usually stripped)+ "details", "summary", "progress", "meter", "input", "textarea", "select",+ "button", "label", "fieldset", "legend", "form", "option", "optgroup",+ "datalist", "output",+ // svg+ "svg", "g", "path", "rect", "circle", "ellipse", "line", "polyline",+ "polygon", "text", "tspan", "use", "defs", "lineargradient",+ "radialgradient", "stop", "marker", "pattern", "mask", "clippath",+ "symbol", "title", "desc", "foreignobject",+ // mathml+ "math", "mi", "mn", "mo", "ms", "mtext", "mrow", "mfrac", "msup", "msub",+ "msubsup", "munder", "mover", "munderover", "mroot", "msqrt", "menclose",+ "mspace", "mtable", "mtr", "mtd",+]);++const HTML_LIKE_TAG_REGEX = /<\/?([A-Za-z][A-Za-z0-9_-]*)\b[^<>]*?\/?>/g;+const PROTECTED_SPAN_REGEX = /```[\s\S]*?```|`[^`\n]*`/g;+const PROTECTED_PLACEHOLDER_REGEX = /\u0000PROTECTED_(\d+)\u0000/g;++function escapeUnknownHtmlTags(content: string): string {+ if (!content || (!content.includes("<") && !content.includes(">"))) {+ return content;+ }+ const protectedSpans: string[] = [];+ const masked = content.replace(PROTECTED_SPAN_REGEX, (match) => {+ protectedSpans.push(match);+ return `\u0000PROTECTED_${protectedSpans.length - 1}\u0000`;+ });+ const escaped = masked.replace(HTML_LIKE_TAG_REGEX, (match, name: string) => {+ const lower = String(name).toLowerCase();+ if (ALLOWED_HTML_TAGS.has(lower)) return match;+ // Already wrapped in backticks (would happen if the source already+ // protected a similar token earlier in the string).+ return `\`${match}\``;+ });+ return escaped.replace(+ PROTECTED_PLACEHOLDER_REGEX,+ (_, idx: string) => protectedSpans[Number(idx)] ?? "",+ );+}+function stripDisplaySyntax(value: string): string {return stripInvisibleCharacters(String(value)).replace(/ /gi, " ")@@ -171,7 +239,8 @@ export function normalizeMarkdownForDisplay(content: string): string {.replace(/^\n+|\n+$/g, "");const cleaned = removeEmptyMarkdownTables(removeEmptyHtmlTables(normalized)).replace(/\n{3,}/g, "\n\n");- return linkifyCitations(unwrapBacktickedCitations(cleaned));+ const safe = escapeUnknownHtmlTags(cleaned);+ return linkifyCitations(unwrapBacktickedCitations(safe));}export function hasVisibleMarkdownContent(content: string): boolean {diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.tsindex 0088a4a7a..cfa297aa5 100644--- a/web/lib/notebook-api.ts+++ b/web/lib/notebook-api.ts@@ -12,8 +12,7 @@ export type NotebookRecordType =| "question"| "research"| "co_writer"- | "chat"- | "guided_learning";+ | "chat";export interface NotebookSummary {id: string;diff --git a/web/lib/notebook-selection-types.ts b/web/lib/notebook-selection-types.tsnew file mode 100644index 000000000..084fea73c--- /dev/null+++ b/web/lib/notebook-selection-types.ts@@ -0,0 +1,40 @@+// Shared types used by Notebook reference pickers.++export interface Notebook {+ id: string;+ name: string;+ description: string;+ record_count: number;+ color: string;+}++export interface NotebookRecord {+ id: string;+ title: string;+ summary?: string;+ user_query: string;+ output: string;+ type: string;+}++export interface SelectedRecord extends NotebookRecord {+ notebookId: string;+ notebookName: string;+}++export function getTypeColor(type: string): string {+ switch (type) {+ case "solve":+ return "bg-blue-100 text-blue-700 border-blue-200";+ case "question":+ return "bg-purple-100 text-purple-700 border-purple-200";+ case "research":+ return "bg-emerald-100 text-emerald-700 border-emerald-200";+ case "co_writer":+ return "bg-amber-100 text-amber-700 border-amber-200";+ case "chat":+ return "bg-cyan-100 text-cyan-700 border-cyan-200";+ default:+ return "bg-slate-100 text-slate-700 border-slate-200";+ }+}diff --git a/web/lib/persistence.ts b/web/lib/persistence.tsindex a4f01758c..49087b4f5 100644--- a/web/lib/persistence.ts+++ b/web/lib/persistence.ts@@ -227,7 +227,6 @@ export const STORAGE_KEYS = {SOLVER_STATE: "solver_state",QUESTION_STATE: "question_state",RESEARCH_STATE: "research_state",- GUIDE_SESSION: "guide_session",COWRITER_CONTENT: "cowriter_content",} as const;@@ -252,5 +251,4 @@ export const EXCLUDE_FIELDS = {"uploadedFile",] as const,RESEARCH: ["status", "logs", "progress"] as const,- GUIDE: ["isLoading", "loadingMessage"] as const,} as const;diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 89e75cd4d..624fe4559 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -64,6 +64,7 @@ export interface StartTurnMessage {record_ids: string[];}[];history_references?: string[];+ question_notebook_references?: number[];}export interface SubscribeTurnMessage {diff --git a/web/lib/visualize-types.ts b/web/lib/visualize-types.tsindex f7feab709..6e13c31e3 100644--- a/web/lib/visualize-types.ts+++ b/web/lib/visualize-types.ts@@ -1,5 +1,10 @@-export type VisualizeRenderType = "svg" | "chartjs" | "mermaid";-export type VisualizeRenderMode = "auto" | "svg" | "chartjs" | "mermaid";+export type VisualizeRenderType = "svg" | "chartjs" | "mermaid" | "html";+export type VisualizeRenderMode =+ | "auto"+ | "svg"+ | "chartjs"+ | "mermaid"+ | "html";export interface VisualizeFormConfig {render_mode: VisualizeRenderMode;@@ -20,6 +25,7 @@ const VISUALIZE_RENDER_LABELS: Record<VisualizeRenderMode, string> = {chartjs: "Chart.js",svg: "SVG",mermaid: "Mermaid",+ html: "HTML",};/**@@ -58,7 +64,13 @@ export function extractVisualizeResult(if (!resultMetadata) return null;const renderType = resultMetadata.render_type;- if (renderType !== "svg" && renderType !== "chartjs" && renderType !== "mermaid") return null;+ if (+ renderType !== "svg" &&+ renderType !== "chartjs" &&+ renderType !== "mermaid" &&+ renderType !== "html"+ )+ return null;const codeRaw =resultMetadata.code && typeof resultMetadata.code === "object"diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 3d5086830..76cb0ed87 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -101,7 +101,6 @@"Research in progress...": "Research in progress...","Co-Writer": "Co-Writer","Intelligent markdown editor with AI-powered writing assistance.": "Intelligent markdown editor with AI-powered writing assistance.",- "Guided Learning": "Guided Learning","TutorBot": "TutorBot","Knowledge": "Knowledge","Memory": "Memory",@@ -141,7 +140,7 @@"Confirm Clear": "Confirm Clear","This will clear all locally cached data": "This will clear all locally cached data","Clear All": "Clear All",- "Including: chat history, solver history, question results, research reports, guided learning progress, Co-Writer content, etc. This action cannot be undone.": "Including: chat history, solver history, question results, research reports, guided learning progress, Co-Writer content, etc. This action cannot be undone.",+ "Including: chat history, solver history, question results, research reports, Co-Writer content, etc. This action cannot be undone.": "Including: chat history, solver history, question results, research reports, Co-Writer content, etc. This action cannot be undone.","Model": "Model","Provider": "Provider","Port Configuration": "Port Configuration",@@ -607,7 +606,6 @@"Select a notebook to inspect its saved records.": "Select a notebook to inspect its saved records.","Unknown time": "Unknown time","Open chat session": "Open chat session",- "Open guided learning session": "Open guided learning session","Query:": "Query:","Delete knowledge base \"{{name}}\"?": "Delete knowledge base \"{{name}}\"?","This knowledge base is in legacy index format and needs reindex before upload.": "This knowledge base is in legacy index format and needs reindex before upload.",@@ -860,7 +858,7 @@"Use Selected Sessions ({n})": "Use Selected Sessions ({n})","Use Selected Records ({n})": "Use Selected Records ({n})","selected": "selected",- "Save a chat or guided learning result first to populate a notebook.": "Save a chat or guided learning result first to populate a notebook.",+ "Save a chat result first to populate a notebook.": "Save a chat result first to populate a notebook.","Create one from the Knowledge → Notebooks page.": "Create one from the Knowledge → Notebooks page.","Delete notebook \"{{name}}\"?": "Delete notebook \"{{name}}\"?","Deselect": "Deselect",@@ -897,7 +895,16 @@"Image Output": "Image Output","Fullscreen math animation output": "Fullscreen math animation output","Delete this chat history?": "Delete this chat history?",- "Question Notebook": "Question Notebook",+ "Question Bank": "Question Bank",+ "Question Bank Reference": "Question Bank Reference",+ "Select Question Bank Entries": "Select Question Bank Entries",+ "Choose quiz questions to ground the next request.": "Choose quiz questions to ground the next request.",+ "Use Selected Questions ({n})": "Use Selected Questions ({n})",+ "Search questions by content": "Search questions by content",+ "1 question selected": "1 question selected",+ "{n} questions selected": "{n} questions selected",+ "No matching questions found.": "No matching questions found.",+ "No quiz entries yet.": "No quiz entries yet.","Review and organize quiz questions across sessions.": "Review and organize quiz questions across sessions.","All": "All","Bookmarked": "Bookmarked",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 789ed5365..652f2e377 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -101,7 +101,6 @@"Research in progress...": "研究进行中…","Co-Writer": "智能写作","Intelligent markdown editor with AI-powered writing assistance.": "带 AI 写作辅助的智能 Markdown 编辑器。",- "Guided Learning": "引导式学习","TutorBot": "辅导机器人","Knowledge": "知识库","Memory": "记忆",@@ -141,7 +140,7 @@"Confirm Clear": "确认清除","This will clear all locally cached data": "此操作将清除所有本地缓存数据","Clear All": "全部清除",- "Including: chat history, solver history, question results, research reports, guided learning progress, Co-Writer content, etc. This action cannot be undone.": "包括:聊天记录、解题历史、题目生成结果、研究报告、引导学习进度、Co-Writer 内容等。此操作不可撤销。",+ "Including: chat history, solver history, question results, research reports, Co-Writer content, etc. This action cannot be undone.": "包括:聊天记录、解题历史、题目生成结果、研究报告、Co-Writer 内容等。此操作不可撤销。","Model": "模型","Provider": "提供商","Port Configuration": "端口配置",@@ -607,7 +606,6 @@"Select a notebook to inspect its saved records.": "选择一个笔记本以查看其保存的记录。","Unknown time": "未知时间","Open chat session": "打开聊天会话",- "Open guided learning session": "打开引导学习会话","Query:": "问题:","Delete knowledge base \"{{name}}\"?": "确定删除知识库「{{name}}」吗?","This knowledge base is in legacy index format and needs reindex before upload.": "该知识库使用旧版索引格式,需要重新索引后才能上传。",@@ -860,7 +858,7 @@"Use Selected Sessions ({n})": "使用所选会话({n})","Use Selected Records ({n})": "使用所选记录({n})","selected": "项已选",- "Save a chat or guided learning result first to populate a notebook.": "请先保存一次聊天或学习结果以填充笔记本。",+ "Save a chat result first to populate a notebook.": "请先保存一次聊天结果以填充笔记本。","Create one from the Knowledge → Notebooks page.": "可在“知识 → 笔记本”页面创建。","Delete notebook \"{{name}}\"?": "确定删除笔记本 “{{name}}” 吗?","Deselect": "取消选择",@@ -897,7 +895,16 @@"Image Output": "图片输出","Fullscreen math animation output": "全屏数学动画输出","Delete this chat history?": "确定删除此聊天记录吗?",- "Question Notebook": "题目笔记本",+ "Question Bank": "题库",+ "Question Bank Reference": "题库引用",+ "Select Question Bank Entries": "选择题库题目",+ "Choose quiz questions to ground the next request.": "选择题库题目作为本次提问的上下文。",+ "Use Selected Questions ({n})": "使用所选题目 ({n})",+ "Search questions by content": "按题目内容搜索",+ "1 question selected": "已选择 1 道题目",+ "{n} questions selected": "已选择 {n} 道题目",+ "No matching questions found.": "未找到匹配的题目。",+ "No quiz entries yet.": "暂无题目记录。","Review and organize quiz questions across sessions.": "跨会话回顾和整理测验题目。","All": "全部","Bookmarked": "已收藏",diff --git a/web/scripts/route_budgets.mjs b/web/scripts/route_budgets.mjsindex ca714b7e4..7e7c41e6d 100644--- a/web/scripts/route_budgets.mjs+++ b/web/scripts/route_budgets.mjs@@ -9,7 +9,6 @@ const ROUTE_BUDGETS_KB = {"/": 700,"/playground": 700,"/co-writer": 700,- "/guide": 700,"/knowledge": 450,"/memory": 450,"/settings": 180,