DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: add remote Hermes connected agent backend (#1208)
Yuv51b0225a01e4
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 8c535f3d2..672bf6145 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -155,6 +155,8 @@ jobs:import-check:name: Import Check (Python ${{ matrix.python-version }}, ${{ matrix.os }})runs-on: ${{ matrix.os }}+ env:+ PYTHONIOENCODING: utf-8strategy:fail-fast: falsematrix:diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 560134722..63d74924c 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -43,7 +43,12 @@ from deeptutor.knowledge.manager import KnowledgeBaseManagerfrom deeptutor.knowledge.naming import validate_knowledge_base_namefrom deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTrackerfrom deeptutor.logging import PROCESS_LOG_PRIVATE_ATTR-from deeptutor.multi_user.context import get_current_user+from deeptutor.multi_user.context import (+ get_current_user,+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)from deeptutor.multi_user.knowledge_access import (assert_writable,current_kb_base_dir,@@ -201,6 +206,14 @@ class SupportedFileTypesInfo(BaseModel):allow_any_extension: bool = False+class IndexingLLMSelectionRequest(BaseModel):+ """Secret-free catalog identity for an empty LightRAG knowledge base."""++ profile_id: str = Field(min_length=1)+ model_id: str = Field(min_length=1)+ reasoning_effort: str | None = None++IMAGE_ACCEPT_MIME_TYPES = {".bmp": "image/bmp",".gif": "image/gif",@@ -651,6 +664,35 @@ def _validate_registered_provider(raw_provider: str | None) -> str:return normalize_provider_name(raw_provider)+def _freeze_indexing_llm_form(raw: str):+ """Parse and resolve the optional LightRAG selection exactly once."""+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ IndexingPolicyError,+ freeze_snapshot,+ )++ try:+ selection = json.loads(raw)+ if not isinstance(selection, dict) or not selection:+ raise ValueError("indexing_llm must be a non-empty JSON object.")+ return selection, freeze_snapshot(selection)+ except (json.JSONDecodeError, ValueError, PermissionError, IndexingPolicyError) as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+++def _freeze_default_indexing_llm():+ """Freeze the released LightRAG model default for one create or rebuild."""+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ IndexingPolicyError,+ freeze_default_snapshot,+ )++ try:+ return freeze_default_snapshot()+ except (ValueError, PermissionError, IndexingPolicyError) as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++def _assert_provider_ready(provider: str) -> None:"""Block creating/using a KB whose engine isn't ready.@@ -846,6 +888,14 @@ def _matching_index_is_valid(kb_name: str, matching_version: dict | None) -> booasync def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id: str):"""Background task for knowledge base initialization"""+ owner = getattr(initializer, "owner", None)+ if owner is not None and get_current_user_or_none() != owner:+ token = set_current_user(owner)+ try:+ return await run_initialization_task(initializer, task_id)+ finally:+ reset_current_user(token)+task_manager = TaskIDManager.get_instance()task_stream_manager = get_task_stream_manager()task_stream_manager.ensure_task(task_id)@@ -908,6 +958,19 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_iderror_msg = str(e)trace = _tb.format_exc()+ if getattr(initializer, "index_published", False):+ _task_log(+ task_id,+ "LightRAG index was published; final status bookkeeping will be reconciled.",+ level="warning",+ )+ _server_task_trace(task_id, trace)+ task_manager.update_task_status(task_id, "completed")+ task_stream_manager.emit_complete(+ task_id,+ f"Knowledge base '{initializer.kb_name}' index published",+ )+ returnfailure_metadata = _exception_failure_metadata(e)_task_log(task_id, f"Initialization failed: {error_msg}", level="error")@@ -949,6 +1012,7 @@ async def run_upload_processing_task(rag_provider: str = None,folder_id: str = None,folder_root: str = None,+ owner=None,):"""Background task for processing uploaded files.@@ -962,9 +1026,25 @@ async def run_upload_processing_task(from a folder sync. Preserves each file's path relative to itinstead of flattening to the bare filename."""+ if owner is not None and get_current_user_or_none() != owner:+ token = set_current_user(owner)+ try:+ return await run_upload_processing_task(+ kb_name=kb_name,+ base_dir=base_dir,+ uploaded_file_paths=uploaded_file_paths,+ task_id=task_id,+ rag_provider=rag_provider,+ folder_id=folder_id,+ folder_root=folder_root,+ )+ finally:+ reset_current_user(token)+task_manager = TaskIDManager.get_instance()task_stream_manager = get_task_stream_manager()task_stream_manager.ensure_task(task_id)+ index_published = Falseprogress_tracker = ProgressTracker(kb_name, Path(base_dir))progress_tracker.task_id = task_id@@ -1059,6 +1139,10 @@ async def run_upload_processing_task()return+ index_published = rag_provider == LIGHTRAG_PROVIDER and bool(+ index_result.processed_count+ )+progress_tracker.update(ProgressStage.PROCESSING_DOCUMENTS,message_key="Saving metadata...",@@ -1103,6 +1187,19 @@ async def run_upload_processing_task(error_msg = f"Upload processing failed (KB '{kb_name}'): {e}"trace = _tb.format_exc()+ if index_published:+ _task_log(+ task_id,+ "LightRAG index changes were published; final upload bookkeeping "+ "will be reconciled.",+ level="warning",+ )+ _server_task_trace(task_id, trace)+ task_manager.update_task_status(task_id, "completed")+ task_stream_manager.emit_complete(+ task_id, f"LightRAG changes for '{kb_name}' published"+ )+ returnfailure_metadata = _exception_failure_metadata(e)_task_log(task_id, error_msg, level="error")_server_task_trace(task_id, trace)@@ -2822,6 +2919,7 @@ async def upload_files(uploaded_file_paths=uploaded_file_paths,task_id=task_id,rag_provider=kb_provider,+ owner=get_current_user(),)return {@@ -2848,6 +2946,7 @@ async def create_knowledge_base(pageindex_mode: str = Form(""),search_mode: str = Form(""),rel_paths: list[str] = Form(None),+ indexing_llm: str = Form(""),):"""Create a new knowledge base and initialize it with files."""try:@@ -2862,6 +2961,17 @@ async def create_knowledge_base(raise HTTPException(status_code=400, detail=f"Knowledge base '{name}' already exists")rag_provider = _validate_registered_provider(rag_provider)+ indexing_snapshot = None+ if rag_provider == LIGHTRAG_PROVIDER:+ if indexing_llm:+ _, indexing_snapshot = _freeze_indexing_llm_form(indexing_llm)+ else:+ indexing_snapshot = _freeze_default_indexing_llm()+ elif indexing_llm:+ raise HTTPException(+ status_code=400,+ detail="indexing_llm is supported only for built-in LightRAG.",+ )pageindex_mode = str(pageindex_mode or "").strip().lower()if rag_provider == PAGEINDEX_OSS_PROVIDER and pageindex_mode not in {"",@@ -2925,6 +3035,10 @@ async def create_knowledge_base(manager.config["knowledge_bases"][name]["pageindex_mode"] = pageindex_modeif search_mode:manager.config["knowledge_bases"][name]["search_mode"] = search_mode+ if indexing_snapshot is not None:+ pending_policy = indexing_snapshot.persisted_policy()+ pending_policy["policy"] = "pending_pinned"+ manager.config["knowledge_bases"][name]["pending_indexing_policy"] = pending_policymanager._save_config()progress_tracker = ProgressTracker(name, kb_base_dir)@@ -2934,6 +3048,8 @@ async def create_knowledge_base(base_dir=str(kb_base_dir),progress_tracker=progress_tracker,rag_provider=rag_provider,+ indexing_snapshot=indexing_snapshot,+ owner=get_current_user(),)initializer.create_directory_structure()@@ -3006,7 +3122,14 @@ async def create_knowledge_base(raise HTTPException(status_code=500, detail=str(e))-async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_hash: str) -> None:+async def run_reindex_task(+ kb_name: str,+ base_dir: str,+ task_id: str,+ signature_hash: str,+ indexing_snapshot=None,+ owner=None,+) -> None:"""Re-index a KB's raw documents against the currently-active embedding config.Each ``(profile, model, dimension, base_url)`` combination gets its own@@ -3014,9 +3137,23 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_untouched so switching the active embedding model back to apreviously-indexed one reuses the existing version with no extra work."""+ if owner is not None and get_current_user_or_none() != owner:+ token = set_current_user(owner)+ try:+ return await run_reindex_task(+ kb_name=kb_name,+ base_dir=base_dir,+ task_id=task_id,+ signature_hash=signature_hash,+ indexing_snapshot=indexing_snapshot,+ )+ finally:+ reset_current_user(token)+task_manager = TaskIDManager.get_instance()task_stream_manager = get_task_stream_manager()task_stream_manager.ensure_task(task_id)+ index_published = Falsewith capture_task_logs(task_id):try:@@ -3072,9 +3209,11 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_kb_name=kb_name,file_paths=file_paths,progress_callback=_on_progress,+ indexing_snapshot=indexing_snapshot,)if not success:raise RuntimeError(f"Re-index found no valid documents to index in '{kb_name}'.")+ index_published = signature_hash == LIGHTRAG_PROVIDERcompleted_at = datetime.now().isoformat()metadata_file = kb_dir / "metadata.json"@@ -3156,6 +3295,16 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_error_msg = str(e)trace = _tb.format_exc()+ if index_published:+ _task_log(+ task_id,+ "LightRAG version was published; final status bookkeeping will be reconciled.",+ level="warning",+ )+ _server_task_trace(task_id, trace)+ task_manager.update_task_status(task_id, "completed")+ task_stream_manager.emit_complete(task_id, f"Re-index of '{kb_name}' published")+ returnfailure_metadata = _exception_failure_metadata(e)_task_log(task_id, f"Re-index failed: {error_msg}", level="error")_server_task_trace(task_id, trace)@@ -3176,6 +3325,7 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_async def reindex_knowledge_base(kb_name: str,background_tasks: BackgroundTasks,+ indexing_llm: str = Form(""),):"""Re-index ``kb_name`` through its bound RAG provider.@@ -3192,6 +3342,17 @@ async def reindex_knowledge_base(kb_entry.get("rag_provider") or DEFAULT_PROVIDER)_assert_provider_ready(kb_provider)+ indexing_snapshot = None+ if kb_provider == LIGHTRAG_PROVIDER:+ if indexing_llm:+ _, indexing_snapshot = _freeze_indexing_llm_form(indexing_llm)+ else:+ indexing_snapshot = _freeze_default_indexing_llm()+ elif indexing_llm:+ raise HTTPException(+ status_code=400,+ detail="indexing_llm is supported only for built-in LightRAG.",+ )kb_dir = kb_base_dir / kb_namesignature_hash = kb_provider@@ -3243,6 +3404,8 @@ async def reindex_knowledge_base(base_dir=str(kb_base_dir),task_id=task_id,signature_hash=signature_hash,+ indexing_snapshot=indexing_snapshot,+ owner=get_current_user(),)return {@@ -3258,6 +3421,92 @@ async def reindex_knowledge_base(raise HTTPException(status_code=500, detail=format_exception_message(e))[email protected]("/knowledge-bases/{kb_name}/indexing-policy")+async def update_pending_indexing_policy(+ kb_name: str,+ payload: IndexingLLMSelectionRequest,+):+ """Change the pending model of an empty, unpublished LightRAG KB."""+ manager, kb_name, kb_base_dir = _writable_kb(kb_name)+ kb_entry = _load_kb_entry_or_404(manager, kb_name)+ _assert_not_connected_kb(kb_name, kb_entry)+ provider = _validate_registered_provider(kb_entry.get("rag_provider"))+ if provider != LIGHTRAG_PROVIDER:+ raise HTTPException(+ status_code=400,+ detail="Indexing-model policy is supported only for built-in LightRAG.",+ )++ def assert_no_active_task(entry: dict) -> None:+ status = str(entry.get("status") or "").lower()+ progress = entry.get("progress")+ stage = str(progress.get("stage") or "").lower() if isinstance(progress, dict) else ""+ if status in {"initializing", "processing"} and stage not in {+ "completed",+ "error",+ }:+ raise HTTPException(+ status_code=409,+ detail=(+ "The pending indexing model cannot change while an indexing task is active."+ ),+ )++ assert_no_active_task(kb_entry)+ kb_dir = kb_base_dir / kb_name+ from deeptutor.services.rag.pipelines.lightrag.storage import latest_published_root++ if latest_published_root(kb_dir) is not None:+ raise HTTPException(+ status_code=409,+ detail=(+ "This knowledge base already has a published index; run a full re-index "+ "to change its model."+ ),+ )+ raw_dir = kb_dir / "raw"+ if raw_dir.is_dir() and any(path.is_file() for path in raw_dir.rglob("*")):+ raise HTTPException(+ status_code=409,+ detail=(+ "The pending indexing model can change only while the knowledge base is empty."+ ),+ )++ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ IndexingPolicyError,+ pending_policy_for_selection,+ )++ try:+ policy = pending_policy_for_selection(payload.model_dump(exclude_none=True))+ except (ValueError, PermissionError, IndexingPolicyError) as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ # Re-read immediately before saving so a task queued during model+ # resolution cannot be overwritten through a stale entry reference.+ kb_entry = _load_kb_entry_or_404(manager, kb_name)+ assert_no_active_task(kb_entry)+ if latest_published_root(kb_dir) is not None:+ raise HTTPException(+ status_code=409,+ detail=(+ "This knowledge base already has a published index; run a full re-index "+ "to change its model."+ ),+ )+ if raw_dir.is_dir() and any(path.is_file() for path in raw_dir.rglob("*")):+ raise HTTPException(+ status_code=409,+ detail=(+ "The pending indexing model can change only while the knowledge base is empty."+ ),+ )+ kb_entry["pending_indexing_policy"] = policy+ manager._save_config()+ return {"indexing_policy": policy}++@router.post("/knowledge-bases/{kb_name}/retry")async def retry_knowledge_base(kb_name: str,@@ -3278,7 +3527,7 @@ async def retry_knowledge_base("Use re-index when you want to rebuild a healthy knowledge base."),)- return await reindex_knowledge_base(resolved_name, background_tasks)+ return await reindex_knowledge_base(resolved_name, background_tasks, indexing_llm="")except HTTPException:raiseexcept Exception as e:@@ -3708,6 +3957,7 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Backgroundrag_provider=kb_provider,folder_id=folder_id, # Pass folder_id to update state on successfolder_root=folder_path, # Preserve each file's path relative to this root+ owner=get_current_user(),)return {diff --git a/deeptutor/api/routers/mastery_path.py b/deeptutor/api/routers/mastery_path.pyindex 89efd5c10..6e6040ec2 100644--- a/deeptutor/api/routers/mastery_path.py+++ b/deeptutor/api/routers/mastery_path.py@@ -653,6 +653,57 @@ async def get_progress_map(book_id: str):}[email protected]("/progress/{book_id}/board")+async def get_progress_board(book_id: str):+ """The visual learning board: every knowledge point as a card, enriched+ with its next review time and a deterministic grid position derived from+ the module order. A read-only projection of the same mastery data the+ tutor and the map view use."""+ _validate_book_id(book_id)+ service = get_learning_service()+ progress = service.get_or_create(book_id)+ summary = learning_policy.map_summary(progress)++ due_by_kp = {task.knowledge_point_id: task.due_at for task in progress.review_queue}++ cards: list[dict] = []+ modules: list[dict] = []+ for module in summary["modules"]:+ module_cards: list[dict] = []+ for index, kp in enumerate(module["knowledge_points"]):+ card = {+ "id": kp["id"],+ "name": kp["name"],+ "type": kp["type"],+ "module_id": module["id"],+ "module_name": module["name"],+ "status": kp["status"],+ "mastery_level": kp["mastery"],+ "next_review_at": due_by_kp.get(kp["id"]),+ "position": {"column": module["order"], "row": index},+ }+ cards.append(card)+ module_cards.append(card)+ modules.append(+ {+ "id": module["id"],+ "name": module["name"],+ "order": module["order"],+ "mastered": module["mastered"],+ "total": module["total"],+ "cards": module_cards,+ }+ )++ return {+ "book_id": book_id,+ "name": summary["name"],+ "path_revision": progress.version,+ "cards": cards,+ "modules": modules,+ }++@router.get("/progress/{book_id}/objectives/{kp_id}")async def get_objective_report(book_id: str, kp_id: str):"""The evidence behind one objective: attempts, schedule, errors, prompts.diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.pyindex 13d9305f4..53b3435c5 100644--- a/deeptutor/api/routers/sessions.py+++ b/deeptutor/api/routers/sessions.py@@ -165,6 +165,20 @@ async def get_session(session_id: str):return session[email protected]("/{session_id}/messages/{message_id}/events")+async def get_message_events(+ session_id: str,+ message_id: str,+ after_seq: int = Query(default=0, ge=0),+ limit: int = Query(default=500, ge=1, le=1000),+):+ store = get_session_store()+ trace = await store.get_message_trace(session_id, message_id, after_seq, limit)+ if trace is None:+ raise HTTPException(status_code=404, detail="Message not found")+ return trace++@router.get("/{session_id}/ask-hint")async def get_session_ask_hint(session_id: str) -> dict[str, Any]:"""One line the user is likely to type next, for the home composer placeholder."""diff --git a/deeptutor/api/routers/subagents.py b/deeptutor/api/routers/subagents.pyindex 6d7448261..e79a3d95c 100644--- a/deeptutor/api/routers/subagents.py+++ b/deeptutor/api/routers/subagents.py@@ -1,17 +1,15 @@"""Subagent connections API.Backs the "My Agents → connected agents" feature: detect which local agent CLIs-(Claude Code, Codex, Antigravity CLI, Kimi CLI, opencode, MiMo Code, Hermes Agent,-OpenClaw, DeepSeek Harness) are installed on-this machine, connect one as a pointer KB the chat composer can select, and-configure the consult budget. Connections are+or configured remote backends are usable, connect one as a pointer KB the chat+composer can select, and configure the consult budget. Connections arestored as ``type: subagent`` knowledge bases (per-user, via the KB manager), sothey ride the same selection/persistence path as the other connected KB types —the subagent capability drives them live, nothing is indexed.-The CLIs run on the host with the host user's own credentials, so detection is-machine-global; whether a connection is usable is simply "is the CLI installed-here". If it isn't, the UI just doesn't offer it.+Local CLIs run on the host with the host user's credentials; remote backends+use deployment-wide server configuration. Detection is therefore machine-+global. Unavailable runtimes are not offered by the connection UI."""from __future__ import annotations@@ -47,7 +45,7 @@ class ConnectSubagentRequest(BaseModel):agent_kind: strcwd: str = ""# For the partner backend (``agent_kind == "partner"``): which partner to- # consult. Ignored by the local-CLI backends, which use ``cwd`` instead.+ # consult. Ignored by local and remote agent backends.partner_id: str = ""@@ -63,7 +61,7 @@ class SubagentMessageRequest(BaseModel):@router.get("/detect")async def detect_subagents():- """Report which agent CLIs are installed and usable on this machine."""+ """Report which local and remote agent backends are usable."""detections = await detect_all()return {"backends": [d.to_dict() for d in detections]}@@ -132,7 +130,7 @@ async def list_connections():@router.post("/connections")async def create_connection(payload: ConnectSubagentRequest):- """Connect a subagent (a local CLI, or one of the user's partners) as a selectable KB.+ """Connect a local, remote, or Partner subagent as a selectable KB.A partner connection (``agent_kind == "partner"``) binds a ``partner_id``instead of a working directory: consulting it opens a fresh session on that@@ -164,8 +162,11 @@ async def create_connection(payload: ConnectSubagentRequest):if not get_partner_manager().partner_exists(partner_id):raise HTTPException(status_code=400, detail=f"No partner named {partner_id!r}.")else:+ from deeptutor.services.subagent import get_backend++ backend = get_backend(agent_kind)raw_cwd = (payload.cwd or "").strip()- if raw_cwd:+ if raw_cwd and backend is not None and getattr(backend, "local_cli", True):try:resolved_cwd = str(assert_path_allowed(raw_cwd))except ValueError as exc:diff --git a/deeptutor/api/routers/video_learning.py b/deeptutor/api/routers/video_learning.pyindex 0218610b0..93daf9dd9 100644--- a/deeptutor/api/routers/video_learning.py+++ b/deeptutor/api/routers/video_learning.py@@ -7,16 +7,18 @@ from typing import Anyfrom urllib.parse import urljoin, urlparsefrom fastapi import APIRouter, HTTPException, Request-from fastapi.responses import Response, StreamingResponse+from fastapi.responses import JSONResponse, Response, StreamingResponseimport httpxfrom pydantic import BaseModel, Fieldfrom starlette.background import BackgroundTask+from deeptutor.multi_user.paths import current_owner_idfrom deeptutor.services.notebook.service import NotebookCorruptedErrorfrom deeptutor.video_learning import (TimedMediaError,TimedMediaNotFound,get_timed_media_store,+ invidious_account,load_video_learning_settings,material_with_playback,refresh_invidious_transcript,@@ -111,6 +113,44 @@ async def test_invidious(payload: VideoLearningSettingsRequest) -> dict[str, Anyraise _http_error(exc) from exc[email protected]("/invidious/account/authorize")+async def authorize_invidious_account() -> dict[str, str]:+ try:+ url = invidious_account.begin_invidious_account_authorization(+ owner_id=current_owner_id(),+ redirect_uri=invidious_account.invidious_redirect_uri(),+ )+ except Exception as exc:+ raise _http_error(exc) from exc+ return {"authorize_url": url}++[email protected]("/invidious/account/callback")+async def invidious_account_callback(token: str = "", state: str = "") -> JSONResponse:+ try:+ status = await invidious_account.complete_invidious_account_authorization(+ owner_id=current_owner_id(),+ state=state,+ token=token,+ )+ except Exception as exc:+ raise _http_error(exc) from exc+ return JSONResponse(status, headers={"Cache-Control": "no-store"})++[email protected]("/invidious/account/status")+async def get_invidious_account_status() -> dict[str, Any]:+ return invidious_account.invidious_account_status(current_owner_id())++[email protected]("/invidious/account/disconnect")+async def disconnect_invidious_account() -> dict[str, Any]:+ try:+ return await invidious_account.disconnect_invidious_account(owner_id=current_owner_id())+ except Exception as exc:+ raise _http_error(exc) from exc++@router.post("/materials/resolve")async def resolve_video(payload: ResolveRequest) -> dict[str, Any]:try:@@ -167,6 +207,22 @@ async def list_video_notes(material_id: str) -> list[dict[str, Any]]:raise _note_error(exc) from exc[email protected]("/materials/{material_id}/notes.md")+async def export_video_notes(material_id: str) -> Response:+ try:+ markdown = video_notes.export_notes(video_notes.get_notebook_manager(), material_id)+ return Response(+ markdown,+ media_type="text/markdown",+ headers={+ "Cache-Control": "no-store",+ "Content-Disposition": 'attachment; filename="video-notes.md"',+ },+ )+ except Exception as exc:+ raise _note_error(exc) from exc++@router.post("/materials/{material_id}/notes")async def create_video_note(material_id: str, payload: CreateVideoNoteRequest) -> dict[str, Any]:try:diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.pyindex 68f6f40d6..8212af3b9 100644--- a/deeptutor/knowledge/add_documents.py+++ b/deeptutor/knowledge/add_documents.py@@ -19,10 +19,12 @@ from deeptutor.services.config import resolve_llm_runtime_configfrom deeptutor.services.file_io import atomic_write_jsonfrom deeptutor.services.rag.factory import (DEFAULT_PROVIDER,+ LIGHTRAG_PROVIDER,has_ready_provider_index,normalize_provider_name,)from deeptutor.services.rag.file_routing import FileTypeRouter+from deeptutor.services.rag.index_versioning import list_kb_versionsfrom deeptutor.services.rag.provider_binding import resolve_bound_providerfrom deeptutor.services.rag.service import RAGService@@ -188,7 +190,10 @@ class DocumentAdder:f"Knowledge base '{kb_name}' uses legacy index format and requires reindex before incremental add")- if not has_provider_index:+ allows_lightrag_bootstrap = self.rag_provider == LIGHTRAG_PROVIDER and not list_kb_versions(+ self.kb_dir+ )+ if not has_provider_index and not allows_lightrag_bootstrap:raise ValueError(f"Knowledge base not initialized ({self.rag_provider}): {kb_name}")self.api_key = api_key@@ -328,7 +333,17 @@ class DocumentAdder:# this runs inside a FastAPI BackgroundTasks entry, which is# awaited on the loop and would otherwise stall unrelated# requests once per indexed file (#777).- await asyncio.to_thread(self._record_successful_hash, doc_file)+ try:+ await asyncio.to_thread(self._record_successful_hash, doc_file)+ except Exception:+ if self.rag_provider != LIGHTRAG_PROVIDER:+ raise+ logger.warning(+ "LightRAG published '%s' before its duplicate-detection hash "+ "was recorded",+ doc_file.name,+ exc_info=True,+ )logger.info(f"Processed: {doc_file.name}")if self.progress_tracker is not None:self.progress_tracker.update(@@ -413,43 +428,53 @@ async def _bootstrap_index_from_files(f"Failed to initialize index for KB '{kb_name}' from {len(source_files)} file(s)")- # Record hashes so future syncs detect unchanged files.- metadata = _read_metadata(metadata_file)- hashes = metadata.setdefault("file_hashes", {})- for fpath_str in source_files:- fpath = Path(fpath_str)- sha = hashlib.sha256()- with open(fpath, "rb") as fh:- for block in iter(lambda: fh.read(65536), b""):- sha.update(block)- hashes[_raw_hash_key(fpath, raw_dir)] = sha.hexdigest()- metadata["rag_provider"] = rag_service._resolve_provider(kb_name)- metadata["needs_reindex"] = False- ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")- metadata["last_updated"] = ts- metadata["last_indexed_at"] = ts- metadata["last_indexed_count"] = len(source_files)- metadata["last_indexed_action"] = "create"- _write_metadata(metadata_file, metadata)-indexed = len(source_files)- manager.update_kb_status(- name=kb_name,- status="ready",- progress={- "stage": "completed",- "message": f"Initialized index with {indexed} file(s).",- "percent": 100,- "current": indexed,- "total": max(indexed, 1),- "file_name": "",- "error": None,- "timestamp": datetime.now().isoformat(),- "indexed_count": indexed,- "index_changed": True,- "index_action": "create",- },- )+ provider = rag_service._resolve_provider(kb_name)+ try:+ # Record hashes so future syncs detect unchanged files.+ metadata = _read_metadata(metadata_file)+ hashes = metadata.setdefault("file_hashes", {})+ for fpath_str in source_files:+ fpath = Path(fpath_str)+ sha = hashlib.sha256()+ with open(fpath, "rb") as fh:+ for block in iter(lambda: fh.read(65536), b""):+ sha.update(block)+ hashes[_raw_hash_key(fpath, raw_dir)] = sha.hexdigest()+ metadata["rag_provider"] = provider+ metadata["needs_reindex"] = False+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")+ metadata["last_updated"] = ts+ metadata["last_indexed_at"] = ts+ metadata["last_indexed_count"] = indexed+ metadata["last_indexed_action"] = "create"+ _write_metadata(metadata_file, metadata)++ manager.update_kb_status(+ name=kb_name,+ status="ready",+ progress={+ "stage": "completed",+ "message": f"Initialized index with {indexed} file(s).",+ "percent": 100,+ "current": indexed,+ "total": max(indexed, 1),+ "file_name": "",+ "error": None,+ "timestamp": datetime.now().isoformat(),+ "indexed_count": indexed,+ "index_changed": True,+ "index_action": "create",+ },+ )+ except Exception:+ if provider != LIGHTRAG_PROVIDER:+ raise+ logger.warning(+ "LightRAG bootstrap for '%s' published before bookkeeping failed",+ kb_name,+ exc_info=True,+ )logger.info("Bootstrapped index for empty KB '%s' with %d file(s)", kb_name, indexed)return indexed@@ -466,6 +491,7 @@ async def add_documents(from deeptutor.knowledge.manager import KnowledgeBaseManagermanager = KnowledgeBaseManager(base_dir=base_dir)+ published_count = 0try:manager.update_kb_status(name=kb_name,@@ -524,6 +550,8 @@ async def add_documents(f"Failed to index {result.failed_count}/{len(new_files)} file(s): "f"{result.failure_summary()}")+ if adder.rag_provider == LIGHTRAG_PROVIDER:+ published_count = result.processed_countadder.update_metadata(result.processed_count)manager.update_kb_status(@@ -545,6 +573,13 @@ async def add_documents()return result.processed_countexcept Exception as exc:+ if published_count:+ logger.warning(+ "LightRAG append for '%s' published before bookkeeping failed",+ kb_name,+ exc_info=True,+ )+ return published_countmanager.update_kb_status(name=kb_name,status="error",diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.pyindex 40feed435..33eb935b2 100644--- a/deeptutor/knowledge/initializer.py+++ b/deeptutor/knowledge/initializer.py@@ -10,7 +10,11 @@ import jsonimport loggingfrom pathlib import Pathimport shutil-from typing import Optional+from typing import TYPE_CHECKING, Optional++if TYPE_CHECKING:+ from deeptutor.multi_user.models import CurrentUser+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingLLMSnapshotfrom deeptutor.knowledge.naming import validate_knowledge_base_namefrom deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker@@ -34,6 +38,8 @@ class KnowledgeBaseInitializer:base_url: str | None = None,progress_tracker: ProgressTracker | None = None,rag_provider: str | None = None,+ indexing_snapshot: IndexingLLMSnapshot | None = None,+ owner: CurrentUser | None = None,):self.kb_name = validate_knowledge_base_name(kb_name)self.base_dir = Path(base_dir)@@ -46,6 +52,9 @@ class KnowledgeBaseInitializer:self.base_url = base_urlself.progress_tracker = progress_tracker or ProgressTracker(self.kb_name, self.base_dir)self.rag_provider = normalize_provider_name(rag_provider)+ self.indexing_snapshot = indexing_snapshot+ self.owner = owner+ self.index_published = Falsedef _register_to_config(self) -> None:"""Register KB in kb_config.json with initializing state."""@@ -205,6 +214,7 @@ class KnowledgeBaseInitializer:file_paths=file_paths,progress_callback=_on_progress,image_progress_callback=_on_image_progress,+ indexing_snapshot=self.indexing_snapshot,)if not success:self.progress_tracker.update(@@ -214,13 +224,23 @@ class KnowledgeBaseInitializer:)raise RuntimeError("RAG pipeline returned failure")- self._update_metadata_with_provider(provider)- self.progress_tracker.update(- ProgressStage.PROCESSING_DOCUMENTS,- message_key="Documents processed successfully",- current=len(doc_files),- total=len(doc_files),- )+ self.index_published = provider == "lightrag"+ try:+ self._update_metadata_with_provider(provider)+ self.progress_tracker.update(+ ProgressStage.PROCESSING_DOCUMENTS,+ message_key="Documents processed successfully",+ current=len(doc_files),+ total=len(doc_files),+ )+ except Exception:+ if not self.index_published:+ raise+ logger.warning(+ "LightRAG index for %s was published before metadata bookkeeping failed",+ self.kb_name,+ exc_info=True,+ )except Exception as e:error_msg = str(e)logger.error(f"Error processing documents: {error_msg}")@@ -231,8 +251,17 @@ class KnowledgeBaseInitializer:)raise- await self.fix_structure()- await self.display_statistics_generic()+ try:+ await self.fix_structure()+ await self.display_statistics_generic()+ except Exception:+ if not self.index_published:+ raise+ logger.warning(+ "LightRAG index for %s was published before statistics bookkeeping failed",+ self.kb_name,+ exc_info=True,+ )return Trueasync def fix_structure(self) -> None:diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 1bea6daf9..a5e2c5cfe 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -35,6 +35,7 @@ from deeptutor.services.rag.factory import (DEFAULT_PROVIDER,IMA_PROVIDER,KNOWN_PROVIDERS,+ LIGHTRAG_PROVIDER,LIGHTRAG_SERVER_PROVIDER,PAGEINDEX_OSS_PROVIDER,PAGEINDEX_PROVIDER,@@ -1390,6 +1391,21 @@ class KnowledgeBaseManager:if kb_config.get("knowledge_base_id"):metadata["knowledge_base_id"] = kb_config.get("knowledge_base_id")+ if rag_provider == LIGHTRAG_PROVIDER:+ from deeptutor.services.rag.pipelines.lightrag.storage import (+ latest_published_root,+ read_published_policy,+ )++ published_root = latest_published_root(kb_dir) if dir_exists else None+ indexing_policy = read_published_policy(published_root)+ if indexing_policy is None:+ pending = kb_config.get("pending_indexing_policy")+ indexing_policy = (+ pending if isinstance(pending, dict) else {"policy": "legacy_unpinned"}+ )+ metadata["indexing_policy"] = indexing_policy+metadata.update(self._embedding_fields(kb_config))# Remove None valuesdiff --git a/deeptutor/learning/tests/test_api_endpoints.py b/deeptutor/learning/tests/test_api_endpoints.pyindex f319ad520..f7f906473 100644--- a/deeptutor/learning/tests/test_api_endpoints.py+++ b/deeptutor/learning/tests/test_api_endpoints.py@@ -683,6 +683,74 @@ class TestGetProgress:assert path_map["path_revision"] == progress["version"]+# -- GET /progress/{book_id}/board ----------------------------------------+++class TestProgressBoard:+ def test_board_empty(self, client):+ resp = client.get("/api/mastery-paths/progress/boardempty/board")+ assert resp.status_code == 200+ data = resp.json()+ assert data["book_id"] == "boardempty"+ assert data["cards"] == []+ assert data["modules"] == []++ def test_board_card_shape_and_position(self, client):+ client.post(+ "/api/mastery-paths/progress/boardbook/init-modules",+ json={+ "modules": [+ {+ "id": "m1",+ "name": "M1",+ "order": 0,+ "knowledge_points": [+ {"id": "kp1", "name": "KP1", "type": "concept", "module_id": "m1"},+ {"id": "kp2", "name": "KP2", "type": "procedure", "module_id": "m1"},+ ],+ },+ {+ "id": "m2",+ "name": "M2",+ "order": 1,+ "knowledge_points": [+ {"id": "kp3", "name": "KP3", "type": "memory", "module_id": "m2"},+ ],+ },+ ]+ },+ )+ resp = client.get("/api/mastery-paths/progress/boardbook/board")+ assert resp.status_code == 200+ data = resp.json()+ assert len(data["cards"]) == 3+ assert len(data["modules"]) == 2++ first = data["cards"][0]+ assert first["id"] == "kp1"+ assert first["name"] == "KP1"+ assert first["type"] == "concept"+ assert first["module_id"] == "m1"+ assert first["module_name"] == "M1"+ assert first["status"] == "new"+ assert first["mastery_level"] == 0.0+ assert first["next_review_at"] is None+ assert first["position"] == {"column": 0, "row": 0}++ third = data["cards"][2]+ assert third["position"] == {"column": 1, "row": 0}++ module = data["modules"][0]+ assert module["name"] == "M1"+ assert module["mastered"] == 0+ assert module["total"] == 2+ assert len(module["cards"]) == 2++ def test_board_invalid_book_id_returns_400(self, client):+ resp = client.get("/api/mastery-paths/progress/a\\b/board")+ assert resp.status_code == 400++# -- DELETE /progress/{book_id} -------------------------------------------diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.pyindex 3cfd5290f..ed95eb6d4 100644--- a/deeptutor/multi_user/model_access.py+++ b/deeptutor/multi_user/model_access.py@@ -101,6 +101,11 @@ def redacted_model_access(user_id: str | None = None) -> dict[str, list[dict[str"model_id": str(model_id),"name": (model or {}).get("name") or str(model_id),"model": (model or {}).get("model") or "",+ "provider": profile.get("binding") or "",+ "reasoning_effort": (model or {}).get("reasoning_effort"),+ "supported_reasoning_efforts": (model or {}).get(+ "codex_supported_reasoning_levels"+ ),"source": "admin","available": model is not None,}@@ -120,6 +125,10 @@ def allowed_llm_options() -> dict[str, Any]:user = get_current_user()if user.is_admin:return list_llm_options(admin_catalog())+ catalog = admin_catalog()+ llm_service = catalog.get("services", {}).get("llm", {})+ active_profile_id = str(llm_service.get("active_profile_id") or "")+ active_model_id = str(llm_service.get("active_model_id") or "")options = [{"profile_id": item.get("profile_id"),@@ -128,14 +137,27 @@ def allowed_llm_options() -> dict[str, Any]:"model_name": item.get("name") or item.get("model") or item.get("model_id"),"label": item.get("name") or item.get("model") or item.get("model_id"),"model": item.get("model") or "",- "provider": "",+ "provider": item.get("provider") or "",+ "reasoning_effort": item.get("reasoning_effort"),+ "supported_reasoning_efforts": item.get("supported_reasoning_efforts"),"source": item.get("source") or "admin",- "is_active_default": False,+ "is_active_default": (+ item.get("profile_id") == active_profile_id+ and item.get("model_id") == active_model_id+ ),}for item in redacted_model_access(user.id).get("llm", [])if item.get("available")]- return {"active": None, "options": options}+ active = next(+ (+ {"profile_id": active_profile_id, "model_id": active_model_id}+ for option in options+ if option["is_active_default"]+ ),+ None,+ )+ return {"active": active, "options": options}def has_capability_access(capability: str, user_id: str | None = None) -> bool:diff --git a/deeptutor/multi_user/personal_models.py b/deeptutor/multi_user/personal_models.pyindex 117166495..7a9c57b3e 100644--- a/deeptutor/multi_user/personal_models.py+++ b/deeptutor/multi_user/personal_models.py@@ -110,6 +110,9 @@ def personal_llm_rows() -> list[dict[str, Any]]:"model_id": model_id,"name": model.get("name") or model_id,"model": model.get("model") or "",+ "provider": profile.get("binding") or "",+ "reasoning_effort": model.get("reasoning_effort"),+ "supported_reasoning_efforts": model.get("codex_supported_reasoning_levels"),"source": "personal","available": True,}diff --git a/deeptutor/services/app_update.py b/deeptutor/services/app_update.pyindex 844c454b6..c565e9ea5 100644--- a/deeptutor/services/app_update.py+++ b/deeptutor/services/app_update.py@@ -166,6 +166,15 @@ def _distribution_direct_url() -> dict[str, Any] | None:return payload if isinstance(payload, dict) else {}+def _running_from_source_checkout() -> bool:+ """Return whether the imported package lives in a Git source checkout."""+ try:+ checkout_root = Path(__file__).resolve().parents[2]+ except IndexError:+ return False+ return (checkout_root / ".git").exists() and (checkout_root / "pyproject.toml").is_file()++def detect_installation() -> Installation:"""Classify only layouts whose update ownership is unambiguous."""@@ -178,6 +187,15 @@ def detect_installation() -> Installation:reason="Container images are updated and recreated by the Docker host.",)+ if _running_from_source_checkout():+ return Installation(+ mode="source",+ current_version=__version__,+ automatic_update=False,+ command="git pull && pip install -e .",+ reason="Source checkouts stay under the developer's Git workflow.",+ )+direct_url = _distribution_direct_url()if direct_url is None:return Installation(diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex 5470d0991..f6e52f2db 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -45,6 +45,9 @@ DEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {"enabled": True,"blocked_domains": [],"trusted_domains": [],+ "content_filtering": True,+ "use_educational_trusted_domains": False,+ "use_moderation": False,},# Chat attachment policy. Size caps gate what the composer accepts and# what the turn runtime / partner upload endpoints extract; the char@@ -1164,6 +1167,11 @@ class RuntimeSettingsService:"enabled": _coerce_bool(source_filter.get("enabled"), True),"blocked_domains": _string_or_list(source_filter.get("blocked_domains")),"trusted_domains": _string_or_list(source_filter.get("trusted_domains")),+ "content_filtering": _coerce_bool(source_filter.get("content_filtering"), True),+ "use_educational_trusted_domains": _coerce_bool(+ source_filter.get("use_educational_trusted_domains"), False+ ),+ "use_moderation": _coerce_bool(source_filter.get("use_moderation"), False),},"chat_attachment_max_file_mb": max_file_mb,"chat_attachment_max_total_mb": max_total_mb,diff --git a/deeptutor/services/github_source/sync.py b/deeptutor/services/github_source/sync.pyindex a4f1e4804..6cc2839d9 100644--- a/deeptutor/services/github_source/sync.py+++ b/deeptutor/services/github_source/sync.py@@ -6,6 +6,8 @@ from dataclasses import dataclassfrom datetime import datetime, timezoneimport loggingfrom pathlib import Path+import re+from urllib.parse import urlsplit, urlunsplitfrom deeptutor.knowledge.add_documents import DEFAULT_BASE_DIRfrom deeptutor.services.github_source.client import (@@ -33,6 +35,46 @@ def _utcnow_iso() -> str:return datetime.now(timezone.utc).isoformat()+def redact_sync_error(exc: Exception) -> str:+ """Return a bounded sync error without credential-shaped values."""+ message = str(exc).strip() or type(exc).__name__++ def redact_url(match: re.Match[str]) -> str:+ try:+ parsed = urlsplit(match.group(0))+ host = parsed.hostname or ""+ if parsed.port is not None:+ host = f"{host}:{parsed.port}"+ return urlunsplit((parsed.scheme, host, parsed.path, "", ""))+ except ValueError:+ # Error strings are untrusted input too. A malformed bracket or port+ # must not make credential redaction mask the original sync failure.+ return "[redacted-url]"++ message = re.sub(r"https?://[^\s,;]+", redact_url, message)+ message = re.sub(r"\bsk-[A-Za-z0-9_-]{4,}\b", "[redacted]", message)+ message = re.sub(+ r"(?i)((?:api[_-]?key|authorization|token|password)\s*[:=]\s*)[^\s,;]+",+ r"\1[redacted]",+ message,+ )+ return message[:1000]+++def _record_sync_failure(kb_name: str, source: dict, base_dir: str, error: str) -> None:+ try:+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ KnowledgeBaseManager(base_dir=base_dir).update_github_source_state(+ kb_name=kb_name,+ source_id=source["id"],+ last_sync_status="error",+ last_sync_error=error,+ )+ except Exception:+ logger.warning("Could not persist GitHub sync failure status for '%s'", kb_name)++def _is_markdown(path: str) -> bool:return path.lower().endswith(MARKDOWN_EXTENSIONS)@@ -107,9 +149,13 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=Nonetry:latest_sha = await client.get_latest_commit_sha(repo, branch)except GitHubAPIError as exc:- return SyncResult(ok=False, error=str(exc))+ error = redact_sync_error(exc)+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)except Exception as exc:- return SyncResult(ok=False, error=f"Failed to fetch latest SHA: {exc}")+ error = f"Failed to fetch latest SHA: {redact_sync_error(exc)}"+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)if old_sha and old_sha == latest_sha:return SyncResult(ok=True, skipped=True)@@ -133,11 +179,16 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=Nonebase_dir,)except GitHubAPIError as exc:- return SyncResult(ok=False, error=str(exc))+ error = redact_sync_error(exc)+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)except Exception as exc:- return SyncResult(ok=False, error=str(exc))+ error = redact_sync_error(exc)+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)if not result.ok:+ _record_sync_failure(kb_name, source, base_dir, result.error)return resultfrom deeptutor.knowledge.manager import KnowledgeBaseManager@@ -218,13 +269,9 @@ async def _incremental_sync(async def _index_files(kb_name, file_paths, base_dir):if not file_paths:return 0- try:- from deeptutor.knowledge.add_documents import add_documents+ from deeptutor.knowledge.add_documents import add_documents- count = await add_documents(- kb_name=kb_name, source_files=file_paths, base_dir=base_dir, allow_duplicates=False- )- return count or 0- except Exception as exc:- logger.warning("Indexing failed: %s", exc)- return 0+ count = await add_documents(+ kb_name=kb_name, source_files=file_paths, base_dir=base_dir, allow_duplicates=False+ )+ return count or 0diff --git a/deeptutor/services/github_source/sync_service.py b/deeptutor/services/github_source/sync_service.pyindex c291ada6c..8e8fa11e3 100644--- a/deeptutor/services/github_source/sync_service.py+++ b/deeptutor/services/github_source/sync_service.py@@ -2,11 +2,13 @@from __future__ import annotations-from datetime import datetime, timezoneimport logging+from pathlib import Path-from deeptutor.services.base_sync import BaseSourceSyncService, is_stale-from deeptutor.services.github_source.sync import SYNC_INTERVAL_HOURS+from deeptutor.multi_user.context import reset_current_user, set_current_user+from deeptutor.multi_user.paths import local_admin_user+from deeptutor.services.base_sync import BaseSourceSyncService, default_base_dir, is_stale+from deeptutor.services.github_source.sync import SYNC_INTERVAL_HOURS, redact_sync_errorlogger = logging.getLogger(__name__)@@ -14,9 +16,13 @@ logger = logging.getLogger(__name__)class GitHubSourceSyncService(BaseSourceSyncService):"""Periodically syncs all GitHub sources."""- def __init__(self, *, base_dir=None, client=None, check_interval_s=3600):+ def __init__(self, *, base_dir=None, client=None, check_interval_s=3600, owner=None):+ if owner is None and base_dir is not None:+ if Path(base_dir).resolve() != Path(default_base_dir()).resolve():+ raise ValueError("A custom GitHub sync base_dir requires an explicit owner.")super().__init__(base_dir=base_dir, check_interval_s=check_interval_s)self._client = client+ self._owner = owner or local_admin_user()@propertydef task_name(self) -> str:@@ -26,39 +32,34 @@ class GitHubSourceSyncService(BaseSourceSyncService):from deeptutor.knowledge.manager import KnowledgeBaseManagerfrom deeptutor.services.github_source.sync import sync_source- base_dir = self.effective_base_dir- manager = KnowledgeBaseManager(base_dir=base_dir)+ token = set_current_user(self._owner)+ try:+ base_dir = self.effective_base_dir+ manager = KnowledgeBaseManager(base_dir=base_dir)- all_sources = manager.get_all_github_sources()- for kb_name, source in all_sources:- if not source.get("enabled", True):- continue- if not is_stale(source, stale_hours=SYNC_INTERVAL_HOURS):- continue- sid = source.get("id", "?")- try:- result = await sync_source(- kb_name=kb_name,- source=source,- base_dir=base_dir,- client=self._client,- )- if not result.ok:+ all_sources = manager.get_all_github_sources()+ for kb_name, source in all_sources:+ if not source.get("enabled", True):+ continue+ if not is_stale(source, stale_hours=SYNC_INTERVAL_HOURS):+ continue+ sid = source.get("id", "?")+ try:+ await sync_source(+ kb_name=kb_name,+ source=source,+ base_dir=base_dir,+ client=self._client,+ )+ except Exception as exc:manager.update_github_source_state(kb_name=kb_name,source_id=sid,last_sync_status="error",- last_sync_error=result.error,- last_synced_at=datetime.now(timezone.utc).isoformat(),+ last_sync_error=redact_sync_error(exc),)- except Exception as exc:- manager.update_github_source_state(- kb_name=kb_name,- source_id=sid,- last_sync_status="error",- last_sync_error=str(exc),- last_synced_at=datetime.now(timezone.utc).isoformat(),- )+ finally:+ reset_current_user(token)_sync_service = Nonediff --git a/deeptutor/services/llm/client.py b/deeptutor/services/llm/client.pyindex a8f805ff7..eb36b9ed5 100644--- a/deeptutor/services/llm/client.py+++ b/deeptutor/services/llm/client.py@@ -14,7 +14,67 @@ from typing import Any, castfrom .capabilities import supports_visionfrom .config import LLMConfig, get_llm_config-from .utils import sanitize_url+++def build_model_func_for_config(+ config: LLMConfig,+ *,+ allow_multimodal: bool,+) -> Callable[..., object]:+ """Build a model callable owned solely by one resolved configuration."""+ from . import factory++ def _resolve_messages(+ prompt: str,+ system_prompt: str | None,+ history_messages: list[dict[str, object]] | None,+ messages: list[dict[str, object]] | None,+ ) -> list[dict[str, Any]] | None:+ if messages:+ return cast(list[dict[str, Any]], messages)+ if not history_messages:+ return None++ full_messages: list[dict[str, Any]] = []+ if system_prompt and not (history_messages and history_messages[0].get("role") == "system"):+ full_messages.append({"role": "system", "content": system_prompt})+ full_messages.extend(cast(list[dict[str, Any]], history_messages))+ if prompt:+ full_messages.append({"role": "user", "content": prompt})+ return full_messages or None++ async def model_func(+ prompt: str,+ system_prompt: str | None = None,+ history_messages: list[dict[str, object]] | None = None,+ image_data: str | None = None,+ messages: list[dict[str, object]] | None = None,+ **kwargs: object,+ ) -> str:+ payload_kwargs: dict[str, object] = dict(kwargs)+ for alias in ("history_messages", "messages", "prompt", "system_prompt"):+ payload_kwargs.pop(alias, None)++ default_system_prompt = system_prompt or "You are a helpful assistant."+ resolved_messages = _resolve_messages(+ prompt,+ default_system_prompt,+ history_messages,+ messages,+ )+ if allow_multimodal and image_data is not None:+ payload_kwargs["image_data"] = image_data++ factory_complete = cast(Callable[..., Awaitable[str]], factory.complete_with_config)+ return await factory_complete(+ config=config,+ prompt=prompt,+ system_prompt=default_system_prompt,+ messages=resolved_messages,+ **payload_kwargs,+ )++ return model_funcclass LLMClient:@@ -132,7 +192,7 @@ class LLMClient:Returns:Callable that can be used as llm_model_func"""- return self._build_factory_model_func(allow_multimodal=False)+ return build_model_func_for_config(self.config, allow_multimodal=False)def get_vision_model_func(self) -> Callable[..., object]:"""@@ -141,81 +201,12 @@ class LLMClient:Returns:Callable that can be used as vision_model_func"""- return self._build_factory_model_func(allow_multimodal=True)+ return build_model_func_for_config(self.config, allow_multimodal=True)def supports_multimodal_images(self) -> bool:"""Return whether the configured LLM can accept image input."""return supports_vision(getattr(self.config, "binding", "openai"), self.config.model)- def _build_factory_model_func(self, allow_multimodal: bool) -> Callable[..., object]:- """Build adapter callables on top of the unified factory.complete API."""- from . import factory-- def _resolve_messages(- prompt: str,- system_prompt: str | None,- history_messages: list[dict[str, object]] | None,- messages: list[dict[str, object]] | None,- ) -> list[dict[str, Any]] | None:- if messages:- return cast(list[dict[str, Any]], messages)- if not history_messages:- return None-- full_messages: list[dict[str, Any]] = []- if system_prompt and not (- history_messages and history_messages[0].get("role") == "system"- ):- full_messages.append({"role": "system", "content": system_prompt})- full_messages.extend(cast(list[dict[str, Any]], history_messages))- if prompt:- full_messages.append({"role": "user", "content": prompt})- return full_messages or None-- async def model_func(- prompt: str,- system_prompt: str | None = None,- history_messages: list[dict[str, object]] | None = None,- image_data: str | None = None,- messages: list[dict[str, object]] | None = None,- **kwargs: object,- ) -> str:- payload_kwargs: dict[str, object] = dict(kwargs)-- # Normalize aliases from legacy callsites.- payload_kwargs.pop("history_messages", None)- payload_kwargs.pop("messages", None)- payload_kwargs.pop("prompt", None)- payload_kwargs.pop("system_prompt", None)-- default_system_prompt = system_prompt or "You are a helpful assistant."- resolved_messages = _resolve_messages(- prompt,- default_system_prompt,- history_messages,- messages,- )-- if allow_multimodal and image_data is not None:- payload_kwargs["image_data"] = image_data-- factory_complete = cast(Callable[..., Awaitable[str]], factory.complete)- return await factory_complete(- prompt=prompt,- system_prompt=default_system_prompt,- model=self.config.model,- api_key=self.config.api_key,- base_url=sanitize_url(self.config.base_url) if self.config.base_url else None,- api_version=getattr(self.config, "api_version", None),- binding=getattr(self.config, "binding", "openai"),- reasoning_effort=getattr(self.config, "reasoning_effort", None),- extra_headers=getattr(self.config, "extra_headers", None),- messages=resolved_messages,- **payload_kwargs,- )-- return model_func-_client: LLMClient | None = Nonediff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 451899447..efa02b987 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -23,7 +23,8 @@ from .capabilities import supports_response_format, supports_visionfrom .config import LLMConfig, get_llm_configfrom .error_mapping import map_errorfrom .multimodal import prepare_multimodal_messages-from .provider_factory import get_runtime_provider+from .provider_core.base import LLMProvider+from .provider_factory import build_isolated_provider, get_runtime_providerfrom .utils import is_local_llm_serverDEFAULT_MAX_RETRIES = settings.retry.max_retries@@ -328,8 +329,12 @@ def _sanitize_call_kwargs("base_url","api_version","binding",+ "effective_url","extra_headers",+ "provider_mode",+ "provider_name","reasoning_effort",+ "wire_api",):extra_kwargs.pop(key, None)@@ -338,37 +343,25 @@ def _sanitize_call_kwargs(return extra_kwargs-async def complete(+async def _complete_with_resolved_config(+ config: LLMConfig,+ provider_spec: Any,+ *,prompt: str,- system_prompt: str = "You are a helpful assistant.",- model: str | None = None,- api_key: str | list[str] | None = None,- base_url: str | None = None,- api_version: str | None = None,- binding: str | None = None,- messages: list[dict[str, Any]] | None = None,- max_retries: int = DEFAULT_MAX_RETRIES,- retry_delay: float = DEFAULT_RETRY_DELAY,- exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,- allow_image_fallback: bool | None = None,- **kwargs: Any,+ system_prompt: str,+ messages: list[dict[str, Any]] | None,+ max_retries: int,+ retry_delay: float,+ exponential_backoff: bool,+ allow_image_fallback: bool | None,+ image_data: str | None,+ image_mime_type: str,+ image_filename: str,+ kwargs: dict[str, Any],+ provider: LLMProvider | None = None,) -> str:- caller_extra_headers = kwargs.pop("extra_headers", None)- reasoning_effort = kwargs.pop("reasoning_effort", None)- image_data = kwargs.pop("image_data", None)- image_mime_type = kwargs.pop("image_mime_type", "image/png")- image_filename = kwargs.pop("image_filename", "image.png")-- config, provider_spec = _resolve_call_config(- model=model,- api_key=api_key,- base_url=base_url,- api_version=api_version,- binding=binding,- extra_headers=caller_extra_headers,- reasoning_effort=reasoning_effort,- )- provider = get_runtime_provider(config)+ """Execute one completion from an already resolved configuration."""+ provider = provider or get_runtime_provider(config)capability_binding = _capability_binding(config, provider_spec)request_messages = _build_messages(prompt, system_prompt, messages)request_messages = _apply_inline_image_data(@@ -408,6 +401,114 @@ async def complete(return response.content or ""+async def complete(+ prompt: str,+ system_prompt: str = "You are a helpful assistant.",+ model: str | None = None,+ api_key: str | list[str] | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ binding: str | None = None,+ messages: list[dict[str, Any]] | None = None,+ max_retries: int = DEFAULT_MAX_RETRIES,+ retry_delay: float = DEFAULT_RETRY_DELAY,+ exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,+ allow_image_fallback: bool | None = None,+ **kwargs: Any,+) -> str:+ caller_extra_headers = kwargs.pop("extra_headers", None)+ reasoning_effort = kwargs.pop("reasoning_effort", None)+ image_data = kwargs.pop("image_data", None)+ image_mime_type = kwargs.pop("image_mime_type", "image/png")+ image_filename = kwargs.pop("image_filename", "image.png")++ config, provider_spec = _resolve_call_config(+ model=model,+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ binding=binding,+ extra_headers=caller_extra_headers,+ reasoning_effort=reasoning_effort,+ )+ return await _complete_with_resolved_config(+ config,+ provider_spec,+ prompt=prompt,+ system_prompt=system_prompt,+ messages=messages,+ max_retries=max_retries,+ retry_delay=retry_delay,+ exponential_backoff=exponential_backoff,+ allow_image_fallback=allow_image_fallback,+ image_data=image_data,+ image_mime_type=str(image_mime_type or "image/png"),+ image_filename=str(image_filename or "image.png"),+ kwargs=kwargs,+ )+++async def complete_with_config(+ config: LLMConfig,+ prompt: str,+ system_prompt: str = "You are a helpful assistant.",+ messages: list[dict[str, Any]] | None = None,+ max_retries: int = DEFAULT_MAX_RETRIES,+ retry_delay: float = DEFAULT_RETRY_DELAY,+ exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,+ allow_image_fallback: bool | None = None,+ **kwargs: Any,+) -> str:+ """Complete using only the supplied, fully resolved configuration."""+ forbidden = {+ "model",+ "api_key",+ "base_url",+ "api_version",+ "binding",+ "effective_url",+ "extra_headers",+ "provider_mode",+ "provider_name",+ "reasoning_effort",+ "wire_api",+ }.intersection(kwargs)+ if forbidden:+ names = ", ".join(sorted(forbidden))+ raise TypeError(f"complete_with_config does not accept config overrides: {names}")++ image_data = kwargs.pop("image_data", None)+ image_mime_type = kwargs.pop("image_mime_type", "image/png")+ image_filename = kwargs.pop("image_filename", "image.png")+ provider_spec = _resolve_provider_spec(+ binding=config.provider_name or config.binding,+ model=config.model,+ api_key=config.api_key,+ base_url=config.effective_url or config.base_url,+ fallback=config.provider_name or config.binding,+ )+ provider = build_isolated_provider(config)+ try:+ return await _complete_with_resolved_config(+ config,+ provider_spec,+ prompt=prompt,+ system_prompt=system_prompt,+ messages=messages,+ max_retries=max_retries,+ retry_delay=retry_delay,+ exponential_backoff=exponential_backoff,+ allow_image_fallback=allow_image_fallback,+ image_data=image_data,+ image_mime_type=str(image_mime_type or "image/png"),+ image_filename=str(image_filename or "image.png"),+ kwargs=kwargs,+ provider=provider,+ )+ finally:+ await provider.aclose()++async def stream(prompt: str,system_prompt: str = "You are a helpful assistant.",diff --git a/deeptutor/services/llm/provider_core/codebuddy_http_provider.py b/deeptutor/services/llm/provider_core/codebuddy_http_provider.pyindex 41c61d18b..bea9452d2 100644--- a/deeptutor/services/llm/provider_core/codebuddy_http_provider.py+++ b/deeptutor/services/llm/provider_core/codebuddy_http_provider.py@@ -51,6 +51,8 @@ class CodeBuddyHTTPProvider(OpenAICompatProvider):self,api_key: str | None = None,default_model: str = DEFAULT_CODEBUDDY_MODEL,+ *,+ configure_env: bool = True,):self._explicit_api_key = normalize_api_key(api_key)self._credentials: CodeBuddyCredentials | None = (@@ -70,6 +72,7 @@ class CodeBuddyHTTPProvider(OpenAICompatProvider):extra_headers=extra_headers,spec=find_by_name("codebuddy"),provider_name="codebuddy",+ configure_env=configure_env,)if self._explicit_api_key:self._apply_token(self._explicit_api_key)@@ -208,6 +211,8 @@ def sdk_installed() -> bool:def build_codebuddy_provider(api_key: str | None = None,default_model: str = DEFAULT_CODEBUDDY_MODEL,+ *,+ configure_env: bool = True,) -> Any:"""Return the HTTP transport when it can authenticate, else the Agent SDK.@@ -226,7 +231,11 @@ def build_codebuddy_provider(use_http = codebuddy_http_available(api_key) or not has_sdkif use_http:- return CodeBuddyHTTPProvider(api_key=api_key, default_model=default_model)+ return CodeBuddyHTTPProvider(+ api_key=api_key,+ default_model=default_model,+ configure_env=configure_env,+ )from deeptutor.services.llm.provider_core.codebuddy_provider import CodeBuddyProviderdiff --git a/deeptutor/services/llm/provider_core/github_copilot_provider.py b/deeptutor/services/llm/provider_core/github_copilot_provider.pyindex 5fa4db94c..d4a3aa686 100644--- a/deeptutor/services/llm/provider_core/github_copilot_provider.py+++ b/deeptutor/services/llm/provider_core/github_copilot_provider.py@@ -24,7 +24,12 @@ _EXPIRY_SKEW_SECONDS = 60class GitHubCopilotProvider(OpenAICompatProvider):"""Provider that first tries existing Copilot auth, then oauth-cli-kit tokens."""- def __init__(self, default_model: str = "github-copilot/gpt-4.1"):+ def __init__(+ self,+ default_model: str = "github-copilot/gpt-4.1",+ *,+ configure_env: bool = True,+ ):self._copilot_access_token: str | None = Noneself._copilot_expires_at: float = 0.0super().__init__(@@ -38,6 +43,7 @@ class GitHubCopilotProvider(OpenAICompatProvider):},spec=find_by_name("github_copilot"),provider_name="github_copilot",+ configure_env=configure_env,)async def _try_existing_local_auth(self) -> None:diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.pyindex 90ba4bd50..f6cda4a90 100644--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py@@ -133,6 +133,7 @@ class OpenAICompatProvider(LLMProvider):spec: Any = None,provider_name: str | None = None,wire_api: str = "auto",+ configure_env: bool = True,):keys = api_key if isinstance(api_key, list) else [api_key]keys = [str(key).strip() for key in keys if str(key or "").strip()]@@ -145,7 +146,7 @@ class OpenAICompatProvider(LLMProvider):self._provider_name = provider_nameself._wire_api = normalize_wire_api(wire_api)- if primary_key and spec and spec.env_key:+ if configure_env and primary_key and spec and spec.env_key:self._setup_env(primary_key, api_base)effective_base = api_base or (spec.default_api_base if spec else None) or None@@ -494,7 +495,7 @@ class OpenAICompatProvider(LLMProvider):or getattr(response, "text", None))body_text = str(body).lower() if body is not None else ""- return any(+ endpoint_unsupported = any(marker in body_textfor marker in ("responses",@@ -508,6 +509,16 @@ class OpenAICompatProvider(LLMProvider):"not supported",))+ # DeepSeek V4 reports a very specific three-part error when a+ # Responses continuation cannot replay its prior reasoning item. Keep+ # these markers conjunctive: each phrase on its own is common in+ # unrelated validation errors and must not trip the circuit breaker.+ reasoning_replay_rejected = (+ any(field in body_text for field in ("reasoning_text", "reasoning_content"))+ and "thinking mode" in body_text+ and "passed back" in body_text+ )+ return endpoint_unsupported or reasoning_replay_rejected@staticmethoddef _is_response_format_error(exc: Exception) -> bool:diff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.pyindex 7268a9f83..b2be33e49 100644--- a/deeptutor/services/llm/provider_factory.py+++ b/deeptutor/services/llm/provider_factory.py@@ -45,7 +45,11 @@ def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> t)-def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:+def _build_runtime_provider(+ llm_config: LLMConfig,+ *,+ configure_env: bool = True,+) -> LLMProvider:"""Construct one provider, importing only the selected backend SDK."""provider_name = llm_config.provider_name or llm_config.bindingapi_key = llm_config.get_api_key()@@ -68,7 +72,10 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:GitHubCopilotProvider,)- provider = GitHubCopilotProvider(default_model=llm_config.model)+ provider = GitHubCopilotProvider(+ default_model=llm_config.model,+ configure_env=configure_env,+ )elif backend == "codebuddy":from deeptutor.services.llm.provider_core.codebuddy_http_provider import (build_codebuddy_provider,@@ -77,6 +84,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:provider = build_codebuddy_provider(api_key=api_key or None,default_model=llm_config.model,+ configure_env=configure_env,)elif backend == "azure_openai":from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProvider@@ -109,6 +117,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:spec=spec,provider_name=provider_name,wire_api=llm_config.wire_api,+ configure_env=configure_env,)provider.generation = GenerationSettings(@@ -119,6 +128,11 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:return provider+def build_isolated_provider(config: LLMConfig) -> LLMProvider:+ """Build an unpooled provider without mutating process-global provider env."""+ return _build_runtime_provider(config, configure_env=False)++def _schedule_close(provider: LLMProvider, loop: asyncio.AbstractEventLoop) -> None:async def _close() -> None:with contextlib.suppress(Exception):@@ -190,6 +204,7 @@ def runtime_provider_pool_size() -> int:__all__ = [+ "build_isolated_provider","close_runtime_provider_pool","get_runtime_provider","reset_runtime_provider_pool",diff --git a/deeptutor/services/model_selection/llm.py b/deeptutor/services/model_selection/llm.pyindex 12701bb95..e3c5b318f 100644--- a/deeptutor/services/model_selection/llm.py+++ b/deeptutor/services/model_selection/llm.py@@ -137,6 +137,14 @@ def list_llm_options(catalog: dict[str, Any]) -> dict[str, Any]:context_window = _coerce_int(model.get("context_window_tokens"))if context_window is not None:option["context_window"] = context_window+ reasoning_effort = str(model.get("reasoning_effort") or "").strip().lower()+ if reasoning_effort:+ option["reasoning_effort"] = reasoning_effort+ supported_levels = model.get("codex_supported_reasoning_levels")+ if isinstance(supported_levels, list):+ option["supported_reasoning_efforts"] = [+ str(level).strip().lower() for level in supported_levels if str(level).strip()+ ]options.append(option)return {diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.pyindex 9017a8735..6f45e3365 100644--- a/deeptutor/services/rag/pipelines/lightrag/config.py+++ b/deeptutor/services/rag/pipelines/lightrag/config.py@@ -24,6 +24,9 @@ import refrom typing import TYPE_CHECKING, TypeVarif TYPE_CHECKING:+ from deeptutor.multi_user.models import CurrentUser+ from deeptutor.services.llm.config import LLMConfig+from .worker import OwnerLoopBridgelogger = logging.getLogger(__name__)@@ -188,8 +191,7 @@ def constructor_kwargs_from_settings() -> dict:return {}-def lightrag_llm_selection_from_settings() -> dict[str, str] | None:- """Return a complete dedicated catalog reference, or use the active LLM."""+def _lightrag_llm_selection_from_settings(*, strict: bool) -> dict[str, str] | None:try:from deeptutor.services.config import load_lightrag_settings@@ -199,10 +201,14 @@ def lightrag_llm_selection_from_settings() -> dict[str, str] | None:if not profile_id and not model_id:return Noneif not profile_id or not model_id:+ if strict:+ raise ValueError("The LightRAG LLM selection is incomplete.")logger.warning("Ignoring incomplete LightRAG LLM selection; using the active model")return Nonereturn {"profile_id": profile_id, "model_id": model_id}except Exception:+ if strict:+ raiselogger.warning("Could not read LightRAG LLM selection; using the active model",exc_info=True,@@ -210,41 +216,49 @@ def lightrag_llm_selection_from_settings() -> dict[str, str] | None:return None-def _resolve_override_llm_config(selection: dict[str, str] | None):- if selection is None:- return None- try:- from deeptutor.services.model_selection.runtime import (- resolve_llm_config_for_selection,- )+def lightrag_llm_selection_from_settings() -> dict[str, str] | None:+ """Return the released query-model selection with its fallback semantics."""+ return _lightrag_llm_selection_from_settings(strict=False)++def lightrag_indexing_selection_from_settings() -> dict[str, str] | None:+ """Return the indexing default, rejecting unreadable or partial settings."""+ return _lightrag_llm_selection_from_settings(strict=True)+++def resolve_lightrag_query_llm_config():+ """Resolve the current LightRAG query model with the released fallback contract."""+ from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection++ selection = lightrag_llm_selection_from_settings()+ try:return resolve_llm_config_for_selection(selection)except ValueError:logger.warning("LightRAG LLM selection %s no longer exists in the catalog; using the active model",selection,)- return None+ return resolve_llm_config_for_selection(None)def build_llm_model_func(*,io_bridge: OwnerLoopBridge | None = None,- llm_selection: dict[str, str] | None = None,+ llm_config: LLMConfig | None = None,+ owner: CurrentUser | None = None,):"""Wrap DeepTutor's unified LLM callable for LightRAG.Drops LightRAG's internal kwargs while preserving explicit ``messages``."""- override = _resolve_override_llm_config(llm_selection)- if override is None:+ if llm_config is None:from deeptutor.services.llm import get_llm_clientbase = get_llm_client().get_model_func()else:- from deeptutor.services.llm.client import LLMClient+ from deeptutor.services.llm.client import build_model_func_for_config- base = LLMClient(config=override, configure_env=False).get_model_func()+ base = build_model_func_for_config(llm_config, allow_multimodal=False)async def llm_model_func(prompt="",@@ -254,14 +268,22 @@ def build_llm_model_func(**_ignored,):async def request():- return await base(- prompt or "",- system_prompt=system_prompt,- history_messages=history_messages or [],- messages=messages,- max_retries=0,- allow_image_fallback=False,- )+ async def complete():+ return await base(+ prompt or "",+ system_prompt=system_prompt,+ history_messages=history_messages or [],+ messages=messages,+ max_retries=0,+ allow_image_fallback=False,+ )++ if owner is None:+ return await complete()+ from deeptutor.multi_user.paths import user_context++ with user_context(owner):+ return await complete()return await _run_adapter_with_retry(request, io_bridge=io_bridge)@@ -271,18 +293,18 @@ def build_llm_model_func(def build_vision_model_func(*,io_bridge: OwnerLoopBridge | None = None,- llm_selection: dict[str, str] | None = None,+ llm_config: LLMConfig | None = None,+ owner: CurrentUser | None = None,):"""Map rc2 ``image_inputs`` to DeepTutor's vision callable."""- override = _resolve_override_llm_config(llm_selection)- if override is None:+ if llm_config is None:from deeptutor.services.llm import get_llm_clientbase = get_llm_client().get_vision_model_func()else:- from deeptutor.services.llm.client import LLMClient+ from deeptutor.services.llm.client import build_model_func_for_config- base = LLMClient(config=override, configure_env=False).get_vision_model_func()+ base = build_model_func_for_config(llm_config, allow_multimodal=True)async def vision_model_func(prompt="",@@ -302,15 +324,23 @@ def build_vision_model_func(raise ValueError("LightRAG vision image input requires a non-empty base64 value")async def request():- return await base(- prompt or "",- system_prompt=system_prompt,- history_messages=history_messages or [],- image_data=image_data,- messages=messages,- max_retries=0,- allow_image_fallback=False,- )+ async def complete():+ return await base(+ prompt or "",+ system_prompt=system_prompt,+ history_messages=history_messages or [],+ image_data=image_data,+ messages=messages,+ max_retries=0,+ allow_image_fallback=False,+ )++ if owner is None:+ return await complete()+ from deeptutor.multi_user.paths import user_context++ with user_context(owner):+ return await complete()return await _run_adapter_with_retry(request, io_bridge=io_bridge)@@ -380,6 +410,7 @@ __all__ = ["indexing_kwargs_from_settings","constructor_kwargs_from_settings","lightrag_llm_selection_from_settings",+ "resolve_lightrag_query_llm_config","build_llm_model_func","build_vision_model_func","vision_model_available",diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.pyindex 9fe8db9dc..3b5f2cb85 100644--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@ -17,9 +17,9 @@ from .config import (build_vision_model_func,constructor_kwargs_from_settings,indexing_kwargs_from_settings,- lightrag_llm_selection_from_settings,normalize_mode,query_kwargs_from_settings,+ resolve_lightrag_query_llm_config,)from .ingress import IngressError, StagedDocument, pending_rootfrom .worker import OwnerLoopBridge@@ -188,31 +188,86 @@ def build_rag(*,io_bridge: OwnerLoopBridge | None = None,enable_vlm: bool = False,+ indexing_snapshot: Any | None = None,) -> Any:"""Construct one exact-version, version-isolated LightRAG instance."""_require_exact_version()_register_parser()from lightrag.llm_roles import RoleLLMConfig- llm_adapter_kwargs: dict[str, Any] = {"llm_selection": lightrag_llm_selection_from_settings()}+ llm_adapter_kwargs: dict[str, Any] = {}embedding_adapter_kwargs: dict[str, Any] = {}if io_bridge is not None:llm_adapter_kwargs["io_bridge"] = io_bridgeembedding_adapter_kwargs["io_bridge"] = io_bridge+ from .indexing_policy import cache_identity_for_config++ query_config = resolve_lightrag_query_llm_config()+ query_func = build_llm_model_func(+ **llm_adapter_kwargs,+ llm_config=query_config,+ )+ query_identity = cache_identity_for_config(query_config)+ query_metadata = {+ "binding": query_config.binding,+ "model": query_identity,+ }constructor = {"working_dir": str(Path(working_dir)),"workspace": workspace_for(working_dir),- "llm_model_func": build_llm_model_func(**llm_adapter_kwargs),+ "llm_model_func": query_func,+ "llm_model_name": query_identity,"embedding_func": build_embedding_func(**embedding_adapter_kwargs),"auto_manage_storages_states": False,"vlm_process_enable": bool(enable_vlm),**indexing_kwargs_from_settings(),**constructor_kwargs_from_settings(),}- if enable_vlm:- constructor["role_llm_configs"] = {- "vlm": RoleLLMConfig(func=build_vision_model_func(**llm_adapter_kwargs))+ role_configs: dict[str, Any] = {+ "keyword": RoleLLMConfig(func=query_func, metadata=query_metadata),+ "query": RoleLLMConfig(func=query_func, metadata=query_metadata),+ }+ if indexing_snapshot is not None:+ from .indexing_policy import cache_identity++ snapshot_kwargs = {+ **llm_adapter_kwargs,+ "llm_config": indexing_snapshot.config,+ "owner": indexing_snapshot.owner,+ }+ metadata = {+ "binding": indexing_snapshot.config.binding,+ "model": cache_identity(indexing_snapshot),+ "host": indexing_snapshot.descriptor.get("endpoint"),}+ role_configs["extract"] = RoleLLMConfig(+ func=build_llm_model_func(**snapshot_kwargs), metadata=metadata+ )+ if enable_vlm:+ if indexing_snapshot is None:+ raise LightRagContractError(+ "LightRAG vision indexing requires a frozen indexing-model policy."+ )+ vision_kwargs = llm_adapter_kwargs+ metadata = None+ if indexing_snapshot is not None:+ from .indexing_policy import cache_identity++ vision_kwargs = {+ **llm_adapter_kwargs,+ "llm_config": indexing_snapshot.config,+ "owner": indexing_snapshot.owner,+ }+ metadata = {+ "binding": indexing_snapshot.config.binding,+ "model": cache_identity(indexing_snapshot),+ "host": indexing_snapshot.descriptor.get("endpoint"),+ }+ role_configs["vlm"] = RoleLLMConfig(+ func=build_vision_model_func(**vision_kwargs), metadata=metadata+ )+ if role_configs:+ constructor["role_llm_configs"] = role_configsreturn _controlled_class()(**constructor)diff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.pynew file mode 100644index 000000000..bbfa81284--- /dev/null+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py@@ -0,0 +1,274 @@+"""Immutable model identity for native LightRAG indexing writes."""++from __future__ import annotations++from dataclasses import dataclass+import hashlib+import json+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit, urlunsplit++from deeptutor.multi_user.context import get_current_user, get_current_user_or_none+from deeptutor.multi_user.model_access import (+ OWNER_BOUND_BINDINGS,+ apply_allowed_llm_selection,+)+from deeptutor.multi_user.models import CurrentUser+from deeptutor.services.llm.capabilities import supports_vision+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.llm.exceptions import LLMConfigError+from deeptutor.services.model_selection.llm import LLMSelection+from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection++POLICY_PINNED = "pinned"+POLICY_PENDING = "pending_pinned"+POLICY_LEGACY = "legacy_unpinned"+++class IndexingPolicyError(RuntimeError):+ """A pinned model can no longer be used without changing index identity."""++ code = "indexing_model_unavailable"+ retryable = False+++class IndexingModelChangedError(IndexingPolicyError):+ """The selected catalog entry no longer matches the published fingerprint."""++ code = "reindex_required"+++def _endpoint_identity(value: str | None) -> str:+ if not value:+ return ""+ parsed = urlsplit(value)+ host = parsed.hostname or ""+ if parsed.port is not None:+ host = f"{host}:{parsed.port}"+ return urlunsplit((parsed.scheme.lower(), host.lower(), parsed.path.rstrip("/"), "", ""))+++def _canonical_identity(+ selection: LLMSelection | None,+ config: LLMConfig,+ *,+ vision_available: bool | None = None,+) -> dict[str, Any]:+ identity = {+ "binding": config.binding,+ "provider_mode": config.provider_mode,+ "endpoint": _endpoint_identity(config.effective_url or config.base_url),+ "api_version": config.api_version or None,+ "model": config.model,+ "reasoning_effort": config.reasoning_effort,+ }+ if selection is not None:+ identity["profile_id"] = selection.profile_id+ identity["model_id"] = selection.model_id+ if vision_available is not None:+ identity["vision_available"] = vision_available+ return identity+++def _fingerprint(identity: dict[str, Any]) -> str:+ encoded = json.dumps(identity, sort_keys=True, separators=(",", ":")).encode("utf-8")+ return hashlib.sha256(encoded).hexdigest()+++@dataclass(frozen=True, slots=True)+class IndexingLLMSnapshot:+ config: LLMConfig+ owner: CurrentUser+ policy: str+ selection: LLMSelection | None+ descriptor: dict[str, Any]+ fingerprint: str | None+ vision_available: bool++ def persisted_policy(self) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "policy": self.policy,+ "descriptor": self.descriptor,+ "fingerprint": self.fingerprint,+ "vision_available": self.vision_available,+ }+ if self.selection is not None:+ payload["selection"] = self.selection.to_dict()+ return payload+++def freeze_snapshot(+ selection_value: Any = None,+ *,+ policy: str | None = None,+ require_explicit_user: bool = True,+) -> IndexingLLMSnapshot:+ """Resolve and freeze one access-checked indexing model in the caller scope."""+ selection = LLMSelection.from_payload(selection_value)+ explicit_user = get_current_user_or_none()+ if selection is not None and explicit_user is None and require_explicit_user:+ raise IndexingPolicyError(+ "Pinned indexing models require an explicit initiating user scope."+ )+ try:+ if selection is not None:+ apply_allowed_llm_selection(selection.to_dict())+ config = resolve_llm_config_for_selection(selection)+ except (LLMConfigError, PermissionError, ValueError) as exc:+ raise IndexingPolicyError(str(exc)) from exc++ if config.binding in OWNER_BOUND_BINDINGS and explicit_user is None:+ raise IndexingPolicyError(+ "Owner-bound indexing models require an explicit initiating user scope."+ )+ owner = explicit_user or get_current_user()+ resolved_policy = policy or (POLICY_PINNED if selection is not None else POLICY_LEGACY)+ vision_available = supports_vision(config.binding, config.model)+ if resolved_policy == POLICY_LEGACY:+ descriptor = {+ "model": config.model,+ "binding": config.binding,+ "reasoning_effort": config.reasoning_effort,+ }+ fingerprint = None+ else:+ identity = _canonical_identity(+ selection,+ config,+ vision_available=vision_available,+ )+ descriptor = identity+ fingerprint = _fingerprint(identity)+ return IndexingLLMSnapshot(+ config=config,+ owner=owner,+ policy=resolved_policy,+ selection=None if resolved_policy == POLICY_LEGACY else selection,+ descriptor=descriptor,+ fingerprint=fingerprint,+ vision_available=vision_available,+ )+++def pending_policy_for_selection(selection_value: Any) -> dict[str, Any]:+ snapshot = freeze_snapshot(selection_value, policy=POLICY_PENDING)+ return snapshot.persisted_policy()+++def _active_catalog_selection() -> dict[str, str] | None:+ from deeptutor.services.config import get_model_catalog_service++ catalog = get_model_catalog_service().load()+ service = catalog.get("services", {}).get("llm", {})+ profile_id = str(service.get("active_profile_id") or "").strip()+ model_id = str(service.get("active_model_id") or "").strip()+ if not profile_id or not model_id:+ return None+ return {"profile_id": profile_id, "model_id": model_id}+++def freeze_default_snapshot() -> IndexingLLMSnapshot:+ """Freeze the released LightRAG model, or the active model when it is unset."""+ from .config import lightrag_indexing_selection_from_settings++ try:+ selection = lightrag_indexing_selection_from_settings()+ except Exception as exc:+ raise IndexingPolicyError(+ "The LightRAG indexing-model setting could not be resolved."+ ) from exc+ if selection is None:+ selection = _active_catalog_selection()+ return freeze_snapshot(+ selection,+ policy=POLICY_PINNED,+ require_explicit_user=False,+ )+++def snapshot_from_persisted(policy: dict[str, Any]) -> IndexingLLMSnapshot:+ selection = policy.get("selection")+ if selection is not None and not isinstance(selection, dict):+ raise IndexingPolicyError("Pinned LightRAG metadata has an invalid model selection.")+ snapshot = freeze_snapshot(selection, policy=POLICY_PINNED)+ expected = str(policy.get("fingerprint") or "")+ if not expected or snapshot.fingerprint != expected:+ raise IndexingModelChangedError(+ "The pinned LightRAG indexing model changed; run a full re-index to publish "+ "the new model identity."+ )+ return snapshot+++def effective_policy(kb_dir: Path, *, base_dir: str, kb_name: str) -> dict[str, Any] | None:+ """Return published policy first, then pre-publication pending policy."""+ from .storage import latest_published_root, read_published_policy++ root = latest_published_root(kb_dir)+ published = read_published_policy(root)+ if published is not None:+ return published++ from deeptutor.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=base_dir)+ entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}+ pending = entry.get("pending_indexing_policy")+ return pending if isinstance(pending, dict) else None+++def resolve_write_snapshot(+ kb_dir: Path,+ *,+ base_dir: str,+ kb_name: str,+ explicit: IndexingLLMSnapshot | None = None,+) -> IndexingLLMSnapshot:+ if explicit is not None:+ return explicit+ policy = effective_policy(kb_dir, base_dir=base_dir, kb_name=kb_name)+ if policy is None:+ return freeze_default_snapshot()+ if policy.get("policy") == POLICY_LEGACY:+ raise IndexingModelChangedError(+ "This LightRAG index has no verified indexing model; run a full re-index "+ "before appending documents."+ )+ return snapshot_from_persisted(policy)+++def cache_identity(snapshot: IndexingLLMSnapshot) -> str:+ if snapshot.fingerprint:+ return snapshot.fingerprint+ identity = {+ "binding": snapshot.config.binding,+ "provider_mode": snapshot.config.provider_mode,+ "endpoint": _endpoint_identity(snapshot.config.effective_url or snapshot.config.base_url),+ "model": snapshot.config.model,+ "reasoning_effort": snapshot.config.reasoning_effort,+ }+ return _fingerprint(identity)+++def cache_identity_for_config(config: LLMConfig) -> str:+ """Return a credential-free cache identity for a resolved query model."""+ return _fingerprint(_canonical_identity(None, config))+++__all__ = [+ "IndexingLLMSnapshot",+ "IndexingModelChangedError",+ "IndexingPolicyError",+ "POLICY_LEGACY",+ "POLICY_PENDING",+ "POLICY_PINNED",+ "cache_identity",+ "cache_identity_for_config",+ "effective_policy",+ "freeze_default_snapshot",+ "freeze_snapshot",+ "pending_policy_for_selection",+ "resolve_write_snapshot",+ "snapshot_from_persisted",+]diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex 679d51d34..5818ce487 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -13,13 +13,19 @@ from typing import Any, Callable, Dict, List, Optionalfrom deeptutor.runtime.home import get_runtime_data_rootfrom deeptutor.services.rag.index_versioning import (list_kb_versions,- resolve_storage_dir_for_read,resolve_storage_dir_for_rebuild,)from deeptutor.services.rag.kb_paths import resolve_kb_dir-from . import block_policy, engine, ingress, storage+from . import block_policy, engine, indexing_policy, ingress, storagefrom . import config as lr_config+from .indexing_policy import (+ IndexingLLMSnapshot,+ IndexingPolicyError,+ effective_policy,+ freeze_default_snapshot,+ resolve_write_snapshot,+)from .worker import OwnerLoopBridge, run_in_worker_looplogger = logging.getLogger(__name__)@@ -36,6 +42,8 @@ class BatchOutcome:nonterminal: dict[str, str] = field(default_factory=dict)missing: tuple[str, ...] = ()track_id: str = ""+ vlm_used: bool = False+ indexing_policy: dict[str, Any] = field(default_factory=dict)@propertydef complete(self) -> bool:@@ -111,7 +119,11 @@ class LightRagPipeline:)def _stage_documents(- self, working_dir: Path, file_paths: List[str]+ self,+ working_dir: Path,+ file_paths: List[str],+ *,+ vision_available: bool,) -> tuple[list[ingress.StagedDocument], dict[str, str]]:from deeptutor.services.parsing import get_parse_service@@ -119,7 +131,6 @@ class LightRagPipeline:staged: list[ingress.StagedDocument] = []failures: dict[str, str] = {}seen: set[str] = set()- vision_available = lr_config.vision_model_available()for raw_path in file_paths:path = Path(raw_path)name = path.name@@ -232,7 +243,10 @@ class LightRagPipeline:block_policy.write_decision_ledger(Path(rag.working_dir), doc_id, item.audit_ledger)- return outcome+ return replace(+ outcome,+ vlm_used=any("i" in getattr(item, "process_options", "") for item in staged),+ )if unknown:return BatchOutcome(requested=len(expected) + len(preflight_failed),@@ -265,10 +279,18 @@ class LightRagPipeline:working_dir: Path,file_paths: List[str],progress_callback: Callable[[int, int], Any] | None,+ snapshot: IndexingLLMSnapshot | None = None,) -> BatchOutcome:+ if snapshot is None:+ snapshot = freeze_default_snapshot()+async def job(io_bridge: OwnerLoopBridge) -> BatchOutcome:io_bridge.raise_if_cancelled()- staged, preflight_failed = self._stage_documents(working_dir, file_paths)+ staged, preflight_failed = self._stage_documents(+ working_dir,+ file_paths,+ vision_available=snapshot.vision_available,+ )if not staged:raise LightRagBatchError(BatchOutcome(requested=len(file_paths), preflight_failed=preflight_failed)@@ -278,6 +300,7 @@ class LightRagPipeline:working_dir,io_bridge=io_bridge,enable_vlm=any("i" in item.process_options for item in staged),+ indexing_snapshot=snapshot,)except BaseException:for item in staged:@@ -332,7 +355,8 @@ class LightRagPipeline:for item in cleanup:ingress.remove_unaccepted(item)- return await run_in_worker_loop(job)+ outcome = await run_in_worker_loop(job)+ return replace(outcome, indexing_policy=snapshot.persisted_policy())def _remove_zero_accepted_candidate(self, root_dir: Path) -> None:if not root_dir.is_dir() or storage.has_any_doc_status(root_dir):@@ -345,14 +369,28 @@ class LightRagPipeline:async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)+ snapshot = kwargs.get("indexing_snapshot")+ if snapshot is None:+ policy = effective_policy(+ kb_dir,+ base_dir=self.kb_base_dir,+ kb_name=kb_name,+ )+ if policy is not None and policy.get("policy") == "pending_pinned":+ snapshot = indexing_policy.snapshot_from_persisted(policy)+ else:+ snapshot = freeze_default_snapshot()root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)try:outcome = await self._run_indexing(- root_dir, file_paths, kwargs.get("progress_callback")+ root_dir, file_paths, kwargs.get("progress_callback"), snapshot)if not storage.has_output(root_dir):raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")- storage.write_meta(root_dir)+ policy = dict(outcome.indexing_policy)+ policy["vlm_used"] = outcome.vlm_used+ storage.write_meta(root_dir, indexing_policy=policy)+ self._clear_pending_policy(kb_name)return outcome.completeexcept asyncio.CancelledError:raise@@ -367,25 +405,52 @@ class LightRagPipeline:async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)- existing = resolve_storage_dir_for_read(kb_dir, None)- if existing is not None and storage.meta_is_native_published(existing):- root_dir = existing- is_update = True- elif existing is not None or list_kb_versions(kb_dir):+ existing = storage.latest_published_root(kb_dir)+ versions = list_kb_versions(kb_dir)+ explicit = kwargs.get("indexing_snapshot")+ if explicit is not None and (existing is not None or versions):+ raise IndexingPolicyError(+ "An explicit LightRAG indexing model cannot override an existing index; "+ "run a full re-index."+ )+ if existing is None and versions:raise LightRagNeedsReindexError("This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt ""before appending.")+ snapshot = resolve_write_snapshot(+ kb_dir,+ base_dir=self.kb_base_dir,+ kb_name=kb_name,+ explicit=explicit,+ )+ if existing is not None:+ root_dir = existing+ is_update = Trueelse:root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)is_update = Falsetry:outcome = await self._run_indexing(- root_dir, file_paths, kwargs.get("progress_callback")+ root_dir, file_paths, kwargs.get("progress_callback"), snapshot)if not storage.has_output(root_dir):raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")- storage.write_meta(root_dir)+ policy = dict(outcome.indexing_policy)+ policy["vlm_used"] = outcome.vlm_used+ if not is_update:+ storage.write_meta(root_dir, indexing_policy=policy)+ self._clear_pending_policy(kb_name)+ else:+ try:+ storage.write_meta(root_dir, indexing_policy=policy)+ self._clear_pending_policy(kb_name)+ except Exception:+ self.logger.warning(+ "LightRAG append completed but metadata refresh failed; preserving the "+ "existing published policy",+ exc_info=True,+ )return outcome.completeexcept LightRagBatchError as exc:if not is_update and exc.outcome.accepted == 0:@@ -396,10 +461,27 @@ class LightRagPipeline:self._remove_zero_accepted_candidate(root_dir)raise+ def _clear_pending_policy(self, kb_name: str) -> None:+ """Best-effort cleanup after version metadata became authoritative."""+ try:+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=self.kb_base_dir)+ entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}+ if "pending_indexing_policy" in entry:+ entry.pop("pending_indexing_policy", None)+ manager._save_config()+ except Exception:+ self.logger.warning(+ "Published LightRAG policy for %s but could not clear pending cache",+ kb_name,+ exc_info=True,+ )+async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)- root_dir = resolve_storage_dir_for_read(kb_dir, None)- if root_dir is None or not storage.meta_is_native_published(root_dir):+ root_dir = storage.latest_published_root(kb_dir)+ if root_dir is None:return {"query": query,"answer": "This LightRAG knowledge base must be rebuilt for the native pipeline.",diff --git a/deeptutor/services/rag/pipelines/lightrag/storage.py b/deeptutor/services/rag/pipelines/lightrag/storage.pyindex 0e477ddf9..a79a9e392 100644--- a/deeptutor/services/rag/pipelines/lightrag/storage.py+++ b/deeptutor/services/rag/pipelines/lightrag/storage.py@@ -211,7 +211,28 @@ def _parser_inputs(root_dir: Path) -> list[dict[str, str]]:]-def write_meta(root_dir: Path) -> None:+def read_published_policy(root_dir: Path | None) -> dict[str, Any] | None:+ if root_dir is None or not meta_is_native_published(root_dir):+ return None+ meta = _read_meta(Path(root_dir)) or {}+ policy = meta.get("indexing_policy")+ if isinstance(policy, dict):+ return policy+ return {"policy": "legacy_unpinned"}+++def latest_published_root(kb_dir: Path) -> Path | None:+ """Return the newest native published version, ignoring failed candidates."""+ from deeptutor.services.rag.index_versioning import list_kb_versions++ for entry in list_kb_versions(Path(kb_dir)):+ root = Path(str(entry.get("storage_path") or ""))+ if meta_is_native_published(root):+ return root+ return None+++def write_meta(root_dir: Path, *, indexing_policy: dict[str, Any] | None = None) -> None:"""Write a flat-layout ``meta.json`` so the version lists as ready.Mirrors ``index_versioning.write_version_meta`` but carries a synthetic@@ -240,6 +261,9 @@ def write_meta(root_dir: Path) -> None:"layout": "flat","created_at": str(previous.get("created_at") or now),"updated_at": now,+ "indexing_policy": indexing_policy+ or previous.get("indexing_policy")+ or {"policy": "legacy_unpinned"},**embedding_meta_fields(),}atomic_write_json(target / META_FILENAME, payload)@@ -254,5 +278,7 @@ __all__ = ["working_dir","has_output","meta_is_native_published",+ "latest_published_root",+ "read_published_policy","write_meta",]diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.pyindex cec76d14a..1fe054a20 100644--- a/deeptutor/services/search/__init__.py+++ b/deeptutor/services/search/__init__.py@@ -263,6 +263,10 @@ def get_current_config() -> dict[str, Any]:"""Get effective web search configuration for UI/CLI display."""config = _get_web_search_config()resolved = resolve_search_runtime_config()+ source_filtering = dict(_get_source_filter_settings())+ # Never surface the bearer token to Settings / CLI — only whether Moderation+ # is wired (key present + use_moderation).+ source_filtering["moderation_configured"] = bool(source_filtering.pop("moderation_api_key", ""))return {"enabled": config.get("enabled", True),"provider": resolved.provider,@@ -277,7 +281,7 @@ def get_current_config() -> dict[str, Any]:"supported_providers": sorted(SUPPORTED_SEARCH_PROVIDERS),"deprecated_providers": sorted(DEPRECATED_SEARCH_PROVIDERS),"consolidation_template": config.get("consolidation_template") or None,- "source_filtering": _get_source_filter_settings(),+ "source_filtering": source_filtering,"template_providers": list(PROVIDER_TEMPLATES.keys()),}diff --git a/deeptutor/services/search/source_filter.py b/deeptutor/services/search/source_filter.pyindex fe0667286..bfb85ccdf 100644--- a/deeptutor/services/search/source_filter.py+++ b/deeptutor/services/search/source_filter.py@@ -3,14 +3,79 @@from __future__ import annotationsimport ipaddress+import json+import logging+import os+import refrom typing import Anyfrom urllib.parse import urlparse+import urllib.requestfrom .types import Citation, SearchResult, WebSearchResponse+_logger = logging.getLogger(__name__)+_ALLOWED_PORTS = frozenset({80, 443})_PRIVATE_HOST_SUFFIXES = (".local", ".internal", ".lan", ".home.arpa")+# Opt-in educational allowlist (#375). Enabled only when+# ``use_educational_trusted_domains`` is true — never silently replaces an+# empty trusted list.+EDUCATIONAL_TRUSTED_DOMAINS: tuple[str, ...] = (+ "wikipedia.org",+ "wikimedia.org",+ "khanacademy.org",+ "britannica.com",+ "arxiv.org",+ "nih.gov",+ "nasa.gov",+ "edu",+ "ac.uk",+ "gov",+ "scholastic.com",+ "coursera.org",+ "edx.org",+ "mit.edu",+ "stanford.edu",+ "harvard.edu",+ "ox.ac.uk",+ "cam.ac.uk",+)++# Title / snippet / URL-path heuristics. Prefer strong tokens over soft words+# that collide with educational topics (e.g. bare "sex" in sex education).+_UNSAFE_CONTENT_PATTERNS: tuple[re.Pattern[str], ...] = tuple(+ re.compile(pattern, re.IGNORECASE)+ for pattern in (+ r"\bporn(?:ography|ographic|hub|tube|o)?\b",+ r"\bxnxx\b",+ r"\bxvideos?\b",+ r"\bonlyfans\b",+ r"\bnsfw\b",+ r"\bxxx\b",+ r"\berotic(?:a)?\b",+ r"\bcamgirl(?:s)?\b",+ r"\bescor(?:t|ts)\b",+ r"\bonline\s+casino\b",+ r"\bgambling\b",+ r"\bbetting\s+odds\b",+ r"\bslot\s+machines?\b",+ r"\bdrug\s+marketplace\b",+ r"\bbuy\s+(?:weed|cocaine|fentanyl)\b",+ )+)++_UNSAFE_URL_PATH_PATTERNS: tuple[re.Pattern[str], ...] = tuple(+ re.compile(pattern, re.IGNORECASE)+ for pattern in (+ r"/(?:porn|xxx|sexcam|escort|casino|gambling)(?:/|$)",+ r"\.(?:xxx)(?:/|$)",+ )+)++_MODERATION_URL = "https://api.openai.com/v1/moderations"+_MODERATION_TIMEOUT_S = 8.0+def _as_bool(value: Any, default: bool = False) -> bool:if value is None:@@ -46,6 +111,15 @@ def _domains(value: Any) -> tuple[str, ...]:return tuple(normalized)+def _merge_domains(*groups: tuple[str, ...]) -> tuple[str, ...]:+ merged: list[str] = []+ for group in groups:+ for host in group:+ if host and host not in merged:+ merged.append(host)+ return tuple(merged)++def _matches_domain(host: str, patterns: tuple[str, ...]) -> bool:return any(host == pattern or host.endswith(f".{pattern}") for pattern in patterns)@@ -102,30 +176,111 @@ def _rejection_reason(return "", host+def _content_rejection_reason(*, title: str, snippet: str, url: str) -> str:+ """Heuristic title/snippet/path check for clearly non-educational material."""+ haystack = f"{title}\n{snippet}".strip()+ if haystack:+ for pattern in _UNSAFE_CONTENT_PATTERNS:+ if pattern.search(haystack):+ return "unsafe_content"+ path = ""+ try:+ path = urlparse(str(url or "")).path or ""+ except ValueError:+ path = str(url or "")+ combined = f"{path}\n{url}"+ for pattern in _UNSAFE_URL_PATH_PATTERNS:+ if pattern.search(combined):+ return "unsafe_content"+ return ""+++def _moderation_rejections(+ texts: list[str],+ *,+ api_key: str,+ request_moderation: Any | None = None,+) -> dict[str, bool]:+ """Return batched Moderation decisions keyed by the submitted text.++ Fail open on transport/API errors so a Moderation outage does not blank+ every web-search turn — heuristics already ran.+ """+ payloads = list(dict.fromkeys(text.strip()[:4000] for text in texts if text.strip()))+ if not payloads or not api_key:+ return {}+ requester = request_moderation or _request_openai_moderation+ try:+ flagged = requester(payloads, api_key=api_key)+ if not isinstance(flagged, (list, tuple)) or len(flagged) != len(payloads):+ raise ValueError("Moderation returned an unexpected result count")+ except Exception as exc: # noqa: BLE001 — network / JSON / provider quirks+ _logger.warning("OpenAI Moderation skipped after error: %s", exc)+ return {}+ return {text: bool(decision) for text, decision in zip(payloads, flagged, strict=True)}+++def _request_openai_moderation(texts: list[str], *, api_key: str) -> list[bool]:+ body = json.dumps({"input": texts}).encode("utf-8")+ request = urllib.request.Request(+ _MODERATION_URL,+ data=body,+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ "User-Agent": "DeepTutor-source-filter/1.0",+ },+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=_MODERATION_TIMEOUT_S) as response:+ raw = json.loads(response.read().decode("utf-8"))+ results = raw.get("results") if isinstance(raw, dict) else None+ if not isinstance(results, list) or len(results) != len(texts):+ raise ValueError("Moderation returned an unexpected result count")+ return [bool(isinstance(result, dict) and result.get("flagged")) for result in results]+++def _reference_text(*, title: str = "", snippet: str = "", content: str = "") -> str:+ parts = [str(title or "").strip(), str(snippet or "").strip(), str(content or "").strip()]+ return "\n".join(part for part in parts if part)++def filter_web_search_response(response: WebSearchResponse,*,enabled: bool = True,blocked_domains: Any = None,trusted_domains: Any = None,+ content_filtering: bool = True,+ use_educational_trusted_domains: bool = False,+ use_moderation: bool = False,+ moderation_api_key: str | None = None,+ request_moderation: Any | None = None,) -> WebSearchResponse:"""Drop unsafe or disallowed references from a provider response.Citation ids and reference labels stay unchanged when an item is removed.Provider-authored answers already cite those labels, so renumbering herewould turn a harmless gap into incorrect citations.++ Stages (in order):+ 1. URL hygiene / domain policy (existing)+ 2. Title + snippet heuristics (``content_filtering``, on by default)+ 3. Optional OpenAI Moderation when ``use_moderation`` and a key are set"""if not enabled:return responseblocked = _domains(blocked_domains)trusted = _domains(trusted_domains)- kept_citations: list[Citation] = []- kept_results: list[SearchResult] = []- removed_citations = 0- removed_results = 0- answer_invalidated = False- rejected_hosts: list[str] = []+ if use_educational_trusted_domains:+ trusted = _merge_domains(trusted, EDUCATIONAL_TRUSTED_DOMAINS)++ moderation_key = str(moderation_api_key or "").strip()+ moderation_active = bool(use_moderation and moderation_key)++ citation_rows: list[tuple[Citation, str, str, str]] = []+ result_rows: list[tuple[SearchResult, str, str, str]] = []for citation in response.citations:reason, host = _rejection_reason(@@ -133,12 +288,22 @@ def filter_web_search_response(blocked_domains=blocked,trusted_domains=trusted,)- if reason:- removed_citations += 1- if host and host not in rejected_hosts:- rejected_hosts.append(host)- else:- kept_citations.append(citation)+ if not reason and content_filtering:+ reason = _content_rejection_reason(+ title=citation.title,+ snippet="\n".join(part for part in (citation.snippet, citation.content) if part),+ url=citation.url,+ )+ moderation_text = (+ _reference_text(+ title=citation.title,+ snippet=citation.snippet,+ content=citation.content,+ )[:4000]+ if not reason and moderation_active+ else ""+ )+ citation_rows.append((citation, reason, host, moderation_text))for result in response.search_results:reason, host = _rejection_reason(@@ -146,14 +311,75 @@ def filter_web_search_response(blocked_domains=blocked,trusted_domains=trusted,)+ if not reason and content_filtering:+ reason = _content_rejection_reason(+ title=result.title,+ snippet="\n".join(part for part in (result.snippet, result.content) if part),+ url=result.url,+ )+ moderation_text = (+ _reference_text(+ title=result.title,+ snippet=result.snippet,+ content=result.content,+ )[:4000]+ if not reason and moderation_active+ else ""+ )+ result_rows.append((result, reason, host, moderation_text))++ moderation_decisions = _moderation_rejections(+ [row[3] for row in (*citation_rows, *result_rows) if row[3]],+ api_key=moderation_key,+ request_moderation=request_moderation,+ )++ kept_citations: list[Citation] = []+ kept_results: list[SearchResult] = []+ removed_citations = 0+ removed_results = 0+ answer_invalidated = False+ rejected_hosts: list[str] = []+ rejected_reasons: list[str] = []++ def _record_reason(reason: str, host: str = "") -> None:+ if reason and reason not in rejected_reasons:+ rejected_reasons.append(reason)+ if host and host not in rejected_hosts:+ rejected_hosts.append(host)++ for citation, reason, host, moderation_text in citation_rows:+ if not reason and moderation_decisions.get(moderation_text, False):+ reason = "moderation_flagged"+ if reason:+ removed_citations += 1+ _record_reason(reason, host)+ else:+ kept_citations.append(citation)++ for result, reason, host, moderation_text in result_rows:+ if not reason and moderation_decisions.get(moderation_text, False):+ reason = "moderation_flagged"if reason:removed_results += 1- if host and host not in rejected_hosts:- rejected_hosts.append(host)+ _record_reason(reason, host)else:kept_results.append(result)+ policy_meta = {+ "removed_citations": removed_citations,+ "removed_search_results": removed_results,+ "rejected_hosts": rejected_hosts,+ "rejected_reasons": rejected_reasons,+ "answer_invalidated": answer_invalidated,+ "content_filtering": content_filtering,+ "moderation_enabled": moderation_active,+ "educational_trusted_domains": use_educational_trusted_domains,+ }+if not removed_citations and not removed_results:+ # Still record policy flags so callers / Settings can introspect.+ response.metadata["source_filter"] = policy_metareturn responseif removed_citations and response.answer.strip():@@ -163,27 +389,46 @@ def filter_web_search_response(# the retained raw results.response.answer = ""answer_invalidated = True+ policy_meta["answer_invalidated"] = Trueresponse.citations = kept_citationsresponse.search_results = kept_results- response.metadata["source_filter"] = {- "removed_citations": removed_citations,- "removed_search_results": removed_results,- "rejected_hosts": rejected_hosts,- "answer_invalidated": answer_invalidated,- }+ response.metadata["source_filter"] = policy_metareturn response+def resolve_moderation_api_key() -> str:+ """Pick a Moderation bearer token from the process environment."""+ for name in ("OPENAI_API_KEY", "DEEPTUTOR_OPENAI_API_KEY"):+ value = str(os.environ.get(name) or "").strip()+ if value:+ return value+ return ""++def settings_from_config(config: Any) -> dict[str, Any]:"""Read the optional ``tools.web_search.source_filtering`` config section."""raw = config.get("source_filtering", {}) if isinstance(config, dict) else {}settings = raw if isinstance(raw, dict) else {}+ use_moderation = _as_bool(settings.get("use_moderation"), False)+ moderation_key = resolve_moderation_api_key()return {"enabled": _as_bool(settings.get("enabled"), True),"blocked_domains": _domains(settings.get("blocked_domains")),"trusted_domains": _domains(settings.get("trusted_domains")),+ "content_filtering": _as_bool(settings.get("content_filtering"), True),+ "use_educational_trusted_domains": _as_bool(+ settings.get("use_educational_trusted_domains"),+ False,+ ),+ "use_moderation": use_moderation,+ "moderation_api_key": moderation_key if use_moderation else "",}-__all__ = ["filter_web_search_response", "settings_from_config"]+__all__ = [+ "EDUCATIONAL_TRUSTED_DOMAINS",+ "filter_web_search_response",+ "resolve_moderation_api_key",+ "settings_from_config",+]diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.pyindex 4d3a11755..5bdf7a523 100644--- a/deeptutor/services/session/_turn_runtime_shared.py+++ b/deeptutor/services/session/_turn_runtime_shared.py@@ -10,6 +10,7 @@ from dataclasses import dataclass, fieldimport loggingimport refrom typing import TYPE_CHECKING, Any, Literal+import unicodedatafrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.services.llm.utils import clean_thinking_tags@@ -118,6 +119,150 @@ def _assemble_persisted_answer()+_FENCED_CODE_BLOCK_RE = re.compile(r"```[\s\S]*?```")+_INLINE_CODE_SPAN_RE = re.compile(r"`[^`\n]*`")+_MATH_SPAN_RE = re.compile(+ r"\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$\$[\s\S]*?\$\$|\$(?!\s)(?:\\.|[^$\n])*?(?<!\s)\$"+)+++def _is_escaped(text: str, index: int) -> bool:+ """Whether the character at index has an odd-length backslash prefix."""+ slash_count = 0+ cursor = index - 1+ while cursor >= 0 and text[cursor] == "\\":+ slash_count += 1+ cursor -= 1+ return slash_count % 2 == 1+++def _is_emphasis_normal_character(value: str | None) -> bool:+ return bool(value and (value.isalpha() or value.isnumeric()))+++def _is_emphasis_punctuation_or_symbol(value: str | None) -> bool:+ return bool(value and unicodedata.category(value)[0] in {"P", "S"})+++def _can_open_emphasis(line: str, index: int, marker: str) -> bool:+ before = line[index - 1] if index else None+ after_index = index + len(marker)+ after = line[after_index] if after_index < len(line) else None+ if after is None or after.isspace():+ return False+ if _is_emphasis_punctuation_or_symbol(after):+ return (+ before is None+ or before.isspace()+ or _is_emphasis_punctuation_or_symbol(before)+ or _is_emphasis_normal_character(before)+ )+ return True+++def _can_close_emphasis(line: str, index: int, marker: str) -> bool:+ before = line[index - 1] if index else None+ after_index = index + len(marker)+ after = line[after_index] if after_index < len(line) else None+ if before is None or before.isspace():+ return False+ if _is_emphasis_punctuation_or_symbol(before):+ return (+ after is None+ or after.isspace()+ or _is_emphasis_punctuation_or_symbol(after)+ or _is_emphasis_normal_character(after)+ )+ return True+++def _paired_emphasis_delimiters(line: str) -> list[tuple[str, int, int]]:+ """Return only syntactically plausible (marker, left opener, right closer) pairs."""+ openers: dict[str, list[int]] = {"*": [], "**": []}+ pairs: list[tuple[str, int, int]] = []+ cursor = 0+ while cursor < len(line):+ if line[cursor] != "*" or _is_escaped(line, cursor):+ cursor += 1+ continue+ run_end = cursor+ while run_end < len(line) and line[run_end] == "*":+ run_end += 1+ marker = line[cursor:run_end]+ if marker in openers:+ can_open = _can_open_emphasis(line, cursor, marker)+ can_close = _can_close_emphasis(line, cursor, marker)+ if can_close and openers[marker]:+ pairs.append((marker, openers[marker].pop(), cursor))+ elif can_open:+ openers[marker].append(cursor)+ cursor = run_end+ return pairs+++def _repair_chinese_emphasis_line(line: str) -> str:+ insertions: set[int] = set()+ for marker, left_opener, right_closer in _paired_emphasis_delimiters(line):+ left_before = line[left_opener - 1] if left_opener else None+ left_inside = (+ line[left_opener + len(marker)] if left_opener + len(marker) < len(line) else None+ )+ right_inside = line[right_closer - 1] if right_closer else None+ right_after_index = right_closer + len(marker)+ right_after = line[right_after_index] if right_after_index < len(line) else None++ left_needs_space = _is_emphasis_normal_character(+ left_before+ ) and _is_emphasis_punctuation_or_symbol(left_inside)+ right_needs_space = _is_emphasis_punctuation_or_symbol(+ right_inside+ ) and _is_emphasis_normal_character(right_after)+ if left_needs_space:+ insertions.add(left_opener)+ if right_needs_space:+ insertions.add(right_after_index)++ # Only mirror a required repair onto the other marker in THIS pair.+ if left_needs_space != right_needs_space:+ if _is_emphasis_normal_character(right_inside) and _is_emphasis_normal_character(+ right_after+ ):+ insertions.add(right_after_index)+ elif _is_emphasis_normal_character(left_before) and _is_emphasis_normal_character(+ left_inside+ ):+ insertions.add(left_opener)++ for index in sorted(insertions, reverse=True):+ line = f"{line[:index]} {line[index:]}"+ return line+++def _repair_chinese_emphasis_for_persistence(content: str, language: str) -> str:+ """Normalize CJK Markdown emphasis before the assistant answer is stored.++ This deliberately runs only for Chinese model output and leaves code and+ mathematics literal, so the persisted source matches its valid rendering.+ """+ if not content or not str(language or "").lower().startswith("zh"):+ return content+ protected: list[str] = []++ def mask(match: re.Match[str]) -> str:+ protected.append(match.group(0))+ return f"\x00CJK_PROTECTED_{len(protected) - 1}\x00"++ masked = _FENCED_CODE_BLOCK_RE.sub(mask, content)+ masked = _MATH_SPAN_RE.sub(mask, masked)+ masked = _INLINE_CODE_SPAN_RE.sub(mask, masked)+ repaired = "\n".join(_repair_chinese_emphasis_line(line) for line in masked.split("\n"))+ return re.sub(+ r"\x00CJK_PROTECTED_(\d+)\x00",+ lambda match: protected[int(match.group(1))],+ repaired,+ )++def _stamp_ask_user_content_offset(payload_event: dict[str, Any],assistant_content: str,diff --git a/deeptutor/services/session/event_preview.py b/deeptutor/services/session/event_preview.pynew file mode 100644index 000000000..167485f78--- /dev/null+++ b/deeptutor/services/session/event_preview.py@@ -0,0 +1,134 @@+"""Bounded event previews used by session-detail responses.++``turn_events`` remains the authoritative full trace. Session lists only need+enough semantic state to render a completed message, resume pending input, and+offer the trace disclosure; the complete trace is fetched on demand.+"""++from __future__ import annotations++import copy+import json+from typing import Any++MAX_TRACE_PREVIEW_EVENTS = 200+MAX_TRACE_PREVIEW_BYTES = 128 * 1024+MAX_LEGACY_EVENT_PAYLOAD_CHARS = 16 * 1024+_TRUNCATION_NOTICE = "...[truncated]"+_TERMINAL_EVENT_TYPES = frozenset({"done", "error", "cancelled"})+_SEMANTIC_EVENT_TYPES = _TERMINAL_EVENT_TYPES | {+ "result",+ "tool_call",+ "tool_result",+}+++def _metadata(event: dict[str, Any]) -> dict[str, Any]:+ metadata = event.get("metadata")+ return metadata if isinstance(metadata, dict) else {}+++def _is_semantic(event: dict[str, Any]) -> bool:+ event_type = str(event.get("type") or "")+ if event_type in _SEMANTIC_EVENT_TYPES:+ return True+ return _has_ask_user(event)+++def _has_ask_user(event: dict[str, Any]) -> bool:+ metadata = _metadata(event)+ return bool(+ metadata.get("ask_user")+ or metadata.get("ask_user_resolved")+ or isinstance(metadata.get("tool_metadata"), dict)+ and isinstance(metadata["tool_metadata"].get("ask_user"), dict)+ )+++def _is_critical(event: dict[str, Any]) -> bool:+ if str(event.get("type") or "") in _TERMINAL_EVENT_TYPES | {"result"}:+ return True+ return _has_ask_user(event)+++def _truncate_legacy_payloads(event: dict[str, Any]) -> dict[str, Any]:+ """Bound old embedded payloads without mutating the source event."""+ truncated = False+ bounded = copy.deepcopy(event)++ def cap(container: dict[str, Any], field: str) -> None:+ nonlocal truncated+ value = container.get(field)+ if isinstance(value, str) and len(value) > MAX_LEGACY_EVENT_PAYLOAD_CHARS:+ container[field] = value[:MAX_LEGACY_EVENT_PAYLOAD_CHARS] + _TRUNCATION_NOTICE+ truncated = True++ cap(bounded, "content")+ metadata = bounded.get("metadata")+ if isinstance(metadata, dict):+ tool_metadata = metadata.get("tool_metadata")+ if isinstance(tool_metadata, dict):+ cap(tool_metadata, "content")+ cap(tool_metadata, "answer")+ return bounded if truncated else event+++def compact_trace_preview(+ events: list[dict[str, Any]],+ *,+ max_events: int = MAX_TRACE_PREVIEW_EVENTS,+ max_bytes: int = MAX_TRACE_PREVIEW_BYTES,+) -> tuple[list[dict[str, Any]], bool]:+ """Return a bounded semantic preview and whether any event was omitted."""+ semantic = [+ (index, event)+ for index, event in enumerate(events)+ if isinstance(event, dict) and _is_semantic(event)+ ]+ # Ask_user, results, errors, and terminal state outrank ordinary trace rows.+ # Keep the most recent critical rows, then fill toward the turn's tail.+ critical = {index for index, event in semantic if _is_critical(event)}+ if len(critical) > max_events:+ ordered_critical = sorted(critical)+ critical = set(ordered_critical[-max_events:])+ selected_indices = set(critical)+ for index, _event in reversed(semantic):+ if len(selected_indices) >= max_events:+ break+ selected_indices.add(index)+ selected = [event for index, event in semantic if index in selected_indices]+ result: list[dict[str, Any]] = []+ used_bytes = 0+ for event in selected:+ bounded = _truncate_legacy_payloads(event)+ size = len(json.dumps(bounded, ensure_ascii=False, default=str).encode("utf-8"))+ if result and used_bytes + size > max_bytes:+ continue+ if not result and size > max_bytes:+ bounded = {+ "type": bounded.get("type", ""),+ "turn_id": bounded.get("turn_id"),+ "session_id": bounded.get("session_id"),+ "seq": bounded.get("seq"),+ "content": _TRUNCATION_NOTICE,+ "_truncated": True,+ }+ size = len(json.dumps(bounded, ensure_ascii=False, default=str).encode("utf-8"))+ result.append(bounded)+ used_bytes += size++ omitted = len(events) != len(result) or len(selected) != len(result)+ terminal = next(+ (+ event+ for event in reversed(result)+ if str(event.get("type") or "") in _TERMINAL_EVENT_TYPES+ ),+ None,+ )+ if terminal is None:+ for event in reversed(events):+ if isinstance(event, dict) and str(event.get("type") or "") in _TERMINAL_EVENT_TYPES:+ result.append(copy.deepcopy(event))+ break+ return result, omitteddiff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.pyindex c05e8f364..7745772aa 100644--- a/deeptutor/services/session/pocketbase_store.py+++ b/deeptutor/services/session/pocketbase_store.py@@ -26,6 +26,7 @@ from typing import Anyimport uuidfrom .ask_user_trace import filter_ask_user_events+from .event_preview import MAX_TRACE_PREVIEW_EVENTS, compact_trace_previewfrom .provider_response_state import redact_private_message_metadatafrom .scope import StoreScopefrom .workspace_preferences import upgrade_workspace_preferences@@ -631,24 +632,94 @@ class PocketBaseSessionStore:logger.warning(f"get_last_message failed: {exc}")return None+ @staticmethod+ def _event_record_to_payload(row: Any, session_id: str, turn_id: str) -> dict[str, Any]:+ return {+ "type": getattr(row, "type", ""),+ "source": getattr(row, "source", "") or "",+ "stage": getattr(row, "stage", "") or "",+ "content": getattr(row, "content", "") or "",+ "metadata": _json_loads(getattr(row, "metadata_json", None), {}),+ "session_id": session_id,+ "turn_id": turn_id,+ "seq": int(getattr(row, "seq", 0) or 0),+ "timestamp": _to_float(getattr(row, "event_timestamp", None)),+ }++ @staticmethod+ def _page_items(page: Any) -> list[Any]:+ return list(getattr(page, "items", ()) or ())++ @staticmethod+ def _page_total(page: Any) -> int:+ value = getattr(page, "total_items", getattr(page, "totalItems", None))+ return max(+ 0, int(value if value is not None else len(PocketBaseSessionStore._page_items(page)))+ )++ def _trace_preview(+ self, pb: Any, *, session_id: str, turn_id: str+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ turn_id = _validate_id(turn_id, "turn_id")+ page = pb.collection("turn_events").get_list(+ 1,+ MAX_TRACE_PREVIEW_EVENTS,+ query_params={"filter": f'turn_id="{turn_id}"', "sort": "-seq"},+ )+ rows = list(reversed(self._page_items(page)))+ events = [self._event_record_to_payload(row, session_id, turn_id) for row in rows]+ preview, omitted = compact_trace_preview(events)+ total = self._page_total(page)+ last_seq = int(getattr(rows[-1], "seq", 0) or 0) if rows else 0+ return preview, {+ "turn_id": turn_id,+ "total": total,+ "last_seq": last_seq,+ "truncated": omitted or total != len(preview),+ }+async def get_messages(self, session_id: str) -> list[dict[str, Any]]:sid = _validate_id(session_id, "session_id")- def _get():- return (- _pb()- .collection("messages")- .get_full_list(- query_params={- "filter": f'session_id="{sid}"',- "sort": "msg_created_at",- }- )+ def _get() -> list[dict[str, Any]]:+ pb = _pb()+ records = pb.collection("messages").get_full_list(+ query_params={+ "filter": f'session_id="{sid}"',+ "sort": "msg_created_at",+ })+ turns = pb.collection("turns").get_full_list(+ query_params={"filter": f'session_id="{sid}"'}+ )+ turns_by_message = {+ str(getattr(turn, "assistant_message_id", "") or ""): turn+ for turn in turns+ if getattr(turn, "assistant_message_id", None)+ }+ result: list[dict[str, Any]] = []+ for record in records:+ message = self._message_record_to_dict(record)+ turn = turns_by_message.get(str(record.id))+ if record.role == "assistant" and turn is not None:+ turn_id = str(getattr(turn, "turn_id", turn.id) or "")+ message["events"], message["trace"] = self._trace_preview(+ pb, session_id=sid, turn_id=turn_id+ )+ elif record.role == "assistant":+ legacy_events = message["events"]+ message["events"], omitted = compact_trace_preview(legacy_events)+ message["trace"] = {+ "turn_id": None,+ "total": len(legacy_events),+ "last_seq": 0,+ "truncated": omitted,+ }+ result.append(message)+ return resulttry:- records = await asyncio.to_thread(_get)- return [self._message_record_to_dict(r) for r in records]+ return await asyncio.to_thread(_get)except Exception as exc:logger.warning(f"get_messages failed: {exc}")return []@@ -740,6 +811,7 @@ class PocketBaseSessionStore:"state_version": 1,"failure_code": "","retryable": False,+ "assistant_message_id": None,}))@@ -761,6 +833,7 @@ class PocketBaseSessionStore:"state_version": 1,"failure_code": "","retryable": False,+ "assistant_message_id": None,}async def create_turn(self, session_id: str, capability: str = "") -> dict[str, Any]:@@ -914,8 +987,107 @@ class PocketBaseSessionStore:"state_version": int(getattr(record, "state_version", 1) or 1),"failure_code": getattr(record, "failure_code", "") or "","retryable": bool(getattr(record, "retryable", False)),+ "assistant_message_id": getattr(record, "assistant_message_id", None),}+ async def link_turn_message(self, turn_id: str, assistant_message_id: int | str) -> bool:+ tid = _validate_id(turn_id, "turn_id")+ message_id = _validate_id(str(assistant_message_id), "assistant_message_id")++ def _link() -> bool:+ page = (+ _pb()+ .collection("turns")+ .get_list(1, 1, query_params={"filter": f'turn_id="{tid}"'})+ )+ turns = self._page_items(page)+ if not turns:+ return False+ record = turns[0]+ if getattr(record, "assistant_message_id", None):+ return False+ _pb().collection("turns").update(+ record.id,+ {+ "assistant_message_id": message_id,+ "turn_updated_at": time.time(),+ },+ )+ return True++ return await asyncio.to_thread(_link)++ async def get_message_trace(+ self,+ session_id: str,+ message_id: int | str,+ after_seq: int = 0,+ limit: int | None = None,+ ) -> dict[str, Any] | None:+ try:+ sid = _validate_id(session_id, "session_id")+ mid = _validate_id(str(message_id), "message_id")+ except ValueError:+ return None+ row_limit = 500 if limit is None else min(1000, max(1, int(limit)))+ uid = _current_user_id()++ def _get():+ pb = _pb()+ if _find_session_record(pb, sid, uid) is None:+ return None+ message_page = pb.collection("messages").get_list(+ 1,+ 1,+ query_params={"filter": f'id="{mid}" && session_id="{sid}"'},+ )+ messages = self._page_items(message_page)+ if not messages:+ return None+ turn_page = pb.collection("turns").get_list(+ 1,+ 1,+ query_params={"filter": f'assistant_message_id="{mid}"'},+ )+ turns = self._page_items(turn_page)+ if not turns:+ return None+ turn = turns[0]+ turn_id = str(getattr(turn, "turn_id", getattr(turn, "id", "")) or "")+ stats_page = pb.collection("turn_events").get_list(+ 1,+ 1,+ query_params={"filter": f'turn_id="{turn_id}"', "sort": "-seq"},+ )+ last_rows = self._page_items(stats_page)+ last_seq = int(getattr(last_rows[0], "seq", 0) or 0) if last_rows else 0+ event_page = pb.collection("turn_events").get_list(+ 1,+ row_limit,+ query_params={+ "filter": f'turn_id="{turn_id}" && seq>{max(0, int(after_seq))}',+ "sort": "seq",+ },+ )+ events = [+ self._event_record_to_payload(row, sid, turn_id)+ for row in self._page_items(event_page)+ ]+ loaded_seq = int(events[-1]["seq"]) if events else max(0, int(after_seq))+ complete = loaded_seq >= last_seq+ return {+ "session_id": sid,+ "message_id": message_id,+ "turn_id": turn_id,+ "events": events,+ "total": self._page_total(stats_page),+ "last_seq": last_seq,+ "next_seq": None if complete else loaded_seq,+ "complete": complete,+ }++ return await asyncio.to_thread(_get)+# ------------------------------------------------------------------# Turn events — synchronously durable before terminal transition# ------------------------------------------------------------------diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.pyindex e9a22605f..8e4491691 100644--- a/deeptutor/services/session/protocol.py+++ b/deeptutor/services/session/protocol.py@@ -132,6 +132,16 @@ class SessionStoreProtocol(SessionRepository, TurnRepository, MessageRepository,async def get_turn_events(self, turn_id: str, after_seq: int = 0) -> list[dict[str, Any]]: ...+ async def link_turn_message(self, turn_id: str, assistant_message_id: int | str) -> bool: ...++ async def get_message_trace(+ self,+ session_id: str,+ message_id: int | str,+ after_seq: int = 0,+ limit: int | None = None,+ ) -> dict[str, Any] | None: ...+async def update_session_title(self, session_id: str, title: str) -> bool: ...async def delete_session(self, session_id: str) -> bool: ...diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex ee59ae100..866cc60c0 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -26,6 +26,7 @@ from deeptutor.services.path_service import get_path_servicefrom deeptutor.utils.secret_files import ensure_private_directory, ensure_private_filefrom .ask_user_trace import select_ask_user_events+from .event_preview import MAX_TRACE_PREVIEW_EVENTS, compact_trace_previewfrom .provider_response_state import redact_private_message_metadatafrom .workspace_preferences import upgrade_workspace_preferences@@ -116,6 +117,7 @@ class TurnRecord:state_version: int = 1failure_code: str = ""retryable: bool = False+ assistant_message_id: int | None = Nonedef to_dict(self) -> dict[str, Any]:return {@@ -134,6 +136,7 @@ class TurnRecord:"state_version": self.state_version,"failure_code": self.failure_code,"retryable": self.retryable,+ "assistant_message_id": self.assistant_message_id,}@@ -274,7 +277,8 @@ class SQLiteSessionStore:fencing_token INTEGER NOT NULL DEFAULT 0,state_version INTEGER NOT NULL DEFAULT 1,failure_code TEXT DEFAULT '',- retryable INTEGER NOT NULL DEFAULT 0+ retryable INTEGER NOT NULL DEFAULT 0,+ assistant_message_id INTEGER);CREATE INDEX IF NOT EXISTS idx_turns_session_updated@@ -452,6 +456,33 @@ class SQLiteSessionStore:for name, definition in additions.items():if name not in columns:conn.execute(f"ALTER TABLE turns ADD COLUMN {name} {definition}")+ if "assistant_message_id" not in columns:+ conn.execute("ALTER TABLE turns ADD COLUMN assistant_message_id INTEGER")+ # v1.6.3 already persisted DONE with the assistant row id. Recover+ # those links once so old traces can be served from turn_events.+ conn.execute(+ """+ UPDATE turns+ SET assistant_message_id = (+ SELECT m.id+ FROM messages AS m, json_each(m.events_json) AS event+ WHERE m.session_id = turns.session_id+ AND m.role = 'assistant'+ AND json_extract(event.value, '$.type') = 'done'+ AND json_extract(event.value, '$.turn_id') = turns.id+ AND json_extract(event.value, '$.metadata.assistant_message_id') IS NOT NULL+ LIMIT 1+ )+ WHERE assistant_message_id IS NULL+ """+ )+ conn.execute(+ """+ CREATE UNIQUE INDEX IF NOT EXISTS idx_turns_assistant_message+ ON turns(assistant_message_id)+ WHERE assistant_message_id IS NOT NULL+ """+ )duplicate_rows = conn.execute("""@@ -778,6 +809,9 @@ class SQLiteSessionStore:state_version=(int(row["state_version"] or 1) if "state_version" in row.keys() else 1),failure_code=(row["failure_code"] or "" if "failure_code" in row.keys() else ""),retryable=(bool(row["retryable"]) if "retryable" in row.keys() else False),+ assistant_message_id=(+ row["assistant_message_id"] if "assistant_message_id" in row.keys() else None+ ),).to_dict()def _begin_turn_sync(@@ -1034,6 +1068,20 @@ class SQLiteSessionStore:and (event.get("metadata") or {}) == _json_loads(row["metadata_json"], {}))+ @staticmethod+ def _turn_event_row_to_payload(row: sqlite3.Row) -> dict[str, Any]:+ return {+ "type": row["type"],+ "source": row["source"] or "",+ "stage": row["stage"] or "",+ "content": row["content"] or "",+ "metadata": _json_loads(row["metadata_json"], {}),+ "session_id": "",+ "turn_id": row["turn_id"],+ "seq": row["seq"],+ "timestamp": row["timestamp"],+ }+def _append_turn_events_sync(self,turn_id: str,@@ -1171,6 +1219,109 @@ class SQLiteSessionStore:async def get_events(self, turn_id: str, after_seq: int = 0) -> list[dict[str, Any]]:return await self.get_turn_events(turn_id, after_seq)+ def _link_turn_message_sync(self, turn_id: str, assistant_message_id: int) -> bool:+ with self._connect() as conn:+ cur = conn.execute(+ """+ UPDATE turns+ SET assistant_message_id = ?, updated_at = ?+ WHERE id = ?+ AND session_id = (SELECT session_id FROM messages WHERE id = ?)+ AND assistant_message_id IS NULL+ """,+ (int(assistant_message_id), time.time(), turn_id, int(assistant_message_id)),+ )+ conn.commit()+ return cur.rowcount > 0++ async def link_turn_message(self, turn_id: str, assistant_message_id: int) -> bool:+ return await self._run(self._link_turn_message_sync, turn_id, int(assistant_message_id))++ def _get_message_trace_sync(+ self,+ session_id: str,+ message_id: int,+ after_seq: int = 0,+ limit: int | None = None,+ ) -> dict[str, Any] | None:+ row_limit = 500 if limit is None else min(1000, max(1, int(limit)))+ with self._connect() as conn:+ message = conn.execute(+ """+ SELECT m.id, m.role, t.id AS turn_id+ FROM messages AS m+ LEFT JOIN turns AS t ON t.assistant_message_id = m.id+ WHERE m.id = ? AND m.session_id = ?+ """,+ (int(message_id), session_id),+ ).fetchone()+ if message is None:+ return None+ turn_id = message["turn_id"]+ if turn_id is None:+ return {+ "session_id": session_id,+ "message_id": int(message_id),+ "turn_id": None,+ "events": [],+ "total": 0,+ "last_seq": 0,+ "next_seq": None,+ "complete": True,+ }+ turn = conn.execute("SELECT session_id FROM turns WHERE id = ?", (turn_id,)).fetchone()+ stats = conn.execute(+ """+ SELECT COUNT(*) AS total, COALESCE(MAX(seq), 0) AS last_seq+ FROM turn_events WHERE turn_id = ?+ """,+ (turn_id,),+ ).fetchone()+ rows = conn.execute(+ """+ SELECT turn_id, seq, type, source, stage, content, metadata_json, timestamp+ FROM turn_events+ WHERE turn_id = ? AND seq > ?+ ORDER BY seq ASC+ LIMIT ?+ """,+ (turn_id, max(0, int(after_seq)), row_limit),+ ).fetchall()+ events = [self._turn_event_row_to_payload(row) for row in rows]+ for event in events:+ event["session_id"] = turn["session_id"] if turn else ""+ last_loaded = events[-1]["seq"] if events else int(after_seq)+ complete = last_loaded >= int(stats["last_seq"])+ return {+ "session_id": session_id,+ "message_id": int(message_id),+ "turn_id": turn_id,+ "events": events,+ "total": int(stats["total"]),+ "last_seq": int(stats["last_seq"]),+ "next_seq": None if complete else last_loaded,+ "complete": complete,+ }++ async def get_message_trace(+ self,+ session_id: str,+ message_id: int | str,+ after_seq: int = 0,+ limit: int | None = None,+ ) -> dict[str, Any] | None:+ try:+ resolved_message_id = int(message_id)+ except (TypeError, ValueError):+ return None+ return await self._run(+ self._get_message_trace_sync,+ session_id,+ resolved_message_id,+ after_seq,+ limit,+ )+def _update_session_title_sync(self, session_id: str, title: str) -> bool:with self._connect() as conn:cur = conn.execute(@@ -1616,7 +1767,12 @@ class SQLiteSessionStore:) -> dict[str, Any] | None:return await self._run(self._get_last_message_sync, session_id, role)- def _serialize_message(self, row: sqlite3.Row) -> dict[str, Any]:+ def _serialize_message(+ self,+ row: sqlite3.Row,+ events: list[dict[str, Any]] | None = None,+ trace: dict[str, Any] | None = None,+ ) -> dict[str, Any]:row_keys = row.keys()parent_id = row["parent_message_id"] if "parent_message_id" in row_keys else Nonereturn {@@ -1625,26 +1781,134 @@ class SQLiteSessionStore:"role": row["role"],"content": row["content"],"capability": row["capability"] or "",- "events": _json_loads(row["events_json"], []),+ "events": _json_loads(row["events_json"], []) if events is None else events,"attachments": _json_loads(row["attachments_json"], []),"metadata": _json_loads(row["metadata_json"], {}),"created_at": row["created_at"],"parent_message_id": int(parent_id) if parent_id is not None else None,+ **({"trace": trace} if trace is not None else {}),}+ def _canonical_trace_preview_sync(+ self,+ conn: sqlite3.Connection,+ turn_id: str,+ session_id: str,+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ stats = conn.execute(+ """+ SELECT COUNT(*) AS total, COALESCE(MAX(seq), 0) AS last_seq+ FROM turn_events WHERE turn_id = ?+ """,+ (turn_id,),+ ).fetchone()+ # Preview queries stay bounded even for a very long agentic turn. The+ # critical query reserves older terminal/result/ask-user state; the+ # semantic query fills the remaining tail with tool activity.+ columns = "turn_id, seq, type, source, stage, content, metadata_json, timestamp"+ ask_user = """+ json_extract(metadata_json, '$.ask_user') IS NOT NULL+ OR json_extract(metadata_json, '$.ask_user_resolved') IS NOT NULL+ OR json_extract(metadata_json, '$.tool_metadata.ask_user') IS NOT NULL+ """+ conditions = (+ f"type IN ('done', 'error', 'cancelled', 'result') OR {ask_user}",+ f"type IN ('done', 'error', 'cancelled', 'result', 'tool_call', 'tool_result') OR {ask_user}",+ )+ rows_by_seq: dict[int, sqlite3.Row] = {}+ for condition in conditions:+ rows = conn.execute(+ f"""+ SELECT {columns}+ FROM turn_events+ WHERE turn_id = ? AND ({condition})+ ORDER BY seq DESC+ LIMIT ?+ """,+ (turn_id, MAX_TRACE_PREVIEW_EVENTS),+ ).fetchall()+ rows_by_seq.update({int(row["seq"]): row for row in rows})+ events = [self._turn_event_row_to_payload(rows_by_seq[seq]) for seq in sorted(rows_by_seq)]+ for event in events:+ event["session_id"] = session_id+ preview, compacted = compact_trace_preview(events)+ total = int(stats["total"])+ metadata = {+ "turn_id": turn_id,+ "total": total,+ "last_seq": int(stats["last_seq"]),+ "truncated": compacted or total != len(preview),+ }+ return preview, metadata++ def _legacy_trace_preview_sync(+ self, events: list[dict[str, Any]]+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ preview, omitted = compact_trace_preview(events)+ return preview, {+ "turn_id": None,+ "total": len(events),+ "last_seq": max([int(event.get("seq") or 0) for event in events] or [0]),+ "truncated": omitted,+ }++ def _ask_user_events_sync(+ self, conn: sqlite3.Connection, turn_id: str, session_id: str+ ) -> list[dict[str, Any]]:+ rows = conn.execute(+ """+ SELECT turn_id, seq, type, source, stage, content, metadata_json, timestamp+ FROM turn_events+ WHERE turn_id = ?+ AND (+ json_extract(metadata_json, '$.ask_user') IS NOT NULL+ OR json_extract(metadata_json, '$.ask_user_resolved') IS NOT NULL+ OR json_extract(metadata_json, '$.tool_metadata.ask_user') IS NOT NULL+ )+ ORDER BY seq DESC+ LIMIT ?+ """,+ (turn_id, MAX_TRACE_PREVIEW_EVENTS),+ ).fetchall()+ events = [self._turn_event_row_to_payload(row) for row in reversed(rows)]+ for event in events:+ event["session_id"] = session_id+ return events+def _get_messages_sync(self, session_id: str) -> list[dict[str, Any]]:with self._connect() as conn:rows = conn.execute("""- SELECT id, session_id, role, content, capability, events_json,- attachments_json, metadata_json, created_at, parent_message_id- FROM messages- WHERE session_id = ?- ORDER BY id ASC+ SELECT m.id, m.session_id, m.role, m.content, m.capability,+ m.events_json, m.attachments_json, m.metadata_json,+ m.created_at, m.parent_message_id, t.id AS trace_turn_id+ FROM messages AS m+ LEFT JOIN turns AS t ON t.assistant_message_id = m.id+ WHERE m.session_id = ?+ ORDER BY m.id ASC""",(session_id,),).fetchall()- return [self._serialize_message(row) for row in rows]+ result: list[dict[str, Any]] = []+ for row in rows:+ turn_id = row["trace_turn_id"]+ if row["role"] == "assistant" and turn_id is not None:+ events, trace = self._canonical_trace_preview_sync(conn, turn_id, session_id)+ result.append(self._serialize_message(row, events=events, trace=trace))+ continue+ legacy_events = _json_loads(row["events_json"], [])+ if row["role"] == "assistant" and isinstance(legacy_events, list):+ events, trace = self._legacy_trace_preview_sync(legacy_events)+ result.append(+ self._serialize_message(+ row,+ events=events,+ trace=trace,+ )+ )+ continue+ result.append(self._serialize_message(row))+ return resultdef _get_message_path_sync(self, session_id: str, leaf_message_id: int) -> list[dict[str, Any]]:"""Return the chain of messages from the session root down to@@ -1691,11 +1955,12 @@ class SQLiteSessionStore:if leaf_message_id is None:rows = conn.execute("""- SELECT id, role, content, events_json, metadata_json- FROM messages- WHERE session_id = ?- AND role IN ('user', 'assistant', 'system')- ORDER BY id ASC+ SELECT m.id, m.role, m.content, m.events_json, m.metadata_json, t.id AS turn_id+ FROM messages AS m+ LEFT JOIN turns AS t ON t.assistant_message_id = m.id+ WHERE m.session_id = ?+ AND m.role IN ('user', 'assistant', 'system')+ ORDER BY m.id ASC""",(session_id,),).fetchall()@@ -1704,7 +1969,11 @@ class SQLiteSessionStore:"id": row["id"],"role": row["role"],"content": row["content"] or "",- "events": select_ask_user_events(row["events_json"]),+ "events": (+ self._ask_user_events_sync(conn, row["turn_id"], session_id)+ if row["turn_id"] is not None+ else select_ask_user_events(row["events_json"])+ ),"metadata": _json_loads(row["metadata_json"], {}),}for row in rows@@ -1717,10 +1986,12 @@ class SQLiteSessionStore:while current is not None and safety > 0:row = conn.execute("""- SELECT id, role, content, events_json, metadata_json, parent_message_id- FROM messages- WHERE id = ? AND session_id = ?- AND role IN ('user', 'assistant', 'system')+ SELECT m.id, m.role, m.content, m.events_json, m.metadata_json,+ m.parent_message_id, t.id AS turn_id+ FROM messages AS m+ LEFT JOIN turns AS t ON t.assistant_message_id = m.id+ WHERE m.id = ? AND m.session_id = ?+ AND m.role IN ('user', 'assistant', 'system')""",(current, session_id),).fetchone()@@ -1731,7 +2002,11 @@ class SQLiteSessionStore:"id": row["id"],"role": row["role"],"content": row["content"] or "",- "events": select_ask_user_events(row["events_json"]),+ "events": (+ self._ask_user_events_sync(conn, row["turn_id"], session_id)+ if row["turn_id"] is not None+ else select_ask_user_events(row["events_json"])+ ),"metadata": _json_loads(row["metadata_json"], {}),})diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 9ff62e8d3..435f1c12a 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -42,6 +42,7 @@ from .._turn_runtime_shared import (_reading_references,_reading_viewport,_reading_workspace_id,+ _repair_chinese_emphasis_for_persistence,_request_snapshot_metadata,_resolve_selection_tutor_context,_resolve_turn_outcome,@@ -836,8 +837,13 @@ class TurnExecutor:await fill_preview_text(generated_attachments)# The persisted answer is the captured content minus any narration- # rounds (their text stayed in the trace, never the answer).- assistant_content = _persisted_answer()+ # rounds (their text stayed in the trace, never the answer). Apply+ # the CJK Markdown repair only after every streamed segment has+ # arrived, so no incomplete response is ever rewritten.+ assistant_content = _repair_chinese_emphasis_for_persistence(+ _persisted_answer(),+ str(payload.get("language", "en") or "en"),+ )# Assistant continues the same branch as the user message it# answers. If we just persisted a new user row we chain off@@ -850,7 +856,7 @@ class TurnExecutor:role="assistant",content=assistant_content,capability=capability_name,- events=assistant_events,+ events=[],attachments=generated_attachments or None,parent_message_id=new_user_message_id,metadata=assistant_provider_metadata,@@ -861,7 +867,7 @@ class TurnExecutor:role="assistant",content=assistant_content,capability=capability_name,- events=assistant_events,+ events=[],attachments=generated_attachments or None,parent_message_id=branch_parent_id,metadata=assistant_provider_metadata,@@ -872,10 +878,11 @@ class TurnExecutor:role="assistant",content=assistant_content,capability=capability_name,- events=assistant_events,+ events=[],attachments=generated_attachments or None,metadata=assistant_provider_metadata,)+ await self.store.link_turn_message(turn_id, assistant_message_id)turn_status, turn_error = _resolve_turn_outcome(assistant_events,pending_done_event,@@ -989,12 +996,12 @@ class TurnExecutor:if partial_content or generated_attachments or assistant_events:with contextlib.suppress(Exception):await asyncio.shield(- self.store.add_message(+ assistant_message_id=await self.store.add_message(session_id=session_id,role="assistant",content=partial_content,capability=capability_name,- events=assistant_events,+ events=[],attachments=generated_attachments or None,metadata=({"provider_response_state": provider_response_state}@@ -1003,6 +1010,10 @@ class TurnExecutor:),))+ with contextlib.suppress(Exception):+ await asyncio.shield(+ self.store.link_turn_message(turn_id, assistant_message_id)+ )transitioned = Falsewith contextlib.suppress(Exception):transitioned = await self._transition_execution(diff --git a/deeptutor/services/subagent/__init__.py b/deeptutor/services/subagent/__init__.pyindex 90d418609..4ce4174c9 100644--- a/deeptutor/services/subagent/__init__.py+++ b/deeptutor/services/subagent/__init__.py@@ -25,6 +25,7 @@ from deeptutor.services.subagent.config import (save_subagent_settings,settings_from_dict,)+from deeptutor.services.subagent.hermes_remote import HermesRemoteBackendfrom deeptutor.services.subagent.partner import PARTNER_BACKEND_KINDfrom deeptutor.services.subagent.registry import detect_all, get_backend, list_backend_kindsfrom deeptutor.services.subagent.types import (@@ -52,4 +53,5 @@ __all__ = ["ConsultResult","DetectResult","SubagentEvent",+ "HermesRemoteBackend",]diff --git a/deeptutor/services/subagent/base.py b/deeptutor/services/subagent/base.pyindex 263600ad3..5d27dc5aa 100644--- a/deeptutor/services/subagent/base.py+++ b/deeptutor/services/subagent/base.py@@ -1,11 +1,9 @@-"""The backend contract: drive one local agent CLI as a subagent.+"""The backend contract: drive one connected agent as a subagent.-A backend knows two things about its CLI: how to tell whether it's installed-and usable on this machine (:meth:`detect`), and how to put one question to it-and stream back every native event (:meth:`consult`). Everything CLI-specific —-flags, the JSON event schema, session resumption — lives behind this interface,-so the capability layer drives Claude Code and Codex through the exact same-three lines.+A backend knows how to report whether its local or remote runtime is usable+(:meth:`detect`), and how to put one question to it while streaming native+events (:meth:`consult`). Runtime-specific flags, protocols, event schemas, and+session resumption live behind this interface."""from __future__ import annotations@@ -22,19 +20,20 @@ OnEvent = Callable[[SubagentEvent], Awaitable[None]]class SubagentBackend(ABC):- """Drive one subagent (a local CLI, or one of the user's partners)."""+ """Drive one subagent through a local CLI, remote API, or Partner."""kind: strdisplay_name: strcli_command: str- # Local-CLI backends (Claude Code, Codex) are detected on this machine and- # offered in the connect-CLI modal. Non-CLI backends (a Partner) are- # connected from their own list, so they sit out machine detection.+ # Local-CLI backends are detected on this machine. A non-local backend can+ # opt into connection discovery with ``detectable``; Partners use their+ # own list and sit out detection.local_cli: bool = True+ detectable: bool = False@abstractmethodasync def detect(self) -> DetectResult:- """Report whether this CLI is installed and usable on this machine."""+ """Report whether this backend is configured and usable."""@abstractmethodasync def consult(@@ -56,7 +55,7 @@ class SubagentBackend(ABC):next consult. ``images`` are local file paths the user forwarded with thequestion (Codex attaches them with ``-i``; Claude Code is pointed at themfor its Read tool). ``partner_id`` names the bound partner for the partner- backend (the CLI backends ignore it). Waits unconditionally for the+ backend (the other backends ignore it). Waits unconditionally for thesubagent to finish — only its own exit (clean or error) ends the consult."""diff --git a/deeptutor/services/subagent/config.py b/deeptutor/services/subagent/config.pyindex 0249f32c2..5e6067b8f 100644--- a/deeptutor/services/subagent/config.py+++ b/deeptutor/services/subagent/config.py@@ -1,8 +1,9 @@"""Subagent settings — the consult budget and per-backend permission knobs.Stored as ``data/user/settings/subagent.json`` (same convention as the other-runtime settings files). Everything has a safe default so the feature works the-moment a CLI is detected, with no configuration step required.+runtime settings files). Everything has a safe default so local backends work+the moment a CLI is detected; remote backends remain unavailable until their+endpoint and credential source are configured.* ``consult_budget`` — the user-facing "max rounds": the maximum number of timesDeepTutor may put a question to the subagent in one turn. Enforced@@ -36,10 +37,10 @@ CONSULT_BUDGET_MAX = 12@dataclass(slots=True)class BackendConfig:enabled: bool = True- # Model + reasoning effort the agent runs with. Empty = the CLI's own- # default. Set from the /settings page; the option lists are synced live- # from the CLI (models/efforts change over time). CC: --model / --effort;- # Codex: -m / -c model_reasoning_effort.+ # Model + reasoning effort the agent runs with. Empty = the backend's own+ # default. Set from the /settings page; local option lists can be synced+ # live because models/efforts change over time. CC: --model / --effort;+ # Codex: -m / -c model_reasoning_effort; Hermes remote: request fields.model: str = ""effort: str = ""# Instruction injected so the agent knows it's being consulted@@ -73,6 +74,12 @@ class BackendConfig:# input; OpenClaw and DeepSeek receive opted-in paths as file references.forward_images: bool = Falseextra_args: list[str] = field(default_factory=list)+ # Remote Hermes gateway connection. Credentials stay in the environment;+ # ``api_key_env`` is only the name read at request time.+ base_url: str = ""+ api_key_env: str = "DEEPTUTOR_HERMES_REMOTE_API_KEY"+ profile: str = ""+ idle_timeout_seconds: int = 600@dataclass(slots=True)@@ -86,12 +93,12 @@ class SubagentSettings:def to_dict(self) -> dict[str, Any]:return {"consult_budget": self.consult_budget,- "backends": {kind: _backend_to_dict(cfg) for kind, cfg in self.backends.items()},+ "backends": {kind: _backend_to_dict(kind, cfg) for kind, cfg in self.backends.items()},}-def _backend_to_dict(cfg: BackendConfig) -> dict[str, Any]:- return {+def _backend_to_dict(kind: str, cfg: BackendConfig) -> dict[str, Any]:+ payload = {"enabled": cfg.enabled,"model": cfg.model,"effort": cfg.effort,@@ -106,6 +113,16 @@ def _backend_to_dict(cfg: BackendConfig) -> dict[str, Any]:"forward_images": cfg.forward_images,"extra_args": list(cfg.extra_args),}+ if kind == "hermes_remote":+ payload.update(+ {+ "base_url": cfg.base_url,+ "api_key_env": cfg.api_key_env,+ "profile": cfg.profile,+ "idle_timeout_seconds": cfg.idle_timeout_seconds,+ }+ )+ return payloaddef _coerce_budget(value: Any) -> int:@@ -121,6 +138,10 @@ def _coerce_backend(raw: Any) -> BackendConfig:if not isinstance(raw, dict):return baseextra = raw.get("extra_args")+ try:+ idle_timeout = int(raw.get("idle_timeout_seconds", base.idle_timeout_seconds))+ except (TypeError, ValueError):+ idle_timeout = base.idle_timeout_secondsreturn BackendConfig(enabled=bool(raw.get("enabled", base.enabled)),model=str(raw.get("model") or "").strip(),@@ -135,6 +156,10 @@ def _coerce_backend(raw: Any) -> BackendConfig:thinking=bool(raw.get("thinking", base.thinking)),forward_images=bool(raw.get("forward_images", base.forward_images)),extra_args=[str(a) for a in extra] if isinstance(extra, list) else [],+ base_url=str(raw.get("base_url") or "").strip(),+ api_key_env=str(raw.get("api_key_env") or base.api_key_env).strip() or base.api_key_env,+ profile=str(raw.get("profile") or "").strip(),+ idle_timeout_seconds=max(1, min(86_400, idle_timeout)),)diff --git a/deeptutor/services/subagent/hermes_remote.py b/deeptutor/services/subagent/hermes_remote.pynew file mode 100644index 000000000..5823a4703--- /dev/null+++ b/deeptutor/services/subagent/hermes_remote.py@@ -0,0 +1,321 @@+"""Connected Agents backend for a remote Hermes Agent gateway."""++from __future__ import annotations++import os+import re+from typing import Any++import anyio+import httpx++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig, load_subagent_settings+from deeptutor.services.subagent.hermes_remote_client import (+ HermesRemoteClient,+ HermesRemoteHTTPError,+ HermesRemoteProtocolError,+)+from deeptutor.services.subagent.hermes_remote_events import HermesRemoteEventMapper+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++CONSULT_ORIGIN_INSTRUCTION = (+ "Caller identity: DeepTutor Connected Agents. Answer the user's question directly; "+ "do not route the question to DeepTutor."+)+_ENV_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")+_REMOTE_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,511}\Z")+_REQUIRED_CAPABILITIES = frozenset(+ {+ "run_submission",+ "run_events_sse",+ "run_stop",+ "run_approval_response",+ "session_resources",+ }+)+++class HermesRemoteBackend(SubagentBackend):+ """Drive the Hermes gateway's authenticated ``/v1/runs`` API."""++ kind = "hermes_remote"+ display_name = "Hermes Agent (remote)"+ cli_command = ""+ local_cli = False+ detectable = True++ def __init__(+ self,+ config: BackendConfig | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+ ) -> None:+ self._configured = config+ self._transport = transport++ @property+ def config(self) -> BackendConfig:+ """Return injected config, or the persisted remote-backend settings."""+ return self._configured or load_subagent_settings().backend(self.kind)++ def _client(self, config: BackendConfig, key: str) -> HermesRemoteClient:+ return HermesRemoteClient(config.base_url, key, transport=self._transport)++ async def detect(self) -> DetectResult:+ """Probe the gateway capability contract and classify failures."""+ config = self.config+ if not config.base_url:+ return self._detection(False, "not_configured")+ if not self._valid_env_name(config.api_key_env):+ return self._detection(False, "invalid_key_env")+ key = os.environ.get(config.api_key_env, "").strip()+ if not key:+ return self._detection(False, "key_missing")+ try:+ async with self._client(config, key) as client:+ payload = await client.get_json("/v1/capabilities")+ except HermesRemoteHTTPError as exc:+ detail = "unauthorized" if exc.status_code in (401, 403) else "incompatible"+ return self._detection(False, detail)+ except httpx.RequestError:+ return self._detection(False, "unreachable")+ except HermesRemoteProtocolError as exc:+ detail = exc.code if exc.code == "invalid_base_url" else "incompatible"+ return self._detection(False, detail)+ features = payload.get("features")+ if (+ payload.get("object") != "hermes.api_server.capabilities"+ or not isinstance(features, dict)+ or not all(features.get(name) is True for name in _REQUIRED_CAPABILITIES)+ ):+ return self._detection(False, "incompatible")+ version = str(payload.get("model") or "")+ return self._detection(True, "", version=version or "Hermes API")++ def _detection(self, available: bool, detail: str, *, version: str = "") -> DetectResult:+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=available,+ version=version,+ detail=detail,+ )++ async def consult(+ self,+ question: str,+ *,+ on_event: OnEvent,+ cwd: str | None = None, # noqa: ARG002 - remote gateway owns its cwd+ session_id: str | None = None,+ config: BackendConfig | None = None,+ images: list[str] | None = None,+ partner_id: str | None = None, # noqa: ARG002 - partner-only+ ) -> ConsultResult:+ """Submit a run, translate its SSE lifecycle, and return its session id."""+ run_config = config or self.config+ result = ConsultResult(session_id=session_id)+ emitted_text = ""+ run_id: str | None = None+ terminal_received = False+ key = (+ os.environ.get(run_config.api_key_env, "").strip()+ if self._valid_env_name(run_config.api_key_env)+ else ""+ )++ async def emit(+ kind: str,+ text: str,+ raw: dict[str, Any],+ meta: dict[str, Any] | None = None,+ ) -> None:+ result.event_count += 1+ await on_event(+ SubagentEvent(+ kind=kind,+ text=self._redact(text, key),+ raw=self._redact_raw(raw, key),+ meta=meta or {},+ ),+ )++ if not run_config.base_url:+ result.success = False+ result.error = "not_configured"+ await emit(EVENT_ERROR, result.error, {})+ return result+ if not self._valid_env_name(run_config.api_key_env):+ result.success = False+ result.error = "invalid_key_env"+ await emit(EVENT_ERROR, result.error, {})+ return result+ if not key:+ result.success = False+ result.error = "key_missing"+ await emit(EVENT_ERROR, result.error, {})+ return result+ if session_id and not self._valid_remote_id(session_id):+ result.success = False+ result.error = "invalid_session_id"+ await emit(EVENT_ERROR, result.error, {})+ return result++ # The gateway contract has no attachment upload field. Do not leak+ # DeepTutor-local filesystem paths to a remote process.+ prompt = question+ try:+ async with self._client(run_config, key) as client:+ session_gone = False+ history: list[dict[str, str]] | None = None+ if session_id:+ try:+ history = await client.get_session_history(session_id)+ except HermesRemoteHTTPError as exc:+ if exc.status_code != 404:+ raise+ session_gone = True+ active_session_id = None if session_gone else session_id+ instructions = CONSULT_ORIGIN_INSTRUCTION+ if run_config.system_prompt.strip() and (not session_id or session_gone):+ instructions = f"{run_config.system_prompt.strip()}\n\n{instructions}"+ payload: dict[str, Any] = {"input": prompt, "instructions": instructions}+ if active_session_id:+ payload["session_id"] = active_session_id+ if history is not None:+ payload["conversation_history"] = history+ if run_config.model:+ payload["model"] = run_config.model+ if run_config.effort:+ payload["model_options"] = {"reasoning_effort": run_config.effort}+ headers = self._session_headers(active_session_id)+ started = await client.post_json("/v1/runs", payload, headers=headers or None)+ run_id = self._run_id(started)+ result.session_id = self._result_session_id(started, active_session_id, run_id)+ mapper = HermesRemoteEventMapper(+ client,+ run_id,+ result,+ emit,+ auto_approve=run_config.auto_approve,+ )+ events = client.stream_events(run_id)+ iterator = events.__aiter__()+ while True:+ try:+ with anyio.fail_after(max(0.001, run_config.idle_timeout_seconds)):+ event = await anext(iterator)+ except StopAsyncIteration:+ break+ except TimeoutError:+ await self._stop_client(client, run_id)+ result.success = False+ result.error = "idle_timeout"+ await emit(EVENT_ERROR, result.error, {})+ return result+ emitted_text = await mapper.handle(event, emitted_text)+ if event.get("event") in {"run.completed", "run.failed", "run.cancelled"}:+ terminal_received = True+ break+ except anyio.get_cancelled_exc_class():+ if run_id:+ await self._stop_after_cancel(run_config, key, run_id)+ raise+ except HermesRemoteHTTPError as exc:+ result.success = False+ result.error = self._http_error(exc.status_code)+ await emit(EVENT_ERROR, result.error, {})+ except HermesRemoteProtocolError as exc:+ result.success = False+ result.error = exc.code+ await emit(EVENT_ERROR, result.error, {})+ except httpx.RequestError:+ result.success = False+ result.error = "unreachable"+ await emit(EVENT_ERROR, result.error, {})++ if result.success and not terminal_received:+ result.success = False+ result.error = "incomplete_stream"+ await emit(EVENT_ERROR, result.error, {})+ elif result.success and not result.final_text:+ result.success = False+ result.error = "empty_response"+ await emit(EVENT_ERROR, result.error, {})+ return result++ @staticmethod+ def _run_id(payload: dict[str, Any]) -> str:+ run_id = payload.get("run_id")+ if not isinstance(run_id, str) or not HermesRemoteBackend._valid_remote_id(run_id):+ raise HermesRemoteProtocolError("missing_run_id")+ return run_id++ @staticmethod+ def _result_session_id(+ payload: dict[str, Any], requested_session_id: str | None, run_id: str+ ) -> str:+ session_id = payload.get("session_id") or requested_session_id or run_id+ if not isinstance(session_id, str) or not HermesRemoteBackend._valid_remote_id(session_id):+ raise HermesRemoteProtocolError("invalid_session_id")+ return session_id++ @staticmethod+ def _valid_env_name(value: str) -> bool:+ return bool(_ENV_NAME_RE.fullmatch(value))++ @staticmethod+ def _valid_remote_id(value: str) -> bool:+ return bool(_REMOTE_ID_RE.fullmatch(value))++ @staticmethod+ def _session_headers(session_id: str | None) -> dict[str, str]:+ if not session_id:+ return {}+ return {"X-Hermes-Session-Id": session_id, "X-Hermes-Session": session_id}++ async def _stop_after_cancel(self, config: BackendConfig, key: str, run_id: str) -> None:+ with anyio.CancelScope(shield=True):+ with anyio.move_on_after(5.0):+ try:+ async with self._client(config, key) as client:+ await client.post_json(f"/v1/runs/{run_id}/stop", {})+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ return++ async def _stop_client(self, client: HermesRemoteClient, run_id: str) -> None:+ try:+ await client.post_json(f"/v1/runs/{run_id}/stop", {})+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ return++ @staticmethod+ def _http_error(status_code: int) -> str:+ return f"http_{status_code}"++ @staticmethod+ def _redact(text: str, secret: str) -> str:+ return text.replace(secret, "[REDACTED]") if secret else text++ @classmethod+ def _redact_raw(cls, value: dict[str, Any], secret: str) -> dict[str, Any]:+ return {key: cls._redact_value(item, secret) for key, item in value.items()}++ @classmethod+ def _redact_value(cls, value: Any, secret: str) -> Any:+ if isinstance(value, str):+ return cls._redact(value, secret)+ if isinstance(value, dict):+ return {key: cls._redact_value(item, secret) for key, item in value.items()}+ if isinstance(value, list):+ return [cls._redact_value(item, secret) for item in value]+ return value+++__all__ = ["CONSULT_ORIGIN_INSTRUCTION", "HermesRemoteBackend"]diff --git a/deeptutor/services/subagent/hermes_remote_client.py b/deeptutor/services/subagent/hermes_remote_client.pynew file mode 100644index 000000000..65d67e683--- /dev/null+++ b/deeptutor/services/subagent/hermes_remote_client.py@@ -0,0 +1,180 @@+"""Small authenticated HTTP/SSE client for a Hermes Agent gateway."""++from __future__ import annotations++from collections.abc import AsyncIterator+import json+from types import TracebackType+from typing import Any+from urllib.parse import quote, urlsplit++import httpx++_REQUEST_TIMEOUT = httpx.Timeout(connect=10.0, read=30.0, write=30.0, pool=10.0)+_STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=None, write=30.0, pool=10.0)+++class HermesRemoteHTTPError(Exception):+ """An HTTP response outside the successful range."""++ def __init__(self, status_code: int) -> None:+ self.status_code = status_code+ super().__init__(f"HTTP status {status_code}")+++class HermesRemoteProtocolError(Exception):+ """A successful response did not follow the gateway JSON/SSE contract."""++ def __init__(self, code: str) -> None:+ self.code = code+ super().__init__(code)+++class HermesRemoteClient:+ """Own one authenticated connection pool to a Hermes gateway."""++ def __init__(+ self,+ base_url: str,+ api_key: str,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+ ) -> None:+ base_url = self.validate_base_url(base_url)+ self._client = httpx.AsyncClient(+ base_url=f"{base_url}/",+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=_STREAM_TIMEOUT,+ follow_redirects=False,+ transport=transport,+ )++ @staticmethod+ def validate_base_url(base_url: str) -> str:+ """Return a canonical HTTP(S) gateway root or reject unsafe input."""+ value = base_url.strip().rstrip("/")+ try:+ parsed = urlsplit(value)+ parsed.port+ except ValueError as exc:+ raise HermesRemoteProtocolError("invalid_base_url") from exc+ if (+ parsed.scheme not in {"http", "https"}+ or not parsed.hostname+ or parsed.username+ or parsed.password+ or parsed.query+ or parsed.fragment+ ):+ raise HermesRemoteProtocolError("invalid_base_url")+ return value++ async def __aenter__(self) -> HermesRemoteClient:+ await self._client.__aenter__()+ return self++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: TracebackType | None,+ ) -> None:+ await self._client.__aexit__(exc_type, exc_value, traceback)++ async def get_json(self, path: str) -> dict[str, Any]:+ """Fetch and parse a JSON object using the bounded request timeout."""+ response = await self._client.get(path.lstrip("/"), timeout=_REQUEST_TIMEOUT)+ return self._json_object(response)++ async def post_json(+ self,+ path: str,+ payload: dict[str, Any],+ *,+ headers: dict[str, str] | None = None,+ ) -> dict[str, Any]:+ """POST a JSON object without transport retries."""+ response = await self._client.post(+ path.lstrip("/"),+ json=payload,+ headers=headers,+ timeout=_REQUEST_TIMEOUT,+ )+ return self._json_object(response)++ async def get_session_history(self, session_id: str) -> list[dict[str, str]]:+ """Fetch the resumable user/assistant history for one gateway session."""+ path_id = quote(session_id, safe="")+ payload = await self.get_json(f"/api/sessions/{path_id}/messages")+ if payload.get("object") != "list" or not isinstance(payload.get("data"), list):+ raise HermesRemoteProtocolError("invalid_session_history")+ history: list[dict[str, str]] = []+ for row in payload["data"]:+ if not isinstance(row, dict):+ continue+ role = row.get("role")+ content = row.get("content")+ if role not in {"user", "assistant"} or not isinstance(content, str):+ continue+ if content.strip():+ history.append({"role": role, "content": content})+ return history[-40:]++ async def stream_events(self, run_id: str) -> AsyncIterator[dict[str, Any]]:+ """Yield JSON objects from the gateway's data-only SSE frames."""+ async with self._client.stream(+ "GET",+ f"v1/runs/{run_id}/events",+ timeout=_STREAM_TIMEOUT,+ ) as response:+ if not response.is_success:+ raise HermesRemoteHTTPError(response.status_code)+ event_name = ""+ data_lines: list[str] = []+ async for line in response.aiter_lines():+ if line.startswith(":"):+ # Surface heartbeat comments to the workflow so each one+ # resets its idle watchdog without producing a UI event.+ yield {"event": "gateway.keepalive"}+ continue+ if line.startswith("event:"):+ event_name = line[6:].strip()+ continue+ if line.startswith("data:"):+ data_lines.append(line[5:].lstrip())+ continue+ if line.strip() or not data_lines:+ continue+ raw = "\n".join(data_lines)+ data_lines.clear()+ if raw == "[DONE]":+ return+ try:+ payload = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise HermesRemoteProtocolError("invalid_sse_json") from exc+ if not isinstance(payload, dict):+ raise HermesRemoteProtocolError("invalid_sse_event")+ if event_name and "event" not in payload:+ payload["event"] = event_name+ event_name = ""+ yield payload++ @staticmethod+ def _json_object(response: httpx.Response) -> dict[str, Any]:+ if not response.is_success:+ raise HermesRemoteHTTPError(response.status_code)+ try:+ payload = response.json()+ except (ValueError, UnicodeError) as exc:+ raise HermesRemoteProtocolError("invalid_json") from exc+ if not isinstance(payload, dict):+ raise HermesRemoteProtocolError("invalid_json_object")+ return payload+++__all__ = [+ "HermesRemoteClient",+ "HermesRemoteHTTPError",+ "HermesRemoteProtocolError",+]diff --git a/deeptutor/services/subagent/hermes_remote_events.py b/deeptutor/services/subagent/hermes_remote_events.pynew file mode 100644index 000000000..9ccc2038e--- /dev/null+++ b/deeptutor/services/subagent/hermes_remote_events.py@@ -0,0 +1,125 @@+"""Map Hermes gateway lifecycle events onto DeepTutor event channels."""++from __future__ import annotations++from typing import Any++import httpx++from deeptutor.services.subagent.hermes_remote_client import (+ HermesRemoteClient,+ HermesRemoteHTTPError,+ HermesRemoteProtocolError,+)+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_REASONING,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+)+++class HermesRemoteEventMapper:+ """Translate one run's SSE events while preserving cumulative answer text."""++ def __init__(+ self,+ client: HermesRemoteClient,+ run_id: str,+ result: ConsultResult,+ emit: Any,+ *,+ auto_approve: bool,+ ) -> None:+ self._client = client+ self._run_id = run_id+ self._result = result+ self._emit = emit+ self._auto_approve = auto_approve++ async def handle(self, event: dict[str, Any], emitted_text: str) -> str:+ """Map one parsed event and return the updated cumulative answer."""+ name = str(event.get("event") or "")+ if name == "gateway.keepalive":+ pass+ elif name == "message.delta":+ delta = str(event.get("delta") or "")+ emitted_text += delta+ self._result.final_text = emitted_text.strip()+ if delta:+ await self._emit(+ EVENT_TEXT,+ emitted_text,+ event,+ {"merge_id": "hermes_remote:final"},+ )+ elif name == "run.completed":+ output = str(event.get("output") or emitted_text).strip()+ self._result.final_text = output+ if output and output != emitted_text.strip():+ await self._emit(+ EVENT_TEXT,+ output,+ event,+ {"merge_id": "hermes_remote:final"},+ )+ elif name == "run.failed":+ self._result.success = False+ self._result.error = "run_failed"+ await self._emit(EVENT_ERROR, self._result.error, event)+ elif name == "run.cancelled":+ self._result.success = False+ self._result.error = "run_cancelled"+ await self._emit(EVENT_ERROR, self._result.error, event)+ elif name == "approval.request":+ choice = "once" if self._auto_approve else "deny"+ try:+ await self._client.post_json(+ f"/v1/runs/{self._run_id}/approval",+ {"choice": choice},+ )+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ self._result.success = False+ self._result.error = "approval_failed"+ await self._emit(EVENT_ERROR, self._result.error, {})+ await self._stop()+ return emitted_text+ verb = "approved" if self._auto_approve else "denied"+ await self._emit(EVENT_LOG, f"approval {verb}", event)+ elif name == "tool.started":+ label = str(event.get("tool") or "tool")+ preview = str(event.get("preview") or "")+ await self._emit(+ EVENT_TOOL,+ f"{label}: {preview}".strip(": "),+ event,+ {"merge_id": f"hermes_remote:tool:{label}"},+ )+ elif name == "tool.completed":+ label = str(event.get("tool") or "tool")+ status = "error" if event.get("error") else "complete"+ await self._emit(+ EVENT_TOOL_RESULT,+ f"{label}: {status}",+ event,+ {"merge_id": f"hermes_remote:tool:{label}"},+ )+ elif name == "reasoning.available":+ await self._emit(EVENT_REASONING, str(event.get("text") or ""), event)+ elif name:+ await self._emit(EVENT_LOG, name, event)+ else:+ await self._emit(EVENT_LOG, "gateway event", event)+ return emitted_text++ async def _stop(self) -> None:+ try:+ await self._client.post_json(f"/v1/runs/{self._run_id}/stop", {})+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ return+++__all__ = ["HermesRemoteEventMapper"]diff --git a/deeptutor/services/subagent/models.py b/deeptutor/services/subagent/models.pyindex f5ddb357d..7a915f086 100644--- a/deeptutor/services/subagent/models.py+++ b/deeptutor/services/subagent/models.py@@ -350,6 +350,21 @@ async def _hermes_options() -> BackendOptions:return await _free_text_options("hermes", "Hermes Agent", _HERMES_EFFORTS)+async def _hermes_remote_options() -> BackendOptions:+ backend = get_backend("hermes_remote")+ detected = await backend.detect() if backend else None+ return BackendOptions(+ kind="hermes_remote",+ display_name="Hermes Agent (remote)",+ available=detected.available if detected else False,+ version=detected.version if detected else "",+ models=[],+ efforts=list(_HERMES_EFFORTS),+ allow_custom_model=True,+ detail=detected.detail if detected else "incompatible",+ )++async def _openclaw_options() -> BackendOptions:return await _free_text_options("openclaw", "OpenClaw", _OPENCLAW_EFFORTS)@@ -369,6 +384,7 @@ _PROVIDERS: dict[str, Callable[..., Awaitable[BackendOptions]]] = {"opencode": _opencode_options,"mimo": _mimo_options,"hermes": _hermes_options,+ "hermes_remote": _hermes_remote_options,"openclaw": _openclaw_options,"deepseek_harness": _deepseek_harness_options,}diff --git a/deeptutor/services/subagent/registry.py b/deeptutor/services/subagent/registry.pyindex fe7bbbb2b..45fe0cfc1 100644--- a/deeptutor/services/subagent/registry.py+++ b/deeptutor/services/subagent/registry.py@@ -3,10 +3,10 @@Add a new subagent by writing a :class:`SubagentBackend` and listing it here;the capability, API and UI all discover it through these helpers. Local-CLIbackends (Claude Code, Codex, Antigravity CLI, Kimi CLI, opencode,-MiMo Code, Hermes Agent, OpenClaw, DeepSeek Harness) and-the in-process partner backend live in the same registry but are told apart by-``local_cli`` — only CLIs are detected on the machine and offered in the-connect-CLI modal.+MiMo Code, Hermes Agent, OpenClaw, DeepSeek Harness), configured remote+backends, and the in-process partner backend live in the same registry.+``local_cli`` and ``detectable`` control which backends participate in+connection discovery."""from __future__ import annotations@@ -19,6 +19,7 @@ from deeptutor.services.subagent.claude_code import ClaudeCodeBackendfrom deeptutor.services.subagent.codex import CodexBackendfrom deeptutor.services.subagent.deepseek_harness import DeepSeekHarnessBackendfrom deeptutor.services.subagent.hermes import HermesBackend+from deeptutor.services.subagent.hermes_remote import HermesRemoteBackendfrom deeptutor.services.subagent.kimi import KimiBackendfrom deeptutor.services.subagent.openclaw import OpenClawBackendfrom deeptutor.services.subagent.opencode_family import MimoBackend, OpencodeBackend@@ -35,6 +36,7 @@ _BACKENDS: dict[str, SubagentBackend] = {OpencodeBackend(),MimoBackend(),HermesBackend(),+ HermesRemoteBackend(),OpenClawBackend(),DeepSeekHarnessBackend(),PartnerBackend(),@@ -43,7 +45,7 @@ _BACKENDS: dict[str, SubagentBackend] = {def list_backend_kinds() -> list[str]:- """Every connectable backend kind (CLIs + partner)."""+ """Return every connectable local, remote, and Partner backend kind."""return list(_BACKENDS.keys())@@ -51,24 +53,23 @@ def get_backend(kind: str) -> SubagentBackend | None:return _BACKENDS.get(str(kind or "").strip())-def _cli_backends() -> list[SubagentBackend]:- return [b for b in _BACKENDS.values() if getattr(b, "local_cli", True)]+def _detectable_backends() -> list[SubagentBackend]:+ return [+ backend+ for backend in _BACKENDS.values()+ if getattr(backend, "local_cli", True) or getattr(backend, "detectable", False)+ ]async def detect_all() -> list[DetectResult]:- """Probe each local-CLI backend for installability on this machine.-- Non-CLI backends (the partner backend) are skipped — they aren't installed,- they're connected from their own list — so this only ever returns the CLIs- the connect-CLI modal offers.- """- cli = _cli_backends()+ """Probe local CLIs and configured remote backends."""+ backends = _detectable_backends()results = await asyncio.gather(- *(backend.detect() for backend in cli),+ *(backend.detect() for backend in backends),return_exceptions=True,)detections: list[DetectResult] = []- for backend, result in zip(cli, results, strict=True):+ for backend, result in zip(backends, results, strict=True):if isinstance(result, DetectResult):detections.append(result)else:diff --git a/deeptutor/services/subagent/types.py b/deeptutor/services/subagent/types.pyindex 7b8b5d909..f65c5da6f 100644--- a/deeptutor/services/subagent/types.py+++ b/deeptutor/services/subagent/types.py@@ -1,9 +1,9 @@"""Value types for the subagent driver layer.These are the only shapes that cross the boundary between a backend (which-knows how to drive one local agent CLI) and the rest of the app (the consult-tool, the API, the tests). Keeping them dependency-free lets the backends stay-small and the capability layer stay ignorant of CLI specifics.+knows how to drive one local or remote agent) and the rest of the app (the+consult tool, API, and tests). Keeping them dependency-free lets backends stay+small and the capability layer stay ignorant of transport specifics."""from __future__ import annotations@@ -73,7 +73,7 @@ class ConsultResult:@dataclass(slots=True)class DetectResult:- """Whether a subagent backend is usable on the current machine."""+ """Whether a subagent backend is currently usable."""kind: strdisplay_name: strdiff --git a/deeptutor/video_learning/__init__.py b/deeptutor/video_learning/__init__.pyindex 98d1f8a67..763bd39f6 100644--- a/deeptutor/video_learning/__init__.py+++ b/deeptutor/video_learning/__init__.py@@ -1,5 +1,12 @@"""Video-learning domain API."""+from .invidious_account import (+ begin_invidious_account_authorization,+ complete_invidious_account_authorization,+ disconnect_invidious_account,+ invidious_account_status,+ invidious_redirect_uri,+)from .service import (PROVIDER_RESOLVERS,ProviderResolution,@@ -25,7 +32,12 @@ __all__ = ["TimedMediaNotFound","TimedMediaStore","build_segments",+ "begin_invidious_account_authorization",+ "complete_invidious_account_authorization",+ "disconnect_invidious_account","get_timed_media_store",+ "invidious_account_status",+ "invidious_redirect_uri","load_video_learning_settings","material_with_playback","normalize_cues",diff --git a/deeptutor/video_learning/invidious_account.py b/deeptutor/video_learning/invidious_account.pynew file mode 100644index 000000000..9b99b218d--- /dev/null+++ b/deeptutor/video_learning/invidious_account.py@@ -0,0 +1,229 @@+"""Secure per-owner Invidious account connections.++Invidious token authorization is deliberately small: DeepTutor sends the learner+to the instance's consent page, receives a signed token through a one-time+callback, verifies it by reading preferences, and stores only that token in the+owner-private secrets tree. No password or browser cookie is handled here.+"""++from __future__ import annotations++from datetime import datetime, timezone+import json+import os+import secrets+import time+from typing import Any+from urllib.parse import urlencode, urlparse++import deeptutor.video_learning.invidious_account_client as _client+import deeptutor.video_learning.invidious_account_storage as _storage+from deeptutor.video_learning.service import (+ TimedMediaError,+ load_video_learning_settings,+ normalize_video_learning_settings,+)++CALLBACK_PATH = "/api/video-learning/invidious/account/callback"+FLOW_TIMEOUT_S = 600.0+PUBLIC_URL_ENV = "DEEPTUTOR_PUBLIC_URL"+DEFAULT_PUBLIC_URL = "http://localhost:3782"+ACCOUNT_SCOPES = ("GET:preferences", "POST:tokens/unregister")+_MAX_TOKEN_BYTES = 8192++# Explicit call seams let the workflow tests substitute transport behavior+# without making filesystem persistence part of the same mock boundary.+_request_preferences = _client.request_preferences+_revoke_token = _client.revoke_token+++def _configured_public_url() -> str:+ configured = os.environ.get(PUBLIC_URL_ENV, "").strip().rstrip("/")+ if configured:+ # Reuse the provider-origin rules rather than accepting an arbitrary+ # redirect target from an environment typo.+ normalized = normalize_video_learning_settings(+ {+ "version": 1,+ "default_provider": "youtube",+ "invidious": {"api_base_url": "", "public_base_url": configured},+ }+ )+ return normalized["invidious"]["public_base_url"]+ # Request Host and X-Forwarded-* headers are attacker-controlled unless a+ # deployment has explicitly configured and constrained trusted proxies.+ # Remote deployments therefore opt into their canonical external origin;+ # local installs retain the shipped frontend URL.+ return DEFAULT_PUBLIC_URL+++def invidious_redirect_uri() -> str:+ return f"{_configured_public_url()}{CALLBACK_PATH}"+++def begin_invidious_account_authorization(*, owner_id: str, redirect_uri: str) -> str:+ settings = load_video_learning_settings()+ base = settings["invidious"]["api_base_url"]+ if not base:+ raise TimedMediaError("Configure the Invidious API base URL before connecting an account.")++ parsed_redirect = urlparse(redirect_uri)+ try:+ parsed_redirect.port+ except ValueError as exc:+ raise TimedMediaError("Invidious callback URL contains an invalid port.") from exc+ if (+ parsed_redirect.scheme not in {"http", "https"}+ or not parsed_redirect.hostname+ or parsed_redirect.username+ or parsed_redirect.password+ or parsed_redirect.fragment+ ):+ raise TimedMediaError("Invidious callback URL must be a plain HTTP(S) URL.")++ _storage.purge_expired(owner_id)+ state = secrets.token_urlsafe(32)+ separator = "&" if parsed_redirect.query else "?"+ callback_url = f"{redirect_uri}{separator}{urlencode({'state': state})}"+ authorize_url = f"{base}/authorize_token?{urlencode({'scopes': ','.join(ACCOUNT_SCOPES), 'callback_url': callback_url})}"++ _storage.replace_pending_flow(+ state=state,+ flow=_storage.PendingFlow(+ owner_id=owner_id,+ api_base_url=base,+ callback_url=callback_url,+ expires_at=time.time() + FLOW_TIMEOUT_S,+ ),+ )+ return authorize_url+++def _parse_token(raw_token: str) -> dict[str, Any]:+ if not raw_token or len(raw_token.encode("utf-8")) > _MAX_TOKEN_BYTES:+ raise TimedMediaError("Invidious returned an invalid account token.")+ try:+ token = json.loads(raw_token)+ except (json.JSONDecodeError, UnicodeError) as exc:+ raise TimedMediaError("Invidious returned an invalid account token.") from exc+ if not isinstance(token, dict):+ raise TimedMediaError("Invidious returned an invalid account token.")++ session = token.get("session")+ scopes = token.get("scopes")+ signature = token.get("signature")+ if (+ not isinstance(session, str)+ or not session+ or not isinstance(signature, str)+ or not signature+ or not isinstance(scopes, list)+ or any(not isinstance(scope, str) for scope in scopes)+ ):+ raise TimedMediaError("Invidious returned an incomplete account token.")+ if not _scopes_include_required(scopes):+ raise TimedMediaError("Invidious account token is missing a required scope.")+ expire = token.get("expire")+ if expire is not None and (not isinstance(expire, int) or expire <= 0):+ raise TimedMediaError("Invidious returned an invalid token expiration.")+ return token+++def _scopes_include_required(scopes: Any) -> bool:+ if not isinstance(scopes, list) or any(not isinstance(scope, str) for scope in scopes):+ return False+ return set(ACCOUNT_SCOPES).issubset(set(scopes))+++def _stored_token_is_usable(token: Any) -> bool:+ if not isinstance(token, dict):+ return False+ session = token.get("session")+ signature = token.get("signature")+ expire = token.get("expire")+ if not isinstance(session, str) or not session:+ return False+ if not isinstance(signature, str) or not signature:+ return False+ if expire is not None and (not isinstance(expire, int) or expire <= 0):+ return False+ return not (isinstance(expire, int) and expire <= datetime.now(timezone.utc).timestamp())+++async def complete_invidious_account_authorization(+ *, owner_id: str, state: str, token: str+) -> dict[str, Any]:+ _storage.purge_expired(owner_id)+ flow = _storage.consume_pending_flow(owner_id, state)+ if flow is None:+ raise TimedMediaError("Invidious account callback is unknown, expired, or already used.")++ parsed_token = _parse_token(token)+ await _request_preferences(api_base_url=flow.api_base_url, token=parsed_token)++ _storage.write_account(+ owner_id,+ {+ "version": 1,+ "api_base_url": flow.api_base_url,+ "scopes": list(ACCOUNT_SCOPES),+ "connected_at": datetime.now(timezone.utc).isoformat(),+ "token": parsed_token,+ },+ )+ return invidious_account_status(owner_id)+++def invidious_account_status(owner_id: str) -> dict[str, Any]:+ payload = _storage.read_account(owner_id)+ token = payload.get("token")+ base = payload.get("api_base_url")+ scopes = payload.get("scopes")+ connected_at = payload.get("connected_at")+ if not _stored_token_is_usable(token) or not isinstance(base, str) or not base:+ return {"connected": False}+ if not _scopes_include_required(scopes):+ return {"connected": False}+ if not isinstance(connected_at, str) or not connected_at:+ return {"connected": False}+ return {+ "connected": True,+ "api_base_url": base,+ "scopes": [str(scope) for scope in scopes],+ "connected_at": connected_at,+ }+++async def disconnect_invidious_account(*, owner_id: str) -> dict[str, Any]:+ payload = _storage.read_account(owner_id)+ token = payload.get("token")+ base = payload.get("api_base_url")+ if not _stored_token_is_usable(token) or not isinstance(base, str) or not base:+ _storage.forget_account(owner_id)+ return {"connected": False}++ try:+ await _revoke_token(api_base_url=base, token=token)+ except _client.InvidiousTransportError as exc:+ raise TimedMediaError(+ "Invidious account disconnection request failed. The saved connection was kept so it can be retried."+ ) from exc+ except TimedMediaError:+ # Do not delete first: if the instance is temporarily unavailable, doing+ # so would leave a valid token registered upstream with no local revoke.+ raise++ _storage.forget_account(owner_id)+ return {"connected": False}+++__all__ = [+ "ACCOUNT_SCOPES",+ "CALLBACK_PATH",+ "FLOW_TIMEOUT_S",+ "begin_invidious_account_authorization",+ "complete_invidious_account_authorization",+ "disconnect_invidious_account",+ "invidious_account_status",+ "invidious_redirect_uri",+]diff --git a/deeptutor/video_learning/invidious_account_client.py b/deeptutor/video_learning/invidious_account_client.pynew file mode 100644index 000000000..6fc25de07--- /dev/null+++ b/deeptutor/video_learning/invidious_account_client.py@@ -0,0 +1,64 @@+"""HTTP boundary for the Invidious account API."""++from __future__ import annotations++import json+from typing import Any++import httpx++from deeptutor.video_learning.service import TimedMediaError+++class InvidiousTransportError(RuntimeError):+ """The Invidious instance could not be reached."""+++def bearer_token(token: dict[str, Any]) -> str:+ return json.dumps(token, ensure_ascii=False, separators=(",", ":"))+++async def request_preferences(*, api_base_url: str, token: dict[str, Any]) -> dict[str, Any]:+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:+ try:+ response = await client.get(+ f"{api_base_url}/api/v1/auth/preferences",+ headers={"Authorization": f"Bearer {bearer_token(token)}"},+ )+ except httpx.HTTPError as exc:+ raise TimedMediaError("Invidious account verification request failed.") from exc+ if response.status_code != 200:+ raise TimedMediaError(+ f"Invidious account verification failed with HTTP {response.status_code}."+ )+ try:+ preferences = response.json()+ except ValueError as exc:+ raise TimedMediaError("Invidious returned invalid account preferences.") from exc+ if not isinstance(preferences, dict):+ raise TimedMediaError("Invidious returned invalid account preferences.")+ return preferences+++async def revoke_token(*, api_base_url: str, token: dict[str, Any]) -> None:+ try:+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:+ response = await client.post(+ f"{api_base_url}/api/v1/auth/tokens/unregister",+ headers={"Authorization": f"Bearer {bearer_token(token)}"},+ json={"session": token["session"]},+ )+ except httpx.HTTPError as exc:+ raise InvidiousTransportError from exc+ if response.status_code < 200 or response.status_code >= 300:+ raise TimedMediaError(+ f"Invidious account disconnection failed with HTTP {response.status_code}."+ )+++__all__ = [+ "InvidiousTransportError",+ "bearer_token",+ "request_preferences",+ "revoke_token",+]diff --git a/deeptutor/video_learning/invidious_account_storage.py b/deeptutor/video_learning/invidious_account_storage.pynew file mode 100644index 000000000..a77f40d09--- /dev/null+++ b/deeptutor/video_learning/invidious_account_storage.py@@ -0,0 +1,177 @@+"""Owner-private persistence for Invidious account authorization.++This module owns filesystem layout, permissions, atomic publication, and the+one-time pending-flow claim. It deliberately knows nothing about HTTP or the+authorization workflow that consumes the records.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass+import hashlib+import json+import os+from pathlib import Path+import secrets+import stat+import time+from typing import Any++from deeptutor.multi_user.paths import owner_secrets_dir++_SECRETS_SUBDIR = ("private", "video-learning-invidious")+++@dataclass(frozen=True, slots=True)+class PendingFlow:+ owner_id: str+ api_base_url: str+ callback_url: str+ expires_at: float+++def asset_dir(owner_id: str) -> Path:+ path = owner_secrets_dir(owner_id)+ for part in _SECRETS_SUBDIR:+ path = path / part+ path.mkdir(parents=True, exist_ok=True)+ os.chmod(path, stat.S_IRWXU)+ return path+++def account_path(owner_id: str) -> Path:+ return asset_dir(owner_id) / "account.json"+++def pending_dir(owner_id: str) -> Path:+ path = asset_dir(owner_id) / "pending"+ path.mkdir(parents=True, exist_ok=True)+ os.chmod(path, stat.S_IRWXU)+ return path+++def flow_path(owner_id: str, state: str) -> Path:+ # State never becomes a path segment. Besides avoiding traversal hazards,+ # hashing keeps a filesystem backup from disclosing a still-live callback+ # state to someone who can list filenames but not read owner-private files.+ digest = hashlib.sha256(state.encode("utf-8")).hexdigest()+ return pending_dir(owner_id) / f"{digest}.json"+++def read_json(path: Path) -> dict[str, Any]:+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError):+ return {}+ return payload if isinstance(payload, dict) else {}+++def write_private_json(path: Path, payload: dict[str, Any]) -> None:+ temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")+ try:+ descriptor = os.open(+ temporary,+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,+ stat.S_IRUSR | stat.S_IWUSR,+ )+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:+ handle.write(json.dumps(payload, ensure_ascii=False, indent=2))+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary, path)+ finally:+ temporary.unlink(missing_ok=True)+++def pending_flow(path: Path) -> PendingFlow | None:+ payload = read_json(path)+ owner_id = payload.get("owner_id")+ api_base_url = payload.get("api_base_url")+ callback_url = payload.get("callback_url")+ expires_at = payload.get("expires_at")+ if (+ not isinstance(owner_id, str)+ or not owner_id+ or not isinstance(api_base_url, str)+ or not api_base_url+ or not isinstance(callback_url, str)+ or not callback_url+ or not isinstance(expires_at, (int, float))+ ):+ return None+ return PendingFlow(+ owner_id=owner_id,+ api_base_url=api_base_url,+ callback_url=callback_url,+ expires_at=float(expires_at),+ )+++def purge_expired(owner_id: str, now: float | None = None) -> None:+ current = time.time() if now is None else now+ for path in pending_dir(owner_id).glob("*.json"):+ flow = pending_flow(path)+ if flow is None or flow.owner_id != owner_id or flow.expires_at <= current:+ path.unlink(missing_ok=True)+++def replace_pending_flow(*, state: str, flow: PendingFlow) -> None:+ """Publish one flow after invalidating older flows for the same instance."""+ for path in pending_dir(flow.owner_id).glob("*.json"):+ existing = pending_flow(path)+ if (+ existing is None+ or existing.owner_id != flow.owner_id+ or existing.api_base_url == flow.api_base_url+ ):+ path.unlink(missing_ok=True)+ write_private_json(+ flow_path(flow.owner_id, state),+ {"version": 1, **asdict(flow)},+ )+++def consume_pending_flow(owner_id: str, state: str) -> PendingFlow | None:+ if not state:+ return None+ source = flow_path(owner_id, state)+ claim = source.with_name(f".{source.name}.{secrets.token_hex(8)}.claim")+ try:+ # Same-filesystem rename is the one-time claim. It works across Uvicorn+ # workers and across restarts, unlike a process-local dictionary.+ source.rename(claim)+ except FileNotFoundError:+ return None+ try:+ flow = pending_flow(claim)+ finally:+ claim.unlink(missing_ok=True)+ if flow is None or flow.owner_id != owner_id or flow.expires_at <= time.time():+ return None+ return flow+++def read_account(owner_id: str) -> dict[str, Any]:+ return read_json(account_path(owner_id))+++def write_account(owner_id: str, payload: dict[str, Any]) -> None:+ write_private_json(account_path(owner_id), payload)+++def forget_account(owner_id: str) -> None:+ account_path(owner_id).unlink(missing_ok=True)+++__all__ = [+ "PendingFlow",+ "consume_pending_flow",+ "flow_path",+ "forget_account",+ "purge_expired",+ "read_account",+ "read_json",+ "replace_pending_flow",+ "write_account",+ "write_private_json",+]diff --git a/deeptutor/video_learning/notes.py b/deeptutor/video_learning/notes.pyindex fa2483fc8..8ebde156b 100644--- a/deeptutor/video_learning/notes.py+++ b/deeptutor/video_learning/notes.py@@ -114,6 +114,33 @@ def list_notes(manager: NotebookManager, material_id: str) -> list[dict[str, Anyreturn notes+def export_notes(manager: NotebookManager, material_id: str) -> str:+ material = get_timed_media_store().get(material_id)+ notes = list_notes(manager, material_id)+ title = _clip_text(+ str(material.get("metadata", {}).get("title") or "Timed media").strip() or "Timed media",+ 140,+ )+ lines = [f"# Video notes: {title}"]+ if not notes:+ lines.extend(["", "_No timestamped notes captured yet._"])+ return "\n".join(lines).strip() + "\n"++ for note in notes:+ lines.extend(+ (+ "",+ f"## {_format_time(note['time_seconds'])}",+ "",+ str(note.get("body") or "").strip(),+ )+ )+ quote = _clip_text(note.get("quote"))+ if quote:+ lines.extend(("", f"> {quote}"))+ return "\n".join(lines).strip() + "\n"++def create_note(manager: NotebookManager, material_id: str, body: str, time_seconds: float) -> dict[str, Any]:@@ -199,6 +226,7 @@ __all__ = ["NOTEBOOK_NAME","create_note","delete_note",+ "export_notes","get_notebook_manager","list_notes","update_note",diff --git a/docs/adr/0004-invidious-account-boundaries.md b/docs/adr/0004-invidious-account-boundaries.mdnew file mode 100644index 000000000..5926b2d95--- /dev/null+++ b/docs/adr/0004-invidious-account-boundaries.md@@ -0,0 +1,64 @@+# ADR-0004: Separate Invidious Account Workflow, Storage, and Transport++## Status++Accepted++## Context++The Invidious account module initially combined three security-sensitive+responsibilities: authorization workflow decisions, owner-private filesystem+persistence, and upstream HTTP requests. The public surface was small, but a+change to token validation could accidentally affect atomic state claims or+transport behavior because all three concerns shared one implementation file.++Pending callbacks also have stricter storage requirements than ordinary+settings: state must not become a path segment, records must be private, and a+callback must be claimed exactly once across workers and process restarts.+Those invariants need an explicit owner independent of the web workflow.++## Decision++- `invidious_account.py` remains the application facade. It validates workflow+ input, chooses scopes, coordinates verification, and exposes the public API.+- `invidious_account_storage.py` owns filesystem layout, permissions, atomic+ JSON publication, expiration cleanup, and one-time pending-flow claims.+- `invidious_account_client.py` owns bearer serialization and all HTTP calls to+ the configured Invidious instance.+- Dependencies point inward from the facade to those two adapters. The storage+ adapter does not import HTTP or workflow services, and callers outside video+ learning continue to use only the facade.+- The persisted JSON shapes, callback lifetime, public functions, and+ user-facing errors remain unchanged.++## Consequences++### Positive++- Filesystem and cross-worker invariants can evolve without touching OAuth-like+ workflow or HTTP code.+- Transport tests patch the transport module directly, making network ownership+ visible.+- The facade is short enough to review as a state transition rather than as a+ mixture of storage and protocol mechanics.++### Negative++- Two private transport call seams remain in the facade so workflow tests can+ substitute upstream behavior without mocking filesystem persistence.+- The feature now spans three modules instead of one.++### Neutral++- This does not introduce a general credential-store abstraction; the unusual+ one-time claim semantics remain local to Invidious accounts.++## Alternatives Considered++- Keep the single module and group functions by comments: rejected because it+ preserves shared implementation ownership and hidden transport coupling.+- Introduce a repository-wide OAuth framework: rejected because Invidious uses+ a provider-specific signed-token callback and there is not yet a second flow+ with the same lifecycle.+- Move only HTTP calls: rejected because the more important concurrency and+ permission invariants would still be embedded in the workflow facade.diff --git a/docs/remote-hermes-backend.md b/docs/remote-hermes-backend.mdnew file mode 100644index 000000000..27e4ed3ea--- /dev/null+++ b/docs/remote-hermes-backend.md@@ -0,0 +1,94 @@+# Remote Hermes Agent backend++DeepTutor Connected Agents can call a Hermes Agent gateway without installing a+Hermes CLI in the DeepTutor container. The backend kind is `hermes_remote` and+its display name is **Hermes Agent (remote)**.++## Configuration++The per-backend settings live under `backends.hermes_remote` in the normal+`subagent.json` settings document:++- `enabled`: whether chat may delegate to this backend.+- `base_url`: gateway root, for example `http://hermes-uni:8642`.+- `api_key_env`: environment-variable name containing the gateway bearer. It+ defaults to `DEEPTUTOR_HERMES_REMOTE_API_KEY`.+- `profile`: informational deployment/profile label; it is not a credential and+ is not used to construct a URL.+- `model`, `effort`, `system_prompt`, `auto_approve`: the run controls shared+ with local backends.+- `idle_timeout_seconds`: maximum idle interval between SSE frames (default+ `600`). Keepalives from the gateway reset this watchdog.++The API key is environment-only. It is never accepted as an inline settings+field, persisted, or returned by `GET /api/subagents/settings`.+The gateway URL must be HTTP(S) without credentials, query text, or fragments.+An optional `/p/<profile>` prefix supports Hermes multi-profile routing.+Redirects are never followed.++## HTTP contract++The adapter uses authenticated bearer requests (`Authorization: Bearer ...`)+with explicit connect/read/write/pool timeouts. The endpoints and machine-+readable feature contract are documented in the+[Hermes API Server guide](https://hermes-agent.nousresearch.com/docs/user-guide/features/api-server/).++1. `GET /v1/capabilities` detects availability and verifies that the configured+ gateway advertises run submission, event streaming, stopping, approval+ responses, and session resources. Detection reports distinct+ `not_configured`, `key_missing`, `unreachable`, `unauthorized`, and+ `incompatible` details.+2. `POST /v1/runs` starts a run. The request uses `input` for the user prompt,+ `instructions` for the optional first-session system instruction, `model`+ when configured, `model_options.reasoning_effort` when configured, and+ `session_id` when resuming. The server returns HTTP 202 with+ `{ "run_id": "...", "status": "started" }`. A fresh run uses its run id as+ the session id; a resumed run keeps the supplied session id.+ Before a resumed run, the adapter fetches+ `GET /api/sessions/{session_id}/messages`. It keeps only non-empty+ user/assistant rows, excludes tool rows, and sends at most the last 40 rows+ as `conversation_history`. A 404 means the session is gone: the old session+ id and headers are dropped, and the run starts fresh without history while+ applying `system_prompt` again.+3. `GET /v1/runs/{run_id}/events` is an SSE stream. Frames contain JSON in a+ `data:` line. The adapter consumes these event objects:+ `message.delta` (`delta`), `tool.started` (`tool`, `preview`),+ `tool.completed` (`tool`, `error`), `reasoning.available` (`text`),+ `approval.request`, `run.completed` (`output`), `run.failed` (`error`), and+ `run.cancelled`. Tool lifecycle events become tool/tool-result rows;+ answer deltas become cumulative text under merge id+ `hermes_remote:final`; other lifecycle events become log/error rows. The+ gateway emits tool/reasoning, text/completion, and approval events through+ the same stream.+4. `POST /v1/runs/{run_id}/approval` resolves a pending approval. The body is+ `{ "choice": "once" }` for auto-approve and `{ "choice": "deny" }` when+ `auto_approve` is false. A failed approval response is surfaced and the run+ is stopped instead of waiting indefinitely.+5. `POST /v1/runs/{run_id}/stop` interrupts a run. Cancellation posts this+ request with a shielded, bounded cleanup window, then re-raises cancellation;+ an SSE idle timeout posts it and returns an error.++Session continuity uses both the gateway's documented+`X-Hermes-Session-Id` header and `session_id` request field. The adapter also+sends the compatibility `X-Hermes-Session` header. Custom `system_prompt` is+sent on a fresh session or when the history lookup reports that the session is+gone (404). Every request carries the fixed+`CONSULT_ORIGIN_INSTRUCTION` recursion guard identifying DeepTutor Connected+Agents and telling the gateway agent to answer directly rather than delegate+back to DeepTutor.++The `/v1/runs` API has no image upload field. Attachments and their DeepTutor-+local paths are therefore not sent to the remote gateway.++## Isolation and security++This backend keeps the Hermes gateway outside the DeepTutor process/container:+tools run on the gateway host, not in DeepTutor. Scope each DeepTutor chat to+its own returned session id; do not share session ids across users or chats.+Keep `API_SERVER_KEY` (the gateway's server-side secret) and+`DEEPTUTOR_HERMES_REMOTE_API_KEY` (the DeepTutor-side env name's value) out of+settings files, logs, event text, and frontend payloads.++Streaming is quiet except for the structured SSE lifecycle exposed by the+adapter. It does not poll or retry `POST /v1/runs`; a caller cancellation or+idle watchdog always attempts a bounded stop.diff --git a/scripts/pb_setup.py b/scripts/pb_setup.pyindex b87356f8f..26f4c6b23 100644--- a/scripts/pb_setup.py+++ b/scripts/pb_setup.py@@ -221,11 +221,13 @@ def main():{"name": "state_version", "type": "number", "required": False},{"name": "failure_code", "type": "text", "required": False},{"name": "retryable", "type": "bool", "required": False},+ {"name": "assistant_message_id", "type": "text", "required": False},],"indexes": ["CREATE UNIQUE INDEX idx_turns_turn_id ON turns (turn_id)","CREATE UNIQUE INDEX idx_turns_one_active_session ON turns (session_id) ""WHERE status IN ('queued', 'running', 'waiting_input')",+ "CREATE UNIQUE INDEX idx_turns_assistant_message ON turns (assistant_message_id)",],"listRule": "","viewRule": "",diff --git a/tests/api/route_introspection.py b/tests/api/route_introspection.pynew file mode 100644index 000000000..40c415daa--- /dev/null+++ b/tests/api/route_introspection.py@@ -0,0 +1,45 @@+"""Compatibility helpers for assertions over FastAPI's registered routes."""++from collections.abc import Iterator++from fastapi import FastAPI+from fastapi.routing import APIWebSocketRoute+++def iter_effective_route_paths(app: FastAPI) -> Iterator[str]:+ """Yield registered paths across flat and nested FastAPI releases."""+ for route in app.routes:+ path = getattr(route, "path", None)+ if isinstance(path, str):+ yield path+ continue++ effective_contexts = getattr(route, "effective_route_contexts", None)+ if not callable(effective_contexts):+ continue+ for context in effective_contexts():+ compiled_route = getattr(context, "starlette_route", None)+ effective_path = getattr(compiled_route, "path", None) or getattr(context, "path", None)+ if isinstance(effective_path, str):+ yield effective_path+++def iter_effective_websocket_routes(app: FastAPI) -> Iterator[APIWebSocketRoute]:+ """Yield compiled WebSocket routes across flat and nested FastAPI releases.++ FastAPI 0.141 stopped flattening included routers into ``app.routes``.+ Included-router entries expose their compiled routes through+ ``effective_route_contexts()``; older releases expose the routes directly.+ """+ for route in app.routes:+ if isinstance(route, APIWebSocketRoute):+ yield route+ continue++ effective_contexts = getattr(route, "effective_route_contexts", None)+ if not callable(effective_contexts):+ continue+ for context in effective_contexts():+ compiled_route = getattr(context, "starlette_route", None)+ if isinstance(compiled_route, APIWebSocketRoute):+ yield compiled_routediff --git a/tests/api/test_canonical_route_surface.py b/tests/api/test_canonical_route_surface.pyindex 955fd2239..6aebed2b7 100644--- a/tests/api/test_canonical_route_surface.py+++ b/tests/api/test_canonical_route_surface.py@@ -3,10 +3,11 @@ from types import SimpleNamespaceimport pytestfrom deeptutor.api.main import app, health_live, health_ready+from tests.api.route_introspection import iter_effective_route_pathsdef test_only_canonical_transport_and_resource_routes_are_registered() -> None:- paths = {route.path for route in app.routes}+ paths = set(iter_effective_route_paths(app))required = {"/api/books",diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 7736621b9..518a017bb 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -8,6 +8,12 @@ from types import SimpleNamespaceimport pytest+from deeptutor.multi_user.context import (+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)+from deeptutor.multi_user.models import CurrentUser, UserScopeimport deeptutor.services.config as config_modulefrom deeptutor.services.config.runtime_settings import RuntimeSettingsServicefrom deeptutor.services.rag.pipelines.ima.client import (@@ -811,6 +817,55 @@ def test_create_normalizes_uploaded_extension_to_lowercase(monkeypatch, tmp_pathassert (tmp_path / "knowledge_bases" / "kb-uppercase" / "raw" / "报告.pdf").exists()[email protected](("role", "fail"), [("user", False), ("admin", True)])+def test_initialization_task_installs_owner_scope_and_restores_caller(+ monkeypatch, tmp_path: Path, role: str, fail: bool+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.config["knowledge_bases"]["kb"] = {"path": "kb", "status": "initializing"}+ raw_dir = manager.base_dir / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ owner = CurrentUser(+ id=f"owner-{role}",+ username=f"owner-{role}",+ role=role,+ scope=UserScope(kind=role, user_id=f"owner-{role}", root=tmp_path / "owner"),+ )+ ambient = CurrentUser(+ id="ambient",+ username="ambient",+ role="user",+ scope=UserScope(kind="user", user_id="ambient", root=tmp_path / "ambient"),+ )++ async def process_documents():+ assert get_current_user_or_none() == owner+ if fail:+ raise RuntimeError("indexing failed")++ tracker = SimpleNamespace(task_id=None, update=lambda *_args, **_kwargs: None)+ initializer = SimpleNamespace(+ owner=owner,+ progress_tracker=tracker,+ kb_name="kb",+ base_dir=manager.base_dir,+ raw_dir=raw_dir,+ process_documents=process_documents,+ index_published=False,+ )+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ token = set_current_user(ambient)+ try:+ asyncio.run(+ knowledge_router_module.run_initialization_task(+ initializer, f"owner-scope-{role}-{fail}"+ )+ )+ assert get_current_user_or_none() == ambient+ finally:+ reset_current_user(token)++def test_upload_returns_409_when_kb_needs_reindex(monkeypatch, tmp_path: Path) -> None:manager = _FakeKBManager(tmp_path / "knowledge_bases")manager.config["knowledge_bases"]["legacy-kb"] = {@@ -1581,8 +1636,54 @@ def test_reindex_task_persists_completed_progress(monkeypatch, tmp_path: Path) -assert "embedding_mismatch" not in entry+def test_reindex_task_preserves_prepublication_failure(monkeypatch, tmp_path: Path) -> None:+ base_dir = tmp_path / "knowledge_bases"+ raw_dir = base_dir / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ (raw_dir / "fixture.txt").write_text("fixture", encoding="utf-8")+ (base_dir / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "rag_provider": "lightrag",+ "status": "processing",+ }+ }+ }+ ),+ encoding="utf-8",+ )++ class _FailingRagService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def initialize(self, *_args, **_kwargs) -> bool:+ raise RuntimeError("original indexing failure")++ rag_service_module = importlib.import_module("deeptutor.services.rag.service")+ monkeypatch.setattr(rag_service_module, "RAGService", _FailingRagService)+ task_id = knowledge_router_module._build_unique_task_id("kb_reindex", "prepublish-fail")++ asyncio.run(+ knowledge_router_module.run_reindex_task(+ kb_name="kb",+ base_dir=str(base_dir),+ task_id=task_id,+ signature_hash="lightrag",+ )+ )++ task = knowledge_router_module.TaskIDManager.get_instance().get_task_metadata(task_id)+ assert task is not None+ assert task["status"] == "error"+ assert task["error"] == "original indexing failure"++@pytest.mark.parametrize("failed_sink", ["progress_file", "central_config"])-def test_reindex_task_fails_closed_when_terminal_progress_is_not_persisted(+def test_reindex_task_does_not_report_a_published_version_as_failed_when_bookkeeping_fails(monkeypatch, tmp_path: Path, failed_sink: str) -> None:base_dir = tmp_path / "knowledge_bases"@@ -1659,13 +1760,16 @@ def test_reindex_task_fails_closed_when_terminal_progress_is_not_persisted(task = task_manager.get_task_metadata(task_id)assert task is not None- assert task["status"] == "error"- assert "terminal state" in task["error"]+ assert task["status"] == "completed"progress = json.loads((base_dir / "kb" / ".progress.json").read_text(encoding="utf-8"))- assert progress["stage"] == "error"persisted = json.loads((base_dir / "kb_config.json").read_text(encoding="utf-8"))entry = persisted["knowledge_bases"]["kb"]- assert entry["status"] == "error"+ if failed_sink == "progress_file":+ assert progress["stage"] != "error"+ assert entry["status"] == "ready"+ else:+ assert progress["stage"] == "completed"+ assert entry["status"] == "processing"assert entry["needs_reindex"] is Trueassert entry["embedding_mismatch"] == {"reason": "test"}@@ -2141,6 +2245,15 @@ def test_create_pageindex_oss_persists_optional_mode(monkeypatch, tmp_path: Pathdef test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path: Path) -> None:manager = _FakeKBManager(tmp_path / "knowledge_bases")+ snapshot = SimpleNamespace(+ persisted_policy=lambda: {+ "policy": "pinned",+ "selection": {"profile_id": "profile-1", "model_id": "model-1"},+ "descriptor": {"model": "safe-model"},+ "fingerprint": "a" * 64,+ "vision_available": True,+ }+ )monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)monkeypatch.setattr(knowledge_router_module, "KnowledgeBaseInitializer", _FakeInitializer)monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases")@@ -2148,6 +2261,11 @@ def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path:monkeypatch.setattr(preflight, "engine_preflight", lambda _provider: {"ok": True, "checks": []})lightrag_config = importlib.import_module("deeptutor.services.rag.pipelines.lightrag.config")monkeypatch.setattr(lightrag_config, "is_lightrag_available", lambda: True)+ monkeypatch.setattr(+ knowledge_router_module,+ "_freeze_default_indexing_llm",+ lambda: snapshot,+ )async def _noop_init_task(*_args, **_kwargs):return None@@ -2168,6 +2286,180 @@ def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path:assert manager.config["knowledge_bases"]["kb-light"]["search_mode"] == "hybrid"+def test_create_empty_lightrag_kb_persists_redacted_pending_policy(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ snapshot = SimpleNamespace(+ persisted_policy=lambda: {+ "policy": "pinned",+ "selection": {"profile_id": "profile-1", "model_id": "model-1"},+ "descriptor": {"model": "safe-model"},+ "fingerprint": "a" * 64,+ "vision_available": True,+ }+ )+ seen: list[str] = []++ def freeze_form(raw: str):+ seen.append(raw)+ return {"profile_id": "profile-1", "model_id": "model-1"}, snapshot++ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "KnowledgeBaseInitializer", _FakeInitializer)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)+ monkeypatch.setattr(knowledge_router_module, "_assert_provider_ready", lambda _provider: None)+ monkeypatch.setattr(knowledge_router_module, "_freeze_indexing_llm_form", freeze_form)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/knowledge-bases",+ data={+ "name": "kb-pending",+ "rag_provider": "lightrag",+ "indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"}),+ },+ )++ assert response.status_code == 200+ assert len(seen) == 1+ pending = manager.config["knowledge_bases"]["kb-pending"]["pending_indexing_policy"]+ assert pending["policy"] == "pending_pinned"+ assert pending["fingerprint"] == "a" * 64+ assert pending["selection"] == {"profile_id": "profile-1", "model_id": "model-1"}+ assert not list((manager.base_dir / "kb-pending").glob("version-*"))+++def test_create_rejects_indexing_selection_for_other_provider_before_registration(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/knowledge-bases",+ data={+ "name": "wrong-provider",+ "rag_provider": "llamaindex",+ "indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"}),+ },+ )++ assert response.status_code == 400+ assert manager.config["knowledge_bases"] == {}+++def test_empty_lightrag_kb_can_update_pending_indexing_policy(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.config["knowledge_bases"]["empty"] = {+ "rag_provider": "lightrag",+ "status": "ready",+ "progress": {"stage": "completed"},+ }+ (manager.base_dir / "empty" / "raw").mkdir(parents=True)+ policy = {+ "policy": "pending_pinned",+ "selection": {+ "profile_id": "profile-1",+ "model_id": "model-1",+ "reasoning_effort": "none",+ },+ "descriptor": {"model": "safe-model", "reasoning_effort": "none"},+ "fingerprint": "b" * 64,+ "vision_available": False,+ }+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.storage.latest_published_root",+ lambda _kb_dir: None,+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.pending_policy_for_selection",+ lambda selection: policy if selection["reasoning_effort"] == "none" else None,+ )++ with TestClient(_build_app()) as client:+ response = client.put(+ "/api/knowledge-bases/empty/indexing-policy",+ json={+ "profile_id": "profile-1",+ "model_id": "model-1",+ "reasoning_effort": "none",+ },+ )++ assert response.status_code == 200+ assert response.json()["indexing_policy"] == policy+ assert manager.config["knowledge_bases"]["empty"]["pending_indexing_policy"] == policy++[email protected]("reason", ["published", "documents", "active"])+def test_pending_indexing_policy_update_rejects_ineligible_kb(+ monkeypatch, tmp_path: Path, reason: str+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ entry = {"rag_provider": "lightrag", "status": "ready"}+ manager.config["knowledge_bases"]["kb"] = entry+ raw_dir = manager.base_dir / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ if reason == "documents":+ (raw_dir / "doc.txt").write_text("content", encoding="utf-8")+ if reason == "active":+ entry.update({"status": "processing", "progress": {"stage": "processing_file"}})+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.storage.latest_published_root",+ lambda _kb_dir: object() if reason == "published" else None,+ )++ with TestClient(_build_app()) as client:+ response = client.put(+ "/api/knowledge-bases/kb/indexing-policy",+ json={"profile_id": "profile-1", "model_id": "model-1"},+ )++ assert response.status_code == 409+ assert "pending_indexing_policy" not in entry+++def test_reindex_passes_frozen_lightrag_snapshot_to_background_task(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.config["knowledge_bases"]["kb"] = {+ "path": "kb",+ "rag_provider": "lightrag",+ "status": "ready",+ }+ (manager.base_dir / "kb" / "raw").mkdir(parents=True)+ snapshot = object()+ captured: dict[str, object] = {}++ async def capture_task(*_args, **kwargs):+ captured.update(kwargs)++ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)+ monkeypatch.setattr(knowledge_router_module, "_assert_provider_ready", lambda _provider: None)+ monkeypatch.setattr(+ knowledge_router_module,+ "_freeze_indexing_llm_form",+ lambda _raw: ({"profile_id": "profile-1", "model_id": "model-1"}, snapshot),+ )+ monkeypatch.setattr(knowledge_router_module, "run_reindex_task", capture_task)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/knowledge-bases/kb/reindex",+ data={"indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"})},+ )++ assert response.status_code == 200+ assert captured["indexing_snapshot"] is snapshot++def test_create_pageindex_oss_rejects_non_pdf(monkeypatch, tmp_path: Path) -> None:manager = _FakeKBManager(tmp_path / "knowledge_bases")monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)diff --git a/tests/api/test_sessions_trace.py b/tests/api/test_sessions_trace.pynew file mode 100644index 000000000..16ab0aa22--- /dev/null+++ b/tests/api/test_sessions_trace.py@@ -0,0 +1,59 @@+from __future__ import annotations++import asyncio++from fastapi import FastAPI+from fastapi.testclient import TestClient++from deeptutor.api.routers import sessions as sessions_router+from deeptutor.services.session.sqlite_store import SQLiteSessionStore+++def test_message_trace_is_paginated_and_session_scoped(tmp_path, monkeypatch) -> None:+ store = SQLiteSessionStore(tmp_path / "chat.db")+ session = asyncio.run(store.ensure_session(None))+ other = asyncio.run(store.ensure_session(None))+ turn = asyncio.run(store.begin_turn(session["id"], capability="chat"))+ message_id = asyncio.run(store.add_message(session["id"], "assistant", "answer"))+ asyncio.run(+ store.append_turn_events(+ turn["id"],+ [+ {"type": "tool_call", "content": "lookup", "metadata": {}},+ {"type": "done", "metadata": {"assistant_message_id": message_id}},+ ],+ )+ )+ assert asyncio.run(store.link_turn_message(turn["id"], message_id)) is True++ monkeypatch.setattr(sessions_router, "get_session_store", lambda: store)+ app = FastAPI()+ app.include_router(sessions_router.router, prefix="/api/sessions")++ with TestClient(app) as client:+ page = client.get(f"/api/sessions/{session['id']}/messages/{message_id}/events?limit=1")+ assert page.status_code == 200+ body = page.json()+ assert body["turn_id"] == turn["id"]+ assert body["total"] == 2+ assert body["events"][0]["seq"] == 1+ assert body["next_seq"] == 1+ assert body["complete"] is False++ denied = client.get(f"/api/sessions/{other['id']}/messages/{message_id}/events")+ assert denied.status_code == 404++ malformed = client.get(f"/api/sessions/{session['id']}/messages/not-a-sqlite-id/events")+ assert malformed.status_code == 404++ detail = asyncio.run(store.get_session_with_messages(session["id"]))+ assert detail is not None+ message = detail["messages"][0]+ assert message["events"][0]["type"] == "tool_call"+ assert message["events"][-1]["type"] == "done"+ assert message["trace"] == {+ "turn_id": turn["id"],+ "total": 2,+ "last_seq": 2,+ "truncated": False,+ }diff --git a/tests/api/test_subagents_router.py b/tests/api/test_subagents_router.pyindex e1690f367..860cb4d5c 100644--- a/tests/api/test_subagents_router.py+++ b/tests/api/test_subagents_router.py@@ -66,7 +66,9 @@ def client(monkeypatch, tmp_path):manager = _FakeKBManager()monkeypatch.setattr(subagents_module, "current_kb_manager", lambda: manager)monkeypatch.setattr(- subagents_module, "list_backend_kinds", lambda: ["claude_code", "codex", "partner"]+ subagents_module,+ "list_backend_kinds",+ lambda: ["claude_code", "codex", "hermes_remote", "partner"],)monkeypatch.setattr(subagents_module, "assert_path_allowed", lambda p: Path(p))# Isolate settings persistence to a temp file — the PUT path otherwise@@ -128,6 +130,19 @@ def test_connect_rejects_unknown_kind(client):assert res.status_code == 400+def test_connect_remote_backend_does_not_persist_a_local_cwd(client):+ created = client.post(+ "/api/subagents/connections",+ json={+ "name": "RemoteHermes",+ "agent_kind": "hermes_remote",+ "cwd": "/private/path-that-must-not-cross-the-boundary",+ },+ )+ assert created.status_code == 200+ assert created.json()["cwd"] == ""++class _FakePartnerManagerForConnect:def __init__(self, known: set[str]) -> None:self._known = knowndiff --git a/tests/api/test_websocket_routing.py b/tests/api/test_websocket_routing.pyindex da7ef6b02..e40763f1b 100644--- a/tests/api/test_websocket_routing.py+++ b/tests/api/test_websocket_routing.py@@ -1,9 +1,8 @@"""WebSocket routes must not inherit HTTP-only application dependencies."""-from fastapi.routing import APIWebSocketRoute-from deeptutor.api.main import appfrom deeptutor.api.routers.auth import require_learning_surface+from tests.api.route_introspection import iter_effective_websocket_routesdef test_websocket_routes_share_one_canonical_namespace() -> None:@@ -18,9 +17,7 @@ def test_websocket_routes_share_one_canonical_namespace() -> None:"/ws/partners/{partner_id}","/ws/partner-groups/{group_id}",}- websocket_routes = {- route.path: route for route in app.routes if isinstance(route, APIWebSocketRoute)- }+ websocket_routes = {route.path: route for route in iter_effective_websocket_routes(app)}assert set(websocket_routes) == expected_pathsfor route in websocket_routes.values():diff --git a/tests/knowledge/test_document_adder_provider.py b/tests/knowledge/test_document_adder_provider.pyindex 4a100177b..680ba25ca 100644--- a/tests/knowledge/test_document_adder_provider.py+++ b/tests/knowledge/test_document_adder_provider.py@@ -23,17 +23,25 @@ def _write_provider_version(kb_dir: Path, provider: str) -> None:output_dir = version_dir / "output"output_dir.mkdir()(output_dir / "entities.parquet").write_bytes(b"placeholder")+ elif provider == "lightrag":+ (version_dir / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )else:(version_dir / "docstore.json").write_text("{}", encoding="utf-8")(version_dir / "index_store.json").write_text("{}", encoding="utf-8")- (version_dir / "meta.json").write_text(- json.dumps(+ meta = {"provider": provider, "signature": provider, "version": "version-1"}+ if provider == "lightrag":+ meta.update({- "provider": provider,- "signature": provider,- "version": "version-1",+ "lightrag_adapter_schema": 2,+ "parser_bridge_schema": 1,+ "state": "published",}- ),+ )+ (version_dir / "meta.json").write_text(+ json.dumps(meta),encoding="utf-8",)@@ -70,6 +78,19 @@ def test_document_adder_preserves_explicit_bound_provider(tmp_path: Path) -> Nonassert adder.rag_provider == "graphrag"+def test_document_adder_allows_empty_lightrag_kb_to_bootstrap(tmp_path: Path) -> None:+ (tmp_path / "empty-kb").mkdir()++ adder = DocumentAdder(+ kb_name="empty-kb",+ base_dir=str(tmp_path),+ rag_provider="lightrag",+ )++ assert adder.rag_provider == "lightrag"+ assert adder.raw_dir.is_dir()++def test_process_new_documents_returns_failures_without_marking_processed(monkeypatch, tmp_path: Path) -> None:@@ -101,6 +122,37 @@ def test_process_new_documents_returns_failures_without_marking_processed(assert adder.get_ingested_hashes() == {}+def test_lightrag_hash_bookkeeping_failure_does_not_deny_published_success(+ monkeypatch, tmp_path: Path+) -> None:+ kb_dir = tmp_path / "kb"+ raw_dir = kb_dir / "raw"+ raw_dir.mkdir(parents=True)+ _write_provider_version(kb_dir, "lightrag")+ doc = raw_dir / "published.txt"+ doc.write_text("hello", encoding="utf-8")++ class _SuccessfulRagService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def add_documents(self, *_args, **_kwargs) -> bool:+ return True++ monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _SuccessfulRagService)+ adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path), rag_provider="lightrag")+ monkeypatch.setattr(+ adder,+ "_record_successful_hash",+ lambda _path: (_ for _ in ()).throw(OSError("metadata unavailable")),+ )++ result = asyncio.run(adder.process_new_documents([doc]))++ assert result.processed_files == [doc]+ assert result.failures == []++def test_remove_raw_document_deletes_file_and_hash_without_index(tmp_path: Path,) -> None:diff --git a/tests/multi_user/test_owner_bound_models.py b/tests/multi_user/test_owner_bound_models.pyindex 5a4f5e998..ea195bedc 100644--- a/tests/multi_user/test_owner_bound_models.py+++ b/tests/multi_user/test_owner_bound_models.py@@ -30,11 +30,27 @@ def _catalog(*, owner_bound: bool) -> dict:profile: dict = {"id": CODEX_PROFILE,"name": "OpenAI Codex",- "models": [{"id": "m-sol", "name": "GPT-5.6-Sol", "model": "gpt-5.6-sol"}],+ "binding": "openai",+ "models": [+ {+ "id": "m-sol",+ "name": "GPT-5.6-Sol",+ "model": "gpt-5.6-sol",+ "reasoning_effort": "high",+ }+ ],}if owner_bound:profile["owner_bound"] = True- return {"services": {"llm": {"profiles": [profile]}}}+ return {+ "services": {+ "llm": {+ "active_profile_id": CODEX_PROFILE,+ "active_model_id": "m-sol",+ "profiles": [profile],+ }+ }+ }def _grant(_user_id=None) -> dict:@@ -47,7 +63,9 @@ def test_owner_bound_profile_is_withheld_from_granted_users(tmp_path, monkeypatctoken = set_current_user(make_user(tmp_path))try:assert model_access.redacted_model_access()["llm"] == []- assert model_access.allowed_llm_options()["options"] == []+ allowed = model_access.allowed_llm_options()+ assert allowed["options"] == []+ assert allowed["active"] is Noneassert model_access.has_capability_access("llm") is Falsewith pytest.raises(PermissionError):model_access.apply_allowed_llm_selection(@@ -83,6 +101,14 @@ def test_ordinary_shared_profiles_stay_grantable(tmp_path, monkeypatch):try:granted = model_access.redacted_model_access()["llm"]assert [item["model_id"] for item in granted] == ["m-sol"]+ option = model_access.allowed_llm_options()["options"][0]+ assert option["provider"] == "openai"+ assert option["reasoning_effort"] == "high"+ assert option["is_active_default"] is True+ assert model_access.allowed_llm_options()["active"] == {+ "profile_id": CODEX_PROFILE,+ "model_id": "m-sol",+ }assert model_access.has_capability_access("llm") is Trueassert model_access.apply_allowed_llm_selection({"profile_id": CODEX_PROFILE, "model_id": "m-sol"}diff --git a/tests/services/config/test_graphrag_lightrag_settings.py b/tests/services/config/test_graphrag_lightrag_settings.pyindex 9c13c6fc7..4cf3b4720 100644--- a/tests/services/config/test_graphrag_lightrag_settings.py+++ b/tests/services/config/test_graphrag_lightrag_settings.py@@ -81,20 +81,6 @@ def test_lightrag_indexing_knobs_round_trip_and_clamp(tmp_path: Path) -> None:assert clamped["response_type"] == "Multiple Paragraphs"-def test_lightrag_dedicated_llm_selection_round_trip(tmp_path: Path) -> None:- """Empty references mean the global model; a complete pair is preserved."""- svc = RuntimeSettingsService(tmp_path, process_env={})- assert svc.load_lightrag()["llm_profile_id"] == ""-- saved = svc.save_lightrag({"llm_profile_id": " profile-1 ", "llm_model_id": " model-1 "})- assert saved["llm_profile_id"] == "profile-1"- assert saved["llm_model_id"] == "model-1"-- cleared = svc.save_lightrag({"llm_profile_id": "", "llm_model_id": ""})- assert cleared["llm_profile_id"] == ""- assert cleared["llm_model_id"] == ""--def test_lightrag_settings_written_before_the_indexing_knobs_still_load(tmp_path: Path,) -> None:@@ -112,6 +98,20 @@ def test_lightrag_settings_written_before_the_indexing_knobs_still_load(assert loaded["llm_model_id"] == ""+def test_lightrag_dedicated_llm_selection_round_trip(tmp_path: Path) -> None:+ """Empty references mean the active model; a complete pair is preserved."""+ svc = RuntimeSettingsService(tmp_path, process_env={})+ assert svc.load_lightrag()["llm_profile_id"] == ""++ saved = svc.save_lightrag({"llm_profile_id": " profile-1 ", "llm_model_id": " model-1 "})+ assert saved["llm_profile_id"] == "profile-1"+ assert saved["llm_model_id"] == "model-1"++ cleared = svc.save_lightrag({"llm_profile_id": "", "llm_model_id": ""})+ assert cleared["llm_profile_id"] == ""+ assert cleared["llm_model_id"] == ""++def test_lightrag_server_defaults_round_trip_without_exposing_shape_drift(tmp_path: Path,) -> None:diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.pyindex 4760f57ed..1be4f9de4 100644--- a/tests/services/config/test_runtime_settings.py+++ b/tests/services/config/test_runtime_settings.py@@ -73,6 +73,30 @@ def test_web_search_source_filter_defaults_to_safe_runtime_json(tmp_path) -> Non"enabled": True,"blocked_domains": [],"trusted_domains": [],+ "content_filtering": True,+ "use_educational_trusted_domains": False,+ "use_moderation": False,+ }++ service.save_system(+ {+ "web_search_source_filtering": {+ "enabled": True,+ "blocked_domains": ["unsafe.example"],+ "trusted_domains": [],+ "content_filtering": False,+ "use_educational_trusted_domains": True,+ "use_moderation": True,+ }+ }+ )+ assert service.load_system()["web_search_source_filtering"] == {+ "enabled": True,+ "blocked_domains": ["unsafe.example"],+ "trusted_domains": [],+ "content_filtering": False,+ "use_educational_trusted_domains": True,+ "use_moderation": True,}diff --git a/tests/services/cron/test_cron_repository.py b/tests/services/cron/test_cron_repository.pynew file mode 100644index 000000000..ca5778954--- /dev/null+++ b/tests/services/cron/test_cron_repository.py@@ -0,0 +1,81 @@+"""SQLiteCronRepository migration lock: cross-platform branches and mutual exclusion."""++from __future__ import annotations++import sys+import threading+import time+from types import SimpleNamespace++import pytest++from deeptutor.services.cron import repository+++class TestMigrationLock:+ def test_acquire_release_round_trip(self, tmp_path):+ repo = repository.SQLiteCronRepository(tmp_path / "cron.db")+ with repo._migration_lock():+ assert repo._migration_lock_path.exists()++ def test_mutually_excludes_concurrent_holders(self, tmp_path):+ repo = repository.SQLiteCronRepository(tmp_path / "cron.db")+ entered = threading.Event()++ def holder():+ with repo._migration_lock():+ entered.set()+ time.sleep(0.3)++ t = threading.Thread(target=holder)+ t.start()+ assert entered.wait(2)+ started = time.monotonic()+ with repo._migration_lock():+ waited = time.monotonic() - started+ t.join(timeout=5)+ assert not t.is_alive()+ # A second acquirer must block until the holder releases its lock.+ assert waited >= 0.2++ def test_module_does_not_bind_fcntl_at_import(self):+ # Top-level ``import fcntl`` breaks cron startup on Windows (#1183).+ assert "fcntl" not in repository.__dict__++ def test_uses_msvcrt_locking_on_windows(self, tmp_path, monkeypatch: pytest.MonkeyPatch):+ repo = repository.SQLiteCronRepository(tmp_path / "cron.db")+ calls: list[tuple[int, int]] = []+ fake_msvcrt = SimpleNamespace(+ LK_LOCK=1,+ LK_UNLCK=2,+ locking=lambda _fileno, mode, length: calls.append((mode, length)),+ )+ monkeypatch.setattr(repository, "sys", SimpleNamespace(platform="win32"))+ monkeypatch.setitem(sys.modules, "msvcrt", fake_msvcrt)++ with repo._migration_lock():+ assert calls == [(fake_msvcrt.LK_LOCK, 1)]++ assert calls == [+ (fake_msvcrt.LK_LOCK, 1),+ (fake_msvcrt.LK_UNLCK, 1),+ ]++ def test_uses_fcntl_locking_on_posix(self, tmp_path, monkeypatch: pytest.MonkeyPatch):+ repo = repository.SQLiteCronRepository(tmp_path / "cron.db")+ calls: list[int] = []+ fake_fcntl = SimpleNamespace(+ LOCK_EX=1,+ LOCK_UN=2,+ flock=lambda _fileno, mode: calls.append(mode),+ )+ monkeypatch.setattr(repository, "sys", SimpleNamespace(platform="linux"))+ monkeypatch.setitem(sys.modules, "fcntl", fake_fcntl)++ with repo._migration_lock():+ assert calls == [fake_fcntl.LOCK_EX]++ assert calls == [+ fake_fcntl.LOCK_EX,+ fake_fcntl.LOCK_UN,+ ]diff --git a/tests/services/llm/test_client.py b/tests/services/llm/test_client.pyindex 968035c24..53c18541c 100644--- a/tests/services/llm/test_client.py+++ b/tests/services/llm/test_client.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom _pytest.monkeypatch import MonkeyPatchimport pytest-from deeptutor.services.llm.client import LLMClient+from deeptutor.services.llm.client import LLMClient, build_model_func_for_configfrom deeptutor.services.llm.config import LLMConfig@@ -80,7 +80,7 @@ async def test_client_get_model_func_uses_factory(monkeypatch: MonkeyPatch) -> Ncaptured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)func = client.get_model_func()result = await func(@@ -90,6 +90,7 @@ async def test_client_get_model_func_uses_factory(monkeypatch: MonkeyPatch) -> N)assert result == "ok"+ assert captured["config"] is configassert captured["prompt"] == "hello"assert captured["system_prompt"] == "sys"assert captured["messages"] == [@@ -113,7 +114,7 @@ async def test_client_get_model_func_empty_history_uses_prompt(captured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)func = client.get_model_func()result = await func("hello", system_prompt="sys", history_messages=[])@@ -138,7 +139,7 @@ async def test_client_get_model_func_explicit_messages_override_prompt(captured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)messages = [{"role": "user", "content": "from messages"}]func = client.get_model_func()@@ -160,7 +161,7 @@ async def test_client_get_vision_model_func_uses_factory(monkeypatch: MonkeyPatccaptured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)func = client.get_vision_model_func()result = await func(@@ -173,3 +174,27 @@ async def test_client_get_vision_model_func_uses_factory(monkeypatch: MonkeyPatcassert captured["prompt"] == "hello"assert captured["messages"] == [{"role": "user", "content": "hi"}]assert captured["image_data"] == "abc123"+++async def test_explicit_config_model_func_does_not_mutate_process_environment(+ monkeypatch: MonkeyPatch,+) -> None:+ config = LLMConfig(+ model="snapshot-model",+ api_key="snapshot-key",+ base_url="https://snapshot.example.com/v1",+ )+ monkeypatch.setenv("OPENAI_API_KEY", "global-key")+ monkeypatch.setenv("OPENAI_BASE_URL", "https://global.example.com/v1")++ async def _fake_complete(**kwargs: object) -> str:+ assert kwargs["config"] is config+ return "ok"++ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)++ func = build_model_func_for_config(config, allow_multimodal=False)+ assert await func("hello") == "ok"+ assert __import__("os").environ["OPENAI_API_KEY"] == "global-key"+ assert __import__("os").environ["OPENAI_BASE_URL"] == "https://global.example.com/v1"diff --git a/tests/services/llm/test_factory_provider_exec.py b/tests/services/llm/test_factory_provider_exec.pyindex 7234fccb3..39e4c2b55 100644--- a/tests/services/llm/test_factory_provider_exec.py+++ b/tests/services/llm/test_factory_provider_exec.py@@ -7,7 +7,7 @@ from typing import Anyimport pytestfrom deeptutor.services.llm.config import LLMConfig-from deeptutor.services.llm.factory import complete, stream+from deeptutor.services.llm.factory import complete, complete_with_config, streamfrom deeptutor.services.llm.provider_core.base import LLMResponse@@ -26,6 +26,10 @@ class _FakeProvider:self.stream_response = stream_response or LLMResponse(content=stream_chunk)self.stream_chunk = stream_chunkself.reasoning_chunk = reasoning_chunk+ self.closed = 0++ async def aclose(self) -> None:+ self.closed += 1async def chat_with_retry(self, **kwargs: Any) -> LLMResponse:self.complete_kwargs = kwargs@@ -155,6 +159,42 @@ async def test_explicit_call_inherits_matching_profile_headers_and_reasoning(assert provider.complete_kwargs["reasoning_effort"] == "minimal"+async def test_complete_with_config_never_resolves_or_merges_global_config(monkeypatch) -> None:+ snapshot = _make_cfg(extra_headers={}, reasoning_effort=None)+ provider = _FakeProvider()+ captured_config: dict[str, LLMConfig] = {}++ def _unexpected_resolver(**_kwargs: Any):+ raise AssertionError("explicit config path must not resolve global config")++ def _fake_build_isolated_provider(config: LLMConfig):+ captured_config["config"] = config+ return provider++ monkeypatch.setattr("deeptutor.services.llm.factory._resolve_call_config", _unexpected_resolver)+ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", _unexpected_resolver)+ monkeypatch.setattr("deeptutor.services.llm.factory._resolve_provider_spec", lambda **_: None)+ monkeypatch.setattr(+ "deeptutor.services.llm.factory.build_isolated_provider",+ _fake_build_isolated_provider,+ )++ assert await complete_with_config(snapshot, "hello") == "ok"+ assert captured_config["config"] is snapshot+ assert captured_config["config"].extra_headers == {}+ assert provider.complete_kwargs["reasoning_effort"] is None+ assert provider.closed == 1+++async def test_complete_with_config_rejects_identity_overrides() -> None:+ snapshot = _make_cfg()++ with pytest.raises(TypeError, match="reasoning_effort"):+ await complete_with_config(snapshot, "hello", reasoning_effort="high")++@pytest.mark.asyncioasync def test_stream_does_not_replay_reasoning_as_final_content(monkeypatch) -> None:cfg = _make_cfg()diff --git a/tests/services/llm/test_openai_compat_responses_fallback.py b/tests/services/llm/test_openai_compat_responses_fallback.pynew file mode 100644index 000000000..deb75d4e1--- /dev/null+++ b/tests/services/llm/test_openai_compat_responses_fallback.py@@ -0,0 +1,113 @@+"""Tests for Responses-error fallback classification on the OpenAI-compatible provider."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from deeptutor.services.llm.provider_core.openai_compat_provider import (+ OpenAICompatProvider,+)+from deeptutor.services.provider_registry import find_by_name+++class _FakeHTTPError(Exception):+ def __init__(self, status_code: int, body: str) -> None:+ super().__init__(body)+ self.status_code = status_code+ self.body = body+++class TestResponsesReasoningReplayFallback:+ @pytest.mark.parametrize(+ "message",+ [+ "The reasoning_text in the thinking mode must be passed back to the API.",+ "The reasoning_content in the thinking mode must be passed back to the API.",+ ],+ )+ def test_deepseek_reasoning_replay_400_falls_back(self, message: str) -> None:+ exc = _FakeHTTPError(400, f"{{'message': '{message}', 'code': 'invalid_request_error'}}")+ assert OpenAICompatProvider._should_fallback_from_responses_error(exc) is True++ def test_unrelated_400_still_does_not_fall_back(self) -> None:+ exc = _FakeHTTPError(+ 400, "{'message': 'Invalid model id', 'code': 'invalid_request_error'}"+ )+ assert OpenAICompatProvider._should_fallback_from_responses_error(exc) is False++ @pytest.mark.parametrize(+ "message",+ [+ "reasoning_text is invalid",+ "thinking mode is unavailable",+ "The previous response must be passed back",+ ],+ )+ def test_partial_reasoning_markers_do_not_fall_back(self, message: str) -> None:+ exc = _FakeHTTPError(400, message)+ assert OpenAICompatProvider._should_fallback_from_responses_error(exc) is False++ def test_non_4xx_reasoning_error_does_not_fall_back(self) -> None:+ exc = _FakeHTTPError(+ 500,+ "The reasoning_text in the thinking mode must be passed back to the API.",+ )+ assert OpenAICompatProvider._should_fallback_from_responses_error(exc) is False++ @pytest.mark.asyncio+ async def test_automatic_responses_mode_retries_through_chat_completions(self) -> None:+ calls = {"responses": 0, "chat": 0}++ class FailingResponses:+ async def create(self, **_kwargs):+ calls["responses"] += 1+ raise _FakeHTTPError(+ 400,+ "The reasoning_text in the thinking mode must be passed back to the API.",+ )++ class SuccessfulChatCompletions:+ async def create(self, **_kwargs):+ calls["chat"] += 1+ message = SimpleNamespace(+ content="fallback answer",+ reasoning_content=None,+ reasoning=None,+ tool_calls=None,+ )+ return SimpleNamespace(+ choices=[SimpleNamespace(message=message, finish_reason="stop")],+ usage=None,+ )++ provider = OpenAICompatProvider(+ api_key="test-key",+ default_model="deepseek-v4-flash",+ spec=find_by_name("deepseek"),+ provider_name="deepseek",+ wire_api="auto",+ )+ provider._client = SimpleNamespace(+ responses=FailingResponses(),+ chat=SimpleNamespace(completions=SuccessfulChatCompletions()),+ )++ result = await provider.chat(+ messages=[{"role": "user", "content": "search"}],+ model="deepseek-v4-flash",+ tools=[+ {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ],+ )++ assert result.content == "fallback answer"+ assert calls == {"responses": 1, "chat": 1}diff --git a/tests/services/llm/test_provider_pool.py b/tests/services/llm/test_provider_pool.pyindex 6464abc90..be282f9ba 100644--- a/tests/services/llm/test_provider_pool.py+++ b/tests/services/llm/test_provider_pool.py@@ -59,6 +59,24 @@ async def test_runtime_provider_reuses_identical_config(monkeypatch) -> None:assert provider_factory.runtime_provider_pool_size() == 1+def test_isolated_provider_disables_environment_setup_and_skips_pool(monkeypatch) -> None:+ captured: dict[str, Any] = {}+ provider = _FakeProvider()++ def _build(config: LLMConfig, *, configure_env: bool = True) -> _FakeProvider:+ captured["config"] = config+ captured["configure_env"] = configure_env+ return provider++ monkeypatch.setattr(provider_factory, "_build_runtime_provider", _build)++ result = provider_factory.build_isolated_provider(_config())++ assert result is provider+ assert captured["configure_env"] is False+ assert provider_factory.runtime_provider_pool_size() == 0++@pytest.mark.asyncioasync def test_runtime_provider_pool_is_bounded_and_closes_evictions(monkeypatch) -> None:built: list[_FakeProvider] = []diff --git a/tests/services/model_selection/test_llm_selection.py b/tests/services/model_selection/test_llm_selection.pyindex b434fa9b9..343f25395 100644--- a/tests/services/model_selection/test_llm_selection.py+++ b/tests/services/model_selection/test_llm_selection.py@@ -27,6 +27,8 @@ def _catalog():"name": "Gemini Flash","model": "google/gemini-3-flash-preview","context_window": "1000000",+ "reasoning_effort": "high",+ "codex_supported_reasoning_levels": ["low", "high"],},{"id": "m2",@@ -59,6 +61,8 @@ def test_list_llm_options_is_redacted_and_marks_active_default():assert [o["model_id"] for o in payload["options"]] == ["m1", "m2", "m3"]assert payload["options"][0]["is_active_default"] is Trueassert payload["options"][0]["context_window"] == 1000000+ assert payload["options"][0]["reasoning_effort"] == "high"+ assert payload["options"][0]["supported_reasoning_efforts"] == ["low", "high"]assert "api_key" not in payload["options"][0]assert "base_url" not in payload["options"][0]assert "extra_headers" not in payload["options"][0]diff --git a/tests/services/rag/test_lightrag_indexing_policy.py b/tests/services/rag/test_lightrag_indexing_policy.pynew file mode 100644index 000000000..bed6ae302--- /dev/null+++ b/tests/services/rag/test_lightrag_indexing_policy.py@@ -0,0 +1,214 @@+from __future__ import annotations++import json+from pathlib import Path++import pytest++from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.rag.pipelines.lightrag import indexing_policy, storage+++def _user(tmp_path: Path) -> CurrentUser:+ return CurrentUser(+ id="user-1",+ username="person",+ role="user",+ scope=UserScope(kind="user", user_id="user-1", root=tmp_path / "workspace"),+ )+++def _config(*, key: str = "secret-a", reasoning: str | None = "high") -> LLMConfig:+ return LLMConfig(+ model="model-v1",+ api_key=key,+ base_url="https://name:[email protected]/v1?token=secret",+ binding="openai",+ provider_name="openai",+ api_version="2026-01-01",+ reasoning_effort=reasoning,+ extra_headers={"Authorization": "private"},+ )+++def _freeze(monkeypatch, tmp_path: Path, config: LLMConfig):+ monkeypatch.setattr(indexing_policy, "get_current_user_or_none", lambda: _user(tmp_path))+ monkeypatch.setattr(indexing_policy, "apply_allowed_llm_selection", lambda value: value)+ monkeypatch.setattr(+ indexing_policy, "resolve_llm_config_for_selection", lambda _selection: config+ )+ monkeypatch.setattr(indexing_policy, "supports_vision", lambda binding, model: True)+ return indexing_policy.freeze_snapshot(+ {"profile_id": "profile-1", "model_id": "model-1", "reasoning_effort": "high"}+ )+++def test_fingerprint_excludes_credentials_and_endpoint_secrets(monkeypatch, tmp_path: Path) -> None:+ first = _freeze(monkeypatch, tmp_path, _config(key="secret-a"))+ second = _freeze(monkeypatch, tmp_path, _config(key="secret-b"))++ assert first.fingerprint == second.fingerprint+ serialized = json.dumps(first.persisted_policy(), sort_keys=True)+ assert "secret" not in serialized+ assert "password" not in serialized+ assert "Authorization" not in serialized+ assert "user-1" not in serialized+ assert first.descriptor["endpoint"] == "https://example.test/v1"+++def test_reasoning_drift_changes_fingerprint_and_blocks_append(monkeypatch, tmp_path: Path) -> None:+ original = _freeze(monkeypatch, tmp_path, _config(reasoning="high"))+ drifted = _config(reasoning=None)+ monkeypatch.setattr(+ indexing_policy, "resolve_llm_config_for_selection", lambda _selection: drifted+ )++ with pytest.raises(indexing_policy.IndexingModelChangedError, match="full re-index"):+ indexing_policy.snapshot_from_persisted(original.persisted_policy())+++def test_reasoning_none_and_literal_none_have_distinct_identity(+ monkeypatch, tmp_path: Path+) -> None:+ unset = _freeze(monkeypatch, tmp_path, _config(reasoning=None))+ literal_none = _freeze(monkeypatch, tmp_path, _config(reasoning="none"))++ assert unset.fingerprint != literal_none.fingerprint+ assert unset.descriptor["reasoning_effort"] is None+ assert literal_none.descriptor["reasoning_effort"] == "none"+++def test_vision_capability_drift_changes_fingerprint_and_blocks_append(+ monkeypatch, tmp_path: Path+) -> None:+ original = _freeze(monkeypatch, tmp_path, _config())+ assert original.vision_available is True+ assert original.descriptor["vision_available"] is True+ monkeypatch.setattr(indexing_policy, "supports_vision", lambda _binding, _model: False)++ with pytest.raises(indexing_policy.IndexingModelChangedError, match="full re-index"):+ indexing_policy.snapshot_from_persisted(original.persisted_policy())+++def test_published_policy_wins_over_residual_pending(tmp_path: Path) -> None:+ kb_dir = tmp_path / "kb"+ version = kb_dir / "version-1"+ version.mkdir(parents=True)+ (version / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ published = {+ "policy": "pinned",+ "selection": {"profile_id": "published", "model_id": "model"},+ "fingerprint": "a" * 64,+ }+ (version / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,+ "parser_bridge_schema": 1,+ "state": "published",+ "indexing_policy": published,+ }+ ),+ encoding="utf-8",+ )+ (tmp_path / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "pending_indexing_policy": {+ "policy": "pending_pinned",+ "selection": {"profile_id": "pending", "model_id": "model"},+ },+ }+ }+ }+ ),+ encoding="utf-8",+ )++ assert (+ indexing_policy.effective_policy(kb_dir, base_dir=str(tmp_path), kb_name="kb") == published+ )+++def test_owner_bound_model_requires_explicit_scope(monkeypatch) -> None:+ monkeypatch.setattr(indexing_policy, "get_current_user_or_none", lambda: None)+ monkeypatch.setattr(indexing_policy, "apply_allowed_llm_selection", lambda value: value)+ monkeypatch.setattr(+ indexing_policy,+ "resolve_llm_config_for_selection",+ lambda _selection: LLMConfig(+ model="gpt",+ api_key="",+ binding="openai_codex",+ provider_name="openai_codex",+ ),+ )++ with pytest.raises(indexing_policy.IndexingPolicyError, match="explicit initiating user"):+ indexing_policy.freeze_snapshot({"profile_id": "personal", "model_id": "gpt"})+++def test_default_snapshot_prefers_released_lightrag_selection(monkeypatch) -> None:+ from deeptutor.services.rag.pipelines.lightrag import config++ selection = {"profile_id": "dedicated", "model_id": "indexer"}+ expected = object()+ calls: list[tuple[object, str | None, bool]] = []+ monkeypatch.setattr(config, "lightrag_indexing_selection_from_settings", lambda: selection)+ monkeypatch.setattr(+ indexing_policy,+ "freeze_snapshot",+ lambda value, *, policy=None, require_explicit_user=True: (+ calls.append((value, policy, require_explicit_user)) or expected+ ),+ )++ assert indexing_policy.freeze_default_snapshot() is expected+ assert calls == [(selection, indexing_policy.POLICY_PINNED, False)]+++def test_default_snapshot_rejects_unreadable_released_setting(monkeypatch) -> None:+ from deeptutor.services.rag.pipelines.lightrag import config++ def fail():+ raise OSError("settings unreadable")++ monkeypatch.setattr(config, "lightrag_indexing_selection_from_settings", fail)++ with pytest.raises(indexing_policy.IndexingPolicyError, match="could not be resolved"):+ indexing_policy.freeze_default_snapshot()+++def test_latest_published_root_ignores_newer_unpublished_candidate(tmp_path: Path) -> None:+ kb_dir = tmp_path / "kb"+ published = kb_dir / "version-1"+ candidate = kb_dir / "version-2"+ for root in (published, candidate):+ root.mkdir(parents=True)+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ (published / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,+ "parser_bridge_schema": 1,+ "state": "published",+ }+ ),+ encoding="utf-8",+ )++ assert storage.latest_published_root(kb_dir) == publisheddiff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.pyindex 3e82371ef..a1dc03be0 100644--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@ -10,11 +10,17 @@ import typesimport pytest+from deeptutor.multi_user.context import (+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)+from deeptutor.multi_user.models import CurrentUser, UserScopefrom deeptutor.services.llm.exceptions import LLMAPIError, LLMAuthenticationErrorfrom deeptutor.services.parsing.types import ParsedDocumentfrom deeptutor.services.rag.factory import get_pipeline, list_pipelines, normalize_provider_namefrom deeptutor.services.rag.index_versioning import list_kb_versions-from deeptutor.services.rag.pipelines.lightrag import config, engine, storage+from deeptutor.services.rag.pipelines.lightrag import config, engine, indexing_policy, storagefrom deeptutor.services.rag.pipelines.lightrag.ingress import (IngressError,bundles_root,@@ -52,6 +58,13 @@ class _Bridge:return await value if inspect.isawaitable(value) else value+def _indexing_snapshot():+ return types.SimpleNamespace(+ vision_available=True,+ persisted_policy=lambda: {"policy": "pinned", "fingerprint": "a" * 64},+ )++def test_factory_routes_without_importing_optional_sdk(tmp_path: Path, monkeypatch) -> None:sys.modules.pop("lightrag", None)pipeline = get_pipeline("lightrag", kb_base_dir=str(tmp_path))@@ -83,71 +96,139 @@ def test_availability_checks_native_lightrag_module(monkeypatch) -> None:assert seen == ["lightrag"]-def test_lightrag_llm_selection_requires_both_catalog_ids(monkeypatch) -> None:- settings_cases = [+ ("settings", "expected"),+ [({}, None),- ({"llm_profile_id": "p", "llm_model_id": "m"}, {"profile_id": "p", "model_id": "m"}),- ({"llm_profile_id": "p", "llm_model_id": ""}, None),- ({"llm_profile_id": "", "llm_model_id": "m"}, None),- ]- for settings, expected in settings_cases:- monkeypatch.setattr(- "deeptutor.services.config.load_lightrag_settings",- lambda settings=settings: settings,- )- assert config.lightrag_llm_selection_from_settings() == expected+ (+ {"llm_profile_id": " profile ", "llm_model_id": " model "},+ {"profile_id": "profile", "model_id": "model"},+ ),+ ({"llm_profile_id": "profile", "llm_model_id": ""}, None),+ ],+)+def test_released_lightrag_query_selection_keeps_fallback_contract(+ monkeypatch, settings, expected+) -> None:+ monkeypatch.setattr("deeptutor.services.config.load_lightrag_settings", lambda: settings)+ assert config.lightrag_llm_selection_from_settings() == expected-def test_lightrag_llm_adapter_resolves_dedicated_catalog_selection(monkeypatch) -> None:- class Client:- def __init__(self, *, config, configure_env) -> None:- assert config is selected_config- assert configure_env is False- def get_model_func(self):- async def model_func(_prompt, **kwargs):- assert kwargs["max_retries"] == 0- return "ok"+def test_indexing_selection_rejects_partial_released_setting(monkeypatch) -> None:+ monkeypatch.setattr(+ "deeptutor.services.config.load_lightrag_settings",+ lambda: {"llm_profile_id": "profile", "llm_model_id": ""},+ )- return model_func+ with pytest.raises(ValueError, match="incomplete"):+ config.lightrag_indexing_selection_from_settings()+++def test_query_model_resolver_falls_back_only_when_selected_entry_is_missing(+ monkeypatch,+) -> None:+ selection = {"profile_id": "profile", "model_id": "model"}+ fallback = object()+ calls: list[object] = []+ monkeypatch.setattr(config, "lightrag_llm_selection_from_settings", lambda: selection)++ def resolve(value):+ calls.append(value)+ if value is selection:+ raise ValueError("missing")+ return fallback- selected_config = object()monkeypatch.setattr("deeptutor.services.model_selection.runtime.resolve_llm_config_for_selection",- lambda selection: selected_config,+ resolve,)- monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", Client)- adapter = config.build_llm_model_func(llm_selection={"profile_id": "p", "model_id": "m"})+ assert config.resolve_lightrag_query_llm_config() is fallback+ assert calls == [selection, None]+++def test_lightrag_llm_adapter_uses_explicit_snapshot_config(monkeypatch) -> None:+ def build_model(config, *, allow_multimodal):+ assert config is selected_config+ assert allow_multimodal is False++ async def model_func(_prompt, **kwargs):+ assert kwargs["max_retries"] == 0+ return "ok"++ return model_func++ selected_config = object()+ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build_model)++ adapter = config.build_llm_model_func(llm_config=selected_config)assert asyncio.run(adapter("prompt")) == "ok"-def test_lightrag_vision_adapter_resolves_dedicated_catalog_selection(monkeypatch) -> None:- class Client:- def __init__(self, *, config, configure_env) -> None:- assert config is selected_config- assert configure_env is False+def test_lightrag_vision_adapter_uses_explicit_snapshot_config(monkeypatch) -> None:+ def build_model(config, *, allow_multimodal):+ assert config is selected_config+ assert allow_multimodal is True- def get_vision_model_func(self):- async def model_func(_prompt, **kwargs):- assert kwargs["allow_image_fallback"] is False- assert kwargs["image_data"] == "sentinel"- return "ok"+ async def model_func(_prompt, **kwargs):+ assert kwargs["allow_image_fallback"] is False+ assert kwargs["image_data"] == "sentinel"+ return "ok"- return model_func+ return model_funcselected_config = object()- monkeypatch.setattr(- "deeptutor.services.model_selection.runtime.resolve_llm_config_for_selection",- lambda selection: selected_config,- )- monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", Client)+ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build_model)- adapter = config.build_vision_model_func(llm_selection={"profile_id": "p", "model_id": "m"})+ adapter = config.build_vision_model_func(llm_config=selected_config)assert asyncio.run(adapter("prompt", image_inputs=[{"base64": "sentinel"}])) == "ok"-def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs([email protected]("role", ["user", "admin"])[email protected]("fail", [False, True])+def test_explicit_adapter_installs_owner_scope_and_restores_ambient_scope(+ monkeypatch, tmp_path: Path, role: str, fail: bool+) -> None:+ owner = CurrentUser(+ id=f"owner-{role}",+ username=f"owner-{role}",+ role=role,+ scope=UserScope(kind=role, user_id=f"owner-{role}", root=tmp_path / "owner"),+ )+ ambient = CurrentUser(+ id="ambient",+ username="ambient",+ role="user",+ scope=UserScope(kind="user", user_id="ambient", root=tmp_path / "ambient"),+ )++ def build_model(_config, *, allow_multimodal):+ assert allow_multimodal is False++ async def model_func(_prompt, **_kwargs):+ assert get_current_user_or_none() == owner+ if fail:+ raise RuntimeError("provider failed")+ return "ok"++ return model_func++ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build_model)+ adapter = config.build_llm_model_func(llm_config=object(), owner=owner)+ token = set_current_user(ambient)+ try:+ if fail:+ with pytest.raises(RuntimeError, match="provider failed"):+ asyncio.run(adapter("prompt"))+ else:+ assert asyncio.run(adapter("prompt")) == "ok"+ assert get_current_user_or_none() == ambient+ finally:+ reset_current_user(token)+++def test_build_rag_keeps_indexing_snapshot_out_of_embedding_kwargs(monkeypatch, tmp_path: Path) -> None:"""The 1.6 native adapter must not pass LLM-only kwargs to embedding."""@@ -159,7 +240,12 @@ def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs(fake_lightrag = types.ModuleType("lightrag")fake_lightrag.__path__ = [] # type: ignore[attr-defined]fake_roles = types.ModuleType("lightrag.llm_roles")- fake_roles.RoleLLMConfig = object # type: ignore[attr-defined]++ class RoleLLMConfig:+ def __init__(self, **kwargs) -> None:+ self.__dict__.update(kwargs)++ fake_roles.RoleLLMConfig = RoleLLMConfig # type: ignore[attr-defined]monkeypatch.setitem(sys.modules, "lightrag", fake_lightrag)monkeypatch.setitem(sys.modules, "lightrag.llm_roles", fake_roles)monkeypatch.setattr(engine, "_require_exact_version", lambda: None)@@ -167,8 +253,9 @@ def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs(monkeypatch.setattr(engine, "_controlled_class", lambda: NativeLightRag)monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)- selection = {"profile_id": "profile-1", "model_id": "model-1"}- monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: selection)+ query_config = types.SimpleNamespace(binding="openai")+ monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)+ monkeypatch.setattr(indexing_policy, "cache_identity_for_config", lambda _config: "query-id")llm_calls: list[dict[str, object]] = []embedding_calls: list[object] = []@@ -185,7 +272,7 @@ def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs(rag = engine.build_rag(tmp_path)- assert llm_calls == [{"llm_selection": selection}]+ assert llm_calls == [{"llm_config": query_config}]assert embedding_calls == [None]assert rag.kwargs["embedding_func"] == "embedding"@@ -401,7 +488,9 @@ def test_preparse_runs_once_and_bundle_ignores_later_parser_drift(monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", ParseService)monkeypatch.setattr(config, "vision_model_available", lambda: False)pipeline = LightRagPipeline(kb_base_dir=str(tmp_path / "kb"))- staged, failures = pipeline._stage_documents(tmp_path / "version-1", [str(source)])+ staged, failures = pipeline._stage_documents(+ tmp_path / "version-1", [str(source)], vision_available=True+ )source.write_text("changed after staging", encoding="utf-8")manifest, bundle = load_verified_bundle(tmp_path / "version-1", "source.md")@@ -536,6 +625,207 @@ def test_flat_schema_two_candidate_fails_closed_until_published(tmp_path: Path)assert list_kb_versions(tmp_path)[0]["ready"] is True+def _write_published_version(root: Path, *, indexing_policy_value: dict | None = None) -> None:+ root.mkdir(parents=True)+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ (root / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,+ "parser_bridge_schema": 1,+ "state": "published",+ "indexing_policy": indexing_policy_value or {"policy": "legacy_unpinned"},+ }+ ),+ encoding="utf-8",+ )+++def test_rebuild_failure_before_index_output_keeps_previous_published_version(+ tmp_path: Path, monkeypatch+) -> None:+ kb_dir = tmp_path / "kb"+ old = kb_dir / "version-1"+ _write_published_version(old)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def fail_before_output(*_args, **_kwargs):+ raise RuntimeError("indexing failed")++ monkeypatch.setattr(pipeline, "_run_indexing", fail_before_output)++ with pytest.raises(RuntimeError, match="indexing failed"):+ asyncio.run(+ pipeline.initialize(+ "kb",+ [str(tmp_path / "doc.md")],+ indexing_snapshot=_indexing_snapshot(),+ )+ )++ assert storage.latest_published_root(kb_dir) == old+ assert not (kb_dir / "version-2").exists()+++def test_atomic_meta_failure_leaves_new_candidate_unpublished(tmp_path: Path, monkeypatch) -> None:+ kb_dir = tmp_path / "kb"+ old = kb_dir / "version-1"+ _write_published_version(old)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def finish_index(root: Path, *_args, **_kwargs):+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"new": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ return BatchOutcome(+ requested=1,+ accepted=1,+ processed=("doc.md",),+ indexing_policy={"policy": "legacy_unpinned"},+ )++ def fail_meta(*_args, **_kwargs):+ raise OSError("atomic publication failed")++ monkeypatch.setattr(pipeline, "_run_indexing", finish_index)+ monkeypatch.setattr(storage, "write_meta", fail_meta)++ with pytest.raises(OSError, match="atomic publication failed"):+ asyncio.run(+ pipeline.initialize(+ "kb",+ [str(tmp_path / "doc.md")],+ indexing_snapshot=_indexing_snapshot(),+ )+ )++ candidate = kb_dir / "version-2"+ assert candidate.is_dir()+ assert not (candidate / "meta.json").exists()+ assert storage.latest_published_root(kb_dir) == old+++def test_append_metadata_refresh_failure_preserves_published_success(+ tmp_path: Path, monkeypatch+) -> None:+ kb_dir = tmp_path / "kb"+ published = kb_dir / "version-1"+ _write_published_version(+ published,+ indexing_policy_value={+ "policy": "pinned",+ "selection": {"profile_id": "profile", "model_id": "model"},+ "fingerprint": "a" * 64,+ },+ )+ original_meta = (published / "meta.json").read_bytes()+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def finish_index(*_args, **_kwargs):+ return BatchOutcome(+ requested=1,+ accepted=1,+ processed=("doc.md",),+ indexing_policy={"policy": "legacy_unpinned"},+ )++ monkeypatch.setattr(pipeline, "_run_indexing", finish_index)+ monkeypatch.setattr(+ indexing_policy,+ "snapshot_from_persisted",+ lambda _policy: _indexing_snapshot(),+ )+ monkeypatch.setattr(+ storage,+ "write_meta",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("metadata unavailable")),+ )++ assert asyncio.run(pipeline.add_documents("kb", [str(tmp_path / "doc.md")])) is True+ assert (published / "meta.json").read_bytes() == original_meta+++def test_append_rejects_legacy_unpinned_index_before_mutation(tmp_path: Path, monkeypatch) -> None:+ published = tmp_path / "kb" / "version-1"+ _write_published_version(published)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def unexpected(*_args, **_kwargs):+ raise AssertionError("legacy append must not reach indexing")++ monkeypatch.setattr(pipeline, "_run_indexing", unexpected)++ with pytest.raises(indexing_policy.IndexingModelChangedError, match="full re-index"):+ asyncio.run(pipeline.add_documents("kb", [str(tmp_path / "doc.md")]))+++def test_append_rejects_explicit_indexing_snapshot_before_mutation(+ tmp_path: Path, monkeypatch+) -> None:+ published = tmp_path / "kb" / "version-1"+ _write_published_version(published)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def unexpected(*_args, **_kwargs):+ raise AssertionError("append must not reach indexing")++ monkeypatch.setattr(pipeline, "_run_indexing", unexpected)++ with pytest.raises(indexing_policy.IndexingPolicyError, match="full re-index"):+ asyncio.run(+ pipeline.add_documents(+ "kb",+ [str(tmp_path / "doc.md")],+ indexing_snapshot=_indexing_snapshot(),+ )+ )+++def test_pending_policy_drift_fails_before_creating_a_version(tmp_path: Path, monkeypatch) -> None:+ kb_dir = tmp_path / "kb"+ kb_dir.mkdir()+ (tmp_path / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "pending_indexing_policy": {+ "policy": "pending_pinned",+ "selection": {"profile_id": "profile", "model_id": "model"},+ "fingerprint": "a" * 64,+ },+ }+ }+ }+ ),+ encoding="utf-8",+ )+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ def changed(_policy):+ raise indexing_policy.IndexingModelChangedError("reindex required")++ monkeypatch.setattr(indexing_policy, "snapshot_from_persisted", changed)++ with pytest.raises(indexing_policy.IndexingModelChangedError):+ asyncio.run(pipeline.initialize("kb", [str(tmp_path / "doc.md")]))++ assert not any(kb_dir.glob("version-*"))++def test_schema_two_metadata_without_processed_workspace_output_is_not_ready(tmp_path: Path,) -> None:@@ -616,8 +906,28 @@ def test_indexing_initializes_processes_reconciles_and_finalizes(rag = Rag()pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args: ([staged], {}))- monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: rag)+ snapshot = _indexing_snapshot()+ freeze_calls = 0++ def freeze_default():+ nonlocal freeze_calls+ freeze_calls += 1+ return snapshot++ def stage(*_args, **kwargs):+ assert kwargs["vision_available"] is True+ return [staged], {}++ def build(*_args, **kwargs):+ assert kwargs["indexing_snapshot"] is snapshot+ return rag++ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.pipeline.freeze_default_snapshot",+ freeze_default,+ )+ monkeypatch.setattr(pipeline, "_stage_documents", stage)+ monkeypatch.setattr(engine, "build_rag", build)async def initialize(_rag):events.append("initialize")@@ -637,6 +947,8 @@ def test_indexing_initializes_processes_reconciles_and_finalizes(outcome = asyncio.run(pipeline._run_indexing(tmp_path, ["doc.pdf"], None))assert outcome.complete is True+ assert freeze_calls == 1+ assert outcome.indexing_policy == {"policy": "pinned", "fingerprint": "a" * 64}assert events == ["initialize", "enqueue", "process", ("finalize", False)]@@ -660,7 +972,7 @@ def test_partial_failure_is_typed_and_finalizes_with_cancellation(}pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args: ([staged], {}))+ monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args, **_kwargs: ([staged], {}))monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: Rag())async def no_op(*_args, **_kwargs):@@ -677,7 +989,7 @@ def test_partial_failure_is_typed_and_finalizes_with_cancellation(monkeypatch.setattr(engine, "finalize", finalize)with pytest.raises(LightRagBatchError) as caught:- asyncio.run(pipeline._run_indexing(tmp_path, ["bad.pdf"], None))+ asyncio.run(pipeline._run_indexing(tmp_path, ["bad.pdf"], None, _indexing_snapshot()))assert caught.value.outcome.failed == {"bad.pdf": "parse failed"}assert events == [("finalize", True)]@@ -710,7 +1022,7 @@ def test_pre_acceptance_failure_removes_ingress_and_allows_same_name_retry(pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- def stage(_working, paths):+ def stage(_working, paths, **_kwargs):staged = freeze_document(working,Path(paths[0]),@@ -738,12 +1050,14 @@ def test_pre_acceptance_failure_removes_ingress_and_allows_same_name_retry(monkeypatch.setattr(engine, "finalize", finalize)with pytest.raises(RuntimeError, match=failure_stage):- asyncio.run(pipeline._run_indexing(working, [str(source)], None))+ asyncio.run(pipeline._run_indexing(working, [str(source)], None, _indexing_snapshot()))assert not (pending_root(working) / "doc.md").exists()assert not (bundles_root(working) / "doc.md.bundle").exists()attempt = 1- outcome = asyncio.run(pipeline._run_indexing(working, [str(source)], None))+ outcome = asyncio.run(+ pipeline._run_indexing(working, [str(source)], None, _indexing_snapshot())+ )assert outcome.complete is True@@ -768,7 +1082,7 @@ def test_enqueue_partial_commit_removes_only_confirmed_unaccepted_ingress(pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- def stage(_working, paths):+ def stage(_working, paths, **_kwargs):return [freeze_document(working,@@ -792,7 +1106,14 @@ def test_enqueue_partial_commit_removes_only_confirmed_unaccepted_ingress(monkeypatch.setattr(engine, "finalize", no_op)with pytest.raises(RuntimeError, match="partially committed"):- asyncio.run(pipeline._run_indexing(working, [str(path) for path in sources], None))+ asyncio.run(+ pipeline._run_indexing(+ working,+ [str(path) for path in sources],+ None,+ _indexing_snapshot(),+ )+ )assert len(status_reads) == 1assert status_reads[0][1] is True@@ -819,7 +1140,7 @@ def test_enqueue_status_read_failure_retains_all_ingress(tmp_path: Path, monkeyppipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- def stage(_working, paths):+ def stage(_working, paths, **_kwargs):return [freeze_document(working,@@ -841,7 +1162,7 @@ def test_enqueue_status_read_failure_retains_all_ingress(tmp_path: Path, monkeypmonkeypatch.setattr(engine, "finalize", no_op)with pytest.raises(ValueError, match="enqueue failed"):- asyncio.run(pipeline._run_indexing(working, [str(source)], None))+ asyncio.run(pipeline._run_indexing(working, [str(source)], None, _indexing_snapshot()))assert (pending_root(working) / "doc.md").is_file()assert (bundles_root(working) / "doc.md.bundle").is_dir()@@ -866,7 +1187,7 @@ def test_public_initial_ingestion_retains_uncertain_ingress(pipeline = LightRagPipeline(kb_base_dir=str(tmp_path / "knowledge-bases"))- def stage(working, paths):+ def stage(working, paths, **_kwargs):nonlocal staged_workingstaged_working = workingreturn [@@ -891,7 +1212,16 @@ def test_public_initial_ingestion_retains_uncertain_ingress(monkeypatch.setattr(engine, "finalize", no_op)with pytest.raises(ValueError, match="original enqueue failure"):- asyncio.run(getattr(pipeline, operation)("kb", [str(source)]))+ asyncio.run(+ getattr(pipeline, operation)(+ "kb",+ [str(source)],+ indexing_snapshot=types.SimpleNamespace(+ vision_available=True,+ persisted_policy=lambda: {"policy": "legacy_unpinned"},+ ),+ )+ )assert staged_working is not Noneassert (pending_root(staged_working) / "doc.md").is_file()@@ -940,7 +1270,12 @@ def test_append_rejects_corrupt_or_unpublished_existing_version(monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)with pytest.raises(LightRagNeedsReindexError, match="unpublished, or corrupt"):- asyncio.run(pipeline.add_documents("kb", [str(tmp_path / "new.md")]))+ asyncio.run(+ pipeline.add_documents(+ "kb",+ [str(tmp_path / "new.md")],+ )+ )assert not (tmp_path / "kb" / "version-2").exists()assert {@@ -954,11 +1289,7 @@ def test_search_failure_is_not_reported_as_empty_success(tmp_path: Path, monkeyproot = tmp_path / "version-1"root.mkdir()pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- monkeypatch.setattr(- "deeptutor.services.rag.pipelines.lightrag.pipeline.resolve_storage_dir_for_read",- lambda *_args: root,- )- monkeypatch.setattr(storage, "meta_is_native_published", lambda _root: True)+ monkeypatch.setattr(storage, "latest_published_root", lambda _kb_dir: root)monkeypatch.setattr(pipeline, "_resolve_mode", lambda *_args: "hybrid")monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: object())diff --git a/tests/services/rag/test_lightrag_settings_wiring.py b/tests/services/rag/test_lightrag_settings_wiring.pyindex a72c2ca99..4b9f7ad0d 100644--- a/tests/services/rag/test_lightrag_settings_wiring.py+++ b/tests/services/rag/test_lightrag_settings_wiring.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport importlib.utilfrom pathlib import Path+import typesimport pytest@@ -21,12 +22,17 @@ class _NativeLightRag:def _stub_build(monkeypatch) -> None:+ query_config = types.SimpleNamespace(binding="openai")monkeypatch.setattr(engine, "_require_exact_version", lambda: None)monkeypatch.setattr(engine, "_register_parser", lambda: None)monkeypatch.setattr(engine, "_controlled_class", lambda: _NativeLightRag)monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: "llm")monkeypatch.setattr(engine, "build_embedding_func", lambda **_kwargs: "embedding")- monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: None)+ monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.cache_identity_for_config",+ lambda _config: "query-fingerprint",+ )def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path: Path) -> None:@@ -51,15 +57,15 @@ def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path:assert rag.kwargs["llm_model_max_async"] == 8assert rag.kwargs["entity_extract_max_gleaning"] == 2assert rag.kwargs["vlm_process_enable"] is False- assert "role_llm_configs" not in rag.kwargs+ assert rag.kwargs["llm_model_name"] == "query-fingerprint"+ assert set(rag.kwargs["role_llm_configs"]) == {"keyword", "query"}-def test_dedicated_selection_reaches_llm_but_not_embedding_adapter(+def test_global_dedicated_selection_drives_query_roles_not_embedding(monkeypatch, tmp_path: Path) -> None:_stub_build(monkeypatch)- selection = {"profile_id": "profile-1", "model_id": "model-1"}- monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: selection)+ query_config = types.SimpleNamespace(binding="dedicated")llm_calls: list[dict[str, object]] = []embedding_calls: list[dict[str, object]] = []@@ -73,12 +79,13 @@ def test_dedicated_selection_reaches_llm_but_not_embedding_adapter(monkeypatch.setattr(engine, "build_llm_model_func", build_llm)monkeypatch.setattr(engine, "build_embedding_func", build_embedding)+ monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)engine.build_rag(tmp_path)- assert llm_calls == [{"llm_selection": selection}]+ assert llm_calls == [{"llm_config": query_config}]assert embedding_calls == [{}]@@ -88,8 +95,59 @@ def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)- rag = engine.build_rag(tmp_path, enable_vlm=True)+ snapshot = types.SimpleNamespace(+ config=types.SimpleNamespace(binding="openai"),+ owner=object(),+ descriptor={"endpoint": "https://example.test/v1"},+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.cache_identity",+ lambda _snapshot: "snapshot-fingerprint",+ )++ rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=snapshot)role = rag.kwargs["role_llm_configs"]["vlm"]assert role.func == "vision"assert rag.kwargs["vlm_process_enable"] is True+++def test_snapshot_routes_only_extract_and_vlm_while_query_base_stays_global(+ monkeypatch, tmp_path: Path+) -> None:+ _stub_build(monkeypatch)+ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)+ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)+ llm_calls: list[dict[str, object]] = []+ vision_calls: list[dict[str, object]] = []++ def build_llm(**kwargs):+ llm_calls.append(kwargs)+ return f"llm-{len(llm_calls)}"++ def build_vision(**kwargs):+ vision_calls.append(kwargs)+ return "vision"++ monkeypatch.setattr(engine, "build_llm_model_func", build_llm)+ monkeypatch.setattr(engine, "build_vision_model_func", build_vision)+ snapshot = types.SimpleNamespace(+ config=types.SimpleNamespace(binding="openai"),+ owner=object(),+ descriptor={"endpoint": "https://example.test/v1"},+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.cache_identity",+ lambda _snapshot: "snapshot-fingerprint",+ )++ rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=snapshot)++ assert "llm_config" in llm_calls[0]+ assert llm_calls[1] == {"llm_config": snapshot.config, "owner": snapshot.owner}+ assert vision_calls == [{"llm_config": snapshot.config, "owner": snapshot.owner}]+ assert rag.kwargs["llm_model_func"] == "llm-1"+ assert rag.kwargs["role_llm_configs"]["extract"].func == "llm-2"+ assert rag.kwargs["role_llm_configs"]["vlm"].func == "vision"+ assert rag.kwargs["role_llm_configs"]["keyword"].func == "llm-1"+ assert rag.kwargs["role_llm_configs"]["query"].func == "llm-1"diff --git a/tests/services/search/test_web_search_runtime.py b/tests/services/search/test_web_search_runtime.pyindex 88ce50cd2..aceaa4e44 100644--- a/tests/services/search/test_web_search_runtime.py+++ b/tests/services/search/test_web_search_runtime.py@@ -6,10 +6,37 @@ import pytestfrom deeptutor.services.config.provider_runtime import ResolvedSearchConfigfrom deeptutor.services.search import web_search-from deeptutor.services.search.source_filter import filter_web_search_response+from deeptutor.services.search.source_filter import (+ EDUCATIONAL_TRUSTED_DOMAINS,+ filter_web_search_response,+ settings_from_config,+)from deeptutor.services.search.types import Citation, SearchResult, WebSearchResponse+def _expected_source_filter(+ *,+ removed_citations: int = 0,+ removed_search_results: int = 0,+ rejected_hosts: list[str] | None = None,+ rejected_reasons: list[str] | None = None,+ answer_invalidated: bool = False,+ content_filtering: bool = True,+ moderation_enabled: bool = False,+ educational_trusted_domains: bool = False,+) -> dict:+ return {+ "removed_citations": removed_citations,+ "removed_search_results": removed_search_results,+ "rejected_hosts": rejected_hosts or [],+ "rejected_reasons": rejected_reasons or [],+ "answer_invalidated": answer_invalidated,+ "content_filtering": content_filtering,+ "moderation_enabled": moderation_enabled,+ "educational_trusted_domains": educational_trusted_domains,+ }++class _FakeProvider:def __init__(self, name: str, supports_answer: bool = False):self.name = name@@ -286,12 +313,16 @@ def test_source_filter_removes_unsafe_references_and_preserves_ids() -> None:assert [citation.id for citation in filtered.citations] == [2]assert [citation.reference for citation in filtered.citations] == ["[2]"]assert [result.title for result in filtered.search_results] == ["Safe"]- assert filtered.metadata["source_filter"] == {- "removed_citations": 2,- "removed_search_results": 1,- "rejected_hosts": ["example.com", "127.0.0.1"],- "answer_invalidated": False,- }+ assert filtered.metadata["source_filter"] == _expected_source_filter(+ removed_citations=2,+ removed_search_results=1,+ rejected_hosts=["example.com", "127.0.0.1"],+ rejected_reasons=[+ "unsupported_scheme",+ "embedded_credentials",+ "unsupported_port",+ ],+ )def test_source_filter_supports_blocked_and_trusted_domain_policies() -> None:@@ -360,12 +391,12 @@ def test_web_search_filters_provider_results_before_consolidation(monkeypatch) -assert "spam.example" not in result["answer"]assert "**[1] School**" in result["answer"]assert [row["url"] for row in result["search_results"]] == ["https://school.example/a"]- assert result["source_filter"] == {- "removed_citations": 1,- "removed_search_results": 1,- "rejected_hosts": ["spam.example"],- "answer_invalidated": False,- }+ assert result["source_filter"] == _expected_source_filter(+ removed_citations=1,+ removed_search_results=1,+ rejected_hosts=["spam.example"],+ rejected_reasons=["blocked_domain"],+ )def test_web_search_filters_answer_provider_citations_without_renumbering(monkeypatch) -> None:@@ -417,3 +448,211 @@ def test_web_search_filters_answer_provider_citations_without_renumbering(monkeyassert [citation["reference"] for citation in result["citations"]] == ["[2]"]assert result["source_filter"]["removed_citations"] == 1assert result["source_filter"]["answer_invalidated"] is True+++def test_source_filter_drops_unsafe_title_and_snippet_content() -> None:+ response = WebSearchResponse(+ query="math",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://lesson.example/algebra",+ title="Free porn tube clips",+ snippet="watch now",+ ),+ Citation(+ id=2,+ reference="[2]",+ url="https://lesson.example/geometry",+ title="Triangle congruence",+ snippet="SAS and ASA",+ ),+ ],+ search_results=[+ SearchResult(+ title="Online casino jackpots",+ url="https://lesson.example/casino",+ snippet="spin the wheel",+ ),+ SearchResult(+ title="Pythagorean theorem",+ url="https://lesson.example/pythagoras",+ snippet="a^2 + b^2 = c^2",+ ),+ ],+ )++ filtered = filter_web_search_response(response)++ assert [c.id for c in filtered.citations] == [2]+ assert [r.title for r in filtered.search_results] == ["Pythagorean theorem"]+ assert "unsafe_content" in filtered.metadata["source_filter"]["rejected_reasons"]+ assert filtered.metadata["source_filter"]["content_filtering"] is True+++def test_source_filter_content_filtering_can_be_disabled() -> None:+ response = WebSearchResponse(+ query="math",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://lesson.example/a",+ title="Free porn tube clips",+ snippet="nsfw",+ ),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(response, content_filtering=False)++ assert len(filtered.citations) == 1+ assert filtered.metadata["source_filter"]["content_filtering"] is False+ assert filtered.metadata["source_filter"]["removed_citations"] == 0+++def test_source_filter_educational_trusted_domains_are_opt_in() -> None:+ response = WebSearchResponse(+ query="history",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="https://en.wikipedia.org/wiki/Gravity"),+ Citation(id=2, reference="[2]", url="https://random.blog.example/post"),+ ],+ search_results=[],+ )++ # Without the educational preset, an empty trusted list means no allowlist.+ open_policy = filter_web_search_response(response)+ assert len(open_policy.citations) == 2+ assert open_policy.metadata["source_filter"]["educational_trusted_domains"] is False++ locked = filter_web_search_response(+ WebSearchResponse(+ query="history",+ answer="",+ provider="test",+ citations=[+ Citation(id=1, reference="[1]", url="https://en.wikipedia.org/wiki/Gravity"),+ Citation(id=2, reference="[2]", url="https://random.blog.example/post"),+ ],+ search_results=[],+ ),+ use_educational_trusted_domains=True,+ )+ assert [c.url for c in locked.citations] == ["https://en.wikipedia.org/wiki/Gravity"]+ assert locked.metadata["source_filter"]["educational_trusted_domains"] is True+ assert "untrusted_domain" in locked.metadata["source_filter"]["rejected_reasons"]+ assert "wikipedia.org" in EDUCATIONAL_TRUSTED_DOMAINS+++def test_source_filter_optional_moderation_uses_injected_requester() -> None:+ calls: list[list[str]] = []++ def _fake_moderation(texts: list[str], *, api_key: str) -> list[bool]:+ assert api_key == "sk-test"+ calls.append(texts)+ return ["flag this" in text.lower() for text in texts]++ response = WebSearchResponse(+ query="news",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://news.example/a",+ title="Ordinary headline",+ snippet="flag this please",+ ),+ Citation(+ id=2,+ reference="[2]",+ url="https://news.example/b",+ title="Keep me",+ snippet="classroom notes",+ ),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ use_moderation=True,+ moderation_api_key="sk-test",+ request_moderation=_fake_moderation,+ )++ assert [c.id for c in filtered.citations] == [2]+ assert filtered.metadata["source_filter"]["moderation_enabled"] is True+ assert "moderation_flagged" in filtered.metadata["source_filter"]["rejected_reasons"]+ assert len(calls) == 1+ assert len(calls[0]) == 2+++def test_source_filter_moderation_fails_open_on_errors() -> None:+ def _boom(texts: list[str], *, api_key: str) -> list[bool]:+ raise RuntimeError("moderation down")++ response = WebSearchResponse(+ query="news",+ answer="",+ provider="test",+ citations=[+ Citation(+ id=1,+ reference="[1]",+ url="https://news.example/a",+ title="Keep me",+ snippet="classroom notes",+ ),+ ],+ search_results=[],+ )++ filtered = filter_web_search_response(+ response,+ content_filtering=False,+ use_moderation=True,+ moderation_api_key="sk-test",+ request_moderation=_boom,+ )++ assert len(filtered.citations) == 1+ assert filtered.metadata["source_filter"]["removed_citations"] == 0+++def test_settings_from_config_defaults_and_educational_flag(monkeypatch) -> None:+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ monkeypatch.delenv("DEEPTUTOR_OPENAI_API_KEY", raising=False)++ defaults = settings_from_config({})+ assert defaults["enabled"] is True+ assert defaults["content_filtering"] is True+ assert defaults["use_educational_trusted_domains"] is False+ assert defaults["use_moderation"] is False+ assert defaults["moderation_api_key"] == ""++ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env")+ enabled = settings_from_config(+ {+ "source_filtering": {+ "use_moderation": True,+ "use_educational_trusted_domains": True,+ "content_filtering": False,+ }+ }+ )+ assert enabled["use_moderation"] is True+ assert enabled["moderation_api_key"] == "sk-from-env"+ assert enabled["use_educational_trusted_domains"] is True+ assert enabled["content_filtering"] is Falsediff --git a/tests/services/session/test_trace_memory.py b/tests/services/session/test_trace_memory.pynew file mode 100644index 000000000..78c46b012--- /dev/null+++ b/tests/services/session/test_trace_memory.py@@ -0,0 +1,231 @@+from __future__ import annotations++import asyncio+import json+import sqlite3+from types import SimpleNamespace++from deeptutor.services.session.event_preview import (+ MAX_LEGACY_EVENT_PAYLOAD_CHARS,+ compact_trace_preview,+)+from deeptutor.services.session.pocketbase_store import PocketBaseSessionStore+from deeptutor.services.session.sqlite_store import SQLiteSessionStore+++def test_preview_keeps_semantic_events_and_bounds_legacy_payloads() -> None:+ events = [+ {"type": "content", "content": "delta"},+ {+ "type": "tool_result",+ "content": "x" * (MAX_LEGACY_EVENT_PAYLOAD_CHARS + 10),+ "metadata": {},+ },+ {"type": "result", "metadata": {"summary": "ok"}},+ {"type": "done", "metadata": {"status": "completed"}},+ ]++ preview, truncated = compact_trace_preview(events)++ assert truncated is True+ assert events[1]["content"] == "x" * (MAX_LEGACY_EVENT_PAYLOAD_CHARS + 10)+ assert [event["type"] for event in preview] == ["tool_result", "result", "done"]+ assert len(preview[0]["content"]) == MAX_LEGACY_EVENT_PAYLOAD_CHARS + len("...[truncated]")+++def test_preview_prioritizes_the_terminal_tail() -> None:+ events = [{"type": "tool_call", "content": str(i)} for i in range(250)]+ events.append({"type": "done", "metadata": {"status": "completed"}})++ preview, truncated = compact_trace_preview(events)++ assert truncated is True+ assert len(preview) == 200+ assert preview[-1]["type"] == "done"+++def test_migration_backfills_assistant_message_link_from_legacy_done(tmp_path) -> None:+ path = tmp_path / "chat.db"+ store = SQLiteSessionStore(path)+ session = asyncio.run(store.ensure_session(None))+ turn = asyncio.run(store.begin_turn(session["id"], capability="chat"))+ asyncio.run(store.transition_turn(turn["id"], "completed"))+ second_turn = asyncio.run(store.begin_turn(session["id"], capability="chat"))+ message_id = asyncio.run(store.add_message(session["id"], "assistant", "answer"))+ second_message_id = asyncio.run(store.add_message(session["id"], "assistant", "second"))++ with sqlite3.connect(path) as conn:+ conn.execute(+ "UPDATE messages SET events_json = ? WHERE id = ?",+ (+ json.dumps(+ [+ {+ "type": "done",+ "turn_id": turn["id"],+ "metadata": {"assistant_message_id": message_id},+ }+ ]+ ),+ message_id,+ ),+ )+ conn.execute(+ "UPDATE messages SET events_json = ? WHERE id = ?",+ (+ json.dumps(+ [+ {+ "type": "done",+ "turn_id": second_turn["id"],+ "metadata": {"assistant_message_id": second_message_id},+ }+ ]+ ),+ second_message_id,+ ),+ )+ conn.execute("UPDATE turns SET assistant_message_id = NULL")+ conn.execute("DROP INDEX idx_turns_assistant_message")+ conn.execute("ALTER TABLE turns DROP COLUMN assistant_message_id")++ reopened = SQLiteSessionStore(path)+ linked = asyncio.run(reopened.get_turn(turn["id"]))+ assert linked is not None+ assert linked["assistant_message_id"] == message_id+ second_linked = asyncio.run(reopened.get_turn(second_turn["id"]))+ assert second_linked is not None+ assert second_linked["assistant_message_id"] == second_message_id+++def test_context_rehydrates_ask_user_from_canonical_turn_events(tmp_path) -> None:+ store = SQLiteSessionStore(tmp_path / "chat.db")+ session = asyncio.run(store.ensure_session(None))+ turn = asyncio.run(store.begin_turn(session["id"], capability="chat"))+ message_id = asyncio.run(store.add_message(session["id"], "assistant", "answer"))+ asyncio.run(+ store.append_turn_events(+ turn["id"],+ [+ {"type": "content", "content": "delta", "metadata": {}},+ {+ "type": "tool_result",+ "metadata": {"tool_metadata": {"ask_user": {"questions": []}}},+ },+ {"type": "progress", "metadata": {"ask_user_resolved": True}},+ ],+ )+ )+ asyncio.run(store.link_turn_message(turn["id"], message_id))++ context = asyncio.run(store.get_messages_for_context(session["id"]))++ assert [event["type"] for event in context[-1]["events"]] == [+ "tool_result",+ "progress",+ ]+++def test_session_preview_reads_a_bounded_number_of_canonical_rows(tmp_path, monkeypatch) -> None:+ store = SQLiteSessionStore(tmp_path / "chat.db")+ session = asyncio.run(store.ensure_session(None))+ turn = asyncio.run(store.begin_turn(session["id"], capability="chat"))+ message_id = asyncio.run(store.add_message(session["id"], "assistant", "answer"))+ asyncio.run(+ store.append_turn_events(+ turn["id"],+ [+ {"type": "tool_call", "content": f"call-{index}", "metadata": {}}+ for index in range(1_000)+ ],+ )+ )+ asyncio.run(store.link_turn_message(turn["id"], message_id))++ converted = 0+ original = store._turn_event_row_to_payload++ def count_conversion(row):+ nonlocal converted+ converted += 1+ return original(row)++ monkeypatch.setattr(store, "_turn_event_row_to_payload", count_conversion)+ detail = asyncio.run(store.get_session_with_messages(session["id"]))++ assert detail is not None+ message = detail["messages"][0]+ assert message["trace"]["total"] == 1_000+ assert message["trace"]["truncated"] is True+ assert len(message["events"]) == 200+ assert converted == 200+++def test_pocketbase_trace_uses_server_side_pagination(monkeypatch) -> None:+ events = [+ SimpleNamespace(+ id=f"event-{seq}",+ turn_id="turn-1",+ seq=seq,+ type="tool_call",+ source="chat",+ stage="",+ content=f"call-{seq}",+ metadata_json={},+ event_timestamp=float(seq),+ )+ for seq in range(1, 1_201)+ ]+ records = {+ "sessions": [SimpleNamespace(id="pb-session", session_id="session-1", user_id="u_ada")],+ "messages": [SimpleNamespace(id="message-1", session_id="session-1", role="assistant")],+ "turns": [+ SimpleNamespace(id="pb-turn", turn_id="turn-1", assistant_message_id="message-1")+ ],+ "turn_events": events,+ }+ full_event_reads = 0++ class Collection:+ def __init__(self, name: str) -> None:+ self.name = name++ def get_full_list(self, query_params=None):+ nonlocal full_event_reads+ if self.name == "turn_events":+ full_event_reads += 1+ return list(records[self.name])++ def get_list(self, page, per_page, query_params=None):+ rows = list(records[self.name])+ params = query_params or {}+ if self.name == "turn_events":+ marker = "seq>"+ filter_value = str(params.get("filter") or "")+ if marker in filter_value:+ after_seq = int(filter_value.rsplit(marker, 1)[1])+ rows = [row for row in rows if row.seq > after_seq]+ rows.sort(key=lambda row: row.seq, reverse=params.get("sort") == "-seq")+ start = (page - 1) * per_page+ return SimpleNamespace(items=rows[start : start + per_page], total_items=len(rows))++ class Client:+ def collection(self, name: str) -> Collection:+ return Collection(name)++ monkeypatch.setattr(+ "deeptutor.services.session.pocketbase_store._current_user_id",+ lambda: "u_ada",+ )+ monkeypatch.setattr("deeptutor.services.session.pocketbase_store._pb", lambda: Client())+ store = PocketBaseSessionStore()++ page = asyncio.run(store.get_message_trace("session-1", "message-1", after_seq=100, limit=50))++ assert page is not None+ assert [event["seq"] for event in page["events"]] == list(range(101, 151))+ assert page["total"] == 1_200+ assert page["last_seq"] == 1_200+ assert page["next_seq"] == 150+ assert page["complete"] is False+ assert full_event_reads == 0diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.pyindex 497cbd446..a1e6a4a8d 100644--- a/tests/services/session/test_turn_runtime.py+++ b/tests/services/session/test_turn_runtime.py@@ -15,6 +15,7 @@ from deeptutor.services.session.turn_runtime import (_format_followup_question_context,_format_selection_tutor_context,_narration_marker_call_id,+ _repair_chinese_emphasis_for_persistence,_resolve_selection_tutor_context,_should_capture_assistant_content,_stamp_ask_user_content_offset,@@ -118,6 +119,33 @@ class TestNarrationMarkerCallId:class TestAssemblePersistedAnswer:+ def test_repairs_chinese_emphasis_boundaries_before_persistence(self) -> None:+ assert (+ _repair_chinese_emphasis_for_persistence("中文*,重点*内容", "zh")+ == "中文 *,重点* 内容"+ )+ assert _repair_chinese_emphasis_for_persistence("**“你好”**啊", "zh-CN") == "**“你好”** 啊"+ assert _repair_chinese_emphasis_for_persistence("中文*,重点*", "en") == "中文*,重点*"++ def test_does_not_change_inner_whitespace_or_literal_stars(self) -> None:+ inputs = [+ "* 重点 *",+ "** 重点 **",+ "*重点 *",+ "** 重点**",+ "*重点 内容*",+ "前言 * 第一项 * 与 * 第二项 * 后记",+ "Use * as multiplication *",+ r"\* 重点 \*",+ "说明 * 这里不是完整强调,后面有 *正常内容*",+ ]+ for content in inputs:+ assert _repair_chinese_emphasis_for_persistence(content, "zh") == content++ def test_preserves_code_math_and_nested_emphasis(self) -> None:+ content = "`中文*,重点*`\n$中文*,重点*$\n中文***,重点***内容"+ assert _repair_chinese_emphasis_for_persistence(content, "zh") == content+def test_continuation_preserves_exact_visible_boundary(self) -> None:segments = [("round-part-1", "Part one. "),diff --git a/tests/services/test_app_update.py b/tests/services/test_app_update.pyindex 7b7711aef..3a2a009eb 100644--- a/tests/services/test_app_update.py+++ b/tests/services/test_app_update.py@@ -151,6 +151,7 @@ def test_detect_installation_keeps_source_and_docker_host_managed(assert app_update.detect_installation().mode == "docker"monkeypatch.setattr(app_update, "_running_in_container", lambda: False)+ monkeypatch.setattr(app_update, "_running_from_source_checkout", lambda: False)monkeypatch.setattr(app_update,"_distribution_direct_url",@@ -166,6 +167,33 @@ def test_detect_installation_keeps_source_and_docker_host_managed(assert installation.automatic_update is True+def test_detect_installation_prefers_source_checkout_when_metadata_is_shadowed(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ checkout_root = tmp_path / "DeepTutor"+ module_path = checkout_root / "deeptutor" / "services" / "app_update.py"+ module_path.parent.mkdir(parents=True)+ module_path.touch()+ (checkout_root / ".git").mkdir()+ (checkout_root / "pyproject.toml").write_text(+ '[project]\nname = "deeptutor"\n',+ encoding="utf-8",+ )++ monkeypatch.setattr(app_update, "__file__", str(module_path))+ monkeypatch.setattr(app_update, "_running_in_container", lambda: False)+ monkeypatch.setattr(app_update, "_distribution_direct_url", lambda: {})+ monkeypatch.setattr(app_update.sys, "prefix", str(tmp_path / "venv"))+ monkeypatch.setattr(app_update.sys, "base_prefix", str(tmp_path / "base"))++ installation = app_update.detect_installation()++ assert installation.mode == "source"+ assert installation.automatic_update is False+ assert installation.command == "git pull && pip install -e ."++def test_update_job_store_persists_trusted_lifecycle(tmp_path: Path) -> None:store = UpdateJobStore(tmp_path / "update")job = store.create(current_version="1.6.1", target_version="1.7.0")diff --git a/tests/services/test_github_source_path_containment.py b/tests/services/test_github_source_path_containment.pyindex 4242827da..e646addcc 100644--- a/tests/services/test_github_source_path_containment.py+++ b/tests/services/test_github_source_path_containment.py@@ -13,6 +13,8 @@ import asynciofrom dataclasses import dataclassfrom pathlib import Path+import pytest+from deeptutor.services.github_source import sync as sync_module@@ -93,3 +95,124 @@ def test_removal_of_an_escaping_path_leaves_the_target_alone(tmp_path: Path) ->assert sync_module._contained_dest(raw_dir, "../victim.md") is Noneassert victim.read_text(encoding="utf-8") == "keep me"+++def test_indexing_failure_propagates_and_retains_downloaded_raw_file(+ tmp_path: Path, monkeypatch+) -> None:+ raw_dir = tmp_path / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ client = _Client([_Entry("guide.md")])++ async def reject_indexing(_kb_name, _files, _base_dir):+ raise RuntimeError("indexing policy rejected")++ monkeypatch.setattr(sync_module, "_index_files", reject_indexing)++ with pytest.raises(RuntimeError, match="indexing policy rejected"):+ asyncio.run(+ sync_module._full_sync(+ client,+ "kb",+ raw_dir,+ "owner/repo",+ "main",+ "",+ "*.md",+ "new-sha",+ str(tmp_path),+ )+ )++ assert (raw_dir / "guide.md").read_bytes() == b"# owned\n"+++def test_failed_sync_does_not_advance_success_markers(tmp_path: Path, monkeypatch) -> None:+ class Client(_Client):+ async def get_latest_commit_sha(self, _repo, _branch):+ return "new-sha"++ class Manager:+ calls: list[dict] = []++ def __init__(self, *, base_dir):+ self.base_dir = base_dir++ def update_github_source_state(self, **kwargs):+ self.calls.append(kwargs)++ async def reject_indexing(_kb_name, _files, _base_dir):+ raise RuntimeError("indexing policy rejected")++ monkeypatch.setattr(sync_module, "_index_files", reject_indexing)+ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)+ source = {"id": "source-1", "repo": "owner/repo", "branch": "main"}++ result = asyncio.run(+ sync_module.sync_source(+ "kb",+ source,+ base_dir=str(tmp_path),+ client=Client([_Entry("guide.md")]),+ )+ )++ assert result.ok is False+ assert result.error == "indexing policy rejected"+ assert Manager.calls == [+ {+ "kb_name": "kb",+ "source_id": "source-1",+ "last_sync_status": "error",+ "last_sync_error": "indexing policy rejected",+ }+ ]+ assert "last_synced_sha" not in Manager.calls[0]+ assert "last_synced_at" not in Manager.calls[0]+ assert (tmp_path / "kb" / "raw" / "guide.md").is_file()+++def test_failed_sync_redacts_credentials_from_result_and_state(tmp_path: Path, monkeypatch) -> None:+ class Client(_Client):+ async def get_latest_commit_sha(self, _repo, _branch):+ return "new-sha"++ class Manager:+ calls: list[dict] = []++ def __init__(self, *, base_dir):+ self.base_dir = base_dir++ def update_github_source_state(self, **kwargs):+ self.calls.append(kwargs)++ async def reject_indexing(_kb_name, _files, _base_dir):+ raise RuntimeError(+ "token=private https://name:[email protected]/v1?api_key=private sk-secret"+ )++ monkeypatch.setattr(sync_module, "_index_files", reject_indexing)+ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)+ result = asyncio.run(+ sync_module.sync_source(+ "kb",+ {"id": "source-1", "repo": "owner/repo", "branch": "main"},+ base_dir=str(tmp_path),+ client=Client([_Entry("guide.md")]),+ )+ )++ assert "private" not in result.error+ assert "password" not in result.error+ assert "sk-secret" not in result.error+ assert Manager.calls[0]["last_sync_error"] == result.error+++def test_sync_error_redaction_fails_closed_for_malformed_urls() -> None:+ error = sync_module.redact_sync_error(+ RuntimeError("token=private https://user:[email protected]:not-a-port/v1")+ )++ assert "private" not in error+ assert "secret" not in error+ assert "[redacted-url]" in errordiff --git a/tests/services/test_github_source_sync_service.py b/tests/services/test_github_source_sync_service.pynew file mode 100644index 000000000..cd78009b9--- /dev/null+++ b/tests/services/test_github_source_sync_service.py@@ -0,0 +1,56 @@+from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.multi_user.context import (+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)+from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.github_source.sync_service import GitHubSourceSyncService+++async def test_periodic_github_sync_installs_owner_and_restores_ambient(+ monkeypatch, tmp_path: Path+) -> None:+ owner = CurrentUser(+ id="owner",+ username="owner",+ role="user",+ scope=UserScope(kind="user", user_id="owner", root=tmp_path / "owner"),+ )+ ambient = CurrentUser(+ id="ambient",+ username="ambient",+ role="user",+ scope=UserScope(kind="user", user_id="ambient", root=tmp_path / "ambient"),+ )+ source = {"id": "source", "enabled": True}++ class _Manager:+ def __init__(self, *, base_dir: str) -> None:+ assert base_dir == str(tmp_path / "kbs")++ def get_all_github_sources(self):+ return [("kb", source)]++ def update_github_source_state(self, **_kwargs) -> None:+ raise AssertionError("sync should succeed")++ async def _sync_source(**_kwargs) -> None:+ assert get_current_user_or_none() == owner++ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", _Manager)+ monkeypatch.setattr("deeptutor.services.github_source.sync.sync_source", _sync_source)+ service = GitHubSourceSyncService(base_dir=str(tmp_path / "kbs"), owner=owner)++ token = set_current_user(ambient)+ try:+ await service._sync_one_cycle()+ assert get_current_user_or_none() == ambient+ finally:+ reset_current_user(token)diff --git a/tests/services/test_hermes_remote_backend.py b/tests/services/test_hermes_remote_backend.pynew file mode 100644index 000000000..2513ce900--- /dev/null+++ b/tests/services/test_hermes_remote_backend.py@@ -0,0 +1,252 @@+"""Behavioral tests for the remote Hermes Connected Agents backend."""++from __future__ import annotations++from collections.abc import AsyncIterator+import json+from typing import Any++import anyio+import httpx+import pytest++from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.hermes_remote import (+ CONSULT_ORIGIN_INSTRUCTION,+ HermesRemoteBackend,+)+from deeptutor.services.subagent.types import EVENT_TEXT, EVENT_TOOL, EVENT_TOOL_RESULT+++class _BlockingStream(httpx.AsyncByteStream):+ def __init__(self, started: anyio.Event) -> None:+ self._started = started++ async def __aiter__(self) -> AsyncIterator[bytes]:+ self._started.set()+ await anyio.sleep_forever()+ yield b"" # pragma: no cover+++class _HermesTransport:+ def __init__(+ self,+ *,+ events: list[dict[str, Any]] | None = None,+ history: list[dict[str, Any]] | None = None,+ history_status: int = 200,+ ) -> None:+ self.events = events or []+ self.history = history or []+ self.history_status = history_status+ self.requests: list[httpx.Request] = []+ self.approvals: list[dict[str, Any]] = []+ self.stops: list[str] = []+ self.block_started = anyio.Event()+ self.blocking = False++ def __call__(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ path = request.url.path+ if request.method == "GET" and path == "/v1/capabilities":+ return httpx.Response(+ 200,+ json={+ "object": "hermes.api_server.capabilities",+ "model": "hermes-agent",+ "features": {+ "run_submission": True,+ "run_events_sse": True,+ "run_stop": True,+ "run_approval_response": True,+ "session_resources": True,+ },+ },+ )+ if request.method == "GET" and path.endswith("/messages"):+ if self.history_status != 200:+ return httpx.Response(self.history_status)+ return httpx.Response(200, json={"object": "list", "data": self.history})+ if request.method == "POST" and path == "/v1/runs":+ return httpx.Response(202, json={"run_id": "run-1", "status": "started"})+ if request.method == "POST" and path.endswith("/approval"):+ self.approvals.append(json.loads(request.content))+ return httpx.Response(200, json={"resolved": 1})+ if request.method == "POST" and path.endswith("/stop"):+ self.stops.append(path.rsplit("/", 2)[-2])+ return httpx.Response(200, json={"status": "stopping"})+ if request.method == "GET" and path.endswith("/events"):+ if self.blocking:+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ stream=_BlockingStream(self.block_started),+ )+ body = "".join(f"data: {json.dumps(event)}\n\n" for event in self.events)+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ content=body.encode(),+ )+ return httpx.Response(404)+++def _backend(+ transport: httpx.AsyncBaseTransport | _HermesTransport,+ *,+ auto_approve: bool = True,+) -> HermesRemoteBackend:+ actual = (+ httpx.MockTransport(transport) if isinstance(transport, _HermesTransport) else transport+ )+ return HermesRemoteBackend(+ config=BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ auto_approve=auto_approve,+ ),+ transport=actual,+ )+++async def test_detect_distinguishes_configuration_failures(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("TEST_HERMES_KEY", raising=False)+ missing_url = await HermesRemoteBackend(config=BackendConfig()).detect()+ missing_key = await HermesRemoteBackend(+ config=BackendConfig(base_url="http://hermes.test", api_key_env="TEST_HERMES_KEY"),+ ).detect()+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ invalid_url = await HermesRemoteBackend(+ config=BackendConfig(base_url="file:///etc/passwd", api_key_env="TEST_HERMES_KEY"),+ ).detect()+ invalid_key_env = await HermesRemoteBackend(+ config=BackendConfig(base_url="http://hermes.test", api_key_env="INVALID=NAME"),+ ).detect()++ def unauthorized(_: httpx.Request) -> httpx.Response:+ return httpx.Response(401)++ unauthorized_result = await _backend(httpx.MockTransport(unauthorized)).detect()++ def incompatible(_: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"unexpected": True})++ incompatible_result = await _backend(httpx.MockTransport(incompatible)).detect()++ def unreachable(_: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("offline")++ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ unreachable_result = await _backend(httpx.MockTransport(unreachable)).detect()++ assert missing_url.detail == "not_configured"+ assert missing_key.detail == "key_missing"+ assert invalid_url.detail == "invalid_base_url"+ assert invalid_key_env.detail == "invalid_key_env"+ assert unauthorized_result.detail == "unauthorized"+ assert incompatible_result.detail == "incompatible"+ assert unreachable_result.detail == "unreachable"+++async def test_consult_streams_text_tools_and_session_continuity(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(+ events=[+ {"event": "message.delta", "delta": "Hello "},+ {"event": "tool.started", "tool": "read", "preview": "notes"},+ {"event": "tool.completed", "tool": "read", "error": False},+ {"event": "message.delta", "delta": "world"},+ {"event": "run.completed", "output": "Hello world"},+ ],+ history=[+ *({"role": "user", "content": f"turn-{index}"} for index in range(42)),+ {"role": "tool", "content": "omit this tool row"},+ {"role": "user", "content": ""},+ {"role": "assistant", "content": "latest answer"},+ ],+ )+ backend = _backend(transport)+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ first = await backend.consult(+ "question",+ on_event=on_event,+ config=backend.config,+ )+ second = await backend.consult(+ "follow-up",+ on_event=on_event,+ session_id=first.session_id,+ config=BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ system_prompt="must not be repeated",+ ),+ )+ first_body = json.loads(transport.requests[0].content)++ second_body = json.loads(transport.requests[3].content)+ assert first.success is True+ assert first.final_text == "Hello world"+ assert first.session_id == "run-1"+ assert second.session_id == "run-1"+ assert first_body["instructions"] == CONSULT_ORIGIN_INSTRUCTION+ assert CONSULT_ORIGIN_INSTRUCTION in first_body["instructions"]+ assert second_body["session_id"] == "run-1"+ assert second_body["instructions"] == CONSULT_ORIGIN_INSTRUCTION+ assert len(second_body["conversation_history"]) == 40+ assert second_body["conversation_history"][0] == {"role": "user", "content": "turn-3"}+ assert second_body["conversation_history"][-1] == {+ "role": "assistant",+ "content": "latest answer",+ }+ assert all(row["role"] in {"user", "assistant"} for row in second_body["conversation_history"])+ assert all(row["content"] for row in second_body["conversation_history"])+ assert "must not be repeated" not in second_body["instructions"]+ assert [event.kind for event in emitted[:4]] == [+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ EVENT_TEXT,+ ]+ assert emitted[0].meta["merge_id"] == "hermes_remote:final"+++async def test_consult_prepends_custom_system_prompt_on_fresh_run(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(events=[{"event": "run.completed", "output": "done"}])+ backend = _backend(transport)++ async def on_event(_: Any) -> None:+ return None++ config = BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ system_prompt="custom instruction",+ model="hermes-agent",+ effort="high",+ )+ result = await backend.consult(+ "question",+ on_event=on_event,+ config=config,+ images=["/private/deeptutor/secret-image.png"],+ )+ body = json.loads(transport.requests[0].content)+ assert result.success is True+ assert body["instructions"].startswith("custom instruction")+ assert CONSULT_ORIGIN_INSTRUCTION in body["instructions"]+ assert body["model"] == "hermes-agent"+ assert body["model_options"]["reasoning_effort"] == "high"+ assert "secret-image.png" not in json.dumps(body)diff --git a/tests/services/test_hermes_remote_backend_lifecycle.py b/tests/services/test_hermes_remote_backend_lifecycle.pynew file mode 100644index 000000000..d5e9e788e--- /dev/null+++ b/tests/services/test_hermes_remote_backend_lifecycle.py@@ -0,0 +1,349 @@+"""Lifecycle and configuration tests for the remote Hermes backend."""++from __future__ import annotations++import json+from typing import Any++import anyio+import httpx+import pytest++from deeptutor.services.subagent.config import BackendConfig, settings_from_dict+from deeptutor.services.subagent.hermes_remote import HermesRemoteBackend+from deeptutor.services.subagent.hermes_remote_client import (+ HermesRemoteClient,+ HermesRemoteProtocolError,+)+from deeptutor.services.subagent.types import EVENT_ERROR, EVENT_LOG+from tests.services.test_hermes_remote_backend import _backend, _HermesTransport+++async def test_approval_is_denied_without_blocking(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(+ events=[+ {"event": "approval.request", "tool": "exec"},+ {"event": "run.completed", "output": "finished"},+ ],+ )+ backend = _backend(transport, auto_approve=False)+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is True+ assert result.final_text == "finished"+ assert transport.approvals == [{"choice": "deny"}]+ assert any(event.kind == EVENT_LOG and "denied" in event.text for event in emitted)+++async def test_consult_http_error_never_leaks_bearer(monkeypatch: pytest.MonkeyPatch) -> None:+ secret = "synthetic-secret"+ monkeypatch.setenv("TEST_HERMES_KEY", secret)++ def unauthorized(_: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text=f"invalid token {secret}")++ backend = _backend(httpx.MockTransport(unauthorized))+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is False+ assert emitted[-1].kind == EVENT_ERROR+ assert secret not in emitted[-1].text+ assert secret not in result.error+++async def test_cancellation_posts_stop_and_reraises(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport()+ transport.blocking = True+ backend = _backend(transport)+ cancellation: list[BaseException] = []++ async def on_event(_: Any) -> None:+ return None++ async def run_consult() -> None:+ try:+ await backend.consult("question", on_event=on_event, config=backend.config)+ except BaseException as exc: # noqa: BLE001 - assert cancellation propagation+ cancellation.append(exc)+ raise++ async with anyio.create_task_group() as group:+ group.start_soon(run_consult)+ await transport.block_started.wait()+ group.cancel_scope.cancel()++ assert cancellation+ assert isinstance(cancellation[0], anyio.get_cancelled_exc_class())+ assert transport.stops == ["run-1"]+++async def test_idle_timeout_stops_run(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport()+ transport.blocking = True+ backend = HermesRemoteBackend(+ config=BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ idle_timeout_seconds=0,+ ),+ transport=httpx.MockTransport(transport),+ )+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is False+ assert "idle_timeout" in result.error+ assert emitted[-1].kind == EVENT_ERROR+ assert transport.stops == ["run-1"]+++async def test_missing_session_history_starts_fresh(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(+ events=[{"event": "run.completed", "output": "fresh"}],+ history_status=404,+ )+ backend = _backend(transport)++ async def on_event(_: Any) -> None:+ return None++ config = BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ system_prompt="reapply this instruction",+ )+ result = await backend.consult(+ "question",+ on_event=on_event,+ session_id="session-gone",+ config=config,+ )+ body = json.loads(transport.requests[1].content)+ assert result.success is True+ assert result.session_id == "run-1"+ assert transport.requests[0].url.path == "/api/sessions/session-gone/messages"+ assert "session_id" not in body+ assert "x-hermes-session-id" not in transport.requests[1].headers+ assert "x-hermes-session" not in transport.requests[1].headers+ assert "conversation_history" not in body+ assert body["instructions"].startswith("reapply this instruction")+++def test_settings_persist_remote_fields_without_inline_secret() -> None:+ settings = settings_from_dict(+ {+ "backends": {+ "hermes_remote": {+ "base_url": " http://hermes.test ",+ "api_key_env": " TEST_HERMES_KEY ",+ "profile": "study",+ "idle_timeout_seconds": "42",+ "api_key": "must-never-persist",+ },+ },+ },+ )+ config = settings.backend("hermes_remote")+ serialized = settings.to_dict()["backends"]["hermes_remote"]+ assert config.base_url == "http://hermes.test"+ assert config.api_key_env == "TEST_HERMES_KEY"+ assert config.profile == "study"+ assert config.idle_timeout_seconds == 42+ assert "api_key" not in serialized+ assert serialized["api_key_env"] == "TEST_HERMES_KEY"++ assert (+ settings_from_dict({"backends": {"hermes_remote": {"idle_timeout_seconds": 0}}})+ .backend("hermes_remote")+ .idle_timeout_seconds+ == 1+ )+ assert (+ settings_from_dict({"backends": {"hermes_remote": {"idle_timeout_seconds": 100_000}}})+ .backend("hermes_remote")+ .idle_timeout_seconds+ == 86_400+ )++ local_serialized = settings_from_dict({"backends": {"codex": {"model": "gpt-5.6"}}}).to_dict()[+ "backends"+ ]["codex"]+ assert "base_url" not in local_serialized+ assert "api_key_env" not in local_serialized+++async def test_redirect_response_is_not_accepted(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")++ def redirect(_: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 302,+ headers={"location": "https://attacker.example.test"},+ json={"run_id": "must-not-be-accepted"},+ )++ backend = _backend(httpx.MockTransport(redirect))++ async def on_event(_: Any) -> None:+ return None++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is False+ assert result.error == "http_302"+++async def test_stream_without_terminal_event_is_not_successful(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ backend = _backend(_HermesTransport(events=[{"event": "message.delta", "delta": "partial"}]))++ async def on_event(_: Any) -> None:+ return None++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.final_text == "partial"+ assert result.success is False+ assert result.error == "incomplete_stream"+++async def test_sse_comments_surface_as_quiet_keepalives() -> None:+ def stream(_: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ content=b': ping\n\ndata: {"event":"run.completed","output":"done"}\n\n',+ )++ async with HermesRemoteClient(+ "http://hermes.test",+ "synthetic-secret",+ transport=httpx.MockTransport(stream),+ ) as client:+ events = [event async for event in client.stream_events("run-1")]++ assert events == [+ {"event": "gateway.keepalive"},+ {"event": "run.completed", "output": "done"},+ ]+++async def test_detect_remote_backend_is_registered(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = httpx.MockTransport(+ lambda _: httpx.Response(+ 200,+ json={+ "object": "hermes.api_server.capabilities",+ "model": "hermes",+ "features": {+ "run_submission": True,+ "run_events_sse": True,+ "run_stop": True,+ "run_approval_response": True,+ "session_resources": True,+ },+ },+ ),+ )+ backend = HermesRemoteBackend(+ config=BackendConfig(base_url="http://hermes.test", api_key_env="TEST_HERMES_KEY"),+ transport=transport,+ )+ assert backend.local_cli is False+ assert backend.detectable is True+ result = await backend.detect()+ assert result.available is True+++async def test_client_preserves_multi_profile_url_prefix() -> None:+ requests: list[httpx.Request] = []++ def capabilities(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return httpx.Response(200, json={})++ async with HermesRemoteClient(+ "https://hermes.test/p/study",+ "synthetic-secret",+ transport=httpx.MockTransport(capabilities),+ ) as client:+ await client.get_json("/v1/capabilities")++ assert requests[0].url.path == "/p/study/v1/capabilities"+++ "base_url",+ [+ "file:///etc/passwd",+ "https://user:[email protected]",+ "https://hermes.test?key=secret",+ "https://hermes.test#fragment",+ "https://hermes.test:invalid",+ ],+)+def test_client_rejects_unsafe_or_invalid_base_urls(base_url: str) -> None:+ with pytest.raises(HermesRemoteProtocolError, match="invalid_base_url"):+ HermesRemoteClient(base_url, "synthetic-secret")+++async def test_invalid_remote_identifiers_never_reach_request_paths(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(events=[{"event": "run.completed", "output": "done"}])+ backend = _backend(transport)++ async def on_event(_: Any) -> None:+ return None++ invalid_session = await backend.consult(+ "question",+ on_event=on_event,+ session_id="bad/session\r\nheader",+ config=backend.config,+ )+ assert invalid_session.success is False+ assert invalid_session.error == "invalid_session_id"+ assert transport.requests == []++ def invalid_run(request: httpx.Request) -> httpx.Response:+ if request.method == "POST" and request.url.path == "/v1/runs":+ return httpx.Response(202, json={"run_id": "bad/run"})+ return httpx.Response(404)++ bad_run = _backend(httpx.MockTransport(invalid_run))+ invalid_result = await bad_run.consult(+ "question",+ on_event=on_event,+ config=bad_run.config,+ )+ assert invalid_result.success is False+ assert invalid_result.error == "missing_run_id"diff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.pyindex 3c176fe61..8956f57a5 100644--- a/tests/services/test_subagent_backends.py+++ b/tests/services/test_subagent_backends.py@@ -942,6 +942,7 @@ async def test_detect_all_excludes_partner_backend() -> None:"hermes","openclaw","deepseek_harness",+ "hermes_remote",}diff --git a/tests/video_learning/test_invidious_account.py b/tests/video_learning/test_invidious_account.pynew file mode 100644index 000000000..36f56f3ca--- /dev/null+++ b/tests/video_learning/test_invidious_account.py@@ -0,0 +1,599 @@+from __future__ import annotations++import asyncio+from concurrent.futures import ThreadPoolExecutor+import json+from pathlib import Path+import stat+from urllib.parse import parse_qs, urlsplit++from fastapi import FastAPI+from fastapi.testclient import TestClient+import httpx+import pytest++from deeptutor.api.routers import video_learning+from deeptutor.multi_user import paths+from deeptutor.video_learning import invidious_account as account+from deeptutor.video_learning import invidious_account_client as account_client+from deeptutor.video_learning import invidious_account_storage as account_storage+from deeptutor.video_learning.service import TimedMediaError+++def system_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ root = (tmp_path / "data" / "system").resolve()+ monkeypatch.setattr(paths, "SYSTEM_ROOT", root)+ monkeypatch.setattr(paths, "ADMIN_WORKSPACE_ROOT", (tmp_path / "data").resolve())+ monkeypatch.setattr(paths, "USERS_ROOT", (tmp_path / "data" / "users").resolve())+ return root+++def configured_instance(monkeypatch: pytest.MonkeyPatch) -> str:+ base = "https://invidious.example.test"+ monkeypatch.setattr(+ account,+ "load_video_learning_settings",+ lambda: {+ "version": 1,+ "default_provider": "youtube",+ "youtube": {"transcript_provider": "none"},+ "invidious": {"api_base_url": base, "public_base_url": ""},+ },+ )+ return base+++def _token(scopes: list[str] | None = None) -> str:+ return json.dumps(+ {+ "session": "v1:test-session",+ "scopes": scopes or list(account.ACCOUNT_SCOPES),+ "signature": "test-signature",+ }+ )+++def _state_from_authorize_url(url: str) -> str:+ callback_url = parse_qs(urlsplit(url).query)["callback_url"][0]+ return parse_qs(urlsplit(callback_url).query)["state"][0]+++def client(+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> TestClient:+ app = FastAPI()+ app.include_router(video_learning.router, prefix="/api/video-learning")+ monkeypatch.setattr(video_learning, "current_owner_id", lambda: "u_ada")+ return TestClient(app)+++def test_authorization_uses_minimal_scopes_and_one_time_state(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def preferences(*, api_base_url: str, token: dict[str, object]) -> dict[str, object]:+ assert api_base_url == configured_instance+ assert token["session"] == "v1:test-session"+ return {"locale": "en-US"}++ monkeypatch.setattr(account, "_request_preferences", preferences)++ url = account.begin_invidious_account_authorization(+ owner_id="u_ada", redirect_uri="https://app.example.test/callback"+ )+ query = parse_qs(urlsplit(url).query)+ state = _state_from_authorize_url(url)++ assert urlsplit(url).path == "/authorize_token"+ assert query["scopes"] == [",".join(account.ACCOUNT_SCOPES)]+ pending = account_storage.flow_path("u_ada", state)+ assert pending.is_file()+ assert stat.S_IMODE(pending.stat().st_mode) == 0o600++ status = asyncio.run(+ account.complete_invidious_account_authorization(+ owner_id="u_ada", state=state, token=_token()+ )+ )+ secret = (+ system_root+ / "user-secrets"+ / "u_ada"+ / "private"+ / "video-learning-invidious"+ / "account.json"+ )+ assert status["connected"] is True+ assert status["api_base_url"] == configured_instance+ assert "token" not in status+ assert "test-session" not in status+ assert "v1:test-session" in secret.read_text(encoding="utf-8")+ assert stat.S_IMODE(secret.stat().st_mode) == 0o600+ for directory in (secret.parent, secret.parent.parent):+ assert stat.S_IMODE(directory.stat().st_mode) == 0o700+++def test_callback_cannot_be_replayed_or_used_by_another_owner(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def preferences(*, api_base_url: str, token: dict[str, object]) -> dict[str, object]:+ return {"locale": "en-US"}++ monkeypatch.setattr(account, "_request_preferences", preferences)+ url = account.begin_invidious_account_authorization(+ owner_id="u_ada", redirect_uri="https://app.example.test/callback"+ )+ state = _state_from_authorize_url(url)++ with pytest.raises(TimedMediaError):+ asyncio.run(+ account.complete_invidious_account_authorization(+ owner_id="u_bob", state=state, token=_token()+ )+ )++ # Looking under another owner's state directory must not consume the real+ # owner's pending callback.+ status = asyncio.run(+ account.complete_invidious_account_authorization(+ owner_id="u_ada", state=state, token=_token()+ )+ )+ assert status["connected"] is True+ with pytest.raises(TimedMediaError):+ asyncio.run(+ account.complete_invidious_account_authorization(+ owner_id="u_ada", state=state, token=_token()+ )+ )+++def test_pending_callback_claim_is_atomic_across_workers(+ system_root: Path,+ configured_instance: str,+) -> None:+ url = account.begin_invidious_account_authorization(+ owner_id="u_ada", redirect_uri="https://app.example.test/callback"+ )+ state = _state_from_authorize_url(url)++ with ThreadPoolExecutor(max_workers=2) as executor:+ claimed = list(+ executor.map(+ lambda _: account_storage.consume_pending_flow("u_ada", state),+ range(2),+ )+ )++ assert sum(flow is not None for flow in claimed) == 1+ assert not account_storage.flow_path("u_ada", state).exists()+++def test_expired_callback_is_rejected_and_never_writes_a_token(+ system_root: Path,+ configured_instance: str,+) -> None:+ url = account.begin_invidious_account_authorization(+ owner_id="u_ada", redirect_uri="https://app.example.test/callback"+ )+ state = _state_from_authorize_url(url)+ pending = account_storage.flow_path("u_ada", state)+ payload = account_storage.read_json(pending)+ payload["expires_at"] = 0+ account_storage.write_private_json(pending, payload)++ with pytest.raises(TimedMediaError):+ asyncio.run(+ account.complete_invidious_account_authorization(+ owner_id="u_ada", state=state, token=_token()+ )+ )+ assert not list(system_root.rglob("account.json"))+++def test_token_missing_disconnect_scope_is_rejected(+ system_root: Path,+ configured_instance: str,+) -> None:+ url = account.begin_invidious_account_authorization(+ owner_id="u_ada", redirect_uri="https://app.example.test/callback"+ )+ state = _state_from_authorize_url(url)++ with pytest.raises(TimedMediaError, match="missing a required scope"):+ asyncio.run(+ account.complete_invidious_account_authorization(+ owner_id="u_ada", state=state, token=_token(["GET:preferences"])+ )+ )+ assert not list(system_root.rglob("account.json"))+++def test_failed_preference_verification_never_writes_a_token(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ original_client = account_client.httpx.AsyncClient++ def refusing_client(**kwargs: object) -> object:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(403, json={"error": "invalid token"})++ return original_client(transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr(account_client.httpx, "AsyncClient", refusing_client)+ url = account.begin_invidious_account_authorization(+ owner_id="u_ada", redirect_uri="https://app.example.test/callback"+ )+ state = _state_from_authorize_url(url)++ with pytest.raises(TimedMediaError, match="verification failed with HTTP 403"):+ asyncio.run(+ account.complete_invidious_account_authorization(+ owner_id="u_ada", state=state, token=_token()+ )+ )+ assert not list(system_root.rglob("account.json"))+++def test_preference_network_failure_is_a_user_facing_error(+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import json++ original_client = account_client.httpx.AsyncClient++ def offline_client(**kwargs: object) -> object:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("offline")++ return original_client(transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr(account_client.httpx, "AsyncClient", offline_client)++ with pytest.raises(TimedMediaError, match="verification request failed"):+ asyncio.run(+ account._request_preferences(+ api_base_url=configured_instance, token=json.loads(_token())+ )+ )+++def test_disconnect_revokes_upstream_and_removes_only_the_local_secret(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"session": "v1:test-session", "signature": "test-signature"},+ },+ )+ account_storage.write_account(+ "u_bob",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"session": "v1:bob-session", "signature": "bob-signature"},+ },+ )+ revoked: dict[str, object] = {}++ async def revoke(*, api_base_url: str, token: dict[str, object]) -> None:+ revoked["api_base_url"] = api_base_url+ revoked["session"] = token["session"]++ monkeypatch.setattr(account, "_revoke_token", revoke)++ status = asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))++ assert status == {"connected": False}+ assert revoked == {+ "api_base_url": configured_instance,+ "session": "v1:test-session",+ }+ assert "u_ada" not in (system_root / "user-secrets").iterdir()+ assert account.invidious_account_status("u_bob")["connected"] is True+++def test_failed_upstream_disconnect_keeps_the_saved_connection_for_retry(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"session": "v1:test-session", "signature": "test-signature"},+ },+ )++ original_client = account_client.httpx.AsyncClient++ def failing_client(**kwargs: object) -> object:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(503)++ return original_client(transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr(account_client.httpx, "AsyncClient", failing_client)++ with pytest.raises(TimedMediaError, match="failed with HTTP 503"):+ asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))+ assert account.invidious_account_status("u_ada")["connected"] is True+++def test_disconnect_network_failure_is_user_facing_and_keeps_connection(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"session": "v1:test-session", "signature": "test-signature"},+ },+ )++ original_client = account_client.httpx.AsyncClient++ def offline_client(**kwargs: object) -> object:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("offline", request=request)++ return original_client(transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr(account_client.httpx, "AsyncClient", offline_client)++ with pytest.raises(TimedMediaError, match="disconnection request failed"):+ asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))+ assert account.invidious_account_status("u_ada")["connected"] is True+++def test_public_url_override_is_the_only_remote_callback_origin(+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv(account.PUBLIC_URL_ENV, "https://public.example.test")+ assert account.invidious_redirect_uri() == "https://public.example.test" + account.CALLBACK_PATH+++def test_default_callback_never_trusts_request_host_headers(+ client: TestClient,+ system_root: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv(account.PUBLIC_URL_ENV, raising=False)+ response = client.post(+ "/api/video-learning/invidious/account/authorize",+ headers={+ "host": "attacker.example.test",+ "x-forwarded-proto": "https",+ "x-forwarded-host": "forwarded-attacker.example.test",+ },+ )+ callback_url = parse_qs(urlsplit(response.json()["authorize_url"]).query)["callback_url"][0]+ assert callback_url.startswith(account.DEFAULT_PUBLIC_URL + account.CALLBACK_PATH)+ assert "attacker.example.test" not in callback_url+++def test_invidious_requests_use_bearer_json_and_unregister_session(+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import json++ token = json.loads(_token())+ requests: list[httpx.Request] = []+ original_client = account_client.httpx.AsyncClient++ def recording_client(**kwargs: object) -> object:+ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if request.url.path == "/api/v1/auth/preferences":+ return httpx.Response(200, json={"locale": "en-US"})+ return httpx.Response(204)++ return original_client(transport=httpx.MockTransport(handler), **kwargs)++ monkeypatch.setattr(account_client.httpx, "AsyncClient", recording_client)++ preferences = asyncio.run(+ account._request_preferences(api_base_url=configured_instance, token=token)+ )+ asyncio.run(account._revoke_token(api_base_url=configured_instance, token=token))++ assert preferences == {"locale": "en-US"}+ assert [request.method for request in requests] == ["GET", "POST"]+ assert [request.url.path for request in requests] == [+ "/api/v1/auth/preferences",+ "/api/v1/auth/tokens/unregister",+ ]+ expected_authorization = f"Bearer {account_client.bearer_token(token)}"+ assert all(request.headers["authorization"] == expected_authorization for request in requests)+ assert json.loads(requests[-1].content) == {"session": "v1:test-session"}+++def test_status_rejects_expired_or_incomplete_stored_tokens(+ system_root: Path,+ configured_instance: str,+) -> None:+ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"session": "v1:test-session", "signature": "sig"},+ },+ )+ assert account.invidious_account_status("u_ada")["connected"] is True++ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"signature": "sig"},+ },+ )+ assert account.invidious_account_status("u_ada") == {"connected": False}+++def test_disconnect_removes_an_expired_local_connection_without_upstream_call(+ system_root: Path,+ configured_instance: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from datetime import datetime, timezone++ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {+ "session": "v1:test-session",+ "signature": "sig",+ "expire": int(datetime.now(timezone.utc).timestamp()) - 1,+ },+ },+ )++ async def revoke(*, api_base_url: str, token: dict[str, object]) -> None:+ raise AssertionError("an expired token must not be sent upstream")++ monkeypatch.setattr(account, "_revoke_token", revoke)+ status = asyncio.run(account.disconnect_invidious_account(owner_id="u_ada"))+ assert status == {"connected": False}+ assert "u_ada" not in (system_root / "user-secrets").iterdir()+++def test_router_authorize_callback_status_and_disconnect(+ client: TestClient,+ configured_instance: str,+ system_root: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv(account.PUBLIC_URL_ENV, "https://app.example.test")+ response = client.post(+ "/api/video-learning/invidious/account/authorize",+ headers={+ "x-forwarded-proto": "https",+ "x-forwarded-host": "forwarded.example.test",+ },+ )++ assert response.status_code == 200+ url = response.json()["authorize_url"]+ state = _state_from_authorize_url(url)+ callback_url = parse_qs(urlsplit(url).query)["callback_url"][0]+ assert callback_url.startswith("https://app.example.test")++ async def complete(*, owner_id: str, state: str, token: str) -> dict[str, object]:+ assert owner_id == "u_ada"+ assert state+ assert "v1:test-session" in token+ return {"connected": True, "api_base_url": configured_instance}++ monkeypatch.setattr(+ video_learning.invidious_account, "complete_invidious_account_authorization", complete+ )+ callback = client.get(+ "/api/video-learning/invidious/account/callback",+ params={"state": state, "token": _token()},+ )+ assert callback.status_code == 200+ assert callback.headers["cache-control"] == "no-store"+ assert "v1:test-session" not in callback.text++ account_storage.write_account(+ "u_ada",+ {+ "version": 1,+ "api_base_url": configured_instance,+ "scopes": list(account.ACCOUNT_SCOPES),+ "connected_at": "2026-09-02T00:00:00+00:00",+ "token": {"session": "v1:test-session", "signature": "test-signature"},+ },+ )+ status_response = client.get("/api/video-learning/invidious/account/status")+ assert status_response.status_code == 200+ assert status_response.json()["connected"] is True+ assert "v1:test-session" not in status_response.text++ disconnected: dict[str, object] = {}++ async def disconnect(*, owner_id: str) -> dict[str, object]:+ disconnected["owner_id"] = owner_id+ return {"connected": False}++ monkeypatch.setattr(+ video_learning.invidious_account, "disconnect_invidious_account", disconnect+ )+ disconnect_response = client.post("/api/video-learning/invidious/account/disconnect")+ assert disconnect_response.status_code == 200+ assert disconnect_response.json() == {"connected": False}+ assert disconnected == {"owner_id": "u_ada"}+++def test_unknown_callback_returns_400_without_calling_invidious(+ client: TestClient,+) -> None:+ response = client.get(+ "/api/video-learning/invidious/account/callback",+ params={"state": "forged", "token": _token()},+ )+ assert response.status_code == 400+ assert "forged" not in response.text+ assert "v1:test-session" not in response.text+++def test_router_start_returns_400_when_invidious_is_not_configured(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ account,+ "load_video_learning_settings",+ lambda: {+ "version": 1,+ "default_provider": "youtube",+ "youtube": {"transcript_provider": "none"},+ "invidious": {"api_base_url": "", "public_base_url": ""},+ },+ )+ response = client.post("/api/video-learning/invidious/account/authorize")+ assert response.status_code == 400+ assert response.json()["detail"] == (+ "Configure the Invidious API base URL before connecting an account."+ )diff --git a/tests/video_learning/test_router.py b/tests/video_learning/test_router.pyindex 498ebbe53..20595f3db 100644--- a/tests/video_learning/test_router.py+++ b/tests/video_learning/test_router.py@@ -190,6 +190,59 @@ def test_video_note_errors_are_bounded_and_useful(client: TestClient) -> None:assert client.put(f"{notes_url}/missing-note", json={"body": "Note"}).status_code == 404+def test_video_notes_export_markdown_and_stay_account_scoped(+ client: TestClient,+ notebook_manager: NotebookManager,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ material = _material()+ material["metadata"]["title"] = "Timestamped lesson"+ material["transcript"]["cues"] = [+ {"start": 1.25, "end": 3.5, "text": "First quoted idea."},+ {"start": 65, "end": 70, "text": "Second quoted idea."},+ {"start": 80, "end": 90, "text": "Unquoted transcript tail."},+ ]+ service.get_timed_media_store().save(material)+ material_id = str(material["material_id"])+ notes_url = f"/api/video-learning/materials/{material_id}/notes"+ export_url = f"{notes_url}.md"++ empty_response = client.get(export_url)+ assert empty_response.status_code == 200+ assert empty_response.headers["content-type"].startswith("text/markdown")+ assert empty_response.text == (+ "# Video notes: Timestamped lesson\n\n_No timestamped notes captured yet._\n"+ )++ client.post(notes_url, json={"body": "Opening note", "time_seconds": 2})+ client.post(notes_url, json={"body": "Later note", "time_seconds": 66})++ response = client.get(export_url)+ assert response.status_code == 200+ assert response.headers["content-disposition"] == 'attachment; filename="video-notes.md"'+ assert response.text == (+ "# Video notes: Timestamped lesson\n\n"+ "## 0:02\n\nOpening note\n\n> First quoted idea.\n\n"+ "## 1:06\n\nLater note\n\n> Second quoted idea.\n"+ )+ assert "Unquoted transcript tail" not in response.text+ assert "https://youtu.be" not in response.text+ assert "provider_cache" not in response.text+ assert "dQw4w9WgXcQ" not in response.text++ other_manager = NotebookManager(+ base_dir=str(notebook_manager.base_dir.parent / "export-account-notebooks")+ )+ monkeypatch.setattr(video_notes, "get_notebook_manager", lambda: other_manager)+ isolated = client.get(export_url)+ assert isolated.status_code == 200+ assert "Opening note" not in isolated.text+ assert "Later note" not in isolated.text++ monkeypatch.setattr(video_notes, "get_notebook_manager", lambda: notebook_manager)+ assert client.get("/api/video-learning/materials/0123456789abcdef/notes.md").status_code == 404++def test_progress_does_not_replace_known_duration_with_client_value(client: TestClient) -> None:material = _material(duration=100)service.get_timed_media_store().save(material)diff --git a/web/app/(utility)/mastery/[pathId]/page.tsx b/web/app/(utility)/mastery/[pathId]/page.tsxindex 5139fd680..8c9ef4e86 100644--- a/web/app/(utility)/mastery/[pathId]/page.tsx+++ b/web/app/(utility)/mastery/[pathId]/page.tsx@@ -9,6 +9,8 @@ import {ArrowRight,BookOpen,Compass,+ LayoutGrid,+ List,Loader2,MoreHorizontal,PencilRuler,@@ -21,6 +23,7 @@ import {import { ModuleOutline } from "@/components/space/learning/ModuleOutline";import { ConfirmDialog } from "@/components/space/learning/ConfirmDialog";import { EditTopicRouteDialog } from "@/components/space/learning/EditTopicRouteDialog";+import { LearningBoard } from "@/components/space/learning/LearningBoard";import {topicDisplayName,type Translate,@@ -33,12 +36,15 @@ import {deleteProgress,fetchMasteryTopic,fetchMasteryTopicSessions,+ fetchLearningBoard,redoProgress,renameProgress,setMasteryObjectiveOverride,type MasteryTopic,+ type BoardResult,type TopicSession,} from "@/lib/learning-api";+import { setPendingPrompt } from "@/lib/pending-prompt";const NEXT_LABELS: Record<string, { zh: string; en: string }> = {probe: {@@ -90,6 +96,10 @@ export default function MasteryTopicPage() {const [confirmAction, setConfirmAction] = useState<"reset" | "delete" | null>(null,);+ const [topicView, setTopicView] = useState<"outline" | "board">("outline");+ const [board, setBoard] = useState<BoardResult | null>(null);+ const [boardError, setBoardError] = useState(false);+ const [boardRequestNonce, setBoardRequestNonce] = useState(0);const [mutationBusy, setMutationBusy] = useState(false);const editorTriggerRef = useRef<HTMLElement | null>(null);const confirmTriggerRef = useRef<HTMLElement | null>(null);@@ -147,6 +157,23 @@ export default function MasteryTopicPage() {void loadSessions();}, [activity.revision, activity.signal, loadSessions]);+ useEffect(() => {+ if (topicView !== "board") return;+ const controller = new AbortController();+ setBoardError(false);+ fetchLearningBoard(pathId, {+ cache: "no-store",+ signal: controller.signal,+ })+ .then((result) => setBoard(result))+ .catch(() => {+ if (controller.signal.aborted) return;+ setBoard(null);+ setBoardError(true);+ });+ return () => controller.abort();+ }, [activity.revision, boardRequestNonce, pathId, topicView]);+useEffect(() => {if (!selectedId || !topic) return;const stillThere = topic.map.modules.some((module) =>@@ -223,6 +250,14 @@ export default function MasteryTopicPage() {}};+ const startBoardTutoring = (knowledgePointName: string) => {+ setPendingPrompt(+ `Please tutor me on: ${knowledgePointName}. Start with a quick check of what I already know, then guide me step by step.`,+ "mastery_path",+ );+ router.push(`/mastery/${encodeURIComponent(pathId)}/sessions`);+ };+if (loading && !topic) {return (<div className="mastery-shell flex h-full items-center justify-center text-[var(--muted-foreground)]">@@ -439,14 +474,66 @@ export default function MasteryTopicPage() {</section>) : (<div className="space-y-5">- <ModuleOutline- topic={topic}- revision={Math.max(topic.path_revision, activity.revision)}- selectedId={selectedId}- zh={zh}- onSelect={setSelectedId}- onOverride={handleOverride}- />+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex items-center gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">+ {(+ [+ ["outline", List, t("Outline")],+ ["board", LayoutGrid, t("Board")],+ ] as const+ ).map(([value, Icon, label]) => (+ <button+ key={value}+ type="button"+ onClick={() => setTopicView(value)}+ aria-pressed={topicView === value}+ className={`flex h-8 items-center gap-1.5 rounded-md px-2.5 text-xs font-medium transition ${+ topicView === value+ ? "bg-[var(--background)] text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ <Icon className="h-3.5 w-3.5" />+ {label}+ </button>+ ))}+ </div>+ {topicView === "board" && boardError && (+ <button+ type="button"+ onClick={() => setBoardRequestNonce((nonce) => nonce + 1)}+ className="text-xs font-medium text-[var(--primary)] hover:underline"+ >+ {t("Try again")}+ </button>+ )}+ </div>+ {topicView === "outline" ? (+ <ModuleOutline+ topic={topic}+ revision={Math.max(topic.path_revision, activity.revision)}+ selectedId={selectedId}+ zh={zh}+ onSelect={setSelectedId}+ onOverride={handleOverride}+ />+ ) : board ? (+ <LearningBoard+ pathId={pathId}+ modules={board.modules}+ revision={Math.max(topic.path_revision, activity.revision)}+ zh={zh}+ onStartTutoring={startBoardTutoring}+ />+ ) : boardError ? (+ <p className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-6 text-center text-sm text-[var(--muted-foreground)]">+ {t("The learning board could not be loaded")}+ </p>+ ) : (+ <div className="flex min-h-40 items-center justify-center rounded-xl border border-[var(--border)] bg-[var(--card)]">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ )}<ReviewTrailreviews={topic.reviews}zh={zh}diff --git a/web/app/(workspace)/books/components/BookChatPanel.tsx b/web/app/(workspace)/books/components/BookChatPanel.tsxindex 1b7deaa49..deac0257e 100644--- a/web/app/(workspace)/books/components/BookChatPanel.tsx+++ b/web/app/(workspace)/books/components/BookChatPanel.tsx@@ -500,6 +500,7 @@ export default function BookChatPanel({{m.role === "assistant" ? (<AssistantResponsecontent={m.content}+ language={book?.language || appLanguage}className="text-sm leading-relaxed"isStreaming={Boolean(m.streaming)}/>diff --git a/web/app/(workspace)/books/components/PageReader.tsx b/web/app/(workspace)/books/components/PageReader.tsxindex 758d47a36..83fdf80e7 100644--- a/web/app/(workspace)/books/components/PageReader.tsx+++ b/web/app/(workspace)/books/components/PageReader.tsx@@ -1,6 +1,7 @@"use client";import { useCallback, useEffect, useRef, useState } from "react";+import { usePathname } from "next/navigation";import {Bookmark,BookmarkCheck,@@ -23,6 +24,7 @@ import {type ChapterScrollPlacement,type SequentialReadDirection,} from "@/lib/book-reader-navigation";+import { browserStorage } from "@/shared/storage";import BlockRenderer from "./blocks/BlockRenderer";import type { QuizAttemptArgs } from "./blocks/QuizBlock";import PageOutlineNav from "./PageOutlineNav";@@ -40,6 +42,41 @@ const INSERTABLE_TYPES: BlockType[] = ["deep_dive","user_note",];+const PENDING_CHAPTER_END_KEY = "deeptutor.book.pendingChapterEnd";+const PENDING_CHAPTER_END_TTL_MS = 30_000;++interface PendingChapterEnd {+ bookId: string;+ pageId: string;+ createdAt: number;+}++function rememberPendingChapterEnd(bookId: string, pageId: string): void {+ browserStorage.writeRaw(+ "session",+ PENDING_CHAPTER_END_KEY,+ JSON.stringify({ bookId, pageId, createdAt: Date.now() }),+ );+}++function hasPendingChapterEnd(bookId: string, pageId: string): boolean {+ const raw = browserStorage.readRaw("session", PENDING_CHAPTER_END_KEY);+ if (!raw) return false;+ try {+ const pending = JSON.parse(raw) as PendingChapterEnd;+ if (+ typeof pending.createdAt !== "number" ||+ Date.now() - pending.createdAt > PENDING_CHAPTER_END_TTL_MS+ ) {+ browserStorage.removeRaw("session", PENDING_CHAPTER_END_KEY);+ return false;+ }+ return pending.bookId === bookId && pending.pageId === pageId;+ } catch {+ browserStorage.removeRaw("session", PENDING_CHAPTER_END_KEY);+ return false;+ }+}export interface PageReaderProps {page: Page | null;@@ -106,6 +143,7 @@ export default function PageReader({onCaptureSelection,}: PageReaderProps) {const { t } = useTranslation();+ const pathname = usePathname();const [showInsertMenu, setShowInsertMenu] = useState(false);/** The chapter outline starts parked so it never covers the prose unasked. */const [outlineCollapsed, setOutlineCollapsed] = useState(true);@@ -162,10 +200,18 @@ export default function PageReader({const isNewPage = lastSeenPageIdRef.current !== page.id;lastSeenPageIdRef.current = page.id;const requestedPageId = pendingScrollPlacementPageIdRef.current;- const pendingMatchesPage = requestedPageId === page.id;- const placement = pendingMatchesPage+ const targetPath = `/books/${encodeURIComponent(page.book_id)}/pages/${encodeURIComponent(page.id)}`;+ // State changes before App Router finishes updating the URL. Let the+ // destination route consume this cross-mount intent; the departing page+ // must not clear it during that short transition window.+ const persistedEnd =+ pathname === targetPath && hasPendingChapterEnd(page.book_id, page.id);+ const pendingMatchesPage = requestedPageId === page.id || persistedEnd;+ const placement = requestedPageId === page.id? pendingScrollPlacementRef.current- : "start";+ : persistedEnd+ ? "end"+ : "start";if (!pendingMatchesPage) {pendingScrollPlacementRef.current = "start";pendingScrollPlacementPageIdRef.current = null;@@ -181,8 +227,6 @@ export default function PageReader({// from surviving into the hydrated chapter. "End" must wait for content.if (waitingForContent && placement === "end") return;- pendingScrollPlacementRef.current = "start";- pendingScrollPlacementPageIdRef.current = null;const pendingFrames: number[] = [];pendingFrames.push(window.requestAnimationFrame(() => {@@ -191,6 +235,15 @@ export default function PageReader({scrollContainer.scrollTop =placement === "end" ? scrollContainer.scrollHeight : 0;updateReadingProgress();+ // Consume the placement only after it has actually reached the+ // DOM. Hydration can rerun this effect between the two frames;+ // clearing earlier loses an owed "land at end" and resets the+ // previous chapter to its first screen.+ pendingScrollPlacementRef.current = "start";+ pendingScrollPlacementPageIdRef.current = null;+ if (persistedEnd) {+ browserStorage.removeRaw("session", PENDING_CHAPTER_END_KEY);+ }}),);}),@@ -201,7 +254,7 @@ export default function PageReader({window.cancelAnimationFrame(frame);}};- }, [scrollContainer, page, loading, updateReadingProgress]);+ }, [scrollContainer, page, loading, pathname, updateReadingProgress]);useEffect(() => {updateReadingProgress();@@ -311,6 +364,8 @@ export default function PageReader({if (direction === "previous" && previousPage) {pendingScrollPlacementRef.current = "end";pendingScrollPlacementPageIdRef.current = previousPage.id;+ const currentBookId = bookId || page?.book_id;+ if (currentBookId) rememberPendingChapterEnd(currentBookId, previousPage.id);onNavigate?.(previousPage.id);return true;}@@ -324,8 +379,10 @@ export default function PageReader({},[loading,+ bookId,nextPage,onNavigate,+ page?.book_id,page?.blocks.length,previousPage,scrollContainer,diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsxindex e5eb0f063..938d863c3 100644--- a/web/components/agents/ConnectedAgents.tsx+++ b/web/components/agents/ConnectedAgents.tsx@@ -20,15 +20,17 @@ import {/*** Connected agents — live agents the chat composer can select and consult in- * real time: a supported local agent harness, or one of the user's partners.+ * real time: a supported local harness, remote gateway, or one of the user's+ * partners.* Distinct from the imported-history agents below it: those replay- * past transcripts, these drive the live agent now. CLI detection is- * machine-global (is the CLI installed here); partners come from the user's- * partner list. Consulting a partner opens a fresh session on it — every- * consult within one DeepTutor chat is archived as one partner session.+ * past transcripts, these drive the live agent now. Runtime detection is+ * machine-global; partners come from the user's partner list. Consulting a+ * partner opens a fresh session on it — every consult within one DeepTutor+ * chat is archived as one partner session.*/const PARTNER_KIND = "partner";+const REMOTE_HERMES_KIND = "hermes_remote";type Lang = { zh: string; en: string };@@ -40,6 +42,7 @@ function backendLabel(kind: string, tr: (l: Lang) => string): string {if (kind === "opencode") return "opencode";if (kind === "mimo") return "MiMo Code";if (kind === "hermes") return "Hermes Agent";+ if (kind === REMOTE_HERMES_KIND) return "Hermes Agent (remote)";if (kind === "openclaw") return "OpenClaw";if (kind === "deepseek_harness") return "DeepSeek Harness";if (kind === PARTNER_KIND) return tr({ zh: "伙伴", en: "Partner" });@@ -82,7 +85,7 @@ export default function ConnectedAgents() {() => backends.filter((b) => b.available),[backends],);- // Something is connectable when a CLI is installed here or a partner exists.+ // Something is connectable when a local/remote backend is available or a partner exists.const canConnect = available.length > 0 || partners.length > 0;const partnerName = useCallback((id: string) => partners.find((p) => p.partner_id === id)?.name || id,@@ -117,8 +120,8 @@ export default function ConnectedAgents() {icon={Plug}title={tr({ zh: "连接的智能体", en: "Connected agents" })}description={tr({- zh: "把本机的 Claude Code、Codex、Antigravity CLI、Kimi CLI、opencode、MiMo Code、Hermes Agent、OpenClaw、DeepSeek Harness 或你的伙伴接进来,在对话中选中后直接向它提问 —— 它的运行过程会实时展示。",- en: "Bring in a supported local harness — including Claude Code, Codex, Hermes Agent, OpenClaw, and DeepSeek Harness — or one of your partners. Select it in chat to consult it directly and see its run live.",+ zh: "把本机智能体、已配置的远程 Hermes 网关或你的伙伴接进来,在对话中选中后直接向它提问——运行过程会实时展示。",+ en: "Bring in a supported local agent, a configured remote Hermes gateway, or one of your partners. Select it in chat to consult it directly and see its run live.",})}action={canConnect ? (@@ -137,20 +140,20 @@ export default function ConnectedAgents() {{loading ? (<div className="flex items-center gap-2 px-1 text-[12px] text-[var(--muted-foreground)]"><Loader2 className="h-3.5 w-3.5 animate-spin" />- {tr({ zh: "检测本机智能体…", en: "Detecting local agents…" })}+ {tr({ zh: "检测可用智能体…", en: "Detecting available agents…" })}</div>) : !canConnect ? (<div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">{tr({- zh: "未在本机检测到受支持的智能体 CLI(包括 Hermes Agent、OpenClaw、DeepSeek Harness),也还没有任何伙伴。安装并登录其中任一 CLI,或在「伙伴」里新建一个,即可连接。",- en: "No supported agent CLI was detected on this machine (including Hermes Agent, OpenClaw, and DeepSeek Harness), and there are no partners yet. Install and log in to one, or create a partner, to connect it.",+ zh: "未检测到可用的本机智能体或已配置的远程 Hermes 网关,也还没有任何伙伴。安装并登录受支持的 CLI、配置远程网关,或在「伙伴」里新建一个,即可连接。",+ en: "No supported local agent or configured remote Hermes gateway is available, and there are no partners yet. Set up a local CLI, configure the gateway, or create a partner to connect one.",})}</div>) : connections.length === 0 ? (<div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">{tr({- zh: "尚未连接任何智能体。点击「连接智能体」把本机检测到的智能体 CLI 或你的伙伴接进来。",- en: "No agents connected yet. Click “Connect agent” to bring in a detected local agent CLI, or a partner.",+ zh: "尚未连接任何智能体。点击「连接智能体」接入本机智能体、远程 Hermes 网关或你的伙伴。",+ en: "No agents connected yet. Click “Connect agent” to add a local agent, remote Hermes gateway, or partner.",})}</div>) : (@@ -253,7 +256,7 @@ function ConnectModal({onClose: () => void;onConnected: () => void;}) {- // The agent-type choices: each detected CLI, plus "Partner" when any exist.+ // The choices include every available runtime plus Partner when one exists.const options = useMemo(() => [...backends.map((b) => ({ kind: b.kind, label: b.display_name })),@@ -273,6 +276,7 @@ function ConnectModal({const [submitting, setSubmitting] = useState(false);const isPartner = kind === PARTNER_KIND;+ const isRemote = kind === REMOTE_HERMES_KIND;// While the user hasn't renamed the connection, mirror the chosen partner's// name so the connection reads as that partner by default.@@ -307,7 +311,9 @@ function ConnectModal({await connectSubagent(isPartner? { name: trimmed, agent_kind: PARTNER_KIND, partner_id: partnerId }- : { name: trimmed, agent_kind: kind, cwd: cwd.trim() },+ : isRemote+ ? { name: trimmed, agent_kind: kind }+ : { name: trimmed, agent_kind: kind, cwd: cwd.trim() },);onConnected();} catch (e) {@@ -315,7 +321,7 @@ function ConnectModal({} finally {setSubmitting(false);}- }, [name, kind, cwd, isPartner, partnerId, existingNames, onConnected, tr]);+ }, [name, kind, cwd, isPartner, isRemote, partnerId, existingNames, onConnected, tr]);return (<div@@ -408,7 +414,7 @@ function ConnectModal({/></div>- {!isPartner && (+ {!isPartner && !isRemote && (<div><label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">{tr({diff --git a/web/components/agents/agent-icons.tsx b/web/components/agents/agent-icons.tsxindex fcaee3a26..acad02fb8 100644--- a/web/components/agents/agent-icons.tsx+++ b/web/components/agents/agent-icons.tsx@@ -211,6 +211,7 @@ export function agentGlyph(kind: string | undefined): AgentGlyph | null {if (kind === "opencode") return OpencodeGlyph;if (kind === "mimo") return MimoGlyph;if (kind === "hermes") return HermesGlyph;+ if (kind === "hermes_remote") return HermesGlyph;if (kind === "openclaw") return OpenClawGlyph;if (kind === "deepseek_harness") return DeepSeekGlyph;if (kind === "partner") return PartnerGlyph;diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsxindex 2d8b34ed9..72619c91b 100644--- a/web/components/common/AssistantResponse.tsx+++ b/web/components/common/AssistantResponse.tsx@@ -9,6 +9,7 @@ import type { StreamEvent } from "@/features/chat/model/protocol";import { useWatching } from "@/context/WatchingContext";import {hasVisibleMarkdownContent,+ repairChineseEmphasis,repairMalformedStrongEmphasis,stripArtifactAnnotations,} from "@/lib/markdown-display";@@ -36,6 +37,7 @@ interface AssistantResponseProps {readingMaterialId?: string;readingMaterialRevision?: number;events?: StreamEvent[];+ language?: string;}function AssistantResponseImpl({@@ -45,6 +47,7 @@ function AssistantResponseImpl({readingMaterialId,readingMaterialRevision,events,+ language,}: AssistantResponseProps) {const displayContent = useSmoothStreamText(content, isStreaming);// A locator becomes interactive only when this turn's persisted reading-tool@@ -135,7 +138,12 @@ function AssistantResponseImpl({/>);}- const repairedContent = repairMalformedStrongEmphasis(segment.content);+ const repairedContent = isStreaming+ ? repairMalformedStrongEmphasis(segment.content)+ : repairChineseEmphasis(+ repairMalformedStrongEmphasis(segment.content),+ language,+ );if (!hasVisibleMarkdownContent(repairedContent)) {return <Fragment key={`text-${index}`} />;diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsxindex 6db08fc05..089750a9d 100644--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@ -16,6 +16,7 @@ import {} from "lucide-react";import Modal from "@/components/common/Modal";import { useImaConnection } from "@/hooks/useImaConnection";+import { useLLMOptions } from "@/hooks/useLLMOptions";import {getGraphRagConfig,getLightRagConfig,@@ -29,6 +30,7 @@ import {probeLinkedFolder,probeWeKnora,type KnowledgeUploadPolicy,+ type IndexingLLMSelection,type LinkedFolderProbe,type RagProviderSummary,type WeKnoraProbe,@@ -45,6 +47,9 @@ import {import FileDropZone from "./FileDropZone";import ImaConnectionFields from "./ImaConnectionFields";import KnowledgeEngineIcon from "./KnowledgeEngineIcon";+import IndexingModelSelector, {+ selectionFromLightRagDefault,+} from "./IndexingModelSelector";const OBSIDIAN_SOURCE = "obsidian";const MARGINNOTE4_SOURCE = "marginnote4";@@ -67,6 +72,7 @@ interface CreateKbModalProps {files: File[];pageindexMode?: "flash" | "standard";searchMode?: string;+ indexingLLM?: IndexingLLMSelection;}) => Promise<void>;/** Link a pre-built engine index folder in place (no copy, no re-index). */onConnectLinkedFolder: (params: {@@ -158,6 +164,14 @@ export default function CreateKbModal({const [weKnoraProbe, setWeKnoraProbe] = useState<WeKnoraProbe | null>(null);const [weKnoraProbing, setWeKnoraProbing] = useState(false);const [submitting, setSubmitting] = useState(false);+ const [indexingLLM, setIndexingLLM] = useState<IndexingLLMSelection | null>(+ null,+ );+ const [lightRagConfig, setLightRagConfig] = useState<Awaited<+ ReturnType<typeof getLightRagConfig>+ > | null>(null);+ const [lightRagConfigLoaded, setLightRagConfigLoaded] = useState(false);+ const [lightRagConfigError, setLightRagConfigError] = useState(false);const [error, setError] = useState<string | null>(null);const linkIsObsidian = linkSource === OBSIDIAN_SOURCE;const linkIsMarginNote = linkSource === MARGINNOTE4_SOURCE;@@ -168,6 +182,7 @@ export default function CreateKbModal({onError: setError,active: linkIsIma,});+ const llmCatalog = useLLMOptions();const firstLinkable = providers.find((p) => p.linkable)?.id;@@ -218,8 +233,41 @@ export default function CreateKbModal({setWeKnoraKnowledgeBaseId("");setWeKnoraProbe(null);setWeKnoraProbing(false);+ setIndexingLLM(null);+ setLightRagConfig(null);+ setLightRagConfigLoaded(false);+ setLightRagConfigError(false);}, [isOpen, providers, firstLinkable, initialMode, initialSource]);+ useEffect(() => {+ if (+ !isOpen ||+ mode !== "new" ||+ provider !== "lightrag" ||+ indexingLLM ||+ !lightRagConfigLoaded ||+ !lightRagConfig+ ) {+ return;+ }+ setIndexingLLM(+ selectionFromLightRagDefault(+ llmCatalog.options,+ lightRagConfig,+ llmCatalog.activeDefault,+ ),+ );+ }, [+ indexingLLM,+ isOpen,+ llmCatalog.activeDefault,+ llmCatalog.options,+ lightRagConfig,+ lightRagConfigLoaded,+ mode,+ provider,+ ]);+useEffect(() => {if (!isOpen || mode !== "new") return;let cancelled = false;@@ -242,6 +290,11 @@ export default function CreateKbModal({];} else if (provider === "lightrag") {const config = await getLightRagConfig();+ if (!cancelled) {+ setLightRagConfig(config);+ setLightRagConfigLoaded(true);+ setLightRagConfigError(false);+ }summary = [`${t("Results per query")}: ${config.top_k}`,`${t("Files in parallel")}: ${config.max_concurrent_files}`,@@ -267,7 +320,13 @@ export default function CreateKbModal({}if (!cancelled) setEngineDefaultSummary(summary);} catch {- if (!cancelled) setEngineDefaultSummary([]);+ if (!cancelled) {+ setEngineDefaultSummary([]);+ if (provider === "lightrag") {+ setLightRagConfigLoaded(true);+ setLightRagConfigError(true);+ }+ }}};@@ -331,6 +390,7 @@ export default function CreateKbModal({!!weKnoraProbe?.ok);}+ if (provider === "lightrag" && !indexingLLM) return false;return !providerUnavailable;}if (linkIsIma) return imaConnection.canSubmit;@@ -432,6 +492,8 @@ export default function CreateKbModal({pageindexMode:isPageIndexOSS && pageIndexMode ? pageIndexMode : undefined,searchMode: retrievalMode || undefined,+ indexingLLM:+ provider === "lightrag" ? indexingLLM || undefined : undefined,});}} else if (linkIsIma) {@@ -552,6 +614,27 @@ export default function CreateKbModal({files={files}setFiles={setFiles}policyForProvider={policyForProvider}+ indexingModelField={+ provider === "lightrag" ? (+ <IndexingModelSelector+ options={llmCatalog.options}+ selection={indexingLLM}+ loading={llmCatalog.loading}+ error={llmCatalog.error}+ defaultUnavailable={+ lightRagConfigLoaded &&+ !!(+ lightRagConfig?.llm_profile_id ||+ lightRagConfig?.llm_model_id+ ) &&+ !indexingLLM+ }+ defaultLoadError={lightRagConfigError}+ disabled={submitting}+ onChange={setIndexingLLM}+ />+ ) : null+ }connectionForm={isLightRagServer ? (<LightRagServerFields@@ -712,6 +795,7 @@ function NewModeFields({files,setFiles,policyForProvider,+ indexingModelField,connectionForm,t,}: {@@ -734,6 +818,7 @@ function NewModeFields({files: File[];setFiles: (files: File[]) => void;policyForProvider: KnowledgeUploadPolicy;+ indexingModelField?: ReactNode;/** When set, replaces the upload step (e.g. a server connection form). */connectionForm?: ReactNode;t: TFn;@@ -868,6 +953,12 @@ function NewModeFields({</div>)}+ {indexingModelField && (+ <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/20 p-3">+ {indexingModelField}+ </div>+ )}+{modeOptions.length > 0 && (<div><label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">diff --git a/web/components/knowledge/IndexingModelSelector.tsx b/web/components/knowledge/IndexingModelSelector.tsxnew file mode 100644index 000000000..ae3b768be--- /dev/null+++ b/web/components/knowledge/IndexingModelSelector.tsx@@ -0,0 +1,208 @@+"use client";++import { useTranslation } from "react-i18next";+import type {+ IndexingLLMSelection,+ LightRagConfig,+} from "@/features/knowledge/model/types";+import type { LLMOption } from "@/lib/llm-options";+import {+ reasoningEffortOptions,+ reasoningEffortOptionsFromSupportedLevels,+} from "@/lib/reasoning-effort";++const INDEXING_REASONING_EFFORTS = new Set([+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+]);++export function selectionFromLLMOption(+ option: LLMOption,+ reasoningEffort = "",+): IndexingLLMSelection {+ const selection: IndexingLLMSelection = {+ profile_id: option.profile_id,+ model_id: option.model_id,+ };+ // `none` is meaningful and must remain present; only the empty inherited+ // value is omitted from the request.+ if (reasoningEffort) selection.reasoning_effort = reasoningEffort;+ return selection;+}++export function selectionFromLightRagDefault(+ options: LLMOption[],+ config: Pick<LightRagConfig, "llm_profile_id" | "llm_model_id">,+ activeDefault?: {+ profile_id?: string | null;+ model_id?: string | null;+ } | null,+): IndexingLLMSelection | null {+ const hasDedicated = Boolean(config.llm_profile_id || config.llm_model_id);+ const profileId = hasDedicated+ ? config.llm_profile_id+ : activeDefault?.profile_id;+ const modelId = hasDedicated ? config.llm_model_id : activeDefault?.model_id;+ const option =+ hasDedicated || (profileId && modelId)+ ? options.find(+ (item) => item.profile_id === profileId && item.model_id === modelId,+ )+ : options.find((item) => item.is_active_default);+ return option ? selectionFromLLMOption(option) : null;+}++interface IndexingModelSelectorProps {+ options: LLMOption[];+ selection: IndexingLLMSelection | null;+ loading: boolean;+ error: boolean;+ defaultUnavailable?: boolean;+ defaultLoadError?: boolean;+ disabled?: boolean;+ onChange: (selection: IndexingLLMSelection | null) => void;+}++export default function IndexingModelSelector({+ options,+ selection,+ loading,+ error,+ defaultUnavailable = false,+ defaultLoadError = false,+ disabled = false,+ onChange,+}: IndexingModelSelectorProps) {+ const { t } = useTranslation();+ const selected = options.find(+ (option) =>+ option.profile_id === selection?.profile_id &&+ option.model_id === selection?.model_id,+ );+ const reasoningOptions = (+ selected+ ? selected.supported_reasoning_efforts?.length+ ? reasoningEffortOptionsFromSupportedLevels(+ selected.supported_reasoning_efforts,+ )+ : reasoningEffortOptions(+ selected.provider,+ selected.model,+ selection?.reasoning_effort || selected.reasoning_effort || "",+ )+ : []+ ).filter(+ (option) =>+ option.value === "" || INDEXING_REASONING_EFFORTS.has(option.value),+ );++ if (loading && options.length === 0) {+ return (+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {t("Loading model catalog…")}+ </p>+ );+ }+ if (error && options.length === 0) {+ return (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {t(+ "The model catalog could not be loaded. Check model settings and try again.",+ )}+ </div>+ );+ }+ if (options.length === 0) {+ return (+ <div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">+ {t("No indexing model is available. Configure an LLM model first.")}+ </div>+ );+ }++ return (+ <div className="space-y-3">+ <label className="block">+ <span className="mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Indexing model")}+ </span>+ <select+ value={selected ? `${selected.profile_id}:${selected.model_id}` : ""}+ disabled={disabled}+ onChange={(event) => {+ const option = options.find(+ (item) =>+ `${item.profile_id}:${item.model_id}` === event.target.value,+ );+ onChange(option ? selectionFromLLMOption(option) : null);+ }}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] disabled:opacity-50"+ >+ <option value="" disabled>+ {t("Select an indexing model")}+ </option>+ {options.map((option) => (+ <option+ key={`${option.profile_id}:${option.model_id}`}+ value={`${option.profile_id}:${option.model_id}`}+ >+ {option.provider_label || option.profile_name} ·{" "}+ {option.model_name}+ {option.model_name !== option.model ? ` (${option.model})` : ""}+ </option>+ ))}+ </select>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.",+ )}+ </p>+ </label>++ {defaultUnavailable && !selection && (+ <div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">+ {t(+ "The current LightRAG query model is unavailable here. Choose an accessible indexing model.",+ )}+ </div>+ )}+ {defaultLoadError && !selection && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {t(+ "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.",+ )}+ </div>+ )}++ {selected && reasoningOptions.length > 0 && (+ <label className="block">+ <span className="mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Reasoning effort")}+ </span>+ <select+ value={selection?.reasoning_effort ?? ""}+ disabled={disabled}+ onChange={(event) =>+ onChange(selectionFromLLMOption(selected, event.target.value))+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] disabled:opacity-50"+ >+ {reasoningOptions.map((option) => (+ <option key={option.value || "auto"} value={option.value}>+ {t(option.label)}+ </option>+ ))}+ </select>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {t("Auto inherits the selected model's saved reasoning effort.")}+ </p>+ </label>+ )}+ </div>+ );+}diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsxindex 61aec12fe..516061135 100644--- a/web/components/knowledge/KbDocumentsSection.tsx+++ b/web/components/knowledge/KbDocumentsSection.tsx@@ -8,8 +8,9 @@ import {type KnowledgeUploadPolicy,} from "@/features/knowledge/api/files";import {- kbIsUploadable,+ kbCanUploadDocuments,kbNeedsReindex,+ kbRequiresLightRagRebuildBeforeAppend,providerUsesEmbeddingMetadata,resolveKbStatus,resolveProgressPercent,@@ -23,6 +24,7 @@ import ProcessLogs from "@/components/common/ProcessLogs";import FileDropZone from "./FileDropZone";import KbIndexFailureBanner from "./KbIndexFailureBanner";import KbUpdateHistory from "./KbUpdateHistory";+import LightRagIndexingProvenance from "./LightRagIndexingProvenance";interface KbDocumentsSectionProps {kb: KnowledgeBase;@@ -79,13 +81,19 @@ export default function KbDocumentsSection({};}, [kb.name]);- const uploadable = kbIsUploadable(kb);const needsReindex = kbNeedsReindex(kb);+ const requiresLightRagRebuild = kbRequiresLightRagRebuildBeforeAppend(kb);const status = resolveKbStatus(kb);const isError = status === "error";const provider =kb.statistics?.rag_provider || kb.metadata?.rag_provider || "llamaindex";const policyForProvider = uploadPolicyForProvider(uploadPolicy, provider);+ const publishedLightRagVersion =+ provider === "lightrag"+ ? kb.statistics?.index_versions?.find(+ (version) => version.provider === "lightrag" && version.ready,+ )+ : undefined;const isUploadingHere = task?.kind === "upload" && task.executing;const isIndexingHere =@@ -96,20 +104,26 @@ export default function KbDocumentsSection({// (Files tab) and upload replacements here, instead of being forced to// delete and rebuild the whole base. Uploads stay open unless a rebuild is// actively running; legacy/transition states remain genuinely blocked.- const canUpload = uploadable || (isError && !isIndexingHere);+ const canUpload = kbCanUploadDocuments(kb, isIndexingHere);const blockedReason = canUpload? null- : needsReindex+ : requiresLightRagRebuild? t(- "This knowledge base is in legacy index format and needs reindex before upload.",+ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",)- : status !== "ready"+ : needsReindex? t(- "This knowledge base is currently {{status}} and cannot accept uploads yet.",- { status: status.replaceAll("_", " ") },+ "This knowledge base is in legacy index format and needs reindex before upload.",)- : null;+ : status !== "ready"+ ? t(+ "This knowledge base is currently {{status}} and cannot accept uploads yet.",+ {+ status: status.replaceAll("_", " "),+ },+ )+ : null;const selection = validateFiles(files, policyForProvider, t);const canRetry = Boolean(onRetry) && isError && !isIndexingHere;@@ -172,6 +186,14 @@ export default function KbDocumentsSection({</p></div>+ {provider === "lightrag" && (+ <LightRagIndexingProvenance+ policy={kb.metadata?.indexing_policy}+ version={publishedLightRagVersion}+ compact+ />+ )}+{blockedReason && (<div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">{blockedReason}diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsxindex d94e7840a..c4d9a33b9 100644--- a/web/components/knowledge/KbIndexVersionsSection.tsx+++ b/web/components/knowledge/KbIndexVersionsSection.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";import {AlertTriangle,@@ -12,9 +12,12 @@ import {Star,} from "lucide-react";import {+ currentLightRagBuildCandidate,formatKnowledgeTimestamp,kbCanReindex,+ kbHasLiveProgress,kbNeedsReindex,+ lightRagVersionDisplayState,providerUsesEmbeddingMetadata,resolveKbStatus,resolveProgressPercent,@@ -23,25 +26,80 @@ import {} from "@/lib/knowledge-helpers";import type { TaskState } from "@/hooks/useKnowledgeProgress";import ProcessLogs from "@/components/common/ProcessLogs";+import Modal from "@/components/common/Modal";+import { useLLMOptions } from "@/hooks/useLLMOptions";+import { getLightRagConfig } from "@/features/knowledge/api/engines";+import type { LLMOption } from "@/lib/llm-options";+import type {+ IndexingLLMSelection,+ LightRagConfig,+} from "@/features/knowledge/model/types";import KbIndexFailureBanner from "./KbIndexFailureBanner";+import IndexingModelSelector, {+ selectionFromLightRagDefault,+ selectionFromLLMOption,+} from "./IndexingModelSelector";+import LightRagIndexingProvenance from "./LightRagIndexingProvenance";++export function selectionForLightRagModelDialog(+ options: LLMOption[],+ config: Pick<LightRagConfig, "llm_profile_id" | "llm_model_id">,+ activeDefault: {+ profile_id?: string | null;+ model_id?: string | null;+ } | null,+ savedPending: IndexingLLMSelection | undefined,+ preserveSavedPending: boolean,+): IndexingLLMSelection | null {+ const savedOption = preserveSavedPending+ ? options.find(+ (option) =>+ option.profile_id === savedPending?.profile_id &&+ option.model_id === savedPending?.model_id,+ )+ : undefined;+ return savedOption+ ? selectionFromLLMOption(+ savedOption,+ savedPending?.reasoning_effort || "",+ )+ : selectionFromLightRagDefault(options, config, activeDefault);+}interface KbIndexVersionsSectionProps {kb: KnowledgeBase;task?: TaskState;- onReindex: () => Promise<void>;+ onReindex: (indexingLLM?: IndexingLLMSelection) => Promise<void>;+ onUpdatePendingIndexingPolicy: (+ indexingLLM: IndexingLLMSelection,+ ) => Promise<void>;}export default function KbIndexVersionsSection({kb,task,onReindex,+ onUpdatePendingIndexingPolicy,}: KbIndexVersionsSectionProps) {const { t } = useTranslation();const [submitting, setSubmitting] = useState(false);+ const [modelDialogOpen, setModelDialogOpen] = useState(false);+ const [indexingLLM, setIndexingLLM] = useState<IndexingLLMSelection | null>(+ null,+ );+ const [dialogError, setDialogError] = useState<string | null>(null);+ const [lightRagConfig, setLightRagConfig] = useState<LightRagConfig | null>(+ null,+ );+ const [lightRagConfigLoaded, setLightRagConfigLoaded] = useState(false);+ const [lightRagConfigError, setLightRagConfigError] = useState(false);+ const llmCatalog = useLLMOptions();const provider = kb.statistics?.rag_provider || "llamaindex";+ const isLightRag = provider === "lightrag";const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);+ const modelInsensitiveProvider = pageIndexProvider || isLightRag;const versions = kb.statistics?.index_versions ?? [];- const activeSig = pageIndexProvider+ const activeSig = modelInsensitiveProvider? null: (kb.statistics?.active_signature ?? null);const needsReindex = kbNeedsReindex(kb);@@ -53,7 +111,78 @@ export default function KbIndexVersionsSection({const lastIndexed = formatKnowledgeTimestamp(kb.metadata?.last_indexed_at);const lastIndexedCount = kb.metadata?.last_indexed_count;+ const publishedLightRagVersion = isLightRag+ ? versions.find(+ (version) => version.provider === "lightrag" && version.ready,+ )+ : undefined;+ const buildingLightRagVersion = isLightRag+ ? currentLightRagBuildCandidate(versions, Boolean(isReindexingHere))+ : undefined;+ const emptyPendingEligible =+ isLightRag &&+ !kb.read_only &&+ kb.statistics?.raw_documents === 0 &&+ !publishedLightRagVersion &&+ !kbHasLiveProgress(kb) &&+ !task?.executing;++ useEffect(() => {+ if (!isLightRag) return;+ let cancelled = false;+ void getLightRagConfig()+ .then((config) => {+ if (!cancelled) {+ setLightRagConfig(config);+ setLightRagConfigError(false);+ }+ })+ .catch(() => {+ if (!cancelled) setLightRagConfigError(true);+ })+ .finally(() => {+ if (!cancelled) setLightRagConfigLoaded(true);+ });+ return () => {+ cancelled = true;+ };+ }, [isLightRag, t]);++ useEffect(() => {+ if (!modelDialogOpen || indexingLLM || llmCatalog.options.length === 0)+ return;+ if (!lightRagConfigLoaded || !lightRagConfig) return;+ setIndexingLLM(+ selectionForLightRagModelDialog(+ llmCatalog.options,+ lightRagConfig,+ llmCatalog.activeDefault,+ kb.metadata?.indexing_policy?.selection,+ emptyPendingEligible,+ ),+ );+ }, [+ emptyPendingEligible,+ indexingLLM,+ kb.metadata?.indexing_policy?.selection,+ llmCatalog.activeDefault,+ llmCatalog.options,+ lightRagConfig,+ lightRagConfigLoaded,+ modelDialogOpen,+ ]);++ const openModelDialog = () => {+ setIndexingLLM(null);+ setDialogError(null);+ setModelDialogOpen(true);+ };+const handleReindex = async () => {+ if (isLightRag) {+ openModelDialog();+ return;+ }setSubmitting(true);try {await onReindex();@@ -62,6 +191,24 @@ export default function KbIndexVersionsSection({}};+ const handleModelSubmit = async () => {+ if (!indexingLLM) return;+ setSubmitting(true);+ setDialogError(null);+ try {+ if (emptyPendingEligible) {+ await onUpdatePendingIndexingPolicy(indexingLLM);+ } else {+ await onReindex(indexingLLM);+ }+ setModelDialogOpen(false);+ } catch (error) {+ setDialogError(error instanceof Error ? error.message : String(error));+ } finally {+ setSubmitting(false);+ }+ };+const showReindexCta = kbCanReindex(kb);return (@@ -80,13 +227,15 @@ export default function KbIndexVersionsSection({{t(pageIndexProvider? "PageIndex versions are model-insensitive and preserve rebuild history."- : "Each embedding configuration gets its own stored vector index.",+ : isLightRag+ ? "Each full rebuild publishes a separate LightRAG index version."+ : "Each embedding configuration gets its own stored vector index.",)}</p></div></div>- {showReindexCta && (+ {(showReindexCta || emptyPendingEligible) && (<buttontype="button"onClick={handleReindex}@@ -97,9 +246,11 @@ export default function KbIndexVersionsSection({"Retry indexing from the documents already stored in this knowledge base.",): t(- pageIndexProvider- ? "Rebuild this PageIndex knowledge base. Existing index versions are preserved."- : "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",+ isLightRag+ ? "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds."+ : pageIndexProvider+ ? "Rebuild this PageIndex knowledge base. Existing index versions are preserved."+ : "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",)}className={`inline-flex shrink-0 items-center gap-1.5 rounded-md border px-2.5 py-1 text-[12px] font-medium transition-colors disabled:opacity-50 ${@@ -113,20 +264,29 @@ export default function KbIndexVersionsSection({) : (<RefreshCw className="h-3 w-3" />)}- {isReindexingHere- ? isError- ? t("Retrying…")- : t("Re-indexing…")- : isError- ? t("Retry indexing")- : t("Re-index")}+ {emptyPendingEligible+ ? t("Change model")+ : isReindexingHere+ ? isError+ ? t("Retrying…")+ : t("Re-indexing…")+ : isError+ ? t("Retry indexing")+ : t("Re-index")}</button>)}</div>{isError && <KbIndexFailureBanner kb={kb} />}- {!pageIndexProvider && !isError && (needsReindex || mismatch) && (+ {isLightRag && (+ <LightRagIndexingProvenance+ policy={kb.metadata?.indexing_policy}+ version={publishedLightRagVersion}+ />+ )}++ {!modelInsensitiveProvider && !isError && (needsReindex || mismatch) && (<div className="rounded-lg border border-amber-200 bg-amber-50/80 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-amber-300">{t("The active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.",@@ -149,7 +309,9 @@ export default function KbIndexVersionsSection({lastIndexedCount === 1? "{{count}} indexed doc": "{{count}} indexed docs",- { count: lastIndexedCount },+ {+ count: lastIndexedCount,+ },)}</span>)}@@ -165,6 +327,15 @@ export default function KbIndexVersionsSection({}version={version}activeSignature={activeSig}+ isPublishedLightRag={version === publishedLightRagVersion}+ isLightRagVersion={isLightRag}+ isLegacyLightRag={+ isLightRag &&+ kb.metadata?.indexing_policy?.policy === "legacy_unpinned" &&+ version.ready === true+ }+ isRebuildActive={version === buildingLightRagVersion}+ kbError={isError}/>))}</ul>@@ -210,6 +381,73 @@ export default function KbIndexVersionsSection({)}</div>)}++ <Modal+ isOpen={modelDialogOpen}+ onClose={() => !submitting && setModelDialogOpen(false)}+ title={+ emptyPendingEligible+ ? t("Change pending indexing model")+ : t("Re-index with a pinned model")+ }+ width="sm"+ footer={+ <div className="flex justify-end gap-2">+ <button+ type="button"+ onClick={() => setModelDialogOpen(false)}+ disabled={submitting}+ className="rounded-md border border-[var(--border)] px-3 py-1.5 text-[12px] text-[var(--foreground)] disabled:opacity-50"+ >+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={() => void handleModelSubmit()}+ disabled={submitting || !indexingLLM}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {submitting && <Loader2 className="h-3 w-3 animate-spin" />}+ {emptyPendingEligible+ ? t("Save model")+ : t("Start full re-index")}+ </button>+ </div>+ }+ >+ <div className="space-y-3 p-4">+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {emptyPendingEligible+ ? t(+ "This selection will take effect when the empty knowledge base is indexed for the first time.",+ )+ : t(+ "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.",+ )}+ </p>+ <IndexingModelSelector+ options={llmCatalog.options}+ selection={indexingLLM}+ loading={llmCatalog.loading}+ error={llmCatalog.error}+ defaultUnavailable={+ lightRagConfigLoaded &&+ !!(+ lightRagConfig?.llm_profile_id || lightRagConfig?.llm_model_id+ ) &&+ !indexingLLM+ }+ defaultLoadError={lightRagConfigError}+ disabled={submitting}+ onChange={setIndexingLLM}+ />+ {dialogError && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {dialogError}+ </div>+ )}+ </div>+ </Modal></div>);}@@ -217,22 +455,48 @@ export default function KbIndexVersionsSection({function IndexVersionRow({version,activeSignature,+ isPublishedLightRag,+ isLightRagVersion,+ isLegacyLightRag,+ isRebuildActive,+ kbError,}: {version: IndexVersion;activeSignature: string | null;+ isPublishedLightRag: boolean;+ isLightRagVersion: boolean;+ isLegacyLightRag: boolean;+ isRebuildActive: boolean;+ kbError: boolean;}) {const { t } = useTranslation();const matchesActive =!!version.signature && version.signature === activeSignature;- const isActive = matchesActive && version.ready === true;+ const lightRagState = isLightRagVersion+ ? lightRagVersionDisplayState(version, {+ published: isPublishedLightRag,+ rebuildActive: isRebuildActive,+ kbError,+ legacy: isLegacyLightRag,+ })+ : null;+ const isActive =+ lightRagState === "published" ||+ (!isLightRagVersion && matchesActive && version.ready === true);const isPhantom = matchesActive && version.ready !== true;- const isLegacy = !!version.legacy;+ const isLegacy = lightRagState === "legacy" || !!version.legacy;+ const isFailedLightRagCandidate = lightRagState === "failed";+ const isBuildingLightRagCandidate = lightRagState === "building";- const title = isLegacy- ? t("Legacy index")- : version.model- ? version.model- : (version.signature ?? t("Unknown"));+ const title = isFailedLightRagCandidate+ ? t("Failed rebuild candidate")+ : isBuildingLightRagCandidate+ ? t("Rebuild candidate in progress")+ : isLegacy+ ? t("Legacy index")+ : version.model+ ? version.model+ : (version.signature ?? t("Unknown"));const created = formatKnowledgeTimestamp(version.created_at);@@ -258,6 +522,8 @@ function IndexVersionRow({>{isActive ? (<Star className="h-3.5 w-3.5" fill="currentColor" />+ ) : isBuildingLightRagCandidate ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />) : isPhantom ? (<AlertTriangle className="h-3.5 w-3.5" />) : isLegacy ? (@@ -293,6 +559,16 @@ function IndexVersionRow({{t("Legacy")}</span>)}+ {isFailedLightRagCandidate && (+ <span className="rounded-full bg-red-100 px-1.5 py-0.5 text-[10px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-300">+ {t("Not published")}+ </span>+ )}+ {isBuildingLightRagCandidate && (+ <span className="rounded-full bg-blue-100 px-1.5 py-0.5 text-[10px] font-medium text-blue-700 dark:bg-blue-950/30 dark:text-blue-300">+ {t("Building")}+ </span>+ )}</div><div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10.5px] text-[var(--muted-foreground)]">{typeof version.dimension === "number" && (@@ -306,6 +582,11 @@ function IndexVersionRow({{version.signature && (<span className="font-mono">{version.signature.slice(0, 10)}</span>)}+ {version.failure_summary && (+ <span className="text-red-600 dark:text-red-300">+ {version.failure_summary}+ </span>+ )}</div></div></li>diff --git a/web/components/knowledge/KbSettingsSection.tsx b/web/components/knowledge/KbSettingsSection.tsxindex c1b191fce..659073c2f 100644--- a/web/components/knowledge/KbSettingsSection.tsx+++ b/web/components/knowledge/KbSettingsSection.tsx@@ -8,6 +8,7 @@ import {providerUsesEmbeddingMetadata,type KnowledgeBase,} from "@/lib/knowledge-helpers";+import LightRagIndexingProvenance from "./LightRagIndexingProvenance";interface KbSettingsSectionProps {kb: KnowledgeBase;@@ -39,6 +40,12 @@ export default function KbSettingsSection({const created = formatKnowledgeTimestamp(meta.created_at);const updated = formatKnowledgeTimestamp(meta.last_updated);const lastIndexed = formatKnowledgeTimestamp(meta.last_indexed_at);+ const publishedLightRagVersion =+ provider === "lightrag"+ ? kb.statistics?.index_versions?.find(+ (version) => version.provider === "lightrag" && version.ready,+ )+ : undefined;return (<div className="space-y-6">@@ -80,6 +87,18 @@ export default function KbSettingsSection({</dl></section>+ {provider === "lightrag" && (+ <section className="space-y-3">+ <div className="text-[13px] font-medium text-[var(--foreground)]">+ {t("Indexing model provenance")}+ </div>+ <LightRagIndexingProvenance+ policy={meta.indexing_policy}+ version={publishedLightRagVersion}+ />+ </section>+ )}+<section className="space-y-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3"><div><div className="text-[12.5px] font-medium text-[var(--foreground)]">diff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsxindex d7148d416..2390c7c43 100644--- a/web/components/knowledge/KnowledgeBaseDetail.tsx+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx@@ -16,7 +16,10 @@ import {Star,Upload,} from "lucide-react";-import type { KnowledgeUploadPolicy } from "@/features/knowledge/model/types";+import type {+ IndexingLLMSelection,+ KnowledgeUploadPolicy,+} from "@/features/knowledge/model/types";import {formatKnowledgeTimestamp,isMarginNoteKb,@@ -52,7 +55,14 @@ interface KnowledgeBaseDetailProps {files: File[],destSubdir?: string,) => Promise<void>;- onReindex: (kbName: string) => Promise<void>;+ onReindex: (+ kbName: string,+ indexingLLM?: IndexingLLMSelection,+ ) => Promise<void>;+ onUpdatePendingIndexingPolicy: (+ kbName: string,+ indexingLLM: IndexingLLMSelection,+ ) => Promise<void>;onRetry: (kbName: string) => Promise<void>;onSetDefault: (kbName: string) => Promise<void>;onDelete: (kbName: string) => Promise<void>;@@ -84,6 +94,7 @@ export default function KnowledgeBaseDetail({onCreate,onUpload,onReindex,+ onUpdatePendingIndexingPolicy,onRetry,onSetDefault,onDelete,@@ -289,12 +300,17 @@ export default function KnowledgeBaseDetail({<KbIndexVersionsSectionkb={kb}task={task}- onReindex={() =>+ onReindex={(indexingLLM) =>kb.read_only? Promise.resolve()- : status === "error"+ : status === "error" && kbProvider(kb) !== "lightrag"? handleRetry()- : onReindex(kb.name)+ : onReindex(kb.name, indexingLLM)+ }+ onUpdatePendingIndexingPolicy={(indexingLLM) =>+ kb.read_only+ ? Promise.resolve()+ : onUpdatePendingIndexingPolicy(kb.name, indexingLLM)}/>)}diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsxindex 92d750761..85c097a20 100644--- a/web/components/knowledge/KnowledgePage.tsx+++ b/web/components/knowledge/KnowledgePage.tsx@@ -14,6 +14,7 @@ import {decodeResourceSegment,knowledgeBaseRoute,} from "@/lib/resource-routes";+import type { IndexingLLMSelection } from "@/features/knowledge/model/types";export default function KnowledgePage() {const { t } = useTranslation();@@ -42,6 +43,7 @@ export default function KnowledgePage() {uploadFiles,setDefault,reindex,+ updatePendingIndexingPolicy,retry,deleteKb,connectObsidian,@@ -229,16 +231,29 @@ export default function KnowledgePage() {);const handleReindex = useCallback(- async (kbName: string) => {+ async (kbName: string, indexingLLM?: IndexingLLMSelection) => {try {- await reindex(kbName);+ await reindex(kbName, indexingLLM);} catch (err) {setError(err instanceof Error ? err.message : String(err));+ throw err;}},[reindex, setError],);+ const handleUpdatePendingIndexingPolicy = useCallback(+ async (kbName: string, indexingLLM: IndexingLLMSelection) => {+ try {+ await updatePendingIndexingPolicy(kbName, indexingLLM);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ throw err;+ }+ },+ [setError, updatePendingIndexingPolicy],+ );+const handleRetry = useCallback(async (kbName: string) => {try {@@ -337,6 +352,7 @@ export default function KnowledgePage() {onCreate={openCreate}onUpload={handleUpload}onReindex={handleReindex}+ onUpdatePendingIndexingPolicy={handleUpdatePendingIndexingPolicy}onRetry={handleRetry}onSetDefault={handleSetDefault}onDelete={handleDelete}diff --git a/web/components/knowledge/LightRagIndexingProvenance.tsx b/web/components/knowledge/LightRagIndexingProvenance.tsxnew file mode 100644index 000000000..337320e68--- /dev/null+++ b/web/components/knowledge/LightRagIndexingProvenance.tsx@@ -0,0 +1,104 @@+"use client";++import { useTranslation } from "react-i18next";+import {+ formatKnowledgeTimestamp,+ type IndexVersion,+ type LightRagIndexingPolicy,+} from "@/lib/knowledge-helpers";++interface LightRagIndexingProvenanceProps {+ policy?: LightRagIndexingPolicy;+ version?: IndexVersion;+ compact?: boolean;+}++export default function LightRagIndexingProvenance({+ policy,+ version,+ compact = false,+}: LightRagIndexingProvenanceProps) {+ const { t } = useTranslation();+ const resolved = policy ?? { policy: "legacy_unpinned" };+ const pending = resolved.policy === "pending_pinned";+ const pinned = resolved.policy === "pinned" || pending;+ const model = resolved.descriptor?.model;+ const binding = resolved.descriptor?.binding;+ const modelLabel = [binding, model].filter(Boolean).join(" · ");+ const effort = resolved.descriptor?.reasoning_effort;+ const title = pending+ ? t("Pending pinned indexing model")+ : pinned+ ? t("Pinned indexing model")+ : t("Legacy unpinned indexing model");+ const summary = pending+ ? t(+ "Takes effect on the first index. No index version has been published yet.",+ )+ : pinned+ ? t("Incremental indexing continues with this pinned model.")+ : t(+ "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.",+ );++ return (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--muted)]/25 px-3 py-2.5">+ <div className="text-[12px] font-medium text-[var(--foreground)]">+ {title}+ </div>+ <p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">+ {summary}+ </p>+ {compact && (+ <p className="mt-1 text-[11px] font-medium text-[var(--foreground)]">+ {modelLabel || t("Unverified historical indexing model")}+ {` · ${t("Reasoning effort")}: ${effort || t("Model default")}`}+ </p>+ )}+ {!compact && (+ <dl className="mt-2 grid gap-x-4 gap-y-1 text-[11px] sm:grid-cols-2">+ <ProvenanceField label={t("Model")}>+ {modelLabel || t("Unverified historical indexing model")}+ </ProvenanceField>+ <ProvenanceField label={t("Reasoning effort")}>+ {effort || t("Model default")}+ </ProvenanceField>+ <ProvenanceField label={t("VLM capability")}>+ {typeof resolved.vision_available === "boolean"+ ? resolved.vision_available+ ? t("Available")+ : t("Unavailable")+ : t("Unknown")}+ {resolved.vlm_used === true+ ? ` · ${t("used for this version")}`+ : resolved.vlm_used === false+ ? ` · ${t("not used for this version")}`+ : ""}+ </ProvenanceField>+ <ProvenanceField label={t("Version source")}>+ {version?.version ||+ (pending ? t("Pending configuration") : t("Legacy metadata"))}+ {version?.created_at+ ? ` · ${formatKnowledgeTimestamp(version.created_at)}`+ : ""}+ </ProvenanceField>+ </dl>+ )}+ </div>+ );+}++function ProvenanceField({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <div>+ <dt className="text-[var(--muted-foreground)]">{label}</dt>+ <dd className="break-words text-[var(--foreground)]">{children}</dd>+ </div>+ );+}diff --git a/web/components/settings/SubagentSettingsEditor.tsx b/web/components/settings/SubagentSettingsEditor.tsxindex 485aa2c89..a07edeefd 100644--- a/web/components/settings/SubagentSettingsEditor.tsx+++ b/web/components/settings/SubagentSettingsEditor.tsx@@ -24,7 +24,7 @@ import {type Lang = { zh: string; en: string };-/** The CLI default sentinel — empty model/effort means "let the CLI decide". */+/** Empty model/effort means "let the selected runtime decide". */const CUSTOM = "__custom__";// Defaults mirror BackendConfig in deeptutor/services/subagent/config.py so the@@ -142,6 +142,15 @@ const KIND_FEATURES: Record<string, KindFeatures> = {thinking: false,forwardImages: true, // --image},+ hermes_remote: {+ effort: true,+ systemPrompt: true,+ permissionMode: false,+ codexSandbox: false,+ autoApprove: true,+ thinking: false,+ forwardImages: false,+ },openclaw: {effort: true, // --thinkingsystemPrompt: true,@@ -171,6 +180,7 @@ const DISPLAY_NAMES: Record<string, string> = {opencode: "opencode",mimo: "MiMo Code",hermes: "Hermes Agent",+ hermes_remote: "Hermes Agent (remote)",openclaw: "OpenClaw",deepseek_harness: "DeepSeek Harness",};@@ -198,6 +208,10 @@ const SYSTEM_PROMPT_HINT: Record<string, Lang> = {zh: "Hermes 没有系统提示 flag——该指令会前缀在每个新会话的第一条消息上。",en: "Hermes has no system-prompt flag — the instruction is prefixed to each new session's first message.",},+ hermes_remote: {+ zh: "新会话(或远端会话已失效)时,通过 Hermes 网关 API 的 instructions 字段注入。",+ en: "Sent through the Hermes gateway API's instructions field for a fresh or expired session.",+ },openclaw: {zh: "该指令会前缀在每个新 OpenClaw session key 的第一条消息上。",en: "The instruction is prefixed to the first message for each new OpenClaw session key.",@@ -330,6 +344,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {);const features = KIND_FEATURES[kind] ?? FALLBACK_FEATURES;+ const isRemote = kind === "hermes_remote";const knownSlugs = useMemo(() => new Set((options?.models ?? []).map((m) => m.slug)),[options],@@ -376,10 +391,17 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {<div><SettingsPageHeadertitle={displayName}- description={tr({- zh: `DeepTutor 通过 consult_subagent 调用本机 ${displayName} 时使用的模型、推理强度与运行参数。设置后即覆盖 CLI 的默认值;留空表示沿用 CLI 默认。`,- en: `Model, reasoning effort, and run parameters DeepTutor drives the local ${displayName} with when consulting it. These override the CLI defaults; leave blank to keep the CLI's own default.`,- })}+ description={+ isRemote+ ? tr({+ zh: "配置 DeepTutor 通过 HTTP 调用的远程 Hermes 网关、模型与运行参数。",+ en: "Configure the remote Hermes gateway, model, and run parameters DeepTutor uses over HTTP.",+ })+ : tr({+ zh: `DeepTutor 通过 consult_subagent 调用本机 ${displayName} 时使用的模型、推理强度与运行参数。设置后即覆盖 CLI 的默认值;留空表示沿用 CLI 默认。`,+ en: `Model, reasoning effort, and run parameters DeepTutor drives the local ${displayName} with when consulting it. These override the CLI defaults; leave blank to keep the CLI's own default.`,+ })+ }/>{loading && (@@ -401,13 +423,24 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {the user can re-pull them on demand. */}<SettingSectiontitle={tr({ zh: "连接与同步", en: "Connection & sync" })}- description={tr({- zh: "供应商会不定期增删模型与推理档位——随时点同步即可重新拉取最新列表。",- en: "Vendors add and retire models and effort levels over time — sync any time to re-pull the latest lists.",- })}+ description={+ isRemote+ ? tr({+ zh: "检查已配置网关的连通性与认证状态。",+ en: "Check connectivity and authentication for the configured gateway.",+ })+ : tr({+ zh: "供应商会不定期增删模型与推理档位——随时点同步即可重新拉取最新列表。",+ en: "Vendors add and retire models and effort levels over time — sync any time to re-pull the latest lists.",+ })+ }><SettingRow- title={tr({ zh: "本机状态", en: "On this machine" })}+ title={+ isRemote+ ? tr({ zh: "网关状态", en: "Gateway status" })+ : tr({ zh: "本机状态", en: "On this machine" })+ }description={options.available? options.version@@ -432,8 +465,12 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {<XCircle className="h-3.5 w-3.5" />)}{options.available- ? tr({ zh: "已安装", en: "Installed" })- : tr({ zh: "未检测到", en: "Not detected" })}+ ? isRemote+ ? tr({ zh: "可连接", en: "Reachable" })+ : tr({ zh: "已安装", en: "Installed" })+ : isRemote+ ? tr({ zh: "不可用", en: "Unavailable" })+ : tr({ zh: "未检测到", en: "Not detected" })}</span>}/>@@ -445,27 +482,115 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {zh: `上次同步:${formatTs(options.synced_at, zh)}`,en: `Last synced: ${formatTs(options.synced_at, zh)}`,})- : tr({- zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",- en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",- })+ : isRemote+ ? tr({+ zh: "远程网关当前不提供模型枚举;可以留空使用网关默认值,或手动填写模型名。",+ en: "The remote gateway does not currently enumerate models here; use its default or enter a model name manually.",+ })+ : tr({+ zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",+ en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",+ })}control={- <button- type="button"- disabled={syncing}- onClick={() => void sync()}- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/40 disabled:opacity-60"- >- <RefreshCw- className={`h-3.5 w-3.5 ${syncing ? "animate-spin" : ""}`}- />- {tr({ zh: "同步", en: "Sync" })}- </button>+ isRemote ? (+ <span className="text-[12px] text-[var(--muted-foreground)]">+ {tr({ zh: "网关模型由服务端提供", en: "Gateway models are server-managed" })}+ </span>+ ) : (+ <button+ type="button"+ disabled={syncing}+ onClick={() => void sync()}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/40 disabled:opacity-60"+ >+ <RefreshCw+ className={`h-3.5 w-3.5 ${syncing ? "animate-spin" : ""}`}+ />+ {tr({ zh: "同步", en: "Sync" })}+ </button>+ )}/></SettingSection>+ {isRemote && (+ <SettingSection+ title={tr({ zh: "远程网关", en: "Remote gateway" })}+ description={tr({+ zh: "密钥只从环境变量读取;这里仅保存变量名,不保存密钥值。",+ en: "The bearer is read only from the environment; this stores the variable name, never the secret.",+ })}+ >+ <SettingRow+ title={tr({ zh: "网关 URL", en: "Gateway URL" })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ value={config.base_url ?? ""}+ placeholder={tr({+ zh: "例如:http://hermes-uni:8642",+ en: "e.g. http://hermes-uni:8642",+ })}+ onChange={(e) => setConfig((p) => ({ ...p, base_url: e.target.value }))}+ onBlur={(e) => void save({ base_url: e.target.value.trim() })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "密钥环境变量", en: "API key environment variable" })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ value={config.api_key_env ?? "DEEPTUTOR_HERMES_REMOTE_API_KEY"}+ onChange={(e) => setConfig((p) => ({ ...p, api_key_env: e.target.value }))}+ onBlur={(e) => void save({ api_key_env: e.target.value.trim() })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "配置 profile", en: "Profile label" })}+ description={tr({+ zh: "仅作部署标识,不会把密钥写入设置。",+ en: "Informational deployment label; it never stores a key.",+ })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ value={config.profile ?? ""}+ onChange={(e) => setConfig((p) => ({ ...p, profile: e.target.value }))}+ onBlur={(e) => void save({ profile: e.target.value.trim() })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "空闲超时(秒)", en: "Idle timeout (seconds)" })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ type="number"+ min={1}+ max={86400}+ value={config.idle_timeout_seconds ?? 600}+ onChange={(e) =>+ setConfig((p) => ({+ ...p,+ idle_timeout_seconds: Number.parseInt(e.target.value, 10),+ }))+ }+ onBlur={(e) =>+ void save({ idle_timeout_seconds: Number.parseInt(e.target.value, 10) })+ }+ />+ }+ />+ </SettingSection>+ )}+<SettingSectiontitle={tr({ zh: "模型", en: "Model" })}description={tr({@@ -498,7 +623,9 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {onChange={(e) => onModelSelect(e.target.value)}><option value="">- {tr({ zh: "CLI 默认", en: "CLI default" })}+ {isRemote+ ? tr({ zh: "网关默认", en: "Gateway default" })+ : tr({ zh: "CLI 默认", en: "CLI default" })}</option>{options.models.map((m) => (<option key={m.slug} value={m.slug}>@@ -542,7 +669,9 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {onChange={(e) => void save({ effort: e.target.value })}><option value="">- {tr({ zh: "CLI 默认", en: "CLI default" })}+ {isRemote+ ? tr({ zh: "网关默认", en: "Gateway default" })+ : tr({ zh: "CLI 默认", en: "CLI default" })}</option>{effortChoices.map((eff) => (<option key={eff} value={eff}>diff --git a/web/components/space/learning/LearningBoard.tsx b/web/components/space/learning/LearningBoard.tsxnew file mode 100644index 000000000..4e1b5d826--- /dev/null+++ b/web/components/space/learning/LearningBoard.tsx@@ -0,0 +1,163 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ BookOpen,+ Circle,+ CircleCheck,+ CircleDot,+ Loader2,+ MessageSquare,+} from "lucide-react";++import {+ fetchObjectiveReport,+ type BoardModule,+ type ObjectiveReport,+ type ObjectiveStatus,+} from "@/lib/learning-api";++import { ObjectiveDetail } from "./ObjectiveDetail";+import { formatRelative, knowledgeTypeLabel } from "./format";++const STATUS_BORDER: Record<ObjectiveStatus, string> = {+ mastered: "border-green-500/50",+ learning: "border-yellow-500/50",+ new: "border-[var(--border)]",+};++const STATUS_ICON: Record<ObjectiveStatus, React.ReactNode> = {+ mastered: <CircleCheck className="h-3.5 w-3.5 text-green-500" />,+ learning: <CircleDot className="h-3.5 w-3.5 text-yellow-500" />,+ new: <Circle className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />,+};++/**+ * The topic as a board: modules become columns and objectives become cards.+ *+ * The projection is read-only; opening a card still reads the same evidence+ * trail as the outline and starts the same Mastery Study surface.+ */+export function LearningBoard({+ pathId,+ modules,+ revision,+ zh,+ onStartTutoring,+}: {+ pathId: string;+ modules: BoardModule[];+ revision: number;+ zh: boolean;+ onStartTutoring: (knowledgePointName: string) => void;+}) {+ const { t } = useTranslation();+ const [openId, setOpenId] = useState<string | null>(null);+ const [report, setReport] = useState<ObjectiveReport | null>(null);+ const [reportError, setReportError] = useState(false);+ const loaded = openId !== null && report?.id === openId;++ useEffect(() => {+ if (!openId) return;+ const controller = new AbortController();+ fetchObjectiveReport(pathId, openId, { signal: controller.signal })+ .then((result) => {+ setReport(result);+ setReportError(false);+ })+ .catch(() => {+ if (controller.signal.aborted) return;+ setReport(null);+ setReportError(true);+ });+ return () => controller.abort();+ }, [openId, pathId, revision]);++ const toggle = useCallback((id: string) => {+ setOpenId((current) => (current === id ? null : id));+ setReport(null);+ setReportError(false);+ }, []);++ return (+ <div className="flex gap-4 overflow-x-auto pb-2">+ {modules.map((module) => (+ <div+ key={module.id}+ className="flex w-64 shrink-0 flex-col gap-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 p-3"+ >+ <div className="flex items-center justify-between gap-2">+ <h3 className="min-w-0 truncate text-[13px] font-semibold text-[var(--foreground)]">+ {module.name}+ </h3>+ <span className="shrink-0 text-[11px] tabular-nums text-[var(--muted-foreground)]">+ {module.mastered}/{module.total}+ </span>+ </div>++ {module.cards.map((card) => {+ const open = openId === card.id;+ return (+ <div key={card.id}>+ <button+ type="button"+ onClick={() => toggle(card.id)}+ aria-expanded={open}+ className={`w-full rounded-lg border bg-[var(--card)] p-3 text-left transition hover:bg-[var(--muted)]/60 ${STATUS_BORDER[card.status]}`}+ >+ <div className="flex items-start justify-between gap-2">+ <span className="text-[13px] leading-snug text-[var(--foreground)]">+ {card.name}+ </span>+ {STATUS_ICON[card.status]}+ </div>+ <div className="mt-2 flex items-center justify-between gap-2 text-[11px]">+ <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[var(--muted-foreground)]">+ {knowledgeTypeLabel(card.type, t)}+ </span>+ <span className="shrink-0 tabular-nums text-[var(--muted-foreground)]">+ {Math.round(card.mastery_level * 100)}%+ </span>+ </div>+ {card.next_review_at && (+ <div className="mt-1.5 flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]">+ <BookOpen className="h-3 w-3" />+ {t("Review")} {formatRelative(card.next_review_at, zh)}+ </div>+ )}+ </button>++ {open && (+ <div className="mt-2 rounded-lg border border-[var(--border)] bg-[var(--card)] p-3">+ {loaded && report ? (+ <>+ <ObjectiveDetail report={report} zh={zh} />+ <button+ type="button"+ onClick={() => onStartTutoring(card.name)}+ className="mt-2 flex h-8 w-full items-center justify-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 text-xs font-medium text-[var(--primary-foreground)] transition hover:opacity-90"+ >+ <MessageSquare className="h-3.5 w-3.5" />+ {t("Start tutoring")}+ </button>+ </>+ ) : reportError ? (+ <p className="py-3 text-center text-xs text-[var(--muted-foreground)]">+ {t("Evidence could not be loaded")}+ </p>+ ) : (+ <div className="flex items-center justify-center py-3 text-[var(--muted-foreground)]">+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ ))}+ </div>+ );+}diff --git a/web/components/watching/WatchingPane.tsx b/web/components/watching/WatchingPane.tsxindex 01a63fb8a..d88f30346 100644--- a/web/components/watching/WatchingPane.tsx+++ b/web/components/watching/WatchingPane.tsx@@ -3,8 +3,10 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {AlertTriangle,+ ChevronsDown,Check,Captions,+ Copy,ExternalLink,Loader2,Pencil,@@ -22,6 +24,7 @@ import type { PlayerController } from "@/lib/video-player-controller";import {createVideoNote,deleteVideoNote,+ exportVideoNotes,listVideoNotes,saveVideoProgress,updateVideoNote,@@ -62,8 +65,13 @@ export function WatchingPane({ onClose }: { onClose(): void }) {const [editingNoteId, setEditingNoteId] = useState<string | null>(null);const [editingDraft, setEditingDraft] = useState("");const [noteBusy, setNoteBusy] = useState(false);+ const [notesExportBusy, setNotesExportBusy] = useState(false);+ const [notesCopied, setNotesCopied] = useState(false);const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);+ const notesExportRequestRef = useRef(0);+ const [followTranscript, setFollowTranscript] = useState(true);const controllerRef = useRef<PlayerController | null>(null);+ const transcriptListRef = useRef<HTMLDivElement | null>(null);const activeMaterialIdRef = useRef(materialId);const lastSavedRef = useRef(0);const stateRef = useRef({ time: 0, duration: 0 });@@ -138,6 +146,26 @@ export function WatchingPane({ onClose }: { onClose(): void }) {[material, time],);+ useEffect(() => {+ setFollowTranscript(true);+ }, [materialId]);++ useEffect(() => {+ if (!followTranscript || tab !== "transcript" || !cue) return;+ const list = transcriptListRef.current;+ const activeRow = list?.querySelector<HTMLButtonElement>(+ '[data-active-cue="true"]',+ );+ if (!list || !activeRow) return;+ const rowTop =+ activeRow.getBoundingClientRect().top -+ list.getBoundingClientRect().top ++ list.scrollTop -+ list.clientHeight / 2 ++ activeRow.clientHeight / 2;+ list.scrollTo({ top: Math.max(0, rowTop), behavior: "smooth" });+ }, [cue, followTranscript, tab]);+const submit = async (providerOverride?: "youtube") => {const url = (providerOverride ? lastUrl || input : input).trim();if (!url) return;@@ -166,6 +194,9 @@ export function WatchingPane({ onClose }: { onClose(): void }) {setEditingNoteId(null);setEditingDraft("");setPendingDeleteId(null);+ notesExportRequestRef.current += 1;+ setNotesExportBusy(false);+ setNotesCopied(false);if (!materialId) {setNotesLoading(false);return () => {@@ -216,6 +247,7 @@ export function WatchingPane({ onClose }: { onClose(): void }) {if (activeMaterialIdRef.current !== requestedMaterialId) return;setNotes((current) => sortNotes([...current, saved]));setNoteDraft("");+ setNotesCopied(false);} catch (caught) {if (activeMaterialIdRef.current !== requestedMaterialId) return;setNotesError(@@ -247,6 +279,7 @@ export function WatchingPane({ onClose }: { onClose(): void }) {);setEditingNoteId(null);setEditingDraft("");+ setNotesCopied(false);} catch (caught) {if (activeMaterialIdRef.current !== requestedMaterialId) return;setNotesError(@@ -273,6 +306,7 @@ export function WatchingPane({ onClose }: { onClose(): void }) {setEditingDraft("");}setPendingDeleteId(null);+ setNotesCopied(false);} catch (caught) {if (activeMaterialIdRef.current !== requestedMaterialId) return;setNotesError(@@ -283,6 +317,31 @@ export function WatchingPane({ onClose }: { onClose(): void }) {}};+ const copyNotes = async () => {+ if (!material || !notes.length || notesExportBusy) return;+ const requestedMaterialId = material.material_id;+ const requestId = ++notesExportRequestRef.current;+ setNotesExportBusy(true);+ setNotesCopied(false);+ try {+ const markdown = await exportVideoNotes(requestedMaterialId);+ await navigator.clipboard.writeText(markdown);+ if (notesExportRequestRef.current !== requestId) return;+ setNotesCopied(true);+ } catch (caught) {+ if (notesExportRequestRef.current !== requestId) return;+ setNotesError(+ caught instanceof Error+ ? caught.message+ : t("Notes could not be copied."),+ );+ } finally {+ if (notesExportRequestRef.current === requestId) {+ setNotesExportBusy(false);+ }+ }+ };+const closePane = () => {persist();close();@@ -454,7 +513,44 @@ export function WatchingPane({ onClose }: { onClose(): void }) {{t("Open official")} <ExternalLink className="h-3 w-3" /></a></div>- <div className="min-h-0 flex-1 overflow-y-auto p-4">+ <div+ ref={transcriptListRef}+ data-testid="video-transcript-list"+ className="min-h-0 flex-1 overflow-y-auto p-4"+ onWheel={(event) => {+ if (tab !== "transcript") return;+ setFollowTranscript(false);+ }}+ onTouchMove={() => {+ if (tab === "transcript") setFollowTranscript(false);+ }}+ onPointerDown={(event) => {+ // Native scrollbar drags target the scroll container itself.+ // Pointer events from cue/control buttons bubble through here+ // and must keep their own click semantics.+ if (+ tab === "transcript" &&+ event.target === event.currentTarget+ ) {+ setFollowTranscript(false);+ }+ }}+ onKeyDown={(event) => {+ if (+ tab === "transcript" &&+ [+ "ArrowDown",+ "ArrowUp",+ "PageDown",+ "PageUp",+ "Home",+ "End",+ ].includes(event.key)+ ) {+ setFollowTranscript(false);+ }+ }}+ ><divclassName="mb-3 grid w-full max-w-56 grid-cols-2 rounded-lg bg-[var(--muted)] p-1"role="tablist"@@ -511,14 +607,25 @@ export function WatchingPane({ onClose }: { onClose(): void }) {</div>) : (<>- <button- type="button"- onClick={askHere}- disabled={!cue}- className="mb-3 rounded-lg bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] disabled:opacity-50"- >- {t("Explain here")}- </button>+ <div className="mb-3 flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={askHere}+ disabled={!cue}+ className="rounded-lg bg-[var(--primary)] px-3 py-2 text-sm text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {t("Explain here")}+ </button>+ <button+ type="button"+ onClick={() => setFollowTranscript((current) => !current)}+ aria-pressed={followTranscript}+ className={`inline-flex items-center gap-1.5 rounded-lg border px-3 py-2 text-sm font-medium ${followTranscript ? "border-[var(--primary)] text-[var(--primary)]" : "border-[var(--border)] text-[var(--muted-foreground)]"}`}+ >+ <ChevronsDown className="h-4 w-4" />+ {t("Follow playback")}+ </button>+ </div><div className="space-y-1">{material.transcript.cues.map((row, index) => {const active = row === cue;@@ -526,6 +633,7 @@ export function WatchingPane({ onClose }: { onClose(): void }) {<buttonkey={`${row.start}-${index}`}type="button"+ data-active-cue={active ? "true" : undefined}onClick={() => controllerRef.current?.seek(row.start)}className={`flex w-full gap-3 rounded-md px-2 py-1.5 text-left text-sm ${active ? "bg-blue-500/15 ring-1 ring-blue-500/30" : "hover:bg-[var(--muted)]"}`}>@@ -568,6 +676,21 @@ export function WatchingPane({ onClose }: { onClose(): void }) {)}{t("Add video note")}</button>+ <button+ type="button"+ onClick={() => void copyNotes()}+ disabled={notesExportBusy || !notes.length}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-2 text-sm disabled:opacity-50"+ >+ {notesExportBusy ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : notesCopied ? (+ <Check className="h-4 w-4" />+ ) : (+ <Copy className="h-4 w-4" />+ )}+ {notesCopied ? t("Notes copied") : t("Copy notes")}+ </button></form>{notesError && (diff --git a/web/context/WatchingContext.tsx b/web/context/WatchingContext.tsxindex 151184a88..a51ec310d 100644--- a/web/context/WatchingContext.tsx+++ b/web/context/WatchingContext.tsx@@ -69,6 +69,7 @@ export function WatchingProvider({ children }: { children: ReactNode }) {useEffect(() => {if (typeof window === "undefined") return;+ if (!active || material) return;const materialId = browserStorage.readRaw("local", LAST_MATERIAL_KEY);if (!materialId) return;const sourceUrl = browserStorage.readRaw("local", LAST_URL_KEY) || "";@@ -85,7 +86,7 @@ export function WatchingProvider({ children }: { children: ReactNode }) {browserStorage.removeRaw("local", LAST_MATERIAL_KEY);}).finally(() => setLoading(false));- }, [accept, t]);+ }, [accept, active, material, t]);const openUrl = useCallback(async (url: string, language = "", providerOverride?: VideoProvider) => {diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex aaba10f98..c989506f9 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -28,12 +28,22 @@ import { UnifiedTurnClient } from "@/features/chat/transport/UnifiedTurnClient";import { buildStartTurnInput } from "@/features/chat/controllers/buildStartTurnInput";import {getSession,+ getMessageTrace,deleteMessage,updateBranchSelection,updateSessionTitle,+ type MessageTracePage,type SessionMessage,} from "@/lib/session-api";-import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";+import {+ TraceCache,+ compactTracePreview,+ type MessageTraceMetadata,+} from "@/features/chat/trace/memory";+import {+ normalizeMarkdownForDisplay,+ repairChineseEmphasis,+} from "@/lib/markdown-display";import { normalizeMessageContent } from "@/lib/message-content";import {buildVisiblePath,@@ -205,10 +215,14 @@ export interface MessageItem {id?: number;role: "user" | "assistant" | "system";content: string;+ /** Original model text accumulated during a live stream. Kept separate from+ * `content`, which may be Markdown-normalized for display. */+ rawContent?: string;capability?: string;events?: StreamEvent[];attachments?: MessageAttachment[];requestSnapshot?: MessageRequestSnapshot;+ trace?: MessageTraceMetadata;/** Edit-branching: id of the message this row continues. */parentMessageId?: number | null;}@@ -301,6 +315,13 @@ type Action =userMessageId?: number | null;assistantMessageId?: number | null;}+ | {+ type: "SET_MESSAGE_TRACE";+ key: string;+ messageId: number;+ events: StreamEvent[];+ trace: MessageTraceMetadata;+ }| { type: "DELETE_TURN"; key: string; messageId: number }| {type: "NEW_SESSION";@@ -605,6 +626,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {id: nextOptimisticId(),role: "assistant",content: "",+ rawContent: "",events: [],capability: session.activeCapability || "",parentMessageId: tip?.id ?? null,@@ -641,6 +663,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {id: nextOptimisticId(),role: "assistant",content: "",+ rawContent: "",events: [],capability: session.activeCapability || "",parentMessageId: last?.id ?? null,@@ -655,19 +678,22 @@ function reducer(state: ProviderState, action: Action): ProviderState {return state;}const events = [...(last?.events || []), action.event];- let content = last?.content || "";+ const language = session.language;+ let rawContent = last?.rawContent ?? last?.content ?? "";if (isNarrationMarker(action.event)) {// A round just resolved as narration (preamble before a tool call):// drop its already-streamed text from the answer — it stays in the- // trace. Recomputing is cheap here (only fires per narration round).- content = recomputeAnswerContent(events);+ // trace. Recompute from immutable event content, never from display text.+ rawContent = recomputeAnswerContent(events);} else if (shouldAppendEventContent(action.event)) {- content += action.event.content;+ rawContent += action.event.content;}+ const content = repairChineseEmphasis(rawContent, language);const capability = last?.capability || session.activeCapability || "";msgs[msgs.length - 1] = {...(last || { role: "assistant", content: "" }),content,+ rawContent,events,capability,};@@ -857,6 +883,22 @@ function reducer(state: ProviderState, action: Action): ProviderState {},};}+ case "SET_MESSAGE_TRACE": {+ const session = state.sessions[action.key];+ if (!session) return state;+ const messages = session.messages.map((message) =>+ message.id === action.messageId && message.role === "assistant"+ ? { ...message, events: action.events, trace: action.trace }+ : message,+ );+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: { ...session, messages, updatedAt: Date.now() },+ },+ };+ }case "SET_SELECTED_BRANCH": {const session = state.sessions[action.key];if (!session) return state;@@ -1056,6 +1098,10 @@ interface ChatContextValue {/** Select an already-loaded session without fetching. Returns false when* it isn't in memory, i.e. the caller must load it. */showCachedSession: (sessionId: string) => boolean;+ /** Lazily fetch one persisted turn trace and retain its compact preview. */+ loadMessageTrace: (sessionId: string, messageId: number) => Promise<void>;+ /** Restore the compact preview when a full trace is collapsed. */+ releaseMessageTrace: (sessionId: string, messageId: number) => void;selectedSessionId: string | null;sessionStatuses: Record<string, SessionStatusSnapshot>;sidebarRefreshToken: number;@@ -1251,6 +1297,8 @@ export function ChatStateAdapterProvider({// assistant message if the server rejects the request (e.g. ``regenerate_busy``// or ``nothing_to_regenerate``). Keyed by session entry key.const pendingRegenerateRef = useRef<Map<string, MessageItem>>(new Map());+ const traceCacheRef = useRef<TraceCache>(new TraceCache());+ const traceRequestsRef = useRef<Map<string, AbortController>>(new Map());// Forward-declared so ``handleRunnerEvent`` (created above// ``loadSession`` in source order) can trigger a server refresh after// a turn finishes without taking a stale closure of ``loadSession``.@@ -1262,12 +1310,34 @@ export function ChatStateAdapterProvider({stateRef.current = state;}, [state]);+ useEffect(() => {+ if (!state.selectedKey) return;+ for (const [key, controller] of traceRequestsRef.current) {+ if (key.startsWith(`${state.selectedKey}:`)) continue;+ controller.abort();+ traceRequestsRef.current.delete(key);+ }+ const released = traceCacheRef.current.releaseExcept(state.selectedKey);+ for (const [key, snapshot] of released) {+ const [sessionId, messageId] = key.split(":");+ dispatch({+ type: "SET_MESSAGE_TRACE",+ key: sessionId,+ messageId: Number(messageId),+ events: snapshot.events,+ trace: snapshot.metadata ?? {},+ });+ }+ }, [state.selectedKey]);+useEffect(() => () => {runnersRef.current.forEach(({ client }) => client.disconnect());runnersRef.current.clear();retryTimersRef.current.forEach((id) => clearTimeout(id));retryTimersRef.current.clear();+ traceRequestsRef.current.forEach((controller) => controller.abort());+ traceRequestsRef.current.clear();},[],);@@ -1313,6 +1383,7 @@ export function ChatStateAdapterProvider({capability: message.capability || "",events: Array.isArray(message.events) ? message.events : [],attachments,+ trace: message.trace,parentMessageId:message.parent_message_id === undefined? null@@ -1445,6 +1516,26 @@ export function ChatStateAdapterProvider({userMessageId: doneMeta?.user_message_id ?? null,assistantMessageId,});+ const finished = stateRef.current.sessions[effectiveKey];+ const finishedMessage = [...(finished?.messages ?? [])].reverse().find(+ (item) => item.role === "assistant",+ );+ if (finishedMessage) {+ const sourceEvents = finishedMessage.events ?? [];+ const preview = compactTracePreview(sourceEvents);+ dispatch({+ type: "SET_MESSAGE_TRACE",+ key: effectiveKey,+ messageId: assistantMessageId,+ events: preview.events,+ trace: {+ turn_id: event.turn_id || null,+ total: sourceEvents.length,+ last_seq: Math.max(0, ...sourceEvents.map((item) => item.seq ?? 0)),+ truncated: preview.truncated,+ },+ });+ }} else {// Older backend without ids on ``done`` — fall back to the// full session refetch.@@ -1610,6 +1701,92 @@ export function ChatStateAdapterProvider({return true;}, []);+ const releaseMessageTrace = useCallback((sessionId: string, messageId: number) => {+ const key = `${sessionId}:${messageId}`;+ traceRequestsRef.current.get(key)?.abort();+ traceRequestsRef.current.delete(key);+ const preview = traceCacheRef.current.release(key);+ if (!preview) return;+ dispatch({+ type: "SET_MESSAGE_TRACE",+ key: sessionId,+ messageId,+ events: preview.events,+ trace: preview.metadata ?? {},+ });+ }, []);++ const loadMessageTrace = useCallback(+ async (sessionId: string, messageId: number) => {+ const key = `${sessionId}:${messageId}`;+ if (traceCacheRef.current.has(key) || traceRequestsRef.current.has(key)) return;+ const session = stateRef.current.sessions[sessionId];+ if (!session || session.isStreaming || session.status === "running") return;+ const message = session.messages.find(+ (item) => item.id === messageId && item.role === "assistant",+ );+ if (!message?.trace?.turn_id) return;++ const controller = new AbortController();+ traceRequestsRef.current.set(key, controller);+ try {+ const events: StreamEvent[] = [];+ let afterSeq = 0;+ let page: MessageTracePage | null = null;+ for (let pageCount = 0; pageCount < 1000; pageCount += 1) {+ page = await getMessageTrace(+ sessionId,+ messageId,+ afterSeq,+ controller.signal,+ );+ events.push(...page.events);+ if (page.complete || page.next_seq == null) break;+ if (page.next_seq <= afterSeq) return;+ afterSeq = page.next_seq;+ }+ if (!page || controller.signal.aborted) return;+ const metadata: MessageTraceMetadata = {+ turn_id: page.turn_id,+ total: page.total,+ last_seq: page.last_seq,+ truncated: false,+ };+ const preview = compactTracePreview(message.events ?? []);+ const evicted = traceCacheRef.current.retain(key, {+ events: preview.events,+ metadata: message.trace,+ });+ for (const [evictedKey, snapshot] of evicted) {+ const [evictedSession, evictedMessage] = evictedKey.split(":");+ dispatch({+ type: "SET_MESSAGE_TRACE",+ key: evictedSession,+ messageId: Number(evictedMessage),+ events: snapshot.events,+ trace: snapshot.metadata ?? {},+ });+ }+ dispatch({+ type: "SET_MESSAGE_TRACE",+ key: sessionId,+ messageId,+ events,+ trace: metadata,+ });+ } catch (reason) {+ if (!(reason instanceof DOMException && reason.name === "AbortError")) {+ console.warn("Failed to load message trace", reason);+ }+ } finally {+ if (traceRequestsRef.current.get(key) === controller) {+ traceRequestsRef.current.delete(key);+ }+ }+ },+ [],+ );+const loadSession = useCallback(async (sessionId: string,@@ -1629,6 +1806,7 @@ export function ChatStateAdapterProvider({const local = stateRef.current.sessions[key];if (!local || local.isStreaming || local.status === "running") return;}+ traceCacheRef.current.clear();const messages = hydrateMessages(session.messages ?? []);const loadedWorkspaceMode = normalizeWorkspaceMode(session.preferences?.workspace_mode,@@ -2397,6 +2575,8 @@ export function ChatStateAdapterProvider({configureSession,loadSession,showCachedSession,+ loadMessageTrace,+ releaseMessageTrace,selectedSessionId: derivedState.sessionId,sessionStatuses,sidebarRefreshToken: state.sidebarRefreshToken,@@ -2423,6 +2603,8 @@ export function ChatStateAdapterProvider({configureSession,loadSession,showCachedSession,+ loadMessageTrace,+ releaseMessageTrace,sessionStatuses,state.sidebarRefreshToken,],diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 6abb4e43c..0083fc6ae 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -287,6 +287,8 @@ export default function ChatWorkspace() {newSession,loadSession,showCachedSession,+ loadMessageTrace,+ releaseMessageTrace,renameSessionTitle,setCourseId,} = useChatStateAdapter();@@ -2406,6 +2408,16 @@ export default function ChatWorkspace() {onEditMessage={editMessage}onSwitchBranch={switchBranch}onSubmitUserReply={submitUserReply}+ onLoadMessageTrace={(messageId) =>+ state.sessionId+ ? loadMessageTrace(state.sessionId, messageId)+ : Promise.resolve()+ }+ onReleaseMessageTrace={(messageId) => {+ if (state.sessionId) {+ releaseMessageTrace(state.sessionId, messageId);+ }+ }}availableKbNames={knowledgeBasesLoaded ? availableKbNames : undefined}diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex 7cc578b2d..4ecaf7c86 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -81,6 +81,7 @@ import {AssistantActivity,NestedTraceFlow,} from "@/features/chat/trace/TracePresentation";+import type { MessageTraceMetadata } from "@/features/chat/trace/memory";import { agentGlyph } from "@/components/agents/agent-icons";import { useConnectedAgentKinds } from "@/hooks/useConnectedAgentKinds";import {@@ -112,6 +113,7 @@ interface ChatMessageItem {content: string;capability?: string;events?: StreamEvent[];+ trace?: MessageTraceMetadata;attachments?: MessageAttachment[];requestSnapshot?: MessageRequestSnapshot;parentMessageId?: number | null;@@ -325,13 +327,21 @@ export const AssistantMessage = memo(function AssistantMessage({onConfirmOutline,onSubmitUserReply,researchRequestSnapshot,+ onTraceToggle,}: {- msg: { content: string; capability?: string; events?: StreamEvent[] };+ msg: {+ id?: number;+ content: string;+ capability?: string;+ events?: StreamEvent[];+ trace?: MessageTraceMetadata;+ };isStreaming?: boolean;outlineStatus?: "editing" | "researching" | "done" | "failed";sessionId?: string | null;language?: string;researchRequestSnapshot?: MessageRequestSnapshot | null;+ onTraceToggle?: (open: boolean) => void;onConfirmOutline?: (outline: Array<{ title: string; overview: string }>,topic: string,@@ -507,6 +517,11 @@ export const AssistantMessage = memo(function AssistantMessage({isStreaming={isStreaming}content={msg.content}className="mb-3"+ onTraceToggle={+ msg.id != null && msg.trace?.turn_id+ ? (open) => onTraceToggle?.(open)+ : undefined+ }/>{outlinePreview && outlinePreview.sub_topics.length > 0 ? (<>@@ -545,6 +560,7 @@ export const AssistantMessage = memo(function AssistantMessage({{showResearchBody ? (<AssistantResponsecontent={msg.content}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}@@ -570,6 +586,7 @@ export const AssistantMessage = memo(function AssistantMessage({{msg.content ? (<AssistantResponsecontent={msg.content}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}@@ -593,6 +610,7 @@ export const AssistantMessage = memo(function AssistantMessage({<AssistantResponsekey={seg.key}content={seg.text}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}@@ -620,6 +638,7 @@ export const AssistantMessage = memo(function AssistantMessage({) : (<AssistantResponsecontent={body}+ language={language}isStreaming={isStreaming}readingMaterialId={readingMaterialId}readingMaterialRevision={readingMaterialRevision}@@ -1304,6 +1323,8 @@ export const ChatMessageList = memo(function ChatMessageList({availableKbNames,onSubmitUserReply,showModeBadge = true,+ onLoadMessageTrace,+ onReleaseMessageTrace,}: {messages: ChatMessageItem[];isStreaming: boolean;@@ -1344,6 +1365,8 @@ export const ChatMessageList = memo(function ChatMessageList({/** Label each user bubble with its capability. Off on surfaces that run a* single capability and already name it in their own chrome. */showModeBadge?: boolean;+ onLoadMessageTrace?: (messageId: number) => Promise<void>;+ onReleaseMessageTrace?: (messageId: number) => void;}) {const { t } = useTranslation();// Visible path: when no branching has happened the result is identical@@ -1599,6 +1622,14 @@ export const ChatMessageList = memo(function ChatMessageList({researchRequestSnapshot={pairedUserMessage?.requestSnapshot ?? null}+ onTraceToggle={(open) => {+ if (msg.id == null) return;+ if (open) {+ void onLoadMessageTrace?.(msg.id);+ } else {+ onReleaseMessageTrace?.(msg.id);+ }+ }}/></InlineFileCardProvider><GeneratedFileCardsdiff --git a/web/features/chat/trace/TracePresentation.tsx b/web/features/chat/trace/TracePresentation.tsxindex deedb34f6..3f3847823 100644--- a/web/features/chat/trace/TracePresentation.tsx+++ b/web/features/chat/trace/TracePresentation.tsx@@ -1733,6 +1733,7 @@ export function AssistantActivity({agentName,showMark = true,headerClassName = "",+ onTraceToggle,}: {events: StreamEvent[];/**@@ -1754,6 +1755,8 @@ export function AssistantActivity({/** Extra classes on the status header row (e.g. a min-height so the row* vertically centers against an adjacent avatar). */headerClassName?: string;+ /** Notified when a persisted trace is opened or collapsed. */+ onTraceToggle?: (open: boolean) => void;}) {const shownTraceEvents = traceEvents ?? events;const hasTrace = useMemo(@@ -1782,7 +1785,11 @@ export function AssistantActivity({content={content}expandable={hasTrace}expanded={open}- onToggle={() => setUserOpen(!open)}+ onToggle={() => {+ const next = !open;+ setUserOpen(next);+ onTraceToggle?.(next);+ }}agentName={agentName}showMark={showMark}className={headerClassName}diff --git a/web/features/chat/trace/memory.ts b/web/features/chat/trace/memory.tsnew file mode 100644index 000000000..45381bf44--- /dev/null+++ b/web/features/chat/trace/memory.ts@@ -0,0 +1,186 @@+import type { StreamEvent } from "@/features/chat/model/protocol";++export const MAX_PREVIEW_EVENTS = 200;+export const MAX_PREVIEW_BYTES = 128 * 1024;+export const MAX_LEGACY_PAYLOAD_CHARS = 16 * 1024;++const TERMINAL_TYPES = new Set(["done", "error", "cancelled"]);+const utf8Encoder = new TextEncoder();+const SEMANTIC_TYPES = new Set([+ "done",+ "error",+ "cancelled",+ "result",+ "tool_call",+ "tool_result",+]);++function metadata(event: StreamEvent): Record<string, unknown> {+ return (event.metadata ?? {}) as Record<string, unknown>;+}++function isSemantic(event: StreamEvent): boolean {+ if (SEMANTIC_TYPES.has(String(event.type ?? ""))) return true;+ const meta = metadata(event);+ const toolMetadata = meta.tool_metadata;+ return Boolean(+ meta.ask_user ||+ meta.ask_user_resolved ||+ (typeof toolMetadata === "object" &&+ toolMetadata !== null &&+ "ask_user" in toolMetadata),+ );+}++function isCritical(event: StreamEvent): boolean {+ if (TERMINAL_TYPES.has(String(event.type ?? "")) || String(event.type ?? "") === "result") {+ return true;+ }+ const meta = metadata(event);+ const toolMetadata = meta.tool_metadata;+ return Boolean(+ meta.ask_user ||+ meta.ask_user_resolved ||+ (typeof toolMetadata === "object" &&+ toolMetadata !== null &&+ "ask_user" in toolMetadata),+ );+}++function boundLegacyPayload(event: StreamEvent): StreamEvent {+ let changed = false;+ const next = { ...event } as StreamEvent & { _truncated?: boolean };+ if (typeof event.content === "string" && event.content.length > MAX_LEGACY_PAYLOAD_CHARS) {+ next.content = `${event.content.slice(0, MAX_LEGACY_PAYLOAD_CHARS)}...[truncated]`;+ changed = true;+ }+ const meta = metadata(event);+ const toolMetadata = meta.tool_metadata;+ if (typeof toolMetadata === "object" && toolMetadata !== null) {+ const boundedToolMetadata = { ...(toolMetadata as Record<string, unknown>) };+ for (const field of ["content", "answer"] as const) {+ const value = boundedToolMetadata[field];+ if (typeof value === "string" && value.length > MAX_LEGACY_PAYLOAD_CHARS) {+ boundedToolMetadata[field] = `${value.slice(0, MAX_LEGACY_PAYLOAD_CHARS)}...[truncated]`;+ changed = true;+ }+ }+ if (changed) next.metadata = { ...meta, tool_metadata: boundedToolMetadata };+ }+ return (changed ? next : event) as StreamEvent;+}++export function compactTracePreview(+ events: StreamEvent[],+ maxEvents = MAX_PREVIEW_EVENTS,+ maxBytes = MAX_PREVIEW_BYTES,+): { events: StreamEvent[]; truncated: boolean } {+ const semantic = events.filter(isSemantic);+ let criticalIndices = semantic.reduce<number[]>((indices, event, index) => {+ if (isCritical(event)) indices.push(index);+ return indices;+ }, []);+ if (criticalIndices.length > maxEvents) {+ criticalIndices = criticalIndices.slice(-maxEvents);+ }+ const selectedIndices = new Set(criticalIndices);+ for (let index = semantic.length - 1; index >= 0; index -= 1) {+ if (selectedIndices.size >= maxEvents) break;+ selectedIndices.add(index);+ }+ const selected = semantic.filter((_, index) => selectedIndices.has(index));+ const result: StreamEvent[] = [];+ let usedBytes = 0;+ for (const source of selected) {+ const event = boundLegacyPayload(source);+ let size = utf8Encoder.encode(JSON.stringify(event)).length;+ if (result.length > 0 && usedBytes + size > maxBytes) continue;+ if (result.length === 0 && size > maxBytes) {+ const bounded = {+ type: event.type,+ source: "",+ stage: "",+ metadata: {},+ turn_id: event.turn_id,+ session_id: event.session_id,+ seq: event.seq,+ timestamp: event.timestamp,+ content: "...[truncated]",+ _truncated: true,+ };+ size = utf8Encoder.encode(JSON.stringify(bounded)).length;+ result.push(bounded as StreamEvent);+ usedBytes += size;+ continue;+ }+ result.push(event);+ usedBytes += size;+ }+ if (!result.some((event) => TERMINAL_TYPES.has(String(event.type ?? "")))) {+ const terminal = [...events].reverse().find((event) => TERMINAL_TYPES.has(String(event.type ?? "")));+ if (terminal) result.push(terminal);+ }+ return {+ events: result,+ truncated: events.length !== result.length || selected.length !== result.length,+ };+}++export interface TraceSnapshot {+ events: StreamEvent[];+ metadata?: MessageTraceMetadata;+}++export interface MessageTraceMetadata {+ turn_id?: string | null;+ total?: number;+ last_seq?: number;+ truncated?: boolean;+}++export class TraceCache {+ private readonly entries = new Map<string, TraceSnapshot>();++ constructor(private readonly capacity = 5) {}++ retain(key: string, snapshot: TraceSnapshot): Array<[string, TraceSnapshot]> {+ this.entries.delete(key);+ this.entries.set(key, snapshot);+ const evicted: Array<[string, TraceSnapshot]> = [];+ while (this.entries.size > this.capacity) {+ const oldest = this.entries.keys().next().value;+ if (oldest === undefined) break;+ const released = this.release(oldest);+ if (released) evicted.push([oldest, released]);+ }+ return evicted;+ }++ release(key: string): TraceSnapshot | undefined {+ const snapshot = this.entries.get(key);+ this.entries.delete(key);+ return snapshot;+ }++ has(key: string): boolean {+ return this.entries.has(key);+ }++ clear(): void {+ this.entries.clear();+ }++ releaseExcept(keyPrefix: string): Array<[string, TraceSnapshot]> {+ const released: Array<[string, TraceSnapshot]> = [];+ for (const [key, snapshot] of this.entries) {+ if (key.startsWith(`${keyPrefix}:`)) continue;+ released.push([key, snapshot]);+ this.entries.delete(key);+ }+ return released;+ }++ get size(): number {+ return this.entries.size;+ }+}diff --git a/web/features/knowledge/api/catalog.ts b/web/features/knowledge/api/catalog.tsindex 5450cc588..f92d4c104 100644--- a/web/features/knowledge/api/catalog.ts+++ b/web/features/knowledge/api/catalog.ts@@ -18,9 +18,11 @@ export {reindexKnowledgeBase,retryKnowledgeBase,setDefaultKnowledgeBase,+ updatePendingIndexingPolicy,} from "./client";export type {+ IndexingLLMSelection,ImaKnowledgeBasePage,ImaProbe,KnowledgeBaseSummary,diff --git a/web/features/knowledge/api/client.ts b/web/features/knowledge/api/client.tsindex 1b4afa8c3..6fc015a69 100644--- a/web/features/knowledge/api/client.ts+++ b/web/features/knowledge/api/client.ts@@ -4,6 +4,12 @@ import type { ImaKnowledgeBaseOption } from "@/lib/ima-connection";const KNOWLEDGE_CACHE_PREFIX = "knowledge:";+export interface IndexingLLMSelection {+ profile_id: string;+ model_id: string;+ reasoning_effort?: string;+}+export interface KnowledgeBaseSummary {id?: string;name: string;@@ -94,7 +100,7 @@ export interface LightRagConfig {llm_model_max_async: number;/** Extra extraction passes per chunk, to recover missed entities. */entity_extract_max_gleaning: number;- /** Stable catalog reference, or empty strings for the global active chat model. */+ /** Query model and default indexing selection; empty uses the active chat model. */llm_profile_id: string;llm_model_id: string;}@@ -683,6 +689,7 @@ export async function createKnowledgeBase(payload: {files: File[];pageindexMode?: "flash" | "standard";searchMode?: string;+ indexingLLM?: IndexingLLMSelection;}): Promise<KnowledgeTaskResponse> {const form = new FormData();form.append("name", payload.name);@@ -691,6 +698,9 @@ export async function createKnowledgeBase(payload: {form.append("pageindex_mode", payload.pageindexMode);}if (payload.searchMode) form.append("search_mode", payload.searchMode);+ if (payload.indexingLLM) {+ form.append("indexing_llm", JSON.stringify(payload.indexingLLM));+ }appendFilesWithPaths(form, payload.files);const res = await apiFetch(apiUrl("/api/knowledge-bases"), {@@ -1173,12 +1183,17 @@ export async function setDefaultKnowledgeBase(name: string): Promise<void> {export async function reindexKnowledgeBase(name: string,+ indexingLLM?: IndexingLLMSelection,): Promise<KnowledgeTaskResponse> {+ const request: RequestInit = { method: "POST" };+ if (indexingLLM) {+ const form = new FormData();+ form.append("indexing_llm", JSON.stringify(indexingLLM));+ request.body = form;+ }const res = await apiFetch(apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/reindex`),- {- method: "POST",- },+ request,);if (!res.ok) {const detail = await readErrorDetail(@@ -1193,6 +1208,30 @@ export async function reindexKnowledgeBase(return (await res.json()) as KnowledgeTaskResponse;}+export async function updatePendingIndexingPolicy(+ name: string,+ indexingLLM: IndexingLLMSelection,+): Promise<{ indexing_policy: Record<string, unknown> }> {+ const res = await apiFetch(+ apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/indexing-policy`),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(indexingLLM),+ },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(+ res,+ `Failed to update indexing model (${res.status})`,+ ),+ );+ }+ invalidateKnowledgeCaches();+ return (await res.json()) as { indexing_policy: Record<string, unknown> };+}+export async function retryKnowledgeBase(name: string,): Promise<KnowledgeTaskResponse> {diff --git a/web/features/knowledge/components/engines/EngineDetail.tsx b/web/features/knowledge/components/engines/EngineDetail.tsxindex 13dd58395..6f827d62b 100644--- a/web/features/knowledge/components/engines/EngineDetail.tsx+++ b/web/features/knowledge/components/engines/EngineDetail.tsx@@ -1126,7 +1126,7 @@ export function LightRagForm({/><label className="flex flex-col gap-1"><span className="text-[12px] font-medium text-[var(--foreground)]">- {t("Chat model")}+ {t("LightRAG query model")}</span><selectvalue={selectedValue}@@ -1144,7 +1144,7 @@ export function LightRagForm({<option value="">{t("Loading models…")}</option>) : (<>- <option value="">{t("Use global active chat model")}</option>+ <option value="">{t("Use active chat model")}</option>{selectedValue && !selectedOption && (<option value={selectedValue}>{t("Selected model unavailable")}@@ -1165,7 +1165,9 @@ export function LightRagForm({)}</select><span className="text-[11px] text-[var(--muted-foreground)]">- {t("Used for LightRAG extraction and query calls")}+ {t(+ "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.",+ )}</span></label></div>diff --git a/web/features/knowledge/model/types.ts b/web/features/knowledge/model/types.tsindex 39ce3e877..eb495bed3 100644--- a/web/features/knowledge/model/types.ts+++ b/web/features/knowledge/model/types.ts@@ -9,6 +9,7 @@ export type {ImaAccountConfig,ImaKnowledgeBasePage,ImaProbe,+ IndexingLLMSelection,KnowledgeBaseFile,KnowledgeBaseSummary,KnowledgeTaskResponse,diff --git a/web/features/settings/navigation/settings-nav.ts b/web/features/settings/navigation/settings-nav.tsindex f162a2b69..46201e5f3 100644--- a/web/features/settings/navigation/settings-nav.ts+++ b/web/features/settings/navigation/settings-nav.ts@@ -364,6 +364,18 @@ const AGENT_CHILDREN: SettingsLeaf[] = [tile: "bg-violet-500/10 text-violet-600 dark:text-violet-400",adminOnly: true,},+ {+ key: "agent-hermes-remote",+ href: "/settings#agent-hermes-remote",+ label: { zh: "Hermes Agent(远程)", en: "Hermes Agent (remote)" },+ blurb: {+ zh: "通过 HTTP 网关调用远程 Hermes Agent,并按会话保持上下文。",+ en: "Call a remote Hermes Agent over HTTP with per-chat session continuity.",+ },+ icon: HermesGlyph as unknown as LucideIcon,+ tile: "bg-violet-500/10 text-violet-600 dark:text-violet-400",+ adminOnly: true,+ },{key: "agent-openclaw",href: "/settings#agent-openclaw",diff --git a/web/features/settings/navigation/settings-scroll.ts b/web/features/settings/navigation/settings-scroll.tsindex 194ec38ef..b7e550c2c 100644--- a/web/features/settings/navigation/settings-scroll.ts+++ b/web/features/settings/navigation/settings-scroll.ts@@ -39,8 +39,15 @@ export function scrollToSettingsSection(scroller.scrollTo({ top: Math.max(0, top), behavior });- // Fragment navigation may have moved the root scrolling element before the- // client handler ran. Keep the full-height application shell pinned.- window.scrollTo({ top: 0, left: 0, behavior: "auto" });+ // Fragment navigation may move the root scrolling element before or after+ // the client handler runs. Keep the full-height application shell pinned+ // now and after the anchor's default-action frame.+ const resetDocumentScroll = () => {+ window.scrollTo({ top: 0, left: 0, behavior: "auto" });+ document.documentElement.scrollTop = 0;+ document.body.scrollTop = 0;+ };+ resetDocumentScroll();+ requestAnimationFrame(resetDocumentScroll);return true;}diff --git a/web/features/settings/sections/AgentsSettingsSection.tsx b/web/features/settings/sections/AgentsSettingsSection.tsxindex a94b4c813..d41ab2dcb 100644--- a/web/features/settings/sections/AgentsSettingsSection.tsx+++ b/web/features/settings/sections/AgentsSettingsSection.tsx@@ -18,6 +18,9 @@ const OpencodeAgentSettingsPage = () => ();const MimoAgentSettingsPage = () => <SubagentSettingsEditor kind="mimo" />;const HermesAgentSettingsPage = () => <SubagentSettingsEditor kind="hermes" />;+const HermesRemoteAgentSettingsPage = () => (+ <SubagentSettingsEditor kind="hermes_remote" />+);const OpenClawAgentSettingsPage = () => (<SubagentSettingsEditor kind="openclaw" />);@@ -33,6 +36,7 @@ const AGENT_SECTIONS = [{ key: "agent-opencode", Component: OpencodeAgentSettingsPage },{ key: "agent-mimo", Component: MimoAgentSettingsPage },{ key: "agent-hermes", Component: HermesAgentSettingsPage },+ { key: "agent-hermes-remote", Component: HermesRemoteAgentSettingsPage },{ key: "agent-openclaw", Component: OpenClawAgentSettingsPage },{key: "agent-deepseek-harness",diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.tsindex 3e71dd524..2b1912439 100644--- a/web/hooks/useKnowledgeBases.ts+++ b/web/hooks/useKnowledgeBases.ts@@ -15,8 +15,10 @@ import {listRagProviders,reindexKnowledgeBase as reindexKbApi,retryKnowledgeBase as retryKbApi,+ updatePendingIndexingPolicy as updatePendingIndexingPolicyApi,setDefaultKnowledgeBase as setDefaultKbApi,type KnowledgeTaskResponse,+ type IndexingLLMSelection,type KnowledgeUploadPolicy,type RagProviderSummary,} from "@/features/knowledge/api/catalog";@@ -180,6 +182,7 @@ export function useKnowledgeBases() {files: File[];pageindexMode?: "flash" | "standard";searchMode?: string;+ indexingLLM?: IndexingLLMSelection;}): Promise<KnowledgeTaskResponse> => {const result = await createKbApi(params);invalidateKnowledgeCaches();@@ -257,8 +260,11 @@ export function useKnowledgeBases() {);const reindex = useCallback(- async (kbName: string): Promise<KnowledgeTaskResponse> => {- const result = await reindexKbApi(kbName);+ async (+ kbName: string,+ indexingLLM?: IndexingLLMSelection,+ ): Promise<KnowledgeTaskResponse> => {+ const result = await reindexKbApi(kbName, indexingLLM);if (result.noop) {await load({ force: true, showSpinner: false });return result;@@ -281,6 +287,14 @@ export function useKnowledgeBases() {[load, progress],);+ const updatePendingIndexingPolicy = useCallback(+ async (kbName: string, indexingLLM: IndexingLLMSelection) => {+ await updatePendingIndexingPolicyApi(kbName, indexingLLM);+ await load({ force: true, showSpinner: false });+ },+ [load],+ );+const retry = useCallback(async (kbName: string): Promise<KnowledgeTaskResponse> => {const result = await retryKbApi(kbName);@@ -401,6 +415,7 @@ export function useKnowledgeBases() {uploadFiles,setDefault,reindex,+ updatePendingIndexingPolicy,retry,deleteKb,connectObsidian,diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex 4b51e31cc..121e0475f 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -91,13 +91,68 @@ export interface KnowledgeIndexFailure {}export interface IndexVersion {+ version?: string;signature?: string;+ provider?: string;+ state?: string;model?: string;dimension?: number;binding?: string;created_at?: string;ready?: boolean;legacy?: boolean;+ failure_summary?: string;+ indexing_policy?: LightRagIndexingPolicy;+}++export interface LightRagIndexingPolicy {+ policy: "pending_pinned" | "pinned" | "legacy_unpinned" | string;+ selection?: {+ profile_id: string;+ model_id: string;+ reasoning_effort?: string;+ };+ descriptor?: {+ model?: string;+ binding?: string;+ provider_mode?: string;+ reasoning_effort?: string | null;+ };+ fingerprint?: string | null;+ vision_available?: boolean;+ vlm_used?: boolean;+}++export type LightRagVersionDisplayState =+ | "published"+ | "building"+ | "failed"+ | "legacy"+ | "inactive";++export function currentLightRagBuildCandidate(+ versions: IndexVersion[],+ rebuildActive: boolean,+): IndexVersion | undefined {+ if (!rebuildActive) return undefined;+ return versions.find((version) => version.ready !== true);+}++export function lightRagVersionDisplayState(+ version: IndexVersion,+ options: {+ published: boolean;+ rebuildActive: boolean;+ kbError: boolean;+ legacy: boolean;+ },+): LightRagVersionDisplayState {+ if (options.published) return "published";+ if (options.legacy || version.legacy) return "legacy";+ if (version.ready) return "inactive";+ if (options.rebuildActive) return "building";+ if (options.kbError || version.failure_summary) return "failed";+ return "inactive";}export interface KnowledgeBase {@@ -127,6 +182,7 @@ export interface KnowledgeBase {agent_kind?: string;/** Bound partner id when agent_kind === "partner". */partner_id?: string;+ indexing_policy?: LightRagIndexingPolicy;};progress?: ProgressInfo;statistics?: {@@ -150,10 +206,7 @@ export interface KnowledgeBase {}export type ProviderConnectionStatus =- | "ready"- | "needs_key"- | "needs_setup"- | "unavailable";+ "ready" | "needs_key" | "needs_setup" | "unavailable";export const providerUsesEmbeddingMetadata = (provider?: string): boolean =>provider !== "pageindex" && provider !== "pageindex-oss";@@ -364,10 +417,28 @@ export const kbNeedsReindex = (kb: KnowledgeBase): boolean =>Boolean(kb.statistics?.needs_reindex) ||resolveKbStatus(kb) === "needs_reindex";+export const kbRequiresLightRagRebuildBeforeAppend = (+ kb: KnowledgeBase,+): boolean =>+ kbProvider(kb) === "lightrag" &&+ kb.metadata?.indexing_policy?.policy === "legacy_unpinned";+export const kbIsUploadable = (kb: KnowledgeBase): boolean =>- resolveKbStatus(kb) === "ready" && !kbNeedsReindex(kb);+ resolveKbStatus(kb) === "ready" &&+ !kbNeedsReindex(kb) &&+ !kbRequiresLightRagRebuildBeforeAppend(kb);++export const kbCanUploadDocuments = (+ kb: KnowledgeBase,+ indexingActive: boolean,+): boolean =>+ kbIsUploadable(kb) ||+ (resolveKbStatus(kb) === "error" &&+ !indexingActive &&+ !kbRequiresLightRagRebuildBeforeAppend(kb));export const kbCanReindex = (kb: KnowledgeBase): boolean => {+ if (kb.read_only) return false;const status = resolveKbStatus(kb);const hasSourceFiles =typeof kb.statistics?.raw_documents === "number"@@ -375,6 +446,7 @@ export const kbCanReindex = (kb: KnowledgeBase): boolean => {: true;if (!hasSourceFiles) return false;if (status === "error") return true;+ if (kbProvider(kb) === "lightrag") return !kbHasLiveProgress(kb);return (Boolean(kb.statistics?.needs_reindex) ||kb.statistics?.active_match === falsediff --git a/web/lib/learning-api.ts b/web/lib/learning-api.tsindex 949131865..8bba4c0d5 100644--- a/web/lib/learning-api.ts+++ b/web/lib/learning-api.ts@@ -112,6 +112,37 @@ export interface MasteryMapResult {map: MasteryMap;}+// ── Visual learning board ─────────────────────────────────────────────────++export interface BoardCard {+ id: string;+ name: string;+ type: string;+ module_id: string;+ module_name: string;+ status: ObjectiveStatus;+ mastery_level: number;+ next_review_at: number | null;+ position: { column: number; row: number };+}++export interface BoardModule {+ id: string;+ name: string;+ order: number;+ mastered: number;+ total: number;+ cards: BoardCard[];+}++export interface BoardResult {+ book_id: string;+ name: string;+ path_revision: number;+ cards: BoardCard[];+ modules: BoardModule[];+}+export async function fetchMasteryMap(pathId: string,init?: RequestInit,@@ -124,6 +155,20 @@ export async function fetchMasteryMap(return res.json() as Promise<MasteryMapResult>;}+export async function fetchLearningBoard(+ pathId: string,+ init?: RequestInit,+): Promise<BoardResult> {+ const res = await apiFetch(+ apiUrl(+ `/api/mastery-paths/progress/${encodeURIComponent(pathId)}/board`,+ ),+ init,+ );+ if (!res.ok) throw new Error(`Failed to fetch learning board: ${res.status}`);+ return res.json() as Promise<BoardResult>;+}+/** Rename a path. An empty name restores the derived display name. */export async function renameProgress(pathId: string, name: string) {const res = await apiFetch(diff --git a/web/lib/llm-options.ts b/web/lib/llm-options.tsindex 98c570f0e..8a9c30c3a 100644--- a/web/lib/llm-options.ts+++ b/web/lib/llm-options.ts@@ -13,6 +13,8 @@ export interface LLMOption extends LLMSelection {/** Human-readable provider name from the registry ("OpenRouter"). */provider_label?: string;context_window?: number;+ reasoning_effort?: string;+ supported_reasoning_efforts?: string[];is_active_default: boolean;}diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.tsindex 227d14767..852e74082 100644--- a/web/lib/markdown-display.ts+++ b/web/lib/markdown-display.ts@@ -334,7 +334,7 @@ function removeEmptyMarkdownTables(content: string): string {const lines = content.split("\n");const cleaned: string[] = [];- for (let index = 0; index < lines.length; ) {+ for (let index = 0; index < lines.length;) {if (!isMarkdownTableStart(lines, index)) {cleaned.push(lines[index]);index += 1;@@ -591,6 +591,191 @@ export function repairMalformedStrongEmphasis(content: string): string {return fenced.restore(math.restore(inline.restore(repaired)));}+// Handle only standalone italic/strong runs. Triple-star runs can represent nested+// emphasis and require full delimiter-run parsing, so leave them untouched.+const EMPHASIS_DELIMITER_REGEX = /(?<!\*)\*\*(?!\*)|(?<!\*)\*(?!\*)/g;++function isNormalEmphasisCharacter(value: string | undefined): boolean {+ return Boolean(value && /[\p{L}\p{N}]/u.test(value));+}++function isPunctuationOrSymbol(value: string | undefined): boolean {+ return Boolean(value && /[\p{P}\p{S}]/u.test(value));+}++function isCjkCharacter(value: string | undefined): boolean {+ return Boolean(value && value >= "\u4e00" && value <= "\u9fff");+}++function firstNonWhitespaceAfter(+ line: string,+ index: number,+): string | undefined {+ return Array.from(line.slice(index)).find((value) => !/\s/u.test(value));+}++function lastNonWhitespaceBefore(+ line: string,+ index: number,+): string | undefined {+ return Array.from(line.slice(0, index))+ .reverse()+ .find((value) => !/\s/u.test(value));+}++function canOpenEmphasis(line: string, index: number, marker: string): boolean {+ const before = Array.from(line.slice(0, index)).pop();+ const afterIndex = index + marker.length;+ const after = Array.from(line.slice(afterIndex))[0];+ if (!after || /\s/u.test(after)) return false;+ if (isPunctuationOrSymbol(after)) {+ return (+ !before ||+ /\s/u.test(before) ||+ isPunctuationOrSymbol(before) ||+ isNormalEmphasisCharacter(before)+ );+ }+ return true;+}++function canCloseEmphasis(+ line: string,+ index: number,+ marker: string,+): boolean {+ const before = Array.from(line.slice(0, index)).pop();+ const afterIndex = index + marker.length;+ const after = Array.from(line.slice(afterIndex))[0];+ if (!before || /\s/u.test(before)) return false;+ if (isPunctuationOrSymbol(before)) {+ return (+ !after ||+ /\s/u.test(after) ||+ isPunctuationOrSymbol(after) ||+ isNormalEmphasisCharacter(after)+ );+ }+ return true;+}++function pairedEmphasisDelimiters(+ line: string,+): Array<{ marker: string; leftOpener: number; rightCloser: number }> {+ const openers = new Map<string, number[]>([+ ["*", []],+ ["**", []],+ ]);+ const pairs: Array<{+ marker: string;+ leftOpener: number;+ rightCloser: number;+ }> = [];+ let cursor = 0;+ while (cursor < line.length) {+ if (line[cursor] !== "*") {+ cursor += 1;+ continue;+ }+ let slashCount = 0;+ for (+ let previous = cursor - 1;+ previous >= 0 && line[previous] === "\\";+ previous -= 1+ ) {+ slashCount += 1;+ }+ if (slashCount % 2 !== 0) {+ cursor += 1;+ continue;+ }+ let runEnd = cursor;+ while (line[runEnd] === "*") runEnd += 1;+ const marker = line.slice(cursor, runEnd);+ if (openers.has(marker)) {+ const canOpen = canOpenEmphasis(line, cursor, marker);+ const canClose = canCloseEmphasis(line, cursor, marker);+ const candidates = openers.get(marker)!;+ if (canClose && candidates.length) {+ pairs.push({+ marker,+ leftOpener: candidates.pop()!,+ rightCloser: cursor,+ });+ } else if (canOpen) {+ candidates.push(cursor);+ }+ }+ cursor = runEnd;+ }+ return pairs;+}++function repairChineseEmphasisLine(line: string): string {+ const insertions: number[] = [];+ for (const { marker, leftOpener, rightCloser } of pairedEmphasisDelimiters(+ line,+ )) {+ const leftBefore = Array.from(line.slice(0, leftOpener)).pop();+ const leftInside = Array.from(line.slice(leftOpener + marker.length))[0];+ const rightInside = Array.from(line.slice(0, rightCloser)).pop();+ const rightAfterIndex = rightCloser + marker.length;+ const rightAfter = Array.from(line.slice(rightAfterIndex))[0];+ const leftNeedsSpace =+ isNormalEmphasisCharacter(leftBefore) &&+ isPunctuationOrSymbol(leftInside);+ const rightNeedsSpace =+ isPunctuationOrSymbol(rightInside) &&+ isNormalEmphasisCharacter(rightAfter);+ if (leftNeedsSpace) insertions.push(leftOpener);+ if (rightNeedsSpace) insertions.push(rightAfterIndex);+ if (leftNeedsSpace !== rightNeedsSpace) {+ if (+ isNormalEmphasisCharacter(rightInside) &&+ isNormalEmphasisCharacter(rightAfter)+ ) {+ insertions.push(rightAfterIndex);+ } else if (+ isNormalEmphasisCharacter(leftBefore) &&+ isNormalEmphasisCharacter(leftInside)+ ) {+ insertions.push(leftOpener);+ }+ }+ }++ return [...new Set(insertions)]+ .sort((a, b) => b - a)+ .reduce(+ (value, index) => `${value.slice(0, index)} ${value.slice(index)}`,+ line,+ );+}++/** Repair CJK emphasis delimiter boundaries for display without mutating source content. */+export function repairChineseEmphasis(+ content: string,+ language?: string,+): string {+ if (!content || !language?.toLowerCase().startsWith("zh")) return content;+ const fenced = maskProtectedSpans(+ content,+ FENCED_CODE_BLOCK_REGEX,+ "CJK_FENCED",+ );+ const math = maskProtectedSpans(fenced.masked, MATH_SPAN_REGEX, "CJK_MATH");+ const inline = maskProtectedSpans(+ math.masked,+ INLINE_CODE_SPAN_REGEX,+ "CJK_INLINE",+ );+ const repaired = inline.masked+ .split("\n")+ .map(repairChineseEmphasisLine)+ .join("\n");+ return fenced.restore(math.restore(inline.restore(repaired)));+}+/*** Repair one line, or leave it exactly as it was.*diff --git a/web/lib/quiz-types.ts b/web/lib/quiz-types.tsindex 634ed0c21..53aa576a3 100644--- a/web/lib/quiz-types.ts+++ b/web/lib/quiz-types.ts@@ -2,6 +2,7 @@* Shared types for Quiz Generation (deep_question capability).*/+import { decodeEscapedUnicodeForDisplay } from "./markdown-display";import {type NormalizedQuizQuestionType,normalizeQuizQuestionType,@@ -78,6 +79,42 @@ export interface QuizFollowupContext {ai_judgment?: string;}+/** Decode dense ``\\uXXXX`` runs on learner-facing quiz strings (#973 family). */+function decodeQuizText(value: string | undefined | null): string {+ return decodeEscapedUnicodeForDisplay(String(value ?? ""));+}++function decodeQuizOptions(+ options: Record<string, string> | undefined,+): Record<string, string> | undefined {+ if (!options || typeof options !== "object") return undefined;+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(options)) {+ out[key] = decodeQuizText(value);+ }+ return out;+}++function buildQuizQuestionFromQa(qa: Record<string, unknown>): QuizQuestion {+ return {+ question_id: String(qa.question_id ?? ""),+ question: decodeQuizText(qa.question as string | undefined | null),+ question_type: normalizeQuizQuestionType(qa.question_type),+ options: decodeQuizOptions(qa.options as Record<string, string> | undefined),+ correct_answer: decodeQuizText(qa.correct_answer as string | undefined | null),+ explanation: decodeQuizText(qa.explanation as string | undefined | null),+ difficulty: qa.difficulty ? String(qa.difficulty) : undefined,+ concentration: qa.concentration ? String(qa.concentration) : undefined,+ knowledge_context:+ qa.metadata &&+ typeof qa.metadata === "object" &&+ "knowledge_context" in qa.metadata &&+ qa.metadata.knowledge_context+ ? decodeQuizText(String(qa.metadata.knowledge_context))+ : undefined,+ };+}+/*** Extract QuizQuestion[] from per-question ``content`` events emitted live* by the new ``QuestionPipeline`` while the quizzing phase is running.@@ -107,16 +144,7 @@ export function extractStreamingQuizQuestions(const qa = meta.qa_pair as Record<string, unknown> | undefined;if (!qa || typeof qa !== "object" || !qa.question) continue;const idx = Number(meta.question_index);- const question: QuizQuestion = {- question_id: String(qa.question_id ?? ""),- question: String(qa.question ?? ""),- question_type: normalizeQuizQuestionType(qa.question_type),- options: qa.options as Record<string, string> | undefined,- correct_answer: String(qa.correct_answer ?? ""),- explanation: String(qa.explanation ?? ""),- difficulty: qa.difficulty ? String(qa.difficulty) : undefined,- concentration: qa.concentration ? String(qa.concentration) : undefined,- };+ const question = buildQuizQuestionFromQa(qa);const key = question.question_id || String(idx);byId.set(key, {idx: Number.isFinite(idx) ? idx : byId.size,@@ -171,24 +199,7 @@ export function extractQuizQuestions(const parsed: Array<QuizQuestion | null> = results.map((item) => {const qa = (item.qa_pair ?? item) as Record<string, unknown>;if (!qa.question) return null;- const question: QuizQuestion = {- question_id: String(qa.question_id ?? ""),- question: String(qa.question ?? ""),- question_type: normalizeQuizQuestionType(qa.question_type),- options: qa.options as Record<string, string> | undefined,- correct_answer: String(qa.correct_answer ?? ""),- explanation: String(qa.explanation ?? ""),- difficulty: qa.difficulty ? String(qa.difficulty) : undefined,- concentration: qa.concentration ? String(qa.concentration) : undefined,- knowledge_context:- qa.metadata &&- typeof qa.metadata === "object" &&- "knowledge_context" in qa.metadata &&- qa.metadata.knowledge_context- ? String(qa.metadata.knowledge_context)- : undefined,- };- return question;+ return buildQuizQuestionFromQa(qa);});return parsed.filter(diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.tsindex 7f8b7b260..b66a2a267 100644--- a/web/lib/reading-api.ts+++ b/web/lib/reading-api.ts@@ -138,6 +138,26 @@ export interface ReadingPosition {updated_at: number;}+export function parseReadingPosition(payload: unknown): ReadingPosition {+ if (!payload || typeof payload !== "object") {+ throw new Error("Invalid reading position response");+ }+ const position = payload as Record<string, unknown>;+ if (+ typeof position.locator !== "number" ||+ !Number.isFinite(position.locator) ||+ position.locator < 1 ||+ typeof position.source_anchor !== "string" ||+ typeof position.percentage !== "number" ||+ !Number.isFinite(position.percentage) ||+ typeof position.updated_at !== "number" ||+ !Number.isFinite(position.updated_at)+ ) {+ throw new Error("Invalid reading position response");+ }+ return position as unknown as ReadingPosition;+}+/*** A place the reader chose to keep, as opposed to the position above — which* is the single automatic "where I got to", overwritten on every move. These@@ -305,10 +325,12 @@ export function rawMaterialUrl(materialId: string): string {export async function getReadingPosition(materialId: string,): Promise<ReadingPosition> {- return unwrap(- await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {- cache: "no-store",- }),+ return parseReadingPosition(+ await unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {+ cache: "no-store",+ }),+ ),);}@@ -316,12 +338,14 @@ export async function saveReadingPosition(materialId: string,position: Pick<ReadingPosition, "locator" | "source_anchor" | "percentage">,): Promise<ReadingPosition> {- return unwrap(- await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(position),- }),+ return parseReadingPosition(+ await unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/position`), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(position),+ }),+ ),);}diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 5e881be20..c624952ff 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -22,12 +22,31 @@ export interface SessionMessage {size_bytes?: number;}>;metadata?: Record<string, unknown>;+ trace?: MessageTraceMetadata;created_at: number;/** Edit-branching: id of the message this row continues. `null` for the* first message in a session. Siblings share the same parent. */parent_message_id?: number | null;}+export interface MessageTraceMetadata {+ turn_id?: string | null;+ total?: number;+ last_seq?: number;+ truncated?: boolean;+}++export interface MessageTracePage {+ session_id: string;+ message_id: number;+ turn_id?: string | null;+ events: StreamEvent[];+ total: number;+ last_seq: number;+ next_seq: number | null;+ complete: boolean;+}+export interface SessionPreferences {capability?: string;/** Stable learning surface, independent of the action used for a turn. */@@ -221,6 +240,21 @@ export async function updateSessionTitle(return data.session;}+export async function getMessageTrace(+ sessionId: string,+ messageId: number,+ afterSeq = 0,+ signal?: AbortSignal,+): Promise<MessageTracePage> {+ const response = await apiFetch(+ apiUrl(+ `/api/sessions/${sessionId}/messages/${messageId}/events?after_seq=${afterSeq}&limit=500`,+ ),+ { cache: "no-store", signal },+ );+ return expectJson<MessageTracePage>(response);+}+export type SessionOrganizationPatch = Partial<{course_id: string;parent_session_id: string;diff --git a/web/lib/subagents-api.ts b/web/lib/subagents-api.tsindex 916e98a34..611a20f96 100644--- a/web/lib/subagents-api.ts+++ b/web/lib/subagents-api.ts@@ -158,6 +158,13 @@ export interface SubagentBackendConfig {thinking?: boolean;forward_images?: boolean;extra_args?: string[];+ /** Remote Hermes gateway URL; the API key itself is never persisted here. */+ base_url?: string;+ /** Environment variable name containing the remote gateway bearer. */+ api_key_env?: string;+ /** Informational profile name associated with the gateway deployment. */+ profile?: string;+ idle_timeout_seconds?: number;}export interface SubagentSettings {diff --git a/web/lib/video-learning-api.ts b/web/lib/video-learning-api.tsindex 65fbe6de4..fe81e48a7 100644--- a/web/lib/video-learning-api.ts+++ b/web/lib/video-learning-api.ts@@ -78,20 +78,31 @@ export interface VideoLearningSettings {async function unwrap<T>(response: Response): Promise<T> {if (!response.ok) {- const payload = await response.json().catch(() => ({}));- const detail = (payload as { detail?: unknown })?.detail;- const message =- typeof detail === "string"- ? detail- : typeof (detail as { message?: unknown } | undefined)?.message ===- "string"- ? (detail as { message: string }).message- : null;- throw new Error(message || `Request failed (${response.status})`);+ throw await responseError(response);}return (await response.json()) as T;}+async function responseError(response: Response): Promise<Error> {+ const payload = await response.json().catch(() => ({}));+ const detail = (payload as { detail?: unknown })?.detail;+ const message =+ typeof detail === "string"+ ? detail+ : typeof (detail as { message?: unknown } | undefined)?.message ===+ "string"+ ? (detail as { message: string }).message+ : null;+ return new Error(message || `Request failed (${response.status})`);+}++async function unwrapText(response: Response): Promise<string> {+ if (!response.ok) {+ throw await responseError(response);+ }+ return response.text();+}+export async function listVideoNotes(materialId: string): Promise<VideoNote[]> {return unwrap(await apiFetch(@@ -122,6 +133,17 @@ export async function createVideoNote();}+export async function exportVideoNotes(materialId: string): Promise<string> {+ return unwrapText(+ await apiFetch(+ apiUrl(+ `/api/video-learning/materials/${encodeURIComponent(materialId)}/notes.md`,+ ),+ { cache: "no-store" },+ ),+ );+}+export async function updateVideoNote(materialId: string,noteId: string,diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 3f13043ad..264b5bd32 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3487,6 +3487,9 @@"paused": "paused","Draft": "Draft","Outline": "Outline",+ "Board": "Board",+ "Start tutoring": "Start tutoring",+ "The learning board could not be loaded": "The learning board could not be loaded","Contents": "Contents","Document contents": "Document contents","Pages": "Pages",@@ -4449,6 +4452,7 @@"no captions": "no captions","Retry captions": "Retry captions","Explain here": "Explain here",+ "Follow playback": "Follow playback","YouTube playback failed.": "YouTube playback failed.","YouTube learning video": "YouTube learning video","The configured Invidious stream could not be played.": "The configured Invidious stream could not be played.",@@ -4523,6 +4527,8 @@"Reading extensions": "Reading extensions","Video notes": "Video notes","Add video note": "Add video note",+ "Copy notes": "Copy notes",+ "Notes copied": "Notes copied","Save video note": "Save video note","Note at {{time}}": "Note at {{time}}","Edit note at {{time}}": "Edit note at {{time}}",@@ -4532,6 +4538,7 @@"No notes yet.": "No notes yet.","Loading notes.": "Loading notes.","Notes could not be loaded.": "Notes could not be loaded.",+ "Notes could not be copied.": "Notes could not be copied.","Note was not saved.": "Note was not saved.","Note was not deleted.": "Note was not deleted.","Video learning panels": "Video learning panels",@@ -4701,5 +4708,50 @@"Regenerate covering these too": "Regenerate covering these too","Or leave them out — you can also edit the outline directly below.": "Or leave them out — you can also edit the outline directly below.","more": "more",- "{{visited}} of {{total}} chapters read": "{{visited}} of {{total}} chapters read"+ "{{visited}} of {{total}} chapters read": "{{visited}} of {{total}} chapters read",+ "Indexing model": "Indexing model",+ "Select an indexing model": "Select an indexing model",+ "Loading model catalog…": "Loading model catalog…",+ "The model catalog could not be loaded. Check model settings and try again.": "The model catalog could not be loaded. Check model settings and try again.",+ "No indexing model is available. Configure an LLM model first.": "No indexing model is available. Configure an LLM model first.",+ "Auto inherits the selected model's saved reasoning effort.": "Auto inherits the selected model's saved reasoning effort.",+ "Indexing model provenance": "Indexing model provenance",+ "Pending pinned indexing model": "Pending pinned indexing model",+ "Pinned indexing model": "Pinned indexing model",+ "Legacy unpinned indexing model": "Legacy unpinned indexing model",+ "Takes effect on the first index. No index version has been published yet.": "Takes effect on the first index. No index version has been published yet.",+ "Incremental indexing continues with this pinned model.": "Incremental indexing continues with this pinned model.",+ "Uses the active chat model when indexing. Re-index to pin a model.": "Uses the active chat model when indexing. Re-index to pin a model.",+ "Active chat model at indexing time": "Active chat model at indexing time",+ "Model default": "Model default",+ "VLM capability": "VLM capability",+ "Available": "Available",+ "Unavailable": "Unavailable",+ "used for this version": "used for this version",+ "not used for this version": "not used for this version",+ "Version source": "Version source",+ "Pending configuration": "Pending configuration",+ "Legacy metadata": "Legacy metadata",+ "Each full rebuild publishes a separate LightRAG index version.": "Each full rebuild publishes a separate LightRAG index version.",+ "Change model": "Change model",+ "Change pending indexing model": "Change pending indexing model",+ "Re-index with a pinned model": "Re-index with a pinned model",+ "Save model": "Save model",+ "Start full re-index": "Start full re-index",+ "This selection will take effect when the empty knowledge base is indexed for the first time.": "This selection will take effect when the empty knowledge base is indexed for the first time.",+ "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.": "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.",+ "Failed rebuild candidate": "Failed rebuild candidate",+ "Not published": "Not published",+ "Rebuild candidate in progress": "Rebuild candidate in progress",+ "Building": "Building",+ "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds.": "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds.",+ "LightRAG query model": "LightRAG query model",+ "Use active chat model": "Use active chat model",+ "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.": "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.",+ "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.": "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.",+ "The current LightRAG query model is unavailable here. Choose an accessible indexing model.": "The current LightRAG query model is unavailable here. Choose an accessible indexing model.",+ "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.": "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.",+ "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.": "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.",+ "Unverified historical indexing model": "Unverified historical indexing model",+ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.": "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 8576f7c93..0d74a1abd 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3487,6 +3487,9 @@"paused": "已暂停","Draft": "草稿","Outline": "大纲",+ "Board": "看板",+ "Start tutoring": "开始辅导",+ "The learning board could not be loaded": "学习看板加载失败","Contents": "目录","Document contents": "文档目录","Pages": "页码",@@ -4449,6 +4452,7 @@"no captions": "没有字幕","Retry captions": "重试字幕","Explain here": "解释此处",+ "Follow playback": "跟随播放","YouTube playback failed.": "YouTube 播放失败。","YouTube learning video": "YouTube 学习视频","The configured Invidious stream could not be played.": "无法播放已配置的 Invidious 视频流。",@@ -4523,6 +4527,8 @@"Reading extensions": "阅读扩展","Video notes": "视频笔记","Add video note": "添加视频笔记",+ "Copy notes": "复制笔记",+ "Notes copied": "笔记已复制","Save video note": "保存视频笔记","Note at {{time}}": "{{time}} 的笔记","Edit note at {{time}}": "编辑 {{time}} 的笔记",@@ -4532,6 +4538,7 @@"No notes yet.": "暂无笔记。","Loading notes.": "正在加载笔记。","Notes could not be loaded.": "无法加载笔记。",+ "Notes could not be copied.": "无法复制笔记。","Note was not saved.": "笔记未保存。","Note was not deleted.": "笔记未删除。","Video learning panels": "视频学习面板",@@ -4701,5 +4708,50 @@"Regenerate covering these too": "重新生成,把它们也覆盖进来","Or leave them out — you can also edit the outline directly below.": "也可以不管它们——下面的大纲你随时可以直接改。","more": "个",- "{{visited}} of {{total}} chapters read": "已读 {{visited}}/{{total}} 章"+ "{{visited}} of {{total}} chapters read": "已读 {{visited}}/{{total}} 章",+ "Indexing model": "索引模型",+ "Select an indexing model": "选择索引模型",+ "Loading model catalog…": "正在加载模型目录…",+ "The model catalog could not be loaded. Check model settings and try again.": "无法加载模型目录。请检查模型设置后重试。",+ "No indexing model is available. Configure an LLM model first.": "没有可用的索引模型。请先配置 LLM 模型。",+ "Auto inherits the selected model's saved reasoning effort.": "自动模式会继承所选模型已保存的推理强度。",+ "Indexing model provenance": "索引模型溯源",+ "Pending pinned indexing model": "待生效的固定索引模型",+ "Pinned indexing model": "固定索引模型",+ "Legacy unpinned indexing model": "旧版未固定索引模型",+ "Takes effect on the first index. No index version has been published yet.": "将在首次建立索引时生效;当前尚未发布索引版本。",+ "Incremental indexing continues with this pinned model.": "后续增量索引将继续使用此固定模型。",+ "Uses the active chat model when indexing. Re-index to pin a model.": "建立索引时使用当前活动对话模型。请完整重建以固定模型。",+ "Active chat model at indexing time": "建立索引时的活动对话模型",+ "Model default": "模型默认值",+ "VLM capability": "VLM 能力",+ "Available": "可用",+ "Unavailable": "不可用",+ "used for this version": "此版本已使用",+ "not used for this version": "此版本未使用",+ "Version source": "版本来源",+ "Pending configuration": "待生效配置",+ "Legacy metadata": "旧版元数据",+ "Each full rebuild publishes a separate LightRAG index version.": "每次完整重建都会发布独立的 LightRAG 索引版本。",+ "Change model": "更改模型",+ "Change pending indexing model": "更改待生效索引模型",+ "Re-index with a pinned model": "使用固定模型完整重建",+ "Save model": "保存模型",+ "Start full re-index": "开始完整重建",+ "This selection will take effect when the empty knowledge base is indexed for the first time.": "该选择将在空知识库首次建立索引时生效。",+ "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.": "完整重建会发布新版本,并将此模型固定为后续增量上传的索引身份。",+ "Failed rebuild candidate": "失败的重建候选版本",+ "Not published": "未发布",+ "Rebuild candidate in progress": "正在构建重建候选版本",+ "Building": "构建中",+ "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds.": "选择模型并发布新的 LightRAG 索引版本;重建成功前,当前已发布版本保持可用。",+ "LightRAG query model": "LightRAG 查询模型",+ "Use active chat model": "使用当前对话模型",+ "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.": "用于当前 LightRAG 查询,并作为新建或完整重建知识库的默认索引模型。已发布索引继续使用其固定的索引模型。",+ "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.": "默认使用当前 LightRAG 查询模型。索引发布后,后续增量索引会继续使用此选择。",+ "The current LightRAG query model is unavailable here. Choose an accessible indexing model.": "当前 LightRAG 查询模型在此不可用。请选择你有权使用的索引模型。",+ "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.": "无法加载 LightRAG 查询模型设置。请选择索引模型或重试。",+ "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.": "历史索引模型无法确认。知识库仍可查询,但增量上传前必须完整重建。",+ "Unverified historical indexing model": "无法确认的历史索引模型",+ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.": "此旧版 LightRAG 索引仍可查询,但增量上传前必须完整重建。"}diff --git a/web/next.config.js b/web/next.config.jsindex 231727948..61e651c40 100644--- a/web/next.config.js+++ b/web/next.config.js@@ -140,6 +140,24 @@ const nextConfig = {// Transpile mermaid and related packages for proper ESM handlingtranspilePackages: ["mermaid"],+ // v1.6.2 and earlier bookmarked Mastery Study at `/study`; tip teaches under+ // `/sessions`. Permanent redirects keep old URLs (and issue repro links)+ // landing on the live surface instead of a bare 404.+ async redirects() {+ return [+ {+ source: "/mastery/:pathId/study",+ destination: "/mastery/:pathId/sessions",+ permanent: true,+ },+ {+ source: "/mastery/:pathId/study/:sessionId",+ destination: "/mastery/:pathId/sessions/:sessionId",+ permanent: true,+ },+ ];+ },+// Next.js 16 blocks cross-origin access to /_next/* dev resources (HMR// WebSocket, fonts, dev-only scripts) unless the request host is on this// allow-list. Without it, browsing http://127.0.0.1:<port>/ against a devdiff --git a/web/scripts/route_budgets.mjs b/web/scripts/route_budgets.mjsindex 316a63ccb..ae2dad5d2 100644--- a/web/scripts/route_budgets.mjs+++ b/web/scripts/route_budgets.mjs@@ -13,7 +13,7 @@ const ROUTE_TARGETS = [{ route: "/", requestPath: "/", budgetKb: 300 },{ route: "/chat/[sessionId]", requestPath: "/chat/perf-budget", budgetKb: 1_020 },{ route: "/settings", requestPath: "/settings", budgetKb: 840 },- { route: "/knowledge-bases", requestPath: "/knowledge-bases", budgetKb: 540 },+ { route: "/knowledge-bases", requestPath: "/knowledge-bases", budgetKb: 550 },{ route: "/co-writer", requestPath: "/co-writer", budgetKb: 320 },{ route: "/co-writer/[docId]", requestPath: "/co-writer/perf-budget", budgetKb: 515 },{diff --git a/web/tests/e2e/book-reader-sequential.audit.ts b/web/tests/e2e/book-reader-sequential.audit.tsindex 382c5a5a8..82334fea7 100644--- a/web/tests/e2e/book-reader-sequential.audit.ts+++ b/web/tests/e2e/book-reader-sequential.audit.ts@@ -134,7 +134,7 @@ test("book arrows read the current chapter before turning chapters", async ({// A hidden reader (for example when the mobile chapter sidebar is expanded)// must not turn the page and skip unread content.await page.keyboard.press("ArrowRight");- await expect(page).toHaveURL(/page=page-2/);+ await expect(page).toHaveURL(/\/pages\/page-2(?:[?#]|$)/);await page.getByRole("button", { name: "Collapse chapters" }).click();await expect(@@ -180,12 +180,14 @@ test("book arrows read the current chapter before turning chapters", async ({).toBe(100);await page.keyboard.press("ArrowRight");+ await expect(page).toHaveURL(/\/pages\/page-3(?:[?#]|$)/);await expect(page.getByRole("heading", { name: "Next chapter" }),).toBeVisible();await expect(await reader.evaluate((element) => element.scrollTop)).toBe(0);await page.keyboard.press("ArrowLeft");+ await expect(page).toHaveURL(/\/pages\/page-2(?:[?#]|$)/);await expect(page.getByRole("heading", { name: "Current long chapter" }),).toBeVisible();diff --git a/web/tests/e2e/settings-navigation.audit.ts b/web/tests/e2e/settings-navigation.audit.tsnew file mode 100644index 000000000..9c0c59cff--- /dev/null+++ b/web/tests/e2e/settings-navigation.audit.ts@@ -0,0 +1,35 @@+import { expect, test } from "@playwright/test";++test.describe("Settings navigation", () => {+ test("keeps scrolling inside the settings pane", async ({ page }) => {+ await page.goto("/settings");++ const settingsScroll = page.locator("[data-settings-scroll]");+ await expect(settingsScroll).toBeVisible();+ await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(0);++ const aboutLink = page.locator('a[data-tour="tour-nav-about"]');+ await aboutLink.click();+ await expect(page).toHaveURL(/\/settings#about$/);+ await expect+ .poll(() => settingsScroll.evaluate((element) => element.scrollTop))+ .toBeGreaterThan(0);++ await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(0);+ });++ test("keeps deep-link scrolling inside the settings pane", async ({+ page,+ }) => {+ await page.goto("/settings#about");++ const settingsScroll = page.locator("[data-settings-scroll]");+ await expect(settingsScroll).toBeVisible();+ await expect(page).toHaveURL(/\/settings#about$/);+ await expect+ .poll(() => settingsScroll.evaluate((element) => element.scrollTop))+ .toBeGreaterThan(0);++ await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(0);+ });+});diff --git a/web/tests/e2e/video-learning.audit.ts b/web/tests/e2e/video-learning.audit.tsindex c540bd68f..7e8034ef2 100644--- a/web/tests/e2e/video-learning.audit.ts+++ b/web/tests/e2e/video-learning.audit.ts@@ -9,8 +9,11 @@ test("YouTube learning survives reload and switches to Invidious without silentlet invidiousOffline = false;let transcriptReady = true;let transcriptRefreshCount = 0;+ let materialRequestCount = 0;let savedPosition = 0;let nativeResolveCount = 0;+ let exportRequestCount = 0;+ let exportShouldFail = false;let nextNoteId = 1;const notes: Array<{notebook_id: string;@@ -23,6 +26,16 @@ test("YouTube learning survives reload and switches to Invidious without silentcreated_at: number;updated_at: number;}> = [];+ const transcriptCues = [+ { start: 7, end: 12, text: "The first grounded concept." },+ ...Array.from({ length: 60 }, (_, index) => ({+ start: 13 + index,+ end: 14 + index,+ text: `Intermediate lesson detail ${index + 1}.`,+ })),+ { start: 70, end: 75, text: "The second grounded concept." },+ { start: 110, end: 115, text: "The third grounded concept." },+ ];const material = (selected: "youtube" | "invidious") => ({version: 1,@@ -45,10 +58,7 @@ test("YouTube learning survives reload and switches to Invidious without silentreason: "",language: "en",source: selected,- cues: [- { start: 7, end: 12, text: "The first grounded concept." },- { start: 70, end: 75, text: "The second grounded concept." },- ],+ cues: transcriptCues,}: {status: "unavailable",@@ -78,6 +88,8 @@ test("YouTube learning survives reload and switches to Invidious without silent},});+ await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);+await page.addInitScript(() => {class FakePlayer {current = 0;@@ -119,6 +131,11 @@ test("YouTube learning survives reload and switches to Invidious without silentplayVideo() {}pauseVideo() {}destroy() {+ const players = (+ window as typeof window & { __fakePlayers?: FakePlayer[] }+ ).__fakePlayers;+ const index = players?.indexOf(this) ?? -1;+ if (index >= 0) players?.splice(index, 1);this.element.remove();}}@@ -161,6 +178,7 @@ test("YouTube learning survives reload and switches to Invidious without silentreturn json(material(body.provider_override || provider));}if (path === `/api/video-learning/materials/${MATERIAL_ID}`) {+ materialRequestCount += 1;if (provider === "invidious" && invidiousOffline) {return json({ detail: "Invidious is offline" }, 400);}@@ -181,6 +199,15 @@ test("YouTube learning survives reload and switches to Invidious without silentif (path.endsWith("/notes") && request.method() === "GET") {return json(notes);}+ if (path.endsWith("/notes.md")) {+ exportRequestCount += 1;+ if (exportShouldFail) return json({ detail: "Notes export failed" }, 500);+ return route.fulfill({+ status: 200,+ contentType: "text/markdown",+ body: "# Video notes: Timestamped lesson\n\n## 0:08\n\nFirst timestamped note\n",+ });+ }if (path.endsWith("/notes") && request.method() === "POST") {const body = request.postDataJSON() as {body: string;@@ -257,14 +284,83 @@ test("YouTube learning survives reload and switches to Invidious without silentpage.getByText("The first grounded concept.").locator(".."),).toHaveClass(/ring-1/);+ const transcriptList = page.getByTestId("video-transcript-list");+ const followButton = page.getByRole("button", { name: "Follow playback" });+ await expect(followButton).toHaveAttribute("aria-pressed", "true");+ await page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1);+ if (player) player.current = 74;+ });+ await expect(+ page.getByText("The second grounded concept.").locator(".."),+ ).toHaveClass(/ring-1/);+ await expect+ .poll(() => transcriptList.evaluate((element) => element.scrollTop))+ .toBeGreaterThan(100);++ await transcriptList.hover();+ await page.mouse.wheel(0, 20);+ await expect(followButton).toHaveAttribute("aria-pressed", "false");+ const pausedScrollTop = await transcriptList.evaluate(+ (element) => element.scrollTop,+ );+ await page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1);+ if (player) player.current = 112;+ });+ await expect(+ page.getByText("The third grounded concept.").locator(".."),+ ).toHaveClass(/ring-1/);+ await expect+ .poll(() => transcriptList.evaluate((element) => element.scrollTop))+ .toBe(pausedScrollTop);+ await followButton.click();+ await expect(followButton).toHaveAttribute("aria-pressed", "true");+ await expect+ .poll(() => transcriptList.evaluate((element) => element.scrollTop))+ .toBeGreaterThan(pausedScrollTop);++ await transcriptList.dispatchEvent("pointerdown", { pointerType: "mouse" });+ await expect(followButton).toHaveAttribute("aria-pressed", "false");+ await followButton.click();+ await expect(followButton).toHaveAttribute("aria-pressed", "true");++ await page.evaluate(() => {+ const player = (+ window as typeof window & { __fakePlayers: Array<{ current: number }> }+ ).__fakePlayers.at(-1);+ if (player) player.current = 8;+ });await page.getByRole("tab", { name: "Video notes" }).click();await expect(page.getByText("No notes yet.")).toBeVisible();+ await expect(page.getByRole("button", { name: "Copy notes" })).toBeDisabled();await page.getByPlaceholder("Note at 0:08").fill("First timestamped note");await page.getByRole("button", { name: "Add video note" }).click();await expect(page.getByText("First timestamped note")).toBeVisible();await expect(page.getByText("The first grounded concept.")).toBeVisible();+ await page.getByRole("button", { name: "Copy notes" }).click();+ await expect(page.getByRole("button", { name: "Notes copied" })).toBeVisible();+ await expect.poll(() => exportRequestCount).toBe(1);+ await expect(+ page.evaluate(() => navigator.clipboard.readText()),+ ).resolves.toContain("First timestamped note");- await page.reload();+ exportShouldFail = true;+ await page.getByRole("button", { name: "Notes copied" }).click();+ await expect(+ page.getByRole("alert").filter({ hasText: "Notes export failed" }),+ ).toBeVisible();+ exportShouldFail = false;++ await page.goto("/");+ await page.waitForTimeout(100);+ expect(materialRequestCount).toBe(0);+ await page.goto("/chat?capability=immersive_watching");+ await expect.poll(() => materialRequestCount).toBe(1);await expect(page.getByText("Timestamped lesson")).toBeVisible();await page.getByRole("tab", { name: "Video notes" }).click();await expect(page.getByText("First timestamped note")).toBeVisible();diff --git a/web/tests/lightrag-indexing-model.test.ts b/web/tests/lightrag-indexing-model.test.tsnew file mode 100644index 000000000..4625008e8--- /dev/null+++ b/web/tests/lightrag-indexing-model.test.ts@@ -0,0 +1,319 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import path from "node:path";++import {+ createKnowledgeBase,+ reindexKnowledgeBase,+ updatePendingIndexingPolicy,+} from "../features/knowledge/api/client";+import {+ selectionFromLightRagDefault,+ selectionFromLLMOption,+} from "../components/knowledge/IndexingModelSelector";+import { selectionForLightRagModelDialog } from "../components/knowledge/KbIndexVersionsSection";+import {+ currentLightRagBuildCandidate,+ kbCanUploadDocuments,+ kbCanReindex,+ kbIsUploadable,+ lightRagVersionDisplayState,+ type KnowledgeBase,+} from "../lib/knowledge-helpers";++function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function stubFetch(+ handler: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,+): () => void {+ const original = globalThis.fetch;+ globalThis.fetch = handler;+ return () => {+ globalThis.fetch = original;+ };+}++test("create and re-index send the exact pinned selection and preserve none", async () => {+ const requests: Array<{ url: string; form: FormData }> = [];+ const restore = stubFetch(async (input, init) => {+ requests.push({ url: String(input), form: init?.body as FormData });+ return jsonResponse(200, { task_id: "task-1", noop: false });+ });+ const selection = {+ profile_id: "profile-1",+ model_id: "model-1",+ reasoning_effort: "none",+ };+ try {+ await createKnowledgeBase({+ name: "papers",+ provider: "lightrag",+ files: [],+ indexingLLM: selection,+ });+ await reindexKnowledgeBase("papers", selection);+ } finally {+ restore();+ }++ assert.equal(requests[0].url, "/api/knowledge-bases");+ assert.deepEqual(+ JSON.parse(String(requests[0].form.get("indexing_llm"))),+ selection,+ );+ assert.equal(requests[1].url, "/api/knowledge-bases/papers/reindex");+ assert.deepEqual(+ JSON.parse(String(requests[1].form.get("indexing_llm"))),+ selection,+ );+});++test("pending-policy update is JSON-only and creates no indexing request", async () => {+ let captured: { url: string; init?: RequestInit } | undefined;+ const restore = stubFetch(async (input, init) => {+ captured = { url: String(input), init };+ return jsonResponse(200, { indexing_policy: { policy: "pending_pinned" } });+ });+ try {+ await updatePendingIndexingPolicy("empty", {+ profile_id: "p",+ model_id: "m",+ });+ } finally {+ restore();+ }+ assert.equal(captured?.url, "/api/knowledge-bases/empty/indexing-policy");+ assert.equal(captured?.init?.method, "PUT");+ assert.deepEqual(JSON.parse(String(captured?.init?.body)), {+ profile_id: "p",+ model_id: "m",+ });+});++test("non-LightRAG re-index keeps the established bodyless request", async () => {+ let captured: RequestInit | undefined;+ const restore = stubFetch(async (_input, init) => {+ captured = init;+ return jsonResponse(200, { task_id: "task-2", noop: false });+ });+ try {+ await reindexKnowledgeBase("vectors");+ } finally {+ restore();+ }+ assert.equal(captured?.method, "POST");+ assert.equal(Object.hasOwn(captured ?? {}, "body"), false);+});++test("model defaults are inherited while an explicit none remains serialized", () => {+ const option = {+ profile_id: "p",+ model_id: "m",+ profile_name: "OpenAI",+ model_name: "GPT",+ model: "gpt-5",+ provider: "openai",+ is_active_default: true,+ reasoning_effort: "high",+ };+ assert.deepEqual(selectionFromLLMOption(option), {+ profile_id: "p",+ model_id: "m",+ });+ assert.deepEqual(selectionFromLLMOption(option, "none"), {+ profile_id: "p",+ model_id: "m",+ reasoning_effort: "none",+ });+});++test("indexing defaults prefer the released LightRAG query model", () => {+ const active = {+ profile_id: "active-profile",+ model_id: "active-model",+ profile_name: "Active",+ model_name: "Active model",+ model: "active",+ provider: "openai",+ is_active_default: true,+ };+ const dedicated = {+ ...active,+ profile_id: "query-profile",+ model_id: "query-model",+ profile_name: "Query",+ model_name: "Query model",+ model: "query",+ is_active_default: false,+ };+ assert.deepEqual(+ selectionFromLightRagDefault(+ [active, dedicated],+ { llm_profile_id: "query-profile", llm_model_id: "query-model" },+ { profile_id: "active-profile", model_id: "active-model" },+ ),+ { profile_id: "query-profile", model_id: "query-model" },+ );+ assert.deepEqual(+ selectionFromLightRagDefault(+ [active, dedicated],+ { llm_profile_id: "", llm_model_id: "" },+ { profile_id: "active-profile", model_id: "active-model" },+ ),+ { profile_id: "active-profile", model_id: "active-model" },+ );+ assert.equal(+ selectionFromLightRagDefault(+ [active],+ { llm_profile_id: "missing", llm_model_id: "missing" },+ { profile_id: "active-profile", model_id: "active-model" },+ ),+ null,+ );+});++test("late catalog loading preserves an empty knowledge base's saved pending model", () => {+ const option = {+ profile_id: "saved-profile",+ model_id: "saved-model",+ profile_name: "Saved",+ model_name: "Saved model",+ model: "saved",+ provider: "openai",+ is_active_default: false,+ };+ assert.deepEqual(+ selectionForLightRagModelDialog(+ [option],+ { llm_profile_id: "current-profile", llm_model_id: "current-model" },+ null,+ {+ profile_id: "saved-profile",+ model_id: "saved-model",+ reasoning_effort: "none",+ },+ true,+ ),+ {+ profile_id: "saved-profile",+ model_id: "saved-model",+ reasoning_effort: "none",+ },+ );+});++test("healthy LightRAG knowledge bases retain a full re-index entry", () => {+ const kb: KnowledgeBase = {+ name: "graph",+ status: "ready",+ statistics: {+ raw_documents: 2,+ rag_provider: "lightrag",+ active_match: true,+ },+ };+ assert.equal(kbCanReindex(kb), true);+ assert.equal(kbCanReindex({ ...kb, read_only: true }), false);+});++test("legacy LightRAG indexes stay queryable but are not uploadable", () => {+ const kb: KnowledgeBase = {+ name: "legacy-graph",+ status: "ready",+ metadata: { indexing_policy: { policy: "legacy_unpinned" } },+ statistics: { rag_provider: "lightrag", raw_documents: 1 },+ };+ assert.equal(kbIsUploadable(kb), false);+ assert.equal(kbCanUploadDocuments(kb, false), false);+ assert.equal(kbCanUploadDocuments({ ...kb, status: "error" }, false), false);+ assert.equal(kbCanReindex(kb), true);+});++test("ordinary error-state knowledge bases can replace failed files unless indexing is active", () => {+ const kb: KnowledgeBase = {+ name: "vectors",+ status: "error",+ statistics: { rag_provider: "llamaindex", raw_documents: 1 },+ };+ assert.equal(kbCanUploadDocuments(kb, false), true);+ assert.equal(kbCanUploadDocuments(kb, true), false);+});++test("LightRAG candidates distinguish active builds from failures", () => {+ const currentCandidate = {+ signature: "version-3",+ ready: false,+ };+ const olderFailure = {+ signature: "version-2",+ provider: "lightrag",+ ready: false,+ failure_summary: "paper.pdf: parse failed",+ };+ assert.equal(+ currentLightRagBuildCandidate([currentCandidate, olderFailure], true),+ currentCandidate,+ );+ assert.equal(currentLightRagBuildCandidate([olderFailure], false), undefined);+ assert.equal(+ lightRagVersionDisplayState(currentCandidate, {+ published: false,+ rebuildActive: true,+ kbError: false,+ legacy: false,+ }),+ "building",+ );+ assert.equal(+ lightRagVersionDisplayState(olderFailure, {+ published: false,+ rebuildActive: false,+ kbError: false,+ legacy: false,+ }),+ "failed",+ );+});++test("model controls are scoped to built-in LightRAG create/rebuild surfaces", () => {+ const root = path.resolve(process.cwd());+ const createSource = readFileSync(+ path.join(root, "components/knowledge/CreateKbModal.tsx"),+ "utf8",+ );+ const uploadSource = readFileSync(+ path.join(root, "components/knowledge/KbDocumentsSection.tsx"),+ "utf8",+ );+ const detailSource = readFileSync(+ path.join(root, "components/knowledge/KnowledgeBaseDetail.tsx"),+ "utf8",+ );+ const provenanceSource = readFileSync(+ path.join(root, "components/knowledge/LightRagIndexingProvenance.tsx"),+ "utf8",+ );+ assert.match(createSource, /provider === ['"]lightrag['"] \? \(/);+ assert.match(createSource, /indexingLLM:\s*provider === ['"]lightrag['"]/);+ assert.doesNotMatch(uploadSource, /IndexingModelSelector/);+ assert.match(uploadSource, /LightRagIndexingProvenance/);+ assert.match(provenanceSource, /compact && \(/);+ assert.match(+ provenanceSource,+ /modelLabel \|\| t\(['"]Unverified historical indexing model['"]\)/,+ );+ assert.match(+ provenanceSource,+ /t\(['"]Reasoning effort['"]\).*effort \|\| t\(['"]Model default['"]\)/s,+ );+ assert.match(+ detailSource,+ /status === ['"]error['"] && kbProvider\(kb\) !== ['"]lightrag['"]/,+ );+});diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.tsindex 43acd5fc0..dc5edebf9 100644--- a/web/tests/markdown-display.test.ts+++ b/web/tests/markdown-display.test.ts@@ -6,10 +6,68 @@ import {hasVisibleMarkdownContent,markdownUrlTransform,normalizeMarkdownForDisplay,+ repairChineseEmphasis,repairMalformedStrongEmphasis,safeDecodeURIComponent,} from "../lib/markdown-display";+test("repairChineseEmphasis repairs punctuation boundaries only for Chinese", () => {+ assert.equal(repairChineseEmphasis("中文*,重点*", "zh-CN"), "中文 *,重点*");+ assert.equal(+ repairChineseEmphasis("中文**,重点**", "zh"),+ "中文 **,重点**",+ );+ assert.equal(repairChineseEmphasis("中文*,重点*", "en"), "中文*,重点*");+ assert.equal(repairChineseEmphasis("中文*,重点*"), "中文*,重点*");+});++test("repairChineseEmphasis balances the opposite delimiter when exactly one boundary is repaired", () => {+ assert.equal(+ repairChineseEmphasis("中文*,重点*内容", "zh"),+ "中文 *,重点* 内容",+ );+});++test("repairChineseEmphasis is fed the complete raw stream, not prior display output", () => {+ const chunks = ["中文*,重", "点*", "内容"];+ const rawContent = chunks.join("");++ assert.equal(repairChineseEmphasis(rawContent, "zh"), "中文 *,重点* 内容");+ assert.equal(+ repairChineseEmphasis(+ repairChineseEmphasis(chunks.slice(0, 2).join(""), "zh") + chunks[2],+ "zh",+ ),+ "中文 *,重点*内容",+ );+});+test("repairChineseEmphasis leaves inner whitespace and literal stars unchanged", () => {+ const inputs = [+ "* 重点 *",+ "** 重点 **",+ "*重点 内容*",+ "前言 * 第一项 * 与 * 第二项 * 后记",+ "Use * as multiplication *",+ String.raw`\* 重点 \*`,+ ];+ for (const input of inputs) {+ assert.equal(repairChineseEmphasis(input, "zh"), input);+ }+});++test("repairChineseEmphasis leaves code, math, escaped, and triple-star spans untouched", () => {+ const input = [+ "`中文*,重点*`",+ "```md",+ "中文**,重点**",+ "```",+ "$中文*,重点*$",+ "\\中文\\*,重点\\*",+ "中文***,重点***内容",+ ].join("\n");+ assert.equal(repairChineseEmphasis(input, "zh"), input);+});+test("repairMalformedStrongEmphasis moves label whitespace outside the closing marker", () => {assert.equal(repairMalformedStrongEmphasis("**發布日期: **2026 年 7 月 30 日"),diff --git a/web/tests/mastery-study-route.test.ts b/web/tests/mastery-study-route.test.tsindex 57ac88c42..24ae2d056 100644--- a/web/tests/mastery-study-route.test.ts+++ b/web/tests/mastery-study-route.test.ts@@ -1,4 +1,5 @@import assert from "node:assert/strict";+import path from "node:path";import test from "node:test";import { isMasteryDraftSessionReady } from "../lib/mastery-study-route";@@ -49,3 +50,28 @@ test("a route or topic switch invalidates an older draft guard", () => {test("an unbound draft stays on the sessionless study route", () => {assert.equal(isMasteryDraftSessionReady({ ...base, sessionId: null }), false);});++test("legacy /mastery/.../study URLs permanently redirect to /sessions", async () => {+ const nextConfig = require(path.resolve(process.cwd(), "next.config.js")) as {+ redirects?: () => Promise<+ Array<{ source: string; destination: string; permanent: boolean }>+ >;+ };+ assert.equal(typeof nextConfig.redirects, "function");+ const redirects = await nextConfig.redirects!();+ assert.deepEqual(+ redirects.filter((entry) => entry.source.includes("/study")),+ [+ {+ source: "/mastery/:pathId/study",+ destination: "/mastery/:pathId/sessions",+ permanent: true,+ },+ {+ source: "/mastery/:pathId/study/:sessionId",+ destination: "/mastery/:pathId/sessions/:sessionId",+ permanent: true,+ },+ ],+ );+});diff --git a/web/tests/quiz-question-type.test.ts b/web/tests/quiz-question-type.test.tsindex 9f367718c..ec2ad2619 100644--- a/web/tests/quiz-question-type.test.ts+++ b/web/tests/quiz-question-type.test.ts@@ -74,3 +74,33 @@ test("extractQuizQuestions normalizes legacy question types from payloads", () =assert.ok(questions);assert.equal(questions?.[0]?.question_type, "choice");});++test("extractQuizQuestions decodes dense unicode escapes in card text", () => {+ const questions = extractQuizQuestions({+ summary: {+ results: [+ {+ qa_pair: {+ question_id: "q_1",+ question:+ "\\u300c\\u6570\\u5236\\u8f6c\\u6362\\u300d\\u8fd8\\u6ca1\\u8fc7\\u5173\\uff1f",+ question_type: "choice",+ options: {+ A: "\\u662f\\u7684\\uff0c\\u5df2\\u7ecf\\u8fc7\\u5173",+ B: "\\u8fd8\\u6ca1\\u6709",+ },+ correct_answer: "B",+ explanation:+ "\\u9898\\u5e72\\u91cc\\u7684\\u8f6c\\u4e49\\u5e94\\u88ab\\u89e3\\u7801",+ },+ },+ ],+ },+ });++ assert.ok(questions);+ assert.equal(questions?.[0]?.question, "「数制转换」还没过关?");+ assert.equal(questions?.[0]?.options?.A, "是的,已经过关");+ assert.equal(questions?.[0]?.options?.B, "还没有");+ assert.equal(questions?.[0]?.explanation, "题干里的转义应被解码");+});diff --git a/web/tests/reading-position.test.ts b/web/tests/reading-position.test.tsnew file mode 100644index 000000000..62028dcd6--- /dev/null+++ b/web/tests/reading-position.test.ts@@ -0,0 +1,32 @@+import assert from "node:assert/strict";+import test from "node:test";++import { parseReadingPosition } from "@/lib/reading-api";++test("reading positions accept the complete API contract", () => {+ const position = {+ locator: 3,+ source_anchor: "chapter-3",+ percentage: 0.5,+ updated_at: 42,+ };++ assert.deepEqual(parseReadingPosition(position), position);+});++test("reading positions reject partial and non-finite responses", () => {+ assert.throws(+ () => parseReadingPosition({}),+ /Invalid reading position response/,+ );+ assert.throws(+ () =>+ parseReadingPosition({+ locator: Number.NaN,+ source_anchor: "",+ percentage: 0,+ updated_at: 0,+ }),+ /Invalid reading position response/,+ );+});diff --git a/web/tests/settings-continuous-navigation.test.ts b/web/tests/settings-continuous-navigation.test.tsindex d1ab97bcd..0063b6d05 100644--- a/web/tests/settings-continuous-navigation.test.ts+++ b/web/tests/settings-continuous-navigation.test.ts@@ -83,6 +83,8 @@ test("settings scroll: the outer document tracks nested section anchors", () =>);assert.match(scrollHelper, /scroller\.scrollTo/);assert.match(scrollHelper, /window\.scrollTo/);+ assert.match(scrollHelper, /document\.documentElement\.scrollTop = 0/);+ assert.match(scrollHelper, /requestAnimationFrame\(resetDocumentScroll\)/);});test("settings page: heavy sections are split and mounted on demand", () => {diff --git a/web/tests/trace-memory.test.ts b/web/tests/trace-memory.test.tsnew file mode 100644index 000000000..4ede64832--- /dev/null+++ b/web/tests/trace-memory.test.ts@@ -0,0 +1,74 @@+import assert from "node:assert/strict";+import test from "node:test";++import type { StreamEvent } from "../features/chat/model/protocol";+import {+ MAX_LEGACY_PAYLOAD_CHARS,+ TraceCache,+ compactTracePreview,+} from "../features/chat/trace/memory";++function event(+ type: StreamEvent["type"],+ content = "",+ metadata: Record<string, unknown> = {},+): StreamEvent {+ return {+ type,+ source: "chat",+ stage: "",+ content,+ metadata,+ timestamp: 1,+ };+}++test("trace previews keep semantic state and bound legacy payloads", () => {+ const preview = compactTracePreview([+ event("content", "delta"),+ event("tool_result", "x".repeat(MAX_LEGACY_PAYLOAD_CHARS + 2)),+ event("result", "", { summary: "ok" }),+ event("done", "", { status: "completed" }),+ ]);++ assert.equal(preview.truncated, true);+ assert.deepEqual(+ preview.events.map((item) => item.type),+ ["tool_result", "result", "done"],+ );+ const bounded = preview.events[0].content ?? "";+ assert.equal(+ bounded.length,+ MAX_LEGACY_PAYLOAD_CHARS + "...[truncated]".length,+ );+});++test("expanded trace cache evicts the oldest message beyond five entries", () => {+ const cache = new TraceCache(5);+ for (let index = 0; index < 6; index += 1) {+ cache.retain(`session:${index}`, { events: [event("done")] });+ }++ const evicted = cache.release("session:0");+ assert.equal(evicted, undefined);+ assert.equal(cache.has("session:1"), true);+ assert.equal(cache.has("session:5"), true);+ assert.equal(cache.size, 5);+});++test("trace previews preserve early critical state before the event cap", () => {+ const preview = compactTracePreview(+ [+ event("content", "", { ask_user: true }),+ event("tool_result"),+ event("tool_result"),+ event("done"),+ ],+ 2,+ );++ assert.deepEqual(+ preview.events.map((item) => item.type),+ ["content", "done"],+ );+});