Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): add backend model catalogs (#1814)
Call White6a40b10e592d
diff --git a/config/v2_config.py b/config/v2_config.pyindex 4fc847ace..5ec836d2e 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -271,18 +271,16 @@ def normalize_model_hub_vendor_id(value: object) -> str:def canonical_opencode_menu_identity(identifier: object) -> tuple[str, str]:"""Validate and split one persisted OpenCode ``provider/model`` identity."""- from core.handlers.model_hub.identifiers import (- STANDARD_OPENCODE_VENDOR_IDS,- parse_opencode_model_id,- )+ from core.handlers.model_hub.identifiers import parse_opencode_model_idif not isinstance(identifier, str) or identifier != identifier.strip():raise ValueError("Invalid OpenCode model identifier")provider_id, model_id = parse_opencode_model_id(identifier)if (- provider_id not in STANDARD_OPENCODE_VENDOR_IDS- and provider_id != "custom"- ) or provider_id != provider_id.strip() or model_id != model_id.strip():+ re.fullmatch(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", provider_id) is None+ or provider_id != provider_id.strip()+ or model_id != model_id.strip()+ ):raise ValueError("Invalid OpenCode model identifier")if _contains_model_hub_credential_material(identifier):raise ValueError("OpenCode model identifier contains credential material")@@ -305,9 +303,9 @@ def model_hub_fixed_menu_ids(backend: str) -> tuple[str, ...]:def _migrate_fixed_menu_routes_on_load(payload: dict) -> dict:"""Adapt fixed-menu route keys to the current bundled catalog on reload.- A changed catalog is a one-time structural migration: newly introduced- menu ids receive empty routes and removed ids are discarded. Existing hop- payloads are copied verbatim; matching and placement never run here.+ Newly introduced menu ids receive empty routes. Legacy route keys remain+ intact so the canonical agent loader can preserve them as manual catalog+ rows; matching and placement never run here."""model_hub = payload.get("model_hub")@@ -323,6 +321,8 @@ def _migrate_fixed_menu_routes_on_load(payload: dict) -> dict:raw_agent = agents.get(backend)if not isinstance(raw_agent, dict):continue+ if "models" in raw_agent:+ continueroutes = raw_agent.get("routes")expected_menu_ids = model_hub_fixed_menu_ids(backend)if not isinstance(routes, dict) or not expected_menu_ids:@@ -331,6 +331,11 @@ def _migrate_fixed_menu_routes_on_load(payload: dict) -> dict:model_id: routes.get(model_id, {"hops": []})for model_id in expected_menu_ids}+ migrated_routes.update(+ (model_id, route)+ for model_id, route in routes.items()+ if model_id not in migrated_routes+ )if migrated_routes == routes:continuemigrated_agent = dict(raw_agent)@@ -663,6 +668,7 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple["mappings","routes","menu",+ "models",}:return payload, False, ()expected_menu_kind = "open" if backend == "opencode" else "fixed"@@ -819,7 +825,7 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[allowed_agent = {key: valuefor key, value in agent.items()- if key in {"backend", "mode", "menu_kind", "menu"}+ if key in {"backend", "mode", "menu_kind", "menu", "models"}}allowed_agent["backend"] = backendagent_mode = agent.get("mode")@@ -3151,6 +3157,178 @@ class ModelHubMenuConfig:return {"view": self.view, "checked": list(self.checked)}+_BACKEND_MODEL_INPUT_MODALITIES = frozenset(+ {"text", "image", "audio", "video", "pdf"}+)+_BACKEND_MODEL_OUTPUT_MODALITIES = frozenset(+ {"text", "image", "audio", "video"}+)+++@dataclass+class ModelHubBackendModelConfig:+ id: str+ origin: Literal["builtin", "models_dev", "manual"] = "manual"+ display_name: Optional[str] = None+ models_dev_id: Optional[str] = None+ context_window: Optional[int] = None+ max_output_tokens: Optional[int] = None+ input_modalities: list[str] = field(default_factory=list)+ output_modalities: list[str] = field(default_factory=list)+ supports_tools: Optional[bool] = None+ supports_reasoning: Optional[bool] = None+ reasoning_efforts: list[str] = field(default_factory=list)++ @classmethod+ def from_payload(cls, payload: object) -> "ModelHubBackendModelConfig":+ if not isinstance(payload, dict):+ raise ValueError("Config 'model_hub.agents.models' entries must be objects")+ allowed = {+ "id",+ "display_name",+ "origin",+ "models_dev_id",+ "context_window",+ "max_output_tokens",+ "input_modalities",+ "output_modalities",+ "supports_tools",+ "supports_reasoning",+ "reasoning_efforts",+ # These are read-only API projection fields. Accepting and dropping+ # them lets a client submit the list it observed without turning+ # server-owned policy into persisted state.+ "locked",+ "routeable",+ }+ if set(payload) - allowed:+ raise ValueError("Config 'model_hub.agents.models' contains unknown fields")+ model_id = payload.get("id")+ origin = payload.get("origin", "manual")+ display_name = payload.get("display_name")+ models_dev_id = payload.get("models_dev_id")+ context_window = payload.get("context_window")+ max_output_tokens = payload.get("max_output_tokens")+ input_modalities = payload.get("input_modalities", [])+ output_modalities = payload.get("output_modalities", [])+ supports_tools = payload.get("supports_tools")+ supports_reasoning = payload.get("supports_reasoning")+ reasoning_efforts = payload.get("reasoning_efforts", [])++ if (+ not isinstance(model_id, str)+ or not model_id.strip()+ or _contains_model_hub_credential_material(model_id)+ ):+ raise ValueError("Config 'model_hub.agents.models.id' is invalid")+ if origin not in {"builtin", "models_dev", "manual"}:+ raise ValueError("Config 'model_hub.agents.models.origin' is invalid")+ for name, value in (+ ("display_name", display_name),+ ("models_dev_id", models_dev_id),+ ):+ if value is not None and (+ not isinstance(value, str)+ or not value.strip()+ or _contains_model_hub_credential_material(value)+ ):+ raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")+ for name, value in (+ ("context_window", context_window),+ ("max_output_tokens", max_output_tokens),+ ):+ if value is not None and (+ isinstance(value, bool) or not isinstance(value, int) or value <= 0+ ):+ raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")+ for name, values, allowed_modalities in (+ (+ "input_modalities",+ input_modalities,+ _BACKEND_MODEL_INPUT_MODALITIES,+ ),+ (+ "output_modalities",+ output_modalities,+ _BACKEND_MODEL_OUTPUT_MODALITIES,+ ),+ ):+ if (+ not isinstance(values, list)+ or any(+ not isinstance(value, str)+ or value not in allowed_modalities+ for value in values+ )+ or len(set(values)) != len(values)+ ):+ raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")+ for name, value in (+ ("supports_tools", supports_tools),+ ("supports_reasoning", supports_reasoning),+ ):+ if value is not None and not isinstance(value, bool):+ raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")+ if (+ not isinstance(reasoning_efforts, list)+ or any(+ not isinstance(value, str)+ or not value.strip()+ or len(value) > 64+ or _contains_model_hub_credential_material(value)+ for value in reasoning_efforts+ )+ or len(set(reasoning_efforts)) != len(reasoning_efforts)+ ):+ raise ValueError(+ "Config 'model_hub.agents.models.reasoning_efforts' is invalid"+ )+ return cls(+ id=model_id.strip(),+ origin=origin,+ display_name=display_name.strip() if isinstance(display_name, str) else None,+ models_dev_id=models_dev_id.strip() if isinstance(models_dev_id, str) else None,+ context_window=context_window,+ max_output_tokens=max_output_tokens,+ input_modalities=list(input_modalities),+ output_modalities=list(output_modalities),+ supports_tools=supports_tools,+ supports_reasoning=supports_reasoning,+ reasoning_efforts=list(reasoning_efforts),+ )++ def to_payload(self) -> dict:+ return {+ "id": self.id,+ "display_name": self.display_name,+ "origin": self.origin,+ "models_dev_id": self.models_dev_id,+ "context_window": self.context_window,+ "max_output_tokens": self.max_output_tokens,+ "input_modalities": list(self.input_modalities),+ "output_modalities": list(self.output_modalities),+ "supports_tools": self.supports_tools,+ "supports_reasoning": self.supports_reasoning,+ "reasoning_efforts": list(self.reasoning_efforts),+ }+++def _default_backend_models(backend: str) -> list[ModelHubBackendModelConfig]:+ if backend not in {"claude", "codex"}:+ return []+ from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog++ return [+ ModelHubBackendModelConfig(+ id=entry["id"],+ origin="builtin",+ display_name=entry.get("label"),+ reasoning_efforts=list(entry.get("reasoning_efforts") or ()),+ )+ for entry in backend_model_entries(backend, load_bundled_catalog())+ ]++@dataclassclass ModelHubAgentSourcesConfig:order: list[str] = field(default_factory=list)@@ -3180,11 +3358,17 @@ class ModelHubAgentSupplyConfig:sources: ModelHubAgentSourcesConfig = field(default_factory=ModelHubAgentSourcesConfig)routes: dict[str, ModelHubRouteConfig] = field(default_factory=dict)menu: Optional[ModelHubMenuConfig] = None+ models: list[ModelHubBackendModelConfig] = field(default_factory=list)@classmethoddef default(cls, backend: str, *, mode: Literal["hub", "direct"]) -> "ModelHubAgentSupplyConfig":if backend == "opencode":- return cls(backend="opencode", mode=mode, menu_kind="open", menu=ModelHubMenuConfig())+ return cls(+ backend="opencode",+ mode=mode,+ menu_kind="open",+ menu=ModelHubMenuConfig(),+ )if backend not in {"claude", "codex"}:raise ValueError(f"Unsupported Model Hub backend: {backend}")return cls(@@ -3192,6 +3376,7 @@ class ModelHubAgentSupplyConfig:mode=mode,menu_kind="fixed",routes={model_id: ModelHubRouteConfig() for model_id in model_hub_fixed_menu_ids(backend)},+ models=_default_backend_models(backend),)@classmethod@@ -3204,7 +3389,15 @@ class ModelHubAgentSupplyConfig:) -> "ModelHubAgentSupplyConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.agents' entries must be objects")- if set(payload) - {"backend", "mode", "menu_kind", "sources", "routes", "menu"}:+ if set(payload) - {+ "backend",+ "mode",+ "menu_kind",+ "sources",+ "routes",+ "menu",+ "models",+ }:raise ValueError("Config 'model_hub.agents' contains unknown fields")raw_backend = payload.get("backend")backend = expected_backend if raw_backend is None else raw_backend@@ -3235,11 +3428,43 @@ class ModelHubAgentSupplyConfig:for model_id, route in routes_payload.items()}menu = ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None+ models_payload = payload.get("models")+ if models_payload is None:+ if backend == "opencode":+ legacy_ids = list(menu.checked if menu else ())+ legacy_ids.extend(+ model_id for model_id in routes if model_id not in legacy_ids+ )+ models = [+ ModelHubBackendModelConfig(id=model_id, origin="manual")+ for model_id in legacy_ids+ ]+ else:+ models = _default_backend_models(backend)+ known = {model.id for model in models}+ models.extend(+ ModelHubBackendModelConfig(id=model_id, origin="manual")+ for model_id in routes+ if model_id not in known+ )+ else:+ if not isinstance(models_payload, list):+ raise ValueError("Config 'model_hub.agents.models' must be an array")+ models = [+ ModelHubBackendModelConfig.from_payload(item)+ for item in models_payload+ ]+ if len({model.id for model in models}) != len(models):+ raise ValueError("Config 'model_hub.agents.models' ids must be unique")if any(_contains_model_hub_credential_material(model_id) for model_id in routes):raise ValueError("Config 'model_hub.agents.routes' contains an invalid model id")if backend == "opencode":- for identifier in (*routes, *(menu.checked if menu else ())):+ for identifier in (*routes, *(model.id for model in models)):canonical_opencode_menu_identity(identifier)+ menu = ModelHubMenuConfig(+ view=menu.view if menu else "featured",+ checked=[model.id for model in models],+ )return cls(backend=backend,mode=mode,@@ -3251,10 +3476,11 @@ class ModelHubAgentSupplyConfig:),routes=routes,menu=menu,+ models=models,)def to_payload(self) -> dict:- return {+ payload = {"backend": self.backend,"mode": self.mode,"menu_kind": self.menu_kind,@@ -3265,6 +3491,8 @@ class ModelHubAgentSupplyConfig:},"menu": self.menu.to_payload() if self.menu else None,}+ payload["models"] = [model.to_payload() for model in self.models]+ return payload@dataclass@@ -3368,10 +3596,8 @@ class ModelHubConfig:expected_backend=backend,repairing=repairing,)- expected_menu_ids = (- model_hub_fixed_menu_ids(backend)- if backend in {"claude", "codex"}- else tuple(agents[backend].menu.checked if agents[backend].menu else ())+ expected_menu_ids = tuple(+ model.id for model in agents[backend].models)missing_route = next((model_id for model_id in expected_menu_ids if model_id not in agents[backend].routes),@@ -3381,19 +3607,21 @@ class ModelHubConfig:raise ValueError(f"Config 'model_hub.agents.{backend}.routes' is missing menu model '{missing_route}'")- if backend in {"claude", "codex"}:- extra_route = next(- (- model_id- for model_id in agents[backend].routes- if model_id not in expected_menu_ids- ),- None,+ extra_route = next(+ (+ model_id+ for model_id in agents[backend].routes+ if model_id not in expected_menu_ids+ ),+ None,+ )+ # The retained OpenCode menu endpoint can hide a checked model while+ # preserving its dormant Route for a later re-enable. Fixed-menu+ # backends have never had that compatibility state.+ if extra_route is not None and backend != "opencode":+ raise ValueError(+ f"Config 'model_hub.agents.{backend}.routes' contains non-menu model '{extra_route}'")- if extra_route is not None:- raise ValueError(- f"Config 'model_hub.agents.{backend}.routes' contains non-menu model '{extra_route}'"- )config = cls(enabled=enabled,sources=sources,diff --git a/core/controller.py b/core/controller.pyindex 43faf1ce4..8e3ab2ee1 100644--- a/core/controller.py+++ b/core/controller.py@@ -500,12 +500,34 @@ class Controller:# post-paint refresh, so controller readiness never waits on npm.refresh_cli_presence(False, None)+ async def backend_catalog_changed(backend: str) -> None:+ try:+ latest = V2Config.load()+ except FileNotFoundError:+ return+ self.config.model_hub = latest.model_hub+ if latest.model_hub.agents[backend].mode != "hub":+ if backend == "codex":+ agent_service = getattr(self, "agent_service", None)+ if agent_service is None:+ raise RuntimeError("Agent service is unavailable")+ await agent_service.invalidate_model_hub_runtime(backend)+ return+ runtime_config = getattr(latest.agents, backend, None)+ if runtime_config is None:+ return+ coordinator = getattr(self, "backend_restart_coordinator", None)+ if coordinator is None:+ raise RuntimeError("Backend restart coordinator is unavailable")+ await coordinator.request_restart(backend)+self.model_hub_service = create_default_service(requested_model_override=default_vibe_agent_model,selected_agent_override=default_vibe_agent_name,named_agents_override=named_vibe_agents,cli_present_override=cli_present,cli_presence_refresh=refresh_cli_presence,+ backend_catalog_changed=backend_catalog_changed,)self.model_hub_turn_gateway = ModelHubTurnGateway(self.model_hub_service,diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.pyindex a9f7b4ed4..3db3a853b 100644--- a/core/handlers/model_hub/identifiers.py+++ b/core/handlers/model_hub/identifiers.py@@ -10,15 +10,20 @@ import hashlib# file an older release wrote must keep loading — so a live, routable identifier# is not always within it, and no surface downstream of config may treat this# bound as the set of identifiers that exist.-MODEL_ID_MAX_LENGTH = 200--# The longest key a usage ledger row can carry, so a persisted row cannot grow-# without limit. It is also the exact length of a folded key: a head bounded by the-# admission bound, one separator, one hex digest. Every key the ledger derives is-# therefore either at most `MODEL_ID_MAX_LENGTH` (stored verbatim) or exactly this-# long (folded), and those two populations cannot overlap — an identifier long-# enough to occupy the folded form is itself folded before anything compares it.-USAGE_LEDGER_KEY_MAX_LENGTH = MODEL_ID_MAX_LENGTH + 1 + 2 * hashlib.sha256().digest_size+MODEL_ID_MAX_LENGTH = 256++# Usage rows shipped with a 200-character readable head. Keep that threshold+# stable even when a later API admits longer model identifiers, or one upgrade+# would start writing a second key for the same model's historical usage.+USAGE_LEDGER_VERBATIM_MAX_LENGTH = 200++# The longest key a usage ledger row can carry: the stable readable head, one+# separator, and one hex digest. At 265 characters it remains outside the model+# identifier admission namespace, so an admitted literal cannot collide with a+# folded key.+USAGE_LEDGER_KEY_MAX_LENGTH = (+ USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1 + 2 * hashlib.sha256().digest_size+)def normalized_model_id(value: str) -> str:@@ -78,22 +83,22 @@ def usage_ledger_key(value: object) -> str | None:would have every one of its calls dropped, and the tab would report anupgraded install as quieter than it actually is.- The bound therefore folds instead of refusing. A value within the admission- bound is its own key; anything longer is keyed by its readable head plus a- digest of the whole value, which is bounded, identical across restarts, and- separated from other identities by that digest rather than by a prefix an- adversary can pad.+ The bound therefore folds instead of refusing. A value within the ledger's+ stable verbatim threshold is its own key; anything longer is keyed by its+ readable head plus a digest of the whole value, which is bounded, identical+ across restarts, and separated from other identities by that digest rather+ than by a prefix an adversary can pad.Where the fold starts is the whole of why two distinct models cannot share one- row. It starts at the admission bound, not at the length of a folded key, so a- verbatim key is at most `MODEL_ID_MAX_LENGTH` and a folded key is always exactly- `USAGE_LEDGER_KEY_MAX_LENGTH`: two populations a length test tells apart. Fold- later and they overlap, and the folded form stops being ours — a config may hold- any string, including the literal `<head>~<digest>` of another model it also- holds, and that second model would then be keyed verbatim onto the first+ row. A verbatim key is at most `USAGE_LEDGER_VERBATIM_MAX_LENGTH` and a folded+ key is always exactly `USAGE_LEDGER_KEY_MAX_LENGTH`: two populations a length+ test tells apart. The folded length also remains above `MODEL_ID_MAX_LENGTH`,+ so no newly admitted model can occupy it literally. Fold later and the+ populations overlap, and the folded form stops being ours — a config may hold+ any legacy string, including the literal `<head>~<digest>` of another model it+ also holds, and that second model would then be keyed verbatim onto the firstmodel's row and billed for its calls. No marker can close that gap, because a- legacy identifier can carry any marker too. Only a length no admissible- identifier can reach can, and reaching it means being folded.+ legacy identifier can carry any marker too.Only a value carrying no identity at all — not text, or empty — has no key,and that is exactly the set no config can hold.@@ -102,10 +107,10 @@ def usage_ledger_key(value: object) -> str | None:if not isinstance(value, str) or not value:return Nonecanonical = normalized_model_id(value)- if len(canonical) <= MODEL_ID_MAX_LENGTH:+ if len(canonical) <= USAGE_LEDGER_VERBATIM_MAX_LENGTH:return canonicaldigest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()- return f"{canonical[:MODEL_ID_MAX_LENGTH]}~{digest}"+ return f"{canonical[:USAGE_LEDGER_VERBATIM_MAX_LENGTH]}~{digest}"def persisted_ledger_key(value: object) -> str | None:diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 7e54c74bd..bced3c4fd 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -500,6 +500,7 @@ class TurnTrace:model_supply_state: Optional[SupplyState] = Noneblockers: list[dict] = field(default_factory=list)gateway_source_id: Optional[str] = None+ gateway_request_model_id: Optional[str] = Nonegateway_model_id: Optional[str] = Noneambiguous: bool = Falseterminal_outcome: TurnOutcomeProjectionInput | None = None@@ -520,6 +521,7 @@ class PreparedGatewayRoute:requested_model_id: strresolved_model_id: strsource_id: str+ gateway_request_model_id: strclass GatewayTurnTerminalizer:@@ -885,8 +887,11 @@ class TurnCorrelationRegistry:)self._traces[turn_id] = traceelif (- trace.gateway_model_id is not None- and trace.gateway_model_id != requested_model_id+ trace.gateway_request_model_id is not None+ and requested_model_id not in {+ trace.gateway_request_model_id,+ trace.gateway_model_id,+ }):trace.ambiguous = Trueself._scopes[key].ambiguous_turns.add(turn_id)@@ -903,6 +908,7 @@ class TurnCorrelationRegistry:resolved_model_id: str,source_id: str,via_mapping: bool,+ gateway_request_model_id: str | None = None,) -> None:"""Retain routing independently from best-effort provenance attribution."""@@ -921,10 +927,12 @@ class TurnCorrelationRegistry:if exact is None:returnroute_turn_id = exact[0]+ request_model_id = gateway_request_model_id or resolved_model_idprepared = PreparedGatewayRoute(requested_model_id=requested_model_id,resolved_model_id=resolved_model_id,source_id=source_id,+ gateway_request_model_id=request_model_id,)existing = scope.prepared_routes.get(route_turn_id)if existing is not None and existing != prepared:@@ -954,6 +962,10 @@ class TurnCorrelationRegistry:trace.gateway_source_id is not Noneand trace.gateway_source_id != source_id)+ or (+ trace.gateway_request_model_id is not None+ and trace.gateway_request_model_id != request_model_id+ )or (trace.gateway_model_id is not Noneand trace.gateway_model_id != resolved_model_id@@ -963,6 +975,7 @@ class TurnCorrelationRegistry:self._scopes[key].ambiguous_turns.add(exact_turn_id)returntrace.gateway_source_id = source_id+ trace.gateway_request_model_id = request_model_idtrace.gateway_model_id = resolved_model_iddef gateway_resolution_model(@@ -989,13 +1002,23 @@ class TurnCorrelationRegistry:matching = [routefor route in active_routes- if route.resolved_model_id == gateway_model_id+ if route.gateway_request_model_id == gateway_model_id]+ # A backend started before this upgrade may still send the resolved+ # upstream id. Prefer the canonical request id, then accept the old+ # shape only when it still identifies one prepared route.+ if not matching:+ matching = [+ route+ for route in active_routes+ if route.resolved_model_id == gateway_model_id+ ]identities = {(route.requested_model_id,route.resolved_model_id,route.source_id,+ route.gateway_request_model_id,)for route in matching}diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 0ba74af0f..04bd53d61 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -133,6 +133,18 @@ async def dispatch_model_hub_rpc(if operation == "set_agent_mode":await _refresh_payload_backend(service, payload.get("backend"))return await service.set_agent_mode(payload.get("backend"), payload.get("mode"))+ if operation == "set_agent_models":+ await _refresh_payload_backend(service, payload.get("backend"))+ return await service.set_agent_models(+ payload.get("backend"),+ payload.get("baseline"),+ payload.get("models"),+ )+ if operation == "models_dev_matches":+ return await asyncio.to_thread(+ service.models_dev_matches,+ payload.get("query"),+ )if operation == "set_agent_chain":return await service.set_agent_chain(payload.get("backend"),diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex fdea3cc15..3f9382964 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -19,6 +19,7 @@ from config.v2_config import (CONFIG_LOCK,MODEL_HUB_BACKENDS,ModelHubAgentSupplyConfig,+ ModelHubBackendModelConfig,ModelHubConfig,model_hub_fixed_menu_ids,ModelHubMenuConfig,@@ -129,36 +130,43 @@ PRE_ATTEMPT_SETTLEMENT_GENERATION = 0def project_opencode_public_model(- identifier: str,- resolution: ModelHubTurnResolution,-) -> dict[str, Any] | None:- """Project one persisted OpenCode route without transport credentials."""-- inspection = (- resolution.candidate_hops[0]- if resolution.candidate_hops- else resolution.projectable_hops[0]- if resolution.projectable_hops- else None- )- if inspection is None or inspection.source is None or inspection.model_id is None:- return None- model = next(- (item for item in inspection.source.models if item.id == inspection.model_id),- None,- )+ model: ModelHubBackendModelConfig,+) -> dict[str, Any]:+ """Project backend-owned metadata without upstream Route details."""++ identifier = model.idprojected: dict[str, Any] = {"id": identifier,- "name": (- model.display_name- if model is not None and model.display_name- else identifier- ),- }- variants = {- effort: {"reasoningEffort": effort}- for effort in (model.reasoning_efforts if model is not None else ())+ "name": model.display_name or identifier,}+ if model.context_window is not None or model.max_output_tokens is not None:+ projected["limit"] = {+ key: value+ for key, value in (+ ("context", model.context_window),+ ("output", model.max_output_tokens),+ )+ if value is not None+ }+ modalities: dict[str, list[str]] = {}+ if model.input_modalities:+ modalities["input"] = list(model.input_modalities)+ if model.output_modalities:+ modalities["output"] = list(model.output_modalities)+ if modalities:+ projected["modalities"] = modalities+ if model.supports_tools is not None:+ projected["tool_call"] = model.supports_tools+ if model.supports_reasoning is not None:+ projected["reasoning"] = model.supports_reasoning+ variants = (+ {+ effort: {"reasoningEffort": effort}+ for effort in model.reasoning_efforts+ }+ if model.supports_reasoning is not False+ else {}+ )if variants:projected["variants"] = variantsreturn projected@@ -376,21 +384,11 @@ def _project_opencode_public_models(unavailable_source_ids: frozenset[str] = frozenset(),) -> dict[str, dict[str, Any]]:agent = config.agents["opencode"]- if agent.mode == "direct" or agent.menu is None:+ if agent.mode == "direct":return {}projected: dict[str, dict[str, Any]] = {}- for identifier in dict.fromkeys(agent.menu.checked):- resolution = resolve_model_hub_turn(- config,- "opencode",- identifier,- now=now,- unavailable_source_ids=unavailable_source_ids,- supply_channel="hub",- )- model = project_opencode_public_model(identifier, resolution)- if model is not None:- projected[identifier] = model+ for model in agent.models:+ projected[model.id] = project_opencode_public_model(model)return projected@@ -645,6 +643,9 @@ class ModelHubService:cli_presence_refresh: Optional[Callable[[bool, tuple[BackendName, ...] | None], None]] = None,+ backend_catalog_changed: Optional[+ Callable[[BackendName], Awaitable[None]]+ ] = None,now: Callable[[], datetime] = _utc_now,):self.store = store@@ -675,6 +676,7 @@ class ModelHubService:self.named_agents_override = named_agents_overrideself.cli_present_override = cli_present_overrideself.cli_presence_refresh = cli_presence_refresh+ self.backend_catalog_changed = backend_catalog_changedself.now = nowself.native_source_ready: Callable[[BackendName, ModelHubSourceConfig], bool] = (lambda _backend, _source: True@@ -721,9 +723,7 @@ class ModelHubService:requested_model: str,) -> list[str]:primary = (- list(_builtin_model_ids(agent.backend))- if agent.menu_kind == "fixed"- else list(agent.menu.checked if agent.menu else ())+ [model.id for model in agent.models])seen: set[str] = set()model_ids: list[str] = []@@ -1618,9 +1618,7 @@ class ModelHubService:@staticmethoddef _agent_menu_model_ids(agent: ModelHubAgentSupplyConfig) -> tuple[str, ...]:- if agent.menu_kind == "fixed":- return tuple(_builtin_model_ids(agent.backend))- return tuple(agent.menu.checked if agent.menu else ())+ return tuple(model.id for model in agent.models)def _added_to(self, source_id: str) -> list[dict]:config = self.store.load()@@ -2881,12 +2879,8 @@ class ModelHubService:if self.named_agents_override is not None:for name, pinned_model in self.named_agents_override(backend):add(pinned_model, name)- if agent.menu_kind == "open" and agent.menu is not None:- for identifier in agent.menu.checked:- add(identifier)- else:- for model_id in _builtin_model_ids(backend):- add(model_id)+ for model in agent.models:+ add(model.id)for model_id in agent.routes:add(model_id)return protected@@ -3371,9 +3365,55 @@ class ModelHubService:# deletion may annotate or remove exact hops, but never re-match menus.return+ @staticmethod+ def _catalog_model_payload(model: ModelHubBackendModelConfig) -> dict:+ return {+ **model.to_payload(),+ "locked": False,+ "routeable": True,+ }++ @staticmethod+ def _claude_default_catalog_payload() -> dict:+ return {+ "id": "default",+ "display_name": None,+ "origin": "builtin",+ "models_dev_id": None,+ "context_window": None,+ "max_output_tokens": None,+ "input_modalities": [],+ "output_modalities": [],+ "supports_tools": None,+ "supports_reasoning": None,+ "reasoning_efforts": [],+ "locked": True,+ "routeable": False,+ }++ @classmethod+ def _catalog_models_payload(+ cls,+ agent: ModelHubAgentSupplyConfig,+ ) -> list[dict]:+ models = [cls._catalog_model_payload(model) for model in agent.models]+ if agent.backend == "claude":+ models.insert(0, cls._claude_default_catalog_payload())+ return models++ def backend_catalog_models(self, backend: str) -> list[dict]:+ if backend not in MODEL_HUB_BACKENDS:+ raise ModelHubError("mapping_target_unavailable", status=404)+ config = self.store.load()+ return self._catalog_models_payload(config.agents[backend])+def _agent_payload(self, config: ModelHubConfig, agent: ModelHubAgentSupplyConfig) -> dict:backend = cast(BackendName, agent.backend)- builtin_models = list(_builtin_model_ids(agent.backend)) if agent.menu_kind == "fixed" else None+ builtin_models = (+ [model.id for model in agent.models]+ if agent.menu_kind == "fixed"+ else None+ )standard_vendors = sorted(STANDARD_OPENCODE_VENDOR_IDS) if agent.backend == "opencode" else Nonerequested_model = self._requested_model(agent)unavailable_source_ids = self._unavailable_native_sources(config, backend)@@ -3385,9 +3425,7 @@ class ModelHubService:now=now,unavailable_source_ids=unavailable_source_ids,)- menu_model_ids = (- builtin_models if builtin_models is not None else list(agent.menu.checked if agent.menu else ())- )+ menu_model_ids = [model.id for model in agent.models]model_supply = [{"model_id": model_id,@@ -3474,6 +3512,7 @@ class ModelHubService:})agent_payload = agent.to_payload()+ agent_payload.pop("models", None)agent_payload["routes"] = (agent_payload["routes"] if agent.mode == "hub" else None)@@ -3493,6 +3532,7 @@ class ModelHubService:),"model_supply": model_supply if agent.mode == "hub" else None,"named_agents": named_agents,+ "catalog_models": self._catalog_models_payload(agent),"builtin_models": builtin_models,"standard_vendors": standard_vendors,}@@ -3634,11 +3674,26 @@ class ModelHubService:),checked=merged_checked,)+ current_models = {model.id: model for model in agent.models}candidate = agent.to_payload()candidate["menu"] = merged_menu.to_payload()- candidate_routes = cast(dict, candidate["routes"])+ candidate["models"] = [+ (+ current_models.get(identifier)+ or ModelHubBackendModelConfig(+ id=identifier,+ origin="manual",+ )+ ).to_payload()+ for identifier in merged_menu.checked+ ]+ merged_routes = dict(agent.routes)for identifier in merged_menu.checked:- candidate_routes.setdefault(identifier, ModelHubRouteConfig().to_payload())+ merged_routes.setdefault(identifier, ModelHubRouteConfig())+ candidate["routes"] = {+ identifier: route.to_payload()+ for identifier, route in merged_routes.items()+ }parsed = ModelHubAgentSupplyConfig.from_payload(candidate,expected_backend="opencode",@@ -3650,9 +3705,208 @@ class ModelHubService:raise ModelHubError("mapping_target_unavailable", status=409)agent.menu = parsed.menuagent.routes = parsed.routes+ agent.models = parsed.modelsawait self._commit_synced(previous, config)+ if self.backend_catalog_changed is not None:+ await self._refresh_backend_catalog("opencode")return self._agent_payload(config, agent)+ @classmethod+ def _parse_backend_catalog_models(+ cls,+ backend: str,+ payload: object,+ ) -> list[ModelHubBackendModelConfig]:+ if backend not in MODEL_HUB_BACKENDS:+ raise ModelHubError("mapping_target_unavailable")+ if not isinstance(payload, list):+ raise ModelHubError("backend_model_catalog_invalid")+ default_indices = [+ index+ for index, item in enumerate(payload)+ if isinstance(item, dict) and item.get("id") == "default"+ ]+ if backend == "claude":+ if (+ default_indices != [0]+ or payload[0] != cls._claude_default_catalog_payload()+ ):+ raise ModelHubError("backend_model_locked", status=409)+ rows: list[ModelHubBackendModelConfig] = []+ for item in payload:+ if (+ backend == "claude"+ and isinstance(item, dict)+ and item.get("id") == "default"+ ):+ continue+ try:+ model = ModelHubBackendModelConfig.from_payload(item)+ except (TypeError, ValueError) as exc:+ raise ModelHubError("backend_model_catalog_invalid") from exc+ if backend == "opencode":+ try:+ canonical_opencode_menu_identity(model.id)+ except ValueError as exc:+ raise ModelHubError("backend_model_id_invalid") from exc+ rows.append(model)+ if len({model.id for model in rows}) != len(rows):+ raise ModelHubError("backend_model_duplicate")+ return rows++ async def _refresh_backend_catalog(self, backend: BackendName) -> None:+ if self.backend_catalog_changed is None:+ return+ try:+ await self.backend_catalog_changed(backend)+ except ModelHubError:+ raise+ except Exception as exc:+ raise ModelHubError("engine_down", status=503) from exc++ async def set_agent_models(+ self,+ backend: str,+ baseline: object,+ models: object,+ ) -> dict:+ async with self._mutation_lock:+ previous = self.store.load()+ config = self._clone_config(previous)+ agent = self._agent(config, backend)+ baseline_models = self._parse_backend_catalog_models(+ backend,+ baseline,+ )+ desired_models = self._parse_backend_catalog_models(+ backend,+ models,+ )++ current_by_id = {model.id: model for model in agent.models}+ baseline_by_id = {model.id: model for model in baseline_models}+ desired_by_id = {model.id: model for model in desired_models}+ for model_id in desired_by_id.keys() - current_by_id.keys():+ canonical = canonical_model_id(model_id)+ if canonical is None or canonical != model_id:+ raise ModelHubError("backend_model_id_invalid")+ for model_id, desired in desired_by_id.items():+ trusted = current_by_id.get(model_id) or baseline_by_id.get(model_id)+ if (+ (trusted is None and desired.origin == "builtin")+ or (trusted is not None and desired.origin != trusted.origin)+ ):+ raise ModelHubError("backend_model_locked", status=409)+ for model_id in desired_by_id.keys() - current_by_id.keys():+ if (+ backend == "claude"+ and model_id not in _builtin_model_ids("claude")+ and not model_id.startswith(("claude-", "anthropic-"))+ ):+ raise ModelHubError("backend_model_id_prefix")+ merged_by_id = dict(current_by_id)++ for model_id in baseline_by_id.keys() - desired_by_id.keys():+ route = agent.routes.get(model_id)+ if route is not None and route.hops:+ raise ModelHubError(+ "backend_model_in_route",+ status=409,+ data={"model_id": model_id},+ )+ current = current_by_id.get(model_id)+ if current is not None and current != baseline_by_id[model_id]:+ raise ModelHubError("backend_model_conflict", status=409)+ merged_by_id.pop(model_id, None)+ agent.routes.pop(model_id, None)++ for model_id, desired in desired_by_id.items():+ baseline_model = baseline_by_id.get(model_id)+ current = current_by_id.get(model_id)+ if baseline_model is None:+ if current is not None and current != desired:+ raise ModelHubError("backend_model_conflict", status=409)+ merged_by_id[model_id] = desired+ agent.routes.setdefault(model_id, ModelHubRouteConfig())+ continue+ if current is None:+ if desired != baseline_model:+ raise ModelHubError("backend_model_conflict", status=409)+ continue+ if (+ desired != baseline_model+ and current != baseline_model+ and current != desired+ ):+ raise ModelHubError("backend_model_conflict", status=409)+ if desired != baseline_model:+ merged_by_id[model_id] = desired++ baseline_survivors = [+ model.id for model in baseline_models if model.id in desired_by_id+ ]+ desired_existing = [+ model.id for model in desired_models if model.id in baseline_by_id+ ]+ desired_order = [model.id for model in desired_models]+ appended_order = [+ *baseline_survivors,+ *(+ model.id+ for model in desired_models+ if model.id not in baseline_by_id+ ),+ ]+ order_changed = (+ baseline_survivors != desired_existing+ or desired_order != appended_order+ )+ concurrent_ids = [+ model.id+ for model in agent.models+ if model.id not in baseline_by_id and model.id not in desired_by_id+ ]+ if order_changed:+ ordered_ids = [+ model.id for model in desired_models if model.id in merged_by_id+ ]+ ordered_ids.extend(+ model_id+ for model_id in concurrent_ids+ if model_id in merged_by_id and model_id not in ordered_ids+ )+ else:+ ordered_ids = [+ model.id for model in agent.models if model.id in merged_by_id+ ]+ for model in desired_models:+ if model.id not in ordered_ids and model.id in merged_by_id:+ ordered_ids.append(model.id)+ agent.models = [merged_by_id[model_id] for model_id in ordered_ids]+ if agent.backend == "opencode":+ agent.menu = ModelHubMenuConfig(+ view=agent.menu.view if agent.menu else "featured",+ checked=list(ordered_ids),+ )+ await self._commit_synced(previous, config)+ await self._refresh_backend_catalog(cast(BackendName, backend))+ committed = self.store.load()+ return self._agent_payload(+ committed,+ self._agent(committed, backend),+ )++ @staticmethod+ def models_dev_matches(query: object) -> list[dict]:+ if not isinstance(query, str) or not query.strip() or len(query) > 256:+ raise ModelHubError("mapping_target_unavailable")+ from vibe.models_dev_catalog import search_models_dev++ try:+ return search_models_dev(query)+ except (OSError, RuntimeError, ValueError):+ raise ModelHubError("models_dev_unavailable", status=502) from None+@staticmethoddef _validated_reasoning_efforts(model: ModelHubModelConfig,@@ -5738,6 +5992,9 @@ def create_default_service(cli_presence_refresh: Optional[Callable[[bool, tuple[BackendName, ...] | None], None]] = None,+ backend_catalog_changed: Optional[+ Callable[[BackendName], Awaitable[None]]+ ] = None,) -> ModelHubService:if adapter is None:from vibe.model_hub_runtime import get_model_hub_engine_adapter@@ -5785,4 +6042,5 @@ def create_default_service(named_agents_override=named_agents_override,cli_present_override=cli_present_override,cli_presence_refresh=cli_presence_refresh,+ backend_catalog_changed=backend_catalog_changed,)diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex e6e006f50..f164b1243 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -328,6 +328,7 @@ class ModelHubTurnGateway:resolved_model_id: Optional[str] = None,source_id: Optional[str] = None,via_mapping: bool = False,+ gateway_request_model_id: Optional[str] = None,) -> tuple[str, str]:if backend not in {"claude", "codex", "opencode"}:raise ModelHubError("mapping_target_unavailable", status=409)@@ -342,6 +343,7 @@ class ModelHubTurnGateway:resolved_model_id=resolved_model_id,source_id=source_id,via_mapping=via_mapping,+ gateway_request_model_id=gateway_request_model_id,)await self._ensure_started()assert self._base_url is not None@@ -371,6 +373,7 @@ class ModelHubTurnGateway:if self._runner is not None:returnapp = web.Application(client_max_size=_MAX_REQUEST_BYTES)+ app.router.add_get("/{backend}/v1/models", self._handle_models)app.router.add_post("/{backend}/v1/{endpoint:.*}", self._handle_request)runner = web.AppRunner(app,@@ -404,6 +407,37 @@ class ModelHubTurnGateway:return candidatereturn None+ async def _handle_models(self, request: web.Request) -> web.StreamResponse:+ backend = request.match_info["backend"]+ if self._authorized_token(request, backend) is None:+ return self._error_response(status=401, code="authentication_error")+ try:+ models = self.service.backend_catalog_models(backend)+ except ModelHubError as exc:+ return self._error_response(status=exc.status, code=exc.code)+ rows = [+ {+ "id": model["id"],+ "display_name": model.get("display_name") or model["id"],+ "type": "model",+ "created_at": "1970-01-01T00:00:00Z",+ }+ for model in models+ if model.get("routeable") is True+ ]+ return web.json_response(+ {+ "data": rows,+ "has_more": False,+ "first_id": rows[0]["id"] if rows else None,+ "last_id": rows[-1]["id"] if rows else None,+ },+ headers={+ "Cache-Control": "no-store",+ "X-Content-Type-Options": "nosniff",+ },+ )+async def _handle_request(self, request: web.Request) -> web.StreamResponse:backend = request.match_info["backend"]token = self._authorized_token(request, backend)diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 1f6d3bc69..0f6059c8a 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -1454,10 +1454,20 @@ class SessionHandler(BaseHandler):)from modules.agents.opencode.utils import normalize_claude_reasoning_effort+ catalog_efforts = (+ model_hub_launch.reasoning_efforts+ if model_hub_launch is not None+ and model_hub_launch.backend == "claude"+ and model_hub_launch.channel in {"hub", "native_cli"}+ else backend_model_catalog.catalog_reasoning_efforts_for_model(+ "claude",+ effective_model,+ )+ )effective_effort = normalize_claude_reasoning_effort(effective_model,explicit_effort,- backend_model_catalog.catalog_reasoning_efforts_for_model("claude", effective_model),+ catalog_efforts,)# Determine final system prompt: agent prompt takes precedence over config.diff --git a/docs/plans/backend-model-catalogs.md b/docs/plans/backend-model-catalogs.mdnew file mode 100644index 000000000..8ee794374--- /dev/null+++ b/docs/plans/backend-model-catalogs.md@@ -0,0 +1,92 @@+# Backend Model Catalogs++Status: implementation contract++## Outcome++Every Model Hub backend has one editable model catalog. The catalog controls the models+the Agent can select and stores one canonical capability description; each runtime adapter+consumes the subset its backend can represent. Supplier inventory and Routes keep their+current ownership.++For example, adding `deepseek-v3.2` to the Codex catalog makes that id appear in Codex.+It does not choose an upstream provider. The new row appears separately in the Route+panel, where the user can configure `aihub/deepseek-v3.2` and any fallbacks.++## One product model++The three Gateway backend cards expose the same `Manage models` action and the same+list/editor interaction. Their runtime adapters remain different:++| Backend | Catalog projection |+| --- | --- |+| Claude Code | The Gateway serves model ids while discovery is enabled. Context and output limits are injected for the selected Hub model. Claude Code's own `Default` selector remains visible and locked. Other canonical fields remain stored metadata. |+| Codex | Avibe writes a content-addressed `model_catalog_json` derived from the running binary's native schema. It projects display name, context, supported input modalities, and reasoning efforts; fields Codex cannot represent remain stored metadata. |+| OpenCode | Avibe writes the configured rows into its private runtime provider overlay, including context/output limits, modalities, tool/reasoning support, and reasoning variants. |++The shared catalog is authoritative. Adapter-specific files are derived runtime artifacts;+they are never edited by the user and never become another source of product state.++## Data ownership++`BackendModel` is defined by `model-hub-contracts/backend-model.schema.json`. The order+of `catalog_models` is the Agent menu order. Editable metadata is persisted under the+backend Agent supply configuration. `locked` and `routeable` are response-only server+projections.++The catalog deliberately contains no Source id, upstream model id, Route status, priority,+or fallback. Removing a routeable model is refused while a non-empty Route still uses its+id; the user removes the Route first, then the model. Supplier models are never removed by+a backend catalog mutation.++Existing installations migrate without losing routes:++- Claude Code and Codex seed their initial catalogs from the bundled backend catalog.+- OpenCode seeds its initial catalog from the existing checked menu, preserving order.+- Existing route keys not already present are appended as catalog rows so a configured+ Route never becomes invisible during migration.++## models.dev++models.dev is an optional metadata source, not an authority. The user enters a backend+model id, asks Avibe to fill it, selects a match when needed, and can edit every populated+field before or after saving. Avibe stores the chosen `provider/model` match and the+normalized snapshot; later models.dev changes do not silently overwrite user settings.++Avibe fetches the public catalog through a server-owned, conditional local cache. A failed+refresh may use a stale cache; no cache means the fill action fails explicitly while manual+entry remains available. Cost is not stored because no current backend catalog projection+consumes it.++## Mutations++`PUT /api/models/agents/<backend>/models` accepts `{baseline, models}`. `baseline` is the+last full list observed by the caller and `models` is its desired replacement. The server+applies the caller's adds, edits, removals, and order changes to the latest list while+preserving unrelated concurrent mutations. Duplicate ids, invalid backend-specific ids,+locked-row changes, and removal of a model with a non-empty Route are rejected.++`GET /api/models/catalog/models-dev?query=<text>` returns normalized matches. It does not+persist anything.++After a successful catalog mutation, the controller invalidates the affected backend's+runtime projection. The next turn observes the committed catalog; an already running+OpenCode server is refreshed before the mutation reports success.++Catalog storage is mode-independent so a Direct to Gateway switch preserves prior work.+The product editor is Gateway-only: Direct mode continues to use each CLI's native model+menu, so showing this editor there would falsely imply that these rows change Direct mode.++## Acceptance++- All three backend cards open the same model-list interaction.+- Add, edit, remove, search, and drag reorder work without exposing Route controls in the+ model-list dialog.+- A models.dev match fills context, output, modality, tool, reasoning, and effort fields,+ and user edits survive reload.+- A catalog change is visible in the corresponding real backend selector after runtime+ refresh.+- Existing Source inventory and Route chains remain byte-for-byte unchanged except when a+ user separately edits them.+- Direct mode preserves the catalog unchanged; switching back to Gateway restores the+ same editable list.diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 0160ba583..041a8c02b 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -145,6 +145,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| `source.schema.json` | Source identity, channel, three protocols, state, usage, inventory, credential reference, and audit metadata. || `source-create.schema.json` | API-key Source creation request, transient credential boundary, optional single-protocol constraint, and lost-response correlation. || `agent-supply.schema.json` | Backend mode, explicit policy-free Source order, configuration eligibility, model-supply and backend-health projections. |+| `backend-model.schema.json` | Backend Agent model identity, editable capability metadata, and server-owned lock/routeability projection. || `agent-chain.schema.json` | Read projection of exact stored hops plus current execution position, runnability, blockers, live connection backoff, retry metadata, and model supply state. || `probe-result.schema.json` | Saved recovery probes and route probes over exact configured hops, including the live connection-backoff reason without persistent network health. || `observation-result.schema.json` | Non-persisting Add-time connectivity, authentication, response-backed protocol, and inventory observation. |diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex 6ea675289..7f7234767 100644--- a/docs/plans/model-hub-contracts/agent-supply.schema.json+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json@@ -17,6 +17,11 @@"description": "Gateway or Direct. Existing installations start Direct until the user switches; fresh installations default Gateway. A native_cli Source is one configured Gateway hop and is distinct from Direct mode."},"menu_kind": { "enum": ["fixed", "open"] },+ "catalog_models": {+ "type": "array",+ "description": "The ordered backend Agent model catalog. It controls the Agent menu and capability metadata only; Route configuration remains in routes.",+ "items": { "$ref": "backend-model.schema.json" }+ },"selected_by_agent": {"type": ["string", "null"],"description": "The Vibe Agent whose explicit `model` produced `selected_model_id`, by name. Model selection does not live at the backend grain: several enabled Vibe Agents can share one backend and each carry a different model. Derived, never persisted; null while mode=direct or when no routed Agent is projected.",@@ -217,7 +222,7 @@]}},- "builtin_models": { "type": ["array", "null"], "items": { "type": "string" }, "description": "v1.2 (2026-07-24 integration): fixed-menu backends only — real built-in model ids, server-populated from vibe/backend_model_catalog.py; null for open-menu backends. UI must not hardcode menus." },+ "builtin_models": { "type": ["array", "null"], "items": { "type": "string" }, "description": "Compatibility projection for older clients. New clients consume catalog_models." },"standard_vendors": { "type": ["array", "null"], "items": { "type": "string" }, "description": "v1.2 (2026-07-24 integration): opencode only — server-populated mirror of STANDARD_OPENCODE_VENDOR_IDS (core/handlers/model_hub/identifiers.py) so the UI never hand-mirrors vendor lists; null otherwise." }},"allOf": [diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex 890e5f081..80d825e12 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -21,6 +21,9 @@{"method": "PUT", "path": "/api/models/agents/<backend>/sources", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/sources", "status": 200, "json": {"order": ["src_conform001"]}}},{"method": "POST", "path": "/api/models/agents/<backend>/chains/reorder", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/chains/reorder", "status": 200}},{"method": "PATCH", "path": "/api/models/agents/<backend>/mode", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/mode", "status": 200, "json": {"mode": "hub"}}},+ {"method": "GET", "path": "/api/models/agents/<backend>/models", "response_schema": "AgentCatalogResponse", "exercise": {"path": "/api/models/agents/claude/models", "status": 200}},+ {"method": "PUT", "path": "/api/models/agents/<backend>/models", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/models", "status": 200, "json": {"baseline": [{"id":"default","display_name":null,"origin":"builtin","models_dev_id":null,"context_window":null,"max_output_tokens":null,"input_modalities":[],"output_modalities":[],"supports_tools":null,"supports_reasoning":null,"reasoning_efforts":[],"locked":true,"routeable":false}], "models": [{"id":"default","display_name":null,"origin":"builtin","models_dev_id":null,"context_window":null,"max_output_tokens":null,"input_modalities":[],"output_modalities":[],"supports_tools":null,"supports_reasoning":null,"reasoning_efforts":[],"locked":true,"routeable":false}]}}},+ {"method": "GET", "path": "/api/models/catalog/models-dev?query=<text>", "response_schema": "ModelsDevResponse", "exercise": {"path": "/api/models/catalog/models-dev?query=contract-model", "status": 200}},{"method": "PUT", "path": "/api/models/agents/opencode/menu", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/opencode/menu", "status": 200, "json": {"baseline": {"view": "featured", "checked": []}, "menu": {"view": "featured", "checked": []}}}},{"method": "GET", "path": "/api/models/agents/<backend>/chains", "response_schema": "ChainListResponse", "exercise": {"path": "/api/models/agents/claude/chains", "status": 200}},{"method": "GET", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200}},@@ -58,7 +61,7 @@"allOf": [{"$ref": "model-hub/agent-supply.schema.json"},{- "required": ["backend", "cli_present", "mode", "menu_kind", "selected_by_agent", "selected_model_id", "selected_model_explicit", "sources", "routes", "supply_status", "menu", "model_supply", "named_agents", "builtin_models", "standard_vendors"],+ "required": ["backend", "cli_present", "mode", "menu_kind", "catalog_models", "selected_by_agent", "selected_model_id", "selected_model_explicit", "sources", "routes", "supply_status", "menu", "model_supply", "named_agents", "builtin_models", "standard_vendors"],"properties": {"sources": {"oneOf": [@@ -224,6 +227,59 @@"agent": {"$ref": "#/definitions/AgentSupplyApi"}}},+ "AgentCatalogResponse": {+ "type": "object",+ "required": ["ok", "contract_version", "agent"],+ "additionalProperties": false,+ "properties": {+ "ok": {"const": true},+ "contract_version": {"const": 6},+ "agent": {+ "type": "object",+ "required": ["backend", "mode", "catalog_models"],+ "additionalProperties": false,+ "properties": {+ "backend": {"enum": ["claude", "codex", "opencode"]},+ "mode": {"enum": ["hub", "direct"]},+ "catalog_models": {+ "type": "array",+ "items": {"$ref": "model-hub/backend-model.schema.json"}+ }+ }+ }+ }+ },+ "ModelsDevResponse": {+ "type": "object",+ "required": ["ok", "contract_version", "matches"],+ "additionalProperties": false,+ "properties": {+ "ok": {"const": true},+ "contract_version": {"const": 6},+ "matches": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["provider_id", "provider_name", "model_id", "models_dev_id", "display_name", "context_window", "max_output_tokens", "input_modalities", "output_modalities", "supports_tools", "supports_reasoning", "reasoning_efforts"],+ "additionalProperties": false,+ "properties": {+ "provider_id": {"type": "string", "minLength": 1},+ "provider_name": {"type": "string", "minLength": 1},+ "model_id": {"type": "string", "minLength": 1},+ "models_dev_id": {"type": "string", "minLength": 3},+ "display_name": {"type": "string", "minLength": 1},+ "context_window": {"type": ["integer", "null"], "minimum": 1},+ "max_output_tokens": {"type": ["integer", "null"], "minimum": 1},+ "input_modalities": {"type": "array", "items": {"enum": ["text", "image", "audio", "video", "pdf"]}, "uniqueItems": true},+ "output_modalities": {"type": "array", "items": {"enum": ["text", "image", "audio", "video"]}, "uniqueItems": true},+ "supports_tools": {"type": ["boolean", "null"]},+ "supports_reasoning": {"type": ["boolean", "null"]},+ "reasoning_efforts": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}+ }+ }+ }+ }+ },"ChainResponse": {"type": "object","required": ["ok", "contract_version", "chain"],diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex a76729a1e..ab3033664 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -40,6 +40,9 @@ compatibility path.| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. This route never touches a Route chain and has no guarded `409` branch. || POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[]}` → `{agent: AgentSupply}` | With `order`, atomically stores the complete Source order and idempotently reorders every stored Route by it; with no body, applies the already stored order. In either form it adds, removes, remaps, matches, and guards nothing. The total order is defined below. || PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. |+| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data; editors use it as the Gateway model menu and fall back to the backend-native catalog in Direct mode, during a rolling upgrade from a pre-catalog server, or while this read is unavailable. |+| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[]}` → `{agent: AgentSupply}` | Applies one full-list backend catalog edit with optimistic merge. The list controls Agent-visible ids, order, and capability metadata only. Removing a model with a non-empty Route is refused; this mutation never changes supplier inventory or Route hops. |+| GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results normalize models.dev metadata into editable BackendModel fields and never persist automatically. || PUT `/api/models/agents/opencode/menu` | `{baseline: AgentMenu, menu: AgentMenu}` → `{agent: AgentSupply}` | Atomically applies the additions, removals, and optional view change between `baseline` and `menu` to the latest stored OpenCode menu. Concurrent unrelated selections survive. A newly added identifier must still be supplied by current OpenCode-eligible inventory at commit time; this includes a dormant Route alias whose saved Route retains an exact eligible inventory hop. Already checked route aliases may be preserved or removed without same-name inventory. || GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. || GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |diff --git a/docs/plans/model-hub-contracts/backend-model.schema.json b/docs/plans/model-hub-contracts/backend-model.schema.jsonnew file mode 100644index 000000000..5bc112ed2--- /dev/null+++ b/docs/plans/model-hub-contracts/backend-model.schema.json@@ -0,0 +1,86 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/backend-model.schema.json",+ "title": "BackendModel",+ "description": "One model exposed by a backend Agent. This is backend menu metadata, not upstream inventory and not a Route.",+ "type": "object",+ "required": [+ "id",+ "display_name",+ "origin",+ "models_dev_id",+ "context_window",+ "max_output_tokens",+ "input_modalities",+ "output_modalities",+ "supports_tools",+ "supports_reasoning",+ "reasoning_efforts",+ "locked",+ "routeable"+ ],+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": "string",+ "minLength": 1,+ "description": "The exact identifier shown to and emitted by the backend Agent. OpenCode identifiers use provider/model form. Responses may echo longer identifiers persisted by older releases; mutation admission limits newly added identifiers to 256 characters."+ },+ "display_name": {+ "type": ["string", "null"],+ "description": "Optional human-readable label. The backend id remains the routing identity."+ },+ "origin": {+ "enum": ["builtin", "models_dev", "manual"],+ "description": "How this row was first created. User edits remain authoritative regardless of origin."+ },+ "models_dev_id": {+ "type": ["string", "null"],+ "description": "The provider/model identity selected from models.dev, or null when no match has been selected. Filling metadata later does not change an existing row's origin."+ },+ "context_window": {+ "type": ["integer", "null"],+ "minimum": 1,+ "description": "Maximum context tokens used by the backend for context budgeting."+ },+ "max_output_tokens": {+ "type": ["integer", "null"],+ "minimum": 1,+ "description": "Maximum output tokens advertised to the backend."+ },+ "input_modalities": {+ "type": "array",+ "items": { "enum": ["text", "image", "audio", "video", "pdf"] },+ "uniqueItems": true,+ "description": "Explicitly supported input modalities. An empty array leaves native metadata in place when the backend has it and otherwise uses that backend adapter's safe default."+ },+ "output_modalities": {+ "type": "array",+ "items": { "enum": ["text", "image", "audio", "video"] },+ "uniqueItems": true,+ "description": "Explicitly supported output modalities. An empty array leaves native metadata in place when the backend has it and otherwise uses that backend adapter's safe default."+ },+ "supports_tools": {+ "type": ["boolean", "null"],+ "description": "True or false explicitly overrides tool support in the backend projection. Null omits that override and preserves the backend's own default."+ },+ "supports_reasoning": {+ "type": ["boolean", "null"],+ "description": "True or false explicitly overrides reasoning support in the backend projection. Null omits that override and preserves the backend's own default."+ },+ "reasoning_efforts": {+ "type": "array",+ "items": { "type": "string", "minLength": 1, "maxLength": 64 },+ "uniqueItems": true,+ "description": "Effort values are sent verbatim unless supports_reasoning is false. False suppresses their runtime projection without deleting the list, so returning the capability to null is lossless. An empty array means the backend omits the effort parameter."+ },+ "locked": {+ "type": "boolean",+ "description": "Server-derived. A locked system row is visible but cannot be edited, removed, or reordered."+ },+ "routeable": {+ "type": "boolean",+ "description": "Server-derived. False only for a backend-owned selector such as Claude Code Default that never names a Route key."+ }+ }+}diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex 0c7edda10..d4b94aa05 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -91,15 +91,12 @@ time order once two rows carry different UTC offsets.Identity is decided once, by `canonical_model_id` in `identifiers.py`: a model ID istrimmed, non-empty, and within `MODEL_ID_MAX_LENGTH`. Both boundaries that admit one-(discovery and custom-model mapping) store what it returns, and the ledger keys rows-by it, so config, resolution, and metering cannot disagree about what "the same-model" means — two spellings of one ID would otherwise become two rows in the tab,-and a listing naming one model twice is a failed discovery rather than two models.-The ledger's re-check is therefore unreachable for anything the hub admits, so it-logs a warning rather than dropping silently: a future boundary that forgets should-show up as lost metering, not as a quietly incomplete tab. The rule is deliberately-*not* applied when loading persisted config — per the persisted-shape rule, a legacy-value must not make startup fail.+(discovery and custom-model mapping) store what it returns, so config and resolution+cannot disagree about what "the same model" means. Metering preserves that identity+through `usage_ledger_key`: keys up to the shipped 200-character verbatim threshold+remain unchanged and longer identities fold to the same bounded key across upgrades.+The ledger never re-runs admission because a persisted legacy model must remain+meterable even when a new request could no longer add that identifier.Every cross-field promise the read contract makes is a `_COUNTER_SUBSETS` entryrepaired in one place — cached input inside input, token reports inside requests —diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex a7d26fda0..850a62ff1 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -804,6 +804,11 @@ class CodexAgent(BaseAgent):self._model_hub_catalog_path = Noneawait self.refresh_auth_state()+ async def invalidate_model_hub_runtime(self) -> None:+ """Make the next Hub launch rebuild its catalog without touching Direct transports."""+ self._model_hub_catalog_generation += 1+ self._model_hub_catalog_path = None+async def prepare_model_hub_runtime(self) -> Path:"""Bind Hub metadata to this Agent's exact configured Codex binary."""from vibe import backend_model_catalog@@ -813,10 +818,20 @@ class CodexAgent(BaseAgent):return self._model_hub_catalog_pathgeneration = self._model_hub_catalog_generationbinary = self.codex_config.binary+ configured_models = None+ model_hub_service = getattr(self.controller, "model_hub_service", None)+ store = getattr(model_hub_service, "store", None)+ if store is not None:+ configured_models = [+ model.to_payload()+ for model in store.load().agents["codex"].models+ ]try:path = await asyncio.to_thread(backend_model_catalog.prepare_codex_hub_catalog,binary,+ None,+ configured_models,)except Exception as exc:raise CodexModelHubCatalogUnavailableError(@@ -2060,13 +2075,18 @@ class CodexAgent(BaseAgent):logger.warning("Failed to load Codex subagent %s: %s", effective_agent, exc)effective_model = explicit_model or (agent_definition.model if agent_definition else None)+ effective_effort = explicit_effort or (agent_definition.reasoning_effort if agent_definition else None)if getattr(self.controller, "model_hub_runtime", None) is not None:from modules.agents.model_hub import launch_for_contextlaunch = launch_for_context(getattr(request, "context", None))if launch is not None and launch.backend == "codex":effective_model = launch.runtime_model or effective_model- effective_effort = explicit_effort or (agent_definition.reasoning_effort if agent_definition else None)+ if (+ launch.channel != "direct"+ and effective_effort not in launch.reasoning_efforts+ ):+ effective_effort = Nonedeveloper_instructions = vibe_instructions or (agent_definition.developer_instructions if agent_definition else None)return effective_agent, effective_model, effective_effort, developer_instructionsdiff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex bffc5408f..d4c895987 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -76,6 +76,11 @@ class ModelHubLaunch:source_id: Optional[str] = Nonegateway_base_url: Optional[str] = Nonegateway_token: Optional[str] = None+ context_window: Optional[int] = None+ max_output_tokens: Optional[int] = None+ supports_tools: Optional[bool] = None+ supports_reasoning: Optional[bool] = None+ reasoning_efforts: tuple[str, ...] = ()settlement_generation: Optional[int] = field(default=None, repr=False)@property@@ -83,15 +88,29 @@ class ModelHubLaunch:if self.channel == "direct":return "direct"if self.channel == "native_cli":- return f"native_cli:{self.source_id or ''}"- token_hash = hashlib.sha256((self.gateway_token or "").encode()).hexdigest()- return ":".join(- (- self.channel,- self.gateway_base_url or "",- token_hash,+ identity = f"native_cli:{self.source_id or ''}"+ else:+ token_hash = hashlib.sha256((self.gateway_token or "").encode()).hexdigest()+ identity = ":".join(+ (+ self.channel,+ self.gateway_base_url or "",+ token_hash,+ ))+ if self.backend != "claude":+ return identity+ process_settings = json.dumps(+ {+ "context_window": self.context_window,+ "max_output_tokens": self.max_output_tokens,+ "reasoning_efforts": self.reasoning_efforts,+ },+ sort_keys=True,+ separators=(",", ":"),)+ settings_hash = hashlib.sha256(process_settings.encode()).hexdigest()+ return f"{identity}:settings:{settings_hash}"@dataclass(frozen=True)@@ -280,17 +299,35 @@ def build_claude_hub_env(base_env: dict[str, str],launch: ModelHubLaunch,) -> dict[str, str]:- """Return a hub-only Claude environment without inherited auth routing."""+ """Return Claude environment overrides for the resolved Hub launch."""- if launch.channel != "hub" or not launch.gateway_base_url or not launch.gateway_token:+ if launch.channel == "direct":return dict(base_env)- result = {- key: value- for key, value in base_env.items()- if not key.startswith("ANTHROPIC_") and key != "CLAUDE_CODE_OAUTH_TOKEN"- }- result["ANTHROPIC_BASE_URL"] = launch.gateway_base_url- result["ANTHROPIC_AUTH_TOKEN"] = launch.gateway_token+ if launch.channel == "hub":+ if not launch.gateway_base_url or not launch.gateway_token:+ return dict(base_env)+ result = {+ key: value+ for key, value in base_env.items()+ if not key.startswith("ANTHROPIC_")+ and key+ not in {+ "CLAUDE_CODE_OAUTH_TOKEN",+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS",+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS",+ }+ }+ result["ANTHROPIC_BASE_URL"] = launch.gateway_base_url+ result["ANTHROPIC_AUTH_TOKEN"] = launch.gateway_token+ result["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] = "1"+ else:+ # A native_cli hop keeps the user's official CLI authentication while+ # applying metadata owned by the selected Hub catalog row.+ result = dict(base_env)+ if launch.context_window is not None:+ result["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] = str(launch.context_window)+ if launch.max_output_tokens is not None:+ result["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] = str(launch.max_output_tokens)return result@@ -534,6 +571,7 @@ class ModelHubRuntimeRouter:resolved_model_id: Optional[str] = None,source_id: Optional[str] = None,via_mapping: bool = False,+ gateway_request_model_id: Optional[str] = None,) -> tuple[str, str]:if self.turn_gateway is not None:return await self.turn_gateway.endpoint(@@ -544,6 +582,7 @@ class ModelHubRuntimeRouter:resolved_model_id=resolved_model_id,source_id=source_id,via_mapping=via_mapping,+ gateway_request_model_id=gateway_request_model_id,)await self.service._ensure_engine_synced()status = await self.service._engine_call(self.service.adapter.start())@@ -806,6 +845,32 @@ class ModelHubRuntimeRouter:target_model = resolution.target_modelsource = resolution.source+ backend_model = next(+ (+ model+ for model in config.agents[backend].models+ if model.id == requested_model+ ),+ None,+ )+ context_window = (+ backend_model.context_window if backend_model is not None else None+ )+ max_output_tokens = (+ backend_model.max_output_tokens if backend_model is not None else None+ )+ supports_tools = (+ backend_model.supports_tools if backend_model is not None else None+ )+ supports_reasoning = (+ backend_model.supports_reasoning if backend_model is not None else None+ )+ reasoning_efforts = (+ tuple(backend_model.reasoning_efforts)+ if backend_model is not None+ and backend_model.supports_reasoning is not False+ else ()+ )self._last_supply_state[(backend, requested_model)] = ("ok", None)if source.supply_channel == "native_cli":if self.service.revocations.list():@@ -821,6 +886,11 @@ class ModelHubRuntimeRouter:target_model=target_model,runtime_model=target_model,source_id=source.id,+ context_window=context_window,+ max_output_tokens=max_output_tokens,+ supports_tools=supports_tools,+ supports_reasoning=supports_reasoning,+ reasoning_efforts=reasoning_efforts,settlement_generation=self.service._reserve_settlement_generation(source.id),@@ -836,6 +906,11 @@ class ModelHubRuntimeRouter:via_mapping=False,)else:+ runtime_model = (+ requested_model+ if self.turn_gateway is not None and backend == "codex"+ else target_model+ )gateway_base_url, gateway_token = await self._gateway_credentials(backend,process_scope=str(process_scope or "").strip() or f"{backend}:untracked",@@ -844,8 +919,8 @@ class ModelHubRuntimeRouter:resolved_model_id=target_model,source_id=source.id,via_mapping=False,+ gateway_request_model_id=runtime_model,)- runtime_model = target_modelif self.turn_gateway is None:prefix = await self._source_prefix(source.id)runtime_model = f"{prefix}/{target_model}"@@ -858,6 +933,11 @@ class ModelHubRuntimeRouter:source_id=source.id,gateway_base_url=gateway_base_url,gateway_token=gateway_token,+ context_window=context_window,+ max_output_tokens=max_output_tokens,+ supports_tools=supports_tools,+ supports_reasoning=supports_reasoning,+ reasoning_efforts=reasoning_efforts,)self._emit_transition(launch, config)return launch@@ -962,9 +1042,9 @@ class ModelHubRuntimeRouter:agent = config.agents["opencode"]if agent.mode == "direct":return None- checked = tuple(agent.menu.checked if agent.menu else ())+ checked = tuple(model.id for model in agent.models)if not checked:- return None+ raise ModelHubError("mapping_target_unavailable", status=409)gateway_base_url, gateway_token = await self._gateway_credentials("opencode",process_scope="opencode:shared-server",@@ -976,6 +1056,9 @@ class ModelHubRuntimeRouter:available_identifiers: list[str] = []launches: list[ModelHubLaunch] = []for identifier in dict.fromkeys(checked):+ backend_model = next(+ model for model in agent.models if model.id == identifier+ )config, resolution = await self._resolve_turn(config,"opencode",@@ -999,14 +1082,6 @@ class ModelHubRuntimeRouter:if resolution.projectable_hopselse None)- if (- inspection is None- or inspection.source is None- or inspection.model_id is None- ):- continue- source = inspection.source- exact_model_id = inspection.model_idpackage = _provider_package()base_url = _provider_base_url(gateway_base_url)provider = providers.setdefault(@@ -1020,24 +1095,33 @@ class ModelHubRuntimeRouter:)runtime_model = identifierif self.turn_gateway is None:+ if (+ inspection is None+ or inspection.source is None+ or inspection.model_id is None+ ):+ continue+ source = inspection.source+ exact_model_id = inspection.model_idprefix = await self._source_prefix(source.id)runtime_model = f"{prefix}/{exact_model_id}"- projected_model = project_opencode_public_model(identifier, resolution)- if projected_model is None:- continue+ projected_model = project_opencode_public_model(backend_model)projected_model["id"] = runtime_modelprovider["models"][identifier] = projected_modelprojected_identifiers.append(identifier)if resolution.candidate_hops:+ candidate = resolution.candidate_hops[0]+ if candidate.source is None or candidate.model_id is None:+ continueavailable_identifiers.append(identifier)launches.append(ModelHubLaunch(backend="opencode",channel="hub",requested_model=identifier,- target_model=exact_model_id,+ target_model=candidate.model_id,runtime_model=runtime_model,- source_id=source.id,+ source_id=candidate.source.id,gateway_base_url=gateway_base_url,gateway_token=gateway_token,)diff --git a/modules/agents/service.py b/modules/agents/service.pyindex e8aa46387..f6129af27 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -1172,6 +1172,17 @@ class AgentService:finally:self.release_runtime_turn_tokens(runtime_tokens)+ async def invalidate_model_hub_runtime(self, agent_name: str) -> bool:+ """Invalidate future Hub-only runtime state without disturbing Direct work."""+ agent = self.agents.get(agent_name)+ if agent is None:+ return False+ invalidate = getattr(agent, "invalidate_model_hub_runtime", None)+ if not callable(invalidate):+ return False+ await invalidate()+ return True+@dataclassclass _RuntimeTurnGate:diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.pyindex c6eb74ffc..1623bcd9a 100644--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py@@ -9,7 +9,12 @@ from pathlib import Pathimport pytest-from config.v2_config import ModelHubConfig, ModelHubRouteConfig, ModelHubRouteHopConfig+from config.v2_config import (+ ModelHubBackendModelConfig,+ ModelHubConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,+)from core.handlers.model_hub.adapter import (SOURCE_PROTOCOLS,ObservationDiscovery,@@ -288,6 +293,7 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ordagent = config.agents[backend]if backend == "opencode":agent.menu.checked = [opencode_model]+ agent.models = [ModelHubBackendModelConfig(id=opencode_model)]agent.routes[menu_model] = ModelHubRouteConfig(hops=tuple(ModelHubRouteHopConfig(item.id, upstream_model)diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pyindex b72047a82..4d0062edb 100644--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -15,6 +15,7 @@ import pytestfrom config.v2_config import (ModelHubAgentSourcesConfig,ModelHubAgentSupplyConfig,+ ModelHubBackendModelConfig,ModelHubConfig,ModelHubModelConfig,ModelHubRouteConfig,@@ -202,6 +203,12 @@ def _config(*sources: ModelHubSourceConfig) -> ModelHubConfig:for source in eligible_sources))+ if backend == "opencode":+ agent.models = [+ ModelHubBackendModelConfig(id=_requested_model(backend))+ ]+ assert agent.menu is not None+ agent.menu.checked = [_requested_model(backend)]return config@@ -279,6 +286,51 @@ def test_unpinned_hub_projection_is_null_while_explicit_turn_resolves(asyncio.run(exercise())+def test_codex_backend_model_id_survives_until_gateway_resolution(+ tmp_path: Path,+) -> None:+ """Codex selects catalog identity while the gateway invokes its routed target."""++ async def exercise() -> None:+ source = _source("src_alias_route")+ source.models.append(ModelHubModelConfig(id="model-b", provenance="manual"))+ config = _config(source)+ codex = config.agents["codex"]+ codex.models.append(ModelHubBackendModelConfig(id="alias-a", origin="manual"))+ codex.routes["alias-a"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "model-b"),)+ )+ adapter = AdapterBoundaryFake(+ [AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')]+ )+ service = _service(+ tmp_path,+ MemoryStore(config),+ adapter,+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),+ )+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ launch = await router.resolve(+ "codex",+ "alias-a",+ process_scope="/repo",+ turn_id="turn_alias",+ )+ assert launch.runtime_model == "alias-a"+ assert launch.target_model == "model-b"++ status, body = await _post_turn(launch, endpoint="responses")+ assert status == 200+ assert body == b'{"ok":true}'+ assert adapter.invocations == [(source.id, "model-b", "codex")]+ finally:+ await gateway.close()++ asyncio.run(exercise())++@pytest.mark.parametrize(("backend", "requested_model", "endpoint"),[@@ -316,8 +368,6 @@ def test_mh_res_live_001_pre_stream_failure_falls_back_within_turn(])store = MemoryStore(_config(_source("src_primary1"), _source("src_backup01")))- assert store.config.agents["opencode"].menu is not None- store.config.agents["opencode"].menu.checked = ["anthropic/model-live"]service = _service(tmp_path, store, adapter, now=lambda: clock[0])gateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)diff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex 6070f6657..d8e93a244 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -354,6 +354,18 @@ def test_agent_service_reports_missing_runtime_refresh_contract() -> None:assert asyncio.run(service.refresh_runtime_config("claude", object())) is False+def test_agent_service_dispatches_model_hub_runtime_invalidation() -> None:+ service = AgentService(controller=SimpleNamespace())+ agent = SimpleNamespace(name="codex", invalidate_model_hub_runtime=AsyncMock())+ service.register(agent)++ handled = asyncio.run(service.invalidate_model_hub_runtime("codex"))++ assert handled is True+ agent.invalidate_model_hub_runtime.assert_awaited_once_with()+ assert asyncio.run(service.invalidate_model_hub_runtime("claude")) is False++def test_agent_service_notifies_run_owner_when_activity_runtime_disconnects() -> None:settle = Mock()controller = SimpleNamespace(diff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.pyindex be969083a..9e7c6453f 100644--- a/tests/test_backend_model_catalog.py+++ b/tests/test_backend_model_catalog.py@@ -103,6 +103,276 @@ def test_codex_hub_catalog_projects_complete_catalog(monkeypatch, tmp_path):}+def test_codex_hub_catalog_projects_custom_backend_models_from_native_shape():+ raw = json.dumps(+ {+ "client_version": "0.149.1",+ "models": [+ {+ "slug": "gpt-native",+ "display_name": "GPT Native",+ "priority": 99,+ "visibility": "list",+ "supported_in_api": True,+ "context_window": 200_000,+ "max_context_window": 200_000,+ "input_modalities": ["text", "image"],+ "supports_image_detail_original": True,+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {"effort": "medium", "description": "Medium"}+ ],+ "use_responses_lite": True,+ "multi_agent_version": "v1",+ "tool_mode": "code_mode_only",+ "prefer_websockets": True,+ "model_messages": {"instructions_template": "preserved"},+ }+ ],+ }+ ).encode()+ configured = [+ {+ "id": "deepseek-v4",+ "display_name": "DeepSeek V4",+ "context_window": 1_048_576,+ "input_modalities": ["text"],+ "reasoning_efforts": ["low", "high"],+ }+ ]++ payload = json.loads(+ backend_model_catalog._codex_hub_catalog_bytes(raw, configured)+ )++ assert payload["client_version"] == "0.149.1"+ assert payload["models"] == [+ {+ "slug": "deepseek-v4",+ "display_name": "DeepSeek V4",+ "priority": 1,+ "visibility": "list",+ "supported_in_api": True,+ "context_window": 1_048_576,+ "max_context_window": 1_048_576,+ "input_modalities": ["text"],+ "supports_image_detail_original": False,+ "default_reasoning_level": "low",+ "supported_reasoning_levels": [+ {"effort": "low", "description": "Low"},+ {"effort": "high", "description": "High"},+ ],+ "use_responses_lite": False,+ "multi_agent_version": None,+ "tool_mode": None,+ "prefer_websockets": False,+ "model_messages": {"instructions_template": "preserved"},+ "support_verbosity": False,+ "experimental_supported_tools": [],+ }+ ]+++def test_codex_hub_catalog_does_not_inherit_native_model_metadata_for_custom_rows():+ raw = json.dumps(+ {+ "models": [+ {+ "slug": "gpt-native",+ "display_name": "GPT Native",+ "description": "Native-only description",+ "priority": 1,+ "visibility": "list",+ "supported_in_api": True,+ "context_window": 200_000,+ "max_context_window": 200_000,+ "auto_compact_token_limit": 180_000,+ "comp_hash": "native-only",+ "input_modalities": ["text", "image"],+ "supports_image_detail_original": True,+ "default_reasoning_level": "medium",+ "supported_reasoning_levels": [+ {"effort": "medium", "description": "Medium"}+ ],+ "additional_speed_tiers": ["fast"],+ "service_tiers": [+ {"id": "priority", "name": "Fast", "description": "Native"}+ ],+ "supports_search_tool": True,+ "shell_type": "unified_exec",+ "support_verbosity": True,+ "experimental_supported_tools": ["native_tool"],+ "truncation_policy": {"mode": "tokens", "limit": 10_000},+ "model_messages": {"instructions_template": "preserved"},+ }+ ]+ }+ ).encode()++ payload = json.loads(+ backend_model_catalog._codex_hub_catalog_bytes(+ raw,+ [{"id": "custom-model", "input_modalities": [], "reasoning_efforts": []}],+ )+ )+ custom = payload["models"][0]++ assert custom["slug"] == "custom-model"+ assert custom["model_messages"] == {"instructions_template": "preserved"}+ assert custom["shell_type"] == "unified_exec"+ assert custom["truncation_policy"] == {"mode": "tokens", "limit": 10_000}+ assert custom["input_modalities"] == ["text"]+ assert custom["supported_reasoning_levels"] == [+ {"effort": "none", "description": "None"}+ ]+ assert custom["support_verbosity"] is False+ assert custom["experimental_supported_tools"] == []+ for key in (+ "description",+ "context_window",+ "max_context_window",+ "auto_compact_token_limit",+ "comp_hash",+ "additional_speed_tiers",+ "service_tiers",+ "supports_search_tool",+ ):+ assert key not in custom+++def test_codex_hub_catalog_preserves_native_modalities_without_an_override():+ raw = json.dumps(+ {+ "models": [+ {+ "slug": "gpt-native",+ "display_name": "GPT Native",+ "context_window": 200_000,+ "max_context_window": 200_000,+ "auto_compact_token_limit": 180_000,+ "input_modalities": ["text", "image"],+ "supports_image_detail_original": True,+ }+ ]+ }+ ).encode()++ payload = json.loads(+ backend_model_catalog._codex_hub_catalog_bytes(+ raw,+ [+ {+ "id": "gpt-native",+ "display_name": "GPT Native",+ "input_modalities": [],+ }+ ],+ )+ )++ assert payload["models"][0]["input_modalities"] == ["text", "image"]+ assert payload["models"][0]["supports_image_detail_original"] is True+ assert payload["models"][0]["auto_compact_token_limit"] == 180_000+++def test_codex_hub_catalog_retires_native_compaction_limit_after_context_override():+ raw = json.dumps(+ {+ "models": [+ {+ "slug": "gpt-native",+ "display_name": "GPT Native",+ "context_window": 200_000,+ "max_context_window": 200_000,+ "auto_compact_token_limit": 180_000,+ "effective_context_window_percent": 90,+ }+ ]+ }+ ).encode()++ payload = json.loads(+ backend_model_catalog._codex_hub_catalog_bytes(+ raw,+ [{"id": "gpt-native", "context_window": 400_000}],+ )+ )+ projected = payload["models"][0]++ assert projected["context_window"] == 400_000+ assert projected["max_context_window"] == 400_000+ assert projected["effective_context_window_percent"] == 90+ assert "auto_compact_token_limit" not in projected+++def test_codex_hub_catalog_does_not_give_custom_models_template_modalities():+ raw = json.dumps(+ {+ "models": [+ {+ "slug": "gpt-native",+ "input_modalities": ["text", "image"],+ "supports_image_detail_original": True,+ }+ ]+ }+ ).encode()++ payload = json.loads(+ backend_model_catalog._codex_hub_catalog_bytes(+ raw,+ [{"id": "custom-model", "input_modalities": []}],+ )+ )++ assert payload["models"][0]["input_modalities"] == ["text"]+ assert payload["models"][0]["supports_image_detail_original"] is False+++def test_codex_hub_catalog_can_disable_and_restore_native_reasoning():+ raw = json.dumps(+ {+ "models": [+ {+ "slug": "gpt-native",+ "default_reasoning_level": "high",+ "supported_reasoning_levels": [+ {"effort": "low", "description": "Low"},+ {"effort": "high", "description": "High"},+ ],+ }+ ]+ }+ ).encode()+ configured = {+ "id": "gpt-native",+ "reasoning_efforts": ["low", "high"],+ }++ disabled = json.loads(+ backend_model_catalog._codex_hub_catalog_bytes(+ raw,+ [{**configured, "supports_reasoning": False}],+ )+ )["models"][0]+ restored = json.loads(+ backend_model_catalog._codex_hub_catalog_bytes(+ raw,+ [{**configured, "supports_reasoning": None}],+ )+ )["models"][0]++ assert disabled["default_reasoning_level"] == "none"+ assert disabled["supported_reasoning_levels"] == [+ {"effort": "none", "description": "None"}+ ]+ assert restored["default_reasoning_level"] == "low"+ assert restored["supported_reasoning_levels"] == [+ {"effort": "low", "description": "Low"},+ {"effort": "high", "description": "High"},+ ]++def test_codex_hub_catalog_export_uses_stable_supervisor(monkeypatch):captured = {}diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex a7b76e657..73305aeae 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -16,6 +16,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import core.handlers.session_handler as session_handler_modulefrom config.v2_compat import to_app_configfrom config.v2_config import AgentsConfig, ClaudeConfig, RuntimeConfig, SlackConfig, V2Config+from config.v2_settings import RoutingSettingsfrom core import git_runtime as git_runtime_modulefrom core.handlers.session_handler import SessionHandlerfrom core.runtime_activation import RuntimeActivationRegistry@@ -181,6 +182,118 @@ def test_session_handler_passes_configured_claude_cli_path(monkeypatch, tmp_pathassert getattr(client, "_vibe_runtime_session_key") == f"slack_C123:{tmp_path}"+def test_session_handler_uses_native_cli_launch_reasoning_catalog(+ monkeypatch,+ tmp_path: Path,+) -> None:+ from modules.agents.model_hub import ModelHubLaunch++ captured: dict[str, Any] = {}++ class _StubClaudeSDKClient:+ def __init__(self, options):+ captured["options"] = options++ async def connect(self) -> None:+ return None++ class _Runtime:+ async def resolve(self, backend, requested_model, **_kwargs):+ return ModelHubLaunch(+ backend=backend,+ channel="native_cli",+ requested_model=requested_model,+ target_model=requested_model,+ runtime_model=requested_model,+ source_id="src_native01",+ context_window=128_000,+ max_output_tokens=32_000,+ reasoning_efforts=("max",),+ )++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)+ monkeypatch.setattr(+ "vibe.backend_model_catalog.catalog_reasoning_efforts_for_model",+ lambda *_args: ["low"],+ )++ controller = _Controller(tmp_path)+ controller.model_hub_runtime = _Runtime()+ controller.settings_manager.get_channel_routing = lambda _key: RoutingSettings(+ model="claude-opus-4-6",+ reasoning_effort="max",+ )+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")++ _run_session(handler, context)++ assert captured["options"].effort == "max"+ assert captured["options"].env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "128000"+ assert captured["options"].env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "32000"+++def test_session_handler_recreates_cached_claude_client_when_catalog_limits_change(+ monkeypatch,+ tmp_path: Path,+) -> None:+ from modules.agents.model_hub import ModelHubLaunch++ captured: dict[str, Any] = {"clients": []}++ class _StubClaudeSDKClient:+ def __init__(self, options):+ self.options = options+ self.disconnects = 0+ captured["clients"].append(self)++ async def connect(self) -> None:+ return None++ async def disconnect(self) -> None:+ self.disconnects += 1++ class _Runtime:+ def __init__(self) -> None:+ self.context_windows = iter((128_000, 256_000))++ async def resolve(self, backend, requested_model, **_kwargs):+ context_window = next(self.context_windows)+ return ModelHubLaunch(+ backend=backend,+ channel="native_cli",+ requested_model=requested_model,+ target_model=requested_model,+ runtime_model=requested_model,+ source_id="src_native01",+ context_window=context_window,+ max_output_tokens=32_000,+ reasoning_efforts=("high",),+ )++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)++ controller = _Controller(tmp_path)+ controller.model_hub_runtime = _Runtime()+ controller.settings_manager.get_channel_routing = lambda _key: RoutingSettings(+ model="claude-opus-4-6",+ reasoning_effort="high",+ )+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")++ first_client = _run_session(handler, context)+ second_client = _run_session(handler, context)++ assert first_client is not second_client+ assert first_client.disconnects == 1+ assert len(captured["clients"]) == 2+ assert first_client.options.env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "128000"+ assert second_client.options.env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "256000"++def test_claude_system_prompt_follows_live_memory_enabled_state(tmp_path: Path) -> None:controller = _Controller(tmp_path)controller.config.memory = type("MemoryConfig", (), {"enabled": False})()diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex a050d49b5..145cbae74 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -3549,6 +3549,111 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):},)+ def test_model_hub_filters_every_codex_effort_source_at_the_adapter_boundary(self):+ from modules.agents.model_hub import ModelHubLaunch, bind_launch++ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(),+ model_hub_runtime=object(),+ )+ launch = ModelHubLaunch(+ backend="codex",+ channel="hub",+ requested_model="no-reasoning-model",+ target_model="upstream-model",+ runtime_model="no-reasoning-model",+ reasoning_efforts=(),+ supports_reasoning=False,+ )+ cases = (+ (+ SimpleNamespace(+ context=SimpleNamespace(),+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort="high",+ ),+ (None, None, None),+ ),+ (+ SimpleNamespace(+ context=SimpleNamespace(),+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ vibe_agent_reasoning_effort="high",+ ),+ (None, None, None),+ ),+ (+ SimpleNamespace(+ context=SimpleNamespace(),+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ ),+ (None, None, "high"),+ ),+ (+ SimpleNamespace(+ context=SimpleNamespace(),+ subagent_name="reviewer",+ subagent_model=None,+ subagent_reasoning_effort=None,+ working_path="/tmp/work",+ ),+ (None, None, None),+ ),+ )++ with patch.object(+ _MODULE,+ "load_codex_subagent",+ return_value=SimpleNamespace(+ model=None,+ reasoning_effort="high",+ developer_instructions=None,+ ),+ ):+ for request, overrides in cases:+ agent.controller.get_codex_overrides.return_value = overrides+ bind_launch(request.context, launch)+ self.assertIsNone(agent._resolve_codex_agent_settings(request)[2])++ def test_model_hub_keeps_supported_codex_effort_and_does_not_filter_direct(self):+ from modules.agents.model_hub import ModelHubLaunch, bind_launch++ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(+ get_codex_overrides=Mock(return_value=(None, None, "high")),+ model_hub_runtime=object(),+ )+ request = SimpleNamespace(+ context=SimpleNamespace(),+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ )+ common = {+ "backend": "codex",+ "requested_model": "gpt-5",+ "target_model": "gpt-5",+ "runtime_model": "gpt-5",+ }++ bind_launch(+ request.context,+ ModelHubLaunch(channel="hub", reasoning_efforts=("high",), **common),+ )+ self.assertEqual(agent._resolve_codex_agent_settings(request)[2], "high")++ bind_launch(+ request.context,+ ModelHubLaunch(channel="direct", reasoning_efforts=(), **common),+ )+ self.assertEqual(agent._resolve_codex_agent_settings(request)[2], "high")+async def test_start_turn_uses_codex_dm_user_effort_from_shared_overrides(self):agent = object.__new__(CodexAgent)agent.settings_manager = SimpleNamespace(@@ -4062,6 +4167,18 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._model_hub_catalog_generation, 1)agent.refresh_auth_state.assert_awaited_once_with()+ async def test_model_hub_catalog_invalidation_preserves_direct_transports(self):+ agent = self._agent()+ transport = SimpleNamespace(stop=AsyncMock())+ agent._transports["/repo"] = transport+ agent._model_hub_catalog_path = Path("/runtime/codex-old.json")++ await agent.invalidate_model_hub_runtime()++ self.assertIsNone(agent._model_hub_catalog_path)+ self.assertEqual(agent._model_hub_catalog_generation, 1)+ transport.stop.assert_not_awaited()+async def test_startup_catalog_preparation_cannot_overwrite_new_runtime_generation(self):agent = self._agent()previous_config = agent.codex_config@@ -4073,8 +4190,8 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):release_previous = threading.Event()calls = []- def prepare(binary):- calls.append(binary)+ def prepare(binary, base_env, configured_models):+ calls.append((binary, base_env, configured_models))if binary == previous_config.binary:previous_started.set()release_previous.wait(timeout=2)@@ -4095,7 +4212,13 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):await startuprecovered = await agent.prepare_model_hub_runtime()- self.assertEqual(calls, [previous_config.binary, next_config.binary])+ self.assertEqual(+ calls,+ [+ (previous_config.binary, None, None),+ (next_config.binary, None, None),+ ],+ )self.assertIs(agent.codex_config, next_config)self.assertEqual(agent._model_hub_catalog_path, next_catalog)self.assertEqual(recovered, next_catalog)@@ -4150,7 +4273,11 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):with self.assertRaises(_MODULE.CodexModelHubCatalogUnavailableError):await agent._get_or_create_transport(cwd, launch)- prepare_catalog.assert_called_once_with(agent.codex_config.binary)+ prepare_catalog.assert_called_once_with(+ agent.codex_config.binary,+ None,+ None,+ )existing.stop.assert_not_awaited()self.assertIs(agent._transports[cwd], existing)agent._session_mgr.invalidate_thread.assert_not_called()diff --git a/tests/test_controller_model_hub_gate.py b/tests/test_controller_model_hub_gate.pyindex be95eac0f..37316783b 100644--- a/tests/test_controller_model_hub_gate.py+++ b/tests/test_controller_model_hub_gate.py@@ -4,6 +4,7 @@ import asyncioimport jsonimport threadingfrom types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest@@ -133,6 +134,42 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp("router", service, controller.model_hub_turn_gateway),]+ runtime_config = object()+ latest = SimpleNamespace(+ model_hub=SimpleNamespace(+ agents={"codex": SimpleNamespace(mode="hub")},+ ),+ agents=SimpleNamespace(codex=runtime_config),+ )+ controller.backend_restart_coordinator = SimpleNamespace(+ request_restart=AsyncMock(return_value="restarted"),+ )+ controller.agent_service = SimpleNamespace(+ invalidate_model_hub_runtime=AsyncMock(),+ refresh_runtime_config=AsyncMock(),+ )+ monkeypatch.setattr(V2Config, "load", classmethod(lambda _cls: latest))++ asyncio.run(captured["backend_catalog_changed"]("codex"))++ assert controller.config.model_hub is latest.model_hub+ controller.backend_restart_coordinator.request_restart.assert_awaited_once_with(+ "codex"+ )+ controller.agent_service.invalidate_model_hub_runtime.assert_not_awaited()+ controller.agent_service.refresh_runtime_config.assert_not_awaited()++ latest.model_hub.agents["codex"].mode = "direct"+ controller.backend_restart_coordinator.request_restart.reset_mock()++ asyncio.run(captured["backend_catalog_changed"]("codex"))++ controller.agent_service.invalidate_model_hub_runtime.assert_awaited_once_with(+ "codex"+ )+ controller.backend_restart_coordinator.request_restart.assert_not_awaited()+ controller.agent_service.refresh_runtime_config.assert_not_awaited()+@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])def test_disabled_controller_resolver_is_direct_without_loading_model_hub_config(diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.pyindex 43d488704..a7d29f2e8 100644--- a/tests/test_instance_authorization.py+++ b/tests/test_instance_authorization.py@@ -293,6 +293,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N("GET", "/api/show-pages/session-1"),# Read-only model catalogs behind Chat's route picker and the Agents# detail panel. Editor-tier because the picker is an editor surface.+ ("GET", "/api/models/agents/claude/models"),("GET", "/api/claude/models"),("GET", "/api/codex/models"),)@@ -327,6 +328,8 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N("DELETE", "/api/agents/demo"),("GET", "/api/models/agents/codex/chains"),("PUT", "/api/models/agents/codex/chain"),+ ("PUT", "/api/models/agents/codex/models"),+ ("GET", "/api/models/catalog/models-dev"),("PUT", "/api/global-prompts"),("POST", "/api/projects"),("PATCH", "/api/projects/project-1"),@@ -478,6 +481,7 @@ def test_agents_page_load_reads_are_admitted_for_every_rank_that_sees_the_page()("GET", "/api/models/agents/claude/chains"),)catalog_reads = (+ ("GET", "/api/models/agents/claude/models"),("GET", "/api/claude/models"),("GET", "/api/codex/models"),)@@ -493,7 +497,6 @@ def test_agents_page_load_reads_are_admitted_for_every_rank_that_sees_the_page()for method, path in (*page_load_reads, *catalog_reads):minimum_role = http_authorization_policy(method, path).minimum_roleassert minimum_role is not None and context.has_role(minimum_role), f"{role} {path}"-# The counterparts a member page load must not announce. Bulk onboarding is a# one-way instance-wide migration and must not be requested at all; the# OpenCode provider catalog may be requested but its refusal is expected data@@ -510,6 +513,27 @@ def test_agents_page_load_reads_are_admitted_for_every_rank_that_sees_the_page()assert not _context("member", remote=True).has_role(minimum_role), path+def test_backend_catalog_surface_follows_the_agent_management_boundary() -> None:+ catalog_surface = (+ ("GET", "/api/models/agents/claude/models", "editor"),+ ("PUT", "/api/models/agents/claude/models", "member"),+ ("GET", "/api/models/catalog/models-dev", "member"),+ )+ for method, path, role in catalog_surface:+ assert http_authorization_policy(method, path).minimum_role == role++ assert not _context("editor", remote=True).has_role("member")+ assert _context("member", remote=True).has_role("member")++ source_model_mutations = (+ ("POST", "/api/models/sources/src-1/models"),+ ("PATCH", "/api/models/sources/src-1/models/model-1"),+ ("DELETE", "/api/models/sources/src-1/models/model-1"),+ )+ for method, source_path in source_model_mutations:+ assert http_authorization_policy(method, source_path).minimum_role == "owner"++def test_workbench_events_follow_role_boundaries() -> None:viewer = _context("viewer", remote=True)editor = _context("editor", remote=True)diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 1af3d1923..a75e11c27 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -17,6 +17,7 @@ from referencing import Registry, Resourcefrom config.v2_config import (ModelHubAgentSupplyConfig,+ ModelHubBackendModelConfig,ModelHubConfig,ModelHubModelConfig,ModelHubRouteConfig,@@ -84,7 +85,11 @@ API_RESPONSE_ROUTES = API_RESPONSE_CONTRACT["x-model-hub-routes"]def _assert_valid(name: str, payload: dict) -> None:errors = sorted(- Draft7Validator(_schema(name), format_checker=FormatChecker()).iter_errors(payload),+ Draft7Validator(+ _schema(name),+ registry=_api_response_registry(),+ format_checker=FormatChecker(),+ ).iter_errors(payload),key=lambda error: list(error.path),)assert not errors, [error.message for error in errors]@@ -554,6 +559,7 @@ def _seed_response_conformance_service(tmp_path: Path) -> ModelHubService:at=service.now(),)asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub"}))+ service.models_dev_matches = lambda _query: []return service@@ -1882,6 +1888,618 @@ def test_agents_endpoint_projects_builtin_models_and_standard_vendors(tmp_path):assert agents["opencode"]["standard_vendors"] == sorted(STANDARD_OPENCODE_VENDOR_IDS)+def test_agents_project_one_shared_backend_catalog_contract(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ agents = {agent["backend"]: agent for agent in service.list_agents()}++ claude_models = agents["claude"]["catalog_models"]+ assert claude_models[0] == {+ "id": "default",+ "display_name": None,+ "origin": "builtin",+ "models_dev_id": None,+ "context_window": None,+ "max_output_tokens": None,+ "input_modalities": [],+ "output_modalities": [],+ "supports_tools": None,+ "supports_reasoning": None,+ "reasoning_efforts": [],+ "locked": True,+ "routeable": False,+ }+ assert all(model["locked"] is False for model in claude_models[1:])+ assert all(model["routeable"] is True for model in claude_models[1:])+ assert agents["codex"]["catalog_models"]+ assert agents["opencode"]["catalog_models"] == []+++ ("backend", "model_id"),+ (+ ("claude", "claude-deepseek-v4"),+ ("codex", "deepseek-v4"),+ ("opencode", "aihub/deepseek-v4"),+ ),+)+def test_backend_catalog_add_edit_and_runtime_refresh(+ tmp_path,+ backend,+ model_id,+):+ service, store, _adapter = _service(tmp_path)+ refreshed = []++ async def refresh(changed_backend):+ refreshed.append(changed_backend)++ service.backend_catalog_changed = refresh+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == backend+ )+ added = {+ "id": model_id,+ "display_name": "DeepSeek V4",+ "origin": "models_dev",+ "models_dev_id": "deepseek/deepseek-v4",+ "context_window": 1_048_576,+ "max_output_tokens": 131_072,+ "input_modalities": ["text", "image"],+ "output_modalities": ["text"],+ "supports_tools": True,+ "supports_reasoning": True,+ "reasoning_efforts": ["low", "high"],+ "locked": False,+ "routeable": True,+ }++ response = asyncio.run(+ service.set_agent_models(backend, baseline, [*baseline, added])+ )++ assert response["catalog_models"][-1] == added+ assert store.config.agents[backend].routes[model_id].hops == ()+ assert refreshed == [backend]+ if backend == "opencode":+ assert store.config.agents[backend].menu.checked == [model_id]++ edited = {**added, "display_name": "DeepSeek V4 edited", "context_window": 262_144}+ desired_catalog = (+ [response["catalog_models"][0], edited, *response["catalog_models"][1:-1]]+ if backend == "claude"+ else [edited, *response["catalog_models"][:-1]]+ )+ edited_response = asyncio.run(+ service.set_agent_models(+ backend,+ response["catalog_models"],+ desired_catalog,+ )+ )+ assert next(+ model+ for model in edited_response["catalog_models"]+ if model["id"] == model_id+ ) == edited+ if backend != "claude":+ assert edited_response["catalog_models"][0] == edited+ assert refreshed == [backend, backend]+++def test_backend_catalog_refuses_model_removal_while_route_is_configured(tmp_path):+ service, store, _adapter = _service(tmp_path)+ backend = "codex"+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == backend+ )+ model_id = baseline[0]["id"]+ source = ModelHubSourceConfig(+ id="src_catalog01",+ kind="api_key",+ vendor="openai",+ display_name="Catalog source",+ protocol="openai_responses",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="upstream-model", provenance="discovered")],+ credential_ref="cred_catalog01",+ )+ store.config.sources = [source]+ store.config.agents[backend].sources.order = [source.id]+ store.config.agents[backend].routes[model_id] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),)+ )++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(+ service.set_agent_models(+ backend,+ baseline,+ baseline[1:],+ )+ )++ assert raised.value.code == "backend_model_in_route"+ assert raised.value.status == 409+ assert store.config.agents[backend].models[0].id == model_id+++def test_backend_catalog_removes_model_with_empty_route(tmp_path):+ service, store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ removed_id = baseline[0]["id"]++ response = asyncio.run(+ service.set_agent_models("codex", baseline, baseline[1:])+ )++ assert removed_id not in {+ model["id"] for model in response["catalog_models"]+ }+ assert removed_id not in store.config.agents["codex"].routes+++def test_backend_catalog_preserves_requested_insertion_position_for_a_new_model(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ added = {+ "id": "inserted-model",+ "display_name": None,+ "origin": "manual",+ "models_dev_id": None,+ "context_window": None,+ "max_output_tokens": None,+ "input_modalities": [],+ "output_modalities": [],+ "supports_tools": None,+ "supports_reasoning": None,+ "reasoning_efforts": [],+ "locked": False,+ "routeable": True,+ }++ response = asyncio.run(+ service.set_agent_models(+ "codex",+ baseline,+ [added, *baseline],+ )+ )++ assert [model["id"] for model in response["catalog_models"]][+ : len(baseline) + 1+ ] == ["inserted-model", *(model["id"] for model in baseline)]+++def test_backend_catalog_allows_editing_a_persisted_legacy_long_id(tmp_path):+ service, store, _adapter = _service(tmp_path)+ legacy_id = "x" * (MODEL_ID_MAX_LENGTH + 1)+ agent = store.config.agents["codex"]+ agent.models.append(ModelHubBackendModelConfig(id=legacy_id, origin="manual"))+ agent.routes[legacy_id] = ModelHubRouteConfig()+ baseline = next(+ projected["catalog_models"]+ for projected in service.list_agents()+ if projected["backend"] == "codex"+ )+ desired = copy.deepcopy(baseline)+ next(model for model in desired if model["id"] == legacy_id)[+ "display_name"+ ] = "Persisted legacy model"++ response = asyncio.run(service.set_agent_models("codex", baseline, desired))++ assert next(+ model for model in response["catalog_models"] if model["id"] == legacy_id+ )["display_name"] == "Persisted legacy model"+ _assert_valid("agent-supply.schema.json", response)+++def test_backend_catalog_allows_a_persisted_legacy_claude_alias_to_round_trip(+ tmp_path,+):+ service, store, _adapter = _service(tmp_path)+ legacy_id = "legacy-opus-alias"+ agent = store.config.agents["claude"]+ agent.models.append(ModelHubBackendModelConfig(id=legacy_id, origin="manual"))+ agent.routes[legacy_id] = ModelHubRouteConfig()+ baseline = next(+ projected["catalog_models"]+ for projected in service.list_agents()+ if projected["backend"] == "claude"+ )+ desired = copy.deepcopy(baseline)+ desired[1]["display_name"] = "Unrelated edit"++ response = asyncio.run(service.set_agent_models("claude", baseline, desired))++ assert any(model["id"] == legacy_id for model in response["catalog_models"])+ assert response["catalog_models"][1]["display_name"] == "Unrelated edit"+++def test_backend_catalog_rejects_a_new_id_past_the_admission_bound(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ added = {+ **baseline[0],+ "id": "x" * (MODEL_ID_MAX_LENGTH + 1),+ "origin": "manual",+ }++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("codex", baseline, [*baseline, added]))++ assert raised.value.code == "backend_model_id_invalid"+++def test_backend_catalog_accepts_a_new_id_at_the_contract_bound(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ model_id = "x" * MODEL_ID_MAX_LENGTH+ added = {+ **baseline[0],+ "id": model_id,+ "origin": "manual",+ }++ response = asyncio.run(+ service.set_agent_models("codex", baseline, [*baseline, added])+ )++ assert response["catalog_models"][-1]["id"] == model_id+++def test_backend_catalog_merges_an_unrelated_concurrent_edit(tmp_path):+ service, store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ assert len(baseline) >= 2+ desired = copy.deepcopy(baseline)+ desired[0]["display_name"] = "Caller edit"+ store.config.agents["codex"].models[1].display_name = "Concurrent edit"++ response = asyncio.run(+ service.set_agent_models("codex", baseline, desired)+ )++ assert response["catalog_models"][0]["display_name"] == "Caller edit"+ assert response["catalog_models"][1]["display_name"] == "Concurrent edit"+++def test_backend_catalog_rejects_a_concurrent_edit_to_the_same_row(tmp_path):+ service, store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ desired = copy.deepcopy(baseline)+ desired[0]["display_name"] = "Caller edit"+ store.config.agents["codex"].models[0].display_name = "Concurrent edit"++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("codex", baseline, desired))++ assert raised.value.code == "backend_model_conflict"+ assert raised.value.status == 409+ assert store.config.agents["codex"].models[0].display_name == "Concurrent edit"+++def test_backend_catalog_is_editable_in_direct_mode(tmp_path):+ service, store, _adapter = _service(tmp_path)+ store.config.agents["codex"].mode = "direct"+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ desired = copy.deepcopy(baseline)+ desired[0]["display_name"] = "Direct-mode edit"++ response = asyncio.run(+ service.set_agent_models("codex", baseline, desired)+ )++ assert response["mode"] == "direct"+ assert response["routes"] is None+ assert response["catalog_models"][0]["display_name"] == "Direct-mode edit"+++def test_backend_catalog_reports_duplicate_ids(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(+ service.set_agent_models(+ "codex",+ baseline,+ [*baseline, copy.deepcopy(baseline[0])],+ )+ )++ assert raised.value.code == "backend_model_duplicate"+++def test_codex_catalog_treats_default_as_an_ordinary_model_id(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "codex"+ )+ added = {+ **baseline[0],+ "id": "default",+ "display_name": "Gateway default",+ "origin": "manual",+ }++ created = asyncio.run(+ service.set_agent_models("codex", baseline, [*baseline, added])+ )+ desired = copy.deepcopy(created["catalog_models"])+ next(model for model in desired if model["id"] == "default")[+ "display_name"+ ] = "Edited default"+ edited = asyncio.run(+ service.set_agent_models("codex", created["catalog_models"], desired)+ )++ assert next(+ model for model in edited["catalog_models"] if model["id"] == "default"+ )["display_name"] == "Edited default"+++def test_backend_catalog_rejects_client_claimed_builtin_origin(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "claude"+ )+ forged = {+ **baseline[1],+ "id": "unprefixed-third-party-model",+ "display_name": "Forged built-in",+ }++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("claude", baseline, [*baseline, forged]))++ assert raised.value.code == "backend_model_locked"+++ ("origin", "replacement"),+ (+ ("manual", "models_dev"),+ ("manual", "builtin"),+ ("models_dev", "manual"),+ ("models_dev", "builtin"),+ ("builtin", "manual"),+ ("builtin", "models_dev"),+ ),+)+def test_backend_catalog_keeps_every_existing_origin_immutable(+ tmp_path,+ origin,+ replacement,+):+ service, store, _adapter = _service(tmp_path)+ model_id = "provenance-model"+ agent = store.config.agents["codex"]+ agent.models.append(ModelHubBackendModelConfig(id=model_id, origin=origin))+ agent.routes[model_id] = ModelHubRouteConfig()+ baseline = next(+ projected["catalog_models"]+ for projected in service.list_agents()+ if projected["backend"] == "codex"+ )+ desired = copy.deepcopy(baseline)+ next(model for model in desired if model["id"] == model_id)[+ "origin"+ ] = replacement++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("codex", baseline, desired))++ assert raised.value.code == "backend_model_locked"+ assert next(model for model in agent.models if model.id == model_id).origin == origin+++def test_backend_catalog_rejects_an_origin_forged_into_the_baseline(tmp_path):+ service, store, _adapter = _service(tmp_path)+ model_id = "manual-provenance-model"+ agent = store.config.agents["codex"]+ agent.models.append(ModelHubBackendModelConfig(id=model_id, origin="manual"))+ agent.routes[model_id] = ModelHubRouteConfig()+ observed = next(+ projected["catalog_models"]+ for projected in service.list_agents()+ if projected["backend"] == "codex"+ )+ forged_baseline = copy.deepcopy(observed)+ forged_desired = copy.deepcopy(observed)+ for catalog in (forged_baseline, forged_desired):+ next(model for model in catalog if model["id"] == model_id)[+ "origin"+ ] = "models_dev"++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(+ service.set_agent_models("codex", forged_baseline, forged_desired)+ )++ assert raised.value.code == "backend_model_locked"+ assert next(model for model in agent.models if model.id == model_id).origin == "manual"++[email protected]("model_id", ["opus", "sonnet[1m]"])+def test_backend_catalog_restores_a_removed_claude_builtin_alias(+ tmp_path,+ model_id,+):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "claude"+ )+ without_alias = [model for model in baseline if model["id"] != model_id]+ removed = asyncio.run(+ service.set_agent_models("claude", baseline, without_alias)+ )+ restored = {+ **next(model for model in baseline if model["id"] == model_id),+ "origin": "manual",+ }++ response = asyncio.run(+ service.set_agent_models(+ "claude",+ removed["catalog_models"],+ [*removed["catalog_models"], restored],+ )+ )++ assert response["catalog_models"][-1] == restored+++def test_backend_catalog_still_rejects_an_unknown_unprefixed_claude_id(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "claude"+ )+ unknown = {+ **baseline[1],+ "id": "deepseek-v4",+ "origin": "manual",+ }++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("claude", baseline, [*baseline, unknown]))++ assert raised.value.code == "backend_model_id_prefix"+++def test_backend_catalog_rejects_a_new_unprefixed_claude_id_forged_into_baseline(+ tmp_path,+):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "claude"+ )+ forged = {+ **baseline[1],+ "id": "deepseek-v4",+ "origin": "manual",+ }++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(+ service.set_agent_models(+ "claude",+ [*baseline, forged],+ [*baseline, forged],+ )+ )++ assert raised.value.code == "backend_model_id_prefix"+++def test_backend_catalog_requires_claude_locked_default_echo(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "claude"+ )++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("claude", baseline, baseline[1:]))++ assert raised.value.code == "backend_model_locked"+ assert raised.value.status == 409++[email protected]("mutation", ["edit", "duplicate", "reorder"])+def test_backend_catalog_rejects_any_claude_locked_default_mutation(+ tmp_path,+ mutation,+):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "claude"+ )+ desired = copy.deepcopy(baseline)+ if mutation == "edit":+ desired[0]["display_name"] = "Not the server sentinel"+ elif mutation == "duplicate":+ desired.insert(1, copy.deepcopy(desired[0]))+ else:+ desired[0], desired[1] = desired[1], desired[0]++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("claude", baseline, desired))++ assert raised.value.code == "backend_model_locked"+ assert raised.value.status == 409+++def test_backend_catalog_reports_claude_discovery_prefix_requirement(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ baseline = next(+ agent["catalog_models"]+ for agent in service.list_agents()+ if agent["backend"] == "claude"+ )+ invalid = {+ **baseline[1],+ "id": "deepseek-v4",+ "origin": "manual",+ }++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("claude", baseline, [*baseline, invalid]))++ assert raised.value.code == "backend_model_id_prefix"++def test_agents_endpoint_projects_cli_presence_from_runtime(tmp_path):service, _store, _adapter = _service(tmp_path)service.cli_present_override = lambda backend: backend in {"claude", "codex"}@@ -2210,6 +2828,33 @@ def test_agents_route_requests_deep_presence_only_when_explicit(monkeypatch):assert calls == [False, True]+def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):+ class AgentService:+ def get_agent_sources(self, backend):+ return {+ "backend": backend,+ "mode": "hub",+ "catalog_models": [{"id": "catalog-model", "routeable": True}],+ "routes": {"catalog-model": {"hops": [{"source_id": "secret-source"}]}},+ "sources": {"order": ["secret-source"]},+ }++ monkeypatch.setattr(ui_server, "_model_hub_service", AgentService)++ response = app.test_client().get("/api/models/agents/codex/models")++ assert response.status_code == 200+ assert response.get_json() == {+ "ok": True,+ "contract_version": 6,+ "agent": {+ "backend": "codex",+ "mode": "hub",+ "catalog_models": [{"id": "catalog-model", "routeable": True}],+ },+ }++def test_usage_summary_rpc_reads_the_ledger_off_the_controller_loop(tmp_path):"""Review 4960570946: the read blocks as hard as the write it mirrors.diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex c50b86dea..ff55523d7 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -19,6 +19,7 @@ from config.v2_config import (MODEL_HUB_LEGACY_CREATED_AT,ModelHubAgentSourcesConfig,ModelHubAgentSupplyConfig,+ ModelHubBackendModelConfig,ModelHubConfig,ModelHubMenuConfig,ModelHubModelConfig,@@ -448,6 +449,7 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():"builtin_models": raw_example.get("builtin_models"),"standard_vendors": raw_example.get("standard_vendors"),}+ serialized.pop("models", None)if "routes" not in raw_example:serialized.pop("routes", None)if "sources" not in raw_example:@@ -2093,10 +2095,21 @@ def test_config_reload_recovers_inner_model_hub_invariant_only(elif invalid_invariant == "subscription-api-key":source["base_url"] = "https://api.anthropic.com"else:- payload["model_hub"]["agents"]["opencode"]["menu"] = {- "view": "featured",- "checked": ["invalid-opencode-identity"],- }+ payload["model_hub"]["agents"]["opencode"]["models"] = [+ {+ "id": "invalid-opencode-identity",+ "display_name": None,+ "origin": "manual",+ "models_dev_id": None,+ "context_window": None,+ "max_output_tokens": None,+ "input_modalities": [],+ "output_modalities": [],+ "supports_tools": None,+ "supports_reasoning": None,+ "reasoning_efforts": [],+ }+ ]if invalid_invariant != "opencode-identity":payload["model_hub"]["sources"] = [source]config_path = tmp_path / "config.json"@@ -2109,9 +2122,9 @@ def test_config_reload_recovers_inner_model_hub_invariant_only(assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]persisted = json.loads(config_path.read_text(encoding="utf-8"))["model_hub"]if invalid_invariant == "opencode-identity":- assert persisted["agents"]["opencode"]["menu"]["checked"] == [+ assert persisted["agents"]["opencode"]["models"][0]["id"] == ("invalid-opencode-identity"- ]+ )else:assert persisted["sources"] == [source]@@ -2856,37 +2869,67 @@ def test_persisted_hub_config_requires_explicit_complete_route_rows():"view": "featured","checked": ["custom/model"],}+ dynamic["agents"]["opencode"]["models"] = [+ {+ "id": "custom/model",+ "display_name": None,+ "origin": "manual",+ "models_dev_id": None,+ "context_window": None,+ "max_output_tokens": None,+ "input_modalities": [],+ "output_modalities": [],+ "supports_tools": None,+ "supports_reasoning": None,+ "reasoning_efforts": [],+ }+ ]dynamic["agents"]["opencode"]["routes"] = {}with pytest.raises(ValueError, match="missing menu model 'custom/model'"):ModelHubConfig.from_payload(dynamic)+ dormant = json.loads(json.dumps(payload))+ dormant["agents"]["opencode"]["routes"]["openai/dormant-model"] = {+ "hops": []+ }+ restored = ModelHubConfig.from_payload(dormant)+ assert restored.agents["opencode"].models == []+ assert "openai/dormant-model" in restored.agents["opencode"].routes+++def test_backend_model_modalities_match_the_contract_directions():+ input_pdf = ModelHubBackendModelConfig.from_payload(+ {"id": "custom-model", "input_modalities": ["pdf"]}+ )+ assert input_pdf.input_modalities == ["pdf"]-def test_config_reload_migrates_fixed_routes_when_bundled_catalog_changes(monkeypatch, tmp_path):+ with pytest.raises(ValueError, match="output_modalities"):+ ModelHubBackendModelConfig.from_payload(+ {"id": "custom-model", "output_modalities": ["pdf"]}+ )+++def test_config_reload_adds_bundled_routes_without_discarding_legacy_models(tmp_path):payload = api.config_to_payload(default_config())- original_ids = tuple(payload["model_hub"]["agents"]["claude"]["routes"])+ claude = payload["model_hub"]["agents"]["claude"]+ original_ids = tuple(claude["routes"])removed_id = original_ids[0]- added_id = "claude-catalog-added-after-save"stale_id = "claude-catalog-removed-after-save"- routes = payload["model_hub"]["agents"]["claude"]["routes"]+ routes = claude["routes"]routes.pop(removed_id)routes[stale_id] = {"hops": []}-- def changed_catalog_ids(backend: str) -> tuple[str, ...]:- if backend == "claude":- return (*original_ids[1:], added_id)- return tuple(payload["model_hub"]["agents"][backend]["routes"])-- monkeypatch.setattr("config.v2_config.model_hub_fixed_menu_ids", changed_catalog_ids)+ claude.pop("models")config_path = tmp_path / "config.json"config_path.write_text(json.dumps(payload), encoding="utf-8")loaded = V2Config.load(config_path=config_path)migrated_routes = loaded.model_hub.agents["claude"].routes+ migrated_models = loaded.model_hub.agents["claude"].models- assert set(migrated_routes) == set(changed_catalog_ids("claude"))- assert migrated_routes[added_id].hops == ()- assert removed_id not in migrated_routes- assert stale_id not in migrated_routes+ assert set(migrated_routes) == {*original_ids, stale_id}+ assert migrated_routes[removed_id].hops == ()+ assert migrated_routes[stale_id].hops == ()+ assert next(model for model in migrated_models if model.id == stale_id).origin == "manual"@pytest.mark.parametrize(diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 82565496d..60290c92b 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -120,22 +120,54 @@ def test_direct_launch_does_not_inject_provider_credentials():def test_hub_launch_masks_inherited_claude_auth_and_injects_gateway():- launch = hub_launch()+ launch = hub_launch(context_window=128_000, max_output_tokens=32_000)env = build_claude_hub_env({"ANTHROPIC_AUTH_TOKEN": "user-token","ANTHROPIC_BASE_URL": "https://user.example","CLAUDE_CODE_OAUTH_TOKEN": "oauth-token",+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "999999",+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "999999","PATH": "/bin",},launch,)assert env["ANTHROPIC_BASE_URL"] == launch.gateway_base_urlassert env["ANTHROPIC_AUTH_TOKEN"] == launch.gateway_token+ assert env["CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"] == "1"+ assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "128000"+ assert env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "32000"assert "CLAUDE_CODE_OAUTH_TOKEN" not in envassert claude_setting_sources_for_launch(launch) == ["project", "local"]+def test_native_cli_launch_keeps_auth_and_applies_catalog_limits():+ launch = hub_launch(+ channel="native_cli",+ gateway_base_url=None,+ gateway_token=None,+ context_window=128_000,+ max_output_tokens=32_000,+ )+ base_env = {+ "ANTHROPIC_AUTH_TOKEN": "user-token",+ "ANTHROPIC_BASE_URL": "https://user.example",+ "CLAUDE_CODE_OAUTH_TOKEN": "oauth-token",+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "999999",+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "999999",+ "PATH": "/bin",+ }++ env = build_claude_hub_env(base_env, launch)++ assert env["ANTHROPIC_AUTH_TOKEN"] == "user-token"+ assert env["ANTHROPIC_BASE_URL"] == "https://user.example"+ assert env["CLAUDE_CODE_OAUTH_TOKEN"] == "oauth-token"+ assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "128000"+ assert env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "32000"+ assert "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY" not in env++def test_codex_hub_launch_uses_responses_wire_api_and_ephemeral_token(tmp_path):"""MH-PROTOCOL-004: Hub launches consume a prepared standard Responses catalog."""@@ -211,3 +243,43 @@ def test_fallback_launch_identity_is_stable_for_same_route():second = hub_launch(target_model="model-b", runtime_model="model-b", source_id="src_inject02")assert first.fingerprint == second.fingerprintassert first.source_id != second.source_id++[email protected]("channel", ["hub", "native_cli"])+def test_claude_launch_fingerprint_covers_process_bound_catalog_metadata(channel):+ common = {+ "channel": channel,+ "gateway_base_url": "http://127.0.0.1:15220" if channel == "hub" else None,+ "gateway_token": "local-test-token" if channel == "hub" else None,+ "source_id": "src_inject01",+ }+ baseline = hub_launch(+ **common,+ context_window=128_000,+ max_output_tokens=32_000,+ reasoning_efforts=("high",),+ )++ for changed in (+ hub_launch(**common, context_window=256_000, max_output_tokens=32_000, reasoning_efforts=("high",)),+ hub_launch(**common, context_window=128_000, max_output_tokens=64_000, reasoning_efforts=("high",)),+ hub_launch(**common, context_window=128_000, max_output_tokens=32_000, reasoning_efforts=()),+ ):+ assert changed.fingerprint != baseline.fingerprint+++def test_codex_launch_fingerprint_ignores_metadata_loaded_by_the_app_server():+ baseline = hub_launch(+ backend="codex",+ context_window=128_000,+ max_output_tokens=32_000,+ reasoning_efforts=("high",),+ )+ changed = hub_launch(+ backend="codex",+ context_window=256_000,+ max_output_tokens=64_000,+ reasoning_efforts=(),+ )++ assert changed.fingerprint == baseline.fingerprintdiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex b0b5050f8..aee95f5e6 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -24,6 +24,7 @@ from sqlalchemy import create_engine, delete, selectfrom config.v2_config import (ModelHubAgentSourcesConfig,ModelHubAgentSupplyConfig,+ ModelHubBackendModelConfig,ModelHubConfig,ModelHubModelConfig,ModelHubRouteConfig,@@ -66,6 +67,7 @@ from core.handlers.model_hub.service import (ModelHubError,ModelHubService,ResolvedInvocation,+ project_opencode_public_model,)from core.handlers.model_hub.turn_gateway import (ModelHubTurnGateway,@@ -1202,6 +1204,9 @@ def _config(sources: list[ModelHubSourceConfig]) -> ModelHubConfig:for source in eligible))+ agents["opencode"].models = [+ ModelHubBackendModelConfig(id="openai/shared-model")+ ]agents["opencode"].menu.checked = ["openai/shared-model"]return ModelHubConfig(sources=sources, agents=agents)@@ -1541,6 +1546,48 @@ def test_terminal_retirement_does_not_restore_ambiguous_scope(assert store.get("turn_first") is None+def test_gateway_models_endpoint_serves_authenticated_backend_catalog(+ tmp_path: Path,+) -> None:+ async def exercise() -> None:+ service = _service(+ tmp_path,+ sources=[_source("src_primary01", "Primary")],+ )+ gateway = ModelHubTurnGateway(service)+ base_url, token = await gateway.endpoint(+ "codex",+ process_scope="/repo",+ turn_id="turn_models_catalog",+ requested_model_id="shared-model",+ resolved_model_id="shared-model",+ source_id="src_primary01",+ )+ expected = [+ model["id"]+ for model in service.backend_catalog_models("codex")+ if model["routeable"] is True+ ]+ try:+ async with aiohttp.ClientSession(trust_env=False) as client:+ unauthorized = await client.get(f"{base_url}/v1/models")+ assert unauthorized.status == 401+ response = await client.get(+ f"{base_url}/v1/models",+ headers={"Authorization": f"Bearer {token}"},+ )+ assert response.status == 200+ payload = await response.json()+ assert [model["id"] for model in payload["data"]] == expected+ assert payload["has_more"] is False+ assert payload["first_id"] == expected[0]+ assert payload["last_id"] == expected[-1]+ finally:+ await gateway.close()++ asyncio.run(exercise())++@pytest.mark.parametrize(("path", "body", "status", "reason"),[@@ -1850,6 +1897,114 @@ def test_runtime_no_candidate_projects_live_exact_hop_blockers(_assert_valid("turn-provenance.schema.json", record)+def test_runtime_launch_carries_claude_catalog_capabilities(tmp_path: Path) -> None:+ source = _source("src_catalogcap", "Catalog capability")+ service = _service(tmp_path, sources=[source])+ agent = service.store.config.agents["claude"]+ agent.models = [+ ModelHubBackendModelConfig(+ id="shared-model",+ context_window=128_000,+ max_output_tokens=32_000,+ supports_tools=True,+ supports_reasoning=True,+ reasoning_efforts=["low", "high"],+ )+ ]+ agent.routes = {+ "shared-model": ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "shared-model"),)+ )+ }+ gateway = SimpleNamespace(+ endpoint=AsyncMock(+ return_value=("http://127.0.0.1:19000/claude", "gateway-token")+ )+ )+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)++ launch = asyncio.run(router.resolve("claude", "shared-model"))++ assert launch.context_window == 128_000+ assert launch.max_output_tokens == 32_000+ assert launch.supports_tools is True+ assert launch.supports_reasoning is True+ assert launch.reasoning_efforts == ("low", "high")+++def test_native_cli_launch_carries_claude_catalog_capabilities(tmp_path: Path) -> None:+ source = _source(+ "src_nativecatalog",+ "Native catalog capability",+ channel="native_cli",+ vendor="anthropic",+ protocol="anthropic",+ )+ service = _service(tmp_path, sources=[source])+ agent = service.store.config.agents["claude"]+ agent.models = [+ ModelHubBackendModelConfig(+ id="shared-model",+ context_window=128_000,+ max_output_tokens=32_000,+ supports_tools=True,+ supports_reasoning=True,+ reasoning_efforts=["low", "max"],+ )+ ]+ agent.routes = {+ "shared-model": ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "shared-model"),)+ )+ }+ router = ModelHubRuntimeRouter(+ service=service,+ native_cli_ready=lambda _backend: True,+ )++ launch = asyncio.run(router.resolve("claude", "shared-model"))++ assert launch.channel == "native_cli"+ assert launch.context_window == 128_000+ assert launch.max_output_tokens == 32_000+ assert launch.supports_tools is True+ assert launch.supports_reasoning is True+ assert launch.reasoning_efforts == ("low", "max")+++def test_runtime_launch_suppresses_efforts_when_reasoning_is_disabled(+ tmp_path: Path,+) -> None:+ source = _source("src_noreasoning", "No reasoning")+ service = _service(tmp_path, sources=[source])+ agent = service.store.config.agents["claude"]+ agent.models = [+ ModelHubBackendModelConfig(+ id="shared-model",+ supports_reasoning=False,+ reasoning_efforts=["low", "high"],+ )+ ]+ agent.routes = {+ "shared-model": ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "shared-model"),)+ )+ }+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(+ endpoint=AsyncMock(+ return_value=("http://127.0.0.1:19000/claude", "gateway-token")+ )+ ),+ )++ launch = asyncio.run(router.resolve("claude", "shared-model"))++ assert launch.supports_reasoning is False+ assert launch.reasoning_efforts == ()++def test_runtime_no_candidate_reinspects_the_full_chain_for_terminal_facts(tmp_path: Path,) -> None:@@ -3885,6 +4040,56 @@ def test_gateway_provenance_retains_pre_mapping_model_identity(_assert_valid("turn-provenance.schema.json", record)+def test_gateway_accepts_canonical_backend_id_and_unique_legacy_target(+ tmp_path: Path,+) -> None:+ store = BoundedProvenanceStore(tmp_path / "provenance.json")+ registry = TurnCorrelationRegistry(store)+ token = registry.credentials("codex", "/repo", "turn_alias")+ registry.prepare_gateway_turn(+ backend="codex",+ token=token,+ requested_model_id="alias-a",+ resolved_model_id="model-b",+ source_id="src_primary01",+ via_mapping=False,+ gateway_request_model_id="alias-a",+ )++ assert (+ registry.begin_gateway_request(+ backend="codex",+ token=token,+ requested_model_id="alias-a",+ )+ == "turn_alias"+ )+ assert (+ registry.gateway_resolution_model(+ backend="codex",+ token=token,+ gateway_model_id="alias-a",+ )+ == "alias-a"+ )+ assert (+ registry.begin_gateway_request(+ backend="codex",+ token=token,+ requested_model_id="model-b",+ )+ == "turn_alias"+ )+ assert (+ registry.gateway_resolution_model(+ backend="codex",+ token=token,+ gateway_model_id="model-b",+ )+ == "alias-a"+ )++def test_gateway_uses_persisted_exact_hops_for_failover(tmp_path: Path,) -> None:@@ -4420,11 +4625,17 @@ def test_settlement_retires_correlation_when_mode_persistence_fails(def test_opencode_overlay_projects_menu_identity_to_exact_hop_model(tmp_path: Path) -> None:source = _source("src_overlay01", "Overlay", model_id="upstream-model")- source.models[0].reasoning_efforts = ["low", "high"]+ source.models[0].reasoning_efforts = ["medium"]config = _config([source])agent = config.agents["opencode"]agent.routes.pop("openai/shared-model")agent.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))+ agent.models = [+ ModelHubBackendModelConfig(+ id="openai/menu-model",+ reasoning_efforts=["low", "high"],+ )+ ]agent.menu.checked = ["openai/menu-model"]service = _service(tmp_path, sources=[source])service.store.config = config@@ -4474,6 +4685,13 @@ def test_opencode_public_models_follow_persisted_config_without_overlay(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))}+ agent.models = [+ ModelHubBackendModelConfig(+ id="custom/current-model",+ display_name="Current model",+ reasoning_efforts=["low", "high"],+ )+ ]agent.menu.checked = ["custom/current-model"]service = _service(tmp_path, sources=[source])service.store.config = config@@ -4493,6 +4711,58 @@ def test_opencode_public_models_follow_persisted_config_without_overlay(assert service.opencode_public_models() == {}+def test_opencode_public_model_hides_preserved_efforts_when_reasoning_is_disabled(+ tmp_path: Path,+) -> None:+ source = _source("src_no_reasoning", "No reasoning", model_id="upstream-model")+ config = _config([source])+ agent = config.agents["opencode"]+ agent.models = [+ ModelHubBackendModelConfig(+ id="custom/no-reasoning",+ supports_reasoning=False,+ reasoning_efforts=["low", "high"],+ )+ ]+ agent.menu.checked = ["custom/no-reasoning"]+ service = _service(tmp_path, sources=[source])+ service.store.config = config++ assert service.opencode_public_models()["custom/no-reasoning"] == {+ "id": "custom/no-reasoning",+ "name": "custom/no-reasoning",+ "reasoning": False,+ }+++ ("input_modalities", "output_modalities", "expected"),+ [+ (["text"], [], {"input": ["text"]}),+ ([], ["text"], {"output": ["text"]}),+ (["text", "image"], ["text"], {"input": ["text", "image"], "output": ["text"]}),+ ([], [], None),+ ],+)+def test_opencode_public_model_omits_unspecified_modality_directions(+ input_modalities: list[str],+ output_modalities: list[str],+ expected: dict[str, list[str]] | None,+) -> None:+ model = ModelHubBackendModelConfig(+ id="custom/modalities",+ input_modalities=input_modalities,+ output_modalities=output_modalities,+ )++ projected = project_opencode_public_model(model)++ if expected is None:+ assert "modalities" not in projected+ else:+ assert projected["modalities"] == expected++def test_opencode_overlay_private_provider_id_is_credential_scoped(tmp_path: Path,) -> None:@@ -4537,6 +4807,10 @@ def test_opencode_overlay_supports_mixed_protocols_under_one_provider(tmp_path:)config = _config([first, second])agent = config.agents["opencode"]+ agent.models = [+ ModelHubBackendModelConfig(id="custom/first-model"),+ ModelHubBackendModelConfig(id="custom/second-model"),+ ]agent.menu.checked = ["custom/first-model", "custom/second-model"]agent.routes = {"custom/first-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(first.id, "first-model"),)),@@ -4585,6 +4859,7 @@ def test_opencode_overlay_selects_supported_fallback_by_exact_hop(tmp_path: PathModelHubRouteHopConfig(source.id, "supported-model"),))+ agent.models = [ModelHubBackendModelConfig(id="openai/menu-model")]agent.menu.checked = ["openai/menu-model"]service = _service(tmp_path, sources=[source])service.store.config = config@@ -4614,6 +4889,7 @@ def test_opencode_overlay_preserves_checked_route_with_stale_exact_hop(agent = config.agents["opencode"]agent.routes.pop("openai/shared-model")agent.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "stale-model"),))+ agent.models = [ModelHubBackendModelConfig(id="openai/menu-model")]agent.menu.checked = ["openai/menu-model"]service = _service(tmp_path, sources=[source])service.store.config = configdiff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 96677fa5a..1d5fcc1fd 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -12,6 +12,7 @@ import pytestfrom config.v2_config import (ModelHubAgentSupplyConfig,+ ModelHubBackendModelConfig,ModelHubConfig,ModelHubMenuConfig,ModelHubModelConfig,@@ -1115,6 +1116,7 @@ def test_opencode_menu_preserves_an_existing_route_alias_while_adding_inventory(view="featured",checked=["openai/menu-model"],)+ opencode.models = [ModelHubBackendModelConfig(id="openai/menu-model")]opencode.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))@@ -1137,10 +1139,15 @@ def test_opencode_menu_preserves_an_existing_route_alias_while_adding_inventory()-def test_opencode_menu_reselects_a_dormant_route_alias_with_an_eligible_exact_hop(tmp_path):- source = _source("src_opencode05", ("upstream-model",), vendor="openai")+def test_opencode_menu_hides_a_model_without_removing_its_route(tmp_path):+ source = _source("src_opencode07", ("upstream-model",), vendor="openai")config = _config([source])opencode = config.agents["opencode"]+ opencode.menu = ModelHubMenuConfig(+ view="featured",+ checked=["openai/menu-model"],+ )+ opencode.models = [ModelHubBackendModelConfig(id="openai/menu-model")]opencode.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))@@ -1148,24 +1155,39 @@ def test_opencode_menu_reselects_a_dormant_route_alias_with_an_eligible_exact_hoasyncio.run(service.set_opencode_menu(- {"view": "featured", "checked": []},{"view": "featured", "checked": ["openai/menu-model"]},+ {"view": "featured", "checked": []},))saved = store.load().agents["opencode"]- assert saved.menu.checked == ["openai/menu-model"]+ assert saved.menu.checked == []+ assert saved.models == []assert saved.routes["openai/menu-model"].hops == (ModelHubRouteHopConfig(source.id, "upstream-model"),)-def test_opencode_menu_rejects_a_dormant_route_alias_with_a_stale_exact_hop(tmp_path):- source = _source("src_opencode06", (), vendor="openai")+def test_opencode_menu_adds_an_inventory_model_with_an_empty_route(tmp_path):+ source = _source("src_opencode05", ("upstream-model",), vendor="openai")config = _config([source])- config.agents["opencode"].routes["openai/menu-model"] = ModelHubRouteConfig(- hops=(ModelHubRouteHopConfig(source.id, "removed-model"),)+ service, store, _ = _service(tmp_path, config)++ asyncio.run(+ service.set_opencode_menu(+ {"view": "featured", "checked": []},+ {"view": "featured", "checked": ["openai/upstream-model"]},+ ))++ saved = store.load().agents["opencode"]+ assert saved.menu.checked == ["openai/upstream-model"]+ assert saved.routes["openai/upstream-model"].hops == ()+++def test_opencode_menu_rejects_a_model_absent_from_inventory(tmp_path):+ source = _source("src_opencode06", (), vendor="openai")+ config = _config([source])service, store, _ = _service(tmp_path, config)with pytest.raises(ModelHubError) as exc:@@ -1192,6 +1214,10 @@ def test_opencode_menu_applies_local_intent_to_the_latest_saved_menu(tmp_path):view="featured",checked=["openai/model-a", "openai/model-b"],)+ config.agents["opencode"].models = [+ ModelHubBackendModelConfig(id="openai/model-a"),+ ModelHubBackendModelConfig(id="openai/model-b"),+ ]config.agents["opencode"].routes.update({"openai/model-a": ModelHubRouteConfig(),@@ -1242,6 +1268,9 @@ def test_explicit_opencode_selection_outside_menu_remains_visible(tmp_path):config = ModelHubConfig()config.agents["opencode"].mode = "hub"config.agents["opencode"].menu.checked = ["openai/visible-model"]+ config.agents["opencode"].models = [+ ModelHubBackendModelConfig(id="openai/visible-model")+ ]service, store, _ = _service(tmp_path, config)store.requested_models["opencode"] = "custom/hidden-model"service.named_agents_override = lambda backend: (@@ -1306,6 +1335,9 @@ def test_chain_write_rejects_models_outside_the_current_menu(source = _source("src_menu0001", ("upstream-model",), vendor="openai")config = _config([source])config.agents["opencode"].menu.checked = ["openai/visible-model"]+ config.agents["opencode"].models = [+ ModelHubBackendModelConfig(id="openai/visible-model")+ ]config.agents["opencode"].routes["openai/visible-model"] = ModelHubRouteConfig()service, store, _ = _service(tmp_path, config)before = store.load().to_payload()@@ -1456,10 +1488,7 @@ def test_opencode_identity_computation_stays_in_validator_and_resolver():)validator_calls = RawIdentityCalls()validator_calls.visit(validator)- assert set(validator_calls.calls) == {- "STANDARD_OPENCODE_VENDOR_IDS",- "parse_opencode_model_id",- }+ assert set(validator_calls.calls) == {"parse_opencode_model_id"}other_config_calls = RawIdentityCalls()other_config_calls.visit(Module(@@ -1736,6 +1765,7 @@ def test_create_source_normalizes_vendor_before_matching_v1_placement(tmp_path):opencode.mode = "hub"assert opencode.menu is not Noneopencode.menu.checked = ["openai/gpt-5.6"]+ opencode.models = [ModelHubBackendModelConfig(id="openai/gpt-5.6")]opencode.routes["openai/gpt-5.6"] = ModelHubRouteConfig()adapter = FakeAdapter(discovered=("gpt-5.6",))service, store, _ = _service(tmp_path, config, adapter)diff --git a/tests/test_model_hub_usage.py b/tests/test_model_hub_usage.pyindex 342ccdaaa..9b5af7813 100644--- a/tests/test_model_hub_usage.py+++ b/tests/test_model_hub_usage.py@@ -31,6 +31,7 @@ from config.v2_config import ModelHubModelConfigfrom core.handlers.model_hub.identifiers import (MODEL_ID_MAX_LENGTH,USAGE_LEDGER_KEY_MAX_LENGTH,+ USAGE_LEDGER_VERBATIM_MAX_LENGTH,persisted_ledger_key,usage_ledger_key,)@@ -1165,6 +1166,14 @@ def test_an_unusable_identifier_is_never_persisted(pytest.param("model-x", id="ordinary"),pytest.param(" model-x ", id="padded"),pytest.param(" ", id="padding-only"),+ pytest.param(+ "m" * USAGE_LEDGER_VERBATIM_MAX_LENGTH,+ id="at-the-ledger-verbatim-bound",+ ),+ pytest.param(+ "m" * (USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1),+ id="one-past-the-ledger-verbatim-bound",+ ),pytest.param("m" * MODEL_ID_MAX_LENGTH, id="at-the-admission-bound"),pytest.param("m" * (MODEL_ID_MAX_LENGTH + 1), id="one-past-it"),pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH * 4), id="far-past-it"),@@ -1184,8 +1193,8 @@ def test_metering_can_key_exactly_the_identities_a_config_can_hold(identifier: oKeying the loaded value and the raw payload alike stops one model from occupyingtwo rows. The length assertion is the review-4966041599 property: a key is either- within the admission bound or exactly a folded key's length, never in between, so- no identifier a config can hold can occupy the folded form. And the read path+ within the stable verbatim bound or exactly a folded key's length, never in+ between, so no admitted identifier can occupy the folded form. And the read pathreturns a derived key unchanged, so a row read back after a restart is the rowthat was written — the guarantee that used to be spelled as self-idempotence,which is what forced the fold to start too late.@@ -1203,7 +1212,10 @@ def test_metering_can_key_exactly_the_identities_a_config_can_hold(identifier: oassert (key is None) == (loadable is None)if key is None:return- assert len(key) <= MODEL_ID_MAX_LENGTH or len(key) == USAGE_LEDGER_KEY_MAX_LENGTH+ assert (+ len(key) <= USAGE_LEDGER_VERBATIM_MAX_LENGTH+ or len(key) == USAGE_LEDGER_KEY_MAX_LENGTH+ )assert usage_ledger_key(loadable) == keyassert persisted_ledger_key(key) == key@@ -1211,6 +1223,14 @@ def test_metering_can_key_exactly_the_identities_a_config_can_hold(identifier: o@pytest.mark.parametrize("model_id",[+ pytest.param(+ "m" * USAGE_LEDGER_VERBATIM_MAX_LENGTH,+ id="at-the-ledger-verbatim-bound",+ ),+ pytest.param(+ "m" * (USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1),+ id="one-past-the-ledger-verbatim-bound",+ ),pytest.param("m" * MODEL_ID_MAX_LENGTH, id="at-the-admission-bound"),pytest.param("m" * (MODEL_ID_MAX_LENGTH + 1), id="one-past-it"),pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH * 4), id="far-past-it"),@@ -1276,8 +1296,9 @@ def test_no_two_identities_a_config_holds_can_share_one_row(tmp_path: Path) -> Nseeds = ("model-x",- "m" * MODEL_ID_MAX_LENGTH,- "m" * (MODEL_ID_MAX_LENGTH + 1),+ "m" * USAGE_LEDGER_VERBATIM_MAX_LENGTH,+ "m" * (USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1),+ "n" * MODEL_ID_MAX_LENGTH,"z" * (USAGE_LEDGER_KEY_MAX_LENGTH * 3),)identities = sorted({*seeds, *(usage_ledger_key(seed) for seed in seeds)})@@ -1301,8 +1322,14 @@ def test_no_two_identities_a_config_holds_can_share_one_row(tmp_path: Path) -> N@pytest.mark.parametrize("key",[- pytest.param("m" * MODEL_ID_MAX_LENGTH, id="a-verbatim-key"),- pytest.param(usage_ledger_key("m" * (MODEL_ID_MAX_LENGTH + 1)), id="a-folded-key"),+ pytest.param(+ "m" * USAGE_LEDGER_VERBATIM_MAX_LENGTH,+ id="a-verbatim-key",+ ),+ pytest.param(+ usage_ledger_key("m" * (USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1)),+ id="a-folded-key",+ ),pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH + 1), id="one-past-every-derivable-key"),pytest.param("m" * (USAGE_LEDGER_KEY_MAX_LENGTH * 8), id="far-past-them"),],@@ -1436,8 +1463,8 @@ def _keying_populations(prefix: str) -> tuple[str, ...]:return (padded(len(prefix) + 8),- padded(MODEL_ID_MAX_LENGTH),- padded(MODEL_ID_MAX_LENGTH + 1),+ padded(USAGE_LEDGER_VERBATIM_MAX_LENGTH),+ padded(USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1),padded(USAGE_LEDGER_KEY_MAX_LENGTH * 2),)diff --git a/tests/test_models_dev_catalog.py b/tests/test_models_dev_catalog.pynew file mode 100644index 000000000..e2ef8a588--- /dev/null+++ b/tests/test_models_dev_catalog.py@@ -0,0 +1,159 @@+from __future__ import annotations++import json+import time+import urllib.error++import pytest++from vibe import models_dev_catalog+++class _Response:+ def __init__(self, payload, *, headers=None):+ self.payload = payload+ self.headers = headers or {}++ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return None++ def read(self, _limit):+ return json.dumps(self.payload).encode()+++def _catalog():+ return {+ "deepseek": {+ "id": "deepseek",+ "name": "DeepSeek",+ "models": {+ "deepseek-v4": {+ "id": "deepseek-v4",+ "name": "DeepSeek V4",+ "reasoning": True,+ "reasoning_options": [+ {"type": "effort", "values": ["low", "high", "low"]}+ ],+ "tool_call": True,+ "modalities": {+ "input": ["text", "image", "image", "pdf", "unknown"],+ "output": ["text", "text", "pdf"],+ },+ "limit": {"context": 1_048_576, "output": 131_072},+ }+ },+ }+ }+++def test_models_dev_search_normalizes_editable_metadata(monkeypatch, tmp_path):+ cache_path = tmp_path / "models-dev.json"+ monkeypatch.setattr(models_dev_catalog, "_cache_path", lambda: cache_path)+ monkeypatch.setattr(+ models_dev_catalog.urllib.request,+ "urlopen",+ lambda request, timeout: _Response(+ _catalog(),+ headers={"ETag": '"catalog-v1"'},+ ),+ )++ matches = models_dev_catalog.search_models_dev("deepseek-v4")++ assert matches == [+ {+ "provider_id": "deepseek",+ "provider_name": "DeepSeek",+ "model_id": "deepseek-v4",+ "models_dev_id": "deepseek/deepseek-v4",+ "display_name": "DeepSeek V4",+ "context_window": 1_048_576,+ "max_output_tokens": 131_072,+ "input_modalities": ["text", "image", "pdf"],+ "output_modalities": ["text"],+ "supports_tools": True,+ "supports_reasoning": True,+ "reasoning_efforts": ["low", "high"],+ }+ ]+ cached = json.loads(cache_path.read_text(encoding="utf-8"))+ assert cached["etag"] == '"catalog-v1"'+ assert cached["catalog"] == _catalog()+++def test_models_dev_search_uses_fresh_cache_without_network(monkeypatch, tmp_path):+ cache_path = tmp_path / "models-dev.json"+ monkeypatch.setattr(models_dev_catalog, "_cache_path", lambda: cache_path)+ cache_path.write_text(+ json.dumps(+ {+ "fetched_at": time.time(),+ "url": models_dev_catalog.DEFAULT_MODELS_DEV_URL,+ "catalog": _catalog(),+ }+ ),+ encoding="utf-8",+ )++ def unexpected(*_args, **_kwargs):+ raise AssertionError("fresh cache must avoid network")++ monkeypatch.setattr(models_dev_catalog.urllib.request, "urlopen", unexpected)++ assert models_dev_catalog.search_models_dev("deepseek/deepseek-v4")[0][+ "models_dev_id"+ ] == "deepseek/deepseek-v4"+++def test_models_dev_search_falls_back_to_stale_cache(monkeypatch, tmp_path):+ cache_path = tmp_path / "models-dev.json"+ monkeypatch.setattr(models_dev_catalog, "_cache_path", lambda: cache_path)+ cache_path.write_text(+ json.dumps(+ {+ "fetched_at": 0,+ "url": models_dev_catalog.DEFAULT_MODELS_DEV_URL,+ "catalog": _catalog(),+ }+ ),+ encoding="utf-8",+ )++ def unavailable(*_args, **_kwargs):+ raise urllib.error.URLError("offline")++ monkeypatch.setattr(models_dev_catalog.urllib.request, "urlopen", unavailable)++ assert models_dev_catalog.search_models_dev("DeepSeek V4")[0][+ "context_window"+ ] == 1_048_576+++def test_models_dev_stale_cache_is_scoped_to_its_url(monkeypatch, tmp_path):+ cache_path = tmp_path / "models-dev.json"+ monkeypatch.setattr(models_dev_catalog, "_cache_path", lambda: cache_path)+ cache_path.write_text(+ json.dumps(+ {+ "fetched_at": 0,+ "url": models_dev_catalog.DEFAULT_MODELS_DEV_URL,+ "catalog": _catalog(),+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setenv(+ models_dev_catalog.MODELS_DEV_URL_ENV,+ "https://catalog.example.invalid/api.json",+ )++ def unavailable(*_args, **_kwargs):+ raise urllib.error.URLError("offline")++ monkeypatch.setattr(models_dev_catalog.urllib.request, "urlopen", unavailable)++ with pytest.raises(RuntimeError, match="unavailable"):+ models_dev_catalog.search_models_dev("deepseek-v4")diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 1dd437de9..386752fa4 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -83,15 +83,52 @@ describe('AgentCard', () => {render(<I18nextProvider i18n={localeInstance('zh')}><AgentCard agents={[agentWithRetainedRoute]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.getByText('网关 · 未配置模型路由')).toBeTruthy();- expect(screen.getByText('已选 0 个模型')).toBeTruthy();- expect(screen.getByText('尚未选择模型')).toBeTruthy();+ expect(screen.getByText('0 个模型')).toBeTruthy();+ // The card offers the catalog instead of reporting missing supply: an empty+ // list is something the user can fix from here, not a broken backend.+ expect(screen.getByText('这个后端的模型列表是空的')).toBeTruthy();expect(screen.queryByText(retainedModelId)).toBeNull();- expect(screen.queryByText('这个后端没有可用模型')).toBeNull();await userEvent.click(screen.getAllByRole('button', { name: '管理模型' })[0]);expect(onOpenModels).toHaveBeenCalledWith(agentWithRetainedRoute);});+ it('offers the same catalog action on every backend and lists the catalog in its own order', async () => {+ const onOpenModels = vi.fn();+ const catalogued = (backend: AgentSupply['backend'], ids: string[]): AgentSupply => ({+ ...hubAgent,+ backend,+ routes: {},+ model_supply: ids.map((modelId) => ({ model_id: modelId, chain_length: 1, has_runnable_hop: true })),+ catalog_models: ids.map((id) => ({+ id, display_name: null, origin: 'manual', models_dev_id: null, context_window: null, max_output_tokens: null,+ input_modalities: ['text'], output_modalities: ['text'], supports_tools: true, supports_reasoning: false,+ reasoning_efforts: [], locked: false, routeable: true,+ })),+ });+ const agents = [+ catalogued('claude', ['claude-two', 'claude-one']),+ catalogued('codex', ['codex-only']),+ catalogued('opencode', ['openai/one']),+ ];+ render(<I18nextProvider i18n={i18n}><AgentCard agents={agents} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);++ // The OpenCode-only distinction is gone: the action is the backend-agnostic one.+ const actions = screen.getAllByRole('button', { name: 'Manage models' });+ expect(actions).toHaveLength(agents.length);+ await userEvent.click(actions[1]);+ expect(onOpenModels).toHaveBeenCalledWith(agents[1]);++ // Catalog order, not an alphabetized or legacy projection.+ const routeRows = screen.getAllByRole('button', { name: /route chain/i });+ expect(routeRows.map((row) => row.getAttribute('aria-label'))).toEqual([+ 'Open claude-two route chain',+ 'Open claude-one route chain',+ 'Open codex-only route chain',+ 'Open openai/one route chain',+ ]);+ });+it('labels a selected OpenCode model with an empty route as unconfigured', () => {const modelId = 'openai/gpt-5.6-luna';render(<I18nextProvider i18n={localeInstance('zh')}><AgentCard agents={[{@@ -100,7 +137,7 @@ describe('AgentCard', () => {model_supply: [{ model_id: modelId, chain_length: 0, has_runnable_hop: false }],}]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);- expect(screen.getByText('已选 1 个模型')).toBeTruthy();+ expect(screen.getByText('1 个模型')).toBeTruthy();expect(screen.getByText(modelId)).toBeTruthy();expect(screen.getByText('未配置模型路由')).toBeTruthy();expect(screen.queryByText('没有可用供应商')).toBeNull();@@ -206,13 +243,19 @@ describe('AgentCard', () => {expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(2);});- it('offers only gateway enablement and ignores stale chain data in direct mode', () => {+ it('hides gateway-owned catalog and supply actions in direct mode', () => {+ const onOpenModels = vi.fn();const key = modelChainKey('claude', 'claude-opus-4-6');- render(<I18nextProvider i18n={i18n}><AgentCard agents={[{ ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null }]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 6, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ const directAgent: AgentSupply = { ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null };+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 6, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.queryByText(/Adjust priority/i)).toBeNull();expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();expect(screen.queryByText(/Backup/)).toBeNull();expect(screen.queryByText(/takeover/i)).toBeNull();++ expect(screen.getByRole('button', { name: 'Switch to gateway' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Manage models' })).toBeNull();+ expect(onOpenModels).not.toHaveBeenCalled();});it.each([diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 89193a449..d310a384b 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -6,7 +6,8 @@ import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { ResponsiveMenu } from '@/components/ui/responsive-menu';import { cn } from '@/lib/utils';-import { collapsedModelRows, modelChainKey, modelSupplyState, visibleModelIds, type ModelChainIndex, type ModelChainRead } from './modelRows';+import { catalogModelIds } from './backendCatalog';+import { collapsedModelRows, modelChainKey, modelSupplyState, type ModelChainIndex, type ModelChainRead } from './modelRows';import { foldRegionRead } from './regionRead';import { agentGroupStatus } from './supply';import { agentHasLiveChainProjection, type FreshRuntimeProjection } from './runtimeLifecycle';@@ -34,6 +35,26 @@ const isTakeoverRead = (read: ModelChainRead | undefined): boolean => {return chain ? isTakeoverChain(chain) : false;};+const ManageModelsButton: React.FC<{+ className?: string;+ disabled: boolean;+ onClick: () => void;+}> = ({ className, disabled, onClick }) => {+ const { t } = useTranslation();+ return (+ <Button+ variant="outline"+ size="xs"+ className={cn('rounded-md bg-background px-2.5 text-[11px] font-semibold shadow-sm', className)}+ onClick={onClick}+ disabled={disabled}+ >+ <ListChecks aria-hidden="true" />+ {t('settings.models.gateway.manageModels')}+ </Button>+ );+};+const ModelRow: React.FC<{agent: AgentSupply;modelId: string;@@ -116,9 +137,7 @@ const AgentModelCard: React.FC<{const { Icon, accent } = backendVisual(agent.backend);const [expanded, setExpanded] = React.useState(false);const [modeMenuOpen, setModeMenuOpen] = React.useState(false);- const allModels = visibleModelIds(agent);- const hasOpenMenu = agent.menu_kind === 'open';- const displayedModelCount = hasOpenMenu ? agent.menu?.checked.length ?? 0 : allModels.length;+ const allModels = catalogModelIds(agent);const chainProjectionLive = agentHasLiveChainProjection(runtime, agent);const collapsed = collapsedModelRows(agent, expanded);const collapsedAtRest = collapsedModelRows(agent);@@ -174,7 +193,7 @@ const AgentModelCard: React.FC<{<Badge variant="secondary" className={cn('model-hub-pill model-hub-fill-0a', hasTakeover && 'model-hub-takeover-chip')}>{hasTakeover? t('settings.models.takeover.chip')- : t(hasOpenMenu ? 'settings.models.gateway.selectedModelCount' : 'settings.models.gateway.modelCount', { count: displayedModelCount })}+ : t('settings.models.gateway.modelCount', { count: allModels.length })}</Badge></span></div>@@ -226,13 +245,13 @@ const AgentModelCard: React.FC<{</button></div></ResponsiveMenu>- {hasOpenMenu && <Button variant="outline" size="xs" className="model-hub-agent-head-action rounded-md bg-background px-2.5 text-[11px] font-semibold shadow-sm" onClick={() => onOpenModels(agent)} disabled={pending}><ListChecks aria-hidden="true" />{t('settings.models.gateway.manageModels')}</Button>}+ <ManageModelsButton className="model-hub-agent-head-action" disabled={pending} onClick={() => onOpenModels(agent)} /><Button variant="outline" size="xs" className="model-hub-agent-head-action rounded-md bg-background px-2.5 text-[11px] font-semibold shadow-sm" onClick={() => onOpenOrder(agent)} disabled={pending}><ArrowDownUp aria-hidden="true" />{t('settings.models.gateway.sourceOrder')}</Button></div>) : <Button variant="default" size="xs" className="model-hub-agent-head-action shrink-0 self-start rounded-md px-2.5 text-[11px] font-semibold sm:self-auto" onClick={() => onConnectHub(agent)} disabled={connecting}><PlugZap aria-hidden="true" />{t('settings.models.gateway.switchToGateway')}</Button>}</div></div>- {agent.mode === 'hub' && (models.length === 0 ? <div className="flex flex-col items-center gap-3 px-4 py-10 text-center sm:px-5"><p className="text-[12.5px] text-muted">{t(hasOpenMenu ? 'settings.models.gateway.group.emptySelection' : 'settings.models.gateway.group.emptyModels')}</p>{hasOpenMenu && <Button variant="outline" size="xs" className="rounded-md bg-background px-2.5 text-[11px] font-semibold shadow-sm" onClick={() => onOpenModels(agent)} disabled={pending}><ListChecks aria-hidden="true" />{t('settings.models.gateway.manageModels')}</Button>}</div> : <div className="space-y-2 p-2">{noUsableSource && <p className="px-3 py-1 text-[11px] font-semibold text-muted">{t('settings.models.gateway.supply.none')}</p>}{models.map((modelId) => <ModelRow key={modelId} agent={agent} modelId={modelId} sources={sources} read={chainProjectionLive ? chains[modelChainKey(agent.backend, modelId)] : undefined} onOpenRoute={onOpenRoute} />)}{canCollapse ? <button type="button" onClick={toggleCollapsed} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground">{expanded ? <ChevronUp /> : <ChevronDown />}{expanded ? t('settings.models.gateway.collapse') : t('settings.models.gateway.moreModels', { count: collapsed.hidden.length })}</button> : needsChainRepair ? <button type="button" onClick={retryChains} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground"><RefreshCw />{t('settings.models.gateway.retry')}</button> : null}</div>)}+ {agent.mode === 'hub' && (models.length === 0 ? <div className="flex flex-col items-center gap-3 px-4 py-10 text-center sm:px-5"><p className="text-[12.5px] text-muted">{t('settings.models.gateway.group.emptyModels')}</p><ManageModelsButton disabled={pending} onClick={() => onOpenModels(agent)} /></div> : <div className="space-y-2 p-2">{noUsableSource && <p className="px-3 py-1 text-[11px] font-semibold text-muted">{t('settings.models.gateway.supply.none')}</p>}{models.map((modelId) => <ModelRow key={modelId} agent={agent} modelId={modelId} sources={sources} read={chainProjectionLive ? chains[modelChainKey(agent.backend, modelId)] : undefined} onOpenRoute={onOpenRoute} />)}{canCollapse ? <button type="button" onClick={toggleCollapsed} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground">{expanded ? <ChevronUp /> : <ChevronDown />}{expanded ? t('settings.models.gateway.collapse') : t('settings.models.gateway.moreModels', { count: collapsed.hidden.length })}</button> : needsChainRepair ? <button type="button" onClick={retryChains} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground"><RefreshCw />{t('settings.models.gateway.retry')}</button> : null}</div>)}</section>);};diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsxnew file mode 100644index 000000000..0fc377548--- /dev/null+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx@@ -0,0 +1,383 @@+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { BackendModelCatalogDialog } from './BackendModelCatalogDialog';+import { blankBackendModel } from './backendCatalog';+import { ApiCallError, modelsApi } from './modelsApi';+import type { AgentSupply, BackendModel } from './types';++const model = (id: string, overrides: Partial<BackendModel> = {}): BackendModel => ({+ ...blankBackendModel(),+ id,+ ...overrides,+});++const locked = model('claude-default', { locked: true, routeable: false });++const agent = (catalog: BackendModel[] | undefined, overrides: Partial<AgentSupply> = {}): AgentSupply => ({+ backend: 'claude',+ cli_present: true,+ mode: 'hub',+ menu_kind: 'fixed',+ sources: { order: [], eligibility: [] },+ routes: {},+ builtin_models: ['legacy-a', 'legacy-b'],+ menu: null,+ ...(catalog ? { catalog_models: catalog } : {}),+ ...overrides,+});++const renderDialog = (overrides: Partial<React.ComponentProps<typeof BackendModelCatalogDialog>> = {}) => {+ const onClose = vi.fn();+ const onSaved = vi.fn();+ const onObserved = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <BackendModelCatalogDialog+ open+ backend="claude"+ onClose={onClose}+ onSaved={onSaved}+ onObserved={onObserved}+ catalogWrite={{ pending: false, track: async (work) => work() }}+ {...overrides}+ />+ </I18nextProvider>,+ );+ return { onClose, onSaved, onObserved };+};++afterEach(async () => {+ cleanup();+ vi.restoreAllMocks();+ await i18n.changeLanguage('en');+});++describe('BackendModelCatalogDialog', () => {+ it('shows a locked row without any way to edit, remove, or reorder it', async () => {+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([locked, model('alpha')]));+ renderDialog();++ expect(await screen.findByRole('heading', { name: 'Claude Code models' })).toBeTruthy();+ expect(screen.getByText('claude-default')).toBeTruthy();+ expect(screen.getByText('Default')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Reorder alpha' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Reorder claude-default' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Edit claude-default' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Remove claude-default' })).toBeNull();+ expect(screen.getByText('2 models')).toBeTruthy();+ });++ it('localizes the server-owned Claude default row instead of rendering backend copy', async () => {+ await i18n.changeLanguage('zh');+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([+ model('default', { display_name: null, locked: true, routeable: false }),+ ]));+ renderDialog();++ expect(await screen.findByText('Claude Code 默认模型')).toBeTruthy();+ expect(screen.getByText('default')).toBeTruthy();+ expect(screen.queryByText('Default')).toBeNull();+ expect(screen.getByLabelText('搜索名称或模型 ID')).toBeTruthy();+ });++ it('shows the catalog and nothing else — no source, route, fallback or mapping control', async () => {+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha')], {+ routes: { alpha: { hops: [{ source_id: 'src_a', model_id: 'alpha' }] } },+ }));+ renderDialog();++ await screen.findByRole('button', { name: 'Reorder alpha' });+ expect(screen.queryByText(/source/i)).toBeNull();+ expect(screen.queryByText(/route/i)).toBeNull();+ expect(screen.queryByText(/fallback/i)).toBeNull();+ expect(screen.queryByText(/priority/i)).toBeNull();+ expect(screen.queryByText('src_a')).toBeNull();+ });++ it('adds a model through the editor and settles the whole list in one write', async () => {+ const user = userEvent.setup();+ const catalog = [locked, model('alpha')];+ const echoed = agent([...catalog, model('added')]);+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ const putAgentModels = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(echoed);+ const { onSaved, onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Add model' }));+ await user.type(screen.getByLabelText('Backend model ID'), 'added');+ await user.click(screen.getByRole('button', { name: 'Add model' }));++ // Nothing is written until the list itself is saved.+ expect(putAgentModels).not.toHaveBeenCalled();+ expect(await screen.findByText('3 models')).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(putAgentModels).toHaveBeenCalledWith('claude', {+ baseline: catalog,+ models: [...catalog, model('added')],+ }));+ expect(onSaved).toHaveBeenCalledWith(echoed);+ expect(onClose).toHaveBeenCalled();+ });++ it('edits an existing row without renaming it', async () => {+ const user = userEvent.setup();+ const catalog = [model('alpha', { context_window: 1000 })];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ const putAgentModels = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(agent(catalog));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Edit alpha' }));+ expect((screen.getByLabelText('Backend model ID') as HTMLInputElement).readOnly).toBe(true);+ await user.clear(screen.getByLabelText('Context window'));+ await user.type(screen.getByLabelText('Context window'), '2000');+ await user.click(screen.getByRole('button', { name: 'Save model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ await waitFor(() => expect(putAgentModels).toHaveBeenCalledWith('claude', {+ baseline: catalog,+ models: [model('alpha', { context_window: 2000 })],+ }));+ });++ it('refuses to remove a model that still has a route', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')], {+ routes: { alpha: { hops: [{ source_id: 'src_a', model_id: 'alpha' }] } },+ }));+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove alpha' }));+ expect(screen.getByRole('alert').textContent).toBe('This model still has a route. Clear its route first, then remove it.');+ expect(screen.getByText('2 models')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);++ await user.click(screen.getByRole('button', { name: 'Remove beta' }));+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByText('1 model')).toBeTruthy();+ });++ it('reorders with the keyboard, announces the move, and leaves the locked row where it is', async () => {+ const user = userEvent.setup();+ const catalog = [locked, model('alpha'), model('beta')];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ const putAgentModels = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(agent(catalog));+ renderDialog();++ const grip = await screen.findByRole('button', { name: 'Reorder alpha' });+ grip.focus();+ await user.keyboard('[Space]');+ expect(screen.getByText('Grabbed alpha, position 1 of 2.')).toBeTruthy();++ await user.keyboard('[ArrowDown]');+ expect(screen.getByText('Moved alpha to position 2 of 2.')).toBeTruthy();+ await user.keyboard('[Space]');+ expect(screen.getByText('Dropped alpha at position 2 of 2.')).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(putAgentModels).toHaveBeenCalledWith('claude', {+ baseline: catalog,+ models: [locked, model('beta'), model('alpha')],+ }));+ });++ it('restores the pre-grab order when the move is cancelled', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));+ renderDialog();++ const grip = await screen.findByRole('button', { name: 'Reorder alpha' });+ grip.focus();+ await user.keyboard('[Space][ArrowDown][Escape]');++ expect(screen.getByText('Cancelled moving alpha and restored its original position.')).toBeTruthy();+ const rows = screen.getAllByRole('button', { name: /^Reorder / });+ expect(rows.map((row) => row.getAttribute('aria-label'))).toEqual(['Reorder alpha', 'Reorder beta']);+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ });++ it('filters by ID or display name and suspends dragging while filtered', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([+ model('alpha', { display_name: 'Bright Alpha' }),+ model('beta'),+ ]));+ renderDialog();++ await user.type(await screen.findByLabelText('Search name or model ID'), 'bright');+ expect(screen.queryByRole('button', { name: 'Reorder beta' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Reorder Bright Alpha' }).hasAttribute('disabled')).toBe(true);++ await user.clear(screen.getByLabelText('Search name or model ID'));+ await user.type(screen.getByLabelText('Search name or model ID'), 'nothing');+ expect(screen.getByText('No model matches this search')).toBeTruthy();+ });++ it('falls back to a read-only list when the server predates the catalog', async () => {+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(undefined));+ const putAgentModels = vi.spyOn(modelsApi, 'putAgentModels');+ renderDialog();++ expect(await screen.findByText('legacy-a')).toBeTruthy();+ expect(screen.getByText('legacy-b')).toBeTruthy();+ expect(screen.getByText('This model engine build does not offer an editable model list yet. These are the models it currently exposes.')).toBeTruthy();+ expect(screen.getByText('2 models')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Add model' }).hasAttribute('disabled')).toBe(true);+ expect(screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')).toBe(true);+ expect(screen.queryByRole('button', { name: /^Reorder / })).toBeNull();+ expect(putAgentModels).not.toHaveBeenCalled();+ });++ it('offers a retry when the catalog cannot be read', async () => {+ const user = userEvent.setup();+ const read = vi.spyOn(modelsApi, 'getAgentSources')+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce(agent([model('alpha')]));+ renderDialog();++ expect(await screen.findByText("This backend's model list could not be read.")).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByRole('button', { name: 'Reorder alpha' })).toBeTruthy();+ expect(read).toHaveBeenCalledTimes(2);+ });++ it('keeps the draft, re-reads, and reports a save that did not land', async () => {+ const user = userEvent.setup();+ const catalog = [model('alpha'), model('beta')];+ const read = vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValue(+ new ApiCallError('invalid_request', 'modelHub.errors.backend_model_conflict', true),+ );+ const { onSaved, onObserved, onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ // The server named a cause the user can act on, so they read that cause —+ // never the raw key the server sent.+ expect(await screen.findByText('This list changed elsewhere while you were editing. Your changes were replayed onto the newer list; check it and save again.')).toBeTruthy();+ expect(screen.queryByText('modelHub.errors.backend_model_conflict')).toBeNull();+ expect(read).toHaveBeenCalledTimes(2);+ expect(onObserved).toHaveBeenCalledTimes(1);+ expect(onSaved).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ // The removal the user asked for survives the rebase onto the re-read list.+ expect(screen.getByText('1 model')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Reorder beta' })).toBeNull();+ });++ it('names the route that refused a removal the client could not see coming', async () => {+ const user = userEvent.setup();+ // The dialog blocks a removal whose route it knows about. This one was routed+ // elsewhere after the read, so only the server can refuse it.+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));+ vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValue(+ new ApiCallError('invalid_request', 'modelHub.errors.backend_model_in_route', true),+ );+ renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ expect(await screen.findByText('A model you removed still has a route. The list was re-read from the server; clear the route first, then remove it.')).toBeTruthy();+ });++ it('treats a lost answer as saved once the re-read shows the intent already applied', async () => {+ const user = userEvent.setup();+ const settled = agent([model('alpha')]);+ vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValueOnce(agent([model('alpha'), model('beta')]))+ .mockResolvedValueOnce(settled);+ vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValue(new Error('connection reset'));+ const { onSaved, onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(onSaved).toHaveBeenCalledWith(settled));+ expect(onClose).toHaveBeenCalled();+ });++ it('refuses to call a runtime-refresh failure a save, and still lets the user retry it', async () => {+ const user = userEvent.setup();+ // The server commits the catalog before it asks the backend to load it, so+ // `engine_down` leaves the rows on disk and out of use at once. The re-read+ // finds the intent applied — and that is exactly the answer that must not be+ // mistaken for success, because the route already said what it did.+ const settled = agent([model('alpha')]);+ vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValueOnce(agent([model('alpha'), model('beta')]))+ .mockResolvedValue(settled);+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(new ApiCallError('engine_down', 'modelHub.errors.engine_down', true))+ .mockResolvedValueOnce(settled);+ const { onSaved, onObserved, onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ expect(await screen.findByText('The list was stored, but this backend did not load it, so it is not in use yet. Save again once the backend is back.')).toBeTruthy();+ expect(screen.queryByText('The model list was not saved. It was re-read from the server; check it and try again.')).toBeNull();+ expect(onSaved).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ expect(onObserved).toHaveBeenCalledWith(settled);++ // The re-read left the draft agreeing with the server, so 「nothing to send」+ // must not read as 「nothing to do」: the write is what failed.+ const save = screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement;+ expect(save.disabled).toBe(false);+ await user.click(save);++ await waitFor(() => expect(onSaved).toHaveBeenCalledWith(settled));+ expect(onClose).toHaveBeenCalled();+ expect(write).toHaveBeenCalledTimes(2);+ });++ it('keeps a refused save named as refused when the server state happens to agree', async () => {+ const user = userEvent.setup();+ // Someone else removed beta too, so the re-read matches the draft exactly.+ // That coincidence says nothing about the write this server refused — only+ // the runtime-refresh failure can leave a list stored and unloaded.+ vi.spyOn(modelsApi, 'getAgentSources')+ .mockResolvedValueOnce(agent([model('alpha'), model('beta')]))+ .mockResolvedValue(agent([model('alpha')]));+ vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValue(+ new ApiCallError('invalid_request', 'modelHub.errors.backend_model_conflict', true),+ );+ const { onSaved, onClose } = renderDialog();++ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ expect(await screen.findByText('This list changed elsewhere while you were editing. Your changes were replayed onto the newer list; check it and save again.')).toBeTruthy();+ expect(screen.queryByText(/The list was stored/)).toBeNull();+ expect(onSaved).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('keeps a reorder-only draft open when an inconclusive save did not land', async () => {+ const user = userEvent.setup();+ const catalog = [model('alpha'), model('beta')];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog));+ vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValue(new Error('connection reset'));+ const { onSaved, onObserved, onClose } = renderDialog();++ const grip = await screen.findByRole('button', { name: 'Reorder alpha' });+ grip.focus();+ await user.keyboard('[Space][ArrowDown][Space]');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(onObserved).toHaveBeenCalledTimes(1));+ expect(screen.getByRole('status').textContent).toBeTruthy();+ expect(onSaved).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getAllByRole('button', { name: /^Reorder / }).map((button) => button.getAttribute('aria-label')))+ .toEqual(['Reorder beta', 'Reorder alpha']);+ });+});diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsxnew file mode 100644index 000000000..abc47c946--- /dev/null+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx@@ -0,0 +1,551 @@+// One model-catalog dialog for every backend.+//+// It replaces OpenCodeMenuDialog, which existed because OpenCode was the only+// backend whose menu the user could edit. That distinction was never a product+// idea — it was the shape of the old data. With one catalog per backend, one+// dialog edits it, and Claude Code's `Default` is not a special case in the UI+// but an ordinary row the server marked `locked`.+//+// It shows the catalog and nothing else: no Source, no Route, no fallback, no+// mapping. Which supplier serves a model is a Route question, and the Route rows+// on the Agent card are where it stays answered.+import * as React from 'react';+import { Reorder, useDragControls } from 'framer-motion';+import { GripVertical, Lock, LoaderCircle, Pencil, Plus, Search, Trash2 } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { cn } from '@/lib/utils';+import type { PendingWrite } from './asyncLifetime';+import {+ applyBackendCatalogIntent,+ backendCatalogIntent,+ backendCatalogIntentApplied,+ catalogModelIds,+ readBackendCatalogBaseline,+ sameCatalog,+ type BackendCatalogBaseline,+} from './backendCatalog';+import { BackendModelEditorDialog } from './BackendModelEditorDialog';+import { apiFailure, modelsApi } from './modelsApi';+import { movedOrder, sameIds } from './reorder';+import { catalogSaveFailureKey, catalogSaveLeftUnloaded } from './serverCopy';+import type { AgentBackend, AgentSupply, BackendModel } from './types';++type ReadState = 'loading' | 'ready' | 'error';++/** Same shape the Source order drawer announces with: the key alone would tell a+ * screen-reader user something moved without telling them where to. */+type AnnouncementKey = 'grabbed' | 'moved' | 'dropped' | 'grabCancelled';++type Announcement = {+ key: AnnouncementKey;+ model: string;+ position: number;+ count: number;+} | null;++const matchesQuery = (model: BackendModel, query: string, renderedLabel: string): boolean => {+ if (query === '') return true;+ const needle = query.toLowerCase();+ return model.id.toLowerCase().includes(needle)+ || renderedLabel.toLowerCase().includes(needle);+};++export const BackendModelCatalogDialog: React.FC<{+ open: boolean;+ backend: AgentBackend;+ onClose: () => void;+ onSaved: (echoed: AgentSupply) => void | Promise<void>;+ onObserved: (observed: AgentSupply) => void | Promise<void>;+ catalogWrite: PendingWrite;+}> = ({ open, backend, onClose, onSaved, onObserved, catalogWrite }) => {+ const { t } = useTranslation();+ const [baseline, setBaseline] = React.useState<BackendCatalogBaseline | null>(null);+ const baselineRef = React.useRef<BackendCatalogBaseline | null>(null);+ const [readState, setReadState] = React.useState<ReadState>('loading');+ const [draft, setDraft] = React.useState<BackendModel[]>([]);+ const draftRef = React.useRef<BackendModel[]>([]);+ const [query, setQuery] = React.useState('');+ const [saveFailedKey, setSaveFailedKey] = React.useState<string | null>(null);+ const [editing, setEditing] = React.useState<{ model: BackendModel | null } | null>(null);+ const [removeBlocked, setRemoveBlocked] = React.useState<string | null>(null);+ const [grabbedId, setGrabbedId] = React.useState<string | null>(null);+ const [announcement, setAnnouncement] = React.useState<Announcement>(null);+ const readAttempt = React.useRef(0);+ const grips = React.useRef(new Map<string, HTMLButtonElement>());+ const grabbedFrom = React.useRef<string[] | null>(null);++ const applyBaseline = React.useCallback((observed: BackendCatalogBaseline, models: BackendModel[]) => {+ baselineRef.current = observed;+ setBaseline(observed);+ draftRef.current = models;+ setDraft(models);+ setReadState('ready');+ }, []);++ const loadBaseline = React.useCallback((preserveDraft: boolean) => {+ const attempt = ++readAttempt.current;+ setReadState('loading');+ void (async () => {+ try {+ const observed = await readBackendCatalogBaseline(modelsApi, backend);+ if (attempt !== readAttempt.current) return;+ const server = observed.models ?? [];+ const previous = baselineRef.current?.models;+ const next = preserveDraft && previous+ ? applyBackendCatalogIntent(server, backendCatalogIntent(previous, draftRef.current))+ : server;+ applyBaseline(observed, next);+ } catch {+ if (attempt === readAttempt.current) setReadState('error');+ }+ })();+ }, [applyBaseline, backend]);++ React.useEffect(() => {+ if (open) loadBaseline(false);+ return () => { readAttempt.current += 1; };+ }, [loadBaseline, open]);++ const mutate = (next: BackendModel[]) => {+ draftRef.current = next;+ setDraft(next);+ setRemoveBlocked(null);+ setSaveFailedKey(null);+ };++ // The server sent no `catalog_models`, so this build is talking to a release+ // that predates the catalog. The legacy list is still worth showing — it is+ // what the backend really exposes — but the dialog will not offer to write a+ // baseline it assembled itself.+ const legacy = baseline !== null && baseline.models === null;+ const legacyIds = legacy && baseline ? catalogModelIds(baseline.agent) : [];+ const ready = readState === 'ready' && baseline !== null;+ const editable = ready && !legacy;+ const busy = catalogWrite.pending;+ const dirty = editable && !sameCatalog(baseline?.models ?? [], draft);+ /** A save that failed after the re-read rebased the draft leaves nothing to+ * send and everything still to do — a catalog the backend never loaded reads+ * as settled, so pressing Save again has to stay possible. */+ const retryable = editable && saveFailedKey !== null;+ const filtering = query.trim() !== '';+ const displayLabel = (model: BackendModel): string => (+ backend === 'claude' && model.id === 'default' && model.locked && !model.routeable+ ? t('settings.models.gateway.catalog.systemDefault') as string+ : model.display_name ?? model.id+ );+ const visible = draft.filter((model) => matchesQuery(model, query.trim(), displayLabel(model)));+ const movableIds = draft.filter((model) => !model.locked).map((model) => model.id);+ const takenIds = new Set(draft.map((model) => model.id));+ const effortSuggestions = [...new Set(draft.flatMap((model) => model.reasoning_efforts))];+ const routeLength = (modelId: string): number => baseline?.agent.routes?.[modelId]?.hops.length ?? 0;++ /** Reordering permutes which movable row sits in which movable slot; a locked+ * row keeps its absolute index, so the order sent never moves one. */+ const reorderMovable = (nextIds: string[]) => {+ const byId = new Map(draft.map((model) => [model.id, model]));+ let cursor = 0;+ mutate(draft.map((model) => (model.locked ? model : byId.get(nextIds[cursor++]) as BackendModel)));+ };++ const label = (modelId: string): string => {+ const model = draft.find((entry) => entry.id === modelId);+ return model ? displayLabel(model) : modelId;+ };++ const announce = (key: AnnouncementKey, modelId: string, order: string[] = movableIds) => {+ setAnnouncement({+ key,+ model: label(modelId),+ position: order.indexOf(modelId) + 1,+ count: order.length,+ });+ };++ const focusGrip = (modelId: string) => {+ requestAnimationFrame(() => grips.current.get(modelId)?.focus());+ };++ const cancelGrab = () => {+ const restored = grabbedFrom.current;+ grabbedFrom.current = null;+ const focused = grabbedId;+ setGrabbedId(null);+ if (restored && !sameIds(restored, movableIds)) reorderMovable(restored);+ if (focused) {+ announce('grabCancelled', focused, restored ?? movableIds);+ focusGrip(focused);+ }+ };++ const handleGripKey = (modelId: string, event: React.KeyboardEvent<HTMLButtonElement>) => {+ const index = movableIds.indexOf(modelId);+ if (index < 0) return;+ if (event.key === ' ') {+ event.preventDefault();+ if (grabbedId === modelId) {+ grabbedFrom.current = null;+ setGrabbedId(null);+ announce('dropped', modelId);+ } else {+ grabbedFrom.current = movableIds;+ setGrabbedId(modelId);+ announce('grabbed', modelId);+ }+ return;+ }+ if (event.key === 'Escape' && grabbedId === modelId) {+ event.preventDefault();+ event.stopPropagation();+ cancelGrab();+ return;+ }+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;+ event.preventDefault();+ const delta = event.key === 'ArrowUp' ? -1 : 1;+ if (grabbedId === modelId) {+ const next = movedOrder(movableIds, index, delta);+ if (sameIds(next, movableIds)) return;+ reorderMovable(next);+ announce('moved', modelId, next);+ focusGrip(modelId);+ return;+ }+ const neighbour = movableIds[index + delta];+ if (neighbour) focusGrip(neighbour);+ };++ const removeModel = (model: BackendModel) => {+ if (routeLength(model.id) > 0) {+ setRemoveBlocked(model.id);+ return;+ }+ mutate(draft.filter((entry) => entry.id !== model.id));+ };++ const commitEdit = (model: BackendModel) => {+ const existing = draft.findIndex((entry) => entry.id === model.id);+ mutate(existing >= 0+ ? draft.map((entry, index) => (index === existing ? { ...model, locked: entry.locked, routeable: entry.routeable } : entry))+ : [...draft, model]);+ setEditing(null);+ };++ const save = () => {+ const base = baselineRef.current;+ // A pre-catalog server has no baseline to send, so there is nothing this+ // branch could honestly PUT.+ if (!base || base.models === null) return;+ const baselineModels = base.models;+ const requested = draftRef.current;+ const intent = backendCatalogIntent(baselineModels, requested);+ setSaveFailedKey(null);+ void catalogWrite.track(async () => {+ let echoed: AgentSupply;+ try {+ echoed = await modelsApi.putAgentModels(backend, { baseline: baselineModels, models: requested });+ } catch (error) {+ const failure = apiFailure(error);+ // A route that named its failure has decided what it did, and for this+ // endpoint 「decided」 can still mean 「wrote」: the server commits the+ // catalog and only then asks the backend to load it, so `engine_down`+ // names rows that reached the disk and never reached the runtime. That+ // is a failed save with a persisted list behind it, and no re-read can+ // turn it into a success. Only an answer this client never got to read+ // leaves the outcome genuinely unknown — and only that may be settled by+ // reading the server's own catalog back.+ const decided = failure?.serverNamed === true;+ const unloaded = decided && catalogSaveLeftUnloaded(failure?.code, failure?.detail);+ const reason = decided+ ? catalogSaveFailureKey(failure?.detail)+ : 'settings.models.gateway.catalog.saveFailed';+ try {+ const observed = await readBackendCatalogBaseline(modelsApi, backend);+ const current = observed.models;+ const landed = current !== null && backendCatalogIntentApplied(current, intent);+ if (current && landed && !decided) {+ applyBaseline(observed, current);+ await Promise.resolve(onSaved(observed.agent)).catch(() => {});+ onClose();+ return;+ }+ applyBaseline(observed, current ? applyBackendCatalogIntent(current, intent) : []);+ await Promise.resolve(onObserved(observed.agent)).catch(() => {});+ // Stored and out of use at the same time, and only for the code that+ // can leave a list that way: a validation or conflict refusal keeps+ // its own sentence even when the re-read happens to agree with the+ // draft, because that write never landed at all.+ setSaveFailedKey(landed && unloaded ? 'settings.models.gateway.catalog.saveNotApplied' : reason);+ return;+ } catch {+ setReadState('error');+ }+ setSaveFailedKey(reason);+ return;+ }+ await Promise.resolve(onSaved(echoed)).catch(() => {});+ onClose();+ });+ };++ const rowActions = (model: BackendModel) => (+ <div className="flex shrink-0 items-center gap-1.5">+ <button+ type="button"+ className="model-hub-catalog-action"+ aria-label={t('settings.models.gateway.catalog.edit', { model: model.display_name ?? model.id }) as string}+ disabled={busy}+ onClick={() => setEditing({ model })}+ >+ <Pencil className="size-[15px]" aria-hidden="true" />+ </button>+ <button+ type="button"+ className="model-hub-catalog-action model-hub-catalog-action--danger"+ aria-label={t('settings.models.gateway.catalog.remove', { model: model.display_name ?? model.id }) as string}+ disabled={busy}+ onClick={() => removeModel(model)}+ >+ <Trash2 className="size-[15px]" aria-hidden="true" />+ </button>+ </div>+ );++ const rowBody = (model: BackendModel) => {+ const renderedLabel = displayLabel(model);+ return (+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="model-hub-catalog-name truncate">{renderedLabel}</span>+ {renderedLabel !== model.id && <span className="model-hub-catalog-id truncate font-mono">{model.id}</span>}+ </span>+ );+ };++ const blockedNote = (model: BackendModel) => (+ removeBlocked === model.id+ ? <p className="model-hub-catalog-blocked" role="alert">{t('settings.models.gateway.catalog.removeBlocked')}</p>+ : null+ );++ return (+ <>+ <Dialog+ open={open}+ onOpenChange={(next) => { if (!next && !busy) onClose(); }}+ >+ <DialogContent+ mobileSheetHeight="tall"+ closeLabel={t('settings.models.gateway.catalog.cancel') as string}+ className="model-hub-catalog-dialog flex h-[min(642px,calc(100dvh-32px))] w-[min(680px,calc(100vw-32px))] max-w-[680px] flex-col gap-0 overflow-hidden rounded-[14px] border-border-strong bg-surface p-0 shadow-[var(--model-hub-dialog-shadow)] max-md:w-full max-md:max-w-none max-md:rounded-t-2xl max-md:p-0 max-md:pt-2"+ onEscapeKeyDown={(event) => { if (busy || grabbedId) event.preventDefault(); }}+ onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}+ >+ <DialogHeader className="model-hub-catalog-head shrink-0 justify-center border-b border-border">+ <DialogTitle className="model-hub-catalog-title">+ {t('settings.models.gateway.catalog.title', { backend: t(`settings.models.backends.${backend}`) })}+ </DialogTitle>+ <DialogDescription className="sr-only">{t('settings.models.gateway.catalog.description')}</DialogDescription>+ </DialogHeader>++ <div className="model-hub-catalog-body flex min-h-0 flex-1 flex-col">+ <div className="flex min-w-0 shrink-0 flex-col gap-2 sm:flex-row sm:items-center">+ <div className="model-hub-catalog-control model-hub-catalog-search flex min-w-0 flex-1 items-center gap-2">+ <Search className="size-4 shrink-0 text-muted" aria-hidden="true" />+ <Input+ variant="bare"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t('settings.models.gateway.catalog.search') as string}+ aria-label={t('settings.models.gateway.catalog.search') as string}+ className="min-w-0 flex-1 text-[12.5px]"+ disabled={!editable || busy}+ />+ </div>+ <Button+ type="button"+ variant="brand"+ className="model-hub-catalog-control shrink-0 rounded-md px-4 text-[12.5px] font-semibold"+ disabled={!editable || busy}+ onClick={() => setEditing({ model: null })}+ >+ <Plus aria-hidden="true" />+ {t('settings.models.gateway.catalog.add')}+ </Button>+ </div>++ {ready && (draft.length > 0 || legacyIds.length > 0) && (+ <div className="model-hub-catalog-columns flex shrink-0 items-center justify-between">+ <span>{t('settings.models.gateway.catalog.columnModel')}</span>+ <span>{legacy ? t('settings.models.gateway.catalog.columnState') : t('settings.models.gateway.catalog.columnActions')}</span>+ </div>+ )}++ <div className="min-h-0 flex-1 overflow-y-auto">+ {!ready ? (+ <div className="flex flex-col items-center gap-3 px-4 py-12 text-center text-[12.5px] text-muted">+ {readState === 'loading' ? (+ <LoaderCircle className="size-5 animate-spin" aria-hidden="true" />+ ) : (+ <>+ <p>{t('settings.models.gateway.catalog.baselineUnavailable')}</p>+ <Button type="button" variant="outline" size="sm" onClick={() => loadBaseline(true)}>+ {t('settings.models.gateway.retry')}+ </Button>+ </>+ )}+ </div>+ ) : legacy ? (+ <div className="flex flex-col gap-2">+ <p className="model-hub-catalog-legacy">{t('settings.models.gateway.catalog.legacy')}</p>+ {legacyIds.map((modelId) => (+ <div key={modelId} className="model-hub-catalog-row model-hub-catalog-row--static flex min-w-0 items-center gap-3">+ <span className="model-hub-catalog-name min-w-0 flex-1 truncate font-mono">{modelId}</span>+ </div>+ ))}+ </div>+ ) : visible.length === 0 ? (+ <p className="px-1 py-10 text-center text-[12.5px] text-muted">+ {t(filtering ? 'settings.models.gateway.catalog.noMatch' : 'settings.models.gateway.catalog.empty')}+ </p>+ ) : (+ <Reorder.Group+ axis="y"+ as="ul"+ values={movableIds}+ onReorder={reorderMovable}+ className="flex list-none flex-col gap-[var(--model-hub-catalog-row-gap)] p-0"+ >+ {visible.map((model) => (+ model.locked+ ? (+ <li key={model.id} className="model-hub-catalog-row model-hub-catalog-row--locked flex min-w-0 flex-col justify-center">+ <div className="flex min-w-0 items-center gap-3">+ <Lock className="model-hub-catalog-grip-icon shrink-0" aria-hidden="true" />+ {rowBody(model)}+ <span className="model-hub-pill model-hub-fill-0a shrink-0 border border-border text-muted">+ {t('settings.models.gateway.catalog.lockedBadge')}+ </span>+ </div>+ </li>+ )+ : (+ <CatalogRow+ key={model.id}+ model={model}+ grabbed={grabbedId === model.id}+ draggable={!filtering && !busy}+ registerGrip={(node) => {+ if (node) grips.current.set(model.id, node);+ else grips.current.delete(model.id);+ }}+ onGripKeyDown={(event) => handleGripKey(model.id, event)}+ body={rowBody(model)}+ actions={rowActions(model)}+ note={blockedNote(model)}+ />+ )+ ))}+ </Reorder.Group>+ )}+ </div>+ <p aria-live="polite" className="sr-only">+ {announcement ? t(`settings.models.gateway.catalog.${announcement.key}`, announcement) : ''}+ </p>+ </div>++ <DialogFooter className="model-hub-catalog-foot shrink-0 items-center border-t border-border sm:justify-between">+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="model-hub-catalog-count">+ {t('settings.models.gateway.modelCount', { count: legacy ? legacyIds.length : draft.length })}+ </span>+ {saveFailedKey && (+ <span className="model-hub-catalog-blocked" role="status">{t(saveFailedKey)}</span>+ )}+ </div>+ <div className="flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row">+ <Button+ type="button"+ variant="outline"+ className="model-hub-catalog-control rounded-md px-5 text-[12.5px] font-semibold"+ onClick={onClose}+ disabled={busy}+ >+ {t('settings.models.gateway.catalog.cancel')}+ </Button>+ <Button+ type="button"+ variant="brand"+ className="model-hub-catalog-control rounded-md px-5 text-[12.5px] font-semibold"+ onClick={save}+ disabled={!editable || (!dirty && !retryable) || busy}+ >+ {busy && <LoaderCircle className="animate-spin" aria-hidden="true" />}+ {t(busy ? 'settings.models.gateway.catalog.saving' : 'settings.models.gateway.catalog.save')}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {editing && (+ <BackendModelEditorDialog+ open+ backend={backend}+ model={editing.model}+ takenIds={takenIds}+ effortSuggestions={effortSuggestions}+ onCancel={() => setEditing(null)}+ onCommit={commitEdit}+ />+ )}+ </>+ );+};++const CatalogRow: React.FC<{+ model: BackendModel;+ grabbed: boolean;+ draggable: boolean;+ registerGrip: (node: HTMLButtonElement | null) => void;+ onGripKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) => void;+ body: React.ReactNode;+ actions: React.ReactNode;+ note: React.ReactNode;+}> = ({ model, grabbed, draggable, registerGrip, onGripKeyDown, body, actions, note }) => {+ const { t } = useTranslation();+ const controls = useDragControls();+ return (+ <Reorder.Item+ value={model.id}+ dragListener={false}+ dragControls={controls}+ className="model-hub-catalog-row flex min-w-0 list-none flex-col justify-center"+ >+ <div className="flex min-w-0 items-center gap-3">+ <button+ ref={registerGrip}+ type="button"+ aria-label={t('settings.models.gateway.catalog.reorder', { model: model.display_name ?? model.id }) as string}+ aria-grabbed={grabbed}+ disabled={!draggable}+ onPointerDown={(event) => { if (draggable) controls.start(event); }}+ onKeyDown={onGripKeyDown}+ className={cn(+ 'model-hub-catalog-grip cursor-grab active:cursor-grabbing disabled:cursor-not-allowed',+ grabbed && 'is-grabbed',+ )}+ >+ <GripVertical className="model-hub-catalog-grip-icon" aria-hidden="true" />+ </button>+ {body}+ {actions}+ </div>+ {note}+ </Reorder.Item>+ );+};++export default BackendModelCatalogDialog;diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsxnew file mode 100644index 000000000..ba41b326f--- /dev/null+++ b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx@@ -0,0 +1,544 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import i18n from '@/i18n';+import { BackendModelEditorDialog } from './BackendModelEditorDialog';+import { blankBackendModel } from './backendCatalog';+import { ApiCallError, modelsApi } from './modelsApi';+import type { BackendModel, ModelsDevMatch } from './types';++const match = (overrides: Partial<ModelsDevMatch> = {}): ModelsDevMatch => ({+ provider_id: 'anthropic',+ provider_name: 'Anthropic',+ model_id: 'claude-sonnet-4-5',+ models_dev_id: 'anthropic/claude-sonnet-4-5',+ display_name: 'Claude Sonnet 4.5',+ context_window: 200000,+ max_output_tokens: 64000,+ input_modalities: ['text', 'image'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: true,+ reasoning_efforts: ['low', 'high'],+ ...overrides,+});++const renderEditor = (overrides: Partial<React.ComponentProps<typeof BackendModelEditorDialog>> = {}) => {+ const onCommit = vi.fn();+ const onCancel = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <BackendModelEditorDialog+ open+ backend="claude"+ model={null}+ takenIds={new Set()}+ effortSuggestions={[]}+ onCancel={onCancel}+ onCommit={onCommit}+ {...overrides}+ />+ </I18nextProvider>,+ );+ return { onCommit, onCancel };+};++/** Input and output share a modality vocabulary, so a chip is only unambiguous+ * inside its own group. */+const modalities = (direction: 'Input' | 'Output') =>+ within(screen.getByRole('group', { name: `${direction} modalities` }));++/** Both capabilities answer Yes/No/Not set, so an option only names one of them+ * from inside its own group. */+const capability = (name: 'Tool calling' | 'Reasoning') =>+ within(screen.getByRole('radiogroup', { name }));++const answered = (name: 'Tool calling' | 'Reasoning'): string | null =>+ capability(name).getAllByRole('radio').find((radio) => radio.getAttribute('aria-checked') === 'true')?.textContent+ ?? null;++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('BackendModelEditorDialog', () => {+ it('refuses an empty, overlong, or already-taken model ID', async () => {+ const user = userEvent.setup();+ const { onCommit } = renderEditor({ takenIds: new Set(['taken']) });++ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(screen.getByText('Enter a backend model ID.')).toBeTruthy();+ expect(onCommit).not.toHaveBeenCalled();++ const id = screen.getByLabelText('Backend model ID');+ await user.type(id, 'taken');+ expect(screen.getByText('This list already has a model with this ID.')).toBeTruthy();++ await user.clear(id);+ await user.type(id, 'kept');+ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(onCommit).toHaveBeenCalledTimes(1);+ expect(onCommit.mock.calls[0][0]).toMatchObject({+ id: 'kept',+ origin: 'manual',+ models_dev_id: null,+ display_name: null,+ });+ });++ it('caps the ID at the contract length while it can still be typed', async () => {+ const user = userEvent.setup();+ const { onCommit } = renderEditor();++ const id = screen.getByLabelText('Backend model ID');+ expect(id.getAttribute('maxlength')).toBe('256');+ // The browser stops at the cap, so reaching the error needs a value the+ // field never lets a keystroke produce.+ fireEvent.change(id, { target: { value: 'x'.repeat(257) } });+ await user.click(screen.getByRole('button', { name: 'Add model' }));++ expect(onCommit).not.toHaveBeenCalled();+ expect(screen.getByText('A model ID may be at most 256 characters.')).toBeTruthy();+ });++ it('edits a persisted ID that predates the length cap', async () => {+ // The id is read-only here and the backend still accepts the metadata, so a+ // ceiling on a field nobody can shorten only locks the row out of every+ // edit it is allowed to make.+ const user = userEvent.setup();+ const legacy: BackendModel = {+ ...blankBackendModel(),+ id: `internal/${'x'.repeat(300)}`,+ origin: 'builtin',+ context_window: 100000,+ };+ const { onCommit } = renderEditor({ model: legacy, takenIds: new Set([legacy.id]) });++ const id = screen.getByLabelText('Backend model ID') as HTMLInputElement;+ // Shown in full, not clipped: the cap belongs to what can be typed.+ expect(id.value).toBe(legacy.id);+ expect(id.getAttribute('maxlength')).toBeNull();+ expect(screen.queryByText('A model ID may be at most 256 characters.')).toBeNull();++ await user.type(screen.getByLabelText('Display name'), 'Legacy house model');+ await user.clear(screen.getByLabelText('Maximum output'));+ await user.type(screen.getByLabelText('Maximum output'), '8192');+ await user.click(screen.getByRole('button', { name: 'Save model' }));++ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ id: legacy.id,+ display_name: 'Legacy house model',+ max_output_tokens: 8192,+ context_window: 100000,+ }));+ });++ it('keeps the ID read-only in edit mode and commits the edited row', async () => {+ const user = userEvent.setup();+ const existing: BackendModel = {+ ...blankBackendModel(),+ id: 'anthropic/claude-opus-4',+ display_name: 'Claude Opus 4',+ origin: 'models_dev',+ models_dev_id: 'anthropic/claude-opus-4',+ context_window: 200000,+ max_output_tokens: 32000,+ };+ const { onCommit } = renderEditor({ model: existing, takenIds: new Set([existing.id]) });++ expect(screen.getByRole('heading', { name: 'Edit model' })).toBeTruthy();+ const id = screen.getByLabelText('Backend model ID') as HTMLInputElement;+ expect(id.readOnly).toBe(true);+ await user.type(id, 'suffix');+ expect(id.value).toBe('anthropic/claude-opus-4');++ // The grouped form is what the field shows, so the grouped form is what it+ // must accept back.+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('200,000');+ const output = screen.getByLabelText('Maximum output');+ await user.clear(output);+ await user.type(output, '128,000');+ await user.click(screen.getByRole('button', { name: 'Save model' }));++ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ id: 'anthropic/claude-opus-4',+ max_output_tokens: 128000,+ context_window: 200000,+ }));+ });++ it('refuses a token count that is not a whole number', async () => {+ const user = userEvent.setup();+ const { onCommit } = renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'm');+ await user.type(screen.getByLabelText('Context window'), '20k');+ await user.click(screen.getByRole('button', { name: 'Add model' }));++ expect(screen.getByLabelText('Context window').getAttribute('aria-invalid')).toBe('true');+ expect(onCommit).not.toHaveBeenCalled();+ });++ it('fills every field from a single models.dev match and leaves them editable', async () => {+ const user = userEvent.setup();+ const search = vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([match()]);+ const { onCommit } = renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'anthropic/claude-sonnet-4-5-20250929');+ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));++ await screen.findByText('models.dev · anthropic/claude-sonnet-4-5');+ expect(search).toHaveBeenCalledWith('anthropic/claude-sonnet-4-5-20250929');+ expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('Claude Sonnet 4.5');+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('200,000');+ expect(modalities('Input').getByRole('checkbox', { name: 'Image' }).getAttribute('aria-checked')).toBe('true');+ expect(answered('Reasoning')).toBe('Yes');++ // Every filled field stays the user's: the fill is a starting point.+ await user.click(modalities('Input').getByRole('checkbox', { name: 'Image' }));+ await user.clear(screen.getByLabelText('Maximum output'));+ await user.type(screen.getByLabelText('Maximum output'), '8000');+ await user.click(screen.getByRole('checkbox', { name: 'low' }));+ await user.click(screen.getByRole('button', { name: 'Add model' }));++ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ // A fill never renames the row the user typed.+ id: 'anthropic/claude-sonnet-4-5-20250929',+ models_dev_id: 'anthropic/claude-sonnet-4-5',+ display_name: 'Claude Sonnet 4.5',+ origin: 'models_dev',+ input_modalities: ['text'],+ max_output_tokens: 8000,+ reasoning_efforts: ['high'],+ }));+ });++ it('offers a selectable list when models.dev returns several matches', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([+ match(),+ match({ provider_id: 'bedrock', provider_name: 'Amazon Bedrock', models_dev_id: 'bedrock/claude-sonnet-4-5', display_name: 'Sonnet 4.5 (Bedrock)', context_window: 180000 }),+ ]);+ renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'claude-sonnet-4-5');+ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));++ const options = await screen.findAllByRole('option');+ expect(options).toHaveLength(2);+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('');++ await user.click(options[1]);++ expect(screen.queryByRole('option')).toBeNull();+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('180,000');+ expect(screen.getByText('models.dev · bedrock/claude-sonnet-4-5')).toBeTruthy();+ });++ it('reports an empty or unreachable models.dev without touching the draft', async () => {+ const user = userEvent.setup();+ const search = vi.spyOn(modelsApi, 'searchModelsDev')+ .mockResolvedValueOnce([])+ .mockRejectedValueOnce(new Error('offline'));+ renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'private/model');+ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));+ expect(await screen.findByText('models.dev has no model matching this ID.')).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));+ expect(await screen.findByText('models.dev could not be reached.')).toBeTruthy();+ expect(search).toHaveBeenCalledTimes(2);+ expect((screen.getByLabelText('Backend model ID') as HTMLInputElement).value).toBe('private/model');+ });++ it('names an upstream models.dev outage as a cause of its own', async () => {+ // The server separates 「the catalog is down」 from every other fill failure,+ // and it is the one where retrying is the wrong advice: the fields it would+ // have filled are all typeable by hand.+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'searchModelsDev').mockRejectedValue(+ new ApiCallError('upstream_unavailable', 'modelHub.errors.models_dev_unavailable', true),+ );+ renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'openai/gpt-5');+ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));+ expect(+ await screen.findByText('The models.dev catalog is unavailable right now. You can fill these fields in by hand.'),+ ).toBeTruthy();+ expect(screen.queryByText('models.dev could not be reached.')).toBeNull();+ expect(screen.queryByText('modelHub.errors.models_dev_unavailable')).toBeNull();+ });++ it('drops a models.dev answer once the ID that asked for it is gone', async () => {+ // The answer describes the id that was typed when 填充 was pressed. Landing+ // it on the id that replaced it would file one model's context window,+ // modalities and efforts under another model's name.+ const user = userEvent.setup();+ let settle: (matches: ModelsDevMatch[]) => void = () => {};+ vi.spyOn(modelsApi, 'searchModelsDev').mockImplementation(+ () => new Promise<ModelsDevMatch[]>((resolve) => { settle = resolve; }),+ );+ const { onCommit } = renderEditor();++ const id = screen.getByLabelText('Backend model ID');+ await user.type(id, 'anthropic/claude-sonnet-4-5');+ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));+ await user.clear(id);+ await user.type(id, 'openai/gpt-5');++ await act(async () => { settle([match()]); });++ expect(screen.queryByText('models.dev · anthropic/claude-sonnet-4-5')).toBeNull();+ expect(screen.queryByRole('option')).toBeNull();+ expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('');+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('');+ // The retired request also releases the button, so the new id can be filled.+ expect((screen.getByRole('button', { name: 'Fill from models.dev' }) as HTMLButtonElement).disabled).toBe(false);++ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ id: 'openai/gpt-5',+ origin: 'manual',+ models_dev_id: null,+ display_name: null,+ context_window: null,+ reasoning_efforts: [],+ }));+ });++ it('retires filled metadata once the ID it describes is replaced', async () => {+ // The settled answer is the same hazard as the one in flight: a fill fetched+ // for one id must not end up saved under another.+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([match()]);+ const { onCommit } = renderEditor();++ const id = screen.getByLabelText('Backend model ID');+ await user.type(id, 'anthropic/claude-sonnet-4-5');+ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));+ await screen.findByText('models.dev · anthropic/claude-sonnet-4-5');++ await user.clear(id);+ await user.type(id, 'openai/gpt-5');++ expect(screen.queryByText('models.dev · anthropic/claude-sonnet-4-5')).toBeNull();+ expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('');+ expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('');+ expect((screen.getByLabelText('Maximum output') as HTMLInputElement).value).toBe('');+ expect(modalities('Input').getByRole('checkbox', { name: 'Image' }).getAttribute('aria-checked')).toBe('false');+ // Back to the blank row's own answers, not the filled model's.+ expect(answered('Reasoning')).toBe('No');+ expect(screen.queryByRole('checkbox', { name: 'high' })).toBeNull();++ await user.click(screen.getByRole('button', { name: 'Add model' }));+ // Nothing of the old model survives — not the provenance, not one field.+ expect(onCommit).toHaveBeenCalledWith({ ...blankBackendModel(), id: 'openai/gpt-5' });+ });++ it('keeps hand-typed metadata while the user corrects the ID', async () => {+ const user = userEvent.setup();+ const { onCommit } = renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'internal/hous');+ await user.type(screen.getByLabelText('Display name'), 'House model');+ await user.type(screen.getByLabelText('Context window'), '32000');+ await user.click(modalities('Input').getByRole('checkbox', { name: 'Image' }));+ // A row that owes models.dev nothing has nothing to retire: fixing a typo in+ // the id is not a decision to retype everything under it.+ await user.type(screen.getByLabelText('Backend model ID'), 'e');+ await user.click(screen.getByRole('button', { name: 'Add model' }));++ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ id: 'internal/house',+ origin: 'manual',+ display_name: 'House model',+ context_window: 32000,+ input_modalities: ['text', 'image'],+ }));+ });++ it('keeps a display name optional, trimmed, and null when the box is empty', async () => {+ const user = userEvent.setup();+ const unnamed: BackendModel = { ...blankBackendModel(), id: 'gpt-5-codex', context_window: 400000 };+ const { onCommit } = renderEditor({ model: unnamed, takenIds: new Set([unnamed.id]) });++ const name = screen.getByLabelText('Display name') as HTMLInputElement;+ expect(name.value).toBe('');++ // A row that arrived without a name still has none after a save it never+ // touched: an empty box is 「no name」, not an empty string the schema refuses.+ await user.click(screen.getByRole('button', { name: 'Save model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ id: 'gpt-5-codex', display_name: null }));++ onCommit.mockClear();+ await user.type(name, ' GPT-5 Codex ');+ await user.click(screen.getByRole('button', { name: 'Save model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ display_name: 'GPT-5 Codex' }));++ onCommit.mockClear();+ await user.clear(name);+ await user.click(screen.getByRole('button', { name: 'Save model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ display_name: null }));+ });++ it('sends a custom reasoning effort verbatim and keeps the list when reasoning is off', async () => {+ const user = userEvent.setup();+ const { onCommit } = renderEditor({ effortSuggestions: ['low'] });++ await user.type(screen.getByLabelText('Backend model ID'), 'm');+ await user.click(capability('Reasoning').getByRole('radio', { name: 'Yes' }));+ await user.click(screen.getByRole('checkbox', { name: 'low' }));+ await user.click(screen.getByRole('button', { name: 'Custom effort' }));+ await user.type(screen.getByLabelText('Custom effort'), 'XHIGH-2{Enter}');++ expect(screen.getByRole('checkbox', { name: 'XHIGH-2' }).getAttribute('aria-checked')).toBe('true');+ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ supports_reasoning: true,+ reasoning_efforts: ['low', 'XHIGH-2'],+ }));++ onCommit.mockClear();+ // 「No reasoning」 hides the efforts; it does not spend them. Dropping them+ // here would make the answer destructive — take it back and there would be+ // nothing left to restore.+ await user.click(capability('Reasoning').getByRole('radio', { name: 'No' }));+ expect(screen.queryByRole('checkbox', { name: 'XHIGH-2' })).toBeNull();+ await user.click(screen.getByRole('button', { name: 'Add model' }));+ await waitFor(() => expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ supports_reasoning: false,+ reasoning_efforts: ['low', 'XHIGH-2'],+ })));+ });++ it('keeps an unstated capability unstated through an unrelated edit', async () => {+ const user = userEvent.setup();+ // How every shipped builtin row arrives: the server states no capability, and+ // null is not false — it means the backend projection omits the flag.+ const shipped: BackendModel = {+ ...blankBackendModel(),+ id: 'gpt-5',+ origin: 'builtin',+ supports_tools: null,+ supports_reasoning: null,+ reasoning_efforts: ['minimal', 'high'],+ };+ const { onCommit } = renderEditor({ model: shipped, takenIds: new Set([shipped.id]) });++ expect(answered('Tool calling')).toBe('Not set');+ expect(answered('Reasoning')).toBe('Not set');+ // An unstated capability still owns its efforts, so they stay visible.+ expect(screen.getByRole('checkbox', { name: 'minimal' }).getAttribute('aria-checked')).toBe('true');++ await user.clear(screen.getByLabelText('Maximum output'));+ await user.type(screen.getByLabelText('Maximum output'), '4096');+ await user.click(screen.getByRole('button', { name: 'Save model' }));++ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ max_output_tokens: 4096,+ supports_tools: null,+ supports_reasoning: null,+ reasoning_efforts: ['minimal', 'high'],+ }));+ });++ it('states a capability once the user answers it', async () => {+ const user = userEvent.setup();+ const shipped: BackendModel = {+ ...blankBackendModel(),+ id: 'gpt-5',+ supports_tools: null,+ supports_reasoning: null,+ reasoning_efforts: ['high'],+ };+ const { onCommit } = renderEditor({ model: shipped, takenIds: new Set([shipped.id]) });++ await user.click(capability('Tool calling').getByRole('radio', { name: 'Yes' }));+ expect(answered('Tool calling')).toBe('Yes');+ expect(answered('Reasoning')).toBe('Not set');+ // Saying "no reasoning" takes the efforts off the surface and leaves them on+ // the row: what a `false` model projects is the backend's question.+ await user.click(capability('Reasoning').getByRole('radio', { name: 'No' }));+ expect(screen.queryByRole('checkbox', { name: 'high' })).toBeNull();+ await user.click(screen.getByRole('button', { name: 'Save model' }));++ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ supports_tools: true,+ supports_reasoning: false,+ reasoning_efforts: ['high'],+ }));+ });++ it('carries a capability models.dev does not state through the fill', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'searchModelsDev')+ .mockResolvedValue([match({ supports_tools: null, supports_reasoning: null, reasoning_efforts: [] })]);+ const { onCommit } = renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'anthropic/claude-sonnet-4-5');+ await user.click(screen.getByRole('button', { name: 'Fill from models.dev' }));+ await screen.findByText('models.dev · anthropic/claude-sonnet-4-5');++ expect(answered('Tool calling')).toBe('Not set');+ expect(answered('Reasoning')).toBe('Not set');+ await user.click(screen.getByRole('button', { name: 'Add model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ supports_tools: null,+ supports_reasoning: null,+ }));+ });++ it('takes a stated capability back to not set', async () => {+ const user = userEvent.setup();+ // A capability is three-valued, and the third value is not a starting state+ // the user can only spend: a row saved as 「no reasoning」 by mistake has to+ // be able to stop claiming anything at all.+ const stated: BackendModel = {+ ...blankBackendModel(),+ id: 'gpt-5',+ supports_tools: true,+ supports_reasoning: false,+ reasoning_efforts: ['high'],+ };+ const { onCommit } = renderEditor({ model: stated, takenIds: new Set([stated.id]) });++ expect(answered('Tool calling')).toBe('Yes');+ expect(answered('Reasoning')).toBe('No');+ // 「No reasoning」 is the one answer that hides the efforts, so withdrawing it+ // brings them back — the row kept them the whole time.+ expect(screen.queryByRole('checkbox', { name: 'high' })).toBeNull();++ await user.click(capability('Tool calling').getByRole('radio', { name: 'Not set' }));+ await user.click(capability('Reasoning').getByRole('radio', { name: 'Not set' }));+ expect(screen.getByRole('checkbox', { name: 'high' }).getAttribute('aria-checked')).toBe('true');++ await user.click(screen.getByRole('button', { name: 'Save model' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ supports_tools: null,+ supports_reasoning: null,+ reasoning_efforts: ['high'],+ }));+ });++ it('cancels without committing anything', async () => {+ const user = userEvent.setup();+ const { onCancel, onCommit } = renderEditor();++ await user.type(screen.getByLabelText('Backend model ID'), 'abandoned');+ // The header close and the footer button are the same decision, so both+ // discard the draft rather than one of them saving it.+ const cancels = screen.getAllByRole('button', { name: 'Cancel' });+ expect(cancels).toHaveLength(2);+ await user.click(cancels[0]);+ await user.click(cancels[1]);++ expect(onCancel).toHaveBeenCalledTimes(2);+ expect(onCommit).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.tsxnew file mode 100644index 000000000..0d4ba72b9--- /dev/null+++ b/ui/src/components/settings/models/BackendModelEditorDialog.tsx@@ -0,0 +1,569 @@+// One editor for every backend catalog row, add and edit alike.+//+// It writes nothing. The row it commits goes back into the catalog dialog's+// draft, so the whole list still settles through one `PUT .../models` with one+// baseline — an editor that saved on its own would make every row its own+// mutation and leave no way to cancel a list still being arranged.+//+// models.dev is a metadata source here, not an authority: it fills fields the+// user can then change, and it never touches the backend model id, which is the+// routing identity the user typed.+import * as React from 'react';+import { Check, Database, DownloadCloud, LoaderCircle, Plus } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Input } from '@/components/ui/input';+import { SegmentedRadio } from '@/components/ui/segmented';+import { cn } from '@/lib/utils';+import { applyModelsDevMatch, blankBackendModel } from './backendCatalog';+import { Field } from './dialogFields';+import { apiFailure, modelsApi } from './modelsApi';+import { modelsDevFillFailureKey } from './serverCopy';+import {+ BACKEND_MODEL_EFFORT_MAX_LENGTH,+ BACKEND_MODEL_ID_MAX_LENGTH,+ BACKEND_MODEL_INPUT_MODALITIES,+ BACKEND_MODEL_OUTPUT_MODALITIES,+ type AgentBackend,+ type BackendModel,+ type BackendModelInputModality,+ type BackendModelOutputModality,+ type ModelsDevMatch,+} from './types';++type FillState = 'idle' | 'loading' | 'empty' | 'error';++/** Digits only. A pasted 「163,840」 is the same number as 「163840」, and the+ * field renders the grouped form itself, so refusing the separator would refuse+ * the value the field just showed. */+const parseTokens = (text: string): { ok: boolean; value: number | null } => {+ const trimmed = text.replace(/[\s,]/g, '');+ if (trimmed === '') return { ok: true, value: null };+ if (!/^\d+$/.test(trimmed)) return { ok: false, value: null };+ const value = Number(trimmed);+ return Number.isSafeInteger(value) && value >= 1 ? { ok: true, value } : { ok: false, value: null };+};++const groupTokens = (value: number | null): string => (value === null ? '' : value.toLocaleString('en-US'));++const ChipButton: React.FC<{+ on: boolean;+ disabled?: boolean;+ onClick: () => void;+ children: React.ReactNode;+}> = ({ on, disabled, onClick, children }) => (+ <button+ type="button"+ role="checkbox"+ aria-checked={on}+ disabled={disabled}+ onClick={onClick}+ className={cn('model-hub-model-chip', on && 'is-on')}+ >+ {on && <Check className="size-[13px] shrink-0" aria-hidden="true" />}+ {children}+ </button>+);++const SectionLabel: React.FC<{ children: React.ReactNode }> = ({ children }) => (+ <p className="model-hub-model-section-label">{children}</p>+);++/**+ * A capability is a three-valued fact, and `null` — 「nobody has said」 — is the+ * value every shipped row arrives with, because the backend projection simply+ * omits the flag.+ *+ * A switch can only spend that value: the first touch turns an unanswered+ * question into a stated `false`, and nothing on the surface gives it back. So+ * all three states are options here, and 「Not set」 is an answer the user can+ * return to as easily as they left it.+ */+const CAPABILITY_CHOICES = ['unset', 'no', 'yes'] as const;+type CapabilityChoice = (typeof CAPABILITY_CHOICES)[number];++const CapabilityField: React.FC<{+ label: string;+ value: boolean | null;+ onChange: (next: boolean | null) => void;+}> = ({ label, value, onChange }) => {+ const { t } = useTranslation();+ return (+ <div className="flex min-w-0 flex-col gap-1.5">+ <p className="model-hub-model-field-label">{label}</p>+ <SegmentedRadio+ value={value === null ? 'unset' : value ? 'yes' : 'no'}+ onChange={(next: CapabilityChoice) => onChange(next === 'unset' ? null : next === 'yes')}+ options={CAPABILITY_CHOICES.map((id) => ({+ id,+ label: t(`settings.models.gateway.modelEditor.capability.${id}`) as string,+ }))}+ ariaLabel={label}+ />+ </div>+ );+};++export const BackendModelEditorDialog: React.FC<{+ open: boolean;+ backend: AgentBackend;+ /** null opens the editor in add mode. */+ model: BackendModel | null;+ /** Ids the draft catalog already holds; a second row may not claim one. */+ takenIds: ReadonlySet<string>;+ /** Effort values this backend's other rows already use. Suggestions, never a+ * vocabulary — every effort is sent verbatim and any string is equally valid. */+ effortSuggestions: readonly string[];+ onCancel: () => void;+ onCommit: (model: BackendModel) => void;+}> = ({ open, backend, model, takenIds, effortSuggestions, onCancel, onCommit }) => {+ const { t } = useTranslation();+ const creating = model === null;+ const [draft, setDraft] = React.useState<BackendModel>(() => model ?? blankBackendModel());+ /** Held as text, like the token fields: the schema's name is a non-empty+ * string or null, and only `commit` gets to decide which an empty box is. */+ const [nameText, setNameText] = React.useState('');+ const [contextText, setContextText] = React.useState('');+ const [outputText, setOutputText] = React.useState('');+ const [fillState, setFillState] = React.useState<FillState>('idle');+ /** Which sentence `fillState === 'error'` shows, resolved while the server's+ * own answer is still in hand. */+ const [fillFailedKey, setFillFailedKey] = React.useState('settings.models.gateway.modelEditor.fillFailed');+ const [matches, setMatches] = React.useState<ModelsDevMatch[]>([]);+ const [matchesOpen, setMatchesOpen] = React.useState(false);+ const [customOpen, setCustomOpen] = React.useState(false);+ const [customEffort, setCustomEffort] = React.useState('');+ const [submitted, setSubmitted] = React.useState(false);+ const fillAttempt = React.useRef(0);++ const seed = React.useCallback((next: BackendModel) => {+ setDraft(next);+ setNameText(next.display_name ?? '');+ setContextText(groupTokens(next.context_window));+ setOutputText(groupTokens(next.max_output_tokens));+ setFillState('idle');+ setMatches([]);+ setMatchesOpen(false);+ setCustomOpen(false);+ setCustomEffort('');+ setSubmitted(false);+ }, []);++ React.useEffect(() => {+ if (open) seed(model ?? blankBackendModel());+ else fillAttempt.current += 1;+ }, [model, open, seed]);++ const context = parseTokens(contextText);+ const output = parseTokens(outputText);+ const trimmedId = draft.id.trim();+ // Every id rule is a rule about what the user may type, and only add mode lets+ // them type it — an edit shows the id read-only. Judging a value the dialog+ // itself locks is what made a persisted row whose id predates the length+ // ceiling uneditable: its metadata is the part the backend still accepts, yet+ // Save refused it and pointed at the one field nobody could shorten.+ const idError = !creating+ ? null+ : trimmedId === ''+ ? 'required'+ : trimmedId.length > BACKEND_MODEL_ID_MAX_LENGTH+ ? 'tooLong'+ : takenIds.has(trimmedId)+ ? 'duplicate'+ : null;+ const valid = idError === null && context.ok && output.ok;++ const patch = (next: Partial<BackendModel>) => setDraft((current) => ({ ...current, ...next }));++ const toggleInput = (value: BackendModelInputModality) => patch({+ input_modalities: draft.input_modalities.includes(value)+ ? draft.input_modalities.filter((entry) => entry !== value)+ : [...draft.input_modalities, value],+ });+ const toggleOutput = (value: BackendModelOutputModality) => patch({+ output_modalities: draft.output_modalities.includes(value)+ ? draft.output_modalities.filter((entry) => entry !== value)+ : [...draft.output_modalities, value],+ });+ const toggleEffort = (value: string) => patch({+ reasoning_efforts: draft.reasoning_efforts.includes(value)+ ? draft.reasoning_efforts.filter((entry) => entry !== value)+ : [...draft.reasoning_efforts, value],+ });++ const applyMatch = (match: ModelsDevMatch) => {+ // `applyModelsDevMatch` leaves `id` alone: a fill never renames the row, even+ // when the chosen match is published under a different id.+ setDraft((current) => applyModelsDevMatch(current, match, creating ? 'models_dev' : current.origin));+ setNameText(match.display_name ?? '');+ setContextText(groupTokens(match.context_window));+ setOutputText(groupTokens(match.max_output_tokens));+ setMatchesOpen(false);+ setFillState('idle');+ };++ /**+ * Retype the id, and every models.dev answer to the old one is retired: the+ * request still in flight, the match list it would open, and the metadata an+ * earlier fill already poured in.+ *+ * `models_dev_id` decides how far that goes, because it is the schema's own+ * record of where a row's metadata came from. A filled draft describes the id+ * that fetched it — keeping its context window, modalities or efforts would+ * save one model's facts under another model's name — so it goes back to+ * blank. A hand-typed draft owes models.dev nothing and keeps every field,+ * since correcting a typo in the id is not a decision to retype the rest.+ */+ const changeId = (nextId: string) => {+ fillAttempt.current += 1;+ setFillState('idle');+ setMatches([]);+ setMatchesOpen(false);+ if (draft.models_dev_id === null) {+ patch({ id: nextId });+ return;+ }+ setDraft({ ...blankBackendModel(), id: nextId });+ setNameText('');+ setContextText('');+ setOutputText('');+ };++ const fill = () => {+ const query = trimmedId;+ if (query === '') return;+ const attempt = ++fillAttempt.current;+ setFillState('loading');+ setMatchesOpen(false);+ void (async () => {+ try {+ const found = await modelsApi.searchModelsDev(query);+ if (attempt !== fillAttempt.current) return;+ setMatches(found);+ if (found.length === 0) {+ setFillState('empty');+ return;+ }+ setFillState('idle');+ if (found.length === 1) applyMatch(found[0]);+ else setMatchesOpen(true);+ } catch (error) {+ if (attempt !== fillAttempt.current) return;+ setFillFailedKey(modelsDevFillFailureKey(apiFailure(error)?.detail));+ setFillState('error');+ }+ })();+ };++ const addCustomEffort = () => {+ const value = customEffort.trim();+ if (value === '' || value.length > BACKEND_MODEL_EFFORT_MAX_LENGTH) return;+ if (!draft.reasoning_efforts.includes(value)) patch({ reasoning_efforts: [...draft.reasoning_efforts, value] });+ setCustomEffort('');+ setCustomOpen(false);+ };++ const commit = () => {+ setSubmitted(true);+ if (!valid) return;+ onCommit({+ ...draft,+ id: trimmedId,+ // An empty box is 「no name」, not an empty name: the schema takes null and+ // the list falls back to the id.+ display_name: nameText.trim() || null,+ context_window: context.value,+ max_output_tokens: output.value,+ // The efforts are the row's own metadata, never a consequence of the+ // capability answer above them: 「no reasoning」 hides the list, and+ // dropping it would make that answer destructive — take it back and the+ // efforts would be gone with nothing to restore them from. Which efforts+ // a `false` row projects is the backend's question, not the editor's.+ });+ };++ const efforts = [...new Set([...effortSuggestions, ...draft.reasoning_efforts])];+ const backendName = t(`settings.models.backends.${backend}`, { defaultValue: backend });+ const idHint = submitted && idError ? t(`settings.models.gateway.modelEditor.id.${idError}`) as string : null;++ return (+ <Dialog open={open} onOpenChange={(next) => { if (!next) onCancel(); }}>+ <DialogContent+ mobileSheetHeight="tall"+ closeLabel={t('settings.models.gateway.modelEditor.cancel') as string}+ className="model-hub-model-editor flex h-[min(660px,calc(100dvh-32px))] w-[min(720px,calc(100vw-32px))] max-w-[720px] flex-col gap-0 overflow-hidden rounded-[14px] border-border-strong bg-surface p-0 shadow-[var(--model-hub-dialog-shadow)] max-md:w-full max-md:max-w-none max-md:rounded-t-2xl max-md:p-0 max-md:pt-2"+ >+ <DialogHeader className="model-hub-model-editor-head shrink-0 justify-center border-b border-border">+ <p className="model-hub-model-editor-eyebrow truncate">{t('settings.models.gateway.modelEditor.eyebrow', { backend: backendName })}</p>+ <DialogTitle className="model-hub-model-editor-title">+ {t(creating ? 'settings.models.gateway.modelEditor.addTitle' : 'settings.models.gateway.modelEditor.editTitle')}+ </DialogTitle>+ <DialogDescription className="sr-only">{t('settings.models.gateway.modelEditor.description')}</DialogDescription>+ </DialogHeader>++ <div className="model-hub-model-editor-body min-h-0 flex-1 overflow-y-auto">+ <section className="model-hub-model-section">+ <SectionLabel>{t('settings.models.gateway.modelEditor.section.basic')}</SectionLabel>+ <div className="flex flex-col gap-2 sm:flex-row sm:items-end">+ <Field+ label={t('settings.models.gateway.modelEditor.id.label')}+ className="min-w-0 flex-1 gap-1.5"+ labelClassName="model-hub-model-field-label"+ >+ {(id) => (+ <Input+ id={id}+ value={draft.id}+ readOnly={!creating}+ aria-invalid={Boolean(idHint)}+ // The ceiling belongs to the field that can still be typed+ // into; a read-only legacy id is shown in full, not clipped.+ maxLength={creating ? BACKEND_MODEL_ID_MAX_LENGTH : undefined}+ spellCheck={false}+ autoComplete="off"+ onChange={(event) => changeId(event.target.value)}+ placeholder={t('settings.models.gateway.modelEditor.id.placeholder') as string}+ className="model-hub-model-control w-full font-mono text-[12.5px] read-only:text-muted"+ />+ )}+ </Field>+ <Button+ type="button"+ variant="outline"+ className="model-hub-model-control shrink-0 rounded-md px-3.5 text-[12.5px] font-semibold"+ disabled={trimmedId === '' || fillState === 'loading'}+ onClick={fill}+ >+ {fillState === 'loading'+ ? <LoaderCircle className="animate-spin" aria-hidden="true" />+ : <DownloadCloud aria-hidden="true" />}+ {t('settings.models.gateway.modelEditor.fill')}+ </Button>+ </div>+ {idHint && <p className="model-hub-model-error" role="alert">{idHint}</p>}+ {fillState === 'empty' && <p className="model-hub-model-error" role="status">{t('settings.models.gateway.modelEditor.fillEmpty')}</p>}+ {fillState === 'error' && <p className="model-hub-model-error" role="status">{t(fillFailedKey)}</p>}++ {draft.models_dev_id && (+ <div className="model-hub-model-source-strip flex min-w-0 items-center gap-2.5">+ <Database className="size-[14px] shrink-0 text-muted" aria-hidden="true" />+ <span className="model-hub-model-source-id shrink-0 font-mono">{`models.dev · ${draft.models_dev_id}`}</span>+ <span className="model-hub-model-source-note min-w-0 flex-1 truncate">{t('settings.models.gateway.modelEditor.filled')}</span>+ <button+ type="button"+ className="model-hub-model-source-view shrink-0"+ aria-expanded={matchesOpen}+ disabled={matches.length === 0}+ onClick={() => setMatchesOpen((value) => !value)}+ >+ {t('settings.models.gateway.modelEditor.viewMatches')}+ </button>+ </div>+ )}++ {matchesOpen && matches.length > 0 && (+ <div className="model-hub-model-match-list flex flex-col" role="listbox" aria-label={t('settings.models.gateway.modelEditor.matches') as string}>+ {matches.map((match) => {+ const selected = draft.models_dev_id === match.models_dev_id;+ return (+ <button+ key={match.models_dev_id}+ type="button"+ role="option"+ aria-selected={selected}+ onClick={() => applyMatch(match)}+ className={cn('model-hub-model-match flex min-w-0 items-center gap-2.5 text-left', selected && 'is-selected')}+ >+ <span className="min-w-0 flex-1">+ <span className="model-hub-model-match-name block truncate">{match.display_name ?? match.model_id}</span>+ <span className="model-hub-model-match-id block truncate font-mono">{match.models_dev_id}</span>+ </span>+ <span className="model-hub-pill model-hub-fill-0a shrink-0 border border-border text-muted">{match.provider_name}</span>+ {selected && <Check className="model-hub-ink-mint size-4 shrink-0" aria-hidden="true" />}+ </button>+ );+ })}+ </div>+ )}++ <Field+ label={t('settings.models.gateway.modelEditor.displayName.label')}+ className="min-w-0 gap-1.5"+ labelClassName="model-hub-model-field-label"+ >+ {(id) => (+ <Input+ id={id}+ value={nameText}+ onChange={(event) => setNameText(event.target.value)}+ placeholder={t('settings.models.gateway.modelEditor.displayName.placeholder') as string}+ className="model-hub-model-control w-full text-[12.5px]"+ />+ )}+ </Field>+ </section>++ <section className="model-hub-model-section">+ <SectionLabel>{t('settings.models.gateway.modelEditor.section.parameters')}</SectionLabel>+ <div className="grid gap-3 sm:grid-cols-2 sm:gap-6">+ <Field+ label={t('settings.models.gateway.modelEditor.contextWindow')}+ className="min-w-0 gap-1.5"+ labelClassName="model-hub-model-field-label"+ >+ {(id) => (+ <TokenInput+ id={id}+ value={contextText}+ invalid={!context.ok}+ onChange={setContextText}+ onBlur={() => context.ok && setContextText(groupTokens(context.value))}+ />+ )}+ </Field>+ <Field+ label={t('settings.models.gateway.modelEditor.maxOutput')}+ className="min-w-0 gap-1.5"+ labelClassName="model-hub-model-field-label"+ >+ {(id) => (+ <TokenInput+ id={id}+ value={outputText}+ invalid={!output.ok}+ onChange={setOutputText}+ onBlur={() => output.ok && setOutputText(groupTokens(output.value))}+ />+ )}+ </Field>+ </div>+ <div className="grid gap-3 sm:grid-cols-2 sm:gap-6">+ <div className="flex min-w-0 flex-col gap-1.5">+ <p className="model-hub-model-field-label" id="model-hub-input-modalities">{t('settings.models.gateway.modelEditor.inputModalities')}</p>+ <div className="flex flex-wrap gap-2" role="group" aria-labelledby="model-hub-input-modalities">+ {BACKEND_MODEL_INPUT_MODALITIES.map((modality) => (+ <ChipButton key={modality} on={draft.input_modalities.includes(modality)} onClick={() => toggleInput(modality)}>+ {t(`settings.models.gateway.modelEditor.modality.${modality}`)}+ </ChipButton>+ ))}+ </div>+ </div>+ <div className="flex min-w-0 flex-col gap-1.5">+ <p className="model-hub-model-field-label" id="model-hub-output-modalities">{t('settings.models.gateway.modelEditor.outputModalities')}</p>+ <div className="flex flex-wrap gap-2" role="group" aria-labelledby="model-hub-output-modalities">+ {BACKEND_MODEL_OUTPUT_MODALITIES.map((modality) => (+ <ChipButton key={modality} on={draft.output_modalities.includes(modality)} onClick={() => toggleOutput(modality)}>+ {t(`settings.models.gateway.modelEditor.modality.${modality}`)}+ </ChipButton>+ ))}+ </div>+ </div>+ </div>+ </section>++ <section className="model-hub-model-section">+ <SectionLabel>{t('settings.models.gateway.modelEditor.section.capabilities')}</SectionLabel>+ <div className="grid gap-3 sm:grid-cols-2 sm:gap-6">+ <CapabilityField+ label={t('settings.models.gateway.modelEditor.supportsTools') as string}+ value={draft.supports_tools}+ onChange={(next) => patch({ supports_tools: next })}+ />+ <CapabilityField+ label={t('settings.models.gateway.modelEditor.supportsReasoning') as string}+ value={draft.supports_reasoning}+ onChange={(next) => patch({ supports_reasoning: next })}+ />+ </div>+ {/* An unstated capability still owns its efforts, so hide the list+ only when the user has actually said this model cannot reason.+ Hidden, not dropped: the draft keeps them for the answer that+ comes back. */}+ {draft.supports_reasoning !== false && (+ <div className="flex flex-col gap-1.5">+ <p className="model-hub-model-field-label" id="model-hub-efforts">{t('settings.models.gateway.modelEditor.reasoningEfforts')}</p>+ <div className="flex flex-wrap gap-2" role="group" aria-labelledby="model-hub-efforts">+ {efforts.map((effort) => (+ <ChipButton key={effort} on={draft.reasoning_efforts.includes(effort)} onClick={() => toggleEffort(effort)}>+ {effort}+ </ChipButton>+ ))}+ {customOpen ? (+ <span className="model-hub-model-chip model-hub-model-chip--custom">+ <Input+ variant="bare"+ autoFocus+ value={customEffort}+ maxLength={BACKEND_MODEL_EFFORT_MAX_LENGTH}+ aria-label={t('settings.models.gateway.modelEditor.customEffort') as string}+ placeholder={t('settings.models.gateway.modelEditor.customEffortPlaceholder') as string}+ onChange={(event) => setCustomEffort(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ event.preventDefault();+ addCustomEffort();+ } else if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ setCustomOpen(false);+ setCustomEffort('');+ }+ }}+ onBlur={addCustomEffort}+ className="w-[104px] text-[12px]"+ />+ </span>+ ) : (+ <button type="button" className="model-hub-model-chip model-hub-model-chip--add" onClick={() => setCustomOpen(true)}>+ <Plus className="size-[13px] shrink-0" aria-hidden="true" />+ {t('settings.models.gateway.modelEditor.customEffort')}+ </button>+ )}+ </div>+ <p className="model-hub-model-note">{t('settings.models.gateway.modelEditor.effortNote')}</p>+ </div>+ )}+ </section>+ </div>++ <DialogFooter className="model-hub-model-editor-foot shrink-0 items-center border-t border-border sm:justify-end">+ <Button type="button" variant="outline" className="model-hub-model-control rounded-md px-5 text-[12.5px] font-semibold" onClick={onCancel}>+ {t('settings.models.gateway.modelEditor.cancel')}+ </Button>+ <Button type="button" variant="brand" className="model-hub-model-control rounded-md px-5 text-[12.5px] font-semibold" onClick={commit}>+ {t(creating ? 'settings.models.gateway.modelEditor.add' : 'settings.models.gateway.modelEditor.apply')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};++const TokenInput: React.FC<{+ id: string;+ value: string;+ invalid: boolean;+ onChange: (next: string) => void;+ onBlur: () => void;+}> = ({ id, value, invalid, onChange, onBlur }) => {+ const { t } = useTranslation();+ return (+ <div className={cn('model-hub-model-control model-hub-model-token flex min-w-0 items-center gap-2', invalid && 'is-invalid')}>+ <Input+ id={id}+ variant="bare"+ inputMode="numeric"+ value={value}+ aria-invalid={invalid}+ onChange={(event) => onChange(event.target.value)}+ onBlur={onBlur}+ className="min-w-0 flex-1 font-mono text-[12.5px]"+ />+ <span className="model-hub-model-token-suffix shrink-0" aria-hidden="true">{t('settings.models.gateway.modelEditor.tokens')}</span>+ </div>+ );+};++export default BackendModelEditorDialog;diff --git a/ui/src/components/settings/models/OpenCodeMenuDialog.test.tsx b/ui/src/components/settings/models/OpenCodeMenuDialog.test.tsxdeleted file mode 100644index 8143cafac..000000000--- a/ui/src/components/settings/models/OpenCodeMenuDialog.test.tsx+++ /dev/null@@ -1,320 +0,0 @@-// @vitest-environment jsdom-import { cleanup, render, screen, waitFor } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { I18nextProvider } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';--import i18n from '@/i18n';-import { ApiCallError, modelsApi } from './modelsApi';-import { OpenCodeMenuDialog } from './OpenCodeMenuDialog';-import type { AgentSupply, Source } from './types';--const source = (overrides: Partial<Source> & Pick<Source, 'id' | 'vendor' | 'display_name'>): Source => ({- last_discovered_at: '2026-08-29T00:00:00Z',- kind: 'api_key',- protocol: 'openai_responses',- supply_channel: 'hub',- billing: 'metered',- state: { status: 'active', retry_at: null, detail_key: null },- models: [],- ...overrides,-});--const sources: Source[] = [- source({- id: 'src_openai',- vendor: 'openai',- display_name: 'OpenAI Relay',- models: [- { id: 'gpt-5.6-luna', origin: 'discovered', reasoning_efforts: [] },- { id: 'gpt-5.6-sol', origin: 'discovered', reasoning_efforts: [] },- { id: 'gpt-retired', origin: 'discovered', reasoning_efforts: [], retired: true },- ],- }),- source({- id: 'src_blocked',- vendor: 'anthropic',- display_name: 'Blocked Source',- protocol: 'anthropic',- models: [{ id: 'claude-opus-4-8', origin: 'discovered', reasoning_efforts: [] }],- }),-];--const agent: AgentSupply = {- backend: 'opencode',- cli_present: true,- mode: 'hub',- menu_kind: 'open',- sources: {- order: ['src_openai'],- eligibility: [- { source_id: 'src_openai', eligible: true },- { source_id: 'src_blocked', eligible: false, reason_key: 'models.eligibility.subscription_wrong_client' },- ],- },- routes: {},- model_supply: [],- named_agents: [],- menu: { view: 'featured', checked: [] },- standard_vendors: ['openai', 'anthropic'],-};--afterEach(() => {- cleanup();- vi.restoreAllMocks();-});--describe('OpenCodeMenuDialog', () => {- it('lists server-eligible inventory and saves the explicit OpenCode selection', async () => {- const user = userEvent.setup();- const echoed = {- ...agent,- menu: { view: 'featured' as const, checked: ['openai/gpt-5.6-luna'] },- model_supply: [{ model_id: 'openai/gpt-5.6-luna', chain_length: 0, has_runnable_hop: false }],- };- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);- const putMenu = vi.spyOn(modelsApi, 'putMenu').mockResolvedValue(echoed);- const onSaved = vi.fn();- const onClose = vi.fn();-- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={onClose}- onSaved={onSaved}- onObserved={vi.fn()}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- expect(await screen.findByText('0 of 2 selected')).toBeTruthy();- expect(screen.queryByText('Blocked Source')).toBeNull();- expect(screen.queryByText(/gpt-retired/)).toBeNull();-- await user.click(screen.getByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i }));- expect(screen.getByText('1 of 2 selected')).toBeTruthy();- await user.click(screen.getByRole('button', { name: 'Save selection' }));-- await waitFor(() => expect(putMenu).toHaveBeenCalledWith(- { view: 'featured', checked: [] },- { view: 'featured', checked: ['openai/gpt-5.6-luna'] },- ));- expect(onSaved).toHaveBeenCalledWith(echoed);- expect(onClose).toHaveBeenCalledOnce();- });-- it('filters by source name without changing the selected menu', async () => {- const user = userEvent.setup();- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue({- ...agent,- menu: { view: 'full', checked: ['openai/gpt-5.6-sol'] },- });- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={vi.fn()}- onSaved={vi.fn()}- onObserved={vi.fn()}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- await user.type(await screen.findByRole('textbox', { name: 'Search models or sources' }), 'luna');- expect(screen.getByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i })).toBeTruthy();- expect(screen.queryByRole('checkbox', { name: /openai\/gpt-5\.6-sol/i })).toBeNull();- expect(screen.getByText('1 of 2 selected')).toBeTruthy();- });-- it('renders a checked route alias and removes it only after an explicit uncheck', async () => {- const user = userEvent.setup();- const configured = {- ...agent,- menu: { view: 'featured' as const, checked: ['openai/menu-model'] },- routes: { 'openai/menu-model': { hops: [{ source_id: 'src_openai', model_id: 'gpt-5.6-luna' }] } },- };- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(configured);- const putMenu = vi.spyOn(modelsApi, 'putMenu').mockResolvedValue({ ...agent, menu: { view: 'featured', checked: [] } });- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={vi.fn()}- onSaved={vi.fn()}- onObserved={vi.fn()}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- const alias = await screen.findByRole('checkbox', { name: /openai\/menu-model/i });- expect(alias.getAttribute('aria-checked')).toBe('true');- expect(screen.getByText('1 of 3 selected')).toBeTruthy();- await user.click(alias);- await user.click(screen.getByRole('button', { name: 'Save selection' }));- await waitFor(() => expect(putMenu).toHaveBeenCalledWith(- { view: 'featured', checked: ['openai/menu-model'] },- { view: 'featured', checked: [] },- ));- });-- it('reselects a dormant route alias backed by an eligible exact hop', async () => {- const user = userEvent.setup();- const configured = {- ...agent,- menu: { view: 'featured' as const, checked: [] },- routes: { 'openai/menu-model': { hops: [{ source_id: 'src_openai', model_id: 'gpt-5.6-sol' }] } },- };- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(configured);- const putMenu = vi.spyOn(modelsApi, 'putMenu').mockResolvedValue({- ...configured,- menu: { view: 'featured', checked: ['openai/menu-model'] },- });- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={vi.fn()}- onSaved={vi.fn()}- onObserved={vi.fn()}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- const alias = await screen.findByRole('checkbox', { name: /openai\/menu-model/i });- expect(alias.getAttribute('aria-checked')).toBe('false');- await user.click(alias);- await user.click(screen.getByRole('button', { name: 'Save selection' }));- await waitFor(() => expect(putMenu).toHaveBeenCalledWith(- { view: 'featured', checked: [] },- { view: 'featured', checked: ['openai/menu-model'] },- ));- });-- it('preserves a checked cross-model route while saving an unrelated addition', async () => {- const user = userEvent.setup();- const configured = {- ...agent,- menu: { view: 'featured' as const, checked: ['openai/menu-model'] },- routes: { 'openai/menu-model': { hops: [{ source_id: 'src_openai', model_id: 'gpt-5.6-sol' }] } },- };- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(configured);- const putMenu = vi.spyOn(modelsApi, 'putMenu').mockResolvedValue({- ...configured,- menu: { view: 'featured', checked: ['openai/menu-model', 'openai/gpt-5.6-luna'] },- });- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={vi.fn()}- onSaved={vi.fn()}- onObserved={vi.fn()}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- await user.click(await screen.findByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i }));- await user.click(screen.getByRole('button', { name: 'Save selection' }));- await waitFor(() => expect(putMenu).toHaveBeenCalledWith(- { view: 'featured', checked: ['openai/menu-model'] },- { view: 'featured', checked: ['openai/menu-model', 'openai/gpt-5.6-luna'] },- ));- });-- it('blocks editing when its dedicated baseline read fails', async () => {- vi.spyOn(modelsApi, 'getAgentSources').mockRejectedValue(new Error('unread'));- const putMenu = vi.spyOn(modelsApi, 'putMenu');- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={vi.fn()}- onSaved={vi.fn()}- onObserved={vi.fn()}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- expect(await screen.findByText('Model menu data is not current. Wait for refresh, or retry the failed section before editing.')).toBeTruthy();- expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();- expect(screen.getByRole('button', { name: 'Save selection' }).hasAttribute('disabled')).toBe(true);- expect(putMenu).not.toHaveBeenCalled();- });-- it('accepts a committed menu after an inconclusive PUT by re-reading it', async () => {- const user = userEvent.setup();- const committed = {- ...agent,- menu: {- view: 'featured' as const,- checked: ['openai/gpt-5.6-sol', 'openai/gpt-5.6-luna'],- },- };- vi.spyOn(modelsApi, 'getAgentSources')- .mockResolvedValueOnce(agent)- .mockResolvedValueOnce(committed);- vi.spyOn(modelsApi, 'putMenu').mockRejectedValue(new ApiCallError('bad_response', undefined, false));- const onSaved = vi.fn();- const onClose = vi.fn();- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={onClose}- onSaved={onSaved}- onObserved={vi.fn()}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- await user.click(await screen.findByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i }));- await user.click(screen.getByRole('button', { name: 'Save selection' }));- await waitFor(() => expect(onSaved).toHaveBeenCalledWith(committed));- expect(onClose).toHaveBeenCalledOnce();- });-- it('rebases a failed draft on the observed menu before enabling retry', async () => {- const user = userEvent.setup();- vi.spyOn(modelsApi, 'getAgentSources')- .mockResolvedValueOnce(agent)- .mockResolvedValueOnce(agent);- vi.spyOn(modelsApi, 'putMenu').mockRejectedValue(new ApiCallError('bad_response', undefined, false));- const onObserved = vi.fn();- render(- <I18nextProvider i18n={i18n}>- <OpenCodeMenuDialog- open- sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}- onClose={vi.fn()}- onSaved={vi.fn()}- onObserved={onObserved}- menuWrite={{ pending: false, track: async (work) => work() }}- />- </I18nextProvider>,- );-- const luna = await screen.findByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i });- await user.click(luna);- await user.click(screen.getByRole('button', { name: 'Save selection' }));-- expect(await screen.findByText('The model selection was not saved')).toBeTruthy();- expect(onObserved).toHaveBeenCalledWith(agent);- expect(luna.getAttribute('aria-checked')).toBe('true');- expect(screen.getByRole('button', { name: 'Save selection' }).hasAttribute('disabled')).toBe(false);- });-});diff --git a/ui/src/components/settings/models/OpenCodeMenuDialog.tsx b/ui/src/components/settings/models/OpenCodeMenuDialog.tsxdeleted file mode 100644index eab7fff8b..000000000--- a/ui/src/components/settings/models/OpenCodeMenuDialog.tsx+++ /dev/null@@ -1,279 +0,0 @@-import * as React from 'react';-import { LoaderCircle, RefreshCw, Search } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';-import { Input } from '@/components/ui/input';-import { cn } from '@/lib/utils';-import type { PendingWrite } from './asyncLifetime';-import type { CollectionReadAuthority } from './collectionReadAuthority';-import { eligibleSources } from './eligibility';-import {- applyOpenCodeMenuIntent,- openCodeMenuIntent,- openCodeMenuIntentApplied,- readOpenCodeMenuBaseline,- type OpenCodeMenuBaseline,-} from './menuBaseline';-import { buildIdentifier } from './menus/identifiers';-import { modelsApi } from './modelsApi';-import type { AgentMenu, AgentSupply, Source } from './types';--type MenuModel = {- id: string;- sourceNames: string[];-};--const selectableModels = (agent: AgentSupply, sources: Source[]): MenuModel[] => {- const standardVendors = new Set(agent.standard_vendors ?? []);- const namesById = new Map<string, Set<string>>();- const sourceNames = new Map(sources.map((source) => [source.id, source.display_name]));- const eligibleById = new Map(eligibleSources(sources, agent).map((source) => [source.id, source]));- for (const source of eligibleById.values()) {- for (const model of source.models) {- if (model.retired) continue;- const id = buildIdentifier(source.vendor, model.id, standardVendors);- const names = namesById.get(id) ?? new Set<string>();- names.add(source.display_name);- namesById.set(id, names);- }- }- for (const [id, route] of Object.entries(agent.routes ?? {})) {- const names = new Set(namesById.get(id));- for (const hop of route.hops) {- const source = eligibleById.get(hop.source_id);- if (source?.models.some((model) => model.id === hop.model_id && !model.retired)) {- names.add(source.display_name);- }- }- if (names.size > 0) namesById.set(id, names);- }- for (const id of agent.menu?.checked ?? []) {- if (namesById.has(id)) continue;- const names = new Set<string>();- for (const hop of agent.routes?.[id]?.hops ?? []) {- const name = sourceNames.get(hop.source_id);- if (name) names.add(name);- }- namesById.set(id, names);- }- return [...namesById.entries()]- .map(([id, names]) => ({ id, sourceNames: [...names].sort((left, right) => left.localeCompare(right)) }))- .sort((left, right) => left.id.localeCompare(right.id));-};--export const OpenCodeMenuDialog: React.FC<{- open: boolean;- sourceReads: Pick<CollectionReadAuthority<Source[]>, 'readValue'>;- onClose: () => void;- onSaved: (echoed: AgentSupply) => void | Promise<void>;- onObserved: (observed: AgentSupply) => void | Promise<void>;- menuWrite: PendingWrite;-}> = ({ open, sourceReads, onClose, onSaved, onObserved, menuWrite }) => {- const { t } = useTranslation();- const [baseline, setBaseline] = React.useState<OpenCodeMenuBaseline | null>(null);- const baselineRef = React.useRef<OpenCodeMenuBaseline | null>(null);- const [readState, setReadState] = React.useState<'loading' | 'ready' | 'error'>('loading');- const [selected, setSelectedState] = React.useState<Set<string>>(new Set());- const selectedRef = React.useRef<Set<string>>(new Set());- const readAttempt = React.useRef(0);- const models = React.useMemo(- () => baseline ? selectableModels(baseline.agent, baseline.sources) : [],- [baseline],- );- const rawChecked = React.useMemo(() => baseline?.agent.menu?.checked ?? [], [baseline]);- const [query, setQuery] = React.useState('');- const [saveFailed, setSaveFailed] = React.useState(false);-- const applyBaseline = React.useCallback((next: OpenCodeMenuBaseline, checked: readonly string[]) => {- const nextSelected = new Set(checked);- baselineRef.current = next;- selectedRef.current = nextSelected;- setBaseline(next);- setSelectedState(nextSelected);- setReadState('ready');- }, []);-- const loadBaseline = React.useCallback(async (preserveDraft: boolean) => {- const attempt = ++readAttempt.current;- const previous = baselineRef.current;- const intent = preserveDraft && previous- ? openCodeMenuIntent(previous.agent.menu?.checked ?? [], [...selectedRef.current])- : null;- setReadState('loading');- try {- const next = await readOpenCodeMenuBaseline(modelsApi, sourceReads);- if (attempt !== readAttempt.current) return;- const selectableIds = new Set(selectableModels(next.agent, next.sources).map((model) => model.id));- applyBaseline(- next,- intent- ? applyOpenCodeMenuIntent(next.agent.menu?.checked ?? [], intent, selectableIds)- : next.agent.menu?.checked ?? [],- );- setQuery('');- setSaveFailed(false);- } catch {- if (attempt === readAttempt.current) setReadState('error');- }- }, [applyBaseline, sourceReads]);-- React.useEffect(() => {- if (open) void loadBaseline(false);- else readAttempt.current += 1;- }, [loadBaseline, open]);-- const normalizedQuery = query.trim().toLocaleLowerCase();- const visibleModels = normalizedQuery- ? models.filter((model) => `${model.id} ${model.sourceNames.join(' ')}`.toLocaleLowerCase().includes(normalizedQuery))- : models;- const savedSet = new Set(rawChecked);- const dirty = selected.size !== savedSet.size || [...selected].some((id) => !savedSet.has(id));- const baselineReady = readState === 'ready' && baseline !== null;-- const toggle = (id: string) => {- if (!baselineReady || menuWrite.pending) return;- setSaveFailed(false);- const next = new Set(selectedRef.current);- if (next.has(id)) next.delete(id);- else next.add(id);- selectedRef.current = next;- setSelectedState(next);- };-- const save = () => {- const current = baselineRef.current;- if (!baselineReady || !current || !dirty || menuWrite.pending) return;- const intent = openCodeMenuIntent(- current.agent.menu?.checked ?? [],- [...selectedRef.current],- );- const baselineMenu: AgentMenu = current.agent.menu ?? { view: 'featured', checked: [] };- const requestedMenu: AgentMenu = {- view: baselineMenu.view,- checked: [...selectedRef.current],- };- setSaveFailed(false);- void menuWrite.track(async () => {- let echoed: AgentSupply;- try {- echoed = await modelsApi.putMenu(baselineMenu, requestedMenu);- } catch {- try {- const observed = await readOpenCodeMenuBaseline(modelsApi, sourceReads);- if (openCodeMenuIntentApplied(observed.agent.menu?.checked ?? [], intent)) {- applyBaseline(observed, observed.agent.menu?.checked ?? []);- await Promise.resolve(onSaved(observed.agent)).catch(() => {});- onClose();- return;- }- const observedSelectable = new Set(selectableModels(observed.agent, observed.sources).map((model) => model.id));- applyBaseline(- observed,- applyOpenCodeMenuIntent(observed.agent.menu?.checked ?? [], intent, observedSelectable),- );- await Promise.resolve(onObserved(observed.agent)).catch(() => {});- } catch {- setReadState('error');- }- setSaveFailed(true);- return;- }- await Promise.resolve(onSaved(echoed)).catch(() => {});- onClose();- });- };-- return (- <Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen && !menuWrite.pending) onClose(); }}>- <DialogContent- mobileSheetHeight="tall"- closeLabel={t('settings.models.gateway.menu.cancel') as string}- className="flex h-[min(640px,calc(100dvh-32px))] w-[min(680px,calc(100vw-32px))] max-w-[680px] flex-col gap-4 overflow-hidden rounded-[14px] border-border-strong bg-surface p-5 shadow-[var(--model-hub-dialog-shadow)] max-md:w-full max-md:max-w-none max-md:rounded-t-2xl"- onEscapeKeyDown={(event) => { if (menuWrite.pending) event.preventDefault(); }}- onPointerDownOutside={(event) => { if (menuWrite.pending) event.preventDefault(); }}- >- <DialogHeader>- <DialogTitle>{t('settings.models.gateway.menu.title')}</DialogTitle>- <DialogDescription className="sr-only">{t('settings.models.gateway.menu.description')}</DialogDescription>- </DialogHeader>-- <div className="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center">- <div className="flex h-9 min-w-0 flex-1 items-center gap-2 rounded-md border border-border bg-background px-3 focus-within:ring-2 focus-within:ring-ring">- <Search className="size-4 shrink-0 text-muted" aria-hidden="true" />- <Input- variant="bare"- value={query}- onChange={(event) => setQuery(event.target.value)}- placeholder={t('settings.models.gateway.menu.search') as string}- aria-label={t('settings.models.gateway.menu.search') as string}- className="min-w-0 flex-1 text-[12.5px]"- disabled={!baselineReady || menuWrite.pending}- />- </div>- <span className="shrink-0 text-[11px] font-semibold text-muted">- {baselineReady- ? t('settings.models.gateway.menu.selected', { selected: selected.size, total: models.length })- : t('settings.models.gateway.selectedModelCount', { count: selected.size })}- </span>- </div>-- <div className="min-h-0 flex-1 overflow-y-auto rounded-md border border-border bg-background p-1.5">- {!baselineReady ? (- <div className="flex flex-col items-center gap-3 px-4 py-10 text-center text-[12.5px] text-muted">- {readState === 'loading' && <LoaderCircle className="size-4 animate-spin" aria-hidden="true" />}- <p>{t('settings.models.gateway.menu.baselineUnavailable')}</p>- {readState === 'error' && <Button type="button" variant="outline" size="xs" onClick={() => void loadBaseline(true)}><RefreshCw aria-hidden="true" />{t('settings.models.gateway.retry')}</Button>}- </div>- ) : models.length === 0 ? (- <p className="px-4 py-10 text-center text-[12.5px] text-muted">{t('settings.models.gateway.menu.empty')}</p>- ) : visibleModels.length === 0 ? (- <p className="px-4 py-10 text-center text-[12.5px] text-muted">{t('settings.models.gateway.menu.noMatch')}</p>- ) : (- <div className="space-y-1">- {visibleModels.map((model) => {- const checked = selected.has(model.id);- const sourceLabel = model.sourceNames.length > 0- ? model.sourceNames.join(' · ')- : t('settings.models.gateway.menu.configured');- return (- <button- key={model.id}- type="button"- role="checkbox"- aria-checked={checked}- disabled={!baselineReady || menuWrite.pending}- onClick={() => toggle(model.id)}- className={cn(- 'flex min-h-11 w-full min-w-0 items-center gap-3 rounded-md px-3 py-2 text-left transition-colors hover:bg-surface-2 disabled:opacity-50',- checked && 'bg-surface-2',- )}- >- <Checkbox checked={checked} presentational />- <span className="min-w-0 flex-1">- <span className="block truncate font-mono text-[12px] font-medium text-foreground" title={model.id}>{model.id}</span>- <span className="mt-0.5 block truncate text-[10.5px] text-muted" title={sourceLabel}>{sourceLabel}</span>- </span>- </button>- );- })}- </div>- )}- </div>-- <DialogFooter className="items-center sm:justify-between">- <div className="min-h-5 text-[11px] font-semibold text-destructive-ink" role="status">{saveFailed ? t('settings.models.gateway.menu.saveFailed') : null}</div>- <div className="flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row">- <Button type="button" variant="outline" onClick={onClose} disabled={menuWrite.pending}>{t('settings.models.gateway.menu.cancel')}</Button>- <Button type="button" onClick={save} disabled={!baselineReady || !dirty || menuWrite.pending}>- {menuWrite.pending && <LoaderCircle className="animate-spin" aria-hidden="true" />}- {t(menuWrite.pending ? 'settings.models.gateway.menu.saving' : 'settings.models.gateway.menu.save')}- </Button>- </div>- </DialogFooter>- </DialogContent>- </Dialog>- );-};diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex f7ac978be..31e96ca3e 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -10,12 +10,12 @@ import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';import { ToggleSwitch } from '../SettingsPrimitives';import { AddApiKeyDialog } from './AddApiKeyDialog';+import { BackendModelCatalogDialog } from './BackendModelCatalogDialog';import { OAuthConnectDialog } from './OAuthConnectDialog';import { EnableGatewayDialog } from './EnableGatewayDialog';import { GatewayModule } from './GatewayModule';import { InstallGatewayDialog } from './InstallGatewayDialog';import { ModelHubInfoHint } from './ModelHubInfoHint';-import { OpenCodeMenuDialog } from './OpenCodeMenuDialog';import { RecentSwitchesCard } from './RecentSwitchesCard';import { RouteChainDialog, type RouteCollectionObservation, type RouteCommitReconciliation, type RouteReport } from './RouteChainDialog';import { routeChainMatchesAttempt } from './routeChainDraft';@@ -927,7 +927,7 @@ export const SettingsModelsPage: React.FC = () => {const selectedSource = sources.find((source) => source.id === selectedSourceId) ?? null;const sourceDetailOpen = selectedSourceId !== null && subscriptionVendor === null;const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;- const menuAgent = agents.find((agent) => agent.backend === menuBackend && agent.backend === 'opencode' && agent.mode === 'hub') ?? null;+ const menuAgent = agents.find((agent) => agent.backend === menuBackend && agent.mode === 'hub') ?? null;const currentRouteAgent = routeTarget? installedAgents.find((agent) => agent.backend === routeTarget.agent.backend) ?? null: null;@@ -1383,7 +1383,7 @@ export const SettingsModelsPage: React.FC = () => {/>)}{orderAgent && <SourceOrderDrawer open agent={orderAgent} sources={sources} sourceReads={sourceCollectionReads} onClose={() => setOrderBackend(null)} onSaved={agentSaved} orderWrite={{ pending: agentWrites.has(orderAgent.backend), track: (work) => agentWriteRegistry.track(orderAgent.backend, work) }} />}- {menuAgent && <OpenCodeMenuDialog open sourceReads={sourceCollectionReads} onClose={() => setMenuBackend(null)} onSaved={agentSaved} onObserved={applyAgentEcho} menuWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}+ {menuAgent && <BackendModelCatalogDialog open backend={menuAgent.backend} onClose={() => setMenuBackend(null)} onSaved={agentSaved} onObserved={applyAgentEcho} catalogWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}<RouteChainDialogselection={routeSelection}sources={sources}diff --git a/ui/src/components/settings/models/backendCatalog.test.ts b/ui/src/components/settings/models/backendCatalog.test.tsnew file mode 100644index 000000000..0352540e0--- /dev/null+++ b/ui/src/components/settings/models/backendCatalog.test.ts@@ -0,0 +1,228 @@+import { describe, expect, it, vi } from 'vitest';++import {+ applyBackendCatalogIntent,+ applyModelsDevMatch,+ backendCatalogIntent,+ backendCatalogIntentApplied,+ blankBackendModel,+ catalogModelIds,+ catalogModels,+ readBackendCatalogBaseline,+ sameBackendModel,+} from './backendCatalog';+import type { AgentSupply, BackendModel, ModelsDevMatch } from './types';++const model = (id: string, overrides: Partial<BackendModel> = {}): BackendModel => ({+ ...blankBackendModel(),+ id,+ ...overrides,+});++const agent: AgentSupply = {+ backend: 'claude',+ cli_present: true,+ mode: 'hub',+ menu_kind: 'fixed',+ sources: { order: [], eligibility: [] },+ builtin_models: ['legacy-a', 'legacy-b'],+ routes: {},+ menu: null,+};++const match: ModelsDevMatch = {+ provider_id: 'anthropic',+ provider_name: 'Anthropic',+ model_id: 'claude-sonnet-4-5',+ models_dev_id: 'anthropic/claude-sonnet-4-5',+ display_name: 'Claude Sonnet 4.5',+ context_window: 200000,+ max_output_tokens: 64000,+ input_modalities: ['text', 'image', 'pdf'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: true,+ reasoning_efforts: ['low', 'high'],+};++describe('catalogModelIds', () => {+ it('enumerates routeable rows in catalog order', () => {+ const catalogued: AgentSupply = {+ ...agent,+ catalog_models: [+ model('second'),+ model('default', { locked: true, routeable: false }),+ model('first'),+ ],+ };++ expect(catalogModelIds(catalogued)).toEqual(['second', 'first']);+ });++ it('keeps a locked row routeable when the server says it names a route key', () => {+ const catalogued: AgentSupply = { ...agent, catalog_models: [model('pinned', { locked: true })] };++ expect(catalogModelIds(catalogued)).toEqual(['pinned']);+ });++ it('falls back to the legacy projection while the server predates the catalog', () => {+ expect(catalogModels(agent)).toBeNull();+ expect(catalogModelIds(agent)).toEqual(['legacy-a', 'legacy-b']);+ expect(catalogModelIds({ ...agent, menu_kind: 'open', builtin_models: null, menu: { view: 'featured', checked: ['x'] } }))+ .toEqual(['x']);+ });++ it('prefers an empty catalog over the legacy projection once the server sends one', () => {+ expect(catalogModelIds({ ...agent, catalog_models: [] })).toEqual([]);+ });+});++describe('applyModelsDevMatch', () => {+ it('fills metadata without ever renaming the row', () => {+ const filled = applyModelsDevMatch(model('anthropic/claude-sonnet-4-5-20250929'), match, 'models_dev');++ expect(filled.id).toBe('anthropic/claude-sonnet-4-5-20250929');+ expect(filled.models_dev_id).toBe('anthropic/claude-sonnet-4-5');+ expect(filled.display_name).toBe('Claude Sonnet 4.5');+ expect(filled.context_window).toBe(200000);+ expect(filled.max_output_tokens).toBe(64000);+ expect(filled.input_modalities).toEqual(['text', 'image', 'pdf']);+ expect(filled.reasoning_efforts).toEqual(['low', 'high']);+ });++ it('takes the origin from the caller so a re-fill never rewrites how the row was created', () => {+ expect(applyModelsDevMatch(model('m', { origin: 'manual' }), match, 'manual').origin).toBe('manual');+ expect(applyModelsDevMatch(blankBackendModel(), match, 'models_dev').origin).toBe('models_dev');+ });++ it('copies the match lists instead of aliasing them', () => {+ const filled = applyModelsDevMatch(model('m'), match, 'models_dev');+ filled.reasoning_efforts.push('mutated');++ expect(match.reasoning_efforts).toEqual(['low', 'high']);+ });+});++describe('sameBackendModel', () => {+ it('ignores the server-derived projections', () => {+ expect(sameBackendModel(model('m'), model('m', { locked: true, routeable: false }))).toBe(true);+ });++ it('separates an unstated capability from a stated no', () => {+ // Treating them as equal would swallow the write that answers the question.+ expect(sameBackendModel(model('m', { supports_tools: null }), model('m', { supports_tools: false }))).toBe(false);+ expect(sameBackendModel(model('m', { supports_tools: null }), model('m', { supports_tools: null }))).toBe(true);+ });++ it('sees every field the user owns, including list order', () => {+ expect(sameBackendModel(model('m'), model('m', { display_name: 'M' }))).toBe(false);+ expect(sameBackendModel(model('m'), model('m', { context_window: 1 }))).toBe(false);+ expect(sameBackendModel(+ model('m', { reasoning_efforts: ['low', 'high'] }),+ model('m', { reasoning_efforts: ['high', 'low'] }),+ )).toBe(false);+ });+});++describe('backendCatalogIntent', () => {+ const baseline = [model('a'), model('b'), model('c')];++ it('records removals, upserts and the desired order as ids', () => {+ const intent = backendCatalogIntent(baseline, [model('c'), model('a', { display_name: 'A' }), model('d')]);++ expect([...intent.removed]).toEqual(['b']);+ expect(intent.upserts.map((entry) => entry.id)).toEqual(['a', 'd']);+ expect(intent.order).toEqual(['c', 'a', 'd']);+ });++ it('treats a pure reorder as no upsert at all', () => {+ const intent = backendCatalogIntent(baseline, [model('c'), model('b'), model('a')]);++ expect(intent.upserts).toEqual([]);+ expect(intent.order).toEqual(['c', 'b', 'a']);+ });+});++describe('applyBackendCatalogIntent', () => {+ it('replays edits onto a newer catalog and keeps a concurrent addition visible', () => {+ const intent = backendCatalogIntent([model('a'), model('b')], [model('b'), model('a', { display_name: 'A' })]);+ const rebased = applyBackendCatalogIntent([model('a'), model('b'), model('fresh')], intent);++ expect(rebased.map((entry) => entry.id)).toEqual(['b', 'a', 'fresh']);+ expect(rebased[1].display_name).toBe('A');+ });++ it('never removes or edits a locked row', () => {+ const current = [model('default', { locked: true, routeable: false }), model('a')];+ const intent = backendCatalogIntent(current, [model('default', { display_name: 'renamed' })]);+ const rebased = applyBackendCatalogIntent(current, intent);++ expect(rebased.map((entry) => entry.id)).toEqual(['default']);+ expect(rebased[0].display_name).toBeNull();+ expect(rebased[0].locked).toBe(true);+ });++ it('keeps the server projections when an edited row lands on a newer catalog', () => {+ const intent = backendCatalogIntent([model('a')], [model('a', { display_name: 'A', routeable: true })]);+ const rebased = applyBackendCatalogIntent([model('a', { routeable: false })], intent);++ expect(rebased[0].display_name).toBe('A');+ expect(rebased[0].routeable).toBe(false);+ });++ it('drops an ordered id the server no longer has', () => {+ const intent = backendCatalogIntent([model('a'), model('b')], [model('b'), model('a')]);++ expect(applyBackendCatalogIntent([model('b')], intent).map((entry) => entry.id)).toEqual(['b']);+ });+});++describe('backendCatalogIntentApplied', () => {+ const intent = backendCatalogIntent([model('a'), model('b')], [model('b'), model('a', { display_name: 'A' })]);++ it('accepts a server catalog that already carries the removals and upserts', () => {+ expect(backendCatalogIntentApplied([model('b'), model('a', { display_name: 'A', locked: true })], intent)).toBe(true);+ });++ it('rejects a catalog that kept a removed row or lost an upsert', () => {+ const removal = backendCatalogIntent([model('a'), model('b')], [model('a')]);++ expect(backendCatalogIntentApplied([model('a'), model('b')], removal)).toBe(false);+ expect(backendCatalogIntentApplied([model('b'), model('a')], intent)).toBe(false);+ });++ it('rejects the old order after an inconclusive reorder-only save', () => {+ const reorder = backendCatalogIntent(+ [model('a'), model('b')],+ [model('b'), model('a')],+ );++ expect(backendCatalogIntentApplied([model('a'), model('b')], reorder)).toBe(false);+ expect(backendCatalogIntentApplied([model('b'), model('a')], reorder)).toBe(true);+ });+});++describe('readBackendCatalogBaseline', () => {+ it('reports the catalog and the agent it came from', async () => {+ const catalogued = { ...agent, catalog_models: [model('a')] };+ const api = { getAgentSources: vi.fn().mockResolvedValue(catalogued) };++ await expect(readBackendCatalogBaseline(api, 'claude')).resolves.toEqual({+ agent: catalogued,+ models: [model('a')],+ });+ });++ it('refuses a read that answered for another backend', async () => {+ // The one thing a baseline cannot survive: describing someone else's list.+ await expect(readBackendCatalogBaseline({ getAgentSources: vi.fn().mockResolvedValue(agent) }, 'codex'))+ .rejects.toThrow('Backend model catalog is unavailable');+ });++ it('refuses a direct-mode catalog that the runtime will not project', async () => {+ const direct = { ...agent, mode: 'direct' as const, routes: null, catalog_models: [model('a')] };++ await expect(readBackendCatalogBaseline({ getAgentSources: vi.fn().mockResolvedValue(direct) }, 'claude'))+ .rejects.toThrow('Backend model catalog is unavailable');+ });+});diff --git a/ui/src/components/settings/models/backendCatalog.ts b/ui/src/components/settings/models/backendCatalog.tsnew file mode 100644index 000000000..7d1e0178b--- /dev/null+++ b/ui/src/components/settings/models/backendCatalog.ts@@ -0,0 +1,251 @@+// The backend model catalog: what a backend Agent's menu holds, and how an edit+// to it settles.+//+// One concept for all three backends. Their runtime adapters still differ —+// Claude Code reads the Gateway's Anthropic projection, Codex gets a written+// `model_catalog_json`, OpenCode gets a provider overlay — but those are derived+// artifacts. The catalog is the state, and this module is the only place that+// reads it, orders it, or turns a draft into a write.+//+// It deliberately knows nothing about Sources or Routes. A catalog row names a+// model the Agent may select; which supplier serves it stays with the Route, and+// mixing the two here is what the contract's 「no Source id, no upstream model+// id, no priority, no fallback」 rule exists to prevent.+import type { ModelsApi } from './modelsApi';+import type { AgentBackend, AgentSupply, BackendModel, BackendModelOrigin, ModelsDevMatch } from './types';++/**+ * The model list the server says this backend exposes, derived from the+ * pre-catalog projections.+ *+ * Kept for the rolling-upgrade window only: a server that predates+ * `catalog_models` still answers with `builtin_models`/`menu`, and an Agent card+ * that rendered nothing there would report 「no models」 about a backend that has+ * them. The extras are the same rule the server's own migration applies — a+ * configured Route never becomes invisible just because it postdates the menu.+ */+export function listedModelIds(agent: AgentSupply): string[] {+ const primary = agent.menu_kind === 'fixed' ? agent.builtin_models ?? [] : agent.menu?.checked ?? [];+ const extras = [+ ...(agent.selected_model_id ? [agent.selected_model_id] : []),+ ...(agent.model_supply ?? []).map((model) => model.model_id),+ ...Object.keys(agent.routes ?? {}),+ ];+ const seen = new Set<string>();+ return [...primary, ...extras].filter((modelId) => {+ if (!modelId || seen.has(modelId)) return false;+ seen.add(modelId);+ return true;+ });+}++/** The canonical catalog, or null when this server predates it. Null is the+ * whole compatibility signal: nothing downstream invents rows to stand in for+ * a payload the server never sent. */+export const catalogModels = (agent: AgentSupply): BackendModel[] | null => agent.catalog_models ?? null;++export function routeableCatalogModelIds(catalog: readonly BackendModel[]): string[] {+ const seen = new Set<string>();+ return catalog+ .filter((model) => model.routeable && model.id && !seen.has(model.id) && seen.add(model.id))+ .map((model) => model.id);+}++/**+ * The model ids an Agent card enumerates, in catalog order.+ *+ * `routeable` is the filter, not `locked`: Claude Code's `Default` is a backend+ * selector that never names a Route key, so a Route row for it would open an+ * editor with nothing to configure. Pre-catalog servers fall back to the legacy+ * projection — OpenCode to its saved menu (dormant routes left behind by an+ * earlier selection are not menu entries), everything else to `listedModelIds`.+ */+export function catalogModelIds(agent: AgentSupply): string[] {+ const catalog = catalogModels(agent);+ if (catalog) {+ return routeableCatalogModelIds(catalog);+ }+ if (agent.menu_kind !== 'open') return listedModelIds(agent);+ return [...new Set(agent.menu?.checked ?? [])].filter(Boolean);+}++/** A new row's starting point: text in, text out, tools on — the floor for any+ * model a coding-agent backend can actually drive. Reasoning stays off because+ * an empty `reasoning_efforts` is a decision (「omit the effort parameter」),+ * not a gap the UI may pre-fill on the user's behalf. */+export const blankBackendModel = (): BackendModel => ({+ id: '',+ display_name: null,+ origin: 'manual',+ models_dev_id: null,+ context_window: null,+ max_output_tokens: null,+ input_modalities: ['text'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: false,+ reasoning_efforts: [],+ locked: false,+ routeable: true,+});++/**+ * A models.dev match, poured into a draft.+ *+ * `id` is never touched: the backend model id is the routing identity the user+ * typed, and models.dev is a metadata source, not an authority over it. `origin`+ * is passed in rather than derived because the schema defines it as how the row+ * was FIRST created — an existing row keeps its own answer no matter how often+ * it is later re-filled.+ */+export const applyModelsDevMatch = (+ draft: BackendModel,+ match: ModelsDevMatch,+ origin: BackendModelOrigin,+): BackendModel => ({+ ...draft,+ display_name: match.display_name,+ origin,+ models_dev_id: match.models_dev_id,+ context_window: match.context_window,+ max_output_tokens: match.max_output_tokens,+ input_modalities: [...match.input_modalities],+ output_modalities: [...match.output_modalities],+ supports_tools: match.supports_tools,+ supports_reasoning: match.supports_reasoning,+ reasoning_efforts: [...match.reasoning_efforts],+});++const sameList = (left: readonly string[], right: readonly string[]): boolean =>+ left.length === right.length && left.every((value, index) => value === right[index]);++/** Equality over the fields a user owns. `locked` and `routeable` are server+ * projections, so a server that recomputed them has not made the row a user+ * edit — comparing them would turn every reconnect into a spurious write. */+export const sameBackendModel = (left: BackendModel, right: BackendModel): boolean =>+ left.id === right.id+ && left.display_name === right.display_name+ && left.origin === right.origin+ && left.models_dev_id === right.models_dev_id+ && left.context_window === right.context_window+ && left.max_output_tokens === right.max_output_tokens+ && sameList(left.input_modalities, right.input_modalities)+ && sameList(left.output_modalities, right.output_modalities)+ && left.supports_tools === right.supports_tools+ && left.supports_reasoning === right.supports_reasoning+ && sameList(left.reasoning_efforts, right.reasoning_efforts);++export const sameCatalog = (left: readonly BackendModel[], right: readonly BackendModel[]): boolean =>+ left.length === right.length && left.every((model, index) => sameBackendModel(model, right[index]));++export type BackendCatalogIntent = {+ removed: ReadonlySet<string>;+ /** Rows this caller added or changed, keyed by id. */+ upserts: BackendModel[];+ /** The caller's complete desired order. */+ order: string[];+};++/** What the user actually did, expressed as ids rather than a whole list — so a+ * rebase onto a newer server catalog can apply exactly those changes and leave+ * a concurrent editor's untouched row alone. */+export const backendCatalogIntent = (+ baseline: readonly BackendModel[],+ draft: readonly BackendModel[],+): BackendCatalogIntent => {+ const before = new Map(baseline.map((model) => [model.id, model]));+ const drafted = new Set(draft.map((model) => model.id));+ return {+ removed: new Set(baseline.filter((model) => !drafted.has(model.id)).map((model) => model.id)),+ upserts: draft.filter((model) => {+ const previous = before.get(model.id);+ return !previous || !sameBackendModel(previous, model);+ }),+ order: draft.map((model) => model.id),+ };+};++/**+ * The user's edits, replayed onto a newer catalog.+ *+ * A locked row survives every branch: it cannot be removed and it cannot be+ * edited, so a draft that appears to do either is describing a row the server+ * changed underneath it, not a user decision to honor. Rows the caller never+ * named keep their server order at the end, which is what makes a concurrent+ * addition visible instead of silently dropped.+ */+export const applyBackendCatalogIntent = (+ current: readonly BackendModel[],+ intent: BackendCatalogIntent,+): BackendModel[] => {+ const kept = current.filter((model) => model.locked || !intent.removed.has(model.id));+ const byId = new Map(kept.map((model) => [model.id, model]));+ for (const upsert of intent.upserts) {+ const existing = byId.get(upsert.id);+ if (existing?.locked) continue;+ byId.set(+ upsert.id,+ existing ? { ...upsert, locked: existing.locked, routeable: existing.routeable } : upsert,+ );+ }+ const ordered: BackendModel[] = [];+ const placed = new Set<string>();+ for (const id of intent.order) {+ const model = byId.get(id);+ if (!model || placed.has(id)) continue;+ ordered.push(model);+ placed.add(id);+ }+ for (const model of kept) {+ if (placed.has(model.id)) continue;+ ordered.push(byId.get(model.id) ?? model);+ placed.add(model.id);+ }+ return ordered;+};++/** Whether a catalog the server now holds already carries this intent — the+ * only honest answer to an inconclusive PUT, which may have committed. */+export const backendCatalogIntentApplied = (+ current: readonly BackendModel[],+ intent: BackendCatalogIntent,+): boolean => {+ const byId = new Map(current.map((model) => [model.id, model]));+ const intendedIds = new Set(intent.order);+ const intendedOrder = intent.order.filter((id) => byId.has(id));+ const observedOrder = current+ .map((model) => model.id)+ .filter((id) => intendedIds.has(id));+ return [...intent.removed].every((id) => !byId.has(id))+ && intent.upserts.every((upsert) => {+ const landed = byId.get(upsert.id);+ return Boolean(landed) && sameBackendModel(landed as BackendModel, upsert);+ })+ && sameList(observedOrder, intendedOrder);+};++export type BackendCatalogBaseline = {+ agent: AgentSupply;+ /** null when this server predates `catalog_models`: the dialog then reads the+ * legacy projection and refuses to write, rather than sending a baseline it+ * assembled itself. */+ models: BackendModel[] | null;+};++/** The catalog read a mutation is allowed to be based on. Unlike the Source+ * order, a catalog has no second projection to converge against: the list is+ * the state, so one fresh per-backend read is the whole baseline.+ *+ * The response must describe the requested backend in gateway mode. Direct+ * backends use their native provider menu, so accepting that snapshot here+ * would expose an editor whose saved rows are not projected into the runtime. */+export const readBackendCatalogBaseline = async (+ api: Pick<ModelsApi, 'getAgentSources'>,+ backend: AgentBackend,+): Promise<BackendCatalogBaseline> => {+ const agent = await api.getAgentSources(backend);+ if (agent.backend !== backend || agent.mode !== 'hub') {+ throw new Error('Backend model catalog is unavailable');+ }+ return { agent, models: catalogModels(agent) };+};diff --git a/ui/src/components/settings/models/menuBaseline.test.ts b/ui/src/components/settings/models/menuBaseline.test.tsdeleted file mode 100644index 120b07d5a..000000000--- a/ui/src/components/settings/models/menuBaseline.test.ts+++ /dev/null@@ -1,109 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import {- applyOpenCodeMenuIntent,- openCodeMenuIntent,- openCodeMenuIntentApplied,- readOpenCodeMenuBaseline,-} from './menuBaseline';-import type { AgentSupply, Source } from './types';--const source = (id: string, modelIds: string[] = []): Source => ({- id,- last_discovered_at: null,- kind: 'api_key',- vendor: 'openai',- display_name: id,- protocol: 'openai_responses',- supply_channel: 'hub',- billing: 'metered',- state: { status: 'active', retry_at: null, detail_key: null },- models: modelIds.map((modelId) => ({ id: modelId, origin: 'manual', reasoning_efforts: [] })),-});--const agent = (sourceIds: string[]): AgentSupply => ({- backend: 'opencode',- cli_present: true,- mode: 'hub',- menu_kind: 'open',- sources: {- order: sourceIds,- eligibility: sourceIds.map((sourceId) => ({ source_id: sourceId, eligible: true })),- },- menu: { view: 'featured', checked: [] },- routes: {},- standard_vendors: ['openai'],-});--describe('readOpenCodeMenuBaseline', () => {- it('accepts an Agent read bracketed by identical complete Source snapshots', async () => {- const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a']));- const stable = [source('src_a', ['model-a'])];- const readValue = vi.fn().mockResolvedValue(stable);-- const baseline = await readOpenCodeMenuBaseline({ getAgentSources }, { readValue });-- expect(baseline.sources).toEqual(stable);- expect(getAgentSources).toHaveBeenCalledTimes(1);- expect(readValue).toHaveBeenCalledTimes(2);- });-- it('accepts identical Source and model inventories returned in different orders', async () => {- const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a', 'src_b']));- const readValue = vi.fn()- .mockResolvedValueOnce([- source('src_b', ['model-b', 'model-a']),- source('src_a', ['model-c']),- ])- .mockResolvedValueOnce([- source('src_a', ['model-c']),- source('src_b', ['model-a', 'model-b']),- ]);-- const baseline = await readOpenCodeMenuBaseline({ getAgentSources }, { readValue });-- expect(baseline.sources.map(({ id }) => id)).toEqual(['src_a', 'src_b']);- });-- it('rejects Source model content that changes across the Agent read', async () => {- const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a']));- const readValue = vi.fn()- .mockResolvedValueOnce([source('src_a', ['retired-model'])])- .mockResolvedValueOnce([source('src_a')]);-- await expect(readOpenCodeMenuBaseline({ getAgentSources }, { readValue })).rejects.toThrow(- 'did not converge',- );- });-- it('rejects stable Source snapshots with an Agent composition hole', async () => {- const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a', 'src_new']));- const readValue = vi.fn().mockResolvedValue([source('src_a')]);-- await expect(readOpenCodeMenuBaseline({ getAgentSources }, { readValue })).rejects.toThrow(- 'did not converge',- );- });-});--describe('OpenCode menu intent', () => {- it('preserves unrelated current selections and ignores additions no longer selectable', () => {- const intent = openCodeMenuIntent(- ['openai/kept', 'openai/removed'],- ['openai/kept', 'openai/added', 'openai/gone'],- );-- expect(applyOpenCodeMenuIntent(- ['openai/concurrent', 'openai/kept', 'openai/removed'],- intent,- new Set(['openai/added']),- )).toEqual(['openai/concurrent', 'openai/kept', 'openai/added']);- });-- it('recognizes an applied intent while ignoring unrelated concurrent selections', () => {- const intent = openCodeMenuIntent(['openai/a', 'openai/remove'], ['openai/a', 'openai/add']);- expect(openCodeMenuIntentApplied(['openai/a', 'openai/concurrent', 'openai/add'], intent)).toBe(true);- expect(openCodeMenuIntentApplied(['openai/a', 'openai/add', 'openai/remove'], intent)).toBe(false);- expect(openCodeMenuIntentApplied(['openai/a'], intent)).toBe(false);- });-});diff --git a/ui/src/components/settings/models/menuBaseline.ts b/ui/src/components/settings/models/menuBaseline.tsdeleted file mode 100644index 69fedbbcd..000000000--- a/ui/src/components/settings/models/menuBaseline.ts+++ /dev/null@@ -1,83 +0,0 @@-import type { CollectionReadAuthority } from './collectionReadAuthority';-import type { ModelsApi } from './modelsApi';-import { combineSourceOrderReads } from './sourceOrderComposition';-import type { AgentSupply, Source } from './types';--export type OpenCodeMenuBaseline = {- agent: AgentSupply;- sources: Source[];-};--export type OpenCodeMenuIntent = {- added: string[];- removed: Set<string>;-};--const byId = <T extends { id: string }>(left: T, right: T): number =>- left.id.localeCompare(right.id);--const canonicalSourceSnapshot = (sources: Source[]): Source[] =>- sources- .map((source) => ({- ...source,- models: [...source.models].sort(byId),- }))- .sort(byId);--const sameSourceSnapshot = (left: Source[], right: Source[]): boolean =>- JSON.stringify(canonicalSourceSnapshot(left)) === JSON.stringify(canonicalSourceSnapshot(right));--/** The Agent read is authoritative only when the complete Source projection is- * unchanged on both sides of it. Source ids alone cannot detect model edits. */-export const readOpenCodeMenuBaseline = async (- api: Pick<ModelsApi, 'getAgentSources'>,- sourceReads: Pick<CollectionReadAuthority<Source[]>, 'readValue'>,-): Promise<OpenCodeMenuBaseline> => {- const before = await sourceReads.readValue();- const agent = await api.getAgentSources('opencode');- const after = await sourceReads.readValue();- if (agent.backend !== 'opencode' || agent.mode !== 'hub' || agent.menu_kind !== 'open') {- throw new Error('OpenCode Model Hub menu is unavailable');- }- if (!sameSourceSnapshot(before, after) || combineSourceOrderReads(agent, after).hasHole) {- throw new Error('OpenCode Model Hub menu reads did not converge');- }- return { agent, sources: after };-};--export const openCodeMenuIntent = (- baseline: readonly string[],- draft: readonly string[],-): OpenCodeMenuIntent => {- const baselineSet = new Set(baseline);- const draftSet = new Set(draft);- return {- added: draft.filter((id) => !baselineSet.has(id)),- removed: new Set(baseline.filter((id) => !draftSet.has(id))),- };-};--/** Rebase only explicit user edits; unrelated changes in a newer menu survive. */-export const applyOpenCodeMenuIntent = (- current: readonly string[],- intent: OpenCodeMenuIntent,- selectableIds: ReadonlySet<string>,-): string[] => {- const rebased = current.filter((id) => !intent.removed.has(id));- const present = new Set(rebased);- for (const id of intent.added) {- if (!selectableIds.has(id) || present.has(id)) continue;- rebased.push(id);- present.add(id);- }- return rebased;-};--export const openCodeMenuIntentApplied = (- current: readonly string[],- intent: OpenCodeMenuIntent,-): boolean => {- const currentSet = new Set(current);- return intent.added.every((id) => currentSet.has(id))- && [...intent.removed].every((id) => !currentSet.has(id));-};diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex 89e70e461..7dee916ad 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -1875,3 +1875,295 @@.model-hub-legend-swatch--connected_unused {height: 1px;}++/* ── Backend model catalog ────────────────────────────────────────────────+ * The catalog dialog and its row editor. One block for both: they are two+ * halves of one editing surface, and the metrics they share — the 40px control+ * height that puts search and 「Add model」 on one line, the row borders, the+ * chip shape — drift the moment they are declared twice.+ */++.model-hub-catalog-dialog {+ --model-hub-catalog-pad-x: 20px;+ --model-hub-catalog-head-height: 70px;+ --model-hub-catalog-title-size: 18px;+ --model-hub-catalog-body-gap: 12px;+ --model-hub-catalog-control-height: 40px;+ --model-hub-catalog-control-radius: 8px;+ --model-hub-catalog-column-size: 11px;+ --model-hub-catalog-row-height: 62px;+ --model-hub-catalog-row-radius: 10px;+ --model-hub-catalog-row-pad-x: 16px;+ --model-hub-catalog-row-gap: 14px;+ --model-hub-catalog-row-locked-fill: var(--model-hub-wash-05);+ --model-hub-catalog-grip-size: 16px;+ --model-hub-catalog-grip-ink: var(--model-hub-ink-4d);+ --model-hub-catalog-name-size: 13.5px;+ --model-hub-catalog-id-size: 11.5px;+ --model-hub-catalog-action-size: 32px;+ --model-hub-catalog-action-radius: 8px;+ --model-hub-catalog-foot-pad-y: 14px;+ --model-hub-catalog-count-size: 12px;+ --model-hub-catalog-note-size: 11px;+}++.model-hub-catalog-head {+ min-height: var(--model-hub-catalog-head-height);+ padding: 0 var(--model-hub-catalog-pad-x);+}+.model-hub-catalog-title { font-size: var(--model-hub-catalog-title-size); }++.model-hub-catalog-body {+ gap: var(--model-hub-catalog-body-gap);+ padding: 16px var(--model-hub-catalog-pad-x) 0;+}++/* The one height search and 「Add model」 both answer to. */+.model-hub-catalog-control { height: var(--model-hub-catalog-control-height); }++.model-hub-catalog-search {+ padding: 0 12px;+ border: 1px solid var(--border);+ border-radius: var(--model-hub-catalog-control-radius);+ background: var(--background);+}+.model-hub-catalog-search:focus-within {+ border-color: var(--ring);+ box-shadow: 0 0 0 1px var(--ring);+}++.model-hub-catalog-columns {+ padding: 4px 4px 0;+ font-size: var(--model-hub-catalog-column-size);+ font-weight: 600;+ color: var(--muted);+}++.model-hub-catalog-row {+ min-height: var(--model-hub-catalog-row-height);+ padding: 10px var(--model-hub-catalog-row-pad-x);+ border: 1px solid var(--border);+ border-radius: var(--model-hub-catalog-row-radius);+ background: var(--background);+}+.model-hub-catalog-row--locked { background: var(--model-hub-catalog-row-locked-fill); }+.model-hub-catalog-row--static { min-height: 48px; }++.model-hub-catalog-grip {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex: none;+ width: var(--model-hub-catalog-grip-size);+ color: var(--model-hub-catalog-grip-ink);+}+.model-hub-catalog-grip.is-grabbed { color: var(--mint-ink); }+.model-hub-catalog-grip:disabled { color: var(--model-hub-wash-33); }+.model-hub-catalog-grip-icon {+ width: var(--model-hub-catalog-grip-size);+ height: var(--model-hub-catalog-grip-size);+ flex: none;+ color: var(--model-hub-catalog-grip-ink);+}++.model-hub-catalog-name {+ font-size: var(--model-hub-catalog-name-size);+ font-weight: 600;+ color: var(--foreground);+}+.model-hub-catalog-id {+ font-size: var(--model-hub-catalog-id-size);+ color: var(--muted);+}++.model-hub-catalog-action {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: var(--model-hub-catalog-action-size);+ height: var(--model-hub-catalog-action-size);+ border: 1px solid var(--border);+ border-radius: var(--model-hub-catalog-action-radius);+ background: var(--background);+ color: var(--muted);+}+.model-hub-catalog-action:hover:not(:disabled) {+ border-color: var(--border-strong);+ color: var(--foreground);+}+.model-hub-catalog-action:disabled { opacity: 0.5; }+.model-hub-catalog-action--danger { color: var(--model-hub-danger-ink); }+.model-hub-catalog-action--danger:hover:not(:disabled) {+ border-color: var(--model-hub-danger-border);+ background: var(--model-hub-danger-fill);+ color: var(--model-hub-danger-ink);+}++.model-hub-catalog-blocked {+ margin-top: 6px;+ font-size: var(--model-hub-catalog-note-size);+ font-weight: 600;+ color: var(--model-hub-danger-ink);+}+.model-hub-catalog-legacy {+ padding: 0 2px 4px;+ font-size: var(--model-hub-catalog-note-size);+ color: var(--muted);+}++.model-hub-catalog-foot {+ padding: var(--model-hub-catalog-foot-pad-y) var(--model-hub-catalog-pad-x);+}+.model-hub-catalog-count {+ font-size: var(--model-hub-catalog-count-size);+ color: var(--muted);+}++.model-hub-model-editor {+ --model-hub-model-pad-x: 24px;+ --model-hub-model-head-height: 84px;+ --model-hub-model-eyebrow-size: 11px;+ --model-hub-model-title-size: 18px;+ --model-hub-model-section-gap: 20px;+ --model-hub-model-section-size: 11px;+ --model-hub-model-label-size: 12px;+ --model-hub-model-control-height: 40px;+ --model-hub-model-control-radius: 8px;+ --model-hub-model-chip-height: 28px;+ --model-hub-model-chip-radius: 7px;+ --model-hub-model-chip-size: 12px;+ --model-hub-model-note-size: 11px;+ --model-hub-model-strip-fill: var(--model-hub-wash-05);+}++.model-hub-model-editor-head {+ min-height: var(--model-hub-model-head-height);+ padding: 0 var(--model-hub-model-pad-x);+}+.model-hub-model-editor-eyebrow {+ font-size: var(--model-hub-model-eyebrow-size);+ font-weight: 600;+ color: var(--muted);+}+.model-hub-model-editor-title { font-size: var(--model-hub-model-title-size); }++.model-hub-model-editor-body {+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-model-section-gap);+ padding: 18px var(--model-hub-model-pad-x);+}+.model-hub-model-editor-foot { padding: 14px var(--model-hub-model-pad-x); }++.model-hub-model-section {+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.model-hub-model-section-label {+ font-size: var(--model-hub-model-section-size);+ font-weight: 600;+ letter-spacing: 0.04em;+ color: var(--muted);+}+.model-hub-model-field-label {+ font-size: var(--model-hub-model-label-size);+ font-weight: 600;+ color: var(--foreground);+}++.model-hub-model-control { height: var(--model-hub-model-control-height); }++.model-hub-model-token {+ padding: 0 12px;+ border: 1px solid var(--border);+ border-radius: var(--model-hub-model-control-radius);+ background: var(--background);+}+.model-hub-model-token:focus-within {+ border-color: var(--ring);+ box-shadow: 0 0 0 1px var(--ring);+}+.model-hub-model-token.is-invalid { border-color: var(--model-hub-danger-border); }+.model-hub-model-token-suffix {+ font-size: 11.5px;+ color: var(--muted);+}++.model-hub-model-chip {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ height: var(--model-hub-model-chip-height);+ padding: 0 11px;+ border: 1px solid var(--border);+ border-radius: var(--model-hub-model-chip-radius);+ background: var(--background);+ font-size: var(--model-hub-model-chip-size);+ font-weight: 500;+ color: var(--muted);+ white-space: nowrap;+}+.model-hub-model-chip:hover:not(:disabled) { border-color: var(--border-strong); }+.model-hub-model-chip.is-on {+ border-color: var(--model-hub-mint-4d);+ background: var(--model-hub-mint-14);+ color: var(--mint-ink);+}+.model-hub-model-chip--add { border-style: dashed; }+.model-hub-model-chip--custom { padding-right: 6px; }++.model-hub-model-source-strip {+ min-height: var(--model-hub-model-control-height);+ padding: 0 12px;+ border: 1px solid var(--border);+ border-radius: var(--model-hub-model-control-radius);+ background: var(--model-hub-model-strip-fill);+}+.model-hub-model-source-id {+ font-size: 11.5px;+ color: var(--foreground);+}+.model-hub-model-source-note {+ font-size: 11px;+ color: var(--muted);+}+.model-hub-model-source-view {+ font-size: 11.5px;+ font-weight: 600;+ color: var(--mint-ink);+}+.model-hub-model-source-view:disabled { color: var(--muted); }++.model-hub-model-match-list {+ overflow: hidden;+ border: 1px solid var(--border);+ border-radius: var(--model-hub-model-control-radius);+ background: var(--background);+}+.model-hub-model-match {+ padding: 8px 12px;+ border-bottom: 1px solid var(--border);+}+.model-hub-model-match:last-child { border-bottom: none; }+.model-hub-model-match:hover { background: var(--model-hub-wash-05); }+.model-hub-model-match.is-selected { background: var(--model-hub-mint-14); }+.model-hub-model-match-name {+ font-size: 12.5px;+ font-weight: 600;+ color: var(--foreground);+}+.model-hub-model-match-id {+ font-size: 11px;+ color: var(--muted);+}++.model-hub-model-note {+ font-size: var(--model-hub-model-note-size);+ color: var(--muted);+}+.model-hub-model-error {+ font-size: var(--model-hub-model-note-size);+ font-weight: 600;+ color: var(--model-hub-danger-ink);+}diff --git a/ui/src/components/settings/models/modelRows.test.ts b/ui/src/components/settings/models/modelRows.test.tsindex 626fd601e..4e9c3ae5c 100644--- a/ui/src/components/settings/models/modelRows.test.ts+++ b/ui/src/components/settings/models/modelRows.test.ts@@ -1,7 +1,13 @@import { describe, expect, it } from 'vitest';-import { COLLAPSED_MODEL_LIMIT, collapsedModelRows, listedModelIds, modelChainKey, modelChainRequests, modelSupplyState, visibleModelIds } from './modelRows';-import type { AgentSupply } from './types';+import { COLLAPSED_MODEL_LIMIT, collapsedModelRows, modelChainKey, modelChainRequests, modelSupplyState } from './modelRows';+import type { AgentSupply, BackendModel } from './types';++const baseModel: BackendModel = {+ id: '', display_name: null, origin: 'manual', models_dev_id: null, context_window: null, max_output_tokens: null,+ input_modalities: ['text'], output_modalities: ['text'], supports_tools: true, supports_reasoning: false,+ reasoning_efforts: [], locked: false, routeable: true,+};const agent: AgentSupply = {backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed', sources: { order: [], eligibility: [] },@@ -10,10 +16,6 @@ const agent: AgentSupply = {};describe('modelRows', () => {- it('lists backend menu models and every persisted Route row exactly once', () => {- expect(listedModelIds(agent)).toEqual(['builtin', 'route-only']);- });-it('requests chains only for hub model rows', () => {expect(modelChainRequests([agent])).toEqual([{ backend: 'claude', modelId: 'builtin' },@@ -22,13 +24,28 @@ describe('modelRows', () => {expect(modelChainKey('claude', 'builtin')).toBe('claude\u0000builtin');});+ it('enumerates the catalog order, not the legacy projection, once the server sends one', () => {+ const catalogued: AgentSupply = {+ ...agent,+ catalog_models: [+ { ...baseModel, id: 'second' },+ { ...baseModel, id: 'first' },+ { ...baseModel, id: 'default', locked: true, routeable: false },+ ],+ };++ expect(collapsedModelRows(catalogued)).toEqual({ visible: ['second', 'first'], hidden: [] });+ expect(modelChainRequests([catalogued])).toEqual([+ { backend: 'claude', modelId: 'second' },+ { backend: 'claude', modelId: 'first' },+ ]);+ });+it('keeps dormant OpenCode routes hidden until their model is selected again', () => {const open = { ...agent, backend: 'opencode' as const, menu_kind: 'open' as const, builtin_models: null, menu: { view: 'featured' as const, checked: [] } };- expect(visibleModelIds(open)).toEqual([]);expect(collapsedModelRows(open)).toEqual({ visible: [], hidden: [] });expect(modelChainRequests([open])).toEqual([]);- expect(visibleModelIds({ ...open, menu: { view: 'featured', checked: ['route-only'] } })).toEqual(['route-only']);});});diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.tsindex 4c27e097f..7122fe223 100644--- a/ui/src/components/settings/models/modelRows.ts+++ b/ui/src/components/settings/models/modelRows.ts@@ -1,3 +1,4 @@+import { catalogModelIds } from './backendCatalog';import { eligibleSources } from './eligibility';import { buildIdentifier } from './menus/identifiers';import type { RegionRead } from './regionRead';@@ -55,28 +56,6 @@ export function modelHasOffOrderSupplier(agent: AgentSupply, sources: Source[],);}-/** The model list the server says this backend exposes. */-export function listedModelIds(agent: AgentSupply): string[] {- const primary = agent.menu_kind === 'fixed' ? agent.builtin_models ?? [] : agent.menu?.checked ?? [];- const extras = [- ...(agent.selected_model_id ? [agent.selected_model_id] : []),- ...(agent.model_supply ?? []).map((model) => model.model_id),- ...Object.keys(agent.routes ?? {}),- ];- const seen = new Set<string>();- return [...primary, ...extras].filter((modelId) => {- if (!modelId || seen.has(modelId)) return false;- seen.add(modelId);- return true;- });-}--/** OpenCode rows are its saved menu, not dormant routes left behind by an earlier selection. */-export function visibleModelIds(agent: AgentSupply): string[] {- if (agent.menu_kind !== 'open') return listedModelIds(agent);- return [...new Set(agent.menu?.checked ?? [])].filter(Boolean);-}-export const COLLAPSED_MODEL_LIMIT = 6;export type CollapsedModelRows = {@@ -94,9 +73,9 @@ export function modelSupplyState(agent: AgentSupply, modelId: string): ModelSuppreturn supply.has_runnable_hop ? 'available' : 'paused';}-/** Keep the backend menu order stable while bounding each collapsed group. */+/** Keep the catalog order stable while bounding each collapsed group. */export function collapsedModelRows(agent: AgentSupply, expanded = false): CollapsedModelRows {- const models = visibleModelIds(agent);+ const models = catalogModelIds(agent);if (expanded) return { visible: models, hidden: [] };return {visible: models.slice(0, COLLAPSED_MODEL_LIMIT),@@ -109,7 +88,7 @@ export function modelChainRequests(agents: AgentSupply[]): ModelChainRequest[] {const requests = new Map<string, ModelChainRequest>();for (const agent of agents) {if (agent.mode !== 'hub') continue;- for (const modelId of visibleModelIds(agent)) {+ for (const modelId of catalogModelIds(agent)) {const key = modelChainKey(agent.backend, modelId);if (!requests.has(key)) requests.set(key, { backend: agent.backend, modelId });}diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 8aa936672..f5087bbf3 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -12,16 +12,17 @@ import type {AgentChain,AgentChainMutation,AgentChainPut,- AgentMenu,AgentMode,AgentSourcesPut,AgentSupply,ApiKeySourceCreate,ApiKeySourceObservation,+ BackendModelsPut,CredentialReplace,CustomModelCreate,MigrationApplyResult,MigrationScan,+ ModelsDevMatch,OAuthFlow,ProbeResult,ResolutionEvent,@@ -127,8 +128,14 @@ export type ModelsApi = {/** One real request through the chain. Hub mode only, same reason. */probeAgent(backend: AgentBackend, model?: string): Promise<ProbeResult>;setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;- /** Apply the change between baseline and menu atomically to the latest saved menu. */- putMenu(baseline: AgentMenu, menu: AgentMenu): Promise<AgentSupply>;+ /** Apply the difference between `baseline` and `models` to the latest saved+ * catalog. The echoed `AgentSupply.catalog_models` is canonical — including+ * the order, the server-derived `locked`/`routeable`, and any concurrent+ * edit this caller never saw. */+ putAgentModels(backend: AgentBackend, body: BackendModelsPut): Promise<AgentSupply>;+ /** Normalized models.dev candidates for a free-text query. A pure read: it+ * persists nothing, so a fill the user abandons leaves no trace. */+ searchModelsDev(query: string, signal?: AbortSignal): Promise<ModelsDevMatch[]>;addCustomModel(sourceId: string, draft: CustomModelCreate): Promise<Source>;updateModelReasoningEfforts(sourceId: string, modelId: string, reasoningEfforts: string[]): Promise<Source>;deleteCustomModel(sourceId: string, modelId: string, confirmation?: GuardConfirmation): Promise<Source>;@@ -467,7 +474,11 @@ export const modelsApi: ModelsApi = {putAgentChain: (backend, model, body) => call<AgentChainMutation>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`, jsonInit('PUT', body)),probeAgent: (backend, model) => call<{ probe: ProbeResult }>(`/api/models/agents/${backend}/probe`, jsonInit('POST', model ? { model } : {})).then((r) => r.probe),setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),- putMenu: (baseline, menu) => call<{ agent?: AgentSupply } & AgentSupply>('/api/models/agents/opencode/menu', jsonInit('PUT', { baseline, menu })).then((r) => (r.agent ?? r) as AgentSupply),+ putAgentModels: (backend, body) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/models`, jsonInit('PUT', body)).then((r) => (r.agent ?? r) as AgentSupply),+ searchModelsDev: (query, signal) => call<{ matches: ModelsDevMatch[] }>(+ `/api/models/catalog/models-dev?query=${encodeURIComponent(query)}`,+ { signal },+ ).then((r) => r.matches ?? []),addCustomModel: (sourceId, draft) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models`, jsonInit('POST', draft)).then((r) => (r.source ?? r) as Source),updateModelReasoningEfforts: (sourceId, modelId, reasoningEfforts) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('PATCH', { reasoning_efforts: reasoningEfforts })).then((r) => (r.source ?? r) as Source),deleteCustomModel: (sourceId, modelId, confirmation) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('DELETE', confirmation ?? {})).then((r) => (r.source ?? r) as Source),diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsindex 0e2eb5f9e..f5a1cf663 100644--- a/ui/src/components/settings/models/serverCopy.test.ts+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -12,6 +12,8 @@ import { describe, expect, it } from 'vitest';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';import {+ catalogSaveFailureKey,+ modelsDevFillFailureKey,NATIVE_LOGIN_IN_PROGRESS_FAILURE,NATIVE_SUBSCRIPTION_EXISTS_FAILURE,oauthFailureKey,@@ -149,3 +151,75 @@ describe('oauthStartFailureKey', () => {expect(oauthStartFailureKey('modelHub.errors.engine_down')).toBe('settings.models.addSub.error.engineDown');});});++describe('catalogSaveFailureKey', () => {+ // Every refusal `PUT /api/models/agents/<backend>/models` can answer with, and+ // the sentence that tells the user what to do about it. Spelled out here rather+ // than imported from the module, so this fails when the UI's table and the+ // service's taxonomy drift apart.+ const REFUSALS = [+ ['backend_model_in_route', 'saveRouted'],+ ['backend_model_conflict', 'saveConflict'],+ ['backend_model_id_prefix', 'saveIdPrefix'],+ ['backend_model_id_invalid', 'saveIdInvalid'],+ ['backend_model_duplicate', 'saveDuplicate'],+ ['backend_model_locked', 'saveLocked'],+ ['backend_model_catalog_invalid', 'saveInvalid'],+ ] as const;++ it.each(REFUSALS)('renders %s as copy, not as a key, in both locales', (code, key) => {+ const resolved = catalogSaveFailureKey(`modelHub.errors.${code}`);+ expect(resolved).toBe(`settings.models.gateway.catalog.${key}`);+ for (const lng of ['en', 'zh'] as const) {+ // Ours, so it must translate outright — a missing entry would reach the+ // user as the key itself.+ const text = t(lng)(resolved, { defaultValue: '' }) as string;+ expect(text, `${lng}: ${resolved}`).not.toBe('');+ expect(text).not.toContain('settings.models');+ }+ });++ it('gives each refusal a next step of its own', () => {+ // Seven codes pointing at one sentence would be the generic fallback wearing+ // seven names; the taxonomy exists because the actions differ.+ const texts = REFUSALS.map(([code]) => t('en')(catalogSaveFailureKey(`modelHub.errors.${code}`)) as string);+ expect(new Set(texts).size).toBe(REFUSALS.length);+ expect(texts).not.toContain(t('en')('settings.models.gateway.catalog.saveFailed'));+ });++ it('asks for a re-add where the ID rule is broken, because the field is read-only', () => {+ // Edit mode keeps the backend model id read-only, so 「fix the ID」 would be+ // advice this dialog refuses to take.+ const prefix = catalogSaveFailureKey('modelHub.errors.backend_model_id_prefix');+ expect(t('en')(prefix)).toMatch(/add it again/i);+ expect(t('zh')(prefix)).toContain('重新添加');+ const invalid = catalogSaveFailureKey('modelHub.errors.backend_model_id_invalid');+ expect(t('en')(invalid)).toMatch(/add it again/i);+ expect(t('zh')(invalid)).toContain('重新添加');+ });++ it('never passes an unrecognized server detail through as copy', () => {+ // `modelHub.errors.*` keys live in the backend bundle, so a code this UI does+ // not know would render as a machine string if it reached i18next.+ for (const detail of [undefined, 'modelHub.errors.some_future_code', 'engine_down']) {+ expect(catalogSaveFailureKey(detail)).toBe('settings.models.gateway.catalog.saveFailed');+ }+ });+});++describe('modelsDevFillFailureKey', () => {+ it('separates an upstream catalog outage from a lookup that simply failed', () => {+ // The one cause that is not about this machine, and the one where retrying is+ // the wrong advice: every field the fill would have set is typeable by hand.+ const down = modelsDevFillFailureKey('modelHub.errors.models_dev_unavailable');+ expect(down).toBe('settings.models.gateway.modelEditor.fillUnavailable');+ expect(t('en')(down)).toMatch(/by hand/i);+ expect(t('zh')(down)).toContain('手动填写');+ });++ it('keeps every other cause on the plain unreachable line', () => {+ for (const detail of [undefined, 'engine_down', 'modelHub.errors.some_future_code']) {+ expect(modelsDevFillFailureKey(detail)).toBe('settings.models.gateway.modelEditor.fillFailed');+ }+ });+});diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.tsindex 5d38e89c0..aa85fe7f9 100644--- a/ui/src/components/settings/models/serverCopy.ts+++ b/ui/src/components/settings/models/serverCopy.ts@@ -99,3 +99,53 @@ export const oauthStartFailureKey = (code: string | undefined): string =>: code === 'engine_down' || code === 'modelHub.errors.engine_down'? 'settings.models.addSub.error.engineDown': 'settings.models.addSub.error.startFailed';++/**+ * Why a backend model catalog refused to save.+ *+ * Each code names a different next step — fix an id, drop a duplicate, clear a+ * route, re-read a list the server owns — so collapsing them into one sentence+ * would leave the user retrying an edit that cannot succeed. The table is the+ * closed set this UI has copy for; anything else falls to the generic sentence,+ * because a `modelHub.errors.*` key lives in the backend bundle and would+ * otherwise render to the user as a machine string.+ */+const CATALOG_SAVE_FAILURE_COPY: Readonly<Record<string, string>> = {+ 'modelHub.errors.backend_model_in_route': 'settings.models.gateway.catalog.saveRouted',+ 'modelHub.errors.backend_model_conflict': 'settings.models.gateway.catalog.saveConflict',+ 'modelHub.errors.backend_model_id_prefix': 'settings.models.gateway.catalog.saveIdPrefix',+ 'modelHub.errors.backend_model_id_invalid': 'settings.models.gateway.catalog.saveIdInvalid',+ 'modelHub.errors.backend_model_duplicate': 'settings.models.gateway.catalog.saveDuplicate',+ 'modelHub.errors.backend_model_locked': 'settings.models.gateway.catalog.saveLocked',+ 'modelHub.errors.backend_model_catalog_invalid': 'settings.models.gateway.catalog.saveInvalid',+};++export const catalogSaveFailureKey = (detail: string | undefined): string =>+ CATALOG_SAVE_FAILURE_COPY[detail ?? ''] ?? 'settings.models.gateway.catalog.saveFailed';++/**+ * Whether a refused save is the one the server can answer AFTER it has already+ * written.+ *+ * `set_agent_models` commits the catalog and only then asks the backend to load+ * it, so `engine_down` is the single code that arrives with the user's rows on+ * disk and out of use. Every other code refused the write itself — a re-read+ * that happens to match the draft only means someone else arrived at the same+ * list, and reporting THAT as 「stored but not loaded」 would describe a write+ * this server never made.+ */+export const catalogSaveLeftUnloaded = (code: string | undefined, detail: string | undefined): boolean =>+ code === 'engine_down' || detail === 'modelHub.errors.engine_down';++/**+ * Why a models.dev fill produced nothing.+ *+ * The server names the one cause that is not about this machine: the upstream+ * catalog is down. That distinction is worth copy of its own, because the user's+ * way forward is to stop retrying and type the fields in — every one of them is+ * editable whether or not a fill ever succeeds.+ */+export const modelsDevFillFailureKey = (detail: string | undefined): string =>+ detail === 'modelHub.errors.models_dev_unavailable'+ ? 'settings.models.gateway.modelEditor.fillUnavailable'+ : 'settings.models.gateway.modelEditor.fillFailed';diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 59b25ed9f..106873f4d 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -145,6 +145,77 @@ export type AgentMenu = {checked: string[];};+// ── backend-model.schema.json ───────────────────────────────────────────+/** How the row was first created. User edits stay authoritative afterwards,+ * which is why this never gates editability — only `locked` does. */+export type BackendModelOrigin = 'builtin' | 'models_dev' | 'manual';+export const BACKEND_MODEL_INPUT_MODALITIES = ['text', 'image', 'audio', 'video', 'pdf'] as const;+export type BackendModelInputModality = (typeof BACKEND_MODEL_INPUT_MODALITIES)[number];+/** One member shorter than the input vocabulary: the schema declares no `pdf`+ * output. Mirrored as two lists rather than one filtered at the call site, so a+ * future divergence is a contract edit and not a UI condition. */+export const BACKEND_MODEL_OUTPUT_MODALITIES = ['text', 'image', 'audio', 'video'] as const;+export type BackendModelOutputModality = (typeof BACKEND_MODEL_OUTPUT_MODALITIES)[number];+export const BACKEND_MODEL_ID_MAX_LENGTH = 256 as const;+export const BACKEND_MODEL_EFFORT_MAX_LENGTH = 64 as const;++/** One model a backend Agent exposes: backend menu metadata, never upstream+ * inventory and never a Route. The catalog deliberately holds no Source id,+ * upstream model id, priority or fallback — those stay with the Route. */+export type BackendModel = {+ /** The exact identifier the backend Agent emits. OpenCode uses provider/model. */+ id: string;+ display_name: string | null;+ origin: BackendModelOrigin;+ /** The provider/model identity chosen on models.dev, null for a manual row. */+ models_dev_id: string | null;+ context_window: number | null;+ max_output_tokens: number | null;+ input_modalities: BackendModelInputModality[];+ output_modalities: BackendModelOutputModality[];+ /** Tri-state. `null` is not `false`: the server omits the capability from the+ * backend projection entirely, leaving the backend's own default in force.+ * Every shipped builtin row starts here, so the editor must never state a+ * value the user did not. */+ supports_tools: boolean | null;+ supports_reasoning: boolean | null;+ /** Sent verbatim upstream. `[]` means the backend omits the effort parameter,+ * which is a decision — not an absence the UI may fill in. */+ reasoning_efforts: string[];+ /** Server-derived: visible, but not editable, removable or reorderable. */+ locked: boolean;+ /** Server-derived: false only for a backend-owned selector such as Claude+ * Code's `Default`, which never names a Route key. */+ routeable: boolean;+};++/** `baseline` is the last full list this caller observed; `models` is its+ * desired replacement. The server applies the difference to the latest saved+ * list, so a concurrent editor's unrelated row survives. */+export type BackendModelsPut = {+ baseline: BackendModel[];+ models: BackendModel[];+};++/** One normalized models.dev candidate. Metadata only: choosing it fills the+ * editor's fields and persists nothing until the catalog itself is saved. */+export type ModelsDevMatch = {+ provider_id: string;+ provider_name: string;+ model_id: string;+ models_dev_id: string;+ display_name: string | null;+ context_window: number | null;+ max_output_tokens: number | null;+ input_modalities: BackendModelInputModality[];+ output_modalities: BackendModelOutputModality[];+ /** Null when models.dev does not state the capability, which a fill carries+ * through rather than resolving to `false` on the model's behalf. */+ supports_tools: boolean | null;+ supports_reasoning: boolean | null;+ reasoning_efforts: string[];+};+/** Why a source cannot serve this backend at all. A closed vocabulary — a new* cause ships its enum member and its locale copy in the same change. */export type EligibilityReasonKey =@@ -251,6 +322,11 @@ export type AgentSupply = {/** AC-9 attribution source. Always present; every entry's `supply_status` is* null in direct mode. */named_agents?: NamedAgentSupply[];+ /** The one editable model catalog for this backend. Its ORDER is the Agent+ * menu order. Presence-gated: a server that predates backend model catalogs+ * omits it, and the UI then falls back to `builtin_models`/`menu` for the+ * rolling-upgrade window rather than synthesizing a payload shape. */+ catalog_models?: BackendModel[] | null;menu?: AgentMenu | null;/** v1.2 read-only projection: fixed-menu backends only — the backend's real* built-in model ids (from vibe/backend_model_catalog.py). null for open-menudiff --git a/ui/src/components/workbench/AgentRoutePicker.test.tsx b/ui/src/components/workbench/AgentRoutePicker.test.tsxindex f1b731970..7425f3f7e 100644--- a/ui/src/components/workbench/AgentRoutePicker.test.tsx+++ b/ui/src/components/workbench/AgentRoutePicker.test.tsx@@ -19,6 +19,11 @@ vi.mock('../../context/ApiContext', async (importOriginal) => ({useApi: () => ({}),}));+// What the catalog answers for this render. A Hub catalog states one entry per+// model, so a test can say "this model has no efforts" the same way the server+// does — and an empty default keeps the backend fallback in play.+let catalogReasoning: Record<string, { value: string; label: string }[]> = {};+// The model column is fetched per backend; serve it synchronously so the test is// about the route state, not about the catalog request.vi.mock('../../lib/backendModels', async (importOriginal) => ({@@ -36,7 +41,7 @@ vi.mock('../../lib/backendModels', async (importOriginal) => ({onLoaded({models: ['sonnet', 'opus'],modelLabels: {},- reasoningOptions: {},+ reasoningOptions: catalogReasoning,catalogRefreshPending: false,});return () => {};@@ -116,7 +121,10 @@ const openMenu = async (user: ReturnType<typeof userEvent.setup>) => {};describe('AgentRoutePicker', () => {- afterEach(cleanup);+ afterEach(() => {+ cleanup();+ catalogReasoning = {};+ });it('highlights the pick while the owner write is still in flight', async () => {const user = userEvent.setup();@@ -163,6 +171,37 @@ describe('AgentRoutePicker', () => {expect(screen.getByLabelText('common.saving')).toBeTruthy();});+ it('clears the effort when the catalog says the picked model has none', async () => {+ // "No efforts" is an answer the catalog gives, not a gap: the effort column+ // empties, so the route must stop carrying one instead of dispatching an+ // effort this model cannot run.+ catalogReasoning = { opus: [], sonnet: [{ value: 'low', label: 'Low' }] };+ const user = userEvent.setup();+ const onWrite = vi.fn();+ render(<OptimisticOwner onWrite={onWrite} />);+ await openMenu(user);++ await user.click(screen.getByRole('button', { name: 'opus' }));++ expect(onWrite).toHaveBeenCalledExactlyOnceWith({ model: 'opus', reasoning_effort: null });+ expect(screen.queryByRole('button', { name: 'chat.picker.effortOptions.low' })).toBeNull();+ // Two-column cascade: a heading with nothing under it would look like a+ // list that failed to load rather than a model that has no efforts.+ expect(screen.queryByText('chat.picker.effort')).toBeNull();+ });++ it('keeps the effort column for a model the catalog gives efforts', async () => {+ catalogReasoning = { opus: [{ value: 'low', label: 'Low' }] };+ const user = userEvent.setup();+ render(<OptimisticOwner onWrite={vi.fn()} />);+ await openMenu(user);++ await user.click(screen.getByRole('button', { name: 'opus' }));++ expect(screen.getByText('chat.picker.effort')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'chat.picker.effortOptions.low' })).toBeTruthy();+ });+it('pins the whole inherited route when a model is picked on a default route', async () => {const user = userEvent.setup();const onWrite = vi.fn();diff --git a/ui/src/components/workbench/AgentRoutePicker.tsx b/ui/src/components/workbench/AgentRoutePicker.tsxindex af93f76a8..c899a5f64 100644--- a/ui/src/components/workbench/AgentRoutePicker.tsx+++ b/ui/src/components/workbench/AgentRoutePicker.tsx@@ -308,10 +308,17 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({</Button></PopoverTrigger><PopoverContent align={align} className="z-50 max-h-[70vh] w-[680px] max-w-[92vw] overflow-y-auto p-0">- {/* On phones the three columns stack into one scrollable list; sm+ keeps- the side-by-side cascading menu. Model gets the widest track (long ids)- and Effort the narrowest (short labels). */}- <div className="grid grid-cols-1 divide-y divide-border sm:grid-cols-[1fr_1.35fr_0.7fr] sm:divide-x sm:divide-y-0">+ {/* On phones the columns stack into one scrollable list; sm+ keeps the+ side-by-side cascading menu. Model gets the widest track (long ids)+ and Effort the narrowest (short labels). When the picked model states+ no efforts the menu is a two-column cascade: an Effort column with a+ heading and nothing under it would look like a list that failed. */}+ <div+ className={clsx(+ 'grid grid-cols-1 divide-y divide-border sm:divide-x sm:divide-y-0',+ effortOptions.length > 0 ? 'sm:grid-cols-[1fr_1.35fr_0.7fr]' : 'sm:grid-cols-[1fr_1.35fr]',+ )}+ >{/* Column 1 — Agent */}<RouteColumn title={t('chat.picker.agent')}>{/* Default option: clears the route back to inherited defaults after@@ -435,19 +442,21 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({</RouteColumn>{/* Column 3 — Effort (uses per-model catalog entries when available) */}- <RouteColumn title={t('chat.picker.effort')}>- {effortOptions.map((opt) => (- <RouteItem- key={opt}- active={opt === currentEffort}- onClick={() => applyPatch({ reasoning_effort: opt })}- >- <span className="flex-1 capitalize">- {t(`chat.picker.effortOptions.${opt}`, { defaultValue: opt })}- </span>- </RouteItem>- ))}- </RouteColumn>+ {effortOptions.length > 0 && (+ <RouteColumn title={t('chat.picker.effort')}>+ {effortOptions.map((opt) => (+ <RouteItem+ key={opt}+ active={opt === currentEffort}+ onClick={() => applyPatch({ reasoning_effort: opt })}+ >+ <span className="flex-1 capitalize">+ {t(`chat.picker.effortOptions.${opt}`, { defaultValue: opt })}+ </span>+ </RouteItem>+ ))}+ </RouteColumn>+ )}</div></PopoverContent></Popover>diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsxindex f832ac5d3..b841266f5 100644--- a/ui/src/components/workbench/AgentsPage.test.tsx+++ b/ui/src/components/workbench/AgentsPage.test.tsx@@ -38,9 +38,18 @@ vi.mock('../../context/ApiContext', async () => {vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast }) }));vi.mock('./CapabilityTabs', () => ({ CapabilityTabs: () => null }));+// What the catalog answers for this render. The default is an empty list, which+// is every test that types its own model; a test about per-model efforts states+// the entries the Hub catalog would have projected.+type FakeModelCatalog = {+ models: string[];+ reasoningOptions?: Record<string, { value: string; label: string }[]>;+};+let modelCatalog: FakeModelCatalog = { models: [] };+vi.mock('../../lib/backendModels', async () => ({- loadBackendModelsWithRefresh: (_api: unknown, _backend: string, onLoaded: (payload: { models: string[] }) => void) => {- onLoaded({ models: [] });+ loadBackendModelsWithRefresh: (_api: unknown, _backend: string, onLoaded: (payload: FakeModelCatalog) => void) => {+ onLoaded(modelCatalog);return () => {};},}));@@ -159,6 +168,7 @@ afterEach(() => {apiRef.current = null;handlers = null;showToast.mockReset();+ modelCatalog = { models: [] };});describe('AgentsPage load requests follow the rank that can serve them', () => {@@ -1367,6 +1377,111 @@ describe('AgentsPage reconnect reconciliation', () => {expect(updateVibeAgent).toHaveBeenCalledWith('agent-a', { system_prompt: 'saved prompt' });});+ it('clears the reasoning effort in the same patch as a model that has none', async () => {+ // The record must never keep an effort the selected model cannot run, and+ // "no efforts at all" is the case a fallback-shaped fix misses: there is no+ // valid value to swap in, so the field has to be cleared instead.+ modelCatalog = { models: [], reasoningOptions: { 'no-effort-model': [] } };+ const initial = {+ ...brief('agent-a', 'description'),+ model: 'old-model',+ reasoning_effort: 'medium' as const,+ };+ // What the server holds once the patch lands: the new model, and no effort.+ const cleared = fullAgent({ ...initial, model: 'no-effort-model' }, 'initial prompt');+ cleared.agent.reasoning_effort = null;+ const getVibeAgent = vi.fn()+ .mockResolvedValueOnce(fullAgent(initial, 'initial prompt'))+ .mockResolvedValue(cleared);+ const updateVibeAgent = vi.fn().mockResolvedValue({ ok: true });+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), getVibeAgent, undefined, undefined, updateVibeAgent);+ renderPage(api, { canManageAgents: true });++ await waitFor(() => expect(screen.getByDisplayValue('description')).toBeTruthy());+ expect(screen.getByRole('button', { name: 'medium', exact: true }).className).toContain('bg-mint-soft');++ fireEvent.click(screen.getByRole('combobox'));+ fireEvent.change(screen.getByPlaceholderText('Search...'), { target: { value: 'no-effort-model' } });+ fireEvent.click(screen.getByText('Use "no-effort-model"'));++ await waitFor(() => expect(updateVibeAgent).toHaveBeenCalledWith('agent-a', {+ model: 'no-effort-model',+ reasoning_effort: null,+ }));+ expect(updateVibeAgent).toHaveBeenCalledTimes(1);+ // The whole field goes, not just its segments: an empty outline under a+ // heading reads as a control that failed to load.+ expect(screen.queryByRole('button', { name: 'medium', exact: true })).toBeNull();+ expect(screen.queryByText('agents.detail.effort')).toBeNull();+ });++ it('keeps an unset server effort unset instead of lighting a default', async () => {+ // The reported inconsistency: the panel showed `medium` for an agent the+ // server held at null, so switching models sent only `model` and the record+ // stayed effort-less while the UI claimed otherwise.+ modelCatalog = {+ models: [],+ reasoningOptions: {+ 'no-effort-model': [],+ 'reasoning-model': [{ value: 'medium', label: 'Medium' }],+ },+ };+ const initial = {+ ...brief('agent-a', 'description'),+ model: 'no-effort-model',+ reasoning_effort: null,+ };+ const full = fullAgent(initial, 'initial prompt');+ full.agent.reasoning_effort = null;+ // What the server holds after the patch: the new model, and still no effort.+ const switched = fullAgent({ ...initial, model: 'reasoning-model' }, 'initial prompt');+ switched.agent.reasoning_effort = null;+ const getVibeAgent = vi.fn().mockResolvedValueOnce(full).mockResolvedValue(switched);+ const updateVibeAgent = vi.fn().mockResolvedValue({ ok: true });+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), getVibeAgent, undefined, undefined, updateVibeAgent);+ renderPage(api, { canManageAgents: true });++ await waitFor(() => expect(screen.getByDisplayValue('description')).toBeTruthy());+ expect(screen.queryByText('agents.detail.effort')).toBeNull();++ fireEvent.click(screen.getByRole('combobox'));+ fireEvent.change(screen.getByPlaceholderText('Search...'), { target: { value: 'reasoning-model' } });+ fireEvent.click(screen.getByText('Use "reasoning-model"'));++ await waitFor(() => expect(updateVibeAgent).toHaveBeenCalledWith('agent-a', { model: 'reasoning-model' }));+ // The column is back because this model has one, but no segment is chosen:+ // the server holds no effort, and the panel may not invent one.+ expect(screen.getByText('agents.detail.effort')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'medium', exact: true }).className).not.toContain('bg-mint-soft');+ });++ it('keeps a still-valid effort untouched when the model changes', async () => {+ modelCatalog = {+ models: [],+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }] },+ };+ const initial = {+ ...brief('agent-a', 'description'),+ model: 'old-model',+ reasoning_effort: 'medium' as const,+ };+ const getVibeAgent = vi.fn().mockResolvedValue(fullAgent(initial, 'initial prompt'));+ const updateVibeAgent = vi.fn().mockResolvedValue({ ok: true });+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), getVibeAgent, undefined, undefined, updateVibeAgent);+ renderPage(api, { canManageAgents: true });++ await waitFor(() => expect(screen.getByDisplayValue('description')).toBeTruthy());+ fireEvent.click(screen.getByRole('combobox'));+ fireEvent.change(screen.getByPlaceholderText('Search...'), { target: { value: 'reasoning-model' } });+ fireEvent.click(screen.getByText('Use "reasoning-model"'));++ // A model switch is not an effort edit: only the field the user changed goes.+ await waitFor(() => expect(updateVibeAgent).toHaveBeenCalledWith('agent-a', { model: 'reasoning-model' }));+ // A model that has an effort keeps the field, still showing the current one.+ expect(screen.getByText('agents.detail.effort')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'medium', exact: true }).className).toContain('bg-mint-soft');+ });+it.each(['model', 'effort'] as const)('restores the authoritative value after a failed %s mutation', async (field) => {const initial = {...brief('agent-a', 'description'),diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex 23449afee..f42998944 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -1909,7 +1909,10 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, onconst [settingDefault, setSettingDefault] = useState(false);const [description, setDescription] = useState(agent.description ?? '');const [model, setModel] = useState(agent.model ?? '');- const [effort, setEffort] = useState(agent.reasoning_effort ?? 'medium');+ // The panel shows what the server holds, so an unset effort stays unset. A+ // `?? 'medium'` here would light a segment nobody chose, and switching models+ // would then send only `model` while the record kept no effort at all.+ const [effort, setEffort] = useState<string | null>(agent.reasoning_effort ?? null);const [systemPrompt, setSystemPrompt] = useState(agent.system_prompt ?? '');const [systemPromptOpen, setSystemPromptOpen] = useState(false);const [editorOpen, setEditorOpen] = useState(false);@@ -1951,12 +1954,19 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on>({});const [running, setRunning] = useState(false);- const serverSnapshotRef = useRef({+ const serverSnapshotRef = useRef<{+ id: string;+ name: string;+ description: string;+ model: string;+ effort: string | null;+ systemPrompt: string;+ }>({id: agent.id,name: agent.name,description: agent.description ?? '',model: agent.model ?? '',- effort: agent.reasoning_effort ?? 'medium',+ effort: agent.reasoning_effort ?? null,systemPrompt: agent.system_prompt ?? '',});@@ -1971,7 +1981,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, onname: agent.name,description: agent.description ?? '',model: agent.model ?? '',- effort: agent.reasoning_effort ?? 'medium',+ effort: agent.reasoning_effort ?? null,systemPrompt: agent.system_prompt ?? '',};const snapshotChanged =@@ -2086,7 +2096,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, onif (field === 'name') setName(snapshot.name);if (field === 'description') setDescription(snapshot.description ?? '');if (field === 'model') setModel(snapshot.model ?? '');- if (field === 'effort') setEffort(snapshot.effort ?? 'medium');+ if (field === 'effort') setEffort(snapshot.effort);if (field === 'systemPrompt') {const value = snapshot.systemPrompt ?? '';setSystemPrompt(value);@@ -2110,7 +2120,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, onif (field === 'name') setName(snapshot.name);if (field === 'description') setDescription(snapshot.description ?? '');if (field === 'model') setModel(snapshot.model ?? '');- if (field === 'effort') setEffort(snapshot.effort ?? 'medium');+ if (field === 'effort') setEffort(snapshot.effort);if (field === 'systemPrompt') setSystemPrompt(snapshot.systemPrompt ?? '');}throw err;@@ -2341,15 +2351,18 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on// keeps an effort the model can't run (Codex P2).const opts = resolveEffortOptions(agent.backend, value, reasoningOptions);if (effort && !opts.includes(effort)) {- const fallback = opts.includes('medium') ? 'medium' : opts[0];- if (fallback) {- markFieldEdit('effort');- markFieldSubmitted('effort');- setEffort(fallback);- patch.reasoning_effort = fallback;- }+ // No valid option is itself a valid answer: a model whose catalog+ // row states no efforts must clear the field, not keep the old+ // value because there was nothing to replace it with.+ const fallback = opts.includes('medium') ? 'medium' : opts[0] ?? null;+ markFieldEdit('effort');+ markFieldSubmitted('effort');+ setEffort(fallback);+ patch.reasoning_effort = fallback;}- consumeBackgroundMutation(submitFields(patch, patch.reasoning_effort ? ['model', 'effort'] : ['model']));+ consumeBackgroundMutation(+ submitFields(patch, 'reasoning_effort' in patch ? ['model', 'effort'] : ['model']),+ );}}placeholder={t('agents.detail.modelPlaceholder')}emptyText={t('agents.detail.modelEmpty')}@@ -2358,7 +2371,10 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on)}</Field>- {/* Reasoning effort — design.pen LsjxT */}+ {/* Reasoning effort — design.pen LsjxT. A model whose catalog row states+ no efforts has nothing to choose, so the field is absent rather than an+ empty outline the user would read as a control that failed to load. */}+ {effortOptions.length > 0 && (<Field label={t('agents.detail.effort')}><divclassName="grid gap-0.5 rounded-lg border border-border-strong bg-surface-2 p-0.5"@@ -2390,6 +2406,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on})}</div></Field>+ )}{/* System prompt — design.pen y3mRv: collapsed by default. Tokenestimate (cheap heuristic, see lib/tokenEstimate) replaces thediff --git a/ui/src/components/workbench/NewAgentDialog.test.tsx b/ui/src/components/workbench/NewAgentDialog.test.tsxnew file mode 100644index 000000000..64d230f66--- /dev/null+++ b/ui/src/components/workbench/NewAgentDialog.test.tsx@@ -0,0 +1,118 @@+/* @vitest-environment jsdom */++import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';++import { NewAgentDialog } from './NewAgentDialog';++const apiRef = vi.hoisted(() => ({ current: null as { createVibeAgent: ReturnType<typeof vi.fn> } | null }));++vi.stubGlobal('ResizeObserver', class {+ observe() {}+ unobserve() {}+ disconnect() {}+});++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${JSON.stringify(values)}` : key),+ }),+}));++vi.mock('../../context/ApiContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../context/ApiContext')>()),+ useApi: () => apiRef.current,+}));++// What the catalog answers for this render: a Hub catalog states one entry per+// model, so a test can say "this model has no efforts" the way the server does.+type FakeModelCatalog = {+ models: string[];+ reasoningOptions?: Record<string, { value: string; label: string }[]>;+};+let modelCatalog: FakeModelCatalog = { models: [] };++vi.mock('../../lib/backendModels', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../lib/backendModels')>()),+ loadBackendModelsWithRefresh: (_api: unknown, _backend: string, onLoaded: (payload: FakeModelCatalog) => void) => {+ onLoaded(modelCatalog);+ return () => {};+ },+}));++const renderDialog = () => {+ const createVibeAgent = vi.fn().mockResolvedValue({ ok: true, agent: { id: 'agt-new' } });+ apiRef.current = { createVibeAgent };+ render(<NewAgentDialog open onClose={vi.fn()} onCreated={vi.fn()} />);+ return { createVibeAgent };+};++const chooseModel = (value: string) => {+ fireEvent.click(screen.getByRole('combobox'));+ fireEvent.change(screen.getByPlaceholderText('Search...'), { target: { value } });+ fireEvent.click(screen.getByText(`Use "${value}"`));+};++const submit = () => fireEvent.click(screen.getByRole('button', { name: /agents\.create\.submit/ }));++afterEach(() => {+ cleanup();+ apiRef.current = null;+ modelCatalog = { models: [] };+});++describe('NewAgentDialog', () => {+ it('creates with no effort when the catalog says the model has none', async () => {+ // `medium` is only a starting suggestion. Sending it for a model whose+ // catalog row states no efforts would create an Agent whose very first+ // dispatch carries a parameter the model cannot take.+ modelCatalog = { models: [], reasoningOptions: { 'no-effort-model': [] } };+ const { createVibeAgent } = renderDialog();++ fireEvent.change(screen.getByPlaceholderText('agents.create.namePlaceholder'), { target: { value: 'router' } });+ chooseModel('no-effort-model');++ // The whole field goes and the model takes the row: an empty outline under a+ // heading reads as a control that failed to load.+ expect(screen.queryByRole('button', { name: 'medium', exact: true })).toBeNull();+ expect(screen.queryByText('agents.detail.effort')).toBeNull();+ expect(screen.getByText('agents.create.model').parentElement?.className).toContain('col-span-2');+ submit();++ await waitFor(() => expect(createVibeAgent).toHaveBeenCalledWith(expect.objectContaining({+ name: 'router',+ model: 'no-effort-model',+ reasoning_effort: null,+ })));+ });++ it('still sends the suggested effort for a model that has one', async () => {+ modelCatalog = { models: [], reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }] } };+ const { createVibeAgent } = renderDialog();++ fireEvent.change(screen.getByPlaceholderText('agents.create.namePlaceholder'), { target: { value: 'router' } });+ chooseModel('reasoning-model');++ expect(screen.getByText('agents.detail.effort')).toBeTruthy();+ expect(screen.getByText('agents.create.model').parentElement?.className).not.toContain('col-span-2');+ submit();++ await waitFor(() => expect(createVibeAgent).toHaveBeenCalledWith(expect.objectContaining({+ model: 'reasoning-model',+ reasoning_effort: 'medium',+ })));+ });++ it('keeps the backend fallback for a model the catalog does not name', async () => {+ const { createVibeAgent } = renderDialog();++ fireEvent.change(screen.getByPlaceholderText('agents.create.namePlaceholder'), { target: { value: 'router' } });+ chooseModel('typed/unknown');+ expect(screen.getByRole('button', { name: 'medium', exact: true })).toBeTruthy();+ submit();++ await waitFor(() => expect(createVibeAgent).toHaveBeenCalledWith(expect.objectContaining({+ reasoning_effort: 'medium',+ })));+ });+});diff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsxindex e480a82f8..d9af942f5 100644--- a/ui/src/components/workbench/NewAgentDialog.tsx+++ b/ui/src/components/workbench/NewAgentDialog.tsx@@ -52,7 +52,9 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, oconst [name, setName] = useState('');const [description, setDescription] = useState('');const [model, setModel] = useState('');- const [effort, setEffort] = useState<string>('medium');+ // null is a real answer, not a missing one: a model whose catalog row states+ // no efforts is created with the effort parameter omitted.+ const [effort, setEffort] = useState<string | null>('medium');const [systemPrompt, setSystemPrompt] = useState('');const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);@@ -101,8 +103,12 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o// change, so handleSubmit never sends an effort the backend would reject// (e.g. picking Codex `xhigh` then switching to Claude).useEffect(() => {- if (effort && !effortOptions.includes(effort)) {- setEffort(effortOptions.includes('medium') ? 'medium' : effortOptions[0] ?? 'medium');+ if (effortOptions.length === 0) {+ setEffort(null);+ return;+ }+ if (effort === null || !effortOptions.includes(effort)) {+ setEffort(effortOptions.includes('medium') ? 'medium' : effortOptions[0]);}}, [effortOptions, effort]);@@ -243,9 +249,12 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o{/* Model + Effort — both rows share a 38px height so the Comboboxon the left and the segmented control on the right align. Thesegments use rounded-md py-2 (was py-0.5 which collapsed to- ~24px and looked stubby next to the model field). */}+ ~24px and looked stubby next to the model field). A model whose+ catalog row states no efforts has no field here at all: an empty+ bordered box would read as a control that failed to load, so the+ model takes the whole row instead. */}<div className="grid grid-cols-2 gap-3">- <div className="flex flex-col gap-1.5">+ <div className={clsx('flex flex-col gap-1.5', effortOptions.length === 0 && 'col-span-2')}><div className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('agents.create.model')}</div>@@ -258,29 +267,31 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, oallowCustomValue/></div>- <div className="flex flex-col gap-1.5">- <div className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">- {t('agents.detail.effort')}- </div>- <div- className="grid h-[38px] gap-0.5 rounded-md border border-border-strong bg-surface-2 p-0.5"- style={{ gridTemplateColumns: `repeat(${effortOptions.length}, minmax(0, 1fr))` }}- >- {effortOptions.map((opt) => (- <button- key={opt}- type="button"- onClick={() => setEffort(opt)}- className={clsx(- 'truncate rounded px-0.5 text-[11px] capitalize transition',- effort === opt ? 'bg-mint-soft font-bold text-mint-ink' : 'font-medium text-muted hover:text-foreground',- )}- >- {opt}- </button>- ))}+ {effortOptions.length > 0 && (+ <div className="flex flex-col gap-1.5">+ <div className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">+ {t('agents.detail.effort')}+ </div>+ <div+ className="grid h-[38px] gap-0.5 rounded-md border border-border-strong bg-surface-2 p-0.5"+ style={{ gridTemplateColumns: `repeat(${effortOptions.length}, minmax(0, 1fr))` }}+ >+ {effortOptions.map((opt) => (+ <button+ key={opt}+ type="button"+ onClick={() => setEffort(opt)}+ className={clsx(+ 'truncate rounded px-0.5 text-[11px] capitalize transition',+ effort === opt ? 'bg-mint-soft font-bold text-mint-ink' : 'font-medium text-muted hover:text-foreground',+ )}+ >+ {opt}+ </button>+ ))}+ </div></div>- </div>+ )}</div>{/* System prompt — with token estimate + expand-to-editor, mirroringdiff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex ebffc1bcf..a2d8c8653 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1,6 +1,7 @@import React, { createContext, useContext, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { useToast } from './ToastContext';+import type { AgentSupply } from '../components/settings/models/types';import { apiFetch, recoverRemoteAuthFromSessionProbe } from '../lib/apiFetch';import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';import type { TurnActivityGroupWire } from '../lib/agentActivity';@@ -681,6 +682,10 @@ export type ApiContextType = {claudeModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; model_labels?: Record<string, string>; catalog_refresh_pending?: boolean; error?: string }>;codexAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string; description?: string }[]; error?: string }>;codexModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; model_labels?: Record<string, string>; catalog_refresh_pending?: boolean; error?: string }>;+ /** Picker-safe persisted catalog. Null tells pickers to use the native fallback. */+ readModelHubAgentCatalogForModelPicker: (+ backend: string,+ ) => Promise<Pick<AgentSupply, 'backend' | 'mode' | 'catalog_models'> | null>;getLogs: (lines?: number, source?: string) => Promise<{ logs: LogEntry[]; total: number; source: string; sources: LogSource[] }>;getVersion: () => Promise<VersionInfo>;doUpgrade: () => Promise<UpgradeResult>;@@ -3862,6 +3867,17 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenclaudeModels: () => getJson('/api/claude/models'),codexAgents: (cwd) => cwd ? getJson(`/api/codex/agents?cwd=${encodeURIComponent(cwd)}`) : getJson('/api/codex/agents'),codexModels: () => getJson('/api/codex/models'),+ // Direct mode, rolling upgrades, and a temporarily unreadable Hub catalog+ // all keep the existing native picker behavior without surfacing a toast.+ readModelHubAgentCatalogForModelPicker: (backend) =>+ getJson(`/api/models/agents/${encodeURIComponent(backend)}/models`, { handleError: false })+ .then((payload) => {+ const agent = payload?.ok === false ? null : payload?.agent;+ return agent && typeof agent === 'object'+ ? (agent as Pick<AgentSupply, 'backend' | 'mode' | 'catalog_models'>)+ : null;+ })+ .catch(() => null),getLogs: (lines = 500, source) => postJson('/api/logs', source ? { lines, source } : { lines }),getVersion: () => getCachedJson('/api/version', 10_000),doUpgrade: () => postJson('/api/upgrade', {}),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 99b2590b2..1b7b0b3be 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -911,8 +911,6 @@},"modelCount_one": "{{count}} model","modelCount_other": "{{count}} models",- "selectedModelCount_one": "{{count}} selected",- "selectedModelCount_other": "{{count}} selected","moreModels_one": "{{count}} more model","moreModels_other": "{{count}} more models","collapse": "Collapse",@@ -942,22 +940,100 @@"unconfigured": "No model route configured","unused": "No Agent uses this backend"},- "emptySelection": "No models selected",- "emptyModels": "This backend has no models"+ "emptyModels": "This backend's model list is empty"},- "menu": {- "title": "OpenCode model menu",- "description": "Choose which models OpenCode can use through the gateway, then configure each selected model's route from its row.",- "search": "Search models or sources",- "selected": "{{selected}} of {{total}} selected",- "empty": "No eligible source models are available",- "configured": "Existing configured model",- "baselineUnavailable": "Model menu data is not current. Wait for refresh, or retry the failed section before editing.",- "noMatch": "No models match this search",- "save": "Save selection",+ "catalog": {+ "title": "{{backend}} models",+ "description": "Add, edit, reorder, and remove the models this backend offers. The order here is the order the Agent sees.",+ "search": "Search name or model ID",+ "add": "Add model",+ "columnModel": "Model",+ "columnActions": "Actions",+ "columnState": "State",+ "lockedBadge": "Default",+ "systemDefault": "Claude Code default",+ "edit": "Edit {{model}}",+ "remove": "Remove {{model}}",+ "reorder": "Reorder {{model}}",+ "removeBlocked": "This model still has a route. Clear its route first, then remove it.",+ "empty": "No models yet. Add the first one.",+ "noMatch": "No model matches this search",+ "legacy": "This model engine build does not offer an editable model list yet. These are the models it currently exposes.",+ "baselineUnavailable": "This backend's model list could not be read.",+ "save": "Save","saving": "Saving…","cancel": "Cancel",- "saveFailed": "The model selection was not saved"+ "saveFailed": "The model list was not saved. It was re-read from the server; check it and try again.",+ "saveNotApplied": "The list was stored, but this backend did not load it, so it is not in use yet. Save again once the backend is back.",+ "saveRouted": "A model you removed still has a route. The list was re-read from the server; clear the route first, then remove it.",+ "saveConflict": "This list changed elsewhere while you were editing. Your changes were replayed onto the newer list; check it and save again.",+ "saveIdPrefix": "Claude model IDs must start with claude- or anthropic-. Remove the model and add it again with a valid ID.",+ "saveIdInvalid": "A model ID in this list is not valid for this backend. Remove the model and add it again.",+ "saveDuplicate": "Two models in this list share the same ID. Remove one, then save again.",+ "saveLocked": "This list disagrees with a model the server owns. It was re-read from the server; check it and save again.",+ "saveInvalid": "A model in this list has a value this backend will not accept. Check its fields, then save again.",+ "grabbed_one": "Grabbed {{model}}, position {{position}} of {{count}}.",+ "grabbed_other": "Grabbed {{model}}, position {{position}} of {{count}}.",+ "moved_one": "Moved {{model}} to position {{position}} of {{count}}.",+ "moved_other": "Moved {{model}} to position {{position}} of {{count}}.",+ "dropped_one": "Dropped {{model}} at position {{position}} of {{count}}.",+ "dropped_other": "Dropped {{model}} at position {{position}} of {{count}}.",+ "grabCancelled": "Cancelled moving {{model}} and restored its original position."+ },+ "modelEditor": {+ "eyebrow": "{{backend}} · Model list",+ "addTitle": "Add model",+ "editTitle": "Edit model",+ "description": "Describe this model so the backend and the gateway can use it.",+ "section": {+ "basic": "Basics",+ "parameters": "Parameters",+ "capabilities": "Capabilities"+ },+ "id": {+ "label": "Backend model ID",+ "placeholder": "The ID the backend requests this model by",+ "required": "Enter a backend model ID.",+ "tooLong": "A model ID may be at most 256 characters.",+ "duplicate": "This list already has a model with this ID."+ },+ "displayName": {+ "label": "Display name",+ "placeholder": "Optional — the list shows the model ID when this is empty"+ },+ "fill": "Fill from models.dev",+ "fillEmpty": "models.dev has no model matching this ID.",+ "fillFailed": "models.dev could not be reached.",+ "fillUnavailable": "The models.dev catalog is unavailable right now. You can fill these fields in by hand.",+ "filled": "Filled the fields below; every one stays editable.",+ "viewMatches": "View",+ "matches": "models.dev matches",+ "contextWindow": "Context window",+ "maxOutput": "Maximum output",+ "tokens": "tokens",+ "inputModalities": "Input modalities",+ "outputModalities": "Output modalities",+ "modality": {+ "text": "Text",+ "image": "Image",+ "audio": "Audio",+ "video": "Video",+ "pdf": "PDF"+ },+ "supportsTools": "Tool calling",+ "supportsReasoning": "Reasoning",+ "capability": {+ "unset": "Not set",+ "no": "No",+ "yes": "Yes"+ },+ "reasoningEfforts": "Reasoning effort",+ "customEffort": "Custom effort",+ "customEffortPlaceholder": "e.g. medium",+ "effortNote": "Efforts are sent to the provider verbatim; with none selected, the request omits the effort parameter.",+ "cancel": "Cancel",+ "add": "Add model",+ "apply": "Save model"}},"takeover": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 22657b297..615127c0f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -911,8 +911,6 @@},"modelCount_one": "{{count}} 个模型","modelCount_other": "{{count}} 个模型",- "selectedModelCount_one": "已选 {{count}} 个模型",- "selectedModelCount_other": "已选 {{count}} 个模型","moreModels_one": "还有 {{count}} 个模型","moreModels_other": "还有 {{count}} 个模型","collapse": "收起",@@ -942,22 +940,100 @@"unconfigured": "未配置模型路由","unused": "暂无 Agent 使用"},- "emptySelection": "尚未选择模型",- "emptyModels": "这个后端没有可用模型"+ "emptyModels": "这个后端的模型列表是空的"},- "menu": {- "title": "OpenCode 模型菜单",- "description": "选择 OpenCode 可通过网关使用的模型;保存后,在模型行中配置各自路由。",- "search": "搜索模型或供应商",- "selected": "已选 {{selected}} / {{total}}",- "empty": "没有可供 OpenCode 选择的模型",- "configured": "已有配置模型",- "baselineUnavailable": "模型菜单数据暂未更新,请等待刷新完成,或重试读取失败的区域后再编辑。",+ "catalog": {+ "title": "{{backend}} 模型",+ "description": "添加、编辑、排序和移除这个后端提供的模型;这里的顺序就是 Agent 看到的顺序。",+ "search": "搜索名称或模型 ID",+ "add": "添加模型",+ "columnModel": "模型",+ "columnActions": "操作",+ "columnState": "状态",+ "lockedBadge": "默认",+ "systemDefault": "Claude Code 默认模型",+ "edit": "编辑 {{model}}",+ "remove": "移除 {{model}}",+ "reorder": "调整 {{model}} 的顺序",+ "removeBlocked": "该模型仍配置了路由,请先清空它的路由再移除。",+ "empty": "还没有模型,先添加一个。","noMatch": "没有匹配的模型",- "save": "保存选择",+ "legacy": "当前模型引擎版本还不支持编辑模型列表,以下是它当前提供的模型。",+ "baselineUnavailable": "没能读取这个后端的模型列表。",+ "save": "保存","saving": "正在保存…","cancel": "取消",- "saveFailed": "模型选择未保存,请重试"+ "saveFailed": "模型列表未保存,已重新读取服务器上的列表,请确认后重试。",+ "saveNotApplied": "列表已存下,但该后端没有加载它,因此尚未生效。等后端恢复后再保存一次。",+ "saveRouted": "你移除的模型仍配置了路由。已重新读取服务器上的列表,请先清空该路由再移除。",+ "saveConflict": "编辑期间该列表在别处发生了变更。你的改动已重放到新列表上,请确认后重新保存。",+ "saveIdPrefix": "Claude 模型 ID 必须以 claude- 或 anthropic- 开头。请移除该模型,再用合法的 ID 重新添加。",+ "saveIdInvalid": "列表中有模型 ID 不适用于这个后端。请移除该模型后重新添加。",+ "saveDuplicate": "列表中有两个模型使用了相同的 ID,请移除其中一个后重新保存。",+ "saveLocked": "该列表与服务端自有的模型不一致。已重新读取服务器上的列表,请确认后重新保存。",+ "saveInvalid": "列表中某个模型的字段值不被这个后端接受,请检查后重新保存。",+ "grabbed_one": "已抓起 {{model}},第 {{position}} / {{count}} 位。",+ "grabbed_other": "已抓起 {{model}},第 {{position}} / {{count}} 位。",+ "moved_one": "已把 {{model}} 移到第 {{position}} / {{count}} 位。",+ "moved_other": "已把 {{model}} 移到第 {{position}} / {{count}} 位。",+ "dropped_one": "已放下 {{model}},第 {{position}} / {{count}} 位。",+ "dropped_other": "已放下 {{model}},第 {{position}} / {{count}} 位。",+ "grabCancelled": "已取消移动 {{model}},位置已还原。"+ },+ "modelEditor": {+ "eyebrow": "{{backend}} · 模型列表",+ "addTitle": "添加模型",+ "editTitle": "编辑模型",+ "description": "填写这个模型的信息,后端与模型网关据此使用它。",+ "section": {+ "basic": "基本",+ "parameters": "参数",+ "capabilities": "能力"+ },+ "id": {+ "label": "Backend 模型 ID",+ "placeholder": "后端请求这个模型时使用的 ID",+ "required": "请填写 Backend 模型 ID。",+ "tooLong": "模型 ID 最多 256 个字符。",+ "duplicate": "列表中已存在相同 ID 的模型。"+ },+ "displayName": {+ "label": "显示名称",+ "placeholder": "可选,留空时列表显示模型 ID"+ },+ "fill": "从 models.dev 填充",+ "fillEmpty": "models.dev 上没有匹配该 ID 的模型。",+ "fillFailed": "没能访问 models.dev。",+ "fillUnavailable": "models.dev 目录暂时不可用,你可以手动填写这些字段。",+ "filled": "已填入下列字段,可逐项修改",+ "viewMatches": "查看",+ "matches": "models.dev 匹配结果",+ "contextWindow": "上下文窗口",+ "maxOutput": "最大输出",+ "tokens": "tokens",+ "inputModalities": "输入模态",+ "outputModalities": "输出模态",+ "modality": {+ "text": "文本",+ "image": "图像",+ "audio": "音频",+ "video": "视频",+ "pdf": "PDF"+ },+ "supportsTools": "工具调用",+ "supportsReasoning": "推理能力",+ "capability": {+ "unset": "未设置",+ "no": "否",+ "yes": "是"+ },+ "reasoningEfforts": "推理强度",+ "customEffort": "自定义档位",+ "customEffortPlaceholder": "如 medium",+ "effortNote": "档位按原样发送给供应商;不选则请求不带 effort 参数。",+ "cancel": "取消",+ "add": "添加模型",+ "apply": "保存模型"}},"takeover": {diff --git a/ui/src/lib/backendModels.test.ts b/ui/src/lib/backendModels.test.tsindex 2ce7ebf66..038a6f767 100644--- a/ui/src/lib/backendModels.test.ts+++ b/ui/src/lib/backendModels.test.ts@@ -1,7 +1,35 @@import { afterEach, describe, expect, it, vi } from 'vitest';+import { blankBackendModel } from '../components/settings/models/backendCatalog';+import type { AgentSupply, BackendModel } from '../components/settings/models/types';import { ApiError, type ApiContextType } from '../context/ApiContext';-import { fetchBackendModels, loadBackendModelsWithRefresh } from './backendModels';+import { fetchBackendModels, loadBackendModelsWithRefresh, modelOptionLabel } from './backendModels';+import { resolveEffortOptions } from './effortOptions';++/** No Model Hub record to read, which is what every pre-Hub server, unreadable+ * answer, and disabled engine amounts to for a picker. */+const noHubCatalog = () => vi.fn().mockResolvedValue(null);++const model = (id: string, overrides: Partial<BackendModel> = {}): BackendModel => ({+ ...blankBackendModel(),+ id,+ ...overrides,+});++const hubAgent = (+ backend: AgentSupply['backend'],+ overrides: Partial<AgentSupply> = {},+): AgentSupply => ({+ backend,+ cli_present: true,+ mode: 'hub',+ menu_kind: backend === 'opencode' ? 'open' : 'fixed',+ sources: { order: [], eligibility: [] },+ routes: {},+ menu: null,+ builtin_models: ['legacy-a', 'legacy-b'],+ ...overrides,+});describe('fetchBackendModels for OpenCode', () => {it('reads the public options catalog without borrowing the native Settings surface', async () => {@@ -21,6 +49,7 @@ describe('fetchBackendModels for OpenCode', () => {});const getOpencodeProviders = vi.fn();const api = {+ readModelHubAgentCatalogForModelPicker: noHubCatalog(),readOpencodeOptionsForModelPicker,getOpencodeProviders,} as unknown as ApiContextType;@@ -40,6 +69,7 @@ describe('fetchBackendModels for OpenCode', () => {it('degrades to an empty catalog when the rank may not read the live options endpoint', async () => {const api = {+ readModelHubAgentCatalogForModelPicker: noHubCatalog(),readOpencodeOptionsForModelPicker: vi.fn().mockRejectedValue(new ApiError('forbidden', 403, 'instance_access_forbidden')),@@ -50,6 +80,7 @@ describe('fetchBackendModels for OpenCode', () => {it('still propagates a failure that is not the expected refusal', async () => {const api = {+ readModelHubAgentCatalogForModelPicker: noHubCatalog(),readOpencodeOptionsForModelPicker: vi.fn().mockRejectedValue(new ApiError('boom', 500, null)),@@ -59,6 +90,221 @@ describe('fetchBackendModels for OpenCode', () => {});});+describe('fetchBackendModels in gateway mode', () => {+ it('does not use inherited Object properties as model labels', () => {+ expect(modelOptionLabel('constructor', {})).toBe('constructor');+ });++ it('offers exactly the models the Model Hub catalog holds', async () => {+ const claudeModels = vi.fn();+ const api = {+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(+ hubAgent('claude', {+ catalog_models: [+ // The backend's own selector: visible in the catalog, never a Route+ // key, so it is not a model anything can be pointed at.+ model('default', { locked: true, routeable: false }),+ model('alpha', {+ display_name: 'Alpha',+ supports_reasoning: true,+ reasoning_efforts: ['low', 'high'],+ }),+ model('beta'),+ ],+ }),+ ),+ claudeModels,+ } as unknown as ApiContextType;++ const result = await fetchBackendModels(api, 'claude');++ expect(claudeModels).not.toHaveBeenCalled();+ expect(result).toEqual({+ models: ['alpha', 'beta'],+ modelLabels: { alpha: 'Alpha' },+ reasoningOptions: {+ alpha: [{ value: 'low', label: 'low' }, { value: 'high', label: 'high' }],+ // Present and empty: `beta` states it does not reason, and only a key+ // the catalog never wrote may fall back to the generic ladder.+ beta: [],+ },+ });+ });++ it('states "no efforts" for every routeable model the catalog says does not reason', async () => {+ const api = {+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(+ hubAgent('codex', {+ catalog_models: [+ // Efforts left behind by an earlier fill: the row now says it does+ // not reason, and the runtime drops the variants for exactly that+ // reason, so the picker must not offer them either.+ model('off-with-leftovers', { supports_reasoning: false, reasoning_efforts: ['low', 'high'] }),+ // A model that reasons but names no ladder — "omit the parameter".+ model('on-without-efforts', { supports_reasoning: true, reasoning_efforts: [] }),+ // Unset stays unset: the row never denies reasoning, so its own+ // empty list is what the picker reports.+ model('unset', { supports_reasoning: null, reasoning_efforts: [] }),+ ],+ }),+ ),+ codexModels: vi.fn(),+ } as unknown as ApiContextType;++ const result = await fetchBackendModels(api, 'codex');++ expect(result.reasoningOptions).toEqual({+ 'off-with-leftovers': [],+ 'on-without-efforts': [],+ unset: [],+ });+ // And the resolver reads those keys as an answer rather than a gap.+ for (const id of result.models) {+ expect(resolveEffortOptions('codex', id, result.reasoningOptions)).toEqual([]);+ }+ });++ it('treats model ids as data rather than Object properties', async () => {+ const api = {+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(+ hubAgent('codex', {+ catalog_models: [+ model('constructor', {+ display_name: 'Constructor',+ supports_reasoning: true,+ reasoning_efforts: ['high'],+ }),+ model('__proto__', { display_name: 'Prototype', reasoning_efforts: [] }),+ ],+ }),+ ),+ codexModels: vi.fn(),+ } as unknown as ApiContextType;++ const result = await fetchBackendModels(api, 'codex');++ expect(result.models).toEqual(['constructor', '__proto__']);+ expect(result.modelLabels.constructor).toBe('Constructor');+ expect(result.modelLabels.__proto__).toBe('Prototype');+ expect(Object.prototype.hasOwnProperty.call(result.modelLabels, '__proto__')).toBe(true);+ expect(resolveEffortOptions('codex', 'constructor', result.reasoningOptions)).toEqual(['high']);+ expect(resolveEffortOptions('codex', '__proto__', result.reasoningOptions)).toEqual([]);+ });++ it('picks up a model the user just added and drops one they removed', async () => {+ const readModelHubAgentCatalogForModelPicker = vi+ .fn()+ .mockResolvedValueOnce(hubAgent('codex', { catalog_models: [model('kept'), model('removed')] }))+ .mockResolvedValueOnce(hubAgent('codex', { catalog_models: [model('kept'), model('added')] }));+ const api = {+ readModelHubAgentCatalogForModelPicker,+ codexModels: vi.fn(),+ } as unknown as ApiContextType;++ await expect(fetchBackendModels(api, 'codex')).resolves.toMatchObject({+ models: ['kept', 'removed'],+ });+ await expect(fetchBackendModels(api, 'codex')).resolves.toMatchObject({+ models: ['kept', 'added'],+ });+ });++ it('keeps an emptied catalog empty instead of reopening the backend list', async () => {+ const codexModels = vi.fn().mockResolvedValue({ ok: true, models: ['gpt-old'] });+ const api = {+ readModelHubAgentCatalogForModelPicker: vi+ .fn()+ .mockResolvedValue(hubAgent('codex', { catalog_models: [] })),+ codexModels,+ } as unknown as ApiContextType;++ await expect(fetchBackendModels(api, 'codex')).resolves.toEqual({+ models: [],+ modelLabels: {},+ reasoningOptions: {},+ });+ expect(codexModels).not.toHaveBeenCalled();+ });++ it('never starts OpenCode to list models the catalog already names', async () => {+ const readOpencodeOptionsForModelPicker = vi.fn();+ const api = {+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(+ hubAgent('opencode', { catalog_models: [model('openrouter/anthropic/claude-x')] }),+ ),+ readOpencodeOptionsForModelPicker,+ } as unknown as ApiContextType;++ await expect(fetchBackendModels(api, 'opencode')).resolves.toMatchObject({+ models: ['openrouter/anthropic/claude-x'],+ // OpenCode has no shared default set to fall back to, so its per-model+ // answer has to arrive as an answer rather than as a missing key.+ reasoningOptions: { 'openrouter/anthropic/claude-x': [] },+ });+ expect(readOpencodeOptionsForModelPicker).not.toHaveBeenCalled();+ });+});++describe('fetchBackendModels outside gateway mode', () => {+ it('uses the backend own catalog in direct mode, whatever the Hub has stored', async () => {+ const claudeModels = vi.fn().mockResolvedValue({+ ok: true,+ models: ['native-a'],+ model_labels: { 'native-a': 'Native A' },+ });+ const api = {+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(+ // A direct backend reaches its provider itself, so this stored catalog+ // describes a gateway that is not in the path.+ hubAgent('claude', { mode: 'direct', routes: null, catalog_models: [model('hub-only')] }),+ ),+ claudeModels,+ } as unknown as ApiContextType;++ await expect(fetchBackendModels(api, 'claude')).resolves.toMatchObject({+ models: ['native-a'],+ modelLabels: { 'native-a': 'Native A' },+ });+ expect(claudeModels).toHaveBeenCalledOnce();+ });++ it('uses the backend own catalog while a server predating the Hub catalog answers', async () => {+ const claudeModels = vi.fn().mockResolvedValue({ ok: true, models: ['native-a'] });+ const api = {+ // Hub mode, and no `catalog_models` key at all — the rolling-upgrade+ // window, where a synthesized list would be this client's invention.+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(hubAgent('claude')),+ claudeModels,+ } as unknown as ApiContextType;++ await expect(fetchBackendModels(api, 'claude')).resolves.toMatchObject({ models: ['native-a'] });+ expect(claudeModels).toHaveBeenCalledOnce();+ });++ it('uses the backend own catalog when the Model Hub cannot be read at all', async () => {+ const claudeModels = vi.fn().mockResolvedValue({ ok: true, models: ['native-a'] });+ const api = {+ readModelHubAgentCatalogForModelPicker: noHubCatalog(),+ claudeModels,+ } as unknown as ApiContextType;++ await expect(fetchBackendModels(api, 'claude')).resolves.toMatchObject({ models: ['native-a'] });+ expect(claudeModels).toHaveBeenCalledOnce();+ });++ it('refuses a record that describes a different backend', async () => {+ const codexModels = vi.fn().mockResolvedValue({ ok: true, models: ['gpt-native'] });+ const api = {+ readModelHubAgentCatalogForModelPicker: vi+ .fn()+ .mockResolvedValue(hubAgent('claude', { catalog_models: [model('alpha')] })),+ codexModels,+ } as unknown as ApiContextType;++ await expect(fetchBackendModels(api, 'codex')).resolves.toMatchObject({ models: ['gpt-native'] });+ });+});+describe('loadBackendModelsWithRefresh', () => {afterEach(() => {vi.useRealTimers();@@ -78,7 +324,10 @@ describe('loadBackendModelsWithRefresh', () => {models: ['gpt-old', 'gpt-new'],catalog_refresh_pending: false,});- const api = { codexModels } as unknown as ApiContextType;+ const api = {+ readModelHubAgentCatalogForModelPicker: noHubCatalog(),+ codexModels,+ } as unknown as ApiContextType;const snapshots: string[][] = [];const cancel = loadBackendModelsWithRefresh(api, 'codex', (result) => {@@ -94,4 +343,27 @@ describe('loadBackendModelsWithRefresh', () => {cancel();});++ it('settles on the persisted catalog without polling for a refresh it cannot have', async () => {+ vi.useFakeTimers();+ const readModelHubAgentCatalogForModelPicker = vi+ .fn()+ .mockResolvedValue(hubAgent('codex', { catalog_models: [model('kept')] }));+ const api = { readModelHubAgentCatalogForModelPicker } as unknown as ApiContextType;+ const snapshots: string[][] = [];++ const cancel = loadBackendModelsWithRefresh(api, 'codex', (result) => {+ snapshots.push(result.models);+ });++ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(3_500);++ // A stored list has no remote refresh pending behind it, so the loader has+ // nothing to wait for and asks once.+ expect(snapshots).toEqual([['kept']]);+ expect(readModelHubAgentCatalogForModelPicker).toHaveBeenCalledOnce();++ cancel();+ });});diff --git a/ui/src/lib/backendModels.ts b/ui/src/lib/backendModels.tsindex fe0025fea..580823599 100644--- a/ui/src/lib/backendModels.ts+++ b/ui/src/lib/backendModels.ts@@ -1,3 +1,5 @@+import { routeableCatalogModelIds } from '../components/settings/models/backendCatalog';+import type { AgentSupply } from '../components/settings/models/types';import { ApiError, type ApiContextType } from '../context/ApiContext';export interface BackendModels {@@ -15,13 +17,46 @@ const CATALOG_REFRESH_RETRY_DELAY_MS = 3_500;const CATALOG_REFRESH_MAX_RETRIES = 2;export function modelOptionLabel(model: string, labels?: Record<string, string>): string {- return labels?.[model] || model;+ return labels && Object.prototype.hasOwnProperty.call(labels, model) && labels[model]+ ? labels[model]+ : model;}+// In Hub mode the persisted catalog is authoritative. A missing catalog uses+// the native fallback; an explicitly empty catalog remains an empty menu.+type PickerAgentCatalog = Pick<AgentSupply, 'backend' | 'mode' | 'catalog_models'>;++const hubCatalogModels = (agent: PickerAgentCatalog | null, backend: string): BackendModels | null => {+ if (!agent || agent.backend !== backend || agent.mode !== 'hub') return null;+ const catalog = agent.catalog_models ?? null;+ if (!catalog) return null;+ // A backend-owned selector such as Claude Code's Default is not routeable.+ const models = routeableCatalogModelIds(catalog);+ const rows = new Map(catalog.map((model) => [model.id, model]));+ // Model ids are user-controlled map keys. A null prototype keeps ids such as+ // "constructor" and "__proto__" from colliding with Object properties.+ const modelLabels = Object.create(null) as Record<string, string>;+ const reasoningOptions = Object.create(null) as Record<string, { value: string; label: string }[]>;+ for (const id of models) {+ const row = rows.get(id);+ if (!row) continue;+ if (row.display_name) modelLabels[id] = row.display_name;+ // Every routeable model gets a key, including an empty one: the catalog is+ // authoritative here, so "this model does not reason" must be sayable and+ // must not read as "nobody answered" and fall back to the generic ladder.+ reasoningOptions[id] = row.supports_reasoning === false+ ? []+ : row.reasoning_efforts.map((effort) => ({ value: effort, label: effort }));+ }+ return { models, modelLabels, reasoningOptions };+};+// Single source of truth for "list the selectable models for a backend",// shared by ChatPage, the Agents detail panel, and the New Agent dialog so a// new backend (or a fix like OpenCode's provider-prefixing) lands in one place.//+// Ask Hub first because reading OpenCode's live catalog may start OpenCode.+//// claude / codex expose flat model arrays. OpenCode's public options catalog is// per-provider and returns RAW model ids (never provider-prefixed), so// we flatten it into ``providerId/modelId`` keys — ALWAYS provider-prefixed,@@ -35,6 +70,8 @@ export async function fetchBackendModels(api: ApiContextType,backend: string,): Promise<BackendModels> {+ const hub = hubCatalogModels(await api.readModelHubAgentCatalogForModelPicker(backend), backend);+ if (hub) return hub;if (backend === 'claude') {const res = await api.claudeModels();return {diff --git a/ui/src/lib/effortOptions.test.ts b/ui/src/lib/effortOptions.test.tsindex b99241430..2be7b7d17 100644--- a/ui/src/lib/effortOptions.test.ts+++ b/ui/src/lib/effortOptions.test.ts@@ -32,4 +32,65 @@ describe('effort options', () => {expect(isEffortSupported('claude', 'future-model', 'ultra', reasoningOptions)).toBe(true);expect(isEffortSupported('codex', 'future-model', 'ultra', reasoningOptions)).toBe(true);});++ it('treats an explicitly empty entry as "no efforts", not as a missing answer', () => {+ const reasoningOptions = {+ '': [{ value: 'low', label: 'Low' }],+ 'no-reasoning-model': [],+ };++ expect(resolveEffortOptions('claude', 'no-reasoning-model', reasoningOptions)).toEqual([]);+ expect(resolveEffortOptions('codex', 'no-reasoning-model', reasoningOptions)).toEqual([]);+ // An empty set supports nothing but "unset".+ expect(isEffortSupported('claude', 'no-reasoning-model', 'medium', reasoningOptions)).toBe(false);+ expect(isEffortSupported('claude', 'no-reasoning-model', null, reasoningOptions)).toBe(true);+ // A key nobody wrote still falls back, including to the catalog default set.+ expect(resolveEffortOptions('claude', 'unlisted-model', reasoningOptions)).toEqual(['low']);+ });++ it('honours OpenCode per-model answers and keeps its fallback for models it never names', () => {+ // OpenCode has no "" default set, and its Hub catalog now states an entry+ // per model like the others: reading only claude/codex would throw those+ // answers away and offer the broad superset for a model that has none.+ const reasoningOptions = {+ 'openrouter/anthropic/claude-x': [],+ 'custom/hub-only': [{ value: 'high', label: 'High' }],+ };++ expect(resolveEffortOptions('opencode', 'openrouter/anthropic/claude-x', reasoningOptions)).toEqual([]);+ expect(isEffortSupported('opencode', 'openrouter/anthropic/claude-x', 'high', reasoningOptions)).toBe(false);+ expect(resolveEffortOptions('opencode', 'custom/hub-only', reasoningOptions)).toEqual(['high']);+ // A typed or Direct-mode model the catalog does not name keeps the superset.+ expect(resolveEffortOptions('opencode', 'typed/unknown', reasoningOptions)).toEqual([+ 'minimal',+ 'low',+ 'medium',+ 'high',+ 'xhigh',+ 'max',+ ]);+ expect(resolveEffortOptions('opencode', null, reasoningOptions)).toHaveLength(6);+ });++ it('drops the backend-chooses sentinel from an entry instead of offering it', () => {+ const reasoningOptions = {+ 'sentinel-plus': [{ value: '__default__', label: 'Default' }, { value: 'ultra', label: 'Ultra' }],+ // The sentinel alone leaves nothing to select, and "the backend picks" is+ // not a reason to offer the generic ladder instead.+ 'sentinel-only': [{ value: '__default__', label: 'Default' }],+ };++ expect(resolveEffortOptions('claude', 'sentinel-plus', reasoningOptions)).toEqual(['ultra']);+ expect(resolveEffortOptions('claude', 'sentinel-only', reasoningOptions)).toEqual([]);+ });++ it('does not mistake inherited Object properties for catalog entries', () => {+ expect(resolveEffortOptions('codex', 'constructor', {})).toEqual([+ 'minimal',+ 'low',+ 'medium',+ 'high',+ 'xhigh',+ ]);+ });});diff --git a/ui/src/lib/effortOptions.ts b/ui/src/lib/effortOptions.tsindex 69643ccaf..d2718d131 100644--- a/ui/src/lib/effortOptions.ts+++ b/ui/src/lib/effortOptions.ts@@ -13,26 +13,44 @@ const DEFAULT_EFFORTS = ['low', 'medium', 'high'];export const effortOptionsFor = (backend: string): string[] => EFFORT_BY_BACKEND[backend] ?? DEFAULT_EFFORTS;-const PER_MODEL_EFFORT_BACKENDS = new Set(['claude', 'codex']);+/** Backends whose catalog carries a "" entry: the set an inherited or custom+ * model inherits when the catalog does not name it. */+const SHARED_DEFAULT_EFFORT_BACKENDS = new Set(['claude', 'codex']);-// Resolve the selectable effort values for a backend + model. Claude and Codex-// consult their catalog maps; other backends always use their static superset so-// stale state cannot leak across backend switches. A known model uses its own-// set, while an inherited or custom model uses the catalog's "" default set.-// We do not union across models because that would offer unsupported pairs.-// ``reasoningOptions`` may be {} before the catalog loads, which yields the-// backend fallback until the immediate snapshot arrives.+/** `__default__` is the IM cards' "let the backend choose" sentinel, not an+ * effort value, so it never becomes a selectable option here. */+const selectableEfforts = (entries: { value: string; label: string }[]): string[] =>+ entries.filter((option) => option.value !== '__default__').map((option) => option.value);++// Resolve the selectable effort values for a backend + model.+//+// A model's own entry is the answer, whichever backend it came from: the Hub+// catalog states one per model for all three, so gating the lookup by backend+// would silently discard OpenCode's answers. We do not union across models+// because that would offer unsupported pairs.+//+// A missing key and an empty entry are different answers. Missing means nobody+// has said, so Claude/Codex fall back to their catalog's "" set and every+// backend then to its static superset — that is also what `{}` means before the+// catalog loads. An empty entry under this model's own key is a statement —+// "this model does not reason" — and resolves to no efforts, not to the+// generic ladder.export function resolveEffortOptions(backend: string,model: string | null | undefined,reasoningOptions: Record<string, { value: string; label: string }[]> | undefined,): string[] {- if (PER_MODEL_EFFORT_BACKENDS.has(backend) && reasoningOptions) {- const perModel = reasoningOptions[model ?? ''] ?? reasoningOptions[''];- const values = perModel?.filter((o) => o.value !== '__default__').map((o) => o.value);- if (values && values.length) return values;+ const modelKey = model ?? '';+ if (reasoningOptions && Object.prototype.hasOwnProperty.call(reasoningOptions, modelKey)) {+ return selectableEfforts(reasoningOptions[modelKey]);}- return effortOptionsFor(backend);+ const shared = SHARED_DEFAULT_EFFORT_BACKENDS.has(backend)+ && reasoningOptions+ && Object.prototype.hasOwnProperty.call(reasoningOptions, '')+ ? reasoningOptions['']+ : undefined;+ const values = shared ? selectableEfforts(shared) : [];+ return values.length ? values : effortOptionsFor(backend);}export function isEffortSupported(diff --git a/vibe/authorization.py b/vibe/authorization.pyindex e1cfa4544..15eb6a588 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -475,6 +475,8 @@ _MEMBER_HTTP_RULES = tuple(("PUT", r"^/api/models/agents/[^/]+/chain$"),("GET", r"^/api/models/agents/[^/]+/sources$"),("PUT", r"^/api/models/agents/[^/]+/sources$"),+ ("PUT", r"^/api/models/agents/[^/]+/models$"),+ ("GET", r"^/api/models/catalog/models-dev$"),("PUT", r"^/api/models/agents/opencode/menu$"),("PATCH", r"^/api/models/agents/[^/]+/mode$"),("POST", r"^/api/models/agents/[^/]+/chains/reorder$"),@@ -510,12 +512,13 @@ _EDITOR_HTTP_RULES = tuple(# `/api/claude/*` nor `/api/codex/*` grows an editor-visible mutation by# accident.#- # OpenCode has no editor-visible catalog. Its only one is- # `/api/backend/opencode/providers`, which is the Settings surface --+ # OpenCode's native live catalog has no editor-visible endpoint. The only+ # live endpoint is `/api/backend/opencode/providers`, a Settings surface --# base URLs, masked API keys, active auth type, tool-call permission# state -- and reaching it runs `ensure_running()`, which can install a# plugin, restart, or launch the daemon. Both stay Owner; the model# picker treats the refusal as "no catalog" instead.+ ("GET", r"^/api/models/agents/[^/]+/models$"),("GET", r"^/api/claude/models$"),("GET", r"^/api/codex/models$"),("GET", r"^/api/running-agents$"),diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.pyindex 01f7318ea..f50bac810 100644--- a/vibe/backend_model_catalog.py+++ b/vibe/backend_model_catalog.py@@ -9,7 +9,7 @@ import timeimport urllib.errorimport urllib.requestfrom pathlib import Path-from typing import Any, Iterable, Sequence+from typing import Any, Iterable, Mapping, Sequencefrom config import pathsfrom config.atomic_io import write_atomic@@ -61,6 +61,26 @@ _REASONING_LABELS = {"ultra": "Ultra",}+# A custom model needs Codex's agent/runtime shape, but it must not inherit+# provider metadata from whichever native model happens to be first.+_CODEX_CUSTOM_SCAFFOLD_KEYS = (+ "shell_type",+ "model_messages",+ "base_instructions",+ "include_skills_usage_instructions",+ "include_plugin_usage_instructions",+ "include_apps_usage_instructions",+ "apply_patch_tool_type",+ "truncation_policy",+ "effective_context_window_percent",+ "node_repl_auto_review_required",+ "node_repl_disabled",+ "use_responses_lite",+ "multi_agent_version",+ "tool_mode",+ "prefer_websockets",+)+_REMOTE_LOCK = threading.Lock()_REMOTE_REFRESH_IN_FLIGHT = False_REMOTE_MEMORY_CACHE: dict[str, Any] = {}@@ -80,7 +100,10 @@ def _codex_hub_catalog_path(catalog: bytes) -> Path:return paths.get_runtime_dir() / "model-hub" / "codex" / f"standard-responses-{digest}.json"-def _codex_hub_catalog_bytes(raw_catalog: bytes) -> bytes:+def _codex_hub_catalog_bytes(+ raw_catalog: bytes,+ configured_models: Sequence[Mapping[str, Any]] | None = None,+) -> bytes:"""Project a complete Codex catalog onto generic Responses semantics."""try:@@ -99,7 +122,7 @@ def _codex_hub_catalog_bytes(raw_catalog: bytes) -> bytes:"tool_mode": None,"prefer_websockets": False,}- projected: list[dict[str, Any]] = []+ native_rows: list[dict[str, Any]] = []for model in models:if not isinstance(model, dict) or not isinstance(model.get("slug"), str):raise ValueError("Codex bundled model catalog contains an invalid model")@@ -107,13 +130,110 @@ def _codex_hub_catalog_bytes(raw_catalog: bytes) -> bytes:for key, value in provider_private_defaults.items():if key in row:row[key] = value- projected.append(row)+ native_rows.append(row)+ if configured_models is None:+ projected = native_rows+ else:+ native_by_slug = {row["slug"]: row for row in native_rows}+ template = native_rows[0]+ projected = []+ for priority, configured in enumerate(configured_models, start=1):+ model_id = configured.get("id")+ if not isinstance(model_id, str) or not model_id:+ raise ValueError("Configured Codex catalog contains an invalid model")+ native_row = native_by_slug.get(model_id)+ if native_row is not None:+ row = dict(native_row)+ else:+ row = {+ key: template[key]+ for key in _CODEX_CUSTOM_SCAFFOLD_KEYS+ if key in template+ }+ # Required in some Codex catalog versions, with no matching+ # user-authored BackendModel field.+ row["support_verbosity"] = False+ row["experimental_supported_tools"] = []+ row["slug"] = model_id+ display_name = configured.get("display_name")+ row["display_name"] = (+ display_name+ if isinstance(display_name, str) and display_name+ else model_id+ )+ row["priority"] = priority+ row["visibility"] = "list"+ row["supported_in_api"] = True+ context_window = configured.get("context_window")+ if (+ isinstance(context_window, int)+ and not isinstance(context_window, bool)+ and context_window > 0+ ):+ row["context_window"] = context_window+ row["max_context_window"] = context_window+ # Codex derives this from the active window when omitted; a+ # bundled value belongs to the native window we just replaced.+ row.pop("auto_compact_token_limit", None)+ input_modalities = configured.get("input_modalities")+ # Persisted built-ins use an empty list to mean "not overridden".+ # Custom rows still need a conservative text-only default instead+ # of inheriting the native template model's image capabilities.+ if native_row is None or (+ isinstance(input_modalities, list) and input_modalities+ ):+ supported_modalities = [+ modality+ for modality in (+ input_modalities if isinstance(input_modalities, list) else []+ )+ if modality in {"text", "image"}+ ]+ row["input_modalities"] = supported_modalities or ["text"]+ row["supports_image_detail_original"] = "image" in supported_modalities+ efforts = configured.get("reasoning_efforts")+ supports_reasoning = configured.get("supports_reasoning")+ if supports_reasoning is False:+ settled_efforts = ["none"]+ elif isinstance(efforts, list) and efforts:+ settled_efforts = [+ effort+ for effort in efforts+ if isinstance(effort, str) and effort+ ]+ elif native_row is None:+ settled_efforts = ["none"]+ else:+ settled_efforts = None+ if settled_efforts is not None:+ row["default_reasoning_level"] = (+ "medium"+ if "medium" in settled_efforts+ else settled_efforts[0]+ )+ row["supported_reasoning_levels"] = [+ {+ "effort": effort,+ "description": (+ _REASONING_LABELS.get(effort)+ or effort.replace("_", " ").title()+ ),+ }+ for effort in settled_efforts+ ]+ for key, value in provider_private_defaults.items():+ if key in row:+ row[key] = value+ projected.append(row)payload["models"] = projectedreturn json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode()-def _publish_codex_hub_catalog(raw_catalog: bytes) -> Path:- catalog = _codex_hub_catalog_bytes(raw_catalog)+def _publish_codex_hub_catalog(+ raw_catalog: bytes,+ configured_models: Sequence[Mapping[str, Any]] | None = None,+) -> Path:+ catalog = _codex_hub_catalog_bytes(raw_catalog, configured_models)path = _codex_hub_catalog_path(catalog)write_atomic(path, catalog)return path@@ -164,11 +284,13 @@ def _export_codex_bundled_catalog(def prepare_codex_hub_catalog(binary: str,base_env: dict[str, str] | None = None,+ configured_models: Sequence[Mapping[str, Any]] | None = None,) -> Path:"""Prepare the exact binary's catalog immediately before a Hub launch."""return _publish_codex_hub_catalog(- _export_codex_bundled_catalog(binary, base_env)+ _export_codex_bundled_catalog(binary, base_env),+ configured_models,)diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 26f1d0451..87882e046 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -902,6 +902,14 @@"source_timeout": "The connection timed out. Check the network and retry.","invalid_source_order": "The source order contains an unavailable, ineligible, or duplicate source.","mode_switch_blocked": "This operation is blocked by the current supply mode or selection.",+ "backend_model_catalog_invalid": "The backend model list contains invalid fields.",+ "backend_model_id_invalid": "This backend model ID is invalid.",+ "backend_model_id_prefix": "Claude Code custom model IDs must start with claude- or anthropic-.",+ "backend_model_duplicate": "Each backend model ID may appear only once.",+ "backend_model_locked": "Claude Code Default and built-in model origins cannot be changed.",+ "backend_model_in_route": "Clear this model's route before removing it from the backend model list.",+ "backend_model_conflict": "This backend model changed elsewhere. Reload the list and retry.",+ "models_dev_unavailable": "models.dev is unavailable. Enter the model metadata manually or retry later.","codex_catalog_unavailable": "Codex could not prepare the local Model Hub catalog. Retry this turn.","engine_down": "The local model gateway is unavailable.","engine_down_streamed": "The local model gateway is unavailable. This turn's output may be incomplete.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex bcc5aac1b..03f5d7c8a 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -902,6 +902,14 @@"source_timeout": "连接超时,请检查网络后重试。","invalid_source_order": "供应商优先级包含不可用、不适用或重复的供应商。","mode_switch_blocked": "当前模型管理方式或选择阻止了此操作。",+ "backend_model_catalog_invalid": "Backend 模型列表中包含无效字段。",+ "backend_model_id_invalid": "这个 Backend 模型 ID 无效。",+ "backend_model_id_prefix": "Claude Code 自定义模型 ID 必须以 claude- 或 anthropic- 开头。",+ "backend_model_duplicate": "同一个 Backend 模型 ID 只能出现一次。",+ "backend_model_locked": "不能修改 Claude Code 的 Default 项或内置模型的来源类型。",+ "backend_model_in_route": "请先清空该模型的路由,再从 Backend 模型列表中移除。",+ "backend_model_conflict": "该 Backend 模型已在其他位置发生变更,请重新加载后再试。",+ "models_dev_unavailable": "models.dev 当前不可用,请手动填写模型参数或稍后重试。","codex_catalog_unavailable": "Codex 无法准备本地模型网关目录,请重试本回合。","engine_down": "本地模型网关不可用。","engine_down_streamed": "本地模型网关不可用。本回合输出可能不完整。",diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 12776d3e5..3a58a9d8f 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -165,6 +165,24 @@ class ModelHubRemoteService:async def set_agent_mode(self, backend: str, mode: object) -> dict:return await _rpc("set_agent_mode", {"backend": backend, "mode": mode})+ async def set_agent_models(+ self,+ backend: str,+ baseline: object,+ models: object,+ ) -> dict:+ return await _rpc(+ "set_agent_models",+ {+ "backend": backend,+ "baseline": baseline,+ "models": models,+ },+ )++ def models_dev_matches(self, query: object) -> list[dict]:+ return _rpc_sync("models_dev_matches", {"query": query})+async def set_agent_chain(self, backend: str, model_id: str, chain: object) -> dict:return await _rpc("set_agent_chain",diff --git a/vibe/models_dev_catalog.py b/vibe/models_dev_catalog.pynew file mode 100644index 000000000..a79950545--- /dev/null+++ b/vibe/models_dev_catalog.py@@ -0,0 +1,287 @@+"""Bounded, cached metadata lookup for the public models.dev catalog."""++from __future__ import annotations++import json+import os+import re+import threading+import time+import urllib.error+import urllib.request+from typing import Any++from config import paths+from config.atomic_io import write_atomic+++MODELS_DEV_URL_ENV = "AVIBE_MODELS_DEV_URL"+DEFAULT_MODELS_DEV_URL = "https://models.dev/api.json"+MODELS_DEV_TIMEOUT_SECONDS = 8.0+MODELS_DEV_CACHE_TTL_SECONDS = 24 * 60 * 60+MODELS_DEV_MAX_BYTES = 16 * 1024 * 1024+MODELS_DEV_MAX_MATCHES = 20+_CACHE_LOCK = threading.Lock()+++def _cache_path():+ return paths.get_state_dir() / "models_dev_catalog.json"+++def _models_dev_url() -> str:+ return (+ os.environ.get(MODELS_DEV_URL_ENV)+ or DEFAULT_MODELS_DEV_URL+ ).strip()+++def _read_cache() -> dict[str, Any]:+ try:+ payload = json.loads(_cache_path().read_text(encoding="utf-8"))+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):+ return {}+ return payload if isinstance(payload, dict) else {}+++def _write_cache(payload: dict[str, Any]) -> None:+ write_atomic(+ _cache_path(),+ json.dumps(+ payload,+ ensure_ascii=True,+ separators=(",", ":"),+ ).encode(),+ )+++def _catalog_from_cache(payload: dict[str, Any]) -> dict[str, Any] | None:+ catalog = payload.get("catalog")+ return catalog if isinstance(catalog, dict) else None+++def _fetch_catalog(previous: dict[str, Any]) -> dict[str, Any]:+ url = _models_dev_url()+ headers = {+ "User-Agent": "avibe/models-dev-catalog",+ "Cache-Control": "no-cache",+ }+ if previous.get("url") == url:+ if isinstance(previous.get("etag"), str):+ headers["If-None-Match"] = previous["etag"]+ if isinstance(previous.get("last_modified"), str):+ headers["If-Modified-Since"] = previous["last_modified"]+ request = urllib.request.Request(url, headers=headers)+ try:+ with urllib.request.urlopen( # noqa: S310 - fixed public endpoint or explicit operator override+ request,+ timeout=MODELS_DEV_TIMEOUT_SECONDS,+ ) as response:+ raw = response.read(MODELS_DEV_MAX_BYTES + 1)+ if len(raw) > MODELS_DEV_MAX_BYTES:+ raise ValueError("models.dev catalog exceeded the safety limit")+ catalog = json.loads(raw.decode("utf-8"))+ if not isinstance(catalog, dict):+ raise ValueError("models.dev catalog must be an object")+ payload = {+ "fetched_at": time.time(),+ "url": url,+ "catalog": catalog,+ }+ for header, key in (+ ("ETag", "etag"),+ ("Last-Modified", "last_modified"),+ ):+ value = response.headers.get(header)+ if isinstance(value, str) and value:+ payload[key] = value+ _write_cache(payload)+ return catalog+ except urllib.error.HTTPError as exc:+ if exc.code == 304:+ catalog = _catalog_from_cache(previous)+ if catalog is not None:+ previous["fetched_at"] = time.time()+ _write_cache(previous)+ return catalog+ raise+++def load_models_dev_catalog() -> dict[str, Any]:+ with _CACHE_LOCK:+ cached = _read_cache()+ catalog = (+ _catalog_from_cache(cached)+ if cached.get("url") == _models_dev_url()+ else None+ )+ fetched_at = cached.get("fetched_at")+ cache_age = (+ time.time() - float(fetched_at)+ if isinstance(fetched_at, (int, float))+ else None+ )+ fresh = (+ cache_age is not None+ and 0 <= cache_age < MODELS_DEV_CACHE_TTL_SECONDS+ )+ if catalog is not None and fresh:+ return catalog+ try:+ return _fetch_catalog(cached)+ except (OSError, UnicodeError, json.JSONDecodeError, ValueError):+ if catalog is not None:+ return catalog+ raise RuntimeError("models.dev catalog is unavailable") from None+++def _search_tokens(query: str) -> tuple[str, ...]:+ lowered = query.strip().lower()+ tokens = [lowered]+ if "/" in lowered:+ tokens.append(lowered.rsplit("/", 1)[-1])+ for prefix in ("claude-avibe-", "anthropic-avibe-", "avibe-"):+ if lowered.startswith(prefix):+ tokens.append(lowered[len(prefix) :])+ return tuple(dict.fromkeys(token for token in tokens if token))+++def _fold(value: str) -> str:+ return re.sub(r"[^a-z0-9]+", "", value.lower())+++def _match_score(+ tokens: tuple[str, ...],+ provider_id: str,+ model_id: str,+ name: str,+) -> int | None:+ identity = f"{provider_id}/{model_id}".lower()+ model_lower = model_id.lower()+ name_lower = name.lower()+ for token in tokens:+ if token == identity:+ return 0+ if token == model_lower:+ return 1+ if _fold(token) == _fold(model_lower):+ return 2+ if token == name_lower:+ return 3+ if any(token in identity or token in name_lower for token in tokens):+ return 4+ return None+++def _reasoning_efforts(model: dict[str, Any]) -> list[str]:+ options = model.get("reasoning_options")+ if not isinstance(options, list):+ return []+ for option in options:+ if not isinstance(option, dict) or option.get("type") != "effort":+ continue+ values = option.get("values")+ if isinstance(values, list):+ return list(+ dict.fromkeys(+ value+ for value in values+ if isinstance(value, str) and value+ )+ )+ return []+++def _modalities(model: dict[str, Any], direction: str) -> list[str]:+ modalities = model.get("modalities")+ values = modalities.get(direction) if isinstance(modalities, dict) else None+ if not isinstance(values, list):+ return []+ allowed = (+ {"text", "image", "audio", "video", "pdf"}+ if direction == "input"+ else {"text", "image", "audio", "video"}+ )+ return list(+ dict.fromkeys(+ value+ for value in values+ if isinstance(value, str) and value in allowed+ )+ )+++def search_models_dev(query: str) -> list[dict[str, Any]]:+ tokens = _search_tokens(query)+ catalog = load_models_dev_catalog()+ matches: list[tuple[int, str, str, dict[str, Any]]] = []+ for provider_key, provider in catalog.items():+ if not isinstance(provider_key, str) or not isinstance(provider, dict):+ continue+ provider_id = (+ provider.get("id")+ if isinstance(provider.get("id"), str)+ else provider_key+ )+ provider_name = (+ provider.get("name")+ if isinstance(provider.get("name"), str)+ else provider_id+ )+ raw_models = provider.get("models")+ if not isinstance(raw_models, dict):+ continue+ for model_key, model in raw_models.items():+ if not isinstance(model_key, str) or not isinstance(model, dict):+ continue+ model_id = (+ model.get("id")+ if isinstance(model.get("id"), str)+ else model_key+ )+ display_name = (+ model.get("name")+ if isinstance(model.get("name"), str)+ else model_id+ )+ score = _match_score(tokens, provider_id, model_id, display_name)+ if score is None:+ continue+ limit = model.get("limit")+ limit = limit if isinstance(limit, dict) else {}+ row = {+ "provider_id": provider_id,+ "provider_name": provider_name,+ "model_id": model_id,+ "models_dev_id": f"{provider_id}/{model_id}",+ "display_name": display_name,+ "context_window": (+ limit.get("context")+ if isinstance(limit.get("context"), int)+ and not isinstance(limit.get("context"), bool)+ and limit["context"] > 0+ else None+ ),+ "max_output_tokens": (+ limit.get("output")+ if isinstance(limit.get("output"), int)+ and not isinstance(limit.get("output"), bool)+ and limit["output"] > 0+ else None+ ),+ "input_modalities": _modalities(model, "input"),+ "output_modalities": _modalities(model, "output"),+ "supports_tools": (+ model.get("tool_call")+ if isinstance(model.get("tool_call"), bool)+ else None+ ),+ "supports_reasoning": (+ model.get("reasoning")+ if isinstance(model.get("reasoning"), bool)+ else None+ ),+ "reasoning_efforts": _reasoning_efforts(model),+ }+ matches.append((score, provider_id, model_id, row))+ matches.sort(key=lambda item: (item[0], item[1], item[2]))+ return [row for _score, _provider, _model, row in matches[:MODELS_DEV_MAX_MATCHES]]diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 8845d48ab..91c378c99 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4636,6 +4636,52 @@ async def model_hub_agent_mode_patch(backend):return _model_hub_error(exc)[email protected]("/api/models/agents/<backend>/models", methods=["GET"])+def model_hub_agent_models_get(backend):+ from core.handlers.model_hub import ModelHubError++ try:+ agent = _model_hub_service().get_agent_sources(backend)+ picker_agent = {+ "backend": agent["backend"],+ "mode": agent["mode"],+ }+ if "catalog_models" in agent:+ picker_agent["catalog_models"] = agent["catalog_models"]+ return _model_hub_success(agent=picker_agent)+ except ModelHubError as exc:+ return _model_hub_error(exc)++[email protected]("/api/models/agents/<backend>/models", methods=["PUT"])+async def model_hub_agent_models_put(backend):+ from core.handlers.model_hub import ModelHubError++ try:+ payload = _model_hub_json_object("mapping_target_unavailable")+ agent = await _model_hub_service().set_agent_models(+ backend,+ payload.get("baseline"),+ payload.get("models"),+ )+ return _model_hub_success(agent=agent)+ except ModelHubError as exc:+ return _model_hub_error(exc)++[email protected]("/api/models/catalog/models-dev", methods=["GET"])+def model_hub_models_dev_get():+ from core.handlers.model_hub import ModelHubError++ try:+ matches = _model_hub_service().models_dev_matches(+ request.args.get("query"),+ )+ return _model_hub_success(matches=matches)+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/models/agents/opencode/menu", methods=["PUT"])async def model_hub_opencode_menu_put():from core.handlers.model_hub import ModelHubError