DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(settings): connections layer + per-task model pinning
Bingxi Zhao (Frank)a9f67eb3aaa6
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 5d8acddb0..7984c0848 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -580,6 +580,99 @@ def _provider_choices() -> dict[str, list[dict[str, Any]]]:}+def _match_service_provider(+ provider: str,+ table: dict[str, Any],+) -> tuple[str, Any] | None:+ """Find *provider*'s entry in one service's provider table.++ Vendors are not named identically across tables — the LLM registry calls+ Alibaba's endpoint ``dashscope`` while the embedding table calls it+ ``aliyun`` — so an exact key miss falls back to the spec's own keywords+ rather than to a second hand-maintained name map.+ """+ if provider in table:+ return provider, table[provider]+ for name, spec in table.items():+ if provider in getattr(spec, "keywords", ()):+ return name, spec+ return None+++def _connection_targets() -> list[dict[str, Any]]:+ """Which services one vendor credential can configure, and with what.++ The connection UI needs to answer "if I paste an OpenRouter key here, what+ does it get me?" — so this joins the six per-service provider tables on the+ vendor and reports, per service, the provider value and the prefills a+ profile created from that connection should start with. Derived rather than+ duplicated: adding a vendor to a service table is enough to make it+ connectable, and the web app never keeps a second copy of the tables.+ """+ from deeptutor.services.config.provider_runtime import (+ EMBEDDING_PROVIDERS,+ IMAGEGEN_PROVIDERS,+ STT_PROVIDERS,+ TTS_PROVIDERS,+ VIDEOGEN_PROVIDERS,+ )+ from deeptutor.services.provider_registry import PROVIDERS++ service_tables: dict[str, dict[str, Any]] = {+ "embedding": {k: v for k, v in EMBEDDING_PROVIDERS.items() if k != "custom_openai_sdk"},+ "tts": TTS_PROVIDERS,+ "stt": STT_PROVIDERS,+ "imagegen": IMAGEGEN_PROVIDERS,+ "videogen": VIDEOGEN_PROVIDERS,+ }++ targets: list[dict[str, Any]] = []+ for spec in PROVIDERS:+ # OAuth vendors sign in through their own flow; there is no key to+ # share, so offering them here would promise something untrue.+ if spec.is_oauth:+ continue+ services: dict[str, dict[str, Any]] = {+ "llm": {+ "provider": spec.name,+ "base_url": spec.default_api_base,+ "default_model": "",+ }+ }+ for service_name, table in service_tables.items():+ match = _match_service_provider(spec.name, table)+ if match is None:+ continue+ name, service_spec = match+ entry: dict[str, Any] = {+ "provider": name,+ "base_url": service_spec.default_api_base,+ "default_model": service_spec.default_model,+ }+ if service_name == "embedding":+ entry["default_dim"] = (+ str(service_spec.default_dim) if service_spec.default_dim else ""+ )+ if service_name == "tts":+ entry["default_voice"] = service_spec.default_voice+ services[service_name] = entry+ targets.append(+ {+ "provider": spec.name,+ "label": (+ "Custom (OpenAI API)"+ if spec.name == "custom"+ else "Custom (Anthropic API)"+ if spec.name == "custom_anthropic"+ else spec.label+ ),+ "default_base_url": spec.default_api_base,+ "services": services,+ }+ )+ return sorted(targets, key=lambda item: str(item["label"]).lower())++def _api_base_source(system: dict[str, Any]) -> str:if system.get("next_public_api_base_external"):return "next_public_api_base_external"@@ -643,6 +736,7 @@ async def get_settings():"ui": load_ui_settings(),"catalog": redact_catalog_secrets(get_model_catalog_service().load()),"providers": _provider_choices(),+ "connection_targets": _connection_targets(),}diff --git a/deeptutor/services/config/model_catalog.py b/deeptutor/services/config/model_catalog.pyindex dec9619f9..2314f979c 100644--- a/deeptutor/services/config/model_catalog.py+++ b/deeptutor/services/config/model_catalog.py@@ -12,7 +12,10 @@ from uuid import uuid4from deeptutor.services.path_service import get_path_service-from .embedding_endpoint import normalize_embedding_endpoint_for_display+from .embedding_endpoint import (+ is_gemini_native_embedding_endpoint,+ normalize_embedding_endpoint_for_display,+)# Fallback only — frozen at admin scope at import time. Production code should# enter through ``get_model_catalog_service()`` so the path is resolved from the@@ -53,6 +56,9 @@ def redact_catalog_secrets(catalog: dict[str, Any]) -> dict[str, Any]:"""Return an API-safe catalog without mutating stored configuration."""redacted = deepcopy(catalog)+ for connection in redacted.get("connections", []) or []:+ if isinstance(connection, dict):+ _redact_profile(connection)for service in redacted.get("services", {}).values():if not isinstance(service, dict):continue@@ -89,6 +95,17 @@ def restore_catalog_secrets("""Replace secret placeholders with stored values from the same profile."""restored = deepcopy(proposed_catalog)+ current_connections = {+ connection.get("id"): connection+ for connection in current_catalog.get("connections", []) or []+ if isinstance(connection, dict) and connection.get("id")+ }+ for connection in restored.get("connections", []) or []:+ if not isinstance(connection, dict):+ continue+ current_connection = current_connections.get(connection.get("id"))+ if current_connection is not None:+ _restore_profile_secrets(connection, current_connection)current_services = current_catalog.get("services", {})for service_name, proposed_service in restored.get("services", {}).items():if not isinstance(proposed_service, dict):@@ -123,9 +140,37 @@ def _search_shell() -> dict[str, Any]:}+# LLM work the product does on the user's behalf rather than in a turn they+# started: naming a conversation, proposing the three lines under the home+# composer. Both are short, frequent and latency-visible, so they are worth+# pointing at a small fast model — but only when the user says so. An entry+# missing (or with blank ids) means "inherit whatever the chat is using".+LLM_TASKS: tuple[str, ...] = ("session_title", "starters")+++# Services whose profiles a connection can supply credentials to. ``search``+# is excluded: its providers are a different namespace (Brave, Tavily, ...)+# that happens to overlap by name with a handful of model vendors only.+CONNECTABLE_SERVICES: tuple[str, ...] = ("llm", "embedding", "tts", "stt", "imagegen", "videogen")++# Where a connection's API base has to grow a path before a service's adapter+# can post to it. Voice/generation adapters append their own path to an API+# base; embedding adapters use the configured URL verbatim.+_CONNECTION_BASE_SUFFIX: dict[str, str] = {"embedding": "/embeddings"}++# Credential fields a linked profile inherits from its connection. base_url is+# handled separately because it is per-service (see _CONNECTION_BASE_SUFFIX).+_CONNECTION_CREDENTIAL_FIELDS: tuple[str, ...] = ("api_key", "api_version", "extra_headers")+++def _connection_base_url_for(service_name: str, connection_base: str) -> str:+ return connection_base.rstrip("/") + _CONNECTION_BASE_SUFFIX.get(service_name, "")++def _default_catalog() -> dict[str, Any]:return {"version": 1,+ "connections": [],"services": {"llm": _service_shell(),"embedding": _service_shell(),@@ -212,9 +257,111 @@ class ModelCatalogService:current = self.save(catalog or self.load())return {"catalog_path": str(self.path), "services": list(current.get("services", {}))}+ def _normalize_llm_tasks(self, catalog: dict[str, Any]) -> bool:+ """Keep task-model pointers honest: unknown targets fall back to inherit."""+ service = catalog.get("services", {}).get("llm", {})+ if not isinstance(service, dict):+ return False+ if "tasks" not in service:+ return False+ raw = service["tasks"]+ if not isinstance(raw, dict):+ service["tasks"] = {}+ return True+ available = {+ str(profile.get("id")): {+ str(model.get("id")) for model in profile.get("models", []) or []+ }+ for profile in service.get("profiles", []) or []+ if isinstance(profile, dict)+ }+ changed = False+ for task in list(raw):+ if task not in LLM_TASKS:+ raw.pop(task)+ changed = True+ continue+ entry = raw[task]+ if not isinstance(entry, dict):+ raw.pop(task)+ changed = True+ continue+ profile_id = str(entry.get("profile_id") or "")+ model_id = str(entry.get("model_id") or "")+ # A profile or model deleted out from under a task pointer must not+ # strand it: an unresolvable task silently reverts to inheriting.+ if not profile_id or model_id not in available.get(profile_id, set()):+ raw.pop(task)+ changed = True+ return changed++ def _normalize_connections(self, catalog: dict[str, Any]) -> dict[str, dict[str, Any]]:+ """Fill in connection defaults and return them keyed by id."""+ raw = catalog.get("connections")+ if not isinstance(raw, list):+ raw = []+ catalog["connections"] = raw+ connections: dict[str, dict[str, Any]] = {}+ for connection in raw:+ if not isinstance(connection, dict):+ continue+ connection.setdefault("id", f"conn-{uuid4().hex[:8]}")+ connection.setdefault("provider", "")+ connection.setdefault("name", connection.get("provider") or "Untitled Connection")+ connection.setdefault("api_key", "")+ connection.setdefault("base_url", "")+ connection.setdefault("api_version", "")+ connection.setdefault("extra_headers", {})+ connections[str(connection["id"])] = connection+ return connections++ def _apply_connection(+ self,+ profile: dict[str, Any],+ service_name: str,+ connections: dict[str, dict[str, Any]],+ ) -> bool:+ """Push a linked connection's credentials down into *profile*.++ Mirroring on write rather than resolving on read is deliberate: every+ consumer of the catalog (runtime resolvers, the test runner, personal+ model merging) keeps reading self-contained profiles exactly as it did+ before connections existed, so linking cannot change how a profile+ resolves — only where its credentials were typed.+ """+ connection_id = str(profile.get("connection_id") or "")+ if not connection_id:+ return False+ connection = connections.get(connection_id)+ if connection is None:+ # The connection was deleted: unlink rather than wipe, so the+ # profile keeps working with the credentials it already holds.+ profile.pop("connection_id", None)+ return True+ changed = False+ for field in _CONNECTION_CREDENTIAL_FIELDS:+ value = deepcopy(connection.get(field))+ if profile.get(field) != value:+ profile[field] = value+ changed = True+ base_url = str(connection.get("base_url") or "").strip()+ if base_url:+ # Gemini's native embedding endpoint carries the model in its path,+ # so it is not derivable from an API base — leave those alone.+ if service_name == "embedding" and is_gemini_native_embedding_endpoint(+ profile.get("base_url")+ ):+ return changed+ resolved = _connection_base_url_for(service_name, base_url)+ if profile.get("base_url") != resolved:+ profile["base_url"] = resolved+ changed = True+ return changed+def _normalize(self, catalog: dict[str, Any]) -> bool:services = catalog.setdefault("services", {})changed = False+ connections = self._normalize_connections(catalog)services.setdefault("llm", _service_shell())services.setdefault("embedding", _service_shell())services.setdefault("search", _search_shell())@@ -227,6 +374,10 @@ class ModelCatalogService:profiles = service.setdefault("profiles", [])for profile in profiles:profile.setdefault("id", f"{service_name}-profile-{uuid4().hex[:8]}")+ if service_name in CONNECTABLE_SERVICES and self._apply_connection(+ profile, service_name, connections+ ):+ changed = Trueprofile.setdefault("name", "Untitled Profile")profile.setdefault("api_version", "")profile.setdefault("base_url", "")@@ -295,6 +446,8 @@ class ModelCatalogService:if models and service.get("active_model_id") not in model_ids:service["active_model_id"] = models[0]["id"]changed = True+ if self._normalize_llm_tasks(catalog):+ changed = Truereturn changeddef get_active_profile(@@ -340,6 +493,8 @@ def get_model_catalog_service() -> ModelCatalogService:__all__ = ["CATALOG_PATH","CATALOG_SECRET_MASK",+ "CONNECTABLE_SERVICES",+ "LLM_TASKS","ModelCatalogService","get_model_catalog_service","redact_catalog_secrets",diff --git a/deeptutor/services/model_selection/tasks.py b/deeptutor/services/model_selection/tasks.pynew file mode 100644index 000000000..41b6bfb43--- /dev/null+++ b/deeptutor/services/model_selection/tasks.py@@ -0,0 +1,101 @@+"""Task models — the LLM behind work the product does on its own.++Two calls happen without anyone asking for them: naming a conversation once it+has its first exchange, and proposing the three starting points under the home+composer. Both are short, both are frequent, and neither benefits from the+model a learner picked for their actual reasoning — a small fast model writes a+four-word title just as well and costs a fraction as much.++So each of these is a *task* that can be pointed at its own configured model.+Pointing is optional and that matters more than the feature: with nothing set+(the state every existing install is in) the scope below is a no-op, and both+call sites keep resolving exactly the LLM they resolved before — for the title+that is the model the turn itself is running on, for the starters the active+default. Nothing changes until someone chooses to change it.++Failure inherits too. A task pointing at a deleted profile, a catalog that will+not load, a malformed entry — none of that is worth failing a title over, so+every error path here falls back to the ambient config rather than raising.+"""++from __future__ import annotations++from collections.abc import Iterator+from contextlib import contextmanager+import logging+from typing import Any++from deeptutor.services.config.model_catalog import LLM_TASKS, get_model_catalog_service+from deeptutor.services.llm.config import LLMConfig++from .llm import LLMSelection+from .runtime import activate_llm_selection, reset_llm_selection++logger = logging.getLogger(__name__)++TASK_SESSION_TITLE = "session_title"+TASK_STARTERS = "starters"+++def _llm_tasks(catalog: dict[str, Any]) -> dict[str, Any]:+ services = catalog.get("services")+ if not isinstance(services, dict):+ return {}+ llm = services.get("llm")+ if not isinstance(llm, dict):+ return {}+ tasks = llm.get("tasks")+ return tasks if isinstance(tasks, dict) else {}+++def resolve_task_selection(+ task: str,+ catalog: dict[str, Any] | None = None,+) -> LLMSelection | None:+ """Return the model a task is pinned to, or ``None`` to inherit."""+ if task not in LLM_TASKS:+ return None+ try:+ loaded = catalog if catalog is not None else get_model_catalog_service().load()+ entry = _llm_tasks(loaded).get(task)+ if not isinstance(entry, dict):+ return None+ return LLMSelection.from_payload(+ {"profile_id": entry.get("profile_id"), "model_id": entry.get("model_id")}+ )+ except Exception:+ logger.debug("Task model lookup failed for %s — inheriting", task, exc_info=True)+ return None+++@contextmanager+def task_llm_scope(task: str) -> Iterator[LLMConfig | None]:+ """Install the task's LLM for the duration of the block.++ Yields the config that was installed, or ``None`` when the task inherits —+ which callers can log but never have to branch on.+ """+ selection = resolve_task_selection(task)+ if selection is None:+ yield None+ return+ try:+ config, token = activate_llm_selection(selection)+ except Exception:+ # The pointer resolved but the profile behind it no longer works.+ # Inheriting is strictly better than not writing a title at all.+ logger.debug("Task model activation failed for %s — inheriting", task, exc_info=True)+ yield None+ return+ try:+ yield config+ finally:+ reset_llm_selection(token)+++__all__ = [+ "TASK_SESSION_TITLE",+ "TASK_STARTERS",+ "resolve_task_selection",+ "task_llm_scope",+]diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 5b673f91f..bc7379f78 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -2594,9 +2594,10 @@ class TurnRuntimeManager:Runs only when the session still carries the ``New conversation``sentinel — once a user manually renames the chat (or this method- has already filled in a title), it short-circuits. Uses the LLM- scope already active on the calling task, which is the user's- currently selected model.+ has already filled in a title), it short-circuits. Uses the model+ pinned in Settings > Task models when there is one, and otherwise+ the LLM scope already active on the calling task, which is the+ user's currently selected model."""if not session_id:return@@ -2665,7 +2666,15 @@ class TurnRuntimeManager:buf.append(c)return "".join(buf)- raw_title = await asyncio.wait_for(_collect_title(), timeout=20.0)+ from deeptutor.services.model_selection.tasks import (+ TASK_SESSION_TITLE,+ task_llm_scope,+ )++ # The scope is entered before the task is created so `wait_for`'s+ # inner task copies it; leaving it un-pinned yields a no-op.+ with task_llm_scope(TASK_SESSION_TITLE):+ raw_title = await asyncio.wait_for(_collect_title(), timeout=20.0)title = _sanitize_session_title(raw_title)except asyncio.TimeoutError:logger.debug("Title LLM call timed out — falling back")diff --git a/deeptutor/services/suggestions.py b/deeptutor/services/suggestions.pyindex 07d5ea71b..b28f859af 100644--- a/deeptutor/services/suggestions.py+++ b/deeptutor/services/suggestions.py@@ -556,16 +556,20 @@ async def _generate(language: str, material: _Material) -> SuggestionSet:try:from deeptutor.services.llm import complete-- raw = await asyncio.wait_for(- complete(- prompt=user_prompt,- system_prompt=_SYSTEM_ZH if zh else _SYSTEM_EN,- temperature=0.8, # suggestions may vary; these are not facts- max_tokens=500,- ),- timeout=_LLM_TIMEOUT,- )+ from deeptutor.services.model_selection.tasks import TASK_STARTERS, task_llm_scope++ # Pinned to its own model when Settings > Task models says so, and to+ # the active default otherwise — which is what this always did.+ with task_llm_scope(TASK_STARTERS):+ raw = await asyncio.wait_for(+ complete(+ prompt=user_prompt,+ system_prompt=_SYSTEM_ZH if zh else _SYSTEM_EN,+ temperature=0.8, # suggestions may vary; these are not facts+ max_tokens=500,+ ),+ timeout=_LLM_TIMEOUT,+ )except asyncio.TimeoutError:logger.debug("suggestions LLM call timed out")return emptydiff --git a/tests/services/config/test_catalog_connections.py b/tests/services/config/test_catalog_connections.pynew file mode 100644index 000000000..5682fff5e--- /dev/null+++ b/tests/services/config/test_catalog_connections.py@@ -0,0 +1,125 @@+"""Connections: one credential typed once, mirrored into linked profiles."""++from __future__ import annotations++from pathlib import Path+from typing import Any++from deeptutor.services.config.model_catalog import (+ CATALOG_SECRET_MASK,+ ModelCatalogService,+ redact_catalog_secrets,+ restore_catalog_secrets,+)+++def _linked_catalog(service: ModelCatalogService, **overrides: Any) -> dict[str, Any]:+ catalog = service.load()+ catalog["connections"] = [+ {+ "id": "conn-1",+ "name": "OpenRouter",+ "provider": "openrouter",+ "api_key": "sk-or-secret",+ "base_url": "https://openrouter.ai/api/v1",+ **overrides,+ }+ ]+ catalog["services"]["llm"]["profiles"] = [+ {+ "id": "llm-1",+ "name": "OpenRouter",+ "binding": "openrouter",+ "connection_id": "conn-1",+ "base_url": "",+ "api_key": "",+ "models": [{"id": "llm-model-1", "model": "anthropic/claude-sonnet-4"}],+ }+ ]+ catalog["services"]["embedding"]["profiles"] = [+ {+ "id": "emb-1",+ "name": "OpenRouter",+ "binding": "openrouter",+ "connection_id": "conn-1",+ "base_url": "",+ "api_key": "",+ "models": [{"id": "emb-model-1", "model": "text-embedding-3-large"}],+ }+ ]+ return catalog+++def test_save_mirrors_connection_credentials_into_linked_profiles(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")++ saved = service.save(_linked_catalog(service))++ llm_profile = saved["services"]["llm"]["profiles"][0]+ assert llm_profile["api_key"] == "sk-or-secret"+ assert llm_profile["base_url"] == "https://openrouter.ai/api/v1"+++def test_embedding_profiles_take_the_endpoint_path_not_the_api_base(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")++ saved = service.save(_linked_catalog(service))++ assert (+ saved["services"]["embedding"]["profiles"][0]["base_url"]+ == "https://openrouter.ai/api/v1/embeddings"+ )+++def test_blank_connection_base_url_leaves_each_profile_endpoint_alone(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ catalog = _linked_catalog(service, base_url="")+ catalog["services"]["embedding"]["profiles"][0]["base_url"] = (+ "https://api.jina.ai/v1/embeddings"+ )++ saved = service.save(catalog)++ assert (+ saved["services"]["embedding"]["profiles"][0]["base_url"]+ == "https://api.jina.ai/v1/embeddings"+ )+ assert saved["services"]["embedding"]["profiles"][0]["api_key"] == "sk-or-secret"+++def test_rotating_the_key_reaches_every_linked_profile(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ service.save(_linked_catalog(service))++ rotated = service.update(+ lambda catalog: catalog["connections"][0].update({"api_key": "sk-or-rotated"})+ )++ assert rotated["services"]["llm"]["profiles"][0]["api_key"] == "sk-or-rotated"+ assert rotated["services"]["embedding"]["profiles"][0]["api_key"] == "sk-or-rotated"+++def test_deleting_a_connection_unlinks_without_wiping_credentials(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ service.save(_linked_catalog(service))++ remaining = service.update(lambda catalog: catalog.update({"connections": []}))++ profile = remaining["services"]["llm"]["profiles"][0]+ assert "connection_id" not in profile+ # Deleting the place a key was typed must not break a working service.+ assert profile["api_key"] == "sk-or-secret"+++def test_connection_secrets_survive_a_redact_edit_restore_round_trip(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ current = service.save(_linked_catalog(service))++ redacted = redact_catalog_secrets(current)+ assert redacted["connections"][0]["api_key"] == CATALOG_SECRET_MASK++ redacted["connections"][0]["name"] = "Renamed"+ restored = restore_catalog_secrets(redacted, current)++ assert restored["connections"][0]["api_key"] == "sk-or-secret"+ assert restored["connections"][0]["name"] == "Renamed"diff --git a/tests/services/test_task_model_call_sites.py b/tests/services/test_task_model_call_sites.pynew file mode 100644index 000000000..e8c863574--- /dev/null+++ b/tests/services/test_task_model_call_sites.py@@ -0,0 +1,206 @@+"""The two task call sites actually run inside the scope they claim to.++Pinning a task model is only worth anything if the LLM call at the other end+resolves the pinned config. Both tests assert the model *observed from inside+the call*: a scope wrapped around the wrong statement, or a call site that was+never wired at all, still looks correct from the outside.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import pytest++from deeptutor.services.config import model_catalog as model_catalog_module+from deeptutor.services.config.model_catalog import ModelCatalogService+from deeptutor.services.llm.config import clear_llm_config_cache, get_llm_config+++class _FakePathService:+ def __init__(self, root: Path) -> None:+ self._root = root++ def get_settings_file(self, name: str) -> Path:+ return self._root / "settings" / f"{name}.json"+++def _pin(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, tasks: dict[str, Any]) -> None:+ """Point every catalog reader at a tmp catalog with *tasks* pinned.++ Patching the path service rather than ``get_model_catalog_service`` is+ deliberate: several modules import that function by value, so patching it+ in one place would leave the others resolving the real user's catalog.+ """+ fake = _FakePathService(tmp_path)+ monkeypatch.setattr(model_catalog_module, "get_path_service", lambda: fake)++ service = ModelCatalogService(path=fake.get_settings_file("model_catalog"))+ catalog = service.load()+ catalog["services"]["llm"]["profiles"] = [+ {+ "id": "llm-1",+ "name": "OpenAI",+ "binding": "openai",+ "base_url": "https://api.openai.com/v1",+ "api_key": "sk-test",+ "models": [+ {"id": "model-default", "model": "gpt-5"},+ {"id": "model-task", "model": "gpt-5-mini"},+ ],+ }+ ]+ catalog["services"]["llm"]["active_profile_id"] = "llm-1"+ catalog["services"]["llm"]["active_model_id"] = "model-default"+ catalog["services"]["llm"]["tasks"] = tasks+ service.save(catalog)++ # get_instance memoizes per resolved path; every reader must land on the+ # instance holding this tmp file rather than a cached admin-scope one.+ monkeypatch.setattr(+ ModelCatalogService, "get_instance", classmethod(lambda cls, path=None: service)+ )+ clear_llm_config_cache()++[email protected](autouse=True)+def _clear_llm_cache() -> Any:+ clear_llm_config_cache()+ yield+ clear_llm_config_cache()+++def test_starter_generation_calls_the_pinned_model(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _pin(tmp_path, monkeypatch, {"starters": {"profile_id": "llm-1", "model_id": "model-task"}})++ from deeptutor.services import suggestions+ import deeptutor.services.llm as llm++ observed: list[str] = []++ async def _complete(prompt: str, **kwargs: Any) -> str:+ observed.append(get_llm_config().model)+ return "[]"++ monkeypatch.setattr(llm, "complete", _complete)++ material = suggestions._Material(+ profile="A learner.",+ topics=[suggestions._Topic(surface="chat", label="Agentic RAG", days_ago=1)],+ )+ asyncio.run(suggestions._generate("en", material))++ assert observed == ["gpt-5-mini"]+++def test_starter_generation_inherits_when_unpinned(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _pin(tmp_path, monkeypatch, {})++ from deeptutor.services import suggestions+ import deeptutor.services.llm as llm++ observed: list[str] = []++ async def _complete(prompt: str, **kwargs: Any) -> str:+ observed.append(get_llm_config().model)+ return "[]"++ monkeypatch.setattr(llm, "complete", _complete)++ material = suggestions._Material(+ profile="A learner.",+ topics=[suggestions._Topic(surface="chat", label="Agentic RAG", days_ago=1)],+ )+ asyncio.run(suggestions._generate("en", material))++ assert observed == ["gpt-5"]+++class _Store:+ def __init__(self) -> None:+ self.title = ""++ async def get_session(self, session_id: str) -> dict[str, Any]:+ return {"id": session_id, "title": "New conversation"}++ async def get_messages(self, session_id: str) -> list[dict[str, Any]]:+ return [+ {"role": "user", "content": "Explain the chain rule."},+ {"role": "assistant", "content": "It composes derivatives."},+ ]++ async def update_session_title(self, session_id: str, title: str) -> None:+ self.title = title+++class _Runtime:+ def __init__(self) -> None:+ self.store = _Store()++ async def _publish_live_event(self, execution: Any, event: Any) -> Any:+ return event+++def _run_title(monkeypatch: pytest.MonkeyPatch, observed: list[str]) -> _Runtime:+ import deeptutor.services.llm as llm+ from deeptutor.services.session import turn_runtime as turn_runtime_module++ async def _stream(**kwargs: Any):+ observed.append(get_llm_config().model)+ yield "Chain rule basics"++ monkeypatch.setattr(llm, "stream", _stream)++ runtime = _Runtime()+ asyncio.run(+ turn_runtime_module.TurnRuntimeManager._maybe_generate_session_title(+ runtime,+ execution=object(),+ session_id="session-1",+ ui_language="en",+ )+ )+ return runtime+++def test_title_generation_calls_the_pinned_model(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _pin(+ tmp_path, monkeypatch, {"session_title": {"profile_id": "llm-1", "model_id": "model-task"}}+ )++ observed: list[str] = []+ runtime = _run_title(monkeypatch, observed)++ assert observed == ["gpt-5-mini"]+ assert runtime.store.title == "Chain rule basics"+++def test_title_generation_inherits_the_turn_model_when_unpinned(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _pin(tmp_path, monkeypatch, {})++ from deeptutor.services.llm.config import (+ LLMConfig,+ reset_scoped_llm_config,+ set_scoped_llm_config,+ )++ # Stand in for the turn's own scope: unpinned must keep resolving whatever+ # the conversation is already running on, not the global default.+ token = set_scoped_llm_config(LLMConfig(model="turn-model", api_key="sk-test"))+ try:+ observed: list[str] = []+ _run_title(monkeypatch, observed)+ finally:+ reset_scoped_llm_config(token)++ assert observed == ["turn-model"]diff --git a/tests/services/test_task_models.py b/tests/services/test_task_models.pynew file mode 100644index 000000000..ef738a41b--- /dev/null+++ b/tests/services/test_task_models.py@@ -0,0 +1,82 @@+"""Task models: pinned when asked for, inherited in every other case."""++from __future__ import annotations++from pathlib import Path+from typing import Any++from deeptutor.services.config.model_catalog import ModelCatalogService+from deeptutor.services.model_selection.tasks import (+ TASK_SESSION_TITLE,+ TASK_STARTERS,+ resolve_task_selection,+)+++def _catalog_with_tasks(service: ModelCatalogService, tasks: dict[str, Any]) -> dict[str, Any]:+ catalog = service.load()+ catalog["services"]["llm"]["profiles"] = [+ {+ "id": "llm-1",+ "name": "OpenRouter",+ "binding": "openrouter",+ "base_url": "https://openrouter.ai/api/v1",+ "api_key": "sk-or",+ "models": [+ {"id": "model-big", "model": "anthropic/claude-opus-4"},+ {"id": "model-small", "model": "openai/gpt-5-mini"},+ ],+ }+ ]+ catalog["services"]["llm"]["tasks"] = tasks+ return catalog+++def test_a_pinned_task_resolves_to_its_profile_and_model(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ catalog = service.save(+ _catalog_with_tasks(+ service,+ {TASK_STARTERS: {"profile_id": "llm-1", "model_id": "model-small"}},+ )+ )++ selection = resolve_task_selection(TASK_STARTERS, catalog)++ assert selection is not None+ assert (selection.profile_id, selection.model_id) == ("llm-1", "model-small")+++def test_an_unpinned_task_inherits(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ catalog = service.save(_catalog_with_tasks(service, {}))++ assert resolve_task_selection(TASK_SESSION_TITLE, catalog) is None+++def test_a_task_pointing_at_a_deleted_model_falls_back_to_inheriting(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ catalog = service.save(+ _catalog_with_tasks(+ service,+ {TASK_SESSION_TITLE: {"profile_id": "llm-1", "model_id": "model-deleted"}},+ )+ )++ # Normalization drops the dangling pointer rather than leaving a task+ # aimed at a model that no longer exists.+ assert catalog["services"]["llm"]["tasks"] == {}+ assert resolve_task_selection(TASK_SESSION_TITLE, catalog) is None+++def test_unknown_task_names_are_dropped(tmp_path: Path) -> None:+ service = ModelCatalogService(path=tmp_path / "model_catalog.json")+ catalog = service.save(+ _catalog_with_tasks(+ service,+ {"not_a_task": {"profile_id": "llm-1", "model_id": "model-big"}},+ )+ )++ assert catalog["services"]["llm"]["tasks"] == {}+ assert resolve_task_selection("not_a_task", catalog) is Nonediff --git a/web/app/(utility)/settings/connections/page.tsx b/web/app/(utility)/settings/connections/page.tsxnew file mode 100644index 000000000..b13545199--- /dev/null+++ b/web/app/(utility)/settings/connections/page.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { ConnectionsEditor } from "@/components/settings/ConnectionsEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function ConnectionsSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Connections")}+ description={t(+ "One vendor credential, supplying every model service that can use it. Services can still hold their own key instead.",+ )}+ />+ <ConnectionsEditor />+ </div>+ );+}diff --git a/web/app/(utility)/settings/starters/page.tsx b/web/app/(utility)/settings/starters/page.tsxindex 046d55fb9..15ad9d535 100644--- a/web/app/(utility)/settings/starters/page.tsx+++ b/web/app/(utility)/settings/starters/page.tsx@@ -1,7 +1,8 @@"use client";import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Loader2 } from "lucide-react";+import Link from "next/link";+import { ArrowUpRight, Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";import {@@ -166,6 +167,19 @@ export default function StarterSettingsPage() {/></SettingSection>)}++ {!loading && payload && (+ <p className="mt-5 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t("These lines are written by the active model unless you pin one.")}{" "}+ <Link+ href="/settings/task-models"+ className="inline-flex items-center gap-1 text-[var(--foreground)] underline-offset-2 hover:underline"+ >+ {t("Task models")}+ <ArrowUpRight className="h-3 w-3" />+ </Link>+ </p>+ )}</div>);}diff --git a/web/app/(utility)/settings/task-models/page.tsx b/web/app/(utility)/settings/task-models/page.tsxnew file mode 100644index 000000000..f36f78f78--- /dev/null+++ b/web/app/(utility)/settings/task-models/page.tsx@@ -0,0 +1,21 @@+"use client";++import { useTranslation } from "react-i18next";++import { TaskModelsEditor } from "@/components/settings/TaskModelsEditor";+import { SettingsPageHeader } from "@/components/settings/shared";++export default function TaskModelsSettingsPage() {+ const { t } = useTranslation();+ return (+ <div>+ <SettingsPageHeader+ title={t("Task models")}+ description={t(+ "The model behind work DeepTutor starts on its own, rather than in a turn you asked for.",+ )}+ />+ <TaskModelsEditor />+ </div>+ );+}diff --git a/web/components/settings/ConnectionsEditor.tsx b/web/components/settings/ConnectionsEditor.tsxnew file mode 100644index 000000000..2e604943c--- /dev/null+++ b/web/components/settings/ConnectionsEditor.tsx@@ -0,0 +1,782 @@+"use client";++import { useMemo, useState } from "react";+import Link from "next/link";+import {+ ArrowUpRight,+ Check,+ ChevronDown,+ Eye,+ EyeOff,+ Loader2,+ Plus,+ Trash2,+ X,+} from "lucide-react";+import { useTranslation } from "react-i18next";++import ProviderIcon from "@/components/common/ProviderIcon";+import { apiFetch, apiUrl } from "@/lib/api";+import {+ CONNECTABLE_SERVICES,+ type CatalogConnection,+ type ConnectionTarget,+ type ServiceName,+ useSettings,+} from "./SettingsContext";+import { inputClass, selectClass, selectOptionClass } from "./shared";++/**+ * Connections — the credential layer.+ *+ * Every model service in DeepTutor stores its own profile with its own key,+ * which is right when the keys differ and absurd when they do not: one+ * OpenRouter key had to be pasted into five pages. A connection is that key,+ * typed once, with one linked profile created per service that can use it.+ *+ * It is additive on purpose. Linking mirrors the credential down into ordinary+ * profiles (the backend does it on save), so a linked profile resolves exactly+ * like a hand-typed one and every service page keeps working unchanged. Users+ * who want a different key per service simply never make a connection.+ */++const SERVICE_LABEL: Record<ServiceName, { en: string; zh: string }> = {+ llm: { en: "LLM", zh: "LLM" },+ embedding: { en: "Embedding", zh: "嵌入模型" },+ search: { en: "Search", zh: "搜索" },+ tts: { en: "Text-to-Speech", zh: "语音合成" },+ stt: { en: "Speech-to-Text", zh: "语音识别" },+ imagegen: { en: "Image", zh: "文生图" },+ videogen: { en: "Video", zh: "文生视频" },+};++const SERVICE_HREF: Record<ServiceName, string> = {+ llm: "/settings/llm",+ embedding: "/settings/embedding",+ search: "/settings/search",+ tts: "/settings/tts",+ stt: "/settings/stt",+ imagegen: "/settings/image",+ videogen: "/settings/video",+};++function maskedKey(value: string): string {+ const key = (value || "").trim();+ if (!key) return "";+ // The stored value comes back from the server already masked as "***";+ // anything else is a key the user typed in this session.+ if (key === "***") return "••••••••";+ if (key.length <= 10) return `${key.slice(0, 2)}••••`;+ return `${key.slice(0, 5)}••••${key.slice(-4)}`;+}++export function ConnectionsEditor() {+ const { t, i18n } = useTranslation();+ const zh = i18n.language?.toLowerCase().startsWith("zh");+ const {+ draft,+ catalogEditable,+ settingsError,+ connectionTargets,+ connectionTarget,+ addConnection,+ updateConnectionField,+ removeConnection,+ linkConnectionToServices,+ setToast,+ } = useSettings();++ const [adding, setAdding] = useState(false);+ const [editingId, setEditingId] = useState<string | null>(null);+ const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);++ const connections = draft.connections ?? [];++ // Which profiles each connection currently feeds, by service.+ const linkage = useMemo(() => {+ const map = new Map<string, ServiceName[]>();+ for (const service of CONNECTABLE_SERVICES) {+ for (const profile of draft.services[service].profiles) {+ if (!profile.connection_id) continue;+ const list = map.get(profile.connection_id) ?? [];+ if (!list.includes(service)) list.push(service);+ map.set(profile.connection_id, list);+ }+ }+ return map;+ }, [draft]);++ // Services configured the old way — a profile with its own credentials and+ // no connection behind it. This is the motivation for the page, so it is+ // shown as a fact rather than left implicit.+ const standaloneServices = useMemo(+ () =>+ CONNECTABLE_SERVICES.filter((service) =>+ draft.services[service].profiles.some(+ (profile) => !profile.connection_id,+ ),+ ),+ [draft],+ );++ if (catalogEditable !== true) {+ // Same shape the service editors use: an ordinary user reaches this page+ // from the Models grid, and an empty panel would read as a broken page+ // rather than a permission boundary.+ return (+ <div className="rounded-xl border border-dashed border-[var(--border)] px-5 py-10 text-center text-[13px] text-[var(--muted-foreground)]">+ {settingsError+ ? t(+ "Backend unreachable — model endpoints will appear once the connection is restored. See the banner above for details.",+ )+ : t(+ "Model endpoints are assigned by your administrator. You can still personalize theme and language here.",+ )}+ </div>+ );+ }++ const label = (service: ServiceName) =>+ zh ? SERVICE_LABEL[service].zh : SERVICE_LABEL[service].en;++ return (+ <div>+ <div className="mb-4 flex items-center justify-between gap-3">+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {connections.length > 0+ ? t("{{count}} connection", { count: connections.length })+ : t("No connections yet.")}+ </p>+ {!adding && (+ <button+ type="button"+ onClick={() => setAdding(true)}+ className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ <Plus className="h-3.5 w-3.5" />+ {t("Add connection")}+ </button>+ )}+ </div>++ {adding && (+ <AddConnectionPanel+ targets={connectionTargets}+ onCancel={() => setAdding(false)}+ onCreate={(input, services) => {+ const connection = addConnection(input);+ const { created, activated } = linkConnectionToServices(+ connection,+ services,+ );+ setAdding(false);+ // The row already lists which services it feeds, so the toast+ // says the one thing that cannot be seen there: which existing+ // selections were left alone.+ const kept = created.filter(+ (service) => !activated.includes(service),+ );+ setToast(+ created.length === 0+ ? t("Connection added.")+ : kept.length === 0+ ? t("Configured {{count}} services and made them active.", {+ count: created.length,+ })+ : t(+ "Configured {{count}} services — {{kept}} kept your existing choice.",+ {+ count: created.length,+ kept: kept.map(label).join(zh ? "、" : ", "),+ },+ ),+ );+ }}+ />+ )}++ {connections.length === 0 && !adding && (+ <div className="rounded-xl border border-dashed border-[var(--border)] px-4 py-5">+ <p className="text-[13px] text-[var(--foreground)]">+ {t(+ "A connection holds one vendor credential and supplies every model service that can use it.",+ )}+ </p>+ {standaloneServices.length > 0 && (+ <p className="mt-2 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Credentials are currently entered separately for {{services}}.",+ {+ services: standaloneServices+ .map(label)+ .join(zh ? "、" : ", "),+ },+ )}+ </p>+ )}+ </div>+ )}++ {connections.length > 0 && (+ <div className="overflow-hidden rounded-xl border border-[var(--border)]">+ {connections.map((connection, index) => (+ <ConnectionRow+ key={connection.id}+ connection={connection}+ target={connectionTarget(connection.provider)}+ linked={linkage.get(connection.id) ?? []}+ first={index === 0}+ editing={editingId === connection.id}+ confirmingDelete={confirmDeleteId === connection.id}+ label={label}+ onEdit={() =>+ setEditingId(editingId === connection.id ? null : connection.id)+ }+ onField={(field, value) =>+ updateConnectionField(connection.id, field, value)+ }+ onLink={(service, model) => {+ const { activated } = linkConnectionToServices(connection, [+ { service, model },+ ]);+ setToast(+ activated.includes(service)+ ? t("{{service}} now uses {{name}}.", {+ service: label(service),+ name: connection.name,+ })+ : t(+ "Added a {{service}} profile — switch to it on its own page.",+ { service: label(service) },+ ),+ );+ }}+ onAskDelete={() =>+ setConfirmDeleteId(+ confirmDeleteId === connection.id ? null : connection.id,+ )+ }+ onDelete={() => {+ removeConnection(connection.id);+ setConfirmDeleteId(null);+ setEditingId(null);+ }}+ />+ ))}+ </div>+ )}+ </div>+ );+}++function ConnectionRow({+ connection,+ target,+ linked,+ first,+ editing,+ confirmingDelete,+ label,+ onEdit,+ onField,+ onLink,+ onAskDelete,+ onDelete,+}: {+ connection: CatalogConnection;+ target: ConnectionTarget | null;+ linked: ServiceName[];+ first: boolean;+ editing: boolean;+ confirmingDelete: boolean;+ label: (service: ServiceName) => string;+ onEdit: () => void;+ onField: (field: keyof CatalogConnection, value: string) => void;+ onLink: (service: ServiceName, model: string) => void;+ onAskDelete: () => void;+ onDelete: () => void;+}) {+ const { t } = useTranslation();+ const [showKey, setShowKey] = useState(false);++ const available = CONNECTABLE_SERVICES.filter(+ (service) => target?.services[service] && !linked.includes(service),+ );++ return (+ <div className={first ? "" : "border-t border-[var(--border)]"}>+ <div className="flex items-start gap-3 px-4 py-3.5">+ <ProviderIcon+ provider={connection.provider}+ size={18}+ className="mt-0.5 shrink-0"+ />+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <span className="text-[13px] font-medium text-[var(--foreground)]">+ {connection.name}+ </span>+ <span className="font-mono text-[11px] text-[var(--muted-foreground)]">+ {maskedKey(connection.api_key) || t("No key")}+ </span>+ </div>+ <div className="mt-1 text-[11px] leading-relaxed text-[var(--muted-foreground)]">+ {linked.length > 0+ ? linked.map(label).join(" · ")+ : t("Not supplying any service yet")}+ </div>+ {available.length > 0 && (+ <div className="mt-2 flex flex-wrap items-center gap-1.5">+ {available.map((service) => (+ <button+ key={service}+ type="button"+ onClick={() =>+ onLink(service, target?.services[service]?.default_model ?? "")+ }+ className="inline-flex h-6 items-center gap-1 rounded-md border border-[var(--border)] px-2 text-[11px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--ring)] hover:text-[var(--foreground)]"+ >+ <Plus className="h-3 w-3" />+ {label(service)}+ </button>+ ))}+ </div>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <button+ type="button"+ onClick={onEdit}+ className="rounded-md px-2 py-1 text-[11px] text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {editing ? t("Done") : t("Edit")}+ </button>+ <button+ type="button"+ onClick={onAskDelete}+ aria-label={t("Delete")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-red-500"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </div>+ </div>++ {confirmingDelete && (+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border)] bg-[var(--muted)]/25 px-4 py-3">+ <p className="text-[11px] leading-relaxed text-[var(--muted-foreground)]">+ {linked.length > 0+ ? t(+ "Profiles it supplies keep their current credentials but stop following this connection.",+ )+ : t("Nothing is using this connection.")}+ </p>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={onAskDelete}+ className="h-7 rounded-md px-2.5 text-[11px] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ >+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={onDelete}+ className="h-7 rounded-md bg-red-500/10 px-2.5 text-[11px] font-medium text-red-600 transition-colors hover:bg-red-500/15 dark:text-red-400"+ >+ {t("Delete")}+ </button>+ </div>+ </div>+ )}++ {editing && (+ <div className="grid gap-3 border-t border-[var(--border)] bg-[var(--muted)]/15 px-4 py-4 sm:grid-cols-2">+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("Name")}+ </div>+ <input+ className={inputClass}+ value={connection.name}+ onChange={(event) => onField("name", event.target.value)}+ />+ </div>+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("Base URL")}+ </div>+ <input+ className={inputClass}+ value={connection.base_url}+ placeholder={target?.default_base_url || "https://…/v1"}+ onChange={(event) => onField("base_url", event.target.value)}+ />+ </div>+ <div className="sm:col-span-2">+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("API Key")}+ </div>+ <div className="relative">+ <input+ type={showKey ? "text" : "password"}+ autoComplete="new-password"+ spellCheck={false}+ className={`${inputClass} pr-10 font-mono`}+ value={connection.api_key}+ onChange={(event) => onField("api_key", event.target.value)}+ placeholder="sk-..."+ />+ <button+ type="button"+ onClick={() => setShowKey((value) => !value)}+ aria-label={showKey ? t("Hide API key") : t("Show API key")}+ className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {showKey ? (+ <EyeOff className="h-4 w-4" />+ ) : (+ <Eye className="h-4 w-4" />+ )}+ </button>+ </div>+ <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "Saving pushes these values into every profile this connection supplies.",+ )}+ </p>+ </div>+ {linked.length > 0 && (+ <div className="flex flex-wrap gap-x-3 gap-y-1 sm:col-span-2">+ {linked.map((service) => (+ <Link+ key={service}+ href={SERVICE_HREF[service]}+ className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {label(service)}+ <ArrowUpRight className="h-3 w-3" />+ </Link>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ );+}++function AddConnectionPanel({+ targets,+ onCancel,+ onCreate,+}: {+ targets: ConnectionTarget[];+ onCancel: () => void;+ onCreate: (+ input: {+ provider: string;+ name: string;+ api_key: string;+ base_url: string;+ },+ services: { service: ServiceName; model: string }[],+ ) => void;+}) {+ const { t, i18n } = useTranslation();+ const zh = i18n.language?.toLowerCase().startsWith("zh");+ const [provider, setProvider] = useState("");+ const [apiKey, setApiKey] = useState("");+ const [baseUrl, setBaseUrl] = useState("");+ const [showKey, setShowKey] = useState(false);+ const [selected, setSelected] = useState<Set<ServiceName>>(new Set());+ const [llmModel, setLlmModel] = useState("");+ const [fetchedModels, setFetchedModels] = useState<string[]>([]);+ const [fetching, setFetching] = useState(false);+ const [fetchError, setFetchError] = useState("");++ const target = targets.find((item) => item.provider === provider) ?? null;+ const supported = CONNECTABLE_SERVICES.filter(+ (service) => target?.services[service],+ );++ const label = (service: ServiceName) =>+ zh ? SERVICE_LABEL[service].zh : SERVICE_LABEL[service].en;++ const choose = (next: string) => {+ setProvider(next);+ setFetchedModels([]);+ setFetchError("");+ setLlmModel("");+ const spec = targets.find((item) => item.provider === next);+ // Everything the vendor can serve starts checked: the whole point is that+ // one key configures the lot, and unchecking is cheaper than hunting.+ setSelected(+ new Set(+ CONNECTABLE_SERVICES.filter((service) => spec?.services[service]),+ ),+ );+ };++ const fetchModels = async () => {+ if (!target) return;+ setFetching(true);+ setFetchError("");+ try {+ const response = await apiFetch(apiUrl("/api/v1/settings/fetch-models"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ binding: target.services.llm?.provider || provider,+ base_url: baseUrl.trim() || target.services.llm?.base_url || "",+ api_key: apiKey || null,+ }),+ });+ const payload = (await response.json()) as {+ models?: { id: string }[];+ detail?: string;+ };+ if (!response.ok) throw new Error(payload.detail || "request failed");+ const ids = (payload.models ?? []).map((item) => item.id);+ setFetchedModels(ids);+ if (ids.length === 0) setFetchError(t("The provider returned no models."));+ } catch (error) {+ setFetchError(+ error instanceof Error ? error.message : t("Could not reach provider."),+ );+ } finally {+ setFetching(false);+ }+ };++ const toggle = (service: ServiceName) => {+ setSelected((current) => {+ const next = new Set(current);+ if (next.has(service)) next.delete(service);+ else next.add(service);+ return next;+ });+ };++ const canSubmit = Boolean(provider) && selected.size > 0;++ return (+ <div className="mb-4 rounded-xl border border-[var(--border)] bg-[var(--muted)]/15 px-4 py-4">+ <div className="grid gap-3 sm:grid-cols-2">+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("Provider")}+ </div>+ <div className="relative">+ {provider && (+ <ProviderIcon+ provider={provider}+ size={15}+ className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2"+ />+ )}+ <select+ className={`${selectClass} ${provider ? "pl-9" : ""}`}+ value={provider}+ onChange={(event) => choose(event.target.value)}+ >+ <option className={selectOptionClass} value="">+ {t("Select provider...")}+ </option>+ {targets.map((item) => (+ <option+ className={selectOptionClass}+ key={item.provider}+ value={item.provider}+ >+ {item.label}+ </option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />+ </div>+ </div>+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("Base URL")}+ </div>+ <input+ className={inputClass}+ value={baseUrl}+ placeholder={target?.default_base_url || "https://…/v1"}+ onChange={(event) => setBaseUrl(event.target.value)}+ />+ <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">+ {t("Leave blank to use each service's official endpoint.")}+ </p>+ </div>+ <div className="sm:col-span-2">+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("API Key")}+ </div>+ <div className="relative">+ <input+ type={showKey ? "text" : "password"}+ autoComplete="new-password"+ spellCheck={false}+ className={`${inputClass} pr-10 font-mono`}+ value={apiKey}+ onChange={(event) => setApiKey(event.target.value)}+ placeholder="sk-..."+ />+ <button+ type="button"+ onClick={() => setShowKey((value) => !value)}+ aria-label={showKey ? t("Hide API key") : t("Show API key")}+ className="absolute right-1 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"+ >+ {showKey ? (+ <EyeOff className="h-4 w-4" />+ ) : (+ <Eye className="h-4 w-4" />+ )}+ </button>+ </div>+ </div>+ </div>++ {target && (+ <div className="mt-4">+ <div className="mb-2 text-[12px] text-[var(--muted-foreground)]">+ {t("Configure these services")}+ </div>+ <div className="overflow-hidden rounded-lg border border-[var(--border)]">+ {supported.map((service, index) => {+ const spec = target.services[service]!;+ const checked = selected.has(service);+ return (+ <div+ key={service}+ className={`flex flex-wrap items-center gap-x-3 gap-y-2 px-3 py-2.5 ${+ index === 0 ? "" : "border-t border-[var(--border)]"+ }`}+ >+ <button+ type="button"+ onClick={() => toggle(service)}+ aria-pressed={checked}+ className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${+ checked+ ? "border-[var(--foreground)] bg-[var(--foreground)] text-[var(--background)]"+ : "border-[var(--border)]"+ }`}+ >+ {checked && <Check className="h-3 w-3" />}+ </button>+ <span className="w-24 shrink-0 text-[12.5px] text-[var(--foreground)]">+ {label(service)}+ </span>+ {service === "llm" ? (+ <div className="flex min-w-0 flex-1 items-center gap-2">+ {fetchedModels.length > 0 ? (+ <div className="relative min-w-0 flex-1">+ <select+ className={`${selectClass} h-8 py-0 text-[12px]`}+ value={llmModel}+ onChange={(event) =>+ setLlmModel(event.target.value)+ }+ >+ <option className={selectOptionClass} value="">+ {t("Select a model...")}+ </option>+ {fetchedModels.map((id) => (+ <option+ className={selectOptionClass}+ key={id}+ value={id}+ >+ {id}+ </option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />+ </div>+ ) : (+ <input+ className={`${inputClass} h-8 min-w-0 flex-1 py-0 font-mono text-[12px]`}+ value={llmModel}+ placeholder={t("Model ID")}+ onChange={(event) => setLlmModel(event.target.value)}+ />+ )}+ <button+ type="button"+ onClick={fetchModels}+ disabled={fetching || !apiKey.trim()}+ className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 text-[11px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-40"+ >+ {fetching && (+ <Loader2 className="h-3 w-3 animate-spin" />+ )}+ {t("List models")}+ </button>+ </div>+ ) : (+ <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-[var(--muted-foreground)]">+ {spec.default_model || t("Set on its own page")}+ </span>+ )}+ </div>+ );+ })}+ </div>+ {fetchError && (+ <p className="mt-1.5 text-[11px] text-amber-600 dark:text-amber-400">+ {fetchError}+ </p>+ )}+ {selected.has("llm") && !llmModel.trim() && (+ <p className="mt-1.5 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "No chat model picked yet — the profile is still created, pick one on the LLM page.",+ )}+ </p>+ )}+ </div>+ )}++ <div className="mt-4 flex items-center justify-end gap-2">+ <button+ type="button"+ onClick={onCancel}+ className="inline-flex h-8 items-center gap-1.5 rounded-lg px-3 text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ <X className="h-3.5 w-3.5" />+ {t("Cancel")}+ </button>+ <button+ type="button"+ disabled={!canSubmit}+ onClick={() =>+ onCreate(+ {+ provider,+ name: target?.label ?? provider,+ api_key: apiKey,+ base_url: baseUrl,+ },+ [...selected].map((service) => ({+ service,+ model:+ service === "llm"+ ? llmModel.trim()+ : (target?.services[service]?.default_model ?? ""),+ })),+ )+ }+ className="inline-flex h-8 items-center rounded-lg bg-[var(--foreground)] px-3.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-90 disabled:opacity-40"+ >+ {t("Add connection")}+ </button>+ </div>+ </div>+ );+}++export default ConnectionsEditor;diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsxindex 3d00dc2a1..6d14c8a10 100644--- a/web/components/settings/ServiceConfigEditor.tsx+++ b/web/components/settings/ServiceConfigEditor.tsx@@ -1,7 +1,9 @@"use client";import { useState } from "react";+import Link from "next/link";import {+ ArrowUpRight,CheckCircle2,ChevronDown,Eye,@@ -1187,9 +1189,19 @@ function ProfileFields({) => void;}) {const { t } = useTranslation();- const { providers, updateProfileField, updateModelField } = useSettings();+ const { draft, providers, updateProfileField, updateModelField, unlinkProfile } =+ useSettings();const [extraOpen, setExtraOpen] = useState(false);+ // A profile fed by a connection shows its credentials but does not let them+ // be edited here: the next save would mirror the connection's values back+ // over anything typed, and a field that silently reverts is worse than one+ // that says where it comes from.+ const linkedConnection =+ (draft.connections ?? []).find(+ (item) => item.id === profile.connection_id,+ ) ?? null;+const providerValue =service === "search" ? profile.provider || "" : profile.binding || "";const providerOption = (providers[service] || []).find(@@ -1328,14 +1340,40 @@ function ProfileFields({<CodeBuddyAuthCard /></div>)}+ {linkedConnection && (+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/25 px-3 py-2.5 sm:col-span-2">+ <span className="text-[11.5px] text-[var(--muted-foreground)]">+ {t("Credentials come from the {{name}} connection.", {+ name: linkedConnection.name,+ })}+ </span>+ <span className="flex items-center gap-3">+ <Link+ href="/settings/connections"+ className="inline-flex items-center gap-1 text-[11.5px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {t("Edit connection")}+ <ArrowUpRight className="h-3 w-3" />+ </Link>+ <button+ type="button"+ onClick={() => unlinkProfile(service, profile.id)}+ className="text-[11.5px] text-[var(--muted-foreground)] underline-offset-2 transition-colors hover:text-[var(--foreground)] hover:underline"+ >+ {t("Use its own key")}+ </button>+ </span>+ </div>+ )}{fields.baseUrl && (<div className="sm:col-span-2"><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">{service === "embedding" ? t("Endpoint URL") : t("Base URL")}</div><input- className={inputClass}+ className={`${inputClass} disabled:opacity-60`}value={profile.base_url}+ disabled={Boolean(linkedConnection)}onChange={(e) =>updateProfileField(service, "base_url", e.target.value)}@@ -1371,8 +1409,9 @@ function ProfileFields({type={showApiKey ? "text" : "password"}autoComplete="new-password"spellCheck={false}- className={`${inputClass} pr-10 font-mono`}+ className={`${inputClass} pr-10 font-mono disabled:opacity-60`}value={profile.api_key}+ disabled={Boolean(linkedConnection)}onChange={(e) =>updateProfileField(service, "api_key", e.target.value)}diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsxindex d53ea79ba..e152dab49 100644--- a/web/components/settings/SettingsContext.tsx+++ b/web/components/settings/SettingsContext.tsx@@ -92,17 +92,75 @@ export type CatalogProfile = {extra_headers?: Record<string, string> | string;proxy?: string;max_results?: number;+ /** Set when this profile's credentials come from a catalog connection. */+ connection_id?: string;models: CatalogModel[];};+/**+ * LLM work the product starts on its own — naming a conversation, writing the+ * three starting points under the home composer. Blank ids mean "inherit".+ */+export type LlmTaskKey = "session_title" | "starters";++export const LLM_TASK_KEYS: LlmTaskKey[] = ["session_title", "starters"];++export type LlmTaskSelection = { profile_id: string; model_id: string };+export type CatalogService = {active_profile_id: string | null;active_model_id?: string | null;profiles: CatalogProfile[];+ /** LLM only: per-task model pins. Absent entry = inherit. */+ tasks?: Partial<Record<LlmTaskKey, LlmTaskSelection>>;+};++/**+ * One vendor credential, typed once and mirrored into every service profile+ * that links to it. The backend does the mirroring on save, so a linked+ * profile still stores its own resolved credentials — linking changes where+ * they were typed, not how they resolve.+ */+export type CatalogConnection = {+ id: string;+ name: string;+ provider: string;+ api_key: string;+ /** Optional endpoint override; blank means each service's own default. */+ base_url: string;+ api_version: string;+ extra_headers?: Record<string, string> | string;+};++/** Per-service prefills a connection's provider can supply, from the backend. */+export type ConnectionTargetService = {+ provider: string;+ base_url: string;+ default_model: string;+ default_dim?: string;+ default_voice?: string;};+export type ConnectionTarget = {+ provider: string;+ label: string;+ default_base_url: string;+ services: Partial<Record<ServiceName, ConnectionTargetService>>;+};++/** Services a connection can supply, in the order the UI lists them. */+export const CONNECTABLE_SERVICES: ServiceName[] = [+ "llm",+ "embedding",+ "tts",+ "stt",+ "imagegen",+ "videogen",+];+export type Catalog = {version: number;+ connections?: CatalogConnection[];services: {llm: CatalogService;embedding: CatalogService;@@ -214,6 +272,7 @@ type SettingsPayload = {ui: UiSettings;catalog?: Catalog;providers?: Record<ServiceName, ProviderOption[]>;+ connection_targets?: ConnectionTarget[];};const DIAGNOSTICS_RESULTS_KEY = "deeptutor.settings.diagnosticsResults.v1";@@ -306,6 +365,7 @@ function prefillsDefaultModel(service: ServiceName): boolean {export function defaultCatalog(): Catalog {return {version: 1,+ connections: [],services: {llm: { active_profile_id: null, active_model_id: null, profiles: [] },embedding: {@@ -498,6 +558,31 @@ type SettingsContextValue = {) => void;updateContextWindowField: (value: string) => void;updateReasoningEffort: (value: string) => void;++ // Connections + task models+ connectionTargets: ConnectionTarget[];+ connectionTarget: (provider: string) => ConnectionTarget | null;+ addConnection: (input: {+ provider: string;+ name: string;+ api_key: string;+ base_url: string;+ }) => CatalogConnection;+ updateConnectionField: (+ id: string,+ field: keyof CatalogConnection,+ value: string,+ ) => void;+ removeConnection: (id: string) => void;+ unlinkProfile: (service: ServiceName, profileId: string) => void;+ linkConnectionToServices: (+ connection: Pick<+ CatalogConnection,+ "id" | "provider" | "name" | "api_key" | "base_url"+ >,+ requests: { service: ServiceName; model: string }[],+ ) => { created: ServiceName[]; activated: ServiceName[] };+ setLlmTask: (task: LlmTaskKey, selection: LlmTaskSelection | null) => void;llmContextDetection: LlmContextWindowDetection | null;applyDetectedContextWindow: () => void;@@ -577,6 +662,9 @@ export function SettingsProvider({ children }: { children: ReactNode }) {imagegen: [],videogen: [],});+ const [connectionTargets, setConnectionTargets] = useState<ConnectionTarget[]>(+ [],+ );const [toast, setToast] = useState("");const [saving, setSaving] = useState(false);const [applying, setApplying] = useState(false);@@ -655,6 +743,8 @@ export function SettingsProvider({ children }: { children: ReactNode }) {// them up, so no separate copy needs seeding here.syncLoadedCodeBlockSettingsToAppShell(payload.ui);if (payload.providers) setProviders(payload.providers);+ if (payload.connection_targets)+ setConnectionTargets(payload.connection_targets);settingsLoaded = true;} catch (err) {console.error("Failed to load settings:", err);@@ -896,6 +986,206 @@ export function SettingsProvider({ children }: { children: ReactNode }) {[embeddingDefaultDim, language, mutateCatalog, providers],);+ // ─── Connections ─────────────────────────────────────────────────────────+ //+ // A connection holds the credential; linking creates one ordinary profile+ // per service that points back at it. The backend mirrors the credential+ // down on save, so everything downstream keeps reading self-contained+ // profiles — nothing about how a profile resolves changes by being linked.++ const connectionTarget = useCallback(+ (provider: string) =>+ connectionTargets.find((target) => target.provider === provider) ?? null,+ [connectionTargets],+ );++ const addConnection = useCallback(+ (input: {+ provider: string;+ name: string;+ api_key: string;+ base_url: string;+ }) => {+ const connection: CatalogConnection = {+ id: `conn-${Date.now().toString(36)}${Math.random()+ .toString(36)+ .slice(2, 6)}`,+ name: input.name.trim() || input.provider,+ provider: input.provider,+ api_key: input.api_key,+ base_url: input.base_url.trim(),+ api_version: "",+ extra_headers: {},+ };+ mutateCatalog((next) => {+ next.connections = [...(next.connections ?? []), { ...connection }];+ });+ // Returned whole because the caller links services in the same click,+ // before the draft carrying it has been committed.+ return connection;+ },+ [mutateCatalog],+ );++ const updateConnectionField = useCallback(+ (id: string, field: keyof CatalogConnection, value: string) => {+ mutateCatalog((next) => {+ const connection = (next.connections ?? []).find(+ (item) => item.id === id,+ );+ if (connection) (connection as Record<string, unknown>)[field] = value;+ });+ },+ [mutateCatalog],+ );++ /**+ * Drop a connection. Profiles it fed keep the credentials already mirrored+ * into them — deleting the place a key was typed must not silently break+ * six working services.+ */+ const removeConnection = useCallback(+ (id: string) => {+ mutateCatalog((next) => {+ next.connections = (next.connections ?? []).filter(+ (item) => item.id !== id,+ );+ for (const service of CONNECTABLE_SERVICES) {+ for (const profile of next.services[service].profiles) {+ if (profile.connection_id === id) delete profile.connection_id;+ }+ }+ });+ },+ [mutateCatalog],+ );++ const unlinkProfile = useCallback(+ (service: ServiceName, profileId: string) => {+ mutateCatalog((next) => {+ const profile = next.services[service].profiles.find(+ (item) => item.id === profileId,+ );+ if (profile) delete profile.connection_id;+ });+ },+ [mutateCatalog],+ );++ /**+ * Create one linked profile per requested service.+ *+ * The plan — ids, which services get one, which of those become active — is+ * computed here rather than inside the catalog mutator: a mutator is a React+ * updater, so it runs during render (twice under StrictMode) and anything it+ * reports back would be both late and doubled.+ *+ * A new profile becomes the active one only for services that had none. A+ * user who already has a working LLM must not find their chat model swapped+ * out because they pasted a key for image generation, so what did and did+ * not become active is returned for the caller to say out loud.+ */+ const linkConnectionToServices = useCallback(+ (+ connection: Pick<+ CatalogConnection,+ "id" | "provider" | "name" | "api_key" | "base_url"+ >,+ requests: { service: ServiceName; model: string }[],+ ) => {+ const target = connectionTargets.find(+ (item) => item.provider === connection.provider,+ );+ const stamp = `${Date.now().toString(36)}${Math.random()+ .toString(36)+ .slice(2, 6)}`;+ const base = connection.base_url.trim().replace(/\/+$/, "");+ const plan = requests.flatMap((request, index) => {+ const spec = target?.services[request.service];+ if (!spec) return [];+ return [+ {+ service: request.service,+ spec,+ profileId: `${request.service}-profile-${stamp}${index}`,+ modelId: `${request.service}-model-${stamp}${index}`,+ model: request.model || spec.default_model || "",+ // Mirrored from the connection on save; seeded here so the draft+ // shows the same values the server will store.+ baseUrl: base+ ? request.service === "embedding"+ ? `${base}/embeddings`+ : base+ : spec.base_url,+ activate: draft.services[request.service].profiles.length === 0,+ },+ ];+ });++ mutateCatalog((next) => {+ for (const item of plan) {+ const bucket = next.services[item.service];+ bucket.profiles.push({+ id: item.profileId,+ name: connection.name,+ connection_id: connection.id,+ binding: item.spec.provider,+ base_url: item.baseUrl,+ api_key: connection.api_key,+ api_version: "",+ extra_headers: {},+ models: [+ {+ id: item.modelId,+ name: item.model || item.spec.provider,+ model: item.model,+ ...(item.service === "embedding"+ ? {+ dimension: item.spec.default_dim || "",+ send_dimensions: true,+ }+ : {}),+ ...(item.service === "tts"+ ? {+ voice: item.spec.default_voice || "",+ response_format: "mp3",+ }+ : {}),+ },+ ],+ });+ if (item.activate) {+ bucket.active_profile_id = item.profileId;+ bucket.active_model_id = item.modelId;+ }+ }+ });++ return {+ created: plan.map((item) => item.service),+ activated: plan+ .filter((item) => item.activate)+ .map((item) => item.service),+ };+ },+ [connectionTargets, draft, mutateCatalog],+ );++ // ─── Task models ─────────────────────────────────────────────────────────++ const setLlmTask = useCallback(+ (task: LlmTaskKey, selection: LlmTaskSelection | null) => {+ mutateCatalog((next) => {+ const llm = next.services.llm;+ const tasks = { ...(llm.tasks ?? {}) };+ if (selection) tasks[task] = selection;+ else delete tasks[task];+ llm.tasks = tasks;+ });+ },+ [mutateCatalog],+ );+const removeActiveModel = useCallback((service: ServiceName) => {if (service === "search") return;@@ -1313,6 +1603,14 @@ export function SettingsProvider({ children }: { children: ReactNode }) {updateModelBoolField,updateContextWindowField,updateReasoningEffort,+ connectionTargets,+ connectionTarget,+ addConnection,+ updateConnectionField,+ removeConnection,+ unlinkProfile,+ linkConnectionToServices,+ setLlmTask,llmContextDetection,applyDetectedContextWindow,saving,@@ -1353,6 +1651,14 @@ export function SettingsProvider({ children }: { children: ReactNode }) {llmContextDetection,logs,mutateCatalog,+ connectionTargets,+ connectionTarget,+ addConnection,+ updateConnectionField,+ removeConnection,+ unlinkProfile,+ linkConnectionToServices,+ setLlmTask,providers,registerExtension,removeActiveModel,diff --git a/web/components/settings/SettingsSectionGrid.tsx b/web/components/settings/SettingsSectionGrid.tsxindex 378fa27fe..58f96a161 100644--- a/web/components/settings/SettingsSectionGrid.tsx+++ b/web/components/settings/SettingsSectionGrid.tsx@@ -51,8 +51,34 @@ export default function SettingsSectionGrid({(leaf: SettingsLeaf,): { label: Lang; tone: "ok" | "bad" | "neutral"; dot: boolean } | null => {- if (!leaf.service) return null;if (catalogEditable !== true) return null;+ // Two leaves in the Models grid configure the catalog without owning a+ // service of their own; their chip counts what they hold instead.+ if (leaf.key === "connections") {+ const count = (catalog.connections ?? []).length;+ return count > 0+ ? {+ tone: "neutral",+ dot: true,+ label: { zh: `${count} 个连接`, en: `${count} connected` },+ }+ : { tone: "neutral", dot: false, label: { zh: "未配置", en: "Not set" } };+ }+ if (leaf.key === "task-models") {+ const count = Object.keys(catalog.services.llm.tasks ?? {}).length;+ return count > 0+ ? {+ tone: "neutral",+ dot: true,+ label: { zh: `${count} 项已指定`, en: `${count} pinned` },+ }+ : {+ tone: "neutral",+ dot: false,+ label: { zh: "跟随默认", en: "Inherited" },+ };+ }+ if (!leaf.service) return null;const readiness = serviceReadiness(catalog,leaf.service,diff --git a/web/components/settings/TaskModelsEditor.tsx b/web/components/settings/TaskModelsEditor.tsxnew file mode 100644index 000000000..2761c0d86--- /dev/null+++ b/web/components/settings/TaskModelsEditor.tsx@@ -0,0 +1,224 @@+"use client";++import { useMemo } from "react";+import Link from "next/link";+import { ArrowUpRight, ChevronDown } from "lucide-react";+import { useTranslation } from "react-i18next";++import ProviderIcon from "@/components/common/ProviderIcon";+import {+ LLM_TASK_KEYS,+ type LlmTaskKey,+ useSettings,+} from "./SettingsContext";+import { selectClass, selectOptionClass } from "./shared";++/**+ * Task models — the LLM behind work DeepTutor starts on its own.+ *+ * Two calls happen without anyone asking: naming a conversation after its+ * first exchange, and writing the three starting points under the home+ * composer. Both are short, frequent and latency-visible, and neither needs+ * the model a learner picked for their reasoning.+ *+ * Inheriting stays the default, and it is a real default rather than a hidden+ * one: with nothing chosen here both calls resolve exactly what they resolved+ * before this page existed.+ */++const TASK_COPY: Record<+ LlmTaskKey,+ {+ label: { en: string; zh: string };+ desc: { en: string; zh: string };+ inherit: { en: string; zh: string };+ href?: string;+ hrefLabel?: { en: string; zh: string };+ }+> = {+ session_title: {+ label: { en: "Conversation title", zh: "会话标题" },+ desc: {+ en: "Names a new conversation once it has its first question and answer.",+ zh: "新会话产生第一轮问答后,为它写一个标题。",+ },+ inherit: {+ en: "Follows the conversation's own model",+ zh: "跟随该会话使用的模型",+ },+ },+ starters: {+ label: { en: "Starting points", zh: "起始建议" },+ desc: {+ en: "The three lines offered under the home composer, drawn from recent work.",+ zh: "主页输入框下方那三行建议,来自最近的学习痕迹。",+ },+ inherit: { en: "Follows the active model", zh: "跟随当前模型" },+ href: "/settings/starters",+ hrefLabel: { en: "Material scope", zh: "素材范围" },+ },+};++export function TaskModelsEditor() {+ const { t, i18n } = useTranslation();+ const zh = i18n.language?.toLowerCase().startsWith("zh");+ const { draft, catalogEditable, settingsError, setLlmTask } = useSettings();++ const options = useMemo(+ () =>+ draft.services.llm.profiles.flatMap((profile) =>+ profile.models+ .filter((model) => model.model.trim())+ .map((model) => ({+ value: `${profile.id}::${model.id}`,+ profileId: profile.id,+ modelId: model.id,+ binding: profile.binding || "",+ profileName: profile.name,+ model: model.model,+ })),+ ),+ [draft],+ );++ const activeValue = useMemo(() => {+ const llm = draft.services.llm;+ return `${llm.active_profile_id ?? ""}::${llm.active_model_id ?? ""}`;+ }, [draft]);++ if (catalogEditable !== true) {+ // Same shape the service editors use: an ordinary user reaches this page+ // from the Models grid, and an empty panel would read as a broken page+ // rather than a permission boundary.+ return (+ <div className="rounded-xl border border-dashed border-[var(--border)] px-5 py-10 text-center text-[13px] text-[var(--muted-foreground)]">+ {settingsError+ ? t(+ "Backend unreachable — model endpoints will appear once the connection is restored. See the banner above for details.",+ )+ : t(+ "Model endpoints are assigned by your administrator. You can still personalize theme and language here.",+ )}+ </div>+ );+ }++ const tr = (value: { en: string; zh: string }) => (zh ? value.zh : value.en);++ return (+ <div>+ {options.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--border)] px-4 py-5">+ <p className="text-[13px] text-[var(--foreground)]">+ {t("No language models are configured yet.")}+ </p>+ <Link+ href="/settings/llm"+ className="mt-2 inline-flex items-center gap-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {t("Configure one")}+ <ArrowUpRight className="h-3 w-3" />+ </Link>+ </div>+ ) : (+ <div className="overflow-hidden rounded-xl border border-[var(--border)]">+ {LLM_TASK_KEYS.map((task, index) => {+ const copy = TASK_COPY[task];+ const pinned = draft.services.llm.tasks?.[task];+ const value = pinned+ ? `${pinned.profile_id}::${pinned.model_id}`+ : "";+ const resolved =+ options.find((option) => option.value === value) ??+ (value+ ? null+ : (options.find((option) => option.value === activeValue) ??+ null));+ return (+ <div+ key={task}+ className={`flex flex-wrap items-start gap-x-6 gap-y-3 px-4 py-4 ${+ index === 0 ? "" : "border-t border-[var(--border)]"+ }`}+ >+ <div className="min-w-0 flex-1 basis-64">+ <div className="text-[13px] font-medium text-[var(--foreground)]">+ {tr(copy.label)}+ </div>+ <p className="mt-1 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {tr(copy.desc)}+ </p>+ {copy.href && copy.hrefLabel && (+ <Link+ href={copy.href}+ className="mt-1.5 inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {tr(copy.hrefLabel)}+ <ArrowUpRight className="h-3 w-3" />+ </Link>+ )}+ </div>+ <div className="w-full sm:w-72">+ <div className="relative">+ <select+ className={`${selectClass} pr-9`}+ value={value}+ onChange={(event) => {+ const next = event.target.value;+ if (!next) {+ setLlmTask(task, null);+ return;+ }+ const [profileId, modelId] = next.split("::");+ setLlmTask(task, {+ profile_id: profileId,+ model_id: modelId,+ });+ }}+ >+ <option className={selectOptionClass} value="">+ {tr(copy.inherit)}+ </option>+ {options.map((option) => (+ <option+ className={selectOptionClass}+ key={option.value}+ value={option.value}+ >+ {option.model} — {option.profileName}+ </option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />+ </div>+ {/* What it resolves to right now — the inherit case is the+ one users cannot otherwise see. */}+ <div className="mt-1.5 flex items-center gap-1.5 text-[11px] text-[var(--muted-foreground)]">+ {resolved ? (+ <>+ <ProviderIcon provider={resolved.binding} size={12} />+ <span className="truncate font-mono">+ {resolved.model}+ </span>+ </>+ ) : (+ <span>{t("Resolves at call time.")}</span>+ )}+ </div>+ </div>+ </div>+ );+ })}+ </div>+ )}++ <p className="mt-3 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Both calls are short and frequent, so a smaller, faster model is usually the better trade here.",+ )}+ </p>+ </div>+ );+}++export default TaskModelsEditor;diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.tsindex e4bdeefde..f9bf46b4c 100644--- a/web/lib/settings-nav.ts+++ b/web/lib/settings-nav.ts@@ -10,7 +10,9 @@ import {Database,FileScan,Image as ImageIcon,+ KeyRound,Library,+ ListChecks,MessagesSquare,Mic,Network,@@ -76,6 +78,17 @@ export interface SettingsCategory {}const MODEL_CHILDREN: SettingsLeaf[] = [+ {+ key: "connections",+ href: "/settings/connections",+ label: { zh: "连接", en: "Connections" },+ blurb: {+ zh: "一份凭据供给多个服务。",+ en: "One credential, supplying several services.",+ },+ icon: KeyRound,+ tile: "bg-sky-500/10 text-sky-600 dark:text-sky-400",+ },{key: "llm",href: "/settings/llm",@@ -157,6 +170,17 @@ const MODEL_CHILDREN: SettingsLeaf[] = [tile: "bg-indigo-500/10 text-indigo-600 dark:text-indigo-400",service: "videogen",},+ {+ key: "task-models",+ href: "/settings/task-models",+ label: { zh: "任务模型", en: "Task models" },+ blurb: {+ zh: "会话标题与起始建议使用的模型。",+ en: "The model behind conversation titles and starting points.",+ },+ icon: ListChecks,+ tile: "bg-cyan-500/10 text-cyan-600 dark:text-cyan-400",+ },];const CHAT_CHILDREN: SettingsLeaf[] = [diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex e18fae6bb..f49a10602 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3553,5 +3553,54 @@"No unused sources in your library yet.": "No unused sources in your library yet.","Close panels": "Close panels","Close AI Companion": "Close AI Companion",- "Close contents": "Close contents"+ "Close contents": "Close contents",+ "{{count}} connection": "{{count}} connection",+ "{{count}} connection_one": "{{count}} connection",+ "{{count}} connection_other": "{{count}} connections",+ "No connections yet.": "No connections yet.",+ "Add connection": "Add connection",+ "Connection added.": "Connection added.",+ "A connection holds one vendor credential and supplies every model service that can use it.": "A connection holds one vendor credential and supplies every model service that can use it.",+ "Credentials are currently entered separately for {{services}}.": "Credentials are currently entered separately for {{services}}.",+ "{{service}} now uses {{name}}.": "{{service}} now uses {{name}}.",+ "Added a {{service}} profile — switch to it on its own page.": "Added a {{service}} profile — switch to it on its own page.",+ "No key": "No key",+ "Not supplying any service yet": "Not supplying any service yet",+ "Profiles it supplies keep their current credentials but stop following this connection.": "Profiles it supplies keep their current credentials but stop following this connection.",+ "Nothing is using this connection.": "Nothing is using this connection.",+ "Saving pushes these values into every profile this connection supplies.": "Saving pushes these values into every profile this connection supplies.",+ "The provider returned no models.": "The provider returned no models.",+ "Could not reach provider.": "Could not reach provider.",+ "Leave blank to use each service's official endpoint.": "Leave blank to use each service's official endpoint.",+ "Configure these services": "Configure these services",+ "Select a model...": "Select a model...",+ "List models": "List models",+ "Set on its own page": "Set on its own page",+ "No chat model picked yet — the profile is still created, pick one on the LLM page.": "No chat model picked yet — the profile is still created, pick one on the LLM page.",+ "No language models are configured yet.": "No language models are configured yet.",+ "Configure one": "Configure one",+ "Resolves at call time.": "Resolves at call time.",+ "Both calls are short and frequent, so a smaller, faster model is usually the better trade here.": "Both calls are short and frequent, so a smaller, faster model is usually the better trade here.",+ "Credentials come from the {{name}} connection.": "Credentials come from the {{name}} connection.",+ "Edit connection": "Edit connection",+ "Use its own key": "Use its own key",+ "Connections": "Connections",+ "One vendor credential, supplying every model service that can use it. Services can still hold their own key instead.": "One vendor credential, supplying every model service that can use it. Services can still hold their own key instead.",+ "Task models": "Task models",+ "The model behind work DeepTutor starts on its own, rather than in a turn you asked for.": "The model behind work DeepTutor starts on its own, rather than in a turn you asked for.",+ "These lines are written by the active model unless you pin one.": "These lines are written by the active model unless you pin one.",+ "Voice": "Voice",+ "Provider-specific voice name, e.g. alloy (OpenAI) or model:voice (SiliconFlow).": "Provider-specific voice name, e.g. alloy (OpenAI) or model:voice (SiliconFlow).",+ "Output format": "Output format",+ "Image size": "Image size",+ "Default pixel size sent with each request. Leave empty for the provider default.": "Default pixel size sent with each request. Leave empty for the provider default.",+ "Quality / Style": "Quality / Style",+ "quality (e.g. hd)": "quality (e.g. hd)",+ "style (e.g. vivid)": "style (e.g. vivid)",+ "Aspect ratio": "Aspect ratio",+ "Defaults sent with each request. Leave empty for the provider default.": "Defaults sent with each request. Leave empty for the provider default.",+ "Duration / Resolution": "Duration / Resolution",+ "seconds": "seconds",+ "Configured {{count}} services and made them active.": "Configured {{count}} services and made them active.",+ "Configured {{count}} services — {{kept}} kept your existing choice.": "Configured {{count}} services — {{kept}} kept your existing choice."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 64017d382..d5b208746 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3553,5 +3553,54 @@"No unused sources in your library yet.": "资料库里暂时没有可添加的其他资料。","Close panels": "关闭面板","Close AI Companion": "关闭 AI 阅读伙伴",- "Close contents": "关闭目录"+ "Close contents": "关闭目录",+ "{{count}} connection": "{{count}} 个连接",+ "{{count}} connection_one": "{{count}} 个连接",+ "{{count}} connection_other": "{{count}} 个连接",+ "No connections yet.": "还没有连接。",+ "Add connection": "添加连接",+ "Connection added.": "已添加连接。",+ "A connection holds one vendor credential and supplies every model service that can use it.": "一个连接保存一份供应商凭据,供给所有能用它的模型服务。",+ "Credentials are currently entered separately for {{services}}.": "目前 {{services}} 的凭据是各自单独填写的。",+ "{{service}} now uses {{name}}.": "{{service}} 现在使用 {{name}}。",+ "Added a {{service}} profile — switch to it on its own page.": "已添加 {{service}} 配置;到它自己的页面切换启用。",+ "No key": "未填 key",+ "Not supplying any service yet": "还没有供给任何服务",+ "Profiles it supplies keep their current credentials but stop following this connection.": "由它供给的配置会保留当前凭据,但不再跟随此连接。",+ "Nothing is using this connection.": "没有配置在使用这个连接。",+ "Saving pushes these values into every profile this connection supplies.": "保存后,这些值会写入由此连接供给的每一个配置。",+ "The provider returned no models.": "供应商没有返回任何模型。",+ "Could not reach provider.": "无法连接到供应商。",+ "Leave blank to use each service's official endpoint.": "留空则各服务使用官方地址。",+ "Configure these services": "为这些服务创建配置",+ "Select a model...": "选择模型…",+ "List models": "获取模型",+ "Set on its own page": "在它自己的页面设置",+ "No chat model picked yet — the profile is still created, pick one on the LLM page.": "还没选聊天模型;配置仍会创建,可到 LLM 页面再选。",+ "No language models are configured yet.": "还没有配置任何语言模型。",+ "Configure one": "去配置",+ "Resolves at call time.": "调用时再解析。",+ "Both calls are short and frequent, so a smaller, faster model is usually the better trade here.": "这两处调用都短小且频繁,指向一个更小更快的模型通常更划算。",+ "Credentials come from the {{name}} connection.": "凭据来自连接「{{name}}」。",+ "Edit connection": "编辑连接",+ "Use its own key": "改用独立凭据",+ "Connections": "连接",+ "One vendor credential, supplying every model service that can use it. Services can still hold their own key instead.": "一份供应商凭据,供给所有能用它的模型服务。各服务也可以继续单独填写自己的 key。",+ "Task models": "任务模型",+ "The model behind work DeepTutor starts on its own, rather than in a turn you asked for.": "DeepTutor 自己发起的调用使用的模型,不属于你主动开始的某一轮对话。",+ "These lines are written by the active model unless you pin one.": "这三行由当前模型生成,除非你为它单独指定。",+ "Voice": "音色",+ "Provider-specific voice name, e.g. alloy (OpenAI) or model:voice (SiliconFlow).": "供应商各自的音色名,例如 alloy(OpenAI)或 model:voice(SiliconFlow)。",+ "Output format": "输出格式",+ "Image size": "图像尺寸",+ "Default pixel size sent with each request. Leave empty for the provider default.": "每次请求默认发送的像素尺寸。留空则用供应商默认值。",+ "Quality / Style": "质量 / 风格",+ "quality (e.g. hd)": "质量(如 hd)",+ "style (e.g. vivid)": "风格(如 vivid)",+ "Aspect ratio": "画面比例",+ "Defaults sent with each request. Leave empty for the provider default.": "每次请求默认发送的参数。留空则用供应商默认值。",+ "Duration / Resolution": "时长 / 分辨率",+ "seconds": "秒",+ "Configured {{count}} services and made them active.": "已配置 {{count}} 个服务并设为当前使用。",+ "Configured {{count}} services — {{kept}} kept your existing choice.": "已配置 {{count}} 个服务;{{kept}} 保留了你原有的选择。"}