DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
prepare v1.3.3 release
Bingxi Zhao (Frank)255738d991ea
diff --git a/README.md b/README.mdindex 08833aadc..68a56ef0a 100644--- a/README.md+++ b/README.md@@ -28,6 +28,8 @@### 📦 Releases+> **[2026.4.30]** [v1.3.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.3) — NVIDIA NIM + Gemini embedding support, unified Space context for chat history/skills/memory, session snapshots, RAG re-index resilience.+> **[2026.4.29]** [v1.3.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.2) — Transparent embedding endpoint URLs, RAG re-index resilience for invalid persisted vectors, memory cleanup for thinking-model output, Deep Solve runtime fix.> **[2026.4.28]** [v1.3.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.1) — Stability: safer RAG routing & embedding validation, Docker persistence, IME-safe input, Windows/GBK robustness.@@ -50,11 +52,11 @@> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Universal "Answer now", Co-Writer scroll sync, unified settings panel, streaming Stop button.-> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX block math overhaul, LLM diagnostic probe, Docker + local LLM guidance.-<details><summary><b>Past releases (more than 2 weeks ago)</b></summary>+> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX block math overhaul, LLM diagnostic probe, Docker + local LLM guidance.+> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — Bookmarkable sessions, Snow theme, WebSocket heartbeat & auto-reconnect, embedding registry overhaul.> **[2026.4.13]** [v1.0.3](https://github.com/HKUDS/DeepTutor/releases/tag/v1.0.3) — Question Notebook with bookmarks & categories, Mermaid in Visualize, embedding mismatch detection, Qwen/vLLM compatibility, LM Studio & llama.cpp support, and Glass theme.diff --git a/assets/releases/ver1-3-3.md b/assets/releases/ver1-3-3.mdnew file mode 100644index 000000000..04a899dfc--- /dev/null+++ b/assets/releases/ver1-3-3.md@@ -0,0 +1,153 @@+# DeepTutor v1.3.3 Release Notes++**Release Date:** 2026.04.30++v1.3.3 is a fast follow-up release after v1.3.2. It expands provider coverage+with NVIDIA NIM and Gemini embeddings, makes Space the unified place to attach+chat history, notebooks, question-bank items, skills, and memory to a turn, and+continues the stability work around RAG re-indexing, thinking-model cleanup,+TutorBot history, and persisted session context.++## Highlights++### Provider and Embedding Coverage++DeepTutor now covers more hosted provider setups out of the box and keeps the+runtime configuration path aligned with the Setup Tour and `.env` examples.++- **NVIDIA NIM is a first-class LLM provider** - provider auto-detection now+ recognizes `nvapi-` keys and NVIDIA API bases, defaults to+ `https://integrate.api.nvidia.com/v1`, and avoids sending+ `stream_options.include_usage` because NIM can hang when that option is+ present.+- **Gemini embeddings are available end to end** - embedding runtime metadata,+ endpoint validation, Setup Tour choices, model suggestions, and `.env`+ examples now include Gemini, with `gemini-embedding-001`, 3072 dimensions, and+ `GEMINI_API_KEY` fallback support.+- **Provider-specific embedding keys survive Settings writes** - `.env` writes+ preserve keys such as SiliconFlow, DashScope, Cohere, Jina, and Gemini instead+ of only preserving the older core provider set.+- **Dependency resolution is less fragile** - the NumPy upper bound was relaxed+ to support current Manim installs in `deeptutor[all]`, and Windows setup docs+ now call out the Visual Studio Build Tools / C++ workload prerequisite.++### Space, Chat Context, Skills, and Memory++The chat composer now treats all learning context as Space context, instead of+splitting references, skills, and memory across separate controls.++- **Space opens on Chat History** - the Space entry point now lands on the new+ Chat History page, where previous conversations can be searched, refreshed,+ renamed, deleted, and reopened directly from the Space workspace.+- **One Space menu powers toolbar and `@` mentions** - the old inline+ `AtMentionPopup` was replaced by a shared Space menu for chat history,+ notebooks, question-bank items, skills, and memory, whether opened from the+ toolbar or by typing `@`.+- **Skills selection is clearer** - skills now open in a full picker with+ search, tags, explicit multi-select, and Auto mode, instead of a small inline+ dropdown beside the composer.+- **Memory can be attached per turn** - users can select the running summary,+ profile, or both through the new Memory picker. The request sends+ `memory_references`, and the backend only injects the selected memory files.+- **Context chips show the full turn setup** - selected history, notebooks,+ question-bank items, skills, and memory all appear as removable chips before+ send; sent user messages also show matching request-snapshot badges.+- **Answer Now and session hydration keep context** - replayed turns and loaded+ sessions now hydrate notebooks, history references, question-bank references,+ skills, memory references, and attachments from persisted message metadata.++### Session Persistence and Message Normalization++Conversation state now records more of the user's actual send-time context and+handles non-text message content more defensively.++- **Message metadata is persisted** - the SQLite session store adds a+ `metadata_json` column and stores a `request_snapshot` for user messages,+ including capability, tools, selected KBs, language, config, attachments,+ Space references, skills, and memory selections.+- **WebSocket turns accept memory and skills explicitly** - incoming payloads+ normalize `memory_references` to `summary` / `profile`, normalize skills into+ a string list, and materialize both into message metadata.+- **TutorBot history handles multimodal content** - bot history and recent bot+ previews normalize string, array, object, and image-style content into safe+ display text, while internal `reasoning_content` is stripped from API+ responses.+- **Frontend message previews are safer** - shared message-content utilities+ now accept unknown content, stringify custom objects, render image parts as+ `[image]`, and truncate previews consistently across chat and session lists.++### Memory, Notebook, and Thinking-Model Cleanup++The thinking-output cleanup introduced in v1.3.2 now reaches more durable+storage surfaces and rejects malformed memory rewrites before they can corrupt+profile or summary files.++- **Memory rewrites must match the expected shape** - profile and summary+ refreshes now verify allowed section headings before writing. If a thinking+ model answers the user instead of returning structured memory, the write is+ rejected rather than persisted.+- **Memory context is explicit** - `build_memory_context()` now only includes+ `summary` and/or `profile` when those files are requested, matching the new+ per-turn Memory picker and avoiding accidental default memory injection.+- **Notebook summaries are cleaned and repaired** - notebook writes, streaming+ summary saves, and notebook loads strip thinking tags from summaries; older+ notebook records are repaired on read when possible.+- **Streaming summary chunks are cleaner** - generated notebook summaries are+ assembled, cleaned, and emitted after cleanup, so empty or scratchpad-only+ chunks are not streamed to clients.++### RAG and Knowledge Base Resilience++RAG validation now catches more invalid persisted indexes before retrieval and+returns clearer events when the user needs to re-index.++- **Stale processing KBs recover when an index is ready** - if `kb_config.json`+ is stuck at `processing` or `initializing` but a ready LlamaIndex version is+ already on disk, Knowledge Base info reports `ready` and hides the stale+ progress bar instead of leaving the UI in a perpetual processing state.+- **More vector stores are validated** - LlamaIndex storage now checks the+ default vector store, `storage_context.vector_stores`, and persisted+ `*vector_store.json` embedding dictionaries for null, dropped, non-numeric,+ non-finite, or inconsistent vectors.+- **Invalid-index failures emit user-facing status events** - RAG search now+ sends a structured error status with `needs_reindex` through the tool event+ stream and avoids treating known invalid-index failures as successful+ retrieval attempts.+- **Low-level vector errors are less exposed** - known invalid embedding/index+ failures are logged and surfaced as re-index guidance instead of raw+ `NoneType * float` style tracebacks in user-facing logs.++## Tests++- Added Knowledge Manager coverage for promoting stale `processing` /+ `initializing` status to `ready` when a valid index version already exists.+- Added provider coverage for NVIDIA NIM registry metadata, stream-option+ behavior, Gemini embedding runtime defaults, endpoint validation, Setup Tour+ provider choices, and `.env` key preservation.+- Added session and WebSocket coverage for `metadata_json`, request snapshots,+ skills normalization, memory reference parsing, and turn materialization.+- Added memory and notebook coverage for thinking-tag stripping, invalid memory+ rewrite rejection, selective memory-context injection, and summary repair on+ read.+- Added RAG/LlamaIndex coverage for multi-vector-store validation,+ disk-persisted invalid vectors, `needs_reindex` status events, and sanitized+ raw logs.+- Added TutorBot and frontend message-content coverage for non-string,+ multimodal, object, image, and truncated message content.++## Upgrade Notes++- Existing SQLite session databases are migrated in place with a new+ `messages.metadata_json` column the first time the session store opens them.+- Custom WebSocket clients that relied on implicit memory injection should now+ pass `memory_references: ["summary"]`, `["profile"]`, or both. Empty or absent+ memory references intentionally mean "do not attach long-term memory".+- Knowledge bases that still report invalid persisted vectors should be+ re-indexed after confirming the active embedding provider, model, dimension,+ and endpoint URL.+- Notebook summary streaming clients should expect cleaned summary output after+ assembly rather than relying on every raw model chunk being forwarded.+- NVIDIA NIM users should configure an OpenAI-compatible model under the new+ provider and keep `stream_options.include_usage` disabled for this gateway.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.2...v1.3.3diff --git a/deeptutor/api/routers/notebook.py b/deeptutor/api/routers/notebook.pyindex 1ec00ca0b..345cd7b1a 100644--- a/deeptutor/api/routers/notebook.py+++ b/deeptutor/api/routers/notebook.py@@ -11,6 +11,7 @@ from fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom deeptutor.agents.notebook import NotebookSummarizeAgent+from deeptutor.services.llm import clean_thinking_tagsfrom deeptutor.services.notebook import notebook_managerrouter = APIRouter()@@ -41,9 +42,7 @@ class AddRecordRequest(BaseModel):"""Add record request"""notebook_ids: list[str]- record_type: Literal[- "solve", "question", "research", "chat", "co_writer", "tutorbot"- ]+ record_type: Literal["solve", "question", "research", "chat", "co_writer", "tutorbot"]title: strsummary: str = ""user_query: str@@ -74,15 +73,17 @@ class UpdateRecordRequest(BaseModel):async def _build_record_summary(request: AddRecordRequest) -> str:if request.summary.strip():- return request.summary.strip()+ return clean_thinking_tags(request.summary).strip()agent = NotebookSummarizeAgent(language=str(request.metadata.get("ui_language", "en")))- return await agent.summarize(- title=request.title,- record_type=request.record_type,- user_query=request.user_query,- output=request.output,- metadata=request.metadata,- )+ return clean_thinking_tags(+ await agent.summarize(+ title=request.title,+ record_type=request.record_type,+ user_query=request.user_query,+ output=request.output,+ metadata=request.metadata,+ )+ ).strip()async def _stream_add_record_with_summary(@@ -92,8 +93,10 @@ async def _stream_add_record_with_summary(agent = NotebookSummarizeAgent(language=str(request.metadata.get("ui_language", "en")))summary_parts: list[str] = []if request.summary.strip():- summary_parts.append(request.summary.strip())- yield f"data: {json.dumps({'type': 'summary_chunk', 'content': request.summary.strip()}, ensure_ascii=False)}\n\n"+ summary = clean_thinking_tags(request.summary).strip()+ summary_parts.append(summary)+ if summary:+ yield f"data: {json.dumps({'type': 'summary_chunk', 'content': summary}, ensure_ascii=False)}\n\n"else:async for chunk in agent.stream_summary(title=request.title,@@ -105,9 +108,12 @@ async def _stream_add_record_with_summary(if not chunk:continuesummary_parts.append(chunk)- yield f"data: {json.dumps({'type': 'summary_chunk', 'content': chunk}, ensure_ascii=False)}\n\n"- summary = "".join(summary_parts).strip()+ summary = clean_thinking_tags("".join(summary_parts)).strip()+ if summary:+ yield f"data: {json.dumps({'type': 'summary_chunk', 'content': summary}, ensure_ascii=False)}\n\n"++ summary = clean_thinking_tags("".join(summary_parts)).strip()result = notebook_manager.add_record(notebook_ids=request.notebook_ids,record_type=request.record_type,diff --git a/deeptutor/services/config/env_store.py b/deeptutor/services/config/env_store.pyindex 11dbe05d7..1a61204ff 100644--- a/deeptutor/services/config/env_store.py+++ b/deeptutor/services/config/env_store.py@@ -25,6 +25,11 @@ ENV_KEY_ORDER = ("EMBEDDING_DIMENSION","EMBEDDING_SEND_DIMENSIONS","EMBEDDING_API_VERSION",+ "SILICONFLOW_API_KEY",+ "DASHSCOPE_API_KEY",+ "COHERE_API_KEY",+ "JINA_API_KEY",+ "GEMINI_API_KEY","SEARCH_PROVIDER","SEARCH_API_KEY","SEARCH_BASE_URL",diff --git a/deeptutor/services/memory/service.py b/deeptutor/services/memory/service.pyindex 0997e3fc3..e573a4e62 100644--- a/deeptutor/services/memory/service.py+++ b/deeptutor/services/memory/service.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport asynciofrom dataclasses import dataclassfrom datetime import datetime+import loggingfrom pathlib import Pathimport refrom typing import Literal@@ -27,6 +28,8 @@ MEMORY_FILES: list[MemoryFile] = ["summary", "profile"]_NO_CHANGE = "NO_CHANGE"+logger = logging.getLogger(__name__)+_FILENAMES: dict[MemoryFile, str] = {"summary": "SUMMARY.md","profile": "PROFILE.md",@@ -168,14 +171,22 @@ class MemoryService:# ── Context building (injected into LLM prompts) ─────────────────- def build_memory_context(self, max_chars: int = 4000) -> str:+ def build_memory_context(+ self,+ files: list[MemoryFile] | None = None,+ max_chars: int = 4000,+ ) -> str:+ requested = {item for item in files or [] if item in MEMORY_FILES}+ if not requested:+ return ""+parts: list[str] = []- profile = self.read_profile()+ profile = self.read_profile() if "profile" in requested else ""if profile:parts.append(f"### User Profile\n{profile}")- summary = self.read_summary()+ summary = self.read_summary() if "summary" in requested else ""if summary:parts.append(f"### Learning Context\n{summary}")@@ -311,6 +322,13 @@ class MemoryService:if raw == current:return False+ if not _is_valid_memory_rewrite(which, raw):+ logger.warning(+ "Skipping invalid %s memory rewrite: missing expected section heading",+ which,+ )+ return False+self.write_file(which, raw)return True@@ -392,6 +410,55 @@ def _strip_code_fence(content: str) -> str:return cleaned.strip()+_EXPECTED_MEMORY_HEADINGS: dict[MemoryFile, set[str]] = {+ "profile": {+ "identity",+ "user identity",+ "learning style",+ "knowledge level",+ "preferences",+ "preference",+ "身份",+ "用户身份",+ "学习风格",+ "学习方式",+ "知识水平",+ "偏好",+ "用户偏好",+ },+ "summary": {+ "current focus",+ "accomplishments",+ "open questions",+ "learning journey",+ "context",+ "当前关注",+ "当前学习",+ "学习重点",+ "已完成",+ "学习成果",+ "成就",+ "开放问题",+ "待解决问题",+ "学习旅程",+ "上下文",+ },+}+++def _normalize_heading(value: str) -> str:+ heading = re.sub(r"[*_`]+", "", str(value or "")).strip()+ heading = re.sub(r"[::#\s]+$", "", heading).strip()+ return heading.lower()+++def _is_valid_memory_rewrite(which: MemoryFile, content: str) -> bool:+ """Accept only target-shaped LLM rewrites, not arbitrary model answers."""+ allowed = _EXPECTED_MEMORY_HEADINGS[which]+ headings = re.findall(r"^##(?!#)\s*(.+?)\s*$", content, flags=re.MULTILINE)+ return any(_normalize_heading(heading) in allowed for heading in headings)++def _clean_memory_content(content: str) -> str:"""Remove code fences and model scratchpad tags before durable memory writes."""return clean_thinking_tags(_strip_code_fence(content)).strip()diff --git a/deeptutor/services/notebook/service.py b/deeptutor/services/notebook/service.pyindex 36e0f9009..9e6f268ba 100644--- a/deeptutor/services/notebook/service.py+++ b/deeptutor/services/notebook/service.py@@ -15,6 +15,7 @@ import uuidfrom pydantic import BaseModel+from deeptutor.services.llm import clean_thinking_tagsfrom deeptutor.services.path_service import get_path_service@@ -59,6 +60,11 @@ class Notebook(BaseModel):_UNSET = object()+def _clean_record_summary(summary: str) -> str:+ """Remove private model scratchpads before notebook summaries are persisted."""+ return clean_thinking_tags(str(summary or "")).strip()++class NotebookManager:"""Manage notebook files stored under ``data/user/workspace/notebook``."""@@ -99,9 +105,30 @@ class NotebookManager:return Nonetry:with open(filepath, encoding="utf-8") as f:- return json.load(f)+ notebook = json.load(f)except Exception:return None+ if self._sanitize_loaded_notebook(notebook):+ try:+ self._save_notebook(notebook)+ except Exception:+ pass+ return notebook++ def _sanitize_loaded_notebook(self, notebook: dict) -> bool:+ changed = False+ records = notebook.get("records", [])+ if not isinstance(records, list):+ return False+ for record in records:+ if not isinstance(record, dict):+ continue+ raw_summary = record.get("summary", "")+ cleaned = _clean_record_summary(raw_summary)+ if cleaned != raw_summary:+ record["summary"] = cleaned+ changed = True+ return changeddef _save_notebook(self, notebook: dict) -> None:filepath = self._get_notebook_file(notebook["id"])@@ -246,7 +273,7 @@ class NotebookManager:"id": record_id,"type": resolved_type,"title": title,- "summary": summary,+ "summary": _clean_record_summary(summary),"user_query": user_query,"output": output,"metadata": metadata or {},@@ -306,7 +333,7 @@ class NotebookManager:if title is not None:record["title"] = titleif summary is not None:- record["summary"] = summary+ record["summary"] = _clean_record_summary(summary)if user_query is not None:record["user_query"] = user_queryif output is not None:diff --git a/deeptutor/services/rag/pipelines/llamaindex/errors.py b/deeptutor/services/rag/pipelines/llamaindex/errors.pyindex 73b9d6c97..dd1d8e157 100644--- a/deeptutor/services/rag/pipelines/llamaindex/errors.py+++ b/deeptutor/services/rag/pipelines/llamaindex/errors.py@@ -21,6 +21,10 @@ def search_error_result(query: str, exc: Exception) -> Dict[str, Any]:"provider": "llamaindex","error": message,"error_type": "invalid_embedding_provider_response",+ "log_message": (+ "Embedding provider returned an invalid query vector; check "+ "the embedding provider/model configuration."+ ),}null_vector_similarity_error = (@@ -42,6 +46,7 @@ def search_error_result(query: str, exc: Exception) -> Dict[str, Any]:"provider": "llamaindex","error": message,"error_type": "invalid_embedding_index",+ "log_message": "RAG index contains invalid embedding vectors; re-index required.","needs_reindex": True,}diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.pyindex 25ebf9469..6048b76da 100644--- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py+++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py@@ -168,7 +168,8 @@ class LlamaIndexPipeline:except Exception as exc:result = search_error_result(query, exc)if result.get("error_type"):- self.logger.warning(f"Search failed ({result['error_type']}): {exc}")+ log_message = result.get("log_message") or str(exc)+ self.logger.warning(f"Search failed ({result['error_type']}): {log_message}")else:self.logger.error(f"Search failed: {exc}")self.logger.error(traceback.format_exc())diff --git a/deeptutor/services/rag/pipelines/llamaindex/storage.py b/deeptutor/services/rag/pipelines/llamaindex/storage.pyindex be540f8dd..ad28ed783 100644--- a/deeptutor/services/rag/pipelines/llamaindex/storage.py+++ b/deeptutor/services/rag/pipelines/llamaindex/storage.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom dataclasses import dataclass+import jsonfrom pathlib import Pathimport shutilfrom typing import Any@@ -72,27 +73,82 @@ def create_index(documents: list[Any], storage_dir: Path, *, show_progress: booldef insert_documents(existing_storage: Path, storage_dir: Path, documents: list[Any]) -> int:storage_context = StorageContext.from_defaults(persist_dir=str(existing_storage))index = load_index_from_storage(storage_context)+ _validate_persisted_embeddings(index, existing_storage)for document in documents:index.insert(document)index.storage_context.persist(persist_dir=str(storage_dir))return len(documents)-def _validate_persisted_embeddings(index: Any) -> None:- """Fail early when a persisted vector store contains unusable vectors."""- vector_store = getattr(index, "vector_store", None)- data = getattr(vector_store, "data", None)- embedding_dict = getattr(data, "embedding_dict", None)+def _validate_embedding_dict(embedding_dict: Any, *, label: str) -> None:if not isinstance(embedding_dict, dict) or not embedding_dict:return+ validate_embedding_batch(+ list(embedding_dict.values()),+ expected_count=len(embedding_dict),+ binding="llamaindex",+ model=f"persisted-index:{label}",+ )+++def _iter_index_embedding_dicts(index: Any):+ """Yield embedding dictionaries exposed by loaded LlamaIndex vector stores."""+ seen: set[int] = set()++ def _yield_store(label: str, vector_store: Any):+ if vector_store is None:+ return+ store_id = id(vector_store)+ if store_id in seen:+ return+ seen.add(store_id)+ data = getattr(vector_store, "data", None)+ embedding_dict = getattr(data, "embedding_dict", None)+ if isinstance(embedding_dict, dict):+ yield label, embedding_dict++ yield from _yield_store("default", getattr(index, "vector_store", None))++ storage_context = getattr(index, "storage_context", None)+ vector_stores = getattr(storage_context, "vector_stores", None)+ if isinstance(vector_stores, dict):+ for namespace, vector_store in vector_stores.items():+ yield from _yield_store(str(namespace), vector_store)+++def _embedding_dict_from_payload(payload: Any) -> Any:+ if not isinstance(payload, dict):+ return None+ if isinstance(payload.get("embedding_dict"), dict):+ return payload["embedding_dict"]+ data = payload.get("data")+ if isinstance(data, dict) and isinstance(data.get("embedding_dict"), dict):+ return data["embedding_dict"]+ return None+++def _iter_file_embedding_dicts(storage_dir: Path):+ """Yield embedding dictionaries from persisted vector-store JSON files."""+ for path in sorted(storage_dir.glob("*vector_store.json")):+ try:+ with open(path, encoding="utf-8") as handle:+ payload = json.load(handle)+ except Exception:+ continue+ embedding_dict = _embedding_dict_from_payload(payload)+ if isinstance(embedding_dict, dict):+ yield path.name, embedding_dict+++def _validate_persisted_embeddings(index: Any, storage_dir: Path | None = None) -> None:+ """Fail early when a persisted vector store contains unusable vectors."""try:- validate_embedding_batch(- list(embedding_dict.values()),- expected_count=len(embedding_dict),- binding="llamaindex",- model="persisted-index",- )+ for label, embedding_dict in _iter_index_embedding_dicts(index):+ _validate_embedding_dict(embedding_dict, label=label)+ if storage_dir is not None:+ for label, embedding_dict in _iter_file_embedding_dicts(storage_dir):+ _validate_embedding_dict(embedding_dict, label=label)except ValueError as exc:raise ValueError("RAG index contains invalid embedding vectors. Re-index the "@@ -104,7 +160,7 @@ def _validate_persisted_embeddings(index: Any) -> None:def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any]:storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))index = load_index_from_storage(storage_context)- _validate_persisted_embeddings(index)+ _validate_persisted_embeddings(index, storage_dir)retriever = index.as_retriever(similarity_top_k=top_k)return retriever.retrieve(query)diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.pyindex d0c96aaf4..9245fabc0 100644--- a/deeptutor/services/rag/service.py+++ b/deeptutor/services/rag/service.py@@ -118,6 +118,22 @@ class RAGService:result["content"] = result["answer"]result["provider"] = DEFAULT_PROVIDER+ if result.get("error_type") or result.get("needs_reindex"):+ await self._emit_tool_event(+ event_sink,+ "status",+ result.get("answer") or result.get("content") or "RAG search failed.",+ {+ "provider": DEFAULT_PROVIDER,+ "kb_name": kb_name,+ "trace_layer": "summary",+ "call_state": "error",+ "error_type": result.get("error_type"),+ "needs_reindex": bool(result.get("needs_reindex")),+ },+ )+ return result+answer = result.get("answer") or result.get("content") or ""await self._emit_tool_event(event_sink,diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex b4a6e64cc..46bbe7b7a 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -103,6 +103,7 @@ class SQLiteSessionStore:capability TEXT DEFAULT '',events_json TEXT DEFAULT '',attachments_json TEXT DEFAULT '',+ metadata_json TEXT DEFAULT '{}',created_at REAL NOT NULL);@@ -187,6 +188,11 @@ class SQLiteSessionStore:columns = {row[1] for row in conn.execute("PRAGMA table_info(sessions)").fetchall()}if "preferences_json" not in columns:conn.execute("ALTER TABLE sessions ADD COLUMN preferences_json TEXT DEFAULT '{}'")+ message_columns = {+ row[1] for row in conn.execute("PRAGMA table_info(messages)").fetchall()+ }+ if "metadata_json" not in message_columns:+ conn.execute("ALTER TABLE messages ADD COLUMN metadata_json TEXT DEFAULT '{}'")conn.commit()async def _run(self, fn, *args):@@ -540,6 +546,7 @@ class SQLiteSessionStore:capability: str = "",events: list[dict[str, Any]] | None = None,attachments: list[dict[str, Any]] | None = None,+ metadata: dict[str, Any] | None = None,) -> int:now = time.time()with self._connect() as conn:@@ -552,8 +559,9 @@ class SQLiteSessionStore:cur = conn.execute("""INSERT INTO messages (- session_id, role, content, capability, events_json, attachments_json, created_at- ) VALUES (?, ?, ?, ?, ?, ?, ?)+ session_id, role, content, capability, events_json,+ attachments_json, metadata_json, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",(session_id,@@ -562,6 +570,7 @@ class SQLiteSessionStore:capability or "",_json_dumps(events or []),_json_dumps(attachments or []),+ _json_dumps(metadata or {}),now,),)@@ -592,6 +601,7 @@ class SQLiteSessionStore:capability: str = "",events: list[dict[str, Any]] | None = None,attachments: list[dict[str, Any]] | None = None,+ metadata: dict[str, Any] | None = None,) -> int:return await self._run(self._add_message_sync,@@ -601,6 +611,7 @@ class SQLiteSessionStore:capability,events,attachments,+ metadata,)def _delete_message_sync(self, message_id: int) -> bool:@@ -619,7 +630,8 @@ class SQLiteSessionStore:if role is None:row = conn.execute("""- SELECT id, session_id, role, content, capability, events_json, attachments_json, created_at+ SELECT id, session_id, role, content, capability, events_json,+ attachments_json, metadata_json, created_atFROM messagesWHERE session_id = ?ORDER BY id DESC@@ -630,7 +642,8 @@ class SQLiteSessionStore:else:row = conn.execute("""- SELECT id, session_id, role, content, capability, events_json, attachments_json, created_at+ SELECT id, session_id, role, content, capability, events_json,+ attachments_json, metadata_json, created_atFROM messagesWHERE session_id = ? AND role = ?ORDER BY id DESC@@ -656,6 +669,7 @@ class SQLiteSessionStore:"capability": row["capability"] or "","events": _json_loads(row["events_json"], []),"attachments": _json_loads(row["attachments_json"], []),+ "metadata": _json_loads(row["metadata_json"], {}),"created_at": row["created_at"],}@@ -663,7 +677,8 @@ class SQLiteSessionStore:with self._connect() as conn:rows = conn.execute("""- SELECT id, session_id, role, content, capability, events_json, attachments_json, created_at+ SELECT id, session_id, role, content, capability, events_json,+ attachments_json, metadata_json, created_atFROM messagesWHERE session_id = ?ORDER BY id ASCdiff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 1e3980d89..5701222db 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -36,6 +36,63 @@ def _clip_text(value: str, limit: int = 4000) -> str:return text[:limit].rstrip() + "\n...[truncated]"+def _extract_memory_references(payload: dict[str, Any]) -> list[str]:+ """Return the explicit public memory files requested for this turn."""+ refs = payload.get("memory_references", []) or []+ if not isinstance(refs, list):+ return []++ out: list[str] = []+ for item in refs:+ if item in {"summary", "profile"} and item not in out:+ out.append(item)+ return out+++def _string_list(value: Any) -> list[str]:+ if not isinstance(value, list):+ return []+ return [item for item in value if isinstance(item, str) and item]+++def _request_snapshot_metadata(+ *,+ payload: dict[str, Any],+ content: str,+ capability: str,+ config: dict[str, Any],+ attachments: list[dict[str, Any]],+ notebook_references: list[Any],+ history_references: list[Any],+ question_notebook_references: list[Any],+ requested_skills: list[str],+ memory_references: list[str],+) -> dict[str, Any]:+ """Persist the front-end context chips with the user message."""+ snapshot: dict[str, Any] = {+ "content": content,+ "capability": capability,+ "enabledTools": _string_list(payload.get("tools")),+ "knowledgeBases": _string_list(payload.get("knowledge_bases")),+ "language": str(payload.get("language", "en") or "en"),+ }+ if attachments:+ snapshot["attachments"] = attachments+ if config:+ snapshot["config"] = dict(config)+ if notebook_references:+ snapshot["notebookReferences"] = notebook_references+ if history_references:+ snapshot["historyReferences"] = history_references+ if question_notebook_references:+ snapshot["questionNotebookReferences"] = question_notebook_references+ if requested_skills:+ snapshot["skills"] = requested_skills+ if memory_references:+ snapshot["memoryReferences"] = memory_references+ return {"request_snapshot": snapshot}++def _format_question_bank_entry(entry: dict[str, Any]) -> str:"""Render a single Question Bank entry as a structured Markdown block."""lines: list[str] = []@@ -542,6 +599,7 @@ class TurnRuntimeManager:notebook_references = payload.get("notebook_references", []) or []history_references = payload.get("history_references", []) or []question_notebook_references = payload.get("question_notebook_references", []) or []+ memory_references = _extract_memory_references(payload)notebook_context = ""history_context = ""question_bank_context = ""@@ -653,10 +711,10 @@ class TurnRuntimeManager:on_event=_emit_context_event,)memory_service = get_memory_service()- memory_context = memory_service.build_memory_context()+ memory_context = memory_service.build_memory_context(memory_references)skill_service = get_skill_service()- requested_skills = list(payload.get("skills") or [])+ requested_skills = _string_list(payload.get("skills"))if not requested_skills or requested_skills == ["auto"]:resolved_skills = skill_service.auto_select(raw_user_content)else:@@ -783,6 +841,18 @@ class TurnRuntimeManager:content=raw_user_content,capability=capability_name,attachments=persisted_attachment_records,+ metadata=_request_snapshot_metadata(+ payload=payload,+ content=raw_user_content,+ capability=capability_name,+ config=request_config,+ attachments=persisted_attachment_records,+ notebook_references=notebook_references,+ history_references=history_references,+ question_notebook_references=question_notebook_references,+ requested_skills=requested_skills,+ memory_references=memory_references,+ ),)context = UnifiedContext(@@ -809,6 +879,7 @@ class TurnRuntimeManager:"notebook_references": notebook_references,"history_references": history_references,"question_notebook_references": question_notebook_references,+ "memory_references": memory_references,"question_bank_context": question_bank_context,"memory_context": memory_context,"active_skills": resolved_skills,diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.pyindex a4c9531fe..733de0c60 100644--- a/deeptutor/services/tutorbot/manager.py+++ b/deeptutor/services/tutorbot/manager.py@@ -13,6 +13,7 @@ import asynciofrom collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom datetime import datetime+import jsonimport loggingfrom pathlib import Pathimport shutil@@ -79,6 +80,32 @@ def mask_channel_secrets(channels: dict[str, Any]) -> dict[str, Any]:return walked+def normalize_message_content(content: Any) -> str:+ """Return a display-safe string for text or multimodal message content."""+ if content is None:+ return ""+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return " ".join(+ part+ for part in (normalize_message_content(item) for item in content)+ if part+ )+ if isinstance(content, dict):+ for key in ("text", "content", "message", "alt"):+ value = content.get(key)+ if isinstance(value, str) and value:+ return value+ if content.get("type") in {"image", "image_url"}:+ return "[image]"+ try:+ return json.dumps(content, ensure_ascii=False)+ except TypeError:+ return str(content)+ return str(content)++@dataclassclass BotConfig:"""Configuration for a single TutorBot instance."""@@ -708,8 +735,6 @@ class TutorBotManager:def get_bot_history(self, bot_id: str, limit: int = 100) -> list[dict[str, Any]]:"""Read chat messages from a bot's JSONL session files."""- import json as _json-sessions_dir = self._bot_workspace(bot_id) / "sessions"if not sessions_dir.exists():return []@@ -724,18 +749,11 @@ class TutorBotManager:line = line.strip()if not line:continue- data = _json.loads(line)+ data = json.loads(line)if data.get("_type") == "metadata":continueif data.get("role") in ("user", "assistant") and data.get("content"):- raw = data["content"]- if isinstance(raw, list):- data["content"] = " ".join(- p.get("text", "") if isinstance(p, dict) else str(p)- for p in raw- )- elif not isinstance(raw, str):- data["content"] = str(raw)+ data["content"] = normalize_message_content(data["content"])data.pop("reasoning_content", None)all_messages.append(data)except Exception:@@ -747,8 +765,6 @@ class TutorBotManager:def get_recent_active_bots(self, limit: int = 3) -> list[dict[str, Any]]:"""Return the most recently active bots with their last message preview."""- import json as _json-bot_activity: list[tuple[float, str, dict[str, Any]]] = []for bid in self._discover_bot_ids():@@ -770,20 +786,11 @@ class TutorBotManager:line = line.strip()if not line:continue- data = _json.loads(line)+ data = json.loads(line)if data.get("_type") == "metadata":continueif data.get("role") in ("user", "assistant") and data.get("content"):- raw = data["content"]- if isinstance(raw, list):- last_msg = " ".join(- p.get("text", "") if isinstance(p, dict) else str(p)- for p in raw- )- elif isinstance(raw, str):- last_msg = raw- else:- last_msg = str(raw)+ last_msg = normalize_message_content(data["content"])except Exception:passdiff --git a/tests/api/test_main_notebook_router.py b/tests/api/test_main_notebook_router.pyindex 526618033..70af1815f 100644--- a/tests/api/test_main_notebook_router.py+++ b/tests/api/test_main_notebook_router.py@@ -6,7 +6,9 @@ Verifies that records can only be saved using real notebook UUIDsfrom __future__ import annotations+import asyncioimport importlib+import jsonimport pytest@@ -112,3 +114,48 @@ def test_add_record_with_numeric_category_id_saves_nothing(manager: NotebookManaassert resp.status_code == 200body = resp.json()assert body["added_to_notebooks"] == []+++def test_stream_add_record_with_summary_strips_thinking_tags(+ manager: NotebookManager,+ monkeypatch,+) -> None:+ class FakeSummarizeAgent:+ def __init__(self, language: str = "en") -> None:+ self.language = language++ async def stream_summary(self, **_kwargs):+ yield "<thi"+ yield "nk>private reasoning</think>\n"+ yield "Final reusable summary."++ monkeypatch.setattr(+ "deeptutor.api.routers.notebook.NotebookSummarizeAgent",+ FakeSummarizeAgent,+ )+ nb = manager.create_notebook(name="My Notes")++ async def collect_events() -> list[dict]:+ request = importlib.import_module("deeptutor.api.routers.notebook").AddRecordRequest(+ notebook_ids=[nb["id"]],+ record_type="chat",+ title="Streaming save",+ user_query="Explain Fourier",+ output="Fourier transform is...",+ )+ events: list[dict] = []+ async for raw in importlib.import_module(+ "deeptutor.api.routers.notebook"+ )._stream_add_record_with_summary(request):+ assert "<think" not in raw.lower()+ assert "private reasoning" not in raw+ events.append(json.loads(raw.removeprefix("data: ").strip()))+ return events++ events = asyncio.run(collect_events())+ assert events[-1]["type"] == "result"+ assert events[-1]["summary"] == "Final reusable summary."++ detail = manager.get_notebook(nb["id"])+ assert detail is not None+ assert detail["records"][0]["summary"] == "Final reusable summary."diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.pyindex 195f4c358..a1e9c9c56 100644--- a/tests/api/test_unified_ws_turn_runtime.py+++ b/tests/api/test_unified_ws_turn_runtime.py@@ -13,6 +13,13 @@ async def _noop_refresh(**_kwargs):return None+def _fake_skill_service() -> SimpleNamespace:+ return SimpleNamespace(+ auto_select=lambda _content: [],+ load_for_context=lambda _skills: "",+ )++@pytest.mark.asyncioasync def test_turn_runtime_replays_events_and_materializes_messages(monkeypatch: pytest.MonkeyPatch,@@ -63,10 +70,14 @@ async def test_turn_runtime_replays_events_and_materializes_messages(monkeypatch.setattr("deeptutor.services.memory.get_memory_service",lambda: SimpleNamespace(- build_memory_context=lambda: "",+ build_memory_context=lambda *_args, **_kwargs: "",refresh_from_turn=_noop_refresh,),)+ monkeypatch.setattr(+ "deeptutor.services.skill.get_skill_service",+ _fake_skill_service,+ )session, turn = await runtime.start_turn({@@ -78,6 +89,8 @@ async def test_turn_runtime_replays_events_and_materializes_messages("knowledge_bases": [],"attachments": [],"language": "en",+ "skills": ["proof-checker"],+ "memory_references": ["summary"],"config": {},})@@ -92,6 +105,12 @@ async def test_turn_runtime_replays_events_and_materializes_messages(detail = await store.get_session_with_messages(session["id"])assert detail is not Noneassert [message["role"] for message in detail["messages"]] == ["user", "assistant"]+ assert detail["messages"][0]["metadata"]["request_snapshot"]["skills"] == [+ "proof-checker"+ ]+ assert detail["messages"][0]["metadata"]["request_snapshot"]["memoryReferences"] == [+ "summary"+ ]assert detail["messages"][1]["content"] == "Hello Frank"assert detail["preferences"] == {"capability": "chat",@@ -153,10 +172,11 @@ async def test_turn_runtime_bootstraps_question_followup_context_once(monkeypatch.setattr("deeptutor.services.memory.get_memory_service",lambda: SimpleNamespace(- build_memory_context=lambda: "",+ build_memory_context=lambda *_args, **_kwargs: "",refresh_from_turn=_noop_refresh,),)+ monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)session, turn = await runtime.start_turn({@@ -270,10 +290,11 @@ async def test_turn_runtime_persists_deep_research_session_preference(monkeypatch.setattr("deeptutor.services.memory.get_memory_service",lambda: SimpleNamespace(- build_memory_context=lambda: "",+ build_memory_context=lambda *_args, **_kwargs: "",refresh_from_turn=_noop_refresh,),)+ monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)session, turn = await runtime.start_turn({@@ -356,10 +377,11 @@ async def test_turn_runtime_injects_memory_and_refreshes_after_completion(monkeypatch.setattr("deeptutor.services.memory.get_memory_service",lambda: SimpleNamespace(- build_memory_context=lambda: "## Memory\n## Preferences\n- Prefer concise answers.",+ build_memory_context=lambda *_args, **_kwargs: "## Memory\n## Preferences\n- Prefer concise answers.",refresh_from_turn=fake_refresh_from_turn,),)+ monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)_session, turn = await runtime.start_turn({diff --git a/tests/core/test_turn_event_store.py b/tests/core/test_turn_event_store.pyindex 430f451b9..3a401886a 100644--- a/tests/core/test_turn_event_store.py+++ b/tests/core/test_turn_event_store.py@@ -56,3 +56,30 @@ async def test_sqlite_store_persists_turns_and_events(tmp_path) -> None:sessions = await store.list_sessions()assert sessions[0]["session_id"] == session["id"]assert sessions[0]["status"] == "completed"+++async def test_sqlite_store_persists_message_metadata(tmp_path) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ session = await store.create_session(title="Demo", session_id="session-demo")++ await store.add_message(+ session_id=session["id"],+ role="user",+ content="hello",+ metadata={+ "request_snapshot": {+ "content": "hello",+ "skills": ["proof-checker"],+ "memoryReferences": ["summary"],+ }+ },+ )++ detail = await store.get_session_with_messages(session["id"])+ assert detail is not None+ assert detail["messages"][0]["metadata"]["request_snapshot"] == {+ "content": "hello",+ "skills": ["proof-checker"],+ "memoryReferences": ["summary"],+ }diff --git a/tests/services/config/test_env_store_send_dimensions.py b/tests/services/config/test_env_store_send_dimensions.pyindex 1a4d41bef..81c0bd01c 100644--- a/tests/services/config/test_env_store_send_dimensions.py+++ b/tests/services/config/test_env_store_send_dimensions.py@@ -161,6 +161,17 @@ def test_write_persists_send_dimensions_when_set(tmp_path: Path) -> None:assert "EMBEDDING_SEND_DIMENSIONS=false" in text+def test_write_preserves_provider_specific_embedding_key(tmp_path: Path) -> None:+ env_path = tmp_path / ".env"+ env_path.write_text("GEMINI_API_KEY=gemini-existing\n", encoding="utf-8")+ env = EnvStore(path=env_path)++ env.write(env.render_from_catalog(_embedding_catalog(send_dimensions=None)))++ text = env_path.read_text(encoding="utf-8")+ assert "GEMINI_API_KEY=gemini-existing" in text++# ---------------------------------------------------------------------------# as_summary() — round-trip from .env back into the embedding dict# ---------------------------------------------------------------------------diff --git a/tests/services/memory/test_memory_service.py b/tests/services/memory/test_memory_service.pyindex b3ef4d371..bcaac9048 100644--- a/tests/services/memory/test_memory_service.py+++ b/tests/services/memory/test_memory_service.py@@ -26,6 +26,43 @@ def test_memory_service_snapshot_is_empty_without_file(tmp_path) -> None:assert snapshot.profile_updated_at is None+def test_memory_context_requires_explicit_files(tmp_path) -> None:+ service = _make_service(tmp_path)+ service.write_file("summary", "## Current Focus\n- Linear algebra")+ service.write_file("profile", "## Preferences\n- Concise answers")++ assert service.build_memory_context() == ""+ assert service.build_memory_context([]) == ""+++def test_memory_context_can_include_summary_only(tmp_path) -> None:+ service = _make_service(tmp_path)+ service.write_file("summary", "## Current Focus\n- Linear algebra")+ service.write_file("profile", "## Preferences\n- Concise answers")++ context = service.build_memory_context(["summary"])++ assert "## Background Memory" in context+ assert "### Learning Context" in context+ assert "Linear algebra" in context+ assert "### User Profile" not in context+ assert "Concise answers" not in context+++def test_memory_context_can_include_profile_only(tmp_path) -> None:+ service = _make_service(tmp_path)+ service.write_file("summary", "## Current Focus\n- Linear algebra")+ service.write_file("profile", "## Preferences\n- Concise answers")++ context = service.build_memory_context(["profile"])++ assert "## Background Memory" in context+ assert "### User Profile" in context+ assert "Concise answers" in context+ assert "### Learning Context" not in context+ assert "Linear algebra" not in context++async def _no_change_stream(**_kwargs):yield "NO_CHANGE"@@ -42,6 +79,10 @@ async def _unclosed_thinking_stream(**_kwargs):yield "## Current Focus\n- Algebra\n<think>unfinished private reasoning"+async def _invalid_profile_stream(**_kwargs):+ yield "The derivative of x^2 is 2x. This is an answer, not a profile."++def test_memory_service_refresh_turn_writes_rewritten_document(monkeypatch, tmp_path) -> None:service = _make_service(tmp_path)monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _rewrite_stream)@@ -130,10 +171,30 @@ def test_memory_service_refresh_strips_unclosed_thinking_tags(monkeypatch, tmp_p))- assert service.read_profile() == "## Current Focus\n- Algebra"+ assert service.read_profile() == ""+ assert service.read_summary() == "## Current Focus\n- Algebra"assert "<think" not in service.read_summary().lower()+def test_memory_service_rejects_invalid_profile_rewrite(monkeypatch, tmp_path) -> None:+ service = _make_service(tmp_path)+ monkeypatch.setattr("deeptutor.services.memory.service.llm_stream", _invalid_profile_stream)++ import asyncio++ changed = asyncio.run(+ service._rewrite_one(+ "profile",+ "[User]\nWhat is d/dx x^2?\n\n[Assistant]\n2x",+ "en",+ )+ )++ assert changed is False+ assert service.read_profile() == ""+ assert not service._path("profile").exists()++def test_memory_service_repairs_existing_thinking_tags_on_read(tmp_path) -> None:service = _make_service(tmp_path)service._path("summary").parent.mkdir(parents=True, exist_ok=True)diff --git a/tests/services/rag/test_llamaindex_embedding_failures.py b/tests/services/rag/test_llamaindex_embedding_failures.pyindex c726c81ef..6a14609f6 100644--- a/tests/services/rag/test_llamaindex_embedding_failures.py+++ b/tests/services/rag/test_llamaindex_embedding_failures.py@@ -1,5 +1,6 @@from __future__ import annotations+import asynciofrom types import SimpleNamespaceimport pytest@@ -128,6 +129,38 @@ def test_retrieve_nodes_rejects_invalid_persisted_embeddings(storage_module.retrieve_nodes(tmp_path, "what is this?")+def test_retrieve_nodes_checks_storage_context_vector_stores(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module++ class _RetrieverShouldNotRun:+ def retrieve(self, query: str): # pragma: no cover - assertion helper+ raise AssertionError("retriever should not run for invalid persisted vectors")++ fake_index = SimpleNamespace(+ vector_store=SimpleNamespace(data=SimpleNamespace(embedding_dict={})),+ storage_context=SimpleNamespace(+ vector_stores={+ "default": SimpleNamespace(+ data=SimpleNamespace(embedding_dict={"bad-node": [0.1, None, 0.3]})+ )+ }+ ),+ as_retriever=lambda similarity_top_k=5: _RetrieverShouldNotRun(),+ )++ monkeypatch.setattr(+ storage_module.StorageContext,+ "from_defaults",+ lambda persist_dir: object(),+ )+ monkeypatch.setattr(storage_module, "load_index_from_storage", lambda _ctx: fake_index)++ with pytest.raises(ValueError, match="RAG index contains invalid embedding vectors"):+ storage_module.retrieve_nodes(tmp_path, "what is this?")++@pytest.mark.asyncioasync def test_search_reconfigures_llamaindex_settings_for_cached_pipeline(tmp_path, monkeypatch: pytest.MonkeyPatch@@ -155,3 +188,58 @@ async def test_search_reconfigures_llamaindex_settings_for_cached_pipeline(assert result["provider"] == "llamaindex"assert configure_calls == ["configure", "configure"]+++async def test_rag_service_hides_low_level_invalid_index_error_in_raw_logs(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module+ from deeptutor.services.rag.pipelines.llamaindex.pipeline import LlamaIndexPipeline+ from deeptutor.services.rag.service import RAGService++ storage_dir = tmp_path / "kb" / "version-1"+ storage_dir.mkdir(parents=True)+ (storage_dir / "docstore.json").write_text("{}", encoding="utf-8")++ monkeypatch.setattr(+ LlamaIndexPipeline,+ "_configure_settings",+ lambda self: None,+ )+ monkeypatch.setattr(+ storage_module,+ "retrieve_nodes",+ lambda storage_dir, query, top_k=5: (_ for _ in ()).throw(+ TypeError("unsupported operand type(s) for *: 'NoneType' and 'float'")+ ),+ )++ pipeline = LlamaIndexPipeline(+ kb_base_dir=str(tmp_path),+ signature_provider=lambda: None,+ )+ service = RAGService(kb_base_dir=str(tmp_path))+ service._pipeline = pipeline+ events: list[tuple[str, str, dict]] = []++ async def event_sink(event_type: str, message: str, metadata: dict) -> None:+ events.append((event_type, message, metadata))++ result = await service.search("what is this?", "kb", event_sink=event_sink)+ await asyncio.sleep(0)++ raw_logs = [message for event_type, message, _ in events if event_type == "raw_log"]+ assert result["error_type"] == "invalid_embedding_index"+ assert any("Search failed (invalid_embedding_index)" in message for message in raw_logs)+ assert not any("unsupported operand" in message for message in raw_logs)+ assert any(+ metadata.get("call_state") == "error" and metadata.get("needs_reindex") is True+ for event_type, _, metadata in events+ if event_type == "status"+ )+ assert not any(+ message.startswith("Retrieved ")+ for event_type, message, _ in events+ if event_type == "status"+ )diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.pyindex 669f7621d..9f8ad5122 100644--- a/tests/services/session/test_turn_runtime.py+++ b/tests/services/session/test_turn_runtime.py@@ -7,6 +7,7 @@ import pytestfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.services.session.turn_runtime import (_clip_text,+ _extract_memory_references,_extract_followup_question_context,_extract_persist_user_message,_format_followup_question_context,@@ -70,6 +71,26 @@ class TestClipText:assert _clip_text(None) == "" # type: ignore[arg-type]+# ---------------------------------------------------------------------------+# _extract_memory_references+# ---------------------------------------------------------------------------+++class TestExtractMemoryReferences:+ def test_extracts_valid_memory_files_in_order(self) -> None:+ payload = {"memory_references": ["profile", "summary"]}++ assert _extract_memory_references(payload) == ["profile", "summary"]++ def test_filters_unknown_and_duplicate_memory_files(self) -> None:+ payload = {"memory_references": ["summary", "unknown", "summary", "profile"]}++ assert _extract_memory_references(payload) == ["summary", "profile"]++ def test_non_list_memory_references_are_ignored(self) -> None:+ assert _extract_memory_references({"memory_references": "summary"}) == []++# ---------------------------------------------------------------------------# _extract_followup_question_context# ---------------------------------------------------------------------------diff --git a/tests/services/test_notebook_service.py b/tests/services/test_notebook_service.pyindex eaa41ed9d..a99961afb 100644--- a/tests/services/test_notebook_service.py+++ b/tests/services/test_notebook_service.py@@ -2,6 +2,8 @@from __future__ import annotations+import json+from deeptutor.services.notebook.service import NotebookManager, RecordType@@ -22,3 +24,46 @@ def test_add_record_accepts_enum_record_type(tmp_path) -> None:stored = manager.get_notebook(notebook["id"])assert stored is not Noneassert stored["records"][0]["type"] == "chat"+++def test_add_record_strips_thinking_tags_from_summary(tmp_path) -> None:+ manager = NotebookManager(base_dir=str(tmp_path))+ notebook = manager.create_notebook("Sanitized notebook")++ result = manager.add_record(+ notebook_ids=[notebook["id"]],+ record_type="chat",+ title="Sample",+ summary="<think>private reasoning</think>\nReusable summary.",+ user_query="Sample",+ output="# Sample",+ )++ assert result["record"]["summary"] == "Reusable summary."++ stored = manager.get_notebook(notebook["id"])+ assert stored is not None+ assert stored["records"][0]["summary"] == "Reusable summary."+++def test_get_notebook_repairs_existing_thinking_tags_in_summary(tmp_path) -> None:+ manager = NotebookManager(base_dir=str(tmp_path))+ notebook = manager.create_notebook("Legacy notebook")+ manager.add_record(+ notebook_ids=[notebook["id"]],+ record_type="chat",+ title="Sample",+ summary="Reusable summary.",+ user_query="Sample",+ output="# Sample",+ )++ path = manager._get_notebook_file(notebook["id"])+ raw = json.loads(path.read_text(encoding="utf-8"))+ raw["records"][0]["summary"] = "<think>old reasoning</think>\nReusable summary."+ path.write_text(json.dumps(raw, ensure_ascii=False, indent=2), encoding="utf-8")++ repaired = manager.get_notebook(notebook["id"])+ assert repaired is not None+ assert repaired["records"][0]["summary"] == "Reusable summary."+ assert "old reasoning" not in path.read_text(encoding="utf-8")diff --git a/tests/services/test_provider_registry.py b/tests/services/test_provider_registry.pynew file mode 100644index 000000000..d4f29e2a4--- /dev/null+++ b/tests/services/test_provider_registry.py@@ -0,0 +1,10 @@+from deeptutor.services.provider_registry import find_by_name, find_gateway+++def test_nvidia_nim_gateway_detection_by_key_and_base() -> None:+ spec = find_by_name("nvidia_nim")++ assert spec is not None+ assert spec.supports_stream_options is False+ assert find_gateway(api_key="nvapi-test-key") == spec+ assert find_gateway(api_base="https://integrate.api.nvidia.com/v1") == specdiff --git a/tests/services/tutorbot/test_manager_config.py b/tests/services/tutorbot/test_manager_config.pyindex 9d485144d..b0f59326f 100644--- a/tests/services/tutorbot/test_manager_config.py+++ b/tests/services/tutorbot/test_manager_config.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncio+import jsonfrom pathlib import Pathfrom types import SimpleNamespace@@ -24,6 +25,13 @@ def manager(tmp_path: Path) -> TutorBotManager:return mgr+def _append_session_line(manager: TutorBotManager, bot_id: str, payload: dict) -> None:+ sessions_dir = manager._bot_workspace(bot_id) / "sessions"+ sessions_dir.mkdir(parents=True, exist_ok=True)+ with open(sessions_dir / "chat.jsonl", "a", encoding="utf-8") as handle:+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")++# ---------------------------------------------------------------------------# load_bot_config / save_bot_config# ---------------------------------------------------------------------------@@ -54,6 +62,44 @@ class TestLoadAndSave:assert manager.load_bot_config("bad-bot") is None+class TestMessageHistory:+ def test_history_normalizes_part_content_and_strips_reasoning(+ self, manager: TutorBotManager+ ):+ _append_session_line(+ manager,+ "bot-history",+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Here is the image"},+ {"type": "image", "alt": "diagram"},+ ],+ "reasoning_content": "internal scratchpad",+ },+ )++ history = manager.get_bot_history("bot-history")++ assert history == [{"role": "assistant", "content": "Here is the image diagram"}]++ def test_recent_active_bots_normalizes_last_message(self, manager: TutorBotManager):+ manager.save_bot_config("bot-recent", BotConfig(name="Recent Bot"))+ _append_session_line(+ manager,+ "bot-recent",+ {+ "role": "user",+ "content": [{"type": "text", "text": "look"}, {"type": "image"}],+ },+ )++ recent = manager.get_recent_active_bots(limit=1)++ assert recent[0]["bot_id"] == "bot-recent"+ assert recent[0]["last_message"] == "look [image]"++# ---------------------------------------------------------------------------# Atomic write# ---------------------------------------------------------------------------diff --git a/web/app/(utility)/space/chat-history/page.tsx b/web/app/(utility)/space/chat-history/page.tsxnew file mode 100644index 000000000..7c9b56341--- /dev/null+++ b/web/app/(utility)/space/chat-history/page.tsx@@ -0,0 +1,5 @@+import ChatHistorySection from "@/components/space/ChatHistorySection";++export default function SpaceChatHistoryPage() {+ return <ChatHistorySection />;+}diff --git a/web/app/(utility)/space/page.tsx b/web/app/(utility)/space/page.tsxindex 77d1d8fb7..3260b8d05 100644--- a/web/app/(utility)/space/page.tsx+++ b/web/app/(utility)/space/page.tsx@@ -1,5 +1,5 @@import { redirect } from "next/navigation";export default function SpaceIndexPage() {- redirect("/space/notebooks");+ redirect("/space/chat-history");}diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex a199f63d2..e60daed84 100644--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@ -78,8 +78,8 @@ import {type ResearchSource,} from "@/lib/research-types";import { listKnowledgeBases } from "@/lib/knowledge-api";-import { listSkills, type SkillInfo } from "@/lib/skills-api";import { downloadChatMarkdown } from "@/lib/chat-export";+import type { SpaceMemoryFile } from "@/lib/space-items";const NotebookRecordPicker = dynamic(() => import("@/components/notebook/NotebookRecordPicker"),@@ -99,6 +99,12 @@ const QuestionBankPicker = dynamic(ssr: false,},);+const SkillsPicker = dynamic(() => import("@/components/chat/SkillsPicker"), {+ ssr: false,+});+const MemoryPicker = dynamic(() => import("@/components/chat/MemoryPicker"), {+ ssr: false,+});const SaveToNotebookModal = dynamic(() => import("@/components/notebook/SaveToNotebookModal"),{@@ -290,9 +296,10 @@ export default function ChatPage() {const [showNotebookPicker, setShowNotebookPicker] = useState(false);const [showHistoryPicker, setShowHistoryPicker] = useState(false);const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);+ const [showSkillsPicker, setShowSkillsPicker] = useState(false);+ const [showMemoryPicker, setShowMemoryPicker] = useState(false);const [toolMenuOpen, setToolMenuOpen] = useState(false);- const [refMenuOpen, setRefMenuOpen] = useState(false);- const [skillMenuOpen, setSkillMenuOpen] = useState(false);+ const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<SelectedRecord[]>([]);@@ -302,18 +309,18 @@ export default function ChatPage() {const [selectedQuestionEntries, setSelectedQuestionEntries] = useState<SelectedQuestionEntry[]>([]);- const [availableSkills, setAvailableSkills] = useState<SkillInfo[]>([]);const [selectedSkills, setSelectedSkills] = useState<string[]>([]);const [skillsAutoMode, setSkillsAutoMode] = useState(false);+ const [selectedMemoryFiles, setSelectedMemoryFiles] = useState<+ SpaceMemoryFile[]+ >([]);const dragCounter = useRef(0);const capMenuRef = useRef<HTMLDivElement>(null);const capBtnRef = useRef<HTMLButtonElement>(null);const toolMenuRef = useRef<HTMLDivElement>(null);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 spaceMenuRef = useRef<HTMLDivElement>(null);+ const spaceBtnRef = useRef<HTMLButtonElement>(null);const initialLoadRef = useRef(false);const activeCap = useMemo(@@ -380,6 +387,10 @@ export default function ChatPage() {() => selectedQuestionEntries.map((entry) => entry.id),[selectedQuestionEntries],);+ const memoryReferencesPayload = useMemo(+ () => [...selectedMemoryFiles],+ [selectedMemoryFiles],+ );const chatSaveMessages = useMemo(() =>state.messages.map((msg) => ({@@ -477,6 +488,8 @@ export default function ChatPage() {requestSnapshotOverride: answerNowSnapshot,},answerNowSnapshot.questionNotebookReferences,+ answerNowSnapshot.skills,+ answerNowSnapshot.memoryReferences,);shouldAutoScrollRef.current = true;}, 0);@@ -503,13 +516,14 @@ export default function ChatPage() {if (sessionIdParam === prevSessionIdParam.current) return;prevSessionIdParam.current = sessionIdParam;if (sessionIdParam) {+ if (sessionIdParam === state.sessionId) return;void loadSession(sessionIdParam).catch(() => {router.replace("/chat", { scroll: false });});} else {newSession();}- }, [sessionIdParam, loadSession, newSession, router]);+ }, [sessionIdParam, loadSession, newSession, router, state.sessionId]);// When a new session_id is assigned by the server, update the URLuseEffect(() => {@@ -599,38 +613,17 @@ export default function ChatPage() {)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)+ spaceMenuRef.current &&+ !spaceMenuRef.current.contains(t) &&+ spaceBtnRef.current &&+ !spaceBtnRef.current.contains(t))- setSkillMenuOpen(false);+ setSpaceMenuOpen(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) =>@@ -871,7 +864,10 @@ export default function ChatPage() {!attachments.length &&!selectedNotebookRecords.length &&!selectedHistorySessions.length &&- !selectedQuestionEntries.length) ||+ !selectedQuestionEntries.length &&+ !selectedSkills.length &&+ !skillsAutoMode &&+ !selectedMemoryFiles.length) ||state.isStreaming)return;@@ -906,26 +902,26 @@ 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(+ const skillsPayload = skillsAutoMode ? ["auto"] : [...selectedSkills];+ const memoryPayload = [...memoryReferencesPayload];+ const messageContent =content ||- (selectedNotebookRecords.length ||- selectedHistorySessions.length ||- selectedQuestionEntries.length- ? "Please use the selected context to help with this request."- : "") ||- (isMathAnimatorMode- ? attachments.some((a) => a.type === "image")- ? "Generate a math animation from the attached reference image(s)."- : ""- : attachments.some((a) => a.type === "image")- ? "Please analyze the attached image(s)."- : ""),+ (selectedNotebookRecords.length ||+ selectedHistorySessions.length ||+ selectedQuestionEntries.length ||+ skillsPayload.length ||+ memoryPayload.length+ ? "Please use the selected context to help with this request."+ : "") ||+ (isMathAnimatorMode+ ? attachments.some((a) => a.type === "image")+ ? "Generate a math animation from the attached reference image(s)."+ : ""+ : attachments.some((a) => a.type === "image")+ ? "Please analyze the attached image(s)."+ : "");+ sendMessage(+ messageContent,extraAttachments,config,notebookReferencesPayload,@@ -933,6 +929,7 @@ export default function ChatPage() {undefined,questionNotebookReferencesPayload,skillsPayload,+ memoryPayload,);shouldAutoScrollRef.current = true;// Auto-collapse the per-capability settings panel after sending so the@@ -942,6 +939,9 @@ export default function ChatPage() {setSelectedNotebookRecords([]);setSelectedHistorySessions([]);setSelectedQuestionEntries([]);+ setSelectedSkills([]);+ setSkillsAutoMode(false);+ setSelectedMemoryFiles([]);},[attachments,@@ -951,19 +951,20 @@ export default function ChatPage() {isResearchMode,isVisualizeMode,mathAnimatorConfig,+ memoryReferencesPayload,notebookReferencesPayload,questionNotebookReferencesPayload,quizConfig,quizPdf,researchConfig,selectedHistorySessions.length,+ selectedMemoryFiles.length,selectedNotebookRecords.length,selectedQuestionEntries.length,selectedSkills,skillsAutoMode,sendMessage,shouldAutoScrollRef,- state.activeCapability,state.isStreaming,visualizeConfig,],@@ -1011,6 +1012,12 @@ export default function ChatPage() {const handleSelectQuestionBankPicker = useCallback(() => {setShowQuestionBankPicker(true);}, []);+ const handleSelectSkillsPicker = useCallback(() => {+ setShowSkillsPicker(true);+ }, []);+ const handleSelectMemoryPicker = useCallback(() => {+ setShowMemoryPicker(true);+ }, []);const handleRemoveHistory = useCallback((sessionId: string) => {setSelectedHistorySessions((prev) =>prev.filter((item) => item.sessionId !== sessionId),@@ -1038,6 +1045,14 @@ export default function ChatPage() {if (auto) setSelectedSkills([]);}, []);+ const handleToggleMemoryFile = useCallback((file: SpaceMemoryFile) => {+ setSelectedMemoryFiles((prev) =>+ prev.includes(file)+ ? prev.filter((item) => item !== file)+ : [...prev, file],+ );+ }, []);+const handleTogglePanelCollapsed = useCallback(() => {setPanelCollapsed((prev) => !prev);}, []);@@ -1068,6 +1083,22 @@ export default function ChatPage() {},[],);+ const handleCloseSkillsPicker = useCallback(() => {+ setShowSkillsPicker(false);+ }, []);+ const handleApplySkillsSelection = useCallback(+ (selection: { auto: boolean; skills: string[] }) => {+ setSkillsAutoMode(selection.auto);+ setSelectedSkills(selection.auto ? [] : selection.skills);+ },+ [],+ );+ const handleCloseMemoryPicker = useCallback(() => {+ setShowMemoryPicker(false);+ }, []);+ const handleApplyMemoryFiles = useCallback((files: SpaceMemoryFile[]) => {+ setSelectedMemoryFiles(files);+ }, []);const handleCloseSaveModal = useCallback(() => {setShowSaveModal(false);}, []);@@ -1179,16 +1210,13 @@ export default function ChatPage() {capBtnRef={capBtnRef}toolMenuRef={toolMenuRef}toolBtnRef={toolBtnRef}- refMenuRef={refMenuRef}- refBtnRef={refBtnRef}- skillMenuRef={skillMenuRef}- skillBtnRef={skillBtnRef}+ spaceMenuRef={spaceMenuRef}+ spaceBtnRef={spaceBtnRef}dragCounter={dragCounter}dragging={dragging}capMenuOpen={capMenuOpen}toolMenuOpen={toolMenuOpen}- refMenuOpen={refMenuOpen}- skillMenuOpen={skillMenuOpen}+ spaceMenuOpen={spaceMenuOpen}hasMessages={hasMessages}attachments={attachments}attachmentError={attachmentError}@@ -1201,9 +1229,9 @@ export default function ChatPage() {selectedHistorySessions={selectedHistorySessions}selectedQuestionEntries={selectedQuestionEntries}notebookReferenceGroups={notebookReferenceGroups}- availableSkills={availableSkills}selectedSkills={selectedSkills}skillsAutoMode={skillsAutoMode}+ selectedMemoryFiles={selectedMemoryFiles}stateKnowledgeBase={state.knowledgeBases[0] || ""}isStreaming={state.isStreaming}isResearchMode={isResearchMode}@@ -1221,15 +1249,17 @@ export default function ChatPage() {researchSources={RESEARCH_SOURCES}onSetCapMenuOpen={setCapMenuOpen}onSetToolMenuOpen={setToolMenuOpen}- onSetRefMenuOpen={setRefMenuOpen}- onSetSkillMenuOpen={setSkillMenuOpen}+ onSetSpaceMenuOpen={setSpaceMenuOpen}onSetKB={handleSetKB}onSelectNotebookPicker={handleSelectNotebookPicker}onSelectHistoryPicker={handleSelectHistoryPicker}onSelectQuestionBankPicker={handleSelectQuestionBankPicker}+ onSelectSkillsPicker={handleSelectSkillsPicker}+ onSelectMemoryPicker={handleSelectMemoryPicker}onToggleTool={toggleTool}onToggleSkill={handleToggleSkill}onSetSkillsAuto={handleSetSkillsAuto}+ onToggleMemoryFile={handleToggleMemoryFile}onToggleResearchSource={toggleResearchSource}onSend={handleSend}onRemoveAttachment={removeAttachment}@@ -1268,6 +1298,19 @@ export default function ChatPage() {onClose={handleCloseQuestionBankPicker}onApply={handleApplyQuestionEntries}/>+ <SkillsPicker+ open={showSkillsPicker}+ initialAuto={skillsAutoMode}+ initialSkills={selectedSkills}+ onClose={handleCloseSkillsPicker}+ onApply={handleApplySkillsSelection}+ />+ <MemoryPicker+ open={showMemoryPicker}+ initialFiles={selectedMemoryFiles}+ onClose={handleCloseMemoryPicker}+ onApply={handleApplyMemoryFiles}+ /><SaveToNotebookModalopen={showSaveModal}payload={chatSavePayload}diff --git a/web/components/chat/AtMentionPopup.tsx b/web/components/chat/AtMentionPopup.tsxdeleted file mode 100644index 7ebfd68f8..000000000--- a/web/components/chat/AtMentionPopup.tsx+++ /dev/null@@ -1,45 +0,0 @@-"use client";--import { memo } from "react";-import { useTranslation } from "react-i18next";--interface AtMentionPopupProps {- open: boolean;- onSelectNotebook: () => void;- onSelectHistory: () => void;- onSelectQuestionBank: () => void;-}--export default memo(function AtMentionPopup({- open,- onSelectNotebook,- onSelectHistory,- onSelectQuestionBank,-}: AtMentionPopupProps) {- const { t } = useTranslation();-- if (!open) return null;-- return (- <div className="absolute bottom-full left-0 z-[70] mb-2 w-56 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-2 shadow-xl">- <button- onClick={onSelectNotebook}- className="w-full rounded-xl px-3 py-2.5 text-left text-[14px] font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)]/70"- >- {t("Notebook")}- </button>- <button- onClick={onSelectHistory}- className="w-full rounded-xl px-3 py-2.5 text-left text-[14px] font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)]/70"- >- {t("Chat History")}- </button>- <button- onClick={onSelectQuestionBank}- className="w-full rounded-xl px-3 py-2.5 text-left text-[14px] font-medium text-[var(--foreground)] transition hover:bg-[var(--muted)]/70"- >- {t("Question Bank")}- </button>- </div>- );-});diff --git a/web/components/chat/HistorySessionPicker.tsx b/web/components/chat/HistorySessionPicker.tsxindex 59272f49a..aea8cc290 100644--- a/web/components/chat/HistorySessionPicker.tsx+++ b/web/components/chat/HistorySessionPicker.tsx@@ -217,14 +217,14 @@ export default function HistorySessionPicker({<div className="text-[12px] text-[var(--muted-foreground)]">{selectedIds.length === 1? t("1 session selected")- : t("{n} sessions selected", { n: selectedIds.length })}+ : t("{{n}} sessions selected", { n: selectedIds.length })}</div><buttononClick={handleApply}disabled={!selectedIds.length}className="btn-primary rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40">- {t("Use Selected Sessions ({n})", { n: selectedIds.length })}+ {t("Use Selected Sessions ({{n}})", { n: selectedIds.length })}</button></div></div>diff --git a/web/components/chat/MemoryPicker.tsx b/web/components/chat/MemoryPicker.tsxnew file mode 100644index 000000000..9ea70ab20--- /dev/null+++ b/web/components/chat/MemoryPicker.tsx@@ -0,0 +1,173 @@+"use client";++import { useEffect, useState } from "react";+import { Brain, Check, FileText, ScrollText, X } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { LucideIcon } from "lucide-react";+import type { SpaceMemoryFile } from "@/lib/space-items";++interface MemoryPickerProps {+ open: boolean;+ initialFiles: SpaceMemoryFile[];+ onClose: () => void;+ onApply: (files: SpaceMemoryFile[]) => void;+}++interface MemoryOption {+ key: SpaceMemoryFile;+ label: string;+ description: string;+ icon: LucideIcon;+}++const MEMORY_OPTIONS: MemoryOption[] = [+ {+ key: "summary",+ label: "Summary",+ description:+ "Inject the assistant's running summary of past learning sessions.",+ icon: ScrollText,+ },+ {+ key: "profile",+ label: "Profile",+ description:+ "Inject the learner profile (preferences, goals, background).",+ icon: FileText,+ },+];++export default function MemoryPicker({+ open,+ initialFiles,+ onClose,+ onApply,+}: MemoryPickerProps) {+ const { t } = useTranslation();+ const [selected, setSelected] = useState<SpaceMemoryFile[]>(initialFiles);++ // IIFE keeps the setState call out of the synchronous effect body to+ // satisfy `react-hooks/set-state-in-effect`.+ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ void (async () => {+ if (cancelled) return;+ setSelected(initialFiles);+ })();+ return () => {+ cancelled = true;+ };+ }, [open, initialFiles]);++ const toggle = (key: SpaceMemoryFile) => {+ setSelected((prev) =>+ prev.includes(key) ? prev.filter((item) => item !== key) : [...prev, key],+ );+ };++ const handleApply = () => {+ onApply(selected);+ onClose();+ };++ if (!open) return null;++ return (+ <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">+ <div className="surface-card w-full max-w-xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">+ <div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">+ <div className="min-w-0">+ <div className="mb-1 inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">+ <Brain className="h-3 w-3" />+ {t("Memory Reference")}+ </div>+ <h2 className="text-lg font-semibold text-[var(--foreground)]">+ {t("Select Memory")}+ </h2>+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">+ {t(+ "Choose which long-form memory artifacts to attach to this turn.",+ )}+ </p>+ </div>+ <button+ onClick={onClose}+ className="rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ aria-label={t("Close")}+ >+ <X size={18} />+ </button>+ </div>++ <div className="bg-[var(--background)]/40 p-5">+ <div className="overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)]">+ <div className="divide-y divide-[var(--border)]">+ {MEMORY_OPTIONS.map((option) => {+ const active = selected.includes(option.key);+ const Icon = option.icon;+ return (+ <button+ key={option.key}+ onClick={() => toggle(option.key)}+ className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors ${+ active+ ? "bg-[var(--primary)]/8"+ : "hover:bg-[var(--muted)]/40"+ }`}+ >+ <div+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${+ active+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"+ : "border-[var(--border)] text-transparent"+ }`}+ >+ <Check size={12} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 text-[14px] font-medium text-[var(--foreground)]">+ <Icon+ size={14}+ strokeWidth={1.7}+ className="text-[var(--primary)]"+ />+ {t(option.label)}+ </div>+ <p className="mt-0.5 text-[12px] leading-5 text-[var(--muted-foreground)]">+ {t(option.description)}+ </p>+ </div>+ </button>+ );+ })}+ </div>+ </div>++ <div className="mt-4 flex items-center justify-between gap-3">+ <div className="text-[12px] text-[var(--muted-foreground)]">+ {selected.length === 1+ ? t("1 memory artifact selected")+ : t("{{n}} memory artifacts selected", { n: selected.length })}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setSelected([])}+ className="rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {t("Clear")}+ </button>+ <button+ onClick={handleApply}+ disabled={!selected.length}+ className="btn-primary rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {t("Use Selected Memory ({{n}})", { n: selected.length })}+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/components/chat/QuestionBankPicker.tsx b/web/components/chat/QuestionBankPicker.tsxindex ea09806b4..19d4e608a 100644--- a/web/components/chat/QuestionBankPicker.tsx+++ b/web/components/chat/QuestionBankPicker.tsx@@ -311,14 +311,14 @@ export default function QuestionBankPicker({<div className="text-[12px] text-[var(--muted-foreground)]">{selectedIds.length === 1? t("1 question selected")- : t("{n} questions selected", { n: selectedIds.length })}+ : t("{{n}} questions selected", { n: selectedIds.length })}</div><buttononClick={handleApply}disabled={!selectedIds.length}className="btn-primary rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40">- {t("Use Selected Questions ({n})", { n: selectedIds.length })}+ {t("Use Selected Questions ({{n}})", { n: selectedIds.length })}</button></div></div>diff --git a/web/components/chat/SkillsPicker.tsx b/web/components/chat/SkillsPicker.tsxnew file mode 100644index 000000000..84e85a978--- /dev/null+++ b/web/components/chat/SkillsPicker.tsx@@ -0,0 +1,288 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import {+ Check,+ Loader2,+ Search,+ Sparkles,+ Wand2,+ X,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import { listSkills, type SkillInfo } from "@/lib/skills-api";++export interface SkillsPickerSelection {+ auto: boolean;+ skills: string[];+}++interface SkillsPickerProps {+ open: boolean;+ initialAuto: boolean;+ initialSkills: string[];+ onClose: () => void;+ onApply: (selection: SkillsPickerSelection) => void;+}++export default function SkillsPicker({+ open,+ initialAuto,+ initialSkills,+ onClose,+ onApply,+}: SkillsPickerProps) {+ const { t } = useTranslation();+ const [skills, setSkills] = useState<SkillInfo[]>([]);+ const [loading, setLoading] = useState(false);+ const [auto, setAuto] = useState(initialAuto);+ const [selected, setSelected] = useState<string[]>(initialSkills);+ const [query, setQuery] = useState("");++ // Sync local state with the parent's current selection every time the+ // picker is reopened so the modal always starts from the latest choice.+ // The IIFE keeps setState calls out of the synchronous effect body to+ // satisfy `react-hooks/set-state-in-effect`.+ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ void (async () => {+ if (cancelled) return;+ setAuto(initialAuto);+ setSelected(initialSkills);+ setQuery("");+ })();+ return () => {+ cancelled = true;+ };+ }, [open, initialAuto, initialSkills]);++ useEffect(() => {+ if (!open) return;+ let mounted = true;+ void (async () => {+ setLoading(true);+ try {+ const items = await listSkills({ force: true });+ if (mounted) setSkills(items);+ } catch {+ if (mounted) setSkills([]);+ } finally {+ if (mounted) setLoading(false);+ }+ })();+ return () => {+ mounted = false;+ };+ }, [open]);++ const filteredSkills = useMemo(() => {+ const keyword = query.trim().toLowerCase();+ if (!keyword) return skills;+ return skills.filter((skill) => {+ const name = skill.name.toLowerCase();+ const desc = (skill.description || "").toLowerCase();+ const tags = (skill.tags || []).join(" ").toLowerCase();+ return (+ name.includes(keyword) ||+ desc.includes(keyword) ||+ tags.includes(keyword)+ );+ });+ }, [skills, query]);++ const toggleSkill = (name: string) => {+ setAuto(false);+ setSelected((prev) =>+ prev.includes(name) ? prev.filter((item) => item !== name) : [...prev, name],+ );+ };++ const toggleAuto = () => {+ setAuto((prev) => {+ const next = !prev;+ if (next) setSelected([]);+ return next;+ });+ };++ const handleApply = () => {+ onApply({ auto, skills: auto ? [] : selected });+ onClose();+ };++ const handleClear = () => {+ setAuto(false);+ setSelected([]);+ };++ if (!open) return null;++ const totalCount = auto ? 1 : selected.length;++ return (+ <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">+ <div className="surface-card w-full max-w-3xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">+ <div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">+ <div className="min-w-0">+ <div className="mb-1 inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">+ <Wand2 className="h-3 w-3" />+ {t("Skills Reference")}+ </div>+ <h2 className="text-lg font-semibold text-[var(--foreground)]">+ {t("Select Skills")}+ </h2>+ <p className="mt-0.5 text-sm text-[var(--muted-foreground)]">+ {t(+ "Pick Auto to let DeepTutor decide, or choose specific skills to apply.",+ )}+ </p>+ </div>+ <button+ onClick={onClose}+ className="rounded-lg p-2 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ aria-label={t("Close")}+ >+ <X size={18} />+ </button>+ </div>++ <div className="bg-[var(--background)]/40 p-5">+ <button+ type="button"+ onClick={toggleAuto}+ className={`mb-3 flex w-full items-start gap-3 rounded-2xl border px-4 py-3 text-left transition-colors ${+ auto+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/8"+ : "border-[var(--border)] bg-[var(--card)] hover:bg-[var(--muted)]/40"+ }`}+ >+ <div+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${+ auto+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"+ : "border-[var(--border)] text-transparent"+ }`}+ >+ <Check size={12} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 text-[14px] font-medium text-[var(--foreground)]">+ <Sparkles size={14} strokeWidth={1.7} className="text-[var(--primary)]" />+ {t("Auto")}+ </div>+ <p className="mt-0.5 text-[12px] leading-5 text-[var(--muted-foreground)]">+ {t(+ "Let the model auto-select relevant skills for this turn.",+ )}+ </p>+ </div>+ </button>++ <div className="mb-4 flex items-center gap-2">+ <div className="relative flex-1">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" />+ <input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t("Search skills by name, description, or tag")}+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--card)] py-2.5 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition focus:border-[var(--primary)]/50 focus:ring-2 focus:ring-[var(--primary)]/15"+ />+ </div>+ <button+ onClick={handleClear}+ className="rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {t("Clear")}+ </button>+ </div>++ <div className="max-h-[48vh] overflow-y-auto rounded-2xl border border-[var(--border)] bg-[var(--card)]">+ {loading ? (+ <div className="flex min-h-[220px] items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : filteredSkills.length ? (+ <div className="divide-y divide-[var(--border)]">+ {filteredSkills.map((skill) => {+ const active = !auto && selected.includes(skill.name);+ const dimmed = auto;+ return (+ <button+ key={skill.name}+ onClick={() => toggleSkill(skill.name)}+ className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors ${+ active+ ? "bg-[var(--primary)]/8"+ : "hover:bg-[var(--muted)]/40"+ } ${dimmed ? "opacity-55" : ""}`}+ >+ <div+ className={`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border transition-colors ${+ active+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"+ : "border-[var(--border)] text-transparent"+ }`}+ >+ <Check size={12} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-[14px] font-medium text-[var(--foreground)]">+ {skill.name}+ </span>+ {skill.tags?.length ? (+ <div className="flex flex-wrap gap-1">+ {skill.tags.slice(0, 3).map((tag) => (+ <span+ key={tag}+ className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]"+ >+ {tag}+ </span>+ ))}+ </div>+ ) : null}+ </div>+ {skill.description ? (+ <p className="mt-1 line-clamp-2 text-[12px] leading-5 text-[var(--muted-foreground)]">+ {skill.description}+ </p>+ ) : null}+ </div>+ </button>+ );+ })}+ </div>+ ) : (+ <div className="px-6 py-14 text-center text-[13px] text-[var(--muted-foreground)]">+ {skills.length === 0+ ? t("No skills yet")+ : t("No matching skills found.")}+ </div>+ )}+ </div>++ <div className="mt-4 flex items-center justify-between gap-3">+ <div className="text-[12px] text-[var(--muted-foreground)]">+ {auto+ ? t("Auto skill selection enabled")+ : selected.length === 1+ ? t("1 skill selected")+ : t("{{n}} skills selected", { n: selected.length })}+ </div>+ <button+ onClick={handleApply}+ disabled={totalCount === 0}+ className="btn-primary rounded-xl bg-[var(--primary)] px-4 py-2.5 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {auto+ ? t("Use Auto Skills")+ : t("Use Selected Skills ({{n}})", { n: selected.length })}+ </button>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex 4f62e9218..5848a59f1 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -14,15 +14,11 @@ import Image from "next/image";import {ArrowUp,AtSign,- BookOpen,ChevronDown,- ClipboardList,Layers,- MessageSquare,Paperclip,Sparkles,Square,- Wand2,X,type LucideIcon,} from "lucide-react";@@ -43,7 +39,17 @@ import type {DeepResearchFormConfig,ResearchSource,} from "@/lib/research-types";-import { ReferenceChips } from "./ChatMessages";+import ChatSpaceMenu from "@/components/chat/space/ChatSpaceMenu";+import type { SpaceMemoryFile } from "@/lib/space-items";++type SpaceSelectionCounts = {+ chatHistory: number;+ notebooks: number;+ questionBank: number;+ skills: number;+ memory: number;+};+import { SpaceContextChips } from "./ChatMessages";import { ComposerInput, type ComposerInputHandle } from "./ComposerInput";const QuizConfigPanel = dynamic(@@ -104,16 +110,13 @@ export default memo(function ChatComposer({capBtnRef,toolMenuRef,toolBtnRef,- refMenuRef,- refBtnRef,- skillMenuRef,- skillBtnRef,+ spaceMenuRef,+ spaceBtnRef,dragCounter,dragging,capMenuOpen,toolMenuOpen,- refMenuOpen,- skillMenuOpen,+ spaceMenuOpen,hasMessages,attachments,attachmentError,@@ -126,9 +129,9 @@ export default memo(function ChatComposer({selectedHistorySessions,selectedQuestionEntries,notebookReferenceGroups,- availableSkills,selectedSkills,skillsAutoMode,+ selectedMemoryFiles,stateKnowledgeBase,isStreaming,isResearchMode,@@ -146,15 +149,17 @@ export default memo(function ChatComposer({researchSources,onSetCapMenuOpen,onSetToolMenuOpen,- onSetRefMenuOpen,- onSetSkillMenuOpen,+ onSetSpaceMenuOpen,onSetKB,onSelectNotebookPicker,onSelectHistoryPicker,onSelectQuestionBankPicker,+ onSelectSkillsPicker,+ onSelectMemoryPicker,onToggleTool,onToggleSkill,onSetSkillsAuto,+ onToggleMemoryFile,onToggleResearchSource,onSend,onRemoveAttachment,@@ -182,16 +187,13 @@ export default memo(function ChatComposer({capBtnRef: RefObject<HTMLButtonElement | null>;toolMenuRef: RefObject<HTMLDivElement | null>;toolBtnRef: RefObject<HTMLButtonElement | null>;- refMenuRef: RefObject<HTMLDivElement | null>;- refBtnRef: RefObject<HTMLButtonElement | null>;- skillMenuRef: RefObject<HTMLDivElement | null>;- skillBtnRef: RefObject<HTMLButtonElement | null>;+ spaceMenuRef: RefObject<HTMLDivElement | null>;+ spaceBtnRef: RefObject<HTMLButtonElement | null>;dragCounter: RefObject<number>;dragging: boolean;capMenuOpen: boolean;toolMenuOpen: boolean;- refMenuOpen: boolean;- skillMenuOpen: boolean;+ spaceMenuOpen: boolean;hasMessages: boolean;attachments: PendingAttachment[];attachmentError: string | null;@@ -208,9 +210,9 @@ export default memo(function ChatComposer({notebookName: string;count: number;}>;- availableSkills: Array<{ name: string; description: string }>;selectedSkills: string[];skillsAutoMode: boolean;+ selectedMemoryFiles: SpaceMemoryFile[];stateKnowledgeBase: string;isStreaming: boolean;isResearchMode: boolean;@@ -228,15 +230,17 @@ export default memo(function ChatComposer({researchSources: ResearchSourceDef[];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;+ onSetSpaceMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;onSetKB: (kb: string) => void;onSelectNotebookPicker: () => void;onSelectHistoryPicker: () => void;onSelectQuestionBankPicker: () => void;+ onSelectSkillsPicker: () => void;+ onSelectMemoryPicker: () => void;onToggleTool: (tool: ToolDef["name"]) => void;onToggleSkill: (skill: string) => void;onSetSkillsAuto: (auto: boolean) => void;+ onToggleMemoryFile: (file: SpaceMemoryFile) => void;onToggleResearchSource: (source: ResearchSource) => void;onSend: (content: string) => void;onRemoveAttachment: (index: number) => void;@@ -308,13 +312,31 @@ export default memo(function ChatComposer({!!attachments.length ||!!selectedNotebookRecords.length ||!!selectedHistorySessions.length ||- !!selectedQuestionEntries.length;+ !!selectedQuestionEntries.length ||+ !!selectedSkills.length ||+ skillsAutoMode ||+ !!selectedMemoryFiles.length;const canSend =(hasContent || hasReferences) &&!isStreaming &&!(isResearchMode && Object.keys(researchValidationErrors).length > 0);+ const skillsCount = skillsAutoMode ? 1 : selectedSkills.length;+ const spaceSelectionCounts: SpaceSelectionCounts = {+ chatHistory: selectedHistorySessions.length,+ notebooks: selectedNotebookRecords.length,+ questionBank: selectedQuestionEntries.length,+ skills: skillsCount,+ memory: selectedMemoryFiles.length,+ };+ const spaceSelectionCount =+ spaceSelectionCounts.chatHistory ++ spaceSelectionCounts.notebooks ++ spaceSelectionCounts.questionBank ++ spaceSelectionCounts.skills ++ spaceSelectionCounts.memory;+const handleManualSend = useCallback(() => {if (!canSend) return;const content = inputHandleRef.current?.getValue() || "";@@ -414,13 +436,19 @@ export default memo(function ChatComposer({{hasReferences && (<div className="px-4 pt-3.5 [&>div]:mb-0">- <ReferenceChips+ <SpaceContextChipshistorySessions={selectedHistorySessions}notebookGroups={notebookReferenceGroups}questionEntries={selectedQuestionEntries}+ selectedSkills={selectedSkills}+ skillsAutoMode={skillsAutoMode}+ memoryFiles={selectedMemoryFiles}onRemoveHistory={onRemoveHistory}onRemoveNotebook={onRemoveNotebook}onRemoveQuestion={onRemoveQuestion}+ onRemoveSkill={onToggleSkill}+ onClearSkillsAuto={() => onSetSkillsAuto(false)}+ onRemoveMemoryFile={onToggleMemoryFile}/></div>)}@@ -434,9 +462,12 @@ export default memo(function ChatComposer({onSend={doSend}onInputChange={handleInputChange}onPaste={onPaste}+ selectedCounts={spaceSelectionCounts}onSelectNotebookPicker={onSelectNotebookPicker}onSelectHistoryPicker={onSelectHistoryPicker}onSelectQuestionBankPicker={onSelectQuestionBankPicker}+ onSelectSkillsPicker={onSelectSkillsPicker}+ onSelectMemoryPicker={onSelectMemoryPicker}/>{!!attachments.length && (@@ -741,179 +772,44 @@ export default memo(function ChatComposer({<div className="relative flex items-center gap-0.5"><button- ref={refBtnRef}- onClick={() => onSetRefMenuOpen((v) => !v)}+ ref={spaceBtnRef}+ type="button"+ onClick={() => onSetSpaceMenuOpen((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)]"><AtSign size={12} strokeWidth={1.7} />- {t("Reference")}+ {t("Space")}<ChevronDownsize={10}- className={`transition-transform ${refMenuOpen ? "rotate-180" : ""}`}+ className={`transition-transform ${spaceMenuOpen ? "rotate-180" : ""}`}/></button>- {(selectedNotebookRecords.length > 0 ||- selectedHistorySessions.length > 0 ||- selectedQuestionEntries.length > 0) && (+ {spaceSelectionCount > 0 && (<span className="shrink-0 rounded-full bg-[var(--primary)]/10 px-1.5 py-px text-[9px] font-semibold text-[var(--primary)]">- {selectedNotebookRecords.length +- selectedHistorySessions.length +- selectedQuestionEntries.length}+ {spaceSelectionCount}</span>)}- {refMenuOpen && (+ {spaceMenuOpen && (<div- ref={refMenuRef}- className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"+ ref={spaceMenuRef}+ className="absolute bottom-full left-0 z-50 mb-1.5">- <button- onClick={() => {- onSetRefMenuOpen(false);- onSelectNotebookPicker();- }}- className="flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] hover:bg-[var(--muted)]/40"- >- <BookOpen size={13} strokeWidth={1.7} />- <span className="flex-1 font-medium">- {t("Notebook")}- </span>- {selectedNotebookRecords.length > 0 && (- <span className="text-[10px] text-[var(--primary)]">- {selectedNotebookRecords.length}- </span>- )}- </button>- <button- onClick={() => {- onSetRefMenuOpen(false);- onSelectHistoryPicker();+ <ChatSpaceMenu+ variant="toolbar"+ selectedCounts={spaceSelectionCounts}+ onSelectItem={(key) => {+ onSetSpaceMenuOpen(false);+ if (key === "chat_history") onSelectHistoryPicker();+ else if (key === "notebooks") onSelectNotebookPicker();+ else if (key === "question_bank")+ onSelectQuestionBankPicker();+ else if (key === "skills") onSelectSkillsPicker();+ else if (key === "memory") onSelectMemoryPicker();}}- className="flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] hover:bg-[var(--muted)]/40"- >- <MessageSquare size={13} strokeWidth={1.7} />- <span className="flex-1 font-medium">- {t("Chat History")}- </span>- {selectedHistorySessions.length > 0 && (- <span className="text-[10px] text-[var(--primary)]">- {selectedHistorySessions.length}- </span>- )}- </button>- <button- onClick={() => {- onSetRefMenuOpen(false);- onSelectQuestionBankPicker();- }}- className="flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] hover:bg-[var(--muted)]/40"- >- <ClipboardList size={13} strokeWidth={1.7} />- <span className="flex-1 font-medium">- {t("Question Bank")}- </span>- {selectedQuestionEntries.length > 0 && (- <span className="text-[10px] text-[var(--primary)]">- {selectedQuestionEntries.length}- </span>- )}- </button>+ /></div>)}</div>-- {!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(--popover)] py-1 shadow-lg backdrop-blur-md"- >- <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/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex e1b8c1287..a93a59151 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -2,14 +2,15 @@import dynamic from "next/dynamic";import { memo, useCallback, useMemo, useState } from "react";-import Image from "next/image";import {BookOpen,+ Brain,ClipboardList,Coins,Copy,MessageSquare,RefreshCcw,+ Wand2,X,Zap,type LucideIcon,@@ -22,12 +23,14 @@ import type {MessageAttachment,MessageRequestSnapshot,} from "@/context/UnifiedChatContext";+import { apiUrl } from "@/lib/api";import { docIconFor } from "@/lib/doc-attachments";import { extractMathAnimatorResult } from "@/lib/math-animator-types";import { extractQuizQuestions } from "@/lib/quiz-types";import { extractVisualizeResult } from "@/lib/visualize-types";import type { StreamEvent } from "@/lib/unified-ws";import { hasVisibleMarkdownContent } from "@/lib/markdown-display";+import type { SpaceMemoryFile } from "@/lib/space-items";import { CallTracePanel } from "./TracePanels";const MathAnimatorViewer = dynamic(@@ -73,6 +76,24 @@ function getModeBadgeLabel(capability?: string | null): string {return capability;}+function imageSrcForAttachment(attachment: MessageAttachment): string | null {+ if (attachment.url) {+ if (+ attachment.url.startsWith("http") ||+ attachment.url.startsWith("blob:") ||+ attachment.url.startsWith("data:")+ ) {+ return attachment.url;+ }+ return apiUrl(attachment.url);+ }++ const base64 = attachment.base64?.trim();+ if (!base64) return null;+ if (base64.startsWith("data:")) return base64;+ return `data:${attachment.mime_type || "image/png"};base64,${base64}`;+}+const AssistantMessage = memo(function AssistantMessage({msg,isStreaming,@@ -306,9 +327,8 @@ const UserMessage = memo(function UserMessage({{msg.attachments.filter((a) => a.type === "image" && (a.base64 || a.url)).map((a, ai) => {- const src = a.url- ? a.url- : `data:image/png;base64,${a.base64}`;+ const src = imageSrcForAttachment(a);+ if (!src) return null;return (<buttonkey={`img-${ai}`}@@ -317,12 +337,10 @@ const UserMessage = memo(function UserMessage({title={a.filename || t("image")}className="overflow-hidden rounded-2xl border border-[var(--border)] transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40">- <Image+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <imgsrc={src}alt={a.filename || t("image")}- width={280}- height={192}- unoptimizedclassName="max-h-48 max-w-[280px] rounded-2xl object-contain"/></button>@@ -373,7 +391,19 @@ const UserMessage = memo(function UserMessage({const snap = msg.requestSnapshot;const hasNotebook = Boolean(snap?.notebookReferences?.length);const hasHistory = Boolean(snap?.historyReferences?.length);- if (!hasNotebook && !hasHistory) return null;+ const hasQuestions = Boolean(+ snap?.questionNotebookReferences?.length,+ );+ const hasSkills = Boolean(snap?.skills?.length);+ const hasMemory = Boolean(snap?.memoryReferences?.length);+ if (+ !hasNotebook &&+ !hasHistory &&+ !hasQuestions &&+ !hasSkills &&+ !hasMemory+ )+ return null;return (<div className="mb-2 flex flex-wrap gap-1.5">{snap?.notebookReferences?.map((ref) => (@@ -394,6 +424,32 @@ const UserMessage = memo(function UserMessage({{t("Chat History")}</span>))}+ {hasQuestions && (+ <span className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]">+ <ClipboardList size={11} strokeWidth={1.8} />+ {t("Question Bank")} ·{" "}+ {snap?.questionNotebookReferences?.length} {t("items")}+ </span>+ )}+ {snap?.skills?.map((skill) => (+ <span+ key={skill}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"+ >+ <Wand2 size={11} strokeWidth={1.8} />+ {skill === "auto" ? t("Skills Auto") : skill}+ </span>+ ))}+ {snap?.memoryReferences?.map((file) => (+ <span+ key={file}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"+ >+ <Brain size={11} strokeWidth={1.8} />+ {t("Memory")} ·{" "}+ {file === "summary" ? t("Summary") : t("Profile")}+ </span>+ ))}</div>);})()}@@ -406,26 +462,41 @@ const UserMessage = memo(function UserMessage({UserMessage.displayName = "UserMessage";-export const ReferenceChips = memo(function ReferenceChips({+export const SpaceContextChips = memo(function SpaceContextChips({historySessions,notebookGroups,questionEntries,+ selectedSkills,+ skillsAutoMode,+ memoryFiles,onRemoveHistory,onRemoveNotebook,onRemoveQuestion,+ onRemoveSkill,+ onClearSkillsAuto,+ onRemoveMemoryFile,}: {historySessions: SelectedHistorySession[];notebookGroups: NotebookReferenceGroup[];questionEntries: SelectedQuestionEntry[];+ selectedSkills: string[];+ skillsAutoMode: boolean;+ memoryFiles: SpaceMemoryFile[];onRemoveHistory: (sessionId: string) => void;onRemoveNotebook: (notebookId: string) => void;onRemoveQuestion: (entryId: number) => void;+ onRemoveSkill: (skill: string) => void;+ onClearSkillsAuto: () => void;+ onRemoveMemoryFile: (file: SpaceMemoryFile) => void;}) {const { t } = useTranslation();if (historySessions.length === 0 &¬ebookGroups.length === 0 &&- questionEntries.length === 0+ questionEntries.length === 0 &&+ selectedSkills.length === 0 &&+ !skillsAutoMode &&+ memoryFiles.length === 0)return null;@@ -487,11 +558,62 @@ export const ReferenceChips = memo(function ReferenceChips({</button></span>))}+ {skillsAutoMode && (+ <span className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200">+ <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Skills")}</span>+ <span className="truncate text-violet-700/90 dark:text-violet-200/90">+ {t("Auto")}+ </span>+ <button+ onClick={onClearSkillsAuto}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ )}+ {selectedSkills.map((skill) => (+ <span+ key={skill}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200"+ >+ <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Skill")}</span>+ <span className="truncate text-violet-700/90 dark:text-violet-200/90">+ {skill}+ </span>+ <button+ onClick={() => onRemoveSkill(skill)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ {memoryFiles.map((file) => (+ <span+ key={file}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-[12px] text-emerald-800 shadow-sm dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200"+ >+ <Brain size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Memory")}</span>+ <span className="truncate text-emerald-700/90 dark:text-emerald-200/90">+ {file === "summary" ? t("Summary") : t("Profile")}+ </span>+ <button+ onClick={() => onRemoveMemoryFile(file)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}</div>);});-ReferenceChips.displayName = "ReferenceChips";+SpaceContextChips.displayName = "SpaceContextChips";export const ChatMessageList = memo(function ChatMessageList({messages,diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsxindex c1517106e..5bf96e7be 100644--- a/web/components/chat/home/ComposerInput.tsx+++ b/web/components/chat/home/ComposerInput.tsx@@ -11,7 +11,9 @@ import {type RefObject,} from "react";import { useTranslation } from "react-i18next";-import AtMentionPopup from "@/components/chat/AtMentionPopup";+import ChatSpaceMenu, {+ type ChatSpaceSelectionCounts,+} from "@/components/chat/space/ChatSpaceMenu";import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";interface ComposerInputProps {@@ -26,9 +28,12 @@ interface ComposerInputProps {onSend: (content: string) => void;onInputChange: (content: string) => void;onPaste: (e: React.ClipboardEvent) => void;+ selectedCounts: ChatSpaceSelectionCounts;onSelectNotebookPicker: () => void;onSelectHistoryPicker: () => void;onSelectQuestionBankPicker: () => void;+ onSelectSkillsPicker: () => void;+ onSelectMemoryPicker: () => void;}export interface ComposerInputHandle {@@ -56,9 +61,12 @@ export const ComposerInput = memo(onSend,onInputChange,onPaste,+ selectedCounts,onSelectNotebookPicker,onSelectHistoryPicker,onSelectQuestionBankPicker,+ onSelectSkillsPicker,+ onSelectMemoryPicker,},ref,) {@@ -67,9 +75,9 @@ export const ComposerInput = memo(const [showAtPopup, setShowAtPopup] = useState(false);// Latest text mirrored into a ref by the change handlers (never updated- // during render). The select-* handlers and the imperative handle read+ // during render). The @space handlers and the imperative handle read// from this ref so their identities stay stable across keystrokes,- // letting `memo` on AtMentionPopup actually skip re-renders when+ // letting `memo` on ChatSpaceMenu actually skip re-renders when// `showAtPopup` doesn't change.const inputRef = useRef("");const isComposingRef = useRef(false);@@ -161,38 +169,50 @@ export const ComposerInput = memo(}, 0);}, []);- const handleSelectNotebook = useCallback(() => {+ const clearTrailingMention = useCallback(() => {const next = stripTrailingAtMention(inputRef.current);setInputBoth(next);onInputChange(next);- setShowAtPopup(false);- onSelectNotebookPicker();- }, [setInputBoth, onInputChange, onSelectNotebookPicker]);-- const handleSelectHistory = useCallback(() => {- const next = stripTrailingAtMention(inputRef.current);- setInputBoth(next);- onInputChange(next);- setShowAtPopup(false);- onSelectHistoryPicker();- }, [setInputBoth, onInputChange, onSelectHistoryPicker]);-- const handleSelectQuestionBank = useCallback(() => {- const next = stripTrailingAtMention(inputRef.current);- setInputBoth(next);- onInputChange(next);- setShowAtPopup(false);- onSelectQuestionBankPicker();- }, [setInputBoth, onInputChange, onSelectQuestionBankPicker]);+ }, [setInputBoth, onInputChange]);++ const handleSelectSpaceItem = useCallback(+ (+ key:+ | "chat_history"+ | "notebooks"+ | "question_bank"+ | "skills"+ | "memory",+ ) => {+ clearTrailingMention();+ setShowAtPopup(false);+ if (key === "chat_history") onSelectHistoryPicker();+ else if (key === "notebooks") onSelectNotebookPicker();+ else if (key === "question_bank") onSelectQuestionBankPicker();+ else if (key === "skills") onSelectSkillsPicker();+ else if (key === "memory") onSelectMemoryPicker();+ },+ [+ clearTrailingMention,+ onSelectHistoryPicker,+ onSelectNotebookPicker,+ onSelectQuestionBankPicker,+ onSelectSkillsPicker,+ onSelectMemoryPicker,+ ],+ );return (<div className="px-4 pt-3.5 pb-2">- <AtMentionPopup- open={showAtPopup}- onSelectNotebook={handleSelectNotebook}- onSelectHistory={handleSelectHistory}- onSelectQuestionBank={handleSelectQuestionBank}- />+ {showAtPopup && (+ <div className="absolute bottom-full left-0 z-[70] mb-2">+ <ChatSpaceMenu+ variant="mention"+ selectedCounts={selectedCounts}+ onSelectItem={handleSelectSpaceItem}+ />+ </div>+ )}<textarearef={textareaRef}value={input}diff --git a/web/components/chat/space/ChatSpaceMenu.tsx b/web/components/chat/space/ChatSpaceMenu.tsxnew file mode 100644index 000000000..cc33bec6f--- /dev/null+++ b/web/components/chat/space/ChatSpaceMenu.tsx@@ -0,0 +1,114 @@+"use client";++import { memo } from "react";+import { useTranslation } from "react-i18next";+import { SPACE_ITEMS, type SpaceItemKey } from "@/lib/space-items";++type SelectableSpaceKey = Extract<+ SpaceItemKey,+ "chat_history" | "notebooks" | "question_bank" | "skills" | "memory"+>;++export interface ChatSpaceSelectionCounts {+ chatHistory: number;+ notebooks: number;+ questionBank: number;+ skills: number;+ memory: number;+}++interface ChatSpaceMenuProps {+ variant: "toolbar" | "mention";+ selectedCounts: ChatSpaceSelectionCounts;+ onSelectItem: (key: SelectableSpaceKey) => void;+}++const ITEM_ORDER: SelectableSpaceKey[] = [+ "chat_history",+ "notebooks",+ "question_bank",+ "skills",+ "memory",+];++function countFor(+ key: SelectableSpaceKey,+ counts: ChatSpaceSelectionCounts,+): number {+ switch (key) {+ case "chat_history":+ return counts.chatHistory;+ case "notebooks":+ return counts.notebooks;+ case "question_bank":+ return counts.questionBank;+ case "skills":+ return counts.skills;+ case "memory":+ return counts.memory;+ default:+ return 0;+ }+}++export default memo(function ChatSpaceMenu({+ variant,+ selectedCounts,+ onSelectItem,+}: ChatSpaceMenuProps) {+ const { t } = useTranslation();+ const compact = variant === "toolbar";++ // Render the items in a fixed, hand-tuned order so the menu always reads+ // the same regardless of how SPACE_ITEMS may be reordered for navigation.+ const items = ITEM_ORDER.map((key) => SPACE_ITEMS.find((it) => it.key === key)!).filter(+ Boolean,+ );++ return (+ <div+ className={`rounded-xl border border-[var(--border)] bg-[var(--popover)] shadow-lg backdrop-blur-md ${+ compact ? "w-[260px] py-1.5" : "w-64 p-2"+ }`}+ >+ <div className={compact ? "space-y-0.5" : "space-y-1"}>+ {items.map(({ key, label, description, icon: Icon }) => {+ const count = countFor(key as SelectableSpaceKey, selectedCounts);+ return (+ <button+ key={key}+ type="button"+ onClick={() => onSelectItem(key as SelectableSpaceKey)}+ className={`flex w-full items-center gap-2.5 text-left transition-colors hover:bg-[var(--muted)]/40 ${+ compact+ ? "px-3 py-1.5 text-[12px]"+ : "rounded-xl px-3 py-2.5 text-[13px]"+ }`}+ >+ <Icon+ size={compact ? 13 : 14}+ strokeWidth={1.7}+ className="shrink-0 text-[var(--muted-foreground)]"+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate font-medium text-[var(--foreground)]">+ {t(label)}+ </span>+ {!compact && (+ <span className="mt-0.5 block truncate text-[11px] text-[var(--muted-foreground)]">+ {t(description)}+ </span>+ )}+ </span>+ {count > 0 && (+ <span className="rounded-full bg-[var(--primary)]/10 px-1.5 py-px text-[9px] font-semibold text-[var(--primary)]">+ {count}+ </span>+ )}+ </button>+ );+ })}+ </div>+ </div>+ );+});diff --git a/web/components/space/ChatHistorySection.tsx b/web/components/space/ChatHistorySection.tsxnew file mode 100644index 000000000..ce8f882f4--- /dev/null+++ b/web/components/space/ChatHistorySection.tsx@@ -0,0 +1,132 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { useRouter } from "next/navigation";+import { History, Loader2, RefreshCw, Search } from "lucide-react";+import { useTranslation } from "react-i18next";+import SessionList from "@/components/SessionList";+import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";+import { useAppShell } from "@/context/AppShellContext";+import {+ deleteSession,+ listSessions,+ updateSessionTitle,+ type SessionSummary,+} from "@/lib/session-api";++export default function ChatHistorySection() {+ const { t } = useTranslation();+ const router = useRouter();+ const { activeSessionId, setActiveSessionId } = useAppShell();+ const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [loading, setLoading] = useState(true);+ const [query, setQuery] = useState("");++ const load = useCallback(async (force = false) => {+ setLoading(true);+ try {+ setSessions(await listSessions(200, 0, { force }));+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void load(true);+ }, [load]);++ const filteredSessions = useMemo(() => {+ const needle = query.trim().toLowerCase();+ if (!needle) return sessions;+ return sessions.filter((session) =>+ [session.title, session.last_message]+ .filter(Boolean)+ .some((value) => value.toLowerCase().includes(needle)),+ );+ }, [query, sessions]);++ const handleSelect = useCallback(+ (sessionId: string) => {+ setActiveSessionId(sessionId);+ router.push(`/chat/${sessionId}`);+ },+ [router, setActiveSessionId],+ );++ const handleRename = useCallback(+ async (sessionId: string, title: string) => {+ await updateSessionTitle(sessionId, title);+ await load(true);+ },+ [load],+ );++ const handleDelete = useCallback(+ async (sessionId: string) => {+ if (!window.confirm(t("Delete this chat?"))) return;+ await deleteSession(sessionId);+ if (activeSessionId === sessionId) setActiveSessionId(null);+ setSessions((prev) =>+ prev.filter((session) => session.session_id !== sessionId),+ );+ },+ [activeSessionId, setActiveSessionId, t],+ );++ return (+ <div className="space-y-6">+ <SpaceSectionHeader+ icon={History}+ title={t("Chat History")}+ description={t(+ "Browse, rename, delete, and reopen previous conversations from your learning space.",+ )}+ meta={+ <span className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">+ {sessions.length} {t("conversations")}+ </span>+ }+ action={+ <button+ type="button"+ onClick={() => void load(true)}+ disabled={loading}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {loading ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <RefreshCw className="h-3 w-3" />+ )}+ {t("Refresh")}+ </button>+ }+ />++ <section className="rounded-2xl border border-[var(--border)] bg-[var(--card)] shadow-sm">+ <div className="border-b border-[var(--border)]/60 px-4 py-3">+ <label className="flex items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--muted-foreground)] focus-within:border-[var(--ring)]">+ <Search size={14} strokeWidth={1.7} />+ <input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t("Search chat history...")}+ className="min-w-0 flex-1 bg-transparent text-[13px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/55"+ />+ </label>+ </div>++ <div className="px-3 py-3">+ <SessionList+ sessions={filteredSessions}+ activeSessionId={activeSessionId}+ loading={loading}+ onSelect={handleSelect}+ onRename={handleRename}+ onDelete={handleDelete}+ />+ </div>+ </section>+ </div>+ );+}diff --git a/web/components/space/SpaceMiniNav.tsx b/web/components/space/SpaceMiniNav.tsxindex 85db97eb4..0b0fc66b7 100644--- a/web/components/space/SpaceMiniNav.tsx+++ b/web/components/space/SpaceMiniNav.tsx@@ -3,48 +3,8 @@import Link from "next/link";import { usePathname } from "next/navigation";import { useTranslation } from "react-i18next";-import {- Brain,- ClipboardList,- LayoutGrid,- NotebookPen,- Wand2,- type LucideIcon,-} from "lucide-react";--interface SpaceNavEntry {- href: string;- label: string;- description: string;- icon: LucideIcon;-}--const SPACE_NAV: SpaceNavEntry[] = [- {- href: "/space/notebooks",- label: "Notebooks",- description: "Organize saved outputs from chat, research, Co-Writer, and more.",- icon: NotebookPen,- },- {- href: "/space/questions",- label: "Question Bank",- description: "Review and organize quiz questions across sessions.",- icon: ClipboardList,- },- {- href: "/space/skills",- label: "Skills",- description: "Behavior playbooks that guide chat responses.",- icon: Wand2,- },- {- href: "/space/memory",- label: "Memory",- description: "Long-form memory the assistant carries across sessions.",- icon: Brain,- },-];+import { LayoutGrid } from "lucide-react";+import { SPACE_ITEMS } from "@/lib/space-items";export default function SpaceMiniNav() {const pathname = usePathname();@@ -65,14 +25,14 @@ export default function SpaceMiniNav() {</h1><p className="mt-0.5 text-[11px] leading-relaxed text-[var(--muted-foreground)]">{t(- "Your personal library of notebooks, questions, playbooks, and memory.",+ "Your personal library of conversations, notebooks, questions, playbooks, and memory.",)}</p></div></div><nav className="flex-1 space-y-1 px-2 py-3">- {SPACE_NAV.map(({ href, label, description, icon: Icon }) => {+ {SPACE_ITEMS.map(({ href, label, description, icon: Icon }) => {const active = pathname.startsWith(href);return (<Linkdiff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex 69efcfc43..f96aeaed2 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -46,6 +46,8 @@ type HistoryReferencePayload = string[];type QuestionNotebookReferencePayload = number[];+type MemoryReferencePayload = Array<"summary" | "profile">;+export interface SendMessageOptions {displayUserMessage?: boolean;persistUserMessage?: boolean;@@ -95,6 +97,7 @@ export interface MessageRequestSnapshot {historyReferences?: HistoryReferencePayload;questionNotebookReferences?: QuestionNotebookReferencePayload;skills?: string[];+ memoryReferences?: MemoryReferencePayload;}export interface MessageItem {@@ -495,6 +498,7 @@ interface ChatContextValue {options?: SendMessageOptions,questionNotebookReferences?: QuestionNotebookReferencePayload,skills?: string[],+ memoryReferences?: MemoryReferencePayload,) => void;cancelStreamingTurn: () => void;regenerateLastMessage: () => void;@@ -507,6 +511,99 @@ interface ChatContextValue {const ChatCtx = createContext<ChatContextValue | null>(null);+function hydrateMessageAttachments(+ attachments: SessionMessage["attachments"],+): MessageAttachment[] {+ return Array.isArray(attachments)+ ? attachments.map((item) => ({+ type: item.type,+ filename: item.filename,+ base64: item.base64,+ url: item.url,+ mime_type: item.mime_type,+ id: item.id,+ extracted_text: item.extracted_text,+ }))+ : [];+}++function asRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function asStringArray(value: unknown): string[] {+ return Array.isArray(value)+ ? value.filter((item): item is string => typeof item === "string" && item.length > 0)+ : [];+}++function asMemoryReferences(value: unknown): MemoryReferencePayload {+ return asStringArray(value).filter(+ (item): item is "summary" | "profile" => item === "summary" || item === "profile",+ );+}++function asNotebookReferences(value: unknown): NotebookReferencePayload[] {+ if (!Array.isArray(value)) return [];+ return value.flatMap((item) => {+ const ref = asRecord(item);+ const notebookId = typeof ref?.notebook_id === "string" ? ref.notebook_id : "";+ const recordIds = asStringArray(ref?.record_ids);+ return notebookId && recordIds.length+ ? [{ notebook_id: notebookId, record_ids: recordIds }]+ : [];+ });+}++function asQuestionReferences(value: unknown): QuestionNotebookReferencePayload {+ return Array.isArray(value)+ ? value+ .map((item) => (typeof item === "number" ? item : Number(item)))+ .filter((item) => Number.isInteger(item))+ : [];+}++function hydrateRequestSnapshot(+ message: SessionMessage,+ content: string,+ attachments: MessageAttachment[],+): MessageRequestSnapshot | undefined {+ const metadata = asRecord(message.metadata);+ const stored = asRecord(metadata?.request_snapshot ?? metadata?.requestSnapshot);+ if (!stored) return undefined;++ const snapshot: MessageRequestSnapshot = {+ content: typeof stored.content === "string" ? stored.content : content,+ capability:+ typeof stored.capability === "string" ? stored.capability : message.capability || "",+ enabledTools: asStringArray(stored.enabledTools),+ knowledgeBases: asStringArray(stored.knowledgeBases),+ language: typeof stored.language === "string" ? stored.language : "en",+ ...(attachments.length ? { attachments } : {}),+ };++ const config = asRecord(stored.config);+ const notebookReferences = asNotebookReferences(stored.notebookReferences);+ const historyReferences = asStringArray(stored.historyReferences);+ const questionNotebookReferences = asQuestionReferences(+ stored.questionNotebookReferences,+ );+ const skills = asStringArray(stored.skills);+ const memoryReferences = asMemoryReferences(stored.memoryReferences);++ if (config && Object.keys(config).length) snapshot.config = config;+ if (notebookReferences.length) snapshot.notebookReferences = notebookReferences;+ if (historyReferences.length) snapshot.historyReferences = historyReferences;+ if (questionNotebookReferences.length) {+ snapshot.questionNotebookReferences = questionNotebookReferences;+ }+ if (skills.length) snapshot.skills = skills;+ if (memoryReferences.length) snapshot.memoryReferences = memoryReferences;+ return snapshot;+}+export function UnifiedChatProvider({children,}: {@@ -557,6 +654,8 @@ export function UnifiedChatProvider({const raw = normalizeMessageContent(message.content as unknown,);+ const attachments = hydrateMessageAttachments(message.attachments);+ const requestSnapshot = hydrateRequestSnapshot(message, raw, attachments);return {role: message.role,content:@@ -565,17 +664,8 @@ export function UnifiedChatProvider({: raw,capability: message.capability || "",events: Array.isArray(message.events) ? message.events : [],- attachments: Array.isArray(message.attachments)- ? message.attachments.map((item) => ({- type: item.type,- filename: item.filename,- base64: item.base64,- url: item.url,- mime_type: item.mime_type,- id: item.id,- extracted_text: item.extracted_text,- }))- : [],+ attachments,+ ...(requestSnapshot ? { requestSnapshot } : {}),};});},@@ -831,6 +921,7 @@ export function UnifiedChatProvider({options?: SendMessageOptions,questionNotebookReferences?: QuestionNotebookReferencePayload,skills?: string[],+ memoryReferences?: MemoryReferencePayload,) => {const msgAttachments = attachments?.map((a) => ({type: a.type,@@ -864,6 +955,8 @@ export function UnifiedChatProvider({(effectiveCapability === "deep_research" &&researchSources.includes("kb"));const effectiveSkills = replaySnapshot?.skills ?? skills;+ const effectiveMemoryReferences =+ replaySnapshot?.memoryReferences ?? memoryReferences;const requestSnapshot: MessageRequestSnapshot = replaySnapshot ?? {content,capability: effectiveCapability,@@ -882,6 +975,9 @@ export function UnifiedChatProvider({? { questionNotebookReferences: [...questionNotebookReferences] }: {}),...(effectiveSkills?.length ? { skills: [...effectiveSkills] } : {}),+ ...(effectiveMemoryReferences?.length+ ? { memoryReferences: [...effectiveMemoryReferences] }+ : {}),};if (options?.displayUserMessage !== false) {dispatch({@@ -919,6 +1015,9 @@ export function UnifiedChatProvider({? { question_notebook_references: questionNotebookReferences }: {}),...(effectiveSkills?.length ? { skills: effectiveSkills } : {}),+ ...(effectiveMemoryReferences?.length+ ? { memory_references: effectiveMemoryReferences }+ : {}),...(effectiveConfig && Object.keys(effectiveConfig).length > 0? { config: effectiveConfig }: {}),diff --git a/web/lib/message-content.ts b/web/lib/message-content.tsindex 80c79935a..05a4ac103 100644--- a/web/lib/message-content.ts+++ b/web/lib/message-content.ts@@ -1,16 +1,30 @@export type MessageContentItem = {type: string;text?: string;+ content?: string;+ message?: string;url?: string;alt?: string;};-export type RawMessageContent =- | string- | MessageContentItem[]- | null- | undefined- | unknown;+export type RawMessageContent = unknown;++function stringifyObject(value: Record<string, unknown>): string {+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+}++function normalizeObjectContent(item: Record<string, unknown>): string {+ for (const key of ["text", "content", "message", "alt"]) {+ const value = item[key];+ if (typeof value === "string" && value) return value;+ }+ if (item.type === "image" || item.type === "image_url") return "[image]";+ return stringifyObject(item);+}export function normalizeMessageContent(content: RawMessageContent): string {if (content == null) return "";@@ -19,14 +33,14 @@ export function normalizeMessageContent(content: RawMessageContent): string {return content.map((item) => {if (!item || typeof item !== "object") return String(item);- if (item.type === "image" || item.type === "image_url") {- return item.alt || item.text || "[image]";- }- return item.text ?? String(item);+ return normalizeObjectContent(item as Record<string, unknown>);}).filter(Boolean).join(" ");}+ if (typeof content === "object") {+ return normalizeObjectContent(content as Record<string, unknown>);+ }return String(content);}diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 68623bf12..4f671988d 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -18,6 +18,7 @@ export interface SessionMessage {id?: string;extracted_text?: string;}>;+ metadata?: Record<string, unknown>;created_at: number;}diff --git a/web/lib/space-items.ts b/web/lib/space-items.tsnew file mode 100644index 000000000..421e16f5f--- /dev/null+++ b/web/lib/space-items.ts@@ -0,0 +1,65 @@+"use client";++import {+ Brain,+ ClipboardList,+ History,+ NotebookPen,+ Wand2,+ type LucideIcon,+} from "lucide-react";++export type SpaceItemKey =+ | "chat_history"+ | "notebooks"+ | "question_bank"+ | "skills"+ | "memory";++export type SpaceMemoryFile = "summary" | "profile";++export interface SpaceItem {+ key: SpaceItemKey;+ href: string;+ label: string;+ description: string;+ icon: LucideIcon;+}++export const SPACE_ITEMS: SpaceItem[] = [+ {+ key: "chat_history",+ href: "/space/chat-history",+ label: "Chat History",+ description: "Review and reopen previous conversations.",+ icon: History,+ },+ {+ key: "notebooks",+ href: "/space/notebooks",+ label: "Notebooks",+ description: "Organize saved outputs from chat, research, Co-Writer, and more.",+ icon: NotebookPen,+ },+ {+ key: "question_bank",+ href: "/space/questions",+ label: "Question Bank",+ description: "Review and organize quiz questions across sessions.",+ icon: ClipboardList,+ },+ {+ key: "skills",+ href: "/space/skills",+ label: "Skills",+ description: "Behavior playbooks that guide chat responses.",+ icon: Wand2,+ },+ {+ key: "memory",+ href: "/space/memory",+ label: "Memory",+ description: "Long-form memory the assistant carries across sessions.",+ icon: Brain,+ },+];diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex cbc63942b..c1c7e646b 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1279,5 +1279,28 @@"Start from template": "Start from template","ago": "ago","Failed to load image.": "Failed to load image.",- "HTML": "HTML"+ "HTML": "HTML",+ "Skills Reference": "Skills Reference",+ "Select Skills": "Select Skills",+ "Pick Auto to let DeepTutor decide, or choose specific skills to apply.": "Pick Auto to let DeepTutor decide, or choose specific skills to apply.",+ "Let the model auto-select relevant skills for this turn.": "Let the model auto-select relevant skills for this turn.",+ "Search skills by name, description, or tag": "Search skills by name, description, or tag",+ "No matching skills found.": "No matching skills found.",+ "1 skill selected": "1 skill selected",+ "{{n}} skills selected": "{{n}} skills selected",+ "Auto skill selection enabled": "Auto skill selection enabled",+ "Use Auto Skills": "Use Auto Skills",+ "Use Selected Skills ({{n}})": "Use Selected Skills ({{n}})",+ "{{n}} sessions selected": "{{n}} sessions selected",+ "Use Selected Sessions ({{n}})": "Use Selected Sessions ({{n}})",+ "{{n}} questions selected": "{{n}} questions selected",+ "Use Selected Questions ({{n}})": "Use Selected Questions ({{n}})",+ "Memory Reference": "Memory Reference",+ "Select Memory": "Select Memory",+ "Choose which long-form memory artifacts to attach to this turn.": "Choose which long-form memory artifacts to attach to this turn.",+ "Inject the assistant's running summary of past learning sessions.": "Inject the assistant's running summary of past learning sessions.",+ "Inject the learner profile (preferences, goals, background).": "Inject the learner profile (preferences, goals, background).",+ "1 memory artifact selected": "1 memory artifact selected",+ "{{n}} memory artifacts selected": "{{n}} memory artifacts selected",+ "Use Selected Memory ({{n}})": "Use Selected Memory ({{n}})"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 95b6d95dc..0e7b9240e 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1279,5 +1279,28 @@"Start from template": "从模板开始","ago": "前","Failed to load image.": "图片加载失败。",- "HTML": "HTML"+ "HTML": "HTML",+ "Skills Reference": "技能引用",+ "Select Skills": "选择技能",+ "Pick Auto to let DeepTutor decide, or choose specific skills to apply.": "选择「Auto」让 DeepTutor 自动判断,或挑选要应用的具体技能。",+ "Let the model auto-select relevant skills for this turn.": "让模型为本轮对话自动挑选相关技能。",+ "Search skills by name, description, or tag": "按名称、描述或标签搜索技能",+ "No matching skills found.": "未找到匹配的技能。",+ "1 skill selected": "已选 1 个技能",+ "{{n}} skills selected": "已选 {{n}} 个技能",+ "Auto skill selection enabled": "已启用技能自动选择",+ "Use Auto Skills": "使用自动技能",+ "Use Selected Skills ({{n}})": "使用所选技能({{n}})",+ "{{n}} sessions selected": "已选 {{n}} 个会话",+ "Use Selected Sessions ({{n}})": "使用所选会话({{n}})",+ "{{n}} questions selected": "已选择 {{n}} 道题目",+ "Use Selected Questions ({{n}})": "使用所选题目({{n}})",+ "Memory Reference": "记忆引用",+ "Select Memory": "选择记忆",+ "Choose which long-form memory artifacts to attach to this turn.": "选择本轮要附加的长期记忆条目。",+ "Inject the assistant's running summary of past learning sessions.": "注入助手对过往学习会话的累积摘要。",+ "Inject the learner profile (preferences, goals, background).": "注入学习者画像(偏好、目标、背景)。",+ "1 memory artifact selected": "已选 1 项记忆",+ "{{n}} memory artifacts selected": "已选 {{n}} 项记忆",+ "Use Selected Memory ({{n}})": "使用所选记忆({{n}})"}diff --git a/web/next-env.d.ts b/web/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/web/next-env.d.ts+++ b/web/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/web/tests/message-content.test.ts b/web/tests/message-content.test.tsnew file mode 100644index 000000000..9bb29d88c--- /dev/null+++ b/web/tests/message-content.test.ts@@ -0,0 +1,25 @@+import test from "node:test";+import assert from "node:assert/strict";+import { normalizeMessageContent, truncateText } from "../lib/message-content";++test("normalizeMessageContent joins multimodal content parts", () => {+ assert.equal(+ normalizeMessageContent([+ { type: "text", text: "Here is the diagram" },+ { type: "image" },+ ]),+ "Here is the diagram [image]",+ );+});++test("normalizeMessageContent renders object payloads without React-unsafe objects", () => {+ assert.equal(+ normalizeMessageContent({ type: "custom", value: 42 }),+ '{"type":"custom","value":42}',+ );+});++test("truncateText preserves short strings and ellipsizes long strings", () => {+ assert.equal(truncateText("short", 10), "short");+ assert.equal(truncateText("abcdefghij", 5), "abcde\u2026");+});