DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
prepare v1.3.6 release
Bingxi Zhao (Frank)eff1c0dff6d9
diff --git a/README.md b/README.mdindex b1e413bf5..a7df151f1 100644--- a/README.md+++ b/README.md@@ -28,6 +28,8 @@### 📦 Releases+> **[2026.5.3]** [v1.3.6](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.6) — Catalog-based model selection for chat and TutorBot, safer RAG re-indexing, OpenAI Responses token-limit fixes, and Skills editor validation.+> **[2026.5.2]** [v1.3.5](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.5) — Smoother local launch settings, safer RAG queries, cleaner local embedding auth, and Settings dark-mode polish.> **[2026.5.1]** [v1.3.4](https://github.com/HKUDS/DeepTutor/releases/tag/v1.3.4) — Book page chat persistence and rebuild flows, chat-to-book references, stronger language/reasoning handling, RAG document extraction hardening.@@ -52,13 +54,13 @@> **[2026.4.20]** [v1.2.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.2.0) — Book Engine "living book" compiler, multi-document Co-Writer, interactive HTML visualizations, Question Bank @-mention.+<details>+<summary><b>Past releases (more than 2 weeks ago)</b></summary>+> **[2026.4.18]** [v1.1.2](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.2) — Schema-driven Channels tab, RAG single-pipeline consolidation, externalized chat prompts.> **[2026.4.17]** [v1.1.1](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.1) — Universal "Answer now", Co-Writer scroll sync, unified settings panel, streaming Stop button.-<details>-<summary><b>Past releases (more than 2 weeks ago)</b></summary>-> **[2026.4.15]** [v1.1.0](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0) — LaTeX block math overhaul, LLM diagnostic probe, Docker + local LLM guidance.> **[2026.4.14]** [v1.1.0-beta](https://github.com/HKUDS/DeepTutor/releases/tag/v1.1.0-beta) — Bookmarkable sessions, Snow theme, WebSocket heartbeat & auto-reconnect, embedding registry overhaul.diff --git a/assets/releases/ver1-3-5.md b/assets/releases/ver1-3-5.mdindex 7e5fbda89..1bfc61d55 100644--- a/assets/releases/ver1-3-5.md+++ b/assets/releases/ver1-3-5.md@@ -11,11 +11,11 @@ servers no longer receive placeholder auth headers.### Smoother Local Launch-- **Setup Tour writes launch ports** - the guided installer now records backend- and frontend ports in `data/user/settings/env.json`, so later launches can use- the same choices.-- **`start_web.py` reads runtime settings first** - backend/frontend ports and UI- language come from web settings when available, with `.env` kept as fallback.+- **Setup Tour writes launch ports to `.env`** - the guided installer records+ backend and frontend ports in the canonical environment file, so later+ launches use the same choices even when runtime settings files are absent.+- **`start_web.py` reads `.env` for launch ports** - backend/frontend ports come+ from `.env` first, while UI language can still come from web settings.- **Cleaner process handling** - the launcher records started processes, detectsport conflicts, waits for readiness, and exposes `scripts/stop_web.py` forcleaning up recorded backend/frontend processes.@@ -69,9 +69,9 @@ servers no longer receive placeholder auth headers.## Upgrade Notes- Local web installs now require Node.js 20.9 or newer.-- `start_web.py` and setup helpers prefer `data/user/settings/env.json` and- `interface.json` over `.env`; edit the web Settings page or rerun- `start_tour.py` when changing launch ports.+- `start_web.py` and setup helpers read launch ports directly from `.env`;+ edit `BACKEND_PORT` / `FRONTEND_PORT` or rerun `start_tour.py` when changing+ launch ports.- Local OpenAI-compatible embedding servers should use an empty API key unless areal key is required. Avoid relying on `sk-no-key-required` as a transmittedcredential.diff --git a/assets/releases/ver1-3-6.md b/assets/releases/ver1-3-6.mdnew file mode 100644index 000000000..d8bede31a--- /dev/null+++ b/assets/releases/ver1-3-6.md@@ -0,0 +1,105 @@+# DeepTutor v1.3.6 Release Notes++**Release Date:** 2026.05.03++v1.3.6 focuses on making model routing explicit across DeepTutor. Users can+choose configured LLM profiles from chat and TutorBot flows, runtime services+resolve those choices without leaking provider secrets, and RAG/knowledge-base+index handling is more defensive when persisted embeddings are invalid.++## Highlights++### Catalog-Based Model Selection++- **Chat can target a configured model** - unified chat turns now carry a+ `profile_id` and `model_id` selection through the WebSocket payload, session+ preferences, turn snapshots, and regenerate flows.+- **Settings exposes safe LLM options** - the new settings options endpoint+ returns display-ready provider/model choices while omitting credentials and+ connection secrets from the response.+- **Runtime model overrides are scoped per turn** - selected profiles are+ resolved through the provider catalog for the active request without writing+ temporary choices back to disk or changing global defaults.+- **Model-selector UI is shared** - chat and TutorBot screens use the same+ configured-model selector, with localized labels and system-default handling.++### TutorBot Model Control++- **Bots can persist model selections** - TutorBot create/update flows now accept+ `llm_selection`, validate it against the configured catalog, and store it with+ each bot.+- **Running bots can reload their LLM** - changing a bot's model updates the+ active agent loop instead of requiring a full bot restart.+- **Recent bot history is steadier** - TutorBot history assembly now sorts by+ message timestamp with stable tie-breaking before taking the latest context.+- **Bot chat route changes are cleaner** - the web chat page cancels in-flight+ bot requests and resets transient reasoning state when switching bots.++### RAG and Knowledge Reliability++- **Invalid vectors trigger rebuilds** - re-indexing no longer treats a matching+ document signature as reusable when the existing vector store fails embedding+ validation.+- **Full rebuilds use fresh version directories** - complete knowledge-base+ rebuilds write to a new flat index version while leaving failed old storage+ available for inspection.+- **RAG tool logs can stream to clients** - retrieval runs can forward captured+ INFO-level process logs as raw tool events when an event sink is available.+- **Knowledge health checks recognize bad embeddings** - invalid persisted+ vectors are surfaced earlier instead of producing opaque search failures.++### Provider and Launch Fixes++- **OpenAI Responses token limits are normalized** - Responses API calls now map+ chat-style `max_completion_tokens` and `max_tokens` to `max_output_tokens`,+ fixing the SDK error reported for newer OpenAI models in #437.+- **Azure and OpenAI-compatible paths share the mapping** - both streaming and+ non-streaming Responses API routes use the same conversion helper.+- **Launch ports come from `.env` and environment variables** - setup and launch+ helpers now keep backend/frontend port behavior aligned around the project+ `.env` file instead of the older runtime settings JSON.++### Web UX Polish++- **Skill names validate before save** - the Skills editor slugifies names,+ flags invalid input inline, and prevents silent API failures for uppercase+ letters, spaces, underscores, or other unsupported characters.+- **Skill editor modals are opaque across themes** - the editor now uses the+ page background token, avoiding text bleed-through in translucent themes.+- **Space navigation is easier to scan** - Space mini-navigation, notebook,+ question-bank, skills, and session-list spacing were tightened with clearer+ card and divider treatment.++## Tests++- Added model-selection service tests for safe option listing, active markers,+ invalid profile/model rejection, and non-mutating catalog overrides.+- Added unified WebSocket turn-runtime tests for persisted LLM selections,+ invalid selections, model switching, snapshots, and regenerate behavior.+- Added TutorBot API and manager tests for `llm_selection` persistence,+ validation, runtime reload, and default-model behavior.+- Added settings, provider-runtime, and LLM-config tests for scoped catalog+ selection and per-turn config precedence.+- Added RAG and knowledge-router tests for invalid vector stores, re-index+ rebuild decisions, and storage version resolution.+- Added OpenAI Responses converter tests for token-limit aliases, precedence,+ `None` filtering, and input immutability.+- Added frontend slug tests for skill-name normalization and validation.++## Upgrade Notes++- Chat and TutorBot clients that want explicit model routing should send+ `llm_selection` as `{ "profile_id": "...", "model_id": "..." }`. Omitting it+ continues to use the configured system default.+- TutorBot configuration files may now contain `llm_selection`. Existing bot+ configs without that field continue to load, and legacy `model` values remain+ usable as model-name overrides.+- Launch ports should be configured in `.env` or process environment variables+ (`BACKEND_PORT` / `FRONTEND_PORT`). The old `data/user/settings/env.json`+ port block is no longer used as a launch-port source.+- Knowledge bases with stale or invalid persisted vectors may rebuild on the+ next re-index even when document signatures have not changed.+- Skill names are now normalized and validated as lowercase slugs of up to 64+ characters using letters, numbers, and hyphens.++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v1.3.5...v1.3.6diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 5500dccef..bdff13d40 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -294,6 +294,26 @@ def _assert_kb_writable_or_409(kb_name: str, kb_entry: dict) -> None:)+def _matching_index_is_valid(kb_name: str, matching_version: dict | None) -> bool:+ """Return whether a matching active index can safely satisfy retrieval."""+ if not matching_version:+ return False+ try:+ from deeptutor.services.rag.pipelines.llamaindex.storage import (+ validate_storage_embeddings,+ )++ validate_storage_embeddings(Path(str(matching_version["storage_path"])))+ return True+ except Exception as exc:+ logger.warning(+ "Matching index for KB '%s' is invalid; forcing re-index: %s",+ kb_name,+ exc,+ )+ return False++async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id: str):"""Background task for knowledge base initialization"""task_manager = TaskIDManager.get_instance()@@ -1114,7 +1134,13 @@ async def reindex_knowledge_base(kb_dir = _kb_base_dir / kb_namematching_version = find_matching_version(kb_dir, signature)- if matching_version and matching_version.get("layout") == "flat" and not force_reindex:+ matching_valid = _matching_index_is_valid(kb_name, matching_version)+ if (+ matching_version+ and matching_version.get("layout") == "flat"+ and matching_valid+ and not force_reindex+ ):return {"message": (f"Knowledge base '{kb_name}' already has an index for the "diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex dbc74e016..1b46e8433 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -20,6 +20,7 @@ from deeptutor.services.config import get_config_test_runner, get_model_catalog_from deeptutor.services.embedding.client import reset_embedding_clientfrom deeptutor.services.llm.client import reset_llm_clientfrom deeptutor.services.llm.config import clear_llm_config_cache+from deeptutor.services.model_selection import list_llm_optionsfrom deeptutor.services.path_service import get_path_servicerouter = APIRouter()@@ -156,6 +157,11 @@ async def get_catalog():return {"catalog": get_model_catalog_service().load()}[email protected]("/llm-options")+async def get_llm_options():+ return list_llm_options(get_model_catalog_service().load())++@router.put("/catalog")async def update_catalog(payload: CatalogPayload):catalog = get_model_catalog_service().save(payload.catalog)diff --git a/deeptutor/api/routers/tutorbot.py b/deeptutor/api/routers/tutorbot.pyindex af7cd8033..661f1e70b 100644--- a/deeptutor/api/routers/tutorbot.py+++ b/deeptutor/api/routers/tutorbot.py@@ -47,6 +47,7 @@ class CreateBotRequest(BaseModel):persona: str | None = Nonechannels: dict | None = Nonemodel: str | None = None+ llm_selection: dict[str, str] | None = Noneclass UpdateBotRequest(BaseModel):@@ -55,6 +56,7 @@ class UpdateBotRequest(BaseModel):persona: str | None = Nonechannels: dict | None = Nonemodel: str | None = None+ llm_selection: dict[str, str] | None = Noneclass FileUpdateRequest(BaseModel):@@ -168,6 +170,8 @@ async def create_and_start_bot(payload: CreateBotRequest):# fields fall back to the on-disk config — preventing the historical bug# where each restart wiped out user-configured channels.overrides = payload.model_dump(exclude_unset=True, exclude={"bot_id"})+ if "llm_selection" in overrides:+ overrides["llm_selection"] = _validate_llm_selection_payload(overrides["llm_selection"])config = mgr.merge_bot_config(payload.bot_id, overrides)try:instance = await mgr.start_bot(payload.bot_id, config)@@ -196,6 +200,7 @@ def _stopped_bot_dict("persona": cfg.persona,"channels": channels,"model": cfg.model,+ "llm_selection": cfg.llm_selection,"running": False,"started_at": None,"last_reload_error": None,@@ -265,9 +270,26 @@ def _validate_channels_payload(channels: dict) -> None:) from None+def _validate_llm_selection_payload(+ value: dict[str, str] | None,+) -> dict[str, str] | None:+ """Validate a bot model selection against the shared LLM catalog."""+ from deeptutor.services.config import get_model_catalog_service+ from deeptutor.services.model_selection import apply_llm_selection_to_catalog+ from deeptutor.services.tutorbot.model_runtime import normalize_tutorbot_llm_selection++ try:+ selection = normalize_tutorbot_llm_selection(value)+ if selection:+ apply_llm_selection_to_catalog(get_model_catalog_service().load(), selection)+ return selection+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from None++def _apply_payload(target: BotConfig | TutorBotInstance, payload: UpdateBotRequest) -> None:"""Apply non-None fields from ``payload`` onto a ``BotConfig`` (or instance.config)."""- cfg: BotConfig = target.config if isinstance(target, TutorBotInstance) else target+ cfg: BotConfig = getattr(target, "config", target)if payload.name is not None:cfg.name = payload.nameif payload.description is not None:@@ -278,14 +300,19 @@ def _apply_payload(target: BotConfig | TutorBotInstance, payload: UpdateBotRequecfg.channels = payload.channelsif payload.model is not None:cfg.model = payload.model+ if "llm_selection" in payload.model_fields_set:+ cfg.llm_selection = _validate_llm_selection_payload(payload.llm_selection)@router.patch("/{bot_id}")async def update_bot(bot_id: str, payload: UpdateBotRequest):if payload.channels is not None:_validate_channels_payload(payload.channels)+ if "llm_selection" in payload.model_fields_set:+ _validate_llm_selection_payload(payload.llm_selection)mgr = get_tutorbot_manager()+ llm_changed = bool({"llm_selection", "model"} & payload.model_fields_set)instance = mgr.get_bot(bot_id)if instance:_apply_payload(instance, payload)@@ -302,6 +329,20 @@ async def update_bot(bot_id: str, payload: UpdateBotRequest):f"({type(exc).__name__}); try stopping and starting the bot."),) from None+ if llm_changed:+ try:+ reload_llm = getattr(mgr, "reload_llm", None)+ if reload_llm is not None:+ await reload_llm(bot_id)+ except Exception as exc:+ logger.exception("reload_llm failed for bot '%s'", bot_id)+ raise HTTPException(+ status_code=500,+ detail=(+ "LLM config saved but failed to reload "+ f"({type(exc).__name__}); try stopping and starting the bot."+ ),+ ) from None# NOTE: response masks secrets — front-end should re-fetch with# ``?include_secrets=true`` if it needs the raw token to refill its form.return instance.to_dict(mask_secrets=True)diff --git a/deeptutor/book/kb_health.py b/deeptutor/book/kb_health.pyindex 6e5a80048..d6aac1e37 100644--- a/deeptutor/book/kb_health.py+++ b/deeptutor/book/kb_health.py@@ -19,7 +19,7 @@ import loggingfrom pathlib import Pathimport re-from deeptutor.knowledge import KnowledgeBaseManager+from deeptutor.knowledge.manager import KnowledgeBaseManagerfrom .models import Bookfrom .storage import BookStorage, get_book_storagediff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.pyindex 1dce55752..28810d9fc 100644--- a/deeptutor/services/config/__init__.py+++ b/deeptutor/services/config/__init__.py@@ -7,6 +7,7 @@ from .knowledge_base_config import (KnowledgeBaseConfigService,get_kb_config_service,)+from .launch_settings import LaunchSettings, load_launch_settingsfrom .loader import (DEFAULT_CHAT_PARAMS,PROJECT_ROOT,@@ -18,7 +19,6 @@ from .loader import (parse_language,resolve_config_path,)-from .launch_settings import LaunchSettings, load_launch_settingsfrom .model_catalog import ModelCatalogService, get_model_catalog_service# Re-export the loader module itself for code paths that monkeypatch via thediff --git a/deeptutor/services/config/launch_settings.py b/deeptutor/services/config/launch_settings.pyindex 8406e7069..d091c8fb3 100644--- a/deeptutor/services/config/launch_settings.py+++ b/deeptutor/services/config/launch_settings.py@@ -21,7 +21,6 @@ class LaunchSettings:language: strsource: strsettings_dir: Path- env_json_path: Pathinterface_json_path: Pathenv_path: Path@@ -60,55 +59,52 @@ def _normalize_language(value: Any) -> str | None:def load_launch_settings(project_root: Path | None = None) -> LaunchSettings:"""Load ports and UI language for launcher-style entry points.- Runtime settings under ``data/user/settings`` are preferred because they- reflect the web Settings flow. When that directory or the relevant files- are absent/empty/invalid, the project ``.env`` remains the compatibility- fallback used by older installs and manual setups.+ Launch ports come from the project ``.env`` so every entry point follows+ the same documented configuration path. Environment variables remain a+ compatibility fallback, then built-in defaults. UI language can still come+ from ``data/user/settings/interface.json`` because that file stores web UI+ preferences rather than launch/runtime provider configuration."""root = project_root or PROJECT_ROOTsettings_dir = root / "data" / "user" / "settings"- env_json_path = settings_dir / "env.json"interface_json_path = settings_dir / "interface.json"env_path = root / ".env"- settings_env = _load_json_object(env_json_path)interface_settings = _load_json_object(interface_json_path)env_store = EnvStore(env_path)env_values = env_store.load()- settings_ports = settings_env.get("ports") if isinstance(settings_env.get("ports"), dict) else {}- settings_backend_port = _coerce_port(settings_ports.get("backend"))- settings_frontend_port = _coerce_port(settings_ports.get("frontend"))+ env_backend_port = _coerce_port(env_values.get("BACKEND_PORT"))+ env_frontend_port = _coerce_port(env_values.get("FRONTEND_PORT"))+ process_backend_port = _coerce_port(os.getenv("BACKEND_PORT"))+ process_frontend_port = _coerce_port(os.getenv("FRONTEND_PORT"))interface_language = _normalize_language(interface_settings.get("language"))- backend_port = (- settings_backend_port- or _coerce_port(env_values.get("BACKEND_PORT"))- or _coerce_port(os.getenv("BACKEND_PORT"))- or DEFAULT_BACKEND_PORT- )- frontend_port = (- settings_frontend_port- or _coerce_port(env_values.get("FRONTEND_PORT"))- or _coerce_port(os.getenv("FRONTEND_PORT"))- or DEFAULT_FRONTEND_PORT- )- language = (- interface_language- or _normalize_language(env_values.get("UI_LANGUAGE"))+ env_language = (+ _normalize_language(env_values.get("UI_LANGUAGE"))or _normalize_language(env_values.get("LANGUAGE"))- or _normalize_language(os.getenv("UI_LANGUAGE"))+ )+ process_language = (+ _normalize_language(os.getenv("UI_LANGUAGE"))or _normalize_language(os.getenv("LANGUAGE"))- or DEFAULT_LANGUAGE)+ backend_port = env_backend_port or process_backend_port or DEFAULT_BACKEND_PORT+ frontend_port = env_frontend_port or process_frontend_port or DEFAULT_FRONTEND_PORT+ language = interface_language or env_language or process_language or DEFAULT_LANGUAGEsources: list[str] = []- if settings_backend_port is not None or settings_frontend_port is not None:- sources.append("data/user/settings/env.json")+ if env_backend_port is not None or env_frontend_port is not None or env_language is not None:+ sources.append(".env")+ elif (+ process_backend_port is not None+ or process_frontend_port is not None+ or process_language is not None+ ):+ sources.append("environment")+ else:+ sources.append("defaults")if interface_language is not None:sources.append("data/user/settings/interface.json")- if not sources:- sources.append(".env")return LaunchSettings(backend_port=backend_port,@@ -116,7 +112,6 @@ def load_launch_settings(project_root: Path | None = None) -> LaunchSettings:language=language,source=" + ".join(sources),settings_dir=settings_dir,- env_json_path=env_json_path,interface_json_path=interface_json_path,env_path=env_path,)diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex 39317f91f..8b6817b88 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -7,6 +7,7 @@ import jsonfrom typing import Anyfrom urllib.parse import urlparse+from deeptutor.services.model_selection import LLMSelection, apply_llm_selection_to_catalogfrom deeptutor.services.provider_registry import (NANOBOT_LLM_PROVIDERS,PROVIDERS,@@ -396,11 +397,13 @@ def resolve_llm_runtime_config(*,env_store: EnvStore | None = None,service: ModelCatalogService | None = None,+ llm_selection: dict[str, Any] | LLMSelection | None = None,) -> ResolvedLLMConfig:"""Resolve active LLM config with TutorBot-style provider matching."""env = env_store or get_env_store()catalog_service = service or get_model_catalog_service()loaded = _load_catalog(catalog)+ loaded = apply_llm_selection_to_catalog(loaded, llm_selection)profile, model = _active_profile_and_model(loaded, catalog_service, "llm")summary = env.as_summary()diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.pyindex ba833c16f..b0f5651e0 100644--- a/deeptutor/services/llm/config.py+++ b/deeptutor/services/llm/config.py@@ -8,6 +8,7 @@ Simplified version - loads from unified config service or falls back to .env.from __future__ import annotations+from contextvars import ContextVar, Tokenfrom dataclasses import dataclass, replaceimport loggingimport os@@ -126,6 +127,20 @@ class LLMConfig:_LLM_CONFIG_CACHE: LLMConfig | None = None+_SCOPED_LLM_CONFIG: ContextVar[LLMConfig | None] = ContextVar(+ "deeptutor_scoped_llm_config",+ default=None,+)+++def set_scoped_llm_config(config: LLMConfig | None) -> Token[LLMConfig | None]:+ """Set the LLM config for the current async context."""+ return _SCOPED_LLM_CONFIG.set(config)+++def reset_scoped_llm_config(token: Token[LLMConfig | None]) -> None:+ """Reset a scoped LLM config token returned by ``set_scoped_llm_config``."""+ _SCOPED_LLM_CONFIG.reset(token)def initialize_environment() -> None:@@ -225,6 +240,10 @@ def get_llm_config() -> LLMConfig:"""global _LLM_CONFIG_CACHE+ scoped = _SCOPED_LLM_CONFIG.get()+ if scoped is not None:+ return scoped+if _LLM_CONFIG_CACHE is not None:return _LLM_CONFIG_CACHEdiff --git a/deeptutor/services/llm/provider_core/openai_responses/converters.py b/deeptutor/services/llm/provider_core/openai_responses/converters.pyindex 32696b57d..2e2f0fb31 100644--- a/deeptutor/services/llm/provider_core/openai_responses/converters.py+++ b/deeptutor/services/llm/provider_core/openai_responses/converters.py@@ -2,9 +2,12 @@from __future__ import annotations+from collections.abc import Mappingimport jsonfrom typing import Any+_CHAT_TOKEN_LIMIT_ALIASES = ("max_completion_tokens", "max_tokens")+def convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]:"""Convert Chat Completions messages to Responses API input items."""@@ -110,28 +113,31 @@ def split_tool_call_id(tool_call_id: Any) -> tuple[str, str | None]:return "call_0", None-def adapt_chat_kwargs_to_responses(extra_kwargs: dict[str, Any]) -> dict[str, Any]:+def adapt_chat_kwargs_to_responses(extra_kwargs: Mapping[str, Any]) -> dict[str, Any]:"""Translate Chat Completions kwargs to Responses API equivalents.Callers building requests for the Chat Completions endpoint may pass- ``max_completion_tokens`` for newer OpenAI models (o1/o3/gpt-4o/gpt-5.x).- The Responses API does not accept that name and uses ``max_output_tokens``- instead, so the OpenAI SDK raises ``TypeError`` from ``responses.create``- before any HTTP request leaves the client. See DeepTutor#437.+ ``max_completion_tokens`` for newer OpenAI models (o1/o3/gpt-4o/gpt-5.x)+ or ``max_tokens`` for older chat models. The Responses API does not accept+ either name and uses ``max_output_tokens`` instead, so the OpenAI SDK raises+ ``TypeError`` from ``responses.create`` before any HTTP request leaves the+ client. See DeepTutor#437.Drops keys with ``None`` values to match the existing merge filter, andonly applies the alias when the caller did not already set the Responsesname explicitly."""- result: dict[str, Any] = {}- legacy_max_completion: int | None = None- for key, value in extra_kwargs.items():- if value is None:- continue- if key == "max_completion_tokens":- legacy_max_completion = value- continue- result[key] = value- if legacy_max_completion is not None and "max_output_tokens" not in result:- result["max_output_tokens"] = legacy_max_completion+ result = {+ key: value+ for key, value in extra_kwargs.items()+ if value is not None and key not in _CHAT_TOKEN_LIMIT_ALIASES+ }+ if "max_output_tokens" in result:+ return result++ for key in _CHAT_TOKEN_LIMIT_ALIASES:+ value = extra_kwargs.get(key)+ if value is not None:+ result["max_output_tokens"] = value+ breakreturn resultdiff --git a/deeptutor/services/model_selection/__init__.py b/deeptutor/services/model_selection/__init__.pynew file mode 100644index 000000000..caf1ef9d6--- /dev/null+++ b/deeptutor/services/model_selection/__init__.py@@ -0,0 +1,5 @@+"""Model selection services for request-scoped runtime switching."""++from .llm import LLMSelection, apply_llm_selection_to_catalog, list_llm_options++__all__ = ["LLMSelection", "apply_llm_selection_to_catalog", "list_llm_options"]diff --git a/deeptutor/services/model_selection/llm.py b/deeptutor/services/model_selection/llm.pynew file mode 100644index 000000000..1c280053f--- /dev/null+++ b/deeptutor/services/model_selection/llm.py@@ -0,0 +1,131 @@+"""Helpers for selecting configured LLM models without mutating settings."""++from __future__ import annotations++from copy import deepcopy+from dataclasses import dataclass+from typing import Any+++@dataclass(frozen=True, slots=True)+class LLMSelection:+ """A safe reference to one configured LLM model.++ The selection intentionally carries IDs only. Provider secrets stay in the+ server-side catalog and are resolved only at runtime.+ """++ profile_id: str+ model_id: str++ @classmethod+ def from_payload(cls, value: Any) -> "LLMSelection | None":+ if isinstance(value, LLMSelection):+ return value+ if value is None:+ return None+ if not isinstance(value, dict):+ raise ValueError("Invalid LLM selection: expected an object.")++ profile_id = str(value.get("profile_id") or "").strip()+ model_id = str(value.get("model_id") or "").strip()+ if not profile_id and not model_id:+ return None+ if not profile_id or not model_id:+ raise ValueError("Invalid LLM selection: profile_id and model_id are required.")+ return cls(profile_id=profile_id, model_id=model_id)++ def to_dict(self) -> dict[str, str]:+ return {"profile_id": self.profile_id, "model_id": self.model_id}+++def _coerce_int(value: Any) -> int | None:+ try:+ parsed = int(str(value).strip())+ except (TypeError, ValueError):+ return None+ return parsed if parsed > 0 else None+++def _llm_service(catalog: dict[str, Any]) -> dict[str, Any]:+ if not isinstance(catalog, dict):+ return {}+ services = catalog.get("services")+ return services.get("llm", {}) if isinstance(services, dict) else {}+++def list_llm_options(catalog: dict[str, Any]) -> dict[str, Any]:+ """Return a redacted list of configured chat-selectable LLM models."""+ service = _llm_service(catalog)+ active_profile_id = str(service.get("active_profile_id") or "")+ active_model_id = str(service.get("active_model_id") or "")++ options: list[dict[str, Any]] = []+ for profile in service.get("profiles", []) or []:+ if not isinstance(profile, dict):+ continue+ profile_id = str(profile.get("id") or "").strip()+ if not profile_id:+ continue+ provider = str(profile.get("binding") or "").strip()+ profile_name = str(profile.get("name") or provider or "LLM").strip()++ for model in profile.get("models", []) or []:+ if not isinstance(model, dict):+ continue+ model_id = str(model.get("id") or "").strip()+ model_value = str(model.get("model") or "").strip()+ if not model_id or not model_value:+ continue++ option: dict[str, Any] = {+ "profile_id": profile_id,+ "model_id": model_id,+ "profile_name": profile_name,+ "model_name": str(model.get("name") or model_value).strip(),+ "model": model_value,+ "provider": provider,+ "is_active_default": (+ profile_id == active_profile_id and model_id == active_model_id+ ),+ }+ context_window = _coerce_int(model.get("context_window"))+ if context_window is None:+ context_window = _coerce_int(model.get("context_window_tokens"))+ if context_window is not None:+ option["context_window"] = context_window+ options.append(option)++ return {+ "active": {"profile_id": active_profile_id, "model_id": active_model_id}+ if active_profile_id and active_model_id+ else None,+ "options": options,+ }+++def apply_llm_selection_to_catalog(+ catalog: dict[str, Any],+ selection: LLMSelection | dict[str, Any] | None,+) -> dict[str, Any]:+ """Return a catalog copy whose active LLM points at *selection*."""+ resolved = LLMSelection.from_payload(selection)+ selected = deepcopy(catalog)+ if resolved is None:+ return selected++ service = _llm_service(selected)+ for profile in service.get("profiles", []) or []:+ if not isinstance(profile, dict) or profile.get("id") != resolved.profile_id:+ continue+ for model in profile.get("models", []) or []:+ if isinstance(model, dict) and model.get("id") == resolved.model_id:+ service["active_profile_id"] = resolved.profile_id+ service["active_model_id"] = resolved.model_id+ return selected+ break++ raise ValueError("Invalid LLM selection: selected profile/model was not found.")+++__all__ = ["LLMSelection", "apply_llm_selection_to_catalog", "list_llm_options"]diff --git a/deeptutor/services/model_selection/runtime.py b/deeptutor/services/model_selection/runtime.pynew file mode 100644index 000000000..b6d34bcd1--- /dev/null+++ b/deeptutor/services/model_selection/runtime.py@@ -0,0 +1,54 @@+"""Runtime helpers for request-scoped model selection."""++from __future__ import annotations++from contextvars import Token+from typing import Any++from deeptutor.services.config.provider_runtime import ResolvedLLMConfig, resolve_llm_runtime_config+from deeptutor.services.llm import config as llm_config_module+from deeptutor.services.llm.config import LLMConfig+++def llm_config_from_resolved(resolved: ResolvedLLMConfig) -> LLMConfig:+ """Convert provider-runtime output into the LLM service config shape."""+ return LLMConfig(+ model=resolved.model,+ api_key=resolved.api_key,+ base_url=resolved.base_url,+ effective_url=resolved.effective_url,+ binding=resolved.binding,+ provider_name=resolved.provider_name,+ provider_mode=resolved.provider_mode,+ api_version=resolved.api_version,+ extra_headers=resolved.extra_headers,+ reasoning_effort=resolved.reasoning_effort,+ context_window=resolved.context_window,+ )+++def resolve_llm_config_for_selection(selection: Any) -> LLMConfig:+ """Resolve the LLM config for a chat/session selection reference."""+ if selection is None:+ return llm_config_module.get_llm_config()+ return llm_config_from_resolved(resolve_llm_runtime_config(llm_selection=selection))+++def activate_llm_selection(selection: Any) -> tuple[LLMConfig, Token[LLMConfig | None]]:+ """Resolve and install a scoped LLM config for the current async context."""+ config = resolve_llm_config_for_selection(selection)+ token = llm_config_module.set_scoped_llm_config(config)+ return config, token+++def reset_llm_selection(token: Token[LLMConfig | None] | None) -> None:+ if token is not None:+ llm_config_module.reset_scoped_llm_config(token)+++__all__ = [+ "activate_llm_selection",+ "llm_config_from_resolved",+ "reset_llm_selection",+ "resolve_llm_config_for_selection",+]diff --git a/deeptutor/services/rag/index_versioning.py b/deeptutor/services/rag/index_versioning.pyindex 0e47562ef..0de6763d6 100644--- a/deeptutor/services/rag/index_versioning.py+++ b/deeptutor/services/rag/index_versioning.py@@ -310,3 +310,17 @@ def resolve_storage_dir_for_write(kb_dir: Path, signature: Optional[EmbeddingSigtarget = Path(str(entry["storage_path"])) if entry else _next_flat_version_dir(kb_dir)target.mkdir(parents=True, exist_ok=True)return target+++def resolve_storage_dir_for_rebuild(kb_dir: Path, signature: Optional[EmbeddingSignature]) -> Path:+ """Return a fresh flat storage dir for a full index rebuild.++ Incremental writes reuse a matching flat version, but a full rebuild should+ not overwrite the last matching version until the new index has been+ persisted successfully. Keeping the old version in place lets a failed+ rebuild remain diagnosable and avoids stale vector-store files.+ """+ _ = signature+ target = _next_flat_version_dir(kb_dir)+ target.mkdir(parents=True, exist_ok=True)+ return targetdiff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.pyindex 15045216a..d96183efa 100644--- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py+++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py@@ -14,7 +14,7 @@ from deeptutor.services.rag.embedding_signature import signature_from_embedding_from deeptutor.services.rag.index_versioning import (EmbeddingSignature,resolve_storage_dir_for_read,- resolve_storage_dir_for_write,+ resolve_storage_dir_for_rebuild,write_version_meta,)@@ -81,7 +81,7 @@ class LlamaIndexPipeline:kb_dir = Path(self.kb_base_dir) / kb_namesignature = self._current_signature()- storage_dir = resolve_storage_dir_for_write(kb_dir, signature)+ storage_dir = resolve_storage_dir_for_rebuild(kb_dir, signature)try:await self._verify_embedding_connectivity()diff --git a/deeptutor/services/rag/pipelines/llamaindex/storage.py b/deeptutor/services/rag/pipelines/llamaindex/storage.pyindex ad28ed783..a82251712 100644--- a/deeptutor/services/rag/pipelines/llamaindex/storage.py+++ b/deeptutor/services/rag/pipelines/llamaindex/storage.py@@ -157,6 +157,11 @@ def _validate_persisted_embeddings(index: Any, storage_dir: Path | None = None)) from exc+def validate_storage_embeddings(storage_dir: Path) -> None:+ """Validate persisted vector-store files without running a retrieval."""+ _validate_persisted_embeddings(None, storage_dir)++def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any]:storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))index = load_index_from_storage(storage_context)diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.pyindex bcc9f20aa..f2b518d7f 100644--- a/deeptutor/services/rag/service.py+++ b/deeptutor/services/rag/service.py@@ -125,7 +125,26 @@ class RAGService:def _capture_raw_logs(self, event_sink):from contextlib import nullcontext- return nullcontext()+ if event_sink is None:+ return nullcontext()++ from deeptutor.logging import capture_process_logs++ def emit(event):+ return self._emit_tool_event(+ event_sink,+ "raw_log",+ event.message,+ {+ "level": event.level,+ "logger": event.logger,+ "timestamp": event.timestamp,+ "trace_layer": "raw",+ **event.context,+ },+ )++ return capture_process_logs(emit, min_level=logging.INFO)async def delete(self, kb_name: str) -> bool:self.logger.info(f"Deleting KB '{kb_name}'")diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 40c51c106..b0473f0f2 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -5,17 +5,21 @@ Turn-level runtime manager for unified chat streaming.from __future__ import annotationsimport asyncio-from collections.abc import AsyncIterator, Sequence+from collections.abc import AsyncIterator, Callable, Sequenceimport contextlib+from contextvars import Tokenfrom dataclasses import dataclass, fieldimport jsonimport logging-from typing import Any, Literal+from typing import TYPE_CHECKING, Any, Literalfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.services.path_service import get_path_servicefrom deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store+if TYPE_CHECKING:+ from deeptutor.services.llm.config import LLMConfig+logger = logging.getLogger(__name__)MemoryReference = Literal["summary", "profile"]@@ -57,6 +61,13 @@ def _string_list(value: Any) -> list[str]:return [item for item in value if isinstance(item, str) and item]+def _llm_selection_dict(value: Any) -> dict[str, str] | None:+ from deeptutor.services.model_selection import LLMSelection++ selection = LLMSelection.from_payload(value)+ return selection.to_dict() if selection else None++def _request_snapshot_metadata(*,payload: dict[str, Any],@@ -70,6 +81,7 @@ def _request_snapshot_metadata(book_references: list[Any],requested_skills: list[str],memory_references: Sequence[str],+ llm_selection: dict[str, str] | None,) -> dict[str, Any]:"""Persist the front-end context chips with the user message."""snapshot: dict[str, Any] = {@@ -95,6 +107,8 @@ def _request_snapshot_metadata(snapshot["skills"] = requested_skillsif memory_references:snapshot["memoryReferences"] = memory_references+ if llm_selection:+ snapshot["llmSelection"] = llm_selectionreturn {"request_snapshot": snapshot}@@ -366,15 +380,38 @@ class TurnRuntimeManager:"config": {**validated_public_config, **runtime_only_config},}session = await self.store.ensure_session(payload.get("session_id"))- await self.store.update_session_preferences(- session["id"],- {- "capability": capability,- "tools": list(payload.get("tools") or []),- "knowledge_bases": list(payload.get("knowledge_bases") or []),- "language": str(payload.get("language") or "en"),- },- )+ preferences = session.get("preferences") or {}+ raw_llm_selection = payload.get("llm_selection")+ if raw_llm_selection is None:+ raw_llm_selection = preferences.get("llm_selection")+ try:+ llm_selection = _llm_selection_dict(raw_llm_selection)+ except ValueError as exc:+ raise RuntimeError(str(exc)) from exc+ if llm_selection:+ from deeptutor.services.config import get_model_catalog_service+ from deeptutor.services.model_selection import (+ LLMSelection,+ apply_llm_selection_to_catalog,+ )++ try:+ apply_llm_selection_to_catalog(+ get_model_catalog_service().load(),+ LLMSelection.from_payload(llm_selection),+ )+ except ValueError as exc:+ raise RuntimeError(str(exc)) from exc+ payload = {**payload, "llm_selection": llm_selection}+ preference_update: dict[str, Any] = {+ "capability": capability,+ "tools": list(payload.get("tools") or []),+ "knowledge_bases": list(payload.get("knowledge_bases") or []),+ "language": str(payload.get("language") or "en"),+ }+ if llm_selection:+ preference_update["llm_selection"] = llm_selection+ await self.store.update_session_preferences(session["id"], preference_update)turn = await self.store.create_turn(session["id"], capability=capability)execution = _TurnExecution(turn_id=turn["id"],@@ -482,6 +519,11 @@ class TurnRuntimeManager:)if previous_turn_id:config["_superseded_turn_id"] = previous_turn_id+ llm_selection = (+ overrides.get("llm_selection")+ if overrides.get("llm_selection") is not None+ else snapshot.get("llmSelection") or preferences.get("llm_selection")+ )payload: dict[str, Any] = {"session_id": session_id,@@ -508,6 +550,8 @@ class TurnRuntimeManager:),"config": config,}+ if llm_selection:+ payload["llm_selection"] = llm_selectionreturn await self.start_turn(payload)async def cancel_turn(self, turn_id: str) -> bool:@@ -594,14 +638,21 @@ class TurnRuntimeManager:attachment_records = []assistant_events: list[dict[str, Any]] = []assistant_content = ""+ llm_scope_token: Token[LLMConfig | None] | None = None+ reset_active_llm_selection: Callable[[Token[LLMConfig | None] | None], None] | None = Nonetry:from deeptutor.agents.notebook import NotebookAnalysisAgentfrom deeptutor.book.context import build_book_contextfrom deeptutor.core.context import Attachment, UnifiedContextfrom deeptutor.runtime.orchestrator import ChatOrchestrator- from deeptutor.services.llm.config import get_llm_configfrom deeptutor.services.memory import get_memory_service+ from deeptutor.services.model_selection.runtime import (+ activate_llm_selection,+ )+ from deeptutor.services.model_selection.runtime import (+ reset_llm_selection as reset_active_llm_selection,+ )from deeptutor.services.notebook import notebook_managerfrom deeptutor.services.session.context_builder import ContextBuilderfrom deeptutor.services.skill import get_skill_service@@ -716,7 +767,7 @@ class TurnRuntimeManager:capability=capability_name or "chat",)- llm_config = get_llm_config()+ llm_config, llm_scope_token = activate_llm_selection(payload.get("llm_selection"))builder = ContextBuilder(self.store)async def _emit_context_event(event: StreamEvent) -> None:@@ -873,6 +924,7 @@ class TurnRuntimeManager:book_references=book_references,requested_skills=requested_skills,memory_references=memory_references,+ llm_selection=payload.get("llm_selection"),),)@@ -907,6 +959,9 @@ class TurnRuntimeManager:"question_bank_context": question_bank_context,"memory_context": memory_context,"active_skills": resolved_skills,+ "llm_selection": payload.get("llm_selection") or {},+ "llm_model": str(getattr(llm_config, "model", "") or ""),+ "llm_provider": str(getattr(llm_config, "provider_name", "") or ""),},)@@ -980,6 +1035,8 @@ class TurnRuntimeManager:),)finally:+ if llm_scope_token is not None and reset_active_llm_selection is not None:+ reset_active_llm_selection(llm_scope_token)async with self._lock:current = self._executions.get(turn_id)if current is not None:diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.pyindex fe58af5da..86b01a6c6 100644--- a/deeptutor/services/setup/init.py+++ b/deeptutor/services/setup/init.py@@ -209,7 +209,7 @@ def _write_yaml_if_missing(file_path: Path, payload: dict) -> None:# ============================================================================# Port Configuration Management# ============================================================================-# Ports are configured via environment variables in .env file:+# Ports are configured via environment variables in the project .env file:# BACKEND_PORT=8001 (default: 8001)# FRONTEND_PORT=3782 (default: 3782)# ============================================================================@@ -217,10 +217,10 @@ def _write_yaml_if_missing(file_path: Path, payload: dict) -> None:def get_backend_port(project_root: Path | None = None) -> int:"""- Get backend port from runtime settings, falling back to environment.+ Get backend port from .env, falling back to environment/defaults.- Preferred source: data/user/settings/env.json -> ports.backend- Fallback source: .env -> BACKEND_PORT+ Preferred source: .env -> BACKEND_PORT+ Fallback source: process environment -> BACKEND_PORTReturns:Backend port number (default: 8001)@@ -244,10 +244,10 @@ def get_backend_port(project_root: Path | None = None) -> int:def get_frontend_port(project_root: Path | None = None) -> int:"""- Get frontend port from runtime settings, falling back to environment.+ Get frontend port from .env, falling back to environment/defaults.- Preferred source: data/user/settings/env.json -> ports.frontend- Fallback source: .env -> FRONTEND_PORT+ Preferred source: .env -> FRONTEND_PORT+ Fallback source: process environment -> FRONTEND_PORTReturns:Frontend port number (default: 3782)diff --git a/deeptutor/services/tutorbot/manager.py b/deeptutor/services/tutorbot/manager.pyindex 9387aed89..30a26591e 100644--- a/deeptutor/services/tutorbot/manager.py+++ b/deeptutor/services/tutorbot/manager.py@@ -104,6 +104,17 @@ def normalize_message_content(content: Any) -> str:return str(content)+def _history_sort_timestamp(message: dict[str, Any], fallback: float) -> float:+ """Return a numeric timestamp for stable cross-session history ordering."""+ raw = message.get("timestamp")+ if isinstance(raw, str) and raw:+ try:+ return datetime.fromisoformat(raw.replace("Z", "+00:00")).timestamp()+ except ValueError:+ pass+ return fallback++@dataclassclass BotConfig:"""Configuration for a single TutorBot instance."""@@ -113,6 +124,7 @@ class BotConfig:persona: str = ""channels: dict[str, Any] = field(default_factory=dict)model: str | None = None+ llm_selection: dict[str, str] | None = None@dataclass@@ -169,6 +181,7 @@ class TutorBotInstance:"persona": self.config.persona,"channels": channels,"model": self.config.model,+ "llm_selection": self.config.llm_selection,"running": self.running,"started_at": self.started_at.isoformat(),"last_reload_error": self.last_reload_error,@@ -291,7 +304,14 @@ class TutorBotManager:# ── Config persistence ────────────────────────────────────────# Field names from BotConfig that are persisted via merge.- _MERGEABLE_FIELDS = ("name", "description", "persona", "channels", "model")+ _MERGEABLE_FIELDS = (+ "name",+ "description",+ "persona",+ "channels",+ "model",+ "llm_selection",+ )def load_bot_config(self, bot_id: str) -> BotConfig | None:"""Read the on-disk ``config.yaml`` for a bot, or ``None`` if missing."""@@ -306,6 +326,7 @@ class TutorBotManager:persona=data.get("persona", ""),channels=data.get("channels", {}),model=data.get("model"),+ llm_selection=data.get("llm_selection"),)except Exception:logger.exception("Failed to load bot config %s", bot_id)@@ -329,6 +350,8 @@ class TutorBotManager:}if config.model:data["model"] = config.model+ if config.llm_selection:+ data["llm_selection"] = config.llm_selectiontmp_path = path.with_suffix(path.suffix + ".tmp")tmp_path.write_text(yaml.dump(data, allow_unicode=True), encoding="utf-8")@@ -378,13 +401,17 @@ class TutorBotManager:config = BotConfig(name=bot_id)self.save_bot_config(bot_id, config)+ from deeptutor.services.tutorbot.model_runtime import (+ resolve_tutorbot_llm_config,+ )from deeptutor.tutorbot.agent.loop import AgentLoopfrom deeptutor.tutorbot.bus.queue import MessageBusfrom deeptutor.tutorbot.config.schema import ExecToolConfigfrom deeptutor.tutorbot.providers.deeptutor_adapter import create_deeptutor_providerfrom deeptutor.tutorbot.session.manager import SessionManager- provider = create_deeptutor_provider()+ llm_config = resolve_tutorbot_llm_config(config)+ provider = create_deeptutor_provider(llm_config)bus = MessageBus()workspace = self._bot_workspace(bot_id)@@ -403,7 +430,8 @@ class TutorBotManager:bus=bus,provider=provider,workspace=workspace,- model=config.model,+ model=llm_config.model,+ context_window_tokens=llm_config.context_window or 65_536,exec_config=exec_config,session_manager=session_adapter,shared_memory_dir=self._shared_memory_dir,@@ -475,6 +503,32 @@ class TutorBotManager:logger.info("TutorBot '%s' started (workspace=%s)", bot_id, workspace)return instance+ async def reload_llm(self, bot_id: str) -> None:+ """Apply the bot's current LLM config to an already-running instance."""+ instance = self._bots.get(bot_id)+ if not instance or not instance.running or not instance.agent_loop:+ return++ from deeptutor.services.tutorbot.model_runtime import (+ resolve_tutorbot_llm_config,+ )+ from deeptutor.tutorbot.providers.deeptutor_adapter import create_deeptutor_provider++ llm_config = resolve_tutorbot_llm_config(instance.config)+ provider = create_deeptutor_provider(llm_config)+ context_window_tokens = (+ llm_config.context_window or instance.agent_loop.context_window_tokens+ )+ instance.agent_loop.update_llm(+ provider=provider,+ model=llm_config.model,+ context_window_tokens=context_window_tokens,+ )+ if instance.heartbeat:+ instance.heartbeat.provider = provider+ instance.heartbeat.model = instance.agent_loop.model+ logger.info("Reloaded LLM for TutorBot '%s' (model=%s)", bot_id, llm_config.model)+async def _outbound_router(self, bot_id: str, bus: Any, instance: TutorBotInstance) -> None:"""Route outbound messages to channels, web notify_queue, and EventBus.@@ -720,6 +774,7 @@ class TutorBotManager:"persona": cfg.persona if cfg else "","channels": list(cfg.channels.keys()) if cfg else [],"model": cfg.model if cfg else None,+ "llm_selection": cfg.llm_selection if cfg else None,"running": False,"started_at": None,}@@ -735,10 +790,10 @@ class TutorBotManager:if not sessions_dir.exists():return []- all_messages: list[dict[str, Any]] = []- for path in sorted(- sessions_dir.glob("*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True- ):+ indexed_messages: list[tuple[float, int, dict[str, Any]]] = []+ sequence = 0+ for path in sorted(sessions_dir.glob("*.jsonl"), key=lambda p: p.stat().st_mtime):+ file_mtime = path.stat().st_mtimetry:with open(path, encoding="utf-8") as f:for line in f:@@ -751,13 +806,20 @@ class TutorBotManager:if data.get("role") in ("user", "assistant") and data.get("content"):data["content"] = normalize_message_content(data["content"])data.pop("reasoning_content", None)- all_messages.append(data)+ indexed_messages.append(+ (+ _history_sort_timestamp(data, file_mtime),+ sequence,+ data,+ )+ )+ sequence += 1except Exception:continue- if len(all_messages) >= limit:- break- return all_messages[-limit:]+ indexed_messages.sort(key=lambda item: (item[0], item[1]))+ messages = [item[2] for item in indexed_messages]+ return messages[-limit:]def get_recent_active_bots(self, limit: int = 3) -> list[dict[str, Any]]:"""Return the most recently active bots with their last message preview."""@@ -879,6 +941,7 @@ class TutorBotManager:persona=data.get("persona", ""),channels=data.get("channels", {}),model=data.get("model"),+ llm_selection=data.get("llm_selection"),)await self.start_bot(bid, config)logger.info("Auto-started bot '%s'", bid)diff --git a/deeptutor/services/tutorbot/model_runtime.py b/deeptutor/services/tutorbot/model_runtime.pynew file mode 100644index 000000000..27bac9b6c--- /dev/null+++ b/deeptutor/services/tutorbot/model_runtime.py@@ -0,0 +1,38 @@+"""TutorBot helpers for resolving per-bot LLM model selection."""++from __future__ import annotations++from typing import Any++from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.model_selection import LLMSelection+from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection+++def normalize_tutorbot_llm_selection(value: Any) -> dict[str, str] | None:+ """Return a validated selection dict, or ``None`` for system default."""+ selection = LLMSelection.from_payload(value)+ return selection.to_dict() if selection else None+++def resolve_tutorbot_llm_config(bot_config: Any) -> LLMConfig:+ """Resolve the effective LLM config for a TutorBot config object.++ New configs store ``llm_selection`` as a stable catalog reference. Legacy+ configs may still contain a raw ``model`` string, which is applied as a+ model-only override on top of the current system default provider.+ """+ selection = normalize_tutorbot_llm_selection(+ getattr(bot_config, "llm_selection", None)+ )+ if selection:+ return resolve_llm_config_for_selection(selection)++ base = resolve_llm_config_for_selection(None)+ legacy_model = str(getattr(bot_config, "model", "") or "").strip()+ if legacy_model:+ return base.model_copy(update={"model": legacy_model})+ return base+++__all__ = ["normalize_tutorbot_llm_selection", "resolve_tutorbot_llm_config"]diff --git a/deeptutor/tutorbot/agent/loop.py b/deeptutor/tutorbot/agent/loop.pyindex 9d852bb8f..d05d54899 100644--- a/deeptutor/tutorbot/agent/loop.py+++ b/deeptutor/tutorbot/agent/loop.py@@ -134,6 +134,33 @@ class AgentLoop:)self._register_default_tools()+ def update_llm(+ self,+ *,+ provider: LLMProvider,+ model: str | None = None,+ context_window_tokens: int | None = None,+ ) -> None:+ """Swap the provider/model used by future TutorBot turns."""+ self.provider = provider+ self.model = model or provider.get_default_model()+ if context_window_tokens:+ self.context_window_tokens = context_window_tokens++ self.subagents.provider = provider+ self.subagents.model = self.model++ self.team.provider = provider+ self.team.model = self.model+ self.team.temperature = provider.generation.temperature+ self.team.max_tokens = provider.generation.max_tokens+ self.team.reasoning_effort = provider.generation.reasoning_effort++ self.memory_consolidator.provider = provider+ self.memory_consolidator.model = self.model+ if context_window_tokens:+ self.memory_consolidator.context_window_tokens = context_window_tokens+def _register_default_tools(self) -> None:"""Register the default set of tools."""self.tools = build_base_tools(diff --git a/deeptutor/tutorbot/providers/deeptutor_adapter.py b/deeptutor/tutorbot/providers/deeptutor_adapter.pyindex 936a0c923..0bacedb96 100644--- a/deeptutor/tutorbot/providers/deeptutor_adapter.py+++ b/deeptutor/tutorbot/providers/deeptutor_adapter.py@@ -9,11 +9,12 @@ from __future__ import annotationsfrom typing import cast+from deeptutor.services.llm.config import LLMConfigfrom deeptutor.tutorbot.providers.base import LLMProvider-def create_deeptutor_provider() -> LLMProvider:+def create_deeptutor_provider(config: LLMConfig | None = None) -> LLMProvider:"""Build a provider pre-configured from DeepTutor's LLMConfig."""from deeptutor.services.llm.provider_factory import get_runtime_provider- return cast(LLMProvider, get_runtime_provider())+ return cast(LLMProvider, get_runtime_provider(config))diff --git a/scripts/start_tour.py b/scripts/start_tour.pyindex f528d9a27..e41dd2ef1 100644--- a/scripts/start_tour.py+++ b/scripts/start_tour.py@@ -24,7 +24,6 @@ configure_text_streams()ENV_PATH = PROJECT_ROOT / ".env"ENV_EXAMPLE_PATH = PROJECT_ROOT / ".env.example"INTERFACE_SETTINGS_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "interface.json"-ENV_SETTINGS_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "env.json"LEGACY_TOUR_CACHE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / ".tour_cache.json"@@ -592,35 +591,6 @@ def _save_ui_language(language: str, path: Path = INTERFACE_SETTINGS_PATH) -> Nopath.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")-def _save_launch_ports(values: dict[str, str], path: Path = ENV_SETTINGS_PATH) -> None:- """Keep launcher ports in runtime settings without rewriting provider data."""- backend = values.get("BACKEND_PORT")- frontend = values.get("FRONTEND_PORT")- if backend is None and frontend is None:- return-- payload: dict[str, Any] = {}- if path.exists() and path.stat().st_size > 0:- try:- loaded = json.loads(path.read_text(encoding="utf-8"))- if isinstance(loaded, dict):- payload = loaded- except Exception:- payload = {}-- payload.setdefault("version", 1)- ports = payload.get("ports")- if not isinstance(ports, dict):- ports = {}- if backend is not None:- ports["backend"] = int(backend)- if frontend is not None:- ports["frontend"] = int(frontend)- payload["ports"] = ports- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")--def _ensure_env_file(env_path: Path = ENV_PATH, template_path: Path = ENV_EXAMPLE_PATH) -> bool:if env_path.exists():return False@@ -1305,7 +1275,6 @@ def _print_review(values: dict[str, str]) -> None:def _write_env(values: dict[str, str]) -> None:get_env_store().write(values)- _save_launch_ports(values)def _tour_banner() -> None:diff --git a/scripts/start_web.py b/scripts/start_web.pyindex d76b17ac2..d68603a35 100644--- a/scripts/start_web.py+++ b/scripts/start_web.py@@ -278,7 +278,9 @@ def _state_process_records(state: dict[str, Any]) -> list[tuple[int | None, intcontinuepid = raw.get("pid")pgid = raw.get("pgid")- records.append((pid if isinstance(pid, int) else None, pgid if isinstance(pgid, int) else None))+ records.append(+ (pid if isinstance(pid, int) else None, pgid if isinstance(pgid, int) else None)+ )return records@@ -454,9 +456,7 @@ def _wait_for_http(if should_stop is not None and should_stop():raise SystemExit(0)if process.process.poll() is not None:- log_error(- _t(language, "process_exited", name=name, code=process.process.returncode)- )+ log_error(_t(language, "process_exited", name=name, code=process.process.returncode))raise SystemExit(1)try:with urlrequest.urlopen(url, timeout=1):@@ -606,7 +606,12 @@ def main() -> None:while not shutdown_requested:if backend.process.poll() is not None:log_error(- _t(language, "process_exited", name=backend.name, code=backend.process.returncode)+ _t(+ language,+ "process_exited",+ name=backend.name,+ code=backend.process.returncode,+ ))exit_code = 1breakdiff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex eeb27cf63..7f9b41a9e 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -1,6 +1,7 @@from __future__ import annotationsimport importlib+import jsonfrom pathlib import Pathimport pytest@@ -393,6 +394,54 @@ def test_reindex_error_status_bypasses_existing_match_noop(monkeypatch, tmp_pathassert manager.config["knowledge_bases"]["failed-kb"]["status"] == "initializing"+def test_reindex_bypasses_existing_match_when_vectors_are_invalid(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.config["knowledge_bases"]["bad-index-kb"] = {+ "path": "bad-index-kb",+ "status": "ready",+ }+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)++ class _Signature:+ def hash(self) -> str:+ return "sig"++ kb_dir = manager.base_dir / "bad-index-kb"+ version_dir = kb_dir / "version-1"+ version_dir.mkdir(parents=True)+ (version_dir / "docstore.json").write_text("{}", encoding="utf-8")+ (version_dir / "meta.json").write_text(+ json.dumps({"signature": "sig", "version": "version-1"}),+ encoding="utf-8",+ )+ (version_dir / "default__vector_store.json").write_text(+ json.dumps({"embedding_dict": {"bad-node": [0.1, None, 0.3]}}),+ encoding="utf-8",+ )++ embedding_signature = importlib.import_module("deeptutor.services.rag.embedding_signature")+ monkeypatch.setattr(+ embedding_signature, "signature_from_embedding_config", lambda: _Signature()+ )++ async def _noop_reindex_task(*_args, **_kwargs):+ return None++ monkeypatch.setattr(knowledge_router_module, "run_reindex_task", _noop_reindex_task)++ with TestClient(_build_app()) as client:+ response = client.post("/api/v1/knowledge/bad-index-kb/reindex")++ assert response.status_code == 200+ body = response.json()+ assert body["noop"] is False+ assert isinstance(body.get("task_id"), str) and body["task_id"]+ assert manager.config["knowledge_bases"]["bad-index-kb"]["status"] == "initializing"++def test_update_config_coerces_legacy_provider_to_llamaindex() -> None:"""Legacy `rag_provider` values are accepted and normalized to llamaindex."""diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex 89daace5f..02e3ec308 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -188,6 +188,30 @@ def test_embedding_provider_choices_use_full_endpoint_urls() -> None:assert "custom_openai_sdk" not in embedding+async def test_get_llm_options_returns_redacted_catalog(monkeypatch: pytest.MonkeyPatch) -> None:+ catalog = _build_catalog(+ llm_model="gpt-4o-mini",+ llm_base_url="https://llm.example/v1",+ llm_api_key="secret-key",+ embedding_model="text-embedding-3-small",+ embedding_base_url="https://emb.example/v1/embeddings",+ embedding_api_key="emb-key",+ )+ service = _FakeCatalogService(catalog)+ monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)++ response = await settings_router.get_llm_options()++ assert response["active"] == {+ "profile_id": "llm-profile-default",+ "model_id": "llm-model-default",+ }+ assert response["options"][0]["model"] == "gpt-4o-mini"+ assert "api_key" not in response["options"][0]+ assert "base_url" not in response["options"][0]++@pytest.fixture(autouse=True)def _reset_runtime_state() -> None:llm_config_module.clear_llm_config_cache()diff --git a/tests/api/test_tutorbot_router.py b/tests/api/test_tutorbot_router.pyindex 5ce13a9a0..fd1d8f40a 100644--- a/tests/api/test_tutorbot_router.py+++ b/tests/api/test_tutorbot_router.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport importlib+from types import SimpleNamespacefrom typing import Anyfrom unittest.mock import MagicMock@@ -49,12 +50,20 @@ def _make_fake_manager(existing: dict | None = None):"persona": "existing persona","channels": {},"model": None,+ "llm_selection": None,}defaults.update(existing)return BotConfig(**defaults)class FakeManager:- _MERGEABLE_FIELDS = ("name", "description", "persona", "channels", "model")+ _MERGEABLE_FIELDS = (+ "name",+ "description",+ "persona",+ "channels",+ "model",+ "llm_selection",+ )def load_bot_config(self, bot_id: str) -> BotConfig | None:return _build_existing()@@ -73,6 +82,7 @@ def _make_fake_manager(existing: dict | None = None):"bot_id": bot_id,"name": config.name,"channels": config.channels,+ "llm_selection": config.llm_selection,"running": True,}return instance@@ -92,6 +102,57 @@ def _make_client(monkeypatch, existing: dict | None = None):return TestClient(app), saved+def _catalog_with_llm_options() -> dict[str, Any]:+ return {+ "version": 1,+ "services": {+ "llm": {+ "active_profile_id": "p-default",+ "active_model_id": "m-default",+ "profiles": [+ {+ "id": "p-default",+ "name": "OpenAI",+ "binding": "openai",+ "base_url": "https://api.openai.com/v1",+ "api_key": "sk-test",+ "models": [+ {+ "id": "m-default",+ "name": "GPT Mini",+ "model": "gpt-4o-mini",+ }+ ],+ },+ {+ "id": "p-alt",+ "name": "OpenRouter",+ "binding": "openrouter",+ "base_url": "https://openrouter.ai/api/v1",+ "api_key": "sk-or-test",+ "models": [+ {+ "id": "m-alt",+ "name": "Claude",+ "model": "anthropic/claude-sonnet-4",+ }+ ],+ },+ ],+ }+ },+ }+++def _patch_llm_catalog(monkeypatch) -> None:+ config_mod = importlib.import_module("deeptutor.services.config")+ monkeypatch.setattr(+ config_mod,+ "get_model_catalog_service",+ lambda: SimpleNamespace(load=_catalog_with_llm_options),+ )++# ---------------------------------------------------------------------------# Tests# ---------------------------------------------------------------------------@@ -216,6 +277,7 @@ class TestCreateBotExplicitClearSemantics:"persona": "Disk Persona","channels": {"telegram": {"enabled": True}},"model": "gpt-4o",+ "llm_selection": {"profile_id": "p-default", "model_id": "m-default"},},)@@ -231,6 +293,7 @@ class TestCreateBotExplicitClearSemantics:assert cfg.persona == "New Persona"assert cfg.channels == {"telegram": {"enabled": True}}assert cfg.model == "gpt-4o"+ assert cfg.llm_selection == {"profile_id": "p-default", "model_id": "m-default"}def test_null_field_in_payload_falls_back_to_existing(self, monkeypatch):"""Explicit ``null`` for an optional field is treated as 'not provided'.@@ -249,6 +312,37 @@ class TestCreateBotExplicitClearSemantics:assert resp.status_code == 200assert saved["config"].description == "Disk Desc"+ def test_create_bot_saves_valid_llm_selection(self, monkeypatch):+ """A new UI-managed bot should persist the selected catalog model."""+ _patch_llm_catalog(monkeypatch)+ client, saved = _make_client(monkeypatch, existing=None)++ selection = {"profile_id": "p-alt", "model_id": "m-alt"}+ resp = client.post(+ "/api/v1/tutorbot",+ json={"bot_id": "my-bot", "name": "My Bot", "llm_selection": selection},+ )++ assert resp.status_code == 200+ assert saved["config"].llm_selection == selection++ def test_create_bot_rejects_invalid_llm_selection(self, monkeypatch):+ """Unknown catalog references fail at the API boundary."""+ _patch_llm_catalog(monkeypatch)+ client, _saved = _make_client(monkeypatch, existing=None)++ resp = client.post(+ "/api/v1/tutorbot",+ json={+ "bot_id": "my-bot",+ "name": "My Bot",+ "llm_selection": {"profile_id": "missing", "model_id": "m-alt"},+ },+ )++ assert resp.status_code == 422+ assert "Invalid LLM selection" in resp.json()["detail"]+class TestGetBotStoppedSecretHandling:"""GET /{bot_id} masks channel secrets by default; ?include_secrets=true reveals them."""@@ -267,7 +361,11 @@ class TestGetBotStoppedSecretHandling:return Nonedef load_bot_config(self, bot_id: str) -> BotConfig | None:- return BotConfig(name="b", channels=TestGetBotStoppedSecretHandling._CHANNELS)+ return BotConfig(+ name="b",+ channels=TestGetBotStoppedSecretHandling._CHANNELS,+ llm_selection={"profile_id": "p-default", "model_id": "m-default"},+ )tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: FakeMgr())@@ -288,6 +386,7 @@ class TestGetBotStoppedSecretHandling:assert body["channels"]["send_progress"] is Trueassert body["running"] is Falseassert body["last_reload_error"] is None+ assert body["llm_selection"] == {"profile_id": "p-default", "model_id": "m-default"}def test_explicit_include_secrets_reveals_token(self, monkeypatch):client = self._client(monkeypatch)@@ -338,6 +437,39 @@ class TestPatchBotStoppedAndRunning:assert body["channels"]["telegram"]["token"] == "***"assert body["channels"]["telegram"]["enabled"] is True+ def test_patch_stopped_can_clear_llm_selection(self, monkeypatch):+ from deeptutor.services.tutorbot.manager import BotConfig++ saved_cfg: list[BotConfig | None] = []++ class FakeMgr:+ def get_bot(self, bot_id: str):+ return None++ def load_bot_config(self, bot_id: str) -> BotConfig | None:+ return BotConfig(+ name="b",+ llm_selection={"profile_id": "p-alt", "model_id": "m-alt"},+ )++ def save_bot_config(+ self, bot_id: str, config: BotConfig, *, auto_start: bool = True+ ) -> None:+ saved_cfg.append(config)++ tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")+ monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: FakeMgr())++ app = FastAPI()+ app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")+ client = TestClient(app)++ resp = client.patch("/api/v1/tutorbot/b", json={"llm_selection": None})++ assert resp.status_code == 200+ assert saved_cfg[0].llm_selection is None+ assert resp.json()["llm_selection"] is None+def test_patch_running_channels_calls_reload(self, monkeypatch):from deeptutor.services.tutorbot.manager import BotConfig@@ -391,6 +523,59 @@ class TestPatchBotStoppedAndRunning:assert resp.status_code == 200assert reloaded == [True]+ def test_patch_running_llm_selection_calls_reload_llm(self, monkeypatch):+ from deeptutor.services.tutorbot.manager import BotConfig++ _patch_llm_catalog(monkeypatch)+ reloaded: list[str] = []+ saved_cfg: list[BotConfig] = []+ selection = {"profile_id": "p-alt", "model_id": "m-alt"}++ class FakeInst:+ def __init__(self):+ self.config = BotConfig(name="b")++ @property+ def running(self) -> bool:+ return True++ def to_dict(self, *, include_secrets: bool = False, mask_secrets: bool = False):+ return {+ "bot_id": "b",+ "name": self.config.name,+ "channels": [],+ "running": True,+ "llm_selection": self.config.llm_selection,+ }++ inst = FakeInst()++ class FakeMgr:+ def get_bot(self, bot_id: str):+ return inst if bot_id == "b" else None++ def save_bot_config(+ self, bot_id: str, config: BotConfig, *, auto_start: bool = True+ ) -> None:+ saved_cfg.append(config)++ async def reload_llm(self, bot_id: str) -> None:+ reloaded.append(bot_id)++ tutorbot_router_mod = importlib.import_module("deeptutor.api.routers.tutorbot")+ monkeypatch.setattr(tutorbot_router_mod, "get_tutorbot_manager", lambda: FakeMgr())++ app = FastAPI()+ app.include_router(tutorbot_router_mod.router, prefix="/api/v1/tutorbot")+ client = TestClient(app)++ resp = client.patch("/api/v1/tutorbot/b", json={"llm_selection": selection})++ assert resp.status_code == 200+ assert saved_cfg[0].llm_selection == selection+ assert reloaded == ["b"]+ assert resp.json()["llm_selection"] == selection+def test_patch_invalid_channels_rejected_422(self, monkeypatch):"""Malformed channels must be rejected at the boundary, not after disk write."""from deeptutor.services.tutorbot.manager import BotConfigdiff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.pyindex 9f0e606de..2a7762d82 100644--- a/tests/api/test_unified_ws_turn_runtime.py+++ b/tests/api/test_unified_ws_turn_runtime.py@@ -20,6 +20,48 @@ def _fake_skill_service() -> SimpleNamespace:)+def _model_catalog() -> dict:+ return {+ "version": 1,+ "services": {+ "llm": {+ "active_profile_id": "p-default",+ "active_model_id": "m-default",+ "profiles": [+ {+ "id": "p-default",+ "name": "Default",+ "binding": "openai",+ "base_url": "https://api.openai.com/v1",+ "api_key": "sk-test",+ "models": [+ {+ "id": "m-default",+ "name": "Default",+ "model": "gpt-4o-mini",+ }+ ],+ },+ {+ "id": "p-alt",+ "name": "Alt",+ "binding": "openrouter",+ "base_url": "https://openrouter.ai/api/v1",+ "api_key": "sk-alt",+ "models": [+ {+ "id": "m-alt",+ "name": "Alt Model",+ "model": "anthropic/claude-sonnet-4",+ }+ ],+ },+ ],+ }+ },+ }++@pytest.mark.asyncioasync def test_turn_runtime_replays_events_and_materializes_messages(monkeypatch: pytest.MonkeyPatch,@@ -140,6 +182,297 @@ async def test_turn_runtime_replays_events_and_materializes_messages(assert persisted_turn["status"] == "completed"+async def test_turn_runtime_persists_llm_selection_in_turn_snapshot(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ captured: dict[str, object] = {}++ class FakeContextBuilder:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def build(self, **kwargs):+ captured["builder_llm_config"] = kwargs["llm_config"]+ return SimpleNamespace(+ conversation_history=[],+ conversation_summary="",+ context_text="",+ token_count=0,+ budget=0,+ )++ class FakeOrchestrator:+ async def handle(self, context):+ captured["metadata"] = context.metadata+ yield StreamEvent(+ type=StreamEventType.CONTENT,+ source="chat",+ stage="responding",+ content="Alt reply",+ metadata={"call_kind": "llm_final_response"},+ )+ yield StreamEvent(type=StreamEventType.DONE, source="chat")++ def fake_activate(selection):+ captured["activated_selection"] = selection+ return SimpleNamespace(+ model="anthropic/claude-sonnet-4", provider_name="openrouter"+ ), object()++ monkeypatch.setattr(+ "deeptutor.services.config.get_model_catalog_service",+ lambda: SimpleNamespace(load=_model_catalog),+ )+ monkeypatch.setattr(+ "deeptutor.services.model_selection.runtime.activate_llm_selection",+ fake_activate,+ )+ monkeypatch.setattr(+ "deeptutor.services.model_selection.runtime.reset_llm_selection",+ lambda _token: captured.setdefault("reset_called", True),+ )+ monkeypatch.setattr(+ "deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder+ )+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_service",+ lambda: SimpleNamespace(+ build_memory_context=lambda *_args, **_kwargs: "",+ refresh_from_turn=_noop_refresh,+ ),+ )+ monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)++ selection = {"profile_id": "p-alt", "model_id": "m-alt"}+ session, turn = await runtime.start_turn(+ {+ "type": "start_turn",+ "content": "use the alt model",+ "session_id": None,+ "capability": None,+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {},+ "llm_selection": selection,+ }+ )++ async for _event in runtime.subscribe_turn(turn["id"], after_seq=0):+ pass++ detail = await store.get_session_with_messages(session["id"])+ assert detail is not None+ assert detail["preferences"]["llm_selection"] == selection+ assert detail["messages"][0]["metadata"]["request_snapshot"]["llmSelection"] == selection+ assert captured["activated_selection"] == selection+ assert captured["builder_llm_config"].model == "anthropic/claude-sonnet-4"+ assert captured["metadata"]["llm_selection"] == selection+ assert captured["metadata"]["llm_model"] == "anthropic/claude-sonnet-4"+ assert captured["metadata"]["llm_provider"] == "openrouter"+ assert captured["reset_called"] is True+++async def test_turn_runtime_rejects_invalid_llm_selection(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ monkeypatch.setattr(+ "deeptutor.services.config.get_model_catalog_service",+ lambda: SimpleNamespace(load=_model_catalog),+ )++ with pytest.raises(RuntimeError, match="Invalid LLM selection"):+ await runtime.start_turn(+ {+ "type": "start_turn",+ "content": "bad model",+ "session_id": None,+ "capability": None,+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {},+ "llm_selection": {"profile_id": "p-alt", "model_id": "m-default"},+ }+ )+++async def test_turn_runtime_allows_model_switching_within_same_session(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ activated: list[dict] = []+ metadata_seen: list[dict] = []++ class FakeContextBuilder:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def build(self, **_kwargs):+ return SimpleNamespace(+ conversation_history=[],+ conversation_summary="",+ context_text="",+ token_count=0,+ budget=0,+ )++ class FakeOrchestrator:+ async def handle(self, context):+ metadata_seen.append(context.metadata)+ yield StreamEvent(+ type=StreamEventType.CONTENT,+ source="chat",+ stage="responding",+ content=f"Reply from {context.metadata['llm_model']}",+ metadata={"call_kind": "llm_final_response"},+ )+ yield StreamEvent(type=StreamEventType.DONE, source="chat")++ def fake_activate(selection):+ activated.append(dict(selection or {}))+ is_alt = (selection or {}).get("profile_id") == "p-alt"+ return (+ SimpleNamespace(+ model="anthropic/claude-sonnet-4" if is_alt else "gpt-4o-mini",+ provider_name="openrouter" if is_alt else "openai",+ ),+ object(),+ )++ monkeypatch.setattr(+ "deeptutor.services.config.get_model_catalog_service",+ lambda: SimpleNamespace(load=_model_catalog),+ )+ monkeypatch.setattr(+ "deeptutor.services.model_selection.runtime.activate_llm_selection",+ fake_activate,+ )+ monkeypatch.setattr(+ "deeptutor.services.model_selection.runtime.reset_llm_selection",+ lambda _token: None,+ )+ monkeypatch.setattr(+ "deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder+ )+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_service",+ lambda: SimpleNamespace(+ build_memory_context=lambda *_args, **_kwargs: "",+ refresh_from_turn=_noop_refresh,+ ),+ )+ monkeypatch.setattr("deeptutor.services.skill.get_skill_service", _fake_skill_service)++ first_selection = {"profile_id": "p-default", "model_id": "m-default"}+ second_selection = {"profile_id": "p-alt", "model_id": "m-alt"}++ session, first_turn = await runtime.start_turn(+ {+ "type": "start_turn",+ "content": "first model",+ "session_id": None,+ "capability": None,+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {},+ "llm_selection": first_selection,+ }+ )+ async for _event in runtime.subscribe_turn(first_turn["id"], after_seq=0):+ pass++ same_session, second_turn = await runtime.start_turn(+ {+ "type": "start_turn",+ "content": "second model",+ "session_id": session["id"],+ "capability": None,+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {},+ "llm_selection": second_selection,+ }+ )+ async for _event in runtime.subscribe_turn(second_turn["id"], after_seq=0):+ pass++ detail = await store.get_session_with_messages(session["id"])+ assert same_session["id"] == session["id"]+ assert detail is not None+ assert detail["preferences"]["llm_selection"] == second_selection+ assert activated == [first_selection, second_selection]+ assert metadata_seen[0]["llm_model"] == "gpt-4o-mini"+ assert metadata_seen[1]["llm_model"] == "anthropic/claude-sonnet-4"+ user_messages = [message for message in detail["messages"] if message["role"] == "user"]+ assert user_messages[0]["metadata"]["request_snapshot"]["llmSelection"] == first_selection+ assert user_messages[1]["metadata"]["request_snapshot"]["llmSelection"] == second_selection+++async def test_regenerate_reuses_snapshot_or_override_llm_selection(tmp_path) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ captured_payloads: list[dict] = []++ class CapturingRuntime(TurnRuntimeManager):+ async def start_turn(self, payload: dict):+ captured_payloads.append(payload)+ return {"id": payload["session_id"]}, {"id": "turn-test"}++ runtime = CapturingRuntime(store)+ session = await store.create_session(session_id="session-with-snapshot")+ await store.update_session_preferences(+ session["id"],+ {"llm_selection": {"profile_id": "p-default", "model_id": "m-default"}},+ )+ await store.add_message(+ session_id=session["id"],+ role="user",+ content="again",+ capability="chat",+ metadata={+ "request_snapshot": {+ "content": "again",+ "llmSelection": {"profile_id": "p-alt", "model_id": "m-alt"},+ }+ },+ )++ await runtime.regenerate_last_turn(session["id"])+ assert captured_payloads[-1]["llm_selection"] == {+ "profile_id": "p-alt",+ "model_id": "m-alt",+ }++ await runtime.regenerate_last_turn(+ session["id"],+ overrides={"llm_selection": {"profile_id": "p-default", "model_id": "m-default"}},+ )+ assert captured_payloads[-1]["llm_selection"] == {+ "profile_id": "p-default",+ "model_id": "m-default",+ }++@pytest.mark.asyncioasync def test_turn_runtime_bootstraps_question_followup_context_once(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/scripts/test_start_tour.py b/tests/scripts/test_start_tour.pyindex c3a0b4eef..b6277c33c 100644--- a/tests/scripts/test_start_tour.py+++ b/tests/scripts/test_start_tour.py@@ -152,7 +152,9 @@ class TestResolvePython:matrix_cmds = start_tour._install_commands("web-matrix", catalog)assert any("requirements/tutorbot.txt" in cmd for cmd, _cwd in tutorbot_cmds)- assert any(cmd[0].startswith("npm") or cmd[0].endswith("npm") for cmd, _cwd in tutorbot_cmds)+ assert any(+ cmd[0].startswith("npm") or cmd[0].endswith("npm") for cmd, _cwd in tutorbot_cmds+ )assert any("requirements/matrix.txt" in cmd for cmd, _cwd in matrix_cmds)def test_requirements_for_install_can_include_math_animator(self) -> None:@@ -200,26 +202,6 @@ def test_save_ui_language_preserves_existing_theme(tmp_path: Path) -> None:assert '"language": "zh"' in saved-def test_save_launch_ports_preserves_existing_env_settings(tmp_path: Path) -> None:- start_tour = _load_start_tour_module()- settings_path = tmp_path / "env.json"- settings_path.write_text(- '{"version":1,"profile":"web-basic","llm":{"binding":"openai"}}',- encoding="utf-8",- )-- start_tour._save_launch_ports(- {"BACKEND_PORT": "9101", "FRONTEND_PORT": "4200"},- path=settings_path,- )-- saved = settings_path.read_text(encoding="utf-8")- assert '"profile": "web-basic"' in saved- assert '"binding": "openai"' in saved- assert '"backend": 9101' in saved- assert '"frontend": 4200' in saved--def test_embedding_model_suggestions_include_gemini() -> None:start_tour = _load_start_tour_module()assert start_tour.EMBEDDING_MODEL_SUGGESTIONS["gemini"] == "gemini-embedding-001"diff --git a/tests/services/config/test_launch_settings.py b/tests/services/config/test_launch_settings.pyindex c421e2526..84e5504f8 100644--- a/tests/services/config/test_launch_settings.py+++ b/tests/services/config/test_launch_settings.py@@ -12,7 +12,9 @@ def _settings_dir(root: Path) -> Path:return path-def test_launch_settings_prefer_runtime_settings(monkeypatch, tmp_path: Path) -> None:+def test_launch_settings_reads_ports_from_env_and_ignores_legacy_env_json(+ monkeypatch, tmp_path: Path+) -> None:for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):monkeypatch.delenv(key, raising=False)@@ -21,6 +23,8 @@ def test_launch_settings_prefer_runtime_settings(monkeypatch, tmp_path: Path) ->encoding="utf-8",)settings_dir = _settings_dir(tmp_path)+ # Legacy file may exist on older installs, but launcher ports now come+ # exclusively from .env / process env / defaults.(settings_dir / "env.json").write_text(json.dumps({"ports": {"backend": 8101, "frontend": 4100}}),encoding="utf-8",@@ -32,14 +36,15 @@ def test_launch_settings_prefer_runtime_settings(monkeypatch, tmp_path: Path) ->settings = load_launch_settings(tmp_path)- assert settings.backend_port == 8101- assert settings.frontend_port == 4100+ assert settings.backend_port == 9001+ assert settings.frontend_port == 4000assert settings.language == "zh"- assert "env.json" in settings.source+ assert ".env" in settings.source+ assert "env.json" not in settings.sourceassert "interface.json" in settings.source-def test_launch_settings_fall_back_to_env_when_settings_missing(+def test_launch_settings_fall_back_to_env_when_interface_settings_missing(monkeypatch, tmp_path: Path) -> None:for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):@@ -56,24 +61,21 @@ def test_launch_settings_fall_back_to_env_when_settings_missing(assert settings.frontend_port == 4200assert settings.source == ".env"assert settings.language == "zh"- assert settings.source == ".env"-def test_launch_settings_fall_back_per_invalid_port(monkeypatch, tmp_path: Path) -> None:+def test_launch_settings_fall_back_per_invalid_env_port(monkeypatch, tmp_path: Path) -> None:for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):monkeypatch.delenv(key, raising=False)+ monkeypatch.setenv("BACKEND_PORT", "9201")+ monkeypatch.setenv("FRONTEND_PORT", "4300")(tmp_path / ".env").write_text(- "BACKEND_PORT=9101\nFRONTEND_PORT=4200\n",- encoding="utf-8",- )- settings_dir = _settings_dir(tmp_path)- (settings_dir / "env.json").write_text(- json.dumps({"ports": {"backend": "not-a-port", "frontend": 70000}}),+ "BACKEND_PORT=not-a-port\nFRONTEND_PORT=70000\n",encoding="utf-8",)settings = load_launch_settings(tmp_path)- assert settings.backend_port == 9101- assert settings.frontend_port == 4200+ assert settings.backend_port == 9201+ assert settings.frontend_port == 4300+ assert settings.source == "environment"diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.pyindex 92a6c1e7f..97d1ccd5f 100644--- a/tests/services/config/test_provider_runtime.py+++ b/tests/services/config/test_provider_runtime.py@@ -267,6 +267,49 @@ def test_llm_context_window_passes_through_from_catalog(tmp_path: Path) -> None:assert resolved.context_window == 128000+def test_llm_selection_overrides_active_model_without_mutating_catalog(tmp_path: Path) -> None:+ profile_a = {+ "id": "p-a",+ "name": "OpenRouter",+ "binding": "openrouter",+ "base_url": "https://openrouter.ai/api/v1",+ "api_key": "sk-or-test",+ "api_version": "",+ "extra_headers": {},+ "models": [+ {+ "id": "m-a",+ "name": "Gemini",+ "model": "google/gemini-3-flash-preview",+ }+ ],+ }+ profile_b = {+ "id": "p-b",+ "name": "Local",+ "binding": "ollama",+ "base_url": "http://localhost:11434/v1",+ "api_key": "",+ "api_version": "",+ "extra_headers": {},+ "models": [{"id": "m-b", "name": "Llama", "model": "llama3.2"}],+ }+ catalog = _build_catalog(llm_profile=profile_a, llm_model=profile_a["models"][0])+ catalog["services"]["llm"]["profiles"].append(profile_b)++ resolved = resolve_llm_runtime_config(+ catalog=catalog,+ env_store=_empty_env(tmp_path),+ llm_selection={"profile_id": "p-b", "model_id": "m-b"},+ )++ assert resolved.model == "llama3.2"+ assert resolved.provider_name == "ollama"+ assert resolved.provider_mode == "local"+ assert catalog["services"]["llm"]["active_profile_id"] == "p-a"+ assert catalog["services"]["llm"]["active_model_id"] == "m-a"++def test_llm_reasoning_effort_env_overrides_catalog(tmp_path: Path) -> None:env_path = tmp_path / ".env"env_path.write_text(diff --git a/tests/services/llm/test_config_module.py b/tests/services/llm/test_config_module.pyindex 298125c56..d36479e06 100644--- a/tests/services/llm/test_config_module.py+++ b/tests/services/llm/test_config_module.py@@ -87,6 +87,38 @@ def test_get_llm_config_falls_back_to_env(monkeypatch, tmp_path: Path) -> None:assert config.binding == "openai"+def test_scoped_llm_config_takes_precedence_over_global_cache(monkeypatch, tmp_path: Path) -> None:+ _reset_config_cache()+ monkeypatch.setattr(+ config_module,+ "resolve_llm_runtime_config",+ lambda: (_ for _ in ()).throw(RuntimeError("boom")),+ )+ _set_temp_env_store(+ monkeypatch,+ tmp_path,+ "\n".join(+ [+ "LLM_MODEL=gpt-global",+ "LLM_HOST=https://global.example/v1",+ "LLM_API_KEY=sk-global",+ "LLM_BINDING=openai",+ ]+ )+ + "\n",+ )+ global_cfg = config_module.get_llm_config()+ scoped_cfg = global_cfg.model_copy(update={"model": "gpt-scoped"})++ token = config_module.set_scoped_llm_config(scoped_cfg)+ try:+ assert config_module.get_llm_config().model == "gpt-scoped"+ finally:+ config_module.reset_scoped_llm_config(token)++ assert config_module.get_llm_config().model == "gpt-global"++def test_initialize_environment_sets_openai_env(monkeypatch) -> None:"""initialize_environment should set OPENAI env vars from resolver output."""monkeypatch.delenv("OPENAI_API_KEY", raising=False)diff --git a/tests/services/llm/test_openai_responses_converters.py b/tests/services/llm/test_openai_responses_converters.pyindex 6e4adb0da..c22bf0ca9 100644--- a/tests/services/llm/test_openai_responses_converters.py+++ b/tests/services/llm/test_openai_responses_converters.py@@ -24,6 +24,11 @@ class TestAdaptChatKwargsToResponses:assert result == {"max_output_tokens": 8192, "temperature": 0.2}assert "max_completion_tokens" not in result+ def test_translates_legacy_max_tokens_to_max_output_tokens(self) -> None:+ result = adapt_chat_kwargs_to_responses({"max_tokens": 2048, "temperature": 0.2})+ assert result == {"max_output_tokens": 2048, "temperature": 0.2}+ assert "max_tokens" not in result+def test_drops_max_completion_tokens_when_none(self) -> None:result = adapt_chat_kwargs_to_responses({"max_completion_tokens": None, "temperature": 0.2})assert result == {"temperature": 0.2}@@ -36,6 +41,10 @@ class TestAdaptChatKwargsToResponses:)assert result == {"max_output_tokens": 4096}+ def test_max_completion_tokens_wins_when_both_chat_aliases_are_present(self) -> None:+ result = adapt_chat_kwargs_to_responses({"max_tokens": 2048, "max_completion_tokens": 8192})+ assert result == {"max_output_tokens": 8192}+def test_empty_input_returns_empty_dict(self) -> None:assert adapt_chat_kwargs_to_responses({}) == {}diff --git a/tests/services/model_selection/test_llm_selection.py b/tests/services/model_selection/test_llm_selection.pynew file mode 100644index 000000000..dbb784856--- /dev/null+++ b/tests/services/model_selection/test_llm_selection.py@@ -0,0 +1,88 @@+from deeptutor.services.model_selection import (+ LLMSelection,+ apply_llm_selection_to_catalog,+ list_llm_options,+)+++def _catalog():+ return {+ "version": 1,+ "services": {+ "llm": {+ "active_profile_id": "p1",+ "active_model_id": "m1",+ "profiles": [+ {+ "id": "p1",+ "name": "OpenRouter",+ "binding": "openrouter",+ "base_url": "https://openrouter.ai/api/v1",+ "api_key": "secret",+ "api_version": "",+ "extra_headers": {"x-secret": "nope"},+ "models": [+ {+ "id": "m1",+ "name": "Gemini Flash",+ "model": "google/gemini-3-flash-preview",+ "context_window": "1000000",+ },+ {+ "id": "m2",+ "name": "GPT Mini",+ "model": "openai/gpt-4o-mini",+ },+ ],+ },+ {+ "id": "p2",+ "name": "Local",+ "binding": "ollama",+ "base_url": "http://localhost:11434/v1",+ "api_key": "",+ "api_version": "",+ "extra_headers": {},+ "models": [{"id": "m3", "name": "Llama", "model": "llama3.2"}],+ },+ ],+ },+ "embedding": {"active_profile_id": None, "active_model_id": None, "profiles": []},+ "search": {"active_profile_id": None, "profiles": []},+ },+ }+++def test_list_llm_options_is_redacted_and_marks_active_default():+ payload = list_llm_options(_catalog())+ assert payload["active"] == {"profile_id": "p1", "model_id": "m1"}+ assert [o["model_id"] for o in payload["options"]] == ["m1", "m2", "m3"]+ assert payload["options"][0]["is_active_default"] is True+ assert payload["options"][0]["context_window"] == 1000000+ assert "api_key" not in payload["options"][0]+ assert "base_url" not in payload["options"][0]+ assert "extra_headers" not in payload["options"][0]+++def test_apply_llm_selection_to_catalog_returns_copy_with_selected_active_ids():+ selected = apply_llm_selection_to_catalog(+ _catalog(), LLMSelection(profile_id="p2", model_id="m3")+ )+ assert selected["services"]["llm"]["active_profile_id"] == "p2"+ assert selected["services"]["llm"]["active_model_id"] == "m3"+++def test_apply_llm_selection_does_not_mutate_source_catalog():+ catalog = _catalog()+ apply_llm_selection_to_catalog(catalog, LLMSelection(profile_id="p2", model_id="m3"))+ assert catalog["services"]["llm"]["active_profile_id"] == "p1"+ assert catalog["services"]["llm"]["active_model_id"] == "m1"+++def test_apply_llm_selection_rejects_model_not_in_profile():+ try:+ apply_llm_selection_to_catalog(_catalog(), LLMSelection(profile_id="p2", model_id="m1"))+ except ValueError as exc:+ assert "Invalid LLM selection" in str(exc)+ else:+ raise AssertionError("expected invalid selection to fail")diff --git a/tests/services/rag/test_index_versioning.py b/tests/services/rag/test_index_versioning.pyindex 96751ef9b..ca9fc4c4f 100644--- a/tests/services/rag/test_index_versioning.py+++ b/tests/services/rag/test_index_versioning.py@@ -8,6 +8,7 @@ from deeptutor.services.rag.index_versioning import (find_matching_version,list_kb_versions,resolve_storage_dir_for_read,+ resolve_storage_dir_for_rebuild,resolve_storage_dir_for_write,write_version_meta,)@@ -51,6 +52,20 @@ def test_resolve_storage_dir_for_write_reuses_matching_flat_version(tmp_path: Paassert resolve_storage_dir_for_write(kb_dir, sig) == version_dir+def test_resolve_storage_dir_for_rebuild_allocates_fresh_version(tmp_path: Path) -> None:+ kb_dir = tmp_path / "kb"+ sig = _signature()+ version_dir = kb_dir / "version-1"+ version_dir.mkdir(parents=True)+ (version_dir / "docstore.json").write_text("{}", encoding="utf-8")+ (version_dir / "meta.json").write_text(+ json.dumps({"signature": sig.hash(), "version": "version-1"}),+ encoding="utf-8",+ )++ assert resolve_storage_dir_for_rebuild(kb_dir, sig) == kb_dir / "version-2"++def test_resolve_storage_dir_for_write_without_signature_still_uses_flat_layout(tmp_path: Path,) -> None:diff --git a/tests/services/rag/test_llamaindex_embedding_failures.py b/tests/services/rag/test_llamaindex_embedding_failures.pyindex 6a14609f6..82a59ed50 100644--- a/tests/services/rag/test_llamaindex_embedding_failures.py+++ b/tests/services/rag/test_llamaindex_embedding_failures.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import jsonfrom types import SimpleNamespaceimport pytest@@ -129,6 +130,18 @@ def test_retrieve_nodes_rejects_invalid_persisted_embeddings(storage_module.retrieve_nodes(tmp_path, "what is this?")+def test_validate_storage_embeddings_rejects_invalid_vector_file(tmp_path) -> None:+ from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module++ (tmp_path / "default__vector_store.json").write_text(+ json.dumps({"embedding_dict": {"bad-node": [0.1, None, 0.3]}}),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="RAG index contains invalid embedding vectors"):+ storage_module.validate_storage_embeddings(tmp_path)++def test_retrieve_nodes_checks_storage_context_vector_stores(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/services/test_path_service.py b/tests/services/test_path_service.pyindex 9ecb3e615..843805be0 100644--- a/tests/services/test_path_service.py+++ b/tests/services/test_path_service.py@@ -26,7 +26,7 @@ def test_public_output_filter_allows_only_whitelisted_artifacts(tmp_path: Path)allowed.parent.mkdir(parents=True, exist_ok=True)allowed.write_text("png", encoding="utf-8")- denied = service._user_data_dir / "settings" / "env.json"+ denied = service._user_data_dir / "settings" / "model_catalog.json"denied.parent.mkdir(parents=True, exist_ok=True)denied.write_text("{}", encoding="utf-8")@@ -34,7 +34,7 @@ def test_public_output_filter_allows_only_whitelisted_artifacts(tmp_path: Path)service.is_public_output_path("workspace/chat/deep_solve/solve_1/artifacts/plot.png")is True)- assert service.is_public_output_path("settings/env.json") is False+ assert service.is_public_output_path("settings/model_catalog.json") is Falseassert service.is_public_output_path("../outside.txt") is Falsefinally:service._project_root = original_rootdiff --git a/tests/services/tutorbot/test_manager_config.py b/tests/services/tutorbot/test_manager_config.pyindex a359424b6..b2b9c0509 100644--- a/tests/services/tutorbot/test_manager_config.py+++ b/tests/services/tutorbot/test_manager_config.py@@ -11,6 +11,7 @@ import pytestimport yamlfrom deeptutor.services.tutorbot.manager import BotConfig, TutorBotInstance, TutorBotManager+from deeptutor.services.tutorbot.model_runtime import resolve_tutorbot_llm_config@pytest.fixture@@ -32,6 +33,21 @@ def _append_session_line(manager: TutorBotManager, bot_id: str, payload: dict) -handle.write(json.dumps(payload, ensure_ascii=False) + "\n")+def _write_session_file(+ manager: TutorBotManager,+ bot_id: str,+ filename: str,+ payloads: list[dict],+) -> Path:+ sessions_dir = manager._bot_workspace(bot_id) / "sessions"+ sessions_dir.mkdir(parents=True, exist_ok=True)+ path = sessions_dir / filename+ with open(path, "w", encoding="utf-8") as handle:+ for payload in payloads:+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")+ return path++# ---------------------------------------------------------------------------# load_bot_config / save_bot_config# ---------------------------------------------------------------------------@@ -48,6 +64,7 @@ class TestLoadAndSave:persona="p",channels={"telegram": {"enabled": True, "token": "tok"}},model="gpt-4o",+ llm_selection={"profile_id": "p1", "model_id": "m1"},)manager.save_bot_config("bot-a", cfg)@@ -81,6 +98,53 @@ class TestMessageHistory:assert history == [{"role": "assistant", "content": "Here is the image diagram"}]+ def test_history_is_chronological_across_legacy_and_canonical_sessions(+ self, manager: TutorBotManager+ ):+ _write_session_file(+ manager,+ "bot-history",+ "web_legacy.jsonl",+ [+ {+ "role": "user",+ "content": "old user",+ "timestamp": "2026-03-20T20:12:59.665712",+ },+ {+ "role": "assistant",+ "content": "old assistant",+ "timestamp": "2026-03-20T20:13:00.665712",+ },+ ],+ )+ _write_session_file(+ manager,+ "bot-history",+ "bot_history.jsonl",+ [+ {+ "role": "user",+ "content": "new user",+ "timestamp": "2026-05-03T15:25:53.085811",+ },+ {+ "role": "assistant",+ "content": "new assistant",+ "timestamp": "2026-05-03T15:25:54.085811",+ },+ ],+ )++ history = manager.get_bot_history("bot-history")++ assert [m["content"] for m in history] == [+ "old user",+ "old assistant",+ "new user",+ "new assistant",+ ]+def test_recent_active_bots_normalizes_last_message(self, manager: TutorBotManager):manager.save_bot_config("bot-recent", BotConfig(name="Recent Bot"))_append_session_line(@@ -219,6 +283,49 @@ class TestMergeBotConfig:assert not hasattr(merged, "unknown_field")+class TestTutorBotModelRuntime:+ def test_selection_is_resolved_through_model_selection_service(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ captured: list[dict[str, str] | None] = []++ def fake_resolve(selection):+ captured.append(selection)+ return SimpleNamespace(model="selected-model")++ monkeypatch.setattr(+ "deeptutor.services.tutorbot.model_runtime.resolve_llm_config_for_selection",+ fake_resolve,+ )++ cfg = BotConfig(+ name="bot",+ llm_selection={"profile_id": "p-alt", "model_id": "m-alt"},+ model="legacy-model",+ )++ resolved = resolve_tutorbot_llm_config(cfg)++ assert resolved.model == "selected-model"+ assert captured == [{"profile_id": "p-alt", "model_id": "m-alt"}]++ def test_legacy_model_overrides_system_default(self, monkeypatch: pytest.MonkeyPatch) -> None:+ class FakeConfig:+ model = "system-model"++ def model_copy(self, update):+ return SimpleNamespace(model=update["model"])++ monkeypatch.setattr(+ "deeptutor.services.tutorbot.model_runtime.resolve_llm_config_for_selection",+ lambda selection: FakeConfig(),+ )++ resolved = resolve_tutorbot_llm_config(BotConfig(name="bot", model="legacy-model"))++ assert resolved.model == "legacy-model"++# ---------------------------------------------------------------------------# auto_start persistence during lifecycle stops# ---------------------------------------------------------------------------@@ -280,7 +387,10 @@ def test_start_bot_passes_shared_memory_dir(class FakeAgentLoop:def __init__(self, *args, **kwargs) -> None:captured["shared_memory_dir"] = kwargs.get("shared_memory_dir")+ captured["model"] = kwargs.get("model")+ captured["context_window_tokens"] = kwargs.get("context_window_tokens")self.model = kwargs.get("model") or "fake-model"+ self.context_window_tokens = kwargs.get("context_window_tokens") or 65_536async def run(self) -> None:return None@@ -298,7 +408,11 @@ def test_start_bot_passes_shared_memory_dir(monkeypatch.setattr("deeptutor.tutorbot.agent.loop.AgentLoop", FakeAgentLoop)monkeypatch.setattr("deeptutor.tutorbot.providers.deeptutor_adapter.create_deeptutor_provider",- lambda: object(),+ lambda *_args, **_kwargs: object(),+ )+ monkeypatch.setattr(+ "deeptutor.services.tutorbot.model_runtime.resolve_tutorbot_llm_config",+ lambda _cfg: SimpleNamespace(model="selected-model", context_window=123456),)monkeypatch.setattr("deeptutor.services.tutorbot.manager.TutorBotManager._build_channel_manager",@@ -321,3 +435,62 @@ def test_start_bot_passes_shared_memory_dir(asyncio.run(run_start())assert captured["shared_memory_dir"] == tmp_path / "memory"+ assert captured["model"] == "selected-model"+ assert captured["context_window_tokens"] == 123456+++def test_reload_llm_updates_running_agent_loop(+ manager: TutorBotManager,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ calls: list[dict[str, object]] = []++ class FakeAgentLoop:+ context_window_tokens = 65_536++ def update_llm(self, **kwargs) -> None:+ calls.append(kwargs)+ self.model = kwargs["model"]++ class FakeHeartbeat:+ provider = None+ model = None++ cfg = BotConfig(+ name="bot",+ llm_selection={"profile_id": "p-alt", "model_id": "m-alt"},+ )+ instance = TutorBotInstance(bot_id="reload-bot", config=cfg)+ instance.agent_loop = FakeAgentLoop()+ instance.heartbeat = FakeHeartbeat()++ selected_provider = object()+ monkeypatch.setattr(+ "deeptutor.services.tutorbot.model_runtime.resolve_tutorbot_llm_config",+ lambda _cfg: SimpleNamespace(model="alt-model", context_window=999),+ )+ monkeypatch.setattr(+ "deeptutor.tutorbot.providers.deeptutor_adapter.create_deeptutor_provider",+ lambda _cfg: selected_provider,+ )++ async def run_reload() -> None:+ task = asyncio.create_task(asyncio.sleep(3600))+ instance.tasks = [task]+ manager._bots["reload-bot"] = instance+ try:+ await manager.reload_llm("reload-bot")+ finally:+ task.cancel()++ asyncio.run(run_reload())++ assert calls == [+ {+ "provider": selected_provider,+ "model": "alt-model",+ "context_window_tokens": 999,+ }+ ]+ assert instance.heartbeat.provider is selected_provider+ assert instance.heartbeat.model == "alt-model"diff --git a/web/.env.local b/web/.env.localindex 2b04f3785..a114876c2 100644--- a/web/.env.local+++ b/web/.env.local@@ -1,2 +1,2 @@-# Auto-generated by start_web.py — do not edit manually+# Auto-generated by start_web.py - do not edit manuallyNEXT_PUBLIC_API_BASE=http://localhost:8001diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsxindex de9779c3f..18b4ba3d5 100644--- a/web/app/(utility)/settings/page.tsx+++ b/web/app/(utility)/settings/page.tsx@@ -204,14 +204,11 @@ function defaultCatalog(): Catalog {const fieldControlClass ="w-full rounded-lg border border-[var(--border)] px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)]";-const inputClass =- `${fieldControlClass} bg-transparent placeholder:text-[var(--muted-foreground)]/40`;+const inputClass = `${fieldControlClass} bg-transparent placeholder:text-[var(--muted-foreground)]/40`;-const nativeSelectClass =- `${fieldControlClass} bg-[var(--background)] cursor-pointer disabled:cursor-not-allowed disabled:opacity-60`;+const nativeSelectClass = `${fieldControlClass} bg-[var(--background)] cursor-pointer disabled:cursor-not-allowed disabled:opacity-60`;-const selectClass =- `${nativeSelectClass} appearance-none`;+const selectClass = `${nativeSelectClass} appearance-none`;const selectOptionClass = "bg-[var(--background)] text-[var(--foreground)]";@@ -506,11 +503,7 @@ function DimensionField({{t("Auto (probe on next test)")}</option>{supported.map((dim) => (- <option- className={selectOptionClass}- key={dim}- value={String(dim)}- >+ <option className={selectOptionClass} key={dim} value={String(dim)}>{dim}</option>))}diff --git a/web/app/(workspace)/agents/[botId]/chat/page.tsx b/web/app/(workspace)/agents/[botId]/chat/page.tsxindex 66e2f2b84..b1af253f9 100644--- a/web/app/(workspace)/agents/[botId]/chat/page.tsx+++ b/web/app/(workspace)/agents/[botId]/chat/page.tsx@@ -119,10 +119,20 @@ export default function BotChatPage() {if (!botId) {return;}+ let cancelled = false;+ setMessages([]);+ setThinking([]);+ thinkingRef.current = [];+ setStreaming(false);+fetch(apiUrl(`/api/v1/tutorbot/${botId}`)).then((r) => (r.ok ? r.json() : null))- .then(setBot)- .catch(() => setBot(null));+ .then((data) => {+ if (!cancelled) setBot(data);+ })+ .catch(() => {+ if (!cancelled) setBot(null);+ });fetch(apiUrl(`/api/v1/tutorbot/${botId}/history`)).then((r) => (r.ok ? r.json() : []))@@ -140,8 +150,9 @@ export default function BotChatPage() {role: m.role as "user" | "assistant",content: normalizeMessageContent(m.content),}));+ if (cancelled) return;+ setMessages(restored);if (restored.length) {- setMessages(restored);requestAnimationFrame(() => scrollToBottom("instant"));window.setTimeout(() => scrollToBottom("instant"), 80);window.setTimeout(() => scrollToBottom("instant"), 250);@@ -149,6 +160,9 @@ export default function BotChatPage() {},).catch(() => {});+ return () => {+ cancelled = true;+ };}, [botId, scrollToBottom]);useEffect(() => {diff --git a/web/app/(workspace)/agents/page.tsx b/web/app/(workspace)/agents/page.tsxindex 19c38a4b7..28b098803 100644--- a/web/app/(workspace)/agents/page.tsx+++ b/web/app/(workspace)/agents/page.tsx@@ -22,6 +22,13 @@ import { useRouter } from "next/navigation";import { useTranslation } from "react-i18next";import dynamic from "next/dynamic";import { apiUrl } from "@/lib/api";+import ModelSelector from "@/components/chat/home/ModelSelector";+import {+ listLLMOptions,+ sameLLMSelection,+ type LLMOption,+} from "@/lib/llm-options";+import type { LLMSelection } from "@/lib/unified-ws";const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"),@@ -45,6 +52,7 @@ interface BotInfo {*/channels: string[];model: string | null;+ llm_selection?: LLMSelection | null;running: boolean;started_at: string | null;/** Set when a previous PATCH succeeded but `reload_channels` failed. */@@ -78,6 +86,12 @@ export default function AgentsPage() {const [loading, setLoading] = useState(true);const [activeTab, setActiveTab] = useState<Tab>("bots");const [toast, setToast] = useState("");+ const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);+ const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(+ null,+ );+ const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);+ const [llmOptionsError, setLLMOptionsError] = useState(false);useEffect(() => {if (!toast) return;@@ -104,10 +118,27 @@ export default function AgentsPage() {}}, []);+ const loadLLMOptions = useCallback(async () => {+ setLLMOptionsLoading(true);+ try {+ const payload = await listLLMOptions();+ setLLMOptions(payload.options);+ setActiveLLMDefault(payload.active);+ setLLMOptionsError(false);+ } catch {+ setLLMOptions([]);+ setActiveLLMDefault(null);+ setLLMOptionsError(true);+ } finally {+ setLLMOptionsLoading(false);+ }+ }, []);+useEffect(() => {void loadBots();void loadSouls();- }, [loadBots, loadSouls]);+ void loadLLMOptions();+ }, [loadBots, loadSouls, loadLLMOptions]);return (<div className="h-full overflow-y-auto [scrollbar-gutter:stable]">@@ -160,6 +191,10 @@ export default function AgentsPage() {bots={bots}souls={souls}loading={loading}+ llmOptions={llmOptions}+ activeLLMDefault={activeLLMDefault}+ llmOptionsLoading={llmOptionsLoading}+ llmOptionsError={llmOptionsError}onReload={loadBots}onToast={setToast}router={router}@@ -819,6 +854,10 @@ function BotsTab({bots,souls,loading,+ llmOptions,+ activeLLMDefault,+ llmOptionsLoading,+ llmOptionsError,onReload,onToast,router,@@ -826,6 +865,10 @@ function BotsTab({bots: BotInfo[];souls: SoulTemplate[];loading: boolean;+ llmOptions: LLMOption[];+ activeLLMDefault: LLMSelection | null;+ llmOptionsLoading: boolean;+ llmOptionsError: boolean;onReload: () => Promise<void>;onToast: (msg: string) => void;router: ReturnType<typeof useRouter>;@@ -838,14 +881,17 @@ function BotsTab({const [formDesc, setFormDesc] = useState("");const [formSoulId, setFormSoulId] = useState("_custom");const [formSoul, setFormSoul] = useState("");- const [formModel, setFormModel] = useState("");+ const [formLLMSelection, setFormLLMSelection] = useState<LLMSelection | null>(+ null,+ );+ const [updatingModelBot, setUpdatingModelBot] = useState<string | null>(null);const resetForm = () => {setFormName("");setFormDesc("");setFormSoulId("_custom");setFormSoul("");- setFormModel("");+ setFormLLMSelection(null);};const botId = useMemo(() => {@@ -887,7 +933,7 @@ function BotsTab({name: formName.trim(),description: formDesc.trim(),persona: formSoul.trim(),- model: formModel.trim() || undefined,+ llm_selection: formLLMSelection,}),});if (res.ok) {@@ -910,7 +956,61 @@ function BotsTab({} finally {setCreating(false);}- }, [botId, formName, formDesc, formSoul, formModel, onReload, onToast, t]);+ }, [+ botId,+ formName,+ formDesc,+ formSoul,+ formLLMSelection,+ onReload,+ onToast,+ t,+ ]);++ const updateBotModel = useCallback(+ async (bid: string, selection: LLMSelection | null) => {+ setUpdatingModelBot(bid);+ try {+ const res = await fetch(apiUrl(`/api/v1/tutorbot/${bid}`), {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ llm_selection: selection,+ ...(selection ? {} : { model: "" }),+ }),+ });+ if (res.ok) {+ onToast(t("Model saved"));+ await onReload();+ } else {+ const err = (await res.json().catch(() => ({}))) as {+ detail?: string;+ };+ onToast(err.detail ?? t("Failed to save model"));+ }+ } catch {+ onToast(t("Failed to save model"));+ } finally {+ setUpdatingModelBot(null);+ }+ },+ [onReload, onToast, t],+ );++ const modelLabelFor = useCallback(+ (bot: BotInfo) => {+ const selected = bot.llm_selection+ ? llmOptions.find((option) =>+ sameLLMSelection(option, bot.llm_selection),+ )+ : null;+ if (selected) return selected.model_name || selected.model;+ if (bot.llm_selection) return t("Selected model");+ if (bot.model) return bot.model;+ return t("System default");+ },+ [llmOptions, t],+ );const startBot = useCallback(async (bid: string) => {@@ -1077,12 +1177,22 @@ function BotsTab({{t("(optional)")}</span></label>- <input- value={formModel}- onChange={(e) => setFormModel(e.target.value)}- placeholder={t("Uses default model if empty")}- className="w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"+ <ModelSelector+ options={llmOptions}+ activeDefault={activeLLMDefault}+ value={formLLMSelection}+ loading={llmOptionsLoading}+ error={llmOptionsError}+ allowSystemDefault+ helperText={t("Applies to this TutorBot")}+ placement="bottom"+ onChange={setFormLLMSelection}/>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]/60">+ {t(+ "Choose a configured Settings model, or keep the system default.",+ )}+ </p></div><div className="flex justify-end"><button@@ -1142,7 +1252,7 @@ function BotsTab({) : (<span>{bot.bot_id}</span>)}- {bot.model && <span>· {bot.model}</span>}+ <span>· {modelLabelFor(bot)}</span>{bot.started_at && (<span>·{" "}@@ -1155,6 +1265,19 @@ function BotsTab({</div></div><div className="flex items-center gap-2 shrink-0">+ <ModelSelector+ options={llmOptions}+ activeDefault={activeLLMDefault}+ value={bot.llm_selection ?? null}+ loading={llmOptionsLoading || updatingModelBot === bot.bot_id}+ error={llmOptionsError}+ allowSystemDefault+ helperText={t("Applies to this TutorBot")}+ placement="bottom"+ onChange={(selection) =>+ updateBotModel(bot.bot_id, selection)+ }+ />{bot.running ? (<><buttondiff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex 02ba16f9c..11ac875ad 100644--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@ -36,7 +36,7 @@ import {} from "@/context/UnifiedChatContext";import { useAppShell } from "@/context/AppShellContext";import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";-import type { StreamEvent } from "@/lib/unified-ws";+import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";import {extractBase64FromDataUrl,readFileAsDataUrl,@@ -78,6 +78,7 @@ import {type ResearchSource,} from "@/lib/research-types";import { listKnowledgeBases } from "@/lib/knowledge-api";+import { listLLMOptions, type LLMOption } from "@/lib/llm-options";import { downloadChatMarkdown } from "@/lib/chat-export";import type { SpaceMemoryFile } from "@/lib/space-items";import {@@ -266,6 +267,7 @@ export default function ChatPage() {setTools,setCapability,setKBs,+ setLLMSelection,sendMessage,cancelStreamingTurn,regenerateLastMessage,@@ -274,6 +276,12 @@ export default function ChatPage() {} = useUnifiedChat();const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);+ const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);+ const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(+ null,+ );+ const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);+ const [llmOptionsError, setLLMOptionsError] = useState(false);const [capabilityConfigs, setCapabilityConfigs] =useState<CapabilityPlaygroundConfigMap>({});const [attachments, setAttachments] = useState<PendingAttachment[]>([]);@@ -585,10 +593,36 @@ export default function ChatPage() {void refreshKnowledgeBases({ force: true });}, [refreshKnowledgeBases]);+ const refreshLLMOptions = useCallback(async () => {+ setLLMOptionsLoading(true);+ try {+ const payload = await listLLMOptions();+ setLLMOptions(payload.options);+ setActiveLLMDefault(payload.active);+ setLLMOptionsError(false);+ } catch {+ setLLMOptionsError(true);+ setLLMOptions([]);+ setActiveLLMDefault(null);+ } finally {+ setLLMOptionsLoading(false);+ }+ }, []);++ useEffect(() => {+ void refreshLLMOptions();+ }, [refreshLLMOptions]);++ useEffect(() => {+ if (state.llmSelection || !activeLLMDefault) return;+ setLLMSelection(activeLLMDefault);+ }, [activeLLMDefault, setLLMSelection, state.llmSelection]);+useEffect(() => {if (typeof window === "undefined") return;const refresh = () => {void refreshKnowledgeBases({ force: true });+ void refreshLLMOptions();};const refreshWhenVisible = () => {if (document.visibilityState === "visible") refresh();@@ -601,7 +635,7 @@ export default function ChatPage() {window.removeEventListener("pageshow", refresh);document.removeEventListener("visibilitychange", refreshWhenVisible);};- }, [refreshKnowledgeBases]);+ }, [refreshKnowledgeBases, refreshLLMOptions]);useEffect(() => {setCapabilityConfigs(loadCapabilityPlaygroundConfigs());@@ -1275,6 +1309,11 @@ export default function ChatPage() {selectedTools={selectedTools}ragActive={ragActive}knowledgeBases={knowledgeBases}+ llmOptions={llmOptions}+ activeLLMDefault={activeLLMDefault}+ llmSelection={state.llmSelection}+ llmOptionsLoading={llmOptionsLoading}+ llmOptionsError={llmOptionsError}selectedBookReferences={selectedBookReferences}selectedNotebookRecords={selectedNotebookRecords}selectedHistorySessions={selectedHistorySessions}@@ -1302,6 +1341,7 @@ export default function ChatPage() {onSetToolMenuOpen={setToolMenuOpen}onSetSpaceMenuOpen={setSpaceMenuOpen}onSetKB={handleSetKB}+ onSelectLLM={setLLMSelection}onSelectNotebookPicker={handleSelectNotebookPicker}onSelectBookPicker={handleSelectBookPicker}onSelectHistoryPicker={handleSelectHistoryPicker}diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsxindex 997a64f0c..131c817e2 100644--- a/web/components/SessionList.tsx+++ b/web/components/SessionList.tsx@@ -297,13 +297,13 @@ export default function SessionList({/* ---- Classic style ---- */return (- <div className="space-y-3">+ <div className="space-y-4">{grouped.map(([label, items]) => (<div key={label}>- <div className="mb-1 px-2 text-[11px] font-semibold uppercase tracking-widest text-[var(--muted-foreground)]">+ <div className="mb-1.5 px-2 text-[11px] font-semibold uppercase tracking-widest text-[var(--muted-foreground)]">{label}</div>- <div className="space-y-px">+ <div className="divide-y divide-[var(--border)]/45 overflow-hidden rounded-lg border border-[var(--border)]/45 bg-[var(--card)]/50">{items.map((session) => {const active = activeSessionId === session.session_id;const isEditing = editingId === session.session_id;@@ -319,14 +319,14 @@ export default function SessionList({}}role="button"tabIndex={0}- className={`group relative w-full rounded-lg px-2.5 py-2 text-left transition-all duration-150 ${+ className={`group relative w-full px-3 py-2.5 text-left transition-colors duration-150 ${active? "bg-[var(--background)]/70 text-[var(--foreground)]": "text-[var(--muted-foreground)] hover:bg-[var(--background)]/50 hover:text-[var(--foreground)]"}`}>{active && (- <span className="absolute left-0 top-1/2 h-4 w-[3px] -translate-y-1/2 rounded-r-full bg-[var(--primary)]" />+ <span className="absolute left-0 top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-r-full bg-[var(--primary)]" />)}<div className="flex items-start gap-1.5"><div className="min-w-0 flex-1">diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex 192f1f6a6..da2381a97 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -35,6 +35,8 @@ import type { SelectedRecord } from "@/lib/notebook-selection-types";import type { DeepQuestionFormConfig } from "@/lib/quiz-types";import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";import type { VisualizeFormConfig } from "@/lib/visualize-types";+import type { LLMSelection } from "@/lib/unified-ws";+import type { LLMOption } from "@/lib/llm-options";import type {DeepResearchFormConfig,ResearchSource,@@ -42,6 +44,7 @@ import type {import ChatSpaceMenu from "@/components/chat/space/ChatSpaceMenu";import type { SpaceMemoryFile } from "@/lib/space-items";import type { SelectedBookReference } from "@/lib/book-references";+import ModelSelector from "./ModelSelector";type SpaceSelectionCounts = {chatHistory: number;@@ -127,6 +130,11 @@ export default memo(function ChatComposer({selectedTools,ragActive,knowledgeBases,+ llmOptions,+ activeLLMDefault,+ llmSelection,+ llmOptionsLoading,+ llmOptionsError,selectedNotebookRecords,selectedBookReferences,selectedHistorySessions,@@ -154,6 +162,7 @@ export default memo(function ChatComposer({onSetToolMenuOpen,onSetSpaceMenuOpen,onSetKB,+ onSelectLLM,onSelectNotebookPicker,onSelectBookPicker,onSelectHistoryPicker,@@ -207,6 +216,11 @@ export default memo(function ChatComposer({selectedTools: Set<string>;ragActive: boolean;knowledgeBases: KnowledgeBase[];+ llmOptions: LLMOption[];+ activeLLMDefault: LLMSelection | null;+ llmSelection: LLMSelection | null;+ llmOptionsLoading: boolean;+ llmOptionsError: boolean;selectedNotebookRecords: SelectedRecord[];selectedBookReferences: SelectedBookReference[];selectedHistorySessions: SelectedHistorySession[];@@ -238,6 +252,7 @@ export default memo(function ChatComposer({onSetToolMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;onSetSpaceMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;onSetKB: (kb: string) => void;+ onSelectLLM: (selection: LLMSelection | null) => void;onSelectNotebookPicker: () => void;onSelectBookPicker: () => void;onSelectHistoryPicker: () => void;@@ -831,6 +846,15 @@ export default memo(function ChatComposer({</div><div className="ml-auto flex shrink-0 items-center gap-1.5">+ <ModelSelector+ options={llmOptions}+ activeDefault={activeLLMDefault}+ value={llmSelection}+ loading={llmOptionsLoading}+ error={llmOptionsError}+ onChange={onSelectLLM}+ />+<selectvalue={stateKnowledgeBase}onChange={(e) => onSetKB(e.target.value)}diff --git a/web/components/chat/home/ModelSelector.tsx b/web/components/chat/home/ModelSelector.tsxnew file mode 100644index 000000000..f40247cff--- /dev/null+++ b/web/components/chat/home/ModelSelector.tsx@@ -0,0 +1,241 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { AlertCircle, Bot, Check, ChevronDown } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { LLMSelection } from "@/lib/unified-ws";+import {+ llmSelectionKey,+ sameLLMSelection,+ type LLMOption,+} from "@/lib/llm-options";++function formatContextWindow(value?: number) {+ if (!value) return "";+ if (value >= 1_000_000) return `${Math.round(value / 1_000_000)}M ctx`;+ if (value >= 1_000) return `${Math.round(value / 1_000)}k ctx`;+ return `${value} ctx`;+}++function providerLabel(option: LLMOption) {+ return option.provider || option.profile_name || "LLM";+}++export default function ModelSelector({+ options,+ activeDefault,+ value,+ loading,+ error,+ allowSystemDefault = false,+ systemDefaultLabel,+ systemDefaultDetail,+ helperText,+ placement = "top",+ onChange,+}: {+ options: LLMOption[];+ activeDefault: LLMSelection | null;+ value: LLMSelection | null;+ loading: boolean;+ error: boolean;+ allowSystemDefault?: boolean;+ systemDefaultLabel?: string;+ systemDefaultDetail?: string;+ helperText?: string;+ placement?: "top" | "bottom";+ onChange: (selection: LLMSelection | null) => void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const rootRef = useRef<HTMLDivElement>(null);++ const selectedSelection = allowSystemDefault ? value : value ?? activeDefault;+ const selectedKey = llmSelectionKey(selectedSelection);+ const selectedOption = useMemo(+ () =>+ options.find((option) => sameLLMSelection(option, selectedSelection)) ??+ null,+ [options, selectedSelection],+ );++ useEffect(() => {+ if (!open) return;+ const handler = (event: MouseEvent) => {+ const target = event.target as Node;+ if (rootRef.current && !rootRef.current.contains(target)) {+ setOpen(false);+ }+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, [open]);++ const defaultLabel = systemDefaultLabel || t("System default");+ const defaultDetail =+ systemDefaultDetail || t("Use the active default model from Settings");+ const disabled =+ loading || error || (options.length === 0 && !allowSystemDefault);+ const label = loading+ ? t("Loading models")+ : error+ ? t("Models unavailable")+ : allowSystemDefault && !selectedSelection+ ? defaultLabel+ : selectedOption?.model_name || t("Select model");+ const detail = selectedOption+ ? `${selectedOption.profile_name} | ${providerLabel(selectedOption)}`+ : allowSystemDefault && !selectedSelection+ ? defaultDetail+ : error+ ? t("Could not load models")+ : options.length === 0+ ? t("No configured models")+ : t("Choose a model");+ const menuPlacementClass =+ placement === "bottom" ? "top-full mt-1.5" : "bottom-full mb-1.5";++ return (+ <div ref={rootRef} className="relative">+ <button+ type="button"+ disabled={disabled}+ onClick={() => setOpen((current) => !current)}+ title={detail}+ aria-label={t("Select model")}+ aria-expanded={open}+ className={`inline-flex h-[28px] max-w-[150px] shrink-0 items-center gap-1.5 rounded-full border px-2.5 text-[11px] font-medium transition-colors sm:max-w-[210px] ${+ disabled+ ? "cursor-not-allowed border-[var(--border)]/25 text-[var(--border)]"+ : open+ ? "border-[var(--primary)]/50 bg-[var(--primary)]/[0.04] text-[var(--foreground)]"+ : "border-[var(--border)]/40 text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)]"+ }`}+ >+ {error ? (+ <AlertCircle size={12} strokeWidth={1.7} className="shrink-0" />+ ) : (+ <Bot size={12} strokeWidth={1.7} className="shrink-0" />+ )}+ <span className="min-w-0 truncate">{label}</span>+ <ChevronDown+ size={10}+ className={`shrink-0 transition-transform ${open ? "rotate-180" : ""}`}+ />+ </button>++ {open && !disabled && (+ <div+ className={`absolute right-0 z-50 ${menuPlacementClass} w-[min(340px,calc(100vw-32px))] overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--popover)] shadow-lg backdrop-blur-md`}+ >+ <div className="border-b border-[var(--border)]/50 px-3 py-2">+ <div className="text-[12px] font-semibold text-[var(--foreground)]">+ {t("Choose model")}+ </div>+ <div className="mt-0.5 text-[10px] text-[var(--muted-foreground)]">+ {helperText || t("Applies to the next message in this chat")}+ </div>+ </div>+ <div className="max-h-[280px] overflow-y-auto py-1">+ {allowSystemDefault && (+ <button+ type="button"+ onClick={() => {+ onChange(null);+ setOpen(false);+ }}+ className={`flex w-full items-center gap-2.5 px-3 py-2 text-left transition-colors ${+ selectedKey === ""+ ? "bg-[var(--primary)]/[0.06]"+ : "hover:bg-[var(--muted)]/45"+ }`}+ >+ <div+ className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full border ${+ selectedKey === ""+ ? "border-[var(--primary)]/35 bg-[var(--primary)]/10 text-[var(--primary)]"+ : "border-[var(--border)]/50 bg-[var(--muted)]/25 text-[var(--muted-foreground)]"+ }`}+ >+ <Bot size={13} strokeWidth={1.7} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[12px] font-medium text-[var(--foreground)]">+ {defaultLabel}+ </div>+ <div className="mt-0.5 truncate text-[10px] text-[var(--muted-foreground)]">+ {defaultDetail}+ </div>+ </div>+ {selectedKey === "" && (+ <Check+ size={14}+ strokeWidth={2}+ className="shrink-0 text-[var(--primary)]"+ />+ )}+ </button>+ )}+ {options.map((option) => {+ const optionSelection = {+ profile_id: option.profile_id,+ model_id: option.model_id,+ };+ const optionKey = llmSelectionKey(optionSelection);+ const selected = optionKey === selectedKey;+ const contextWindow = formatContextWindow(option.context_window);+ return (+ <button+ key={optionKey}+ type="button"+ onClick={() => {+ onChange(optionSelection);+ setOpen(false);+ }}+ className={`flex w-full items-center gap-2.5 px-3 py-2 text-left transition-colors ${+ selected+ ? "bg-[var(--primary)]/[0.06]"+ : "hover:bg-[var(--muted)]/45"+ }`}+ >+ <div+ className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full border ${+ selected+ ? "border-[var(--primary)]/35 bg-[var(--primary)]/10 text-[var(--primary)]"+ : "border-[var(--border)]/50 bg-[var(--muted)]/25 text-[var(--muted-foreground)]"+ }`}+ >+ <Bot size={13} strokeWidth={1.7} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-[12px] font-medium text-[var(--foreground)]">+ {option.model_name || option.model}+ </span>+ {option.is_active_default && (+ <span className="shrink-0 rounded-full bg-[var(--muted)] px-1.5 py-px text-[9px] font-semibold uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Default")}+ </span>+ )}+ </div>+ <div className="mt-0.5 truncate text-[10px] text-[var(--muted-foreground)]">+ {option.profile_name} | {providerLabel(option)}+ {contextWindow ? ` | ${contextWindow}` : ""}+ </div>+ </div>+ {selected && (+ <Check+ size={14}+ strokeWidth={2}+ className="shrink-0 text-[var(--primary)]"+ />+ )}+ </button>+ );+ })}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/web/components/space/NotebooksSection.tsx b/web/components/space/NotebooksSection.tsxindex 73cb165bf..686fa70a2 100644--- a/web/components/space/NotebooksSection.tsx+++ b/web/components/space/NotebooksSection.tsx@@ -287,16 +287,16 @@ export default function NotebooksSection() {</div><div className="grid gap-5 xl:grid-cols-[280px_minmax(0,1fr)]">- <div className="xl:sticky xl:top-8 xl:max-h-[calc(100vh-12rem)] space-y-3 overflow-y-auto pr-1">+ <div className="xl:sticky xl:top-8 xl:max-h-[calc(100vh-12rem)] space-y-2 overflow-y-auto pr-1">{notebooks.map((notebook) => {const active = selectedId === notebook.id;return (<divkey={notebook.id}- className={`group relative w-full rounded-xl border p-4 text-left transition-all ${+ className={`group relative w-full rounded-xl border p-3.5 text-left transition-all ${active- ? "border-[var(--primary)]/40 bg-[var(--primary)]/8 shadow-sm"- : "border-[var(--border)] bg-[var(--background)] hover:border-[var(--foreground)]/15 hover:bg-[var(--muted)]/30"+ ? "border-[var(--primary)]/40 bg-[var(--primary)]/[0.08] shadow-sm"+ : "border-[var(--border)] bg-[var(--background)] hover:border-[var(--foreground)]/20 hover:bg-[var(--muted)]/30"}`}><button@@ -304,27 +304,29 @@ export default function NotebooksSection() {onClick={() => void loadDetail(notebook.id)}className="block w-full text-left">- <div className="flex items-start gap-3">+ <div className="flex items-start gap-2.5"><div- className="mt-1 h-3 w-3 rounded-full"+ className="mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full ring-2 ring-[var(--background)]"style={{backgroundColor: notebook.color || "var(--primary)",}}/><div className="min-w-0 flex-1">- <div className="text-[14px] font-semibold text-[var(--foreground)]">+ <div className="truncate text-[13.5px] font-semibold text-[var(--foreground)]">{notebook.name}</div>- {notebook.description && (- <p className="mt-1 line-clamp-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">- {notebook.description}- </p>- )}- <div className="mt-3 flex items-center justify-between text-[11px] text-[var(--muted-foreground)]">+ <p className="mt-0.5 line-clamp-1 min-h-[1.1em] text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {notebook.description || (+ <span className="italic text-[var(--muted-foreground)]/60">+ {t("No description.")}+ </span>+ )}+ </p>+ <div className="mt-2 flex items-center justify-between gap-2 text-[10.5px] tabular-nums text-[var(--muted-foreground)]"><span>{notebook.record_count ?? 0} {t("records")}</span>- <span>+ <span className="truncate text-right">{notebook.updated_at? formatTimestamp(notebook.updated_at): ""}@@ -340,9 +342,9 @@ export default function NotebooksSection() {void handleDelete(notebook.id, notebook.name);}}title={t("Delete")}- className="absolute right-2 top-2 rounded-md p-1.5 text-[var(--muted-foreground)] opacity-0 transition-opacity hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] group-hover:opacity-100"+ className="absolute right-1.5 top-1.5 rounded-md p-1.5 text-[var(--muted-foreground)] opacity-0 transition-opacity hover:bg-[var(--destructive)]/10 hover:text-[var(--destructive)] group-hover:opacity-100">- <Trash2 size={13} />+ <Trash2 size={12} /></button></div>);diff --git a/web/components/space/QuestionBankSection.tsx b/web/components/space/QuestionBankSection.tsxindex f129e9013..85278b1d7 100644--- a/web/components/space/QuestionBankSection.tsx+++ b/web/components/space/QuestionBankSection.tsx@@ -188,7 +188,7 @@ export default function QuestionBankSection() {);return (- <div className="space-y-0">+ <div className="space-y-4"><SpaceSectionHeadericon={ClipboardList}title={t("Question Bank")}@@ -204,20 +204,22 @@ export default function QuestionBankSection() {{/* Category manager */}<div- className={`mb-4 overflow-hidden rounded-xl border transition-colors ${showCategoryManager ? "border-[var(--border)] bg-[var(--card)]" : "border-[var(--border)]/50 bg-transparent"}`}+ className={`overflow-hidden rounded-xl border transition-colors ${+ showCategoryManager+ ? "border-[var(--border)] bg-[var(--card)] shadow-sm"+ : "border-[var(--border)]/60 bg-[var(--card)]/40"+ }`}><buttononClick={() => setShowCategoryManager((v) => !v)}- className="flex w-full items-center justify-between px-4 py-2.5 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/40"+ className="flex w-full items-center justify-between px-4 py-3 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/30"><span className="flex items-center gap-2"><FolderOpen className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />{t("Manage Categories")}- {categories.length > 0 && (- <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] text-[var(--muted-foreground)]">- {categories.length}- </span>- )}+ <span className="rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] tabular-nums text-[var(--muted-foreground)]">+ {categories.length}+ </span></span><ChevronDownclassName={`h-3.5 w-3.5 text-[var(--muted-foreground)] transition-transform duration-200 ${showCategoryManager ? "rotate-180" : ""}`}@@ -225,7 +227,7 @@ export default function QuestionBankSection() {</button>{showCategoryManager && (- <div className="border-t border-[var(--border)] px-4 pb-4 pt-3">+ <div className="border-t border-[var(--border)]/70 px-4 pb-4 pt-3"><div className="space-y-1.5">{categories.map((cat) => (<div@@ -304,7 +306,7 @@ export default function QuestionBankSection() {</div>{/* Filter bar */}- <div className="mb-5 flex items-center justify-between border-b border-[var(--border)]/50 pb-3">+ <div className="flex items-center justify-between gap-3 px-1"><div className="flex items-center gap-1 overflow-x-auto">{FILTERS.map(({ mode, label }) => {const active = filter === mode && activeCategoryId === null;@@ -396,7 +398,7 @@ export default function QuestionBankSection() {return (<likey={item.id}- className={`rounded-xl border border-[var(--border)] px-5 py-4 transition-opacity ${+ className={`rounded-xl border border-[var(--border)] bg-[var(--card)] px-5 py-4 shadow-sm transition-opacity ${disabled ? "opacity-60" : ""}`}>diff --git a/web/components/space/SkillsSection.tsx b/web/components/space/SkillsSection.tsxindex bef30e9b4..9f718d141 100644--- a/web/components/space/SkillsSection.tsx+++ b/web/components/space/SkillsSection.tsx@@ -15,6 +15,7 @@ import {X,} from "lucide-react";import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";+import { isValidSkillName, slugifySkillName } from "@/lib/skill-slug";import {createSkill,createSkillTag,@@ -43,23 +44,6 @@ function normalizeTag(value: string): string {return value.trim().toLowerCase();}-/** Must match the backend regex: ^[a-z0-9][a-z0-9-]{0,63}$ */-const NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;--/**- * Convert any free-text input into a valid skill slug:- * "Socratic Math Mentor" → "socratic-math-mentor"- * "My Skill__v2" → "my-skill-v2"- */-function slugifyName(raw: string): string {- return raw- .toLowerCase()- .replace(/[\s_]+/g, "-") // spaces & underscores → hyphens- .replace(/[^a-z0-9-]/g, "") // strip anything else- .replace(/-{2,}/g, "-") // collapse repeated hyphens- .replace(/^-+/, ""); // strip leading hyphens-}-export default function SkillsSection() {const { t } = useTranslation();@@ -186,7 +170,7 @@ export default function SkillsSection() {setEditor({ ...editor, error: t("Name is required") });return;}- if (!NAME_RE.test(trimmedName)) {+ if (!isValidSkillName(trimmedName)) {setEditor({...editor,error: t(@@ -339,6 +323,9 @@ export default function SkillsSection() {),[editor?.tags, tagVocab],);+ const editorNameInvalid = Boolean(+ editor?.name && !isValidSkillName(editor.name),+ );return (<div className="space-y-6">@@ -356,7 +343,7 @@ export default function SkillsSection() {action={<buttononClick={openCreate}- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--foreground)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--background)] shadow-sm transition-opacity hover:opacity-90"+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] shadow-sm transition-opacity hover:opacity-90"><Plus size={13} strokeWidth={2} />{t("New skill")}@@ -534,7 +521,7 @@ export default function SkillsSection() {</p><buttononClick={openCreate}- className="mt-4 inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--foreground)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--background)] shadow-sm transition-opacity hover:opacity-90"+ className="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[12.5px] font-medium text-[var(--primary-foreground)] shadow-sm transition-opacity hover:opacity-90"><Plus size={13} strokeWidth={2} />{t("Create your first skill")}@@ -651,18 +638,21 @@ export default function SkillsSection() {<inputvalue={editor.name}onChange={(e) =>- setEditor({ ...editor, name: slugifyName(e.target.value) })+ setEditor({+ ...editor,+ name: slugifySkillName(e.target.value),+ })}placeholder={t("e.g. socratic-math-mentor")}className={`w-full rounded-lg border bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25 ${- editor.name && !NAME_RE.test(editor.name)+ editorNameInvalid? "border-red-400 dark:border-red-600": "border-[var(--border)]"}`}/><pclassName={`mt-1 text-[11px] transition-colors ${- editor.name && !NAME_RE.test(editor.name)+ editorNameInvalid? "text-red-500 dark:text-red-400": "text-[var(--muted-foreground)]/70"}`}diff --git a/web/components/space/SpaceMiniNav.tsx b/web/components/space/SpaceMiniNav.tsxindex 0b0fc66b7..6aca13fd8 100644--- a/web/components/space/SpaceMiniNav.tsx+++ b/web/components/space/SpaceMiniNav.tsx@@ -12,57 +12,59 @@ export default function SpaceMiniNav() {return (<aside className="flex h-full w-[224px] shrink-0 flex-col border-r border-[var(--border)] bg-[var(--card)]">- <div className="flex items-start gap-2.5 border-b border-[var(--border)]/60 px-4 pb-4 pt-5">+ <div className="flex items-center gap-2.5 border-b border-[var(--border)]/60 px-4 py-4"><spanaria-hidden- className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-[var(--border)]/70 bg-[var(--background)] text-[var(--foreground)]"+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-[var(--border)]/70 bg-[var(--background)] text-[var(--foreground)]">- <LayoutGrid size={13} strokeWidth={1.6} />+ <LayoutGrid size={14} strokeWidth={1.7} /></span><div className="min-w-0">- <h1 className="text-[14.5px] font-semibold leading-tight tracking-tight text-[var(--foreground)]">+ <h1 className="text-[15px] font-semibold leading-tight tracking-tight text-[var(--foreground)]">{t("Space")}</h1>- <p className="mt-0.5 text-[11px] leading-relaxed text-[var(--muted-foreground)]">- {t(- "Your personal library of conversations, notebooks, questions, playbooks, and memory.",- )}+ <p className="mt-0.5 line-clamp-1 text-[10.5px] leading-snug text-[var(--muted-foreground)]/80">+ {t("Your personal learning library.")}</p></div></div>- <nav className="flex-1 space-y-1 px-2 py-3">+ <nav className="flex-1 space-y-0.5 px-2 py-3">{SPACE_ITEMS.map(({ href, label, description, icon: Icon }) => {const active = pathname.startsWith(href);return (<Linkkey={href}href={href}- className={`group block rounded-xl px-2.5 py-2 transition-colors ${+ title={t(description)}+ className={`group flex h-12 items-center gap-2.5 rounded-lg px-2.5 transition-colors ${active- ? "bg-[var(--background)]/70 text-[var(--foreground)] shadow-sm ring-1 ring-[var(--border)]/80"+ ? "bg-[var(--muted)]/60 text-[var(--foreground)]": "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40 hover:text-[var(--foreground)]"}`}>- <div className="flex items-start gap-2.5">+ <span+ className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border transition-colors ${+ active+ ? "border-[var(--border)] bg-[var(--card)] text-[var(--foreground)] shadow-sm"+ : "border-[var(--border)]/50 bg-[var(--background)]/40 text-[var(--muted-foreground)] group-hover:border-[var(--border)]/80 group-hover:text-[var(--foreground)]"+ }`}+ >+ <Icon size={13} strokeWidth={active ? 1.9 : 1.6} />+ </span>+ <span+ className={`min-w-0 flex-1 truncate text-[13px] leading-tight tracking-tight ${+ active ? "font-semibold" : "font-medium"+ }`}+ >+ {t(label)}+ </span>+ {active && (<span- className={`mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg border transition-colors ${- active- ? "border-[var(--border)] bg-[var(--card)] text-[var(--foreground)]"- : "border-[var(--border)]/50 bg-[var(--background)]/40 text-[var(--muted-foreground)] group-hover:border-[var(--border)]/80 group-hover:text-[var(--foreground)]"- }`}- >- <Icon size={12} strokeWidth={active ? 1.9 : 1.5} />- </span>- <div className="min-w-0">- <div className="text-[12.5px] font-medium leading-tight tracking-tight">- {t(label)}- </div>- <p className="mt-0.5 line-clamp-2 text-[10.5px] leading-snug text-[var(--muted-foreground)]/80">- {t(description)}- </p>- </div>- </div>+ aria-hidden+ className="h-4 w-[2px] shrink-0 rounded-full bg-[var(--foreground)]/60"+ />+ )}</Link>);})}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex 378eddf7c..4de77e30e 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -17,7 +17,7 @@ import {readStoredLanguage,writeStoredActiveSessionId,} from "@/context/app-shell-storage";-import type { StreamEvent, ChatMessage } from "@/lib/unified-ws";+import type { StreamEvent, ChatMessage, LLMSelection } from "@/lib/unified-ws";import { UnifiedWSClient } from "@/lib/unified-ws";import { getSession, type SessionMessage } from "@/lib/session-api";import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";@@ -67,6 +67,7 @@ export interface ChatState {enabledTools: string[];activeCapability: string | null;knowledgeBases: string[];+ llmSelection: LLMSelection | null;messages: MessageItem[];isStreaming: boolean;currentStage: string;@@ -107,6 +108,7 @@ export interface MessageRequestSnapshot {bookReferences?: BookReferencePayload[];skills?: string[];memoryReferences?: MemoryReferencePayload;+ llmSelection?: LLMSelection | null;}export interface MessageItem {@@ -136,6 +138,7 @@ type Action =| { type: "SET_TOOLS"; tools: string[] }| { type: "SET_CAPABILITY"; cap: string | null }| { type: "SET_KB"; kbs: string[] }+ | { type: "SET_LLM_SELECTION"; selection: LLMSelection | null }| { type: "SET_LANGUAGE"; lang: string }| {type: "ADD_USER_MSG";@@ -171,6 +174,7 @@ type Action =tools?: string[];capability?: string | null;knowledgeBases?: string[];+ llmSelection?: LLMSelection | null;language?: string;}| { type: "NEW_SESSION"; key: string };@@ -185,6 +189,7 @@ function createSessionEntry(enabledTools: [],activeCapability: null,knowledgeBases: [],+ llmSelection: null,messages: [],isStreaming: false,currentStage: "",@@ -237,6 +242,11 @@ function reducer(state: ProviderState, action: Action): ProviderState {...session,knowledgeBases: action.kbs,}));+ case "SET_LLM_SELECTION":+ return updateSelectedSession(state, (session) => ({+ ...session,+ llmSelection: action.selection,+ }));case "SET_LANGUAGE":return updateSelectedSession(state, (session) => ({...session,@@ -450,6 +460,10 @@ function reducer(state: ProviderState, action: Action): ProviderState {? action.capability: existing.activeCapability,knowledgeBases: action.knowledgeBases ?? existing.knowledgeBases,+ llmSelection:+ action.llmSelection !== undefined+ ? action.llmSelection+ : existing.llmSelection,messages: action.messages,isStreaming: (action.status || "idle") === "running",currentStage: "",@@ -497,6 +511,7 @@ interface ChatContextValue {setTools: (tools: string[]) => void;setCapability: (cap: string | null) => void;setKBs: (kbs: string[]) => void;+ setLLMSelection: (selection: LLMSelection | null) => void;setLanguage: (lang: string) => void;sendMessage: (content: string,@@ -550,6 +565,17 @@ function asStringArray(value: unknown): string[] {: [];}+function asLLMSelection(value: unknown): LLMSelection | null {+ const record = asRecord(value);+ const profileId =+ typeof record?.profile_id === "string" ? record.profile_id.trim() : "";+ const modelId =+ typeof record?.model_id === "string" ? record.model_id.trim() : "";+ return profileId && modelId+ ? { profile_id: profileId, model_id: modelId }+ : null;+}+function asMemoryReferences(value: unknown): MemoryReferencePayload {return asStringArray(value).filter((item): item is "summary" | "profile" =>@@ -612,6 +638,7 @@ function hydrateRequestSnapshot(const skills = asStringArray(stored.skills);const memoryReferences = asMemoryReferences(stored.memoryReferences);const bookReferences = normalizeBookReferences(stored.bookReferences);+ const llmSelection = asLLMSelection(stored.llmSelection);if (config && Object.keys(config).length) snapshot.config = config;if (notebookReferences.length)@@ -623,6 +650,7 @@ function hydrateRequestSnapshot(if (bookReferences.length) snapshot.bookReferences = bookReferences;if (skills.length) snapshot.skills = skills;if (memoryReferences.length) snapshot.memoryReferences = memoryReferences;+ if (llmSelection) snapshot.llmSelection = llmSelection;return snapshot;}@@ -866,6 +894,7 @@ export function UnifiedChatProvider({knowledgeBases: Array.isArray(session.preferences?.knowledge_bases)? session.preferences.knowledge_bases: [],+ llmSelection: asLLMSelection(session.preferences?.llm_selection),// The Settings language is global UI state. Historical sessions may// have stale persisted preferences, so new turns follow the current// app language rather than the language saved when the session began.@@ -993,6 +1022,10 @@ export function UnifiedChatProvider({replaySnapshot?.enabledTools ?? session.enabledTools;const effectiveKnowledgeBases =replaySnapshot?.knowledgeBases ?? session.knowledgeBases;+ const effectiveLLMSelection =+ replaySnapshot && "llmSelection" in replaySnapshot+ ? (replaySnapshot.llmSelection ?? null)+ : session.llmSelection;const effectiveLanguage =replaySnapshot?.language ?? readStoredLanguage();const researchSources = Array.isArray(config?.sources)@@ -1033,6 +1066,9 @@ export function UnifiedChatProvider({...(effectiveMemoryReferences?.length? { memoryReferences: [...effectiveMemoryReferences] }: {}),+ ...(effectiveLLMSelection+ ? { llmSelection: effectiveLLMSelection }+ : {}),};if (options?.displayUserMessage !== false) {dispatch({@@ -1076,6 +1112,9 @@ export function UnifiedChatProvider({...(effectiveMemoryReferences?.length? { memory_references: effectiveMemoryReferences }: {}),+ ...(effectiveLLMSelection+ ? { llm_selection: effectiveLLMSelection }+ : {}),...(effectiveConfig && Object.keys(effectiveConfig).length > 0? { config: effectiveConfig }: {}),@@ -1138,6 +1177,7 @@ export function UnifiedChatProvider({enabledTools: current.enabledTools,activeCapability: current.activeCapability,knowledgeBases: current.knowledgeBases,+ llmSelection: current.llmSelection,messages: current.messages,isStreaming: current.isStreaming,currentStage: current.currentStage,@@ -1171,6 +1211,10 @@ export function UnifiedChatProvider({dispatch({ type: "SET_KB", kbs });}, []);+ const setLLMSelection = useCallback((selection: LLMSelection | null) => {+ dispatch({ type: "SET_LLM_SELECTION", selection });+ }, []);+const setLanguage = useCallback((lang: string) => {dispatch({ type: "SET_LANGUAGE", lang });}, []);@@ -1184,6 +1228,7 @@ export function UnifiedChatProvider({setTools,setCapability,setKBs,+ setLLMSelection,setLanguage,sendMessage,cancelStreamingTurn,diff --git a/web/lib/llm-options.ts b/web/lib/llm-options.tsnew file mode 100644index 000000000..d5f1c4dbf--- /dev/null+++ b/web/lib/llm-options.ts@@ -0,0 +1,42 @@+import { apiUrl } from "@/lib/api";+import type { LLMSelection } from "@/lib/unified-ws";++export interface LLMOption extends LLMSelection {+ profile_name: string;+ model_name: string;+ model: string;+ provider: string;+ context_window?: number;+ is_active_default: boolean;+}++export interface LLMOptionsResponse {+ active: LLMSelection | null;+ options: LLMOption[];+}++export function llmSelectionKey(selection: LLMSelection | null | undefined) {+ if (!selection?.profile_id || !selection.model_id) return "";+ return `${selection.profile_id}:${selection.model_id}`;+}++export function sameLLMSelection(+ a: LLMSelection | null | undefined,+ b: LLMSelection | null | undefined,+) {+ return llmSelectionKey(a) === llmSelectionKey(b);+}++export async function listLLMOptions(): Promise<LLMOptionsResponse> {+ const response = await fetch(apiUrl("/api/v1/settings/llm-options"), {+ cache: "no-store",+ });+ if (!response.ok) {+ throw new Error(`Failed to load LLM options: ${response.status}`);+ }+ const data = (await response.json()) as LLMOptionsResponse;+ return {+ active: data.active ?? null,+ options: Array.isArray(data.options) ? data.options : [],+ };+}diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 4f671988d..b5d4e1801 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -1,4 +1,4 @@-import type { StreamEvent } from "@/lib/unified-ws";+import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";import { apiUrl } from "@/lib/api";import { invalidateClientCache, withClientCache } from "@/lib/client-cache";@@ -43,6 +43,7 @@ export interface SessionSummary {tools?: string[];knowledge_bases?: string[];language?: string;+ llm_selection?: LLMSelection | null;};}@@ -80,6 +81,7 @@ export interface SessionDetail {tools?: string[];knowledge_bases?: string[];language?: string;+ llm_selection?: LLMSelection | null;};messages: SessionMessage[];active_turns?: ActiveTurnSummary[];diff --git a/web/lib/skill-slug.ts b/web/lib/skill-slug.tsnew file mode 100644index 000000000..1346b98e1--- /dev/null+++ b/web/lib/skill-slug.ts@@ -0,0 +1,15 @@+export const SKILL_NAME_PATTERN = "^[a-z0-9][a-z0-9-]{0,63}$";+export const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;++export function slugifySkillName(raw: string): string {+ return raw+ .toLowerCase()+ .replace(/[\s_]+/g, "-")+ .replace(/[^a-z0-9-]/g, "")+ .replace(/-{2,}/g, "-")+ .replace(/^-+/, "");+}++export function isValidSkillName(value: string): boolean {+ return SKILL_NAME_RE.test(value);+}diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.tsindex 33845562e..8c2c4d28e 100644--- a/web/lib/unified-ws.ts+++ b/web/lib/unified-ws.ts@@ -41,6 +41,11 @@ export interface StreamEvent {timestamp: number;}+export interface LLMSelection {+ profile_id: string;+ model_id: string;+}+// ---- Client message ----export interface StartTurnMessage {@@ -70,6 +75,7 @@ export interface StartTurnMessage {page_ids: string[];}[];skills?: string[];+ llm_selection?: LLMSelection | null;}export interface SubscribeTurnMessage {diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 5d85a6809..58579d53e 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -47,6 +47,16 @@"No KB": "No KB","Enable Knowledge Base source first": "Enable Knowledge Base source first","Tools": "Tools",+ "Loading models": "Loading models",+ "Models unavailable": "Models unavailable",+ "Select model": "Select model",+ "Choose model": "Choose model",+ "Choose a model": "Choose a model",+ "Could not load models": "Could not load models",+ "No configured models": "No configured models",+ "Applies to the next message in this chat": "Applies to the next message in this chat",+ "System default": "System default",+ "Use the active default model from Settings": "Use the active default model from Settings","Send": "Send","Drop images here": "Drop images here","Drop files here": "Drop files here",@@ -782,6 +792,11 @@"Define the bot's personality, values, and communication style in markdown...": "Define the bot's personality, values, and communication style in markdown...","Pick a soul from the library above, or write your own. Manage the library in the Souls tab.": "Pick a soul from the library above, or write your own. Manage the library in the Souls tab.","Uses default model if empty": "Uses default model if empty",+ "Applies to this TutorBot": "Applies to this TutorBot",+ "Choose a configured Settings model, or keep the system default.": "Choose a configured Settings model, or keep the system default.",+ "Model saved": "Model saved",+ "Failed to save model": "Failed to save model",+ "Selected model": "Selected model","Create & Start": "Create & Start","No TutorBots yet": "No TutorBots yet","Create your first TutorBot to get started.": "Create your first TutorBot to get started.",@@ -1198,9 +1213,11 @@"No description.": "No description.","Markdown body": "Markdown body","Lowercase letters, digits, and hyphens only.": "Lowercase letters, digits, and hyphens only.",+ "Name must use only lowercase letters, digits, and hyphens, and must start with a letter or digit.": "Name must use only lowercase letters, digits, and hyphens, and must start with a letter or digit.","Short summary used by Auto mode": "Short summary used by Auto mode","YAML frontmatter is optional and is auto-managed for name, description, and tags.": "YAML frontmatter is optional and is auto-managed for name, description, and tags.","e.g. teacher": "e.g. teacher",+ "e.g. socratic-math-mentor": "e.g. socratic-math-mentor","Name is required": "Name is required","Delete skill \"{{name}}\"?": "Delete skill \"{{name}}\"?","Tags": "Tags",@@ -1225,6 +1242,7 @@"Long-form memory the assistant carries across sessions — your running summary and learner profile.": "Long-form memory the assistant carries across sessions — your running summary and learner profile.","Long-form memory the assistant carries across sessions.": "Long-form memory the assistant carries across sessions.","Your personal library of notebooks, questions, playbooks, and memory.": "Your personal library of notebooks, questions, playbooks, and memory.",+ "Your personal learning library.": "Your personal learning library.","Not updated yet": "Not updated yet","Running summary of the learning journey. Auto-updated after conversations.": "Running summary of the learning journey. Auto-updated after conversations.","User identity, preferences, and knowledge levels. Auto-updated after conversations.": "User identity, preferences, and knowledge levels. Auto-updated after conversations.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 30d80988b..4dd09574d 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -47,6 +47,16 @@"No KB": "无知识库","Enable Knowledge Base source first": "请先启用知识库来源","Tools": "工具",+ "Loading models": "模型加载中",+ "Models unavailable": "模型不可用",+ "Select model": "选择模型",+ "Choose model": "选择模型",+ "Choose a model": "请选择模型",+ "Could not load models": "无法加载模型",+ "No configured models": "暂无已配置模型",+ "Applies to the next message in this chat": "应用于本聊天的下一条消息",+ "System default": "系统默认",+ "Use the active default model from Settings": "使用设置中的当前默认模型","Send": "发送","Drop images here": "将图片拖放到此处","Drop files here": "拖拽文件到此处",@@ -715,6 +725,11 @@"Define the bot's personality, values, and communication style in markdown...": "用 Markdown 定义机器人的性格、价值观和沟通风格…","Pick a soul from the library above, or write your own. Manage the library in the Souls tab.": "从上方的灵魂库中选择,或自行编写。可在「灵魂」标签页管理灵魂库。","Uses default model if empty": "留空则使用默认模型",+ "Applies to this TutorBot": "应用于这个 TutorBot",+ "Choose a configured Settings model, or keep the system default.": "选择设置中已配置的模型,或保留系统默认。",+ "Model saved": "模型已保存",+ "Failed to save model": "模型保存失败",+ "Selected model": "已选择模型","Create & Start": "创建并启动","No TutorBots yet": "暂无 TutorBot","Create your first TutorBot to get started.": "创建你的第一个 TutorBot 开始使用。",@@ -1198,9 +1213,11 @@"No description.": "暂无描述。","Markdown body": "Markdown 正文","Lowercase letters, digits, and hyphens only.": "仅支持小写字母、数字与连字符。",+ "Name must use only lowercase letters, digits, and hyphens, and must start with a letter or digit.": "名称只能包含小写字母、数字和连字符,并且必须以字母或数字开头。","Short summary used by Auto mode": "Auto 模式使用的简短说明","YAML frontmatter is optional and is auto-managed for name, description, and tags.": "YAML frontmatter 可选,名称、描述与标签会自动维护。","e.g. teacher": "例如:teacher",+ "e.g. socratic-math-mentor": "例如:socratic-math-mentor","Name is required": "请填写名称","Delete skill \"{{name}}\"?": "确定删除技能 “{{name}}” 吗?","Tags": "标签",@@ -1225,6 +1242,7 @@"Long-form memory the assistant carries across sessions — your running summary and learner profile.": "助手在多次会话之间保留的长时记忆——包含你的学习摘要与学习者画像。","Long-form memory the assistant carries across sessions.": "助手在多次会话之间保留的长时记忆。","Your personal library of notebooks, questions, playbooks, and memory.": "你的个人空间:笔记本、题库、技能与长时记忆。",+ "Your personal learning library.": "你的个人学习空间。","Not updated yet": "尚未更新","Running summary of the learning journey. Auto-updated after conversations.": "学习旅程的实时摘要,会在对话结束后自动更新。","User identity, preferences, and knowledge levels. Auto-updated after conversations.": "用户身份、偏好与知识水平,会在对话结束后自动更新。",diff --git a/web/tests/skill-slug.test.ts b/web/tests/skill-slug.test.tsnew file mode 100644index 000000000..d6d279ca0--- /dev/null+++ b/web/tests/skill-slug.test.ts@@ -0,0 +1,30 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ isValidSkillName,+ SKILL_NAME_PATTERN,+ slugifySkillName,+} from "../lib/skill-slug";++test("slugifySkillName normalizes common free-text names", () => {+ assert.equal(slugifySkillName("Socratic Math Mentor"), "socratic-math-mentor");+ assert.equal(slugifySkillName("My Skill__v2"), "my-skill-v2");+ assert.equal(slugifySkillName("___Tutor!! 2026"), "tutor-2026");+});++test("slugifySkillName preserves valid hyphenated names", () => {+ assert.equal(slugifySkillName("proof-checker"), "proof-checker");+ assert.equal(slugifySkillName("math-v2"), "math-v2");+});++test("isValidSkillName mirrors backend skill name contract", () => {+ assert.equal(SKILL_NAME_PATTERN, "^[a-z0-9][a-z0-9-]{0,63}$");+ assert.equal(isValidSkillName("socratic-math-mentor"), true);+ assert.equal(isValidSkillName("a".repeat(64)), true);+ assert.equal(isValidSkillName(""), false);+ assert.equal(isValidSkillName("-teacher"), false);+ assert.equal(isValidSkillName("Teacher"), false);+ assert.equal(isValidSkillName("math_tutor"), false);+ assert.equal(isValidSkillName("a".repeat(65)), false);+});