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): seed the Avibe Agent's providers and starting models (#2368)
Call Whited9c04138ae8b
diff --git a/config/v2_config.py b/config/v2_config.pyindex 58753829a..b9bdd6f0c 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -3012,18 +3012,29 @@ class ModelHubConfig:sources: list[ModelHubSourceConfig] = field(default_factory=list)agents: dict[str, ModelHubAgentSupplyConfig] = field(default_factory=lambda: {- backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in MODEL_HUB_BACKENDS+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")+ for backend in MODEL_HUB_BACKENDS+ if backend != "avibe"})# Fresh configs and explicit Start/Stop consume the default. Disk observers# retain a pending false marker until lock-owning startup commits promotion;# an unrelated save must not acknowledge an upgrade it did not perform.runtime_default_applied: bool = True+ # Not persisted, like ``V2Config.load_warnings``. True while the Avibe+ # entry was never supplied: a fresh install, or a file written before the+ # Avibe Agent existed. The empty entry standing in waits for its starting+ # supply (see ``ModelHubService._seed_avibe``), and until that seed, or any+ # other edit, touches it, ``to_payload`` keeps it absent, so an unrelated+ # write cannot record an empty supply as the user's choice.+ avibe_supply_pending: ClassVar[bool] = Falsedef __post_init__(self) -> None:# Existing in-process config producers may still supply the released# three-backend shape, just like older on-disk configurations.- self.agents.setdefault("avibe", ModelHubAgentSupplyConfig.default("avibe", mode="hub"))+ if "avibe" not in self.agents:+ self.agents["avibe"] = ModelHubAgentSupplyConfig.default("avibe", mode="hub")+ self.avibe_supply_pending = True@staticmethoddef source_eligible_for_backend(@@ -3106,6 +3117,9 @@ class ModelHubConfig:)agents = {}for backend in MODEL_HUB_BACKENDS:+ if backend == "avibe" and backend not in agents_payload:+ # Supplied by ``__post_init__``, which marks it pending.+ continueif backend not in agents_payload:# An omitted legacy backend is not consent to change its# working authentication. Fresh installs use the dataclass@@ -3128,6 +3142,7 @@ class ModelHubConfig:agents=agents,runtime_default_applied=runtime_default_applied,)+ agents = config.agentsfor backend in MODEL_HUB_BACKENDS:configured_sources = agents[backend].sourcesinvalid_id = next(@@ -3161,11 +3176,18 @@ class ModelHubConfig:return configdef to_payload(self) -> dict:+ unseeded = self.avibe_supply_pending and self.agents["avibe"] == ModelHubAgentSupplyConfig.default(+ "avibe", mode="hub"+ )return {"enabled": self.enabled,"runtime_default_applied": self.runtime_default_applied,"sources": [source.to_payload() for source in self.sources],- "agents": {backend: self.agents[backend].to_payload() for backend in MODEL_HUB_BACKENDS},+ "agents": {+ backend: self.agents[backend].to_payload()+ for backend in MODEL_HUB_BACKENDS+ if not (backend == "avibe" and unseeded)+ },}diff --git a/core/controller.py b/core/controller.pyindex 3723edf52..cacd9e615 100644--- a/core/controller.py+++ b/core/controller.py@@ -317,6 +317,7 @@ class Controller:# Background task for cleanupself.cleanup_task: Optional[asyncio.Task] = None+ self.avibe_model_supply_task: Optional[asyncio.Task] = Nonefrom modules.agents.avibe.recovery import AvibeRecovery# The single owner of the Avibe Agent's settlement outside a Turn.@@ -368,6 +369,83 @@ class Controller:result.append(backend)return result+ def _builtin_agent_models(self) -> list[tuple[str, str]]:+ """The models the built-in native Agents run, by backend name: claude, codex, opencode."""++ store = self.vibe_agent_store+ selections = []+ for backend in sorted(NATIVE_CLI_BACKENDS):+ agent = store.get_builtin_default_agent_for_backend(backend)+ model = str(getattr(agent, "model", None) or "").strip()+ if model:+ selections.append((backend, model))+ return selections++ def _reconcile_avibe_agent_model(self) -> None:+ """Give the built-in Avibe Agent its catalog's first model while it has none.++ An Avibe Agent without a model cannot run a turn, so this only makes an+ unrunnable Agent runnable. Decided under the store's write lock, it never+ replaces a model the user chose. It runs whenever the Avibe catalog+ changes (``backend_catalog_changed``) and at every start, so a hand-off a+ failed write or an exit lost heals on the next one. No built-in exists+ when a user Agent already holds the name.+ """++ from vibe.authorization import instance_owner_context++ models = self.model_hub_service.store.load().agents["avibe"].models+ if not models:+ return+ store = self.vibe_agent_store+ avibe = store.get_builtin_default_agent_for_backend("avibe", enabled_only=False)+ if avibe is None or str(avibe.model or "").strip():+ return+ store.update(+ avibe.name,+ model=models[0].id,+ only_if_model_unset=True,+ user_context=instance_owner_context(),+ )++ async def _model_hub_catalog_changed(self, backend: str) -> None:+ """Follow a committed Model Hub catalog change for one backend."""++ from config.v2_config import V2Config++ if backend == "avibe":+ try:+ self._reconcile_avibe_agent_model()+ except Exception:+ # The catalog change stands; the next start reconciles again.+ logger.warning("Avibe Agent model reconciliation failed", exc_info=True)+ try:+ latest = V2Config.load()+ except FileNotFoundError:+ return+ self.config.model_hub = latest.model_hub+ # Each runtime moves to the committed catalog at its next turn;+ # nothing restarts or drains. A disabled backend has nothing to adopt.+ agent = getattr(getattr(self, "agent_service", None), "agents", {}).get(backend)+ adopt_catalog = getattr(agent, "adopt_model_hub_catalog", None)+ if callable(adopt_catalog):+ await adopt_catalog()++ async def _seed_avibe_model_supply(self) -> None:+ """Seed the Avibe Agent's Model Hub entry from existing Sources, then reconcile its model."""++ model_hub_service = getattr(self, "model_hub_service", None)+ if model_hub_service is None:+ return+ try:+ await model_hub_service.seed_avibe_supply()+ except Exception:+ logger.warning("Avibe Agent starting model supply failed", exc_info=True)+ try:+ self._reconcile_avibe_agent_model()+ except Exception:+ logger.warning("Avibe Agent model reconciliation failed", exc_info=True)+def get_native_session_service(self):if self.native_session_service is None:from modules.agents.native_sessions.service import AgentNativeSessionService@@ -1170,6 +1248,14 @@ class Controller:exc_info=True,)+ try:+ # Off the readiness path: on a first start the seed may wait for a+ # models.dev copy, and nothing below needs it.+ if getattr(self, "avibe_model_supply_task", None) is None:+ self.avibe_model_supply_task = asyncio.create_task(self._seed_avibe_model_supply())+ except Exception as e:+ logger.error("Failed to start the Avibe Agent's model supply seed: %s", e, exc_info=True)+try:if self.cleanup_task is None or self.cleanup_task.done():self.cleanup_task = asyncio.create_task(self.periodic_cleanup())@@ -2332,6 +2418,16 @@ class Controller:passself.cleanup_task = None+ async def _cancel_avibe_model_supply_task() -> None:+ task = getattr(self, "avibe_model_supply_task", None)+ if task is not None and not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ self.avibe_model_supply_task = None+async def _cancel_trace_retention_task() -> None:cancel_event = getattr(self, "_trace_retention_cancel_event", None)if cancel_event is not None:@@ -2376,6 +2472,7 @@ class Controller:logger.debug(f"Internal dispatch server status write skipped: {e}")_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")+ _stop_loop_coroutine(_cancel_avibe_model_supply_task(), "Avibe Agent model supply seed")# Retention cancellation is cooperative at a delete-batch boundary;# wait for that bounded join instead of abandoning the worker after# the generic five-second cleanup timeout.@@ -2728,19 +2825,6 @@ 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- # Each runtime moves to the committed catalog at its next turn;- # nothing restarts or drains. A disabled backend has nothing to adopt.- agent = getattr(getattr(self, "agent_service", None), "agents", {}).get(backend)- adopt_catalog = getattr(agent, "adopt_model_hub_catalog", None)- if callable(adopt_catalog):- await adopt_catalog()-async def repair_model_selections(addresses: frozenset[str]) -> int:# A Vibe Agent's model, a channel's routing override, and a# session's pin are each a copy of an id the Model Hub menu once@@ -2759,9 +2843,10 @@ class Controller:requested_model_override=default_vibe_agent_model,selected_agent_override=default_vibe_agent_name,named_agents_override=named_vibe_agents,+ builtin_agent_models_override=self._builtin_agent_models,cli_present_override=cli_present,cli_presence_refresh=refresh_cli_presence,- backend_catalog_changed=backend_catalog_changed,+ backend_catalog_changed=self._model_hub_catalog_changed,repair_model_selections=repair_model_selections,)set_remote_catalog_refresh_completed(diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex 333f2d051..2439f98da 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -143,6 +143,10 @@ class MigrationHost(Protocol):def _save_config(self, config: ModelHubConfig) -> ModelHubConfig: ...+ async def _seed_avibe(self, config: ModelHubConfig) -> bool: ...++ async def _announce_avibe_seed(self) -> None: ...+def _carry_agent_selections(self, config: ModelHubConfig, backend: Any) -> None: ...def _reconcile_native_auth(self, backends: tuple[str, ...]) -> None: ...@@ -1862,6 +1866,10 @@ async def _prepare_takeover(source = ModelHubSourceConfig.from_payload(replacement)updated.sources = [source if value.id == source.id else value for value in updated.sources]_ensure_takeover_placement(updated, source, item.backend)+ # Now on the Hub, it is new to the Avibe Agent, which reaches every+ # Hub Source: placed like a new Source (a pending entry is seeded+ # below instead).+ host._apply_source_placement(updated, source, ("avibe",))else:updated.sources.append(source)host._apply_source_placement(updated, source)@@ -1874,6 +1882,9 @@ async def _prepare_takeover("store_backend": item.backend, "store_routing": item.native_store_routing or "",} if item.native_store_revision else {}),}+ if updated.avibe_supply_pending:+ # Once every Source of the batch is in place, reused identities too.+ await host._seed_avibe(updated)backends = sorted({item.backend for item in [*(consented or selected), *retained_keys]})native_before = _native_auth_snapshot(host, tuple(backends))# Copy-only keeps the Avibe-saved native key; Hub launches shadow it.@@ -2075,6 +2086,8 @@ async def _resume_takeover(# Save the decision without projecting staged grants into CPA.# sync_sources is a runtime write, not a config-only operation.host._save_config(updated)+ if previous.avibe_supply_pending and not updated.avibe_supply_pending:+ await host._announce_avibe_seed()host._engine_synced = Falsehost._reconcile_native_auth(tuple(record["backends"]))# This durable marker precedes any credential exposure to CPA.diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 9636c98f7..dd2e403aa 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -1052,6 +1052,9 @@ class ModelHubService:named_agents_override: Optional[Callable[[BackendName], list[tuple[str, Optional[str]]]]] = None,+ builtin_agent_models_override: Optional[+ Callable[[], list[tuple[BackendName, str]]]+ ] = None,cli_present_override: Optional[Callable[[BackendName], bool]] = None,cli_presence_refresh: Optional[Callable[[bool, tuple[BackendName, ...] | None], None]@@ -1102,6 +1105,9 @@ class ModelHubService:self.requested_model_override = requested_model_overrideself.selected_agent_override = selected_agent_overrideself.named_agents_override = named_agents_override+ # The built-in Agents' models for the Avibe starting supply; the+ # controller owns those Agent rows.+ self.builtin_agent_models_override = builtin_agent_models_overrideself.cli_present_override = cli_present_overrideself.cli_presence_refresh = cli_presence_refreshself.backend_catalog_changed = backend_catalog_changed@@ -2475,21 +2481,30 @@ class ModelHubService:number += 1config.sources.append(source)self._apply_source_placement(config, source)+ seeded = config.avibe_supply_pending and await self._seed_avibe(config)await self._commit_synced(previous, config)+ if seeded:+ await self._announce_avibe_seed()def _apply_source_placement(self,config: ModelHubConfig,source: ModelHubSourceConfig,+ backends: Iterable[str] = MODEL_HUB_BACKENDS,) -> None:"""Add a new Source to eligible backend defaults without editing overrides.A subscription serves a fixed catalog, so it joins only the backends whose- menu that catalog serves (OpenCode reaches every vendor), ahead of the API- keys there. API keys stay open to every eligible backend, appended.+ menu that catalog serves (OpenCode and the Avibe Agent reach every+ vendor), ahead of the API keys there. API keys stay open to every+ eligible backend, appended."""- for backend in MODEL_HUB_BACKENDS:+ for backend in backends:+ if backend == "avibe" and config.avibe_supply_pending:+ # Its seed places every Source at once, once the mutation's+ # Sources are final (see _seed_avibe).+ continueagent = config.agents[backend]if not self._eligible_for_agent(source, backend) or source.id in agent.sources.order:continue@@ -2515,9 +2530,13 @@ class ModelHubService:source: ModelHubSourceConfig,backend: BackendName,) -> bool:- if backend == "opencode" or _NATIVE_VENDOR_BACKENDS.get(source.vendor) == backend:- # The vendor's own Agent serves its subscription even when the- # catalog is ahead of the backend's menu.+ if (+ backend not in _NATIVE_VENDOR_BACKENDS.values()+ or _NATIVE_VENDOR_BACKENDS.get(source.vendor) == backend+ ):+ # A backend that is no one vendor's client (OpenCode, the Avibe+ # Agent) reaches every vendor, and the vendor's own Agent serves its+ # subscription even when the catalog is ahead of the backend's menu.return Trueif not agent.models or not any(not model.retired for model in source.models):return False@@ -5119,6 +5138,124 @@ class ModelHubService:checked=[model.id for model in agent.models],)+ async def _seed_avibe(self, config: ModelHubConfig) -> bool:+ """Give a pending Avibe entry its starting supply, in place; whether it took.++ Its Sources are every existing one this backend may use, placed as a+ newly created Source would be. Its models are the built-in Agents'+ selections, in order, that one of those Sources lists, each added as the+ picker adds a provider model; none qualifying leaves the list empty+ rather than picking one. The seed counts only once it has placed a+ Source: until then the entry stays pending, so the first Source the user+ adds still brings every Source and the starting models with it. Each+ mutation that adds Sources seeds after its Sources are final, so one+ that adds several seeds from all of them.+ """++ agent = config.agents["avibe"]+ if not any(self._eligible_for_agent(source, "avibe") for source in config.sources):+ return False+ # Seeded rows keep the models.dev metadata they are written with, so a+ # seed with no copy cached fetches one in the foreground, bounded; a+ # foreground fetch already running (the startup warm-up) is shared.+ await asyncio.to_thread(self._ensure_models_dev_copy)+ config.avibe_supply_pending = False+ for source in config.sources:+ self._apply_source_placement(config, source, ("avibe",))+ # A starting model is one a placed Source's own inventory lists; a+ # route, passthrough included, is no evidence.+ listed = {+ model.id+ for source in config.sources+ if source.id in agent.sources.order+ for model in source.models+ if not model.retired+ }+ selections = self.builtin_agent_models_override() if self.builtin_agent_models_override else ()+ model_ids: list[str] = []+ for backend, selected in selections:+ served = next(+ (+ candidate+ for candidate in (+ opencode_menu_model_candidates(selected)+ if backend == "opencode"+ else (selected,)+ )+ if candidate in listed+ ),+ None,+ )+ if served is not None and served not in model_ids:+ model_ids.append(served)+ described = self._models_dev_descriptions(model_ids)+ rows = []+ for model_id in model_ids:+ candidate = self._provider_candidate(config, "avibe", model_id, described.get(model_id))+ if candidate is not None:+ rows.append(candidate[0])+ agent.models = rows+ return True++ async def _announce_avibe_seed(self) -> None:+ """Announce a committed seed as the Avibe catalog change it is.++ Like every catalog mutation it ends in ``_refresh_backend_catalog``,+ whose owner reconciles the Avibe Agent's model. The seed is already+ committed, so a failed announcement is logged; the next start reconciles.+ """++ try:+ await self._refresh_backend_catalog("avibe")+ except Exception: # noqa: BLE001 - the committed supply stands+ logger.warning("Model Hub: the Avibe Agent's seeded catalog was not announced", exc_info=True)++ async def seed_avibe_supply(self) -> list[str]:+ """Seed a pending Avibe entry from the Sources that existed at startup.++ Source creation seeds a pending entry in its own mutation; this covers+ Sources that predate the Avibe Agent. Returns the seeded model ids.+ """++ if not self.store.load().avibe_supply_pending:+ return []+ # Seeded rows are written once and then kept, so a first models.dev copy+ # is worth one bounded foreground fetch, off the loop and outside the+ # lock. Taken even with no Source yet, so a fresh install's first+ # Source usually finds it.+ await asyncio.to_thread(self._ensure_models_dev_copy)+ async with self._mutation_lock:+ previous = self.store.load()+ if not previous.avibe_supply_pending:+ return []+ config = self._clone_config(previous)+ if not await self._seed_avibe(config):+ return []+ try:+ # An engine that is not up must not undo the seed: the config is+ # saved first, and the engine takes it on its next demand.+ await self._commit_synced(previous, config, rollback_on_sync_failure=False)+ except ModelHubError:+ if self.store.load().avibe_supply_pending:+ raise+ await self._announce_avibe_seed()+ return [model.id for model in config.agents["avibe"].models]++ def _ensure_models_dev_copy(self) -> None:+ """Fetch models.dev in the foreground, bounded, when no copy is cached.++ A foreground fetch already running is shared through the catalog's cache+ lock; a background refresh is not waited for. A failure leaves no copy.+ """++ from vibe.models_dev_catalog import load_models_dev_catalog++ try:+ if not self.models_dev_catalog():+ load_models_dev_catalog()+ except Exception as exc: # noqa: BLE001 - optional metadata never fails a seed+ logger.info("Avibe Agent seed has no models.dev metadata: %s", type(exc).__name__)+async def set_agent_mode(self, backend: str, mode: object) -> dict:if mode not in {"hub", "direct"} or (backend == "avibe" and mode != "hub"):raise ModelHubError("mode_switch_blocked")@@ -8694,6 +8831,9 @@ def create_default_service(named_agents_override: Optional[Callable[[BackendName], list[tuple[str, Optional[str]]]]] = None,+ builtin_agent_models_override: Optional[+ Callable[[], list[tuple[BackendName, str]]]+ ] = None,cli_present_override: Optional[Callable[[BackendName], bool]] = None,cli_presence_refresh: Optional[Callable[[bool, tuple[BackendName, ...] | None], None]@@ -8754,6 +8894,7 @@ def create_default_service(requested_model_override=requested_model_override,selected_agent_override=selected_agent_override,named_agents_override=named_agents_override,+ builtin_agent_models_override=builtin_agent_models_override,cli_present_override=cli_present_override,cli_presence_refresh=cli_presence_refresh,backend_catalog_changed=backend_catalog_changed,diff --git a/core/vibe_agents.py b/core/vibe_agents.pyindex 071532721..4c9dbf12d 100644--- a/core/vibe_agents.py+++ b/core/vibe_agents.py@@ -1048,6 +1048,7 @@ class VibeAgentStore:system_prompt: Any = _UNSET,metadata: Any = _UNSET,enabled: Any = _UNSET,+ only_if_model_unset: bool = False,user_context: Any = None,) -> VibeAgent:normalized = normalize_agent_name(name)@@ -1068,6 +1069,9 @@ class VibeAgentStore:)if existing.archived_at is not None:raise AgentArchivedEditError(agent_name=name)+ if only_if_model_unset and _clean_optional(existing.model):+ # Decided under the write lock, so a model chosen meanwhile stands.+ return existingvalues: dict[str, Any] = {"updated_at": _utc_now_iso()}if description is not _UNSET:diff --git a/docs/plans/model-hub-contracts/avibe-consumer.md b/docs/plans/model-hub-contracts/avibe-consumer.mdindex 7c0949299..8a215035b 100644--- a/docs/plans/model-hub-contracts/avibe-consumer.md+++ b/docs/plans/model-hub-contracts/avibe-consumer.md@@ -12,10 +12,34 @@ the existing `resolve("avibe", ...)`; `ModelHubLaunch.to_hop_resolution()` projethat launch. There is no second planner, credential store, or upstream client.The backend id is `avibe`. It has a fixed catalog (ordinary editable model rows),-no native protocol pin, no native CLI, and no Direct mode. Its default catalog and-source order are empty. Old configurations acquire only that empty Hub row;-existing backend modes, model metadata, routes, source order, and runtime intent-remain unchanged. An empty Avibe catalog does not prevent an explicit runtime Stop.+no native protocol pin, no native CLI, and no Direct mode. Until its starting+supply is seeded, the Avibe row is pending: a fresh configuration, or one written+before the Avibe Agent existed, reads an empty Hub row that writes leave absent.+The seed runs once, when a Source it can place exists: in the background after+the service reports ready for Sources that already exist (so a first models.dev+fetch never delays startup), and otherwise inside the mutation that creates the+first eligible Source, API key, OAuth, or native takeover alike, once that+mutation's Sources are final, so no restart is needed. Its source order becomes every existing eligible Source, placed exactly as+a newly created Source would be (like OpenCode, Avibe reaches every vendor, so a+subscription joins it whether or not a starting model matches, ahead of the API+keys), and its catalog becomes the models the built-in+Claude, Codex, and OpenCode Agents run, in that order, that one of those Sources+lists, deduplicated and added as the picker adds a provider model (models.dev+metadata included). None qualifying leaves the catalog empty; no model is picked+on the user's behalf. An Avibe Agent without a model cannot run a turn, so the+built-in one takes its catalog's first model while it has none: one controller+rule, decided under the Agent store's write lock so a chosen model stands, run+on every Avibe catalog change (`_refresh_backend_catalog`, which each seed also+announces) and at every start, so a lost hand-off heals on the next start. A+seed with no models.dev copy cached first fetches one in the foreground, bounded,+so its rows usually carry the limits the Agent budgets with; a starting model is+one a placed Source's own non-retired inventory lists, never a passthrough route. A native Source that later moves+to the Hub joins Avibe like a new Source.+Where a user Agent already holds the name and no built-in exists, only the+supply is seeded.+The persisted row then belongs to the user and is never seeded again. Existing+backend modes, model metadata, routes, source order, and runtime intent remain+unchanged. An empty Avibe catalog does not prevent an explicit runtime Stop.The primary currently selected hop owns `protocol`, `provider` (the Source's vendoridentity), and `source_id`. `base_url` is the loopback gateway's `/avibe/v1` API root;@@ -164,6 +188,9 @@ The header needs no upstream credentials and is never forwarded upstream.- Released-shape loading: old modes/routes/capabilities survive without mutation;the new row is empty Hub, and native-cli Sources remain ineligible.+- Starting supply (MH-AVIBE-007): an unrelated write keeps the unseeded row absent;+ the seed places existing Sources for Avibe alone and keeps only routable Agent+ models; a second start leaves the persisted row, including removed Sources, alone.- Real loopback gateway requests through the existing service, with hermetic enginefixtures: primary protocol resolution, cross-protocol failover, non-ASCII origin,slow Anthropic resolution, buffered/streamed bodies, and concurrent requests.diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex f14bc05b6..eefef499d 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -135,6 +135,18 @@ scenarios:kind: compatibilitylayer: contracttest: tests/test_model_hub_avibe_consumer.py::test_released_config_adds_only_empty_avibe_supply+ - id: MH-AVIBE-007+ name: The Avibe Agent starts once with the user's Sources and built-in Agent models, seeded when its first Source exists+ status: covered+ kind: compatibility+ layer: contract+ test: tests/test_model_hub_avibe_consumer.py::test_avibe_agent_predating_its_supply_starts_with_the_users_providers_and_models+ related_tests:+ - tests/test_model_hub_avibe_consumer.py::test_fresh_install_seeds_avibe_with_its_first_source+ - tests/test_model_hub_native_takeover.py::test_takeover_seeds_a_pending_avibe_entry_from_its_whole_batch+ - tests/test_avibe_backend_registration.py::test_avibe_agent_runs_its_catalogs_first_model_until_it_has_one+ - tests/test_avibe_backend_registration.py::test_a_lost_avibe_model_hand_off_heals_on_the_next_start+ - tests/test_controller_im_ready.py::test_runtime_services_start_when_post_update_notification_fails- id: MH-AVIBE-004name: Avibe refuses native CLI sources and Direct modestatus: covereddiff --git a/tests/test_avibe_backend_registration.py b/tests/test_avibe_backend_registration.pyindex 903e421fe..7194d641a 100644--- a/tests/test_avibe_backend_registration.py+++ b/tests/test_avibe_backend_registration.py@@ -2,11 +2,14 @@from __future__ import annotations+import asyncioimport jsonfrom pathlib import Pathfrom types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest+from sqlalchemy.exc import OperationalErrorfrom config.v2_config import V2Configfrom config.v2_compat import to_app_config@@ -210,3 +213,144 @@ def test_avibe_model_options_come_from_configured_hub_catalog(monkeypatch):]config.model_hub.agents["avibe"].models = []assert api.agent_model_options("avibe")["models"] == []+++def _hub_catalog(*model_ids, origin="provider"):+ from config.v2_config import ModelHubBackendModelConfig, ModelHubConfig++ config = ModelHubConfig()+ config.agents["avibe"].models = [ModelHubBackendModelConfig(id=model_id, origin=origin) for model_id in model_ids]+ return SimpleNamespace(store=SimpleNamespace(load=lambda: config))++[email protected]("avibe", ["seeded", "user-built list", "chosen", "name taken", "empty list"])+def test_avibe_agent_runs_its_catalogs_first_model_until_it_has_one(tmp_path, sqlite_db_factory, avibe):+ """MH-AVIBE-007: the Agent rows behind the Hub seed, owned by this process.++ The built-in native Agents' models feed the seed in backend-name order. An+ Avibe Agent without a model cannot run a turn, so it takes its catalog's+ first model, seeded or listed by the user, and only while it has none: a+ model the user chose stands. When a user Agent already holds the name, no+ built-in exists and that Agent is left alone.+ """+ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))+ try:+ if avibe == "name taken":+ store.create(name="avibe", backend="claude", model="claude-haiku-4-5")+ store.ensure_builtin_default_agents(["opencode", "claude", "codex", "avibe"])+ store.create(name="reviewer", backend="claude", model="claude-sonnet-5-5")+ for name, model in (("claude", "claude-opus-5-5"), ("codex", "gpt-5.5"), ("opencode", "openai/gpt-6-sol")):+ store.update(name, model=model)+ if avibe == "chosen":+ store.update("avibe", model="chosen-model")+ controller = Controller.__new__(Controller)+ controller.vibe_agent_store = store+ controller.model_hub_service = {+ "empty list": _hub_catalog(),+ "user-built list": _hub_catalog("my-relay-model", "gpt-5.5", origin="manual"),+ }.get(avibe, _hub_catalog("gpt-5.5", "claude-opus-5-5"))++ assert controller._builtin_agent_models() == [+ ("claude", "claude-opus-5-5"), ("codex", "gpt-5.5"), ("opencode", "openai/gpt-6-sol"),+ ]+ controller._reconcile_avibe_agent_model()+ assert (store.get("avibe").backend, store.get("avibe").model) == {+ "seeded": ("avibe", "gpt-5.5"),+ "user-built list": ("avibe", "my-relay-model"),+ "chosen": ("avibe", "chosen-model"),+ "name taken": ("claude", "claude-haiku-4-5"),+ "empty list": ("avibe", None),+ }[avibe]+ finally:+ store.close()+++def test_a_lost_avibe_model_hand_off_heals_on_the_next_start(tmp_path, sqlite_db_factory, monkeypatch):+ """MH-AVIBE-007: a failed Agent write after a committed seed heals at the next start."""+ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))+ try:+ store.ensure_builtin_default_agents(["avibe"])+ controller = Controller.__new__(Controller)+ controller.vibe_agent_store = store+ hub = _hub_catalog("gpt-5.5")+ controller.model_hub_service = SimpleNamespace(store=hub.store, seed_avibe_supply=AsyncMock(return_value=[]))+ real_update = store.update++ def locked_database(*args, **kwargs):+ raise OperationalError("UPDATE agents", {}, Exception("database is locked"))++ # The seed's catalog announcement: its reconciliation fails, the supply stays.+ monkeypatch.setattr(store, "update", locked_database)+ asyncio.run(controller._model_hub_catalog_changed("avibe"))+ assert store.get("avibe").model is None++ monkeypatch.setattr(store, "update", real_update)+ asyncio.run(controller._seed_avibe_model_supply())+ assert store.get("avibe").model == "gpt-5.5"+ finally:+ store.close()+++async def test_the_first_model_a_user_adds_makes_the_avibe_agent_runnable(tmp_path, sqlite_db_factory):+ """MH-AVIBE-007: any Avibe catalog change reconciles the Agent, not only a seed.++ A seed that found no starting model leaves the catalog empty; the model the+ user then adds by hand reaches the Agent without a restart, through the+ same catalog-change notification every catalog edit sends.+ """+ from tests.test_model_hub_l3 import _canonicalize_fixed_test_routes, _service, _source++ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))+ try:+ store.ensure_builtin_default_agents(["avibe"])+ service = _service(tmp_path, sources=[_source("src_relay0001", "Relay", protocol="openai_chat", model_id="relay-model")])+ _canonicalize_fixed_test_routes(service)+ controller = Controller.__new__(Controller)+ controller.vibe_agent_store = store+ controller.model_hub_service = service+ service.backend_catalog_changed = controller._model_hub_catalog_changed++ assert await service.seed_avibe_supply() == []+ assert store.get("avibe").model is None+ candidate, = service.agent_model_candidates("avibe")["providers"]+ await service.set_agent_models("avibe", [], [{key: value for key, value in candidate.items() if key != "suppliers"}])+ assert store.get("avibe").model == "relay-model"+ finally:+ store.close()+++async def test_a_starting_model_needs_a_source_that_lists_it(tmp_path, sqlite_db_factory):+ """MH-AVIBE-007: a Source's inventory, not a route, decides a starting model.++ An Anthropic key could pass any model id through, but it lists only Claude+ models: the Codex Agent's ``gpt-6-astra`` is no starting model for Avibe,+ and the Avibe Agent stays without a model rather than routing it there.+ """+ from config.v2_config import ModelHubConfig+ from tests.test_model_hub_l3 import _service, _source++ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))+ try:+ store.ensure_builtin_default_agents(["codex", "avibe"])+ store.update("codex", model="gpt-6-astra")+ service = _service(tmp_path, sources=[])+ service.store.config = ModelHubConfig()+ controller = Controller.__new__(Controller)+ controller.vibe_agent_store = store+ controller.model_hub_service = service+ service.builtin_agent_models_override = controller._builtin_agent_models+ service.backend_catalog_changed = controller._model_hub_catalog_changed+ anthropic = _source(+ "src_anthropic01", "Anthropic key", vendor="anthropic", protocol="anthropic", model_id="claude-opus-5-5",+ )++ async with service._mutation_lock:+ await service._commit_new_source_locked(anthropic)++ avibe = service.store.load().agents["avibe"]+ assert (avibe.sources.order, avibe.models) == ([anthropic.id], [])+ assert store.get("avibe").model is None+ finally:+ store.close()diff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.pyindex ef677386a..6120c8208 100644--- a/tests/test_controller_im_ready.py+++ b/tests/test_controller_im_ready.py@@ -33,9 +33,18 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:recover_persisted_agent_run_queue=AsyncMock(return_value=[]),)controller.runtime_work_supervisor = SimpleNamespace(activate=AsyncMock())+ seed_started = []++ async def seed_avibe_supply():+ # A first start may wait on models.dev; startup must not wait with it.+ seed_started.append(True)+ await asyncio.Event().wait()+controller.model_hub_service = SimpleNamespace(- recover_runtime_intent=AsyncMock()+ recover_runtime_intent=AsyncMock(),+ seed_avibe_supply=seed_avibe_supply,)+ controller.avibe_model_supply_task = Nonecontroller._get_idle_cleanup_timeouts = Mock(return_value=(0, 0))controller.cleanup_task = Nonecontroller.trace_retention_task = None@@ -46,7 +55,12 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:# the service lock, which no test process does.controller._im_run_exception = None- asyncio.run(controller._on_runtime_ready())+ async def start_up():+ await asyncio.wait_for(controller._on_runtime_ready(), timeout=5)+ await asyncio.sleep(0)++ asyncio.run(start_up())+ assert seed_started == [True]opencode_agent.restore_active_polls.assert_awaited_once_with({"avibe"})codex_agent.prepare_model_hub_runtime.assert_awaited_once_with()diff --git a/tests/test_model_hub_avibe_consumer.py b/tests/test_model_hub_avibe_consumer.pyindex fe3bd076a..eb01b23d6 100644--- a/tests/test_model_hub_avibe_consumer.py+++ b/tests/test_model_hub_avibe_consumer.py@@ -21,10 +21,14 @@ from jsonschema import Draft7Validator, ValidationErrorfrom referencing import Registry, Resourcefrom config.v2_config import (+ ModelHubAgentSupplyConfig,ModelHubBackendModelConfig,ModelHubConfig,+ ModelHubModelConfig,ModelHubRouteConfig,ModelHubRouteHopConfig,+ ModelHubSourceConfig,+ ModelHubSourceStateConfig,)from core.handlers.model_hub.adapter import RawOutcomeKindfrom core.handlers.model_hub.provenance import BoundedProvenanceStore, HopOrigin, SERVED_HOP_HEADER@@ -562,6 +566,199 @@ def test_released_config_adds_only_empty_avibe_supply():assert ModelHubConfig.from_payload(config.to_payload()).to_payload() == config.to_payload()+class _PersistedStore:+ """Reads and writes the persisted payload, as the config file does."""++ def __init__(self, payload: dict):+ self.payload = payload++ def load(self) -> ModelHubConfig:+ return ModelHubConfig.from_payload(copy.deepcopy(self.payload))++ def save(self, config: ModelHubConfig) -> None:+ self.payload = config.to_payload()+++def _seed_source(source_id, day, *model_ids, kind="api_key", vendor="openai", protocol="openai_responses", channel="hub"):+ return ModelHubSourceConfig(+ id=source_id, kind=kind, vendor=vendor, display_name=source_id[4:], protocol=protocol,+ supply_channel=channel, billing="metered" if kind == "api_key" else "monthly",+ state=ModelHubSourceStateConfig(status="active" if channel == "native_cli" else "standby"),+ models=[ModelHubModelConfig(id=model_id, provenance="discovered") for model_id in model_ids],+ created_at=f"2026-01-0{day}T00:00:00Z",+ credential_ref=None if channel == "native_cli" else f"cred_{source_id}",+ )+++SEED_ANTHROPIC = _seed_source(+ "src_seedanthropic", 1, "claude-opus-5-5", "claude-sonnet-5-5", vendor="anthropic", protocol="anthropic",+)+SEED_RESPONSES = _seed_source("src_seedresponses", 2, "gpt-5.6-sol")+SEED_CHAT = _seed_source("src_seedchat0001", 3, "模型/β", vendor="custom", protocol="openai_chat")+SEED_SUBSCRIPTION = _seed_source("src_seedsubscribe", 4, "gpt-5.6-sol", kind="subscription")+SEED_NATIVE = _seed_source(+ "src_seednative01", 5, "claude-opus-5-5",+ kind="subscription", vendor="anthropic", protocol="anthropic", channel="native_cli",+)+SEED_KEYS = [SEED_ANTHROPIC.id, SEED_RESPONSES.id, SEED_CHAT.id]+SEED_CATALOG = {"anthropic": {"name": "Anthropic", "models": {+ "claude-opus-5-5": {"name": "Claude Opus 5.5", "limit": {"context": 1_000_000, "output": 128_000}},+}}}+++def _seed_service(tmp_path, payload, selections):+ """A service over persisted state, with the controller's two Agent-row hooks."""+ service = _service(tmp_path, sources=[])+ service.store = _PersistedStore(payload)+ service.models_dev_catalog = lambda: SEED_CATALOG+ service.builtin_agent_models_override = lambda: list(selections)+ announced = []++ async def catalog_changed(backend):+ announced.append(backend)++ service.backend_catalog_changed = catalog_changed+ return service, service.store, announced++[email protected](("selections", "seeded"), [+ # Each built-in Agent's model, in order; OpenCode's names its provider, and+ # a model reached twice is listed once.+ (+ [("claude", "claude-opus-5-5"), ("codex", "gpt-5.6-sol"), ("opencode", "openai/gpt-5.6-sol")],+ ["claude-opus-5-5", "gpt-5.6-sol"],+ ),+ # A model no Source lists is no start, and a menu id may carry a slash.+ (+ [("claude", "opus"), ("codex", "gpt-6-astra"), ("opencode", "custom/模型/β")],+ ["模型/β"],+ ),+ # Nothing qualifies: the list starts empty, and the picker offers every+ # provider model.+ ([], []),+])+async def test_avibe_agent_predating_its_supply_starts_with_the_users_providers_and_models(+ tmp_path, selections, seeded,+):+ """MH-AVIBE-007: one seed from the Sources and Agent models the user already has.++ A config written before the Avibe Agent existed has Sources that were never+ placed for it, so its picker offered no provider model at all.+ """+ agents = {backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in ("claude", "codex", "opencode")}+ # The user keeps one Source for Claude; seeding Avibe must not restore the rest.+ agents["claude"].sources.order = [SEED_ANTHROPIC.id]+ sources = [SEED_ANTHROPIC, SEED_RESPONSES, SEED_CHAT, SEED_SUBSCRIPTION, SEED_NATIVE]+ service, store, _announced = _seed_service(tmp_path, {+ "enabled": True,+ "runtime_default_applied": True,+ "sources": [source.to_payload() for source in sources],+ "agents": {backend: agent.to_payload() for backend, agent in agents.items()},+ }, selections)+ # An unrelated write ahead of the seed (a startup reconcile, a settings+ # save) must not record the empty placeholder as the user's entry.+ store.save(store.load())+ assert "avibe" not in store.payload["agents"]++ async def engine_not_started(_bindings):+ # Startup seeds before the engine is up; the seed must not depend on it.+ raise ModelHubError("engine_down", status=503)++ service.adapter.sync_sources = engine_not_started+ others = {backend: store.payload["agents"][backend] for backend in agents}++ assert await service.seed_avibe_supply() == seeded+ avibe = store.payload["agents"]["avibe"]+ # Every Source Avibe may use joins, subscriptions ahead of keys, whether or+ # not a starting model matches: like OpenCode, it reaches every vendor.+ assert avibe["sources"]["order"] == [SEED_SUBSCRIPTION.id, *SEED_KEYS]+ assert [model["id"] for model in avibe["models"]] == seeded+ assert {backend: store.payload["agents"][backend] for backend in agents} == others+ if "claude-opus-5-5" in seeded:+ row = next(model for model in avibe["models"] if model["id"] == "claude-opus-5-5")+ assert (row["origin"], row["display_name"], row["context_window"], row["max_output_tokens"]) == (+ "provider", "Claude Opus 5.5", 1_000_000, 128_000,+ )+ candidates = service.agent_model_candidates("avibe")+ listed = {model.id for source in (SEED_ANTHROPIC, SEED_RESPONSES, SEED_CHAT, SEED_SUBSCRIPTION) for model in source.models}+ assert {candidate["id"] for candidate in candidates["providers"]} == listed - set(seeded)+ assert [candidate["id"] for candidate in candidates["in_list"]] == seeded++ # The persisted entry is the user's: a Source they removed stays removed.+ avibe["sources"]["order"].remove(SEED_CHAT.id)+ kept = copy.deepcopy(store.payload)+ assert await service.seed_avibe_supply() == []+ assert store.payload == kept++[email protected](("first", "selections", "seeded"), [+ (SEED_ANTHROPIC, [("claude", "claude-opus-5-5"), ("codex", "gpt-6-astra")], ["claude-opus-5-5"]),+ # Typical of a fresh install: no Agent runs a model this Source lists, and+ # none is picked for the user.+ (SEED_ANTHROPIC, [("codex", "gpt-6-astra")], []),+ # A subscription joins even when no starting model matches it, so its+ # catalog still reaches the picker.+ (SEED_SUBSCRIPTION, [("codex", "gpt-6-astra")], []),+])+async def test_fresh_install_seeds_avibe_with_its_first_source(tmp_path, first, selections, seeded):+ """MH-AVIBE-007: on a fresh install the first eligible Source seeds Avibe at once.++ A seed with no Source to place is not a seed: counted as done, it would+ leave every later Source without starting models, and skipping the pending+ entry at placement would leave the first Source out until a restart.+ """+ service, store, announced = _seed_service(tmp_path, ModelHubConfig().to_payload(), selections)+ assert "avibe" not in store.payload["agents"]++ assert await service.seed_avibe_supply() == []+ native = copy.deepcopy(SEED_NATIVE)+ await service._commit_new_source_locked(native)+ assert "avibe" not in store.payload["agents"]+ assert announced == []++ await service._commit_new_source_locked(copy.deepcopy(first))+ avibe = store.payload["agents"]["avibe"]+ assert avibe["sources"]["order"] == [first.id]+ assert [model["id"] for model in avibe["models"]] == seeded+ assert announced == ["avibe"]+ assert {candidate["id"] for candidate in service.agent_model_candidates("avibe")["providers"]} == (+ {model.id for model in first.models} - set(seeded)+ )++ # Seeded once: a later Source is placed like any other, and nothing re-seeds.+ await service._commit_new_source_locked(copy.deepcopy(SEED_CHAT))+ avibe = store.payload["agents"]["avibe"]+ assert avibe["sources"]["order"] == [first.id, SEED_CHAT.id]+ assert [model["id"] for model in avibe["models"]] == seeded+ assert announced == ["avibe"]+++async def test_the_first_source_seed_fetches_a_models_dev_copy_when_none_is_cached(tmp_path, monkeypatch):+ """MH-AVIBE-007: seeded rows keep the metadata they are written with.++ On a fresh install the first Source can arrive before any models.dev copy+ is cached, so the seed fetches one first rather than writing rows without+ the context window and output limit the Agent budgets with.+ """+ service, store, _announced = _seed_service(+ tmp_path, ModelHubConfig().to_payload(), [("claude", "claude-opus-5-5")],+ )+ copy_on_disk = {}+ service.models_dev_catalog = lambda: copy_on_disk++ def fetch_first_copy():+ copy_on_disk.update(SEED_CATALOG)+ return copy_on_disk++ monkeypatch.setattr("vibe.models_dev_catalog.load_models_dev_catalog", fetch_first_copy)+ await service._commit_new_source_locked(copy.deepcopy(SEED_ANTHROPIC))+ [row] = store.payload["agents"]["avibe"]["models"]+ assert (row["id"], row["context_window"], row["max_output_tokens"]) == ("claude-opus-5-5", 1_000_000, 128_000)++def test_native_cli_and_direct_are_not_avibe_channels(tmp_path):"""MH-AVIBE-004: neither invalid persisted state nor routing can select a CLI."""native = _source("src_native001", "Native", channel="native_cli", vendor="anthropic", protocol="anthropic")diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 8c0c2c967..6a1b88094 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -3156,6 +3156,8 @@ def test_v2_empty_route_normalizes_on_load_without_writing_until_save(tmp_path,@pytest.mark.parametrize("bad_key", ["", "authorization=sk-unsafe-fixture"])def test_invalid_empty_route_key_keeps_v2_recovery_fence(tmp_path, backend, bad_key):payload = api.config_to_payload(default_config())+ # A fresh config leaves the Avibe entry unwritten until it is seeded.+ payload["model_hub"]["agents"].setdefault(backend, ModelHubAgentSupplyConfig.default(backend, mode="hub").to_payload())payload["model_hub"]["agents"][backend]["routes"][bad_key] = {"hops": []}path = tmp_path / "config.json"path.write_text(json.dumps(payload), encoding="utf-8")diff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.pyindex 6519e8f1f..716aa3b21 100644--- a/tests/test_model_hub_native_takeover.py+++ b/tests/test_model_hub_native_takeover.py@@ -10,7 +10,12 @@ import pytestfrom core.handlers.model_hub.migration_journal import NativeFileEdit, NativeTakeoverJournalfrom core.handlers.model_hub.service import EngineUnavailableError, ModelHubError-from config.v2_config import ModelHubConfig+from config.v2_config import (+ ModelHubConfig,+ ModelHubModelConfig,+ ModelHubSourceConfig,+ ModelHubSourceStateConfig,+)from core.handlers.model_hub.adapter import (OAuthCredentialRejectedError,OAuthFlowState,@@ -87,6 +92,70 @@ def test_oauth_is_not_exposed_until_native_cleanup_and_mode_commit(monkeypatch,assert "refresh_token" not in service.migration_journal.path.with_name("last-completed.json").read_text()[email protected]("batch", ["two new Sources", "a reused native Source", "a reused native Source after the seed"])+def test_takeover_seeds_a_pending_avibe_entry_from_its_whole_batch(monkeypatch, tmp_path, batch):+ """MH-AVIBE-007: a takeover seeds Avibe once its Sources are final.++ A batch importing several Sources seeds from all of them, so a starting+ model only a later Source serves still arrives; a native Source converted+ to the Hub in place seeds too. The takeover commits through its journal,+ so its own save announces the Avibe catalog change like any other. Once+ seeded, a native Source moving to the Hub is new to Avibe and joins it.+ """+ home = tmp_path / "native"+ _write_claude_oauth(home)+ _isolate_native_home(monkeypatch, home)+ service, store, _adapter = _service(tmp_path, migration_home=home)+ store.config.agents["claude"].mode = "direct"+ if batch == "two new Sources":+ _write_codex_oauth(home)+ store.config.agents["codex"].mode = "direct"+ # The first Source alone would already seed; gpt-5.5 is served only by+ # the Codex subscription, which the batch adds second.+ selections = [("claude", "claude-opus-5-5"), ("codex", "gpt-5.5")]+ else:+ native = ModelHubSourceConfig(+ id="src_nativeclaude", kind="subscription", vendor="anthropic", display_name="Claude",+ protocol="anthropic", supply_channel="native_cli", billing="monthly",+ state=ModelHubSourceStateConfig(status="active"),+ models=[ModelHubModelConfig(id="claude-opus-5-5", provenance="discovered")],+ )+ store.config.sources.append(native)+ store.config.agents["claude"].sources.order = [native.id]+ selections = [("claude", "claude-opus-5-5")]+ if batch == "a reused native Source after the seed":+ store.config.avibe_supply_pending = False+ else:+ assert store.config.avibe_supply_pending+ service.builtin_agent_models_override = lambda: selections+ announced = []++ async def catalog_changed(backend):+ announced.append(backend)++ service.backend_catalog_changed = catalog_changed+ items = service.migration_scan()["items"]+ assert [item["backend"] for item in items] == (+ ["claude", "codex"] if batch == "two new Sources" else ["claude"]+ )++ asyncio.run(service.migration_apply([item["id"] for item in items], clean_api_keys=True))++ starting = [model for _backend, model in selections]+ serving = [+ source.id for model in starting for source in store.config.sources+ if source.supply_channel == "hub" and any(item.id == model for item in source.models)+ ]+ avibe = store.config.agents["avibe"]+ assert not store.config.avibe_supply_pending+ if batch == "a reused native Source after the seed":+ # Placed like a new Source; the user's catalog is not seeded again.+ assert (avibe.sources.order, avibe.models, announced) == (serving, [], [])+ return+ assert (avibe.sources.order, [model.id for model in avibe.models]) == (serving, starting)+ assert announced == ["avibe"]++def test_failure_after_possible_rotation_retains_current_owner_and_retries(monkeypatch, tmp_path):home = tmp_path / "native"_write_codex_oauth(home)diff --git a/tests/test_model_hub_runtime_default_upgrade.py b/tests/test_model_hub_runtime_default_upgrade.pyindex 155681cf1..92add2901 100644--- a/tests/test_model_hub_runtime_default_upgrade.py+++ b/tests/test_model_hub_runtime_default_upgrade.py@@ -16,20 +16,14 @@ from config import v2_configfrom config.v2_config import ModelHubConfig, V2Config, update_config_fields-EMPTY_AVIBE_SUPPLY = {- "backend": "avibe", "mode": "hub", "menu_kind": "fixed",- "sources": {"order": []}, "routes": {}, "menu": None,- "models": [], "removed_model_ids": [],-}--def legacy_payload(tmp_path, *, enabled=False):fixture_path = tmp_path / "fixture-default.json"V2Config.default().save(config_path=fixture_path)payload = read_config(fixture_path)payload["model_hub"].pop("runtime_default_applied")payload["model_hub"]["enabled"] = enabled- payload["model_hub"]["agents"].pop("avibe")+ # A released config predates the Avibe entry (a fresh one leaves it unwritten too).+ payload["model_hub"]["agents"].pop("avibe", None)for backend in ("claude", "codex", "opencode"):payload["model_hub"]["agents"][backend]["mode"] = "direct"# Synthetic state proves the upgrade does not clear credentials or change@@ -54,9 +48,8 @@ def read_config(path):def assert_no_native_change(original, upgraded):assert upgraded["agents"] == original["agents"]- assert upgraded["model_hub"]["agents"] == {- **original["model_hub"]["agents"], "avibe": EMPTY_AVIBE_SUPPLY,- }+ # The Avibe row stays absent until startup seeds it (MH-AVIBE-007).+ assert upgraded["model_hub"]["agents"] == original["model_hub"]["agents"]assert upgraded["model_hub"]["sources"] == original["model_hub"]["sources"]assert {key: value for key, value in upgraded.items() if key != "model_hub"} == {key: value for key, value in original.items() if key != "model_hub"@@ -207,9 +200,7 @@ def test_service_runtime_stop_round_trips_real_store_with_fake_runtime(tmp_path,assert loaded.model_hub.runtime_default_applied is Trueassert path.read_bytes() == persistedassert read_config(path)["agents"] == payload["agents"]- assert read_config(path)["model_hub"]["agents"] == {- **payload["model_hub"]["agents"], "avibe": EMPTY_AVIBE_SUPPLY,- }+ assert read_config(path)["model_hub"]["agents"] == payload["model_hub"]["agents"]def test_new_explicit_stop_is_not_reinterpreted_as_old_default(tmp_path):