Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): migrate saved API keys without upstream validation (#2602)

Call Whitefb81ec164307
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.py
index 9c01c19f4..68dd1120b 100644
--- a/core/handlers/model_hub/migration.py
+++ b/core/handlers/model_hub/migration.py
@@ -17,16 +17,12 @@ from typing import Any, Awaitable, Callable, Collection, Literal, Mapping, Optio
from config.v2_config import (
MODEL_HUB_BACKENDS,
ModelHubConfig,
- ModelHubModelConfig,
ModelHubSourceConfig,
ModelHubSourceStateConfig,
)
from core.handlers.model_hub.adapter import (
DiscoveredModel,
- ObservationDiscovery,
- ObservationOutcome,
OAuthCredentialRejectedError,
- SourceObservation,
)
from core.handlers.model_hub.events import contains_credential_material
from core.handlers.model_hub.identifiers import canonical_model_id
@@ -144,11 +140,14 @@ class MigrationHost(Protocol):
def _save_config(self, config: ModelHubConfig) -> ModelHubConfig: ...
- async def _seed_vibey(self, config: ModelHubConfig) -> bool: ...
+ async def _seed_vibey(self, config: ModelHubConfig, *, fetch_catalog: bool = True) -> bool: ...
async def _announce_vibey_seed(self) -> None: ...
- def _carry_agent_selections(self, config: ModelHubConfig, backend: Any) -> None: ...
+ def _carry_agent_selections(
+ self, config: ModelHubConfig, backend: Any, *, native_sources: Collection[tuple[str, str]] = (),
+ fetch_catalog: bool = True,
+ ) -> None: ...
def _reconcile_native_auth(self, backends: tuple[str, ...]) -> None: ...
@@ -168,28 +167,6 @@ class MigrationHost(Protocol):
*, on_reserved: Callable[[str], None] | None = None,
) -> str: ...
- async def _require_proven_source_payload(
- self,
- payload: dict[str, object],
- *, on_reserved: Callable[[str], None] | None = None,
- auth_scheme: str | None = None,
- ) -> SourceObservation: ...
-
- async def _require_proven_observation(
- self, vendor: str, base_url: str | None, credential_ref: str,
- protocol_order: tuple[str, ...],
- ) -> SourceObservation: ...
-
- def _apply_discovered_models(
- self,
- source: ModelHubSourceConfig,
- manual_models: list[ModelHubModelConfig],
- discovered: list[DiscoveredModel],
- *,
- allow_empty: bool = False,
- catalog_efforts_by_model: Mapping[str, tuple[str, ...]] | None = None,
- ) -> list[tuple[str, Literal["upstream", "catalog"]]]: ...
-
def _apply_source_placement(
self,
config: ModelHubConfig,
@@ -1444,20 +1421,13 @@ def _deduplicate_opencode_items(
return [replacements.get(item.id, item) for item in items if item.id not in duplicates]
-def _require_native_api_key_transport(
- item: NativeMigrationItem, *, observed_protocol: str | None = None,
-) -> None:
+def _require_native_api_key_transport(item: NativeMigrationItem) -> None:
if item.kind == "oauth_native":
return
- protocol = observed_protocol if observed_protocol is not None else item.protocol
try:
validate_migration_api_key_transport(
- item.vendor, protocol, item.base_url, item.secret, item.auth_scheme,
+ item.vendor, item.protocol, item.base_url, item.secret, item.auth_scheme,
)
- if (protocol == "anthropic") != (item.protocol == "anthropic"):
- # None is legacy protocol-auth, not permission to replace a native
- # x-api-key with Bearer (or vice versa) after observation.
- raise ValueError
except ValueError:
raise MigrationConflictError from None
@@ -1466,8 +1436,8 @@ def _bearer_transport(item: NativeMigrationItem) -> NativeMigrationItem | None:
"""Carry a custom-endpoint Anthropic key over as the Bearer the engine sends.
The pinned engine sends ``x-api-key`` only to the official origin. Custom
- endpoints get Bearer, so migration proves and provisions exactly that header;
- an endpoint that refuses it fails proof and the native files stay untouched.
+ endpoints get Bearer. Migration records that transport without contacting the
+ endpoint; normal Gateway requests report whether it accepts the credential.
"""
if item.kind == "oauth_native" or item.protocol != "anthropic" or item.auth_scheme is not None:
return None
@@ -1654,10 +1624,27 @@ def _validated_source(
"discovered_at": discovered_at,
}
)
+ else:
+ # Configured model entries remain manual; migration never invents an
+ # upstream inventory or a last-discovered timestamp for them.
+ for model in item.manual_models:
+ resolution = resolve_reasoning_tiers(
+ protocol=protocol,
+ model_id=model.id,
+ catalog_efforts_by_model=catalog_efforts_by_model,
+ )
+ models.append({
+ "id": model.id,
+ "display_name": model.display_name,
+ "origin": "manual",
+ "reasoning_efforts": list(resolution.efforts),
+ "reasoning_efforts_source": resolution.source,
+ "discovered_at": None,
+ })
payload: dict[str, object] = {
"id": item.source_id,
"created_at": discovered_at,
- "last_discovered_at": discovered_at if models else None,
+ "last_discovered_at": discovered_at if models and (keep_native or imported_oauth) else None,
"kind": "subscription" if keep_native or controlled or imported_oauth else "api_key",
"vendor": item.vendor,
"display_name": item.display_name,
@@ -1724,7 +1711,7 @@ async def _prepare_takeover(
cleanup batch withdraws them natively without provisioning them again.
"""
for item in selected:
- # Recheck before cleanup planning, reuse, proof or credential custody.
+ # Recheck local representability before cleanup, reuse or credential custody.
_require_native_api_key_transport(item)
clean_native_stores = dict(clean_native_stores or {})
cleanup_items = [
@@ -1742,6 +1729,7 @@ async def _prepare_takeover(
provisioned: list[dict[str, str]] = []
source_ids: list[str] = list(retained_source_ids or ())
item_sources: dict[str, dict[str, str]] = {}
+ native_sources: dict[str, list[tuple[str, str]]] = {}
catalog = bundled_catalog_wire_efforts_by_model()
handoff_attempted = False
try:
@@ -1755,7 +1743,7 @@ async def _prepare_takeover(
continue
protocol = item.protocol
auth_options = {"auth_scheme": item.auth_scheme} if item.auth_scheme is not None else {}
- observation: SourceObservation | None = None
+ reused = False
existing = next((source for source in updated.sources if source.id == item.source_id), None)
if item.kind != "oauth_native":
if not item.secret:
@@ -1775,15 +1763,14 @@ async def _prepare_takeover(
**auth_options,
))
):
- # Identity reuse is not current authentication proof.
- # Observe the exact existing target/ref without changing
- # its inventory, state, or user-owned routes.
- reuse_observation = await host._require_proven_observation(
- candidate.vendor, candidate.base_url,
- candidate.credential_ref, (candidate.protocol,),
- )
- _require_native_api_key_transport(item, observed_protocol=reuse_observation.protocol)
+ # Matching custody is sufficient for identity reuse.
+ # Migration neither re-tests the key nor rewrites the
+ # existing Source's inventory, evidence or health.
+ reused = True
_ensure_takeover_placement(updated, candidate, item.backend)
+ native_sources.setdefault(item.backend, []).append((
+ item.native_provider_id or item.vendor, candidate.id,
+ ))
source_ids.append(candidate.id)
item_sources[_retained_key_identity(item)] = {
"source_id": candidate.id, "credential_ref": candidate.credential_ref,
@@ -1793,17 +1780,7 @@ async def _prepare_takeover(
} if item.native_store_revision else {}),
}
break
- else:
- observation = await host._require_proven_source_payload({
- "vendor": item.vendor,
- "base_url": validate_base_url(item.base_url),
- "key": item.secret,
- # Bearer exists only on the Anthropic interface.
- **({"protocol": "anthropic"} if item.auth_scheme == "bearer" else {}),
- }, on_reserved=lambda ref: host.revocations.add("observation", ref), **auth_options)
- protocol = cast(Any, observation.protocol)
- _require_native_api_key_transport(item, observed_protocol=protocol)
- if observation is None:
+ if reused:
continue
if existing is not None and not (
existing.kind == "subscription"
@@ -1844,17 +1821,11 @@ async def _prepare_takeover(
masked_credential=mask_credential(item.secret) if item.secret else None,
catalog_efforts_by_model=catalog,
)
- if observation is not None:
- manual = [ModelHubModelConfig.from_payload({
- "id": model.id, "display_name": model.display_name,
- "origin": "manual", "reasoning_efforts": [], "discovered_at": None,
- }) for model in item.manual_models]
- host._apply_discovered_models(
- source, manual, list(observation.models),
- allow_empty=True, catalog_efforts_by_model=catalog,
- )
- if observation.discovery is not ObservationDiscovery.SUCCEEDED:
- host._mark_source_unverified(source)
+ if item.kind != "oauth_native":
+ # A migration is a local configuration transfer, not proof that
+ # the upstream accepts the saved key. Use the existing Saved
+ # marker until a real Gateway call verifies it.
+ host._mark_source_unverified(source)
if existing is not None:
# Custody changes, not the identity/menu/orders the user owns.
replacement = existing.to_payload()
@@ -1881,6 +1852,9 @@ async def _prepare_takeover(
host._apply_source_placement(updated, source)
source_ids.append(source.id)
if item.kind != "oauth_native":
+ native_sources.setdefault(item.backend, []).append((
+ item.native_provider_id or item.vendor, source.id,
+ ))
item_sources[_retained_key_identity(item)] = {
"source_id": source.id, "credential_ref": source.credential_ref,
"key_fingerprint": _retained_key_fingerprint(item),
@@ -1890,7 +1864,8 @@ async def _prepare_takeover(
}
if updated.vibey_supply_pending:
# Once every Source of the batch is in place, reused identities too.
- await host._seed_vibey(updated)
+ # Optional catalog enrichment must not add a network wait to migration.
+ await host._seed_vibey(updated, fetch_catalog=False)
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.
@@ -1916,9 +1891,12 @@ async def _prepare_takeover(
}
updated.enabled = True
for backend in backends:
- if updated.agents[backend].mode != "hub":
- updated.agents[backend].mode = "hub"
- host._carry_agent_selections(updated, backend)
+ updated.agents[backend].mode = "hub"
+ # Source import owns this reconciliation, not the mode transition:
+ # a user may have switched to Hub before accepting migration.
+ host._carry_agent_selections(
+ updated, backend, native_sources=native_sources.get(backend, ()), fetch_catalog=False,
+ )
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.py
index 22605dd3b..bf1970982 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -12,7 +12,7 @@ from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Awaitable, Callable, Iterable, Literal, Mapping, Optional, Protocol, cast
+from typing import Any, Awaitable, Callable, Collection, Iterable, Literal, Mapping, Optional, Protocol, cast
from sqlalchemy import func, literal_column, select
@@ -5304,7 +5304,7 @@ class ModelHubService:
reasoning_efforts.append(effort)
return suppliers, display_name, reasoning_efforts
- def _models_dev_descriptions(self, model_ids: list[str]) -> dict[str, dict]:
+ def _models_dev_descriptions(self, model_ids: list[str], *, fetch_catalog: bool = True) -> dict[str, dict]:
"""Exact models.dev matches for provider candidates; empty when unknown.
The description is optional: an unreadable catalog leaves every
@@ -5313,10 +5313,11 @@ class ModelHubService:
if not model_ids:
return {}
- from vibe.models_dev_catalog import exact_models_dev_matches
+ from vibe.models_dev_catalog import cached_models_dev_catalog, exact_models_dev_matches
try:
- return exact_models_dev_matches(model_ids, dict(self.models_dev_catalog()))
+ catalog = self.models_dev_catalog() if fetch_catalog else cached_models_dev_catalog()
+ return exact_models_dev_matches(model_ids, dict(catalog))
except Exception as exc: # noqa: BLE001 - optional metadata never fails a read
logger.info("Model Hub candidates have no models.dev metadata: %s", type(exc).__name__)
return {}
@@ -5576,28 +5577,43 @@ class ModelHubService:
self,
config: ModelHubConfig,
backend: BackendName,
+ *,
+ native_sources: Collection[tuple[str, str]] = (),
+ fetch_catalog: bool = True,
) -> 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
+ Called after confirmed migration or 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.
+ serves stays visible as an Agent that needs attention. During migration,
+ a static Source carried from that selection's native provider can instead
+ retain it by passthrough, without claiming an upstream inventory.
"""
if self.named_agents_override is None:
return
agent = config.agents[backend]
+ source_by_id = {source.id: source for source in config.sources}
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
+ if backend == "opencode" and native_sources:
+ provider, separator, model = selected.partition("/")
+ if not separator or not model or not any(
+ native_provider == provider for native_provider, _ in native_sources
+ ):
+ # A same-named inventory entry from a different provider
+ # does not consent to migrating this Direct selection.
+ continue
candidates = (
opencode_menu_model_candidates(selected)
if backend == "opencode"
@@ -5613,11 +5629,29 @@ class ModelHubService:
),
None,
)
+ if served is None and native_sources:
+ provider, separator, model = selected.partition("/")
+ native_model = model if backend == "opencode" and separator else selected
+ if (
+ (backend != "opencode" or (provider and separator and model))
+ and native_model not in agent.removed_model_ids
+ and native_model not in carried
+ and any(
+ (backend != "opencode" or native_provider == provider)
+ and source_id in agent.sources.order
+ and (source := source_by_id.get(source_id)) is not None
+ and self._eligible_for_agent(source, backend)
+ and source_supports_passthrough(source)
+ and not source_model_retired(source, native_model)
+ for native_provider, source_id in native_sources
+ )
+ ):
+ served = native_model
if served is not None:
carried.append(served)
if not carried:
return
- described = self._models_dev_descriptions(carried)
+ described = self._models_dev_descriptions(carried, fetch_catalog=fetch_catalog)
for model_id in carried:
candidate = self._provider_candidate(
config,
@@ -5633,7 +5667,7 @@ class ModelHubService:
checked=[model.id for model in agent.models],
)
- async def _seed_vibey(self, config: ModelHubConfig) -> bool:
+ async def _seed_vibey(self, config: ModelHubConfig, *, fetch_catalog: bool = True) -> bool:
"""Give a pending Vibey entry its starting supply, in place; whether it took.
Its Sources are every existing one this backend may use, placed as a
@@ -5652,10 +5686,11 @@ class ModelHubService:
agent = config.agents["vibey"]
if not any(self._eligible_for_agent(source, "vibey") 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)
+ # Seeded rows keep the models.dev metadata they are written with.
+ # Migration uses only the cached copy so moving a saved key never waits
+ # on optional network metadata; ordinary background backfill still runs.
+ if fetch_catalog:
+ await asyncio.to_thread(self._ensure_models_dev_copy)
config.vibey_supply_pending = False
for source in config.sources:
self._apply_source_placement(config, source, ("vibey",))
@@ -5685,7 +5720,7 @@ class ModelHubService:
)
if served is not None and served not in model_ids:
model_ids.append(served)
- described = self._models_dev_descriptions(model_ids)
+ described = self._models_dev_descriptions(model_ids, fetch_catalog=fetch_catalog)
rows = []
for model_id in model_ids:
match = described.get(model_id)
@@ -5697,12 +5732,14 @@ class ModelHubService:
if candidate is not None:
rows.append(candidate[0])
if not rows:
- starting = self._vibey_starting_model(config)
+ starting = self._vibey_starting_model(config, fetch_catalog=fetch_catalog)
rows = [starting] if starting is not None else []
agent.models = rows
return True
- def _vibey_starting_model(self, config: ModelHubConfig) -> ModelHubBackendModelConfig | None:
+ def _vibey_starting_model(
+ self, config: ModelHubConfig, *, fetch_catalog: bool = True,
+ ) -> ModelHubBackendModelConfig | None:
"""The one model a seed with no qualifying selection starts Vibey on, or ``None``.
The first model, in Vibey's Source order and then each Source's own
@@ -5722,7 +5759,7 @@ class ModelHubService:
if not model.retired
)
)
- described = self._models_dev_descriptions(listed)
+ described = self._models_dev_descriptions(listed, fetch_catalog=fetch_catalog)
for model_id in listed:
match = described.get(model_id)
if match is None or not _described_as_fit_for_agent_turns(match):
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index cc44f55e7..1be287ea3 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -78,7 +78,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua
| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A callback address is recognized with or without its `http(s)://` scheme, which browsers drop when copying a page that failed to load; any other value is a bare code. An address the flow refuses before anything reaches the provider is the non-terminal `422 submission_rejected`: one with no `code` or `error`, or one whose `state` answers a different sign-in link than this flow's (`detail: modelHub.errors.submission_rejected_other_attempt`). The flow stays `awaiting_action` and accepts another submission until its `expires_at`. |
| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels provider work. A committed flow with `client_nonce` remains the same bounded terminal `OAuthFlow` with `state: "cancelled"` until its existing `expires_at`; a flow without a nonce is forgotten. |
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
-| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It validates selected items before withdrawal, upgrades an existing native Source in place when present, commits Source/Routes/backend mode atomically, and removes only replaced native material. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. |
+| POST `/api/models/migration/apply` | `{item_ids: string[], clean_api_keys?: boolean}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It checks saved configuration and custody locally, copies API keys without upstream validation, upgrades an existing native subscription Source in place when present, and commits Source/Routes/backend mode atomically. API-key originals are kept unless cleanup was selected. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. |
| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 12 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
| POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. |
@@ -121,6 +121,23 @@ hourly buckets incomplete; its daily count is never assigned to an hour using
`last_metered_at`. Bucket rows are sparse `(source_id, model_id)` pairs, and the
`totals`, `sources`, and `days` fields aggregate those same measured bucket rows.
+### Native API-key migration
+
+Static-key migration is a local configuration transfer, not a connection test.
+It never authenticates the key, probes the upstream interface, or fetches a model
+inventory as part of applying the migration. The protocol, Base URL and declared
+manual models come from the saved native configuration. New API-key Sources carry
+`verification_pending` and are presented as **Saved**, with no fabricated upstream
+inventory or discovery timestamp. A matching existing Source is reused without
+re-testing or resetting its inventory, health, or verification evidence.
+
+An expired key or unavailable endpoint therefore does not stop the other selected
+keys from being migrated; neither is silently dropped. Later Gateway calls report
+upstream failures and establish successful-use evidence. Background model discovery
+remains separate from migration, and optional catalog enrichment does not add a
+foreground network wait. Local parsing/transport checks, stale consent, credential
+access, cleanup consent, and atomic custody/recovery protections still apply.
+
### Native migration terminal recovery
The migration apply response is successful only after the grouped custody transaction
diff --git a/docs/plans/model-hub-offline-key-migration.md b/docs/plans/model-hub-offline-key-migration.md
new file mode 100644
index 000000000..41f6862d5
--- /dev/null
+++ b/docs/plans/model-hub-offline-key-migration.md
@@ -0,0 +1,96 @@
+# Native API-key migration without upstream validation
+
+## Owner decision (2026-10-14)
+
+Migration transfers saved configuration and credentials; it is not an upstream
+connection test. The owner explicitly replaced the earlier partial-skip proposal:
+import all locally valid selected API-key entries without authenticating them,
+probing their protocols, or fetching their model lists during migration. An
+expired key, offline endpoint, or unavailable model list must not prevent or slow
+the batch. Normal Gateway use reports provider failures after migration.
+
+The earlier partial-skip proposal is superseded; no skipped-result API, report UI,
+or receipt schema is added. The public response remains `{applied, sources, added_to}`
+and the existing transaction/replay format stays unchanged.
+
+## Smallest complete change
+
+- In shared migration preparation, remove static-key observation for both new
+ Sources and matching existing Sources. Native parsing already supplies the
+ protocol and target; do not re-detect or rewrite the protocol over the network.
+- Provision selected keys into the existing custody adapter and construct Sources
+ from saved metadata. Preserve declared manual models and known configuration;
+ never fabricate upstream-discovered models or claim successful authentication.
+- Newly imported static Sources use the existing `verification_pending` marker
+ and neutral Saved presentation. A reused Source retains its existing identity,
+ credential ref, model inventory and current health/evidence; migration does not
+ newly verify it or reset an existing failure.
+- Preserve useful model configuration and selections without making catalog
+ download another migration admission gate. No per-provider upstream discovery
+ in the static-key migration call path. Ordinary background discovery and later
+ explicit tests/requests remain separate owners.
+- Keep Avibe-owned named Agent selections runnable when entering Gateway mode.
+ If a migrated static Source has no inventory, carry the selection through its
+ supported passthrough path. OpenCode's native provider prefix must match a
+ Source actually imported or reused in this batch. Preserve removed-model
+ intent and retired Source/model pairs; do not fabricate discovered entries.
+- Keep local format/URL/transport representability checks, stale-consent and file
+ guards, credential access checks, backend retirement, copy-vs-cleanup consent,
+ atomic write-ahead custody and recovery exactly as required. Do not skip or
+ erase keys because they might be invalid upstream.
+- OAuth is a separate grant-ownership transfer: its existing activation, refresh
+ rejection, and forward-only recovery rules are unchanged by this static-key
+ decision. Engine installation/startup readiness is not API-key authentication.
+
+## Copy and tests
+
+Migration copy says keys are saved, not tested; failures from local config/custody
+checks must not tell users to validate a key online. Reuse existing Saved status
+and its hints rather than adding a new partial-migration UI.
+
+Primary regression at shared migration owner: make every static observation /
+model-discovery function raise if called; import mixed good-looking, rejected and
+unreachable fixture keys (same backend and across backends), preserve protocol,
+manual models and configured transport, check neutral pending marker, copy/cleanup,
+identity reuse and receipt replay. The pre-fix code must fail because it invokes
+observation. Old tests demanding proof, protocol re-detection or auth-failure
+rollback must be updated to the new owner-approved contract, not simply deleted.
+Existing transport/permission/concurrency/OAuth safety tests must continue passing.
+
+Independent integration: real HTTP/CSRF/controller IPC + a mock upstream that
+rejects all requests; assert all keys import and no credential-bearing observation
+or discovery request was made during migration. Verify replay and native copy/
+cleanup in the disposable local Incus worktree, never on a live tenant.
+
+## Review root-cause decision
+
+Reviews of `312018cb` and `988bfea49` exposed the same incomplete boundary:
+selection reconciliation was inherited from a mode-switch helper rather than
+owned by the confirmed migration. Provider membership must be checked before
+both inventory and passthrough admission, and the reconciliation must run whether
+the user entered through a Direct-to-Hub switch or imported keys after already
+switching to Hub. The owner decision is to reconcile every migrated backend after
+its Sources are staged, independently of whether its mode changed. Existing menu
+rows, user removals, Source health and ordinary non-migration switching retain
+ownership; identical receipt replay does not become a new catalog edit.
+
+The regression matrix covers both initial modes and removed-model intent, with
+an unimported provider whose selected model suffix collides with a migrated
+manual model. This closes the whole entrypoint/admission class, not only the
+latest symptom. No new state, routing system or upstream verification is needed.
+
+## Validation and delivery
+
+- MH-MIG-015 protects local transfer, saved protocols, neutral pending markers,
+ identity reuse, native copy/cleanup, and identical replay without any upstream
+ call. Its pre-fix failure is an attempted observation.
+- MH-SWITCH-001 keeps native model selections usable without discovery; a removed
+ model stays removed and an unrelated provider selection stays unconfigured.
+- The real HTTP/IPC suite passed all seven migration cases against a rejecting
+ fixture upstream inside an isolated local Incus worktree. Additional persisted
+ shell/native-input checks retain their file and credential-custody boundaries.
+- Migration dialog tests and the UI production build passed. Related existing
+ proof tests are updated to assert no observation, while keeping local consent,
+ canonical-value, transport, rollback, and OAuth recovery checks.
+- Delivery requires exact-head review and CI. Public documentation is coordinated
+ with the release; no deployment or service restart is implied by this change.
diff --git a/tests/e2e/test_model_hub_migration.py b/tests/e2e/test_model_hub_migration.py
index 2c2502111..81caba493 100644
--- a/tests/e2e/test_model_hub_migration.py
+++ b/tests/e2e/test_model_hub_migration.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import hashlib
import json
from pathlib import Path
@@ -175,9 +174,6 @@ def test_f2_apply_takes_over_selected_key_and_preserves_blocked_native_material(
"""F2: grouped custody cleans the selected key without touching blockers."""
seeded_api_key = SYNTHETIC_MIGRATION_API_KEY
- seeded_api_key_digest = hashlib.sha256(
- seeded_api_key.encode("utf-8")
- ).hexdigest()
_configure_protocol(
mock_llm_upstream,
"anthropic",
@@ -205,11 +201,16 @@ def test_f2_apply_takes_over_selected_key_and_preserves_blocked_native_material(
mock_llm_upstream.reset_requests()
applied = app.client.post(
- "/api/models/migration/apply", {"item_ids": item_ids}
+ "/api/models/migration/apply", {"item_ids": item_ids, "clean_api_keys": True}
)
body = applied.json()
assert applied.status == 200, body
assert body["applied"] == 1
+ # Check migration before the Sources page read below schedules its
+ # own independent background inventory refresh.
+ assert mock_llm_upstream.requests() == []
+ assert body["sources"][0]["verification_pending"]
+ assert body["sources"][0]["last_discovered_at"] is None
assert [
(source["vendor"], source["kind"], source["supply_channel"])
for source in body["sources"]
@@ -234,47 +235,79 @@ def test_f2_apply_takes_over_selected_key_and_preserves_blocked_native_material(
assert "sk-ant-e2e-claude-independent-123456" not in serialized
assert "codex-oauth-e2e-123456" not in serialized
- captured_digests = set()
- for request in mock_llm_upstream.requests():
- headers = request["headers"]
- credential = headers.get("x-api-key")
- if credential is None:
- authorization = headers.get("authorization", "")
- prefix = "Bearer "
- credential = (
- authorization[len(prefix) :]
- if authorization.startswith(prefix)
- else authorization
- )
- if credential:
- captured_digests.add(
- hashlib.sha256(credential.encode("utf-8")).hexdigest()
- )
- assert seeded_api_key_digest in captured_digests
- catalogue_headers = [
- request["headers"]
- for request in mock_llm_upstream.requests()
- if request["path"] == "/v1/models"
- ]
- assert any(
- headers.get("authorization") == f"Bearer {seeded_api_key}"
- and "x-api-key" not in headers
- for headers in catalogue_headers
- )
- assert any(
- not headers.get("x-api-key") and not headers.get("authorization")
- for headers in catalogue_headers
- )
+
+
[email protected]("clean_api_keys", [False, True])
+def test_mh_mig_015_keys_migrate_over_http_without_any_upstream_request(
+ model_hub_app_factory, mock_llm_upstream, clean_api_keys,
+) -> None:
+ """MH-MIG-015: HTTP/IPC imports even rejected keys, without probing them.
+
+ Service doubles alone cannot show that the real custody/runtime adapters do
+ not authenticate or fetch inventories. This local upstream rejects every
+ credential; its request log must remain empty through migration and replay.
+ """
+ mock_llm_upstream.configure(auth="401", protocol="openai_chat")
+ credentials = {
+ "deepseek": "fixture-stale-native-key",
+ "custom-relay": "fixture-unchecked-native-key",
+ }
+ paths: list[Path] = []
+
+ def seed(app) -> None:
+ path = app.home / ".config/opencode/opencode.json"
+ paths.append(path)
+ _write(path, json.dumps({"provider": {
+ vendor: {
+ "npm": "@ai-sdk/openai-compatible",
+ "options": {"apiKey": key, "baseURL": mock_llm_upstream.url},
+ "models": {"configured-model": {"name": "Configured model"}},
+ }
+ for vendor, key in credentials.items()
+ }}))
+
+ with model_hub_app_factory(before_start=seed) as app:
+ before = paths[0].read_bytes()
+ scan = app.client.post("/api/models/migration/scan", {})
+ assert scan.status == 200, scan.json()
+ items = scan.json()["scan"]["items"]
+ assert {item["vendor"] for item in items} == set(credentials)
+ request = {"item_ids": [item["id"] for item in items], "clean_api_keys": clean_api_keys}
+ response = app.client.post("/api/models/migration/apply", request)
+ body = response.json()
+ assert response.status == 200, body
+ assert body["applied"] == 2
+ assert {source["vendor"] for source in body["sources"]} == set(credentials)
+ assert mock_llm_upstream.requests() == []
+ for source in body["sources"]:
+ assert source["protocol"] == "openai_chat"
+ assert source["verification_pending"]
+ assert source["last_discovered_at"] is None
+ assert [(model["id"], model["origin"]) for model in source["models"]] == [
+ ("configured-model", "manual"),
+ ]
+ assert all(key not in json.dumps(body) for key in credentials.values())
+ if clean_api_keys:
+ assert all(key not in paths[0].read_text() for key in credentials.values())
+ else:
+ assert paths[0].read_bytes() == before
+ replay = app.client.post("/api/models/migration/apply", request)
+ assert replay.status == 200, replay.json()
+ assert replay.json()["applied"] == 2
+ assert {source["id"] for source in replay.json()["sources"]} == {
+ source["id"] for source in body["sources"]
+ }
+ assert mock_llm_upstream.requests() == []
@pytest.mark.parametrize(
"required_api_key", [None, "sk-ant-e2e-different-key"],
ids=["public-catalogue", "rejected-key"],
)
-def test_f2_unproven_key_keeps_all_native_material(
+def test_f2_unproven_key_is_copied_without_upstream_validation(
model_hub_app_factory, mock_llm_upstream, required_api_key: str | None,
) -> None:
- """F2: a public catalogue or credential rejection cannot authorize cleanup."""
+ """F2: upstream authentication is not admission to a configuration transfer."""
_configure_protocol(
mock_llm_upstream, "anthropic",
models=[{"id": "claude-sonnet-4-6"}],
@@ -296,9 +329,12 @@ def test_f2_unproven_key_keeps_all_native_material(
response = app.client.post(
"/api/models/migration/apply", {"item_ids": [item["id"] for item in selected]},
)
- assert response.status == 409, response.json()
- assert response.json()["error"] == "migration_item_conflict"
+ body = response.json()
+ assert response.status == 200, body
+ assert body["applied"] == 1
+ assert body["sources"][0]["verification_pending"]
+ assert mock_llm_upstream.requests() == []
assert all(path.read_bytes() == before[path] for path in seeded_paths)
listed = app.client.get("/api/models/sources")
assert listed.status == 200, listed.json()
- assert listed.json()["sources"] == []
+ assert len(listed.json()["sources"]) == 1
diff --git a/tests/e2e/test_model_hub_migration_persisted.py b/tests/e2e/test_model_hub_migration_persisted.py
index f688aaf7d..bda24e50c 100644
--- a/tests/e2e/test_model_hub_migration_persisted.py
+++ b/tests/e2e/test_model_hub_migration_persisted.py
@@ -37,8 +37,15 @@ def _seed_hub(app) -> None:
_write(path, json.dumps(payload))
-def _assert_cpa_bearer_consumption(app, upstream, key: str) -> None:
- """Read only fixture engine output; consume it through the actual CPA."""
+def _assert_cpa_bearer_consumption(app, upstream, key: str, source_id: str) -> None:
+ """After migration, explicitly discover the fixture model and consume CPA.
+
+ Migration no longer publishes an eagerly discovered ``mock-model`` alias.
+ Direct CPA calls bypass Avibe's per-request model admission, so this transport
+ check explicitly requests the inventory it needs after migration has finished.
+ """
+ refreshed = app.client.post(f"/api/models/sources/{source_id}/refresh", {})
+ assert refreshed.status == 200, refreshed.json()
status = app.client.get("/api/models/runtime/status").json()["runtime"]["status"]
listening = status["listening"]
[config_path] = list((app.avibe_home / "runtime/model-hub/state/instances").glob("*/config.yaml"))
@@ -126,11 +133,16 @@ def test_f4_persisted_configuration_migrates_with_runtime_auth_present(
assert rows[0]["proposed_action"] == "import"
assert rows[0]["source_paths"] == [str(source_paths[0])]
assert KEY not in json.dumps(rows)
- applied = app.client.post("/api/models/migration/apply", {"item_ids": [rows[0]["id"]]})
+ applied = app.client.post(
+ "/api/models/migration/apply", {"item_ids": [rows[0]["id"]], "clean_api_keys": True},
+ )
assert applied.status == 200, applied.json()
assert applied.json()["applied"] == 1
[source] = applied.json()["sources"]
assert source["supply_channel"] == "hub"
+ assert source["protocol"] == protocol
+ assert source["verification_pending"]
+ assert mock_llm_upstream.requests() == []
assert app.env == before_env
if shell_fixture:
assert source_paths[0].read_bytes() == retained.encode()
@@ -145,15 +157,15 @@ def test_f4_persisted_configuration_migrates_with_runtime_auth_present(
assert app.client.post("/api/models/migration/scan", {}).json()["scan"]["items"] == []
if backend == "claude":
- # Test the pinned engine consumer, not just direct discovery proof.
- _assert_cpa_bearer_consumption(app, mock_llm_upstream, KEY)
+ # Only a later real model call tests the pinned engine's transport.
+ _assert_cpa_bearer_consumption(app, mock_llm_upstream, KEY, source["id"])
@pytest.mark.parametrize("required", [None, "fixture-rejected-key"], ids=["public", "wrong-key"])
-def test_f4_unproven_shell_key_is_not_removed(
+def test_f4_unproven_shell_key_is_copied_without_validation(
model_hub_app_factory, mock_llm_upstream, required,
):
- """F4: a readable static file is not proof of credential authentication."""
+ """F4: copying persisted configuration does not require upstream acceptance."""
_configure_protocol(mock_llm_upstream, "anthropic")
mock_llm_upstream.configure(required_api_key=required, required_auth_scheme="bearer")
paths = []
@@ -172,16 +184,18 @@ def test_f4_unproven_shell_key_is_not_removed(
rows = app.client.post("/api/models/migration/scan", {}).json()["scan"]["items"]
assert len(rows) == 1 and rows[0]["proposed_action"] == "import"
result = app.client.post("/api/models/migration/apply", {"item_ids": [rows[0]["id"]]})
- assert result.status == 409, result.json()
+ assert result.status == 200, result.json()
+ assert result.json()["applied"] == 1
assert paths[0].read_bytes() == before
- assert app.client.get("/api/models/sources").json()["sources"] == []
+ assert len(app.client.get("/api/models/sources").json()["sources"]) == 1
+ assert mock_llm_upstream.requests() == []
@pytest.mark.parametrize("shape", ["settings", "shell"])
-def test_f4_custom_api_key_refusing_bearer_is_kept_without_cleanup(
+def test_f4_custom_api_key_refusing_bearer_is_copied_without_validation(
model_hub_app_factory, mock_llm_upstream, shape,
):
- """F4: proof uses the Bearer header the pinned engine sends to a relay."""
+ """F4: relay authentication errors belong to later use, not key migration."""
_configure_protocol(mock_llm_upstream, "anthropic")
mock_llm_upstream.configure(required_api_key=KEY, required_auth_scheme="protocol")
paths = []
@@ -207,11 +221,13 @@ def test_f4_custom_api_key_refusing_bearer_is_kept_without_cleanup(
assert response.status == 200, response.json()
[row] = response.json()["scan"]["items"]
assert row["selected"] is True and row["proposed_action"] == "import"
- refused = app.client.post("/api/models/migration/apply", {"item_ids": [row["id"]]})
- assert refused.status >= 400, refused.json()
+ migrated = app.client.post("/api/models/migration/apply", {"item_ids": [row["id"]]})
+ assert migrated.status == 200, migrated.json()
+ assert migrated.json()["applied"] == 1
assert paths[0].read_bytes() == before
- assert app.client.get("/api/models/sources").json()["sources"] == []
- assert all("x-api-key" not in request["headers"] for request in mock_llm_upstream.requests())
+ [source] = app.client.get("/api/models/sources").json()["sources"]
+ assert source["verification_pending"]
+ assert mock_llm_upstream.requests() == []
@pytest.mark.parametrize("profile,writer", [
@@ -321,7 +337,9 @@ def test_f4_shell_data_roles_allow_http_migration_without_changing_data(
[row] = response.json()["scan"]["items"]
assert row["selected"] is True
assert row["proposed_action"] == "import"
- applied = app.client.post("/api/models/migration/apply", {"item_ids": [row["id"]]})
+ applied = app.client.post(
+ "/api/models/migration/apply", {"item_ids": [row["id"]], "clean_api_keys": True},
+ )
assert applied.status == 200, applied.json()
assert applied.json()["applied"] == 1
assert len(applied.json()["sources"]) == 1
@@ -351,7 +369,7 @@ def test_f4_replace_migrated_bearer_without_old_secret_retains_cpa_transport(
assert applied.status == 200, applied.json()
[source] = applied.json()["sources"]
assert source["credential_ref"].startswith("cred_auth_bearer_")
- _assert_cpa_bearer_consumption(app, mock_llm_upstream, KEY)
+ _assert_cpa_bearer_consumption(app, mock_llm_upstream, KEY, source["id"])
config_path = app.avibe_home / "config/config.json"
agents_before = json.loads(config_path.read_text())["model_hub"]["agents"]
old_path = (
@@ -377,7 +395,7 @@ def test_f4_replace_migrated_bearer_without_old_secret_retains_cpa_transport(
assert not old_path.exists()
pending = app.avibe_home / "state/model_hub_pending_revocations.json"
assert json.loads(pending.read_text()) == []
- _assert_cpa_bearer_consumption(app, mock_llm_upstream, replacement)
+ _assert_cpa_bearer_consumption(app, mock_llm_upstream, replacement, source["id"])
@pytest.mark.parametrize("history", ["marked", "legacy-unknown"])
@@ -421,7 +439,9 @@ def test_f4_oauth_history_fence_survives_later_api_batch_over_http(
applied = app.client.post("/api/models/migration/apply", {"item_ids": [api["id"]]})
assert applied.status == 200, applied.json()
assert "codex" in json.loads(paths[1].read_text())["oauth_custody_backends"]
- sources_before = app.client.get("/api/models/sources").json()["sources"]
+ # Reading the Sources page starts independent background discovery.
+ # Use the migration receipt here so this custody test does not race it.
+ sources_before = applied.json()["sources"]
[oauth] = app.client.post("/api/models/migration/scan", {}).json()["scan"]["items"]
assert oauth["backend"] == "codex" and oauth["proposed_action"] == "import"
mock_llm_upstream.reset_requests()
@@ -429,5 +449,5 @@ def test_f4_oauth_history_fence_survives_later_api_batch_over_http(
assert refused.status == 409, refused.json()
assert refused.json()["error"] == "migration_reauthorization_required"
assert paths[0].read_bytes() == before
- assert app.client.get("/api/models/sources").json()["sources"] == sources_before
assert mock_llm_upstream.requests() == []
+ assert app.client.get("/api/models/sources").json()["sources"] == sources_before
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index ba8c63253..600f46e31 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -1822,6 +1822,14 @@ scenarios:
test: tests/test_model_hub_native_takeover.py::test_refused_migration_says_whether_avibe_or_an_outside_cli_holds_the_backend
related_tests:
- ui/src/components/settings/models/MigrationDialog.test.tsx
+ - id: MH-MIG-015
+ name: Migration saves static API keys from their native configuration without contacting the provider, so rejected keys and offline endpoints import alike
+ status: covered
+ kind: migration
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_015_static_keys_migrate_from_saved_configuration_without_upstream_contact
+ related_tests:
+ - tests/e2e/test_model_hub_migration.py::test_mh_mig_015_keys_migrate_over_http_without_any_upstream_request
- id: MH-TAKEOVER-001
name: Recoverable failures walk the configured route and exhaust only at its end
status: covered
@@ -2208,8 +2216,8 @@ scenarios:
layer: e2e-auto
test: tests/e2e/test_model_hub_migration_persisted.py::test_f4_persisted_configuration_migrates_with_runtime_auth_present
related_tests:
- - tests/e2e/test_model_hub_migration_persisted.py::test_f4_unproven_shell_key_is_not_removed
- - tests/e2e/test_model_hub_migration_persisted.py::test_f4_custom_api_key_refusing_bearer_is_kept_without_cleanup
+ - tests/e2e/test_model_hub_migration_persisted.py::test_f4_unproven_shell_key_is_copied_without_validation
+ - tests/e2e/test_model_hub_migration_persisted.py::test_f4_custom_api_key_refusing_bearer_is_copied_without_validation
- tests/e2e/test_model_hub_migration_persisted.py::test_f4_explicit_dynamic_writer_refuses_http_apply_without_proof
- tests/e2e/test_model_hub_migration_persisted.py::test_f4_replace_migrated_bearer_without_old_secret_retains_cpa_transport
- tests/e2e/test_model_hub_migration_persisted.py::test_f4_oauth_history_fence_survives_later_api_batch_over_http
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.py
index c7735bda4..66bbf95b6 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
@@ -812,16 +812,7 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_
menu_model = fixed_model("claude")
store = MemoryModelHubStore(config_with_sources([]))
- adapter = ModelHubScenarioAdapter(
- observation=SourceObservation(
- outcome=ObservationOutcome.OBSERVED,
- reachable=True,
- authenticated=True,
- protocol="anthropic",
- discovery=ObservationDiscovery.SUCCEEDED,
- models=(DiscoveredModel(id=menu_model),),
- )
- )
+ adapter = ModelHubScenarioAdapter()
service = service_for(tmp_path, store, adapter)
service.migration_home = native_home
@@ -850,9 +841,8 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_
assert menu_model not in reloaded.agents["claude"].routes
inherited = service_for(tmp_path, MemoryModelHubStore(reloaded), adapter).agent_chain("claude", menu_model)
assert inherited["manual_override"] is None
- assert inherited["route_origin"] == "automatic"
- assert {(hop["source_id"], hop["model_id"]) for hop in inherited["chain"]} == {
- (position["source_id"], position["model_id"])
- for position in result["added_to"]
- if position["backend"] == "claude" and position["menu_model"] == menu_model
- }
+ # Migration fetches no inventory, so the saved key serves the menu model
+ # by passthrough until discovery or a real call says otherwise.
+ [migrated] = reloaded.sources
+ assert inherited["route_origin"] == "passthrough"
+ assert [(hop["source_id"], hop["model_id"]) for hop in inherited["chain"]] == [(migrated.id, menu_model)]
diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
index 0b31729eb..b3fe40963 100644
--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -79,6 +79,7 @@ class MigrationAdapter:
"zhipuai": "openai_chat",
}
self.unproven_observation_vendor: str | None = None
+ self.fail_provision_vendor: str | None = None
self.synced: list[tuple[object, ...]] = []
self.fail_revoke_refs: set[str] = set()
self.fail_sync_count = 0
@@ -159,6 +160,8 @@ class MigrationAdapter:
base_url: str | None,
*, on_reserved=None, auth_scheme=None,
) -> str:
+ if vendor == self.fail_provision_vendor:
+ raise OSError("redacted custody failure")
credential_ref = f"cred_migration_{len(self.provisioned) + 1}"
if on_reserved:
on_reserved(credential_ref)
@@ -207,10 +210,10 @@ class MigrationAdapter:
def _service(
- tmp_path: Path, *, migration_home: Path | None = None,
+ tmp_path: Path, *, migration_home: Path | None = None, adapter: MigrationAdapter | None = None,
) -> tuple[ModelHubService, MemoryStore, MigrationAdapter]:
store = MemoryStore()
- adapter = MigrationAdapter()
+ adapter = adapter or MigrationAdapter()
state = tmp_path / "avibe-state"
async def verify_fixture_idle():
@@ -694,8 +697,8 @@ def test_mh_mig_001_api_apply_takes_over_credentials_and_cleans_native_auth(
assert len(adapter.provisioned) == 4
assert len(adapter.oauth_provisioned) == 2
assert adapter.revoked == []
- assert adapter.transient_revoked == adapter.transient_refs
- assert len(adapter.observed) == len(adapter.transient_refs)
+ # Saved keys move as configuration; none is probed on the way.
+ assert adapter.transient_refs == [] and adapter.observed == []
assert before != _tree_digest(native_home)
claude_settings = json.loads(
(native_home / ".claude" / "settings.json").read_text(encoding="utf-8")
@@ -746,7 +749,8 @@ def test_mh_mig_001_api_apply_takes_over_credentials_and_cleans_native_auth(
codex_source = next(
source for source in store.config.sources if source.vendor == "openai" and source.kind == "api_key"
)
- assert codex_source.protocol == "openai_responses"
+ # The relay's saved wire_api, not a re-detected dialect.
+ assert codex_source.protocol == "openai_chat"
assert codex_source.base_url == "https://codex-relay.example/v1"
openrouter_source = next(source for source in store.config.sources if source.vendor == "openrouter")
assert openrouter_source.base_url == "https://openrouter.ai/api/v1"
@@ -1008,9 +1012,8 @@ def test_mh_mig_007_shell_startup_key_is_removed_only_on_request(
assert bool(service.migration_journal.completed()["retained_native_ids"]) is not clean_api_keys
[email protected]("discovery", (ObservationDiscovery.SUCCEEDED, ObservationDiscovery.FAILED))
-def test_mh_mig_001_long_manual_inventory_survives_takeover_even_when_discovery_fails(
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, discovery: ObservationDiscovery,
+def test_mh_mig_001_long_manual_inventory_survives_takeover_without_discovery(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
) -> None:
"""MH-MIG-001: new manual imports share admission without rewriting native files."""
native_home = tmp_path / "native-home"
@@ -1030,15 +1033,6 @@ def test_mh_mig_001_long_manual_inventory_survives_takeover_even_when_discovery_
before = _tree_digest(native_home)
service, store, adapter = _service(tmp_path)
_assert_sources_validated_before_commit(monkeypatch, service)
-
- async def observe(*_args):
- return SourceObservation(
- outcome=ObservationOutcome.OBSERVED, reachable=True, authenticated=True,
- protocol="openai_chat", discovery=discovery,
- models=(DiscoveredModel(id=identity + "-discovered"),) if discovery is ObservationDiscovery.SUCCEEDED else (),
- )
-
- adapter.observe_source = observe
[item] = service.migration_scan()["items"]
result = asyncio.run(service.migration_apply([item["id"]], clean_api_keys=True))
assert result["applied"] == 1
@@ -1047,9 +1041,8 @@ def test_mh_mig_001_long_manual_inventory_survives_takeover_even_when_discovery_
assert [(model.id, model.display_name) for model in manual] == [(identity, "Long manual")]
assert all(model.id not in invalid for model in source.models)
assert source.state.status == "standby"
- # Failed discovery admits the Source on protocol evidence alone; the first
- # successful call must still prove it.
- assert bool(source.verification_pending) is (discovery is ObservationDiscovery.FAILED)
+ # Saved, not tested: the first successful call proves it.
+ assert source.verification_pending
assert _tree_digest(native_home) != before
config_payload = json.loads(
(native_home / ".config" / "opencode" / "opencode.json").read_text(
@@ -1059,7 +1052,7 @@ def test_mh_mig_001_long_manual_inventory_survives_takeover_even_when_discovery_
provider = config_payload["provider"]["openrouter"]
assert "apiKey" not in provider.get("options", {})
assert provider["models"][" " + identity + " "] == {"name": "Long manual"}
- assert adapter.transient_revoked == adapter.transient_refs
+ assert adapter.observed == []
assert "sk-fabricated-never-persist-this" not in json.dumps(result)
@@ -1367,22 +1360,28 @@ def test_opencode_native_provider_without_stable_identifier_is_visible_blocker(
assert item.selected is False
[email protected]("removed", [False, True])
[email protected]("initial_mode", ["direct", "hub"])
def test_mh_switch_001_migration_carries_agent_models_into_the_switched_menu(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
+ removed: bool,
+ initial_mode: str,
) -> None:
- """MH-SWITCH-001: accepting migration carries each Agent's Direct selection
- into the menu it switches, served by the Sources that migration imported."""
+ """MH-SWITCH-001: migration carries saved Direct selections into the
+ Gateway menu whether mode was switched earlier or by this import."""
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"
+ store.config.agents["opencode"].mode = initial_mode
+ if removed:
+ store.config.agents["opencode"].removed_model_ids = ["openrouter-model"]
service.named_agents_override = lambda backend: [
("opencode", "openrouter/openrouter-model"),
("zhipu", "zhipuai/zhipuai-model"),
- ("stranger", "openai/not-served"),
+ ("stranger", "openai/manual-openrouter-model"),
] if backend == "opencode" else []
items = [item["id"] for item in service.migration_scan()["items"] if item["backend"] == "opencode"]
@@ -1390,18 +1389,27 @@ def test_mh_switch_001_migration_carries_agent_models_into_the_switched_menu(
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"),
- ]
+ expected = [("zhipuai-model", "provider", "openai_responses")]
+ if not removed:
+ expected.insert(0, ("openrouter-model", "provider", "openai_responses"))
+ assert [(model.id, model.origin, model.native_protocol) for model in agent.models] == expected
assert {
row["name"]: (row["effective_model_id"], row["route_reason"])
for row in service.get_agent_sources("opencode")["named_agents"]
} == {
- "opencode": ("openrouter-model", None),
+ "opencode": (
+ ("openrouter/openrouter-model", "route_unconfigured") if removed
+ else ("openrouter-model", None)
+ ),
"zhipu": ("zhipuai-model", None),
- "stranger": ("openai/not-served", "route_unconfigured"),
+ "stranger": ("openai/manual-openrouter-model", "route_unconfigured"),
}
+ # Carrying a saved selection creates a menu row, not a made-up discovered
+ # Source inventory. The old provider prefix stays on the named Agent.
+ assert all(
+ model.id not in {"openrouter-model", "zhipuai-model"}
+ for source in store.config.sources for model in source.models
+ )
def test_scan_keeps_invalid_endpoint_visible_while_valid_backend_items_remain_usable(
@@ -1486,13 +1494,13 @@ def test_failed_batch_revokes_every_provisioned_credential(
_isolate_native_home(monkeypatch, native_home)
service, store, adapter = _service(tmp_path)
item_ids = [item["id"] for item in service.migration_scan()["items"]]
- adapter.unproven_observation_vendor = "zhipuai"
+ adapter.fail_provision_vendor = "zhipuai"
with pytest.raises(ModelHubError) as error:
asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))
- assert error.value.code == "migration_item_conflict"
+ # A local custody failure, never a claim about the key upstream.
+ assert error.value.code == "engine_down"
assert adapter.revoked == ["cred_migration_1"]
- assert adapter.transient_revoked == adapter.transient_refs
assert store.config.sources == []
assert all(agent.sources.order == [] for agent in store.config.agents.values())
@@ -1930,3 +1938,188 @@ def test_mh_mig_007_default_copy_leaves_a_key_only_codex_store_byte_identical(
assert ids
assert asyncio.run(service.migration_apply(ids))["applied"] == len(ids)
assert auth_path.read_bytes() == before
+
+
+class OfflineUpstreamAdapter(MigrationAdapter):
+ """Every upstream contact fails once the native keys are being migrated.
+
+ A key that the provider would reject and an endpoint that is offline look
+ the same to migration: it must never ask. Each call is recorded before it
+ raises, so a caller that swallows the failure is still caught.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.offline = False
+ self.upstream_calls: list[str] = []
+
+ def _refuse(self, name: str) -> None:
+ if self.offline:
+ self.upstream_calls.append(name)
+ raise AssertionError(f"static-key migration must not call {name}")
+
+ async def provision_transient_credential(self, *args, **kwargs):
+ self._refuse("provision_transient_credential")
+ return await super().provision_transient_credential(*args, **kwargs)
+
+ async def observe_source(self, *args, **kwargs):
+ self._refuse("observe_source")
+ return await super().observe_source(*args, **kwargs)
+
+ async def discover_models(self, *args, **kwargs):
+ self._refuse("discover_models")
+ return await super().discover_models(*args, **kwargs)
+
+
+_REUSED_CLAUDE_KEY = "sk-ant-revoked-123456789"
+
+
+def _write_offline_static_keys(home: Path) -> None:
+ """Static keys across backends, two of them on one backend, none reachable."""
+ # Already a Hub Source, whose last call found the key revoked upstream.
+ _write(
+ home / ".claude" / "settings.json",
+ json.dumps({"env": {"ANTHROPIC_API_KEY": _REUSED_CLAUDE_KEY}, "permissions": {"allow": ["Read"]}}),
+ )
+ # The relay speaks Chat Completions; nothing may re-detect it as Responses.
+ _write(home / ".codex" / "auth.json", json.dumps({"OPENAI_API_KEY": "sk-openai-offline-123456"}))
+ _write(
+ home / ".codex" / "config.toml",
+ 'cli_auth_credentials_store = "file"\nmodel_provider = "Relay"\n\n'
+ '[model_providers.Relay]\nbase_url = "https://offline-relay.example/v1"\nwire_api = "chat"\n',
+ )
+ _write(
+ home / ".config" / "opencode" / "opencode.json",
+ json.dumps({"provider": {
+ "openrouter": {"models": {"manual-openrouter-model": {"name": "Manual OpenRouter Model"}}},
+ "zhipuai": {"options": {"baseURL": "https://offline-zhipu.example/v1"}},
+ }}),
+ )
+ _write(
+ home / ".local" / "share" / "opencode" / "auth.json",
+ json.dumps({
+ "openrouter": {"type": "api", "key": "sk-or-expired-123456"},
+ "zhipuai": {"type": "api", "key": "sk-zhipu-offline-123456"},
+ }),
+ )
+ _write(
+ home / ".cache" / "opencode" / "models.json",
+ json.dumps({
+ "openrouter": {
+ "id": "openrouter", "npm": "@openrouter/ai-sdk-provider",
+ "api": "https://openrouter.ai/api/v1",
+ },
+ "zhipuai": {
+ "id": "zhipuai", "npm": "@ai-sdk/openai-compatible",
+ "api": "https://offline-zhipu.example/v1",
+ },
+ }),
+ )
+
+
[email protected]("clean_api_keys", (False, True))
+def test_mh_mig_015_static_keys_migrate_from_saved_configuration_without_upstream_contact(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, clean_api_keys: bool,
+) -> None:
+ """Scenario: MH-MIG-015."""
+ native_home = tmp_path / "native-home"
+ _isolate_native_home(monkeypatch, native_home)
+ adapter = OfflineUpstreamAdapter()
+ service, store, _ = _service(tmp_path, adapter=adapter)
+ # Seeded while the provider still answered; it has since revoked the key.
+ asyncio.run(service.create_source({
+ "kind": "api_key", "vendor": "anthropic", "key": _REUSED_CLAUDE_KEY,
+ "display_name": "Existing Claude key",
+ }))
+ [reused] = store.config.sources
+ reused.state = ModelHubSourceStateConfig(
+ status="needs_action", detail_key="models.source.needs_action.credential_revoked",
+ )
+ reused_before = reused.to_payload()
+ provisioned_before = len(adapter.provisioned)
+
+ _write_offline_static_keys(native_home)
+ before = _tree_digest(native_home)
+ # No models.dev refresh may sneak in through menu carry or Vibey's seed.
+ # The normal cache getter starts a background fetch on a miss; merely
+ # avoiding the explicit foreground loader is not sufficient.
+ catalog_requests = []
+
+ def unexpected_catalog_request(*args, **kwargs):
+ catalog_requests.append("models.dev")
+ raise AssertionError("migration must read models.dev only from cache")
+
+ monkeypatch.setattr("vibe.models_dev_catalog.load_models_dev_catalog_with_date", unexpected_catalog_request)
+ monkeypatch.setattr("vibe.models_dev_catalog.load_models_dev_catalog", unexpected_catalog_request)
+ store.config.vibey_supply_pending = True
+ store.config.agents["opencode"].mode = "direct"
+ service.named_agents_override = lambda backend: [
+ ("offline", "openrouter/manual-openrouter-model"),
+ ] if backend == "opencode" else []
+ adapter.offline = True
+ items = service.migration_scan()["items"]
+ assert {(item["backend"], item.get("vendor")) for item in items} == {
+ ("claude", "anthropic"), ("codex", "openai"),
+ ("opencode", "openrouter"), ("opencode", "zhipuai"),
+ }
+ assert all(item["proposed_action"] == "import" for item in items)
+ ids = [item["id"] for item in items]
+
+ try:
+ result = asyncio.run(service.migration_apply(ids, clean_api_keys=clean_api_keys))
+ finally:
+ # A refused call may resurface only as a generic conflict; name it.
+ assert adapter.upstream_calls == []
+ assert catalog_requests == []
+ assert set(result) == {"applied", "sources", "added_to"}
+ assert result["applied"] == len(items)
+ config = _assert_canonical_round_trip(store.config)
+ by_id = {source.id: source for source in config.sources}
+ # The matching Source keeps its identity, custody, inventory and the
+ # failure it last observed: migration neither re-verifies nor clears it.
+ assert by_id[reused.id].to_payload() == reused_before
+ # Every other key is a new Source built from its saved native settings.
+ assert len(adapter.provisioned) == provisioned_before + 3
+ new = {source.vendor: source for source in config.sources if source.id != reused.id}
+ assert set(new) == {"openai", "openrouter", "zhipuai"}
+ assert {vendor: (source.protocol, source.base_url) for vendor, source in new.items()} == {
+ "openai": ("openai_chat", "https://offline-relay.example/v1"),
+ "openrouter": ("openai_chat", "https://openrouter.ai/api/v1"),
+ "zhipuai": ("openai_chat", "https://offline-zhipu.example/v1"),
+ }
+ for source in new.values():
+ assert source.kind == "api_key" and source.supply_channel == "hub"
+ assert source.credential_ref in adapter.keys
+ # Saved, not tested: the first real call proves or fails it.
+ assert source.verification_pending and source.verification_pending.startswith("vp_")
+ assert source.state.status == "standby"
+ # Nothing was fetched, so nothing claims to be upstream inventory.
+ assert all(model.provenance == "manual" for model in source.models)
+ assert [
+ (model.id, model.display_name) for model in new["openrouter"].models
+ ] == [("manual-openrouter-model", "Manual OpenRouter Model")]
+ assert all(store.config.agents[backend].mode == "hub" for backend in ("claude", "codex", "opencode"))
+
+ receipt = service.migration_journal.completed()
+ assert receipt is not None and receipt["clean_api_keys"] is clean_api_keys
+ if clean_api_keys:
+ assert json.loads((native_home / ".claude" / "settings.json").read_text(encoding="utf-8")) == {
+ "env": {}, "permissions": {"allow": ["Read"]},
+ }
+ assert not (native_home / ".codex" / "auth.json").exists()
+ assert "sk-" not in (native_home / ".local" / "share" / "opencode" / "auth.json").read_text(encoding="utf-8")
+ assert receipt["retained_native_ids"] == {}
+ else:
+ assert _tree_digest(native_home) == before
+ assert {copy["source_id"] for copy in receipt["retained_native_ids"].values()} == set(by_id)
+ assert service.migration_scan()["items"] == []
+
+ # The same batch replays its receipt: still no upstream contact, no new
+ # custody, and the same Sources.
+ settled = store.config.to_payload()
+ replay = asyncio.run(service.migration_apply(ids, clean_api_keys=clean_api_keys))
+ assert adapter.upstream_calls == []
+ assert replay["applied"] == result["applied"]
+ assert replay["sources"] == result["sources"]
+ assert len(adapter.provisioned) == provisioned_before + 3
+ assert store.config.to_payload() == settled
diff --git a/tests/test_model_hub_migration_review_boundaries.py b/tests/test_model_hub_migration_review_boundaries.py
index f29a84fe6..3cd79dd15 100644
--- a/tests/test_model_hub_migration_review_boundaries.py
+++ b/tests/test_model_hub_migration_review_boundaries.py
@@ -52,29 +52,22 @@ def _seed(home: Path, shape: str) -> tuple[str, Path]:
"claude-api", "claude-bearer", "codex-api", "codex-alias",
"opencode-api", "codex-reference", "opencode-reference",
])
-def test_persisted_key_proof_and_custody_use_one_value(home, tmp_path, shape):
+def test_persisted_key_custody_holds_the_canonical_value(home, tmp_path, shape):
backend, profile = _seed(home, shape)
service, store, adapter = _service(tmp_path, migration_home=home)
- proof_values = []
- transient = adapter.provision_transient_credential
-
- async def capture_proof(vendor, secret, base_url, **kwargs):
- proof_values.append(secret)
- return await transient(vendor, secret, base_url, **kwargs)
-
- adapter.provision_transient_credential = capture_proof
rows = [row for row in service.migration_scan()["items"] if row["backend"] == backend]
assert len(rows) == 1 and rows[0]["proposed_action"] == "import"
result = asyncio.run(service.migration_apply([rows[0]["id"]], clean_api_keys=True))
assert result["applied"] == 1
[source] = store.config.sources
- assert proof_values == [adapter.keys[source.credential_ref][2]] == [KEY]
+ assert adapter.keys[source.credential_ref][2] == KEY
+ assert not adapter.transient_refs and not adapter.observed
assert profile.read_bytes() == "# 保留偏好\r\n".encode()
assert service.migration_journal.load() is None
@pytest.mark.parametrize("shape", ["claude-bearer", "codex-api", "codex-reference", "opencode-reference"])
-def test_padded_persisted_key_reuses_the_proven_canonical_credential(home, tmp_path, shape):
+def test_padded_persisted_key_reuses_the_canonical_credential(home, tmp_path, shape):
backend, profile = _seed(home, shape)
service, store, adapter = _service(tmp_path, migration_home=home)
vendor = "anthropic" if backend == "claude" else "openai"
@@ -92,7 +85,7 @@ def test_padded_persisted_key_reuses_the_proven_canonical_credential(home, tmp_p
asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))
assert len(adapter.provisioned) == len(store.config.sources) == 1
assert store.config.sources[0].credential_ref == ref
- assert adapter.observed and not adapter.transient_refs
+ assert not adapter.observed and not adapter.transient_refs
assert profile.read_bytes() == "# 保留偏好\r\n".encode()
diff --git a/tests/test_model_hub_migration_static_cleanup.py b/tests/test_model_hub_migration_static_cleanup.py
index 237482a9a..29a089bef 100644
--- a/tests/test_model_hub_migration_static_cleanup.py
+++ b/tests/test_model_hub_migration_static_cleanup.py
@@ -91,25 +91,18 @@ def _selected(items):
@pytest.mark.parametrize("shape", SHAPES)
@pytest.mark.parametrize("raw", [KEY, RAW, f"\u00a0{KEY}\u2003"])
-def test_static_proof_and_custody_use_canonical_value(home, tmp_path, shape, raw):
+def test_static_custody_holds_the_canonical_value(home, tmp_path, shape, raw):
path, roots = _seed(home, shape, raw)
service, store, adapter = _service(tmp_path, migration_home=home)
service.migration_project_roots = lambda: roots
- proof_values = []
- transient = adapter.provision_transient_credential
-
- async def capture(vendor, secret, base_url, **kwargs):
- proof_values.append(secret)
- return await transient(vendor, secret, base_url, **kwargs)
-
- adapter.provision_transient_credential = capture
item = _selected(_items(service, roots))
assert item.secret == KEY
assert raw not in json.dumps(item.to_payload()) and KEY not in repr(item)
result = asyncio.run(service.migration_apply([item.id], clean_api_keys=True))
assert result["applied"] == 1
[source] = store.config.sources
- assert proof_values == [adapter.keys[source.credential_ref][2]] == [KEY]
+ assert adapter.keys[source.credential_ref][2] == KEY
+ assert not adapter.transient_refs and not adapter.observed
assert adapter.auth_schemes[source.credential_ref] == item.auth_scheme
assert KEY.encode() not in path.read_bytes()
if shape == "opencode-auth":
@@ -154,7 +147,7 @@ def test_static_canonical_value_reuses_existing_ref(home, tmp_path, shape):
asyncio.run(service.migration_apply([item.id], clean_api_keys=True))
assert len(adapter.provisioned) == len(store.config.sources) == 1
assert store.config.sources[0].credential_ref == ref
- assert adapter.observed and not adapter.transient_refs
+ assert not adapter.observed and not adapter.transient_refs
assert KEY.encode() not in path.read_bytes()
@@ -171,7 +164,7 @@ def test_other_canonical_credential_is_left_in_place(home, tmp_path, shape):
@pytest.mark.parametrize("shape", CONFIG_SHAPES)
[email protected]("when", ["after-scan", "during-proof"])
[email protected]("when", ["after-scan", "during-custody"])
def test_padding_only_change_never_bypasses_exact_consent(home, tmp_path, shape, when):
path, roots = _seed(home, shape)
service, store, adapter = _service(tmp_path, migration_home=home)
@@ -187,13 +180,13 @@ def test_padding_only_change_never_bypasses_exact_consent(home, tmp_path, shape,
if when == "after-scan":
change()
else:
- observe = adapter.observe_source
+ provision = adapter.provision_credential
async def mutate(*args, **kwargs):
change()
- return await observe(*args, **kwargs)
+ return await provision(*args, **kwargs)
- adapter.observe_source = mutate
+ adapter.provision_credential = mutate
with pytest.raises(ModelHubError):
asyncio.run(service.migration_apply([item.id], clean_api_keys=True))
assert changed is not None and path.read_bytes() == changed
diff --git a/tests/test_model_hub_migration_transport.py b/tests/test_model_hub_migration_transport.py
index 321730141..278f70be0 100644
--- a/tests/test_model_hub_migration_transport.py
+++ b/tests/test_model_hub_migration_transport.py
@@ -245,11 +245,11 @@ def test_apply_entry_revalidates_before_proof_or_source_reuse(tmp_path, native,
@pytest.mark.parametrize("reuse", [False, True])
[email protected]("native_protocol,observed", [
- ("anthropic", "openai_chat"), ("openai_chat", "anthropic"),
[email protected]("native_protocol,upstream_protocol", [
+ ("anthropic", "openai_chat"), ("openai_chat", "anthropic"), ("openai_chat", "openai_responses"),
])
-def test_observation_cannot_change_native_auth_semantics(
- tmp_path, native, reuse, native_protocol, observed,
+def test_migration_keeps_the_saved_protocol_whatever_upstream_would_report(
+ tmp_path, native, reuse, native_protocol, upstream_protocol,
):
_seed(native, "opencode-custom", base_url=OFFICIAL)
path = native / ".config/opencode/opencode.json"
@@ -258,33 +258,21 @@ def test_observation_cannot_change_native_auth_semantics(
"npm": "@ai-sdk/openai-compatible",
"options": {"apiKey": KEY, "baseURL": OFFICIAL},
}}}))
- before = path.read_bytes()
service, store, adapter = _service(tmp_path, migration_home=native)
- adapter.observed_protocols["custom"] = observed
+ adapter.observed_protocols["custom"] = upstream_protocol
if reuse:
ref = asyncio.run(adapter.provision_credential("custom", native_protocol, KEY, OFFICIAL))
store.config.sources.append(_source(ref, vendor="custom", protocol=native_protocol, base_url=OFFICIAL))
adapter.provisioned.clear()
[row] = service.migration_scan()["items"]
assert row["proposed_action"] == "import"
- with pytest.raises(ModelHubError):
- asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))
- assert path.read_bytes() == before
- assert not adapter.provisioned
- assert service.migration_journal.load() is None
-
-
-def test_observation_may_change_openai_dialect_without_changing_bearer_auth(tmp_path, native):
- path = native / ".config/opencode/opencode.json"
- _write(path, json.dumps({"provider": {"custom": {
- "npm": "@ai-sdk/openai-compatible",
- "options": {"apiKey": KEY, "baseURL": CUSTOM},
- }}}))
- service, store, adapter = _service(tmp_path, migration_home=native)
- adapter.observed_protocols["custom"] = "openai_responses"
- [row] = service.migration_scan()["items"]
assert asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))["applied"] == 1
- assert store.config.sources[0].protocol == "openai_responses"
+ assert adapter.observed == []
+ [source] = store.config.sources
+ assert source.protocol == native_protocol
+ assert len(adapter.provisioned) == (0 if reuse else 1)
+ assert KEY.encode() not in path.read_bytes()
+ assert service.migration_journal.load() is None
@asynccontextmanager
@@ -337,47 +325,42 @@ def _real_http_adapter(service, tmp_path):
return runtime
[email protected]("entry", ["claude-settings", "shell", "opencode-custom"])
[email protected]("reuse", [False, True])
-def test_custom_endpoint_refusing_bearer_fails_proof_and_keeps_native_files(
- tmp_path, native, entry, reuse,
[email protected]("accepts", ["x-api-key", "bearer"])
[email protected]("entry,bearer", [
+ ("claude-settings", True), ("shell", True),
+ ("claude-settings", False), ("shell", False), ("opencode-custom", False),
+])
+def test_custom_anthropic_key_migrates_as_bearer_without_contacting_its_endpoint(
+ tmp_path, native, accepts, entry, bearer,
):
async def scenario():
- async with _upstream("x-api-key") as (origin, requests):
- paths, _, _ = _seed(native, entry, base_url=origin)
- before = {path: path.read_bytes() for path in paths}
+ async with _upstream(accepts) as (origin, requests):
+ paths, _, _ = _seed(native, entry, base_url=origin, bearer=bearer)
service, store, _ = _service(tmp_path, migration_home=native)
runtime = _real_http_adapter(service, tmp_path)
- if reuse:
- vendor = "custom" if entry == "opencode-custom" else "anthropic"
- ref = await runtime.provision_credential(vendor, "anthropic", KEY, origin)
- store.config.sources.append(_source(ref, vendor=vendor, base_url=origin))
- config_before = store.config.to_payload()
- credentials_before = set((runtime.state_store.root / "credentials").glob("*.json"))
- # Actual consuming HTTP witness: this upstream accepts the native
- # header, and rejects the pinned CPA custom-origin Bearer header.
+ # Actual consuming HTTP witness: whether this endpoint would accept
+ # the Bearer the engine sends is irrelevant to migration.
+ headers_by_scheme = {"x-api-key": {"x-api-key": KEY}, "bearer": {"Authorization": f"Bearer {KEY}"}}
async with aiohttp.ClientSession() as client:
- for headers, status in (({"x-api-key": KEY}, 200), ({"Authorization": f"Bearer {KEY}"}, 401)):
+ for scheme, headers in headers_by_scheme.items():
async with client.post(origin + "/v1/messages", headers=headers, json={"model": "claude-fixture"}) as response:
- assert response.status == status
+ assert response.status == (200 if scheme == accepts else 401)
requests.clear()
- # Offered as the Bearer the engine would send; a native x-api-key
- # proof never licenses the migration.
rows = service.migration_scan()["items"]
assert rows and all(row["proposed_action"] == "import" for row in rows)
- with pytest.raises(ModelHubError):
- await service.migration_apply([row["id"] for row in rows])
- assert requests
- assert all("x-api-key" not in headers for _, headers in requests)
- assert {path: path.read_bytes() for path in paths} == before
- assert store.config.to_payload() == config_before
- assert set((runtime.state_store.root / "credentials").glob("*.json")) == credentials_before
- assert service.migration_journal.load() is None
+ result = await service.migration_apply([row["id"] for row in rows], clean_api_keys=True)
+ assert result["applied"] == 1
+ assert requests == []
+ [source] = store.config.sources
+ assert await runtime.credential_auth_scheme(source.credential_ref) == "bearer"
+ assert source.models == [] and source.verification_pending
+ assert all(KEY.encode() not in path.read_bytes() for path in paths)
+ assert service.migration_scan()["items"] == []
asyncio.run(scenario())
-def test_real_observation_cannot_promote_custom_key_to_anthropic_transport(tmp_path, native):
+def test_custom_openai_key_stays_openai_against_an_anthropic_endpoint(tmp_path, native):
async def scenario():
async with _upstream("x-api-key") as (origin, requests):
path = native / ".config/opencode/opencode.json"
@@ -385,42 +368,15 @@ def test_real_observation_cannot_promote_custom_key_to_anthropic_transport(tmp_p
"npm": "@ai-sdk/openai-compatible",
"options": {"apiKey": KEY, "baseURL": origin},
}}}))
- before = path.read_bytes()
service, store, _ = _service(tmp_path, migration_home=native)
runtime = _real_http_adapter(service, tmp_path)
[row] = service.migration_scan()["items"]
assert row["proposed_action"] == "import"
- with pytest.raises(ModelHubError):
- await service.migration_apply([row["id"]], clean_api_keys=True)
- assert any(headers.get("x-api-key") == KEY for _, headers in requests)
- assert path.read_bytes() == before
- assert not store.config.sources
- assert not list((runtime.state_store.root / "credentials").glob("*.json"))
- assert service.migration_journal.load() is None
-
- asyncio.run(scenario())
-
-
[email protected]("entry,bearer", [
- ("claude-settings", True), ("shell", True),
- ("claude-settings", False), ("shell", False),
-])
-def test_custom_bearer_keeps_actual_proof_discovery_and_cleanup(tmp_path, native, entry, bearer):
- async def scenario():
- async with _upstream("bearer") as (origin, requests):
- paths, _, _ = _seed(native, entry, base_url=origin, bearer=bearer)
- service, store, _ = _service(tmp_path, migration_home=native)
- runtime = _real_http_adapter(service, tmp_path)
- rows = service.migration_scan()["items"]
- result = await service.migration_apply([row["id"] for row in rows], clean_api_keys=True)
- assert result["applied"] == 1
+ assert (await service.migration_apply([row["id"]], clean_api_keys=True))["applied"] == 1
+ assert requests == []
[source] = store.config.sources
- assert await runtime.credential_auth_scheme(source.credential_ref) == "bearer"
- assert [model.id for model in source.models] == ["claude-fixture"]
- assert all("x-api-key" not in headers for _, headers in requests)
- assert any(headers.get("authorization") == f"Bearer {KEY}" for _, headers in requests)
- assert any("authorization" not in headers for _, headers in requests)
- assert all(KEY.encode() not in path.read_bytes() for path in paths)
- assert service.migration_scan()["items"] == []
+ assert source.protocol == "openai_chat"
+ assert await runtime.credential_auth_scheme(source.credential_ref) is None
+ assert KEY.encode() not in path.read_bytes()
asyncio.run(scenario())
diff --git a/tests/test_model_hub_persisted_inventory.py b/tests/test_model_hub_persisted_inventory.py
index 7c6f509b2..5c5e02204 100644
--- a/tests/test_model_hub_persisted_inventory.py
+++ b/tests/test_model_hub_persisted_inventory.py
@@ -283,7 +283,7 @@ def test_claude_key_and_bearer_are_both_retained(home):
assert len({row.id for row in rows}) == 2
-def test_bearer_scheme_reaches_proof_and_custody_and_prevents_wrong_reuse(home, tmp_path):
+def test_bearer_scheme_reaches_custody_and_prevents_wrong_reuse(home, tmp_path):
path = home / ".claude/settings.json"
_write(path, json.dumps({"env": {
"ANTHROPIC_AUTH_TOKEN": "fixture-same-bytes",
@@ -291,10 +291,8 @@ def test_bearer_scheme_reaches_proof_and_custody_and_prevents_wrong_reuse(home,
}}))
service, store, adapter = _service(tmp_path, migration_home=home)
provision = adapter.provision_credential
- transient = adapter.provision_transient_credential
matches = adapter.matches_api_key_credential
schemes = {}
- proof_schemes = []
async def provision_with_scheme(*args, **kwargs):
scheme = kwargs.pop("auth_scheme", None)
@@ -302,15 +300,10 @@ def test_bearer_scheme_reaches_proof_and_custody_and_prevents_wrong_reuse(home,
schemes[ref] = scheme
return ref
- async def transient_with_scheme(*args, **kwargs):
- proof_schemes.append(kwargs.pop("auth_scheme", None))
- return await transient(*args, **kwargs)
-
async def matches_with_scheme(ref, *args, auth_scheme=None):
return schemes.get(ref) == auth_scheme and await matches(ref, *args)
adapter.provision_credential = provision_with_scheme
- adapter.provision_transient_credential = transient_with_scheme
adapter.matches_api_key_credential = matches_with_scheme
# A pre-existing legacy Source has the same bytes/target but a different
# header scheme. It must not be reused for the new saved Bearer token.
@@ -328,7 +321,7 @@ def test_bearer_scheme_reaches_proof_and_custody_and_prevents_wrong_reuse(home,
rows = service.migration_scan()["items"]
ids = [row["id"] for row in rows]
assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1
- assert proof_schemes == ["bearer"]
+ assert not adapter.transient_refs
assert set(schemes.values()) == {None, "bearer"}
assert len(store.config.sources) == len(adapter.provisioned) == 2
assert "auth_scheme" not in json.dumps(store.config.to_payload())
diff --git a/tests/test_model_hub_provisional_ownership.py b/tests/test_model_hub_provisional_ownership.py
index 75b955984..92cb5a594 100644
--- a/tests/test_model_hub_provisional_ownership.py
+++ b/tests/test_model_hub_provisional_ownership.py
@@ -33,14 +33,13 @@ def _native(monkeypatch, tmp_path, kind):
return service, store, adapter, path, [rows[0]["id"]]
[email protected]("kind", ["oauth", "api_key", "observation"])
[email protected]("kind", ["oauth", "api_key"])
def test_provision_failure_before_return_keeps_durable_cleanup_owner(monkeypatch, tmp_path, kind):
service, store, adapter, native, ids = _native(monkeypatch, tmp_path, kind)
original = native.read_bytes()
method = {
"oauth": "provision_oauth_credential",
"api_key": "provision_credential",
- "observation": "provision_transient_credential",
}[kind]
provision = getattr(adapter, method)
observed = []
@@ -50,9 +49,7 @@ def test_provision_failure_before_return_keeps_durable_cleanup_owner(monkeypatch
on_reserved(ref)
entry, = service.revocations.list()
assert entry.credential_ref == ref
- if kind == "observation":
- assert entry.source_id == "observation"
- elif kind == "oauth":
+ if kind == "oauth":
assert entry.source_id == args[0]
else:
assert entry.source_id.startswith("src_")
@@ -79,7 +76,7 @@ def test_provision_failure_before_return_keeps_durable_cleanup_owner(monkeypatch
adapter.fail_revoke_refs.clear()
asyncio.run(recovered._ensure_engine_synced())
assert recovered.revocations.list() == []
- assert observed[0].credential_ref in adapter.revoked + adapter.transient_revoked
+ assert observed[0].credential_ref in adapter.revoked
assert native.read_bytes() == original
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 9b8b1ae0c..2ce325e56 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -1278,12 +1278,14 @@ def test_machine_error_extractor_reads_only_declared_envelope_paths() -> None:
def test_reasoning_tier_resolver_call_inventory_requires_batch_indexes() -> None:
+ # owner -> (needs the batch index, call sites)
expected = {
- ("service.py", "apply_tiers"): True,
- ("service.py", "_create_oauth_source"): True,
- ("service.py", "create_source"): True,
- ("service.py", "_apply_reasoning_tier_ladder"): False,
- ("migration.py", "_validated_source"): True,
+ ("service.py", "apply_tiers"): (True, 1),
+ ("service.py", "_create_oauth_source"): (True, 1),
+ ("service.py", "create_source"): (True, 1),
+ ("service.py", "_apply_reasoning_tier_ladder"): (False, 1),
+ # A fixed subscription catalog and an API key's saved manual models.
+ ("migration.py", "_validated_source"): (True, 2),
}
calls_by_owner: dict[tuple[str, str | None], list[ast.Call]] = {}
for path in (SERVICE, MIGRATION):
@@ -1296,22 +1298,23 @@ def test_reasoning_tier_resolver_call_inventory_requires_batch_indexes() -> None
calls_by_owner.setdefault(key, []).append(node)
assert set(calls_by_owner) == set(expected)
- assert all(len(calls) == 1 for calls in calls_by_owner.values())
- for key, needs_batch_index in expected.items():
- [call] = calls_by_owner[key]
- injected = next(
- (
- keyword.value
- for keyword in call.keywords
- if keyword.arg == "catalog_efforts_by_model"
- ),
- None,
- )
- if needs_batch_index:
- assert isinstance(injected, ast.Name)
- assert injected.id == "catalog_efforts_by_model"
- else:
- assert injected is None
+ for key, (needs_batch_index, call_sites) in expected.items():
+ calls = calls_by_owner[key]
+ assert len(calls) == call_sites
+ for call in calls:
+ injected = next(
+ (
+ keyword.value
+ for keyword in call.keywords
+ if keyword.arg == "catalog_efforts_by_model"
+ ),
+ None,
+ )
+ if needs_batch_index:
+ assert isinstance(injected, ast.Name)
+ assert injected.id == "catalog_efforts_by_model"
+ else:
+ assert injected is None
def test_settlement_abandonment_cannot_overwrite_a_committed_terminal_fact() -> None:
diff --git a/tests/test_model_hub_takeover_inventory.py b/tests/test_model_hub_takeover_inventory.py
index af4a86c0b..3b9f92190 100644
--- a/tests/test_model_hub_takeover_inventory.py
+++ b/tests/test_model_hub_takeover_inventory.py
@@ -384,8 +384,7 @@ def test_existing_hub_key_still_clears_legacy_auth_when_hub_config_is_unchanged(
assert service.migration_journal.load() is None
[email protected]("accepted", [False, True])
-def test_reused_hub_key_requires_current_proof_before_native_cleanup(monkeypatch, tmp_path, accepted):
+def test_reused_hub_key_cleans_native_copy_without_current_proof(monkeypatch, tmp_path):
home = tmp_path / "native"
_isolate_native_home(monkeypatch, home)
service, store, adapter = _service(tmp_path, migration_home=home)
@@ -396,22 +395,15 @@ def test_reused_hub_key_requires_current_proof_before_native_cleanup(monkeypatch
store.config.agents["claude"].mode = "direct"
native = home / ".claude/settings.json"
_write(native, '{"env":{"ANTHROPIC_API_KEY":"fixture-key"},"mcp":{"keep":true}}')
- before = native.read_bytes()
previous = store.config.to_payload()
observed = len(adapter.observed)
ids = [row["id"] for row in service.migration_scan()["items"]]
- if not accepted:
- adapter.unproven_observation_vendor = "anthropic"
- with pytest.raises(ModelHubError) as failure:
- asyncio.run(service.migration_apply(ids, clean_api_keys=True))
- assert failure.value.code == "migration_item_conflict"
- assert native.read_bytes() == before
- assert store.config.to_payload() == previous
- else:
- assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1
- assert store.config.to_payload()["sources"] == previous["sources"]
- assert json.loads(native.read_text()) == {"env": {}, "mcp": {"keep": True}}
- assert len(adapter.observed) == observed + 1
+ # The provider would no longer prove this key; migration does not ask.
+ adapter.unproven_observation_vendor = "anthropic"
+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1
+ assert store.config.to_payload()["sources"] == previous["sources"]
+ assert json.loads(native.read_text()) == {"env": {}, "mcp": {"keep": True}}
+ assert len(adapter.observed) == observed
assert len(adapter.provisioned) == 1
assert service.migration_journal.load() is None
diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsx
index 12211229a..08406f2d0 100644
--- a/ui/src/components/settings/models/MigrationDialog.test.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx
@@ -317,7 +317,7 @@ describe('MigrationDialog — the settings default', () => {
['migration_runtime_stopping', 'The task these assistants were running in Avibe is still stopping. Try again in a moment.'],
['migration_permission_needed', 'Allow credential access, then retry.'],
['migration_recovery_pending', 'Migration is unfinished. Retry to continue.'],
- ['migration_item_conflict', 'Migration could not verify the saved configuration or its credentials. Check the files and authentication before retrying, or add the source manually in Model Hub.'],
+ ['migration_item_conflict', 'The selected configuration could not be migrated safely. Reopen the migration dialog to scan the latest configuration. If it still fails, check the file format and access permissions.'],
['migration_configuration_blocked', 'Adjust the native configuration, then scan again.'],
['migration_reauthorization_required', 'This backend was already migrated, and the changed native login cannot be verified as a new authorization. The original files are unchanged. Sign in again for the existing source in Model Hub instead of importing this login.'],
] as const)('explains a batch refused as %s inside the dialog', async (code, message) => {
@@ -336,7 +336,7 @@ describe('MigrationDialog — the settings default', () => {
expect(showToast).not.toHaveBeenCalledWith(message, 'error');
});
- it('keeps selection and explains configuration or credential verification failure in Chinese', async () => {
+ it('keeps selection and explains a local migration conflict in Chinese', async () => {
await i18n.changeLanguage('zh');
const onClose = vi.fn();
vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
@@ -349,7 +349,7 @@ describe('MigrationDialog — the settings default', () => {
await user.click(within(dialog).getByRole('button', { name: '开始迁移' }));
expect((await within(dialog).findByRole('alert')).textContent).toBe(
- '无法验证已保存的配置或凭据。请检查配置文件和认证是否有效后重试,或在模型网关中手动添加供应商。',
+ '无法安全迁移所选配置。请重新打开迁移窗口以扫描最新配置;若仍然失败,请检查配置文件格式和访问权限。',
);
expect(onClose).not.toHaveBeenCalled();
expect(rowCheckboxes(dialog)[0].getAttribute('aria-checked')).toBe('true');
@@ -425,8 +425,8 @@ describe('MigrationDialog — the settings default', () => {
describe('MigrationDialog — persisted authentication', () => {
it.each([
- ['en', 'Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, assistants authenticate through Model Hub: subscription sign-ins move into Model Hub, and API keys are copied while the originals stay in place.'],
- ['zh', '导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。迁移后,助手统一通过模型网关认证:订阅登录转交模型网关托管,API Key 复制导入,原配置默认保留。'],
+ ['en', 'Import authentication saved in configuration files, shell startup files, or supported credential stores. Subscription sign-ins move into Model Hub. API keys are copied as saved, with the originals kept by default; migration does not test keys online or fetch model lists. Later model requests establish whether a key works.'],
+ ['zh', '导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。订阅登录转交模型网关托管;API Key 直接复制导入,原配置默认保留,迁移时不联网校验 Key 或拉取模型列表。Key 是否可用由后续模型调用确认。'],
] as const)('explains the saved source boundary and consequence in %s', async (language, sentence) => {
await i18n.changeLanguage(language);
serve([CODEX_KEY]);
@@ -768,7 +768,7 @@ describe('MigrationDialog — the Settings surface the setup scope must not dist
expect(visibleText(dialog)).toEqual([
'Migrate to the Model Hub',
- 'Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, assistants authenticate through Model Hub: subscription sign-ins move into Model Hub, and API keys are copied while the originals stay in place.',
+ 'Import authentication saved in configuration files, shell startup files, or supported credential stores. Subscription sign-ins move into Model Hub. API keys are copied as saved, with the originals kept by default; migration does not test keys online or fetch model lists. Later model requests establish whether a key works.',
'Claude Code',
'Anthropic',
'Claude 账号登录(OAuth) · Claude Code configuration',
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 991b9643c..e7b3661da 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -337,7 +337,7 @@ describe('SettingsModelsPage surface branches', () => {
await userEvent.click(await screen.findByRole('button', { name: /Switch to gateway|切换到模型网关/i }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByRole('checkbox', { name: /Claude native login/ })).toBeTruthy();
- expect(within(dialog).getByText(/After migration|迁移后/)).toBeTruthy();
+ expect(within(dialog).getByText(/migration does not test keys online|迁移时不联网校验 Key/)).toBeTruthy();
expect(setMode).not.toHaveBeenCalled();
if (refused) {
await userEvent.click(within(dialog).getByRole('button', { name: /Start migration|开始迁移/i }));
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a979594f3..fe14c957d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2084,7 +2084,7 @@
"migration": {
"open": "Migrate configuration",
"title": "Migrate to the Model Hub",
- "subtitle": "Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, assistants authenticate through Model Hub: subscription sign-ins move into Model Hub, and API keys are copied while the originals stay in place.",
+ "subtitle": "Import authentication saved in configuration files, shell startup files, or supported credential stores. Subscription sign-ins move into Model Hub. API keys are copied as saved, with the originals kept by default; migration does not test keys online or fetch model lists. Later model requests establish whether a key works.",
"cleanApiKeys": "Also remove the API keys from the native CLI configuration",
"cleanApiKeysHint": "Includes shell startup files and each CLI’s config files. Left unchecked, those keys stay as they are; assistants launched through Model Hub don’t use them.",
"empty": "No configuration found to migrate.",
@@ -2112,7 +2112,7 @@
"runtimeStopping": "The task these assistants were running in Avibe is still stopping. Try again in a moment.",
"permissionNeeded": "Allow credential access, then retry.",
"recoveryPending": "Migration is unfinished. Retry to continue.",
- "itemConflict": "Migration could not verify the saved configuration or its credentials. Check the files and authentication before retrying, or add the source manually in Model Hub.",
+ "itemConflict": "The selected configuration could not be migrated safely. Reopen the migration dialog to scan the latest configuration. If it still fails, check the file format and access permissions.",
"configurationBlocked": "Adjust the native configuration, then scan again.",
"credentialsInvalid": "Authentication has expired. Sign in again in Model Hub.",
"reauthorizationRequired": "This backend was already migrated, and the changed native login cannot be verified as a new authorization. The original files are unchanged. Sign in again for the existing source in Model Hub instead of importing this login."
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 8e6ccaade..8260063fb 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2084,7 +2084,7 @@
"migration": {
"open": "迁移配置",
"title": "迁移到模型网关",
- "subtitle": "导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。迁移后,助手统一通过模型网关认证:订阅登录转交模型网关托管,API Key 复制导入,原配置默认保留。",
+ "subtitle": "导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。订阅登录转交模型网关托管;API Key 直接复制导入,原配置默认保留,迁移时不联网校验 Key 或拉取模型列表。Key 是否可用由后续模型调用确认。",
"cleanApiKeys": "同时清理原生 CLI 中的 API Key 配置",
"cleanApiKeysHint": "包括 Shell 启动文件和各 CLI 的配置文件。不勾选时这些 Key 保持原样,经模型网关启动的助手不会使用它们。",
"empty": "没有检测到可迁移的配置。",
@@ -2112,7 +2112,7 @@
"runtimeStopping": "这些助手刚才在 Avibe 中运行的任务还在停止中,请稍后重试。",
"permissionNeeded": "请允许访问凭据,再重试。",
"recoveryPending": "迁移尚未完成,请重试以继续。",
- "itemConflict": "无法验证已保存的配置或凭据。请检查配置文件和认证是否有效后重试,或在模型网关中手动添加供应商。",
+ "itemConflict": "无法安全迁移所选配置。请重新打开迁移窗口以扫描最新配置;若仍然失败,请检查配置文件格式和访问权限。",
"configurationBlocked": "请先调整原生配置,再重新扫描。",
"credentialsInvalid": "认证已过期,请在模型网关中重新登录。",
"reauthorizationRequired": "此后端已迁移过,无法确认改动后的原生登录是否是新授权。原配置文件未改动,请在模型网关中为已有供应商重新登录,不要再次导入这份登录。"