DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: add selection tutor and course workspaces
diffaudit-review3709c9e85438
diff --git a/deeptutor/agents/chat/prompt_blocks.py b/deeptutor/agents/chat/prompt_blocks.pyindex 73b02daf8..34ab65048 100644--- a/deeptutor/agents/chat/prompt_blocks.py+++ b/deeptutor/agents/chat/prompt_blocks.py@@ -76,6 +76,8 @@ class ChatPromptAssembler:# Capability playbooks sit high so they frame the whole turn when active;# empty blocks are omitted by ``system_prompt``'s join.blocks.extend(capability_blocks or [])+ if context.sidebar_context:+ blocks.append(PromptBlock("sidebar_tutor_context", context.sidebar_context))if context.persona_context:blocks.append(PromptBlock("persona_style", context.persona_context))partner_policy = self._partner_turn_policy(context)diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex bc10bea7d..edaf91865 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -365,6 +365,7 @@ from deeptutor.api.routers import (capabilities_settings,chat,co_writer,+ courses,dashboard,imports,knowledge,@@ -465,6 +466,7 @@ app.include_router(app.include_router(sessions.router, prefix="/api/v1/sessions", tags=["sessions"], dependencies=_auth)+app.include_router(courses.router, prefix="/api/v1/courses", tags=["courses"], dependencies=_auth)app.include_router(question_notebook.router,prefix="/api/v1/question-notebook",diff --git a/deeptutor/api/routers/courses.py b/deeptutor/api/routers/courses.pynew file mode 100644index 000000000..6d9dacfed--- /dev/null+++ b/deeptutor/api/routers/courses.py@@ -0,0 +1,87 @@+"""Study-course CRUD and session organization endpoints."""++from __future__ import annotations++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from deeptutor.services.courses import (+ COURSE_COLORS,+ CourseNameConflictError,+ CourseNotFoundError,+ get_course_service,+)+from deeptutor.services.session import get_session_store++router = APIRouter()+++class CreateCourseRequest(BaseModel):+ name: str = Field(..., min_length=1, max_length=60)+ description: str = Field(default="", max_length=300)+ color: str = ""+++class UpdateCourseRequest(BaseModel):+ name: str | None = Field(default=None, min_length=1, max_length=60)+ description: str | None = Field(default=None, max_length=300)+ color: str | None = None+++async def list_courses() -> dict[str, object]:+ return {+ "courses": [course.to_dict() for course in get_course_service().list_courses()],+ "colors": list(COURSE_COLORS),+ }+++async def create_course(payload: CreateCourseRequest) -> dict[str, object]:+ try:+ course = get_course_service().create(**payload.model_dump())+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except CourseNameConflictError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"course": course.to_dict()}++[email protected]("/{course_id}")+async def update_course(course_id: str, payload: UpdateCourseRequest) -> dict[str, object]:+ try:+ course = get_course_service().update(+ course_id,+ **payload.model_dump(exclude_unset=True),+ )+ except CourseNotFoundError as exc:+ raise HTTPException(status_code=404, detail="Course not found") from exc+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except CourseNameConflictError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"course": course.to_dict()}++[email protected]("/{course_id}")+async def delete_course(course_id: str) -> dict[str, object]:+ service = get_course_service()+ try:+ service.get(course_id)+ except CourseNotFoundError as exc:+ raise HTTPException(status_code=404, detail="Course not found") from exc++ # Course deletion is non-destructive: conversations become unclassified.+ store = get_session_store()+ offset = 0+ while True:+ sessions = await store.list_sessions(limit=200, offset=offset)+ for session in sessions:+ preferences = session.get("preferences") or {}+ if str(preferences.get("course_id") or "") == course_id:+ await store.update_session_preferences(session["session_id"], {"course_id": ""})+ if len(sessions) < 200:+ break+ offset += len(sessions)+ service.delete(course_id)+ return {"deleted": True, "course_id": course_id}diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.pyindex a72758f95..09aa28baf 100644--- a/deeptutor/api/routers/sessions.py+++ b/deeptutor/api/routers/sessions.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport asyncioimport logging-from typing import Any+from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, Queryfrom pydantic import BaseModel, Field, field_validator@@ -34,6 +34,16 @@ class BranchSelectionRequest(BaseModel):selected_branches: dict[str, int] = Field(default_factory=dict)+class SessionOrganizationRequest(BaseModel):+ """User-controlled organization metadata stored with the conversation."""++ course_id: str | None = None+ parent_session_id: str | None = None+ session_kind: Literal["chat", "selection_tutor"] | None = None+ pinned: bool | None = None+ archived: bool | None = None++class QuizResultItem(BaseModel):question_id: str = ""question: str = Field(..., min_length=1)@@ -152,6 +162,60 @@ async def rename_session(session_id: str, payload: SessionRenameRequest):return {"session": session}[email protected]("/{session_id}/organization")+async def update_session_organization(session_id: str, payload: SessionOrganizationRequest):+ store = get_session_store()+ session = await store.get_session(session_id)+ if session is None:+ raise HTTPException(status_code=404, detail="Session not found")++ updates: dict[str, Any] = {}+ fields = payload.model_fields_set+ if "course_id" in fields:+ course_id = str(payload.course_id or "").strip()+ if course_id:+ from deeptutor.services.courses import CourseNotFoundError, get_course_service++ try:+ get_course_service().get(course_id)+ except CourseNotFoundError as exc:+ raise HTTPException(status_code=404, detail="Course not found") from exc+ updates["course_id"] = course_id+ if "parent_session_id" in fields:+ parent_id = str(payload.parent_session_id or "").strip()+ if parent_id == session_id:+ raise HTTPException(status_code=400, detail="A session cannot be its own parent")+ if parent_id and await store.get_session(parent_id) is None:+ raise HTTPException(status_code=404, detail="Parent session not found")+ updates["parent_session_id"] = parent_id+ if "session_kind" in fields:+ updates["session_kind"] = payload.session_kind or "chat"+ if "pinned" in fields:+ updates["pinned"] = bool(payload.pinned)+ if "archived" in fields:+ updates["archived"] = bool(payload.archived)++ if updates:+ await store.update_session_preferences(session_id, updates)+ cascade_updates = {key: updates[key] for key in ("course_id", "archived") if key in updates}+ if cascade_updates:+ # Selected-text tutor threads stay with their source conversation.+ offset = 0+ while True:+ candidates = await store.list_sessions(limit=200, offset=offset)+ for candidate in candidates:+ prefs = candidate.get("preferences") or {}+ if str(prefs.get("parent_session_id") or "") == session_id:+ await store.update_session_preferences(+ candidate["session_id"], cascade_updates+ )+ if len(candidates) < 200:+ break+ offset += len(candidates)+ refreshed = await store.get_session(session_id)+ return {"session": refreshed}++@router.delete("/{session_id}")async def delete_session(session_id: str):store = get_session_store()diff --git a/deeptutor/core/context.py b/deeptutor/core/context.pyindex 5c2f9a350..2f159bab1 100644--- a/deeptutor/core/context.py+++ b/deeptutor/core/context.py@@ -56,6 +56,8 @@ class UnifiedContext:persona_context: Selected persona's instructions, eagerly injectedinto the system prompt (a persona must shape the voice from thefirst token; empty when no persona is active).+ sidebar_context: High-priority grounding for an isolated sidebar tutor+ (for example, the exact passage selected in another chat).skills_manifest: System-prompt Skills block — one line percapability skill visible to this user, plus any ``always``skills' full bodies. The model pulls full skill content on@@ -79,6 +81,7 @@ class UnifiedContext:language: str = "en"memory_context: str = ""persona_context: str = ""+ sidebar_context: str = ""skills_manifest: str = ""source_manifest: str = ""metadata: dict[str, Any] = field(default_factory=dict)diff --git a/deeptutor/runtime/request_contracts.py b/deeptutor/runtime/request_contracts.pyindex 883ce92d4..b280dabfb 100644--- a/deeptutor/runtime/request_contracts.py+++ b/deeptutor/runtime/request_contracts.py@@ -18,6 +18,8 @@ from deeptutor.agents.research.request_config import (_RUNTIME_ONLY_KEYS = {"_persist_user_message","followup_question_context",+ "selection_tutor_context",+ "_course_id",# Per-turn subagent consult budget (composer stepper). Not part of any# capability's public config schema; stripped here so it never trips# ``extra="forbid"`` (turn_runtime carries it through to the turn config).diff --git a/deeptutor/services/courses.py b/deeptutor/services/courses.pynew file mode 100644index 000000000..62bb33f2c--- /dev/null+++ b/deeptutor/services/courses.py@@ -0,0 +1,202 @@+"""Per-user study course registry for organizing learning resources."""++from __future__ import annotations++from dataclasses import asdict, dataclass+import json+from pathlib import Path+import threading+import time+import uuid++from deeptutor.services.file_io import atomic_write_json+from deeptutor.services.path_service import get_path_service++COURSE_COLORS: tuple[str, ...] = (+ "#C65D2E",+ "#3F6F8F",+ "#4F7655",+ "#8A6543",+ "#705B8E",+ "#A04F5F",+)+++class CourseNotFoundError(Exception):+ pass+++class CourseNameConflictError(Exception):+ pass+++@dataclass(slots=True)+class StudyCourse:+ id: str+ name: str+ description: str+ color: str+ created_at: float+ updated_at: float++ def to_dict(self) -> dict[str, object]:+ return asdict(self)+++_LOCKS_GUARD = threading.Lock()+_LOCKS: dict[str, threading.RLock] = {}+++def _lock_for(path: Path) -> threading.RLock:+ key = str(path.resolve())+ with _LOCKS_GUARD:+ lock = _LOCKS.get(key)+ if lock is None:+ lock = threading.RLock()+ _LOCKS[key] = lock+ return lock+++class CourseService:+ """Small durable registry stored inside the active user's workspace."""++ def __init__(self, root: Path | None = None) -> None:+ self.root = root or (get_path_service().get_workspace_dir() / "courses")+ self.index_file = self.root / "courses.json"+ self._lock = _lock_for(self.index_file)++ @staticmethod+ def _clean_name(value: str) -> str:+ name = " ".join(str(value or "").split()).strip()+ if not name:+ raise ValueError("Course name is required.")+ return name[:60]++ @staticmethod+ def _clean_description(value: str) -> str:+ return str(value or "").strip()[:300]++ @staticmethod+ def _clean_color(value: str, fallback_index: int = 0) -> str:+ candidate = str(value or "").strip().upper()+ allowed = {color.upper(): color for color in COURSE_COLORS}+ return allowed.get(candidate, COURSE_COLORS[fallback_index % len(COURSE_COLORS)])++ def _load(self) -> list[StudyCourse]:+ try:+ raw = json.loads(self.index_file.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return []+ except (OSError, json.JSONDecodeError):+ return []+ rows = raw.get("courses", []) if isinstance(raw, dict) else []+ courses: list[StudyCourse] = []+ for index, row in enumerate(rows if isinstance(rows, list) else []):+ if not isinstance(row, dict):+ continue+ course_id = str(row.get("id") or "").strip()+ name = str(row.get("name") or "").strip()+ if not course_id or not name:+ continue+ created_at = float(row.get("created_at") or time.time())+ courses.append(+ StudyCourse(+ id=course_id,+ name=name[:60],+ description=self._clean_description(str(row.get("description") or "")),+ color=self._clean_color(str(row.get("color") or ""), index),+ created_at=created_at,+ updated_at=float(row.get("updated_at") or created_at),+ )+ )+ return courses++ def _save(self, courses: list[StudyCourse]) -> None:+ atomic_write_json(self.index_file, {"courses": [course.to_dict() for course in courses]})++ @staticmethod+ def _assert_unique(courses: list[StudyCourse], name: str, except_id: str = "") -> None:+ folded = name.casefold()+ if any(course.id != except_id and course.name.casefold() == folded for course in courses):+ raise CourseNameConflictError(f"A course named {name!r} already exists.")++ def list_courses(self) -> list[StudyCourse]:+ with self._lock:+ return sorted(+ self._load(), key=lambda course: (course.created_at, course.name.casefold())+ )++ def get(self, course_id: str) -> StudyCourse:+ target = str(course_id or "").strip()+ with self._lock:+ for course in self._load():+ if course.id == target:+ return course+ raise CourseNotFoundError(target)++ def create(self, *, name: str, description: str = "", color: str = "") -> StudyCourse:+ with self._lock:+ courses = self._load()+ clean_name = self._clean_name(name)+ self._assert_unique(courses, clean_name)+ now = time.time()+ course = StudyCourse(+ id=f"course_{uuid.uuid4().hex[:12]}",+ name=clean_name,+ description=self._clean_description(description),+ color=self._clean_color(color, len(courses)),+ created_at=now,+ updated_at=now,+ )+ courses.append(course)+ self._save(courses)+ return course++ def update(+ self,+ course_id: str,+ *,+ name: str | None = None,+ description: str | None = None,+ color: str | None = None,+ ) -> StudyCourse:+ target = str(course_id or "").strip()+ with self._lock:+ courses = self._load()+ course = next((item for item in courses if item.id == target), None)+ if course is None:+ raise CourseNotFoundError(target)+ if name is not None:+ clean_name = self._clean_name(name)+ self._assert_unique(courses, clean_name, except_id=target)+ course.name = clean_name+ if description is not None:+ course.description = self._clean_description(description)+ if color is not None:+ course.color = self._clean_color(color)+ course.updated_at = time.time()+ self._save(courses)+ return course++ def delete(self, course_id: str) -> None:+ target = str(course_id or "").strip()+ with self._lock:+ courses = self._load()+ kept = [course for course in courses if course.id != target]+ if len(kept) == len(courses):+ raise CourseNotFoundError(target)+ self._save(kept)+++def get_course_service() -> CourseService:+ return CourseService()+++__all__ = [+ "COURSE_COLORS",+ "CourseNameConflictError",+ "CourseNotFoundError",+ "CourseService",+ "StudyCourse",+ "get_course_service",+]diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 96df1a6eb..2986f026c 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -497,6 +497,25 @@ def _extract_followup_question_context(}+def _extract_selection_tutor_context(+ config: dict[str, Any] | None,+) -> dict[str, str] | None:+ """Remove and normalize context for the selected-text side tutor."""+ if not isinstance(config, dict):+ return None+ raw = config.pop("selection_tutor_context", None)+ if not isinstance(raw, dict):+ return None++ selected_text = _clip_text(str(raw.get("selected_text", "") or "").strip())+ if not selected_text:+ return None+ return {+ "selected_text": selected_text,+ "parent_session_id": str(raw.get("parent_session_id", "") or "").strip(),+ }++def _extract_persist_user_message(config: dict[str, Any] | None) -> bool:if not isinstance(config, dict):return True@@ -657,6 +676,43 @@ def _format_followup_question_context(context: dict[str, Any], language: str = "return "\n".join(lines).strip()+def _format_selection_tutor_context(context: dict[str, str], language: str = "en") -> str:+ selected_text = context.get("selected_text", "").strip()+ parent_session_id = context.get("parent_session_id", "").strip() or "(none)"+ if str(language or "en").lower().startswith("zh"):+ return "\n".join(+ [+ "你是侧栏中的“小老师”,负责回答学习者对一段选中聊天内容的追问。",+ "把选中内容当作当前问题的直接指代和首要上下文:解释概念、拆解推理、补充例子,并指出其中可能的歧义或错误。",+ "不要读取、引用或写入全局记忆;不要把用户问题里的“这个/它/上述内容”解释成记忆系统。",+ "如果先前回答偏离了选中内容,请明确纠正并回到选中内容本身。",+ "回答当前问题时要简明、循序渐进;选中内容没有提供的信息不要臆造。",+ "后续对话要保持与这段内容的连续性,但用户明确转向相关主题时也可以正常扩展。",+ "",+ "[选中内容]",+ selected_text,+ "",+ f"来源会话:{parent_session_id}",+ ]+ ).strip()++ return "\n".join(+ [+ "You are the Little Tutor in a sidebar, answering questions about selected chat text.",+ "Treat the selected passage as the direct referent of the current question and its primary context: explain concepts, unpack reasoning, add examples, and flag ambiguity or mistakes.",+ "Do not read, cite, or write global memory. Never reinterpret words such as 'this', 'it', or 'the above' as referring to the memory system.",+ "If an earlier answer drifted away from the selection, correct it explicitly and return to the selected passage.",+ "Answer the current question clearly and step by step; do not invent information absent from the passage.",+ "Maintain continuity with this passage across later turns, while allowing explicit related-topic expansion.",+ "",+ "[Selected passage]",+ selected_text,+ "",+ f"Source session: {parent_session_id}",+ ]+ ).strip()++@dataclassclass _LiveSubscriber:queue: asyncio.Queue[dict[str, Any]]@@ -827,6 +883,8 @@ class TurnRuntimeManager:"_regenerated_from_message_id","_superseded_turn_id","followup_question_context",+ "selection_tutor_context",+ "_course_id",# Per-turn subagent consult budget (composer stepper). Not part of# any capability's public config schema, so it rides as a runtime# key — stripped before validation, merged back into the turn config@@ -977,6 +1035,34 @@ class TurnRuntimeManager:"knowledge_bases": list(payload.get("knowledge_bases") or []),"language": str(payload.get("language") or "en"),}+ requested_course_id = str(runtime_only_config.get("_course_id") or "").strip()+ if requested_course_id:+ from deeptutor.services.courses import (+ CourseNotFoundError,+ get_course_service,+ )++ try:+ get_course_service().get(requested_course_id)+ except CourseNotFoundError:+ requested_course_id = ""+ if "_course_id" in runtime_only_config:+ preference_update["course_id"] = requested_course_id++ raw_selection_context = runtime_only_config.get("selection_tutor_context")+ if isinstance(raw_selection_context, dict):+ parent_session_id = str(raw_selection_context.get("parent_session_id") or "").strip()+ if parent_session_id and parent_session_id != session["id"]:+ parent_session = await self.store.get_session(parent_session_id)+ if parent_session is not None:+ parent_preferences = parent_session.get("preferences") or {}+ preference_update.update(+ {+ "parent_session_id": parent_session_id,+ "session_kind": "selection_tutor",+ "course_id": str(parent_preferences.get("course_id") or ""),+ }+ )if llm_selection:preference_update["llm_selection"] = llm_selectionif persona_explicit:@@ -1468,6 +1554,8 @@ class TurnRuntimeManager:request_config = dict(payload.get("config", {}) or {})followup_question_context = _extract_followup_question_context(request_config)+ selection_tutor_context = _extract_selection_tutor_context(request_config)+ request_config.pop("_course_id", None)persist_user_message = _extract_persist_user_message(request_config)is_regenerate = _extract_regenerate_flag(request_config)request_config.pop("_regenerated_from_message_id", None)@@ -1582,20 +1670,17 @@ class TurnRuntimeManager:for r in attachment_records]- if followup_question_context:- existing_messages = await self.store.get_messages_for_context(- session_id, leaf_message_id=branch_parent_id+ sidebar_system_context = ""+ if selection_tutor_context:+ sidebar_system_context = _format_selection_tutor_context(+ selection_tutor_context,+ language=str(payload.get("language", "en") or "en"),+ )+ elif followup_question_context:+ sidebar_system_context = _format_followup_question_context(+ followup_question_context,+ language=str(payload.get("language", "en") or "en"),)- if not existing_messages:- await self.store.add_message(- session_id=session_id,- role="system",- content=_format_followup_question_context(- followup_question_context,- language=str(payload.get("language", "en") or "en"),- ),- capability=capability_name or "chat",- )llm_config, llm_scope_token = activate_llm_selection(payload.get("llm_selection"))builder = ContextBuilder(self.store)@@ -1870,6 +1955,9 @@ class TurnRuntimeManager:user_message=effective_user_message,conversation_history=conversation_history,enabled_tools=payload.get("tools"),+ # Selected-text tutoring must stay isolated from global+ # memory and every other auto-mounted built-in.+ allowed_builtin_tools=[] if selection_tutor_context else None,active_capability=payload.get("capability"),knowledge_bases=payload.get("knowledge_bases", []),attachments=attachments,@@ -1877,6 +1965,7 @@ class TurnRuntimeManager:language=payload.get("language", "en"),memory_context=memory_context,persona_context=persona_context,+ sidebar_context=sidebar_system_context,skills_manifest=skills_manifest,source_manifest=source_manifest_text,metadata={@@ -1886,6 +1975,7 @@ class TurnRuntimeManager:"history_budget": history_result.budget,"turn_id": turn_id,"question_followup_context": followup_question_context or {},+ "selection_tutor_context": selection_tutor_context or {},"notebook_references": notebook_references,"history_references": history_references,"question_notebook_references": question_notebook_references,diff --git a/tests/agents/chat/test_language_prompts.py b/tests/agents/chat/test_language_prompts.pyindex 537223a45..44b661e4d 100644--- a/tests/agents/chat/test_language_prompts.py+++ b/tests/agents/chat/test_language_prompts.py@@ -136,6 +136,7 @@ def test_prompt_blocks_include_localized_optional_context() -> None:}ctx = UnifiedContext(user_message="解释光合作用",+ sidebar_context="[选中内容]\n把代码和静态数据加载进内存",persona_context="用苏格拉底式提问",memory_context="学生喜欢例子",)@@ -145,8 +146,12 @@ def test_prompt_blocks_include_localized_optional_context() -> None:names = [block.name for block in blocks]assert names[:4] == ["general", "runtime_context", "runtime_policy", "loop"]+ assert "sidebar_tutor_context" in namesassert "persona_style" in namesassert "memory" in namesassert "workspace" in namesassert assembler.user_message(context=ctx) == "用户说:解释光合作用"assert assembler.finish_exhausted_instruction() == "预算已用完,请直接回答。"+ system_prompt = assembler.render(blocks)+ assert "## sidebar_tutor_context" in system_prompt+ assert "把代码和静态数据加载进内存" in system_promptdiff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.pyindex 110373c47..a56f228a1 100644--- a/tests/services/session/test_turn_runtime.py+++ b/tests/services/session/test_turn_runtime.py@@ -11,7 +11,9 @@ from deeptutor.services.session.turn_runtime import (_extract_followup_question_context,_extract_memory_references,_extract_persist_user_message,+ _extract_selection_tutor_context,_format_followup_question_context,+ _format_selection_tutor_context,_narration_marker_call_id,_should_capture_assistant_content,_stamp_ask_user_content_offset,@@ -238,6 +240,35 @@ class TestExtractFollowupQuestionContext:assert "C" not in result["options"] # empty value excluded+class TestSelectionTutorContext:+ def test_extracts_and_pops_valid_context(self) -> None:+ config = {+ "selection_tutor_context": {+ "selected_text": " fork() returns in two processes. ",+ "parent_session_id": "main-1",+ }+ }+ result = _extract_selection_tutor_context(config)+ assert result == {+ "selected_text": "fork() returns in two processes.",+ "parent_session_id": "main-1",+ }+ assert "selection_tutor_context" not in config++ def test_rejects_empty_selection(self) -> None:+ config = {"selection_tutor_context": {"selected_text": " "}}+ assert _extract_selection_tutor_context(config) is None++ def test_formats_bilingual_tutor_grounding(self) -> None:+ context = {"selected_text": "fork() returns twice", "parent_session_id": "main-1"}+ zh = _format_selection_tutor_context(context, language="zh")+ en = _format_selection_tutor_context(context, language="en")+ assert "小老师" in zh+ assert "fork() returns twice" in zh+ assert "Little Tutor" in en+ assert "main-1" in en++# ---------------------------------------------------------------------------# _extract_persist_user_message# ---------------------------------------------------------------------------diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.pyindex 1cc6ce73d..6bd530df7 100644--- a/tests/services/session/test_turn_runtime_subscribe.py+++ b/tests/services/session/test_turn_runtime_subscribe.py@@ -8,6 +8,7 @@ import pytestfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.learning.storage import LearningStore+from deeptutor.services.courses import CourseServicefrom deeptutor.services.session.sqlite_store import SQLiteSessionStorefrom deeptutor.services.session.turn_runtime import (TurnRuntimeManager,@@ -175,6 +176,121 @@ async def test_start_turn_clears_orphan_running_turn_before_create(assert persisted["status"] == "failed"+async def test_start_turn_preserves_selection_tutor_runtime_context(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Selected text must survive public config validation into turn execution."""++ store = SQLiteSessionStore(tmp_path / "selection-tutor.db")+ runtime = TurnRuntimeManager(store)++ async def _noop_run_turn(_execution):+ return None++ monkeypatch.setattr(runtime, "_run_turn", _noop_run_turn)++ selected_context = {+ "selected_text": "把代码和静态数据加载进内存",+ "parent_session_id": "main-session",+ }+ _, turn = await runtime.start_turn(+ {+ "type": "start_turn",+ "session_id": None,+ "capability": "chat",+ "content": "内存不会爆炸吗?",+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "zh",+ "config": {"selection_tutor_context": selected_context},+ }+ )++ execution = runtime._executions[turn["id"]]+ assert execution.payload["config"]["selection_tutor_context"] == selected_context+++async def test_start_turn_persists_requested_course(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ store = SQLiteSessionStore(tmp_path / "course-chat.db")+ runtime = TurnRuntimeManager(store)+ course_service = CourseService(tmp_path / "courses")+ course = course_service.create(name="Operating Systems")++ monkeypatch.setattr("deeptutor.services.courses.get_course_service", lambda: course_service)++ async def _noop_run_turn(_execution):+ return None++ monkeypatch.setattr(runtime, "_run_turn", _noop_run_turn)++ session, _ = await runtime.start_turn(+ {+ "type": "start_turn",+ "session_id": None,+ "capability": "chat",+ "content": "Explain virtual memory",+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {"_course_id": course.id},+ }+ )++ persisted = await store.get_session(session["id"])+ assert persisted is not None+ assert persisted["preferences"]["course_id"] == course.id+++async def test_selection_tutor_inherits_parent_course(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ store = SQLiteSessionStore(tmp_path / "course-tutor.db")+ runtime = TurnRuntimeManager(store)+ course_service = CourseService(tmp_path / "courses")+ course = course_service.create(name="Operating Systems")+ parent = await store.ensure_session(None)+ await store.update_session_preferences(parent["id"], {"course_id": course.id})++ monkeypatch.setattr("deeptutor.services.courses.get_course_service", lambda: course_service)++ async def _noop_run_turn(_execution):+ return None++ monkeypatch.setattr(runtime, "_run_turn", _noop_run_turn)++ child, _ = await runtime.start_turn(+ {+ "type": "start_turn",+ "session_id": None,+ "capability": "chat",+ "content": "Will memory explode?",+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {+ "selection_tutor_context": {+ "selected_text": "Load code and static data into memory",+ "parent_session_id": parent["id"],+ }+ },+ }+ )++ persisted = await store.get_session(child["id"])+ assert persisted is not None+ assert persisted["preferences"]["course_id"] == course.id+ assert persisted["preferences"]["parent_session_id"] == parent["id"]+ assert persisted["preferences"]["session_kind"] == "selection_tutor"++@pytest.mark.asyncioasync def test_reconnect_after_turn_completion_still_carries_message_ids(monkeypatch: pytest.MonkeyPatch, tmp_pathdiff --git a/tests/services/test_courses.py b/tests/services/test_courses.pynew file mode 100644index 000000000..b7318c78d--- /dev/null+++ b/tests/services/test_courses.py@@ -0,0 +1,59 @@+from __future__ import annotations++import json++import pytest++from deeptutor.services.courses import (+ COURSE_COLORS,+ CourseNameConflictError,+ CourseNotFoundError,+ CourseService,+)+++def test_course_registry_round_trip_and_atomic_persistence(tmp_path) -> None:+ service = CourseService(tmp_path / "courses")++ operating_systems = service.create(+ name=" Operating Systems ",+ description="Processes and memory",+ color=COURSE_COLORS[1],+ )+ security = service.create(name="Network Security")++ assert operating_systems.name == "Operating Systems"+ assert operating_systems.color == COURSE_COLORS[1]+ assert security.color == COURSE_COLORS[1]+ assert [course.name for course in service.list_courses()] == [+ "Operating Systems",+ "Network Security",+ ]++ updated = service.update(+ operating_systems.id,+ description="Processes, memory, and filesystems",+ color=COURSE_COLORS[3],+ )+ assert updated.description == "Processes, memory, and filesystems"+ assert service.get(operating_systems.id).color == COURSE_COLORS[3]++ stored = json.loads(service.index_file.read_text(encoding="utf-8"))+ assert len(stored["courses"]) == 2++ service.delete(security.id)+ assert [course.id for course in service.list_courses()] == [operating_systems.id]+ with pytest.raises(CourseNotFoundError):+ service.get(security.id)+++def test_course_names_are_unique_case_insensitively(tmp_path) -> None:+ service = CourseService(tmp_path / "courses")+ course = service.create(name="Operating Systems")++ with pytest.raises(CourseNameConflictError):+ service.create(name="operating systems")++ security = service.create(name="Network Security")+ with pytest.raises(CourseNameConflictError):+ service.update(security.id, name=course.name)diff --git a/web/app/(utility)/space/courses/[courseId]/page.tsx b/web/app/(utility)/space/courses/[courseId]/page.tsxnew file mode 100644index 000000000..5c03048d4--- /dev/null+++ b/web/app/(utility)/space/courses/[courseId]/page.tsx@@ -0,0 +1,314 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import Link from "next/link";+import { useParams, useRouter } from "next/navigation";+import {+ Archive,+ BookOpen,+ ClipboardList,+ GraduationCap,+ MessageSquarePlus,+ MoreHorizontal,+ NotebookPen,+ Pencil,+ Trash2,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import CourseDialog from "@/components/courses/CourseDialog";+import OrganizedSessionList from "@/components/courses/OrganizedSessionList";+import { ConfirmDialog } from "@/components/ui/ConfirmDialog";+import {+ deleteCourse,+ listCourses,+ updateCourse,+ type StudyCourse,+} from "@/lib/courses-api";+import {+ deleteSession,+ listAllSessions,+ updateSessionOrganization,+ updateSessionTitle,+ type SessionOrganizationPatch,+ type SessionSummary,+} from "@/lib/session-api";++export default function CourseDetailPage() {+ const { t } = useTranslation();+ const router = useRouter();+ const params = useParams<{ courseId: string }>();+ const courseId = String(params.courseId || "");+ const [course, setCourse] = useState<StudyCourse | null>(null);+ const [courses, setCourses] = useState<StudyCourse[]>([]);+ const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [loading, setLoading] = useState(true);+ const [editOpen, setEditOpen] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);+ const [menuOpen, setMenuOpen] = useState(false);++ const load = useCallback(async () => {+ setLoading(true);+ try {+ const [nextCourses, nextSessions] = await Promise.all([+ listCourses({ force: true }),+ listAllSessions({ force: true }),+ ]);+ setCourses(nextCourses);+ setCourse(nextCourses.find((item) => item.id === courseId) ?? null);+ setSessions(nextSessions);+ } finally {+ setLoading(false);+ }+ }, [courseId]);++ useEffect(() => {+ void load();+ }, [load]);++ const courseSessions = useMemo(+ () =>+ sessions.filter((session) => session.preferences?.course_id === courseId),+ [courseId, sessions],+ );+ const activeSessions = useMemo(+ () => courseSessions.filter((session) => !session.preferences?.archived),+ [courseSessions],+ );+ const archivedSessions = useMemo(+ () => courseSessions.filter((session) => session.preferences?.archived),+ [courseSessions],+ );++ const patchSession = useCallback(+ async (sessionId: string, patch: SessionOrganizationPatch) => {+ await updateSessionOrganization(sessionId, patch);+ await load();+ },+ [load],+ );++ const renameSession = useCallback(+ async (sessionId: string, title: string) => {+ await updateSessionTitle(sessionId, title);+ await load();+ },+ [load],+ );++ const removeSession = useCallback(+ async (sessionId: string) => {+ if (!window.confirm(t("Delete this chat?"))) return;+ await deleteSession(sessionId);+ await load();+ },+ [load, t],+ );++ if (loading) {+ return (+ <div className="space-y-4" aria-label={t("Loading course")}>+ <div className="h-10 w-64 animate-pulse rounded bg-[var(--muted)]" />+ <div className="h-48 animate-pulse rounded-2xl bg-[var(--card)]" />+ </div>+ );+ }++ if (!course) {+ return (+ <div className="py-16 text-center">+ <BookOpen className="mx-auto text-[var(--muted-foreground)]" />+ <h1 className="mt-4 font-serif text-xl font-semibold">+ {t("Course not found")}+ </h1>+ <Link+ href="/space"+ className="mt-3 inline-block text-sm text-[var(--primary)]"+ >+ {t("Back to Learning Space")}+ </Link>+ </div>+ );+ }++ const rootCount = activeSessions.filter(+ (session) => !session.preferences?.parent_session_id,+ ).length;++ return (+ <div>+ <header className="relative overflow-visible rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 pl-8">+ <span+ className="absolute inset-y-0 left-0 w-2 rounded-l-2xl"+ style={{ backgroundColor: course.color }}+ aria-hidden+ />+ <div className="flex items-start justify-between gap-5">+ <div className="min-w-0">+ <p className="text-[10px] font-medium uppercase tracking-[0.18em] text-[var(--muted-foreground)]">+ {t("Course")}+ </p>+ <h1 className="mt-1 font-serif text-[28px] font-semibold leading-tight tracking-tight text-[var(--foreground)]">+ {course.name}+ </h1>+ <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">+ {course.description || t("A focused home for this subject.")}+ </p>+ <p className="mt-3 text-[11px] text-[var(--muted-foreground)]/75">+ {t("{{count}} active conversations", { count: rootCount })}+ </p>+ </div>+ <div className="relative flex shrink-0 items-center gap-2">+ <Link+ href={`/home?course=${encodeURIComponent(course.id)}`}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-2 text-[12px] font-medium text-[var(--background)] hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)]"+ >+ <MessageSquarePlus size={14} />+ {t("New course chat")}+ </Link>+ <button+ type="button"+ onClick={() => setMenuOpen((open) => !open)}+ className="rounded-lg border border-[var(--border)] p-2 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ aria-label={t("Course actions")}+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ >+ <MoreHorizontal size={15} />+ </button>+ {menuOpen ? (+ <div className="absolute right-0 top-10 z-20 w-40 rounded-xl border border-[var(--border)] bg-[var(--popover)] p-1.5 text-[12px] shadow-xl">+ <button+ type="button"+ onClick={() => {+ setMenuOpen(false);+ setEditOpen(true);+ }}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-[var(--muted)]"+ >+ <Pencil size={13} /> {t("Edit course")}+ </button>+ <button+ type="button"+ onClick={() => {+ setMenuOpen(false);+ setDeleteOpen(true);+ }}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-[var(--destructive)] hover:bg-[var(--muted)]"+ >+ <Trash2 size={13} /> {t("Delete course")}+ </button>+ </div>+ ) : null}+ </div>+ </div>+ </header>++ <div className="mt-5 grid gap-3 sm:grid-cols-3">+ <Shortcut href="/notebook" icon={NotebookPen} label={t("Notebooks")} />+ <Shortcut+ href="/space/questions"+ icon={ClipboardList}+ label={t("Question Bank")}+ />+ <Shortcut+ href="/space/learning"+ icon={GraduationCap}+ label={t("Mastery Path")}+ />+ </div>++ <section className="mt-7 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-3">+ <div className="flex items-center justify-between px-2 pb-2">+ <div>+ <h2 className="font-serif text-[17px] font-semibold">+ {t("Conversations")}+ </h2>+ <p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "Tutor threads stay nested under the conversation they came from.",+ )}+ </p>+ </div>+ </div>+ <OrganizedSessionList+ sessions={activeSessions}+ courses={courses}+ activeSessionId={null}+ emptyLabel={t("No conversations in this course")}+ onSelect={(sessionId) => router.push(`/home/${sessionId}`)}+ onRename={renameSession}+ onDelete={removeSession}+ onOrganize={patchSession}+ />+ </section>++ {archivedSessions.length > 0 ? (+ <details className="mt-4 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-3">+ <summary className="flex cursor-pointer list-none items-center gap-2 px-2 py-1 text-[13px] font-medium">+ <Archive size={14} />+ {t("Archived conversations")}+ <span className="text-[11px] font-normal text-[var(--muted-foreground)]">+ {archivedSessions.length}+ </span>+ </summary>+ <OrganizedSessionList+ sessions={archivedSessions}+ courses={courses}+ activeSessionId={null}+ onSelect={(sessionId) => router.push(`/home/${sessionId}`)}+ onRename={renameSession}+ onDelete={removeSession}+ onOrganize={patchSession}+ />+ </details>+ ) : null}++ <CourseDialog+ open={editOpen}+ course={course}+ onClose={() => setEditOpen(false)}+ onSave={async (input) => {+ const updated = await updateCourse(course.id, input);+ setCourse(updated);+ setCourses((previous) =>+ previous.map((item) => (item.id === updated.id ? updated : item)),+ );+ }}+ />+ <ConfirmDialog+ open={deleteOpen}+ title={t("Delete course?")}+ confirmLabel={t("Delete course")}+ tone="danger"+ onCancel={() => setDeleteOpen(false)}+ onConfirm={() => {+ void deleteCourse(course.id).then(() => router.push("/space"));+ }}+ >+ {t(+ "Conversations will not be deleted. They will move to Unclassified.",+ )}+ </ConfirmDialog>+ </div>+ );+}++function Shortcut({+ href,+ icon: Icon,+ label,+}: {+ href: string;+ icon: typeof NotebookPen;+ label: string;+}) {+ return (+ <Link+ href={href}+ className="flex items-center gap-2.5 rounded-xl border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/20 hover:text-[var(--foreground)]"+ >+ <Icon size={15} strokeWidth={1.7} />+ {label}+ </Link>+ );+}diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex f3acd46da..c226a7ec6 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -123,6 +123,7 @@ import {selectedBooksToPayload,type SelectedBookReference,} from "@/lib/book-references";+import { normalizeSelectedText } from "@/lib/selection-tutor";const NotebookRecordPicker = dynamic(() => import("@/components/notebook/NotebookRecordPicker"),@@ -168,7 +169,9 @@ const SaveToNotebookModal = dynamic(// don't need a form (Chat / Solve) don't ship the form JS.const CapabilityConfigCard = dynamic(() => import("@/components/chat/home/CapabilityConfigCard"),- { ssr: false },+ {+ ssr: false,+ },);const QuizConfigPanel = dynamic(() => import("@/components/quiz/QuizConfigPanel"),@@ -176,11 +179,15 @@ const QuizConfigPanel = dynamic();const VisualizeConfigPanel = dynamic(() => import("@/components/visualize/VisualizeConfigPanel"),- { ssr: false },+ {+ ssr: false,+ },);const ResearchConfigPanel = dynamic(() => import("@/components/research/ResearchConfigPanel"),- { ssr: false },+ {+ ssr: false,+ },);/* ------------------------------------------------------------------ */@@ -436,6 +443,15 @@ export default function ChatPage() {? null: new URLSearchParams(window.location.search).get("agent");}+ // A course-page "New course chat" link carries the destination only until+ // the first turn creates its durable session. Consume it once so later+ // messages cannot undo an explicit move made from the sidebar.+ const pendingCourseRef = useRef<string | null | undefined>(undefined);+ useEffect(() => {+ pendingCourseRef.current = new URLSearchParams(window.location.search).get(+ "course",+ );+ }, []);const agentPreselectDoneRef = useRef(false);const {options: llmOptions,@@ -469,6 +485,11 @@ export default function ChatPage() {// Single right-side panel: the Activity/Viewer. Its home view is the// session activity; files and web pages open as tabs alongside it.const [viewerPanelOpen, setViewerPanelOpen] = useState(false);+ const [selectionTutorPrompt, setSelectionTutorPrompt] = useState<{+ text: string;+ left: number;+ top: number;+ } | null>(null);useEffect(() => {if (typeof window === "undefined") return;if (window.localStorage.getItem("dt:chat:viewer-panel") === "1") {@@ -1651,6 +1672,56 @@ export default function ChatPage() {viewerPanelRef.current?.openWebTab(href);}, []);+ const handleMessagesSelection = useCallback(() => {+ const container = messagesContainerRef.current;+ const selection = window.getSelection();+ if (+ !container ||+ !selection ||+ selection.isCollapsed ||+ !selection.rangeCount+ ) {+ setSelectionTutorPrompt(null);+ return;+ }+ const range = selection.getRangeAt(0);+ if (!container.contains(range.commonAncestorContainer)) {+ setSelectionTutorPrompt(null);+ return;+ }+ const text = normalizeSelectedText(selection.toString());+ if (text.length < 2) {+ setSelectionTutorPrompt(null);+ return;+ }++ const rects = range.getClientRects();+ const rect =+ rects.length > 0+ ? rects[rects.length - 1]+ : range.getBoundingClientRect();+ const buttonWidth = 118;+ const buttonHeight = 38;+ const left = Math.max(+ 12,+ Math.min(rect.right - buttonWidth, window.innerWidth - buttonWidth - 12),+ );+ const below = rect.bottom + 8;+ const top =+ below + buttonHeight <= window.innerHeight - 12+ ? below+ : Math.max(12, rect.top - buttonHeight - 8);+ setSelectionTutorPrompt({ text, left, top });+ }, [messagesContainerRef]);++ const openSelectionTutor = useCallback(() => {+ const selectedText = selectionTutorPrompt?.text;+ if (!selectedText) return;+ viewerPanelRef.current?.openSelectionTutorTab(selectedText, state.language);+ setSelectionTutorPrompt(null);+ window.getSelection()?.removeAllRanges();+ }, [selectionTutorPrompt, state.language]);+const handleClosePreview = useCallback(() => {setPreviewSource(null);}, []);@@ -1780,6 +1851,10 @@ export default function ChatPage() {if (selectedAgent && subagentBudget) {config = { ...(config ?? {}), subagent_consult_budget: subagentBudget };}+ const launchCourseId = pendingCourseRef.current?.trim();+ if (launchCourseId) {+ config = { ...(config ?? {}), _course_id: launchCourseId };+ }const memoryPayload = [...memoryReferencesPayload];const messageContent =@@ -1809,6 +1884,7 @@ export default function ChatPage() {undefined,memoryPayload,);+ pendingCourseRef.current = null;shouldAutoScrollRef.current = true;setAttachments([]);setSelectedBookReferences([]);@@ -2220,8 +2296,13 @@ export default function ChatPage() {<divref={messagesContainerRef}data-chat-scroll-root="true"- onScroll={handleMessagesScroll}+ onScroll={() => {+ setSelectionTutorPrompt(null);+ handleMessagesScroll();+ }}onClick={handleMessagesClick}+ onMouseUp={handleMessagesSelection}+ onKeyUp={handleMessagesSelection}// `both-edges` reserves the scrollbar gutter on both sides so// the inner mx-auto column centers on the same axis as the// header and composer (siblings outside this scrollport) on@@ -2277,6 +2358,22 @@ export default function ChatPage() {/></div></div>+ {selectionTutorPrompt ? (+ <button+ type="button"+ onPointerDown={(event) => event.preventDefault()}+ onClick={openSelectionTutor}+ aria-label={t("Ask Little Tutor")}+ className="fixed z-[45] inline-flex h-[38px] items-center gap-1.5 rounded-xl border border-[var(--border)] bg-[var(--foreground)] px-3 text-[12px] font-medium text-[var(--background)] shadow-lg transition-transform hover:-translate-y-0.5"+ style={{+ left: selectionTutorPrompt.left,+ top: selectionTutorPrompt.top,+ }}+ >+ <GraduationCap size={15} strokeWidth={1.8} />+ {t("Ask Little Tutor")}+ </button>+ ) : null}<TurnNavigatorentries={chatOutline}scrollRootRef={messagesContainerRef}diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsxindex f6c1c5bfb..9d5ea33d3 100644--- a/web/components/chat/home/SessionViewerPanel.tsx+++ b/web/components/chat/home/SessionViewerPanel.tsx@@ -34,6 +34,7 @@ import {ExternalLink,FileUp,Globe,+ GraduationCap,Loader2,MessageSquarePlus,Paperclip,@@ -56,6 +57,10 @@ import type { GeogebraTabPayload } from "@/context/GeogebraTabContext";import { apiUrl } from "@/lib/api";import type { MessageAttachment } from "@/context/UnifiedChatContext";import type { StreamEvent } from "@/lib/unified-ws";+import {+ normalizeSelectedText,+ selectionTutorKey,+} from "@/lib/selection-tutor";const PdfPreview = dynamic(() => import("@/components/chat/preview/previewers/PdfPreview"),@@ -135,6 +140,12 @@ type ViewerTab =label: string;context: QuizFollowupTabContext;}+ | {+ kind: "selection-tutor";+ id: string;+ label: string;+ context: QuizFollowupTabContext;+ }| {kind: "geogebra";id: string;@@ -154,6 +165,8 @@ export interface SessionViewerPanelHandle {openWebTab(url: string): void;/** Opens (or focuses) the follow-up chat tab for a quiz question. */openQuizFollowupTab(context: QuizFollowupTabContext): void;+ /** Opens an independent Little Tutor thread grounded in selected chat text. */+ openSelectionTutorTab(selectedText: string, language: string): void;/** Opens (or focuses) an interactive GeoGebra applet tab. */openGeogebraTab(payload: GeogebraTabPayload): void;/** Opens (first time) or live-updates a connected subagent's run tab. */@@ -186,6 +199,10 @@ function quizFollowupTabIdFor(questionKey: string): string {return `quiz-followup:${questionKey}`;}+function selectionTutorTabIdFor(questionKey: string): string {+ return `selection-tutor:${questionKey}`;+}+function geogebraTabIdFor(payloadId: string): string {return `geogebra:${payloadId}`;}@@ -375,6 +392,58 @@ function SessionViewerPanelInner([onAutoOpen],);+ const openSelectionTutorTab = useCallback(+ (rawSelectedText: string, language: string) => {+ const selectedText = normalizeSelectedText(rawSelectedText);+ if (!selectedText) return;+ const questionKey = selectionTutorKey(selectedText, sessionId);+ const id = selectionTutorTabIdFor(questionKey);+ const context: QuizFollowupTabContext = {+ questionKey,+ question: {+ question_id: questionKey,+ question: selectedText,+ question_type: "concept",+ correct_answer: "",+ explanation: "",+ },+ userAnswer: "",+ isCorrect: null,+ answerImages: [],+ aiJudgment: "",+ parentQuizSessionId: null,+ notebookEntryId: null,+ followupSessionId: null,+ language,+ tabLabel: t("Little Tutor"),+ tutorSelection: {+ selectedText,+ parentSessionId: sessionId,+ },+ };++ setTabs((prev) => {+ const existingIdx = prev.findIndex((tab) => tab.id === id);+ const tab: ViewerTab = {+ kind: "selection-tutor",+ id,+ label: t("Little Tutor"),+ context,+ };+ if (existingIdx >= 0) {+ const next = [...prev];+ next[existingIdx] = tab;+ setActiveTabId(id);+ return next;+ }+ setActiveTabId(id);+ return [...prev, tab];+ });+ onAutoOpen();+ },+ [onAutoOpen, sessionId, t],+ );+const openGeogebraTab = useCallback((payload: GeogebraTabPayload) => {setTabs((prev) => {@@ -448,6 +517,7 @@ function SessionViewerPanelInner(openFileTab,openWebTab,openQuizFollowupTab,+ openSelectionTutorTab,openGeogebraTab,openSubagentTab,focusActivityHome,@@ -456,6 +526,7 @@ function SessionViewerPanelInner(openFileTab,openWebTab,openQuizFollowupTab,+ openSelectionTutorTab,openGeogebraTab,openSubagentTab,focusActivityHome,@@ -571,6 +642,11 @@ function SessionViewerPanelInner(key={activeTab.context.questionKey}context={activeTab.context}/>+ ) : activeTab?.kind === "selection-tutor" ? (+ <QuizFollowupTabBody+ key={activeTab.context.questionKey}+ context={activeTab.context}+ />) : activeTab?.kind === "geogebra" ? (<GeogebraTabBody key={activeTab.id} script={activeTab.script} />) : activeTab?.kind === "subagent" ? (@@ -650,11 +726,13 @@ function TabBar({const Icon =tab.kind === "web"? Globe- : tab.kind === "quiz-followup"- ? MessageSquarePlus- : tab.kind === "geogebra"- ? Compass- : Paperclip;+ : tab.kind === "selection-tutor"+ ? GraduationCap+ : tab.kind === "quiz-followup"+ ? MessageSquarePlus+ : tab.kind === "geogebra"+ ? Compass+ : Paperclip;return (<divkey={tab.id}diff --git a/web/components/courses/CourseDialog.tsx b/web/components/courses/CourseDialog.tsxnew file mode 100644index 000000000..9f65be830--- /dev/null+++ b/web/components/courses/CourseDialog.tsx@@ -0,0 +1,153 @@+"use client";++import { useEffect, useState } from "react";+import { BookOpen } from "lucide-react";+import { useTranslation } from "react-i18next";+import Modal from "@/components/common/Modal";+import { DEFAULT_COURSE_COLORS, type StudyCourse } from "@/lib/courses-api";++interface CourseDialogProps {+ open: boolean;+ course?: StudyCourse | null;+ onClose: () => void;+ onSave: (input: {+ name: string;+ description: string;+ color: string;+ }) => Promise<void>;+}++export default function CourseDialog({+ open,+ course,+ onClose,+ onSave,+}: CourseDialogProps) {+ const { t } = useTranslation();+ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [color, setColor] = useState(DEFAULT_COURSE_COLORS[0]);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ useEffect(() => {+ if (!open) return;+ setName(course?.name ?? "");+ setDescription(course?.description ?? "");+ setColor(course?.color ?? DEFAULT_COURSE_COLORS[0]);+ setError("");+ }, [course, open]);++ const submit = async (event: React.FormEvent) => {+ event.preventDefault();+ const cleanName = name.trim();+ if (!cleanName || busy) return;+ setBusy(true);+ setError("");+ try {+ await onSave({ name: cleanName, description: description.trim(), color });+ onClose();+ } catch (reason) {+ setError(+ reason instanceof Error+ ? reason.message+ : t("Couldn't save this course."),+ );+ } finally {+ setBusy(false);+ }+ };++ return (+ <Modal+ isOpen={open}+ onClose={onClose}+ title={course ? t("Edit course") : t("Create a course")}+ titleIcon={<BookOpen size={18} strokeWidth={1.7} />}+ width="sm"+ closeOnBackdrop={!busy}+ closeOnEscape={!busy}+ >+ <form onSubmit={submit} className="space-y-5 p-5">+ <label className="block">+ <span className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Course name")}+ </span>+ <input+ data-autofocus+ value={name}+ maxLength={60}+ onChange={(event) => setName(event.target.value)}+ placeholder={t("e.g. Operating Systems")}+ className="w-full rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-2.5 text-[13px] outline-none transition-colors focus:border-[var(--ring)]"+ />+ </label>++ <label className="block">+ <span className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Description")}+ </span>+ <textarea+ value={description}+ maxLength={300}+ rows={3}+ onChange={(event) => setDescription(event.target.value)}+ placeholder={t("What are you learning in this course?")}+ className="w-full resize-none rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-2.5 text-[13px] leading-relaxed outline-none transition-colors focus:border-[var(--ring)]"+ />+ </label>++ <fieldset>+ <legend className="mb-2 text-[12px] font-medium text-[var(--foreground)]">+ {t("Book-spine color")}+ </legend>+ <div className="flex flex-wrap gap-2">+ {DEFAULT_COURSE_COLORS.map((candidate) => (+ <button+ key={candidate}+ type="button"+ onClick={() => setColor(candidate)}+ aria-label={`${t("Choose color")} ${candidate}`}+ aria-pressed={color === candidate}+ className="h-8 w-8 rounded-full border-2 transition-transform hover:scale-105 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:ring-offset-2"+ style={{+ backgroundColor: candidate,+ borderColor:+ color === candidate ? "var(--foreground)" : "transparent",+ }}+ />+ ))}+ </div>+ </fieldset>++ {error ? (+ <p role="alert" className="text-[12px] text-[var(--destructive)]">+ {error}+ </p>+ ) : null}++ <div className="flex justify-end gap-2 pt-1">+ <button+ type="button"+ onClick={onClose}+ disabled={busy}+ className="rounded-lg px-3 py-2 text-[13px] text-[var(--muted-foreground)] hover:text-[var(--foreground)] disabled:opacity-50"+ >+ {t("Cancel")}+ </button>+ <button+ type="submit"+ disabled={!name.trim() || busy}+ className="rounded-lg bg-[var(--foreground)] px-4 py-2 text-[13px] font-medium text-[var(--background)] transition-opacity hover:opacity-90 disabled:opacity-40"+ >+ {busy+ ? t("Saving...")+ : course+ ? t("Save changes")+ : t("Create course")}+ </button>+ </div>+ </form>+ </Modal>+ );+}diff --git a/web/components/courses/CoursesShelf.tsx b/web/components/courses/CoursesShelf.tsxnew file mode 100644index 000000000..e0d7e3d3b--- /dev/null+++ b/web/components/courses/CoursesShelf.tsx@@ -0,0 +1,160 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import Link from "next/link";+import { ArrowRight, BookOpen, Plus } from "lucide-react";+import { useTranslation } from "react-i18next";+import CourseDialog from "@/components/courses/CourseDialog";+import { createCourse, listCourses, type StudyCourse } from "@/lib/courses-api";+import { listAllSessions, type SessionSummary } from "@/lib/session-api";++export default function CoursesShelf() {+ const { t } = useTranslation();+ const [courses, setCourses] = useState<StudyCourse[]>([]);+ const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [loading, setLoading] = useState(true);+ const [dialogOpen, setDialogOpen] = useState(false);++ useEffect(() => {+ let cancelled = false;+ void Promise.all([+ listCourses({ force: true }),+ listAllSessions({ force: true }),+ ])+ .then(([nextCourses, nextSessions]) => {+ if (cancelled) return;+ setCourses(nextCourses);+ setSessions(nextSessions);+ })+ .finally(() => {+ if (!cancelled) setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const counts = useMemo(() => {+ const result = new Map<string, number>();+ for (const session of sessions) {+ if (+ session.preferences?.archived ||+ session.preferences?.parent_session_id+ )+ continue;+ const courseId = session.preferences?.course_id;+ if (courseId) result.set(courseId, (result.get(courseId) ?? 0) + 1);+ }+ return result;+ }, [sessions]);++ const saveCourse = useCallback(+ async (input: { name: string; description: string; color: string }) => {+ const course = await createCourse(input);+ setCourses((previous) => [...previous, course]);+ },+ [],+ );++ return (+ <section className="mb-9" aria-labelledby="courses-shelf-title">+ <div className="mb-3 flex items-end justify-between gap-4">+ <div>+ <h2+ id="courses-shelf-title"+ className="font-serif text-[18px] font-semibold tracking-tight text-[var(--foreground)]"+ >+ {t("My courses")}+ </h2>+ <p className="mt-1 text-[12.5px] text-[var(--muted-foreground)]">+ {t(+ "Keep each subject's conversations together without mixing their context.",+ )}+ </p>+ </div>+ <button+ type="button"+ onClick={() => setDialogOpen(true)}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/25 hover:bg-[var(--muted)]/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)]"+ >+ <Plus size={14} />+ {t("New course")}+ </button>+ </div>++ {loading ? (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {[0, 1, 2].map((item) => (+ <div+ key={item}+ className="h-28 animate-pulse rounded-xl border border-[var(--border)] bg-[var(--card)]"+ />+ ))}+ </div>+ ) : courses.length === 0 ? (+ <button+ type="button"+ onClick={() => setDialogOpen(true)}+ className="group flex w-full items-center gap-4 rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/55 p-5 text-left transition-colors hover:border-[var(--foreground)]/25 hover:bg-[var(--card)]"+ >+ <span className="flex h-11 w-9 items-center justify-center rounded-r-md border border-l-4 border-[var(--border)] border-l-[#C65D2E] bg-[var(--background)]">+ <BookOpen size={17} strokeWidth={1.6} />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-[14px] font-medium text-[var(--foreground)]">+ {t("Create your first course")}+ </span>+ <span className="mt-1 block text-[12px] text-[var(--muted-foreground)]">+ {t(+ "Start with a subject such as Operating Systems or Network Security.",+ )}+ </span>+ </span>+ <ArrowRight size={16} className="text-[var(--muted-foreground)]" />+ </button>+ ) : (+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {courses.map((course) => (+ <Link+ key={course.id}+ href={`/space/courses/${course.id}`}+ className="group relative min-h-28 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 pl-5 transition-all duration-150 hover:-translate-y-0.5 hover:border-[var(--foreground)]/20 hover:shadow-[0_6px_20px_-12px_rgba(0,0,0,0.25)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--ring)]"+ >+ <span+ aria-hidden+ className="absolute inset-y-0 left-0 w-1.5"+ style={{ backgroundColor: course.color }}+ />+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <h3 className="truncate font-serif text-[16px] font-semibold text-[var(--foreground)]">+ {course.name}+ </h3>+ <p className="mt-1 line-clamp-2 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {course.description ||+ t("A focused home for this subject.")}+ </p>+ </div>+ <ArrowRight+ size={15}+ className="mt-0.5 shrink-0 text-[var(--muted-foreground)]/45 transition-transform group-hover:translate-x-0.5"+ />+ </div>+ <div className="mt-3 text-[10.5px] text-[var(--muted-foreground)]/75">+ {t("{{count}} conversations", {+ count: counts.get(course.id) ?? 0,+ })}+ </div>+ </Link>+ ))}+ </div>+ )}++ <CourseDialog+ open={dialogOpen}+ onClose={() => setDialogOpen(false)}+ onSave={saveCourse}+ />+ </section>+ );+}diff --git a/web/components/courses/OrganizedSessionList.tsx b/web/components/courses/OrganizedSessionList.tsxnew file mode 100644index 000000000..8b892f737--- /dev/null+++ b/web/components/courses/OrganizedSessionList.tsx@@ -0,0 +1,453 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { createPortal } from "react-dom";+import {+ Archive,+ ArchiveRestore,+ Check,+ ChevronRight,+ GraduationCap,+ MoreHorizontal,+ Pencil,+ Pin,+ PinOff,+ Trash2,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import { SessionAvatar } from "@/components/sidebar/SessionAvatar";+import type { StudyCourse } from "@/lib/courses-api";+import type {+ SessionOrganizationPatch,+ SessionSummary,+} from "@/lib/session-api";+import { isPlaceholderSessionTitle } from "@/lib/session-title";++interface OrganizedSessionListProps {+ sessions: SessionSummary[];+ courses: StudyCourse[];+ activeSessionId: string | null;+ emptyLabel?: string;+ nested?: boolean;+ onSelect: (sessionId: string) => void | Promise<void>;+ onRename: (sessionId: string, title: string) => void | Promise<void>;+ onDelete: (sessionId: string) => void | Promise<void>;+ onOrganize: (+ sessionId: string,+ patch: SessionOrganizationPatch,+ ) => void | Promise<void>;+}++interface FloatingMenuPosition {+ left: number;+ top: number;+ maxHeight: number;+ openUpward: boolean;+}++const MENU_WIDTH = 240;+const MENU_GAP = 8;+const VIEWPORT_MARGIN = 12;++function placeMenu(anchor: DOMRect): FloatingMenuPosition {+ const viewportWidth = window.innerWidth;+ const viewportHeight = window.innerHeight;+ const preferredHeight = Math.min(380, viewportHeight - VIEWPORT_MARGIN * 2);+ const roomBelow = viewportHeight - anchor.bottom - MENU_GAP - VIEWPORT_MARGIN;+ const roomAbove = anchor.top - MENU_GAP - VIEWPORT_MARGIN;+ const openUpward = roomBelow < preferredHeight && roomAbove > roomBelow;+ const maxHeight = Math.max(+ 140,+ Math.min(preferredHeight, openUpward ? roomAbove : roomBelow),+ );++ const roomRight = viewportWidth - anchor.right - MENU_GAP - VIEWPORT_MARGIN;+ const roomLeft = anchor.left - MENU_GAP - VIEWPORT_MARGIN;+ const preferredLeft =+ roomRight >= MENU_WIDTH || roomRight >= roomLeft+ ? anchor.right + MENU_GAP+ : anchor.left - MENU_WIDTH - MENU_GAP;+ const left = Math.max(+ VIEWPORT_MARGIN,+ Math.min(preferredLeft, viewportWidth - MENU_WIDTH - VIEWPORT_MARGIN),+ );+ const top = openUpward ? anchor.top - MENU_GAP : anchor.bottom + MENU_GAP;++ return { left, top, maxHeight, openUpward };+}++function byPriority(a: SessionSummary, b: SessionSummary): number {+ const pinned =+ Number(Boolean(b.preferences?.pinned)) -+ Number(Boolean(a.preferences?.pinned));+ return pinned || b.updated_at - a.updated_at;+}++export default function OrganizedSessionList({+ sessions,+ courses,+ activeSessionId,+ emptyLabel,+ nested = true,+ onSelect,+ onRename,+ onDelete,+ onOrganize,+}: OrganizedSessionListProps) {+ const { t } = useTranslation();+ const [editingId, setEditingId] = useState<string | null>(null);+ const [draftTitle, setDraftTitle] = useState("");+ const [openMenuId, setOpenMenuId] = useState<string | null>(null);+ const [menuPosition, setMenuPosition] = useState<FloatingMenuPosition | null>(+ null,+ );+ const [collapsedParents, setCollapsedParents] = useState<Set<string>>(+ new Set(),+ );+ const menuRootRef = useRef<HTMLDivElement>(null);+ const menuAnchorRef = useRef<HTMLButtonElement | null>(null);++ const { roots, childrenByParent } = useMemo(() => {+ const ids = new Set(sessions.map((session) => session.session_id));+ const childMap = new Map<string, SessionSummary[]>();+ const rootRows: SessionSummary[] = [];+ for (const session of sessions) {+ const parentId = String(session.preferences?.parent_session_id || "");+ if (nested && parentId && ids.has(parentId)) {+ const children = childMap.get(parentId) ?? [];+ children.push(session);+ childMap.set(parentId, children);+ } else {+ rootRows.push(session);+ }+ }+ rootRows.sort(byPriority);+ for (const children of childMap.values()) children.sort(byPriority);+ return { roots: rootRows, childrenByParent: childMap };+ }, [nested, sessions]);++ useEffect(() => {+ if (!openMenuId) return;+ const closeMenu = () => {+ setOpenMenuId(null);+ setMenuPosition(null);+ };+ const close = (event: MouseEvent) => {+ const target = event.target as Node;+ if (+ !menuRootRef.current?.contains(target) &&+ !menuAnchorRef.current?.contains(target)+ ) {+ closeMenu();+ }+ };+ const closeOnEscape = (event: KeyboardEvent) => {+ if (event.key === "Escape") closeMenu();+ };+ const closeOnViewportChange = (event: Event) => {+ const target = event.target;+ if (target instanceof Node && menuRootRef.current?.contains(target))+ return;+ closeMenu();+ };+ document.addEventListener("mousedown", close);+ document.addEventListener("keydown", closeOnEscape);+ window.addEventListener("resize", closeMenu);+ window.addEventListener("scroll", closeOnViewportChange, true);+ return () => {+ document.removeEventListener("mousedown", close);+ document.removeEventListener("keydown", closeOnEscape);+ window.removeEventListener("resize", closeMenu);+ window.removeEventListener("scroll", closeOnViewportChange, true);+ };+ }, [openMenuId]);++ const commitEdit = async () => {+ if (!editingId) return;+ const next = draftTitle.trim();+ if (next) await onRename(editingId, next);+ setEditingId(null);+ setDraftTitle("");+ };++ const toggleChildren = (sessionId: string) => {+ setCollapsedParents((previous) => {+ const next = new Set(previous);+ if (next.has(sessionId)) next.delete(sessionId);+ else next.add(sessionId);+ return next;+ });+ };++ if (roots.length === 0) {+ return (+ <div className="px-3 py-2 text-[11px] text-[var(--muted-foreground)]/65">+ {emptyLabel ?? t("No conversations yet")}+ </div>+ );+ }++ const renderRow = (session: SessionSummary, child = false) => {+ const active = activeSessionId === session.session_id;+ const editing = editingId === session.session_id;+ const children = childrenByParent.get(session.session_id) ?? [];+ const expanded =+ children.length > 0 && !collapsedParents.has(session.session_id);+ const menuOpen = openMenuId === session.session_id;+ const archived = Boolean(session.preferences?.archived);+ const pinned = Boolean(session.preferences?.pinned);++ return (+ <div key={session.session_id} className="relative">+ <div+ role="button"+ tabIndex={0}+ onClick={() => void onSelect(session.session_id)}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ void onSelect(session.session_id);+ }+ }}+ className={`group/session flex min-w-0 items-center gap-1.5 rounded-lg py-1.5 pr-1 transition-colors ${+ child ? "ml-4 border-l border-[var(--border)]/60 pl-2" : "pl-1.5"+ } ${+ active+ ? "bg-[var(--background)]/60 text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--background)]/40 hover:text-[var(--foreground)]"+ }`}+ >+ {children.length > 0 ? (+ <button+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ toggleChildren(session.session_id);+ }}+ className="rounded p-0.5 hover:bg-[var(--muted)]"+ aria-label={+ expanded ? t("Hide tutor threads") : t("Show tutor threads")+ }+ aria-expanded={expanded}+ >+ <ChevronRight+ size={11}+ className={`transition-transform ${expanded ? "rotate-90" : ""}`}+ />+ </button>+ ) : (+ <span className="w-3" />+ )}+ <SessionAvatar+ sessionId={session.session_id}+ running={session.status === "running"}+ className={child ? "h-3.5 w-3.5 opacity-55" : "opacity-70"}+ />+ {child ? (+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-[var(--muted)]/70 px-1.5 py-0.5 text-[9px] font-medium text-[var(--muted-foreground)]">+ <GraduationCap size={9} strokeWidth={1.8} />+ {t("Little Tutor")}+ </span>+ ) : null}+ {editing ? (+ <input+ value={draftTitle}+ autoFocus+ onChange={(event) => setDraftTitle(event.target.value)}+ onBlur={() => void commitEdit()}+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => {+ event.stopPropagation();+ if (event.key === "Enter") void commitEdit();+ if (event.key === "Escape") setEditingId(null);+ }}+ className="min-w-0 flex-1 rounded border border-[var(--border)] bg-[var(--background)] px-1.5 py-0.5 text-[12px] outline-none focus:border-[var(--ring)]"+ />+ ) : (+ <span+ className={`min-w-0 flex-1 truncate text-[12.5px] ${+ isPlaceholderSessionTitle(session.title)+ ? "italic opacity-70"+ : ""+ }`}+ title={session.title}+ >+ {session.title || t("New chat")}+ </span>+ )}+ {pinned ? <Pin size={10} className="shrink-0 opacity-55" /> : null}+ {children.length > 0 && !expanded ? (+ <span className="shrink-0 rounded-full bg-[var(--muted)] px-1.5 text-[9px] tabular-nums">+ {children.length}+ </span>+ ) : null}+ <button+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ if (menuOpen) {+ setOpenMenuId(null);+ setMenuPosition(null);+ return;+ }+ menuAnchorRef.current = event.currentTarget;+ setMenuPosition(+ placeMenu(event.currentTarget.getBoundingClientRect()),+ );+ setOpenMenuId(session.session_id);+ }}+ className={`rounded p-1 hover:bg-[var(--muted)] ${+ menuOpen+ ? "opacity-100"+ : "opacity-0 group-hover/session:opacity-100 focus:opacity-100"+ }`}+ aria-label={t("Conversation actions")}+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ >+ <MoreHorizontal size={13} />+ </button>+ </div>++ {menuOpen && menuPosition && typeof document !== "undefined"+ ? createPortal(+ <div+ ref={menuRootRef}+ role="menu"+ style={{+ left: menuPosition.left,+ top: menuPosition.top,+ maxHeight: menuPosition.maxHeight,+ transform: menuPosition.openUpward+ ? "translateY(-100%)"+ : undefined,+ transformOrigin: menuPosition.openUpward ? "bottom" : "top",+ }}+ className="fixed z-[100] w-60 overflow-y-auto rounded-xl border border-[var(--border)] bg-[var(--popover)] p-2 text-[12px] shadow-xl"+ >+ <MenuButton+ icon={editing ? Check : Pencil}+ label={t("Rename chat")}+ onClick={() => {+ setDraftTitle(session.title);+ setEditingId(session.session_id);+ setOpenMenuId(null);+ setMenuPosition(null);+ }}+ />+ <MenuButton+ icon={pinned ? PinOff : Pin}+ label={pinned ? t("Unpin") : t("Pin")}+ onClick={() => {+ void onOrganize(session.session_id, { pinned: !pinned });+ setOpenMenuId(null);+ setMenuPosition(null);+ }}+ />+ <MenuButton+ icon={archived ? ArchiveRestore : Archive}+ label={archived ? t("Restore from archive") : t("Archive")}+ onClick={() => {+ void onOrganize(session.session_id, {+ archived: !archived,+ });+ setOpenMenuId(null);+ setMenuPosition(null);+ }}+ />+ <div className="my-1 border-t border-[var(--border)]/70" />+ <div className="px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]/65">+ {t("Move to course")}+ </div>+ <MenuButton+ icon={GraduationCap}+ label={t("Unclassified")}+ checked={!session.preferences?.course_id}+ onClick={() => {+ void onOrganize(session.session_id, { course_id: "" });+ setOpenMenuId(null);+ setMenuPosition(null);+ }}+ />+ <div>+ {courses.map((course) => (+ <MenuButton+ key={course.id}+ color={course.color}+ label={course.name}+ checked={session.preferences?.course_id === course.id}+ onClick={() => {+ void onOrganize(session.session_id, {+ course_id: course.id,+ });+ setOpenMenuId(null);+ setMenuPosition(null);+ }}+ />+ ))}+ </div>+ <div className="my-1 border-t border-[var(--border)]/70" />+ <MenuButton+ icon={Trash2}+ label={t("Delete chat")}+ danger+ onClick={() => {+ setOpenMenuId(null);+ setMenuPosition(null);+ void onDelete(session.session_id);+ }}+ />+ </div>,+ document.body,+ )+ : null}++ {expanded ? children.map((row) => renderRow(row, true)) : null}+ </div>+ );+ };++ return (+ <div className="py-0.5">{roots.map((session) => renderRow(session))}</div>+ );+}++function MenuButton({+ icon: Icon,+ label,+ color,+ checked = false,+ danger = false,+ onClick,+}: {+ icon?: typeof Pencil;+ label: string;+ color?: string;+ checked?: boolean;+ danger?: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ role="menuitem"+ onClick={onClick}+ className={`flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-[var(--muted)] ${+ danger ? "text-[var(--destructive)]" : "text-[var(--foreground)]"+ }`}+ >+ {color ? (+ <span+ className="h-3 w-1 rounded-full"+ style={{ backgroundColor: color }}+ />+ ) : Icon ? (+ <Icon size={13} strokeWidth={1.7} />+ ) : (+ <span className="w-3" />+ )}+ <span className="min-w-0 flex-1 truncate">{label}</span>+ {checked ? <Check size={12} /> : null}+ </button>+ );+}diff --git a/web/components/quiz/FollowupChatComposer.tsx b/web/components/quiz/FollowupChatComposer.tsxindex 3cd057bd7..72e5c6569 100644--- a/web/components/quiz/FollowupChatComposer.tsx+++ b/web/components/quiz/FollowupChatComposer.tsx@@ -23,6 +23,7 @@ import {useQuizFollowupController,} from "@/context/QuizFollowupContext";import { buildQuizFollowupConfig } from "@/lib/quiz-types";+import { buildSelectionTutorConfig } from "@/lib/selection-tutor";import { classifyFile, isSvgFilename } from "@/lib/doc-attachments";import { useAttachmentLimits } from "@/lib/attachment-limits";import {@@ -41,15 +42,21 @@ import type { LLMSelection } from "@/lib/unified-ws";const NotebookRecordPicker = dynamic(() => import("@/components/notebook/NotebookRecordPicker"),- { ssr: false },+ {+ ssr: false,+ },);const HistorySessionPicker = dynamic(() => import("@/components/chat/HistorySessionPicker"),- { ssr: false },+ {+ ssr: false,+ },);const QuestionBankPicker = dynamic(() => import("@/components/chat/QuestionBankPicker"),- { ssr: false },+ {+ ssr: false,+ },);const PersonaPicker = dynamic(() => import("@/components/chat/PersonaPicker"), {ssr: false,@@ -59,7 +66,9 @@ const MemoryPicker = dynamic(() => import("@/components/chat/MemoryPicker"), {});const BookReferencePicker = dynamic(() => import("@/components/chat/BookReferencePicker"),- { ssr: false },+ {+ ssr: false,+ },);interface KnowledgeBase {@@ -518,18 +527,20 @@ function FollowupChatComposerImpl({ context }: FollowupChatComposerProps) {const personaPayload = selectedPersona ?? undefined;- const baseConfig = buildQuizFollowupConfig(- context.question,- context.userAnswer,- context.isCorrect,- context.parentQuizSessionId,- {- userAnswerImageFilenames: context.answerImages.map(- (image) => image.filename,- ),- aiJudgment: context.aiJudgment,- },- );+ const baseConfig = context.tutorSelection+ ? buildSelectionTutorConfig(context.tutorSelection)+ : buildQuizFollowupConfig(+ context.question,+ context.userAnswer,+ context.isCorrect,+ context.parentQuizSessionId,+ {+ userAnswerImageFilenames: context.answerImages.map(+ (image) => image.filename,+ ),+ aiJudgment: context.aiJudgment,+ },+ );// Memory references ride on ``config`` — same convention as the// main chat sendMessage path.diff --git a/web/components/quiz/QuizFollowupTabBody.tsx b/web/components/quiz/QuizFollowupTabBody.tsxindex 104f27e69..6b91ef839 100644--- a/web/components/quiz/QuizFollowupTabBody.tsx+++ b/web/components/quiz/QuizFollowupTabBody.tsx@@ -21,7 +21,7 @@ import {useMemo,useRef,} from "react";-import { Sparkles } from "lucide-react";+import { GraduationCap, Sparkles } from "lucide-react";import { useTranslation } from "react-i18next";import MarkdownRenderer from "@/components/common/MarkdownRenderer";import FollowupChatComposer from "@/components/quiz/FollowupChatComposer";@@ -125,25 +125,36 @@ export default function QuizFollowupTabBody({const visibleMessages = thread.messages.filter((m) => m.role !== "system");const isCoding = context.question.question_type === "coding";+ const isSelectionTutor = Boolean(context.tutorSelection);return (<div className="flex h-full flex-col bg-[var(--card)]">{/* Header strip — mimics a chat-page title bar but with quiz crumbs. */}<div className="flex shrink-0 items-center gap-2 border-b border-[var(--border)]/40 bg-[var(--card)] px-4 py-2.5"><div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[var(--primary)]/12">- <Sparkles- size={14}- strokeWidth={1.7}- className="text-[var(--primary)]"- />+ {isSelectionTutor ? (+ <GraduationCap+ size={15}+ strokeWidth={1.7}+ className="text-[var(--primary)]"+ />+ ) : (+ <Sparkles+ size={14}+ strokeWidth={1.7}+ className="text-[var(--primary)]"+ />+ )}</div><div className="min-w-0 flex-1"><div className="truncate text-[12.5px] font-semibold text-[var(--foreground)]">- {context.tabLabel}+ {isSelectionTutor ? t("Little Tutor") : context.tabLabel}</div><div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">- {t("Follow-up Chat")}- {context.question.question_type+ {isSelectionTutor+ ? t("Ask about selected text")+ : t("Follow-up Chat")}+ {!isSelectionTutor && context.question.question_type? ` · ${context.question.question_type}`: ""}</div>@@ -164,7 +175,7 @@ export default function QuizFollowupTabBody({<div className="mx-auto flex max-w-[640px] flex-col gap-3"><div className="rounded-md border border-[var(--border)]/70 bg-[var(--background)]/70 px-3 py-2"><div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Question")}+ {t(isSelectionTutor ? "Selected text" : "Question")}</div><div className="text-[13px] leading-relaxed text-[var(--foreground)]"><MarkdownRenderer@@ -174,56 +185,58 @@ export default function QuizFollowupTabBody({</div></div>- <div className="rounded-md border border-[var(--border)]/70 bg-[var(--background)]/70 px-3 py-2">- <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">- {t("Your Answer")}- </div>- {context.userAnswer ? (- <div className="text-[13px] leading-relaxed text-[var(--foreground)]">- <MarkdownRenderer- content={- isCoding &&- !context.userAnswer.trimStart().startsWith("```")- ? `\`\`\`python\n${context.userAnswer}\n\`\`\``- : context.userAnswer- }- variant="compact"- />- </div>- ) : context.answerImages.length === 0 ? (- <div className="text-[12px] italic text-[var(--muted-foreground)]">- {t("No answer recorded.")}+ {!isSelectionTutor && (+ <div className="rounded-md border border-[var(--border)]/70 bg-[var(--background)]/70 px-3 py-2">+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--muted-foreground)]">+ {t("Your Answer")}</div>- ) : null}- {context.answerImages.length > 0 && (- <div className="mt-2 grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-5">- {context.answerImages.map((image) => {- const src = image.previewUrl ?? resolveImageSrc(image.url);- return (- <div- key={image.id}- className="overflow-hidden rounded-md border border-[var(--border)] bg-[var(--card)]"- >- {src ? (- // eslint-disable-next-line @next/next/no-img-element- <img- src={src}- alt={image.filename}- className="h-16 w-full object-cover"- />- ) : (- <div className="flex h-16 w-full items-center justify-center text-[10px] text-[var(--muted-foreground)]">- {image.filename}- </div>- )}- </div>- );- })}- </div>- )}- </div>+ {context.userAnswer ? (+ <div className="text-[13px] leading-relaxed text-[var(--foreground)]">+ <MarkdownRenderer+ content={+ isCoding &&+ !context.userAnswer.trimStart().startsWith("```")+ ? `\`\`\`python\n${context.userAnswer}\n\`\`\``+ : context.userAnswer+ }+ variant="compact"+ />+ </div>+ ) : context.answerImages.length === 0 ? (+ <div className="text-[12px] italic text-[var(--muted-foreground)]">+ {t("No answer recorded.")}+ </div>+ ) : null}+ {context.answerImages.length > 0 && (+ <div className="mt-2 grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-5">+ {context.answerImages.map((image) => {+ const src = image.previewUrl ?? resolveImageSrc(image.url);+ return (+ <div+ key={image.id}+ className="overflow-hidden rounded-md border border-[var(--border)] bg-[var(--card)]"+ >+ {src ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={src}+ alt={image.filename}+ className="h-16 w-full object-cover"+ />+ ) : (+ <div className="flex h-16 w-full items-center justify-center text-[10px] text-[var(--muted-foreground)]">+ {image.filename}+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>+ )}- {context.aiJudgment && (+ {!isSelectionTutor && context.aiJudgment && (<div className="rounded-md border border-[var(--primary)]/30 bg-[var(--primary)]/[0.04] px-3 py-2"><div className="mb-1 flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--primary)]"><Sparkles size={10} />@@ -242,7 +255,9 @@ export default function QuizFollowupTabBody({{visibleMessages.length === 0 ? (<div className="rounded-md border border-dashed border-[var(--border)] bg-[var(--background)]/40 px-3 py-3 text-[12px] text-[var(--muted-foreground)]">{t(- "Ask anything about this question, your answer, or the AI judgment.",+ isSelectionTutor+ ? "Ask anything about the selected text."+ : "Ask anything about this question, your answer, or the AI judgment.",)}</div>) : (diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsxindex 5ef3c627d..f3fe5836e 100644--- a/web/components/sidebar/SidebarShell.tsx+++ b/web/components/sidebar/SidebarShell.tsx@@ -24,11 +24,16 @@ import {type LucideIcon,} from "lucide-react";import { useTranslation } from "react-i18next";+import OrganizedSessionList from "@/components/courses/OrganizedSessionList";import SessionList from "@/components/SessionList";import { useSidebarDrawer } from "@/components/layout/AppShell";import { useDevice } from "@/hooks/useDevice";import { VersionBadge } from "@/components/sidebar/VersionBadge";-import type { SessionSummary } from "@/lib/session-api";+import type {+ SessionOrganizationPatch,+ SessionSummary,+} from "@/lib/session-api";+import type { StudyCourse } from "@/lib/courses-api";import { Tooltip } from "@/components/ui/Tooltip";import { useCapabilityAccess } from "@/components/access/CapabilityAccessContext";import type { Capability } from "@/lib/capability-routes";@@ -124,6 +129,11 @@ interface SidebarShellProps {onSelectSession?: (sessionId: string) => void | Promise<void>;onRenameSession?: (sessionId: string, title: string) => void | Promise<void>;onDeleteSession?: (sessionId: string) => void | Promise<void>;+ courses?: StudyCourse[];+ onOrganizeSession?: (+ sessionId: string,+ patch: SessionOrganizationPatch,+ ) => void | Promise<void>;/*** Footer content rendered below the nav. Pass a render function to receive* the current ``collapsed`` state so footer items (e.g. Admin / Sign out) can@@ -141,6 +151,8 @@ export function SidebarShell({onSelectSession,onRenameSession,onDeleteSession,+ courses = [],+ onOrganizeSession,footerSlot,}: SidebarShellProps) {const pathname = usePathname();@@ -201,6 +213,14 @@ export function SidebarShell({router.push("/home");};+ const recentSessions = sessions+ .filter(+ (session) =>+ !session.preferences?.archived &&+ !session.preferences?.parent_session_id,+ )+ .slice(0, 8);+/* ---- Collapsed state ---- */if (collapsed) {return (@@ -446,18 +466,42 @@ export function SidebarShell({</button>{!recentsCollapsed && (<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2 pt-0.5">- <SessionList- sessions={sessions}- activeSessionId={activeSessionId}- loading={loadingSessions}- onSelect={(sessionId) => {- drawer?.close();- return onSelectSession(sessionId);- }}- onRename={onRenameSession}- onDelete={onDeleteSession}- compact- />+ {loadingSessions ? (+ <SessionList+ sessions={[]}+ activeSessionId={activeSessionId}+ loading+ onSelect={onSelectSession}+ onRename={onRenameSession}+ onDelete={onDeleteSession}+ compact+ />+ ) : onOrganizeSession ? (+ <OrganizedSessionList+ sessions={recentSessions}+ courses={courses}+ activeSessionId={activeSessionId}+ onSelect={(sessionId) => {+ drawer?.close();+ return onSelectSession(sessionId);+ }}+ onRename={onRenameSession}+ onDelete={onDeleteSession}+ onOrganize={onOrganizeSession}+ />+ ) : (+ <SessionList+ sessions={recentSessions}+ activeSessionId={activeSessionId}+ onSelect={(sessionId) => {+ drawer?.close();+ return onSelectSession(sessionId);+ }}+ onRename={onRenameSession}+ onDelete={onDeleteSession}+ compact+ />+ )}</div>)}</section>diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsxindex 34f9f4bbb..2dbb7fed1 100644--- a/web/components/sidebar/UtilitySidebar.tsx+++ b/web/components/sidebar/UtilitySidebar.tsx@@ -11,15 +11,19 @@ import { useAppShell } from "@/context/AppShellContext";import {deleteSession,listSessions,+ updateSessionOrganization,updateSessionTitle,+ type SessionOrganizationPatch,type SessionSummary,} from "@/lib/session-api";+import { listCourses, type StudyCourse } from "@/lib/courses-api";export default function UtilitySidebar() {const { t } = useTranslation();const router = useRouter();const { activeSessionId, setActiveSessionId } = useAppShell();const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [courses, setCourses] = useState<StudyCourse[]>([]);const [loadingSessions, setLoadingSessions] = useState(false);const hasLoadedSessionsRef = useRef(false);@@ -28,7 +32,12 @@ export default function UtilitySidebar() {setLoadingSessions(true);}try {- setSessions(await listSessions(50, 0, { force: true }));+ const [nextSessions, nextCourses] = await Promise.all([+ listSessions(50, 0, { force: true }),+ listCourses({ force: true }),+ ]);+ setSessions(nextSessions);+ setCourses(nextCourses);hasLoadedSessionsRef.current = true;} catch (error) {console.error("Failed to load sessions", error);@@ -81,16 +90,36 @@ export default function UtilitySidebar() {[activeSessionId, setActiveSessionId, t],);+ const handleOrganizeSession = useCallback(+ async (sessionId: string, patch: SessionOrganizationPatch) => {+ const updated = await updateSessionOrganization(sessionId, patch);+ setSessions((previous) =>+ previous.map((session) =>+ session.session_id === sessionId+ ? {+ ...session,+ updated_at: updated.updated_at,+ preferences: updated.preferences,+ }+ : session,+ ),+ );+ },+ [],+ );+return (<SidebarShellshowSessionssessions={sessions}+ courses={courses}activeSessionId={activeSessionId}loadingSessions={loadingSessions}onNewChat={() => setActiveSessionId(null)}onSelectSession={handleSelectSession}onRenameSession={handleRenameSession}onDeleteSession={handleDeleteSession}+ onOrganizeSession={handleOrganizeSession}footerSlot={(collapsed) => (<><ProfileLink collapsed={collapsed} />diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsxindex b13268815..94ac2d269 100644--- a/web/components/sidebar/WorkspaceSidebar.tsx+++ b/web/components/sidebar/WorkspaceSidebar.tsx@@ -11,9 +11,12 @@ import { useUnifiedChat } from "@/context/UnifiedChatContext";import {deleteSession,listSessions,+ updateSessionOrganization,updateSessionTitle,+ type SessionOrganizationPatch,type SessionSummary,} from "@/lib/session-api";+import { listCourses, type StudyCourse } from "@/lib/courses-api";export default function WorkspaceSidebar() {const { t } = useTranslation();@@ -26,6 +29,7 @@ export default function WorkspaceSidebar() {sidebarRefreshToken,} = useUnifiedChat();const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [courses, setCourses] = useState<StudyCourse[]>([]);const [loadingSessions, setLoadingSessions] = useState(false);const hasLoadedSessionsRef = useRef(false);@@ -34,7 +38,12 @@ export default function WorkspaceSidebar() {setLoadingSessions(true);}try {- setSessions(await listSessions(50, 0, { force: true }));+ const [nextSessions, nextCourses] = await Promise.all([+ listSessions(50, 0, { force: true }),+ listCourses({ force: true }),+ ]);+ setSessions(nextSessions);+ setCourses(nextCourses);hasLoadedSessionsRef.current = true;} catch (error) {console.error("Failed to load sessions", error);@@ -123,16 +132,36 @@ export default function WorkspaceSidebar() {[cancelStreamingTurn, newSession, router, selectedSessionId, t],);+ const handleOrganizeSession = useCallback(+ async (sessionId: string, patch: SessionOrganizationPatch) => {+ const updated = await updateSessionOrganization(sessionId, patch);+ setSessions((previous) =>+ previous.map((session) =>+ session.session_id === sessionId+ ? {+ ...session,+ updated_at: updated.updated_at,+ preferences: updated.preferences,+ }+ : session,+ ),+ );+ },+ [],+ );+return (<SidebarShellshowSessionssessions={orderedSessions}+ courses={courses}activeSessionId={selectedSessionId}loadingSessions={loadingSessions}onNewChat={handleNewChat}onSelectSession={handleSelectSession}onRenameSession={handleRenameSession}onDeleteSession={handleDeleteSession}+ onOrganizeSession={handleOrganizeSession}footerSlot={(collapsed) => (<><ProfileLink collapsed={collapsed} />diff --git a/web/components/space/ChatHistorySection.tsx b/web/components/space/ChatHistorySection.tsxindex 3ba17b8aa..db32c5971 100644--- a/web/components/space/ChatHistorySection.tsx+++ b/web/components/space/ChatHistorySection.tsx@@ -10,15 +10,18 @@ import {type LucideIcon,} from "lucide-react";import { useTranslation } from "react-i18next";-import SessionList from "@/components/SessionList";+import OrganizedSessionList from "@/components/courses/OrganizedSessionList";import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";import { useAppShell } from "@/context/AppShellContext";import {deleteSession,- listSessions,+ listAllSessions,updateSessionTitle,+ updateSessionOrganization,+ type SessionOrganizationPatch,type SessionSummary,} from "@/lib/session-api";+import { listCourses, type StudyCourse } from "@/lib/courses-api";/*** Sessions list for chat history. Reopened sessions always route back to@@ -40,13 +43,22 @@ export default function ChatHistorySection({const router = useRouter();const { activeSessionId, setActiveSessionId } = useAppShell();const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [courses, setCourses] = useState<StudyCourse[]>([]);const [loading, setLoading] = useState(true);const [query, setQuery] = useState("");+ const [courseFilter, setCourseFilter] = useState("all");+ const [kindFilter, setKindFilter] = useState("all");+ const [archiveFilter, setArchiveFilter] = useState("active");const load = useCallback(async (force = false) => {setLoading(true);try {- setSessions(await listSessions(200, 0, { force }));+ const [nextSessions, nextCourses] = await Promise.all([+ listAllSessions({ force }),+ listCourses({ force }),+ ]);+ setSessions(nextSessions);+ setCourses(nextCourses);} finally {setLoading(false);}@@ -58,13 +70,30 @@ export default function ChatHistorySection({const filteredSessions = useMemo(() => {const needle = query.trim().toLowerCase();- if (!needle) return sessions;- return sessions.filter((session) =>- [session.title, session.last_message]+ return sessions.filter((session) => {+ const prefs = session.preferences ?? {};+ if (archiveFilter === "active" && prefs.archived) return false;+ if (archiveFilter === "archived" && !prefs.archived) return false;+ if (courseFilter === "unclassified" && prefs.course_id) return false;+ if (+ courseFilter !== "all" &&+ courseFilter !== "unclassified" &&+ prefs.course_id !== courseFilter+ )+ return false;+ if (kindFilter === "chat" && prefs.session_kind === "selection_tutor")+ return false;+ if (+ kindFilter === "selection_tutor" &&+ prefs.session_kind !== "selection_tutor"+ )+ return false;+ if (!needle) return true;+ return [session.title, session.last_message].filter(Boolean)- .some((value) => value.toLowerCase().includes(needle)),- );- }, [query, sessions]);+ .some((value) => value.toLowerCase().includes(needle));+ });+ }, [archiveFilter, courseFilter, kindFilter, query, sessions]);const handleSelect = useCallback((sessionId: string) => {@@ -94,6 +123,14 @@ export default function ChatHistorySection({[activeSessionId, setActiveSessionId, t],);+ const handleOrganize = useCallback(+ async (sessionId: string, patch: SessionOrganizationPatch) => {+ await updateSessionOrganization(sessionId, patch);+ await load(true);+ },+ [load],+ );+const HeaderIcon = icon ?? History;const headerTitle = title ?? t("Chat History");const headerDescription =@@ -141,17 +178,74 @@ export default function ChatHistorySection({className="min-w-0 flex-1 bg-transparent text-[13px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/55"/></label>+ <div className="mt-2 grid gap-2 sm:grid-cols-3">+ <label className="sr-only" htmlFor="history-course-filter">+ {t("Filter by course")}+ </label>+ <select+ id="history-course-filter"+ value={courseFilter}+ onChange={(event) => setCourseFilter(event.target.value)}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"+ >+ <option value="all">{t("All courses")}</option>+ <option value="unclassified">{t("Unclassified")}</option>+ {courses.map((course) => (+ <option key={course.id} value={course.id}>+ {course.name}+ </option>+ ))}+ </select>+ <label className="sr-only" htmlFor="history-kind-filter">+ {t("Filter by conversation type")}+ </label>+ <select+ id="history-kind-filter"+ value={kindFilter}+ onChange={(event) => setKindFilter(event.target.value)}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"+ >+ <option value="all">{t("All conversation types")}</option>+ <option value="chat">{t("Main conversations")}</option>+ <option value="selection_tutor">{t("Tutor threads")}</option>+ </select>+ <label className="sr-only" htmlFor="history-archive-filter">+ {t("Filter by archive status")}+ </label>+ <select+ id="history-archive-filter"+ value={archiveFilter}+ onChange={(event) => setArchiveFilter(event.target.value)}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5 text-[12px] text-[var(--foreground)] outline-none focus:border-[var(--ring)]"+ >+ <option value="active">{t("Active")}</option>+ <option value="archived">{t("Archived")}</option>+ <option value="all">{t("Active and archived")}</option>+ </select>+ </div></div><div className="px-3 py-3">- <SessionList- sessions={filteredSessions}- activeSessionId={activeSessionId}- loading={loading}- onSelect={handleSelect}- onRename={handleRename}- onDelete={handleDelete}- />+ {loading ? (+ <div className="space-y-2 p-2">+ {[0, 1, 2, 3].map((item) => (+ <div+ key={item}+ className="h-8 animate-pulse rounded bg-[var(--muted)]/45"+ />+ ))}+ </div>+ ) : (+ <OrganizedSessionList+ sessions={filteredSessions}+ courses={courses}+ activeSessionId={activeSessionId}+ onSelect={handleSelect}+ onRename={handleRename}+ onDelete={handleDelete}+ onOrganize={handleOrganize}+ />+ )}</div></section></div>diff --git a/web/components/space/SpaceDashboard.tsx b/web/components/space/SpaceDashboard.tsxindex 54bec4160..b191c566e 100644--- a/web/components/space/SpaceDashboard.tsx+++ b/web/components/space/SpaceDashboard.tsx@@ -26,6 +26,7 @@ import { listNotebooks, listNotebookEntries } from "@/lib/notebook-api";import { listPersonas } from "@/lib/personas-api";import { listSkills } from "@/lib/skills-api";import { fetchAllProgress } from "@/lib/learning-api";+import CoursesShelf from "@/components/courses/CoursesShelf";/*** Learning Space dashboard — the hub of `/space`.@@ -305,6 +306,8 @@ export default function SpaceDashboard() {</p></header>+ <CoursesShelf />+<div className="space-y-9">{groups.map((group) => (<section key={group.label.en}>diff --git a/web/context/QuizFollowupContext.tsx b/web/context/QuizFollowupContext.tsxindex 377431db1..e0fc37b45 100644--- a/web/context/QuizFollowupContext.tsx+++ b/web/context/QuizFollowupContext.tsx@@ -107,6 +107,11 @@ export interface QuizFollowupTabContext {language: string;/** Short label for the tab strip, e.g. "Q1 follow-up". */tabLabel: string;+ /** Present when this thread tutors a selected chat passage, not a quiz. */+ tutorSelection?: {+ selectedText: string;+ parentSessionId: string | null;+ };}export interface SendMessageInput {diff --git a/web/lib/courses-api.ts b/web/lib/courses-api.tsnew file mode 100644index 000000000..a9e9b7cd7--- /dev/null+++ b/web/lib/courses-api.ts@@ -0,0 +1,79 @@+import { apiFetch, apiUrl } from "@/lib/api";+import { invalidateClientCache, withClientCache } from "@/lib/client-cache";++export interface StudyCourse {+ id: string;+ name: string;+ description: string;+ color: string;+ created_at: number;+ updated_at: number;+}++export const DEFAULT_COURSE_COLORS = [+ "#C65D2E",+ "#3F6F8F",+ "#4F7655",+ "#8A6543",+ "#705B8E",+ "#A04F5F",+];++async function expectJson<T>(response: Response): Promise<T> {+ if (!response.ok) throw new Error(`Request failed: ${response.status}`);+ return response.json() as Promise<T>;+}++export async function listCourses(options?: {+ force?: boolean;+}): Promise<StudyCourse[]> {+ return withClientCache<StudyCourse[]>(+ "courses:list",+ async () => {+ const response = await apiFetch(apiUrl("/api/v1/courses"), {+ cache: "no-store",+ });+ return (+ (await expectJson<{ courses: StudyCourse[] }>(response)).courses ?? []+ );+ },+ { force: options?.force, ttlMs: 15_000 },+ );+}++export async function createCourse(input: {+ name: string;+ description?: string;+ color?: string;+}): Promise<StudyCourse> {+ const response = await apiFetch(apiUrl("/api/v1/courses"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ });+ const course = (await expectJson<{ course: StudyCourse }>(response)).course;+ invalidateClientCache("courses:");+ return course;+}++export async function updateCourse(+ courseId: string,+ input: Partial<Pick<StudyCourse, "name" | "description" | "color">>,+): Promise<StudyCourse> {+ const response = await apiFetch(apiUrl(`/api/v1/courses/${courseId}`), {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ });+ const course = (await expectJson<{ course: StudyCourse }>(response)).course;+ invalidateClientCache("courses:");+ return course;+}++export async function deleteCourse(courseId: string): Promise<void> {+ const response = await apiFetch(apiUrl(`/api/v1/courses/${courseId}`), {+ method: "DELETE",+ });+ await expectJson<{ deleted: boolean }>(response);+ invalidateClientCache("courses:");+}diff --git a/web/lib/selection-tutor.ts b/web/lib/selection-tutor.tsnew file mode 100644index 000000000..b0207b9a8--- /dev/null+++ b/web/lib/selection-tutor.ts@@ -0,0 +1,42 @@+const MAX_SELECTED_TEXT_LENGTH = 12_000;++export interface SelectionTutorContext {+ selectedText: string;+ parentSessionId: string | null;+}++/** Collapse selection-only whitespace while preserving paragraph breaks. */+export function normalizeSelectedText(value: string): string {+ return value+ .replace(/\r\n?/g, "\n")+ .replace(/[\t\f\v ]+/g, " ")+ .replace(/ *\n */g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim()+ .slice(0, MAX_SELECTED_TEXT_LENGTH);+}++/** Small deterministic id so selecting the same passage reuses its tutor tab. */+export function selectionTutorKey(+ selectedText: string,+ parentSessionId: string | null,+): string {+ let hash = 2166136261;+ const source = `${parentSessionId ?? "draft"}\u0000${selectedText}`;+ for (let i = 0; i < source.length; i += 1) {+ hash ^= source.charCodeAt(i);+ hash = Math.imul(hash, 16777619);+ }+ return `selection-tutor:${parentSessionId ?? "draft"}:${(hash >>> 0).toString(36)}`;+}++export function buildSelectionTutorConfig(+ context: SelectionTutorContext,+): Record<string, unknown> {+ return {+ selection_tutor_context: {+ selected_text: normalizeSelectedText(context.selectedText),+ parent_session_id: context.parentSessionId ?? "",+ },+ };+}diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 724a5d5ea..33ed92c61 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -41,6 +41,13 @@ export interface SessionPreferences {* shown at that branch point. Missing keys default to the latest* sibling (most recently created child). */selected_branches?: Record<string, number>;+ /** Study-course organization. Empty/absent means Unclassified. */+ course_id?: string;+ /** Source conversation for nested selected-text tutor threads. */+ parent_session_id?: string;+ session_kind?: "chat" | "selection_tutor";+ pinned?: boolean;+ archived?: boolean;}export interface SessionSummary {@@ -52,12 +59,7 @@ export interface SessionSummary {message_count: number;last_message: string;status?:- | "idle"- | "running"- | "completed"- | "failed"- | "cancelled"- | "rejected";+ "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";active_turn_id?: string;preferences?: SessionPreferences;}@@ -82,12 +84,7 @@ export interface SessionDetail {created_at: number;updated_at: number;status?:- | "idle"- | "running"- | "completed"- | "failed"- | "cancelled"- | "rejected";+ "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";active_turn_id?: string;compressed_summary?: string;summary_up_to_msg_id?: number;@@ -148,6 +145,19 @@ export async function listSessions();}+/** Fetch the complete session index in bounded pages for course organization. */+export async function listAllSessions(options?: {+ force?: boolean;+}): Promise<SessionSummary[]> {+ const pageSize = 200;+ const sessions: SessionSummary[] = [];+ for (let offset = 0; ; offset += pageSize) {+ const page = await listSessions(pageSize, offset, options);+ sessions.push(...page);+ if (page.length < pageSize) return sessions;+ }+}+export async function getSession(sessionId: string,signal?: AbortSignal,@@ -173,6 +183,31 @@ export async function updateSessionTitle(return data.session;}+export type SessionOrganizationPatch = Partial<{+ course_id: string;+ parent_session_id: string;+ session_kind: "chat" | "selection_tutor";+ pinned: boolean;+ archived: boolean;+}>;++export async function updateSessionOrganization(+ sessionId: string,+ patch: SessionOrganizationPatch,+): Promise<SessionDetail> {+ const response = await apiFetch(+ apiUrl(`/api/v1/sessions/${sessionId}/organization`),+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ },+ );+ const data = await expectJson<{ session: SessionDetail }>(response);+ invalidateClientCache("sessions:");+ return data.session;+}+export async function deleteSession(sessionId: string): Promise<void> {const response = await apiFetch(apiUrl(`/api/v1/sessions/${sessionId}`), {method: "DELETE",diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 0cd2ec5fc..bc6f28b3f 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3344,5 +3344,57 @@"No chat accounts connected yet.": "No chat accounts connected yet.","Disconnect": "Disconnect","Shared with you": "Shared with you",- "Your companions, plus the ones shared with you — each with its own soul, library, and channels.": "Your companions, plus the ones shared with you — each with its own soul, library, and channels."+ "Your companions, plus the ones shared with you — each with its own soul, library, and channels.": "Your companions, plus the ones shared with you — each with its own soul, library, and channels.",+ "Little Tutor": "Little Tutor",+ "Ask Little Tutor": "Ask Little Tutor",+ "Ask about selected text": "Ask about selected text",+ "Selected text": "Selected text",+ "Ask anything about the selected text.": "Ask anything about the selected text.",+ "My courses": "My courses",+ "Create a course": "Create a course",+ "Create your first course": "Create your first course",+ "Course name": "Course name",+ "e.g. Operating Systems": "e.g. Operating Systems",+ "What are you learning in this course?": "What are you learning in this course?",+ "Book-spine color": "Book-spine color",+ "Choose color": "Choose color",+ "Couldn't save this course.": "Couldn't save this course.",+ "Create course": "Create course",+ "No conversations in this course": "No conversations in this course",+ "Unclassified": "Unclassified",+ "Conversation actions": "Conversation actions",+ "Hide tutor threads": "Hide tutor threads",+ "Show tutor threads": "Show tutor threads",+ "Unpin": "Unpin",+ "Pin": "Pin",+ "Restore from archive": "Restore from archive",+ "Archive": "Archive",+ "Move to course": "Move to course",+ "Keep each subject's conversations together without mixing their context.": "Keep each subject's conversations together without mixing their context.",+ "New course": "New course",+ "Start with a subject such as Operating Systems or Network Security.": "Start with a subject such as Operating Systems or Network Security.",+ "A focused home for this subject.": "A focused home for this subject.",+ "Loading course": "Loading course",+ "Course not found": "Course not found",+ "Back to Learning Space": "Back to Learning Space",+ "Course": "Course",+ "{{count}} active conversations": "{{count}} active conversations",+ "New course chat": "New course chat",+ "Course actions": "Course actions",+ "Edit course": "Edit course",+ "Delete course": "Delete course",+ "Conversations": "Conversations",+ "Tutor threads stay nested under the conversation they came from.": "Tutor threads stay nested under the conversation they came from.",+ "Archived conversations": "Archived conversations",+ "Delete course?": "Delete course?",+ "Conversations will not be deleted. They will move to Unclassified.": "Conversations will not be deleted. They will move to Unclassified.",+ "Filter by course": "Filter by course",+ "All courses": "All courses",+ "Filter by conversation type": "Filter by conversation type",+ "All conversation types": "All conversation types",+ "Main conversations": "Main conversations",+ "Tutor threads": "Tutor threads",+ "Filter by archive status": "Filter by archive status",+ "Active and archived": "Active and archived",+ "Loading conversations": "Loading conversations"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 767360e96..cca26990d 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3344,5 +3344,57 @@"No chat accounts connected yet.": "还没有关联任何聊天账号。","Disconnect": "解除关联","Shared with you": "共享给你",- "Your companions, plus the ones shared with you — each with its own soul, library, and channels.": "你的伙伴,以及共享给你的伙伴——每个都有自己的灵魂、资料库和频道。"+ "Your companions, plus the ones shared with you — each with its own soul, library, and channels.": "你的伙伴,以及共享给你的伙伴——每个都有自己的灵魂、资料库和频道。",+ "Little Tutor": "小老师",+ "Ask Little Tutor": "问小老师",+ "Ask about selected text": "针对选中内容提问",+ "Selected text": "选中内容",+ "Ask anything about the selected text.": "可以针对这段选中内容继续提问。",+ "My courses": "我的课程",+ "Create a course": "创建课程",+ "Create your first course": "创建第一门课程",+ "Course name": "课程名称",+ "e.g. Operating Systems": "例如:操作系统",+ "What are you learning in this course?": "这门课程主要学习什么?",+ "Book-spine color": "书脊颜色",+ "Choose color": "选择颜色",+ "Couldn't save this course.": "无法保存这门课程。",+ "Create course": "创建课程",+ "No conversations in this course": "这门课程还没有聊天",+ "Unclassified": "未分类",+ "Conversation actions": "聊天操作",+ "Hide tutor threads": "收起小老师追问",+ "Show tutor threads": "展开小老师追问",+ "Unpin": "取消置顶",+ "Pin": "置顶",+ "Restore from archive": "从归档恢复",+ "Archive": "归档",+ "Move to course": "移动到课程",+ "Keep each subject's conversations together without mixing their context.": "按课程归拢聊天,同时保持各自上下文独立。",+ "New course": "新建课程",+ "Start with a subject such as Operating Systems or Network Security.": "可以先从“操作系统”或“网络安全”开始。",+ "A focused home for this subject.": "这门课程的专属学习空间。",+ "Loading course": "正在加载课程",+ "Course not found": "未找到课程",+ "Back to Learning Space": "返回学习空间",+ "Course": "课程",+ "{{count}} active conversations": "{{count}} 个进行中的聊天",+ "New course chat": "新建课程聊天",+ "Course actions": "课程操作",+ "Edit course": "编辑课程",+ "Delete course": "删除课程",+ "Conversations": "聊天",+ "Tutor threads stay nested under the conversation they came from.": "小老师追问会折叠在它所来源的聊天下面。",+ "Archived conversations": "已归档聊天",+ "Delete course?": "删除课程?",+ "Conversations will not be deleted. They will move to Unclassified.": "聊天不会被删除,而会移动到“未分类”。",+ "Filter by course": "按课程筛选",+ "All courses": "全部课程",+ "Filter by conversation type": "按聊天类型筛选",+ "All conversation types": "全部聊天类型",+ "Main conversations": "主聊天",+ "Tutor threads": "小老师追问",+ "Filter by archive status": "按归档状态筛选",+ "Active and archived": "进行中与已归档",+ "Loading conversations": "正在加载聊天"}diff --git a/web/tests/course-organization-api.test.ts b/web/tests/course-organization-api.test.tsnew file mode 100644index 000000000..ffa884a2c--- /dev/null+++ b/web/tests/course-organization-api.test.ts@@ -0,0 +1,69 @@+import test from "node:test";+import assert from "node:assert/strict";++import { listAllSessions, updateSessionOrganization } from "../lib/session-api";++test("course organization fetches every session page", async () => {+ const original = globalThis.fetch;+ const offsets: number[] = [];+ (globalThis as { fetch: typeof fetch }).fetch = async (input) => {+ const url = new URL(String(input), "http://deeptutor.local");+ const offset = Number(url.searchParams.get("offset") || 0);+ offsets.push(offset);+ const count = offset === 0 ? 200 : offset === 200 ? 3 : 0;+ return new Response(+ JSON.stringify({+ sessions: Array.from({ length: count }, (_, index) => ({+ id: `session-${offset + index}`,+ session_id: `session-${offset + index}`,+ title: "Chat",+ created_at: 1,+ updated_at: 1,+ message_count: 1,+ last_message: "",+ })),+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ };++ try {+ const sessions = await listAllSessions({ force: true });+ assert.equal(sessions.length, 203);+ assert.deepEqual(offsets, [0, 200]);+ } finally {+ (globalThis as { fetch: typeof fetch }).fetch = original;+ }+});++test("course organization patch sends only the requested metadata", async () => {+ const original = globalThis.fetch;+ let capturedUrl = "";+ let capturedBody: unknown;+ (globalThis as { fetch: typeof fetch }).fetch = async (input, init) => {+ capturedUrl = String(input);+ capturedBody = JSON.parse(String(init?.body));+ return new Response(+ JSON.stringify({+ session: {+ id: "child",+ session_id: "child",+ preferences: capturedBody,+ },+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ };++ try {+ const session = await updateSessionOrganization("child", {+ course_id: "course-os",+ pinned: true,+ });+ assert.equal(capturedUrl, "/api/v1/sessions/child/organization");+ assert.deepEqual(capturedBody, { course_id: "course-os", pinned: true });+ assert.equal(session.preferences?.course_id, "course-os");+ } finally {+ (globalThis as { fetch: typeof fetch }).fetch = original;+ }+});diff --git a/web/tests/selection-tutor.test.ts b/web/tests/selection-tutor.test.tsnew file mode 100644index 000000000..556566ce1--- /dev/null+++ b/web/tests/selection-tutor.test.ts@@ -0,0 +1,36 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ buildSelectionTutorConfig,+ normalizeSelectedText,+ selectionTutorKey,+} from "../lib/selection-tutor";++test("normalizes selected chat text without flattening paragraphs", () => {+ assert.equal(+ normalizeSelectedText(" first line\r\n\r\n\r\n second\tline "),+ "first line\n\nsecond line",+ );+});++test("selection tutor keys are stable per passage and parent session", () => {+ const a = selectionTutorKey("fork() returns twice", "session-a");+ assert.equal(a, selectionTutorKey("fork() returns twice", "session-a"));+ assert.notEqual(a, selectionTutorKey("fork() returns twice", "session-b"));+ assert.notEqual(a, selectionTutorKey("wait() blocks", "session-a"));+});++test("builds runtime-only selected text context", () => {+ assert.deepEqual(+ buildSelectionTutorConfig({+ selectedText: " selected passage ",+ parentSessionId: "parent-1",+ }),+ {+ selection_tutor_context: {+ selected_text: "selected passage",+ parent_session_id: "parent-1",+ },+ },+ );+});