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
fix(model-hub): keep Agent models runnable when switching to the Gateway (#2301)
Call White1f4ff1eee9d1
diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.pyindex 21bdacf0e..e9e73c73e 100644--- a/core/handlers/model_hub/identifiers.py+++ b/core/handlers/model_hub/identifiers.py@@ -91,6 +91,29 @@ OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL = {}+def opencode_menu_model_candidates(selected: str) -> tuple[str, ...]:+ """The OpenCode menu ids one Agent model selection can name, exact first.++ OpenCode addresses a model as ``<provider>/<model>``, split on the first+ ``/``. A selection made in Direct mode names one of the user's own+ providers, which Gateway mode never loads, so only its model part can name+ a Gateway menu row. The whole selection still comes first: a menu id may+ itself carry a slash (``moonshotai/kimi-k2``) and then names its own row.+ """++ provider, separator, model = selected.partition("/")+ return (selected, model) if provider and separator and model else (selected,)+++def opencode_menu_model_id(selected: str, menu_ids: Container[str]) -> str:+ """Return the OpenCode menu id a selection names, or the selection itself."""++ return next(+ (candidate for candidate in opencode_menu_model_candidates(selected) if candidate in menu_ids),+ selected,+ )++def normalized_model_id(value: str) -> str:"""Spell one identifier the one way this product spells it.diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex 9f63e2e1f..b4ba63f59 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -142,6 +142,8 @@ class MigrationHost(Protocol):def _save_config(self, config: ModelHubConfig) -> ModelHubConfig: ...+ def _carry_agent_selections(self, config: ModelHubConfig, backend: Any) -> None: ...+def _reconcile_native_auth(self, backends: tuple[str, ...]) -> None: ...async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None: ...@@ -1896,7 +1898,9 @@ async def _prepare_takeover(}updated.enabled = Truefor backend in backends:- updated.agents[backend].mode = "hub"+ if updated.agents[backend].mode != "hub":+ updated.agents[backend].mode = "hub"+ host._carry_agent_selections(updated, backend)updated = ModelHubConfig.from_payload(updated.to_payload())for edit in edits:edit.check()diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex a03767b64..70bfd7803 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -101,7 +101,13 @@ from .events import (contains_credential_material,)from .errors import ModelDiscoveryError-from .identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL, canonical_model_id, normalized_model_id+from .identifiers import (+ OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL,+ canonical_model_id,+ normalized_model_id,+ opencode_menu_model_candidates,+ opencode_menu_model_id,+)from .migration import (MigrationConflictError,MigrationCredentialsInvalidError,@@ -1055,9 +1061,25 @@ class ModelHubService:self.requested_model_override(cast(BackendName, agent.backend)) or "").strip()if requested_model:- return requested_model+ return self._menu_model_for_selection(agent, requested_model)return ""+ @staticmethod+ def _menu_model_for_selection(+ agent: ModelHubAgentSupplyConfig,+ selected: str,+ ) -> str:+ """Name the menu row an Agent's model selection runs on in Gateway mode.++ Only OpenCode spells a Direct selection differently from its Gateway+ menu id; the turn path applies the same rule to its overlay snapshot.+ Direct mode runs the selection as it is spelled.+ """++ if agent.backend != "opencode" or agent.mode != "hub":+ return selected+ return opencode_menu_model_id(selected, {model.id for model in agent.models})+def _agent_model_ids(self,agent: ModelHubAgentSupplyConfig,@@ -3801,7 +3823,10 @@ class ModelHubService:if self.named_agents_override is not None:for name, pinned_model in self.named_agents_override(backend):- add(pinned_model, name)+ add(+ self._menu_model_for_selection(agent, str(pinned_model or "").strip()),+ name,+ )for model in agent.models:add(model.id)for model_id, route in agent.routes.items():@@ -4511,7 +4536,9 @@ class ModelHubService:named_agents = []if self.named_agents_override is not None:for name, pinned_model in self.named_agents_override(backend):- requested = str(pinned_model or "").strip()+ requested = self._menu_model_for_selection(+ agent, str(pinned_model or "").strip()+ )named_resolution = resolve_model_hub_turn(config,backend,@@ -4617,6 +4644,66 @@ class ModelHubService:logger.info("Model Hub candidates have no models.dev metadata: %s", type(exc).__name__)return {}+ def _provider_candidate(+ self,+ config: ModelHubConfig,+ backend: BackendName,+ model_id: str,+ match: Mapping[str, Any] | None,+ ) -> tuple[ModelHubBackendModelConfig, list[dict], tuple[str, ...]] | None:+ """Build the catalog row a provider-supplied model is added as.++ Returns the admitted row, its suppliers in Source order, and the+ models.dev fields that filled it, or None when the id is not admissible.+ """++ from vibe.models_dev_catalog import native_protocol_for_model_id++ suppliers, display_name, reasoning_efforts = self._candidate_suppliers(+ config,+ backend,+ model_id,+ )+ # Suppliers speak first, models.dev fills what they left unsaid, and+ # an unstated ladder falls back to the tiers the backend's request+ # protocol accepts, unless models.dev says the model cannot reason.+ enrichment = (+ {field: match[field] for field in _MODELS_DEV_CANDIDATE_FIELDS}+ if match is not None+ else {}+ )+ if reasoning_efforts and enrichment.get("supports_reasoning") is False:+ # A supplier's ladder outranks the catalog's flag, and a false+ # flag would suppress that ladder at launch.+ enrichment["supports_reasoning"] = None+ display_name = display_name or (match or {}).get("display_name")+ if not reasoning_efforts and match is not None:+ reasoning_efforts = list(match["reasoning_efforts"])+ if not reasoning_efforts and enrichment.get("supports_reasoning") is not False:+ request_protocol = _FIXED_BACKEND_PROTOCOLS.get(+ backend+ ) or native_protocol_for_model_id(model_id)+ reasoning_efforts = list(PROTOCOL_REASONING_EFFORT_DEFAULTS[request_protocol])+ admitted = admissible_backend_model(+ backend,+ model_id,+ {+ "origin": "provider",+ "display_name": display_name,+ "reasoning_efforts": reasoning_efforts,+ **enrichment,+ **(+ {"native_protocol": native_protocol_for_model_id(model_id)}+ if backend == "opencode"+ else {}+ ),+ },+ claude_builtin_ids=_builtin_model_ids("claude"),+ )+ if admitted is None:+ return None+ return admitted, suppliers, tuple(enrichment)+def agent_model_candidates(self, backend: str) -> dict:agent_backend = cast(BackendName, backend)config = self.store.load()@@ -4697,46 +4784,15 @@ class ModelHubService:providers = []described = self._models_dev_descriptions(provider_ids)for model_id in provider_ids:- suppliers, display_name, reasoning_efforts = self._candidate_suppliers(+ candidate = self._provider_candidate(config,agent_backend,model_id,+ described.get(model_id),)- # Suppliers speak first, models.dev fills what they left unsaid, and- # an unstated ladder falls back to the tiers the backend's request- # protocol accepts, unless models.dev says the model cannot reason.- match = described.get(model_id)- enrichment = (- {field: match[field] for field in _MODELS_DEV_CANDIDATE_FIELDS}- if match is not None- else {}- )- if reasoning_efforts and enrichment.get("supports_reasoning") is False:- # A supplier's ladder outranks the catalog's flag, and a false- # flag would suppress that ladder at launch.- enrichment["supports_reasoning"] = None- display_name = display_name or (match or {}).get("display_name")- if not reasoning_efforts and match is not None:- reasoning_efforts = list(match["reasoning_efforts"])- if not reasoning_efforts and enrichment.get("supports_reasoning") is not False:- request_protocol = _FIXED_BACKEND_PROTOCOLS.get(- agent_backend- ) or native_protocol_for_model_id(model_id)- reasoning_efforts = list(PROTOCOL_REASONING_EFFORT_DEFAULTS[request_protocol])- admitted = admissible_backend_model(- agent_backend,- model_id,- {- "origin": "provider",- "display_name": display_name,- "reasoning_efforts": reasoning_efforts,- **enrichment,- **protocol_payload(model_id),- },- claude_builtin_ids=_builtin_model_ids("claude"),- )- if admitted is None:+ if candidate is None:continue+ admitted, suppliers, enriched_fields = candidateproviders.append({"id": admitted.id,@@ -4746,7 +4802,7 @@ class ModelHubService:"origin": "provider",**{field: getattr(admitted, field)- for field in enrichment+ for field in enriched_fields},**protocol_payload(admitted.id),}@@ -4836,6 +4892,67 @@ class ModelHubService:)return any(item.backend == backend and item.config_blocker for item in available)+ def _carry_agent_selections(+ self,+ config: ModelHubConfig,+ backend: BackendName,+ ) -> None:+ """Give each Agent's model a Gateway menu row when a Source serves it.++ Called as a backend enters Gateway mode. Direct mode never reads the+ Gateway menu, so an Agent there keeps a model its CLI offered, and an+ OpenCode one spells it with its own provider (``openai/gpt-5.6-sol``).+ The row added is the one the picker adds for a provider model, only+ when a Source in this backend's default routing lists it. The Agent's+ selection itself is untouched, so switching back to Direct still runs+ it. A row the user removed stays removed, and a selection nothing+ serves stays visible as an Agent that needs attention.+ """++ if self.named_agents_override is None:+ return+ agent = config.agents[backend]+ carried: list[str] = []+ for _name, selected in self.named_agents_override(backend):+ selected = str(selected or "").strip()+ menu_ids = {model.id for model in agent.models}+ if not selected or self._menu_model_for_selection(agent, selected) in menu_ids:+ continue+ candidates = (+ opencode_menu_model_candidates(selected)+ if backend == "opencode"+ else (selected,)+ )+ served = next(+ (+ candidate+ for candidate in candidates+ if candidate not in agent.removed_model_ids+ and candidate not in carried+ and self._matching_menu_model_hops(config, backend, candidate)+ ),+ None,+ )+ if served is not None:+ carried.append(served)+ if not carried:+ return+ described = self._models_dev_descriptions(carried)+ for model_id in carried:+ candidate = self._provider_candidate(+ config,+ backend,+ model_id,+ described.get(model_id),+ )+ if candidate is not None:+ agent.models.append(candidate[0])+ if backend == "opencode":+ agent.menu = ModelHubMenuConfig(+ view=agent.menu.view if agent.menu else "featured",+ checked=[model.id for model in agent.models],+ )+async def set_agent_mode(self, backend: str, mode: object) -> dict:if mode not in {"hub", "direct"}:raise ModelHubError("mode_switch_blocked")@@ -4872,6 +4989,8 @@ class ModelHubService:raise ModelHubError("mode_switch_blocked", status=409)config = self._clone_config(previous)self._agent(config, backend).mode = mode+ if mode == "hub":+ self._carry_agent_selections(config, cast(BackendName, backend))await self._commit_synced(previous, config)committed = self.store.load()return self._agent_payload(committed, self._agent(committed, backend))diff --git a/docs/plans/model-hub-gateway-switch-agent-models.md b/docs/plans/model-hub-gateway-switch-agent-models.mdnew file mode 100644index 000000000..18c999202--- /dev/null+++ b/docs/plans/model-hub-gateway-switch-agent-models.md@@ -0,0 +1,100 @@+# Agent models across a switch to the Gateway (MH-SWITCH-001/002)++Status: change contract for the fix branch `fix/opencode-gateway-first-turn`.+The owner decides the merge.++## Background++Observed on a fresh install at master `219c81d`: all backends were on Direct and+OpenCode's native `opencode.json` configured `anthropic` and `openai` providers.+The built-in `opencode` Agent carried Avibe's recommended Direct model+`openai/gpt-5.6-sol`.++1. The user switched OpenCode to the Gateway, either through the migration dialog+ (which deduplicated both providers into the existing Sources) or through+ "Later" (a mode-only switch).+2. OpenCode's Gateway menu stayed empty, so the Agent's model had no menu row and+ the first turn failed with `modelHub.errors.mapping_target_unavailable`.+3. The Models page reported "`openai/gpt-5.6-sol` is not a known model name".+ Adding `gpt-5.6-sol` through Manage models did not help, because an OpenCode+ selection had to equal a menu id byte for byte. Only rewriting the Agent's+ model to `gpt-5.6-sol` made the turn run.++Claude Code and Codex were unaffected only because their fixed menus already+contain the built-in ids their Agents use. A Codex or Claude Agent pinned to a+non-built-in model has the same gap.++## Cause++Two facts meet at the switch, and neither owner handled it:++- Every Gateway turn runs a menu row (`effective_model_route` requires menu+ membership; OpenCode's overlay projects only menu rows). Entering the Gateway+ never added the models Agents already select, even when a Source lists them.+- OpenCode's two modes spell models differently (`model-hub.md` §4.8.3). A+ Direct selection is an OpenCode reference, `<native provider>/<model>`; a+ Gateway menu id is the bare model. Nothing read a Direct selection in the+ Gateway world, so even a matching row was unreachable.++## Contract++1. **Carry Agent selections on entering the Gateway (MH-SWITCH-001).** When a+ backend switches from Direct to Hub, through `set_agent_mode` or the+ migration transaction, each enabled Agent's model that the menu does not+ list gains the row the model picker adds for a provider model: origin+ `provider`, supplier metadata and models.dev enrichment as the picker derives+ them, and OpenCode's `native_protocol` from the vendor family. It is added+ only with inventory evidence: a configuration-eligible Source in the backend's+ default order lists the model (the automatic route tier). Speculative API-key+ passthrough is not evidence. For OpenCode the whole selection is tried first,+ then its model part. The rows are committed atomically with the mode, inside+ the existing switch guard or migration record.+2. **Read an OpenCode selection as an OpenCode reference (MH-SWITCH-002).** In+ Gateway mode an OpenCode selection names the menu row equal to the whole+ selection, otherwise the row equal to its model part after the first `/`,+ provided both parts are nonempty. An exact id always wins, so a namespaced+ upstream id such as `moonshotai/kimi-k2` keeps its own row. The same pure rule+ (`identifiers.opencode_menu_model_id`) serves the turn's overlay snapshot and+ the service projections that consume Agent selections: the default Agent's+ requested model, `named_agents`, and the interruption/removal guards.+3. **Selections are not rewritten.** Agents, channel overrides and session pins+ keep their spelling, so switching back to Direct runs them unchanged. Direct+ mode projects each selection exactly as spelled.++## Interaction with "Agent needs attention"++- A carried selection resolves to its row, so it no longer appears as an issue,+ and `effective_model_id` names the row that actually runs. The UI's supply+ attribution therefore counts that row as claimed instead of unassigned.+- A selection nothing serves keeps today's issue and copy, naming the selection+ as spelled. The repair the copy implies now works for OpenCode: adding the+ model part (`gpt-5.6-sol`) through Manage models makes `openai/gpt-5.6-sol`+ runnable without editing the Agent.+- Removing a row an Agent runs through its model part is reported by the+ existing interruption guard, because the guard reads the same resolution.++## Known by design++- Carry-over runs only on the Direct-to-Hub transition. A Source added later, or+ a Hub-mode backend whose Agent selects an absent model, keeps using the+ attention repair; the menu stays user-owned between switches.+- A row in `removed_model_ids` is never re-added: the user removed it on purpose.+- The reverse switch is unchanged. An Agent whose model was set to a bare Gateway+ id still needs a provider in Direct mode (`opencode.default_provider`).+- The attention copy is unchanged; it stays truthful for both populations.++## Validation++- `MH-SWITCH-001`: service-boundary scenario from Direct with two API-key+ Sources and four OpenCode Agents (served, served by another vendor, removed,+ unserved), plus a Codex non-built-in selection. Asserts the carried rows and+ their metadata, the per-Agent projection, a real loopback gateway turn from+ the prepared overlay reaching the right Source and upstream id, and the Direct+ round trip. A related case applies the real migration transaction.+- `MH-SWITCH-002`: overlay unit contract, replacing the former+ `test_opencode_overlay_never_repairs_a_prefixed_identifier`, which asserted+ the opposite.+- Existing Model Hub API, routing-modes, resolution, injection, takeover and+ scenario suites; changed-file Ruff.+- Real E2E on a temporary worktree Incus environment: Direct install with native+ OpenCode providers, switch to the Gateway both ways, first turn succeeds.diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 496d90cfa..773caaf33 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -1670,6 +1670,12 @@ and under v4 the two modes no longer share a namespace at all (§4.8.3).applies the Codex admission rule; the retired "three buckets" repair of `custom/` prefixesdoes not exist. Two different vendors' models that share an id cannot coexist in oneOpenCode menu — the same rule Codex already has.+6. **Agent selections cross the switch** (amendment,+ `model-hub-gateway-switch-agent-models.md`). Menu ids stay bare and are never+ repaired. An Agent's selection is not a menu id: in Gateway mode it names the row+ equal to the whole selection, otherwise the row equal to its OpenCode model part, so+ a Direct-era `openai/gpt-5.6-sol` runs the row `gpt-5.6-sol`. Entering Gateway mode+ adds a row for each Agent selection that a Source in default routing lists.History: 07-23 locked `provider/model` with a standard-vendor segment and no `avibe-`namespace so ids read like native OpenCode and survived Gateway⇄Direct switches. 09-04 thediff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex 9684f5ae2..78338c6c6 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -20,7 +20,10 @@ from core.handlers.model_hub.events import (EventAgent,EventReason,)-from core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL+from core.handlers.model_hub.identifiers import (+ OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL,+ opencode_menu_model_id,+)from core.handlers.model_hub.provenance import (ENGINE_DOWN_TURN_OUTCOME,PreparedGatewayRoute,@@ -1242,6 +1245,7 @@ def opencode_requested_model_for_overlay(if not overlay.available_identifiers:raise ModelHubError("mapping_target_unavailable", status=409)return overlay.available_identifiers[0]+ candidate = opencode_menu_model_id(candidate, overlay.checked_identifiers)if candidate in overlay.checked_identifiers:return candidateraise ModelHubError("mapping_target_unavailable", status=409)diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex efc5bb308..a4a2ea003 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -1202,6 +1202,20 @@ scenarios:kind: selectionlayer: scenariotest: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_unpinned_hub_projection_is_null_while_explicit_turn_resolves+ - id: MH-SWITCH-001+ name: Entering Gateway mode keeps each enabled Agent's model runnable when a Source serves it+ status: covered+ kind: selection+ layer: scenario+ test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_mh_switch_001_switching_to_gateway_keeps_agent_models_runnable+ related_tests:+ - tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_switch_001_migration_carries_agent_models_into_the_switched_menu+ - id: MH-SWITCH-002+ name: A Direct-era OpenCode provider/model selection runs on the Gateway menu row its model part names+ status: covered+ kind: selection+ layer: unit+ test: tests/test_model_hub_injection.py::test_opencode_overlay_runs_a_provider_qualified_selection_on_its_menu_row- id: MH-MIG-001name: Native migration takes over selected credentials and cleans replaced native authstatus: covereddiff --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 d0b8a10de..ea1033bac 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@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport json+from contextlib import asynccontextmanagerfrom collections import dequefrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezone@@ -36,6 +37,7 @@ from core.handlers.model_hub.provenance import BoundedProvenanceStorefrom core.handlers.model_hub.revocations import CredentialRevocationJournalfrom core.handlers.model_hub.service import (PRE_ATTEMPT_SETTLEMENT_GENERATION,+ ModelHubError,ModelHubService,)from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway@@ -44,6 +46,8 @@ from modules.agents.model_hub import (ModelHubRuntimeRouter,bind_launch,bind_persisted_launch,+ opencode_model_for_overlay,+ opencode_requested_model_for_overlay,persisted_launch_identity,)@@ -326,6 +330,159 @@ def test_unpinned_hub_projection_is_null_while_explicit_turn_resolves(asyncio.run(exercise())+@asynccontextmanager+async def _idle_switch_guard(backends, *, external_processes=True):+ async def verify_idle() -> None:+ return None++ yield verify_idle+++def test_mh_switch_001_switching_to_gateway_keeps_agent_models_runnable(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """MH-SWITCH-001: entering Gateway mode carries each enabled Agent's model+ into the backend menu when a Source serves it, so the first OpenCode turn+ of a Direct-era ``openai/...`` selection runs through the gateway."""++ native_home = tmp_path / "native-home"+ for name, path in {+ "HOME": native_home,+ "XDG_CONFIG_HOME": native_home / ".config",+ "XDG_DATA_HOME": native_home / ".local" / "share",+ "XDG_CACHE_HOME": native_home / ".cache",+ "CLAUDE_CONFIG_DIR": native_home / ".claude",+ "CODEX_HOME": native_home / ".codex",+ }.items():+ monkeypatch.setenv(name, str(path))+ monkeypatch.setattr(Path, "home", lambda: native_home)++ def api_source(source_id: str, vendor: str, protocol: str, models: list[str]) -> ModelHubSourceConfig:+ return ModelHubSourceConfig(+ id=source_id,+ kind="api_key",+ vendor=vendor,+ display_name=source_id,+ protocol=protocol,+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id=model_id, provenance="discovered", reasoning_efforts=["low", "high"],+ )+ for model_id in models+ ],+ credential_ref=f"cred_{source_id}",+ )++ anthropic = api_source("src_anthropic", "anthropic", "anthropic", ["claude-opus-5-5"])+ openai = api_source(+ "src_openai01", "openai", "openai_responses", ["gpt-5.6-sol", "gpt-removed", "relay-custom-1"],+ )+ config = ModelHubConfig(+ sources=[anthropic, openai],+ agents={+ backend: ModelHubAgentSupplyConfig.default(backend, mode="direct")+ for backend in ("claude", "codex", "opencode")+ },+ )+ for agent in config.agents.values():+ agent.sources = ModelHubAgentSourcesConfig(order=[anthropic.id, openai.id])+ # An explicit removal made during an earlier Gateway period stays removed.+ config.agents["opencode"].removed_model_ids = ["gpt-removed"]+ codex_menu_before = [model.to_payload() for model in config.agents["codex"].models]+ selections = {+ "claude": [],+ "codex": [("codex", "gpt-5.6-sol"), ("relay", "relay-custom-1")],+ "opencode": [+ ("opencode", "openai/gpt-5.6-sol"),+ ("writer", "anthropic/claude-opus-5-5"),+ ("pruned", "openai/gpt-removed"),+ ("stranger", "openai/not-served"),+ ],+ }+ store = MemoryStore(config)+ adapter = AdapterBoundaryFake([+ AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}', recovery_verified=True),+ ])+ service = _service(tmp_path, store, adapter, now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc))+ service.migration_home = native_home+ service.migration_guard = _idle_switch_guard+ service.named_agents_override = lambda backend: selections[backend]+ service.requested_model_override = lambda backend: dict(selections[backend]).get(backend)++ async def exercise() -> None:+ opencode = await service.set_agent_mode("opencode", "hub")+ codex = await service.set_agent_mode("codex", "hub")++ catalog = {model.id: model for model in store.load().agents["opencode"].models}+ assert list(catalog) == ["gpt-5.6-sol", "claude-opus-5-5"]+ assert store.load().agents["opencode"].menu.checked == list(catalog)+ assert {model_id: (model.origin, model.native_protocol, model.reasoning_efforts)+ for model_id, model in catalog.items()} == {+ "gpt-5.6-sol": ("provider", "openai_responses", ["low", "high"]),+ "claude-opus-5-5": ("provider", "anthropic", ["low", "high"]),+ }+ assert opencode["selected_model_id"] == "gpt-5.6-sol"+ assert {row["name"]: (row["effective_model_id"], row["supply_status"], row["route_reason"])+ for row in opencode["named_agents"]} == {+ "opencode": ("gpt-5.6-sol", "ok", None),+ "writer": ("claude-opus-5-5", "ok", None),+ "pruned": ("openai/gpt-removed", "interrupted", "route_unconfigured"),+ "stranger": ("openai/not-served", "interrupted", "route_unconfigured"),+ }+ # A fixed menu gains only what it lacked; its built-in rows are untouched.+ codex_models = [model.to_payload() for model in store.load().agents["codex"].models]+ assert codex_models[:-1] == codex_menu_before+ assert codex_models[-1]["id"] == "relay-custom-1"+ assert {row["name"]: row["supply_status"] for row in codex["named_agents"]} == {+ "codex": "ok", "relay": "ok",+ }++ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(+ service=service, turn_gateway=gateway, overlay_path=tmp_path / "overlay.json",+ )+ try:+ overlay = await router.prepare_opencode_overlay()+ assert overlay is not None+ requested = opencode_requested_model_for_overlay("openai/gpt-5.6-sol", overlay)+ assert requested == "gpt-5.6-sol"+ assert opencode_model_for_overlay("openai/gpt-5.6-sol", overlay) == "avibe-openai/gpt-5.6-sol"+ launch = await router.resolve_opencode_overlay_launch(overlay, requested)+ assert (launch.source_id, launch.target_model) == (openai.id, "gpt-5.6-sol")+ status, body = await _post_turn(+ launch, endpoint="responses",+ payload={"model": launch.runtime_model, "input": "hello", "stream": False},+ )+ assert (status, body) == (200, b'{"ok":true}')+ assert adapter.invocations == [(openai.id, "gpt-5.6-sol", "opencode")]+ finally:+ await gateway.close()++ # The row now runs an Agent, so removing it names that Agent.+ baseline = service.backend_catalog_models("opencode")+ with pytest.raises(ModelHubError) as refused:+ await service.set_agent_models(+ "opencode", baseline, [row for row in baseline if row["id"] != "gpt-5.6-sol"],+ )+ assert refused.value.data["would_interrupt"] == [+ {"backend": "opencode", "model_id": "openai/gpt-5.6-sol", "agents": ["opencode"]},+ ]++ # Leaving the Gateway keeps the catalog, and Direct runs each Agent's+ # own spelling again.+ direct = await service.set_agent_mode("opencode", "direct")+ assert list(model.id for model in store.load().agents["opencode"].models) == list(catalog)+ assert {row["name"]: row["effective_model_id"] for row in direct["named_agents"]} == dict(+ selections["opencode"]+ )++ asyncio.run(exercise())++def test_codex_backend_model_id_survives_until_gateway_resolution(tmp_path: Path,) -> None:diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.pyindex 075ff9efa..24ba226c7 100644--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py@@ -1365,6 +1365,43 @@ def test_opencode_native_provider_without_stable_identifier_is_visible_blocker(assert item.selected is False+def test_mh_switch_001_migration_carries_agent_models_into_the_switched_menu(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """MH-SWITCH-001: accepting migration carries each Agent's Direct selection+ into the menu it switches, served by the Sources that migration imported."""++ native_home = tmp_path / "native-home"+ _write_opencode(native_home)+ _isolate_native_home(monkeypatch, native_home)+ service, store, _ = _service(tmp_path)+ store.config.agents["opencode"].mode = "direct"+ service.named_agents_override = lambda backend: [+ ("opencode", "openrouter/openrouter-model"),+ ("zhipu", "zhipuai/zhipuai-model"),+ ("stranger", "openai/not-served"),+ ] if backend == "opencode" else []++ items = [item["id"] for item in service.migration_scan()["items"] if item["backend"] == "opencode"]+ assert asyncio.run(service.migration_apply(items))["applied"] == 2++ agent = _assert_canonical_round_trip(store.config).agents["opencode"]+ assert agent.mode == "hub"+ assert [(model.id, model.origin, model.native_protocol) for model in agent.models] == [+ ("openrouter-model", "provider", "openai_responses"),+ ("zhipuai-model", "provider", "openai_responses"),+ ]+ assert {+ row["name"]: (row["effective_model_id"], row["route_reason"])+ for row in service.get_agent_sources("opencode")["named_agents"]+ } == {+ "opencode": ("openrouter-model", None),+ "zhipu": ("zhipuai-model", None),+ "stranger": ("openai/not-served", "route_unconfigured"),+ }++def test_scan_keeps_invalid_endpoint_visible_while_valid_backend_items_remain_usable(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 2d82614c2..0e00414b7 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -389,14 +389,31 @@ def test_opencode_overlay_addresses_bare_ids_through_their_native_provider():opencode_model_for_overlay("missing", overlay)-def test_opencode_overlay_never_repairs_a_prefixed_identifier():+def test_opencode_overlay_runs_a_provider_qualified_selection_on_its_menu_row():+ """MH-SWITCH-002: a Direct-era ``<provider>/<model>`` selection names the+ Gateway row for its model part; an exact menu id always wins."""+overlay = SimpleNamespace(- model_provider_ids=(("gpt-5", "avibe-openai"),),- checked_identifiers=("gpt-5",),- available_identifiers=("gpt-5",),+ model_provider_ids=(+ ("gpt-5", "avibe-openai"),+ ("kimi-k2", "avibe-openai"),+ ("moonshotai/kimi-k2", "avibe-anthropic"),+ ),+ checked_identifiers=("gpt-5", "kimi-k2", "moonshotai/kimi-k2"),+ available_identifiers=("gpt-5", "kimi-k2", "moonshotai/kimi-k2"),)- with pytest.raises(ModelHubError):- opencode_model_for_overlay("openai/gpt-5", overlay)+ for selection in ("openai/gpt-5", "anthropic/gpt-5", "avibe-openai/gpt-5"):+ assert opencode_requested_model_for_overlay(selection, overlay) == "gpt-5"+ assert opencode_model_for_overlay(selection, overlay) == "avibe-openai/gpt-5"+ assert opencode_model_for_overlay("moonshotai/kimi-k2", overlay) == (+ "avibe-anthropic/moonshotai/kimi-k2"+ )+ assert opencode_model_for_overlay("openrouter/moonshotai/kimi-k2", overlay) == (+ "avibe-anthropic/moonshotai/kimi-k2"+ )+ for unserved in ("openai/gpt-6", "gpt-5/", "/gpt-5"):+ with pytest.raises(ModelHubError):+ opencode_model_for_overlay(unserved, overlay)def test_fallback_launch_identity_is_stable_for_same_route():