DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: readme, kb-management, book management
Bingxi Zhao (Frank)cb7deebc787d
diff --git a/README.md b/README.mdindex 30ed9191e..7265562a3 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@[](./Communication.md)[](https://github.com/HKUDS/DeepTutor/issues/78)-[Features](#-key-features) · [Get Started](#-get-started) · [Explore](#-explore-deeptutor) · [TutorBot](#-tutorbot--persistent-autonomous-ai-tutors) · [CLI](#%EF%B8%8F-deeptutor-cli--agent-native-interface) · [Community](#-community--ecosystem)+[Features](#-key-features) · [Get Started](#-get-started) · [Explore](#-explore-deeptutor) · [TutorBot](#-tutorbot--persistent-autonomous-ai-tutors) · [CLI](#%EF%B8%8F-deeptutor-cli--agent-native-interface) · [Roadmap](#%EF%B8%8F-roadmap) · [Community](#-community--ecosystem)[🇨🇳 中文](assets/README/README_CN.md) · [🇯🇵 日本語](assets/README/README_JA.md) · [🇪🇸 Español](assets/README/README_ES.md) · [🇫🇷 Français](assets/README/README_FR.md) · [🇸🇦 العربية](assets/README/README_AR.md) · [🇷🇺 Русский](assets/README/README_RU.md) · [🇮🇳 हिन्दी](assets/README/README_HI.md) · [🇵🇹 Português](assets/README/README_PT.md) · [🇹🇭 ภาษาไทย](assets/README/README_TH.md)@@ -82,12 +82,12 @@## ✨ Key Features-- **Unified Chat Workspace** — Five modes, one thread. Chat, Deep Solve, Quiz Generation, Deep Research, and Math Animator share the same context — start a conversation, escalate to multi-agent problem solving, generate quizzes, then deep-dive into research, all without losing a single message.-- **Personal TutorBots** — Not chatbots — autonomous tutors. Each TutorBot lives in its own workspace with its own memory, personality, and skill set. They set reminders, learn new abilities, and evolve as you grow. Powered by [nanobot](https://github.com/HKUDS/nanobot).-- **AI Co-Writer** — A Markdown editor where AI is a first-class collaborator. Select text, rewrite, expand, or summarize — drawing from your knowledge base and the web. Every piece feeds back into your learning ecosystem.-- **Guided Learning** — Turn your materials into structured, visual learning journeys. DeepTutor designs multi-step plans, generates interactive pages for each knowledge point, and lets you discuss alongside each step.-- **Knowledge Hub** — Upload PDFs, Markdown, and text files to build RAG-ready knowledge bases. Organize insights across sessions in color-coded notebooks. Your documents don't just sit there — they actively power every conversation.+- **Unified Chat Workspace** — Six modes, one thread. Chat, Deep Solve, Quiz Generation, Deep Research, Math Animator, and Visualize share the same context — start a conversation, escalate to multi-agent problem solving, generate quizzes, visualize concepts, then deep-dive into research, all without losing a single message.+- **AI Co-Writer** — A multi-document Markdown workspace where AI is a first-class collaborator. Select text, rewrite, expand, or summarize — drawing from your knowledge base and the web. Every piece feeds back into your learning ecosystem.+- **Book Engine** — Turn your materials into structured, interactive "living books". A multi-agent pipeline designs outlines, retrieves relevant sources, and compiles rich pages with 14 block types — quizzes, flash cards, timelines, concept graphs, interactive demos, and more.+- **Knowledge Hub** — Upload PDFs, Markdown, and text files to build RAG-ready knowledge bases. Organize insights in color-coded notebooks, revisit quiz questions in the Question Bank, and create custom Skills that shape how DeepTutor teaches you. Your documents don't just sit there — they actively power every conversation.- **Persistent Memory** — DeepTutor builds a living profile of you: what you've studied, how you learn, and where you're heading. Shared across all features and TutorBots, it gets sharper with every interaction.+- **Personal TutorBots** — Not chatbots — autonomous tutors. Each TutorBot lives in its own workspace with its own memory, personality, and skill set. They set reminders, learn new abilities, and evolve as you grow. Powered by [nanobot](https://github.com/HKUDS/nanobot).- **Agent-Native CLI** — Every capability, knowledge base, session, and TutorBot is one command away. Rich terminal output for humans, structured JSON for AI agents and pipelines. Hand DeepTutor a [`SKILL.md`](SKILL.md) and your agents can operate it autonomously.---@@ -243,6 +243,7 @@ OpenAI-compatible providers (DashScope, SiliconFlow, etc.) work via the `custom`|:--|:--|:--|| Brave | `BRAVE_API_KEY` | Recommended, free tier available || Tavily | `TAVILY_API_KEY` | |+| Serper | `SERPER_API_KEY` | Google Search results via Serper || Jina | `JINA_API_KEY` | || SearXNG | — | Self-hosted, no API key needed || DuckDuckGo | — | No API key needed |@@ -443,7 +444,7 @@ deeptutor kb create my-kb --doc textbook.pdf # Build a knowledge base<img src="assets/figs/dt-chat.png" alt="Chat Workspace" width="800"></div>-Five distinct modes coexist in a single workspace, bound by a **unified context management system**. Conversation history, knowledge bases, and references persist across modes — switch between them freely within the same topic, whenever the moment calls for it.+Six distinct modes coexist in a single workspace, bound by a **unified context management system**. Conversation history, knowledge bases, and references persist across modes — switch between them freely within the same topic, whenever the moment calls for it.| Mode | What It Does ||:---|:---|@@ -452,35 +453,33 @@ Five distinct modes coexist in a single workspace, bound by a **unified context| **Quiz Generation** | Generate assessments grounded in your knowledge base, with built-in validation. || **Deep Research** | Decompose a topic into subtopics, dispatch parallel research agents across RAG, web, and academic papers, and produce a fully cited report. || **Math Animator** | Turn mathematical concepts into visual animations and storyboards powered by Manim. |+| **Visualize** | Generate interactive SVG diagrams, Chart.js charts, Mermaid graphs, or self-contained HTML pages from natural language descriptions. |Tools are **decoupled from workflows** — in every mode, you decide which tools to enable, how many to use, or whether to use any at all. The workflow orchestrates the reasoning; the tools are yours to compose.-> Start with a quick chat question, escalate to Deep Solve when it gets hard, generate quiz questions to test yourself, then launch a Deep Research to go deeper — all in one continuous thread.+> Start with a quick chat question, escalate to Deep Solve when it gets hard, visualize a concept, generate quiz questions to test yourself, then launch a Deep Research to go deeper — all in one continuous thread.-### ✍️ Co-Writer — AI Inside Your Editor+### ✍️ Co-Writer — Multi-Document AI Writing Workspace<div align="center"><img src="assets/figs/dt-cowriter.png" alt="Co-Writer" width="800"></div>-Co-Writer brings the intelligence of Chat directly into a writing surface. It is a full-featured Markdown editor where AI is a first-class collaborator — not a sidebar, not an afterthought.+Co-Writer brings the intelligence of Chat directly into a writing surface. Create and manage multiple documents, each persisted in its own workspace — not a single throwaway scratchpad, but a full-featured multi-document Markdown editor where AI is a first-class collaborator.Select any text and choose **Rewrite**, **Expand**, or **Shorten** — optionally drawing context from your knowledge base or the web. The editing flow is non-destructive with full undo/redo, and every piece you write can be saved straight to your notebooks, feeding back into your learning ecosystem.-### 🎓 Guided Learning — Visual, Step-by-Step Mastery+### 📖 Book Engine — Interactive "Living Books"<div align="center">-<img src="assets/figs/dt-guide.png" alt="Guided Learning" width="800">+<img src="assets/figs/dt-book-0.png" alt="Book Library" width="270"><img src="assets/figs/dt-book-1.png" alt="Book Reader" width="270"><img src="assets/figs/dt-book-2.png" alt="Book Animation" width="270"></div>-Guided Learning turns your personal materials into structured, multi-step learning journeys. Provide a topic, optionally link notebook records, and DeepTutor will:+Give DeepTutor a topic, point it at your knowledge base, and it produces a structured, interactive book — not a static export, but a living document you can read, quiz yourself on, and discuss in context.-1. **Design a learning plan** — Identify 3–5 progressive knowledge points from your materials.-2. **Generate interactive pages** — Each point becomes a rich visual HTML page with explanations, diagrams, and examples.-3. **Enable contextual Q&A** — Chat alongside each step for deeper exploration.-4. **Summarize your progress** — Upon completion, receive a learning summary of everything you've covered.+Behind the scenes, a multi-agent pipeline handles the heavy lifting: proposing an outline, retrieving relevant sources from your knowledge base, synthesizing a chapter tree, planning each page, and compiling every block. You stay in control — review the proposal, reorder chapters, and chat alongside any page.-Sessions are persistent — pause, resume, or revisit any step at any time.+Pages are assembled from 14 block types — text, callout, quiz, flash cards, code, figure, deep dive, animation, interactive demo, timeline, concept graph, section, user note, and placeholder — each rendered with its own interactive component. A real-time progress timeline lets you watch compilation unfold as the book takes shape.### 📚 Knowledge Management — Your Learning Infrastructure@@ -488,10 +487,12 @@ Sessions are persistent — pause, resume, or revisit any step at any time.<img src="assets/figs/dt-knowledge.png" alt="Knowledge Management" width="800"></div>-Knowledge is where you build and manage the document collections that power everything else in DeepTutor.+Knowledge is where you build and manage the document collections, notes, and teaching personas that power everything else in DeepTutor.- **Knowledge Bases** — Upload PDF, TXT, or Markdown files to create searchable, RAG-ready collections. Add documents incrementally as your library grows.-- **Notebooks** — Organize learning records across sessions. Save insights from Chat, Guided Learning, Co-Writer, or Deep Research into categorized, color-coded notebooks.+- **Notebooks** — Organize learning records across sessions. Save insights from Chat, Co-Writer, Book, or Deep Research into categorized, color-coded notebooks.+- **Question Bank** — Browse and revisit all generated quiz questions. Bookmark entries and @-mention them directly in chat to reason over past performance.+- **Skills** — Create custom teaching personas via `SKILL.md` files. Each skill defines a name, description, optional triggers, and a Markdown body that is injected into the chat system prompt when active — turning DeepTutor into a Socratic tutor, a peer study partner, a research assistant, or any role you design.Your knowledge base is not passive storage — it actively participates in every conversation, every research session, and every learning path you create.@@ -555,6 +556,7 @@ deeptutor run chat "Explain the Fourier transform" -t rag --kb textbookdeeptutor run deep_solve "Prove that √2 is irrational" -t reasondeeptutor run deep_question "Linear algebra" --config num_questions=5deeptutor run deep_research "Attention mechanisms in transformers"+deeptutor run visualize "Draw the architecture of a transformer"```**Interactive REPL** — A persistent chat session with live mode switching:@@ -594,7 +596,7 @@ deeptutor session open <id> # Resume in REPL| Command | Description ||:---|:---|-| `deeptutor run <capability> <message>` | Run any capability in a single turn (`chat`, `deep_solve`, `deep_question`, `deep_research`, `math_animator`) |+| `deeptutor run <capability> <message>` | Run any capability in a single turn (`chat`, `deep_solve`, `deep_question`, `deep_research`, `math_animator`, `visualize`) || `deeptutor chat` | Interactive REPL with optional `--capability`, `--tool`, `--kb`, `--language` || `deeptutor serve` | Start the DeepTutor API server |@@ -647,6 +649,14 @@ deeptutor session open <id> # Resume in REPL| `deeptutor notebook replace-md <id> <rec> <path>` | Replace a markdown record || `deeptutor notebook remove-record <id> <rec>` | Remove a record |+**`deeptutor book`**++| Command | Description |+|:---|:---|+| `deeptutor book list` | List all books in the workspace |+| `deeptutor book health <book_id>` | Check KB drift and book health |+| `deeptutor book refresh-fingerprints <book_id>` | Refresh KB fingerprints and clear stale pages |+**`deeptutor config` / `plugin` / `provider`**| Command | Description |diff --git a/assets/figs/dt-book-0.png b/assets/figs/dt-book-0.pngnew file mode 100644index 000000000..1bdaa80deBinary files /dev/null and b/assets/figs/dt-book-0.png differdiff --git a/assets/figs/dt-book-1.png b/assets/figs/dt-book-1.pngnew file mode 100644index 000000000..00547f60aBinary files /dev/null and b/assets/figs/dt-book-1.png differdiff --git a/assets/figs/dt-book-2.png b/assets/figs/dt-book-2.pngnew file mode 100644index 000000000..ba850b982Binary files /dev/null and b/assets/figs/dt-book-2.png differdiff --git a/assets/figs/dt-chat.png b/assets/figs/dt-chat.pngindex f2d5d7820..eb0f1753b 100644Binary files a/assets/figs/dt-chat.png and b/assets/figs/dt-chat.png differdiff --git a/assets/figs/dt-cowriter.png b/assets/figs/dt-cowriter.pngindex b9b0710f3..d5369686b 100644Binary files a/assets/figs/dt-cowriter.png and b/assets/figs/dt-cowriter.png differdiff --git a/assets/figs/dt-guide.png b/assets/figs/dt-guide.pngdeleted file mode 100644index f82d022fd..000000000Binary files a/assets/figs/dt-guide.png and /dev/null differdiff --git a/assets/figs/dt-knowledge.png b/assets/figs/dt-knowledge.pngindex 7dc88877f..8c9250bf8 100644Binary files a/assets/figs/dt-knowledge.png and b/assets/figs/dt-knowledge.png differdiff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex a3868d796..edd0faadc 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -930,6 +930,8 @@ class AgenticChatPipeline:system_parts = [system_prompt]if context.memory_context:system_parts.append(context.memory_context)+ if context.skills_context:+ system_parts.append(context.skills_context)messages: list[dict[str, Any]] = [{"role": "system", "content": "\n\n".join(system_parts)}]for item in context.conversation_history:diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 1f83cfda3..3ecd42503 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -211,6 +211,7 @@ from deeptutor.api.routers import (question_notebook,sessions,settings,+ skills,solve,system,tutorbot,@@ -233,6 +234,7 @@ app.include_router(question_notebook.router, prefix="/api/v1/question-notebook", tags=["question-notebook"])app.include_router(settings.router, prefix="/api/v1/settings", tags=["settings"])+app.include_router(skills.router, prefix="/api/v1/skills", tags=["skills"])app.include_router(system.router, prefix="/api/v1/system", tags=["system"])app.include_router(plugins_api.router, prefix="/api/v1/plugins", tags=["plugins"])app.include_router(agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"])diff --git a/deeptutor/api/routers/skills.py b/deeptutor/api/routers/skills.pynew file mode 100644index 000000000..06cfc1603--- /dev/null+++ b/deeptutor/api/routers/skills.py@@ -0,0 +1,100 @@+"""+Skills API Router+=================++CRUD endpoints for user-authored SKILL.md files stored under+``data/user/workspace/skills/<name>/SKILL.md``.++Mounted at ``/api/v1/skills``.+"""++from __future__ import annotations++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from deeptutor.services.skill import get_skill_service+from deeptutor.services.skill.service import (+ InvalidSkillNameError,+ SkillExistsError,+ SkillNotFoundError,+)++router = APIRouter()+++class CreateSkillRequest(BaseModel):+ name: str = Field(..., min_length=1, max_length=64)+ description: str = ""+ content: str = ""+++class UpdateSkillRequest(BaseModel):+ description: str | None = None+ content: str | None = None+ rename_to: str | None = None++[email protected]("/list")+async def list_skills() -> dict[str, list[dict[str, str]]]:+ service = get_skill_service()+ items = [info.to_dict() for info in service.list_skills()]+ return {"skills": items}++[email protected]("/{name}")+async def get_skill(name: str) -> dict[str, str]:+ service = get_skill_service()+ try:+ return service.get_detail(name).to_dict()+ except SkillNotFoundError:+ raise HTTPException(status_code=404, detail=f"Skill not found: {name}")+ except InvalidSkillNameError as exc:+ raise HTTPException(status_code=400, detail=str(exc))++[email protected]("/create")+async def create_skill(payload: CreateSkillRequest) -> dict[str, str]:+ service = get_skill_service()+ try:+ info = service.create(+ name=payload.name,+ description=payload.description,+ content=payload.content,+ )+ return info.to_dict()+ except SkillExistsError:+ raise HTTPException(status_code=409, detail=f"Skill already exists: {payload.name}")+ except InvalidSkillNameError as exc:+ raise HTTPException(status_code=400, detail=str(exc))++[email protected]("/{name}")+async def update_skill(name: str, payload: UpdateSkillRequest) -> dict[str, str]:+ service = get_skill_service()+ try:+ info = service.update(+ name,+ description=payload.description,+ content=payload.content,+ rename_to=payload.rename_to,+ )+ return info.to_dict()+ except SkillNotFoundError:+ raise HTTPException(status_code=404, detail=f"Skill not found: {name}")+ except SkillExistsError as exc:+ raise HTTPException(status_code=409, detail=str(exc))+ except InvalidSkillNameError as exc:+ raise HTTPException(status_code=400, detail=str(exc))++[email protected]("/{name}")+async def delete_skill(name: str) -> dict[str, str]:+ service = get_skill_service()+ try:+ service.delete(name)+ return {"status": "deleted", "name": name}+ except SkillNotFoundError:+ raise HTTPException(status_code=404, detail=f"Skill not found: {name}")+ except InvalidSkillNameError as exc:+ raise HTTPException(status_code=400, detail=str(exc))diff --git a/deeptutor/app/facade.py b/deeptutor/app/facade.pyindex 4d5ae10ff..3089847d0 100644--- a/deeptutor/app/facade.py+++ b/deeptutor/app/facade.py@@ -26,6 +26,7 @@ class TurnRequest:notebook_references: list[dict[str, Any]] = field(default_factory=list)history_references: list[str] = field(default_factory=list)attachments: list[dict[str, Any]] = field(default_factory=list)+ skills: list[str] = field(default_factory=list)def to_payload(self) -> dict[str, Any]:return {@@ -39,6 +40,7 @@ class TurnRequest:"notebook_references": list(self.notebook_references),"history_references": list(self.history_references),"attachments": list(self.attachments),+ "skills": list(self.skills),}diff --git a/deeptutor/core/context.py b/deeptutor/core/context.pyindex 898e3cc75..752e76646 100644--- a/deeptutor/core/context.py+++ b/deeptutor/core/context.py@@ -55,4 +55,5 @@ class UnifiedContext:notebook_context: str = ""history_context: str = ""memory_context: str = ""+ skills_context: str = ""metadata: dict[str, Any] = field(default_factory=dict)diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 32b04f68d..7a77549ad 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -657,7 +657,11 @@ class KnowledgeBaseManager:if name not in self.list_knowledge_bases():raise ValueError(f"Knowledge base not found: {name}")- kb_dir = self.get_knowledge_base_path(name)+ # Resolve the directory directly to stay idempotent: if the on-disk+ # folder was already removed (e.g. manually rm-rf'd) we still want to+ # purge the orphaned entry from kb_config.json instead of failing.+ kb_dir = self.base_dir / name+ dir_exists = kb_dir.exists()if not confirm:# Ask for confirmation in CLI@@ -668,8 +672,19 @@ class KnowledgeBaseManager:print("Deletion cancelled.")return False- # Delete the directory- shutil.rmtree(kb_dir)+ if dir_exists:+ try:+ shutil.rmtree(kb_dir)+ except FileNotFoundError:+ # Race: someone else deleted it between exists() and rmtree.+ pass+ except OSError as e:+ logger.error(f"Failed to remove KB directory '{kb_dir}': {e}")+ raise+ else:+ logger.warning(+ f"KB directory '{kb_dir}' missing on disk; cleaning up orphaned config entry."+ )# Remove from configif name in self.config.get("knowledge_bases", {}):@@ -677,8 +692,8 @@ class KnowledgeBaseManager:# Update default if this was the defaultif self.config.get("default") == name:- remaining = self.list_knowledge_bases()- self.config["default"] = remaining[0] if remaining else None+ remaining = [n for n in self.config.get("knowledge_bases", {}).keys() if n != name]+ self.config["default"] = sorted(remaining)[0] if remaining else Noneself._save_config()return Truediff --git a/deeptutor/services/llm/capabilities.py b/deeptutor/services/llm/capabilities.pyindex 56a7388a1..3c24c4a22 100644--- a/deeptutor/services/llm/capabilities.py+++ b/deeptutor/services/llm/capabilities.py@@ -249,11 +249,43 @@ def get_capability(return default+# Runtime cache for response_format incompatibilities discovered at request time.+# Keyed by (binding_lower, model_lower). Populated when a provider rejects a+# request with response_format={"type": "json_object"} (commonly LM Studio /+# Ollama serving Gemma/Qwen-style models that only accept "json_schema" or "text").+# Once a pair is recorded here, subsequent calls skip response_format entirely+# instead of paying the cost of a failed request + retry.+_RUNTIME_DISABLED_RESPONSE_FORMAT: set[tuple[str, str]] = set()+++def disable_response_format_at_runtime(binding: str | None, model: str | None) -> None:+ """Mark a (binding, model) pair as not supporting ``response_format``.++ Subsequent calls to :func:`supports_response_format` for the same pair+ will return ``False`` without re-checking the static configuration. This+ is useful when a provider unexpectedly rejects ``response_format`` at+ runtime (e.g. LM Studio + ``gemma-4-e2b`` returning+ ``"'response_format.type' must be 'json_schema' or 'text'"``).+ """+ if not binding or not model:+ return+ _RUNTIME_DISABLED_RESPONSE_FORMAT.add((binding.lower(), model.lower()))+++def is_response_format_disabled_at_runtime(binding: str | None, model: str | None) -> bool:+ """Return True if (binding, model) was disabled via :func:`disable_response_format_at_runtime`."""+ if not binding or not model:+ return False+ return (binding.lower(), model.lower()) in _RUNTIME_DISABLED_RESPONSE_FORMAT++def supports_response_format(binding: str, model: str | None = None) -> bool:"""Check if the provider/model supports response_format parameter.This is a convenience function for the most common capability check.+ A runtime override (set via :func:`disable_response_format_at_runtime`)+ always wins over static capability configuration.Args:binding: Provider binding name@@ -262,6 +294,8 @@ def supports_response_format(binding: str, model: str | None = None) -> bool:Returns:True if response_format is supported"""+ if is_response_format_disabled_at_runtime(binding, model):+ return Falsevalue = get_capability(binding, "supports_response_format", model, default=True)return bool(value)@@ -395,4 +429,6 @@ __all__ = ["supports_vision","requires_api_version","get_effective_temperature",+ "disable_response_format_at_runtime",+ "is_response_format_disabled_at_runtime",]diff --git a/deeptutor/services/llm/cloud_provider.py b/deeptutor/services/llm/cloud_provider.pyindex f4bd0e880..1590301dd 100644--- a/deeptutor/services/llm/cloud_provider.py+++ b/deeptutor/services/llm/cloud_provider.py@@ -14,7 +14,11 @@ from typing import castimport aiohttp-from .capabilities import get_effective_temperature, supports_response_format+from .capabilities import (+ disable_response_format_at_runtime,+ get_effective_temperature,+ supports_response_format,+)from .config import get_token_limit_kwargsfrom .exceptions import LLMAPIError, LLMAuthenticationError, LLMConfigErrorfrom .utils import (@@ -80,6 +84,25 @@ def _coerce_int(value: object, default: int | None) -> int | None:_ssl_warning_logged = False+def _looks_like_unsupported_response_format(error_text: str) -> bool:+ """Detect whether a 400 error body indicates ``response_format`` is unsupported.++ Mirrors the heuristic in ``executors._is_unsupported_response_format_error``+ so the aiohttp-based ``_openai_complete`` / ``_openai_stream`` paths can+ auto-recover when ``response_format`` is sent to a model that rejects it.+ """+ text = (error_text or "").lower()+ if "response_format" not in text and "response format" not in text:+ return False+ return (+ "json_object" in text+ or "json_schema" in text+ or "not supported" in text+ or "not valid" in text+ or "must be" in text+ )++def _get_aiohttp_connector() -> aiohttp.TCPConnector | None:"""Build an optional aiohttp connector with SSL verification disabled.@@ -326,11 +349,51 @@ async def _openai_complete(content = extract_response_content(cast(dict[str, object], message))else:error_text = await resp.text()- raise LLMAPIError(- f"OpenAI API error: {error_text}",- status_code=resp.status,- provider=binding or "openai",- )+ # Auto-fallback: if the model rejects response_format, drop it+ # and retry once (then cache so future calls skip it upfront).+ if (+ resp.status == 400+ and "response_format" in data+ and _looks_like_unsupported_response_format(error_text)+ ):+ logger.warning(+ "Provider %s rejected response_format for model %s "+ "(HTTP 400); retrying without it. Body: %s",+ binding,+ model,+ error_text[:200],+ )+ disable_response_format_at_runtime(binding, model)+ retry_data = dict(data)+ retry_data.pop("response_format", None)+ async with session.post(url, headers=headers, json=retry_data) as retry_resp:+ if retry_resp.status == 200:+ result = cast(dict[str, object], await retry_resp.json())+ choices = result.get("choices")+ if isinstance(choices, list) and choices:+ choices_list = cast(list[object], choices)+ first_choice = choices_list[0]+ if isinstance(first_choice, Mapping):+ message = cast(Mapping[str, object], first_choice).get("message")+ else:+ message = None+ if isinstance(message, Mapping):+ content = extract_response_content(+ cast(dict[str, object], message)+ )+ else:+ retry_text = await retry_resp.text()+ raise LLMAPIError(+ f"OpenAI API error: {retry_text}",+ status_code=retry_resp.status,+ provider=binding or "openai",+ )+ else:+ raise LLMAPIError(+ f"OpenAI API error: {error_text}",+ status_code=resp.status,+ provider=binding or "openai",+ )except aiohttp.ClientError as e:# Handle connection errors with more specific messagesif "forcibly closed" in str(e).lower() or "10054" in str(e):@@ -428,15 +491,46 @@ async def _openai_stream(timeout = aiohttp.ClientTimeout(total=300)connector = _get_aiohttp_connector()async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:- async with session.post(url, headers=headers, json=data) as resp:- if resp.status != 200:+ # Try once; if the server rejects response_format with HTTP 400,+ # disable it for this (binding, model) pair and retry once before+ # yielding any chunks. After yielding starts, we cannot retry safely.+ attempt_data = data+ for retry_attempt in range(2):+ resp_cm = session.post(url, headers=headers, json=attempt_data)+ resp = await resp_cm.__aenter__()+ try:+ if resp.status == 200:+ breakerror_text = await resp.text()+ if (+ retry_attempt == 0+ and resp.status == 400+ and "response_format" in attempt_data+ and _looks_like_unsupported_response_format(error_text)+ ):+ logger.warning(+ "Provider %s rejected response_format for model %s "+ "(HTTP 400); retrying stream without it. Body: %s",+ binding,+ model,+ error_text[:200],+ )+ disable_response_format_at_runtime(binding, model)+ attempt_data = dict(attempt_data)+ attempt_data.pop("response_format", None)+ await resp_cm.__aexit__(None, None, None)+ continue+ await resp_cm.__aexit__(None, None, None)raise LLMAPIError(f"OpenAI stream error: {error_text}",status_code=resp.status,provider=binding or "openai",)+ except BaseException:+ await resp_cm.__aexit__(None, None, None)+ raise+ try:# Track thinking block state for streamingin_thinking_block = Falsethinking_buffer = ""@@ -507,6 +601,8 @@ async def _openai_stream(yield contentexcept json.JSONDecodeError:continue+ finally:+ await resp_cm.__aexit__(None, None, None)async def _anthropic_complete(diff --git a/deeptutor/services/llm/executors.py b/deeptutor/services/llm/executors.pyindex f2c8b9675..6f3ac90d6 100644--- a/deeptutor/services/llm/executors.py+++ b/deeptutor/services/llm/executors.py@@ -7,9 +7,10 @@ import uuidfrom collections.abc import AsyncGeneratorfrom typing import Any-from openai import AsyncOpenAI+from openai import AsyncOpenAI, BadRequestErrorfrom deeptutor.logging import get_logger+from deeptutor.services.llm.capabilities import disable_response_format_at_runtimefrom deeptutor.services.llm.provider_registry import find_by_name, strip_provider_prefixfrom .config import get_token_limit_kwargs@@ -18,6 +19,57 @@ from .utils import extract_response_contentlogger = get_logger("LLMExecutors")+def _is_unsupported_response_format_error(exc: BaseException) -> bool:+ """Detect whether a BadRequestError stems from an unsupported ``response_format``.++ Examples seen in the wild:+ - LM Studio + Gemma: ``"'response_format.type' must be 'json_schema' or 'text'"``+ - DashScope + various models: ``"'response_format.type' specified ... not valid: 'json_object' is not supported by this model"``+ """+ text = str(exc).lower()+ if "response_format" not in text and "response format" not in text:+ return False+ return (+ "json_object" in text+ or "json_schema" in text+ or "not supported" in text+ or "not valid" in text+ or "must be" in text+ )+++async def _create_with_format_fallback(+ client: AsyncOpenAI,+ payload: dict[str, Any],+ *,+ binding: str,+ model: str,+) -> Any:+ """Run ``client.chat.completions.create`` with auto-fallback on response_format errors.++ Some local servers (LM Studio + Gemma/Qwen) reject ``response_format``+ with HTTP 400. On a matching :class:`BadRequestError`, drop the offending+ field and retry once, then cache the (binding, model) pair so future calls+ skip ``response_format`` upfront.+ """+ try:+ return await client.chat.completions.create(**payload)+ except BadRequestError as exc:+ if "response_format" not in payload or not _is_unsupported_response_format_error(exc):+ raise+ logger.warning(+ "Provider %s rejected response_format for model %s (%s); "+ "retrying without it and disabling response_format for this binding+model.",+ binding,+ model,+ exc,+ )+ disable_response_format_at_runtime(binding, model)+ retry_payload = dict(payload)+ retry_payload.pop("response_format", None)+ return await client.chat.completions.create(**retry_payload)++def _build_messages(*,prompt: str,@@ -112,7 +164,9 @@ async def sdk_complete(payload["reasoning_effort"] = reasoning_effortpayload.update(kwargs)- response = await client.chat.completions.create(**payload)+ response = await _create_with_format_fallback(+ client, payload, binding=provider_name or "openai", model=resolved_model+ )choices = getattr(response, "choices", None) or []if not choices:return ""@@ -174,7 +228,9 @@ async def sdk_stream(payload["reasoning_effort"] = reasoning_effortpayload.update(kwargs)- stream_response = await client.chat.completions.create(**payload)+ stream_response = await _create_with_format_fallback(+ client, payload, binding=provider_name or "openai", model=resolved_model+ )async for chunk in stream_response:choices = getattr(chunk, "choices", None) or []if not choices:diff --git a/deeptutor/services/rag/pipelines/llamaindex.py b/deeptutor/services/rag/pipelines/llamaindex.pyindex 126bc5704..dd6ed229d 100644--- a/deeptutor/services/rag/pipelines/llamaindex.py+++ b/deeptutor/services/rag/pipelines/llamaindex.py@@ -74,11 +74,24 @@ class CustomEmbedding(BaseEmbedding):async def _aget_query_embedding(self, query: str) -> List[float]:"""Get embedding for a query."""embeddings = await self._client.embed([query])+ if not embeddings or embeddings[0] is None:+ # Surface a clear error so the chat layer can show a meaningful+ # message instead of crashing later in similarity computation+ # with ``TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'``.+ raise ValueError(+ "Embedding provider returned None for query vector. "+ "Check the embedding API configuration and connectivity."+ )return embeddings[0]async def _aget_text_embedding(self, text: str) -> List[float]:"""Get embedding for a text."""embeddings = await self._client.embed([text])+ if not embeddings or embeddings[0] is None:+ raise ValueError(+ "Embedding provider returned None for text vector. "+ "Check the embedding API configuration and connectivity."+ )return embeddings[0]async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:@@ -102,13 +115,27 @@ class CustomEmbedding(BaseEmbedding):# Guard against None embeddings that would crash similarity computationnone_indices = [i for i, vec in enumerate(result) if vec is None]if none_indices:+ # Determine dimension: prefer a sibling vector, fall back to configured dim,+ # raise if neither is available (otherwise we'd persist zero-length vectors+ # that crash retrieval later, which is exactly what this guard tries to avoid).+ dim = next((len(v) for v in result if v is not None), 0)+ if dim == 0:+ try:+ dim = int(get_embedding_config().dim or 0)+ except Exception:+ dim = 0+ if dim <= 0:+ raise ValueError(+ f"Embedding provider returned None for all {len(texts)} chunk(s) "+ "and no fallback dimension is configured. Check the embedding "+ "API configuration and connectivity."+ )self._logger.error(f"Embedding returned None for {len(none_indices)} chunk(s) "f"at indices {none_indices}. These will be replaced with "- f"zero vectors to prevent storage corruption."+ f"{dim}-dim zero vectors to prevent storage corruption. "+ "Affected chunks will not be retrievable; consider re-indexing.")- # Determine dimension from the first valid embedding- dim = next((len(v) for v in result if v is not None), 0)for i in none_indices:result[i] = [0.0] * dimself._logger.info(f"Embedding complete: {len(result)} vectors")diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 7dbd3f7c2..a40149dd4 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -538,6 +538,7 @@ class TurnRuntimeManager:from deeptutor.services.notebook import notebook_managerfrom deeptutor.services.llm.config import get_llm_configfrom deeptutor.services.session.context_builder import ContextBuilder+ from deeptutor.services.skill import get_skill_servicerequest_config = dict(payload.get("config", {}) or {})followup_question_context = _extract_followup_question_context(request_config)@@ -590,6 +591,14 @@ class TurnRuntimeManager:memory_service = get_memory_service()memory_context = memory_service.build_memory_context()+ skill_service = get_skill_service()+ requested_skills = list(payload.get("skills") or [])+ if not requested_skills or requested_skills == ["auto"]:+ resolved_skills = skill_service.auto_select(raw_user_content)+ else:+ resolved_skills = [s for s in requested_skills if isinstance(s, str) and s != "auto"]+ skills_context = skill_service.load_for_context(resolved_skills)+if notebook_references:referenced_records = notebook_manager.get_records_by_references(notebook_references)if referenced_records:@@ -721,6 +730,7 @@ class TurnRuntimeManager:notebook_context=notebook_context,history_context=history_context,memory_context=memory_context,+ skills_context=skills_context,metadata={"conversation_summary": history_result.conversation_summary,"conversation_context_text": conversation_context_text,@@ -733,6 +743,7 @@ class TurnRuntimeManager:"question_notebook_references": question_notebook_references,"question_bank_context": question_bank_context,"memory_context": memory_context,+ "active_skills": resolved_skills,},)diff --git a/deeptutor/services/skill/__init__.py b/deeptutor/services/skill/__init__.pynew file mode 100644index 000000000..b48f6051e--- /dev/null+++ b/deeptutor/services/skill/__init__.py@@ -0,0 +1,5 @@+"""Skill service: load user-authored SKILL.md files and inject them into the chat system prompt."""++from deeptutor.services.skill.service import SkillService, get_skill_service++__all__ = ["SkillService", "get_skill_service"]diff --git a/deeptutor/services/skill/service.py b/deeptutor/services/skill/service.pynew file mode 100644index 000000000..b546c4ec6--- /dev/null+++ b/deeptutor/services/skill/service.py@@ -0,0 +1,323 @@+"""+SkillService+============++Loads user-authored SKILL.md files from ``data/user/workspace/skills/``.++Each skill lives in its own directory:++ data/user/workspace/skills/<name>/SKILL.md++The file starts with a YAML frontmatter block holding ``name`` and+``description`` (optionally ``triggers``), followed by Markdown body that+is injected verbatim into the chat system prompt when the skill is active.+"""++from __future__ import annotations++import re+import shutil+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import yaml++from deeptutor.services.path_service import get_path_service++_FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?", re.DOTALL)+_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")+++@dataclass(slots=True)+class SkillInfo:+ name: str+ description: str++ def to_dict(self) -> dict[str, str]:+ return {"name": self.name, "description": self.description}+++@dataclass(slots=True)+class SkillDetail:+ name: str+ description: str+ content: str++ def to_dict(self) -> dict[str, str]:+ return {+ "name": self.name,+ "description": self.description,+ "content": self.content,+ }+++class SkillNotFoundError(Exception):+ pass+++class SkillExistsError(Exception):+ pass+++class InvalidSkillNameError(Exception):+ pass+++class SkillService:+ """CRUD + selection for SKILL.md files under the user workspace."""++ def __init__(self, root: Path | None = None) -> None:+ self._root = root or (get_path_service().get_workspace_dir() / "skills")++ @property+ def root(self) -> Path:+ return self._root++ # ── path helpers ────────────────────────────────────────────────────++ def _validate_name(self, name: str) -> str:+ candidate = (name or "").strip().lower()+ if not _NAME_RE.match(candidate):+ raise InvalidSkillNameError(+ "Skill name must match ^[a-z0-9][a-z0-9-]{0,63}$"+ )+ return candidate++ def _skill_dir(self, name: str) -> Path:+ return self._root / self._validate_name(name)++ def _skill_file(self, name: str) -> Path:+ return self._skill_dir(name) / "SKILL.md"++ # ── parsing ─────────────────────────────────────────────────────────++ @staticmethod+ def _parse_frontmatter(content: str) -> tuple[dict[str, Any], str]:+ match = _FRONTMATTER_RE.match(content)+ if not match:+ return {}, content+ raw = match.group(1)+ body = content[match.end():]+ try:+ data = yaml.safe_load(raw) or {}+ except yaml.YAMLError:+ data = {}+ if not isinstance(data, dict):+ data = {}+ return data, body++ def _load_info(self, name: str) -> SkillInfo | None:+ file = self._skill_file(name)+ if not file.exists():+ return None+ try:+ text = file.read_text(encoding="utf-8")+ except OSError:+ return None+ meta, _ = self._parse_frontmatter(text)+ description = str(meta.get("description") or "").strip()+ return SkillInfo(name=name, description=description)++ # ── public read API ─────────────────────────────────────────────────++ def list_skills(self) -> list[SkillInfo]:+ if not self._root.exists():+ return []+ out: list[SkillInfo] = []+ for entry in sorted(self._root.iterdir()):+ if not entry.is_dir():+ continue+ try:+ info = self._load_info(entry.name)+ except InvalidSkillNameError:+ continue+ if info is not None:+ out.append(info)+ return out++ def get_detail(self, name: str) -> SkillDetail:+ file = self._skill_file(name)+ if not file.exists():+ raise SkillNotFoundError(name)+ text = file.read_text(encoding="utf-8")+ meta, _ = self._parse_frontmatter(text)+ description = str(meta.get("description") or "").strip()+ return SkillDetail(name=name, description=description, content=text)++ def load_for_context(self, names: list[str]) -> str:+ """Render selected skills into a single system-prompt block.++ Frontmatter is stripped; body is concatenated under a shared header+ so the LLM treats the section as authoritative behavior guidance.+ """+ if not names:+ return ""+ parts: list[str] = []+ for name in names:+ try:+ detail = self.get_detail(name)+ except (SkillNotFoundError, InvalidSkillNameError):+ continue+ _, body = self._parse_frontmatter(detail.content)+ body = body.strip()+ if not body:+ continue+ parts.append(f"### Skill: {detail.name}\n\n{body}")+ if not parts:+ return ""+ return (+ "## Active Skills\n"+ "Follow the playbooks below. They override generic defaults.\n\n"+ + "\n\n---\n\n".join(parts)+ )++ # ── auto-select (keyword based, no LLM) ─────────────────────────────++ def auto_select(self, user_message: str, limit: int = 1) -> list[str]:+ """Pick the most relevant skill(s) for the message via keyword scoring.++ Scoring rules (cheap and predictable):+ - +3 for each frontmatter ``triggers`` term that appears in the message.+ - +1 for each non-stopword token from ``description`` that appears.+ """+ message = (user_message or "").lower()+ if not message.strip():+ return []+ scored: list[tuple[int, str]] = []+ for entry in sorted((self._root.iterdir() if self._root.exists() else [])):+ if not entry.is_dir():+ continue+ try:+ detail = self.get_detail(entry.name)+ except (SkillNotFoundError, InvalidSkillNameError):+ continue+ meta, _ = self._parse_frontmatter(detail.content)+ score = 0+ for trig in meta.get("triggers") or []:+ term = str(trig).strip().lower()+ if term and term in message:+ score += 3+ for token in re.findall(r"[\w\u4e00-\u9fff]{3,}", detail.description.lower()):+ if token in message:+ score += 1+ if score > 0:+ scored.append((score, detail.name))+ scored.sort(reverse=True)+ return [name for _, name in scored[: max(0, limit)]]++ # ── public write API ────────────────────────────────────────────────++ def create(self, name: str, description: str, content: str) -> SkillInfo:+ slug = self._validate_name(name)+ target_dir = self._skill_dir(slug)+ if target_dir.exists():+ raise SkillExistsError(slug)+ body = self._normalize_content(slug, description, content)+ target_dir.mkdir(parents=True, exist_ok=False)+ self._skill_file(slug).write_text(body, encoding="utf-8")+ return SkillInfo(name=slug, description=description.strip())++ def update(+ self,+ name: str,+ *,+ description: str | None = None,+ content: str | None = None,+ rename_to: str | None = None,+ ) -> SkillInfo:+ slug = self._validate_name(name)+ target_dir = self._skill_dir(slug)+ if not target_dir.exists():+ raise SkillNotFoundError(slug)++ if content is not None:+ text = content+ else:+ text = self._skill_file(slug).read_text(encoding="utf-8")++ if description is not None:+ text = self._rewrite_frontmatter(text, description=description.strip())++ meta, _ = self._parse_frontmatter(text)+ final_description = str(meta.get("description") or "").strip()++ if rename_to and rename_to != slug:+ new_slug = self._validate_name(rename_to)+ new_dir = self._skill_dir(new_slug)+ if new_dir.exists():+ raise SkillExistsError(new_slug)+ text = self._rewrite_frontmatter(text, name=new_slug)+ target_dir.rename(new_dir)+ slug = new_slug+ target_dir = new_dir++ self._skill_file(slug).write_text(text, encoding="utf-8")+ return SkillInfo(name=slug, description=final_description)++ def delete(self, name: str) -> None:+ slug = self._validate_name(name)+ target_dir = self._skill_dir(slug)+ if not target_dir.exists():+ raise SkillNotFoundError(slug)+ shutil.rmtree(target_dir)++ # ── content helpers ────────────────────────────────────────────────++ def _normalize_content(self, name: str, description: str, content: str) -> str:+ """Ensure the saved file has a valid frontmatter block with ``name``/``description``.++ If the user-provided ``content`` already has frontmatter we patch the+ ``name`` and ``description`` fields; otherwise we synthesise a header.+ """+ text = content if content is not None else ""+ if _FRONTMATTER_RE.match(text):+ text = self._rewrite_frontmatter(+ text, name=name, description=description.strip()+ )+ return text+ header = yaml.safe_dump(+ {"name": name, "description": description.strip()},+ sort_keys=False,+ allow_unicode=True,+ ).strip()+ body = text.lstrip()+ return f"---\n{header}\n---\n\n{body}".rstrip() + "\n"++ def _rewrite_frontmatter(+ self,+ text: str,+ *,+ name: str | None = None,+ description: str | None = None,+ ) -> str:+ meta, body = self._parse_frontmatter(text)+ if name is not None:+ meta["name"] = name+ if description is not None:+ meta["description"] = description+ if not meta:+ return text+ header = yaml.safe_dump(meta, sort_keys=False, allow_unicode=True).strip()+ return f"---\n{header}\n---\n\n{body.lstrip()}".rstrip() + "\n"+++_singleton: SkillService | None = None+++def get_skill_service() -> SkillService:+ global _singleton+ if _singleton is None:+ _singleton = SkillService()+ return _singleton+++__all__ = [+ "InvalidSkillNameError",+ "SkillDetail",+ "SkillExistsError",+ "SkillInfo",+ "SkillNotFoundError",+ "SkillService",+ "get_skill_service",+]diff --git a/web/app/(utility)/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsxindex a7c2ad8b5..23d9c62f0 100644--- a/web/app/(utility)/knowledge/page.tsx+++ b/web/app/(utility)/knowledge/page.tsx@@ -26,6 +26,7 @@ import {Star,Trash2,Upload,+ Wand2,X,} from "lucide-react";import { apiUrl, wsUrl } from "@/lib/api";@@ -50,6 +51,14 @@ import {type NotebookEntry,type NotebookCategory,} from "@/lib/notebook-api";+import {+ createSkill,+ deleteSkill,+ getSkill,+ listSkills,+ updateSkill,+ type SkillInfo,+} from "@/lib/skills-api";const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {ssr: false,@@ -143,7 +152,7 @@ const kbNeedsReindex = (kb: KnowledgeBase): boolean =>const kbIsUploadable = (kb: KnowledgeBase): boolean =>resolveKbStatus(kb) === "ready" && !kbNeedsReindex(kb);-type TabKey = "knowledge" | "notebooks" | "questions";+type TabKey = "knowledge" | "notebooks" | "questions" | "skills";function KnowledgePageContent() {const router = useRouter();@@ -195,6 +204,128 @@ function KnowledgePageContent() {const [qNewCatName, setQNewCatName] = useState("");const [qRenamingCat, setQRenamingCat] = useState<{ id: number; name: string } | null>(null);+ // ── Skills state ──+ const [skills, setSkills] = useState<SkillInfo[]>([]);+ const [skillsLoading, setSkillsLoading] = useState(false);+ const [skillsError, setSkillsError] = useState<string | null>(null);+ const [skillEditor, setSkillEditor] = useState<{+ mode: "create" | "edit";+ originalName: string | null;+ name: string;+ description: string;+ content: string;+ saving: boolean;+ error: string | null;+ } | null>(null);+ const [skillDeleting, setSkillDeleting] = useState<string | null>(null);++ const loadSkills = useCallback(async () => {+ setSkillsLoading(true);+ setSkillsError(null);+ try {+ const items = await listSkills({ force: true });+ setSkills(items);+ } catch (err) {+ setSkillsError(err instanceof Error ? err.message : String(err));+ } finally {+ setSkillsLoading(false);+ }+ }, []);++ const openCreateSkill = useCallback(() => {+ setSkillEditor({+ mode: "create",+ originalName: null,+ name: "",+ description: "",+ content:+ "# My Skill\n\nDescribe how the assistant should behave when this skill is active.\n",+ saving: false,+ error: null,+ });+ }, []);++ const openEditSkill = useCallback(async (name: string) => {+ setSkillEditor({+ mode: "edit",+ originalName: name,+ name,+ description: "",+ content: "",+ saving: true,+ error: null,+ });+ try {+ const detail = await getSkill(name);+ setSkillEditor({+ mode: "edit",+ originalName: name,+ name: detail.name,+ description: detail.description,+ content: detail.content,+ saving: false,+ error: null,+ });+ } catch (err) {+ setSkillEditor((prev) =>+ prev+ ? { ...prev, saving: false, error: err instanceof Error ? err.message : String(err) }+ : prev,+ );+ }+ }, []);++ const handleSaveSkill = useCallback(async () => {+ if (!skillEditor) return;+ const trimmedName = skillEditor.name.trim();+ if (!trimmedName) {+ setSkillEditor({ ...skillEditor, error: "Name is required" });+ return;+ }+ setSkillEditor({ ...skillEditor, saving: true, error: null });+ try {+ if (skillEditor.mode === "create") {+ await createSkill({+ name: trimmedName,+ description: skillEditor.description,+ content: skillEditor.content,+ });+ } else if (skillEditor.originalName) {+ await updateSkill(skillEditor.originalName, {+ description: skillEditor.description,+ content: skillEditor.content,+ rename_to:+ trimmedName !== skillEditor.originalName ? trimmedName : undefined,+ });+ }+ setSkillEditor(null);+ await loadSkills();+ } catch (err) {+ setSkillEditor((prev) =>+ prev+ ? { ...prev, saving: false, error: err instanceof Error ? err.message : String(err) }+ : prev,+ );+ }+ }, [skillEditor, loadSkills]);++ const handleDeleteSkill = useCallback(async (name: string) => {+ if (!window.confirm(`Delete skill "${name}"?`)) return;+ setSkillDeleting(name);+ try {+ await deleteSkill(name);+ await loadSkills();+ } catch (err) {+ setSkillsError(err instanceof Error ? err.message : String(err));+ } finally {+ setSkillDeleting(null);+ }+ }, [loadSkills]);++ useEffect(() => {+ if (tab === "skills") void loadSkills();+ }, [tab, loadSkills]);+// ── Question Notebook handlers ──const loadQCategories = useCallback(async () => {try { setQCategories(await listCategories()); } catch { /* ignore */ }@@ -649,9 +780,34 @@ function KnowledgePageContent() {const deleteKnowledgeBase = async (kbName: string) => {if (!window.confirm(t('Delete knowledge base "{{name}}"?', { name: kbName }))) return;- await fetch(apiUrl(`/api/v1/knowledge/${kbName}`), { method: "DELETE" });- invalidateKnowledgeCaches();- await loadAll();+ setPageError(null);+ try {+ const res = await fetch(+ apiUrl(`/api/v1/knowledge/${encodeURIComponent(kbName)}`),+ { method: "DELETE" },+ );+ if (!res.ok) {+ let detail = `Delete failed (${res.status})`;+ try {+ const body = await res.json();+ if (body?.detail) detail = String(body.detail);+ } catch {+ // Response body was not JSON; keep generic message.+ }+ throw new Error(detail);+ }+ closeProgressSocket(kbName);+ setProgressMap((prev) => {+ if (!(kbName in prev)) return prev;+ const next = { ...prev };+ delete next[kbName];+ return next;+ });+ invalidateKnowledgeCaches();+ await loadAll();+ } catch (err) {+ setPageError(err instanceof Error ? err.message : String(err));+ }};const handleCreateNotebook = async () => {@@ -787,6 +943,7 @@ function KnowledgePageContent() {{ key: "knowledge", label: t("Knowledge Bases"), icon: Database },{ key: "notebooks", label: t("Notebooks"), icon: NotebookPen },{ key: "questions", label: t("Question Bank"), icon: ClipboardList },+ { key: "skills", label: t("Skills"), icon: Wand2 },].map((item) => (<buttonkey={item.key}@@ -1360,7 +1517,7 @@ function KnowledgePageContent() {</div></section></div>- ) : (+ ) : tab === "questions" ? (/* ── Questions tab content ── */<div className="space-y-0">{/* Category manager */}@@ -1724,6 +1881,187 @@ function KnowledgePageContent() {</ul>)}</div>+ ) : (+ /* ── Skills tab content ── */+ <div className="space-y-5">+ <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">+ <div className="mb-4 flex items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <Wand2 size={15} className="text-[var(--muted-foreground)]" />+ <h2 className="text-[14px] font-semibold text-[var(--foreground)]">+ {t("Skills")}+ </h2>+ <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] text-[var(--muted-foreground)]">+ {skills.length}+ </span>+ </div>+ <button+ onClick={openCreateSkill}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--muted)]/40 px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <Plus size={13} /> {t("New skill")}+ </button>+ </div>+ <p className="mb-4 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Skills are short markdown playbooks that shape the assistant's behavior in chat. Pick one from the composer or use Auto.",+ )}+ </p>++ {skillsError && (+ <div className="mb-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {skillsError}+ </div>+ )}++ {skillsLoading ? (+ <div className="flex items-center justify-center py-12">+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : skills.length === 0 ? (+ <div className="rounded-lg border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">+ {t("No skills yet. Create your first one to customize chat.")}+ </div>+ ) : (+ <ul className="divide-y divide-[var(--border)]/50 rounded-lg border border-[var(--border)]">+ {skills.map((skill) => (+ <li+ key={skill.name}+ className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-[var(--muted)]/30"+ >+ <Wand2 size={14} className="shrink-0 text-[var(--muted-foreground)]" />+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13px] font-medium text-[var(--foreground)]">+ {skill.name}+ </div>+ {skill.description && (+ <div className="mt-0.5 truncate text-[12px] text-[var(--muted-foreground)]">+ {skill.description}+ </div>+ )}+ </div>+ <div className="flex items-center gap-1">+ <button+ onClick={() => void openEditSkill(skill.name)}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ title={t("Edit")}+ >+ <Pencil size={13} />+ </button>+ <button+ onClick={() => void handleDeleteSkill(skill.name)}+ disabled={skillDeleting === skill.name}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-red-50 hover:text-red-600 disabled:opacity-50 dark:hover:bg-red-950/30"+ title={t("Delete")}+ >+ {skillDeleting === skill.name ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <Trash2 size={13} />+ )}+ </button>+ </div>+ </li>+ ))}+ </ul>+ )}+ </section>++ {skillEditor && (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">+ <div className="flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-2xl">+ <div className="flex items-center justify-between border-b border-[var(--border)] px-5 py-3">+ <div className="flex items-center gap-2">+ <Wand2 size={14} className="text-[var(--muted-foreground)]" />+ <h3 className="text-[14px] font-semibold text-[var(--foreground)]">+ {skillEditor.mode === "create" ? t("New skill") : t("Edit skill")}+ </h3>+ </div>+ <button+ onClick={() => setSkillEditor(null)}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ <X size={14} />+ </button>+ </div>++ <div className="flex-1 space-y-3 overflow-y-auto px-5 py-4">+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Name")}+ </label>+ <input+ value={skillEditor.name}+ onChange={(e) =>+ setSkillEditor({ ...skillEditor, name: e.target.value })+ }+ placeholder={t("e.g. teacher")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"+ />+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]/70">+ {t("Lowercase letters, digits, and hyphens only.")}+ </p>+ </div>++ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Description")}+ </label>+ <input+ value={skillEditor.description}+ onChange={(e) =>+ setSkillEditor({ ...skillEditor, description: e.target.value })+ }+ placeholder={t("Short summary used by Auto mode")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"+ />+ </div>++ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Markdown body")}+ </label>+ <textarea+ value={skillEditor.content}+ onChange={(e) =>+ setSkillEditor({ ...skillEditor, content: e.target.value })+ }+ rows={16}+ spellCheck={false}+ className="w-full resize-y rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12px] leading-relaxed outline-none transition-colors focus:border-[var(--foreground)]/25"+ />+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]/70">+ {t("YAML frontmatter is optional and is auto-managed for name and description.")}+ </p>+ </div>++ {skillEditor.error && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {skillEditor.error}+ </div>+ )}+ </div>++ <div className="flex items-center justify-end gap-2 border-t border-[var(--border)] px-5 py-3">+ <button+ onClick={() => setSkillEditor(null)}+ className="rounded-md px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {t("Cancel")}+ </button>+ <button+ onClick={() => void handleSaveSkill()}+ disabled={skillEditor.saving}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--foreground)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-90 disabled:opacity-50"+ >+ {skillEditor.saving && <Loader2 size={12} className="animate-spin" />}+ {t("Save")}+ </button>+ </div>+ </div>+ </div>+ )}+ </div>)}</div></div>diff --git a/web/app/(workspace)/book/components/BookLibrary.tsx b/web/app/(workspace)/book/components/BookLibrary.tsxnew file mode 100644index 000000000..79a850f26--- /dev/null+++ b/web/app/(workspace)/book/components/BookLibrary.tsx@@ -0,0 +1,469 @@+"use client";++import { useMemo, useState } from "react";+import {+ BookOpen,+ Clock3,+ FileText,+ Layers,+ Library,+ Loader2,+ Plus,+ Search,+ Sparkles,+ Trash2,+} from "lucide-react";+import type { CSSProperties } from "react";++import type { Book, BookStatus } from "@/lib/book-types";++const STATUS_STYLES: Record<+ BookStatus,+ { label: string; className: string; dot: string }+> = {+ draft: {+ label: "Draft",+ className:+ "bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-300",+ dot: "bg-amber-500",+ },+ spine_ready: {+ label: "Outline",+ className:+ "bg-sky-50 text-sky-700 dark:bg-sky-500/10 dark:text-sky-300",+ dot: "bg-sky-500",+ },+ compiling: {+ label: "Compiling",+ className:+ "bg-violet-50 text-violet-700 dark:bg-violet-500/10 dark:text-violet-300",+ dot: "bg-violet-500 animate-pulse",+ },+ ready: {+ label: "Ready",+ className:+ "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300",+ dot: "bg-emerald-500",+ },+ error: {+ label: "Error",+ className:+ "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-300",+ dot: "bg-rose-500",+ },+ archived: {+ label: "Archived",+ className:+ "bg-zinc-100 text-zinc-600 dark:bg-zinc-500/10 dark:text-zinc-400",+ dot: "bg-zinc-400",+ },+};++function relativeTime(seconds: number): string {+ if (!seconds || Number.isNaN(seconds)) return "";+ const diff = Date.now() / 1000 - seconds;+ if (diff < 60) return "just now";+ const mins = Math.floor(diff / 60);+ if (mins < 60) return `${mins}m ago`;+ const hrs = Math.floor(mins / 60);+ if (hrs < 24) return `${hrs}h ago`;+ const days = Math.floor(hrs / 24);+ if (days < 30) return `${days}d ago`;+ const months = Math.floor(days / 30);+ if (months < 12) return `${months}mo ago`;+ return `${Math.floor(months / 12)}y ago`;+}++// Stable, deterministic palette per book id so each cover feels distinct+// without resorting to placeholder letters.+const COVER_PALETTES: Array<{+ base: string;+ accent: string;+ spine: string;+ glow: string;+}> = [+ {+ base: "linear-gradient(135deg, #fdf3e7 0%, #f6dcc1 55%, #e9b88a 100%)",+ accent: "#c97a3f",+ spine: "rgba(168, 87, 35, 0.55)",+ glow: "rgba(255, 198, 140, 0.6)",+ },+ {+ base: "linear-gradient(135deg, #eef5ff 0%, #cfe1f7 55%, #9ec0e8 100%)",+ accent: "#3b6fb6",+ spine: "rgba(43, 89, 156, 0.55)",+ glow: "rgba(150, 196, 255, 0.55)",+ },+ {+ base: "linear-gradient(135deg, #f6efff 0%, #e2cff8 55%, #c2a3ec 100%)",+ accent: "#8254cf",+ spine: "rgba(96, 56, 159, 0.55)",+ glow: "rgba(204, 162, 255, 0.55)",+ },+ {+ base: "linear-gradient(135deg, #ecf8f0 0%, #c8eddc 55%, #93d6b6 100%)",+ accent: "#3a9c72",+ spine: "rgba(36, 117, 80, 0.55)",+ glow: "rgba(160, 232, 199, 0.55)",+ },+ {+ base: "linear-gradient(135deg, #fff4e9 0%, #fcd9b7 55%, #f4ad7d 100%)",+ accent: "#d2683a",+ spine: "rgba(178, 75, 35, 0.55)",+ glow: "rgba(255, 195, 145, 0.6)",+ },+ {+ base: "linear-gradient(135deg, #f1efff 0%, #d6d2f6 55%, #a7a1e6 100%)",+ accent: "#5d54c6",+ spine: "rgba(64, 56, 158, 0.55)",+ glow: "rgba(189, 184, 255, 0.55)",+ },+];++function paletteFor(id: string) {+ let hash = 0;+ for (let i = 0; i < id.length; i++) {+ hash = (hash * 31 + id.charCodeAt(i)) >>> 0;+ }+ return COVER_PALETTES[hash % COVER_PALETTES.length];+}++export interface BookLibraryProps {+ books: Book[];+ loading: boolean;+ onNewBook: () => void;+ onSelectBook: (id: string) => void;+ onDeleteBook: (id: string) => void;+}++export default function BookLibrary({+ books,+ loading,+ onNewBook,+ onSelectBook,+ onDeleteBook,+}: BookLibraryProps) {+ const [query, setQuery] = useState("");+ const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);++ const filtered = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (!q) return books;+ return books.filter((b) => {+ const t = (b.title || "").toLowerCase();+ const d = (b.description || "").toLowerCase();+ return t.includes(q) || d.includes(q);+ });+ }, [books, query]);++ const stats = useMemo(() => {+ const total = books.length;+ const ready = books.filter((b) => b.status === "ready").length;+ const inProgress = books.filter(+ (b) =>+ b.status === "compiling" ||+ b.status === "spine_ready" ||+ b.status === "draft",+ ).length;+ const chapters = books.reduce((acc, b) => acc + (b.chapter_count || 0), 0);+ return { total, ready, inProgress, chapters };+ }, [books]);++ return (+ <div className="flex h-full min-h-full flex-col overflow-hidden bg-[var(--background)]">+ {/* Header bar */}+ <header className="flex shrink-0 items-center justify-between border-b border-[var(--border)] px-6 py-3">+ <div className="flex items-center gap-3">+ <Library size={18} className="text-[var(--muted-foreground)]" />+ <div>+ <div className="text-sm font-semibold text-[var(--foreground)]">+ Books+ </div>+ <div className="text-xs text-[var(--muted-foreground)]">+ Generate, browse and study your AI-authored books.+ </div>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <div className="relative hidden items-center sm:flex">+ <Search+ size={13}+ className="pointer-events-none absolute left-2.5 text-[var(--muted-foreground)]/70"+ />+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search books"+ className="h-8 w-56 rounded-md border border-[var(--border)] bg-[var(--secondary)]/30 pl-7 pr-2.5 text-xs text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/60 focus:border-[var(--primary)]/40 focus:outline-none"+ />+ </div>+ <button+ type="button"+ onClick={onNewBook}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-xs font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"+ >+ <Plus size={13} />+ New book+ </button>+ </div>+ </header>++ <main className="flex-1 overflow-y-auto px-6 py-6">+ {/* Stats row */}+ <div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">+ <StatCard+ icon={<BookOpen size={14} />}+ label="Total books"+ value={stats.total}+ />+ <StatCard+ icon={<Sparkles size={14} />}+ label="Ready"+ value={stats.ready}+ accent="text-emerald-600 dark:text-emerald-400"+ />+ <StatCard+ icon={<Loader2 size={14} />}+ label="In progress"+ value={stats.inProgress}+ accent="text-violet-600 dark:text-violet-400"+ />+ <StatCard+ icon={<Layers size={14} />}+ label="Chapters"+ value={stats.chapters}+ />+ </div>++ {/* Section heading */}+ <div className="mb-3 flex items-end justify-between">+ <div>+ <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-[var(--muted-foreground)]">+ My library+ </div>+ <div className="text-xs text-[var(--muted-foreground)]/80">+ {filtered.length} of {books.length} books+ {query ? ` · matching “${query}”` : ""}+ </div>+ </div>+ </div>++ {loading ? (+ <div className="flex items-center justify-center gap-2 py-20 text-sm text-[var(--muted-foreground)]">+ <Loader2 size={16} className="animate-spin" />+ Loading books…+ </div>+ ) : books.length === 0 ? (+ <EmptyState onNewBook={onNewBook} />+ ) : filtered.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--secondary)]/30 px-6 py-12 text-center text-sm text-[var(--muted-foreground)]">+ No books match “{query}”.+ </div>+ ) : (+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">+ {filtered.map((book) => {+ const isPendingDelete = pendingDeleteId === book.id;+ const status =+ STATUS_STYLES[book.status] || STATUS_STYLES.draft;+ const palette = paletteFor(book.id);+ const coverStyle: CSSProperties = { background: palette.base };+ const glowStyle: CSSProperties = {+ background: `radial-gradient(circle at 80% 25%, ${palette.glow} 0%, transparent 60%)`,+ };++ return (+ <div+ key={book.id}+ role="button"+ tabIndex={0}+ onClick={() => onSelectBook(book.id)}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onSelectBook(book.id);+ }+ }}+ className="group relative flex cursor-pointer flex-col overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)]/70 transition-all hover:-translate-y-0.5 hover:border-[var(--primary)]/40 hover:shadow-md"+ >+ {/* Cover */}+ <div+ className="relative h-28 w-full overflow-hidden"+ style={coverStyle}+ >+ {/* Soft glow accent */}+ <div+ className="pointer-events-none absolute inset-0"+ style={glowStyle}+ />+ {/* Stylized "book spine" stripes on the left edge */}+ <div+ className="pointer-events-none absolute inset-y-0 left-0 w-2"+ style={{+ background: `linear-gradient(180deg, ${palette.spine} 0%, transparent 100%)`,+ }}+ />+ <div+ className="pointer-events-none absolute inset-y-3 left-3.5 w-px"+ style={{ background: palette.spine, opacity: 0.45 }}+ />+ {/* Decorative diagonal line pattern */}+ <svg+ className="pointer-events-none absolute inset-0 h-full w-full opacity-[0.07]"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden+ >+ <defs>+ <pattern+ id={`diag-${book.id}`}+ width="14"+ height="14"+ patternUnits="userSpaceOnUse"+ patternTransform="rotate(35)"+ >+ <line+ x1="0"+ y1="0"+ x2="0"+ y2="14"+ stroke="currentColor"+ strokeWidth="1"+ />+ </pattern>+ </defs>+ <rect+ width="100%"+ height="100%"+ fill={`url(#diag-${book.id})`}+ />+ </svg>+ <BookOpen+ size={20}+ className="absolute bottom-3 right-3 opacity-50"+ style={{ color: palette.accent }}+ />++ <span+ className={`absolute left-4 top-3 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider ${status.className}`}+ >+ <span+ className={`h-1.5 w-1.5 rounded-full ${status.dot}`}+ />+ {status.label}+ </span>+ <button+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ if (isPendingDelete) {+ onDeleteBook(book.id);+ setPendingDeleteId(null);+ } else {+ setPendingDeleteId(book.id);+ }+ }}+ title={+ isPendingDelete+ ? "Click again to confirm"+ : "Delete book"+ }+ className={`absolute right-2 top-2 rounded-md p-1.5 transition-colors ${+ isPendingDelete+ ? "bg-rose-500/15 text-rose-600 dark:text-rose-400"+ : "bg-white/60 text-[var(--muted-foreground)] opacity-0 backdrop-blur-sm hover:bg-rose-500/10 hover:text-rose-600 group-hover:opacity-100 dark:bg-black/30 dark:hover:text-rose-400"+ }`}+ >+ <Trash2 size={13} />+ </button>+ </div>++ {/* Body */}+ <div className="flex flex-1 flex-col gap-2 p-4">+ <div+ className="line-clamp-2 text-sm font-semibold text-[var(--foreground)]"+ title={book.title || "Untitled book"}+ >+ {book.title || "Untitled book"}+ </div>+ <p className="line-clamp-3 flex-1 text-xs leading-relaxed text-[var(--muted-foreground)]">+ {book.description ||+ "No description yet. Open the book to view its outline."}+ </p>+ <div className="mt-auto flex items-center justify-between text-[10px] text-[var(--muted-foreground)]/80">+ <div className="flex items-center gap-3">+ <span className="inline-flex items-center gap-1">+ <Layers size={11} />+ {book.chapter_count || 0} ch+ </span>+ <span className="inline-flex items-center gap-1">+ <FileText size={11} />+ {book.page_count || 0} pages+ </span>+ </div>+ <span className="inline-flex items-center gap-1">+ <Clock3 size={11} />+ {relativeTime(book.updated_at) || "—"}+ </span>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </main>+ </div>+ );+}++function StatCard({+ icon,+ label,+ value,+ accent,+}: {+ icon: React.ReactNode;+ label: string;+ value: number;+ accent?: string;+}) {+ return (+ <div className="rounded-xl border border-[var(--border)] bg-[var(--secondary)]/40 px-4 py-3">+ <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]">+ <span className={accent || "text-[var(--muted-foreground)]"}>+ {icon}+ </span>+ {label}+ </div>+ <div+ className={`mt-1 text-xl font-semibold ${accent || "text-[var(--foreground)]"}`}+ >+ {value}+ </div>+ </div>+ );+}++function EmptyState({ onNewBook }: { onNewBook: () => void }) {+ return (+ <div className="flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed border-[var(--border)] bg-[var(--secondary)]/30 px-8 py-16 text-center">+ <BookOpen size={28} className="text-[var(--muted-foreground)]/50" />+ <div>+ <p className="text-base font-medium text-[var(--foreground)]">+ No books yet+ </p>+ <p className="mt-1 text-sm text-[var(--muted-foreground)]">+ Create your first AI-generated book from a knowledge base, chat+ selections or simply a topic.+ </p>+ </div>+ <button+ type="button"+ onClick={onNewBook}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-sm font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"+ >+ <Plus size={14} />+ New book+ </button>+ </div>+ );+}diff --git a/web/app/(workspace)/book/components/BookSidebar.tsx b/web/app/(workspace)/book/components/BookSidebar.tsxindex 3162a45eb..271d807be 100644--- a/web/app/(workspace)/book/components/BookSidebar.tsx+++ b/web/app/(workspace)/book/components/BookSidebar.tsx@@ -1,6 +1,6 @@"use client";-import { Plus, Library, Loader2, Trash2, Compass } from "lucide-react";+import { ArrowLeft, Compass } from "lucide-react";import type { Book, Page } from "@/lib/book-types";const STATUS_LABEL: Record<string, string> = {@@ -13,24 +13,16 @@ const STATUS_LABEL: Record<string, string> = {};export interface BookSidebarProps {- books: Book[];- loadingBooks: boolean;- selectedBookId: string | null;- onSelectBook: (id: string | null) => void;- onNewBook: () => void;- onDeleteBook: (id: string) => void;+ book: Book | null;+ onBackToLibrary: () => void;pages?: Page[];selectedPageId?: string | null;onSelectPage?: (id: string) => void;}export default function BookSidebar({- books,- loadingBooks,- selectedBookId,- onSelectBook,- onNewBook,- onDeleteBook,+ book,+ onBackToLibrary,pages = [],selectedPageId = null,onSelectPage,@@ -38,101 +30,73 @@ export default function BookSidebar({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"+ onClick={onBackToLibrary}+ className="inline-flex items-center gap-1.5 self-start rounded-md px-2 py-1 text-xs font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]">- <Plus className="h-4 w-4" /> New book+ <ArrowLeft className="h-3.5 w-3.5" /> All books</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…+ {book && (+ <div className="px-1">+ <div+ className="line-clamp-2 text-sm font-semibold text-[var(--foreground)]"+ title={book.title || "Untitled book"}+ >+ {book.title || "Untitled book"}</div>- ) : books.length === 0 ? (+ <div className="mt-0.5 text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {book.status} · {book.chapter_count || 0} chapters+ </div>+ </div>+ )}++ <section className="flex-1 overflow-y-auto">+ {pages.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.+ Pages will appear here once the spine is confirmed.</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)]"- }`}- >+ <>+ <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={() => onSelectBook(book.id)}- className="flex flex-1 flex-col gap-0.5 text-left"+ 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="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 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>- <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>+ </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/blocks/AnimationBlock.tsx b/web/app/(workspace)/book/components/blocks/AnimationBlock.tsxindex d4fdd9eb3..2cffa7a7f 100644--- a/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx+++ b/web/app/(workspace)/book/components/blocks/AnimationBlock.tsx@@ -1,6 +1,9 @@"use client";+import { Download, ExternalLink } from "lucide-react";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import { apiUrl } from "@/lib/api";import type { Block } from "@/lib/book-types";export interface AnimationBlockProps {@@ -15,14 +18,20 @@ interface Artifact {label?: string;}+function resolveAssetUrl(url: string): string {+ if (!url) return url;+ if (url.startsWith("http://") || url.startsWith("https://")) return url;+ return apiUrl(url);+}+export default function AnimationBlock({ block }: AnimationBlockProps) {const payload = (block.payload || {}) as Record<string, unknown>;- const videoUrl = String(payload.video_url || "");+ const rawVideoUrl = 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) {+ if (!rawVideoUrl && 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)@@ -30,24 +39,58 @@ export default function AnimationBlock({ block }: AnimationBlockProps) {);}- const primary = videoUrl || artifacts[0]?.url || "";+ const primaryRaw = rawVideoUrl || artifacts[0]?.url || "";+ const primary = resolveAssetUrl(primaryRaw);const isVideo =- primary.endsWith(".mp4") ||- primary.endsWith(".webm") ||+ primaryRaw.endsWith(".mp4") ||+ primaryRaw.endsWith(".webm") ||artifacts.some((a) => (a.content_type || "").startsWith("video/"));+ const filename =+ String(payload.filename || "") ||+ artifacts[0]?.filename ||+ "";return (<figure className="rounded-2xl border border-[var(--border)] bg-[var(--card)] p-3 shadow-sm">- <div className="overflow-hidden rounded-xl bg-black">+ <div className="relative overflow-hidden rounded-xl bg-black">{isVideo ? (<videosrc={primary}controls- className="h-auto w-full"+ playsInlinepreload="metadata"+ className="aspect-video h-auto w-full object-contain"/>) : (- <img src={primary} alt={description || "Animation frame"} className="h-auto w-full" />+ <img+ src={primary}+ alt={description || "Animation frame"}+ className="h-auto w-full"+ />+ )}+ {primary && (+ <div className="absolute right-2 top-2 z-10 flex items-center gap-1">+ <a+ href={primary}+ target="_blank"+ rel="noopener noreferrer"+ title="Open in new tab"+ className="inline-flex items-center gap-1 rounded-md bg-black/40 px-2 py-1 text-[10px] font-medium text-white/90 backdrop-blur-sm transition-colors hover:bg-black/60 hover:text-white"+ >+ <ExternalLink size={11} strokeWidth={1.8} />+ Open+ </a>+ {isVideo && (+ <a+ href={primary}+ download={filename || true}+ title="Download video"+ className="inline-flex items-center gap-1 rounded-md bg-black/40 px-2 py-1 text-[10px] font-medium text-white/90 backdrop-blur-sm transition-colors hover:bg-black/60 hover:text-white"+ >+ <Download size={11} strokeWidth={1.8} />+ </a>+ )}+ </div>)}</div>{(summary || description) && (diff --git a/web/app/(workspace)/book/page.tsx b/web/app/(workspace)/book/page.tsxindex 8bc645553..b72d0930c 100644--- a/web/app/(workspace)/book/page.tsx+++ b/web/app/(workspace)/book/page.tsx@@ -24,6 +24,7 @@ import {import BookChatPanel from "./components/BookChatPanel";import BookCreator from "./components/BookCreator";import BookHealthBanner from "./components/BookHealthBanner";+import BookLibrary from "./components/BookLibrary";import BookProgressTimeline from "./components/BookProgressTimeline";import BookSidebar from "./components/BookSidebar";import PageReader from "./components/PageReader";@@ -376,17 +377,15 @@ function BookPageInner() {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}- />+ {view !== "list" && (+ <BookSidebar+ book={detail?.book || pendingBook || null}+ onBackToLibrary={() => void handleSelectBook(null)}+ 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@@ -399,9 +398,13 @@ function BookPageInner() {)}<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>+ <BookLibrary+ books={books}+ loading={loadingBooks}+ onNewBook={handleNewBook}+ onSelectBook={(id) => void handleSelectBook(id)}+ onDeleteBook={(id) => void handleDeleteBook(id)}+ />)}{view === "creator" && (diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex b744f92e6..90112fb35 100644--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@ -59,6 +59,7 @@ import {type ResearchSource,} from "@/lib/research-types";import { listKnowledgeBases } from "@/lib/knowledge-api";+import { listSkills, type SkillInfo } from "@/lib/skills-api";const NotebookRecordPicker = dynamic(() => import("@/components/notebook/NotebookRecordPicker"), {ssr: false,@@ -238,9 +239,13 @@ export default function ChatPage() {const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);const [toolMenuOpen, setToolMenuOpen] = useState(false);const [refMenuOpen, setRefMenuOpen] = useState(false);+ const [skillMenuOpen, setSkillMenuOpen] = useState(false);const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<SelectedRecord[]>([]);const [selectedHistorySessions, setSelectedHistorySessions] = useState<SelectedHistorySession[]>([]);const [selectedQuestionEntries, setSelectedQuestionEntries] = useState<SelectedQuestionEntry[]>([]);+ const [availableSkills, setAvailableSkills] = useState<SkillInfo[]>([]);+ const [selectedSkills, setSelectedSkills] = useState<string[]>([]);+ const [skillsAutoMode, setSkillsAutoMode] = useState(true);const dragCounter = useRef(0);const capMenuRef = useRef<HTMLDivElement>(null);const capBtnRef = useRef<HTMLButtonElement>(null);@@ -248,6 +253,8 @@ export default function ChatPage() {const toolBtnRef = useRef<HTMLButtonElement>(null);const refMenuRef = useRef<HTMLDivElement>(null);const refBtnRef = useRef<HTMLButtonElement>(null);+ const skillMenuRef = useRef<HTMLDivElement>(null);+ const skillBtnRef = useRef<HTMLButtonElement>(null);const initialLoadRef = useRef(false);const activeCap = useMemo(() => getCapability(state.activeCapability), [state.activeCapability]);@@ -464,11 +471,24 @@ export default function ChatPage() {if (capMenuRef.current && !capMenuRef.current.contains(t) && capBtnRef.current && !capBtnRef.current.contains(t)) setCapMenuOpen(false);if (toolMenuRef.current && !toolMenuRef.current.contains(t) && toolBtnRef.current && !toolBtnRef.current.contains(t)) setToolMenuOpen(false);if (refMenuRef.current && !refMenuRef.current.contains(t) && refBtnRef.current && !refBtnRef.current.contains(t)) setRefMenuOpen(false);+ if (skillMenuRef.current && !skillMenuRef.current.contains(t) && skillBtnRef.current && !skillBtnRef.current.contains(t)) setSkillMenuOpen(false);};document.addEventListener("mousedown", handler);return () => document.removeEventListener("mousedown", handler);}, []);+ useEffect(() => {+ let cancelled = false;+ listSkills().then((items) => {+ if (!cancelled) setAvailableSkills(items);+ }).catch(() => {+ if (!cancelled) setAvailableSkills([]);+ });+ return () => {+ cancelled = true;+ };+ }, []);+useEffect(() => {const allowed = new Set(visibleTools.map((tool) => tool.name));const nextTools = state.enabledTools.filter((tool) => allowed.has(tool as ToolName));@@ -583,6 +603,12 @@ export default function ChatPage() {if (isVisualizeMode) config = buildVisualizeWSConfig(visualizeConfig);if (isResearchMode) config = buildResearchWSConfig(researchConfig);+ const isChatMode = !state.activeCapability;+ const skillsPayload = isChatMode+ ? skillsAutoMode+ ? ["auto"]+ : selectedSkills+ : undefined;sendMessage(content ||(selectedNotebookRecords.length ||@@ -599,6 +625,7 @@ export default function ChatPage() {historyReferencesPayload,undefined,questionNotebookReferencesPayload,+ skillsPayload,);shouldAutoScrollRef.current = true;// Auto-collapse the per-capability settings panel after sending so the@@ -608,7 +635,7 @@ export default function ChatPage() {setSelectedNotebookRecords([]);setSelectedHistorySessions([]);setSelectedQuestionEntries([]);- }, [attachments, historyReferencesPayload, isMathAnimatorMode, isQuizMode, isResearchMode, isVisualizeMode, mathAnimatorConfig, notebookReferencesPayload, questionNotebookReferencesPayload, quizConfig, quizPdf, researchConfig, selectedHistorySessions.length, selectedNotebookRecords.length, selectedQuestionEntries.length, sendMessage, shouldAutoScrollRef, state.isStreaming, visualizeConfig]);+ }, [attachments, historyReferencesPayload, isMathAnimatorMode, isQuizMode, isResearchMode, isVisualizeMode, mathAnimatorConfig, notebookReferencesPayload, questionNotebookReferencesPayload, quizConfig, quizPdf, researchConfig, selectedHistorySessions.length, selectedNotebookRecords.length, selectedQuestionEntries.length, selectedSkills, skillsAutoMode, sendMessage, shouldAutoScrollRef, state.activeCapability, state.isStreaming, visualizeConfig]);const handleConfirmOutline = useCallback((outline: OutlineItem[], _topic: string, originalConfig?: Record<string, unknown> | null) => {@@ -727,11 +754,14 @@ export default function ChatPage() {toolBtnRef={toolBtnRef}refMenuRef={refMenuRef}refBtnRef={refBtnRef}+ skillMenuRef={skillMenuRef}+ skillBtnRef={skillBtnRef}dragCounter={dragCounter}dragging={dragging}capMenuOpen={capMenuOpen}toolMenuOpen={toolMenuOpen}refMenuOpen={refMenuOpen}+ skillMenuOpen={skillMenuOpen}hasMessages={hasMessages}attachments={attachments}activeCap={activeCap}@@ -743,6 +773,9 @@ export default function ChatPage() {selectedHistorySessions={selectedHistorySessions}selectedQuestionEntries={selectedQuestionEntries}notebookReferenceGroups={notebookReferenceGroups}+ availableSkills={availableSkills}+ selectedSkills={selectedSkills}+ skillsAutoMode={skillsAutoMode}stateKnowledgeBase={state.knowledgeBases[0] || ""}isStreaming={state.isStreaming}isResearchMode={isResearchMode}@@ -761,11 +794,22 @@ export default function ChatPage() {onSetCapMenuOpen={setCapMenuOpen}onSetToolMenuOpen={setToolMenuOpen}onSetRefMenuOpen={setRefMenuOpen}+ onSetSkillMenuOpen={setSkillMenuOpen}onSetKB={handleSetKB}onSelectNotebookPicker={handleSelectNotebookPicker}onSelectHistoryPicker={handleSelectHistoryPicker}onSelectQuestionBankPicker={handleSelectQuestionBankPicker}onToggleTool={toggleTool}+ onToggleSkill={(name) => {+ setSkillsAutoMode(false);+ setSelectedSkills((prev) =>+ prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],+ );+ }}+ onSetSkillsAuto={(auto) => {+ setSkillsAutoMode(auto);+ if (auto) setSelectedSkills([]);+ }}onToggleResearchSource={toggleResearchSource}onSend={handleSend}onRemoveAttachment={removeAttachment}diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex 9ec69dbb5..f3951dfe0 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -15,6 +15,7 @@ import {Paperclip,Sparkles,Square,+ Wand2,X,type LucideIcon,} from "lucide-react";@@ -93,11 +94,14 @@ export default memo(function ChatComposer({toolBtnRef,refMenuRef,refBtnRef,+ skillMenuRef,+ skillBtnRef,dragCounter,dragging,capMenuOpen,toolMenuOpen,refMenuOpen,+ skillMenuOpen,hasMessages,attachments,activeCap,@@ -109,6 +113,9 @@ export default memo(function ChatComposer({selectedHistorySessions,selectedQuestionEntries,notebookReferenceGroups,+ availableSkills,+ selectedSkills,+ skillsAutoMode,stateKnowledgeBase,isStreaming,isResearchMode,@@ -127,11 +134,14 @@ export default memo(function ChatComposer({onSetCapMenuOpen,onSetToolMenuOpen,onSetRefMenuOpen,+ onSetSkillMenuOpen,onSetKB,onSelectNotebookPicker,onSelectHistoryPicker,onSelectQuestionBankPicker,onToggleTool,+ onToggleSkill,+ onSetSkillsAuto,onToggleResearchSource,onSend,onRemoveAttachment,@@ -159,11 +169,14 @@ export default memo(function ChatComposer({toolBtnRef: RefObject<HTMLButtonElement | null>;refMenuRef: RefObject<HTMLDivElement | null>;refBtnRef: RefObject<HTMLButtonElement | null>;+ skillMenuRef: RefObject<HTMLDivElement | null>;+ skillBtnRef: RefObject<HTMLButtonElement | null>;dragCounter: RefObject<number>;dragging: boolean;capMenuOpen: boolean;toolMenuOpen: boolean;refMenuOpen: boolean;+ skillMenuOpen: boolean;hasMessages: boolean;attachments: PendingAttachment[];activeCap: CapabilityDef;@@ -175,6 +188,9 @@ export default memo(function ChatComposer({selectedHistorySessions: SelectedHistorySession[];selectedQuestionEntries: SelectedQuestionEntry[];notebookReferenceGroups: Array<{ notebookId: string; notebookName: string; count: number }>;+ availableSkills: Array<{ name: string; description: string }>;+ selectedSkills: string[];+ skillsAutoMode: boolean;stateKnowledgeBase: string;isStreaming: boolean;isResearchMode: boolean;@@ -193,11 +209,14 @@ export default memo(function ChatComposer({onSetCapMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;onSetToolMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;onSetRefMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;+ onSetSkillMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;onSetKB: (kb: string) => void;onSelectNotebookPicker: () => void;onSelectHistoryPicker: () => void;onSelectQuestionBankPicker: () => void;onToggleTool: (tool: ToolDef["name"]) => void;+ onToggleSkill: (skill: string) => void;+ onSetSkillsAuto: (auto: boolean) => void;onToggleResearchSource: (source: ResearchSource) => void;onSend: (content: string) => void;onRemoveAttachment: (index: number) => void;@@ -618,6 +637,80 @@ export default memo(function ChatComposer({</div>)}</div>++ {!activeCap.value && (+ <div className="relative flex items-center gap-0.5">+ <button+ ref={skillBtnRef}+ onClick={() => onSetSkillMenuOpen((v) => !v)}+ className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ <Wand2 size={12} strokeWidth={1.7} />+ {t("Skills")}+ <ChevronDown size={10} className={`transition-transform ${skillMenuOpen ? "rotate-180" : ""}`} />+ </button>+ {(skillsAutoMode || selectedSkills.length > 0) && (+ <div className="flex items-center gap-[3px] overflow-hidden">+ {skillsAutoMode ? (+ <span className="shrink-0 text-[10px] text-[var(--muted-foreground)]/35">{t("Auto")}</span>+ ) : (+ selectedSkills.map((name, i) => (+ <span key={name} className="shrink-0 text-[10px] text-[var(--muted-foreground)]/35">+ {i > 0 && <span className="text-[12px] leading-none">·</span>}+ {name}+ </span>+ ))+ )}+ </div>+ )}+ {skillMenuOpen && (+ <div+ ref={skillMenuRef}+ className="absolute bottom-full left-0 z-50 mb-1.5 max-h-[280px] min-w-[220px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--card)] py-1 shadow-lg"+ >+ <button+ onClick={() => onSetSkillsAuto(!skillsAutoMode)}+ className={`flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] transition-colors ${+ skillsAutoMode+ ? "text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ } hover:bg-[var(--muted)]/40`}+ >+ <Sparkles size={13} strokeWidth={1.7} />+ <span className="flex-1 font-medium">{t("Auto")}</span>+ {skillsAutoMode && <div className="h-1.5 w-1.5 rounded-full bg-[var(--primary)]" />}+ </button>+ {availableSkills.length > 0 && (+ <div className="my-1 h-px bg-[var(--border)]/40" />+ )}+ {availableSkills.map((skill) => {+ const active = selectedSkills.includes(skill.name);+ return (+ <button+ key={skill.name}+ onClick={() => onToggleSkill(skill.name)}+ title={skill.description}+ className={`flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] transition-colors ${+ active+ ? "text-[var(--primary)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ } hover:bg-[var(--muted)]/40`}+ >+ <Wand2 size={13} strokeWidth={1.7} />+ <span className="flex-1 truncate font-medium">{skill.name}</span>+ {active && <div className="h-1.5 w-1.5 rounded-full bg-[var(--primary)]" />}+ </button>+ );+ })}+ {availableSkills.length === 0 && (+ <div className="px-3 py-2 text-[11px] text-[var(--muted-foreground)]/60">+ {t("No skills yet")}+ </div>+ )}+ </div>+ )}+ </div>+ )}</div><div className="ml-auto flex shrink-0 items-center gap-1.5">diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsxindex cfe946dfd..62a2b1162 100644--- a/web/components/visualize/VisualizationViewer.tsx+++ b/web/components/visualize/VisualizationViewer.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { Code2, Copy, Check, ExternalLink } from "lucide-react";+import { Code2, Copy, Check, ExternalLink, Maximize2, X } from "lucide-react";import { useTranslation } from "react-i18next";import { Mermaid } from "@/components/Mermaid";import { prepareIframeHtml } from "@/lib/iframe-html";@@ -151,6 +151,19 @@ function SvgRenderer({ svg }: { svg: string }) {);}+function renderVisualization(result: VisualizeResult) {+ if (result.render_type === "svg") {+ return <SvgRenderer svg={result.code.content} />;+ }+ if (result.render_type === "mermaid") {+ return <Mermaid chart={result.code.content} />;+ }+ if (result.render_type === "html") {+ return <HtmlRenderer html={result.code.content} />;+ }+ return <ChartJsRenderer config={result.code.content} />;+}+export default function VisualizationViewer({result,}: {@@ -159,6 +172,25 @@ export default function VisualizationViewer({const { t } = useTranslation();const [showCode, setShowCode] = useState(false);const [copied, setCopied] = useState(false);+ const [fullscreen, setFullscreen] = useState(false);++ // HTML iframe already provides its own "Open in new tab" affordance; the+ // sandboxed iframe also doesn't behave well inside a re-rendered modal.+ const supportsFullscreen = result.render_type !== "html";++ useEffect(() => {+ if (!fullscreen) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") setFullscreen(false);+ };+ document.addEventListener("keydown", onKey);+ const prevOverflow = document.body.style.overflow;+ document.body.style.overflow = "hidden";+ return () => {+ document.removeEventListener("keydown", onKey);+ document.body.style.overflow = prevOverflow;+ };+ }, [fullscreen]);const handleCopy = async () => {try {@@ -174,21 +206,24 @@ export default function VisualizationViewer({<div className="space-y-3">{/* Visualization area */}<div- className={+ className={`relative ${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} />+ {supportsFullscreen && (+ <button+ type="button"+ onClick={() => setFullscreen(true)}+ title={t("Fullscreen")}+ 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)]"+ >+ <Maximize2 size={10} strokeWidth={1.8} />+ {t("Fullscreen")}+ </button>)}+ {renderVisualization(result)}</div>{/* Toolbar */}@@ -240,6 +275,44 @@ export default function VisualizationViewer({{t("Review")}: {result.review.review_notes}</p>)}++ {/* Fullscreen overlay */}+ {fullscreen && supportsFullscreen && (+ <div+ className="fixed inset-0 z-[120] flex flex-col bg-black/85 p-4 backdrop-blur-sm"+ onClick={() => setFullscreen(false)}+ >+ <div className="mb-2 flex shrink-0 items-center justify-between text-white">+ <div className="text-xs uppercase tracking-wider opacity-80">+ {result.render_type === "svg"+ ? "SVG"+ : result.render_type === "mermaid"+ ? `Mermaid · ${result.analysis.chart_type || "diagram"}`+ : `Chart.js · ${result.analysis.chart_type || "chart"}`}+ </div>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreen(false);+ }}+ title={t("Close")}+ className="inline-flex items-center gap-1 rounded-md bg-white/10 px-2.5 py-1.5 text-[11px] font-medium text-white transition-colors hover:bg-white/20"+ >+ <X size={12} strokeWidth={1.8} />+ {t("Close")}+ </button>+ </div>+ <div+ className="flex flex-1 items-center justify-center overflow-auto rounded-xl bg-white p-6 shadow-2xl"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="w-full max-w-[1600px]">+ {renderVisualization(result)}+ </div>+ </div>+ </div>+ )}</div>);}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex d89d3a7bf..89799c825 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -87,6 +87,7 @@ export interface MessageRequestSnapshot {notebookReferences?: NotebookReferencePayload[];historyReferences?: HistoryReferencePayload;questionNotebookReferences?: QuestionNotebookReferencePayload;+ skills?: string[];}export interface MessageItem {@@ -439,6 +440,7 @@ interface ChatContextValue {historyReferences?: HistoryReferencePayload,options?: SendMessageOptions,questionNotebookReferences?: QuestionNotebookReferencePayload,+ skills?: string[],) => void;cancelStreamingTurn: () => void;regenerateLastMessage: () => void;@@ -729,6 +731,7 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })historyReferences?: HistoryReferencePayload,options?: SendMessageOptions,questionNotebookReferences?: QuestionNotebookReferencePayload,+ skills?: string[],) => {const msgAttachments = attachments?.map((a) => ({type: a.type,@@ -755,6 +758,7 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })const shouldSendKnowledgeBases =effectiveTools.includes("rag") ||(effectiveCapability === "deep_research" && researchSources.includes("kb"));+ const effectiveSkills = replaySnapshot?.skills ?? skills;const requestSnapshot: MessageRequestSnapshot = replaySnapshot ?? {content,capability: effectiveCapability,@@ -768,6 +772,7 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })...(questionNotebookReferences?.length? { questionNotebookReferences: [...questionNotebookReferences] }: {}),+ ...(effectiveSkills?.length ? { skills: [...effectiveSkills] } : {}),};if (options?.displayUserMessage !== false) {dispatch({@@ -802,6 +807,7 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })...(questionNotebookReferences?.length? { question_notebook_references: questionNotebookReferences }: {}),+ ...(effectiveSkills?.length ? { skills: effectiveSkills } : {}),...(effectiveConfig && Object.keys(effectiveConfig).length > 0? { config: effectiveConfig }: {}),diff --git a/web/lib/skills-api.ts b/web/lib/skills-api.tsnew file mode 100644index 000000000..16a6963ba--- /dev/null+++ b/web/lib/skills-api.ts@@ -0,0 +1,110 @@+import { apiUrl } from "@/lib/api";+import { invalidateClientCache, withClientCache } from "@/lib/client-cache";++const SKILLS_CACHE_PREFIX = "skills:";++export interface SkillInfo {+ name: string;+ description: string;+}++export interface SkillDetail extends SkillInfo {+ content: string;+}++export interface CreateSkillPayload {+ name: string;+ description: string;+ content: string;+}++export interface UpdateSkillPayload {+ description?: string;+ content?: string;+ rename_to?: string;+}++async function asJson(response: Response) {+ if (!response.ok) {+ let detail = `${response.status} ${response.statusText}`;+ try {+ const body = await response.json();+ if (body?.detail) detail = String(body.detail);+ } catch {+ /* ignore */+ }+ throw new Error(detail);+ }+ return response.json();+}++export async function listSkills(options?: { force?: boolean }): Promise<SkillInfo[]> {+ return withClientCache<SkillInfo[]>(+ `${SKILLS_CACHE_PREFIX}list`,+ async () => {+ const response = await fetch(apiUrl("/api/v1/skills/list"), { cache: "no-store" });+ const data = await asJson(response);+ const items = Array.isArray(data?.skills) ? data.skills : [];+ return items.map((item: { name?: unknown; description?: unknown }) => ({+ name: String(item?.name ?? ""),+ description: String(item?.description ?? ""),+ }));+ },+ { force: options?.force },+ );+}++export async function getSkill(name: string): Promise<SkillDetail> {+ const response = await fetch(apiUrl(`/api/v1/skills/${encodeURIComponent(name)}`), {+ cache: "no-store",+ });+ const data = await asJson(response);+ return {+ name: String(data?.name ?? name),+ description: String(data?.description ?? ""),+ content: String(data?.content ?? ""),+ };+}++export async function createSkill(payload: CreateSkillPayload): Promise<SkillInfo> {+ const response = await fetch(apiUrl("/api/v1/skills/create"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ const data = await asJson(response);+ invalidateSkillsCache();+ return {+ name: String(data?.name ?? payload.name),+ description: String(data?.description ?? payload.description ?? ""),+ };+}++export async function updateSkill(+ name: string,+ payload: UpdateSkillPayload,+): Promise<SkillInfo> {+ const response = await fetch(apiUrl(`/api/v1/skills/${encodeURIComponent(name)}`), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ const data = await asJson(response);+ invalidateSkillsCache();+ return {+ name: String(data?.name ?? name),+ description: String(data?.description ?? ""),+ };+}++export async function deleteSkill(name: string): Promise<void> {+ const response = await fetch(apiUrl(`/api/v1/skills/${encodeURIComponent(name)}`), {+ method: "DELETE",+ });+ await asJson(response);+ invalidateSkillsCache();+}++export function invalidateSkillsCache() {+ invalidateClientCache(SKILLS_CACHE_PREFIX);+}diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 2ca774760..9bf7fa38b 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -65,6 +65,7 @@ export interface StartTurnMessage {}[];history_references?: string[];question_notebook_references?: number[];+ skills?: string[];}export interface SubscribeTurnMessage {