Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): keep native API keys by default when migrating (#2165)
Call White5f512e06b04b
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex 214147190..9f63e2e1f 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -11,7 +11,7 @@ import refrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Awaitable, Callable, Literal, Mapping, Optional, Protocol, cast+from typing import Any, Awaitable, Callable, Collection, Literal, Mapping, Optional, Protocol, castfrom config.v2_config import (ModelHubConfig,@@ -34,6 +34,7 @@ from core.handlers.model_hub.migration_files import (codex_config_paths,env_reference,env_references,+ native_store_items,opencode_auth_path,opencode_config_paths,plan_native_cleanup,@@ -232,6 +233,8 @@ class NativeMigrationItem:# A metadata-only OS-store row represents one selected credential# container. Its API-key/OAuth components are resolved after consent.native_store_placeholder: bool = False+ # Codex routing (provider, URL, wire API) the store's credential feeds.+ native_store_routing: Optional[str] = field(default=None, repr=False)source_paths: tuple[str, ...] = ()required_backends: tuple[str, ...] = ()shell_variables: tuple[str, ...] = field(default=(), repr=False)@@ -269,6 +272,10 @@ class NativeMigrationItem:# The backend's native config cannot be parsed, so Hub mode would# fail every launch: the whole group is blocked, not just this row."config_blocker": self.config_blocker,+ # An opaque store resolves only after consent and may hold a key.+ "may_hold_api_key": self.kind != "oauth_native" or (+ self.native_store_placeholder and self.backend == "codex"+ ),}@@ -277,6 +284,33 @@ def _stable_suffix(*parts: str) -> str:return hashlib.sha256(identity).hexdigest()[:16]+def _retained_key_identity(item: NativeMigrationItem) -> str:+ """Name a copied static key independently of the store revision holding it."""+ return "key_" + _stable_suffix(+ item.backend, item.vendor, item.protocol, item.auth_scheme or "",+ item.native_provider_id or "", item.secret or "", item.base_url or "",+ )+++def _retained_key_fingerprint(item: NativeMigrationItem) -> str:+ """Name a copied static key by backend and material alone, across routes."""+ return "keymat_" + _stable_suffix(item.backend, (item.secret or "").strip())+++def _retained_copy_live(copy: Mapping[str, str] | None, live_credentials: Mapping[str, object]) -> bool:+ """A kept native key is shadowed only while Hub still holds its exact copy."""+ return copy is not None and live_credentials.get(copy["source_id"], None) == copy["credential_ref"]+++def _receipt_sources_intact(host: MigrationHost, record: Mapping[str, Any]) -> bool:+ """Whether every Source a completed batch created still holds its credential."""+ current = {source.id: source.credential_ref for source in host.store.load().sources}+ return all(+ source_id in current and current[source_id] == record.get("source_credentials", {}).get(source_id)+ for source_id in record["source_ids"]+ )++def _ids(backend: str,kind: str,@@ -531,7 +565,13 @@ def _native_store_items(_oauth_text(state, "wire_api") or "",_oauth_text(state, "active_provider_id") or "",)- items = [replace(item, id=f"mig_{_stable_suffix(item.id, routing_revision)}") for item in items]+ items = [+ replace(+ item, id=f"mig_{_stable_suffix(item.id, routing_revision)}",+ native_store_routing=routing_revision,+ )+ for item in items+ ]return items@@ -1289,46 +1329,6 @@ def _shell_items(return items-def _surface_surviving_auth_references(- items: list[NativeMigrationItem], *, home: Path | None,- project_roots: tuple[Path, ...],-) -> list[NativeMigrationItem]:- """Preview the same native after images used by the cleanup transaction."""- selected = [item for item in items if item.proposed_action == "import"]- auth_names = {- name for item in selected for name, _ in item.shell_values- if name in item.shell_auth_variables- }- if not auth_names:- return items- try:- edits = {- edit.path: edit for edit in plan_native_cleanup(- selected, home=home, project_roots=project_roots, _include_shell=False,- )- }- references = planned_native_references(edits, home=home, project_roots=project_roots)- except (OSError, TakeoverStateError):- # Store permissions and unsupported credentials have their own rows.- # A preview cannot replace the consent-time native-store resolution.- return items- return [- replace(- item, proposed_action="reauth", selected=False,- notes_key="settings.models.migration.blocked.reference",- source_paths=tuple(dict.fromkeys([- *item.source_paths,- *(path for name in item.shell_auth_variables if name in references- for path in references[name]),- ])),- ) if (- item.proposed_action == "import"- and set(item.shell_auth_variables) & auth_names & references.keys()- ) else item- for item in items- ]--def _bind_persisted_inventory(items: list[NativeMigrationItem], persisted: PersistedInventory,) -> list[NativeMigrationItem]:@@ -1480,6 +1480,7 @@ def scan_native_configs(secret_backends: tuple[str, ...] = (),project_roots: tuple[Path, ...] = (),clean_native_stores: Mapping[str, str] | None = None,+ retained_native_ids: Mapping[str, Mapping[str, str]] | None = None,) -> list[NativeMigrationItem]:"""Read native stores without modifying or deleting any path."""@@ -1559,6 +1560,7 @@ def scan_native_configs(for source in config.sourcesif source.kind == "subscription" and source.supply_channel == "native_cli"}+ live_credentials = {source.id: source.credential_ref for source in config.sources}candidates: list[NativeMigrationItem] = []for item in items:# Keep the credential/target identity independent of both consent's@@ -1574,6 +1576,25 @@ def scan_native_configs(# only unrelated native data (e.g. MCP OAuth). Do not read it again# merely to rediscover the absence of subscription credentials.continue+ if item.native_store_placeholder and any(+ copy.get("store_backend") == item.backend+ and copy.get("store_routing", "") == (item.native_store_routing or "")+ and copy.get("store_revision") == item.native_store_revision+ and _retained_copy_live(copy, live_credentials)+ for copy in (retained_native_ids or {}).values()+ ):+ # An opaque store whose only credential is a kept, copied key. Its+ # metadata revision was recorded at completion; any change re-offers.+ continue+ if (+ item.kind != "oauth_native" and item.secret+ and _retained_copy_live(+ (retained_native_ids or {}).get(_retained_key_identity(item)), live_credentials,+ )+ ):+ # A completed takeover copied this exact static key and left it+ # native by choice. It is shadowed by the Hub launch, not pending.+ continuenative_source = existing_native_sources.get(item.vendor)if item.kind == "oauth_native" and native_source is not None:candidates.append(replace(@@ -1583,9 +1604,6 @@ def scan_native_configs())continuecandidates.append(item)- candidates = _surface_surviving_auth_references(- candidates, home=home, project_roots=project_roots,- )return _bind_persisted_inventory(candidates, persisted)@@ -1688,22 +1706,33 @@ async def _prepare_takeover(retained_source_ids: tuple[str, ...] | None = None,retained_item_ids: frozenset[str] = frozenset(),clean_native_stores: Mapping[str, str] | None = None,+ clean_api_keys: bool = False,+ retained_keys: tuple[NativeMigrationItem, ...] = (),) -> dict[str, Any]:- """Stage all grants and durable before/after images, still native-owned."""+ """Stage all grants and durable before/after images, still native-owned.++ ``retained_keys`` are keys an earlier copy-only batch already copied; a+ cleanup batch withdraws them natively without provisioning them again.+ """for item in selected:# Recheck before cleanup planning, reuse, proof or credential custody._require_native_api_key_transport(item)clean_native_stores = dict(clean_native_stores or {})cleanup_items = [*selected,+ *retained_keys,*(item for item in (consented or []) if (item.native_store_placeholder and item.backend in clean_native_stores)),]- edits = plan_native_cleanup(cleanup_items, home=host.migration_home, project_roots=project_roots)+ edits = plan_native_cleanup(+ cleanup_items, home=host.migration_home, project_roots=project_roots,+ clean_api_keys=clean_api_keys,+ )updated = host._clone_config(previous)provisioned: list[dict[str, str]] = []source_ids: list[str] = list(retained_source_ids or ())+ item_sources: dict[str, dict[str, str]] = {}catalog = bundled_catalog_reasoning_efforts_by_model()handoff_attempted = Falsetry:@@ -1711,7 +1740,9 @@ async def _prepare_takeover(# reintroduced by an external writer. Its current Hub refs are already# authoritative; never provision that old OAuth snapshot again.for item in selected:- if item.id in retained_item_ids:+ # A static key reuses its existing Source below, which also+ # records the copy's receipt; only a login is never re-provisioned.+ if item.id in retained_item_ids and item.kind == "oauth_native":continueprotocol = item.protocolauth_options = {"auth_scheme": item.auth_scheme} if item.auth_scheme is not None else {}@@ -1745,6 +1776,13 @@ async def _prepare_takeover(_require_native_api_key_transport(item, observed_protocol=reuse_observation.protocol)_ensure_takeover_placement(updated, candidate, item.backend)source_ids.append(candidate.id)+ item_sources[_retained_key_identity(item)] = {+ "source_id": candidate.id, "credential_ref": candidate.credential_ref,+ "key_fingerprint": _retained_key_fingerprint(item),+ **({+ "store_backend": item.backend, "store_routing": item.native_store_routing or "",+ } if item.native_store_revision else {}),+ }breakelse:observation = await host._require_proven_source_payload({@@ -1825,9 +1863,30 @@ async def _prepare_takeover(updated.sources.append(source)host._apply_source_placement(updated, source)source_ids.append(source.id)- backends = sorted({item.backend for item in (consented or selected)})+ if item.kind != "oauth_native":+ item_sources[_retained_key_identity(item)] = {+ "source_id": source.id, "credential_ref": source.credential_ref,+ "key_fingerprint": _retained_key_fingerprint(item),+ **({+ "store_backend": item.backend, "store_routing": item.native_store_routing or "",+ } if item.native_store_revision else {}),+ }+ backends = sorted({item.backend for item in [*(consented or selected), *retained_keys]})native_before = _native_auth_snapshot(host, tuple(backends))- credential_backends = {item.backend for item in selected}+ # Copy-only keeps the Avibe-saved native key; Hub launches shadow it.+ # Cleanup clears the Avibe-saved key only when this batch carries it; an+ # excluded key (e.g. an unimportable endpoint) keeps its Direct config.+ carried = {+ (item.backend, item.secret, item.base_url)+ for item in [*selected, *retained_keys] if item.secret+ }+ credential_backends = {+ backend for backend in {item.backend for item in [*selected, *retained_keys]}+ if not native_before.get(backend, {}).get("api_key")+ or (+ backend, native_before[backend]["api_key"], native_before[backend].get("base_url"),+ ) in carried+ } if clean_api_keys else set()native_after = {backend: ({name: ("oauth" if name == "auth_mode" else True if name == "auth_mode_set" else None)@@ -1852,9 +1911,22 @@ async def _prepare_takeover("native_before": native_before, "native_after": native_after,"keychain": [],"clean_native_stores": clean_native_stores,+ # Each copied key stays hidden only while its Hub Source exists.+ "clean_api_keys": clean_api_keys,+ "retained_native_ids": {} if clean_api_keys else {+ identity: copy for identity, copy in item_sources.items()+ },+ # A cleanup batch withdraws these kept keys, retiring their receipts.+ # Identities and material fingerprints both retire: a receipt+ # written under an earlier route still names this withdrawn key.+ "withdrawn_native_ids": sorted({+ name for item in [*selected, *retained_keys]+ if clean_api_keys and item.kind != "oauth_native"+ for name in (_retained_key_identity(item), _retained_key_fingerprint(item))+ }),}seen_stores: set[str] = set()- for item in selected:+ for item in native_store_items([*selected, *retained_keys], clean_api_keys=clean_api_keys):edit = item.native_store_editif not edit or item.native_store_revision in seen_stores:continue@@ -1919,6 +1991,26 @@ async def _verify_clean_native_stores(host: MigrationHost, record: Mapping[str,raise MigrationConflictError+async def _record_retained_store_revisions(host: MigrationHost, record: dict[str, Any]) -> None:+ """Bind each kept key held in an opaque store to that store's final revision."""+ for copy in record.get("retained_native_ids", {}).values():+ backend = copy.get("store_backend")+ if backend is None:+ continue+ # The store still holds this key, so it is not verified clean: it stays+ # hidden only while the copied Hub source is live.+ record.get("clean_native_stores", {}).pop(backend, None)+ snapshot = await asyncio.to_thread(read_native_oauth, backend, home=host.migration_home)+ verified = record.get("verified_store_revisions", {}).get(backend)+ # Bind only the revision verified against our post-edit image; a later+ # external write stays unbound, so its store is offered again.+ if (+ snapshot is not None and (snapshot.payload or {}).get("status") == "metadata_only"+ and (verified is None or snapshot.revision == verified)+ ):+ copy["store_revision"] = snapshot.revision++async def _resume_takeover(host: MigrationHost,record: dict[str, Any],@@ -2011,10 +2103,14 @@ async def _resume_takeover(# Bind the public metadata revision to the verified private# post-state. A detected intervening login prevents completion.await asyncio.to_thread(check_keychain_edit, edit, applied=True)+ if snapshot is not None:+ record.setdefault("verified_store_revisions", {})[edit["backend"]] = snapshot.revisionif snapshot and (snapshot.payload or {}).get("status") == "metadata_only":record["clean_native_stores"][edit["backend"]] = snapshot.revisionawait verify_idle()if terminal:+ # Every terminal path binds kept keys before its receipt.+ await _record_retained_store_revisions(host, record)return _finish_rejected_takeover(host, record)for credential in record["credentials"]:if credential["kind"] == "oauth":@@ -2058,6 +2154,7 @@ async def _resume_takeover(# Persist the terminal decision before its config write. A crash# between either write and the receipt must finish custody, never# restore the original grant or repeat a rejected refresh.+ await _record_retained_store_revisions(host, record)record["terminal"] = {"invalid_source_ids": invalid_source_ids,"config": terminal_config.to_payload(),@@ -2065,6 +2162,7 @@ async def _resume_takeover(host.migration_journal.save(record)return _finish_rejected_takeover(host, record)host._reconcile_native_auth(tuple(record["backends"]))+ await _record_retained_store_revisions(host, record)host.migration_journal.complete(record)host.migration_blocked_backends.difference_update(record["backends"])return len(record["items"]), [@@ -2092,8 +2190,12 @@ async def apply_native_migration(*,mask_credential: Callable[[str], str],validate_base_url: Callable[[object], Optional[str]],+ clean_api_keys: bool = False,) -> tuple[int, list[dict]]:- """Own a takeover from consent through cleanup; callers shield cancellation."""+ """Own a takeover from consent through cleanup; callers shield cancellation.++ Static API keys are copied and left native unless ``clean_api_keys``.+ """if (not isinstance(item_ids, list)or not all(isinstance(value, str) and value for value in item_ids)@@ -2105,11 +2207,28 @@ async def apply_native_migration(async with host._migration_lock:completed_record = Nonerecord = host.migration_journal.load() or host.migration_journal.completed()+ # A copy-only batch whose Sources were deleted or re-keyed no longer+ # holds its still-native keys; the same rows then migrate afresh. A+ # cleanup receipt keeps guarding the material it withdrew.+ replayable = record is not None and (+ record["phase"] != "complete" or record.get("clean_api_keys", True)+ or _receipt_sources_intact(host, record)+ )if record is not None:same_selection = {item["id"] for item in record["items"]} == set(item_ids)if record["phase"] != "complete" and not same_selection:raise MigrationConflictError- if same_selection:+ # Receipts predating the option always cleaned native keys. A+ # pending journal from before it already staged that decision and+ # resumes as staged. A completed batch is replayed only with its+ # own choice; with another one the rows migrate afresh, which+ # requires the native credentials to be present again.+ option_changed = replayable and same_selection and (+ "clean_api_keys" in record or record["phase"] == "complete"+ ) and record.get("clean_api_keys", True) != clean_api_keys+ if option_changed and record["phase"] != "complete":+ raise MigrationConflictError+ if same_selection and replayable and not option_changed:if record["phase"] == "complete":async with host.migration_guard(tuple(record["backends"])) as verify_idle:async with host._mutation_lock:@@ -2122,6 +2241,7 @@ async def apply_native_migration(legacy_auth=_native_auth_snapshot(host, tuple(record["backends"])),project_roots=host.migration_project_roots(),clean_native_stores=record.get("clean_native_stores"),+ retained_native_ids=record.get("retained_native_ids"),)if not any(item.backend in record["backends"]@@ -2141,6 +2261,7 @@ async def apply_native_migration(legacy_auth=_native_auth_snapshot(host, ("claude", "codex", "opencode")),project_roots=host.migration_project_roots(),clean_native_stores=(host.migration_journal.completed() or {}).get("clean_native_stores"),+ retained_native_ids=(host.migration_journal.completed() or {}).get("retained_native_ids"),)selected = [item for item in available if item.id in item_ids]if len(selected) != len(item_ids) or any(item.proposed_action != "import" for item in selected):@@ -2159,10 +2280,40 @@ async def apply_native_migration(# Hub mode over a native config the CLI cannot parse fails every launch.if any(item.backend in backends and item.config_blocker for item in available):raise MigrationConflictError+ if clean_api_keys:+ # Cleanup also withdraws keys a copy-only batch kept. Such a key+ # may be shared with another backend (e.g. one shell variable);+ # joint cleanup then spans that backend's kept keys as well.+ hidden = [+ item for item in await asyncio.to_thread(+ scan_native_configs, host.store.load(), mask_credential=mask_credential,+ home=host.migration_home, validate_base_url=validate_base_url,+ legacy_auth=_native_auth_snapshot(host, ("claude", "codex", "opencode")),+ project_roots=host.migration_project_roots(),+ clean_native_stores=(host.migration_journal.completed() or {}).get("clean_native_stores"),+ )+ if item.kind != "oauth_native" and item.proposed_action == "import"+ and item.id not in {row.id for row in available}+ ]+ scope = set(backends)+ while True:+ grown = scope | {+ backend for item in hidden if item.backend in scope for backend in item.required_backends+ }+ if grown == scope:+ break+ scope = grown+ if any(+ item.backend in scope - set(backends) and item.proposed_action == "import"+ for item in available+ ):+ # A linked backend still has credentials awaiting consent.+ raise MigrationConflictError+ backends = tuple(sorted(scope))retained_inventory_ids = (set(record.get("inventory_ids", [item["id"] for item in record["items"]]))& {item.receipt_identity or item.id for item in selected}- if record is not None and record["phase"] == "complete" else set()+ if replayable and record["phase"] == "complete" else set())previous_oauth_backends = (host.migration_journal.oauth_custody_backends(record)@@ -2192,6 +2343,7 @@ async def apply_native_migration(secret_backends=backends,project_roots=project_roots,clean_native_stores=(host.migration_journal.completed() or {}).get("clean_native_stores"),+ retained_native_ids=(host.migration_journal.completed() or {}).get("retained_native_ids"),)consented = selectedselected = []@@ -2263,6 +2415,24 @@ async def apply_native_migration(for item in rescanned):raise MigrationConflictError+ retained_keys: tuple[NativeMigrationItem, ...] = ()+ if clean_api_keys:+ # Keys a copy-only batch kept are hidden from consent while+ # their Hub copy lives, yet cleanup must withdraw them too+ # or they read as unselected native credentials.+ shown = {item.id for item in rescanned}+ unfiltered = await asyncio.to_thread(+ scan_native_configs, previous, mask_credential=mask_credential,+ home=host.migration_home, validate_base_url=validate_base_url,+ legacy_auth=_native_auth_snapshot(host, backends),+ secret_backends=backends, project_roots=project_roots,+ clean_native_stores=(host.migration_journal.completed() or {}).get("clean_native_stores"),+ )+ retained_keys = tuple(+ item for item in unfiltered+ if item.backend in backends and item.id not in shown+ and item.kind != "oauth_native" and item.proposed_action == "import" and item.secret+ )record = await _prepare_takeover(host, previous, selected, mask_credential=mask_credential,validate_base_url=validate_base_url,@@ -2274,6 +2444,8 @@ async def apply_native_migration(),retained_item_ids=frozenset(retained_item_ids),clean_native_stores=clean_native_stores,+ clean_api_keys=clean_api_keys,+ retained_keys=retained_keys,)return await _resume_takeover(host, record, verify_idle)diff --git a/core/handlers/model_hub/migration_files.py b/core/handlers/model_hub/migration_files.pyindex 175511e22..58a882379 100644--- a/core/handlers/model_hub/migration_files.py+++ b/core/handlers/model_hub/migration_files.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport jsonimport osimport re+from dataclasses import replace+from functools import partialfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -21,6 +23,7 @@ from vibe.codex_config import (_dump_toml,get_codex_config_paths,)+from vibe.native_oauth_store import codex_edit_keeping_api_keyfrom vibe.opencode_config import (get_opencode_auth_path,get_opencode_config_paths,@@ -191,18 +194,88 @@ def planned_native_references(return {name: tuple(paths) for name, paths in references.items()}+def _keep(payload: dict) -> None:+ """Guard a file whose static credentials stay native."""+++def native_store_items(+ items: list[NativeMigrationItem], *, clean_api_keys: bool,+) -> list[NativeMigrationItem]:+ """Items with the native credential-store edit (file or Keychain) to apply.++ A subscription login is always withdrawn. A Codex store keeps its static+ key unless cleanup was requested and this batch carries that key, and a+ store left unchanged becomes a compare-only guard so a change during the+ migration is still detected.+ """+ # Only a key carried from the store itself withdraws it; equal bytes+ # carried from a provider entry never authorize removing the store's key.+ withdrawn = frozenset(+ item.secret.strip() for item in items+ if clean_api_keys and _codex_store_key_item(item)+ )+ # Key cleanup consent never extends to a login the batch did not carry.+ withdraw_login = any(+ item.backend == "codex" and item.kind == "oauth_native" for item in items+ )+ return [+ replace(item, native_store_edit=codex_edit_keeping_api_key(+ item.native_store_edit, withdrawn_keys=withdrawn, withdraw_login=withdraw_login,+ ))+ if item.backend == "codex" and item.native_store_edit else item+ for item in items+ ]+++def _codex_store_key_item(item: NativeMigrationItem) -> bool:+ """Whether the item carries the static key held in the Codex credential store."""+ return (+ item.backend == "codex" and item.kind == "api_key"+ and item.native_store_revision is not None and bool(item.secret)+ )+++def _codex_store_holds_api_key(+ items: list[NativeMigrationItem], auth_path: Path, edits: dict[Path, NativeFileEdit],+) -> bool:+ """Whether the Codex credential store (auth.json or Keychain) holds a static key."""+ staged = edits.get(auth_path.absolute())+ raw = staged.before if staged else _read_regular(auth_path.absolute())+ values: list[object] = [raw.decode(errors="replace")] if raw is not None else []+ for item in items:+ if item.backend != "codex":+ continue+ for operation in (item.native_store_edit or {}).get("operations", []):+ before = operation.get("before")+ if isinstance(before, dict) and before.get("exists"):+ values.append(before.get("raw", before.get("value")))+ for value in values:+ if isinstance(value, str):+ try:+ value = json.loads(value)+ except ValueError:+ continue+ if isinstance(value, dict) and isinstance(value.get("OPENAI_API_KEY"), str) and value["OPENAI_API_KEY"].strip():+ return True+ return False++def plan_native_cleanup(items: list[NativeMigrationItem],*,home: Path | None,project_roots: tuple[Path, ...] = (),_include_shell: bool = True,+ clean_api_keys: bool = True,) -> list[NativeFileEdit]:"""One before/after image per path, even when providers share a file.Only selected backend authentication is removed. Planning refuses malformedfiles instead of using the forgiving UI probes that can return an empty- document after a parse failure.+ document after a parse failure. Without ``clean_api_keys`` static keys are+ copied, not withdrawn: a Hub launch pins its own connection above them.+ Subscription grants rotate and keep a single owner, so they are always+ withdrawn. Unchanged files are still guarded."""edits: dict[Path, NativeFileEdit] = {}selected_backends = {item.backend for item in items}@@ -216,7 +289,7 @@ def plan_native_cleanup(edits[guard.path] = guard# Native-store resolution owns credential paths (including isolated secure# roots), while this planner owns one final file image for the whole batch.- for item in items:+ for item in native_store_items(items, clean_api_keys=clean_api_keys):for operation in (item.native_store_edit or {}).get("operations", []):if operation.get("kind") != "file":continue@@ -263,6 +336,10 @@ def plan_native_cleanup(for item in items:if item.secret:selected_by_backend.setdefault(item.backend, set()).add(item.secret)+ oauth_backends = {+ item.backend for item in items+ if item.kind == "oauth_native" and not item.native_store_placeholder+ }def selected_api_key(value: object, backend: str) -> bool:# Producers normalize static keys for proof/custody. Exact raw bytes@@ -272,17 +349,21 @@ def plan_native_cleanup(if "claude" in backends:claude_keys = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")- # Consent is per field too: equal bytes carried from one Claude field- # never authorize removing another field the scan kept native.- selected_by_field: dict[str, set[str]] = {}+ # Consent is per layer and field: equal bytes carried from another+ # layer or field never authorize removing a credential the scan kept+ # native (for example one bound to an endpoint the Hub cannot reach).+ selected_by_field: dict[tuple[str, str], set[str]] = {}for item in items:- if item.backend == "claude" and item.secret:- for field in (item.native_field, *item.shell_auth_variables):- if field:- selected_by_field.setdefault(field, set()).add(item.secret)-- def claude_retained(key: str, value: object) -> bool:- selected = isinstance(value, str) and value.strip() in selected_by_field.get(key, set())+ if item.backend == "claude" and item.secret and item.native_field:+ for source in item.source_paths:+ selected_by_field.setdefault(+ (str(Path(source).absolute()), item.native_field), set(),+ ).add(item.secret)++ def claude_retained(path: Path, key: str, value: object) -> bool:+ selected = isinstance(value, str) and value.strip() in selected_by_field.get(+ (str(path.absolute()), key), set(),+ )return bool(value) and not selected# Claude merges its settings layers, so a credential kept native in any@@ -296,11 +377,11 @@ def plan_native_cleanup(layer = _object(raw)env = layer.get("env")if layer.get("apiKeyHelper") or (- isinstance(env, dict) and any(claude_retained(key, env.get(key)) for key in claude_keys)+ isinstance(env, dict) and any(claude_retained(path, key, env.get(key)) for key in claude_keys)):claude_auth_retained = True- def clear_settings(payload: dict) -> None:+ def clear_settings(path: Path, payload: dict) -> None:env = payload.get("env")if env is not None and not isinstance(env, dict):raise TakeoverStateError("native configuration cannot be parsed")@@ -308,13 +389,15 @@ def plan_native_cleanup(# URL it may depend on. Hub launches pin their own connection.if isinstance(env, dict):for key in claude_keys:- if not claude_retained(key, env.get(key)):+ if not claude_retained(path, key, env.get(key)):env.pop(key, None)if not claude_auth_retained:env.pop("ANTHROPIC_BASE_URL", None)for path in claude_settings_paths(home, project_roots):- edit_json(path, clear_settings, guard_unchanged=True)+ edit_json(+ path, partial(clear_settings, path) if clean_api_keys else _keep, guard_unchanged=True,+ )backup_path = get_claude_oauth_settings_backup_path(home).absolute()backup_edit = edits.get(backup_path)if backup_edit and backup_edit.before != backup_edit.after and backup_edit.after is not None:@@ -324,20 +407,43 @@ def plan_native_cleanup(if "codex" in backends:config_path, auth_path = get_codex_config_paths(home)+ store_keys = {item.secret.strip() for item in items if _codex_store_key_item(item)}+ # Provider credentials are carried per layer and provider entry.+ carried_provider_keys = {+ (str(Path(item.source_paths[0]).absolute()), item.native_provider_id, item.secret.strip())+ for item in items+ if item.backend == "codex" and item.kind == "api_key" and item.secret+ and item.native_provider_id and item.native_store_revision is None and item.source_paths+ }def clear_auth(payload: dict) -> None:- # Credentials outside the selection stay native (see Claude above).- if not payload.get("OPENAI_API_KEY") or selected_api_key(payload["OPENAI_API_KEY"], "codex"):+ # Credentials outside the selection stay native (see Claude above);+ # without cleanup a selected key is copied and stays native too.+ if clean_api_keys and (+ not payload.get("OPENAI_API_KEY")+ or (isinstance(payload["OPENAI_API_KEY"], str) and payload["OPENAI_API_KEY"].strip() in store_keys)+ ):payload.pop("OPENAI_API_KEY", None)if not payload.get("tokens") or any(item.backend == "codex" and item.kind == "oauth_native"and not item.native_store_placeholderfor item in items):- for key in ("tokens", "auth_mode", "last_refresh"):+ for key in ("tokens", "last_refresh"):payload.pop(key, None)-- edit_json(auth_path, clear_auth, guard_unchanged=True)+ # A kept key still authenticates native launches; only the login goes.+ if not payload.get("OPENAI_API_KEY") or payload.get("auth_mode") == "chatgpt":+ payload.pop("auth_mode", None)++ edit_json(+ auth_path, clear_auth if clean_api_keys or "codex" in oauth_backends else _keep,+ guard_unchanged=True,+ )+ # A key kept in the store (copied, or never carried) still routes+ # through the store's provider, so that routing and selector stay too.+ codex_key_kept = (not clean_api_keys or not store_keys) and _codex_store_holds_api_key(+ items, auth_path, edits,+ )managed_ids = {MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS}# An env_key is carried only when a selected row resolved it to a# selected key; an unresolved or unselected one stays native.@@ -347,16 +453,25 @@ def plan_native_cleanup(if value.strip() in selected_by_backend.get("codex", set())}- def codex_auth_retained(provider_id: str, provider: dict) -> bool:- if provider_id in managed_ids:- return False+ def provider_key_carried(config_path: Path, provider_id: str, token: object) -> bool:+ return isinstance(token, str) and (+ str(config_path.absolute()), provider_id, token.strip(),+ ) in carried_provider_keys++ def codex_auth_retained(config_path: Path, provider_id: str, provider: dict) -> bool:env_key = provider.get("env_key")- return bool(- any(provider.get(field) for field in ("http_headers", "env_http_headers"))- or (provider.get("experimental_bearer_token")- and not selected_api_key(provider["experimental_bearer_token"], "codex"))+ # A managed provider is Avibe-owned routing, but a key the batch did+ # not carry (e.g. an unimportable endpoint) still keeps it native.+ uncarried_key = bool(+ (provider.get("experimental_bearer_token")+ and not provider_key_carried(config_path, provider_id, provider["experimental_bearer_token"]))or (env_key and env_key not in carried_env_keys))+ if provider_id in managed_ids:+ return uncarried_key+ return uncarried_key or any(+ provider.get(field) for field in ("http_headers", "env_http_headers")+ )layers: list[tuple[Path, bytes | None, dict | None]] = []for config_path in codex_config_paths(home, project_roots):@@ -376,18 +491,34 @@ def plan_native_cleanup(# selectors included, or direct mode would stop using what was kept.retained_ids = {provider_id- for _, _, config in layers if config is not None+ for layer_path, _, config in layers if config is not Nonefor provider_id, provider in (config["model_providers"].items() if isinstance(config.get("model_providers"), dict) else ())- if isinstance(provider, dict) and codex_auth_retained(provider_id, provider)+ if isinstance(provider, dict) and codex_auth_retained(layer_path, provider_id, provider)}for config_path, content, config in layers:if config is None:continuebefore = json.dumps(config, sort_keys=True, default=str)- removable = set(managed_ids)- removable.update(item.native_provider_id for item in items if item.backend == "codex" and item.native_provider_id)+ # Without key cleanup a provider stays unless only the withdrawn+ # login routes through it.+ removable = set(managed_ids) if clean_api_keys else set()+ removable.update(+ item.native_provider_id for item in items+ if item.backend == "codex" and item.native_provider_id+ and (clean_api_keys or item.kind == "oauth_native")+ )+ if not clean_api_keys:+ removable -= {+ item.native_provider_id for item in items+ if item.backend == "codex" and item.kind != "oauth_native"+ }+ if codex_key_kept:+ removable -= {+ item.native_provider_id for item in items+ if item.backend == "codex" and item.kind == "oauth_native"+ }providers = config.get("model_providers")if isinstance(providers, dict):# A retained provider keeps its selectors and whatever@@ -399,7 +530,7 @@ def plan_native_cleanup(if not isinstance(provider, dict):continuetoken = provider.get("experimental_bearer_token")- if token and selected_api_key(token, "codex"):+ if token and provider_key_carried(config_path, provider_id, token):provider.pop("experimental_bearer_token")if provider.get("env_key") in carried_env_keys:provider.pop("env_key")@@ -430,7 +561,10 @@ def plan_native_cleanup(# A consented empty container is unrelated data, not replaced# authentication. Keep its selector so the recorded clean revision# remains observable (and a later native login is not hidden).- if not any(item.backend == "codex" and item.native_store_placeholder for item in items):+ # A kept key may live in the selected store, so only cleanup drops it.+ if clean_api_keys and not codex_key_kept and not any(+ item.backend == "codex" and item.native_store_placeholder for item in items+ ):config.pop(CREDENTIALS_STORE_KEY, None)if json.dumps(config, sort_keys=True, default=str) != before:edits[config_path] = NativeFileEdit(config_path.absolute(), content, _dump_toml(config).encode())@@ -440,8 +574,20 @@ def plan_native_cleanup(shell_values = dict(pair for item in items for pair in item.shell_values)absent = object()+ # A key is carried per file and vendor it was read from: equal bytes+ # read elsewhere never authorize removing this copy.+ carried_opencode = {+ (str(Path(source).absolute()), item.vendor, item.secret.strip())+ for item in items if item.backend == "opencode" and item.secret+ for source in item.source_paths+ }- def auth_entry_retained(entry: object) -> bool:+ def opencode_carried(path: Path, vendor: str, value: object) -> bool:+ return isinstance(value, str) and (+ str(path.absolute()), vendor, value.strip(),+ ) in carried_opencode++ def auth_entry_retained(vendor: str, entry: object) -> bool:# An entry the Hub could not carry (OAuth, a key outside the# selection, or a value of no shape it reads) stays native, like# every other unselected credential. Only an absent entry and the@@ -449,11 +595,13 @@ def plan_native_cleanup(return entry is not absent and not (isinstance(entry, dict)and "type" in entry and entry["type"] == "api"- and selected_api_key(entry.get("key"), "opencode")+ and opencode_carried(opencode_auth_path(home), vendor, entry.get("key")))native_auth = read_native_config(opencode_auth_path(home)) or {}- retained_auth = {vendor for vendor in vendors if auth_entry_retained(native_auth.get(vendor, absent))}+ retained_auth = {+ vendor for vendor in vendors if auth_entry_retained(vendor, native_auth.get(vendor, absent))+ }# References a selected row read: bound to its saved assignment, or# proved empty before it selected the auth.json fallback. Any other@@ -462,8 +610,8 @@ def plan_native_cleanup(name for item in items if item.backend == "opencode" for name in item.shell_variables}- def api_key_retained(value: object) -> bool:- if not value or selected_api_key(value, "opencode"):+ def api_key_retained(path: Path, vendor: str, value: object) -> bool:+ if not value or opencode_carried(path, vendor, value):return Falsereturn not (isinstance(value, str)@@ -489,10 +637,12 @@ def plan_native_cleanup(for vendor in vendors:provider = providers.get(vendor)options = provider.get("options") if isinstance(provider, dict) else None- if isinstance(options, dict) and (options.get("headers") or api_key_retained(options.get("apiKey"))):+ if isinstance(options, dict) and (+ options.get("headers") or api_key_retained(path, vendor, options.get("apiKey"))+ ):retained_auth.add(vendor)- def clear_providers(payload: dict) -> None:+ def clear_providers(path: Path, payload: dict) -> None:providers = payload.get("provider")if providers is None:return@@ -504,7 +654,7 @@ def plan_native_cleanup(continueoptions = provider.get("options")if isinstance(options, dict):- if api_key_retained(options.get("apiKey")):+ if api_key_retained(path, vendor, options.get("apiKey")):continueoptions.pop("apiKey", None)if vendor not in retained_auth:@@ -515,20 +665,26 @@ def plan_native_cleanup(provider.pop("options", None)for path in opencode_config_paths(home, project_roots):- edit_json(path, clear_providers, jsonc=True, guard_unchanged=True)+ edit_json(+ path, partial(clear_providers, path) if clean_api_keys else _keep,+ jsonc=True, guard_unchanged=True,+ )def clear_provider_auth(payload: dict) -> None:for vendor in vendors:- if vendor not in payload or auth_entry_retained(payload[vendor]):+ if vendor not in payload or auth_entry_retained(vendor, payload[vendor]):continuepayload.pop(vendor, None)- edit_json(opencode_auth_path(home), clear_provider_auth, guard_unchanged=True)+ edit_json(+ opencode_auth_path(home), clear_provider_auth if clean_api_keys else _keep,+ guard_unchanged=True,+ )if backends and _include_shell:from .migration_shell import cleanup_shell_profile, read_shell_profilesselected_values: dict[str, str] = {}- for item in items:+ for item in items if clean_api_keys else ():for name, value in item.shell_values:if name in selected_values and selected_values[name] != value:raise TakeoverStateError("conflicting native credential snapshots")diff --git a/core/handlers/model_hub/migration_journal.py b/core/handlers/model_hub/migration_journal.pyindex ff41efb0d..7b271d7a1 100644--- a/core/handlers/model_hub/migration_journal.py+++ b/core/handlers/model_hub/migration_journal.py@@ -256,6 +256,16 @@ class NativeTakeoverJournal:or any(not isinstance(value, str) or not value for value in payload["inventory_ids"])))+ or not isinstance(payload.get("retained_native_ids", {}), dict)+ or any(+ not isinstance(key, str) or not key or not isinstance(value, dict)+ or not isinstance(value.get("source_id"), str) or not value["source_id"]+ or not isinstance(value.get("credential_ref"), str) or not value["credential_ref"]+ for key, value in payload.get("retained_native_ids", {}).items()+ )+ or not isinstance(payload.get("withdrawn_native_ids", []), list)+ or any(not isinstance(value, str) for value in payload.get("withdrawn_native_ids", []))+ or not isinstance(payload.get("clean_api_keys", True), bool)or not isinstance(payload.get("clean_native_stores", {}), dict)or any(backend not in {"claude", "codex"}@@ -375,12 +385,26 @@ class NativeTakeoverJournal:receipt = NativeTakeoverJournal(self.path.with_name("last-completed.json"))previous = receipt.load()custody_backends = self.oauth_custody_backends(previous) | self.oauth_custody_backends(record)+ # A batch replaces only the store proofs it touched; a copy-only batch+ # leaves another batch's verified-clean store revision in place.+ touched_stores = {store.get("backend") for store in record.get("keychain", [])}clean_stores = {backend: revisionfor backend, revision in (previous or {}).get("clean_native_stores", {}).items()- if backend not in record["backends"]+ if backend not in touched_stores}clean_stores.update(record.get("clean_native_stores", {}))+ # Static keys copied without cleanup stay native across later batches;+ # each one remains hidden from pending inventory while its Source lives.+ withdrawn = set(record.get("withdrawn_native_ids", ()))+ retained = {+ **{+ identity: copy+ for identity, copy in (previous or {}).get("retained_native_ids", {}).items()+ if identity not in withdrawn and copy.get("key_fingerprint") not in withdrawn+ },+ **record.get("retained_native_ids", {}),+ }receipt.save({"version": 1,"phase": "complete",@@ -399,6 +423,8 @@ class NativeTakeoverJournal:if source["id"] in record["source_ids"]},"clean_native_stores": clean_stores,+ "retained_native_ids": retained,+ **({"clean_api_keys": record["clean_api_keys"]} if "clean_api_keys" in record else {}),"oauth_custody_backends": sorted(custody_backends),})self.forget()diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 5da138a52..853f54536 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -230,7 +230,9 @@ async def dispatch_model_hub_rpc(if operation == "migration_scan":return service.migration_scan()if operation == "migration_apply":- return await service.migration_apply(payload.get("item_ids"))+ return await service.migration_apply(+ payload.get("item_ids"), payload.get("clean_api_keys", False),+ )if operation == "runtime_status":return await service.runtime_status()if operation == "runtime_install":diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 051079f0b..563598044 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -920,7 +920,7 @@ class ModelHubService:self.migration_reconcile_auth = migration_reconcile_authself._migration_lock = asyncio.Lock()self._migration_task: asyncio.Task | None = None- self._migration_item_ids: tuple[str, ...] | None = None+ self._migration_item_ids: tuple[tuple[str, ...], bool] | None = Noneself.requested_model_override = requested_model_overrideself.selected_agent_override = selected_agent_overrideself.named_agents_override = named_agents_override@@ -4666,6 +4666,9 @@ class ModelHubService:clean_native_stores=(self.migration_journal.completed() or {}).get("clean_native_stores"),+ retained_native_ids=(+ self.migration_journal.completed() or {}+ ).get("retained_native_ids"),)# Retained auth stays native beside the Hub, but a# config the CLI cannot parse fails every launch.@@ -6688,6 +6691,7 @@ class ModelHubService:validate_base_url=_validated_base_url,project_roots=self.migration_project_roots(),clean_native_stores=(self.migration_journal.completed() or {}).get("clean_native_stores"),+ retained_native_ids=(self.migration_journal.completed() or {}).get("retained_native_ids"),legacy_auth=(self.store.native_auth_snapshot(MODEL_HUB_BACKENDS)if isinstance(self.store, V2ModelHubConfigStore) else None@@ -6696,13 +6700,15 @@ class ModelHubService:]}- async def migration_apply(self, item_ids: object) -> dict:+ async def migration_apply(self, item_ids: object, clean_api_keys: object = False) -> dict:from core.backend_restart import NativeMigrationBlockedErrorfrom vibe.native_oauth_store import NativeOAuthError, NativeOAuthPermissionErrortry:+ if not isinstance(clean_api_keys, bool):+ raise MigrationConflictErrorselection = (- tuple(sorted(item_ids))+ (tuple(sorted(item_ids)), clean_api_keys)if isinstance(item_ids, list) and all(isinstance(value, str) for value in item_ids)else None)@@ -6714,6 +6720,7 @@ class ModelHubService:task = asyncio.create_task(apply_native_migration(self, item_ids, mask_credential=_mask_credential,validate_base_url=_validated_base_url,+ clean_api_keys=clean_api_keys,), name="model-hub-native-takeover")self._migration_task = taskself._migration_item_ids = selectiondiff --git a/docs/plans/model-hub-contracts/migration-scan.schema.json b/docs/plans/model-hub-contracts/migration-scan.schema.jsonindex 500afa8e9..112a0f584 100644--- a/docs/plans/model-hub-contracts/migration-scan.schema.json+++ b/docs/plans/model-hub-contracts/migration-scan.schema.json@@ -42,6 +42,10 @@"config_blocker": {"type": "boolean","description": "The backend's native config cannot be parsed, so Hub mode would fail every launch. Blocks the row's whole consent group; apply refuses it."+ },+ "may_hold_api_key": {+ "type": "boolean",+ "description": "Whether applying this row may copy a native API key, including an opaque Codex credential store that resolves only after consent. Clients offer the optional API key cleanup only when a selected row sets it."}}}diff --git a/docs/plans/model-hub-native-takeover.md b/docs/plans/model-hub-native-takeover.mdindex e423e54b9..b2c11e00f 100644--- a/docs/plans/model-hub-native-takeover.md+++ b/docs/plans/model-hub-native-takeover.md@@ -10,7 +10,9 @@ remaining live-account verification boundaries are described below.Runtime enablement is not consent to transfer or delete native credentials.- Switching a backend from Direct to Hub first offers the existing migrationdialog when native credentials are present. The dialog selects accounts and- has one consequence sentence plus **Not now** / **Start migration**.+ has one consequence sentence plus **Not now** / **Start migration**. When the+ selection includes an API key it also offers one unchecked-by-default opt-in,+ **Also remove the API keys from the native CLI configuration**.Dismissing it leaves the backend and native authentication unchanged.- The same dialog is available to existing Hub users through **One-clickmigration**. Existing native subscription sources are eligible for custody@@ -24,7 +26,9 @@ remaining live-account verification boundaries are described below.Success means takeover and cleanup completed, not just import accepted.- Chinese product name: `模型网关`; English: `Model Hub`. The approved Chineseconsequence sentence is exactly:- `迁移后,CLI的认证信息将完全交由模型网关管理`+ `迁移后,助手统一通过模型网关认证:订阅登录转交模型网关托管,API Key 复制导入,原配置默认保留。`+ It replaces the earlier `迁移后,CLI的认证信息将完全交由模型网关管理`, which+ promised a withdrawal API keys no longer undergo by default.## Public boundary@@ -33,7 +37,7 @@ The existing endpoints and response envelopes remain compatible:| Endpoint | Request | Successful response data || --- | --- | --- || `POST /api/models/migration/scan` | none | `scan: { items: MigrationItem[] }` |-| `POST /api/models/migration/apply` | `{ item_ids: string[] }` | `{ applied: number, sources: Source[], added_to: Placement[] }` |+| `POST /api/models/migration/apply` | `{ item_ids: string[], clean_api_keys?: boolean }` | `{ applied: number, sources: Source[], added_to: Placement[] }` |Scan is read-only. It never transfers custody, prompts for browser login,refreshes tokens, deletes native material, or returns secrets. Item IDs bind@@ -70,7 +74,22 @@ and then present that two-request sequence as atomic.5. Upload HTTP 200 and protocol inventory are not upstream OAuth validation.No completion claim may be based only on them. No new browser login isrequired for a compatible, valid, refresh-capable native grant.-6. Remove only replaced authentication and direct-routing settings. Preserve+6. Subscription OAuth always changes owner: its native grant is withdrawn,+ because a rotating refresh token cannot have two holders. An API key is a+ static credential Hub launches already shadow, so by default it is copied and+ its native configuration (shell startup files, each backend's config and+ provider routing, the Avibe-saved `agents.<backend>` key, and a Codex+ `OPENAI_API_KEY` even when it shares a store with a withdrawn ChatGPT login)+ stays in place; only `clean_api_keys: true` removes it. A kept key-only+ store is still guarded compare-only. The completion receipt maps each kept+ key to the Hub Source and credential it was copied into, so a later scan+ does not offer the same unchanged key again while Hub holds that copy; a+ changed key, or one whose Source was deleted or re-keyed, is offered and+ migrates afresh. The receipt records the cleanup choice, and a retry that+ changes it is a conflict rather than a replay. A scan admits a key another+ native config still references; only its cleanup is refused before any+ write. When cleanup runs, remove only replaced+ authentication and direct-routing settings. Preservesessions, skills, MCP, unrelated providers, and unrelated configurationfields. Recheck all supported precedence layers so an overriding project,environment, or legacy setting cannot silently keep direct authentication.diff --git a/docs/plans/setup-three-screen/contracts.md b/docs/plans/setup-three-screen/contracts.mdindex 7108f1539..c1c6d2d0f 100644--- a/docs/plans/setup-three-screen/contracts.md+++ b/docs/plans/setup-three-screen/contracts.md@@ -424,8 +424,10 @@ after exposure. Setup must not duplicate cleanup, custody writes, mode transitioor retry machinery, and must not send a second mode PATCH after successful apply.Cards, the primary action and Detected actions delegate to this feature's complete-group review. Keep-every required backend/file visible and show the exact consequence-`迁移后,CLI的认证信息将完全交由模型网关管理`, with **Not now / Start migration**. Only the latter+every required backend/file visible and show the exact consequence from `copy-contract.json`+(`onboarding.import.description`: subscription sign-ins move, API keys are copied and their native+configuration is kept unless the dialog's unchecked cleanup opt-in is chosen), with+**Not now / Start migration**. Only the latterexplicit confirmation invokes apply. New/incomplete takeover invokes server dependency ensurebefore credential withdrawal and again before sync/start; it retains installation admissioneven when a healthy engine exists (operation table below). Selection, setup entry, gateway installation/start anddiff --git a/docs/plans/setup-three-screen/copy-contract.json b/docs/plans/setup-three-screen/copy-contract.jsonindex 842fbd902..dbfb8b031 100644--- a/docs/plans/setup-three-screen/copy-contract.json+++ b/docs/plans/setup-three-screen/copy-contract.json@@ -202,9 +202,9 @@},"import": {"title": "迁移到模型网关",- "description": "迁移后,CLI的认证信息将完全交由模型网关管理",+ "description": "迁移后,这些助手改用模型网关连接模型。原配置文件里的 Key 默认保留,这些助手不再使用它们,其他设置不变。","review": "查看并迁移",- "helpBody": "模型网关统一管理认证和模型连接。迁移会清理已替代的原生认证,并将关联助手切换到模型网关;其他无关设置会保留。",+ "helpBody": "模型网关统一管理认证和模型连接。迁移会转交订阅登录并复制 API Key,将关联助手切换到模型网关;原生 API Key 配置默认保留。","action_one": "查看选中的 {{count}} 项","action_other": "查看选中的 {{count}} 项","scopeNote": "此入口仅处理完整的 API Key 组。涉及订阅登录或阻塞项的关联组不可在此接管,请前往设置检查。",@@ -214,7 +214,7 @@"progressDetail": "正在迁移认证并更新关联助手的连接","done_one": "已迁移 {{count}} 项配置","done_other": "已迁移 {{count}} 项配置",- "doneDetail": "迁移和原生认证清理已完成。请确认助手的模型路由。",+ "doneDetail": "迁移已完成。请确认助手的模型路由。","remaining_one": "还有 {{count}} 项需要查看,可随时继续","remaining_other": "还有 {{count}} 项需要查看,可随时继续","remainingAction": "继续选择",@@ -326,9 +326,9 @@},"import": {"title": "Migrate to Model Hub",- "description": "After migration, CLI authentication will be managed entirely by Model Hub.",+ "description": "After migration, these assistants connect through Model Hub. The keys in their original config files stay in place and are no longer used by these assistants; other settings stay as they are.","review": "Review migration",- "helpBody": "Model Hub manages authentication and model connections. Migration removes replaced native authentication and switches linked assistants to Model Hub; unrelated settings are preserved.",+ "helpBody": "Model Hub manages authentication and model connections. Migration moves subscription sign-ins, copies API keys, and switches linked assistants to Model Hub; native API key configuration stays in place by default.","action_one": "Review {{count}} selected","action_other": "Review {{count}} selected","scopeNote": "This entry handles complete API-key groups only. Linked groups with subscription sign-ins or blockers cannot be taken over here; review them in Settings.",@@ -338,7 +338,7 @@"progressDetail": "Migrating authentication and updating linked assistant connections","done_one": "Migrated {{count}} configuration item","done_other": "Migrated {{count}} configuration items",- "doneDetail": "Migration and native authentication cleanup are complete. Check the assistants’ model routes.",+ "doneDetail": "Migration is complete. Check the assistants’ model routes.","remaining_one": "{{count}} item needs review. Continue any time.","remaining_other": "{{count}} items need review. Continue any time.","remainingAction": "Review remaining",diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex e2b6cc6be..07d14a045 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -780,6 +780,12 @@ scenarios:kind: migrationlayer: unittest: "ui/src/components/onboarding/providers/providerStage.test.ts::MH-MIG-006: keeps a key whose display mask collides with a Hub source"+ - id: MH-MIG-007+ name: Default migration copies API keys, withdraws only subscription logins, and does not rediscover kept keys+ status: covered+ kind: migration+ layer: scenario+ test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_007_default_apply_copies_api_keys_and_withdraws_only_subscriptions- id: MH-TAKEOVER-001name: Recoverable failures walk the configured route and exhaust only at its endstatus: covereddiff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.pyindex c05145912..8e85167b5 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@@ -829,7 +829,7 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_service.migration_guard = lambda backends: nullcontext(verify_fixture_idle)scan = service.migration_scan()["items"]- result = asyncio.run(service.migration_apply([item["id"] for item in scan]))+ result = asyncio.run(service.migration_apply([item["id"] for item in scan], clean_api_keys=True))serialized = json.loads(json.dumps(store.load().to_payload()))reloaded = ModelHubConfig.from_payload(serialized)diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.pyindex fb9effca1..80667ee36 100644--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py@@ -4,6 +4,7 @@ import asyncioimport hashlibimport jsonfrom contextlib import nullcontext+from dataclasses import replacefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Mapping@@ -679,7 +680,7 @@ def test_mh_mig_001_api_apply_takes_over_credentials_and_cleans_native_auth(apply_response = client.post("/api/models/migration/apply",- json={"item_ids": [item["id"] for item in scan["items"]]},+ json={"item_ids": [item["id"] for item in scan["items"]], "clean_api_keys": True},headers=headers,base_url=base_url,)@@ -769,6 +770,242 @@ def test_mh_mig_001_api_apply_takes_over_credentials_and_cleans_native_auth(assert secret not in serialized+def test_mh_mig_007_default_apply_copies_api_keys_and_withdraws_only_subscriptions(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """Scenario: MH-MIG-007."""++ native_home = tmp_path / "native-home"+ _write_claude(native_home)+ _write_codex(native_home)+ _write_opencode(native_home)+ _isolate_native_home(monkeypatch, native_home)+ kept = {+ path: path.read_bytes() for path in (+ native_home / ".claude" / "settings.json",+ native_home / ".config" / "opencode" / "opencode.json",+ native_home / ".local" / "share" / "opencode" / "auth.json",+ )+ }++ service, store, adapter = _service(tmp_path)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ headers = csrf_headers(client, base_url)+ items = client.post(+ "/api/models/migration/scan", headers=headers, base_url=base_url,+ ).get_json()["scan"]["items"]+ assert {item["kind"] for item in items} == {"api_key", "oauth_native", "opencode_provider"}++ rejected = client.post(+ "/api/models/migration/apply",+ json={"item_ids": [item["id"] for item in items], "clean_api_keys": "yes"},+ headers=headers, base_url=base_url,+ )+ assert rejected.status_code == 409+ assert not adapter.provisioned and not adapter.oauth_provisioned++ response = client.post(+ "/api/models/migration/apply",+ json={"item_ids": [item["id"] for item in items]},+ headers=headers, base_url=base_url,+ )+ assert response.status_code == 200+ assert response.get_json()["applied"] == len(items)+ assert len(adapter.oauth_provisioned) == 2+ assert all(store.config.agents[backend].mode == "hub" for backend in ("claude", "codex", "opencode"))++ # Static keys were copied; every native file holding only them is intact.+ assert {path: path.read_bytes() for path in kept} == kept+ # Subscription logins rotate refresh tokens: exactly one owner remains.+ assert not (native_home / ".claude" / ".credentials.json").exists()+ # A static key stored beside the ChatGPT login stays, with its routing.+ assert json.loads((native_home / ".codex" / "auth.json").read_text(encoding="utf-8")) == {+ "OPENAI_API_KEY": "sk-openai-test-123456",+ }+ assert 'model_provider = "Relay"' in (native_home / ".codex" / "config.toml").read_text(encoding="utf-8")++ # Retained keys are shadowed by Hub launches, not pending imports: neither+ # the migrate entry nor the Direct-to-Hub gate reappears for them.+ assert service.migration_scan()["items"] == []+ receipt = service.migration_journal.completed()+ assert receipt["retained_native_ids"]+ assert all(value.startswith("key_") for value in receipt["retained_native_ids"])+ assert {copy["source_id"] for copy in receipt["retained_native_ids"].values()} <= {+ source["id"] for source in service.list_sources()+ }++ # A different key saved later is new native authentication again.+ settings = native_home / ".claude" / "settings.json"+ settings.write_text(settings.read_text(encoding="utf-8").replace("sk-ant-test-123456789", "sk-ant-new-987654321"))+ [changed] = service.migration_scan()["items"]+ assert changed["backend"] == "claude" and changed["kind"] == "api_key"+ assert asyncio.run(service.migration_apply([changed["id"]], clean_api_keys=True))["applied"] == 1+ assert json.loads(settings.read_text(encoding="utf-8"))["env"] == {}+ assert service.migration_scan()["items"] == []+ # Earlier retained rows survive a later batch's receipt.+ assert set(receipt["retained_native_ids"]) <= set(+ service.migration_journal.completed()["retained_native_ids"]+ )+++def test_mh_mig_007_codex_key_only_store_and_routing_stay_native(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: a Codex API-key store is not a subscription login."""+ native_home = tmp_path / "native-home"+ _write(native_home / ".codex" / "auth.json", json.dumps({"OPENAI_API_KEY": "sk-openai-test-123456"}))+ _write(+ native_home / ".codex" / "config.toml",+ 'model_provider = "Relay"\n\n[model_providers.Relay]\n'+ 'base_url = "https://codex-relay.example/v1"\nwire_api = "responses"\n',+ )+ _isolate_native_home(monkeypatch, native_home)+ before = _tree_digest(native_home)+ service, store, adapter = _service(tmp_path)+ [item] = service.migration_scan()["items"]+ assert item["kind"] == "api_key" and item["proposed_action"] == "import"+ assert asyncio.run(service.migration_apply([item["id"]]))["applied"] == 1+ assert len(adapter.provisioned) == 1 and store.config.agents["codex"].mode == "hub"+ assert _tree_digest(native_home) == before+ assert service.migration_scan()["items"] == []+++def test_mh_mig_007_managed_codex_provider_key_stays_native(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: a key in a managed-named Codex provider is not cleaned by default."""+ native_home = tmp_path / "native-home"+ _write(+ native_home / ".codex" / "config.toml",+ 'model_provider = "openai-managed"\n\n[model_providers.openai-managed]\n'+ 'base_url = "https://codex-relay.example/v1"\nwire_api = "responses"\n'+ 'experimental_bearer_token = "sk-openai-managed-123456"\n',+ )+ _isolate_native_home(monkeypatch, native_home)+ before = _tree_digest(native_home)+ service, _store, adapter = _service(tmp_path)+ [item] = service.migration_scan()["items"]+ assert item["kind"] == "api_key" and item["may_hold_api_key"]+ assert asyncio.run(service.migration_apply([item["id"]]))["applied"] == 1+ assert len(adapter.provisioned) == 1+ assert _tree_digest(native_home) == before+++def test_mh_mig_007_retained_key_returns_after_its_hub_source_is_deleted(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: a kept key is hidden only while its copied Hub source exists."""+ native_home = tmp_path / "native-home"+ _write(native_home / ".zshrc", "export ANTHROPIC_API_KEY=sk-ant-shell-123456\n")+ _isolate_native_home(monkeypatch, native_home)+ service, store, adapter = _service(tmp_path)+ [item] = service.migration_scan()["items"]+ assert asyncio.run(service.migration_apply([item["id"]]))["applied"] == 1+ assert service.migration_scan()["items"] == []+ # A retry with a different cleanup choice is not a replay of this batch.+ with pytest.raises(ModelHubError):+ asyncio.run(service.migration_apply([item["id"]], clean_api_keys=True))+ [copy] = service.migration_journal.completed()["retained_native_ids"].values()+ payload = store.config.to_payload()+ payload["sources"] = [source for source in payload["sources"] if source["id"] != copy["source_id"]]+ for agent in payload["agents"].values():+ agent["sources"]["order"] = [value for value in agent["sources"]["order"] if value != copy["source_id"]]+ agent["routes"] = {}+ store.config = ModelHubConfig.from_payload(payload)+ [again] = service.migration_scan()["items"]+ assert again["backend"] == "claude" and again["proposed_action"] == "import"+ # The re-offered row migrates afresh instead of replaying the stale receipt.+ assert asyncio.run(service.migration_apply([again["id"]]))["applied"] == 1+ assert len(adapter.provisioned) == 2+ assert service.migration_scan()["items"] == []+++def test_mh_mig_007_retained_key_returns_after_its_hub_key_is_replaced(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: replacing the copied Hub credential re-offers the native key."""+ native_home = tmp_path / "native-home"+ _write(native_home / ".zshrc", "export ANTHROPIC_API_KEY=sk-ant-shell-123456\n")+ _isolate_native_home(monkeypatch, native_home)+ service, store, _adapter = _service(tmp_path)+ [item] = service.migration_scan()["items"]+ assert asyncio.run(service.migration_apply([item["id"]]))["applied"] == 1+ [copy] = service.migration_journal.completed()["retained_native_ids"].values()+ store.config.sources = [+ replace(source, credential_ref="ref_replaced") if source.id == copy["source_id"] else source+ for source in store.config.sources+ ]+ [again] = service.migration_scan()["items"]+ assert again["backend"] == "claude" and again["proposed_action"] == "import"+++def test_mh_mig_007_later_cleanup_also_withdraws_a_kept_key(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: a cleanup batch withdraws a kept key it cannot show for selection."""+ native_home = tmp_path / "native-home"+ profile = native_home / ".zshrc"+ _write(profile, "export ANTHROPIC_API_KEY=sk-ant-shell-123456\n")+ _isolate_native_home(monkeypatch, native_home)+ service, _store, adapter = _service(tmp_path)+ [kept] = service.migration_scan()["items"]+ assert asyncio.run(service.migration_apply([kept["id"]]))["applied"] == 1+ settings = native_home / ".claude" / "settings.json"+ _write(settings, json.dumps({"env": {"ANTHROPIC_API_KEY": "sk-ant-new-987654321"}}))+ [added] = service.migration_scan()["items"]+ assert added["id"] != kept["id"]+ assert asyncio.run(service.migration_apply([added["id"]], clean_api_keys=True))["applied"] == 1+ # The kept key's Hub copy already exists; it is withdrawn, not re-provisioned.+ assert len(adapter.provisioned) == 2+ assert json.loads(settings.read_text(encoding="utf-8"))["env"] == {}+ assert "ANTHROPIC_API_KEY" not in profile.read_text(encoding="utf-8")+ assert service.migration_scan()["items"] == []+ assert service.migration_journal.completed()["retained_native_ids"] == {}+ # A native restore of the withdrawn key is reported, not hidden by its old receipt.+ _write(profile, "export ANTHROPIC_API_KEY=sk-ant-shell-123456\n")+ assert [row["backend"] for row in service.migration_scan()["items"]] == ["claude"]+++def test_mh_mig_007_retained_key_identity_includes_provider() -> None:+ """MH-MIG-007: providers sharing one key and URL keep separate receipts."""+ from core.handlers.model_hub.migration import NativeMigrationItem, _retained_key_identity++ def item(provider: str) -> NativeMigrationItem:+ return NativeMigrationItem(+ id=provider, source_id=provider, backend="opencode", kind="opencode_provider",+ masked_detail="", proposed_action="import", selected=True, notes_key=None,+ vendor="openai", protocol="openai_chat", display_name=provider,+ base_url="https://relay.example/v1", secret="sk-shared-123456", native_provider_id=provider,+ )++ assert _retained_key_identity(item("relay-a")) != _retained_key_identity(item("relay-b"))++[email protected]("clean_api_keys", (False, True))+def test_mh_mig_007_shell_startup_key_is_removed_only_on_request(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, clean_api_keys: bool,+) -> None:+ """MH-MIG-007: a shell startup key is copied unless its cleanup was requested."""+ native_home = tmp_path / "native-home"+ profile = native_home / ".zshrc"+ _write(profile, "alias ll='ls -l'\nexport ANTHROPIC_API_KEY=sk-ant-shell-123456\n")+ _isolate_native_home(monkeypatch, native_home)+ service, store, adapter = _service(tmp_path)+ [item] = service.migration_scan()["items"]+ assert item["backend"] == "claude" and item["proposed_action"] == "import"+ assert asyncio.run(service.migration_apply([item["id"]], clean_api_keys=clean_api_keys))["applied"] == 1+ assert len(adapter.provisioned) == 1 and store.config.agents["claude"].mode == "hub"+ assert profile.read_text(encoding="utf-8") == (+ "alias ll='ls -l'\n" if clean_api_keys+ else "alias ll='ls -l'\nexport ANTHROPIC_API_KEY=sk-ant-shell-123456\n"+ )+ assert service.migration_scan()["items"] == []+ assert bool(service.migration_journal.completed()["retained_native_ids"]) is not clean_api_keys++@pytest.mark.parametrize("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,@@ -801,7 +1038,7 @@ def test_mh_mig_001_long_manual_inventory_survives_takeover_even_when_discovery_adapter.observe_source = observe[item] = service.migration_scan()["items"]- result = asyncio.run(service.migration_apply([item["id"]]))+ result = asyncio.run(service.migration_apply([item["id"]], clean_api_keys=True))assert result["applied"] == 1[source] = _assert_canonical_round_trip(store.config).sourcesmanual = [model for model in source.models if model.provenance == "manual"]@@ -839,7 +1076,7 @@ def test_mh_mig_002_oauth_grants_move_into_engine_custody(assert {item["backend"] for item in oauth_items} == {"claude", "codex"}assert {item["proposed_action"] for item in oauth_items} == {"import"}- result = asyncio.run(service.migration_apply([item["id"] for item in oauth_items]))+ result = asyncio.run(service.migration_apply([item["id"] for item in oauth_items], clean_api_keys=True))assert result["applied"] == 2assert {position["source_id"] for position in result["added_to"]} == {source.id for source in store.config.sources@@ -956,7 +1193,7 @@ def test_claude_auth_token_preserves_supported_static_header_semantics(assert token not in json.dumps(item)if allowed:assert item["proposed_action"] == "import"- result = asyncio.run(service.migration_apply([item["id"]]))+ result = asyncio.run(service.migration_apply([item["id"]], clean_api_keys=True))assert result["applied"] == 1[source] = store.config.sourcesassert adapter.auth_schemes[source.credential_ref] == "bearer"@@ -968,7 +1205,7 @@ def test_claude_auth_token_preserves_supported_static_header_semantics(assert item["notes_key"] == "settings.models.migration.blocked.token"with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply([item["id"]]))+ asyncio.run(service.migration_apply([item["id"]], clean_api_keys=True))assert error.value.code == "migration_item_conflict"assert adapter.provisioned == []assert store.config.sources == []@@ -1015,7 +1252,7 @@ def test_codex_wire_protocol_change_invalidates_scanned_item()with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply([item_id]))+ asyncio.run(service.migration_apply([item_id], clean_api_keys=True))assert error.value.code == "migration_item_conflict"assert adapter.provisioned == []assert store.config.sources == []@@ -1152,7 +1389,7 @@ def test_scan_keeps_invalid_endpoint_visible_while_valid_backend_items_remain_usassert claude_blockers[0]["proposed_action"] == "reauth"assert claude_blockers[0]["selected"] is Falseopencode_items = [item for item in scan if item["backend"] == "opencode"]- result = asyncio.run(service.migration_apply([item["id"] for item in opencode_items]))+ result = asyncio.run(service.migration_apply([item["id"] for item in opencode_items], clean_api_keys=True))assert result["applied"] == 2assert {source.vendor for source in store.config.sources} == {"openrouter",@@ -1210,7 +1447,7 @@ def test_failed_batch_revokes_every_provisioned_credential(adapter.unproven_observation_vendor = "zhipuai"with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply(item_ids))+ asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))assert error.value.code == "migration_item_conflict"assert adapter.revoked == ["cred_migration_1"]assert adapter.transient_revoked == adapter.transient_refs@@ -1241,7 +1478,7 @@ def test_canonical_source_rejection_aborts_batch_and_revokes_credentials()with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply(item_ids))+ asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))assert error.value.code == "migration_item_conflict"assert adapter.revoked == ["cred_migration_2", "cred_migration_1"]@@ -1261,7 +1498,7 @@ def test_failed_persist_sync_restores_config_and_revokes_credentials(adapter.fail_sync_count = 1with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply(item_ids))+ asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))assert error.value.code == "migration_recovery_pending"assert store.config.sourcesassert service.migration_journal.load()["phase"] == "exposed"@@ -1278,7 +1515,7 @@ def test_migration_requires_grouped_backend_selection_before_provisioning(item_ids = [item["id"] for item in service.migration_scan()["items"]]with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply([item_ids[0]]))+ asyncio.run(service.migration_apply([item_ids[0]], clean_api_keys=True))assert error.value.code == "migration_item_conflict"assert adapter.provisioned == []assert adapter.revoked == []@@ -1304,7 +1541,7 @@ def test_apply_rejects_a_credential_changed_after_scan()with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply([stale_id]))+ asyncio.run(service.migration_apply([stale_id], clean_api_keys=True))assert error.value.code == "migration_item_conflict"assert adapter.provisioned == []assert store.config.sources == []@@ -1535,3 +1772,119 @@ def test_presentation_metadata_leaves_every_pre_existing_value_and_id_alone(assert row["proposed_action"] == item.proposed_actionassert row["selected"] == item.selectedassert row["notes_key"] == item.notes_key+++def test_mh_mig_007_default_oauth_withdrawal_keeps_routing_of_an_excluded_key(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: an unimportable kept key keeps the provider routing it needs."""+ native_home = tmp_path / "native-home"+ _write(+ native_home / ".codex" / "auth.json",+ json.dumps({+ "OPENAI_API_KEY": "sk-openai-test-123456",+ "tokens": {+ "access_token": "codex-access-123456",+ "refresh_token": "codex-refresh-123456",+ "account_id": "acct_codex_test",+ },+ }),+ )+ config_path = native_home / ".codex" / "config.toml"+ config = (+ 'cli_auth_credentials_store = "file"\nmodel_provider = "Relay"\n\n[model_providers.Relay]\n'+ 'base_url = "ftp://relay.example/v1"\nwire_api = "responses"\n'+ )+ _write(config_path, config)+ _isolate_native_home(monkeypatch, native_home)+ service, _store, _adapter = _service(tmp_path)+ scan = service.migration_scan()["items"]+ oauth = [item for item in scan if item["kind"] == "oauth_native"]+ assert [item["proposed_action"] for item in scan if item["kind"] == "api_key"] == ["reauth"]+ assert asyncio.run(service.migration_apply([oauth[0]["id"]]))["applied"] == 1+ assert config_path.read_text(encoding="utf-8") == config+ auth = json.loads((native_home / ".codex" / "auth.json").read_text(encoding="utf-8"))+ assert auth["OPENAI_API_KEY"] == "sk-openai-test-123456" and "tokens" not in auth+++def test_mh_mig_007_managed_provider_keeps_an_excluded_key_beside_the_login(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: withdrawing a login keeps a managed provider's unimported key."""+ native_home = tmp_path / "native-home"+ _write(+ native_home / ".codex" / "auth.json",+ json.dumps({"tokens": {+ "access_token": "codex-access-123456",+ "refresh_token": "codex-refresh-123456",+ "account_id": "acct_codex_test",+ }}),+ )+ config_path = native_home / ".codex" / "config.toml"+ config = (+ 'cli_auth_credentials_store = "file"\nmodel_provider = "openai-managed"\n\n'+ '[model_providers.openai-managed]\nbase_url = "ftp://relay.example/v1"\n'+ 'wire_api = "responses"\nexperimental_bearer_token = "sk-openai-managed-123456"\n'+ )+ _write(config_path, config)+ _isolate_native_home(monkeypatch, native_home)+ service, _store, _adapter = _service(tmp_path)+ scan = service.migration_scan()["items"]+ assert "reauth" in [item["proposed_action"] for item in scan if item["kind"] == "api_key"]+ oauth = [item["id"] for item in scan if item["kind"] == "oauth_native"]+ assert asyncio.run(service.migration_apply(oauth))["applied"] == 1+ assert config_path.read_text(encoding="utf-8") == config+++def test_mh_mig_007_cleanup_keeps_an_excluded_key_in_the_withdrawn_store(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: cleanup removes only keys the batch carried from a withdrawn store."""+ native_home = tmp_path / "native-home"+ auth_path = native_home / ".codex" / "auth.json"+ _write(+ auth_path,+ json.dumps({+ "OPENAI_API_KEY": "sk-openai-test-123456",+ "tokens": {+ "access_token": "codex-access-123456",+ "refresh_token": "codex-refresh-123456",+ "account_id": "acct_codex_test",+ },+ }),+ )+ _write(+ native_home / ".codex" / "config.toml",+ 'cli_auth_credentials_store = "file"\nmodel_provider = "Relay"\n\n[model_providers.Relay]\n'+ 'base_url = "ftp://relay.example/v1"\nwire_api = "responses"\n'+ '\n[model_providers.Other]\nbase_url = "https://other.example/v1"\nwire_api = "responses"\n'+ 'experimental_bearer_token = "sk-openai-other-654321"\n',+ )+ _isolate_native_home(monkeypatch, native_home)+ service, _store, _adapter = _service(tmp_path)+ scan = service.migration_scan()["items"]+ ids = [item["id"] for item in scan if item["proposed_action"] == "import"]+ assert any(item["proposed_action"] == "reauth" for item in scan)+ assert any(item["kind"] == "oauth_native" and item["id"] in ids for item in scan)+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == len(ids)+ auth = json.loads(auth_path.read_text(encoding="utf-8"))+ assert auth["OPENAI_API_KEY"] == "sk-openai-test-123456" and "tokens" not in auth+++def test_mh_mig_007_default_copy_leaves_a_key_only_codex_store_byte_identical(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,+) -> None:+ """MH-MIG-007: with no login selected, a key-only Codex store is not rewritten."""+ native_home = tmp_path / "native-home"+ auth_path = native_home / ".codex" / "auth.json"+ _write(auth_path, json.dumps({+ "OPENAI_API_KEY": "sk-openai-test-123456", "auth_mode": "chatgpt",+ "tokens": {}, "last_refresh": "2026-01-01T00:00:00Z",+ }))+ _isolate_native_home(monkeypatch, native_home)+ before = auth_path.read_bytes()+ service, _store, _adapter = _service(tmp_path)+ ids = [item["id"] for item in service.migration_scan()["items"] if item["proposed_action"] == "import"]+ assert ids+ assert asyncio.run(service.migration_apply(ids))["applied"] == len(ids)+ assert auth_path.read_bytes() == beforediff --git a/tests/test_model_hub_migration_auth_mirror.py b/tests/test_model_hub_migration_auth_mirror.pyindex 14974093d..cf638cc0f 100644--- a/tests/test_model_hub_migration_auth_mirror.py+++ b/tests/test_model_hub_migration_auth_mirror.py@@ -400,7 +400,7 @@ class TestTakeoverMirrorConsumers:save(record)monkeypatch.setattr(service.migration_journal, "save", save_checked)ids = [item["id"] for item in service.migration_scan()["items"] if item["backend"] == "claude"]- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert service.migration_journal.load() is Noneassert not runtime.admissions and not runtime.turns_assert_mirrored(runtime, service.store.native_auth_snapshot(("claude",)))diff --git a/tests/test_model_hub_migration_auth_recovery.py b/tests/test_model_hub_migration_auth_recovery.pyindex 445508e13..0af5ccf3a 100644--- a/tests/test_model_hub_migration_auth_recovery.py+++ b/tests/test_model_hub_migration_auth_recovery.py@@ -98,7 +98,7 @@ def test_live_auth_is_mirrored_before_publication_and_completed_receipt(monkeypaadapter.sync_sources = checked_syncservice.migration_journal.complete = checked_complete- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert [phase for phase, _ in observations] == ["withdrawn", "exposed"]assert service.migration_journal.load() is Noneassert not runtime.admissions and not runtime.turns@@ -121,7 +121,7 @@ def test_preexposure_mirror_failure_recovers_the_restored_direction(monkeypatch,service.migration_reconcile_auth = failwith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert service.store.native_auth_snapshot(("claude",)) == beforeassert not adapter.syncedassert not adapter.activated@@ -152,7 +152,7 @@ def test_exposed_mirror_failure_keeps_current_ref_and_forward_only_recovery(monkservice.migration_reconcile_auth = fail_before_receiptwith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))record = service.migration_journal.load()assert record["phase"] == "exposed"ref = service.store.load().sources[0].credential_ref@@ -192,7 +192,7 @@ def test_terminal_oauth_recovery_mirrors_before_releasing_custody(monkeypatch, tadapter.validate_oauth_credential = rejectedservice.migration_reconcile_auth = fail_terminalwith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert service.migration_journal.load()["terminal"]["invalid_source_ids"]assert service.migration_journal.completed() is Noneassert service.migration_blocked_backends == {"claude"}@@ -209,3 +209,35 @@ def test_terminal_oauth_recovery_mirrors_before_releasing_custody(monkeypatch, tassert service.migration_journal.completed()["outcome"] == "needs_auth"assert service.migration_journal.load() is Noneassert not runtime.admissions and not runtime.turns+++def test_copy_only_takeover_keeps_the_avibe_saved_native_key(monkeypatch, tmp_path):+ """MH-MIG-007: without cleanup the V2 native key survives for Direct mode."""+ service, adapter, before, _live, _observations, ids, _runtime = _persistent_takeover(monkeypatch, tmp_path)+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert len(adapter.provisioned) == 1+ assert V2Config.load().model_hub.agents["claude"].mode == "hub"+ assert service.store.native_auth_snapshot(("claude",)) == before+ assert service.migration_scan()["items"] == []+++def test_copy_only_batch_keeps_an_earlier_clean_store_receipt(tmp_path):+ from core.handlers.model_hub.migration_journal import NativeTakeoverJournal++ journal = NativeTakeoverJournal(tmp_path / "takeover.json")++ def record(**extra):+ return {+ "version": 1, "phase": "exposed", "items": [], "backends": ["codex"],+ "source_ids": [], "credentials": [], "previous": {}, "updated": {"sources": []},+ "files": [], "keychain": [], **extra,+ }++ journal.complete(record(clean_native_stores={"codex": "rev-clean"}))+ journal.complete(record(retained_native_ids={"key_fixture": {"source_id": "src_fixture", "credential_ref": "ref_fixture"}}))+ receipt = journal.completed()+ assert receipt["clean_native_stores"] == {"codex": "rev-clean"}+ assert receipt["retained_native_ids"] == {"key_fixture": {"source_id": "src_fixture", "credential_ref": "ref_fixture"}}+ # A batch that edited the store itself replaces the earlier proof.+ journal.complete(record(keychain=[{"backend": "codex", "operations": []}]))+ assert journal.completed()["clean_native_stores"] == {}diff --git a/tests/test_model_hub_migration_custody_history.py b/tests/test_model_hub_migration_custody_history.pyindex dd946dd22..8a933b0f4 100644--- a/tests/test_model_hub_migration_custody_history.py+++ b/tests/test_model_hub_migration_custody_history.py@@ -77,7 +77,7 @@ def _ids(service, backend: str | None = None) -> list[str]:def _apply(service, backend: str | None = None) -> dict:ids = _ids(service, backend)assert ids- return asyncio.run(service.migration_apply(ids))+ return asyncio.run(service.migration_apply(ids, clean_api_keys=True))def _legacy(service) -> None:@@ -353,7 +353,7 @@ def test_first_receipt_interrupted_forget_preserves_explicit_new_history(home, twith monkeypatch.context() as patch:patch.setattr(service.migration_journal, "forget", crash)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))expected = ["claude"] if first == "oauth" else []assert service.migration_journal.completed()["oauth_custody_backends"] == expectedcounts = _counts(adapter)@@ -368,7 +368,7 @@ def test_first_receipt_interrupted_forget_preserves_explicit_new_history(home, tasyncio.run(restarted.recover_runtime_intent())assert restarted.migration_journal.load() is Noneasyncio.run(restarted.recover_runtime_intent())- assert asyncio.run(restarted.migration_apply(ids))["applied"] == 1+ assert asyncio.run(restarted.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert _counts(adapter) == countsassert restarted.migration_journal.completed()["oauth_custody_backends"] == expectedassert restarted.migration_journal.load() is None@@ -418,7 +418,7 @@ def test_completion_crash_replays_custody_union_once(home, tmp_path, monkeypatchpatch.setattr(NativeTakeoverJournal, "save", crash_save)patch.setattr(NativeTakeoverJournal, "forget", crash_forget)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert triggeredcounts = _counts(adapter)restarted, _, _ = _service(tmp_path, migration_home=home)@@ -426,9 +426,9 @@ def test_completion_crash_replays_custody_union_once(home, tmp_path, monkeypatchasyncio.run(restarted.recover_runtime_intent())if rejected:with pytest.raises(ModelHubError):- asyncio.run(restarted.migration_apply(ids))+ asyncio.run(restarted.migration_apply(ids, clean_api_keys=True))else:- assert asyncio.run(restarted.migration_apply(ids))["applied"] == 1+ assert asyncio.run(restarted.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert _counts(adapter) == countsassert restarted.migration_journal.load() is Nonereceipt = restarted.migration_journal.completed()@@ -464,7 +464,7 @@ def test_invalid_custody_evidence_is_not_empty_or_legacy(home, tmp_path, marker,native = _oauth(home, "claude")before = native.read_bytes()with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(["mig_fixture_untrusted"]))+ asyncio.run(service.migration_apply(["mig_fixture_untrusted"], clean_api_keys=True))assert native.read_bytes() == beforeassert _counts(adapter) == counts and store.config.to_payload() == previousassert journal.path.read_bytes() == originaldiff --git a/tests/test_model_hub_migration_review_boundaries.py b/tests/test_model_hub_migration_review_boundaries.pyindex 2ff32dcf1..65c940f38 100644--- a/tests/test_model_hub_migration_review_boundaries.py+++ b/tests/test_model_hub_migration_review_boundaries.py@@ -65,7 +65,7 @@ def test_persisted_key_proof_and_custody_use_one_value(home, tmp_path, shape):adapter.provision_transient_credential = capture_proofrows = [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"]]))+ result = asyncio.run(service.migration_apply([rows[0]["id"]], clean_api_keys=True))assert result["applied"] == 1[source] = store.config.sourcesassert proof_values == [adapter.keys[source.credential_ref][2]] == [KEY]@@ -89,7 +89,7 @@ def test_padded_persisted_key_reuses_the_proven_canonical_credential(home, tmp_p"state": {"status": "standby"}, "models": [], "credential_ref": ref,}))[row] = service.migration_scan()["items"]- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert len(adapter.provisioned) == len(store.config.sources) == 1assert store.config.sources[0].credential_ref == refassert adapter.observed and not adapter.transient_refs@@ -108,7 +108,7 @@ def test_padded_bearer_key_remains_usable_after_actual_http_proof_and_custody(horuntime = _real_http_adapter(service, tmp_path)[row] = service.migration_scan()["items"]assert row["proposed_action"] == "import"- await service.migration_apply([row["id"]])+ await service.migration_apply([row["id"]], clean_api_keys=True)[source] = store.config.sourcesassert runtime.state_store.read_api_key(source.credential_ref) == HTTP_KEYassert await runtime.credential_auth_scheme(source.credential_ref) == "bearer"@@ -164,7 +164,7 @@ def test_prepared_journal_contains_only_selected_credential_store_guards(home, toriginal = {path: path.read_bytes() for backend, (path, _) in unrelated.items() if backend != selected_backend}rows = [row for row in service.migration_scan()["items"] if row["backend"] == selected_backend]assert len(rows) == 1 and rows[0]["proposed_action"] == "import"- asyncio.run(service.migration_apply([rows[0]["id"]]))+ asyncio.run(service.migration_apply([rows[0]["id"]], clean_api_keys=True))assert saved and adapter.provisionedfor record in saved:edits = [NativeFileEdit.from_payload(payload) for payload in record["files"]]@@ -307,7 +307,7 @@ def test_service_rejects_tightened_shell_permissions_without_restoring_them(homesetattr(adapter, boundary, tighten)[row] = service.migration_scan()["items"]with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert path.read_bytes() == originalassert stat.S_IMODE(path.stat().st_mode) == 0o600assert not store.config.sourcesdiff --git a/tests/test_model_hub_migration_source_identity.py b/tests/test_model_hub_migration_source_identity.pyindex 82cbb9d48..7bfe6a201 100644--- a/tests/test_model_hub_migration_source_identity.py+++ b/tests/test_model_hub_migration_source_identity.py@@ -70,7 +70,7 @@ def test_reused_credential_remains_available_to_consented_backend(before = store.config.to_payload()ids = [row["id"] for row in service.migration_scan()["items"]]- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1after = store.config.to_payload()assert after["sources"] == before["sources"]@@ -129,7 +129,7 @@ def test_shared_auth_is_one_source_per_credential_target_not_config_path(rows = service.migration_scan()["items"]assert len(rows) == expectedassert rows == service.migration_scan()["items"]- assert asyncio.run(service.migration_apply([row["id"] for row in rows]))["applied"] == expected+ assert asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))["applied"] == expectedassert len(adapter.provisioned) == expectedassert len(store.config.sources) == expectedassert len(store.config.agents["opencode"].sources.order) == expected@@ -148,7 +148,7 @@ def test_shared_auth_is_one_source_per_credential_target_not_config_path(assert result["mcp"] == {"unrelated": True}assert json.loads(auth.read_text()) == {}assert service.migration_scan()["items"] == []- assert asyncio.run(service.migration_apply([row["id"] for row in rows]))["applied"] == expected+ assert asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))["applied"] == expectedassert len(adapter.provisioned) == expected@@ -168,7 +168,7 @@ def test_shared_credential_consent_binds_every_contributing_config(monkeypatch,paths[1].write_text(json.dumps(payload))before = {path: path.read_bytes() for path in [*paths, auth]}with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert error.value.code == "migration_item_conflict"assert not adapter.provisionedassert {path: path.read_bytes() for path in before} == before@@ -196,7 +196,7 @@ def test_existing_native_source_conversion_also_restores_missing_placement(before = service._clone_config(store.config).to_payload()ids = [row["id"] for row in service.migration_scan()["items"]]- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1source, = store.config.sourcesassert source.id == "src_existingnative"@@ -226,7 +226,7 @@ def test_deduplicated_auth_reversal_restores_every_physical_config(monkeypatch,monkeypatch.setattr(NativeFileEdit, "apply", fail_second)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert len(adapter.provisioned) == 1assert len(adapter.revoked) == 1assert store.config.to_payload() == previous@@ -327,7 +327,7 @@ def test_async_provision_cannot_hide_changed_model_only_layer(monkeypatch, tmp_padapter.provision_credential = change_after_planwith pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert error.value.code == "migration_configuration_blocked"assert store.config.to_payload() == beforeassert auth.read_bytes() == original_authdiff --git a/tests/test_model_hub_migration_static_cleanup.py b/tests/test_model_hub_migration_static_cleanup.pyindex 5084a1c5c..237482a9a 100644--- a/tests/test_model_hub_migration_static_cleanup.py+++ b/tests/test_model_hub_migration_static_cleanup.py@@ -106,7 +106,7 @@ def test_static_proof_and_custody_use_canonical_value(home, tmp_path, shape, rawitem = _selected(_items(service, roots))assert item.secret == KEYassert raw not in json.dumps(item.to_payload()) and KEY not in repr(item)- result = asyncio.run(service.migration_apply([item.id]))+ result = asyncio.run(service.migration_apply([item.id], clean_api_keys=True))assert result["applied"] == 1[source] = store.config.sourcesassert proof_values == [adapter.keys[source.credential_ref][2]] == [KEY]@@ -151,7 +151,7 @@ def test_static_canonical_value_reuses_existing_ref(home, tmp_path, shape):"base_url": item.base_url, "supply_channel": "hub", "billing": "metered","state": {"status": "standby"}, "models": [], "credential_ref": ref,}))- asyncio.run(service.migration_apply([item.id]))+ asyncio.run(service.migration_apply([item.id], clean_api_keys=True))assert len(adapter.provisioned) == len(store.config.sources) == 1assert store.config.sources[0].credential_ref == refassert adapter.observed and not adapter.transient_refs@@ -195,7 +195,7 @@ def test_padding_only_change_never_bypasses_exact_consent(home, tmp_path, shape,adapter.observe_source = mutatewith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([item.id]))+ asyncio.run(service.migration_apply([item.id], clean_api_keys=True))assert changed is not None and path.read_bytes() == changedassert not store.config.sourcesassert not adapter.oauth_provisioned@@ -234,7 +234,7 @@ def test_padded_settings_bearer_uses_proven_header_after_custody(home, tmp_path)service, store, _ = _service(tmp_path, migration_home=home)runtime = _real_http_adapter(service, tmp_path)[row] = service.migration_scan()["items"]- await service.migration_apply([row["id"]])+ await service.migration_apply([row["id"]], clean_api_keys=True)[source] = store.config.sourcesassert runtime.state_store.read_api_key(source.credential_ref) == HTTP_KEYassert await runtime.credential_auth_scheme(source.credential_ref) == "bearer"diff --git a/tests/test_model_hub_migration_transport.py b/tests/test_model_hub_migration_transport.pyindex e5fd86064..321730141 100644--- a/tests/test_model_hub_migration_transport.py+++ b/tests/test_model_hub_migration_transport.py@@ -136,7 +136,7 @@ def test_all_anthropic_native_producers_refuse_unpreservable_transport(tmp_path,assert all(row.notes_key == BLOCKED for row in rows)assert secret not in json.dumps([row.to_payload() for row in rows])with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row.id for row in rows]))+ asyncio.run(service.migration_apply([row.id for row in rows], clean_api_keys=True))assert {path: path.read_bytes() for path in paths} == beforeassert not store.config.sourcesassert not adapter.provisioned and not adapter.transient_refs@@ -153,7 +153,7 @@ def test_official_api_key_still_migrates_from_every_native_producer(tmp_path, nastore.native_auth_snapshot = lambda backends: legacyrows = _scan(service, roots, legacy)assert rows and all(row.proposed_action == "import" for row in rows)- result = asyncio.run(service.migration_apply([row.id for row in rows]))+ result = asyncio.run(service.migration_apply([row.id for row in rows], clean_api_keys=True))assert result["applied"] == len(rows)assert all(source.protocol == "anthropic" for source in store.config.sources)assert all(scheme is None for scheme in adapter.auth_schemes.values())@@ -268,7 +268,7 @@ def test_observation_cannot_change_native_auth_semantics([row] = service.migration_scan()["items"]assert row["proposed_action"] == "import"with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert path.read_bytes() == beforeassert not adapter.provisionedassert service.migration_journal.load() is None@@ -283,7 +283,7 @@ def test_observation_may_change_openai_dialect_without_changing_bearer_auth(tmp_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"]]))["applied"] == 1+ assert asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))["applied"] == 1assert store.config.sources[0].protocol == "openai_responses"@@ -391,7 +391,7 @@ def test_real_observation_cannot_promote_custom_key_to_anthropic_transport(tmp_p[row] = service.migration_scan()["items"]assert row["proposed_action"] == "import"with pytest.raises(ModelHubError):- await service.migration_apply([row["id"]])+ 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() == beforeassert not store.config.sources@@ -412,7 +412,7 @@ def test_custom_bearer_keeps_actual_proof_discovery_and_cleanup(tmp_path, nativeservice, 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])+ result = await service.migration_apply([row["id"] for row in rows], clean_api_keys=True)assert result["applied"] == 1[source] = store.config.sourcesassert await runtime.credential_auth_scheme(source.credential_ref) == "bearer"diff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.pyindex 80ed07923..bcc8bd437 100644--- a/tests/test_model_hub_native_takeover.py+++ b/tests/test_model_hub_native_takeover.py@@ -99,12 +99,12 @@ def test_oauth_is_not_exposed_until_native_cleanup_and_mode_commit(monkeypatch,await activate(ref)adapter.activate_oauth_credential = checked_activate- result = asyncio.run(service.migration_apply(item_ids))+ result = asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))assert result["applied"] == 1assert adapter.validated == adapter.activatedassert service.migration_journal.load() is Noneassert not service.migration_blocked_backends- assert asyncio.run(service.migration_apply(item_ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))["applied"] == 1assert len(adapter.oauth_provisioned) == 1assert "refresh_token" not in service.migration_journal.path.with_name("last-completed.json").read_text()@@ -126,7 +126,7 @@ def test_failure_after_possible_rotation_retains_current_owner_and_retries(monkeadapter.activate_oauth_credential = activate_then_failwith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(item_ids))+ asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))assert service.migration_journal.load()["phase"] == "exposed"assert store.config.agents["codex"].mode == "hub"assert not (home / ".codex/auth.json").exists()@@ -139,7 +139,7 @@ def test_failure_after_possible_rotation_retains_current_owner_and_retries(monkeawait activate(ref)adapter.activate_oauth_credential = resume- assert asyncio.run(service.migration_apply(item_ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))["applied"] == 1assert len(adapter.oauth_provisioned) == 1assert service.migration_journal.load() is None@@ -165,7 +165,7 @@ def test_unavailable_runtime_preserves_native_oauth_before_custody(monkeypatch,adapter.ensure_installed = unavailablewith pytest.raises(ModelHubError) as failure:- asyncio.run(service.migration_apply(item_ids))+ asyncio.run(service.migration_apply(item_ids, clean_api_keys=True))assert failure.value.code == codeassert native.read_bytes() == beforeassert store.config.to_payload() == previous@@ -197,7 +197,7 @@ def test_completed_receipt_recleans_resurrected_credentials_without_reimport(original = native.read_bytes()service, store, adapter = _service(tmp_path, migration_home=home)ids = [row["id"] for row in service.migration_scan()["items"]]- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1if legacy_receipt:# Published receipts predate snapshot-bound consent. Their item IDs# encode the same grant/target inventory, without the new display data.@@ -217,9 +217,9 @@ def test_completed_receipt_recleans_resurrected_credentials_without_reimport(# Cleanup may have changed other configuration layers. Fresh consent# is required, but it must not provision the restored old OAuth again.with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))ids = rescanned_ids- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert service.migration_scan()["items"] == []assert store.config.to_payload() == currentassert (len(adapter.provisioned), len(adapter.oauth_provisioned)) == provisions@@ -234,11 +234,11 @@ def test_completed_receipt_does_not_authorize_new_unconsented_native_key(monkeyp_write(native, '{"provider":{"openai":{"options":{"apiKey":"fixture-first"}}}}')service, _, adapter = _service(tmp_path, migration_home=home)ids = [row["id"] for row in service.migration_scan()["items"]]- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))changed = '{"provider":{"openai":{"options":{"apiKey":"fixture-new"}}}}'native.write_text(changed)with pytest.raises(ModelHubError) as failure:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert failure.value.code == "migration_item_conflict"assert native.read_text() == changedassert len(adapter.provisioned) == 1@@ -260,7 +260,7 @@ def test_receipt_retains_known_oauth_with_a_different_fresh_selection(_write(other, other_payload)service, store, adapter = _service(tmp_path, migration_home=home)ids = [row["id"] for row in service.migration_scan()["items"]]- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))receipt = service.migration_journal.completed()if legacy_receipt:for row, identity in zip(receipt["items"], receipt.pop("inventory_ids"), strict=True):@@ -274,7 +274,7 @@ def test_receipt_retains_known_oauth_with_a_different_fresh_selection(assert {row["backend"] for row in rows} == ({"codex", "opencode"} if selection == "mixed" else {"codex"})- result = asyncio.run(service.migration_apply([row["id"] for row in rows]))+ result = asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert result["applied"] == len(rows)assert len(adapter.oauth_provisioned) == 1assert len(adapter.provisioned) == 1@@ -299,7 +299,7 @@ def test_receipt_cannot_prove_a_second_native_oauth_authorization(original = json.loads(native.read_text())service, store, adapter = _service(tmp_path, migration_home=home)ids = [row["id"] for row in service.migration_scan()["items"]]- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))receipt = service.migration_journal.completed()if legacy_receipt:for row, identity in zip(receipt["items"], receipt.pop("inventory_ids"), strict=True):@@ -314,7 +314,7 @@ def test_receipt_cannot_prove_a_second_native_oauth_authorization(before = native.read_bytes(), store.config.to_payload()rows = service.migration_scan()["items"]with pytest.raises(ModelHubError) as failure:- asyncio.run(service.migration_apply([row["id"] for row in rows]))+ asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert failure.value.code == "migration_reauthorization_required"assert (native.read_bytes(), store.config.to_payload()) == beforeassert len(adapter.oauth_provisioned) == 1@@ -335,7 +335,7 @@ def test_restart_recovers_exposed_handoff_without_native_tokens(monkeypatch, tmpadapter.validate_oauth_credential = offlinewith pytest.raises(ModelHubError):- asyncio.run(first.migration_apply(ids))+ asyncio.run(first.migration_apply(ids, clean_api_keys=True))second, _, _ = _service(tmp_path, migration_home=home)second.store = storesecond.adapter = adapter@@ -364,7 +364,7 @@ def test_caller_cancellation_does_not_abandon_credential_custody(monkeypatch, tmawait activate(ref)adapter.activate_oauth_credential = paused- task = asyncio.create_task(service.migration_apply(ids))+ task = asyncio.create_task(service.migration_apply(ids, clean_api_keys=True))await entered.wait()task.cancel()await asyncio.sleep(0)@@ -391,7 +391,7 @@ def test_native_compare_and_swap_does_not_erase_a_concurrent_login(monkeypatch,service.migration_guard = lambda backends: nullcontext(changed_during_preparation)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert path.read_text() == concurrentassert adapter.activated == []assert service.migration_journal.load()["phase"] == "reverting"@@ -452,7 +452,7 @@ def test_rejected_refresh_finishes_custody_without_claiming_success(monkeypatch,adapter.validate_oauth_credential = reject_claudewith pytest.raises(ModelHubError) as failure:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert failure.value.code == "migration_credentials_invalid"assert len(adapter.validated) == 2assert service.migration_journal.load() is None@@ -466,7 +466,7 @@ def test_rejected_refresh_finishes_custody_without_claiming_success(monkeypatch,assert codex.state.status != "needs_action"assert service.migration_journal.completed()["outcome"] == "needs_auth"with pytest.raises(ModelHubError) as repeated:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert repeated.value.code == "migration_credentials_invalid"assert len(adapter.validated) == 2# Normal Hub config/auth repair is not trapped behind the migration gate.@@ -489,7 +489,7 @@ def test_explicit_hub_reauth_can_repair_inconclusive_exposed_takeover(adapter.validate_oauth_credential = inconclusivewith pytest.raises(ModelHubError) as pending:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert pending.value.code == "migration_recovery_pending"source = store.config.sources[0]retained_ref = source.credential_ref@@ -537,7 +537,7 @@ def test_explicit_hub_reauth_can_repair_inconclusive_exposed_takeover(assert not (home / ".codex/auth.json").exists()assert store.config.sources[0].state.status == "needs_action"with pytest.raises(ModelHubError) as replay:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert replay.value.code != "migration_credentials_invalid"@@ -559,7 +559,7 @@ def test_explicit_reauth_keeps_verified_sibling_usable(monkeypatch, tmp_path):adapter.validate_oauth_credential = validatewith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))claude = next(source for source in store.config.sources if source.vendor == "anthropic")codex = next(source for source in store.config.sources if source.vendor == "openai")assert service.migration_journal.load()["validated_source_ids"] == [claude.id]@@ -599,7 +599,7 @@ def test_rejected_grant_terminal_decision_recovers_after_crash(monkeypatch, tmp_else:service.migration_journal.complete = fail_receiptwith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))record = service.migration_journal.load()assert record["phase"] == "exposed"assert record["terminal"]["invalid_source_ids"]diff --git a/tests/test_model_hub_persisted_inventory.py b/tests/test_model_hub_persisted_inventory.pyindex e40d68e3a..7c6f509b2 100644--- a/tests/test_model_hub_persisted_inventory.py+++ b/tests/test_model_hub_persisted_inventory.py@@ -191,10 +191,10 @@ def test_shared_consent_is_public_and_partial_selection_stops_before_provision(hassert all(row["required_backends"] == ["codex", "opencode"] for row in rows)before = shell.read_bytes(), path.read_bytes()with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([rows[0]["id"]]))+ asyncio.run(service.migration_apply([rows[0]["id"]], clean_api_keys=True))assert not adapter.provisioned and not adapter.transient_refsassert (shell.read_bytes(), path.read_bytes()) == before- assert asyncio.run(service.migration_apply([row["id"] for row in rows]))["applied"] == 2+ assert asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))["applied"] == 2assert len(adapter.provisioned) == 1assert len(store.config.sources) == 1assert shell.read_bytes() == b""@@ -215,7 +215,7 @@ def test_new_shared_consumer_during_provision_preserves_original_sources(home, tadapter.provision_credential = racewith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert shell.read_bytes() == beforeassert not store.config.sourcesassert len(adapter.revoked) == len(adapter.provisioned) == 1@@ -227,7 +227,7 @@ def test_consumer_added_after_scan_invalidates_old_consent(home, tmp_path):[row] = service.migration_scan()["items"]config(home, "opencode", {"openai": {"options": {"apiKey": "{env:OPENAI_API_KEY}"}}})with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert not adapter.provisioned@@ -327,12 +327,12 @@ 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))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert proof_schemes == ["bearer"]assert set(schemes.values()) == {None, "bearer"}assert len(store.config.sources) == len(adapter.provisioned) == 2assert "auth_scheme" not in json.dumps(store.config.to_payload())- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert len(adapter.provisioned) == 2@@ -396,7 +396,7 @@ def test_absent_profile_created_during_native_key_proof_blocks_cleanup(home, tmpadapter.provision_credential = racewith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert path.read_bytes() == beforeassert not store.config.sourcesassert len(adapter.revoked) == len(adapter.provisioned) == 1@@ -421,7 +421,7 @@ def test_live_base_reference_survives_actual_planned_cleanup(home, tmp_path, selassert len(rows) == 1 + selected_opencode_vendorassert all(row["proposed_action"] == "import" for row in rows)assert all("shell_auth_variables" not in row for row in rows)- assert asyncio.run(service.migration_apply([row["id"] for row in rows]))["applied"] == len(rows)+ assert asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))["applied"] == len(rows)assert shell.read_bytes() == base_lineafter = json.loads(path.read_bytes())assert after["provider"]["openai"] == providers["openai"]@@ -433,7 +433,7 @@ def test_live_base_reference_survives_actual_planned_cleanup(home, tmp_path, sel@pytest.mark.parametrize("root_reference", [False, True])-def test_live_auth_reference_without_a_row_blocks_before_any_write(home, tmp_path, root_reference):+def test_live_auth_reference_without_a_row_blocks_only_cleanup(home, tmp_path, root_reference):shell = home / ".profile"shell.write_text("export OPENAI_API_KEY=fixture-codex\n")if root_reference:@@ -445,10 +445,11 @@ def test_live_auth_reference_without_a_row_blocks_before_any_write(home, tmp_patservice, store, adapter = _service(tmp_path, migration_home=home)[row] = service.migration_scan()["items"]assert row["backend"] == "codex"- assert row["notes_key"].endswith(".reference")- assert str(path) in row["source_paths"]+ # Copy-only leaves both the assignment and its consumer, so the row stays+ # selectable. Only the requested cleanup is refused before any write.+ assert row["proposed_action"] == "import"with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert (shell.read_bytes(), path.read_bytes()) == originalassert not adapter.provisioned and not adapter.transient_refsassert not store.config.sources@@ -467,12 +468,14 @@ def test_same_backend_surviving_reference_uses_auth_role_over_base_role(home, sa})[row] = scan(home)assert row.shell_auth_variables == ("CUSTOM_FIXTURE_KEY",)- assert row.notes_key.endswith(".reference")+ assert row.proposed_action == "import"original = shell.read_bytes(), path.read_bytes()+ for edit in plan_native_cleanup([row], home=home, clean_api_keys=False):+ assert edit.after == edit.before# Planner enforcement is independent of scan presentation and backend# selection: selecting OpenCode does not remove the orphan provider.with pytest.raises(NativeReferenceError) as error:- plan_native_cleanup([replace(row, proposed_action="import", selected=True)], home=home)+ plan_native_cleanup([row], home=home)assert error.value.references == {"CUSTOM_FIXTURE_KEY": (str(path),)}assert (shell.read_bytes(), path.read_bytes()) == original@@ -519,3 +522,23 @@ def test_cross_project_reference_with_no_row_is_also_preserved(home, tmp_path):edit.apply()assert shell.read_text() == "export OPENAI_BASE_URL=https://fixture.example/v1\n"assert path.read_bytes() == original+++def test_later_cleanup_spans_the_backends_of_a_kept_shared_key(home, tmp_path):+ shell, _path = shared(home)+ service, _store, adapter = _service(tmp_path, migration_home=home)+ rows = service.migration_scan()["items"]+ assert asyncio.run(service.migration_apply([row["id"] for row in rows]))["applied"] == len(rows)+ assert service.migration_scan()["items"] == []+ copied = len(adapter.provisioned)+ auth = home / ".codex" / "auth.json"+ auth.parent.mkdir(parents=True, exist_ok=True)+ auth.write_text('{"OPENAI_API_KEY": "fixture-codex-new"}')+ added = service.migration_scan()["items"]+ assert {row["backend"] for row in added} == {"codex"}+ applied = asyncio.run(service.migration_apply([row["id"] for row in added], clean_api_keys=True))+ assert applied["applied"] == len(added)+ assert "OPENAI_API_KEY" not in shell.read_text()+ # The kept shared key is withdrawn for both consumers, not copied again.+ assert len(adapter.provisioned) == copied + 1+ assert service.migration_scan()["items"] == []diff --git a/tests/test_model_hub_persisted_migration.py b/tests/test_model_hub_persisted_migration.pyindex 9cc452835..476e17125 100644--- a/tests/test_model_hub_persisted_migration.py+++ b/tests/test_model_hub_persisted_migration.py@@ -64,7 +64,7 @@ def test_mh_mig_005_runtime_auth_cannot_disable_saved_opencode_keys(assert len(rows) == 2assert all(row["proposed_action"] == "import" and row["selected"] for row in rows)assert all(row["source_paths"] == [str(path)] for row in rows)- result = asyncio.run(service.migration_apply([row["id"] for row in rows]))+ result = asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert result["applied"] == 2assert len(adapter.provisioned) == 2assert "fixture-runtime" not in json.dumps(adapter.keys)@@ -90,13 +90,13 @@ def test_shell_saved_key_takeover_keeps_unrelated_bytes_and_runtime(assert rows[0]["source_paths"] == [str(profile)]assert "fixture-shell-key" not in json.dumps(rows)ids = [row["id"] for row in rows]- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert profile.read_bytes() == retained.encode()assert len(store.load().sources) == 1assert store.load().sources[0].base_url == "https://fixture.example"assert list(adapter.keys.values())[0][2] == "fixture-shell-key"assert service.migration_scan()["items"] == []- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert len(adapter.provisioned) == 1assert os.environ["ANTHROPIC_API_KEY"] == "fixture-runtime-preserved"@@ -119,7 +119,7 @@ def test_new_shell_layer_during_provision_cannot_escape_consent(monkeypatch.setattr(adapter, "provision_credential", new_layer)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert profile.read_bytes() == originalassert "fixture-new-key" in (home / ".profile").read_text()assert not store.load().sources@@ -140,10 +140,10 @@ def test_shared_shell_key_requires_both_backend_consents(assert all(set(row["required_backends"]) == {"codex", "opencode"} for row in rows)before = profile.read_bytes(), config_path.read_bytes()with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"] for row in rows if row["backend"] == "opencode"]))+ asyncio.run(service.migration_apply([row["id"] for row in rows if row["backend"] == "opencode"], clean_api_keys=True))assert adapter.provisioned == []assert (profile.read_bytes(), config_path.read_bytes()) == before- asyncio.run(service.migration_apply([row["id"] for row in rows]))+ asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert profile.read_bytes() == b""assert "apiKey" not in json.dumps(json.loads(config_path.read_text()))assert len(store.load().sources) == 1@@ -194,7 +194,7 @@ def test_external_noop_guard_change_never_owns_rollback_bytes(adapter.ensure_installed = installadapter.start = startwith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert profile.read_text() == f"# external preference during {boundary}\n"assert service.migration_journal.completed() is Noneif has_grant and boundary == "start":@@ -223,7 +223,7 @@ def test_receipt_replay_requires_same_grant_target_and_current_hub_ref(write(path, payload)service, store, adapter = _service(tmp_path, migration_home=home)[original] = service.migration_scan()["items"]- asyncio.run(service.migration_apply([original["id"]]))+ asyncio.run(service.migration_apply([original["id"]], clean_api_keys=True))original_ref = store.config.sources[0].credential_refif changed_identity == "new-grant":payload["env"]["ANTHROPIC_AUTH_TOKEN"] = "fixture-new"@@ -235,14 +235,14 @@ def test_receipt_replay_requires_same_grant_target_and_current_hub_ref([current] = service.migration_scan()["items"]if changed_identity == "replaced-hub-ref":with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([current["id"]]))+ asyncio.run(service.migration_apply([current["id"]], clean_api_keys=True))assert len(adapter.provisioned) == 1assert json.loads(path.read_text()) == payloadelse:assert current["id"] != original["id"]with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([original["id"]]))- asyncio.run(service.migration_apply([current["id"]]))+ asyncio.run(service.migration_apply([original["id"]], clean_api_keys=True))+ asyncio.run(service.migration_apply([current["id"]], clean_api_keys=True))assert len(adapter.provisioned) == 2assert store.config.sources[0].credential_ref == original_refassert len(store.config.sources) == 2diff --git a/tests/test_model_hub_provisional_ownership.py b/tests/test_model_hub_provisional_ownership.pyindex 7c596d78a..1c0f0c57f 100644--- a/tests/test_model_hub_provisional_ownership.py+++ b/tests/test_model_hub_provisional_ownership.py@@ -66,7 +66,7 @@ def test_provision_failure_before_return_keeps_durable_cleanup_owner(monkeypatchsetattr(adapter, method, write_then_lose_return)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert len(observed) == 1assert service.revocations.list() == observedassert not store.config.sources@@ -93,7 +93,7 @@ def test_failed_journal_durability_prevents_secret_provision(monkeypatch, tmp_pamonkeypatch.setattr(service.revocations, "_sync_directory", fail_flush)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert not adapter.provisioned and not adapter.oauth_provisioned and not adapter.transient_refsassert not store.config.sourcesassert native.read_bytes() == original@@ -129,7 +129,7 @@ def test_exposed_grant_is_owned_by_its_current_source_during_revocation_replay(madapter.validate_oauth_credential = validation_pendingwith pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))record = service.migration_journal.load()assert record["phase"] == "exposed"source, = store.config.sources@@ -158,7 +158,7 @@ def test_prepared_save_uncertain_outcome_keeps_its_provisional_grant(monkeypatch.setattr(service.migration_journal, "save", committed_then_failed)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))pending = service.migration_journal.load()assert pending["phase"] == "prepared"assert not adapter.revoked@@ -218,7 +218,7 @@ def test_real_engine_material_is_recovered_without_a_prepared_takeover_record(monkeypatch.setattr(service.migration_journal, "save", fail_prepared)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert native.read_bytes() == originalassert not store.config.sourcesassert service.migration_journal.load() is Nonediff --git a/tests/test_model_hub_shell_core_inventory.py b/tests/test_model_hub_shell_core_inventory.pyindex fec6313eb..4d22a8af8 100644--- a/tests/test_model_hub_shell_core_inventory.py+++ b/tests/test_model_hub_shell_core_inventory.py@@ -605,7 +605,7 @@ def test_core_standalone_writer_scan(home, tmp_path, role, filename, name, line,rows = service.migration_scan()["items"]assert rows and all(row["proposed_action"] == "reauth" for row in rows)with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"] for row in rows]))+ asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert not adapter.provisioned and not adapter.oauth_provisioned and not adapter.transient_refsassert not adapter.observed and not store.config.sourcesassert path.read_bytes() == line.encode()@@ -633,7 +633,7 @@ def test_core_independent_backend(home, tmp_path, filename, line):rows = {row["backend"]: row for row in service.migration_scan()["items"]}assert rows["codex"]["notes_key"].endswith(".dynamic_shell")assert rows["claude"]["proposed_action"] == "import"- assert asyncio.run(service.migration_apply([rows["claude"]["id"]]))["applied"] == 1+ assert asyncio.run(service.migration_apply([rows["claude"]["id"]], clean_api_keys=True))["applied"] == 1assert len(adapter.provisioned) == len(store.config.sources) == 1assert path.read_text() == keptdiff --git a/tests/test_model_hub_shell_writer_roles.py b/tests/test_model_hub_shell_writer_roles.pyindex f7b215f22..cf493747e 100644--- a/tests/test_model_hub_shell_writer_roles.py+++ b/tests/test_model_hub_shell_writer_roles.py@@ -329,13 +329,13 @@ def test_builtin_roles_reach_scan_and_apply(home, tmp_path, filename, name, lineassert row["proposed_action"] == "reauth"assert not row["selected"]with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"]]))+ asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))assert path.read_bytes() == beforeassert not adapter.provisioned and not adapter.oauth_provisioned and not adapter.transient_refsassert not store.config.sourceselse:assert row["proposed_action"] == "import"- assert asyncio.run(service.migration_apply([row["id"]]))["applied"] == 1+ assert asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))["applied"] == 1assert len(adapter.provisioned) == len(store.config.sources) == 1assert path.read_bytes() == ("# 保留偏好\r\n" + line).encode()@@ -376,7 +376,7 @@ def test_unrelated_consented_backend_can_still_migrate(home, tmp_path, writer):rows = {row["backend"]: row for row in service.migration_scan()["items"]}assert rows["codex"]["notes_key"].endswith(".dynamic_shell")assert rows["claude"]["proposed_action"] == "import"- result = asyncio.run(service.migration_apply([rows["claude"]["id"]]))+ result = asyncio.run(service.migration_apply([rows["claude"]["id"]], clean_api_keys=True))assert result["applied"] == 1assert len(adapter.provisioned) == len(store.config.sources) == 1assert path.read_text() == keptdiff --git a/tests/test_model_hub_takeover_integration.py b/tests/test_model_hub_takeover_integration.pyindex 8d5964bb2..514b28252 100644--- a/tests/test_model_hub_takeover_integration.py+++ b/tests/test_model_hub_takeover_integration.py@@ -169,7 +169,7 @@ async def test_real_store_http_takeover_recovers_rotated_grant(monkeypatch, tmp_async with management_fixture(state, service, native_path, backend) as fixture:service.adapter = real_adapter(state, fixture.origin)with pytest.raises(ModelHubError) as failure:- await service.migration_apply(ids)+ await service.migration_apply(ids, clean_api_keys=True)assert failure.value.code == "migration_recovery_pending"assert service.migration_journal.load()["phase"] == "exposed"assert not native_path.exists()@@ -182,7 +182,7 @@ async def test_real_store_http_takeover_recovers_rotated_grant(monkeypatch, tmp_reopened = EngineStateStore(tmp_path / "engine")restarted.adapter = real_adapter(reopened, fixture.origin)fixture.fail_validation = False- result = await restarted.migration_apply(ids)+ result = await restarted.migration_apply(ids, clean_api_keys=True)assert result["applied"] == 1assert not restarted.migration_blocked_backendsdiff --git a/tests/test_model_hub_takeover_inventory.py b/tests/test_model_hub_takeover_inventory.pyindex df06546f0..af4a86c0b 100644--- a/tests/test_model_hub_takeover_inventory.py+++ b/tests/test_model_hub_takeover_inventory.py@@ -8,7 +8,7 @@ from contextlib import asynccontextmanagerimport pytestfrom config import paths-from config.v2_config import V2Config+from config.v2_config import ModelHubConfig, V2Configfrom core.handlers.model_hub.migration import MigrationConflictErrorfrom core.handlers.model_hub.service import ModelHubError, V2ModelHubConfigStorefrom vibe.native_oauth_store import NativeOAuthSnapshot@@ -34,7 +34,7 @@ def test_global_and_project_keys_are_all_imported_and_unrelated_data_survives(moservice.migration_project_roots = lambda: (project,)ids = [item["id"] for item in service.migration_scan()["items"]]assert len(ids) == 2- assert asyncio.run(service.migration_apply(ids))["applied"] == 2+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 2assert len(adapter.provisioned) == 2assert store.config.agents["opencode"].mode == "hub"for path in (global_path, project_path):@@ -55,9 +55,9 @@ def test_shadowed_opencode_auth_key_is_not_silently_deleted(monkeypatch, tmp_patids = [item["id"] for item in service.migration_scan()["items"]]assert len(ids) == 2with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids[:1]))+ asyncio.run(service.migration_apply(ids[:1], clean_api_keys=True))assert adapter.provisioned == []- assert asyncio.run(service.migration_apply(ids))["applied"] == 2+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 2assert len(adapter.keys) == 2assert json.loads(auth_path.read_text()) == {}@@ -85,20 +85,20 @@ def test_keychain_takeover_preserves_mcp_without_offering_it_as_a_new_login(monkservice, _, adapter = _service(tmp_path, migration_home=home)ids = [row["id"] for row in service.migration_scan()["items"]]assert keychain.read_calls == [] # Metadata-only consent.- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert len(adapter.oauth_provisioned) == 1assert json.loads(path.read_text()) == {"mcpOAuth": {"provider": "preserved"}}assert json.loads(keychain.items[locator][0]) == {"mcpOAuth": {"provider": "preserved"}}reads_after_takeover = len(keychain.read_calls)assert service.migration_scan()["items"] == []assert len(keychain.read_calls) == reads_after_takeover- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1# A subsequent backend migration must not forget the verified clean store._write(home / ".config/opencode/opencode.json", json.dumps({"provider": {"openai": {"options": {"apiKey": "fixture-other-key"}}},}))next_ids = [row["id"] for row in service.migration_scan()["items"]]- assert asyncio.run(service.migration_apply(next_ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(next_ids, clean_api_keys=True))["applied"] == 1assert service.migration_scan()["items"] == []assert len(keychain.read_calls) == reads_after_takeover# A changed metadata revision is never suppressed by that receipt.@@ -131,7 +131,7 @@ def test_unchanged_unrelated_keychain_container_completes_without_import(monkeypids = [row["id"] for row in service.migration_scan()["items"]]assert len(ids) == 1assert not keychain.read_calls- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert store.config.agents[backend].mode == "hub"assert not store.config.sourcesassert not adapter.provisioned and not adapter.oauth_provisioned@@ -140,7 +140,7 @@ def test_unchanged_unrelated_keychain_container_completes_without_import(monkeypreads = len(keychain.read_calls)assert reads > 0assert service.migration_scan()["items"] == []- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert len(keychain.read_calls) == readskeychain.items[locator] = (original[locator][0], "fixture-new-revision")keychain.mdates[locator] += 1@@ -179,9 +179,9 @@ def test_empty_codex_container_never_authorizes_deleting_dormant_file_grant(store.config.agents["codex"].mode = "direct"ids = [row["id"] for row in service.migration_scan()["items"]]if with_api_key:- # The key migrates; the dormant file grant is never deleted.- asyncio.run(service.migration_apply(ids))- assert json.loads(dormant.read_bytes()) == {"tokens": payload["tokens"]}+ # The key migrates; the dormant file (and equal bytes it holds) is never touched.+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))+ assert dormant.read_bytes() == beforeassert store.config.agents["codex"].mode == "hub"assert len(adapter.provisioned) == len(store.config.sources) == 1assert not adapter.oauth_provisioned@@ -189,7 +189,7 @@ def test_empty_codex_container_never_authorizes_deleting_dormant_file_grant(assert service.migration_journal.load() is Nonereturnelse:- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert store.config.agents["codex"].mode == "hub"assert dormant.read_bytes() == beforeassert not store.config.sources@@ -240,7 +240,7 @@ def test_empty_container_evidence_cannot_hide_denial_or_an_intervening_login(adapter.start = startkeychain.read_denied = boundary == "permission"with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert not store.config.sourcesassert not adapter.oauth_provisioned and not adapter.provisionedassert not keychain.delete_calls and not keychain.write_calls@@ -255,7 +255,7 @@ def test_empty_container_evidence_cannot_hide_denial_or_an_intervening_login(# A new, explicit consent can now take over the new login.adapter.ensure_installed = lambda **kwargs: _return_async(EngineEnsureResult(status, False))adapter.start = lambda: _return_async(status)- assert asyncio.run(service.migration_apply(new_ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(new_ids, clean_api_keys=True))["applied"] == 1assert len(adapter.oauth_provisioned) == 1assert service.migration_journal.load() is None@@ -276,7 +276,9 @@ def test_unsupported_provider_blocks_only_its_cli_before_any_cleanup(monkeypatchservice, _, adapter = _service(tmp_path, migration_home=home)rows = service.migration_scan()["items"]assert {row["proposed_action"] for row in rows} == {"import", "reauth"}- asyncio.run(service.migration_apply([row["id"] for row in rows if row["proposed_action"] == "import"]))+ asyncio.run(service.migration_apply(+ [row["id"] for row in rows if row["proposed_action"] == "import"], clean_api_keys=True,+ ))# The OAuth provider the Hub cannot carry stays exactly as it was.assert json.loads(path.read_bytes()) == {"github-copilot": json.loads(before)["github-copilot"],@@ -294,7 +296,7 @@ def test_project_key_changed_after_consent_refuses_without_import(monkeypatch, tids = [row["id"] for row in service.migration_scan()["items"]]_write(path, json.dumps({"env": {"ANTHROPIC_API_KEY": "fixture-second"}}))with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert adapter.provisioned == []assert json.loads(path.read_text())["env"]["ANTHROPIC_API_KEY"] == "fixture-second"@@ -342,7 +344,7 @@ wire_api = "responses"service.migration_guard = guardwith pytest.raises(ModelHubError) as failure:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert failure.value.code == "migration_item_conflict"assert not adapter.provisioned and not adapter.oauth_provisionedassert store.config.agents["codex"].mode == "direct"@@ -358,7 +360,7 @@ def test_existing_hub_key_still_clears_legacy_auth_when_hub_config_is_unchanged(}))service, memory, adapter = _service(tmp_path, migration_home=home)ids = [row["id"] for row in service.migration_scan()["items"]]- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))config_path = tmp_path / "avibe-config.json"monkeypatch.setattr(paths, "get_config_path", lambda: config_path)config = V2Config.default()@@ -371,7 +373,7 @@ def test_existing_hub_key_still_clears_legacy_auth_when_hub_config_is_unchanged(ids = [row["id"] for row in service.migration_scan()["items"]]assert len(ids) == 1- result = asyncio.run(service.migration_apply(ids))+ result = asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert result["applied"] == 1loaded = V2Config.load(config_path=config_path)@@ -401,12 +403,12 @@ def test_reused_hub_key_requires_current_proof_before_native_cleanup(monkeypatchif not accepted:adapter.unproven_observation_vendor = "anthropic"with pytest.raises(ModelHubError) as failure:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert failure.value.code == "migration_item_conflict"assert native.read_bytes() == beforeassert store.config.to_payload() == previouselse:- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert store.config.to_payload()["sources"] == previous["sources"]assert json.loads(native.read_text()) == {"env": {}, "mcp": {"keep": True}}assert len(adapter.observed) == observed + 1@@ -450,7 +452,7 @@ def test_interrupted_claude_auth_backup_is_imported_and_cannot_restore_old_key(mservice, _, adapter = _service(tmp_path, migration_home=home)rows = service.migration_scan()["items"]assert len(rows) == 3- result = asyncio.run(service.migration_apply([row["id"] for row in rows]))+ result = asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert result["applied"] == 3assert len(adapter.oauth_provisioned) == 1assert {target[2] for target in adapter.keys.values()} == {@@ -482,7 +484,7 @@ def test_explicit_incompatible_native_grant_is_blocked_before_custody(monkeypatcrows = service.migration_scan()["items"]assert len(rows) == 1 and rows[0]["proposed_action"] == "keep_native"with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([rows[0]["id"]]))+ asyncio.run(service.migration_apply([rows[0]["id"]], clean_api_keys=True))assert path.read_bytes() == originalassert not adapter.oauth_provisioned@@ -521,7 +523,7 @@ request_max_retries = 3service, _, adapter = _service(tmp_path, migration_home=home)ids = [row["id"] for row in service.migration_scan()["items"]]assert len(ids) == 1- assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1assert len(adapter.provisioned) == 1content = path.read_text()assert "fixture-bearer-key" not in content@@ -552,9 +554,9 @@ def test_duplicate_apply_joins_owned_operation_and_shutdown_waits(monkeypatch, tstopped.append(True)adapter.sync_sources, adapter.stop = paused_sync, stop- first = asyncio.create_task(service.migration_apply(ids))+ first = asyncio.create_task(service.migration_apply(ids, clean_api_keys=True))await entered.wait()- second = asyncio.create_task(service.migration_apply(ids))+ second = asyncio.create_task(service.migration_apply(ids, clean_api_keys=True))shutdown = asyncio.create_task(service.stop())await asyncio.sleep(0)assert not second.done() and not shutdown.done()@@ -565,3 +567,374 @@ def test_duplicate_apply_joins_owned_operation_and_shutdown_waits(monkeypatch, tasyncio.run(exercise())assert len(adapter.provisioned) == 1+++def test_kept_keychain_codex_key_is_not_offered_again(monkeypatch, tmp_path):+ from tests.test_native_oauth_store import FakeKeychain+ from vibe import native_oauth_store++ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ keychain = FakeKeychain()+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)+ _write(home / ".codex/config.toml", 'cli_auth_credentials_store = "keyring"\n')+ account = "cli|" + hashlib.sha256(str((home / ".codex").resolve()).encode()).hexdigest()[:16]+ locator = ("Codex Auth", account)+ keychain.items[locator] = ('{"OPENAI_API_KEY":"fixture-key-123456"}', "fixture-original")+ original = dict(keychain.items)+ service, store, adapter = _service(tmp_path, migration_home=home)+ store.config.agents["codex"].mode = "direct"+ ids = [row["id"] for row in service.migration_scan()["items"]]+ assert ids+ asyncio.run(service.migration_apply(ids))+ assert store.config.agents["codex"].mode == "hub"+ assert len(adapter.provisioned) == 1+ assert keychain.items == original+ assert not keychain.write_calls and not keychain.delete_calls+ assert service.migration_scan()["items"] == []+ # The store still holds the kept key: it is hidden only while the copy lives.+ [copy] = service.migration_journal.completed()["retained_native_ids"].values()+ payload = store.config.to_payload()+ payload["sources"] = [source for source in payload["sources"] if source["id"] != copy["source_id"]]+ for agent in payload["agents"].values():+ agent["sources"]["order"] = [value for value in agent["sources"]["order"] if value != copy["source_id"]]+ agent["routes"] = {}+ store.config = ModelHubConfig.from_payload(payload)+ assert [row["backend"] for row in service.migration_scan()["items"]] == ["codex"]+++def test_rejected_oauth_completion_still_binds_a_kept_keychain_key(monkeypatch, tmp_path):+ from core.handlers.model_hub.adapter import OAuthCredentialRejectedError+ from tests.test_native_oauth_store import FakeKeychain+ from vibe import native_oauth_store++ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ keychain = FakeKeychain()+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)+ _write(home / ".codex/config.toml", 'cli_auth_credentials_store = "keyring"\n')+ account = "cli|" + hashlib.sha256(str((home / ".codex").resolve()).encode()).hexdigest()[:16]+ locator = ("Codex Auth", account)+ keychain.items[locator] = (json.dumps({+ "OPENAI_API_KEY": "fixture-key-123456",+ "tokens": {+ "access_token": "fixture-access", "refresh_token": "fixture-refresh",+ "account_id": "acct_fixture",+ },+ }), "fixture-original")+ service, store, adapter = _service(tmp_path, migration_home=home)+ store.config.agents["codex"].mode = "direct"+ ids = [row["id"] for row in service.migration_scan()["items"]]+ validate = adapter.validate_oauth_credential++ async def reject(ref):+ await validate(ref)+ raise OAuthCredentialRejectedError()++ adapter.validate_oauth_credential = reject+ with pytest.raises(ModelHubError) as failure:+ asyncio.run(service.migration_apply(ids))+ assert failure.value.code == "migration_credentials_invalid"+ assert json.loads(keychain.items[locator][0]) == {"OPENAI_API_KEY": "fixture-key-123456"}+ assert service.migration_scan()["items"] == []+ [copy] = service.migration_journal.completed()["retained_native_ids"].values()+ payload = store.config.to_payload()+ payload["sources"] = [source for source in payload["sources"] if source["id"] != copy["source_id"]]+ for agent in payload["agents"].values():+ agent["sources"]["order"] = [value for value in agent["sources"]["order"] if value != copy["source_id"]]+ agent["routes"] = {}+ store.config = ModelHubConfig.from_payload(payload)+ assert [row["backend"] for row in service.migration_scan()["items"]] == ["codex"]+++def test_cleanup_keeps_an_unimported_avibe_saved_key(monkeypatch, tmp_path):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ _write(home / ".claude/settings.json", json.dumps({+ "env": {"ANTHROPIC_API_KEY": "fixture-native-key"},+ }))+ config_path = tmp_path / "avibe-config.json"+ monkeypatch.setattr(paths, "get_config_path", lambda: config_path)+ service, memory, _adapter = _service(tmp_path, migration_home=home)+ config = V2Config.default()+ config.model_hub = memory.config+ config.agents.claude.auth_mode = "api_key"+ config.agents.claude.api_key = "fixture-saved-key"+ config.agents.claude.base_url = "ftp://saved.example/v1"+ config.save(config_path=config_path)+ service.store = V2ModelHubConfigStore()+ scan = service.migration_scan()["items"]+ assert sorted(row["proposed_action"] for row in scan) == ["import", "reauth"]+ ids = [row["id"] for row in scan if row["proposed_action"] == "import"]+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1+ loaded = V2Config.load(config_path=config_path)+ assert loaded.agents.claude.api_key == "fixture-saved-key"+ assert loaded.agents.claude.base_url == "ftp://saved.example/v1"+++def _keychain_codex_key_migrated(monkeypatch, tmp_path):+ from tests.test_native_oauth_store import FakeKeychain+ from vibe import native_oauth_store++ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ keychain = FakeKeychain()+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)+ _write(home / ".codex/config.toml", 'cli_auth_credentials_store = "keyring"\n')+ account = "cli|" + hashlib.sha256(str((home / ".codex").resolve()).encode()).hexdigest()[:16]+ locator = ("Codex Auth", account)+ keychain.items[locator] = ('{"OPENAI_API_KEY":"fixture-key-123456"}', "fixture-original")+ service, store, _adapter = _service(tmp_path, migration_home=home)+ store.config.agents["codex"].mode = "direct"+ ids = [row["id"] for row in service.migration_scan()["items"]]+ asyncio.run(service.migration_apply(ids))+ assert service.migration_scan()["items"] == []+ return home, keychain, locator, service+++def test_kept_keychain_key_is_offered_again_after_codex_routing_changes(monkeypatch, tmp_path):+ home, _keychain, _locator, service = _keychain_codex_key_migrated(monkeypatch, tmp_path)+ _write(home / ".codex/config.toml", (+ 'cli_auth_credentials_store = "keyring"\nmodel_provider = "Relay"\n\n'+ '[model_providers.Relay]\nbase_url = "https://relay.example/v1"\nwire_api = "responses"\n'+ ))+ assert [row["backend"] for row in service.migration_scan()["items"]] == ["codex"]+++def test_retained_receipt_binds_only_the_verified_store_revision(monkeypatch, tmp_path):+ from core.handlers.model_hub.migration import _record_retained_store_revisions++ home, keychain, locator, service = _keychain_codex_key_migrated(monkeypatch, tmp_path)+ record = {+ "retained_native_ids": {"key_fixture": {+ "source_id": "src_fixture", "credential_ref": "cred_fixture",+ "store_backend": "codex", "store_routing": "",+ }},+ "verified_store_revisions": {"codex": "codex:keychain:verified-before-external-write"},+ }+ keychain.items[locator] = ('{"OPENAI_API_KEY":"fixture-other-key"}', "fixture-external")+ keychain.mdates[locator] += 1+ asyncio.run(_record_retained_store_revisions(service, record))+ assert "store_revision" not in record["retained_native_ids"]["key_fixture"]+++_RELAY_AND_OTHER = (+ 'cli_auth_credentials_store = "file"\nmodel_provider = "Relay"\n\n[model_providers.Relay]\n'+ 'base_url = "ftp://relay.example/v1"\nwire_api = "responses"\n\n'+ '[model_providers.Other]\nbase_url = "https://other.example/v1"\nwire_api = "responses"\n'+ 'experimental_bearer_token = "{token}"\n'+)+++def _clean_importable(service):+ scan = service.migration_scan()["items"]+ assert any(row["proposed_action"] == "reauth" for row in scan)+ ids = [row["id"] for row in scan if row["proposed_action"] == "import"]+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == len(ids)++[email protected]("with_login", [False, True])+def test_cleanup_keeps_routing_and_store_of_an_uncarried_codex_key(monkeypatch, tmp_path, with_login):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ auth = {"OPENAI_API_KEY": "fixture-store-key-123456"}+ if with_login:+ auth["tokens"] = {+ "access_token": "fixture-access", "refresh_token": "fixture-refresh", "account_id": "acct",+ }+ _write(home / ".codex/auth.json", json.dumps(auth))+ config = home / ".codex/config.toml"+ _write(config, _RELAY_AND_OTHER.format(token="fixture-other-key-654321"))+ service, _store, _adapter = _service(tmp_path, migration_home=home)+ _clean_importable(service)+ assert json.loads((home / ".codex/auth.json").read_text()) == {"OPENAI_API_KEY": "fixture-store-key-123456"}+ text = config.read_text()+ assert 'model_provider = "Relay"' in text+ assert "ftp://relay.example/v1" in text+ assert 'cli_auth_credentials_store = "file"' in text+ assert "fixture-other-key-654321" not in text+++def test_cleanup_keeps_a_codex_store_key_equal_to_a_carried_provider_key(monkeypatch, tmp_path):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ shared = "fixture-shared-key-123456"+ _write(home / ".codex/auth.json", json.dumps({"OPENAI_API_KEY": shared}))+ _write(home / ".codex/config.toml", _RELAY_AND_OTHER.format(token=shared))+ service, _store, _adapter = _service(tmp_path, migration_home=home)+ _clean_importable(service)+ assert json.loads((home / ".codex/auth.json").read_text()) == {"OPENAI_API_KEY": shared}+++def test_cleanup_keeps_a_claude_layer_key_equal_to_a_carried_one(monkeypatch, tmp_path):+ home, project = tmp_path / "native", tmp_path / "project"+ _isolate_native_home(monkeypatch, home)+ shared = "fixture-shared-anthropic-key"+ _write(home / ".claude/settings.json", json.dumps({"env": {"ANTHROPIC_API_KEY": shared}}))+ project_settings = project / ".claude/settings.json"+ _write(project_settings, json.dumps({+ "env": {"ANTHROPIC_API_KEY": shared, "ANTHROPIC_BASE_URL": "ftp://relay.example"},+ }))+ before = project_settings.read_bytes()+ service, _store, _adapter = _service(tmp_path, migration_home=home)+ service.migration_project_roots = lambda: (project,)+ _clean_importable(service)+ assert project_settings.read_bytes() == before+ assert "ANTHROPIC_API_KEY" not in (home / ".claude/settings.json").read_text()+++def test_cleanup_keeps_an_opencode_layer_key_equal_to_a_carried_one(monkeypatch, tmp_path):+ home, project = tmp_path / "native", tmp_path / "project"+ _isolate_native_home(monkeypatch, home)+ shared = "fixture-shared-opencode-key"+ global_path = home / ".config/opencode/opencode.jsonc"+ _write(global_path, json.dumps({"provider": {"openai": {"options": {"apiKey": shared}}}}))+ project_path = project / ".opencode/opencode.json"+ _write(project_path, json.dumps({"provider": {"openai": {+ "options": {"apiKey": shared, "baseURL": "ftp://relay.example/v1"},+ }}}))+ before = project_path.read_bytes()+ service, _store, _adapter = _service(tmp_path, migration_home=home)+ service.migration_project_roots = lambda: (project,)+ _clean_importable(service)+ assert project_path.read_bytes() == before+++def test_reauth_terminal_completion_still_binds_a_kept_keychain_key(monkeypatch, tmp_path):+ from core.handlers.model_hub.oauth import OAuthFlowState+ from tests.test_native_oauth_store import FakeKeychain+ from vibe import native_oauth_store++ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ keychain = FakeKeychain()+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)+ _write(home / ".codex/config.toml", 'cli_auth_credentials_store = "keyring"\n')+ account = "cli|" + hashlib.sha256(str((home / ".codex").resolve()).encode()).hexdigest()[:16]+ locator = ("Codex Auth", account)+ keychain.items[locator] = (json.dumps({+ "OPENAI_API_KEY": "fixture-key-123456",+ "tokens": {+ "access_token": "fixture-access", "refresh_token": "fixture-refresh",+ "account_id": "acct_fixture",+ },+ }), "fixture-original")+ service, store, adapter = _service(tmp_path, migration_home=home)+ store.config.agents["codex"].mode = "direct"+ ids = [row["id"] for row in service.migration_scan()["items"]]++ async def inconclusive(ref):+ raise RuntimeError("fixture inconclusive")++ adapter.validate_oauth_credential = inconclusive+ with pytest.raises(ModelHubError):+ asyncio.run(service.migration_apply(ids))+ assert service.migration_journal.load()["phase"] == "exposed"+ oauth_source = next(source for source in store.config.sources if source.kind == "subscription")++ async def start(source_id, vendor):+ return OAuthFlowState(+ flow_id="oaf_fixture123", source_id=source_id, vendor=vendor,+ state="awaiting_action", auth_url="https://fixture.example/authorize", device_code=None,+ expects=None, instructions_key=None, error_key=None,+ expires_at_iso="2099-01-01T00:00:00+00:00", credential_ref=None,+ )++ adapter.start_oauth = start+ asyncio.run(service.reauth_source(oauth_source.id, {"acknowledge_irreversible": True}))+ assert json.loads(keychain.items[locator][0]) == {"OPENAI_API_KEY": "fixture-key-123456"}+ [copy] = service.migration_journal.completed()["retained_native_ids"].values()+ payload = store.config.to_payload()+ payload["sources"] = [source for source in payload["sources"] if source["id"] != copy["source_id"]]+ for agent in payload["agents"].values():+ agent["sources"]["order"] = [value for value in agent["sources"]["order"] if value != copy["source_id"]]+ agent["routes"] = {}+ store.config = ModelHubConfig.from_payload(payload)+ assert [row["backend"] for row in service.migration_scan()["items"]] == ["codex"]+++def test_key_cleanup_keeps_an_unselected_codex_login(monkeypatch, tmp_path):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ tokens = {"access_token": "fixture-access-only"}+ _write(home / ".codex/auth.json", json.dumps({"OPENAI_API_KEY": "fixture-key-123456", "tokens": tokens}))+ _write(home / ".codex/config.toml", 'cli_auth_credentials_store = "file"\n')+ service, _store, _adapter = _service(tmp_path, migration_home=home)+ scan = service.migration_scan()["items"]+ assert {row["kind"]: row["proposed_action"] for row in scan} == {+ "oauth_native": "keep_native", "api_key": "import",+ }+ ids = [row["id"] for row in scan if row["proposed_action"] == "import"]+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1+ assert json.loads((home / ".codex/auth.json").read_text())["tokens"] == tokens+++def test_cleanup_retires_a_receipt_copied_under_an_earlier_route(monkeypatch, tmp_path):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ auth, config = home / ".codex/auth.json", home / ".codex/config.toml"+ route_a = 'cli_auth_credentials_store = "file"\n'+ route_b = route_a + (+ 'model_provider = "Relay"\n\n[model_providers.Relay]\n'+ 'base_url = "https://relay.example/v1"\nwire_api = "responses"\n'+ )+ _write(auth, json.dumps({"OPENAI_API_KEY": "fixture-key-123456"}))+ _write(config, route_a)+ service, _store, _adapter = _service(tmp_path, migration_home=home)+ ids = [row["id"] for row in service.migration_scan()["items"]]+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert service.migration_scan()["items"] == []+ _write(config, route_b)+ ids = [row["id"] for row in service.migration_scan()["items"]]+ assert asyncio.run(service.migration_apply(ids, clean_api_keys=True))["applied"] == 1+ assert not auth.exists() or "OPENAI_API_KEY" not in json.loads(auth.read_text())+ # The key the user cleaned comes back under route A: it is offered again.+ _write(auth, json.dumps({"OPENAI_API_KEY": "fixture-key-123456"}))+ _write(config, route_a)+ assert [row["kind"] for row in service.migration_scan()["items"]] == ["api_key"]+++def test_pending_journal_from_before_the_cleanup_option_resumes(monkeypatch, tmp_path):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ _write_claude_oauth(home)+ service, _store, adapter = _service(tmp_path, migration_home=home)+ ids = [row["id"] for row in service.migration_scan()["items"]]+ validate = adapter.validate_oauth_credential++ async def inconclusive(ref):+ raise RuntimeError("fixture inconclusive")++ adapter.validate_oauth_credential = inconclusive+ with pytest.raises(ModelHubError):+ asyncio.run(service.migration_apply(ids))+ record = service.migration_journal.load()+ assert record["phase"] != "complete"+ record.pop("clean_api_keys")+ service.migration_journal.save(record)+ adapter.validate_oauth_credential = validate+ assert asyncio.run(service.migration_apply(ids))["applied"] == len(ids)++[email protected]("restore", ["same_row", "same_receipt_identity", "new_bytes"])+def test_a_key_restored_after_cleanup_can_be_copied_and_stays_hidden(monkeypatch, tmp_path, restore):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ auth, config = home / ".codex/auth.json", home / ".codex/config.toml"+ _write(auth, json.dumps({"OPENAI_API_KEY": "fixture-key-123456"}))+ _write(config, 'cli_auth_credentials_store = "file"\n')+ service, store, _adapter = _service(tmp_path, migration_home=home)+ first = [row["id"] for row in service.migration_scan()["items"]]+ assert asyncio.run(service.migration_apply(first, clean_api_keys=True))["applied"] == 1+ # A sync restores the key: the same row, the same receipt identity under+ # another file snapshot (cleanup dropped the store selector), or new bytes.+ indent = 2 if restore == "new_bytes" else None+ _write(auth, json.dumps({"OPENAI_API_KEY": "fixture-key-123456"}, indent=indent))+ if restore != "same_receipt_identity":+ _write(config, 'cli_auth_credentials_store = "file"\n')+ ids = [row["id"] for row in service.migration_scan()["items"]]+ assert len(ids) == 1 and (ids == first) == (restore == "same_row")+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1+ assert json.loads(auth.read_text()) == {"OPENAI_API_KEY": "fixture-key-123456"}+ assert len(store.config.sources) == 1+ assert service.migration_scan()["items"] == []diff --git a/tests/test_native_oauth_store.py b/tests/test_native_oauth_store.pyindex 16b410dae..ed68967fd 100644--- a/tests/test_native_oauth_store.py+++ b/tests/test_native_oauth_store.py@@ -958,7 +958,7 @@ def test_claude_mcp_only_keychain_and_file_oauth_complete_real_consumer_flow([row] = service.migration_scan()["items"]assert row["proposed_action"] == "import"assert fake_keychain.read_calls == []- assert asyncio.run(service.migration_apply([row["id"]]))["applied"] == 1+ assert asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))["applied"] == 1assert len(adapter.oauth_provisioned) == 1assert service.migration_journal.load() is Nonefor name in filenames:@@ -969,7 +969,7 @@ def test_claude_mcp_only_keychain_and_file_oauth_complete_real_consumer_flow(assert service.migration_journal.completed()["clean_native_stores"]["claude"]assert service.migration_scan()["items"] == []assert fake_keychain.read_calls == reads- assert asyncio.run(service.migration_apply([row["id"]]))["applied"] == 1+ assert asyncio.run(service.migration_apply([row["id"]], clean_api_keys=True))["applied"] == 1assert len(adapter.oauth_provisioned) == 1fake_keychain.items[locator] = (raw, "fixture-new-login")fake_keychain.mdates[locator] += 1@@ -1011,7 +1011,7 @@ def test_completed_metadata_revision_does_not_prove_no_prior_oauth('{"provider":{"openai":{"options":{"apiKey":"fixture-other"}}}}')service, config_store, adapter = _service(tmp_path, migration_home=home)rows = service.migration_scan()["items"]- asyncio.run(service.migration_apply([row["id"] for row in rows]))+ asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert "claude" in service.migration_journal.completed()["clean_native_stores"]provisions = len(adapter.oauth_provisioned)fake_keychain.items[locator] = (oauth, "fixture-restored")@@ -1021,14 +1021,14 @@ def test_completed_metadata_revision_does_not_prove_no_prior_oauth(if first_grant or other_source:# A mixed bundle cannot prove that this opaque container was empty.with pytest.raises(ModelHubError) as failure:- asyncio.run(service.migration_apply([row["id"] for row in rows]))+ asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert failure.value.code == "migration_reauthorization_required"assert len(adapter.oauth_provisioned) == provisionsassert fake_keychain.items[locator] == (oauth, "fixture-restored")assert config_store.config.to_payload() == beforeelse:# An entirely source-free confirmation transferred no old OAuth.- asyncio.run(service.migration_apply([row["id"] for row in rows]))+ asyncio.run(service.migration_apply([row["id"] for row in rows], clean_api_keys=True))assert len(adapter.oauth_provisioned) == 1assert service.migration_journal.load() is None@@ -2044,3 +2044,20 @@ def test_apply_is_idempotent_after_keychain_cleanup(def test_keychain_backend_has_no_security_cli_secret_path() -> None:assert not hasattr(store, "_run_security")assert "security" not in store.__dict__+++def test_codex_edit_keeping_api_key_withdraws_only_the_login():+ login = {"OPENAI_API_KEY": "fixture-key", "auth_mode": "chatgpt", "tokens": {"refresh_token": "fixture"}}+ key_only = {"OPENAI_API_KEY": "fixture-key"}+ edit = {"version": 1, "backend": "codex", "operations": [+ {"kind": "keychain", "service": "fixture", "account": "a",+ "before": {"exists": True, "value": json.dumps(login)}, "after": {"exists": False}},+ {"kind": "keychain", "service": "fixture", "account": "b",+ "before": {"exists": True, "value": json.dumps(key_only)}, "after": {"exists": False}},+ ]}+ kept = store.codex_edit_keeping_api_key(edit)+ first, second = kept["operations"]+ assert json.loads(first["after"]["value"]) == key_only+ # A key-only item becomes a compare-only guard, not a missing check.+ assert second["after"] == second["before"]+ assert edit["operations"][0]["after"] == {"exists": False}diff --git a/tests/test_native_process_inventory.py b/tests/test_native_process_inventory.pyindex 0cd610c89..298172ac6 100644--- a/tests/test_native_process_inventory.py+++ b/tests/test_native_process_inventory.py@@ -183,7 +183,7 @@ def test_real_guard_blocks_wrapped_cli_before_takeover(monkeypatch, tmp_path, baassert rows and all(row["proposed_action"] == "import" for row in rows)ids = [row["id"] for row in rows]with pytest.raises(ModelHubError) as error:- asyncio.run(service.migration_apply(ids))+ asyncio.run(service.migration_apply(ids, clean_api_keys=True))assert error.value.code == "migration_native_busy"assert len(calls) == (1 if boundary == "entry" else 2)assert paths.get_config_path().read_bytes() == beforediff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsxindex aecc1f665..8edd4e939 100644--- a/ui/src/components/settings/models/MigrationDialog.test.tsx+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx@@ -122,6 +122,12 @@ afterEach(() => {showToast.mockReset();});+/** Import rows only; the API key cleanup opt-in is a checkbox too, but not a row. */+const rowCheckboxes = (root: HTMLElement) =>+ within(root).getAllByRole('checkbox').filter(+ (box) => !/native CLI configuration|原生 CLI 中的 API Key/.test(box.getAttribute('aria-label') ?? ''),+ );+describe('MigrationDialog — the settings default', () => {it('hides rows the Hub cannot carry and keeps every backend actionable', async () => {serve();@@ -148,6 +154,62 @@ describe('MigrationDialog — the settings default', () => {expect(applied[0]).toEqual(['mig_claude_oauth', 'mig_codex_key', 'mig_opencode_legacy']);});+ it('keeps native API keys unless their cleanup is explicitly checked', async () => {+ serve();+ const calls = vi.mocked(modelsApi.applyMigration).mock.calls;+ renderDialog();+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());+ const clean = within(dialog).getByRole('checkbox', { name: 'Also remove the API keys from the native CLI configuration' });+ expect(clean.getAttribute('aria-checked')).toBe('false');+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await waitFor(() => expect(calls).toHaveLength(1));+ expect(calls[0]).toEqual([['mig_claude_oauth', 'mig_codex_key', 'mig_opencode_legacy'], false]);++ cleanup();+ renderDialog();+ const reopened = await screen.findByRole('dialog');+ await waitFor(() => expect(within(reopened).getByText('OpenAI')).toBeTruthy());+ await user.click(within(reopened).getByRole('checkbox', { name: 'Also remove the API keys from the native CLI configuration' }));+ await user.click(within(reopened).getByRole('button', { name: 'Start migration' }));+ await waitFor(() => expect(calls).toHaveLength(2));+ expect(calls[1]).toEqual([['mig_claude_oauth', 'mig_codex_key', 'mig_opencode_legacy'], true]);+ });++ it('offers no API key cleanup when only subscription logins move', async () => {+ serve([SUBSCRIPTION]);+ const calls = vi.mocked(modelsApi.applyMigration).mock.calls;+ renderDialog();+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await waitFor(() => expect(within(dialog).getByText(/Claude 账号登录/)).toBeTruthy());+ expect(within(dialog).queryByRole('checkbox', { name: 'Also remove the API keys from the native CLI configuration' })).toBeNull();+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await waitFor(() => expect(calls).toHaveLength(1));+ expect(calls[0]).toEqual([['mig_claude_oauth'], false]);+ });++ it('offers API key cleanup for an opaque native store that may hold a key', async () => {+ const opaque: MigrationItem = {+ ...SUBSCRIPTION, id: 'mig_codex_store', backend: 'codex', vendor: 'openai',+ display_name: 'ChatGPT', masked_detail: '', may_hold_api_key: true,+ };+ serve([opaque]);+ const calls = vi.mocked(modelsApi.applyMigration).mock.calls;+ renderDialog();+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ const cleanup = await within(dialog).findByRole('checkbox', { name: 'Also remove the API keys from the native CLI configuration' });+ await user.click(cleanup);+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await waitFor(() => expect(calls).toHaveLength(1));+ expect(calls[0]).toEqual([['mig_codex_store'], true]);+ });+it('selects and submits every import candidate for a backend as one group', async () => {serve([SUBSCRIPTION, SUBSCRIPTION_2, CODEX_KEY, LEGACY]);renderDialog();@@ -155,7 +217,7 @@ describe('MigrationDialog — the settings default', () => {const dialog = await screen.findByRole('dialog');await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());- const claudeRows = within(dialog).getAllByRole('checkbox').slice(0, 2);+ const claudeRows = rowCheckboxes(dialog).slice(0, 2);expect(claudeRows).toHaveLength(2);await user.click(claudeRows[0]);await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));@@ -287,7 +349,7 @@ describe('MigrationDialog — the settings default', () => {'error',));expect(onClose).not.toHaveBeenCalled();- expect(within(dialog).getByRole('checkbox').getAttribute('aria-checked')).toBe('true');+ expect(rowCheckboxes(dialog)[0].getAttribute('aria-checked')).toBe('true');expect((within(dialog).getByRole('button', { name: '开始迁移' }) as HTMLButtonElement).disabled).toBe(false);});@@ -357,14 +419,14 @@ describe('MigrationDialog — the settings default', () => {const dialog = await screen.findByRole('dialog');await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());expect(within(dialog).queryByRole('status')).toBeNull();- expect(within(dialog).getAllByRole('checkbox')).toHaveLength(1);+ expect(rowCheckboxes(dialog)).toHaveLength(1);});});describe('MigrationDialog — persisted authentication', () => {it.each([- ['en', 'Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, Model Hub will manage the selected authentication.'],- ['zh', '导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。迁移后,所选认证由模型网关管理。'],+ ['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 复制导入,原配置默认保留。'],] as const)('explains the saved source boundary and consequence in %s', async (language, sentence) => {await i18n.changeLanguage(language);serve([CODEX_KEY]);@@ -499,7 +561,7 @@ describe('MigrationDialog — shared persisted files', () => {const dialog = await screen.findByRole('dialog');await within(dialog).findByText('OpenAI');- const checkboxes = within(dialog).getAllByRole('checkbox');+ const checkboxes = rowCheckboxes(dialog);expect(checkboxes).toHaveLength(3);expect(within(dialog).queryByText('Anthropic')).toBeNull();const sharedMessage = language === 'en'@@ -526,7 +588,7 @@ describe('MigrationDialog — shared persisted files', () => {const dialog = await screen.findByRole('dialog');await within(dialog).findByText('OpenAI');- const checkboxes = within(dialog).getAllByRole('checkbox');+ const checkboxes = rowCheckboxes(dialog);for (const checkbox of checkboxes) expect(checkbox.getAttribute('aria-checked')).toBe('false');const start = within(dialog).getByRole('button', { name: 'Start migration' });expect((start as HTMLButtonElement).disabled).toBe(true);@@ -555,7 +617,7 @@ describe('MigrationDialog — shared persisted files', () => {const dialog = await screen.findByRole('dialog');await within(dialog).findByText('OpenAI');expect(within(dialog).queryByRole('status')).toBeNull();- const checkboxes = within(dialog).getAllByRole('checkbox');+ const checkboxes = rowCheckboxes(dialog);expect(checkboxes).toHaveLength(3);for (const checkbox of checkboxes) expect((checkbox as HTMLButtonElement).disabled).toBe(false);await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));@@ -580,7 +642,7 @@ describe('MigrationDialog — shared persisted files', () => {const dialog = await screen.findByRole('dialog');await within(dialog).findByText('OpenAI');- const [checkbox] = within(dialog).getAllByRole('checkbox');+ const [checkbox] = rowCheckboxes(dialog);expect((checkbox as HTMLButtonElement).disabled).toBe(true);expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(true);});@@ -603,7 +665,7 @@ describe('MigrationDialog — shared persisted files', () => {const dialog = await screen.findByRole('dialog');await within(dialog).findAllByText('OpenAI');- const [checkbox] = within(dialog).getAllByRole('checkbox');+ const [checkbox] = rowCheckboxes(dialog);expect((checkbox as HTMLButtonElement).disabled).toBe(true);expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(true);});@@ -639,7 +701,7 @@ describe('MigrationDialog — shared persisted files', () => {const dialog = await screen.findByRole('dialog');await within(dialog).findByText('OpenAI');- const checkboxes = within(dialog).getAllByRole('checkbox');+ const checkboxes = rowCheckboxes(dialog);expect(checkboxes).toHaveLength(3);expect(within(dialog).getAllByText(/must migrate together: Claude Code, Codex, OpenCode/)).toHaveLength(3);await user.click(checkboxes[2]);@@ -663,7 +725,7 @@ describe('MigrationDialog — shared persisted files', () => {const dialog = await screen.findByRole('dialog');await within(dialog).findByText('OpenAI');expect(within(dialog).queryByText(/must migrate together/)).toBeNull();- const checkboxes = within(dialog).getAllByRole('checkbox');+ const checkboxes = rowCheckboxes(dialog);await user.click(checkboxes[0]);expect(checkboxes[1].getAttribute('aria-checked')).toBe('true');await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));@@ -706,13 +768,15 @@ describe('MigrationDialog — the Settings surface the setup scope must not distexpect(visibleText(dialog)).toEqual(['Migrate to the Model Hub',- 'Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, Model Hub will manage the selected authentication.',+ '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.','Claude Code','Anthropic','Claude 账号登录(OAuth) · Claude Code configuration','Codex','OpenAI','sk-…9f21 · Codex configuration',+ 'Also remove the API keys from the native CLI configuration',+ '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.','Later','Start migration','Close',@@ -720,6 +784,7 @@ describe('MigrationDialog — the Settings surface the setup scope must not distexpect(controls(dialog)).toEqual([{ role: 'checkbox', name: 'Anthropic · Claude 账号登录(OAuth) · Claude Code configuration', disabled: false },{ role: 'checkbox', name: 'OpenAI · sk-…9f21 · Codex configuration', disabled: false },+ { role: 'checkbox', name: 'Also remove the API keys from the native CLI configuration', disabled: false },{ role: null, name: 'Later', disabled: false },{ role: null, name: 'Start migration', disabled: false },{ role: null, name: 'Close', disabled: false },@@ -748,6 +813,7 @@ describe('MigrationDialog — the Settings surface the setup scope must not distexpect(controls(dialog)).toEqual([{ role: 'checkbox', name: 'Anthropic · Claude 账号登录(OAuth) · Claude Code configuration', disabled: false },{ role: 'checkbox', name: 'Anthropic · sk-ant-…1c05 · Claude Code configuration', disabled: false },+ { role: 'checkbox', name: 'Also remove the API keys from the native CLI configuration', disabled: false },{ role: null, name: 'Later', disabled: false },{ role: null, name: 'Start migration', disabled: false },{ role: null, name: 'Close', disabled: false },diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsxindex 0dd8d2bdd..638b7e8be 100644--- a/ui/src/components/settings/models/MigrationDialog.tsx+++ b/ui/src/components/settings/models/MigrationDialog.tsx@@ -280,6 +280,9 @@ export const MigrationDialog: React.FC<{const [ownLoading, setOwnLoading] = React.useState(true);const [applying, setApplying] = React.useState(false);const [phase, setPhase] = React.useState<SetupPhase>({ kind: 'select' });+ /** Consent to also delete the copied API keys natively. Subscription logins+ * always move: a rotating refresh token cannot have two owners. */+ const [cleanApiKeys, setCleanApiKeys] = React.useState(false);/** Everything this dialog session has taken over, across re-entries. */const [completed, setCompleted] = React.useState(0);const aliveRef = React.useRef(true);@@ -294,6 +297,7 @@ export const MigrationDialog: React.FC<{if (!open) return;setPhase({ kind: 'select' });setCompleted(0);+ setCleanApiKeys(false);}, [open]);React.useEffect(() => {@@ -362,6 +366,7 @@ export const MigrationDialog: React.FC<{};const appliable = appliableItems(items, selectedBackends);const selectedCount = appliable.length;+ const selectsApiKeys = appliable.some((item) => item.may_hold_api_key ?? item.kind !== 'oauth_native');/** What a re-entry would still find, once a batch has landed. */const remaining = grouped.filter(groupSelectable).reduce((total, group) => total + group.importRows.length, 0);@@ -376,7 +381,7 @@ export const MigrationDialog: React.FC<{if (scope === 'setup') setPhase({ kind: 'applying', count: selectedCount });try {const ids = appliable.map((i) => i.id);- const result = await modelsApi.applyMigration(ids);+ const result = await modelsApi.applyMigration(ids, selectsApiKeys && cleanApiKeys);if (!aliveRef.current) return;showToast(t('settings.models.migration.applied', { count: result.applied }) as string, 'success');setCompleted((prior) => prior + result.applied);@@ -482,6 +487,21 @@ export const MigrationDialog: React.FC<{))}</div>))}+ {selectsApiKeys && (+ <div className="flex items-start gap-3 rounded-xl border border-border px-3.5 py-3">+ <Checkbox+ checked={cleanApiKeys}+ onCheckedChange={setCleanApiKeys}+ disabled={applying}+ label={t('settings.models.migration.cleanApiKeys') as string}+ className="mt-px"+ />+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="text-[14px] font-semibold text-foreground">{t('settings.models.migration.cleanApiKeys')}</span>+ <span className="text-[12px] leading-relaxed text-muted">{t('settings.models.migration.cleanApiKeysHint')}</span>+ </div>+ </div>+ )}</div>)}diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 9d83e413b..6df889104 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -155,7 +155,8 @@ export type ModelsApi = {updateModelReasoningEfforts(sourceId: string, modelId: string, reasoningEfforts: string[]): Promise<Source>;deleteCustomModel(sourceId: string, modelId: string, confirmation?: GuardConfirmation): Promise<Source>;scanMigration(): Promise<MigrationScan>;- applyMigration(itemIds: string[]): Promise<MigrationApplyResult>;+ /** API keys are copied and kept natively unless `cleanApiKeys`. */+ applyMigration(itemIds: string[], cleanApiKeys?: boolean): Promise<MigrationApplyResult>;/** `before` is an event id cursor (「查看全部」 pagination). */listEvents(limit?: number, before?: string): Promise<ResolutionEvent[]>;/** Metered token report over a trailing local-day window. `days` is a REQUEST:@@ -635,7 +636,10 @@ export const modelsApi: ModelsApi = {updateModelReasoningEfforts: (sourceId, modelId, reasoningEfforts) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('PATCH', { reasoning_efforts: reasoningEfforts })).then((r) => (r.source ?? r) as Source),deleteCustomModel: (sourceId, modelId, confirmation) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(sourceId)}/models/${encodeURIComponent(modelId)}`, jsonInit('DELETE', confirmation ?? {})).then((r) => (r.source ?? r) as Source),scanMigration: () => call<{ scan?: MigrationScan } & MigrationScan>('/api/models/migration/scan', jsonInit('POST')).then((r) => (r.scan ?? r) as MigrationScan),- applyMigration: (itemIds) => call<MigrationApplyResult>('/api/models/migration/apply', jsonInit('POST', { item_ids: itemIds })),+ applyMigration: (itemIds, cleanApiKeys = false) => call<MigrationApplyResult>(+ '/api/models/migration/apply',+ jsonInit('POST', { item_ids: itemIds, clean_api_keys: cleanApiKeys }),+ ),listEvents: (limit = 20, before) =>call<{ events: ResolutionEvent[] }>(`/api/models/events?limit=${limit}${before ? `&before=${encodeURIComponent(before)}` : ''}`,diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 910978003..e143c3ab1 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -471,6 +471,10 @@ export type MigrationItem = {/** The backend's native config cannot be parsed, so Hub mode would fail every* launch: the row blocks its whole consent group. Optional for older servers. */config_blocker?: boolean;+ /** Whether applying this row may copy a native API key, including an+ * opaque credential store that resolves only after consent. Older servers+ * omit it; then only non-subscription rows hold keys. */+ may_hold_api_key?: boolean;};export type MigrationScan = { items: MigrationItem[] };diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex c38a5ff52..178184570 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1710,7 +1710,9 @@"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, Model Hub will manage the selected authentication.",+ "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.",+ "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.","sharedFiles": "These backends share authentication saved in files and must migrate together: {{backends}}. Changing one selection updates the others.","scanFailed": "Couldn't scan native configs, please retry",@@ -5071,7 +5073,7 @@},"import": {"title": "Migrate to Model Hub",- "description": "After migration, these assistants connect through Model Hub. The matching keys are removed from their original config files; other settings stay as they are.",+ "description": "After migration, these assistants connect through Model Hub. The keys in their original config files stay in place and are no longer used by these assistants; other settings stay as they are.","action_one": "Review {{count}} selected","action_other": "Review {{count}} selected","scopeNote": "Only API keys can be migrated here. Handle subscription sign-ins and anything else in Settings.",@@ -5081,7 +5083,7 @@"progressDetail": "Migrating authentication and updating linked assistant connections","done_one": "Migrated {{count}} configuration item","done_other": "Migrated {{count}} configuration items",- "doneDetail": "Migration and native authentication cleanup are complete. Check the assistants’ model routes.",+ "doneDetail": "Migration is complete. Check the assistants’ model routes.","remaining_one": "{{count}} item needs review. Continue any time.","remaining_other": "{{count}} items need review. Continue any time.","remainingAction": "Review remaining",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex eae8af048..119616af8 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1710,7 +1710,9 @@"migration": {"open": "迁移配置","title": "迁移到模型网关",- "subtitle": "导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。迁移后,所选认证由模型网关管理。",+ "subtitle": "导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。迁移后,助手统一通过模型网关认证:订阅登录转交模型网关托管,API Key 复制导入,原配置默认保留。",+ "cleanApiKeys": "同时清理原生 CLI 中的 API Key 配置",+ "cleanApiKeysHint": "包括 Shell 启动文件和各 CLI 的配置文件。不勾选时这些 Key 保持原样,经模型网关启动的助手不会使用它们。","empty": "没有检测到可迁移的配置。","sharedFiles": "这些后端共用文件中保存的认证,需要一起迁移:{{backends}}。勾选或取消其中一个,会同时更新全部关联后端。","scanFailed": "扫描 Agent 配置失败,请重试",@@ -5071,7 +5073,7 @@},"import": {"title": "迁移到模型网关",- "description": "迁移后,这些助手改用模型网关连接模型,原配置文件里对应的 Key 会被移除,其他设置不变。",+ "description": "迁移后,这些助手改用模型网关连接模型。原配置文件里的 Key 默认保留,这些助手不再使用它们,其他设置不变。","action_one": "查看选中的 {{count}} 项","action_other": "查看选中的 {{count}} 项","scopeNote": "这里只迁移 API Key。订阅登录和无法迁移的配置,请到设置中处理。",@@ -5081,7 +5083,7 @@"progressDetail": "正在迁移认证并更新关联助手的连接","done_one": "已迁移 {{count}} 项配置","done_other": "已迁移 {{count}} 项配置",- "doneDetail": "迁移和原生认证清理已完成。请确认助手的模型路由。",+ "doneDetail": "迁移已完成。请确认助手的模型路由。","remaining_one": "还有 {{count}} 项需要查看,可随时继续","remaining_other": "还有 {{count}} 项需要查看,可随时继续","remainingAction": "继续选择",diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 337c6f2f7..fe168a0bf 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -322,8 +322,8 @@ class ModelHubRemoteService:def migration_scan(self) -> dict:return _rpc_sync("migration_scan")- async def migration_apply(self, item_ids: object) -> dict:- return await _rpc("migration_apply", {"item_ids": item_ids})+ async def migration_apply(self, item_ids: object, clean_api_keys: object = False) -> dict:+ return await _rpc("migration_apply", {"item_ids": item_ids, "clean_api_keys": clean_api_keys})async def runtime_status(self) -> dict:return await _rpc("runtime_status")diff --git a/vibe/native_oauth_store.py b/vibe/native_oauth_store.pyindex f06a7de8c..d342a454d 100644--- a/vibe/native_oauth_store.py+++ b/vibe/native_oauth_store.py@@ -370,16 +370,63 @@ def _claude_same_account()-def _remove_codex_oauth(payload: Mapping[str, Any]) -> dict[str, Any]:+def _remove_codex_oauth(payload: Mapping[str, Any], *, keep_api_key: bool = False) -> dict[str, Any]:result = dict(payload)result.pop("tokens", None)result.pop("last_refresh", None)- result.pop("OPENAI_API_KEY", None)+ if not keep_api_key:+ result.pop("OPENAI_API_KEY", None)if result.get("auth_mode") == "chatgpt":result.pop("auth_mode", None)return result+def codex_edit_keeping_api_key(+ edit: Mapping[str, Any] | None, *, withdrawn_keys: frozenset[str] = frozenset(),+ withdraw_login: bool = True,+) -> dict[str, Any] | None:+ """Withdraw only the login from a Codex store edit; its static key stays+ unless it is one of ``withdrawn_keys``.++ A store with nothing to withdraw becomes a compare-only guard, so a change+ made while the migration is in flight is still detected.+ """++ if edit is None:+ return None+ operations = []+ for operation in _normalize_operations(edit):+ before = operation.get("before")+ exists, value = _state_value(before) if isinstance(before, dict) else (False, None)+ payload: object = value+ if isinstance(value, str):+ try:+ payload = json.loads(value)+ except ValueError:+ payload = None+ if not exists or not isinstance(payload, dict):+ operations.append(operation)+ continue+ key = payload.get("OPENAI_API_KEY")+ withdraw_key = isinstance(key, str) and key.strip() in withdrawn_keys+ if withdraw_login:+ after_payload = _remove_codex_oauth(payload, keep_api_key=not withdraw_key)+ else:+ # No login is withdrawn: only a carried key leaves, byte-for-byte otherwise.+ after_payload = dict(payload)+ if withdraw_key:+ after_payload.pop("OPENAI_API_KEY", None)+ if after_payload == payload:+ after: dict[str, Any] = dict(before)+ elif operation.get("kind") == "file":+ after = _state_for_json_payload(after_payload, value if isinstance(value, str) else "")+ else:+ stored = after_payload if isinstance(value, dict) else json.dumps(after_payload, ensure_ascii=False, indent=2)+ after = {"exists": True, "value": stored} if after_payload else {"exists": False}+ operations.append({**operation, "after": after})+ return {**edit, "operations": operations}++def _remove_claude_oauth(payload: Mapping[str, Any]) -> dict[str, Any]:result = dict(payload)if isinstance(result.get("claudeAiOauth"), dict):diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex ac05350e6..5022a468b 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5109,8 +5109,9 @@ async def model_hub_migration_apply():from core.handlers.model_hub import ModelHubErrortry:+ payload = _model_hub_json_object("migration_item_conflict", status=409)result = await _model_hub_service().migration_apply(- _model_hub_json_object("migration_item_conflict", status=409).get("item_ids")+ payload.get("item_ids"), payload.get("clean_api_keys", False),)return _model_hub_success(**result)except ModelHubError as exc: