Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(model-hub): add one-click native credential takeover (#2060)

Call White162fda594246
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 2abc593ef..edbc6582c 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -57,6 +57,7 @@ jobs:
npx playwright install --with-deps chromium webkit
npm run test:model-catalog
npm run test:model-provider
+ npm run test:onboarding-fidelity -- hub-ownership.spec.ts
npm run test:project-order
npm run test:inbox-return
npm run test:badge-triggers
diff --git a/config/v2_config.py b/config/v2_config.py
index 2b15933df..0a0f43323 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -1288,8 +1288,12 @@ def _reset_recoverable_config_section(
# second time and discard otherwise valid settings.
payload[section] = {"default_cwd": str(Path.home() / "work")}
return True
+ if section == "model_hub":
+ # Recovery is not an installation upgrade or consent to reroute native
+ # backends. Keep the optional runtime disabled until the file is fixed.
+ payload[section] = {"enabled": False, "runtime_default_applied": True}
+ return True
if section in {
- "model_hub",
"memory",
"remote_access",
"update",
@@ -3554,13 +3558,18 @@ class ModelHubAgentSupplyConfig:
@dataclass
class ModelHubConfig:
- enabled: bool = False
+ # New installations enable the runtime. Disk loading promotes pre-marker
+ # installations once; a later explicit stop remains a deliberate opt-out.
+ enabled: bool = True
sources: list[ModelHubSourceConfig] = field(default_factory=list)
agents: dict[str, ModelHubAgentSupplyConfig] = field(
default_factory=lambda: {
- backend: ModelHubAgentSupplyConfig.default(backend, mode="direct") for backend in MODEL_HUB_BACKENDS
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in MODEL_HUB_BACKENDS
}
)
+ # Current writers stamp this even when saving enabled=False. Only disk
+ # loading may promote an old absent/false marker together with enabled=True.
+ runtime_default_applied: bool = True
@staticmethod
def source_eligible_for_backend(
@@ -3600,11 +3609,14 @@ class ModelHubConfig:
def from_payload(cls, payload: dict, *, repairing: bool = False) -> "ModelHubConfig":
if not isinstance(payload, dict):
raise ValueError("Config 'model_hub' must be an object")
- if set(payload) - {"enabled", "sources", "agents"}:
+ if set(payload) - {"enabled", "sources", "agents", "runtime_default_applied"}:
raise ValueError("Config 'model_hub' contains unknown fields")
- enabled = payload.get("enabled", False)
+ enabled = payload.get("enabled", True)
if not isinstance(enabled, bool):
raise ValueError("Config 'model_hub.enabled' must be a boolean")
+ runtime_default_applied = payload.get("runtime_default_applied", True)
+ if not isinstance(runtime_default_applied, bool):
+ raise ValueError("Config 'model_hub.runtime_default_applied' must be a boolean")
sources_payload = payload.get("sources") or []
agents_payload = payload.get("agents") or {}
if not isinstance(sources_payload, list):
@@ -3641,6 +3653,9 @@ class ModelHubConfig:
agents = {}
for backend in MODEL_HUB_BACKENDS:
if backend not in agents_payload:
+ # An omitted legacy backend is not consent to change its
+ # working authentication. Fresh installs use the dataclass
+ # defaults; the migration transaction adopts selected backends.
raw_agent = ModelHubAgentSupplyConfig.default(backend, mode="direct").to_payload()
else:
raw_agent = agents_payload[backend]
@@ -3657,6 +3672,7 @@ class ModelHubConfig:
enabled=enabled,
sources=sources,
agents=agents,
+ runtime_default_applied=runtime_default_applied,
)
for backend in MODEL_HUB_BACKENDS:
configured_sources = agents[backend].sources
@@ -3693,6 +3709,7 @@ class ModelHubConfig:
def to_payload(self) -> dict:
return {
"enabled": self.enabled,
+ "runtime_default_applied": self.runtime_default_applied,
"sources": [source.to_payload() for source in self.sources],
"agents": {backend: self.agents[backend].to_payload() for backend in MODEL_HUB_BACKENDS},
}
@@ -3948,7 +3965,7 @@ class V2Config:
@classmethod
def default(cls) -> "V2Config":
- """Return the minimal safe config used for first-run and recovery."""
+ """Return the minimal safe config used for first-run."""
return cls(
mode="self_host",
@@ -3965,6 +3982,13 @@ class V2Config:
platform=WORKBENCH_PLATFORM_ID,
)
+ @classmethod
+ def _recovery_default(cls) -> "V2Config":
+ """Unreadable installations must not acquire fresh-install Hub modes."""
+ config = cls.default()
+ config.model_hub = ModelHubConfig.from_payload({"enabled": False})
+ return config
+
@classmethod
def load(
cls,
@@ -3986,7 +4010,7 @@ class V2Config:
backup = _backup_config_file(path, "invalid-encoding", content=raw_bytes)
warning = f"Config is not valid UTF-8; using recovery defaults: {exc.reason}"
logger.error("%s (backup=%s)", warning, backup)
- config = cls.default()
+ config = cls._recovery_default()
config.load_warnings = (warning,)
config.recovered_sections = ()
config.whole_config_recovery = True
@@ -3998,7 +4022,7 @@ class V2Config:
backup = _backup_config_file(path, "invalid-json", content=raw_bytes)
warning = f"Config JSON could not be parsed; using recovery defaults: {exc.msg}"
logger.error("%s (backup=%s)", warning, backup)
- config = cls.default()
+ config = cls._recovery_default()
config.load_warnings = (warning,)
config.recovered_sections = ()
config.whole_config_recovery = True
@@ -4008,7 +4032,7 @@ class V2Config:
backup = _backup_config_file(path, "invalid-root", content=raw_bytes)
warning = "Config root is not an object; using recovery defaults"
logger.error("%s (backup=%s)", warning, backup)
- config = cls.default()
+ config = cls._recovery_default()
config.load_warnings = (warning,)
config.recovered_sections = ()
config.whole_config_recovery = True
@@ -4019,6 +4043,25 @@ class V2Config:
recovery_warnings = config.load_warnings
recovered_sections = config.recovered_sections
whole_config_recovery = config.whole_config_recovery
+ # Use raw marker presence, not the current writer's dataclass default.
+ # Only a fully valid installation qualifies; recovery must never make
+ # an old runtime opt-in look like a successful upgrade.
+ runtime_default_pending = (
+ not migration_warnings
+ and not recovery_warnings
+ and (migrated_payload.get("model_hub") or {}).get("runtime_default_applied") is not True
+ )
+ stored_hub = payload.get("model_hub")
+ previous_runtime_enabled = isinstance(stored_hub, dict) and stored_hub.get("enabled") is True
+ if runtime_default_pending:
+ config.model_hub.enabled = True
+ config.model_hub.runtime_default_applied = True
+ migrated = True
+ elif migration_warnings or recovery_warnings:
+ # Do not materialize a new runtime default while recovering an
+ # unrelated malformed section. Preserve an already enabled Hub
+ # only when its own config could be parsed safely.
+ config.model_hub.enabled = config.model_hub.enabled and previous_runtime_enabled
all_warnings = tuple(dict.fromkeys((*migration_warnings, *recovery_warnings)))
if (
persist_migrations
@@ -4037,6 +4080,11 @@ class V2Config:
except OSError as exc:
persistence_warning = f"Model Hub config migration could not be persisted: {exc}"
if persistence_warning:
+ if runtime_default_pending:
+ # A failed backup/CAS must not activate an uncommitted
+ # default. A future successful load may retry the upgrade.
+ config.model_hub.enabled = previous_runtime_enabled
+ config.model_hub.runtime_default_applied = False
all_warnings = tuple(dict.fromkeys((*all_warnings, persistence_warning)))
logger.warning("%s (%s)", persistence_warning, path)
if "file changed" in persistence_warning and _migration_reload_depth == 0:
@@ -4083,14 +4131,14 @@ class V2Config:
if section is None or recovered in recovered_sections:
warning = f"Config could not be loaded; using recovery defaults: {exc}"
logger.error("%s", warning)
- config = cls.default()
+ config = cls._recovery_default()
recovery_warnings.append(warning)
whole_config_recovery = True
break
if not _reset_recoverable_config_section(candidate, section, field_name):
warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"
logger.error("%s", warning)
- config = cls.default()
+ config = cls._recovery_default()
recovery_warnings.append(warning)
whole_config_recovery = True
break
@@ -4244,9 +4292,9 @@ class V2Config:
model_hub_payload = payload.get("model_hub")
if model_hub_payload is None:
- # Existing installs predate Model Hub and remain in Direct mode until
- # the user explicitly opts in after the release capability is enabled.
- model_hub = ModelHubConfig()
+ # Enable the gateway runtime on upgrade without changing the
+ # authentication owner of existing native CLI installations.
+ model_hub = ModelHubConfig.from_payload({})
else:
# The one repairing door, because this is the one caller parsing a
# document a previous release wrote. Every other entry into these
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 256af73b9..e4b38cbdd 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -3,7 +3,9 @@
from __future__ import annotations
import asyncio
+import copy
import errno
+import inspect
import json
import logging
import os
@@ -11,11 +13,13 @@ import re
import signal
import time
import uuid
+from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Coroutine, Optional
from core.backend_failure import terminal_backend_failure_output
+from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError, finish_native_operation
from core.delivery_evidence import DeliveryEvidence, STAGE_PERSIST, STAGE_SEND
from core.delivery_target import routed_delivery_context
from core.message_output import MessageOutput, terminal_turn_output
@@ -62,6 +66,10 @@ CLAUDE_PROBE_DISCONNECT_TIMEOUT_SECONDS = 3.0
CLAUDE_PROBE_PROCESS_EXIT_GRACE_SECONDS = 0.2
+async def _native_auth_thread(function: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
+ return await finish_native_operation(asyncio.to_thread(function, *args, **kwargs))
+
+
class BackendLoginInProgressError(RuntimeError):
"""Raised when a native credential already has a live login owner."""
@@ -351,6 +359,10 @@ class AgentAuthFlow:
claude_oauth_attempt: "ClaudeOAuthAttempt | None" = None
native_cli: bool = False
expires_at_iso: str | None = None
+ native_lease: NativeCredentialLease | None = field(default=None, repr=False)
+ cancel_requested: bool = field(default=False, repr=False)
+ submission_task: asyncio.Task[Any] | None = field(default=None, repr=False)
+ native_closing: bool = field(default=False, repr=False)
@property
def flow_key(self) -> str:
@@ -424,6 +436,10 @@ class WebAuthFlow:
source_signed_in: bool | None = None
source_account_label: str | None = None
native_cli: bool = False
+ native_lease: NativeCredentialLease | None = field(default=None, repr=False)
+ cancel_requested: bool = field(default=False, repr=False)
+ submission_task: asyncio.Task[Any] | None = field(default=None, repr=False)
+ native_closing: bool = field(default=False, repr=False)
class AuthFlowRegistry:
@@ -489,6 +505,105 @@ class AgentAuthService:
clients.append(flow.claude_client)
return clients
+ def _acquire_native_lease(self, backend: str, *, source_id: str | None = None) -> NativeCredentialLease:
+ try:
+ lease = NativeCredentialLease((backend,)).acquire()
+ except NativeMigrationBlockedError as error:
+ if error.reason != "native_auth_in_progress":
+ raise
+ owner = next((
+ flow for flow in self._flows_by_id.values()
+ if flow.backend == backend and flow.native_lease is not None
+ ), None)
+ raise BackendLoginInProgressError(
+ self._native_vendor_for_flow(backend, None), backend,
+ owner_ref=getattr(owner, "source_id", None),
+ flow_id=getattr(owner, "flow_id", None),
+ ) from None
+ try:
+ lease.assert_auth_custody(backend, source_id=source_id)
+ return lease
+ except BaseException:
+ lease.release()
+ raise
+
+ @staticmethod
+ def _cancel_flow_waiter(flow: AgentAuthFlow | WebAuthFlow) -> None:
+ if (
+ flow.waiter_task is not None and flow.waiter_task is not asyncio.current_task()
+ and not flow.waiter_task.done() and not flow.cancel_requested
+ ):
+ flow.cancel_requested = True
+ flow.waiter_task.cancel()
+
+ async def _run_flow_submission(
+ self, flow: AgentAuthFlow | WebAuthFlow, operation: Coroutine[Any, Any, Any]
+ ) -> Any:
+ """Join request-owned callbacks before the flow can surrender its lease."""
+ if flow.native_closing or (flow.submission_task is not None and not flow.submission_task.done()):
+ operation.close()
+ raise RuntimeError("native_auth_submission_unavailable")
+ task = asyncio.create_task(operation)
+ flow.submission_task = task
+ try:
+ return await finish_native_operation(task)
+ finally:
+ if task.done():
+ flow.submission_task = None
+
+ async def _join_flow_submission(self, flow: AgentAuthFlow | WebAuthFlow) -> None:
+ flow.native_closing = True
+ task = flow.submission_task
+ if task is not None:
+ # The submitter owns its result/error. Cleanup owns joining it,
+ # including a failed or cancelled HTTP request's threaded tail.
+ await finish_native_operation(asyncio.gather(task, return_exceptions=True))
+
+ async def _cleanup_native_flow(self, flow: AgentAuthFlow | WebAuthFlow) -> None:
+ """Release credential ownership only after every native writer is gone."""
+ await self._join_flow_submission(flow)
+ if flow.reader_task and flow.reader_task is not asyncio.current_task():
+ if not flow.reader_task.done():
+ flow.reader_task.cancel()
+ try:
+ await flow.reader_task
+ except asyncio.CancelledError:
+ pass
+ if flow.process is not None and flow.process.returncode is None:
+ try:
+ flow.process.terminate()
+ except ProcessLookupError:
+ pass
+ try:
+ await asyncio.wait_for(flow.process.wait(), timeout=5)
+ except asyncio.TimeoutError:
+ flow.process.kill()
+ await asyncio.wait_for(flow.process.wait(), timeout=5)
+ if flow.process.returncode is None:
+ raise RuntimeError("Native auth process did not exit")
+ if flow.claude_client is not None:
+ await self._disconnect_claude_client(flow.claude_client, strict=True)
+ flow.claude_client = None
+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)
+ if isinstance(flow, AgentAuthFlow) and flow.pty_master_fd is not None:
+ os.close(flow.pty_master_fd)
+ flow.pty_master_fd = None
+ if flow.native_lease is not None:
+ flow.native_lease.release()
+ flow.native_lease = None
+
+ async def _owned_flow_waiter(
+ self, flow: AgentAuthFlow | WebAuthFlow, waiter: Coroutine[Any, Any, None]
+ ) -> None:
+ try:
+ await waiter
+ finally:
+ # A terminal UI state alone does not mean its process is retired.
+ # Retain the lease if cleanup fails; never silently permit takeover.
+ await finish_native_operation(self._cleanup_native_flow(flow))
+ if isinstance(flow, AgentAuthFlow):
+ self._flow_registry.drop(flow)
+
def active_claude_auth_client_pids(self) -> set[int]:
"""Return Claude SDK client pids owned by in-progress auth flows."""
pids: set[int] = set()
@@ -553,7 +668,7 @@ class AgentAuthService:
def _make_flow_key(self, context: MessageContext, backend: str) -> str:
return f"{self._get_settings_key(context)}:{backend}"
- def _get_cli_binary(self, backend: str) -> str:
+ def _get_cli_binary(self, backend: str, *, strict: bool = False) -> str:
# Same dual-shape issue as ``_resolve_backend_config``: V2Config
# carries the binary under ``config.agents.<backend>.cli_path``,
# but ``AppCompatConfig`` (the shape live IM controllers run on)
@@ -563,12 +678,26 @@ class AgentAuthService:
# flows ignore a non-default cli_path and fall through to
# ``$PATH``, breaking installs that pin a specific binary.
backend_cfg = self._resolve_backend_config(backend)
- if backend_cfg is None:
+ # Compatibility projection can erase recovery provenance, so inventory
+ # validates persisted evidence even when a live backend object exists.
+ if strict or backend_cfg is None:
try:
from config.v2_config import V2Config
- backend_cfg = getattr(V2Config.load().agents, backend, None)
+ config = V2Config.load(persist_migrations=False) if strict else V2Config.load()
+ if strict and (
+ config.whole_config_recovery
+ or any(section in {"agents", f"agents.{backend}", f"agents.{backend}.cli_path"}
+ for section in config.recovered_sections)
+ ):
+ raise NativeMigrationBlockedError("process_inventory_unavailable", (backend,))
+ if backend_cfg is None:
+ backend_cfg = getattr(config.agents, backend, None)
except Exception: # noqa: BLE001
+ if strict:
+ # A missing/unknown configured identity is not evidence of
+ # native idleness. Do not expose config error payloads.
+ raise NativeMigrationBlockedError("process_inventory_unavailable", (backend,)) from None
logger.debug(
"Failed to load persisted %s config for Settings probe",
backend,
@@ -823,6 +952,14 @@ class AgentAuthService:
)
return
except Exception as err: # noqa: BLE001
+ if isinstance(err, NativeMigrationBlockedError) and err.reason == "native_auth_hub_owned":
+ # A native reset button would repeat the same refused write.
+ # Custody stays in Hub; tell the user where to manage it.
+ await self._send_message(
+ context,
+ self._t("command.setup.hubOwned", backend=resolved_backend),
+ )
+ return
logger.error("Agent auth setup failed to start for %s: %s", resolved_backend, err, exc_info=True)
await self._send_setup_start_failure(context, resolved_backend, str(err))
return
@@ -851,6 +988,18 @@ class AgentAuthService:
if flow.initiator_user_id != context.user_id:
await self._send_message(context, f"❌ {self._t('command.setup.notFlowOwner')}")
return
+ try:
+ await self._run_flow_submission(flow, self._submit_code_owned(flow, context, code))
+ finally:
+ if (
+ flow.backend == "opencode"
+ and self._supports_direct_opencode_api_key_setup(flow.provider)
+ and not flow.awaiting_code
+ ):
+ await finish_native_operation(self._cleanup_native_flow(flow))
+ self._drop_flow(flow)
+
+ async def _submit_code_owned(self, flow: AgentAuthFlow, context: MessageContext, code: str) -> None:
if flow.backend == "claude":
if flow.claude_client is None:
await self._send_message(context, f"❌ {self._t('command.setup.codeNotSupported')}")
@@ -879,7 +1028,6 @@ class AgentAuthService:
await self._refresh_backend_runtime("opencode")
await self._clear_backend_sessions_for_context("opencode", context)
await self._send_message(context, f"✅ {self._t('command.setup.success', backend=flow.backend)}")
- self._drop_flow(flow)
return
if flow.pty_master_fd is None:
await self._send_message(context, f"❌ {self._t('command.setup.codeNotSupported')}")
@@ -888,7 +1036,7 @@ class AgentAuthService:
await self._send_message(context, f"❌ {self._t('command.setup.notAwaitingCode')}")
return
- await asyncio.to_thread(os.write, flow.pty_master_fd, f"{normalized_code}\n".encode("utf-8"))
+ await _native_auth_thread(os.write, flow.pty_master_fd, f"{normalized_code}\n".encode("utf-8"))
flow.awaiting_code = False
await self._send_message(context, f"✅ {self._t('command.setup.codeSubmitted', backend=flow.backend)}")
@@ -1131,7 +1279,7 @@ class AgentAuthService:
flow.expires_at_iso = (
datetime.now(timezone.utc) + timedelta(seconds=self.setup_timeout_seconds)
).isoformat()
- flow.waiter_task = asyncio.create_task(waiter)
+ flow.waiter_task = asyncio.create_task(self._owned_flow_waiter(flow, waiter))
def _remaining_flow_timeout(self, flow: AgentAuthFlow | WebAuthFlow) -> float:
"""Return the time left on the deadline advertised by this flow."""
@@ -1146,7 +1294,23 @@ class AgentAuthService:
except (TypeError, ValueError):
return self.setup_timeout_seconds
- async def _start_auth_flow(
+ async def _start_auth_flow(self, backend: str, **kwargs: Any) -> AgentAuthFlow | WebAuthFlow:
+ # Starting may already have launched a process or begun a file write.
+ # If the caller disappears, finish startup, then clean its owned flow.
+ task = asyncio.create_task(self._start_auth_flow_owned(backend, **kwargs))
+ try:
+ return await asyncio.shield(task)
+ except asyncio.CancelledError:
+ try:
+ flow = await finish_native_operation(task)
+ if isinstance(flow, WebAuthFlow):
+ await finish_native_operation(self._terminate_web_flow(flow, final_state="cancelled"))
+ else:
+ await finish_native_operation(self._terminate_flow(flow))
+ finally:
+ raise
+
+ async def _start_auth_flow_owned(
self,
backend: str,
*,
@@ -1167,18 +1331,23 @@ class AgentAuthService:
if existing is not None:
await self._terminate_flow(existing)
- provider = provider_id
- if backend == "opencode" and context is not None:
- provider = await self._resolve_opencode_provider(context)
- native_cli = backend != "opencode" or not (
- context is not None and self._supports_direct_opencode_api_key_setup(provider)
- )
- if native_cli:
- self._claim_shared_native_flow(
- backend,
- provider=provider,
- owner_ref=owner_ref,
+ lease = self._acquire_native_lease(backend, source_id=owner_ref)
+ try:
+ provider = provider_id
+ if backend == "opencode" and context is not None:
+ provider = await self._resolve_opencode_provider(context)
+ native_cli = backend != "opencode" or not (
+ context is not None and self._supports_direct_opencode_api_key_setup(provider)
)
+ if native_cli:
+ self._claim_shared_native_flow(
+ backend,
+ provider=provider,
+ owner_ref=owner_ref,
+ )
+ except BaseException:
+ lease.release()
+ raise
flow_id = uuid.uuid4().hex[:12]
if context is None:
@@ -1203,6 +1372,7 @@ class AgentAuthService:
provider=provider,
native_cli=native_cli,
)
+ flow.native_lease = lease
self._flow_registry.put(flow, flow_key=flow_key)
try:
if backend == "codex":
@@ -1227,6 +1397,7 @@ class AgentAuthService:
claude_kwargs = {
"force_reset": force_reset,
"login_with_claude_ai": claude_login_method != "console",
+ "owner_flow": flow,
}
if on_irreversible_start is not None:
claude_kwargs["on_irreversible_start"] = on_irreversible_start
@@ -1267,6 +1438,7 @@ class AgentAuthService:
)
self._arm_flow_waiter(flow, self._wait_for_completion(flow))
except BaseException:
+ await finish_native_operation(self._cleanup_native_flow(flow))
self._flow_registry.drop(flow)
raise
return flow
@@ -1304,6 +1476,7 @@ class AgentAuthService:
on_irreversible_start: Callable[
[], Callable[[], None] | None
] | None = None,
+ owner_flow: AgentAuthFlow | WebAuthFlow | None = None,
) -> tuple[ClaudeSDKClient, str, ClaudeOAuthAttempt]:
if not CLAUDE_SDK_AVAILABLE:
raise ModuleNotFoundError("claude_agent_sdk is required for Claude setup flows")
@@ -1319,10 +1492,16 @@ class AgentAuthService:
# OAuth flow must clear stale API-key settings before the control
# client or follow-up probes launch.
attempt = await self._begin_claude_oauth_attempt()
+ if owner_flow is not None:
+ owner_flow.claude_oauth_attempt = attempt
client = None
self._claude_control_flow_starts_in_flight += 1
try:
- client = await self._create_claude_control_client(context)
+ client = await self._create_claude_control_client(
+ context, **({"owner_flow": owner_flow} if owner_flow is not None else {})
+ )
+ if owner_flow is not None:
+ owner_flow.claude_client = client
register_claude_owned_process(client, owner=AVIBE_CLAUDE_AUTH_OWNER)
response = await self._send_claude_control_request(
client,
@@ -1332,9 +1511,10 @@ class AgentAuthService:
},
)
except Exception:
- await self._finish_claude_oauth_attempt(attempt, succeeded=False)
- if client is not None:
- await self._disconnect_claude_client(client)
+ if owner_flow is None:
+ await self._finish_claude_oauth_attempt(attempt, succeeded=False)
+ if client is not None:
+ await self._disconnect_claude_client(client)
raise
finally:
self._claude_control_flow_starts_in_flight = max(
@@ -1344,14 +1524,16 @@ class AgentAuthService:
manual_url = str(response.get("manualUrl") or "").strip()
if not manual_url:
- await self._finish_claude_oauth_attempt(attempt, succeeded=False)
- if client is not None:
- await self._disconnect_claude_client(client)
+ if owner_flow is None:
+ await self._finish_claude_oauth_attempt(attempt, succeeded=False)
+ if client is not None:
+ await self._disconnect_claude_client(client)
raise RuntimeError("Claude auth flow did not return a manual login URL")
return client, manual_url, attempt
async def _create_claude_control_client(
- self, context: Optional[MessageContext] = None
+ self, context: Optional[MessageContext] = None,
+ *, owner_flow: AgentAuthFlow | WebAuthFlow | None = None,
) -> ClaudeSDKClient:
session_handler = getattr(self.controller, "session_handler", None)
get_working_path = getattr(session_handler, "get_working_path", None) if session_handler else None
@@ -1409,6 +1591,9 @@ class AgentAuthService:
option_kwargs["cli_path"] = cli_override
client = ClaudeSDKClient(options=ClaudeAgentOptions(**option_kwargs))
+ if owner_flow is not None:
+ # Connect can spawn before failing: publish the cleanup owner first.
+ owner_flow.claude_client = client
await client.connect()
governor_from_controller(self.controller).apply_to_pid(
get_claude_client_pid(client),
@@ -1451,15 +1636,24 @@ class AgentAuthService:
}
await transport.write(json.dumps(message) + "\n")
- async def _disconnect_claude_client(self, client: ClaudeSDKClient) -> None:
+ async def _disconnect_claude_client(self, client: ClaudeSDKClient, *, strict: bool = False) -> None:
disconnect = getattr(client, "disconnect", None)
close = getattr(client, "close", None)
+ process = getattr(getattr(client, "_transport", None), "_process", None)
try:
if callable(disconnect):
await disconnect()
elif callable(close):
await close()
+ elif strict:
+ raise RuntimeError("Claude auth client has no disconnect operation")
+ if strict and process is not None and process.returncode is None:
+ await asyncio.wait_for(process.wait(), timeout=5)
+ if process.returncode is None:
+ raise RuntimeError("Claude auth process did not exit")
except Exception as exc: # noqa: BLE001
+ if strict:
+ raise
logger.warning("Error disconnecting Claude auth client: %s", exc)
async def _start_opencode_process(
@@ -1548,6 +1742,29 @@ class AgentAuthService:
except Exception as err: # noqa: BLE001
logger.info("Utility command raised for %s: %s", " ".join(cmd), err)
return False, str(err)
+ finally:
+ await finish_native_operation(self._stop_native_auth_process(process))
+
+ async def _stop_native_auth_process(self, process: Any) -> None:
+ """An exited utility/probe is required before giving up its lease."""
+ if process.returncode is None:
+ try:
+ process.terminate()
+ except ProcessLookupError:
+ pass
+ try:
+ await asyncio.wait_for(process.wait(), timeout=5)
+ except asyncio.TimeoutError:
+ process.kill()
+ await asyncio.wait_for(process.wait(), timeout=5)
+ if process.returncode is None:
+ raise RuntimeError("Native auth process did not exit")
+
+ async def _communicate_native_auth_probe(self, process: Any) -> tuple[bytes, Any]:
+ try:
+ return await asyncio.wait_for(process.communicate(), timeout=20)
+ finally:
+ await finish_native_operation(self._stop_native_auth_process(process))
async def _read_codex_output(
self,
@@ -1780,10 +1997,17 @@ class AgentAuthService:
)
finally:
if flow.claude_client is not None:
- await self._disconnect_claude_client(flow.claude_client)
+ if flow.native_lease is not None:
+ await self._disconnect_claude_client(flow.claude_client, strict=True)
+ flow.claude_client = None
+ else:
+ await self._disconnect_claude_client(flow.claude_client)
self._drop_flow(flow)
async def _verify_login(self, flow: AgentAuthFlow) -> tuple[bool, str]:
+ return await finish_native_operation(self._verify_login_owned(flow))
+
+ async def _verify_login_owned(self, flow: AgentAuthFlow) -> tuple[bool, str]:
backend = flow.backend
if backend == "codex":
binary = self._get_cli_binary("codex")
@@ -1794,7 +2018,7 @@ class AgentAuthService:
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
- stdout, _ = await process.communicate()
+ stdout, _ = await self._communicate_native_auth_probe(process)
text = stdout.decode("utf-8", errors="replace").strip()
return ("not logged in" not in text.lower(), text)
@@ -1807,7 +2031,7 @@ class AgentAuthService:
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
- stdout, _ = await process.communicate()
+ stdout, _ = await self._communicate_native_auth_probe(process)
text = stdout.decode("utf-8", errors="replace").strip()
if process.returncode and process.returncode != 0:
return False, self._describe_opencode_cli_failure(process.returncode, text)
@@ -1827,7 +2051,7 @@ class AgentAuthService:
stderr=asyncio.subprocess.STDOUT,
env=self._build_claude_full_subprocess_env(force_oauth=force_oauth),
)
- stdout, _ = await process.communicate()
+ stdout, _ = await self._communicate_native_auth_probe(process)
text = stdout.decode("utf-8", errors="replace").strip()
try:
payload = json.loads(text)
@@ -1867,7 +2091,7 @@ class AgentAuthService:
raise RuntimeError("OpenCode server does not support non-interactive auth setup.")
await setter(provider, api_key)
try:
- await asyncio.to_thread(
+ await _native_auth_thread(
remove_opencode_provider_api_key,
provider,
logger_instance=logger,
@@ -1884,7 +2108,7 @@ class AgentAuthService:
"""
try:
- await asyncio.to_thread(
+ await _native_auth_thread(
remove_opencode_provider_api_key,
provider,
logger_instance=logger,
@@ -1910,6 +2134,72 @@ class AgentAuthService:
return getattr(to_app_config(V2Config.load()), backend, None)
+ def reconcile_native_auth_snapshot(self, snapshot: dict[str, dict[str, Any]]) -> None:
+ """Mirror committed auth fields without invoking any runtime or native writer.
+
+ The coordinator owns retirement and admission. Preflight every known
+ consumer before changing any of them; plain mutable config fields are
+ updated in place so detached and shared aliases both lose stale keys.
+ """
+ from core.handlers.model_hub.service import V2ModelHubConfigStore
+
+ updates: dict[int, tuple[dict, dict]] = {}
+ missing = object()
+ try:
+ if not isinstance(snapshot, Mapping):
+ raise ValueError
+ for backend, values in snapshot.items():
+ fields = V2ModelHubConfigStore._NATIVE_AUTH_FIELDS.get(backend)
+ if fields is None or not isinstance(values, Mapping) or set(values) - set(fields):
+ raise ValueError
+
+ owners = [self.controller]
+ owners.extend(
+ getattr(self.controller, name, None)
+ for name in ("command_handler", "settings_handler", "message_handler", "session_handler")
+ )
+ agents = getattr(getattr(self.controller, "agent_service", None), "agents", {})
+ owners.extend(agents.values())
+ for backend, values in snapshot.items():
+ targets = []
+ for owner in owners:
+ if owner is None:
+ continue
+ config = getattr(owner, "config", None)
+ targets.extend((
+ getattr(config, backend, None),
+ getattr(getattr(config, "agents", None), backend, None),
+ getattr(owner, f"{backend}_config", None),
+ ))
+ if backend == "claude":
+ targets.append(getattr(getattr(owner, "claude_client", None), "config", None))
+ for target in targets:
+ if target is None:
+ continue
+ for name, value in values.items():
+ if inspect.getattr_static(target, name, missing) is missing:
+ # Codex's compat view has auth_mode, not stored keys.
+ continue
+ attributes = vars(target)
+ descriptor = inspect.getattr_static(type(target), name, None)
+ if (
+ type(attributes) is not dict or name not in attributes
+ or inspect.isdatadescriptor(descriptor)
+ or getattr(getattr(type(target), "__dataclass_params__", None), "frozen", False)
+ ):
+ raise ValueError
+ _, changes = updates.setdefault(id(target), (attributes, {}))
+ if name in changes and changes[name] != value:
+ raise ValueError
+ changes[name] = copy.deepcopy(value)
+ except Exception:
+ # Config descriptors and values must never appear in an error.
+ raise ValueError("Native authentication consumers cannot be reconciled") from None
+ for attributes, changes in updates.values():
+ # Only preflighted plain instance fields reach this non-callback
+ # write. No setter, native I/O or config persistence can run here.
+ attributes.update(changes)
+
def _load_saved_enabled_backends(self) -> list[str] | None:
try:
from config.v2_config import V2Config
@@ -2146,28 +2436,14 @@ class AgentAuthService:
return mapped if mapped in CLAUDE_LOGIN_METHODS else None
async def _terminate_flow(self, flow: AgentAuthFlow) -> None:
- await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)
if flow.waiter_task and not flow.waiter_task.done():
- flow.waiter_task.cancel()
+ self._cancel_flow_waiter(flow)
try:
await flow.waiter_task
except asyncio.CancelledError:
pass
- if flow.reader_task and not flow.reader_task.done():
- flow.reader_task.cancel()
- try:
- await flow.reader_task
- except asyncio.CancelledError:
- pass
- if flow.process is not None and flow.process.returncode is None:
- flow.process.terminate()
- try:
- await asyncio.wait_for(flow.process.wait(), timeout=5)
- except asyncio.TimeoutError:
- flow.process.kill()
- await flow.process.wait()
- if flow.claude_client is not None:
- await self._disconnect_claude_client(flow.claude_client)
+ if flow.native_lease is not None or flow.waiter_task is None:
+ await finish_native_operation(self._cleanup_native_flow(flow))
self._drop_flow(flow)
async def _terminate_process_for_timeout(self, flow: AgentAuthFlow) -> None:
@@ -2186,6 +2462,12 @@ class AgentAuthService:
await flow.process.wait()
def _drop_flow(self, flow: AgentAuthFlow) -> None:
+ if flow.waiter_task is not None and flow.native_lease is not None:
+ # The owning waiter performs strict cleanup before dropping the row.
+ return
+ if flow.waiter_task is None and flow.native_lease is not None:
+ flow.native_lease.release()
+ flow.native_lease = None
self._flow_registry.drop(flow)
# ------------------------------------------------------------------
@@ -2257,7 +2539,7 @@ class AgentAuthService:
)
except asyncio.CancelledError:
raise
- except BackendLoginInProgressError:
+ except (BackendLoginInProgressError, NativeMigrationBlockedError):
raise
except Exception as err: # noqa: BLE001
logger.error("Web auth start failed for %s: %s", backend, err, exc_info=True)
@@ -2277,6 +2559,18 @@ class AgentAuthService:
flow = self._web_flows.get(flow_id)
if flow is None:
return {"ok": False, "error": "flow_not_found"}
+ if flow.native_closing or (flow.submission_task is not None and not flow.submission_task.done()):
+ return {"ok": False, "error": "not_awaiting_code"}
+ if flow.backend == "opencode" and flow.callback_kind == "code":
+ if self._remaining_flow_timeout(flow) <= 0:
+ await self._terminate_web_flow(flow, final_state="failed", error="timed_out")
+ return {"ok": False, "error": "timed_out"}
+ # This branch only resolves the start-time waiter's future, with
+ # no I/O or yield. Keep cancel-before-dispatch admission atomic.
+ return await self._submit_web_code_owned(flow, code)
+ return await self._run_flow_submission(flow, self._submit_web_code_owned(flow, code))
+
+ async def _submit_web_code_owned(self, flow: WebAuthFlow, code: str) -> dict[str, Any]:
if flow.backend == "opencode":
if flow.callback_kind == "code":
if (
@@ -2287,9 +2581,6 @@ class AgentAuthService:
raw = (code or "").strip()
if not raw:
return {"ok": False, "error": "invalid_format"}
- if self._remaining_flow_timeout(flow) <= 0:
- await self._terminate_web_flow(flow, final_state="failed", error="timed_out")
- return {"ok": False, "error": "timed_out"}
# The start-time waiter keeps the same deadline and ownership.
# Resolving once before any await excludes duplicate submissions.
flow.awaiting_code = False
@@ -2349,6 +2640,8 @@ class AgentAuthService:
continue
if flow.state not in self._WEB_FLOW_TERMINAL_STATES:
continue
+ if flow.native_lease is not None:
+ continue
if flow.terminal_at is None:
flow.terminal_at = now
continue
@@ -2416,6 +2709,15 @@ class AgentAuthService:
flow.source_account_label = account_label
async def remove_web_auth(self, backend: str) -> dict[str, Any]:
+ if backend not in {"claude", "codex"}:
+ return {"ok": False, "error": "unsupported_backend"}
+ lease = self._acquire_native_lease(backend)
+ try:
+ return await finish_native_operation(self._remove_web_auth_owned(backend))
+ finally:
+ lease.release()
+
+ async def _remove_web_auth_owned(self, backend: str) -> dict[str, Any]:
"""Drop the stored credentials for a Claude/Codex backend.
Runs the backend's own ``logout`` subcommand so the on-disk state
@@ -2500,7 +2802,7 @@ class AgentAuthService:
hook = self._post_web_success_hook
if callable(hook):
try:
- await asyncio.to_thread(hook, backend)
+ await _native_auth_thread(hook, backend)
except Exception as err: # noqa: BLE001
logger.warning("post_web_success_hook failed after remove for %s: %s", backend, err)
# Surface logout failures even though V2Config was cleared. The
@@ -2524,7 +2826,16 @@ class AgentAuthService:
}
return {"ok": True}
- async def test_web_auth(
+ async def test_web_auth(self, backend: str, **kwargs: Any) -> dict[str, Any]:
+ if backend not in {"claude", "codex", "opencode"}:
+ return {"ok": False, "error": "unsupported_backend"}
+ lease = self._acquire_native_lease(backend)
+ try:
+ return await finish_native_operation(self._test_web_auth_owned(backend, **kwargs))
+ finally:
+ lease.release()
+
+ async def _test_web_auth_owned(
self,
backend: str,
*,
@@ -2836,6 +3147,23 @@ class AgentAuthService:
*,
model: str | None = None,
timeout: float = 60.0,
+ ) -> dict[str, Any]:
+ # A native connectivity probe can refresh subscription credentials.
+ # Hold the same ownership as login until its session cleanup settles.
+ lease = self._acquire_native_lease("opencode")
+ try:
+ return await finish_native_operation(
+ self._test_opencode_provider_owned(provider_id, model=model, timeout=timeout)
+ )
+ finally:
+ lease.release()
+
+ async def _test_opencode_provider_owned(
+ self,
+ provider_id: str,
+ *,
+ model: str | None = None,
+ timeout: float = 60.0,
) -> dict[str, Any]:
"""Probe a single OpenCode provider via the live ``opencode serve`` HTTP API.
@@ -3142,11 +3470,12 @@ class AgentAuthService:
flow = self._web_flows.get(flow_id)
if flow is None:
return {"ok": False, "error": "flow_not_found"}
- try:
- await self._terminate_web_flow(flow, final_state="cancelled")
- finally:
- async with self._flow_lock:
- self._flow_registry.drop(flow)
+ # Revoke a queued callback before yielding to the shielded cleanup task.
+ # Otherwise a just-submitted manual code can dispatch ahead of cancel.
+ self._cancel_flow_waiter(flow)
+ await finish_native_operation(self._terminate_web_flow(flow, final_state="cancelled"))
+ async with self._flow_lock:
+ self._flow_registry.drop(flow)
return {"ok": True}
async def _opencode_server(self):
@@ -3475,7 +3804,7 @@ class AgentAuthService:
flow.error = str(err)
finally:
if flow.claude_client is not None:
- await self._disconnect_claude_client(flow.claude_client)
+ await self._disconnect_claude_client(flow.claude_client, strict=flow.native_lease is not None)
flow.claude_client = None
async def _verify_web_login(
@@ -3557,7 +3886,7 @@ class AgentAuthService:
return
# Failure must reach the flow's terminal result. Credentials may have
# been persisted, but an unacknowledged/failed apply is not connection.
- await asyncio.to_thread(hook, backend)
+ await _native_auth_thread(hook, backend)
def _capture_codex_relay_for_oauth(self) -> tuple[dict | None, bool]:
"""Read the live relay identity before OAuth cleanup.
@@ -3601,7 +3930,7 @@ class AgentAuthService:
try:
from vibe.claude_config import apply_claude_auth
- await asyncio.to_thread(
+ await _native_auth_thread(
apply_claude_auth,
auth_mode="oauth",
api_key=None,
@@ -3617,7 +3946,7 @@ class AgentAuthService:
try:
from vibe.codex_config import apply_codex_auth
- await asyncio.to_thread(
+ await _native_auth_thread(
apply_codex_auth,
auth_mode="oauth",
api_key=None,
@@ -3635,12 +3964,28 @@ class AgentAuthService:
try:
from vibe.claude_config import read_claude_oauth_settings_backup
- return await asyncio.to_thread(read_claude_oauth_settings_backup)
+ return await _native_auth_thread(read_claude_oauth_settings_backup)
except Exception as err: # noqa: BLE001
logger.warning("Failed to read pending Claude OAuth settings backup: %s", err)
return None
- def _recover_interrupted_claude_oauth_settings_backup(self) -> None:
+ def _recover_interrupted_claude_oauth_settings_backup(
+ self, *, lease: NativeCredentialLease | None = None
+ ) -> None:
+ if lease is not None:
+ lease.assert_auth_custody("claude")
+ self._recover_interrupted_claude_oauth_settings_backup_owned()
+ return
+ try:
+ with NativeCredentialLease(("claude",)) as owned:
+ owned.assert_auth_custody("claude")
+ self._recover_interrupted_claude_oauth_settings_backup_owned()
+ except NativeMigrationBlockedError:
+ # Another process owns a live flow, or takeover recovery owns the
+ # snapshot. This constructor must not restore over that owner.
+ logger.info("Deferring Claude settings recovery to the native credential owner")
+
+ def _recover_interrupted_claude_oauth_settings_backup_owned(self) -> None:
try:
from vibe.claude_config import (
clear_claude_oauth_settings_backup,
@@ -3670,7 +4015,7 @@ class AgentAuthService:
try:
from vibe.claude_config import write_claude_oauth_settings_backup
- await asyncio.to_thread(write_claude_oauth_settings_backup, settings_backup)
+ await _native_auth_thread(write_claude_oauth_settings_backup, settings_backup)
return True
except Exception as err: # noqa: BLE001
raise RuntimeError(
@@ -3682,7 +4027,7 @@ class AgentAuthService:
try:
from vibe.claude_config import clear_claude_oauth_settings_backup
- await asyncio.to_thread(clear_claude_oauth_settings_backup)
+ await _native_auth_thread(clear_claude_oauth_settings_backup)
except Exception as err: # noqa: BLE001
logger.warning("Failed to clear pending Claude OAuth settings backup: %s", err)
@@ -3695,7 +4040,7 @@ class AgentAuthService:
try:
from vibe.claude_config import read_claude_settings_env
- settings_backup = await asyncio.to_thread(read_claude_settings_env)
+ settings_backup = await _native_auth_thread(read_claude_settings_env)
except Exception as err: # noqa: BLE001
raise RuntimeError(
"Failed to read Claude Code settings env before OAuth flow; "
@@ -3715,7 +4060,7 @@ class AgentAuthService:
try:
from vibe.claude_config import restore_claude_settings_env
- await asyncio.to_thread(
+ await _native_auth_thread(
restore_claude_settings_env,
settings_backup,
)
@@ -3780,6 +4125,11 @@ class AgentAuthService:
attempt: ClaudeOAuthAttempt | None,
*,
succeeded: bool,
+ ) -> None:
+ await finish_native_operation(self._finish_claude_oauth_attempt_owned(attempt, succeeded=succeeded))
+
+ async def _finish_claude_oauth_attempt_owned(
+ self, attempt: ClaudeOAuthAttempt | None, *, succeeded: bool,
) -> None:
async with self._claude_oauth_lock:
if attempt is None or not attempt.active:
@@ -3822,7 +4172,19 @@ class AgentAuthService:
return str(err)
return None
- async def clear_claude_oauth_credentials_only(self) -> dict[str, Any]:
+ async def clear_claude_oauth_credentials_only(
+ self, *, lease: NativeCredentialLease | None = None
+ ) -> dict[str, Any]:
+ owned = lease is None
+ lease = self._acquire_native_lease("claude") if owned else lease
+ try:
+ lease.assert_auth_custody("claude")
+ return await finish_native_operation(self._clear_claude_oauth_credentials_owned())
+ finally:
+ if owned:
+ lease.release()
+
+ async def _clear_claude_oauth_credentials_owned(self) -> dict[str, Any]:
"""Remove Claude Code account tokens without changing API-key mode.
Claude Code reapplies ``settings.json`` env values at startup. To make
@@ -3837,7 +4199,7 @@ class AgentAuthService:
)
try:
- settings_backup = await asyncio.to_thread(read_claude_settings_env)
+ settings_backup = await _native_auth_thread(read_claude_settings_env)
except Exception as err: # noqa: BLE001
detail = (
"Failed to read Claude Code settings before clearing OAuth "
@@ -3863,7 +4225,7 @@ class AgentAuthService:
env=logout_env,
)
try:
- await asyncio.to_thread(clear_claude_oauth_credentials_files)
+ await _native_auth_thread(clear_claude_oauth_credentials_files)
except Exception as err: # noqa: BLE001
logout_ok = False
logout_error = str(err)
@@ -4024,7 +4386,7 @@ class AgentAuthService:
# synchronous file I/O. Keep both the fresh-snapshot decision and
# the mutation inside the worker, but do not block the ASGI loop
# that services OAuth polling and unrelated UI requests.
- await asyncio.to_thread(update_config_fields, _apply_auth_fields)
+ await _native_auth_thread(update_config_fields, _apply_auth_fields)
if applied.get("skip"):
return
@@ -4064,6 +4426,19 @@ class AgentAuthService:
final_state: WebFlowState,
error: str | None = None,
) -> None:
+ await self._join_flow_submission(flow)
+ if flow.waiter_task is not None and flow.waiter_task is not asyncio.current_task():
+ if not flow.waiter_task.done():
+ self._cancel_flow_waiter(flow)
+ try:
+ await flow.waiter_task
+ except asyncio.CancelledError:
+ pass
+ if flow.native_lease is None:
+ if flow.state not in self._WEB_FLOW_TERMINAL_STATES:
+ flow.state = final_state
+ flow.error = error
+ return
if flow.reader_task and not flow.reader_task.done():
flow.reader_task.cancel()
try:
@@ -4071,7 +4446,7 @@ class AgentAuthService:
except asyncio.CancelledError:
pass
if flow.waiter_task and flow.waiter_task is not asyncio.current_task() and not flow.waiter_task.done():
- flow.waiter_task.cancel()
+ self._cancel_flow_waiter(flow)
try:
await flow.waiter_task
except asyncio.CancelledError:
@@ -4087,7 +4462,7 @@ class AgentAuthService:
except ProcessLookupError:
pass
if flow.claude_client is not None:
- await self._disconnect_claude_client(flow.claude_client)
+ await self._disconnect_claude_client(flow.claude_client, strict=flow.native_lease is not None)
flow.claude_client = None
if flow.submitted_code is not None:
flow.submitted_code.cancel()
@@ -4099,3 +4474,5 @@ class AgentAuthService:
flow.state = final_state
if error:
flow.error = error
+ if flow.waiter_task is not asyncio.current_task() and flow.native_lease is not None:
+ await finish_native_operation(self._cleanup_native_flow(flow))
diff --git a/core/backend_restart.py b/core/backend_restart.py
index 13bcc5848..2b28d6ec0 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -4,15 +4,337 @@ from __future__ import annotations
import asyncio
import inspect
+import json
import logging
import os
-from collections.abc import Awaitable, Callable
+import re
+import stat
+from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
+from contextlib import AsyncExitStack, asynccontextmanager
+from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
DEFAULT_DRAIN_TIMEOUT_SECONDS = 300.0
_POLL_INTERVAL_SECONDS = 0.1
+_NATIVE_BACKENDS = frozenset({"claude", "codex", "opencode"})
+
+
+class NativeMigrationBlockedError(RuntimeError):
+ """Credential-free refusal before native credential ownership can change."""
+
+ def __init__(self, reason: str, backends: tuple[str, ...], *, pids: tuple[int, ...] = ()) -> None:
+ super().__init__(reason)
+ self.reason = reason
+ self.backends = backends
+ self.pids = pids
+
+
+def pending_native_backends(directory: Path) -> set[str]:
+ """Read only the pending transaction envelope; corrupt state blocks all."""
+ try:
+ data = json.loads((directory / "current.json").read_text())
+ except FileNotFoundError:
+ return set()
+ except (OSError, ValueError):
+ return set(_NATIVE_BACKENDS)
+ if (
+ not isinstance(data, dict)
+ or type(data.get("version")) is not int
+ or data.get("version") != 1
+ or not isinstance(data.get("phase"), str)
+ or data.get("phase") not in {
+ "prepared", "withdrawn", "exposed", "reverting",
+ }
+ ):
+ return set(_NATIVE_BACKENDS)
+ blocked = data.get("backends")
+ if not isinstance(blocked, list) or not blocked or any(
+ not isinstance(name, str) or name not in _NATIVE_BACKENDS for name in blocked
+ ):
+ return set(_NATIVE_BACKENDS)
+ return set(blocked)
+
+
+class NativeCredentialLease:
+ """Non-reentrant, cross-process ownership of backend-native credentials.
+
+ Every acquire opens a separate file description (not a thread-reentrant
+ MigrationFileLock). Never unlink these files: waiters must share one inode.
+ An explicit lease may be passed to nested owned operations across threads.
+ """
+
+ def __init__(self, backends: tuple[str, ...], *, state_dir: Path | None = None) -> None:
+ from config.paths import get_state_dir
+
+ if not backends or any(name not in _NATIVE_BACKENDS for name in backends):
+ raise ValueError("Unsupported native credential backend")
+ self.backends = tuple(sorted(set(backends)))
+ self.directory = (state_dir if state_dir is not None else get_state_dir()) / "native-takeover"
+ self._handles: list[Any] = []
+
+ def acquire(self, *, recovery: bool = False) -> NativeCredentialLease:
+ from storage.lock import _try_lock
+
+ if self._handles:
+ raise RuntimeError("Native credential lease is not reentrant")
+ try:
+ self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
+ directory_stat = self.directory.lstat()
+ if not stat.S_ISDIR(directory_stat.st_mode) or (
+ hasattr(os, "getuid") and directory_stat.st_uid != os.getuid()
+ ):
+ raise OSError("Unsafe native lease directory")
+ for backend in self.backends:
+ fd = os.open(
+ self.directory / f"{backend}.lock",
+ os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0),
+ 0o600,
+ )
+ handle = os.fdopen(fd, "a+b")
+ self._handles.append(handle)
+ info = os.fstat(handle.fileno())
+ if (
+ not stat.S_ISREG(info.st_mode)
+ or info.st_nlink != 1
+ or (hasattr(os, "getuid") and info.st_uid != os.getuid())
+ or info.st_mode & 0o077
+ ):
+ raise OSError("Unsafe native lease file")
+ if not _try_lock(handle):
+ raise NativeMigrationBlockedError("native_auth_in_progress", (backend,))
+ if not recovery:
+ if pending_native_backends(self.directory).intersection(self.backends):
+ raise NativeMigrationBlockedError("migration_recovery_pending", self.backends)
+ return self
+ except BaseException:
+ self.release()
+ raise
+
+ def assert_owned(self, backend: str) -> None:
+ if backend not in self.backends or len(self._handles) != len(self.backends):
+ raise RuntimeError("Native credential operation has no ownership")
+
+ def assert_auth_custody(self, backend: str, *, source_id: str | None = None) -> None:
+ """Authorize a native writer from durable routing, while holding its lease.
+
+ Runtime enablement is not credential ownership. A Hub backend may
+ maintain only the explicitly bound, retained native subscription;
+ generic Settings/IM login and API-key writes must use Hub instead.
+ Read without load-time migration writes: this is an admission check.
+ """
+ from config.v2_config import V2Config
+
+ self.assert_owned(backend)
+ try:
+ config = V2Config.load(persist_migrations=False)
+ except FileNotFoundError:
+ config = V2Config.default()
+ except (OSError, TypeError, ValueError):
+ raise NativeMigrationBlockedError("config_recovery", (backend,)) from None
+ if config.load_warnings:
+ raise NativeMigrationBlockedError("config_recovery", (backend,))
+ hub = config.model_hub
+ if hub.agents[backend].mode == "direct":
+ return
+ vendor = {"claude": "anthropic", "codex": "openai"}.get(backend)
+ if source_id is not None and vendor is not None and any(
+ source.id == source_id
+ and source.vendor == vendor
+ and source.kind == "subscription"
+ and source.supply_channel == "native_cli"
+ for source in hub.sources
+ ):
+ return
+ raise NativeMigrationBlockedError("native_auth_hub_owned", (backend,))
+
+ def release(self) -> None:
+ # Closing the descriptor releases the OS lock, including on Windows.
+ while self._handles:
+ self._handles.pop().close()
+
+ def __enter__(self) -> NativeCredentialLease:
+ return self.acquire()
+
+ def __exit__(self, *_: Any) -> None:
+ self.release()
+
+
+async def finish_native_operation(awaitable: Awaitable[Any]) -> Any:
+ """Keep ownership until a started operation settles, even on cancellation.
+
+ In particular, cancelling asyncio.to_thread does not stop its writer.
+ """
+ task = asyncio.ensure_future(awaitable)
+ cancelled = False
+ while True:
+ try:
+ result = await asyncio.shield(task)
+ break
+ except asyncio.CancelledError:
+ if task.cancelled():
+ raise
+ cancelled = True
+ continue
+ except BaseException:
+ # shield retrieved the worker exception; do not leave a writer.
+ raise
+ if cancelled:
+ raise asyncio.CancelledError
+ return result
+
+
+def _native_executable_backend(executable: str, binaries: Mapping[str, str]) -> str | None:
+ name = executable.replace("\\", "/").rsplit("/", 1)[-1].lower()
+ for backend, binary in binaries.items():
+ if executable == binary or name in {backend, f"{backend}.exe"}:
+ return backend
+ normalized = executable.replace("\\", "/").lower()
+ if backend == "claude" and normalized.endswith("/@anthropic-ai/claude-code/cli.js"):
+ return backend
+ if backend == "codex" and normalized.endswith("/@openai/codex/bin/codex.js"):
+ return backend
+ if backend == "opencode" and normalized.endswith("/opencode-ai/bin/opencode"):
+ return backend
+ return None
+
+
+def _native_process_backend(command: list[str], binaries: Mapping[str, str]) -> str | None:
+ """Match a direct executable or interpreter entrypoint, never script arguments."""
+ if not command:
+ return None
+ direct = _native_executable_backend(command[0], binaries)
+ if direct:
+ return direct
+ name = command[0].replace("\\", "/").rsplit("/", 1)[-1].lower().removesuffix(".exe")
+ if re.fullmatch(r"(?:pythonw?|pypy)(?:\d+(?:\.\d+)*)?", name):
+ family = "python"
+ values = {"--check-hash-based-pycs"}
+ flags = set()
+ elif name.lstrip("-") in {"sh", "bash", "dash", "zsh", "ksh", "ash"}:
+ family = "shell"
+ values = {"--rcfile", "--init-file"}
+ flags = {"--noprofile", "--norc", "--login", "--posix", "--restricted", "--verbose", "--debugger"}
+ elif name in {"node", "nodejs", "bun"}:
+ family = "javascript"
+ values = {
+ "--require", "--import", "--loader", "--experimental-loader", "--conditions",
+ "--env-file", "--env-file-if-exists", "--title", "--icu-data-dir",
+ "--openssl-config", "--diagnostic-dir", "--input-type", "--preload",
+ "--cwd", "--config", "--watch-path",
+ }
+ flags = {
+ "--inspect", "--inspect-brk", "--inspect-wait", "--trace-warnings",
+ "--no-warnings", "--enable-source-maps", "--experimental-strip-types",
+ "--watch", "--check", "--no-addons",
+ }
+ else:
+ return None
+
+ def unknown(index: int) -> None:
+ # Unknown startup syntax cannot establish that a possible native script
+ # is only data. Refuse this inventory rather than guess an idle backend.
+ # This is reached only BEFORE an entrypoint or non-script mode is found.
+ if any(_native_executable_backend(value, binaries) for value in command[index:]):
+ raise NativeMigrationBlockedError("process_inventory_unavailable", tuple(sorted(binaries)))
+
+ index = 1
+ bun_run = False
+ while index < len(command):
+ value = command[index]
+ if value == "--" or family == "shell" and value == "-":
+ return _native_executable_backend(command[index + 1], binaries) if index + 1 < len(command) else None
+ if value == "-" or value in {"--help", "--version"}:
+ return None
+ if name == "bun" and value == "run" and not bun_run:
+ bun_run = True
+ index += 1
+ continue
+ if not value.startswith("-") and not (family == "shell" and value.startswith("+")):
+ return _native_executable_backend(value, binaries)
+ option, separator, _ = value.partition("=")
+ if family == "javascript" and (
+ option in {"--eval", "--print"} or value.startswith(("-e", "-p")) or value in {"-h", "-v"}
+ ):
+ return None
+ if option in values:
+ index += 1 if separator else 2
+ continue
+ if option in flags:
+ index += 1
+ continue
+ if value.startswith("--"):
+ return unknown(index)
+ short = value[1:]
+ if family == "javascript":
+ if short[:1] in {"r", "C"}:
+ index += 2 if len(short) == 1 else 1
+ continue
+ return unknown(index)
+ for position, flag in enumerate(short):
+ if (
+ family == "python" and flag in "cmhV?"
+ or family == "shell" and value.startswith("-") and flag in "cs"
+ ):
+ return None # Code/module/stdin is not a script path or prompt.
+ if flag in ("WX" if family == "python" else "oO"):
+ if position == len(short) - 1:
+ index += 1 # The next token is this option's operand.
+ break
+ if flag not in ("bBdEiIOPqRsStuUvVx" if family == "python" else "abefhiklmnprtuvxBCEHPT"):
+ return unknown(index)
+ index += 1
+ return None
+
+
+def native_cli_processes(binaries: Mapping[str, str]) -> tuple[int, ...]:
+ """Read same-user process identities without reading environments or killing.
+
+ After managed retirement any matching process is a blocker, including login,
+ interactive CLIs and untracked descendants. An incomplete inventory is not
+ evidence that the native credential has no remaining reader.
+ """
+ import psutil
+
+ backends = tuple(sorted(binaries))
+ uid = os.getuid() if hasattr(os, "getuid") else None
+ owner_field = "uids" if uid is not None else "username"
+ try:
+ username = psutil.Process().username() if uid is None else None
+ processes = psutil.process_iter(["pid", owner_field, "name", "cmdline", "status"])
+ blockers: list[int] = []
+ for process in processes:
+ try:
+ info = process.info
+ if info.get("status") in {psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD}:
+ continue
+ owner = info.get(owner_field)
+ owner = getattr(owner, "real", None) if uid is not None else owner
+ if owner is not None and owner != (uid if uid is not None else username):
+ continue
+ command = info.get("cmdline")
+ if not command:
+ # A known other executable with inaccessible owner metadata
+ # is not a CLI match; same-user unreadable command lines are
+ # conservatively refused rather than silently skipped.
+ name = str(info.get("name") or "")
+ if owner is None and _native_process_backend([name], binaries) is None:
+ continue
+ raise NativeMigrationBlockedError("process_inventory_unavailable", backends)
+ if _native_process_backend(command, binaries) is not None:
+ if owner is None:
+ raise NativeMigrationBlockedError("process_inventory_unavailable", backends)
+ blockers.append(int(info["pid"]))
+ except psutil.NoSuchProcess:
+ continue
+ except (psutil.AccessDenied, KeyError, TypeError, ValueError):
+ raise NativeMigrationBlockedError("process_inventory_unavailable", backends) from None
+ return tuple(sorted(set(blockers)))
+ except psutil.NoSuchProcess:
+ raise NativeMigrationBlockedError("process_inventory_unavailable", backends) from None
+ except (psutil.Error, OSError, ValueError):
+ raise NativeMigrationBlockedError("process_inventory_unavailable", backends) from None
def _configured_drain_timeout() -> float:
@@ -34,6 +356,7 @@ class BackendRestartCoordinator:
*,
drain_timeout: float | None = None,
poll_interval: float = _POLL_INTERVAL_SECONDS,
+ process_inventory: Callable[[Mapping[str, str]], tuple[int, ...]] = native_cli_processes,
) -> None:
self.controller = controller
self._refresh = refresh
@@ -42,11 +365,187 @@ class BackendRestartCoordinator:
self._tasks: dict[str, asyncio.Task[None]] = {}
self._request_locks: dict[str, asyncio.Lock] = {}
self._outcomes: dict[str, dict[str, str]] = {}
+ self._migration_backends: set[str] = set()
+ self._migration_auth_owners: dict[str, tuple[asyncio.Task, NativeCredentialLease]] = {}
+ self._process_inventory = process_inventory
+
+ def _blocked_backends(self) -> set[str]:
+ service = getattr(self.controller, "model_hub_service", None)
+ return set(getattr(service, "migration_blocked_backends", set())) | pending_native_backends(
+ self._native_state_dir() / "native-takeover"
+ )
+
+ def _native_state_dir(self) -> Path:
+ from config.paths import get_state_dir
+
+ service = getattr(self.controller, "model_hub_service", None)
+ event_path = getattr(getattr(service, "events", None), "path", None)
+ return Path(event_path).parent if isinstance(event_path, (str, Path)) else get_state_dir()
+
+ def restore_migration_blocks(self) -> None:
+ """Apply recovered durable exclusions before any producer is admitted."""
+ for backend in self._blocked_backends():
+ self.controller.agent_service.begin_backend_drain(backend)
+ self.controller.session_turns.begin_backend_drain(backend)
+
+ @staticmethod
+ def _migration_targets(backends: tuple[str, ...]) -> tuple[str, ...]:
+ if not isinstance(backends, tuple) or any(backend not in _NATIVE_BACKENDS for backend in backends):
+ raise ValueError("Unsupported native migration backend")
+ return tuple(sorted(set(backends)))
+
+ def assert_native_auth_available(self, backend: str) -> None:
+ if backend in self._migration_backends or backend in self._blocked_backends():
+ raise NativeMigrationBlockedError("migration_in_progress", (backend,))
+
+ def _assert_no_native_login(self, targets: tuple[str, ...]) -> None:
+ auth_service = getattr(self.controller, "agent_auth_service", None)
+ flows = getattr(auth_service, "_flows_by_id", {})
+ for backend in targets:
+ if any(
+ getattr(flow, "backend", None) == backend
+ and getattr(flow, "state", "starting") not in {"success", "failed", "cancelled"}
+ for flow in flows.values()
+ ):
+ raise NativeMigrationBlockedError("native_auth_in_progress", (backend,))
+
+ def _native_binaries(self, targets: tuple[str, ...]) -> dict[str, str]:
+ result: dict[str, str] = {}
+ config = getattr(self.controller, "config", None)
+ resolve = getattr(getattr(self.controller, "agent_auth_service", None), "_get_cli_binary", None)
+ for backend in targets:
+ if callable(resolve):
+ # This existing owner handles raw/compat config and reloads a
+ # configured path omitted by a disabled compatibility backend.
+ result[backend] = str(resolve(backend, strict=True))
+ continue
+ backend_config = getattr(config, backend, None) or getattr(getattr(config, "agents", None), backend, None)
+ result[backend] = str(
+ getattr(backend_config, "binary", None)
+ or getattr(backend_config, "cli_path", None)
+ or backend
+ )
+ return result
+
+ def reconcile_migration_auth(self, snapshot: dict[str, dict[str, Any]]) -> None:
+ """Update retired consumers only for the task holding this migration guard."""
+ try:
+ task = asyncio.current_task()
+ except RuntimeError:
+ task = None
+ owned = {
+ backend: lease for backend, (owner, lease) in self._migration_auth_owners.items()
+ if task is not None and owner is task
+ }
+ targets = tuple(sorted(owned))
+ if not owned or any(backend not in owned for backend in snapshot):
+ raise NativeMigrationBlockedError("native_reconciliation_unowned", targets)
+ ready = getattr(self.controller.agent_service, "is_backend_ready", None)
+ draining = getattr(self.controller.session_turns, "_draining_backends", ())
+ for backend, lease in owned.items():
+ lock = self._request_locks.get(backend)
+ if (
+ backend not in self._migration_backends
+ or lock is None or not lock.locked()
+ or not callable(ready) or ready(backend)
+ or backend not in draining
+ ):
+ raise NativeMigrationBlockedError("native_reconciliation_unowned", targets)
+ try:
+ lease.assert_owned(backend)
+ except RuntimeError:
+ raise NativeMigrationBlockedError("native_reconciliation_unowned", targets) from None
+ mirror = getattr(
+ getattr(self.controller, "agent_auth_service", None),
+ "reconcile_native_auth_snapshot", None,
+ )
+ if not callable(mirror):
+ raise NativeMigrationBlockedError("native_reconciliation_unavailable", targets)
+ mirror(snapshot)
+
+ @asynccontextmanager
+ async def migration_guard(
+ self, backends: tuple[str, ...]
+ ) -> AsyncIterator[Callable[[], Awaitable[None]]]:
+ """Yield an idle recheck under the same lease and closed admissions.
+
+ Call the recheck immediately before native withdrawal and CPA activation:
+ external CLIs do not participate in Avibe's advisory ownership protocol.
+ No external process is ever terminated by the check. Authentication
+ reconciliation is synchronous and available only to this guard's task
+ after retirement, while its existing lease and both gates remain owned.
+ """
+ targets = self._migration_targets(backends)
+ closed: list[str] = []
+ async with AsyncExitStack() as locks:
+ for backend in targets:
+ await locks.enter_async_context(self._request_locks.setdefault(backend, asyncio.Lock()))
+ restart = self._tasks.get(backend)
+ if restart is not None and not restart.done():
+ raise NativeMigrationBlockedError("backend_restart_in_progress", (backend,))
+ self._assert_no_native_login(targets)
+ lease = NativeCredentialLease(targets, state_dir=self._native_state_dir()).acquire(recovery=True)
+ locks.callback(lease.release)
+ self._migration_backends.update(targets)
+ try:
+ for backend in targets:
+ self.controller.agent_service.begin_backend_drain(backend)
+ self.controller.session_turns.begin_backend_drain(backend)
+ closed.append(backend)
+ for backend in targets:
+ await self.controller.agent_service.prepare_backend_restart(backend)
+ deadline = asyncio.get_running_loop().time() + self._drain_timeout
+ for backend in targets:
+ while await self._has_active_turns(backend):
+ if asyncio.get_running_loop().time() >= deadline:
+ raise NativeMigrationBlockedError("native_runtime_busy", (backend,))
+ await asyncio.sleep(self._poll_interval)
+ self._assert_no_native_login(targets)
+ for backend in targets:
+ agent = self.controller.agent_service.agents.get(backend)
+ if agent is None:
+ # A disabled backend has no controller-owned runtime.
+ # The mandatory process inventory still checks its CLI.
+ continue
+ retire = getattr(agent, "retire_for_native_migration", None)
+ if not callable(retire):
+ raise NativeMigrationBlockedError("native_retirement_unavailable", (backend,))
+ try:
+ await finish_native_operation(retire())
+ except Exception:
+ raise NativeMigrationBlockedError("native_retirement_failed", (backend,)) from None
+ async def verify_idle() -> None:
+ for backend in targets:
+ lease.assert_owned(backend)
+ if await self._has_active_turns(backend):
+ raise NativeMigrationBlockedError("native_runtime_busy", (backend,))
+ self._assert_no_native_login(targets)
+ pids = await asyncio.to_thread(self._process_inventory, self._native_binaries(targets))
+ if pids:
+ raise NativeMigrationBlockedError("external_native_processes", targets, pids=pids)
+
+ await verify_idle()
+ task = asyncio.current_task()
+ if task is None:
+ raise NativeMigrationBlockedError("native_reconciliation_unowned", targets)
+ for backend in targets:
+ self._migration_auth_owners[backend] = (task, lease)
+ yield verify_idle
+ finally:
+ for backend in targets:
+ self._migration_auth_owners.pop(backend, None)
+ self._migration_backends.difference_update(targets)
+ for backend in closed:
+ if backend not in self._blocked_backends():
+ self.controller.agent_service.end_backend_drain(backend)
+ await self.controller.session_turns.end_backend_drain(backend)
async def request_restart(self, backend: str) -> str:
"""Begin or join a restart and return without waiting for a long drain."""
+ self.assert_native_auth_available(backend)
lock = self._request_locks.setdefault(backend, asyncio.Lock())
async with lock:
+ self.assert_native_auth_available(backend)
existing = self._tasks.get(backend)
if existing is not None:
if not existing.done():
@@ -62,8 +561,9 @@ class BackendRestartCoordinator:
had_active_work = await self._has_active_turns(backend)
except BaseException as exc:
self._outcomes[backend] = {"state": "failed", "error": str(exc) or type(exc).__name__}
- agent_service.end_backend_drain(backend)
- await session_turns.end_backend_drain(backend, resume_deferred=False)
+ if backend not in self._blocked_backends():
+ agent_service.end_backend_drain(backend)
+ await session_turns.end_backend_drain(backend, resume_deferred=False)
raise
task = asyncio.create_task(self._run(backend), name=f"backend-restart:{backend}")
self._tasks[backend] = task
@@ -96,6 +596,8 @@ class BackendRestartCoordinator:
def snapshot(self, backend: str) -> dict[str, str | bool]:
"""Read application without starting another cutover or credential probe."""
+ if backend in self._blocked_backends() or backend in self._migration_backends:
+ return {"state": "draining"}
lock = self._request_locks.get(backend)
if lock is not None and lock.locked():
return {"state": "draining"}
@@ -164,8 +666,9 @@ class BackendRestartCoordinator:
finally:
# Runtime admission opens before durable queues are flushed. A flush
# therefore always enters the refreshed generation.
- self.controller.agent_service.end_backend_drain(backend)
- await self.controller.session_turns.end_backend_drain(backend, resume_deferred=refreshed)
+ if backend not in self._blocked_backends():
+ self.controller.agent_service.end_backend_drain(backend)
+ await self.controller.session_turns.end_backend_drain(backend, resume_deferred=refreshed)
async def wait(self, backend: str) -> None:
"""Testing/diagnostic hook: wait for the current restart, if any."""
diff --git a/core/controller.py b/core/controller.py
index 0b16c702c..46e0dfe0d 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -368,6 +368,10 @@ class Controller:
self,
self.agent_auth_service._apply_backend_runtime_refresh,
)
+ if self.model_hub_service is not None:
+ self.model_hub_service.migration_guard = self.backend_restart_coordinator.migration_guard
+ self.model_hub_service.migration_reconcile_auth = self.backend_restart_coordinator.reconcile_migration_auth
+ self.backend_restart_coordinator.restore_migration_blocks()
self.vibe_agent_store = VibeAgentStore()
self.vibe_agent_store.ensure_builtin_default_agents(
@@ -2818,6 +2822,10 @@ class Controller:
logger.debug("IM runtime could not signal the event loop to stop", exc_info=True)
async def _restore_active_polls(self, platforms: set[str]) -> None:
+ coordinator = getattr(self, "backend_restart_coordinator", None)
+ if coordinator is not None and "opencode" in coordinator._blocked_backends():
+ coordinator.restore_migration_blocks()
+ return
opencode_agent = self.agent_service.agents.get("opencode")
if opencode_agent and hasattr(opencode_agent, "restore_active_polls"):
try:
@@ -2968,8 +2976,12 @@ class Controller:
await recover_model_hub()
except Exception:
logger.exception(
- "Model Hub runtime recovery failed; continuing without it"
+ "Model Hub runtime recovery failed; retaining blocked backend admission"
)
+ finally:
+ coordinator = getattr(self, "backend_restart_coordinator", None)
+ if coordinator is not None:
+ coordinator.restore_migration_blocks()
recover_deliveries = getattr(
self.session_turns,
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 28a16009e..311ab5b74 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -62,6 +62,14 @@ class RuntimePlatformUnsupportedError(RuntimeError):
"""The pinned managed runtime has no asset for the server host."""
+class OAuthCredentialRejectedError(RuntimeError):
+ """Authoritative rejection of a refresh grant, requiring new authorization.
+
+ An expired access token, generic 401, or profile-only permission failure
+ does not establish this outcome. Exceptions must carry no secret material.
+ """
+
+
@dataclass(frozen=True)
class SourceBinding:
"""Engine-side registration of one hub-channel source (projection of config)."""
@@ -441,15 +449,70 @@ class EngineAdapter(Protocol):
protocol: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
"""Store an API-key secret in the ENGINE-OWNED credential store and
return the opaque ``credential_ref``.
``secret`` is transient: the adapter must never log it; L2 must never
- persist it (config stores refs only). Hub OAuth credentials never pass
- through here — they are created engine-side by the OAuth flow and
- surfaced via ``OAuthFlowState.credential_ref``. Native OAuth material
- remains CLI-owned and has no ref on this seam."""
+ persist it (config stores refs only). When supplied, ``on_reserved`` is
+ called synchronously with the opaque ref after an atomic no-secret
+ reservation and before any secret bytes are written. A callback failure
+ forbids the write. Hub OAuth credentials never pass through here —
+ they are created engine-side by the OAuth flow and surfaced via
+ ``OAuthFlowState.credential_ref``."""
+ ...
+
+ async def provision_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ material: Mapping[str, object],
+ *,
+ on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
+ """Stage a native OAuth grant outside CPA's watched auth directory.
+
+ ``material`` is transient and must never cross the L2 config boundary.
+ Return a durable opaque ref, with the provider, source, and prefix
+ already bound. When supplied, ``on_reserved`` is called synchronously
+ with the opaque ref after an atomic no-secret reservation and before
+ any grant bytes are written. A callback failure forbids the write.
+ Neither provisioning nor a restart may expose the staged grant to CPA.
+ Only ``activate_oauth_credential`` transfers refresh ownership, after
+ the caller has durably withdrawn native ownership.
+ """
+ ...
+
+ async def activate_oauth_credential(self, credential_ref: str) -> None:
+ """Publish a staged grant without ever overwriting a rotated live grant.
+
+ Idempotent and cancellation-safe. The caller must persist an activation
+ intent first and must not restore old native tokens after this call may
+ have started. Preserve the only recovery handle on any failure.
+ """
+ ...
+
+ async def validate_oauth_credential(self, credential_ref: str) -> None:
+ """Require credential-specific upstream acceptance, not auth inventory.
+
+ Used for imported grants, whose origin is not a completed engine OAuth
+ flow. Does not generate inference. Raise a sanitized error on denied or
+ inconclusive authentication; never equate an auth-file upload or the
+ engine's serving-protocol pin with upstream acceptance.
+ """
+ ...
+
+ async def matches_api_key_credential(
+ self,
+ credential_ref: str,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> bool:
+ """Compare transient native material inside custody; return no secrets."""
...
async def retarget_api_key_credential(
@@ -484,8 +547,15 @@ class EngineAdapter(Protocol):
vendor: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
- """Provision an unbound credential for an unsaved observation."""
+ """Provision an unbound credential for an unsaved observation.
+
+ The optional callback has the same write-ahead semantics as the
+ permanent and OAuth provisioners. Callers that own transient cleanup
+ may journal the ref before the observation secret reaches disk.
+ """
...
async def cleanup_orphaned_oauth_material(self, credential_ref: str) -> bool:
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.py
index bb67666cc..71ecfe14a 100644
--- a/core/handlers/model_hub/migration.py
+++ b/core/handlers/model_hub/migration.py
@@ -1,14 +1,15 @@
-"""Read-only native-config discovery and copy-only Model Hub migration."""
+"""Native-config discovery and transactional Model Hub credential takeover."""
from __future__ import annotations
import asyncio
+import base64
import hashlib
import json
import os
import re
-from dataclasses import dataclass, field
-from datetime import datetime
+from dataclasses import dataclass, field, replace
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Awaitable, Callable, Literal, Mapping, Optional, Protocol, cast
@@ -16,26 +17,47 @@ from config.v2_config import (
ModelHubConfig,
ModelHubModelConfig,
ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
)
from core.handlers.model_hub.adapter import (
DiscoveredModel,
ObservationDiscovery,
+ ObservationOutcome,
+ OAuthCredentialRejectedError,
SourceObservation,
)
from core.handlers.model_hub.events import contains_credential_material
from core.handlers.model_hub.identifiers import canonical_model_id
from core.handlers.model_hub.reasoning_tiers import resolve_reasoning_tiers
+from core.handlers.model_hub.migration_files import (
+ claude_settings_paths,
+ codex_config_paths,
+ opencode_auth_path,
+ opencode_config_paths,
+ plan_native_cleanup,
+ read_native_config,
+ read_native_toml,
+)
+from core.handlers.model_hub.migration_journal import (
+ NativeFileEdit,
+ NativeTakeoverJournal,
+ TakeoverStateError,
+)
from vibe.backend_model_catalog import (
backend_model_entries,
bundled_catalog_reasoning_efforts_by_model,
load_bundled_catalog,
)
-from vibe.claude_config import read_claude_oauth_signed_in, read_claude_settings_env
-from vibe.codex_config import _load_auth, get_codex_config_paths, read_codex_auth_state
+from vibe.codex_config import (
+ read_codex_auth_state,
+)
+from vibe.native_oauth_store import (
+ NativeOAuthSnapshot,
+ apply_keychain_edit,
+ read_native_oauth,
+)
from vibe.opencode_config import (
get_opencode_custom_provider_adapter,
- load_first_opencode_user_config,
- read_opencode_provider_auth_entries,
)
MigrationAction = Literal["import", "controlled_import", "keep_native", "reauth"]
@@ -51,19 +73,42 @@ _OPENCODE_BUILTIN_PROTOCOLS: dict[
"openrouter": "openai_chat",
}
_OPENCODE_UNSUPPORTED_NATIVE_IDS = {"alibaba-cn", "poe"}
+# Pinned CPA ordinary-grant compatibility. Extra native scopes are permitted,
+# but the gateway does not promise to retain connector/plugin capabilities.
+_OAUTH_CLIENT_IDS = {
+ "codex": "app_EMoamEEZ73f0CkXaXp7hrann",
+ "claude": "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
+}
+_OAUTH_REFRESH_SCOPES = {
+ "codex": frozenset({"openid", "profile", "email"}),
+ "claude": frozenset({
+ "user:profile", "user:inference", "user:sessions:claude_code",
+ "user:mcp_servers", "user:file_upload",
+ }),
+}
class MigrationConflictError(ValueError):
pass
+class MigrationCredentialsInvalidError(RuntimeError):
+ """Custody transferred, but one or more grants require Hub reauthentication."""
+
+
class MigrationHost(Protocol):
store: Any
adapter: Any
+ revocations: Any
_mutation_lock: Any
now: Callable[[], datetime]
- migration_claude_oauth_probe: Optional[Callable[[], bool]]
migration_home: Optional[Path]
+ migration_project_roots: Callable[[], tuple[Path, ...]]
+ migration_journal: NativeTakeoverJournal
+ migration_blocked_backends: set[str]
+ migration_guard: Any
+ _migration_lock: Any
+ _engine_synced: bool
@staticmethod
def _clone_config(config: ModelHubConfig) -> ModelHubConfig: ...
@@ -77,17 +122,41 @@ class MigrationHost(Protocol):
self,
previous: ModelHubConfig,
updated: ModelHubConfig,
+ *,
+ rollback_on_sync_failure: bool = True,
) -> None: ...
+ async def _ensure_runtime_dependency(self) -> Any: ...
+
+ def _save_config(self, config: ModelHubConfig) -> ModelHubConfig: ...
+
+ def _reconcile_native_auth(self, backends: tuple[str, ...]) -> None: ...
+
+ async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None: ...
+
async def _rollback_credential(
self,
source_id: str,
credential_ref: str,
) -> None: ...
+ async def _provision_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ material: Mapping[str, object],
+ *, on_reserved: Callable[[str], None] | None = None,
+ ) -> str: ...
+
async def _require_proven_source_payload(
self,
payload: dict[str, object],
+ *, on_reserved: Callable[[str], None] | None = None,
+ ) -> SourceObservation: ...
+
+ async def _require_proven_observation(
+ self, vendor: str, base_url: str | None, credential_ref: str,
+ protocol_order: tuple[str, ...],
) -> SourceObservation: ...
def _apply_discovered_models(
@@ -135,12 +204,22 @@ class NativeMigrationItem:
base_url: Optional[str] = None
secret: Optional[str] = field(default=None, repr=False)
account_label: Optional[str] = None
+ native_provider_id: Optional[str] = field(default=None, repr=False)
manual_models: tuple[NativeManualModel, ...] = ()
# Already-masked credential text, produced by the same `mask_credential` the
# producer used for `masked_detail`. Carried as its own field so a client can
# render provider and key as separate elements without re-parsing the
# composed detail string; never holds plaintext.
masked_credential: Optional[str] = None
+ # Native OAuth material is process-local only. It is converted into the
+ # engine's auth-file shape before the source is persisted and is never
+ # serialized in the scan response.
+ oauth_material: Optional[dict[str, object]] = field(default=None, repr=False)
+ native_store_edit: Optional[dict[str, object]] = field(default=None, repr=False)
+ native_store_revision: Optional[str] = field(default=None, repr=False)
+ # 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
def to_payload(self) -> dict[str, object]:
# Presentation metadata is additive: `vendor` and `display_name` let a
@@ -198,103 +277,274 @@ def _safe_account_label(value: object) -> Optional[str]:
return candidate
-def _claude_items(
+def _oauth_field(payload: Mapping[str, object], *names: str) -> object:
+ for name in names:
+ value = payload.get(name)
+ if value is not None:
+ return value
+ return None
+
+
+def _oauth_text(payload: Mapping[str, object], *names: str) -> Optional[str]:
+ value = _oauth_field(payload, *names)
+ if not isinstance(value, str) or not value.strip():
+ return None
+ return value.strip()
+
+
+def _jwt_claims(token: str | None) -> dict[str, object]:
+ """Read local grant metadata, not an authentication or signature verdict."""
+ if not token:
+ return {}
+ parts = token.split(".")
+ if len(parts) != 3:
+ return {}
+ try:
+ claims = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4)))
+ except (ValueError, UnicodeError):
+ return {}
+ return claims if isinstance(claims, dict) else {}
+
+
+def _normalize_oauth_material(
+ *,
+ provider: Literal["claude", "codex"],
+ payload: Mapping[str, object],
+ account_id: Optional[str] = None,
+) -> Optional[dict[str, object]]:
+ """Convert native CLI OAuth JSON into the engine auth-file shape."""
+
+ nested = payload
+ if provider == "claude" and isinstance(payload.get("claudeAiOauth"), dict):
+ nested = cast(Mapping[str, object], payload["claudeAiOauth"])
+ if provider == "codex" and isinstance(payload.get("tokens"), dict):
+ nested = cast(Mapping[str, object], payload["tokens"])
+
+ # Official native stores often omit client/scope metadata. Their locator
+ # establishes the ordinary CLI grant; explicit contrary metadata must
+ # never be discarded and silently replaced with CPA's fixed defaults.
+ for metadata in (payload, nested):
+ for name in ("client_id", "clientId"):
+ if name in metadata and metadata[name] != _OAUTH_CLIENT_IDS[provider]:
+ return None
+ for name in ("scope", "scopes"):
+ if name not in metadata:
+ continue
+ scopes = metadata[name]
+ if isinstance(scopes, str):
+ granted = set(scopes.split())
+ elif isinstance(scopes, list) and all(isinstance(value, str) for value in scopes):
+ granted = set(scopes)
+ else:
+ return None
+ if not _OAUTH_REFRESH_SCOPES[provider].issubset(granted):
+ return None
+
+ access_token = _oauth_text(nested, "access_token", "accessToken")
+ refresh_token = _oauth_text(nested, "refresh_token", "refreshToken")
+ id_token = _oauth_text(nested, "id_token", "idToken")
+ # The gateway must own a refresh-capable grant after takeover. An access
+ # token without its refresh token would work only until its current expiry,
+ # then leave the user with a source that cannot be maintained.
+ if not refresh_token:
+ return None
+
+ material: dict[str, object] = {
+ "type": provider,
+ }
+ for target, value in (
+ ("access_token", access_token),
+ ("refresh_token", refresh_token),
+ ("id_token", id_token),
+ (
+ "last_refresh",
+ _oauth_field(nested, "last_refresh", "lastRefresh")
+ or _oauth_field(payload, "last_refresh", "lastRefresh"),
+ ),
+ ("email", _oauth_text(nested, "email") or _oauth_text(payload, "email")),
+ ("expired", _oauth_field(nested, "expired")),
+ ):
+ if value is not None:
+ material[target] = value
+ claims = _jwt_claims(id_token)
+ if provider == "codex":
+ auth_claims = claims.get("https://api.openai.com/auth")
+ if not account_id and isinstance(auth_claims, dict):
+ account_id = _oauth_text(auth_claims, "chatgpt_account_id")
+ # CPA's importer does not derive the account header from the id token.
+ if not account_id:
+ return None
+ material["account_id"] = account_id
+ email = _oauth_text(claims, "email")
+ if email:
+ material.setdefault("email", email)
+ if "expired" not in material:
+ expires_at = _oauth_field(nested, "expiresAt", "expires_at")
+ if isinstance(expires_at, (int, float)) and not isinstance(expires_at, bool):
+ # Claude's native expiresAt is epoch milliseconds.
+ seconds = expires_at / 1000 if "expiresAt" in nested else expires_at
+ else:
+ seconds = _jwt_claims(access_token).get("exp")
+ if isinstance(seconds, (int, float)) and not isinstance(seconds, bool):
+ try:
+ material["expired"] = datetime.fromtimestamp(
+ seconds, tz=timezone.utc
+ ).isoformat()
+ except (OverflowError, OSError, ValueError):
+ return None
+ if provider == "claude":
+ for target, names in (
+ ("account_uuid", ("account_uuid", "accountUuid")),
+ ("organization_uuid", ("organization_uuid", "organizationUuid")),
+ ("organization_name", ("organization_name", "organizationName")),
+ ("claude_device_ids", ("claude_device_ids", "claudeDeviceIds")),
+ ):
+ value = _oauth_field(nested, *names)
+ if value is not None:
+ material[target] = value
+ return material
+
+
+def _read_codex_oauth_material(
+ auth_data: Mapping[str, object],
+) -> Optional[dict[str, object]]:
+ tokens = auth_data.get("tokens")
+ if not isinstance(tokens, dict):
+ return None
+ account_id: Optional[str] = None
+ raw_account_id = tokens.get("account_id") or auth_data.get("account_id")
+ if isinstance(raw_account_id, str) and raw_account_id.strip():
+ account_id = raw_account_id.strip()
+ return _normalize_oauth_material(
+ provider="codex",
+ payload=auth_data,
+ account_id=account_id,
+ )
+
+
+def _native_store_items(
+ backend: Literal["claude", "codex"],
+ snapshot: NativeOAuthSnapshot | None,
*,
- home: Optional[Path],
mask_credential: Callable[[str], str],
- oauth_probe: Optional[Callable[[], bool]],
+ state: Mapping[str, object] | None = None,
) -> list[NativeMigrationItem]:
+ if snapshot is None:
+ return []
+ payload = snapshot.payload or {}
+ state = state or {}
+ vendor = "anthropic" if backend == "claude" else "openai"
+ oauth_protocol = "anthropic" if backend == "claude" else "openai_responses"
+ material = (
+ _normalize_oauth_material(provider="claude", payload=payload)
+ if backend == "claude" else _read_codex_oauth_material(payload)
+ ) if snapshot.exportable else None
+ secret = _oauth_text(payload, "OPENAI_API_KEY") if backend == "codex" and snapshot.exportable else None
+ placeholder = payload.get("store") == "keychain" and payload.get("status") == "metadata_only"
+ blocked = not snapshot.exportable and not placeholder
+ has_oauth = backend == "claude" or bool(payload.get("tokens"))
+ if has_oauth and material is None and not placeholder:
+ blocked = True
+ primary_id = f"mig_{_stable_suffix(backend, 'native-store', snapshot.revision)}"
items: list[NativeMigrationItem] = []
- env = read_claude_settings_env(home)
- api_key = env.get("ANTHROPIC_API_KEY")
- auth_token = env.get("ANTHROPIC_AUTH_TOKEN")
- base_url = env.get("ANTHROPIC_BASE_URL")
- if api_key:
- action: MigrationAction = "import"
- item_id, source_id = _ids(
- "claude",
- "api_key",
- "settings-env",
- action,
- _stable_suffix(api_key, base_url or ""),
- )
- detail = mask_credential(api_key)
- items.append(
- NativeMigrationItem(
- id=item_id,
- source_id=source_id,
- backend="claude",
- kind="api_key",
- masked_detail=detail,
- proposed_action=action,
- selected=True,
- notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
- vendor="anthropic",
- protocol="anthropic",
- display_name="Anthropic",
- base_url=base_url,
- secret=api_key,
- masked_credential=detail,
- )
+ if has_oauth or placeholder or blocked:
+ action: MigrationAction = "keep_native" if blocked else "import"
+ _, source_id = _ids(backend, "oauth_native", "native-store", action)
+ account = _safe_account_label(material.get("email")) if material else None
+ items.append(NativeMigrationItem(
+ id=primary_id, source_id=source_id, backend=backend,
+ kind="oauth_native", masked_detail=account or "",
+ proposed_action=action, selected=not blocked,
+ notes_key=_NATIVE_SUPPLY_NOTE, vendor=vendor,
+ protocol=cast(Any, oauth_protocol),
+ display_name="Claude" if backend == "claude" else "ChatGPT",
+ account_label=account, oauth_material=material,
+ native_provider_id=_oauth_text(state, "active_provider_id"),
+ native_store_edit=snapshot.keychain_edit,
+ native_store_revision=snapshot.revision,
+ native_store_placeholder=placeholder,
+ ))
+ if secret:
+ base_url = _oauth_text(state, "base_url")
+ protocol = "openai_chat" if state.get("wire_api") == "chat" else "openai_responses"
+ _, source_id = _ids(backend, "api_key", "native-store", "import")
+ # Metadata-only consent binds this same primary ID for an API-only bag.
+ item_id = primary_id if not items else f"mig_{_stable_suffix(primary_id, 'api_key')}"
+ detail = mask_credential(secret)
+ items.append(NativeMigrationItem(
+ id=item_id, source_id=source_id, backend=backend, kind="api_key",
+ masked_detail=detail, proposed_action="import", selected=True,
+ notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor=vendor, protocol=cast(Any, protocol), display_name="OpenAI",
+ base_url=base_url, secret=secret, masked_credential=detail,
+ native_provider_id=_oauth_text(state, "active_provider_id"),
+ native_store_edit=snapshot.keychain_edit,
+ native_store_revision=snapshot.revision,
+ ))
+ if backend == "codex":
+ routing_revision = _stable_suffix(
+ _oauth_text(state, "base_url") or "",
+ _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]
+ return items
- if auth_token:
- action = "reauth"
- item_id, source_id = _ids(
- "claude",
- "api_key",
- "settings-auth-token",
- action,
- _stable_suffix(auth_token, base_url or ""),
- )
- detail = mask_credential(auth_token)
- items.append(
- NativeMigrationItem(
- id=item_id,
- source_id=source_id,
- backend="claude",
- kind="api_key",
- masked_detail=detail,
- proposed_action=action,
- selected=False,
- notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
- vendor="anthropic",
- protocol="anthropic",
- display_name="Anthropic",
- base_url=base_url,
- masked_credential=detail,
- )
- )
- # Claude settings env takes precedence over the native OAuth store. A
- # leftover OAuth credential must not outrank the auth the CLI will use.
- if api_key or auth_token:
- return items
+def _blocked_item(backend: str, identity: str, reason: str = "config") -> NativeMigrationItem:
+ item_id, source_id = _ids(backend, "api_key", identity, "reauth")
+ return NativeMigrationItem(
+ id=item_id, source_id=source_id, backend=cast(Any, backend),
+ kind="api_key", masked_detail="", proposed_action="reauth",
+ selected=False, notes_key=f"settings.models.migration.blocked.{reason}",
+ vendor={"claude": "anthropic", "codex": "openai", "opencode": "opencode"}[backend],
+ protocol="anthropic" if backend == "claude" else "openai_responses",
+ display_name={"claude": "Claude Code", "codex": "Codex", "opencode": "OpenCode"}[backend],
+ )
+
- oauth_signed_in = read_claude_oauth_signed_in(home)
- if not oauth_signed_in and oauth_probe is not None:
+def _claude_items(
+ *,
+ home: Optional[Path],
+ mask_credential: Callable[[str], str],
+ allow_secret: bool = False,
+ project_roots: tuple[Path, ...] = (),
+) -> list[NativeMigrationItem]:
+ items: list[NativeMigrationItem] = []
+ for path in claude_settings_paths(home, project_roots):
try:
- oauth_signed_in = bool(oauth_probe())
- except Exception:
- oauth_signed_in = False
- if oauth_signed_in:
- action = "keep_native"
- item_id, source_id = _ids("claude", "oauth_native", "oauth", action)
- items.append(
- NativeMigrationItem(
- id=item_id,
- source_id=source_id,
- backend="claude",
- kind="oauth_native",
- masked_detail="",
- proposed_action=action,
- selected=True,
- notes_key=_NATIVE_SUPPLY_NOTE,
- vendor="anthropic",
- protocol="anthropic",
- display_name="Claude",
+ config = read_native_config(path)
+ except (TakeoverStateError, OSError):
+ items.append(_blocked_item("claude", str(path)))
+ continue
+ if config is None:
+ continue
+ env = config.get("env", {})
+ if not isinstance(env, dict):
+ items.append(_blocked_item("claude", str(path)))
+ continue
+ base_url = _oauth_text(env, "ANTHROPIC_BASE_URL")
+ api_key = _oauth_text(env, "ANTHROPIC_API_KEY")
+ if api_key:
+ item_id, source_id = _ids(
+ "claude", "api_key", str(path), "import",
+ _stable_suffix(api_key, base_url or ""),
)
- )
+ detail = mask_credential(api_key)
+ items.append(NativeMigrationItem(
+ id=item_id, source_id=source_id, backend="claude", kind="api_key",
+ masked_detail=detail, proposed_action="import", selected=True,
+ notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor="anthropic", protocol="anthropic", display_name="Anthropic",
+ base_url=base_url, secret=api_key, masked_credential=detail,
+ ))
+ if config.get("apiKeyHelper") or env.get("ANTHROPIC_AUTH_TOKEN") or env.get("CLAUDE_CODE_OAUTH_TOKEN"):
+ items.append(_blocked_item("claude", f"{path}:helper-or-token", "credential"))
+
+ items.extend(_native_store_items(
+ "claude", read_native_oauth("claude", home=home, allow_secret=allow_secret),
+ mask_credential=mask_credential,
+ ))
return items
@@ -302,90 +552,58 @@ def _codex_items(
*,
home: Optional[Path],
mask_credential: Callable[[str], str],
+ allow_secret: bool = False,
+ project_roots: tuple[Path, ...] = (),
) -> list[NativeMigrationItem]:
- _, auth_path = get_codex_config_paths(home)
- auth_data = _load_auth(auth_path)
- if not isinstance(auth_data, dict):
- return []
- state = read_codex_auth_state(home)
- items: list[NativeMigrationItem] = []
- raw_auth_mode = auth_data.get("auth_mode")
- auth_mode = raw_auth_mode.strip().lower() if isinstance(raw_auth_mode, str) else None
-
- api_key = auth_data.get("OPENAI_API_KEY")
- has_api_key = isinstance(api_key, str) and bool(api_key.strip())
- importable_api_key = state.get("file_store_active") is True and has_api_key
- api_key_is_active = auth_mode != "chatgpt" and importable_api_key
- oauth_is_active = auth_mode == "chatgpt" or (
- auth_mode != "apikey" and not importable_api_key
+ items = _native_store_items(
+ "codex", read_native_oauth("codex", home=home, allow_secret=allow_secret),
+ mask_credential=mask_credential, state=read_codex_auth_state(home),
)
- if api_key_is_active:
- assert isinstance(api_key, str)
- api_key = api_key.strip()
- base_url = state.get("base_url")
- if not isinstance(base_url, str) or not base_url.strip():
- base_url = None
- wire_api = state.get("wire_api")
- protocol = "openai_chat" if wire_api == "chat" else "openai_responses"
- item_id, source_id = _ids(
- "codex",
- "api_key",
- "auth-json-api-key",
- "import",
- _stable_suffix(api_key, base_url or "", protocol),
- )
- detail = mask_credential(api_key)
- items.append(
- NativeMigrationItem(
- id=item_id,
- source_id=source_id,
- backend="codex",
- kind="api_key",
- masked_detail=detail,
- proposed_action="import",
- selected=True,
- notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
- vendor="openai",
- protocol=protocol,
- display_name="OpenAI",
- base_url=base_url,
- secret=api_key,
- masked_credential=detail,
+ for path in codex_config_paths(home, project_roots):
+ try:
+ config = read_native_toml(path)
+ except (TakeoverStateError, OSError):
+ items.append(_blocked_item("codex", str(path)))
+ continue
+ if config is None:
+ continue
+ providers = config.get("model_providers", {})
+ if not isinstance(providers, dict):
+ items.append(_blocked_item("codex", str(path)))
+ continue
+ for provider_id, provider in providers.items():
+ if not isinstance(provider, dict):
+ continue
+ key = _oauth_text(provider, "experimental_bearer_token")
+ env_key = _oauth_text(provider, "env_key")
+ headers = provider.get("http_headers", {})
+ env_headers = provider.get("env_http_headers", {})
+ if (
+ (env_key and os.environ.get(env_key))
+ or env_headers
+ or (headers and (key or config.get("model_provider") == provider_id))
+ ):
+ # Header templates and shell-owned keys cannot be silently
+ # reinterpreted as an ordinary Authorization bearer grant.
+ items.append(_blocked_item("codex", f"{path}:{provider_id}", "environment"))
+ continue
+ if not key:
+ continue
+ base_url = _oauth_text(provider, "base_url")
+ protocol = "openai_chat" if provider.get("wire_api") == "chat" else "openai_responses"
+ item_id, source_id = _ids(
+ "codex", "api_key", f"{path}:{provider_id}", "import",
+ _stable_suffix(key, base_url or "", protocol),
)
- )
-
- tokens = auth_data.get("tokens")
- if not oauth_is_active or not isinstance(tokens, dict) or not any(
- isinstance(tokens.get(key), str) and bool(tokens[key].strip())
- for key in ("access_token", "refresh_token", "id_token")
- ):
- return items
-
- action: MigrationAction = "keep_native"
- item_id, source_id = _ids(
- "codex",
- "oauth_native",
- "auth-json",
- action,
- )
- account = state.get("chatgpt_account")
- account_label = _safe_account_label(account.get("email") if isinstance(account, dict) else None)
- items.append(
- NativeMigrationItem(
- id=item_id,
- source_id=source_id,
- backend="codex",
- kind="oauth_native",
- masked_detail=account_label or "",
- proposed_action=action,
- selected=True,
- notes_key=_NATIVE_SUPPLY_NOTE,
- vendor="openai",
- protocol="openai_responses",
- display_name="ChatGPT",
- account_label=account_label,
- )
- )
+ masked = mask_credential(key)
+ items.append(NativeMigrationItem(
+ id=item_id, source_id=source_id, backend="codex", kind="api_key",
+ masked_detail=masked, proposed_action="import", selected=True,
+ notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor="openai", protocol=protocol, display_name="OpenAI",
+ secret=key, base_url=base_url, masked_credential=masked,
+ native_provider_id=provider_id,
+ ))
return items
@@ -467,7 +685,7 @@ def _opencode_plaintext_key(value: object) -> Optional[str]:
if not isinstance(value, str) or not value.strip():
return None
candidate = value.strip()
- if re.fullmatch(r"\{env:[^{}]+\}", candidate):
+ if "{env:" in candidate or "{file:" in candidate:
return None
return candidate
@@ -476,42 +694,78 @@ def _opencode_items(
*,
home: Optional[Path],
mask_credential: Callable[[str], str],
+ project_roots: tuple[Path, ...] = (),
) -> list[NativeMigrationItem]:
- probe = load_first_opencode_user_config(home=home)
- provider_configs: dict[str, dict[str, Any]] = {}
- if isinstance(probe.config, dict):
- raw_providers = probe.config.get("provider")
- if isinstance(raw_providers, dict):
- provider_configs = {
- provider_id.strip().lower(): provider_config
- for provider_id, provider_config in raw_providers.items()
- if isinstance(provider_id, str) and provider_id.strip() and isinstance(provider_config, dict)
- }
- auth_entries = {
- provider_id.strip().lower(): entry
- for provider_id, entry in read_opencode_provider_auth_entries(home=home).items()
- if provider_id.strip()
- }
+ items: list[NativeMigrationItem] = []
+ try:
+ auth_entries = read_native_config(opencode_auth_path(home)) or {}
+ except (TakeoverStateError, OSError):
+ return [_blocked_item("opencode", "auth-file")]
provider_catalog = _load_opencode_provider_catalog(home)
+ seen_providers: set[str] = set()
+ for path in opencode_config_paths(home, project_roots):
+ try:
+ config = read_native_config(path, jsonc=True)
+ except (TakeoverStateError, OSError):
+ items.append(_blocked_item("opencode", str(path)))
+ continue
+ if config is None:
+ continue
+ provider_configs = config.get("provider", {})
+ if not isinstance(provider_configs, dict):
+ items.append(_blocked_item("opencode", str(path)))
+ continue
+ seen_providers.update(provider_configs)
+ relevant_auth = {key: value for key, value in auth_entries.items() if key in provider_configs}
+ items.extend(_opencode_candidates(
+ provider_configs, relevant_auth, provider_catalog, str(path), mask_credential,
+ ))
+ unseen_auth = {key: value for key, value in auth_entries.items() if key not in seen_providers}
+ items.extend(_opencode_candidates({}, unseen_auth, provider_catalog, "auth-file", mask_credential))
+ return items
+
+
+def _opencode_candidates(
+ provider_configs: dict, auth_entries: dict, provider_catalog: dict,
+ locator: str, mask_credential: Callable[[str], str],
+) -> list[NativeMigrationItem]:
provider_ids = set(provider_configs) | set(auth_entries)
items: list[NativeMigrationItem] = []
for provider_id in sorted(provider_ids):
if (
- not provider_id
+ not isinstance(provider_id, str) or not provider_id
or len(provider_id) > 64
or any(char not in "abcdefghijklmnopqrstuvwxyz0123456789_.-" for char in provider_id)
or not provider_id[0].isalnum()
or contains_credential_material(provider_id)
):
- continue
- if provider_id in _OPENCODE_UNSUPPORTED_NATIVE_IDS:
+ items.append(_blocked_item("opencode", f"{locator}:invalid-provider"))
continue
provider_config = provider_configs.get(provider_id, {})
+ if not isinstance(provider_config, dict):
+ items.append(_blocked_item("opencode", f"{locator}:{provider_id}"))
+ continue
options = provider_config.get("options")
if not isinstance(options, dict):
options = {}
+ key_setting = options.get("apiKey")
+ if isinstance(key_setting, str) and (
+ "{file:" in key_setting
+ or (
+ "{env:" in key_setting
+ and (
+ re.fullmatch(r"\{env:[^{}]+\}", key_setting) is None
+ or os.environ.get(key_setting[5:-1])
+ )
+ )
+ ):
+ items.append(_blocked_item("opencode", f"{locator}:{provider_id}:key-reference", "environment"))
+ continue
config_key = _opencode_plaintext_key(options.get("apiKey"))
auth_entry = auth_entries.get(provider_id, {})
+ if not isinstance(auth_entry, dict):
+ items.append(_blocked_item("opencode", f"{locator}:{provider_id}"))
+ continue
auth_key = (
_opencode_plaintext_key(auth_entry.get("key"))
if auth_entry.get("type") == "api"
@@ -519,6 +773,8 @@ def _opencode_items(
)
secret = config_key or auth_key
if secret is None:
+ if options.get("apiKey") or auth_entry:
+ items.append(_blocked_item("opencode", f"{locator}:{provider_id}", "credential"))
continue
raw_base_url = options.get("baseURL")
base_url = raw_base_url.strip() if isinstance(raw_base_url, str) and raw_base_url.strip() else None
@@ -528,16 +784,19 @@ def _opencode_items(
if isinstance(catalog_api, str) and catalog_api.strip():
base_url = catalog_api.strip()
protocol = _opencode_protocol(provider_id, provider_config, catalog_provider)
- if protocol is None:
- continue
- if base_url is None and provider_id not in {"anthropic", "openai"}:
+ if (
+ protocol is None or provider_id in _OPENCODE_UNSUPPORTED_NATIVE_IDS
+ or (base_url is None and provider_id not in {"anthropic", "openai"})
+ or (auth_entry and auth_entry.get("type") != "api")
+ ):
+ items.append(_blocked_item("opencode", f"{locator}:{provider_id}", "credential"))
continue
manual_models = _opencode_manual_models(provider_config)
action: MigrationAction = "import"
item_id, source_id = _ids(
"opencode",
"opencode_provider",
- provider_id,
+ f"{provider_id}:{locator}",
action,
_stable_suffix(
secret,
@@ -567,16 +826,62 @@ def _opencode_items(
masked_credential=masked_secret,
)
)
+ if auth_key and auth_key != secret:
+ # Preserve both settings and auth-store keys, even when one is
+ # currently shadowed. Cleanup cannot discard an unimported account.
+ alternate = items[-1]
+ masked = mask_credential(auth_key)
+ items.append(replace(
+ alternate, id=f"mig_{_stable_suffix(alternate.id, auth_key)}",
+ source_id=f"src_{_stable_suffix(alternate.source_id, auth_key)}",
+ secret=auth_key, masked_detail=f"{provider_id} · {masked}",
+ masked_credential=masked,
+ ))
return items
+def _deduplicate_opencode_items(
+ items: list[NativeMigrationItem],
+ validate_base_url: Callable[[object], Optional[str]] | None,
+) -> list[NativeMigrationItem]:
+ """One logical credential/target, with consent covering every native copy."""
+ groups: dict[tuple[str, str, str | None, str], list[NativeMigrationItem]] = {}
+ for item in items:
+ if item.kind == "opencode_provider" and item.proposed_action == "import" and item.secret:
+ target = validate_base_url(item.base_url) if validate_base_url else item.base_url
+ groups.setdefault((item.vendor, item.protocol, target, item.secret), []).append(item)
+ replacements: dict[str, NativeMigrationItem] = {}
+ duplicates: set[str] = set()
+ for group in groups.values():
+ if len(group) < 2:
+ continue
+ first = group[0]
+ models: dict[str, NativeManualModel] = {}
+ for item in group:
+ for model in item.manual_models:
+ # Keep the complete model union; the later configuration layer
+ # supplies a label when the same model is named in both.
+ models[model.id] = model
+ # Layer order also owns repeated model labels, so it is consent-bound.
+ revision = _stable_suffix(*(item.id for item in group))
+ replacements[first.id] = replace(
+ first, id=f"mig_{revision}", source_id=f"src_{revision}",
+ manual_models=tuple(models.values()),
+ )
+ duplicates.update(item.id for item in group[1:])
+ return [replacements.get(item.id, item) for item in items if item.id not in duplicates]
+
+
def scan_native_configs(
config: ModelHubConfig,
*,
mask_credential: Callable[[str], str],
home: Optional[Path] = None,
- claude_oauth_probe: Optional[Callable[[], bool]] = None,
validate_base_url: Optional[Callable[[object], Optional[str]]] = None,
+ legacy_auth: Mapping[str, Mapping[str, object]] | None = None,
+ secret_backends: tuple[str, ...] = (),
+ project_roots: tuple[Path, ...] = (),
+ clean_native_stores: Mapping[str, str] | None = None,
) -> list[NativeMigrationItem]:
"""Read native stores without modifying or deleting any path."""
@@ -584,35 +889,91 @@ def scan_native_configs(
*_claude_items(
home=home,
mask_credential=mask_credential,
- oauth_probe=claude_oauth_probe,
+ allow_secret="claude" in secret_backends,
+ project_roots=project_roots,
+ ),
+ *_codex_items(
+ home=home, mask_credential=mask_credential,
+ allow_secret="codex" in secret_backends,
+ project_roots=project_roots,
),
- *_codex_items(home=home, mask_credential=mask_credential),
- *_opencode_items(home=home, mask_credential=mask_credential),
+ *_opencode_items(home=home, mask_credential=mask_credential, project_roots=project_roots),
]
+ if home is None:
+ # The process cannot remove a key from the parent shell or its startup
+ # files. Do not claim complete native takeover while that precedence
+ # layer remains active, and never execute a helper to obtain its key.
+ inherited = {
+ "claude": ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN"),
+ "codex": ("OPENAI_API_KEY", "OPENAI_BASE_URL", "CODEX_API_KEY"),
+ "opencode": ("OPENCODE_CONFIG_CONTENT", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "OPENROUTER_API_KEY"),
+ }
+ for backend, names in inherited.items():
+ if any(os.environ.get(name) for name in names):
+ items.append(_blocked_item(backend, "inherited-environment", "environment"))
+ for backend, auth in (legacy_auth or {}).items():
+ if backend not in {"claude", "codex"}:
+ continue
+ secret = _oauth_text(auth, "api_key")
+ base_url = _oauth_text(auth, "base_url")
+ if not secret or any(
+ item.backend == backend and item.secret == secret and item.base_url == base_url
+ for item in items
+ ):
+ continue
+ item_id, source_id = _ids(
+ backend, "api_key", "avibe-config", "import",
+ _stable_suffix(secret, base_url or ""),
+ )
+ masked = mask_credential(secret)
+ items.append(NativeMigrationItem(
+ id=item_id, source_id=source_id, backend=cast(Any, backend),
+ kind="api_key", masked_detail=masked, proposed_action="import",
+ selected=True, notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,
+ vendor="anthropic" if backend == "claude" else "openai",
+ protocol="anthropic" if backend == "claude" else "openai_responses",
+ display_name="Anthropic" if backend == "claude" else "OpenAI",
+ secret=secret, base_url=base_url, masked_credential=masked,
+ ))
if validate_base_url is not None:
valid_items: list[NativeMigrationItem] = []
for item in items:
try:
validate_base_url(item.base_url)
except Exception:
+ valid_items.append(replace(
+ item, proposed_action="reauth", selected=False, secret=None,
+ base_url=None, notes_key="settings.models.migration.blocked.config",
+ ))
continue
valid_items.append(item)
items = valid_items
- existing_source_ids = {source.id for source in config.sources}
- existing_native_vendors = {
- source.vendor
+ items = _deduplicate_opencode_items(items, validate_base_url)
+ existing_native_sources = {
+ source.vendor: source
for source in config.sources
if source.kind == "subscription" and source.supply_channel == "native_cli"
}
- return [
- item
- for item in items
- if item.source_id not in existing_source_ids
- and not (
- item.proposed_action == "keep_native"
- and item.vendor in existing_native_vendors
- )
- ]
+ candidates: list[NativeMigrationItem] = []
+ for item in items:
+ if (
+ item.native_store_placeholder
+ and (clean_native_stores or {}).get(item.backend) == item.native_store_revision
+ ):
+ # A completed cleanup verified this exact metadata revision holds
+ # only unrelated native data (e.g. MCP OAuth). Do not read it again
+ # merely to rediscover the absence of subscription credentials.
+ continue
+ native_source = existing_native_sources.get(item.vendor)
+ if item.kind == "oauth_native" and native_source is not None:
+ candidates.append(replace(
+ item,
+ source_id=native_source.id,
+ id=f"mig_{_stable_suffix(item.id, native_source.id)}",
+ ))
+ continue
+ candidates.append(item)
+ return candidates
def _validated_source(
@@ -623,14 +984,21 @@ def _validated_source(
validate_base_url: Callable[[object], Optional[str]],
credential_ref: str | None = None,
masked_credential: str | None = None,
+ discovered: tuple[DiscoveredModel, ...] = (),
catalog_efforts_by_model: Mapping[str, tuple[str, ...]],
) -> ModelHubSourceConfig:
keep_native = item.proposed_action == "keep_native"
controlled = item.proposed_action == "controlled_import"
+ imported_oauth = item.kind == "oauth_native" and item.proposed_action == "import"
discovered_at = now.isoformat()
models = []
- if keep_native:
- for model_id in _native_model_ids(item.backend):
+ if keep_native or imported_oauth:
+ model_ids = (
+ tuple(model.id for model in discovered)
+ if imported_oauth and discovered
+ else _native_model_ids(item.backend)
+ )
+ for model_id in model_ids:
resolution = resolve_reasoning_tiers(
protocol=protocol,
model_id=model_id,
@@ -650,13 +1018,13 @@ def _validated_source(
"id": item.source_id,
"created_at": discovered_at,
"last_discovered_at": discovered_at if models else None,
- "kind": "subscription" if keep_native or controlled else "api_key",
+ "kind": "subscription" if keep_native or controlled or imported_oauth else "api_key",
"vendor": item.vendor,
"display_name": item.display_name,
"protocol": protocol,
"base_url": validate_base_url(item.base_url),
"supply_channel": "native_cli" if keep_native else "hub",
- "billing": "monthly" if keep_native or controlled else "metered",
+ "billing": "monthly" if keep_native or controlled or imported_oauth else "metered",
"state": {"status": "standby", "retry_at": None, "detail_key": None},
"usage": {
"cycle_used_pct": None,
@@ -669,30 +1037,418 @@ def _validated_source(
"account_label": item.account_label,
"masked_credential": masked_credential,
}
- return ModelHubSourceConfig.from_payload(payload)
+ try:
+ return ModelHubSourceConfig.from_payload(payload)
+ except ValueError:
+ # Canonical Source validation is the last input boundary before custody.
+ # Invalid native metadata must not escape as an unredacted server error.
+ raise MigrationConflictError from None
-def build_native_migration_source(
- item: NativeMigrationItem,
+def _native_auth_snapshot(host: MigrationHost, backends: tuple[str, ...]) -> dict:
+ reader = getattr(host.store, "native_auth_snapshot", None)
+ return reader(backends) if callable(reader) else {}
+
+
+def _ensure_takeover_placement(
+ config: ModelHubConfig, source: ModelHubSourceConfig, backend: str,
+) -> None:
+ """Identity reuse still owes the consenting backend a configured placement."""
+ if not config.source_eligible_for_backend(source, backend):
+ raise MigrationConflictError
+ agent = config.agents[backend]
+ if source.id not in agent.sources.order and not any(
+ hop.source_id == source.id for route in agent.routes.values() for hop in route.hops
+ ):
+ agent.sources.order.append(source.id)
+
+
+async def _prepare_takeover(
+ host: MigrationHost,
+ previous: ModelHubConfig,
+ selected: list[NativeMigrationItem],
*,
- now: datetime,
+ mask_credential: Callable[[str], str],
validate_base_url: Callable[[object], Optional[str]],
-) -> ModelHubSourceConfig:
- """Build the Source represented by one recognized native-login item."""
-
- if item.proposed_action != "keep_native":
+ consented: list[NativeMigrationItem] | None = None,
+ project_roots: tuple[Path, ...] = (),
+ retained_source_ids: tuple[str, ...] | None = None,
+ clean_native_stores: Mapping[str, str] | None = None,
+) -> dict[str, Any]:
+ """Stage all grants and durable before/after images, still native-owned."""
+ clean_native_stores = dict(clean_native_stores or {})
+ cleanup_items = [
+ *selected,
+ *(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)
+ updated = host._clone_config(previous)
+ provisioned: list[dict[str, str]] = []
+ source_ids: list[str] = list(retained_source_ids or ())
+ catalog = bundled_catalog_reasoning_efforts_by_model()
+ handoff_attempted = False
+ try:
+ # A completed receipt can authorize cleanup of the exact old material
+ # reintroduced by an external writer. Its current Hub refs are already
+ # authoritative; never provision that old OAuth snapshot again.
+ for item in selected if retained_source_ids is None else ():
+ protocol = item.protocol
+ observation: SourceObservation | None = None
+ existing = next((source for source in updated.sources if source.id == item.source_id), None)
+ if item.kind != "oauth_native":
+ if not item.secret:
+ raise MigrationConflictError
+ # Old copy-only imports, including manually created sources,
+ # can retain their identity and routing without another key.
+ for candidate in updated.sources:
+ if (
+ candidate.kind == "api_key"
+ and candidate.vendor == item.vendor
+ and candidate.protocol == protocol
+ and candidate.base_url == validate_base_url(item.base_url)
+ and candidate.credential_ref
+ and await host._engine_call(host.adapter.matches_api_key_credential(
+ candidate.credential_ref, item.vendor, protocol,
+ item.secret, validate_base_url(item.base_url),
+ ))
+ ):
+ # Identity reuse is not current authentication proof.
+ # Observe the exact existing target/ref without changing
+ # its inventory, state, or user-owned routes.
+ await host._require_proven_observation(
+ candidate.vendor, candidate.base_url,
+ candidate.credential_ref, (candidate.protocol,),
+ )
+ _ensure_takeover_placement(updated, candidate, item.backend)
+ source_ids.append(candidate.id)
+ break
+ else:
+ observation = await host._require_proven_source_payload({
+ "vendor": item.vendor,
+ "base_url": validate_base_url(item.base_url),
+ "key": item.secret,
+ }, on_reserved=lambda ref: host.revocations.add("observation", ref))
+ protocol = cast(Any, observation.protocol)
+ if observation is None:
+ continue
+ if existing is not None and not (
+ existing.kind == "subscription"
+ and existing.supply_channel == "native_cli"
+ and item.kind == "oauth_native"
+ ):
+ # A different key at the same native locator is a new Source,
+ # not permission to replace an already edited Hub source.
+ item = replace(item, source_id=f"src_{_stable_suffix(item.id, 'takeover')}")
+ existing = None
+
+ def reserved(ref: str) -> None:
+ # Use the final Source identity so recovery retains current
+ # Hub grants instead of misclassifying them as orphaned keys.
+ host.revocations.add(item.source_id, ref)
+ provisioned.append({
+ "source_id": item.source_id, "credential_ref": ref,
+ "kind": "oauth" if item.kind == "oauth_native" else "api_key",
+ })
+
+ if item.kind == "oauth_native":
+ if not item.oauth_material:
+ raise MigrationConflictError
+ credential_ref = await host._engine_call(host._provision_oauth_credential(
+ item.source_id, item.vendor, item.oauth_material,
+ on_reserved=reserved,
+ ))
+ else:
+ credential_ref = await host._engine_call(host.adapter.provision_credential(
+ item.vendor, protocol, item.secret, validate_base_url(item.base_url),
+ on_reserved=reserved,
+ ))
+ if not provisioned or provisioned[-1]["credential_ref"] != credential_ref:
+ raise MigrationConflictError
+ source = _validated_source(
+ item, now=host.now(), protocol=protocol,
+ validate_base_url=validate_base_url, credential_ref=credential_ref,
+ masked_credential=mask_credential(item.secret) if item.secret else None,
+ catalog_efforts_by_model=catalog,
+ )
+ if observation is not None:
+ manual = [ModelHubModelConfig.from_payload({
+ "id": model.id, "display_name": model.display_name,
+ "origin": "manual", "reasoning_efforts": [], "discovered_at": None,
+ }) for model in item.manual_models]
+ host._apply_discovered_models(
+ source, manual, list(observation.models),
+ allow_empty=True, catalog_efforts_by_model=catalog,
+ )
+ if observation.discovery is not ObservationDiscovery.SUCCEEDED:
+ host._mark_source_unverified(source)
+ if existing is not None:
+ # Custody changes, not the identity/menu/orders the user owns.
+ replacement = existing.to_payload()
+ replacement.update({
+ "supply_channel": "hub", "credential_ref": credential_ref,
+ "account_label": item.account_label or existing.account_label,
+ "state": source.state.to_payload(),
+ })
+ if not existing.models:
+ replacement["models"] = [model.to_payload() for model in source.models]
+ source = ModelHubSourceConfig.from_payload(replacement)
+ updated.sources = [source if value.id == source.id else value for value in updated.sources]
+ _ensure_takeover_placement(updated, source, item.backend)
+ else:
+ 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)})
+ native_before = _native_auth_snapshot(host, tuple(backends))
+ credential_backends = {item.backend for item in selected}
+ native_after = {
+ backend: ({
+ name: ("oauth" if name == "auth_mode" else True if name == "auth_mode_set" else None)
+ for name in values
+ } if backend in credential_backends else dict(values))
+ for backend, values in native_before.items()
+ }
+ updated.enabled = True
+ for backend in backends:
+ updated.agents[backend].mode = "hub"
+ updated = ModelHubConfig.from_payload(updated.to_payload())
+ for edit in edits:
+ edit.check()
+ record = {
+ "version": 1, "phase": "prepared",
+ "items": [item.to_payload() for item in (consented or selected)],
+ "backends": backends, "source_ids": source_ids,
+ "credentials": provisioned,
+ "previous": previous.to_payload(), "updated": updated.to_payload(),
+ "files": [edit.to_payload() for edit in edits],
+ "native_before": native_before, "native_after": native_after,
+ "keychain": [],
+ "clean_native_stores": clean_native_stores,
+ }
+ seen_stores: set[str] = set()
+ for item in selected:
+ edit = item.native_store_edit
+ if not edit or item.native_store_revision in seen_stores:
+ continue
+ operations = [operation for operation in edit["operations"] if operation["kind"] == "keychain"]
+ if operations:
+ record["keychain"].append({**edit, "operations": operations})
+ seen_stores.add(item.native_store_revision)
+ # Replacement can succeed before a durability/readback failure is
+ # reported. From this attempt onward recovery owns the refs: the
+ # prepared record if present, otherwise their write-ahead revocations.
+ # Never revoke a grant that a possibly durable prepared record needs.
+ handoff_attempted = True
+ host.migration_journal.save(record)
+ return record
+ finally:
+ if not handoff_attempted:
+ for credential in reversed(provisioned):
+ await host._rollback_credential(
+ credential["source_id"],
+ credential["credential_ref"],
+ )
+
+
+async def _revert_takeover(host: MigrationHost, record: dict[str, Any]) -> None:
+ record["phase"] = "reverting"
+ host.migration_journal.save(record)
+ previous = ModelHubConfig.from_payload(record["previous"])
+ updated = ModelHubConfig.from_payload(record["updated"])
+ current = host.store.load()
+ if current.to_payload() not in (previous.to_payload(), updated.to_payload()):
raise MigrationConflictError
- return _validated_source(
- item,
- now=now,
- protocol=item.protocol,
- validate_base_url=validate_base_url,
- catalog_efforts_by_model=bundled_catalog_reasoning_efforts_by_model(),
- )
+ if current.to_payload() == updated.to_payload():
+ host._save_config(previous)
+ host._engine_synced = False
+ for raw in reversed(record["files"]):
+ NativeFileEdit.from_payload(raw).apply(reverse=True)
+ for edit in reversed(record.get("keychain", [])):
+ await asyncio.to_thread(apply_keychain_edit, edit, reverse=True)
+ for credential in reversed(record["credentials"]):
+ await host._rollback_credential(
+ credential["source_id"],
+ credential["credential_ref"],
+ )
+ host._reconcile_native_auth(tuple(record["backends"]))
+ host.migration_journal.forget()
+ host.migration_blocked_backends.difference_update(record["backends"])
-def _migration_rollback_id(source_id: str, credential_ref: str) -> str:
- return f"{source_id}:migration:{_stable_suffix(credential_ref)}"
+async def _verify_clean_native_stores(host: MigrationHost, record: Mapping[str, Any]) -> None:
+ for backend, revision in record.get("clean_native_stores", {}).items():
+ snapshot = await asyncio.to_thread(
+ read_native_oauth, backend, home=host.migration_home,
+ )
+ if (
+ snapshot is None or snapshot.revision != revision
+ or (snapshot.payload or {}).get("status") != "metadata_only"
+ ):
+ raise MigrationConflictError
+
+
+async def _resume_takeover(
+ host: MigrationHost,
+ record: dict[str, Any],
+ verify_idle: Callable[[], Awaitable[None]] | None = None,
+) -> tuple[int, list[dict]]:
+ if record["phase"] == "complete":
+ current = host.store.load()
+ if (
+ not set(record["source_ids"]).issubset(source.id for source in current.sources)
+ or any(current.agents[backend].mode != "hub" for backend in record["backends"])
+ or record.get("source_credentials") != {
+ source.id: source.credential_ref
+ for source in current.sources if source.id in record["source_ids"]
+ }
+ ):
+ raise MigrationConflictError
+ if record.get("outcome") == "needs_auth":
+ raise MigrationCredentialsInvalidError
+ if record.get("outcome") == "reauth_requested":
+ raise MigrationConflictError
+ return len(record["items"]), [
+ position for source_id in record["source_ids"] for position in host._added_to(source_id)
+ ]
+ host.migration_blocked_backends.update(record["backends"])
+ if verify_idle is None:
+ raise MigrationConflictError
+ if record["phase"] == "reverting":
+ await _revert_takeover(host, record)
+ raise MigrationConflictError
+ try:
+ await _verify_clean_native_stores(host, record)
+ if record["phase"] == "prepared":
+ # Installation and host compatibility are knowable before custody.
+ # Staged grants are outside CPA's watched directory, so ensuring
+ # the dependency here cannot publish them. An unavailable runtime
+ # must leave a working native login intact.
+ await host._ensure_runtime_dependency()
+ await verify_idle()
+ await _verify_clean_native_stores(host, record)
+ for edit in record.get("keychain", []):
+ await asyncio.to_thread(apply_keychain_edit, edit)
+ for raw in record["files"]:
+ NativeFileEdit.from_payload(raw).apply()
+ record["phase"] = "withdrawn"
+ host.migration_journal.save(record)
+ previous = ModelHubConfig.from_payload(record["previous"])
+ updated = ModelHubConfig.from_payload(record["updated"])
+ current = host.store.load()
+ terminal = record.get("terminal")
+ if current.to_payload() not in (
+ previous.to_payload(), updated.to_payload(),
+ terminal.get("config") if terminal else None,
+ ):
+ raise MigrationConflictError
+ if record["phase"] == "withdrawn":
+ await _verify_clean_native_stores(host, record)
+ # Save the decision without projecting staged grants into CPA.
+ # sync_sources is a runtime write, not a config-only operation.
+ host._save_config(updated)
+ host._engine_synced = False
+ host._reconcile_native_auth(tuple(record["backends"]))
+ # This durable marker precedes any credential exposure to CPA.
+ # An empty-container-only confirmation transferred no grant and
+ # changed no native bytes: keep it reversible through runtime start
+ # so a newly observed login can be presented for fresh consent.
+ if (
+ record["source_ids"] or record["credentials"]
+ or record["files"] or record.get("keychain")
+ or record["native_before"] != record["native_after"]
+ ):
+ record["phase"] = "exposed"
+ host.migration_journal.save(record)
+ else:
+ # Recovery may start with an equal persisted Hub config but stale
+ # launch consumers. Reconcile before any possible publication.
+ host._reconcile_native_auth(tuple(record["backends"]))
+ for raw in record["files"]:
+ NativeFileEdit.from_payload(raw).check(applied=True)
+ # Store mutations are replayable and must still match their cleaned
+ # state before a grant can be published to CPA.
+ if record.get("keychain"):
+ from vibe.native_oauth_store import check_keychain_edit
+
+ record.setdefault("clean_native_stores", {})
+ for edit in record["keychain"]:
+ snapshot = await asyncio.to_thread(
+ read_native_oauth, edit["backend"], home=host.migration_home,
+ )
+ # 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 and (snapshot.payload or {}).get("status") == "metadata_only":
+ record["clean_native_stores"][edit["backend"]] = snapshot.revision
+ await verify_idle()
+ if terminal:
+ return _finish_rejected_takeover(host, record)
+ for credential in record["credentials"]:
+ if credential["kind"] == "oauth":
+ await host._engine_call(host.adapter.activate_oauth_credential(credential["credential_ref"]))
+ await host._ensure_runtime_dependency()
+ # Always reconcile, including recovery with equal before/after config.
+ # _commit_synced intentionally skips equal bindings and cannot do this.
+ await host._sync_sources(updated)
+ host._engine_synced = True
+ await host._engine_call(host.adapter.start())
+ invalid_source_ids = []
+ for credential in record["credentials"]:
+ if credential["kind"] == "oauth":
+ if credential["source_id"] in record.get("validated_source_ids", []):
+ continue
+ async def validate(ref: str) -> bool:
+ try:
+ await host.adapter.validate_oauth_credential(ref)
+ except OAuthCredentialRejectedError:
+ return False
+ return True
+
+ if not await host._engine_call(validate(credential["credential_ref"])):
+ invalid_source_ids.append(credential["source_id"])
+ else:
+ record.setdefault("validated_source_ids", []).append(credential["source_id"])
+ host.migration_journal.save(record)
+ await _verify_clean_native_stores(host, record)
+ if invalid_source_ids:
+ terminal_config = host._clone_config(updated)
+ for source in terminal_config.sources:
+ if source.id in invalid_source_ids:
+ source.state = ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.oauth_expired",
+ )
+ # 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.
+ record["terminal"] = {
+ "invalid_source_ids": invalid_source_ids,
+ "config": terminal_config.to_payload(),
+ }
+ host.migration_journal.save(record)
+ return _finish_rejected_takeover(host, record)
+ host._reconcile_native_auth(tuple(record["backends"]))
+ host.migration_journal.complete(record)
+ host.migration_blocked_backends.difference_update(record["backends"])
+ return len(record["items"]), [
+ position for source_id in record["source_ids"] for position in host._added_to(source_id)
+ ]
+ except BaseException:
+ if record["phase"] in {"prepared", "withdrawn"}:
+ await _revert_takeover(host, record)
+ raise
+
+
+def _finish_rejected_takeover(
+ host: MigrationHost, record: dict[str, Any],
+) -> tuple[int, list[dict]]:
+ host._save_config(ModelHubConfig.from_payload(record["terminal"]["config"]))
+ host._reconcile_native_auth(tuple(record["backends"]))
+ host.migration_journal.complete(record)
+ host.migration_blocked_backends.difference_update(record["backends"])
+ raise MigrationCredentialsInvalidError
async def apply_native_migration(
@@ -702,168 +1458,202 @@ async def apply_native_migration(
mask_credential: Callable[[str], str],
validate_base_url: Callable[[object], Optional[str]],
) -> tuple[int, list[dict]]:
- """Provision, probe, and atomically persist a selected migration batch."""
-
+ """Own a takeover from consent through cleanup; callers shield cancellation."""
if (
not isinstance(item_ids, list)
- or not all(isinstance(item_id, str) and item_id for item_id in item_ids)
+ or not all(isinstance(value, str) and value for value in item_ids)
or len(set(item_ids)) != len(item_ids)
):
raise MigrationConflictError
if not item_ids:
return 0, []
-
- async with host._mutation_lock:
- previous = host.store.load()
+ async with host._migration_lock:
+ completed_record = None
+ record = host.migration_journal.load() or host.migration_journal.completed()
+ 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:
+ if record["phase"] == "complete":
+ async with host.migration_guard(tuple(record["backends"])) as verify_idle:
+ async with host._mutation_lock:
+ result = await _resume_takeover(host, record)
+ await verify_idle()
+ residual = 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, tuple(record["backends"])),
+ project_roots=host.migration_project_roots(),
+ clean_native_stores=record.get("clean_native_stores"),
+ )
+ if not any(item.backend in record["backends"] for item in residual):
+ return result
+ completed_record = record
+ else:
+ async with host.migration_guard(tuple(record["backends"])) as verify_idle:
+ async with host._mutation_lock:
+ return await _resume_takeover(host, record, verify_idle)
available = await asyncio.to_thread(
- scan_native_configs,
- previous,
- mask_credential=mask_credential,
+ scan_native_configs, host.store.load(), mask_credential=mask_credential,
home=host.migration_home,
- claude_oauth_probe=host.migration_claude_oauth_probe,
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"),
)
- by_id = {item.id: item for item in available}
- missing = [item_id for item_id in item_ids if item_id not in by_id]
- if missing:
- raise MigrationConflictError
-
- selected = [by_id[item_id] for item_id in item_ids]
- if any(item.proposed_action in {"controlled_import", "reauth"} for item in selected):
+ 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):
raise MigrationConflictError
- selected.sort(key=lambda item: item.proposed_action != "keep_native")
- updated = host._clone_config(previous)
- existing_ids = {source.id for source in updated.sources}
- if any(item.source_id in existing_ids for item in selected):
+ backends = tuple(sorted({item.backend for item in selected}))
+ # A CLI takeover cannot leave an unselected credential maintaining its
+ # original authentication. Selection is therefore grouped by backend.
+ if any(item.backend in backends and item.id not in item_ids for item in available):
raise MigrationConflictError
-
- provisioned: list[tuple[str, str]] = []
- persisted = False
- catalog_efforts_by_model = bundled_catalog_reasoning_efforts_by_model()
- try:
- for item in selected:
- protocol = item.protocol
- observation: SourceObservation | None = None
- if item.proposed_action == "import":
- if not item.secret:
- raise MigrationConflictError
- observation = await host._require_proven_source_payload(
- {
- "vendor": item.vendor,
- "base_url": validate_base_url(item.base_url),
- "key": item.secret,
- }
- )
- protocol = cast(
- Literal[
- "anthropic",
- "openai_responses",
- "openai_chat",
- ],
- observation.protocol,
- )
- if item.proposed_action == "import":
- assert item.secret is not None
- assert observation is not None
- credential_ref = await host._engine_call(
- host.adapter.provision_credential(
- item.vendor,
- protocol,
- item.secret,
- validate_base_url(item.base_url),
+ async with host.migration_guard(backends) as verify_idle:
+ async with host._mutation_lock:
+ if completed_record is not None:
+ # The guards above and below are separate acquisitions:
+ # recheck persisted ownership before a cleanup-only replay.
+ await _resume_takeover(host, completed_record)
+ previous = host.store.load()
+ project_roots = host.migration_project_roots()
+ rescanned = 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"),
+ )
+ consented = selected
+ selected = []
+ clean_native_stores: dict[str, str] = {}
+ for original in consented:
+ resolved = [
+ item for item in rescanned
+ if (
+ item.backend == original.backend
+ and item.native_store_revision == original.native_store_revision
+ and item.native_store_revision is not None
)
- )
- provisioned.append((item.source_id, credential_ref))
- try:
- source = _validated_source(
- item,
- now=host.now(),
- protocol=protocol,
+ ] if original.native_store_placeholder else [
+ item for item in rescanned if item.id == original.id
+ ]
+ if original.native_store_placeholder and not resolved:
+ # A consent-time secret read can establish that an
+ # opaque container holds only unrelated data. Bind the
+ # absence to the same metadata, routing and Source
+ # identity before recording it as verified clean.
+ metadata_rows = await asyncio.to_thread(
+ scan_native_configs, previous,
+ mask_credential=mask_credential, home=host.migration_home,
validate_base_url=validate_base_url,
- credential_ref=credential_ref,
- masked_credential=mask_credential(item.secret),
- catalog_efforts_by_model=catalog_efforts_by_model,
+ legacy_auth=_native_auth_snapshot(host, backends),
+ project_roots=project_roots,
)
- manual_models = [
- ModelHubModelConfig.from_payload(
- {
- "id": model.id,
- "display_name": model.display_name,
- "origin": "manual",
- "reasoning_efforts": [],
- "discovered_at": None,
- }
- )
- for model in item.manual_models
- ]
- for model in manual_models:
- resolution = resolve_reasoning_tiers(
- protocol=protocol,
- model_id=model.id,
- existing_efforts=model.reasoning_efforts,
- existing_source=model.reasoning_efforts_source,
- catalog_efforts_by_model=catalog_efforts_by_model,
- )
- model.reasoning_efforts = list(resolution.efforts)
- model.reasoning_efforts_source = resolution.source
- if observation.discovery is ObservationDiscovery.SUCCEEDED:
- host._apply_discovered_models(
- source,
- manual_models,
- list(observation.models),
- allow_empty=True,
- catalog_efforts_by_model=catalog_efforts_by_model,
- )
- else:
- failed_payload = source.to_payload()
- failed_payload["models"] = [
- model.to_payload() for model in manual_models
- ]
- failed_payload["state"] = {
- "status": "error",
- "retry_at": None,
- "detail_key": "models.source.error.unclassified",
- }
- source = ModelHubSourceConfig.from_payload(
- failed_payload
+ if any(
+ item.id == original.id
+ and item.native_store_placeholder
+ and item.native_store_revision == original.native_store_revision
+ for item in metadata_rows
+ ) and not any(
+ item.backend == original.backend and item.native_store_revision is not None
+ for item in rescanned
+ ):
+ clean_native_stores[original.backend] = original.native_store_revision
+ continue
+ if original.native_store_placeholder and not any(
+ item.id == original.id for item in resolved
+ ):
+ # Container revision alone does not bind the routing
+ # target or an existing native Source selected by UI.
+ raise MigrationConflictError
+ if not resolved or any(
+ item.proposed_action != "import" or item.native_store_placeholder
+ for item in resolved
+ ):
+ raise MigrationConflictError
+ selected.extend(item for item in resolved if item not in selected)
+ if any(item.backend in backends and item not in selected for item in rescanned):
+ raise MigrationConflictError
+ record = await _prepare_takeover(
+ host, previous, selected, mask_credential=mask_credential,
+ validate_base_url=validate_base_url,
+ consented=consented,
+ project_roots=project_roots,
+ retained_source_ids=(
+ tuple(completed_record["source_ids"])
+ if completed_record is not None else None
+ ),
+ clean_native_stores=clean_native_stores,
+ )
+ return await _resume_takeover(host, record, verify_idle)
+
+
+async def recover_native_migration(host: MigrationHost) -> None:
+ """Recover confirmed work before CPA runtime recovery or native admission."""
+ record = host.migration_journal.load()
+ if record is None or record["phase"] == "complete":
+ return
+ host.migration_blocked_backends.update(record["backends"])
+ async with host._migration_lock:
+ async with host.migration_guard(tuple(record["backends"])) as verify_idle:
+ async with host._mutation_lock:
+ try:
+ await _resume_takeover(host, record, verify_idle)
+ except MigrationCredentialsInvalidError:
+ # The durable Source state is the repair entry point.
+ # No native credential or admission gate remains owned.
+ pass
+
+
+async def prepare_takeover_reauthentication(host: MigrationHost, source_id: str) -> None:
+ """Honor explicit Hub reauthentication without guessing refresh validity.
+
+ This is not a migration-success path. The user has acknowledged replacing
+ authentication in Hub; release only the completed native withdrawal, keep
+ every current engine grant, and let the existing Hub OAuth flow repair it.
+ """
+ async with host._migration_lock:
+ record = host.migration_journal.load()
+ if record is None:
+ return
+ if record["phase"] != "exposed":
+ raise MigrationConflictError
+ oauth_ids = [
+ credential["source_id"] for credential in record["credentials"]
+ if credential["kind"] == "oauth"
+ ]
+ if source_id not in oauth_ids:
+ raise MigrationConflictError
+ async with host.migration_guard(tuple(record["backends"])) as verify_idle:
+ async with host._mutation_lock:
+ if not record.get("terminal"):
+ updated = ModelHubConfig.from_payload(record["updated"])
+ if host.store.load().to_payload() != updated.to_payload():
+ raise MigrationConflictError
+ unresolved = [
+ value for value in oauth_ids
+ if value == source_id or value not in record.get("validated_source_ids", [])
+ ]
+ terminal = host._clone_config(updated)
+ for source in terminal.sources:
+ if source.id in unresolved:
+ source.state = ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.oauth_expired",
)
- source = ModelHubSourceConfig.from_payload(
- source.to_payload()
- )
- except (TypeError, ValueError):
- raise MigrationConflictError from None
- else:
- try:
- source = _validated_source(
- item,
- now=host.now(),
- protocol=item.protocol,
- validate_base_url=validate_base_url,
- catalog_efforts_by_model=catalog_efforts_by_model,
- )
- except (TypeError, ValueError):
- raise MigrationConflictError from None
- if source.supply_channel == "hub":
- host._mark_source_unverified(source)
- updated.sources.append(source)
- host._apply_source_placement(updated, source)
-
- try:
- updated = ModelHubConfig.from_payload(updated.to_payload())
- except (TypeError, ValueError):
- raise MigrationConflictError from None
- await host._commit_synced(previous, updated)
- persisted = True
- added_to = [
- position
- for item in selected
- for position in host._added_to(item.source_id)
- ]
- return len(selected), added_to
- finally:
- if not persisted:
- for source_id, credential_ref in reversed(provisioned):
- await host._rollback_credential(
- _migration_rollback_id(source_id, credential_ref),
- credential_ref,
- )
+ record["terminal"] = {
+ "invalid_source_ids": unresolved,
+ "config": terminal.to_payload(),
+ "reason": "reauth_requested",
+ }
+ host.migration_journal.save(record)
+ try:
+ # Reuses strict file/store cleanup checks, persisted config
+ # identity, and idle verification before removing any gate.
+ await _resume_takeover(host, record, verify_idle)
+ except MigrationCredentialsInvalidError:
+ pass
diff --git a/core/handlers/model_hub/migration_files.py b/core/handlers/model_hub/migration_files.py
new file mode 100644
index 000000000..5b70bc713
--- /dev/null
+++ b/core/handlers/model_hub/migration_files.py
@@ -0,0 +1,283 @@
+"""Plan native configuration cleanup without changing any native file."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+try:
+ import tomllib
+except ImportError: # Python 3.10 uses the existing conditional dependency.
+ import tomli as tomllib
+
+from vibe.claude_config import get_claude_oauth_settings_backup_path, get_claude_settings_path
+from vibe.codex_config import (
+ CREDENTIALS_STORE_KEY,
+ LEGACY_MANAGED_PROVIDER_IDS,
+ MANAGED_PROVIDER_ID,
+ _dump_toml,
+ get_codex_config_paths,
+)
+from vibe.opencode_config import (
+ get_opencode_auth_path,
+ get_opencode_config_paths,
+ parse_jsonc_object,
+)
+
+from .migration_journal import NativeFileEdit, TakeoverStateError, _read_regular
+
+if TYPE_CHECKING:
+ from .migration import NativeMigrationItem
+
+def _object(content: bytes, *, jsonc: bool = False) -> dict:
+ try:
+ result = parse_jsonc_object(content.decode()) if jsonc else json.loads(content)
+ except (ValueError, UnicodeError):
+ raise TakeoverStateError("native configuration cannot be parsed") from None
+ if not isinstance(result, dict):
+ raise TakeoverStateError("native configuration cannot be parsed")
+ return result
+
+
+def _json_bytes(payload: dict) -> bytes:
+ # Preserve even unrelated escaped surrogate values without accepting them
+ # as Hub model identities or failing halfway through native cleanup.
+ return (json.dumps(payload, ensure_ascii=True, indent=2) + "\n").encode()
+
+
+def claude_settings_paths(home: Path | None, projects: tuple[Path, ...]) -> tuple[Path, ...]:
+ # An interrupted OAuth flow can restore its backup into settings.json.
+ # It is therefore a credential writer's input, not an unrelated archive.
+ return tuple(dict.fromkeys([
+ get_claude_settings_path(home).absolute(),
+ get_claude_oauth_settings_backup_path(home).absolute(),
+ *(root / ".claude" / name for root in projects for name in ("settings.json", "settings.local.json")),
+ ]))
+
+
+def opencode_config_paths(home: Path | None, projects: tuple[Path, ...]) -> tuple[Path, ...]:
+ candidates = get_opencode_config_paths(home)
+ if home is None:
+ config_home = os.environ.get("XDG_CONFIG_HOME")
+ if config_home:
+ candidates.append(Path(config_home).expanduser() / "opencode/opencode.json")
+ directory = os.environ.get("OPENCODE_CONFIG_DIR")
+ if directory:
+ candidates.append(Path(directory).expanduser() / "opencode.json")
+ paths = [path for candidate in candidates for path in (candidate, candidate.with_suffix(".jsonc"))]
+ if home is None and os.environ.get("OPENCODE_CONFIG"):
+ paths.append(Path(os.environ["OPENCODE_CONFIG"]).expanduser())
+ paths.extend(
+ root / name for root in projects
+ for name in ("opencode.json", "opencode.jsonc", ".opencode/opencode.json", ".opencode/opencode.jsonc")
+ )
+ return tuple(dict.fromkeys(path.absolute() for path in paths))
+
+
+def opencode_auth_path(home: Path | None) -> Path:
+ if home is None and os.environ.get("XDG_DATA_HOME"):
+ return Path(os.environ["XDG_DATA_HOME"]).expanduser() / "opencode/auth.json"
+ return get_opencode_auth_path(home)
+
+
+def codex_config_paths(home: Path | None, projects: tuple[Path, ...]) -> tuple[Path, ...]:
+ config_path, _ = get_codex_config_paths(home)
+ return tuple(dict.fromkeys([config_path.absolute(), *(root / ".codex/config.toml" for root in projects)]))
+
+
+def read_native_toml(path: Path) -> dict | None:
+ content = _read_regular(path)
+ if content is None:
+ return None
+ try:
+ return tomllib.loads(content.decode())
+ except (ValueError, UnicodeError):
+ raise TakeoverStateError("native configuration cannot be parsed") from None
+
+
+def read_native_config(path: Path, *, jsonc: bool = False) -> dict | None:
+ content = _read_regular(path)
+ return None if content is None else _object(content, jsonc=jsonc)
+
+
+def plan_native_cleanup(
+ items: list[NativeMigrationItem],
+ *,
+ home: Path | None,
+ project_roots: tuple[Path, ...] = (),
+) -> list[NativeFileEdit]:
+ """One before/after image per path, even when providers share a file.
+
+ Only selected backend authentication is removed. Planning refuses malformed
+ files instead of using the forgiving UI probes that can return an empty
+ document after a parse failure.
+ """
+ edits: dict[Path, NativeFileEdit] = {}
+ # 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 operation in (item.native_store_edit or {}).get("operations", []):
+ if operation.get("kind") != "file":
+ continue
+ path = Path(operation["path"]).absolute()
+ before = operation["before"]
+ after = operation["after"]
+ edit = NativeFileEdit(
+ path,
+ before["raw"].encode() if before["exists"] else None,
+ after["raw"].encode() if after["exists"] else None,
+ )
+ if path in edits and edits[path] != edit:
+ raise TakeoverStateError("conflicting native credential snapshots")
+ edits[path] = edit
+
+ def edit_json(path: Path, transform, *, jsonc: bool = False, guard_unchanged: bool = False) -> None:
+ path = path.absolute()
+ staged = edits.get(path)
+ original = staged.before if staged else _read_regular(path)
+ if guard_unchanged and staged is None:
+ # Model-only and currently absent OpenCode layers also determine
+ # the consented inventory. Preserve their exact snapshots through
+ # asynchronous proof/provision and journaled cleanup/recovery.
+ edits[path] = NativeFileEdit(path, original, original)
+ if original is None:
+ return
+ working = staged.after if staged else original
+ if working is None:
+ return
+ payload = _object(working, jsonc=jsonc)
+ before = json.dumps(payload, sort_keys=True)
+ transform(payload)
+ if json.dumps(payload, sort_keys=True) != before:
+ edits[path] = NativeFileEdit(path.absolute(), original, _json_bytes(payload))
+
+ # Consent to inspect an opaque, verified-empty container does not transfer
+ # any credential. It cannot authorize cleanup of another native store.
+ backends = {item.backend for item in items if not item.native_store_placeholder}
+ selected_secrets = {item.secret for item in items if item.secret}
+ if "claude" in backends:
+ def clear_settings(payload: dict) -> None:
+ env = payload.get("env")
+ if env is not None and not isinstance(env, dict):
+ raise TakeoverStateError("native configuration cannot be parsed")
+ if isinstance(env, dict):
+ for key in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN"):
+ if key != "ANTHROPIC_BASE_URL" and env.get(key) and env[key] not in selected_secrets:
+ raise TakeoverStateError("another native credential requires migration")
+ env.pop(key, None)
+ if payload.get("apiKeyHelper"):
+ raise TakeoverStateError("native credential helper requires configuration")
+ payload.pop("apiKeyHelper", None)
+
+ for path in claude_settings_paths(home, project_roots):
+ edit_json(path, clear_settings)
+ backup_path = get_claude_oauth_settings_backup_path(home).absolute()
+ backup_edit = edits.get(backup_path)
+ if backup_edit and backup_edit.after is not None:
+ backup = _object(backup_edit.after)
+ if set(backup) <= {"version", "env"} and not backup.get("env"):
+ edits[backup_path] = NativeFileEdit(backup_path, backup_edit.before, None)
+
+ if "codex" in backends:
+ config_path, auth_path = get_codex_config_paths(home)
+
+ def clear_auth(payload: dict) -> None:
+ if payload.get("OPENAI_API_KEY") and payload["OPENAI_API_KEY"] not in selected_secrets:
+ raise TakeoverStateError("another native credential requires migration")
+ if payload.get("tokens") and not any(
+ item.backend == "codex" and item.kind == "oauth_native"
+ and not item.native_store_placeholder
+ for item in items
+ ):
+ raise TakeoverStateError("another native credential requires migration")
+ for key in ("OPENAI_API_KEY", "tokens", "auth_mode", "last_refresh"):
+ payload.pop(key, None)
+
+ edit_json(auth_path, clear_auth)
+ for config_path in codex_config_paths(home, project_roots):
+ content = _read_regular(config_path)
+ if content is None:
+ continue
+ try:
+ config = tomllib.loads(content.decode())
+ except (ValueError, UnicodeError):
+ raise TakeoverStateError("native configuration cannot be parsed") from None
+ before = json.dumps(config, sort_keys=True, default=str)
+ removable = {MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS}
+ removable.update(item.native_provider_id for item in items if item.backend == "codex" and item.native_provider_id)
+ providers = config.get("model_providers")
+ if isinstance(providers, dict):
+ for provider_id in removable:
+ provider = providers.get(provider_id)
+ if not isinstance(provider, dict):
+ continue
+ if provider.get("experimental_bearer_token") and provider["experimental_bearer_token"] not in selected_secrets:
+ raise TakeoverStateError("another native credential requires migration")
+ # Retain user labels, capabilities, and timeout preferences.
+ for key in ("base_url", "env_key", "experimental_bearer_token", "requires_openai_auth"):
+ provider.pop(key, None)
+ for header_field in ("http_headers", "env_http_headers"):
+ headers = provider.get(header_field)
+ if isinstance(headers, dict):
+ for name in list(headers):
+ if name.lower() in {"authorization", "x-api-key"}:
+ headers.pop(name)
+ if not providers:
+ config.pop("model_providers", None)
+ if config.get("model_provider") in removable:
+ config.pop("model_provider", None)
+ profiles = config.get("profiles")
+ if isinstance(profiles, dict):
+ for profile in profiles.values():
+ if isinstance(profile, dict) and profile.get("model_provider") in removable:
+ profile.pop("model_provider")
+ # 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):
+ 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())
+
+ if "opencode" in backends:
+ vendors = {item.vendor for item in items if item.backend == "opencode"}
+
+ def clear_providers(payload: dict) -> None:
+ providers = payload.get("provider")
+ if providers is None:
+ return
+ if not isinstance(providers, dict):
+ raise TakeoverStateError("native configuration cannot be parsed")
+ for vendor in vendors:
+ provider = providers.get(vendor)
+ if not isinstance(provider, dict):
+ continue
+ options = provider.get("options")
+ if isinstance(options, dict):
+ value = options.get("apiKey")
+ if value and value not in selected_secrets:
+ # An unset environment placeholder supplied no native
+ # credential; an auth.json fallback was the imported key.
+ unresolved = (
+ isinstance(value, str)
+ and value.startswith("{env:") and value.endswith("}")
+ and not os.environ.get(value[5:-1])
+ )
+ if not unresolved:
+ raise TakeoverStateError("another native credential requires migration")
+ options.pop("apiKey", None)
+ options.pop("baseURL", None)
+ if not options:
+ provider.pop("options", None)
+
+ for path in opencode_config_paths(home, project_roots):
+ edit_json(path, clear_providers, jsonc=True, guard_unchanged=True)
+
+ def clear_provider_auth(payload: dict) -> None:
+ for vendor in vendors:
+ payload.pop(vendor, None)
+
+ edit_json(opencode_auth_path(home), clear_provider_auth, guard_unchanged=True)
+ return list(edits.values())
diff --git a/core/handlers/model_hub/migration_journal.py b/core/handlers/model_hub/migration_journal.py
new file mode 100644
index 000000000..0ccdd2d72
--- /dev/null
+++ b/core/handlers/model_hub/migration_journal.py
@@ -0,0 +1,310 @@
+"""Private write-ahead state for native credential ownership transitions.
+
+This document is never an API payload. Native snapshots are retained for
+compare-before-write recovery until custody settles, never for rollback after
+CPA exposure. The completed receipt contains opaque IDs, not secrets.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import stat
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from config.atomic_io import write_atomic
+from config.v2_config import ModelHubConfig
+
+
+class TakeoverStateError(RuntimeError):
+ """Sanitized failure: never include a credential or native file contents."""
+
+
+def _read_regular(path: Path) -> bytes | None:
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError:
+ return None
+ if not stat.S_ISREG(mode):
+ raise TakeoverStateError("native configuration is not a regular file")
+ return path.read_bytes()
+
+
+def _encoded(content: bytes | None) -> str | None:
+ return base64.b64encode(content).decode("ascii") if content is not None else None
+
+
+def _decoded(content: object) -> bytes | None:
+ if content is None:
+ return None
+ if not isinstance(content, str):
+ raise TakeoverStateError("invalid takeover snapshot")
+ try:
+ return base64.b64decode(content, validate=True)
+ except ValueError:
+ raise TakeoverStateError("invalid takeover snapshot") from None
+
+
+@dataclass(frozen=True, repr=False)
+class NativeFileEdit:
+ path: Path
+ before: bytes | None
+ after: bytes | None
+ mode: int = 0o600
+
+ @classmethod
+ def plan(cls, path: Path, after: bytes | None) -> NativeFileEdit:
+ before = _read_regular(path)
+ mode = stat.S_IMODE(path.stat().st_mode) if before is not None else 0o600
+ return cls(path.absolute(), before, after, mode)
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "path": str(self.path),
+ "before": _encoded(self.before),
+ "after": _encoded(self.after),
+ "mode": self.mode,
+ }
+
+ @classmethod
+ def from_payload(cls, payload: object) -> NativeFileEdit:
+ if not isinstance(payload, dict) or set(payload) != {"path", "before", "after", "mode"}:
+ raise TakeoverStateError("invalid takeover snapshot")
+ path = payload["path"]
+ mode = payload["mode"]
+ if (
+ not isinstance(path, str)
+ or not Path(path).is_absolute()
+ or not isinstance(mode, int)
+ or isinstance(mode, bool)
+ or mode < 0
+ or mode > 0o777
+ ):
+ raise TakeoverStateError("invalid takeover snapshot")
+ return cls(Path(path), _decoded(payload["before"]), _decoded(payload["after"]), mode)
+
+ def check(self, *, applied: bool = False) -> None:
+ expected = self.after if applied else self.before
+ if _read_regular(self.path) != expected:
+ raise TakeoverStateError("native configuration changed")
+
+ def apply(self, *, reverse: bool = False) -> None:
+ """Compare before writing; replay accepts only either recorded state."""
+ source, target = (self.after, self.before) if reverse else (self.before, self.after)
+ actual = _read_regular(self.path)
+ if actual == target:
+ return
+ if actual != source:
+ raise TakeoverStateError("native configuration changed")
+ if target is None:
+ self.path.unlink()
+ # The absence is part of the ownership decision, not best effort.
+ if _read_regular(self.path) is not None:
+ raise TakeoverStateError("native cleanup did not persist")
+ _fsync_directory(self.path.parent)
+ return
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ # Authentication-bearing files must never become more permissive.
+ write_atomic(self.path, target)
+ _fsync_directory(self.path.parent)
+ if _read_regular(self.path) != target:
+ raise TakeoverStateError("native configuration did not persist")
+
+
+def _fsync_directory(path: Path) -> None:
+ if os.name == "nt":
+ return
+ descriptor = os.open(path, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
+
+class NativeTakeoverJournal:
+ """One controller-owned transaction, plus the last idempotency receipt."""
+
+ def __init__(self, path: Path):
+ self.path = path
+
+ def _prepare(self) -> None:
+ self.path.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
+ mode = self.path.parent.lstat().st_mode
+ if not stat.S_ISDIR(mode) or stat.S_IMODE(mode) != 0o700:
+ raise TakeoverStateError("unsafe takeover directory")
+
+ def load(self) -> dict[str, Any] | None:
+ try:
+ mode = self.path.lstat().st_mode
+ except FileNotFoundError:
+ return None
+ if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600:
+ raise TakeoverStateError("unsafe takeover journal")
+ try:
+ payload = json.loads(self.path.read_bytes())
+ except (ValueError, UnicodeError):
+ raise TakeoverStateError("invalid takeover journal") from None
+ if (
+ not isinstance(payload, dict)
+ or payload.get("version") != 1
+ or payload.get("phase") not in {
+ "prepared", "withdrawn", "exposed", "complete", "reverting"
+ }
+ or not isinstance(payload.get("items"), list)
+ or not isinstance(payload.get("backends"), list)
+ or not payload["backends"]
+ or any(backend not in {"claude", "codex", "opencode"} for backend in payload["backends"])
+ or len(set(payload["backends"])) != len(payload["backends"])
+ or not isinstance(payload.get("source_ids"), list)
+ or any(not isinstance(value, str) or not value for value in payload["source_ids"])
+ or any(
+ not isinstance(item, dict)
+ or not isinstance(item.get("id"), str)
+ or item.get("backend") not in payload["backends"]
+ for item in payload["items"]
+ )
+ or not isinstance(payload.get("clean_native_stores", {}), dict)
+ or any(
+ backend not in {"claude", "codex"}
+ or not isinstance(revision, str) or not revision
+ for backend, revision in payload.get("clean_native_stores", {}).items()
+ )
+ ):
+ raise TakeoverStateError("invalid takeover journal")
+ if payload["phase"] != "complete":
+ try:
+ ModelHubConfig.from_payload(payload["previous"])
+ ModelHubConfig.from_payload(payload["updated"])
+ except (KeyError, TypeError, ValueError):
+ raise TakeoverStateError("invalid takeover configuration") from None
+ if (
+ not isinstance(payload.get("files"), list)
+ or not isinstance(payload.get("credentials"), list)
+ or any(
+ not isinstance(value, dict)
+ or value.get("kind") not in {"oauth", "api_key"}
+ or not isinstance(value.get("source_id"), str)
+ or not isinstance(value.get("credential_ref"), str)
+ for value in payload["credentials"]
+ )
+ or not isinstance(payload.get("keychain", []), list)
+ or not isinstance(payload.get("native_before", {}), dict)
+ or not isinstance(payload.get("native_after", {}), dict)
+ ):
+ raise TakeoverStateError("invalid takeover journal")
+ edits = [NativeFileEdit.from_payload(value) for value in payload["files"]]
+ if len({edit.path for edit in edits}) != len(edits):
+ raise TakeoverStateError("duplicate takeover path")
+ validated = payload.get("validated_source_ids", [])
+ oauth_ids = {
+ credential["source_id"] for credential in payload["credentials"]
+ if credential["kind"] == "oauth"
+ }
+ if (
+ not isinstance(validated, list)
+ or any(not isinstance(value, str) or value not in oauth_ids for value in validated)
+ or len(set(validated)) != len(validated)
+ ):
+ raise TakeoverStateError("invalid takeover validation evidence")
+ for edit in payload.get("keychain", []):
+ if (
+ not isinstance(edit, dict)
+ or edit.get("version") != 1
+ or edit.get("backend") not in payload["backends"]
+ or not isinstance(edit.get("operations"), list)
+ or not edit["operations"]
+ or any(
+ not isinstance(operation, dict)
+ or operation.get("kind") != "keychain"
+ or not isinstance(operation.get("service"), str)
+ or not isinstance(operation.get("account"), str)
+ or not isinstance(operation.get("before"), dict)
+ or not isinstance(operation.get("after"), dict)
+ for operation in edit["operations"]
+ )
+ ):
+ raise TakeoverStateError("invalid takeover credential store")
+ terminal = payload.get("terminal")
+ if terminal is not None:
+ if (
+ payload["phase"] != "exposed"
+ or not isinstance(terminal, dict)
+ or set(terminal) - {"invalid_source_ids", "config", "reason"}
+ or terminal.get("reason", "rejected") not in {"rejected", "reauth_requested"}
+ or not isinstance(terminal["invalid_source_ids"], list)
+ or not terminal["invalid_source_ids"]
+ or any(
+ not isinstance(value, str) or value not in payload["source_ids"]
+ for value in terminal["invalid_source_ids"]
+ )
+ ):
+ raise TakeoverStateError("invalid takeover terminal decision")
+ try:
+ expected = ModelHubConfig.from_payload(payload["updated"]).to_payload()
+ actual = ModelHubConfig.from_payload(terminal["config"]).to_payload()
+ except (KeyError, TypeError, ValueError):
+ raise TakeoverStateError("invalid takeover terminal configuration") from None
+ for source in expected["sources"]:
+ if source["id"] in terminal["invalid_source_ids"]:
+ from config.v2_config import ModelHubSourceStateConfig
+
+ source["state"] = ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.oauth_expired",
+ ).to_payload()
+ if actual != expected:
+ raise TakeoverStateError("invalid takeover terminal configuration")
+ elif payload.get("outcome", "success") not in {"success", "needs_auth", "reauth_requested"}:
+ raise TakeoverStateError("invalid takeover receipt")
+ return payload
+
+ def save(self, payload: dict[str, Any]) -> None:
+ self._prepare()
+ if self.path.exists():
+ self.load() # Refuse unsafe/corrupt state, never silently overwrite.
+ content = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode()
+ write_atomic(self.path, content)
+ _fsync_directory(self.path.parent)
+ if self.path.read_bytes() != content:
+ raise TakeoverStateError("takeover journal did not persist")
+
+ def forget(self) -> None:
+ if not self.path.exists():
+ return
+ self.load()
+ self.path.unlink()
+ _fsync_directory(self.path.parent)
+
+ def complete(self, record: dict[str, Any]) -> None:
+ receipt = NativeTakeoverJournal(self.path.with_name("last-completed.json"))
+ clean_stores = {
+ backend: revision
+ for backend, revision in (receipt.load() or {}).get("clean_native_stores", {}).items()
+ if backend not in record["backends"]
+ }
+ clean_stores.update(record.get("clean_native_stores", {}))
+ receipt.save({
+ "version": 1,
+ "phase": "complete",
+ "items": record["items"],
+ "backends": record["backends"],
+ "source_ids": record["source_ids"],
+ "outcome": (
+ "reauth_requested"
+ if (record.get("terminal") or {}).get("reason") == "reauth_requested"
+ else "needs_auth" if record.get("terminal") else "success"
+ ),
+ "source_credentials": {
+ source["id"]: source["credential_ref"]
+ for source in record["updated"]["sources"]
+ if source["id"] in record["source_ids"]
+ },
+ "clean_native_stores": clean_stores,
+ })
+ self.forget()
+
+ def completed(self) -> dict[str, Any] | None:
+ return NativeTakeoverJournal(self.path.with_name("last-completed.json")).load()
diff --git a/core/handlers/model_hub/revocations.py b/core/handlers/model_hub/revocations.py
index 7becda19d..e0317cbd3 100644
--- a/core/handlers/model_hub/revocations.py
+++ b/core/handlers/model_hub/revocations.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import os
import threading
from dataclasses import dataclass
from pathlib import Path
@@ -36,6 +37,17 @@ class CredentialRevocationJournal:
self.path = path
self._lock = threading.RLock()
+ def _sync_directory(self) -> None:
+ # write_atomic flushes the file. Provisional ownership also requires a
+ # durable directory entry before the engine can write any secret.
+ if os.name == "nt":
+ return
+ descriptor = os.open(self.path.parent, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
def _read(self) -> list[PendingCredentialRevocation]:
if not self.path.exists():
return []
@@ -129,6 +141,8 @@ class CredentialRevocationJournal:
if entry not in entries:
entries.append(entry)
self._write(entries)
+ # Retry the fence if a previous add wrote the row but failed flush.
+ self._sync_directory()
def remove(self, source_id: str, credential_ref: str) -> None:
with self._lock:
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 76cbe7726..92c8df110 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -8,6 +8,7 @@ import json
import logging
import time
import uuid
+from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -92,10 +93,13 @@ from .errors import ModelDiscoveryError
from .identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL, canonical_model_id, normalized_model_id
from .migration import (
MigrationConflictError,
+ MigrationCredentialsInvalidError,
apply_native_migration,
- build_native_migration_source,
+ prepare_takeover_reauthentication,
+ recover_native_migration,
scan_native_configs,
)
+from .migration_journal import NativeTakeoverJournal, TakeoverStateError
from .oauth import (
NativeOAuthAdapter,
NativeOAuthUnavailableError,
@@ -290,6 +294,47 @@ class ModelHubConfigStore(Protocol):
class V2ModelHubConfigStore:
+ _NATIVE_AUTH_FIELDS = {
+ "claude": ("auth_mode", "api_key", "base_url", "auth_mode_set"),
+ "codex": ("auth_mode", "api_key", "base_url", "oauth_relay_marker"),
+ }
+
+ def native_auth_snapshot(self, backends: tuple[str, ...]) -> dict[str, dict]:
+ try:
+ config = V2Config.load()
+ except FileNotFoundError:
+ return {}
+ return {
+ backend: {
+ name: getattr(getattr(config.agents, backend), name)
+ for name in self._NATIVE_AUTH_FIELDS[backend]
+ }
+ for backend in backends if backend in self._NATIVE_AUTH_FIELDS
+ }
+
+ def save_takeover(
+ self,
+ model_hub: ModelHubConfig,
+ expected: dict[str, dict],
+ desired: dict[str, dict],
+ *,
+ expected_hub: tuple[dict, ...],
+ ) -> None:
+ from config.v2_config import config_write_transaction
+
+ self.ensure_writable()
+ with config_write_transaction() as config:
+ if config.model_hub.to_payload() not in expected_hub:
+ raise MigrationConflictError
+ for backend, values in desired.items():
+ target = getattr(config.agents, backend)
+ actual = {name: getattr(target, name) for name in values}
+ if actual not in (expected.get(backend), values):
+ raise MigrationConflictError
+ for name, value in values.items():
+ setattr(target, name, value)
+ config.model_hub = ModelHubConfig.from_payload(model_hub.to_payload())
+
def load(self) -> ModelHubConfig:
try:
return V2Config.load().model_hub
@@ -358,10 +403,37 @@ class UnavailableEngineAdapter:
async def gateway_token(self) -> str:
raise EngineUnavailableError
- async def provision_credential(self, vendor: str, protocol: str, secret: str, base_url: str | None) -> str:
+ async def provision_credential(
+ self, vendor: str, protocol: str, secret: str, base_url: str | None,
+ *, on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
+ raise EngineUnavailableError
+
+ async def provision_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ material: Mapping[str, object],
+ *, on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
+ raise EngineUnavailableError
+
+ async def activate_oauth_credential(self, credential_ref: str) -> None:
+ raise EngineUnavailableError
+
+ async def validate_oauth_credential(self, credential_ref: str) -> None:
+ raise EngineUnavailableError
+
+ async def matches_api_key_credential(
+ self, credential_ref: str, vendor: str, protocol: str,
+ secret: str, base_url: str | None,
+ ) -> bool:
raise EngineUnavailableError
- async def provision_transient_credential(self, vendor: str, secret: str, base_url: str | None) -> str:
+ async def provision_transient_credential(
+ self, vendor: str, secret: str, base_url: str | None,
+ *, on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
raise EngineUnavailableError
async def revoke_credential(self, credential_ref: str) -> None:
@@ -568,10 +640,12 @@ async def _provision_transient_credential_with_cancellation_ownership(
vendor: str,
key: str,
base_url: str | None,
+ *, on_reserved: Callable[[str], None] | None = None,
) -> str:
+ options = {"on_reserved": on_reserved} if on_reserved is not None else {}
return await _acquire_credential_ref_with_cancellation_ownership(
service,
- service.adapter.provision_transient_credential(vendor, key, base_url),
+ service.adapter.provision_transient_credential(vendor, key, base_url, **options),
"observation",
)
@@ -770,8 +844,11 @@ class ModelHubService:
native_oauth_adapter: Optional[NativeOAuthAdapter] = None,
oauth_flows: Optional[OAuthFlowRegistry] = None,
revocations: Optional[CredentialRevocationJournal] = None,
- migration_claude_oauth_probe: Optional[Callable[[], bool]] = None,
migration_home: Optional[Path] = None,
+ migration_project_roots: Callable[[], tuple[Path, ...]] | None = None,
+ migration_guard: Any = None,
+ migration_reconcile_auth: Callable[[dict[str, dict[str, Any]]], None] | None = None,
+ migration_journal: NativeTakeoverJournal | None = None,
requested_model_override: Optional[Callable[[BackendName], Optional[str]]] = None,
selected_agent_override: Optional[Callable[[BackendName], Optional[str]]] = None,
named_agents_override: Optional[
@@ -808,8 +885,17 @@ class ModelHubService:
self.revocations = revocations or CredentialRevocationJournal(
paths.get_state_dir() / "model_hub_pending_revocations.json"
)
- self.migration_claude_oauth_probe = migration_claude_oauth_probe
self.migration_home = migration_home
+ self.migration_project_roots = migration_project_roots or (lambda: ())
+ self.migration_journal = migration_journal or NativeTakeoverJournal(
+ events.path.parent / "native-takeover" / "current.json"
+ )
+ self.migration_blocked_backends: set[str] = set()
+ self.migration_guard = migration_guard or self._unavailable_migration_guard
+ self.migration_reconcile_auth = migration_reconcile_auth
+ self._migration_lock = asyncio.Lock()
+ self._migration_task: asyncio.Task | None = None
+ self._migration_item_ids: tuple[str, ...] | None = None
self.requested_model_override = requested_model_override
self.selected_agent_override = selected_agent_override
self.named_agents_override = named_agents_override
@@ -838,6 +924,15 @@ class ModelHubService:
self._builtin_snapshot_cache: dict[BackendName, list[dict[str, Any]]] = {}
self._pending_builtin_catalog_refresh: set[BackendName] = set()
+ @staticmethod
+ @asynccontextmanager
+ async def _unavailable_migration_guard(backends):
+ # A stand-alone UI service cannot retire Controller-owned credentials.
+ # Tests explicitly inject a fixture-only guard; production is wired by
+ # the Controller's shared backend lifecycle coordinator.
+ raise ModelHubError("mode_switch_blocked", status=409)
+ yield # pragma: no cover - required async context-manager shape
+
@staticmethod
def _source(config: ModelHubConfig, source_id: str) -> ModelHubSourceConfig:
source = next((item for item in config.sources if item.id == source_id), None)
@@ -984,9 +1079,41 @@ class ModelHubService:
for source in config.sources
)
+ def _reconcile_native_auth(self, backends: tuple[str, ...]) -> None:
+ """Mirror the actual persisted direction while takeover still owns admission."""
+ reader = getattr(self.store, "native_auth_snapshot", None)
+ snapshot = reader(backends) if callable(reader) else {}
+ if self.migration_reconcile_auth is not None:
+ self.migration_reconcile_auth(snapshot)
+
def _save_config(self, config: ModelHubConfig) -> ModelHubConfig:
canonical = ModelHubConfig.from_payload(config.to_payload())
- self.store.save(canonical)
+ try:
+ pending = self.migration_journal.load()
+ except (TakeoverStateError, OSError):
+ raise ModelHubError("migration_item_conflict", status=409) from None
+ reverse = pending is not None and pending["phase"] == "reverting"
+ if pending is not None and canonical.to_payload() not in (
+ (pending["previous"],) if reverse else (
+ pending["updated"], (pending.get("terminal") or {}).get("config"),
+ )
+ ):
+ # The write-ahead decision must not overwrite intervening route
+ # edits on recovery. Finish/revert that decision before new writes.
+ raise ModelHubError("migration_item_conflict", status=409)
+ if pending is not None and isinstance(self.store, V2ModelHubConfigStore):
+ native_before = pending.get("native_before", {})
+ self.store.save_takeover(
+ canonical,
+ pending.get("native_after", {}) if reverse else native_before,
+ native_before if reverse else pending.get("native_after", {}),
+ expected_hub=tuple(value for value in (
+ pending["previous"], pending["updated"],
+ (pending.get("terminal") or {}).get("config"),
+ ) if value is not None),
+ )
+ else:
+ self.store.save(canonical)
self.recovery.reconcile(canonical)
self.recovery.notify()
return canonical
@@ -1122,6 +1249,11 @@ class ModelHubService:
if self._engine_synced and not pending_revocations:
return
config = self.store.load()
+ takeover = self.migration_journal.load()
+ takeover_credentials = {
+ (credential["source_id"], credential["credential_ref"])
+ for credential in (takeover or {}).get("credentials", [])
+ }
await self._sync_sources(config, force_empty=bool(pending_revocations))
self._engine_synced = True
active_credentials = {
@@ -1137,6 +1269,11 @@ class ModelHubService:
except OSError:
pass
continue
+ if (pending.source_id, pending.credential_ref) in takeover_credentials:
+ # A prepared takeover owns refs before they appear in
+ # config. Other Hub consumers may reconcile between a
+ # failed request and recovery; they cannot revoke its grant.
+ continue
if pending.operation == "cleanup_orphaned_oauth_material":
try:
cleaned = (
@@ -1200,6 +1337,13 @@ class ModelHubService:
async def recover_runtime_intent(self) -> None:
"""Restore the runtime only when the user left it enabled."""
+ try:
+ await recover_native_migration(self)
+ except (TakeoverStateError, OSError):
+ # Unknown recovery state cannot authorize any native credential
+ # writer or native launch. Controller recovery preserves this gate.
+ self.migration_blocked_backends.update(MODEL_HUB_BACKENDS)
+ raise ModelHubError("migration_item_conflict", status=409) from None
async with self._runtime_lifecycle_lock:
await self.reconcile_runtime_installation()
if not self.store.load().enabled:
@@ -1220,6 +1364,15 @@ class ModelHubService:
)
async def stop(self) -> None:
+ task = self._migration_task
+ if task is not None and not task.done():
+ try:
+ # A disconnected requester does not own the handoff lifetime.
+ # Retire the runtime only once custody has settled or a durable
+ # recovery record has captured the failure.
+ await await_owned_task(task)
+ except Exception:
+ logger.warning("Native takeover remains pending during shutdown")
async with self._runtime_lifecycle_lock:
await self.adapter.stop()
@@ -1518,6 +1671,7 @@ class ModelHubService:
payload: Mapping[str, Any],
*,
require_proven: bool = False,
+ on_reserved: Callable[[str], None] | None = None,
) -> SourceObservation:
if set(payload) - {"vendor", "base_url", "key", "protocol"}:
raise ModelHubError("discovery_failed")
@@ -1536,6 +1690,7 @@ class ModelHubService:
vendor,
key.strip(),
base_url,
+ on_reserved=on_reserved,
)
try:
if require_proven:
@@ -1561,8 +1716,25 @@ class ModelHubService:
async def _require_proven_source_payload(
self,
payload: Mapping[str, Any],
+ *, on_reserved: Callable[[str], None] | None = None,
) -> SourceObservation:
- return await self._observe_source_payload(payload, require_proven=True)
+ return await self._observe_source_payload(
+ payload, require_proven=True, on_reserved=on_reserved,
+ )
+
+ async def _provision_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ material: Mapping[str, object],
+ *, on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
+ return await self.adapter.provision_oauth_credential(
+ source_id,
+ vendor,
+ material,
+ on_reserved=on_reserved,
+ )
async def observe_source(self, payload: object) -> dict:
if not isinstance(payload, dict):
@@ -4185,36 +4357,52 @@ class ModelHubService:
async def set_agent_mode(self, backend: str, mode: object) -> dict:
if mode not in {"hub", "direct"}:
raise ModelHubError("mode_switch_blocked")
+ if mode == "hub":
+ from core.backend_restart import NativeMigrationBlockedError
+
+ # A UI scan is advisory. Serialize with takeover, then recheck
+ # native absence while writers and launches are held out. Never
+ # treat mode-only consent as permission to import a new login.
+ async with self._migration_lock:
+ async with self._mutation_lock:
+ current = self.store.load()
+ agent = self._agent(current, backend)
+ if agent.mode == "hub":
+ return self._agent_payload(current, agent)
+ try:
+ async with self.migration_guard((backend,)) as verify_idle:
+ async with self._mutation_lock:
+ # Inventory must follow the last asynchronous drain:
+ # a CLI may have logged in and exited during it.
+ await verify_idle()
+ previous = self.store.load()
+ available = await asyncio.to_thread(
+ scan_native_configs, previous,
+ mask_credential=_mask_credential,
+ home=self.migration_home,
+ validate_base_url=_validated_base_url,
+ legacy_auth=(
+ self.store.native_auth_snapshot((backend,))
+ if isinstance(self.store, V2ModelHubConfigStore) else None
+ ),
+ project_roots=self.migration_project_roots(),
+ clean_native_stores=(
+ self.migration_journal.completed() or {}
+ ).get("clean_native_stores"),
+ )
+ if any(item.backend == backend for item in available):
+ raise ModelHubError("mode_switch_blocked", status=409)
+ config = self._clone_config(previous)
+ self._agent(config, backend).mode = "hub"
+ await self._commit_synced(previous, config)
+ committed = self.store.load()
+ return self._agent_payload(committed, self._agent(committed, backend))
+ except (NativeMigrationBlockedError, TakeoverStateError, OSError):
+ raise ModelHubError("mode_switch_blocked", status=409) from None
async with self._mutation_lock:
previous = self.store.load()
config = self._clone_config(previous)
agent = self._agent(config, backend)
- if agent.mode == "direct" and mode == "hub":
- native_items = await asyncio.to_thread(
- scan_native_configs,
- config,
- mask_credential=_mask_credential,
- home=self.migration_home,
- claude_oauth_probe=self.migration_claude_oauth_probe,
- validate_base_url=_validated_base_url,
- )
- native_item = next(
- (
- item
- for item in native_items
- if item.backend == backend
- and item.proposed_action == "keep_native"
- ),
- None,
- )
- if native_item is not None:
- source = build_native_migration_source(
- native_item,
- now=self.now(),
- validate_base_url=_validated_base_url,
- )
- config.sources.append(source)
- self._apply_source_placement(config, source)
agent.mode = mode
await self._commit_synced(previous, config)
committed = self.store.load()
@@ -5661,6 +5849,19 @@ class ModelHubService:
):
raise ModelHubError("reauth_confirmation_required", status=409)
+ from core.backend_restart import NativeMigrationBlockedError
+ from vibe.native_oauth_store import NativeOAuthError
+
+ try:
+ await await_owned_task(asyncio.create_task(
+ prepare_takeover_reauthentication(self, source_id),
+ name="model-hub-takeover-reauthentication",
+ ))
+ except NativeMigrationBlockedError:
+ raise ModelHubError("migration_native_busy", status=409) from None
+ except (MigrationConflictError, TakeoverStateError, NativeOAuthError, OSError):
+ raise ModelHubError("migration_recovery_pending", status=409) from None
+
async with self._mutation_lock:
config = self.store.load()
source = self._source(config, source_id)
@@ -6169,6 +6370,14 @@ class ModelHubService:
return _runtime_payload(status, enabled=False)
def migration_scan(self) -> dict:
+ try:
+ pending = self.migration_journal.load()
+ except (TakeoverStateError, OSError):
+ raise ModelHubError("migration_item_conflict", status=409) from None
+ if pending is not None:
+ # Resume the selected operation even though native credentials
+ # have already been withdrawn. Never expose the private journal.
+ return {"items": pending["items"]}
config = self.store.load()
return {
"items": [
@@ -6177,23 +6386,57 @@ class ModelHubService:
config,
mask_credential=_mask_credential,
home=self.migration_home,
- claude_oauth_probe=self.migration_claude_oauth_probe,
validate_base_url=_validated_base_url,
+ project_roots=self.migration_project_roots(),
+ clean_native_stores=(self.migration_journal.completed() or {}).get("clean_native_stores"),
+ legacy_auth=(
+ self.store.native_auth_snapshot(MODEL_HUB_BACKENDS)
+ if isinstance(self.store, V2ModelHubConfigStore) else None
+ ),
)
]
}
async def migration_apply(self, item_ids: object) -> dict:
+ from core.backend_restart import NativeMigrationBlockedError
+ from vibe.native_oauth_store import NativeOAuthError, NativeOAuthPermissionError
+
try:
- applied, added_to = await apply_native_migration(
- self,
- item_ids,
- mask_credential=_mask_credential,
- validate_base_url=_validated_base_url,
+ selection = (
+ tuple(sorted(item_ids))
+ if isinstance(item_ids, list) and all(isinstance(value, str) for value in item_ids)
+ else None
)
- except MigrationConflictError:
+ task = self._migration_task
+ if task is not None and not task.done():
+ if selection != self._migration_item_ids:
+ raise ModelHubError("migration_native_busy", status=409)
+ else:
+ task = asyncio.create_task(apply_native_migration(
+ self, item_ids, mask_credential=_mask_credential,
+ validate_base_url=_validated_base_url,
+ ), name="model-hub-native-takeover")
+ self._migration_task = task
+ self._migration_item_ids = selection
+ applied, added_to = await await_owned_task(task)
+ except MigrationCredentialsInvalidError:
+ raise ModelHubError("migration_credentials_invalid", status=409) from None
+ except NativeMigrationBlockedError:
+ raise ModelHubError("migration_native_busy", status=409) from None
+ except (NativeOAuthPermissionError, PermissionError):
+ raise ModelHubError("migration_permission_needed", status=409) from None
+ except (TakeoverStateError, NativeOAuthError):
+ raise ModelHubError("migration_configuration_blocked", status=409) from None
+ except (MigrationConflictError, OSError):
raise ModelHubError("migration_item_conflict", status=409)
except ModelHubError as exc:
+ try:
+ pending = self.migration_journal.load()
+ except (TakeoverStateError, OSError):
+ self.migration_blocked_backends.update(MODEL_HUB_BACKENDS)
+ raise ModelHubError("migration_configuration_blocked", status=409) from None
+ if pending is not None and pending["phase"] == "exposed":
+ raise ModelHubError("migration_recovery_pending", status=409) from None
if exc.code != "discovery_failed":
raise
raise ModelHubError("migration_item_conflict", status=409) from None
@@ -7471,27 +7714,32 @@ def create_default_service(
native_oauth_adapter = create_native_oauth_adapter()
- def claude_oauth_probe() -> bool:
- from vibe.api import (
- _build_claude_status_probe_env,
- _read_claude_cli_oauth_signed_in,
- _resolve_claude_status_probe_cwd,
- )
- from vibe.claude_config import build_claude_subprocess_env
-
+ def migration_project_roots() -> tuple[Path, ...]:
+ # This owner-only operation covers registered local projects and the
+ # default workdir, never an unbounded home/filesystem walk.
+ roots: set[Path] = set()
try:
config = V2Config.load()
except FileNotFoundError:
- config = default_config()
- claude = config.agents.claude
- env = _build_claude_status_probe_env(
- build_claude_subprocess_env(claude, force_oauth=True)
- )
- return _read_claude_cli_oauth_signed_in(
- claude.cli_path,
- env=env,
- cwd=_resolve_claude_status_probe_cwd(config),
- ) is True
+ pass
+ else:
+ if config.runtime.default_cwd:
+ roots.add(Path(config.runtime.default_cwd).expanduser().resolve())
+ if paths.get_sqlite_state_path().exists():
+ from storage.db import get_cached_sqlite_engine
+ from storage.projects_service import list_projects
+ from vibe.authorization import instance_owner_context
+
+ with get_cached_sqlite_engine().connect() as connection:
+ projects = list_projects(
+ connection, include_archived=True,
+ authorization_context=instance_owner_context(),
+ )
+ roots.update(
+ Path(project["folder_path"]).expanduser().resolve()
+ for project in projects if project.get("folder_path")
+ )
+ return tuple(sorted(roots))
return ModelHubService(
store=V2ModelHubConfigStore(),
@@ -7501,7 +7749,7 @@ def create_default_service(
native_oauth_adapter=native_oauth_adapter,
oauth_flows=OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json"),
revocations=CredentialRevocationJournal(paths.get_state_dir() / "model_hub_pending_revocations.json"),
- migration_claude_oauth_probe=claude_oauth_probe,
+ migration_project_roots=migration_project_roots,
requested_model_override=requested_model_override,
selected_agent_override=selected_agent_override,
named_agents_override=named_agents_override,
diff --git a/docs/plans/2026-09-18-shared-backend-connection.md b/docs/plans/2026-09-18-shared-backend-connection.md
index 2f90127c6..8636b7de7 100644
--- a/docs/plans/2026-09-18-shared-backend-connection.md
+++ b/docs/plans/2026-09-18-shared-backend-connection.md
@@ -129,9 +129,10 @@ ledger, config generations, schema or second lifecycle controller is added.
retains failure to deliver a refresh marker; querying an idle controller
cannot erase that failure. Only explicit successful apply clears it.
- `GET /api/backend/{backend}/connection` produces `BackendConnectionState`:
- `{ok, backend, installed, enabled, auth: subscription | api_key | none | unknown,
+ `{ok, backend, installed, enabled, supply_mode: direct | hub,
+ auth: subscription | api_key | none | unknown,
application: applied | draining | failed | stopped | unknown, ready,
- entry_eligible, permission_required?, message?}`. The existing native auth
+ entry_eligible, permission_required?, message?}`. In Direct mode, existing native auth
readers/provider catalog produce `auth`; no model-call test is added. A
provider counts only with an effective API/OAuth entry, not a keyless/local
catalog row. Codex keychain uncertainty is `unknown` regardless of saved mode.
@@ -139,7 +140,7 @@ ledger, config generations, schema or second lifecycle controller is added.
source, controller applied and (OpenCode only) existing tool permission.
`entry_eligible` additionally accepts a confirmed stopped controller with
persisted auth. A running service with unavailable IPC stays unknown.
-- A fresh GET observes native launch auth and the last Avibe application, not
+- A fresh GET observes the persisted authentication owner and the last Avibe application, not
continuous remote credential validity or external-file hot reload. This
limitation applies equally to Settings; known apply failure takes precedence.
- Wizard explicitly rechecks candidates, starts only a confirmed stopped
@@ -149,6 +150,16 @@ ledger, config generations, schema or second lifecycle controller is added.
and documented before choosing that route. Existing invalid enabled IM drafts
retain credential validation and the inline saved-platform recovery below.
+The Model Hub takeover extension adds `supply_mode` without changing existing
+field types or application states. Hub mode observes only referenced,
+backend-eligible runnable Sources and current credential ownership; it never
+falls back to an unrelated native login. Engine-owned presence checks return
+only a boolean and do not repair state, start processes or expose credentials.
+Pending takeover recovery blocks readiness. Setup offers Model Hub management
+before native authentication and retains the wizard while Settings is open.
+See [Backend connection ownership](model-hub-native-takeover.md#backend-connection-ownership)
+for eligibility, cooldown and retained-native subscription boundaries.
+
### Owner amendment and parallel delivery
On 2026-09-18 the owner restored the existing Web `BrandLogo` at the left of the
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index ff3e2da3b..9ecced1d0 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -64,7 +64,8 @@ No underlying engine expansion or OAuth alias substitution is part of this chang
1. Plaintext upstream credentials never appear in config, API payloads, events, logs,
or Agent runtime configuration. Hub-held material is referenced by an opaque engine
- credential id; native credentials remain in the sanctioned CLI store.
+ credential id; a retained `native_cli` Source remains in the sanctioned CLI store,
+ while an approved native migration explicitly transfers selected custody into Hub.
2. Every persisted Source has a protocol with a named owner before commit: a shipped
api-key vendor catalog pin, a user declaration on `custom`, or a matching
protocol-shaped upstream response. `POST /api/models/sources/observe` is the
@@ -110,6 +111,53 @@ No underlying engine expansion or OAuth alias substitution is part of this chang
8. Direct mode and a Native hop are distinct. Direct bypasses Gateway for the backend;
Native is one configured hop inside Gateway mode.
+### Takeover producer/consumer closure
+
+Source identity reuse retains the current credential proof and Source/ref/state.
+If the consenting backend references that Source in neither its default order nor
+an explicit Route, append it only to that backend's defaults before withdrawal.
+Do not rewrite existing Routes or other backends' orders. This also applies when
+an existing native subscription Source changes custody in place.
+
+OpenCode candidates sharing vendor, protocol, normalized target and credential
+are one logical import even when several native config layers reference them.
+Union their manual model IDs (later layer labels win for a repeated ID), and bind
+the consent identity to every contributing candidate. Distinct credentials or
+targets and all blockers remain separate. Physical cleanup still inventories and
+journals every supported config/auth path; logical deduplication cannot remove
+file compare guards or unrelated settings.
+
+Persisted native authentication and live launch configuration must converge
+before custody can complete or native admission can reopen. The internal,
+synchronous seam is:
+
+- `ModelHubService._reconcile_native_auth(backends: tuple[str, ...]) -> None`
+ reads the store's current `native_auth_snapshot`, not a guessed Hub-mode
+ projection, and supplies it to optional `migration_reconcile_auth`.
+- The Controller binds that callback to
+ `BackendRestartCoordinator.reconcile_migration_auth(snapshot) -> None`.
+ It is valid only inside that coordinator's existing migration guard with
+ request locks, native lease and both admission gates still owned.
+- The coordinator calls
+ `AgentAuthService.reconcile_native_auth_snapshot(snapshot) -> None`.
+ Only the existing native-auth fields are mirrored to live compatibility/raw
+ config consumers: Controller, handlers, agents, Claude control client and
+ Codex config aliases. Update existing objects/fields so shared aliases stay
+ coherent; do not register agents, call native auth or HTTP, launch processes,
+ release turns, restart services, or change unrelated runtime configuration.
+- After a successful V2 takeover save, mirror before the first possible
+ exposure. On exposed recovery mirror even when the Hub payload is unchanged.
+ Success and terminal completion mirror before writing a completed receipt;
+ reversal mirrors the restored persistent direction before forgetting its
+ journal. A mirror failure retains a recoverable pending transaction and closed
+ admission. Exposure remains forward-only; a pre-exposure failure may use the
+ existing reversal path. Empty-only/native-retained state is not blindly cleared.
+
+Standalone fixture services may omit the callback because they have no live
+Controller cache. Production cannot acquire the migration guard without its
+Controller owner. This is a memory-consumer correction inside the existing
+lifecycle, not another journal, marker, lock, phase or public API field.
+
## Authority and mirror guard
`mirror-registry.json` is the executable index for closed vocabularies and decision
@@ -185,7 +233,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `usage-summary.schema.json` | Metered token usage over a trailing local-day window, aggregated from proxied turns. A report only: no consumer may feed it back into resolution, admission, or cooldown. |
| `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. |
| `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. |
-| `migration-scan.schema.json` | Copy-only import of existing native CLI/provider configuration; not an internal contract migration. |
+| `migration-scan.schema.json` | Server-owned custody-takeover scan of existing native CLI/provider configuration; not an internal contract migration. |
| `runtime-dependency.schema.json` | Managed local Gateway asset, persisted enablement intent, lifecycle, and health. |
| `guard-refusal.schema.json` | Shared guarded-mutation refusal whose two arrays are the exact plan echoed by a confirmed retry. |
| `api.md` | Routes, envelopes, default Source order and manual Route writes/Restore/preview, guards, OAuth/import results, provenance, usage, and runtime status. |
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 28a16009e..311ab5b74 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -62,6 +62,14 @@ class RuntimePlatformUnsupportedError(RuntimeError):
"""The pinned managed runtime has no asset for the server host."""
+class OAuthCredentialRejectedError(RuntimeError):
+ """Authoritative rejection of a refresh grant, requiring new authorization.
+
+ An expired access token, generic 401, or profile-only permission failure
+ does not establish this outcome. Exceptions must carry no secret material.
+ """
+
+
@dataclass(frozen=True)
class SourceBinding:
"""Engine-side registration of one hub-channel source (projection of config)."""
@@ -441,15 +449,70 @@ class EngineAdapter(Protocol):
protocol: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
"""Store an API-key secret in the ENGINE-OWNED credential store and
return the opaque ``credential_ref``.
``secret`` is transient: the adapter must never log it; L2 must never
- persist it (config stores refs only). Hub OAuth credentials never pass
- through here — they are created engine-side by the OAuth flow and
- surfaced via ``OAuthFlowState.credential_ref``. Native OAuth material
- remains CLI-owned and has no ref on this seam."""
+ persist it (config stores refs only). When supplied, ``on_reserved`` is
+ called synchronously with the opaque ref after an atomic no-secret
+ reservation and before any secret bytes are written. A callback failure
+ forbids the write. Hub OAuth credentials never pass through here —
+ they are created engine-side by the OAuth flow and surfaced via
+ ``OAuthFlowState.credential_ref``."""
+ ...
+
+ async def provision_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ material: Mapping[str, object],
+ *,
+ on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
+ """Stage a native OAuth grant outside CPA's watched auth directory.
+
+ ``material`` is transient and must never cross the L2 config boundary.
+ Return a durable opaque ref, with the provider, source, and prefix
+ already bound. When supplied, ``on_reserved`` is called synchronously
+ with the opaque ref after an atomic no-secret reservation and before
+ any grant bytes are written. A callback failure forbids the write.
+ Neither provisioning nor a restart may expose the staged grant to CPA.
+ Only ``activate_oauth_credential`` transfers refresh ownership, after
+ the caller has durably withdrawn native ownership.
+ """
+ ...
+
+ async def activate_oauth_credential(self, credential_ref: str) -> None:
+ """Publish a staged grant without ever overwriting a rotated live grant.
+
+ Idempotent and cancellation-safe. The caller must persist an activation
+ intent first and must not restore old native tokens after this call may
+ have started. Preserve the only recovery handle on any failure.
+ """
+ ...
+
+ async def validate_oauth_credential(self, credential_ref: str) -> None:
+ """Require credential-specific upstream acceptance, not auth inventory.
+
+ Used for imported grants, whose origin is not a completed engine OAuth
+ flow. Does not generate inference. Raise a sanitized error on denied or
+ inconclusive authentication; never equate an auth-file upload or the
+ engine's serving-protocol pin with upstream acceptance.
+ """
+ ...
+
+ async def matches_api_key_credential(
+ self,
+ credential_ref: str,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> bool:
+ """Compare transient native material inside custody; return no secrets."""
...
async def retarget_api_key_credential(
@@ -484,8 +547,15 @@ class EngineAdapter(Protocol):
vendor: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
- """Provision an unbound credential for an unsaved observation."""
+ """Provision an unbound credential for an unsaved observation.
+
+ The optional callback has the same write-ahead semantics as the
+ permanent and OAuth provisioners. Callers that own transient cleanup
+ may journal the ref before the observation secret reaches disk.
+ """
...
async def cleanup_orphaned_oauth_material(self, credential_ref: str) -> bool:
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 40e71f3e7..90b89b8f5 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -48,7 +48,7 @@ remain readable; ephemeral envelopes use only the terminal version.
| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
| PUT `/api/models/agents/<backend>/sources` | `{order: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Atomically replaces default membership/order, preserves manual overrides, and guards effective hop removal or protected-supply loss. Pure reordering needs no guard. |
| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Compatibility default-order entry point with the same guards as Sources PUT. Never reorders manual arrays. Without order, returns the current projection. New UI uses Sources PUT. |
-| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. |
+| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. Direct-to-Hub rechecks native absence under the shared migration guard and returns `mode_switch_blocked` if credentials require consent. It does not auto-create or adopt a native Source; native custody takeover is the grouped migration transaction. Hub-to-Direct remains mode-only. |
| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data. Every OpenCode row carries required `native_protocol`; Claude and Codex rows omit it. |
| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Every OpenCode Candidate carries server-derived `native_protocol`; other backends omit it. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal. |
| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. OpenCode rows require a literal `native_protocol: openai_responses | anthropic`; rows for other backends forbid it. Each caller addition still absent from the latest list starts automatic without a route key. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |
@@ -67,11 +67,11 @@ remain readable; ephemeral envelopes use only the terminal version.
| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. |
| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels provider work. A committed flow with `client_nonce` remains the same bounded terminal `OAuthFlow` with `state: "cancelled"` until its existing `expires_at`; a flow without a nonce is forgotten. |
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
-| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same default placement and effective adoption as Add Source; original files remain byte-identical. |
+| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It validates selected items before withdrawal, upgrades an existing native Source in place when present, commits Source/Routes/backend mode atomically, and removes only replaced native material. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. |
| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 10 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
| POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. |
-| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
+| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent; runtime availability has no separate enable-confirmation step. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
The removed product-global route `PUT /api/models/priority` has no replacement. Sources
@@ -79,6 +79,38 @@ PUT and compatibility chains/reorder share backend-default semantics and effecti
preserving all manual arrays. Exact manual order is saved through the chain resource;
DELETE restores automatic and POST preview evaluates the draft without a write.
+### Native migration terminal recovery
+
+The migration apply response is successful only after the grouped custody transaction
+has completed. A transient failure after exposure keeps the private takeover journal
+pending and returns `migration_recovery_pending`; retry continues cleanup and projection
+without restoring native custody.
+
+An exposed journal may instead carry the private terminal decision
+`terminal: {invalid_source_ids: string[], config: <canonical target Model Hub config>, reason?: "reauth_requested"}`.
+The terminal `config` and optional `reason` are durable replay inputs and are never
+returned as new public request/response fields. Without `reason`, this decision is
+reserved for an authoritative credential-specific refresh rejection: crash recovery
+trusts it, finalizes each `invalid_source_ids` Source as `status: needs_action` with
+`detail_key: models.source.needs_action.oauth_expired`, and does not revalidate the
+rejected grant. Once that terminalization is durable, the pending journal and
+admission block are cleared and the receipt records `outcome: needs_auth`.
+The original apply and identical retries return `migration_credentials_invalid` and
+never report migration success. An expired access token, generic `401`, or a pinned
+CPA inventory/status string alone cannot create this terminal decision; an
+inconclusive or generic failure remains pending.
+
+When an existing, explicitly acknowledged `reauth_source` requests repair, the
+guarded finish-custody path records `reason: reauth_requested`, verifies native
+withdrawal and the current CPA credential references, marks unresolved OAuth Sources
+as needing sign-in, retains the current Hub grants, and then starts the usual Hub
+login. Its durable receipt records `outcome: reauth_requested`, never migration
+success or proof of expiration. Crash replay finalizes the recorded decision without
+another upstream validation or automatic browser start. If the exact consented native
+material reappears, durable cleanup removes it again while retaining the current Hub
+references; an old receipt never restores a stale OAuth snapshot, and changed or
+additional rows require fresh consent.
+
## Unsaved Source observation
`POST /api/models/sources/observe` accepts only the observation subset of a Source
@@ -297,7 +329,8 @@ every other existing field and enum meaning remains unchanged.
| `Source.adopted_by` | Source read assembler | Source cards and Source detail status | Complete unique persisted-reference projection for backends currently in Hub mode, sorted by backend then menu model; clients do not derive it from `hops`. Routes retained by Direct-mode backends are excluded because they bypass the gateway. |
| `AgentSupply.cli_present` | backend CLI detector | zero-installed-backend state | Boolean installation fact only; it does not imply login or process readiness. |
| `AgentSupply.model_supply[].has_runnable_hop` | exact-chain live annotator | backend-group collapse predicate | Uses the AgentChain runnability axiom rather than inferring liveness from configured membership. `chain_length: 0` forces false; a nonzero length may carry either value. |
-| `RuntimeDependency.enabled` | explicit runtime start/stop mutation | Gateway switch and service-start recovery | Persisted user intent, independent of observed process health. Missing in older config defaults to false; an older response without the field falls back to observed health in the UI. |
+| `RuntimeDependency.enabled` | explicit runtime start/stop mutation | Gateway switch and service-start recovery | Persisted user intent, independent of observed process health. Fresh/default configuration is true; explicit Stop persists false. |
+| `model_hub.runtime_default_applied` | config loader/default migration | one-time legacy upgrade and runtime-start recovery | Additive persisted marker. Missing on disk upgrades once to `enabled: true` and `runtime_default_applied: true`; later explicit Stop remains false. |
| `RuntimeDependency.host_platform` | server host detector | unsupported-host runtime pill | Names the Avibe host, not the browser; exact membership in `manifest.assets[].platform` decides install support. |
| `RuntimeDependency.status.error_key` | runtime installer | install-failed runtime state | Closed persisted i18n key: `settings.models.install.fail.detail` after installation fails; null after a new attempt begins and in every non-failure state. |
| `RouteHopRef.position` | guarded mutation planner | guarded-change hop row | One-based position in the named Route before the attempted mutation. |
@@ -444,8 +477,9 @@ Both accept optional `force`, `would_remove_hops`, and `would_interrupt` fields.
The order is the complete desired default subset, including an empty subset. Every id
is unique, existing and configuration-eligible; invalid input returns
`invalid_source_order`. Manual routes can name other eligible Sources and are never
-rewritten by either operation. Source creation/native import append eligible defaults;
-refresh, health and turns do not rewrite order.
+rewritten by either operation. Source creation and migration choose or retain eligible
+defaults according to their transaction contract; refresh, health and turns do not
+rewrite order.
`mutation.default_sources` stages the order under the mutation lock and compares
before/after effective plans. Existing exact-plan guards cover effective hop removal
@@ -457,20 +491,15 @@ Eligibility remains server-authoritative. Ineligible rows carry the closed reaso
eligible rows carry null. The frontend never matches inventory or infers intent from
array equality. Default changes affect only the chosen backend.
-### Direct-to-Gateway native adoption
+### Direct-to-Gateway mode switch
For `PATCH /api/models/agents/<backend>/mode`, a transition from `direct` to `hub`
-reuses the same sanctioned native-login recognition and response-backed observation
-boundary as native import. If that backend has a recognized CLI login and has no
-`native_cli` Source, the mode change, creation of the backend's singleton native Source,
-default Source-order insertion commit in
-one transaction. The returned `AgentSupply` is assembled after that commit and exposes
-the resulting order, eligibility, sparse manual Routes, and effective supply summaries.
-
-An existing native Source, an unrecognized or absent CLI login, or any transition other
-than `direct` → `hub` creates nothing. The mode switch itself remains legal in those
-cases. Repeating the request never creates a second native Source. `cli_present` alone
-does not satisfy the recognition predicate.
+changes only the persisted backend mode. It does not inspect native login state, create
+or adopt a `native_cli` Source, insert default membership, or invoke the migration
+transaction. Native custody takeover is the grouped migration operation described in
+§6 and requires its own consent and journal. Repeating the request remains idempotent
+and creates no Source; the returned `AgentSupply` reflects the mode with its existing
+Source order, sparse manual Routes, and effective supply summaries.
### Manual Route configuration and preview
@@ -1394,7 +1423,9 @@ Minimum v5 set:
`candidate_suppliers_changed`, `mode_switch_blocked`, `engine_down`,
`runtime_platform_unsupported`, `reauth_confirmation_required`,
`native_source_already_exists`, `native_login_in_progress`,
-`migration_item_conflict`, `source_model_tiers_managed`, `turn_not_found`,
+`migration_item_conflict`, `migration_native_busy`, `migration_permission_needed`,
+`migration_configuration_blocked`, `migration_recovery_pending`,
+`migration_credentials_invalid`, `source_model_tiers_managed`, `turn_not_found`,
`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.
`source_model_tiers_managed` is the HTTP 409 refusal for editing an `upstream` or
@@ -1408,6 +1439,23 @@ its structured sibling is `{existing_source_id}` and the adapter is not invoked.
owner. It means another login currently owns the same credential; retry remains on the
native channel and the response does not assert that a native Source already exists.
+Migration action errors are closed, redacted boundary codes:
+
+- `migration_native_busy`: a managed native process could not be drained or an
+ external CLI still owns the credential.
+- `migration_permission_needed`: the selected native store or file operation requires
+ permission that was not granted.
+- `migration_configuration_blocked`: a malformed, unsupported, conflicting, or
+ overriding native configuration blocks the whole backend; no partial import is
+ presented as success.
+- `migration_recovery_pending`: custody was exposed but durable cleanup or projection
+ is incomplete; the affected backend remains blocked and retry continues recovery.
+- `migration_credentials_invalid`: an authoritative adapter established refresh
+ grant rejection (the pinned CPA inventory alone cannot). Hub custody is retained, the Source is
+ marked `needs_action` with `models.source.needs_action.oauth_expired`, the pending
+ transaction is cleared only after durable terminalization, and a retry receipt never
+ reports success. An expired access token alone is not this error.
+
Boundary-only action-refusal values cover operations the UI already does not offer but
a script or regression can call directly. `reauth_confirmation_required` is API/test-
only truth: it has no product copy key or rendering slot.
diff --git a/docs/plans/model-hub-contracts/migration-scan.schema.json b/docs/plans/model-hub-contracts/migration-scan.schema.json
index 791fda604..9eaffbae1 100644
--- a/docs/plans/model-hub-contracts/migration-scan.schema.json
+++ b/docs/plans/model-hub-contracts/migration-scan.schema.json
@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/migration-scan.schema.json",
"title": "MigrationScan",
- "description": "Result of scanning native backend configs (spec §6, frame 03). Non-destructive: apply copies only; originals are never modified or deleted (tested property, plan M4).",
+ "description": "Result of scanning native backend configs. Rows marked import are eligible for the server-owned custody-takeover transaction; native material is withdrawn only after staged replacement validation and durable exposure. Blocked native shapes remain visible as keep_native or reauth rows.",
"type": "object",
"required": ["items"],
"additionalProperties": false,
@@ -20,7 +20,7 @@
"masked_detail": { "type": "string", "description": "e.g. 'sk-…dd3c + 自定义 Base URL'; never full secrets" },
"proposed_action": {
"enum": ["import", "controlled_import", "keep_native", "reauth"],
- "description": "Claude and Codex native OAuth logins remain in the sanctioned CLI store via keep_native; subscription OAuth tokens are never copied by this file-import surface. Hub-held subscriptions are established only by the explicit OAuth add flow. controlled_import remains reserved for a future engine-owned import capability. API keys and Base URLs use import."
+ "description": "import is a supported API-key or complete refresh-capable OAuth takeover. keep_native is a visible, unselected blocker for access-only, unsupported, malformed, or otherwise non-exportable native material; reauth is the explicit invalid-grant/authentication path. controlled_import remains parseable and reserved."
},
"selected": { "type": "boolean" },
"notes_key": { "type": ["string", "null"], "description": "i18n key for the row's secondary line" },
@@ -35,7 +35,7 @@
{
"items": [
{ "id": "mig_1", "backend": "claude", "kind": "api_key", "masked_detail": "sk-…dd3c + custom base URL", "proposed_action": "import", "selected": true, "notes_key": null },
- { "id": "mig_2", "backend": "claude", "kind": "oauth_native", "masked_detail": "Claude 账号登录(OAuth)", "proposed_action": "keep_native", "selected": true, "notes_key": "models.migration.keep_native.sanctioned" },
+ { "id": "mig_2", "backend": "claude", "kind": "oauth_native", "masked_detail": "Claude 账号登录(OAuth)", "proposed_action": "import", "selected": true, "notes_key": null },
{ "id": "mig_3", "backend": "opencode", "kind": "opencode_provider", "masked_detail": "智谱 API Key · glm-…c31b", "proposed_action": "import", "selected": true, "notes_key": null }
]
}
diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
index ecc295724..b5c03e7cc 100644
--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json
+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/runtime-dependency.schema.json",
"title": "RuntimeDependency",
- "description": "v5 managed engine dependency manifest + persisted user intent + server-owned installation and runtime status. not_installed -> installing -> not_started is the installation path; not_started is installed lazy-start idleness, and down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.",
+ "description": "v5 managed engine dependency manifest + persisted user intent + server-owned installation and runtime status. not_installed -> installing -> not_started is the installation path; not_started is installed lazy-start idleness, and down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin. The one-time default-on upgrade marker is persisted in model_hub config, not returned on this runtime response.",
"type": "object",
"required": ["contract_version", "manifest", "status"],
"additionalProperties": false,
@@ -10,7 +10,7 @@
"contract_version": { "const": 10 },
"enabled": {
"type": "boolean",
- "description": "Persisted user intent for the managed gateway. Missing on older payloads means clients must fall back to observed health."
+ "description": "Persisted user intent for the managed gateway. Fresh/default configuration is true; explicit stop persists false."
},
"host_platform": {
"type": "string",
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.md
index 851fcd2f5..259558fe0 100644
--- a/docs/plans/model-hub-e2e-test-plan.md
+++ b/docs/plans/model-hub-e2e-test-plan.md
@@ -90,8 +90,8 @@ Out of scope (documented, not dropped silently):
### F. Migration (C61–C67)
| ID | Steps | Expect | Status |
|---|---|---|---|
-| F1 | seed hermetic HOME with native claude/codex/opencode configs; scan | correct action matrix; opencode unsupported ids noted | assert |
-| F2 | apply selection | copy-only import; native login committed before imported keys (one-time sort); original files untouched | assert |
+| F1 | seed hermetic HOME with native claude/codex/opencode configs; scan | complete Claude API-key custody is importable; access-only Codex OAuth and unsupported OpenCode credentials remain visible blockers; no credential material is returned | assert |
+| F2 | apply the selected complete backend group | Claude API-key custody is committed and its direct native auth is cleaned; blocked Codex/OpenCode material and unrelated Claude settings remain unchanged | assert |
| F3 | first open `/settings/models` after upgrade with importable items | banner visible (B2 — currently only in wizard: expected-fail until mounted) | fix-first |
### G. Guards and contract hygiene (C51–C53, B3,B7,B13,B16)
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
index e73ef957d..f4c52fe89 100644
--- a/docs/plans/model-hub-implementation.md
+++ b/docs/plans/model-hub-implementation.md
@@ -229,7 +229,7 @@ that reconciliation may change content but is not expected to change file owners
| **I4 Sources / Gateway UI** *(tentative; one lane, two increments)* | codex | `ui/src/components/settings/models/**`; `ui/src/i18n/*.json`; `vibe/i18n/*.json`; UI tests. Both i18n trees are I4-exclusive. The current increment consumes the already-specified install/unsupported-host surfaces for AC-38/AC-43; each model row may open frame 02, render the drawing, and consume the chain read projection, but no chain-write caller is wired and Save remains disabled. Exact-chain editing and its UI tests belong to the second increment only after K5's third-round G-32 specification merges. That second increment sends visible noninterrupting hop removal as one ordinary PUT and echoes both refusal-plan arrays unchanged only when protected supply would be interrupted, after I7 freezes both fixtures; the current increment continues to consume master's pre-I7 refusal shape and must not add inactive confirmation fields. It consumes AC-36/37/39–42/44–50 only after K5 round 2 changes their G rows from gaps to contract references and registers the live-backoff presentation; AC-51's read-before-retry client rule activates in the second increment after I7 freezes the deletion/recreate fixture. AC-53's materialization-error `interrupted_pairs` consumer activates only in that second increment after K5 round 2 registers E6 and I7 freezes positive/negative API payload fixtures. AC-54's `accept_unavailable_inventory` producer also belongs to the second increment after K5 round 2 names state ⑤ and I7 freezes both server-result cells; clean creation and pull-origin state ⑤′ never emit it. This is an ordering split inside I4, not a new lane identity. **Revised through the 2026-08-12 04:40 PM ruling.** | current increment: I1 envelopes + K4 contracts; second increment: K5 rounds 1–3 merged + frozen I7/I2/I3 fixtures |
| **I7 contract-completion implementation (backend)** | codex | After K6 merges, exclusive ownership transfers from I1 for `config/v2_config.py`; `core/handlers/model_hub/{service,resolver,classification,rpc,request,errors,events}.py`; `modules/agents/model_hub.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; and `tests/test_model_hub_resolution.py`. For the Model Hub failure-callback seam only, I7 also exclusively owns `modules/agents/base.py`, `modules/agents/claude_agent.py`, `modules/agents/codex/{agent,event_handler}.py`, `modules/agents/opencode/{agent,poll_loop}.py`, exact cross-backend phase fixtures in `tests/{test_claude_agent_sessions,test_codex_agent,test_opencode_server}.py`, and mechanical signature consumers in `tests/{test_claude_cli_path,test_multi_platform_runtime}.py`. I7 owns AC-35–AC-47 and AC-50–AC-54's backend producers/tests plus AC-48's API/service half. `service.py` is the sole shared guard-plan owner and implements every guard-totality row and the error-to-required-array relation; it also enforces AC-52's both-channel re-auth acknowledgement before any OAuth adapter call and AC-53's materialization-error response condition, and AC-54's unavailable-inventory consent gate against the repeated server observation. `modules/agents/model_hub.py` owns the native classification/state decision: backend callbacks supply raw failure shape and phase only, and no native path writes a persistent network cooldown. The transferred resolver/classifier/event boundary owns `retired: false` filtering and all four network-failure cells; its post-output executor/provenance fixture consumes K6's G-34 row without inventing an outcome id, copy key, or payload shape. I7 delegates OAuth tuple claim/coalescing and terminal-flow expiry to I3's registry; its service/API half branches explicit cancellation by nonce presence, retaining the I3 flow for nonce-bearing reconciliation and forgetting only no-nonce flows. Its first AC-50 mechanical action is the sole owner-authorized I2-file exception: delete the strict xfail marker from `tests/test_model_hub_l3.py::test_probe_transport_failures_await_ac50_backoff_contract` in the same commit that makes its forward contract assertions XPASS; it otherwise consumes I2 managed-Gateway facts and I3 OAuth fixtures without editing their files. It never edits contracts, UI/i18n, scenario trees, or any other I2–I5 file. **Revised through the 2026-08-12 04:40 PM ruling.** | K4 + #1312 + K6 merged; every listed transfer and native callback seam activates only after all three merge |
| **I5 scenario validation** *(tentative)* | codex | `tests/scenarios/model_hub/**` except I3's native-import scenario; `tests/scenario_harness/**` | I1–I4 + I7 |
-| **I8 bounded recovery presentation integration** *(orchestrator-approved 2026-09-09)* | codex | `core/model_hub_progress.py` consumes canonical resolver timestamps and the read-only request recovery snapshot for the existing live working/activity surface. It does not classify, retry, write Source health, or own another recovery timer. Controller, native-terminal and UI integration remain orchestrator-owned; this registration gives the new resolver consumer one explicit owner without transferring core policy ownership. | Approved recovery contracts and the core policy/provenance hooks |
+| **I8 bounded recovery and readiness observation** *(orchestrator-approved)* | codex | `core/model_hub_progress.py` consumes canonical resolver timestamps and the read-only request recovery snapshot for the existing live working/activity surface. `vibe/api.py` projects backend connection readiness from canonical eligibility/runnability and an engine-owned boolean credential-ownership check, following the native takeover contract. Neither observer classifies, retries, writes Source health, or owns another recovery timer. Controller, native-terminal and UI integration remain orchestrator-owned; each resolver consumer has one explicit owner without transferring core policy ownership. | Approved recovery contracts, native takeover connection-ownership contract, and the core policy/provenance hooks |
| **I6 default-on availability** *(owner-approved 2026-09-06)* | codex | Replace the shared capability resolver's absent-variable default with enabled; retain its explicit deployment/emergency opt-out. Verify controller aggregate construction, public API/capability projection and internal RPC with no environment opt-in. Saved backend modes, routing, model selection and engine-install consent remain unchanged. This supersedes the historical default-off and full gate-deletion directions below; it is not a constant-true shell. | Owner requested a PR to make Model Hub available by default. Full merged LOCAL live/visual acceptance remains outstanding and is not waived or claimed by this release-default change. |
**Executor ruling (owner, 2026-08-09; I7/K5/K6 registry completed 2026-08-12).** Every new K5, K6, and I1–I7 lane uses
diff --git a/docs/plans/model-hub-native-takeover.md b/docs/plans/model-hub-native-takeover.md
new file mode 100644
index 000000000..e423e54b9
--- /dev/null
+++ b/docs/plans/model-hub-native-takeover.md
@@ -0,0 +1,349 @@
+# Model Hub native credential takeover
+
+Status: approved product and custody contract. Acceptance requirements and
+remaining live-account verification boundaries are described below.
+
+## Approved user flow
+
+- The gateway runtime is enabled by default for new and upgraded installations.
+ Starting or installing it does not require an enable-confirmation dialog.
+ Runtime enablement is not consent to transfer or delete native credentials.
+- Switching a backend from Direct to Hub first offers the existing migration
+ dialog when native credentials are present. The dialog selects accounts and
+ has one consequence sentence plus **Not now** / **Start migration**.
+ Dismissing it leaves the backend and native authentication unchanged.
+- The same dialog is available to existing Hub users through **One-click
+ migration**. Existing native subscription sources are eligible for custody
+ conversion, not suppressed as duplicates.
+- With no native credentials to migrate, the mode switch proceeds directly.
+ Missing credentials use the existing Add subscription / Add API key flows.
+ The service rechecks absence under the shared migration/native-writer guard;
+ a login created after the UI scan rejects the mode-only switch. It never
+ imports or deletes that new login without migration consent.
+- Progress and failures describe only the current state and a necessary action.
+ Success means takeover and cleanup completed, not just import accepted.
+- Chinese product name: `模型网关`; English: `Model Hub`. The approved Chinese
+ consequence sentence is exactly:
+ `迁移后,CLI的认证信息将完全交由模型网关管理`
+
+## Public boundary
+
+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[] }` |
+
+Scan is read-only. It never transfers custody, prompts for browser login,
+refreshes tokens, deletes native material, or returns secrets. Item IDs bind
+the selected credential revision and destination identity. Applying a stale
+selection must not transfer a different account.
+
+`proposed_action: "import"` identifies a supported transfer. Existing legacy
+`keep_native`, `controlled_import`, and `reauth` values remain parseable, but
+are not successful takeovers and must not be submitted by the migration
+confirmation UI. File and OS credential-store support belongs behind the same
+native-store interface; Keychain storage alone is not a reason to require a
+new browser login. An actual permission or compatibility problem is actionable.
+
+The server owns source placement, backend mode changes, and native cleanup.
+The UI must not run a destructive migration followed by a separate mode PATCH
+and then present that two-request sequence as atomic.
+
+## Ownership invariants
+
+1. All selected credentials are checked before native ownership is withdrawn.
+ Provisioning an OAuth auth file in a live CPA is already an ownership
+ transition: CPA may refresh immediately, without an inference request.
+2. Stage credentials privately outside CPA's watched auth directory. Quiesce
+ native users and verify the native revision has not changed before cleanup.
+ Avibe-managed launches must not race the handoff. An external CLI that must
+ exit is reported as an actionable blocker, never silently killed.
+3. Engine custody, source identity, route placement, and backend mode are
+ recoverable together. An existing native source keeps its ID and user-owned
+ routes when converted; no duplicate or silently reordered paid source.
+4. Before engine activation, rollback can restore an unchanged native snapshot.
+ After activation might have rotated a token, never delete the newest grant
+ or restore a stale token as if it were an all-or-nothing rollback. Recovery
+ must retain the single current owner and finish the handoff.
+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 is
+ required for a compatible, valid, refresh-capable native grant.
+6. Remove only replaced authentication and direct-routing settings. Preserve
+ sessions, skills, MCP, unrelated providers, and unrelated configuration
+ fields. Recheck all supported precedence layers so an overriding project,
+ environment, or legacy setting cannot silently keep direct authentication.
+7. A partial cleanup, denied Keychain operation, busy native process, invalid
+ grant, or failed persistence is not success. Error messages contain no token
+ material. Cancellation must not abandon an ownership transition.
+
+## Acceptance
+
+Use hermetic fixture homes, mocked OS credential stores, and a fake management
+server; never develop against real user credentials. Cover API-key and OAuth
+takeover, existing-native-source conversion, repeated application, stale scans,
+mixed providers, non-ASCII metadata, read/write denial, active CLI users,
+cancellation and crash boundaries, and preservation of unrelated settings.
+UI checks cover both entry points, dismissal with no mutation, no automatic
+migration on runtime start, exact approved copy, locale parity, and truthful
+completion/failure states. Real-account refresh and inference remain a separate
+explicitly authorized acceptance check.
+
+## Implementation seams
+
+- `EngineAdapter.provision_oauth_credential(source_id, vendor, material) -> str`
+ stages only, outside the watched auth directory.
+- API-key, transient observation-key, and OAuth provisioning accept the optional
+ keyword `on_reserved: Callable[[str], None] | None = None`. The engine atomically
+ reserves a fresh opaque ref without secrets, refuses an existing ref before
+ invoking the callback, and invokes it synchronously before writing any secret
+ bytes. The callback receives only the ref; failure forbids secret writes.
+ The owned worker is joined even on repeated cancellation. This is an internal
+ write-ahead seam, not a public reservation endpoint or another journal.
+- Migration registers `(final_source_id, credential_ref, revoke_credential)` in
+ the existing revocation journal; rollback uses that same identity. Transient
+ observation keys use their existing `observation` cleanup owner. The callback
+ returns only after both the journal file and its directory are fsynced.
+ Provisioning failure before returning a ref is still covered by that owner.
+ The prepared takeover record must be durable before relinquishing provisional
+ ownership. Startup recovers takeover before replaying pending revocations;
+ a matching current Source/ref is retained, including a rotated OAuth grant.
+- Revocation first confirms the ref is unbound. Even without credential
+ metadata, it deletes only that ref's private OAuth stage/reservation and
+ fsyncs the affected directory; absent paths are idempotent success. Missing
+ metadata never authorizes guessing an auth filename, deleting watched grants,
+ management API calls, or sweeping a directory. Cleanup/fsync failure retains
+ the pending ref. Unlocatable possibly exposed material stays pending.
+- `EngineAdapter.activate_oauth_credential(credential_ref) -> None` publishes
+ idempotently after the durable ownership decision; a retry never overwrites
+ an existing live (possibly rotated) grant.
+- `EngineAdapter.validate_oauth_credential(credential_ref) -> None` requires
+ credential-specific upstream acceptance, without inference. The existing
+ `observe_source` protocol pin is insufficient for imported grants.
+ Validation uses CPA's credential-scoped `/api-call` with a bodyless GET to
+ Claude's `/api/oauth/profile` or Codex's `/backend-api/wham/usage`. Only a
+ 2xx upstream response with the provider's account/usage shape is an
+ authentication witness: a nonempty string `account.uuid` for Claude or
+ `plan_type` for Codex. Unknown nonempty plan names remain forward-compatible;
+ quota/entitlement fields do not decide authentication. Error envelopes,
+ malformed payloads and non-2xx responses remain inconclusive. No inference
+ endpoint, model catalog, or direct refresh is used. This proves current
+ access-token acceptance, not inference entitlement or future refresh success.
+- `ModelHubService.migration_guard` is a callable taking
+ `tuple[BackendName, ...]` and returning an asynchronous context manager.
+ Entering it closes managed native admission, waits for active work (without
+ a forced cancellation), strictly retires credential-bearing idle processes,
+ and checks for external CLI users. It is acquired before `_mutation_lock`.
+ Production installs wire it from the Controller; no production no-op.
+ Configured CLI identity is independent of backend enablement: the existing
+ auth-service binary resolver supplies raw/compatibility paths and persisted
+ paths omitted by disabled compatibility backends. Inventory validates persisted
+ evidence for every raw/compatibility shape: unreadable or recovered binary
+ configuration cannot fall back to a default identity and certify idleness;
+ ordinary Settings probes remain best-effort. Process matching recognizes direct
+ executables and script entrypoints behind Node/Bun, Python-family and
+ POSIX-shell interpreters. Startup options consume their operands; matching stops
+ at the script or an eval/module/stdin mode, never a later prompt argument.
+ A lone `-` ends shell options but selects stdin for Python/Node.
+ Ambiguous startup syntax containing a possible native executable refuses the
+ inventory. No script contents, process environments or arbitrary shell/eval
+ code are inspected or executed. Initial admission and idle rechecks use the
+ same matcher; this does not promise exclusion of arbitrary uncooperative
+ writers or new external launches after the check.
+- `ModelHubService.migration_blocked_backends` is a set of backend names that
+ must remain blocked after the guard exits if durable takeover recovery is
+ incomplete. Completed or fully reverted transactions remove their names.
+ Startup recovery restores this set before runtime startup or admission.
+- `vibe.native_oauth_store.read_native_oauth(backend, *, home=None,
+ allow_secret=False) -> NativeOAuthSnapshot | None` resolves the effective
+ native store. A snapshot has `backend`, stable selection `revision`, private
+ `payload: dict | None`, `exportable: bool`, and
+ `keychain_edit: dict | None`. File-backed payloads may be read by scan;
+ secret-bearing OS-store access occurs only with `allow_secret=True`.
+ A caller-supplied fixture `home` never accesses the real OS credential store.
+ An unsupported store must not fall back to an inactive stale file.
+- `vibe.native_oauth_store.apply_keychain_edit(edit: dict, *, reverse=False)`
+ compares the live entry against recorded before/after states before changing
+ it, preserving unrelated fields. The private edit is journal-serializable;
+ scan never serializes it. This function never performs remote logout/revoke.
+ A Keychain candidate's selection revision must match between metadata-only
+ scan and its secret-bearing apply read.
+- `check_keychain_edit(edit, *, applied=False)` checks the exact before/after
+ value without mutation. The Controller journals a bundle of keychain
+ operations, and folds file operations into one `NativeFileEdit` per path.
+ Store helpers never silently roll back: the durable transaction owns recovery.
+- A metadata-only Keychain candidate may request consent without claiming its
+ value is exportable. The selected container revision is checked after drain;
+ only then are its supported API-key and OAuth components expanded. A denied
+ read or unsupported component leaves native ownership intact.
+ A consented, unchanged container containing only unrelated data is verified
+ clean, not an error or an imported Source. Its revision is retained in the
+ existing completed receipt; unrelated bytes are not changed. Any new revision
+ requires consent again. A selector for a verified-empty Codex store remains
+ unchanged so later native logins at that locator remain observable.
+ Empty-container evidence never authorizes cleanup of an unimported file
+ grant. When the entire batch contains only verified-empty containers, no
+ credential is exposed: the existing `withdrawn` phase remains reversible
+ through runtime start. A changed container restores the previous mode and
+ releases the pending transaction for fresh consent, without restoring or
+ deleting any credential bytes.
+
+## Durable transaction
+
+The private `native-takeover/current.json` envelope has `version: 1`,
+`phase: prepared | withdrawn | exposed | reverting`, and a nonempty
+`backends: string[]`. A pending journal blocks conflicting native auth writers
+and selected backend launches across Controller/Web processes. Completed work
+writes a sanitized idempotency receipt and removes the pending journal.
+
+The prepared record contains selected public rows, opaque source/credential
+identities, previous/target Hub config, legacy native-auth before/after values,
+and private native file/store edits. The containing directory is mode 0700;
+the record is mode 0600. These snapshots are never response or log payloads.
+
+Prepare, runtime dependency installation, and API-key validation precede
+cleanup. Reusing an existing API-key Source/ref still requires current upstream
+proof of that exact protocol and target; equality of saved key bytes alone is
+not validation. Installation or unsupported-host failures leave native ownership
+intact; staged OAuth grants remain outside the watched auth directory even
+if dependency installation restarts an existing runtime.
+After cleanup, Source/Routes/
+backend mode and legacy auth fields are committed without calling the runtime.
+The `exposed` marker is durable before activation **or engine projection**.
+Recovery explicitly reconciles the projection even when saved config is
+already identical. While a prepared transaction still owns provisional refs,
+ordinary engine reconciliation must not revoke those refs merely because
+they are not yet bound in config. An uncertain prepared-record save outcome
+is resolved by durable recovery, not local grant deletion.
+OAuth completion additionally requires credential-specific
+upstream validation; an invalid or unavailable grant after possible exposure
+is never restored as a native login. Unavailable or inconclusive validation
+keeps takeover pending. Authoritative refresh-grant rejection instead records
+a terminal decision in the exposed journal, marks affected Sources
+`needs_action` / `models.source.needs_action.oauth_expired`, and finishes custody
+without reporting migration success. The receipt records `outcome: needs_auth`;
+apply and identical retries return `migration_credentials_invalid`. The pending
+journal and admission block are removed so the existing Hub reauthentication
+flow remains usable. Crash recovery replays the terminal decision without
+repeating a rejected refresh. An expired access token or generic 401 alone
+cannot establish this terminal outcome.
+
+The pinned CPA version does not expose refresh-specific error provenance:
+scheduled refresh failures can become `token expired`, while request errors
+can populate the same inventory status string. The concrete adapter therefore
+does not infer authoritative rejection from that inventory. No runtime upgrade
+or heuristic classification is part of this change.
+
+An inconclusive exposed takeover remains retryable. The user's existing,
+explicitly acknowledged Hub reauthentication action is also a repair path:
+under the same lifecycle/credential guard, persist a terminal decision with
+`reason: reauth_requested`, verify native withdrawal and the current Hub refs,
+mark the unresolved OAuth Sources as needing sign-in, and finish custody
+before starting the existing Hub flow. Keep the engine's current grants;
+never restore native material. The receipt records `reauth_requested`, not
+success or proof of expiration. Recovery replays this decision after a crash
+without another upstream validation or automatically starting a browser flow.
+Per-Source successful validation is persisted in the pending journal, so a
+verified sibling does not require another sign-in because a later Source fails.
+
+Shutdown joins the owned operation before stopping the runtime. Client
+cancellation cannot cancel credential custody. A retry after completion checks
+the retained source IDs, opaque credential references, and native inventory
+under the lifecycle guard, not IDs alone. If the exact consented native material
+has reappeared, a new durable cleanup retains the current Hub credentials;
+replaying an old receipt never republishes a stale OAuth snapshot. Changed or
+additional native credentials require fresh consent.
+Completed receipts also retain metadata-only revisions of verified clean
+native stores containing unrelated material. Scans suppress only those exact
+placeholders; a changed revision becomes a candidate again. This avoids reading
+Keychain secrets on every scan or presenting preserved MCP data as a new login.
+
+### Authentication witness evidence
+
+- Pinned CPA commit `2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`,
+ `internal/auth/claude/anthropic_auth.go`: `ProfileURL`,
+ `fetchOAuthControlPlaneJSON`, and `FetchOAuthProfile`.
+- Official Codex `rust-v0.154.0`, commit
+ `6b9826e3aa83b1a5947db50f4332cb9c65f1b340`:
+ `codex-rs/backend-client/src/client/rate_limit_resets.rs` and
+ `codex-rs/codex-backend-openapi-models/src/models/rate_limit_status_payload.rs`.
+ The usage decoder requires `plan_type` and accepts unknown enum names;
+ missing quota windows and `allowed: false` do not negate authentication.
+- Pinned CPA `internal/api/handlers/management/api_tools.go`: `/api-call`
+ substitutes `$TOKEN$` from the selected current engine record. Its outer
+ HTTP success is not the inner upstream acceptance.
+
+These source contracts justify the synthetic success fixtures. Live-provider
+acceptance, refresh and inference still require separate authorized testing.
+
+## Backend connection ownership
+
+The existing backend connection observation must follow persisted supply mode.
+It exposes additive `supply_mode: "direct" | "hub"`; existing `auth`,
+`application`, `ready`, and `entry_eligible` fields retain their types.
+Direct observations retain native credential behavior. Hub observations use
+the configured backend-eligible Sources and their credential ownership, not
+the native stores that takeover deliberately cleared. A missing, disabled or
+unusable Hub supply must not fall back to an unrelated native login. Existing
+application/drain, backend enablement, installation and OpenCode permission
+gates remain effective. This is connection readiness, not an inference probe
+or a promise that every selected model is available.
+
+Direct Claude retains its existing bounded `auth status --json` observation
+for Keychain-backed sign-in; opaque Keychain metadata cannot distinguish an
+OAuth grant from an unrelated MCP-only container. The native credential lease
+covers that query and its thread completion, with custody checked before
+launch. This is not a login, refresh or inference request. Hub connection
+observation never launches this query or borrows an unrelated native login.
+
+Only Sources referenced by the backend's effective source order or explicit
+route hops participate. Eligibility reuses the existing backend and
+`source_runnable(now=...)` rules: an unexpired cooldown temporarily prevents
+entry; verification-pending standby Sources remain eligible. No selected model,
+inventory or entitlement check is added. Hub-owned credentials require a
+current matching private credential record, observed through an engine-owned
+read-only boolean helper. This observation neither exposes credential payloads
+nor creates directories, repairs permissions, starts CPA or contacts upstream.
+A nonempty reference alone is not evidence that its credential still exists.
+Retained native subscriptions use the existing native-source readiness check,
+only for an explicitly referenced subscription owner of the same backend.
+Pending takeover recovery blocks readiness without inventing a new public
+`application` state.
+
+Setup and Settings consume `supply_mode` to offer Model Hub management before
+asking for a native login or key. Server ownership refusals remain the race-safe
+fallback. Opening Model Hub from setup preserves the wizard and all session,
+owner and capability authorization checks; returning refreshes connection
+observations so the cleared native store cannot strand setup.
+
+## Writer-boundary review decision
+
+The integration audit found the same ownership-boundary class beyond login
+flows: recovery backups and whole-document native configuration writers can
+reintroduce credentials after a successful handoff. The correction covers
+every Avibe writer of those shared documents for the full read-modify-write
+duration. Authentication writes also consult persisted Direct/native-Source
+ownership after acquiring the lease; stopping the Hub runtime does not hand
+custody back. Non-authentication edits may continue under the shared lease.
+Claude's interrupted-OAuth settings backup is included in the migration
+inventory and cleanup, so constructor recovery cannot restore a replaced key.
+This scope preserves legacy native subscription Sources until explicit
+takeover, without introducing another permanent ownership marker.
+
+## Compatibility and platform limits
+
+Migration targets ordinary Codex and Claude Code native grants supported by
+the pinned CPA runtime. Explicit custom client IDs or grants whose recorded
+scopes omit CPA's refresh scopes are blocked before custody. Missing metadata
+uses the ordinary native-store contract; validation still requires upstream
+acceptance. Extra connector/plugin permissions are not promised to survive a
+CPA refresh.
+
+OS-store mutations use the observed item identity and metadata, immediate
+compare-before-write, and readback. macOS Security does not provide an atomic
+value-CAS against arbitrary external writers. The application-wide lease and
+external-CLI drain are therefore required; they do not claim to prevent an
+uncooperative process starting or modifying the same item during the native
+API's internal mutation window. This limitation is not permission to overwrite
+a detected concurrent login.
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 661c257f8..13423f89c 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -960,9 +960,13 @@ dead-end error string.
and installation is supported exactly when it equals one
`manifest.assets[].platform`. The install route and status reads mirror this closed
state set; prose cannot add another runtime health value. `RuntimeDependency.enabled`
-is orthogonal persisted user intent: it defaults to false when absent, explicit Start
-sets it true, explicit Stop sets it false, and service startup starts the runtime only
-when it is true. A transient process loss changes health, never this switch state.
+is orthogonal persisted user intent. New configurations default it to true without an
+enable-confirmation dialog. The additive persisted
+`model_hub.runtime_default_applied: bool` marker defaults to true; a pre-marker disk
+shape is upgraded once to `enabled: true` and the marker is then persisted. Later
+explicit Stop writes `enabled: false` and does not get re-enabled by that one-time
+defaulting rule. Service startup starts the runtime only when the persisted intent is
+true, and a transient process loss changes health, never this switch state.
| Decision | Meaning | Entry and exit rule | `status.error_key` |
| --- | --- | --- | --- |
@@ -1733,11 +1737,11 @@ delivery lane. It must not appear as a placeholder third module in the v3 UI.
## 6. Modes & onboarding
- **Gateway (wire value `hub`, default)**: every backend on a fresh installation starts
- in Gateway mode. An existing installation with no Model Hub state starts in Direct;
- each backend moves to Gateway only after the user explicitly switches it in the
- Models page. This onboarding rule prevents a silent routing change for existing
- users without introducing an internal contract-conversion path. Avibe injects
- runtime-only configuration into processes
+ in Gateway mode. An existing installation with no backend-mode state remains in
+ Direct; each backend moves to Gateway only after the user explicitly switches it in
+ the Models page. Runtime availability is default-on independently of this per-backend
+ mode choice and never asks the user to confirm enablement. Avibe injects runtime-only
+ configuration into processes
it launches (env vars for Claude Code; `-c` overrides for Codex app-server;
`OPENCODE_CONFIG` overlay for OpenCode, gateway-config hash tracked for
long-lived `opencode serve`). Native user configs are never written.
@@ -1762,28 +1766,44 @@ delivery lane. It must not appear as a placeholder third module in the v3 UI.
A `native_cli` hop inside Gateway mode is labelled **Native**, not Direct: Avibe still
owns the pre-stream same-turn fallback and recovery policy. Product copy reserves
“Direct” for `mode: direct` and does not explain either path as “not through Gateway.”
-- **Native-config import** remains copy-only and reversible, a per-item checklist
- grouped by backend. Its action comes only from the authoritative matrix below; prose,
- scan code, and contract examples cannot add another value or infer a different default.
+- **Native-config import** is a custody-takeover flow, not a copy-only compatibility
+ path. Consent is grouped by backend and CLI account, with one consequence sentence
+ and one Start migration action. Its action comes only from the authoritative matrix
+ below; prose, scan code, and contract examples cannot add another value or infer a
+ different default. Runtime enablement never substitutes for this consent.
**Native-config import action matrix (authoritative and exhaustive; owner ruling
-2026-08-09).** Originals are never modified or deleted, and Direct remains available.
+2026-09-19).** The server owns one transaction for Source custody, default Route
+placement, backend mode, and native cleanup. Before the transaction is exposed,
+failure or dismissal can leave the native snapshot unchanged. Once exposed, recovery
+is forward-only: it retains the current owner, blocks the affected backend, and
+finishes cleanup and projection rather than restoring a stale native grant.
| Decision | Action | Eligible detected item | Default / apply behavior |
| --- | --- | --- | --- |
-| `import.keep_native` | `keep_native` | Claude or Codex subscription OAuth held by the sanctioned local CLI | selected by default; retain the credential in the CLI store, create the backend's singleton `native_cli` Source, and run the same §4.2 default placement and effective adoption as Add Source; reject a duplicate native Source before OAuth or partial commit |
-| `import.copy_key` | `import` | API key plus optional Base URL, including an OpenCode provider key | selected by default; copy into a validated Hub Source, run the same §4.2 default placement and effective adoption as Add Source, and leave the original file byte-identical |
-| `import.reauth` | `reauth` | detected material that cannot be safely copied or retained as a usable native login | not auto-applied as import; direct the user into the explicit authentication flow |
+| `import.copy_key` | `import` | Claude or Codex OAuth with a complete refresh-capable grant (Codex also requires `account_id`), or an API key plus optional Base URL including an OpenCode provider key | API-key rows are selected by default when the backend has no blocker; OAuth rows are selected only after grouped CLI consent. Stage and validate the Hub credential, then expose custody, convert or create the Source, place its Routes, switch the selected backend to Hub, and remove only the replaced native material |
+| `import.keep_native` | `keep_native` | access-only, unsupported, malformed, or otherwise non-exportable native credential | visible and unselected as an action-required blocker; it is never silently skipped and cannot be submitted as a successful takeover. The affected backend remains blocked until re-authentication or repair |
+| `import.reauth` | `reauth` | explicitly invalid grant or credential shape requiring a new authentication flow | visible and unselected; it cannot be applied as an import and routes the user to the existing explicit authentication path |
| `import.controlled` | `controlled_import` | future engine-owned OAuth-import capability that can preserve refresh semantics | reserved and not selectable/applicable in v3; explicit OAuth add is the only hub-held subscription path |
The final mirror registry compares this exact action enum with
`models.migration.action.<value>` in both UI locale files, following AC-19's closed-enum
guard; deferred still has explanatory copy even though it is not selectable.
-The `keep_native` default prevents silent credential movement and does not replace
-§4.1's ChatGPT add-flow recommendation. A hub-held subscription is established only
-through explicit OAuth add, not native-file import. The import entry points are first
-open after upgrade, the setup wizard, and the backend-page banner.
+`keep_native` and `reauth` are blocker presentations, not successful outcomes. A
+compatible refresh-capable grant does not require a new browser login. If a matching
+native Source already exists, takeover upgrades that Source in place: its Source ID,
+user-owned default membership, and Route identities remain intact while custody changes
+from `native_cli` to `hub`. If a reused API-key or native Source is absent from both
+the consenting backend's defaults and explicit Routes, append it to that backend's
+defaults before cleanup; preserve all other memberships and Routes. A duplicate
+Source is never created. Shared OpenCode credentials resolving to the same vendor,
+protocol and target across config layers produce one candidate with the union of
+manual model IDs; consent still binds every contributing layer and cleanup journals
+every physical path, including no-op snapshots for model-only and absent OpenCode
+layers so asynchronous provisioning cannot hide a changed credential or model. The import entry
+points are the setup wizard, the backend-page migration dialog, and One-click migration
+for existing Hub users.
- **Add-source closing loop (v3).** Creating a Source returns
`added_to: [{backend, menu_model, source_id, model_id, position}]` for every exact hop
selected by the effective planner after commit. `adopted_by: [{backend, menu_model}]` is the stable
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 5096c19f4..415430442 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -711,6 +711,35 @@ class ClaudeAgent(BaseAgent):
except Exception as exc: # noqa: BLE001
logger.warning("Error stopping Claude receiver during cleanup: %s", exc)
+ async def retire_for_native_migration(self) -> None:
+ """Strict retirement without the broad duplicate-process reaper."""
+ handler = self.session_handler
+ for key, client in list(self.claude_sessions.items()):
+ async with handler._claude_runtime_generation_lock(key):
+ if self.claude_sessions.get(key) is not client:
+ raise RuntimeError("Claude runtime generation changed")
+ if key in handler.active_sessions or not handler._retire_claude_runtime_activation(
+ key, client, lambda: self.claude_sessions.get(key) is client
+ ):
+ raise RuntimeError("Claude runtime retirement was refused")
+ process = getattr(getattr(client, "_transport", None), "_process", None)
+ if process is None:
+ raise RuntimeError("Claude runtime process ownership is unavailable")
+ await client.disconnect()
+ if process.returncode is None:
+ await asyncio.wait_for(process.wait(), timeout=5)
+ if process.returncode is None:
+ raise RuntimeError("Claude runtime process did not exit")
+ await self._stop_receiver_task(self.receiver_tasks.get(key))
+ self.receiver_tasks.pop(key, None)
+ self.claude_sessions.pop(key, None)
+ handler.clear_session_tracking(key)
+ handler._retire_model_hub_process_scope(key)
+ self._native_session_ids.pop(key, None)
+ self._last_assistant_text.pop(key, None)
+ self._pending_assistant_message.pop(key, None)
+ self._retire_steering_state(key)
+
async def _cleanup_runtime_session(
self,
composite_key: str,
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 09830dd3f..374b9a645 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -818,6 +818,24 @@ class CodexAgent(BaseAgent):
cwd = self._session_mgr.get_cwd(base_session_id)
return f"{base_session_id}:{cwd}" if cwd else base_session_id
+ async def retire_for_native_migration(self) -> None:
+ """Retire every idle app-server generation or refuse credential mutation."""
+ for cwd, transport in list(self._transports.items()):
+ async with self._transport_locks.setdefault(cwd, asyncio.Lock()):
+ detached = await self._stop_and_detach_transport_generation(
+ cwd,
+ transport,
+ final_predicate=lambda: self._transport_replacement_is_safe(cwd, transport),
+ require_process_exit=True,
+ )
+ if not detached:
+ raise RuntimeError("Codex runtime retirement was refused")
+ self._retire_model_hub_process_scope(cwd)
+ for base_session_id in self._session_mgr.all_base_sessions():
+ self._session_mgr.invalidate_thread(base_session_id)
+ self._turn_registry.clear_session(base_session_id)
+ self._clear_thread_developer_instructions(base_session_id)
+
async def refresh_auth_state(self) -> None:
"""Drop app-server runtime state so future turns pick up fresh auth."""
if not hasattr(self, "_transport_last_activity"):
@@ -1240,6 +1258,7 @@ class CodexAgent(BaseAgent):
transport: CodexTransport,
*,
final_predicate: Callable[[], Awaitable[bool]] | None = None,
+ require_process_exit: bool = False,
) -> bool:
"""Stop one exact generation, retaining it if validation or stop fails."""
@@ -1250,7 +1269,12 @@ class CodexAgent(BaseAgent):
if final_predicate is not None and not await final_predicate():
self._finish_transport_retirement(reserved, retire=False)
return False
+ process = getattr(transport, "_process", None)
await transport.stop()
+ if require_process_exit and process is not None and process.returncode is None:
+ await asyncio.wait_for(process.wait(), timeout=5)
+ if process.returncode is None:
+ raise RuntimeError("Codex native process did not exit")
except BaseException:
self._finish_transport_retirement(reserved, retire=False)
raise
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index a31945420..5bca86047 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -996,6 +996,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"""Adopt persisted server state before the shared drain snapshot."""
await self._get_server()
+ async def retire_for_native_migration(self) -> None:
+ server = self._client_manager._server_manager
+ if server is not None:
+ await server.retire_for_native_migration()
+
def runtime_has_active_turns(self) -> bool:
if any(not task.done() for task in self._active_requests.values()):
return True
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index b4530806b..d9feef321 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -487,6 +487,41 @@ class OpenCodeServerManager:
return
await self._close_http_session_locked()
+ async def retire_for_native_migration(self) -> None:
+ """Strictly stop our tracked server, never an arbitrary port occupant."""
+ from core.backend_restart import finish_native_operation
+
+ async with self._get_lock():
+ if self._active_requests or self._has_active_run_sessions():
+ raise RuntimeError("OpenCode runtime is busy")
+ retire = self._runtime_activation_retire
+ if callable(retire) and not retire(False, True):
+ raise RuntimeError("OpenCode runtime retirement was refused")
+ process = self._process
+ # A pid-file without a live child handle is not sufficient proof of
+ # ownership (PID reuse). Leave it for the external-process blocker.
+ info = self._read_pid_file()
+ recorded_pid = info.get("pid") if isinstance(info, dict) else None
+ if process is None and isinstance(recorded_pid, int) and self._pid_exists(recorded_pid):
+ raise RuntimeError("OpenCode server ownership cannot be proven")
+ if process is not None and process.returncode is None:
+ if not await finish_native_operation(
+ asyncio.to_thread(self._terminate_pid_tree_sync, process.pid)
+ ):
+ raise RuntimeError("OpenCode server did not exit")
+ await asyncio.wait_for(process.wait(), timeout=5)
+ if process.returncode is None:
+ raise RuntimeError("OpenCode server did not exit")
+ await self._close_http_session_locked()
+ self._clear_pid_file()
+ self._process = None
+ self._process_loop = None
+ self._base_url = None
+ self._runtime_generation_token = None
+ self._auth_refresh_pending = False
+ self._auth_refresh_pending_port = None
+ self._apply_pending_runtime_config_locked()
+
async def _restart_for_auth_refresh_locked(
self,
*,
diff --git a/tests/e2e/test_model_hub_migration.py b/tests/e2e/test_model_hub_migration.py
index f427455a1..0aa668ee0 100644
--- a/tests/e2e/test_model_hub_migration.py
+++ b/tests/e2e/test_model_hub_migration.py
@@ -34,7 +34,7 @@ def _seed_native_configs(app, upstream_url: str) -> list[Path]:
json.dumps(
{
"env": {
- "ANTHROPIC_API_KEY": "sk-ant-e2e-copy-only-123456",
+ "ANTHROPIC_API_KEY": "sk-ant-e2e-claude-independent-123456",
"ANTHROPIC_BASE_URL": upstream_url,
},
"permissions": {"allow": ["Read"]},
@@ -105,11 +105,11 @@ def _launch_seeded_app(model_hub_app_factory, mock_llm_upstream):
return model_hub_app_factory(before_start=seed), seeded_paths
-def test_f1_native_scan_returns_the_copy_only_action_matrix(
+def test_f1_native_scan_returns_the_grouped_full_custody_action_matrix(
model_hub_app_factory,
mock_llm_upstream,
) -> None:
- """F1: Claude key and Codex login map to import/keep-native actions."""
+ """F1: complete credentials import; blocked credentials stay visible."""
launch, _ = _launch_seeded_app(
model_hub_app_factory, mock_llm_upstream
@@ -120,53 +120,59 @@ def test_f1_native_scan_returns_the_copy_only_action_matrix(
assert response.status == 200, body
items = body["scan"]["items"]
assert [
- (item["backend"], item["kind"], item["proposed_action"])
+ (
+ item["backend"],
+ item["kind"],
+ item["proposed_action"],
+ item["selected"],
+ )
for item in items
] == [
- ("claude", "api_key", "import"),
- ("codex", "oauth_native", "keep_native"),
+ ("claude", "api_key", "import", True),
+ ("codex", "oauth_native", "keep_native", False),
+ ("opencode", "api_key", "reauth", False),
]
- assert all(item["selected"] is True for item in items)
serialized = json.dumps(items)
for secret in (
- "sk-ant-e2e-copy-only-123456",
+ "sk-ant-e2e-claude-independent-123456",
"codex-oauth-e2e-123456",
"sk-unsupported-e2e-123456",
):
assert secret not in serialized
- reason=(
- "F1 product/contract gap: unsupported OpenCode provider ids are silently "
- "dropped and migration-scan.schema.json has no notice field"
- )
-)
-def test_f1_unsupported_opencode_provider_ids_are_noted(
+def test_f1_unsupported_opencode_provider_ids_remain_visible_blockers(
model_hub_app_factory,
mock_llm_upstream,
) -> None:
- """F1: an unsupported native OpenCode provider must be visible as a note."""
+ """F1: an unsupported native OpenCode provider blocks only OpenCode."""
launch, _ = _launch_seeded_app(
model_hub_app_factory, mock_llm_upstream
)
with launch as app:
response = app.client.post("/api/models/migration/scan", {})
- assert any(
- item["backend"] == "opencode"
- and item.get("notes_key")
+ opencode_items = [
+ item
for item in response.json()["scan"]["items"]
+ if item["backend"] == "opencode"
+ ]
+ assert [
+ (item["kind"], item["proposed_action"], item["selected"])
+ for item in opencode_items
+ ] == [("api_key", "reauth", False)]
+ assert opencode_items[0]["notes_key"] == (
+ "settings.models.migration.blocked.credential"
)
-def test_f2_apply_is_copy_only_and_places_native_login_before_keys(
+def test_f2_apply_takes_over_selected_key_and_preserves_blocked_native_material(
model_hub_app_factory,
mock_llm_upstream,
) -> None:
- """F2: apply copies selected material and performs the one-time sort."""
+ """F2: grouped custody cleans the selected key without touching blockers."""
- seeded_api_key = "sk-ant-e2e-copy-only-123456"
+ seeded_api_key = "sk-ant-e2e-claude-independent-123456"
seeded_api_key_digest = hashlib.sha256(
seeded_api_key.encode("utf-8")
).hexdigest()
@@ -183,7 +189,16 @@ def test_f2_apply_is_copy_only_and_places_native_login_before_keys(
scan = app.client.post("/api/models/migration/scan", {})
scan_body = scan.json()
assert scan.status == 200, scan_body
- item_ids = [item["id"] for item in scan_body["scan"]["items"]]
+ item_ids = [
+ item["id"]
+ for item in scan_body["scan"]["items"]
+ if item["selected"] is True
+ ]
+ assert [
+ (item["backend"], item["kind"])
+ for item in scan_body["scan"]["items"]
+ if item["id"] in item_ids
+ ] == [("claude", "api_key")]
mock_llm_upstream.reset_requests()
applied = app.client.post(
@@ -191,15 +206,21 @@ def test_f2_apply_is_copy_only_and_places_native_login_before_keys(
)
body = applied.json()
assert applied.status == 200, body
- assert body["applied"] == 2
+ assert body["applied"] == 1
assert [
(source["vendor"], source["kind"], source["supply_channel"])
for source in body["sources"]
] == [
- ("openai", "subscription", "native_cli"),
("anthropic", "api_key", "hub"),
]
- assert all(path.read_bytes() == content for path, content in before.items())
+ claude_settings = seeded_paths[0]
+ assert json.loads(claude_settings.read_text(encoding="utf-8")) == {
+ "env": {},
+ "permissions": {"allow": ["Read"]},
+ }
+ assert all(
+ path.read_bytes() == before[path] for path in seeded_paths[1:]
+ )
listed = app.client.get("/api/models/sources")
assert listed.status == 200, listed.json()
@@ -207,7 +228,7 @@ def test_f2_apply_is_copy_only_and_places_native_login_before_keys(
source["id"] for source in body["sources"]
]
serialized = json.dumps(body)
- assert "sk-ant-e2e-copy-only-123456" not in serialized
+ assert "sk-ant-e2e-claude-independent-123456" not in serialized
assert "codex-oauth-e2e-123456" not in serialized
captured_digests = set()
diff --git a/tests/scenario_harness/auth_setup.py b/tests/scenario_harness/auth_setup.py
index 01e7b777d..480663af7 100644
--- a/tests/scenario_harness/auth_setup.py
+++ b/tests/scenario_harness/auth_setup.py
@@ -1,12 +1,28 @@
+from config.v2_config import V2Config
from core.agent_auth_service import AgentAuthService
from tests.scenario_harness.core import BaseScenarioHarness, FakeProcess, ScenarioControllerBase
+def save_direct_auth_config(config: V2Config | None = None) -> V2Config:
+ """Persist the native-auth scenario precondition in its isolated test home."""
+ if config is None:
+ try:
+ config = V2Config.load()
+ except FileNotFoundError:
+ config = V2Config.default()
+ for agent in config.model_hub.agents.values():
+ agent.mode = "direct"
+ config.save()
+ return config
+
+
class AuthSetupScenarioHarness(BaseScenarioHarness):
- """Reusable harness for capability-level auth/setup scenarios."""
+ """Native Direct-mode setup; Hub OAuth uses its separate scenario harness."""
def __init__(self):
super().__init__(ScenarioControllerBase(default_backend="codex"))
+ config = save_direct_auth_config()
+ self.controller.config.model_hub = config.model_hub
self.service = AgentAuthService(self.controller)
def flow(self, backend: str):
diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.py
index 4e9da5c0f..2d854e72c 100644
--- a/tests/scenario_harness/model_hub.py
+++ b/tests/scenario_harness/model_hub.py
@@ -10,7 +10,7 @@ from collections import deque
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
-from typing import AsyncIterator, Iterable, Mapping
+from typing import AsyncIterator, Callable, Iterable, Mapping
from config.v2_config import (
ModelHubAgentSourcesConfig,
@@ -157,8 +157,12 @@ class ModelHubScenarioAdapter:
vendor: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
ref = f"cred_observation_{len(self.provisioned_transient) + 1}"
+ if on_reserved is not None:
+ on_reserved(ref)
self.provisioned_transient.append(ref)
return ref
@@ -168,8 +172,12 @@ class ModelHubScenarioAdapter:
protocol: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
ref = f"cred_source_{len(self.provisioned) + 1}"
+ if on_reserved is not None:
+ on_reserved(ref)
self.provisioned.append(ref)
return ref
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 7bd81e1aa..bacedf943 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -121,7 +121,7 @@ scenarios:
backend: shared
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_api_key_setup_does_not_schedule_a_model
- id: AUTH-SETUP-113
- name: Hub OAuth retains completed credentials as unverified and preserves explicit rejection state
+ name: Hub OAuth retains completed credentials as unverified without treating access-token rejection as grant revocation
status: covered
kind: negative_path
layer: scenario
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 0242585bd..b3519bc79 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -48,7 +48,7 @@ from core.handlers.model_hub.service import (
)
from core.show_pages import ShowPageStore
from modules.agents.codex.agent import CodexAgent
-from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcess
+from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcess, save_direct_auth_config
from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep
from tests.ui_server_test_helpers import _save_config, csrf_headers, remote_session_cookie
from storage import remote_access_authorization_service
@@ -79,6 +79,26 @@ from vibe.model_hub_runtime.adapter import (
)
[email protected](autouse=True)
+def _guard_native_auth_boundaries(monkeypatch, _isolate_vibe_remote_home):
+ """Scenario transports must be fakes, even when the suite runs on its own."""
+ import subprocess
+
+ import psutil
+
+ from vibe import native_oauth_store
+
+ def forbidden(*_args, **_kwargs):
+ raise AssertionError("Real native processes and process inventory are forbidden in auth scenarios")
+
+ monkeypatch.setattr(subprocess, "run", forbidden)
+ monkeypatch.setattr(subprocess.Popen, "__init__", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_shell", forbidden)
+ monkeypatch.setattr(psutil, "process_iter", forbidden)
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
+
+
def test_auth_setup_catalog_priorities_reference_live_scenarios():
catalog = yaml.safe_load((ROOT / "tests/scenarios/auth_setup/catalog.yaml").read_text())
live_ids = {scenario["id"] for scenario in catalog["scenarios"]}
@@ -372,6 +392,11 @@ class _ReloadingV2ConfigController:
return V2Config.load()
+async def _wait_for_flow_cancellation(_flow):
+ """Keep an unfinished provider flow alive until the test tears it down."""
+ await asyncio.Event().wait()
+
+
def _save_remote_web_auth_config() -> V2Config:
config = V2Config(
mode="self_host",
@@ -849,7 +874,8 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
cleanup_calls = []
restart_calls = []
- def clear_oauth(service=None):
+ def clear_oauth(service=None, *, lease=None):
+ lease.assert_owned("claude")
cleanup_calls.append(service)
credentials_path.unlink()
return {"ok": True}
@@ -903,7 +929,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
)
config.agents.claude.auth_mode = "oauth"
config.agents.claude.auth_mode_set = True
- config.save()
+ save_direct_auth_config(config)
await runner.run(
ScenarioStep("confirm_oauth_is_active", capture_oauth_state),
@@ -969,7 +995,8 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
cleanup_calls = []
restart_calls = []
- def clear_oauth(cleanup_service=None):
+ def clear_oauth(cleanup_service=None, *, lease=None):
+ lease.assert_owned("claude")
cleanup_calls.append(cleanup_service)
credentials_path.unlink()
return {"ok": True}
@@ -1045,7 +1072,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
config.agents.claude.auth_mode = "oauth"
config.agents.claude.auth_mode_set = True
config.agents.claude.cli_path = "claude-probe"
- config.save()
+ save_direct_auth_config(config)
await runner.run(
ScenarioStep("confirm_oauth_is_active", capture_oauth_state),
@@ -1164,7 +1191,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
agents=AgentsConfig(),
)
config.agents.codex.cli_path = "codex-probe"
- config.save()
+ save_direct_auth_config(config)
await runner.run(ScenarioStep("test_connection", run_connection_probe))
self.assertTrue(harness.test_result["ok"])
@@ -1886,12 +1913,13 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
process = FakeProcess()
harness.service._start_codex_process = AsyncMock(return_value=process)
harness.service._read_codex_output_web = AsyncMock()
- harness.service._wait_for_codex_completion_web = AsyncMock()
+ harness.service._wait_for_codex_completion_web = AsyncMock(side_effect=_wait_for_flow_cancellation)
web_flow = await harness.service.start_web_setup(
"codex",
force_reset=False,
)
+ self.addAsyncCleanup(harness.service.cancel_web_flow, web_flow.flow_id)
await harness.service.start_setup(
harness.context,
backend="codex",
@@ -2092,13 +2120,13 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_claude_wrong_user_cannot_submit_callback_into_active_flow(self):
"""Scenario: AUTH-SETUP-103"""
harness = AuthSetupScenarioHarness()
- fake_client = object()
+ fake_client = SimpleNamespace(disconnect=AsyncMock())
runner = ScenarioRunner(harness)
callback_payloads = []
harness.service._start_claude_control_flow = AsyncMock(
return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None)
)
- harness.service._wait_for_claude_completion = AsyncMock(return_value=None)
+ harness.service._wait_for_claude_completion = AsyncMock(side_effect=_wait_for_flow_cancellation)
harness.service._send_claude_callback = AsyncMock(
side_effect=lambda client, authorization_code, state: callback_payloads.append((client, authorization_code, state))
)
@@ -2115,6 +2143,8 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
),
)
+ flow = harness.flow("claude")
+ self.addAsyncCleanup(harness.service._terminate_flow, flow)
intruder_context = harness.make_context(user_id="U2")
consumed = await harness.service.maybe_consume_setup_reply(intruder_context, "auth-code#oauth-state")
self.assertFalse(consumed)
@@ -2132,12 +2162,14 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
ScenarioExpect.text_contains(harness, "https://platform.claude.com/oauth/code/callback", index=1)
ScenarioExpect.text_contains(harness, "only the user who started this setup flow")
self.assertIn("C1:claude", harness.service._flows)
+ self.assertFalse(flow.native_closing)
+ flow.native_lease.assert_owned("claude")
self.assertEqual(callback_payloads, [])
async def test_callback_submission_and_fallback_command_do_not_double_consume_claude_flow(self):
"""Scenario: AUTH-SETUP-105"""
harness = AuthSetupScenarioHarness()
- fake_client = object()
+ fake_client = SimpleNamespace(disconnect=AsyncMock())
completion_released = asyncio.Event()
callback_payloads = []
runner = ScenarioRunner(harness)
@@ -2200,7 +2232,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_claude_manual_callback_scenario_accepts_plain_reply_and_completes(self):
"""Scenario: AUTH-SETUP-002"""
harness = AuthSetupScenarioHarness()
- fake_client = object()
+ fake_client = SimpleNamespace(disconnect=AsyncMock())
completion_released = asyncio.Event()
callback_payloads = []
runner = ScenarioRunner(harness)
@@ -2249,7 +2281,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(callback_payloads, [("auth-code", "oauth-state")])
harness.service._refresh_backend_runtime.assert_awaited_once_with("claude")
- harness.service._disconnect_claude_client.assert_awaited_once_with(fake_client)
+ harness.service._disconnect_claude_client.assert_awaited_once_with(fake_client, strict=True)
ScenarioExpect.step_history(runner, ["start_setup", "submit_callback_reply"])
ScenarioExpect.text_contains(harness, "starting claude", index=0)
ScenarioExpect.text_contains(harness, "https://platform.claude.com/oauth/code/callback", index=1)
@@ -2260,12 +2292,12 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_claude_malformed_callback_keeps_flow_active_and_instructs_retry(self):
"""Scenario: AUTH-SETUP-102"""
harness = AuthSetupScenarioHarness()
- fake_client = object()
+ fake_client = SimpleNamespace(disconnect=AsyncMock())
runner = ScenarioRunner(harness)
harness.service._start_claude_control_flow = AsyncMock(
return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None)
)
- harness.service._wait_for_claude_completion = AsyncMock(return_value=None)
+ harness.service._wait_for_claude_completion = AsyncMock(side_effect=_wait_for_flow_cancellation)
harness.service._send_claude_callback = AsyncMock()
await runner.run(
@@ -2284,15 +2316,19 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
),
)
+ flow = harness.flow("claude")
+ self.addAsyncCleanup(harness.service._terminate_flow, flow)
harness.service._send_claude_callback.assert_not_awaited()
ScenarioExpect.step_history(runner, ["start_setup", "submit_malformed_callback"])
ScenarioExpect.text_contains(harness, "authorizationCode#state")
self.assertIn("C1:claude", harness.service._flows)
+ self.assertFalse(flow.native_closing)
+ flow.native_lease.assert_owned("claude")
async def test_concurrent_setup_flows_route_replies_to_the_matching_backend(self):
"""Scenario: AUTH-SETUP-205"""
harness = AuthSetupScenarioHarness()
- fake_client = object()
+ fake_client = SimpleNamespace(disconnect=AsyncMock())
completion_released = asyncio.Event()
callback_payloads = []
runner = ScenarioRunner(harness)
@@ -2365,7 +2401,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_claude_timeout_emits_recoverable_terminal_state(self):
"""Scenario: AUTH-SETUP-203"""
harness = AuthSetupScenarioHarness()
- fake_client = object()
+ fake_client = SimpleNamespace(disconnect=AsyncMock())
runner = ScenarioRunner(harness)
completion_started = asyncio.Event()
release_completion = asyncio.Event()
@@ -2406,7 +2442,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
ScenarioExpect.text_contains(harness, "timed out")
ScenarioExpect.button_callback_contains(harness, "auth_setup:claude")
ScenarioExpect.flow_missing(harness, "C1:claude")
- harness.service._disconnect_claude_client.assert_awaited_once_with(fake_client)
+ harness.service._disconnect_claude_client.assert_awaited_once_with(fake_client, strict=True)
async def test_opencode_direct_key_scenario_installs_key_and_refreshes_runtime(self):
"""Scenario: AUTH-SETUP-003"""
@@ -2795,7 +2831,7 @@ class CodexRelayRoundTripScenarioTests(unittest.IsolatedAsyncioTestCase):
real_cfg = V2Config.default()
real_cfg.agents.codex.auth_mode = "api_key"
real_cfg.agents.codex.api_key = "sk-relay"
- real_cfg.save()
+ save_direct_auth_config(real_cfg)
def _api_module(self):
from vibe import api as vibe_api
@@ -3270,7 +3306,6 @@ def test_hub_oauth_model_free_observation_closed_loop(
state_store = EngineStateStore(tmp_path / "engine-state")
api_calls = []
inventory_calls = []
- rejected = status == 401 or (not credential_valid and not (validation_before_auth and status == 400))
is_openai = vendor in {"openai", "codex"}
protocol = "openai_responses" if is_openai else "anthropic"
if vendor == "anthropic" and "error" in body:
@@ -3282,7 +3317,8 @@ def test_hub_oauth_model_free_observation_closed_loop(
else "sk-ant-oat01-test-valid" if credential_valid else "sk-ant-oat01-test-expired"
)
auth_name = "oauth-test.json"
- state_store._secure_write_json(state_store.auth_dir / auth_name, {"access_token": bound_token})
+ grant = {"access_token": bound_token, "refresh_token": "test-refresh-grant"}
+ state_store._secure_write_json(state_store.auth_dir / auth_name, grant)
def management_request(method, path, *, query=None, payload=None):
if path == "/auth-files":
@@ -3357,17 +3393,20 @@ def test_hub_oauth_model_free_observation_closed_loop(
assert source["supply_channel"] == "hub"
assert source["credential_ref"] == h.credential_ref
assert source["verification_pending"]
- assert source["state"]["status"] == ("needs_action" if rejected else "standby")
- assert [model["id"] for model in source["models"]] == ([] if rejected else ["gpt-5.6"])
+ # A request-level access-token rejection is not refresh-grant evidence.
+ # Retain the completed OAuth grant as unverified and use best-effort
+ # inventory; neither a 401 nor a schema response proves it unusable.
+ assert source["state"]["status"] == "standby"
+ assert [model["id"] for model in source["models"]] == ["gpt-5.6"]
assert service.list_sources() == [source]
- assert bound_token not in json.dumps(terminal)
+ assert all(secret not in json.dumps(terminal) for secret in grant.values())
assert (await service.oauth_status(h.flow_id))["source"] == source
assert adapter.revoked == []
assert len(api_calls) == 1
assert api_calls[0]["header"]["Authorization"] == "Bearer $TOKEN$"
- assert len(inventory_calls) == int(not rejected)
- assert json.loads((state_store.auth_dir / auth_name).read_text())["access_token"] == bound_token
- assert bound_token not in caplog.text
+ assert len(inventory_calls) == 1
+ assert json.loads((state_store.auth_dir / auth_name).read_text()) == grant
+ assert all(secret not in caplog.text for secret in grant.values())
asyncio.run(runner.run(
ScenarioStep("start_login", start_login),
@@ -3464,6 +3503,7 @@ def test_instance_manager_backend_credentials_round_trip(monkeypatch, tmp_path,
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path, paired=True, instance_kind="organization")
+ save_direct_auth_config(config)
client = app.test_client()
base_url = "https://alex.avibe.bot"
client.set_cookie(remote_access.SESSION_COOKIE_NAME, remote_session_cookie(
@@ -3478,8 +3518,10 @@ def test_instance_manager_backend_credentials_round_trip(monkeypatch, tmp_path,
from vibe import claude_config
native_dir = tmp_path / "test-claude"
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(native_dir))
- monkeypatch.setattr(api, "_get_oauth_service", lambda: object())
- monkeypatch.setattr(api, "_clear_claude_oauth_credentials_after_api_key_save", lambda service: {"ok": True})
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: SimpleNamespace(
+ _recover_interrupted_claude_oauth_settings_backup=Mock(),
+ ))
+ monkeypatch.setattr(api, "_clear_claude_oauth_credentials_after_api_key_save", lambda service, **kw: {"ok": True})
monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", lambda *a, **kw: False)
monkeypatch.setattr(claude_config, "read_claude_oauth_signed_in", lambda: False)
refreshed = []
@@ -3514,7 +3556,7 @@ def test_manual_provider_connection_reaches_controller_confirmed_readiness(monke
monkeypatch.setenv("XDG_DATA_HOME", str(isolated / "data"))
config = V2Config.default()
config.agents.opencode.enabled = True
- config.save()
+ save_direct_auth_config(config)
upsert_opencode_provider_api_key("test-provider", "old-test-key")
api.setup_opencode_permission()
monkeypatch.setattr(api, "resolve_cli_path", lambda _: str(isolated / "bin/opencode"))
@@ -3693,6 +3735,8 @@ def test_explicit_opencode_model_recovery_preserves_agent_and_completes(monkeypa
config = V2Config.default()
config.agents.opencode.enabled = True
config.agents.opencode.default_provider = provider
+ # This scenario repairs native provider-qualified routing, not Hub supply.
+ config.model_hub.agents["opencode"].mode = "direct"
config.save()
upsert_opencode_provider_api_key(provider, "fixture-only-key")
if model_id == "family/custom-model":
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 6d3fb3c3d..d8dc80f68 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -730,17 +730,17 @@ scenarios:
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_unpinned_hub_projection_is_null_while_explicit_turn_resolves
- id: MH-MIG-001
- name: Native import copies without modifying native configuration
+ name: Native migration takes over selected credentials and cleans replaced native auth
status: covered
kind: migration
layer: scenario
- test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_001_api_apply_keeps_native_tree_byte_identical
+ test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_001_api_apply_takes_over_credentials_and_cleans_native_auth
- id: MH-MIG-002
- name: Native OAuth subscriptions remain in sanctioned CLI stores
+ name: Native OAuth grants move into Hub custody
status: covered
kind: migration
layer: scenario
- test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_002_oauth_defaults_to_native_sources
+ test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_002_oauth_grants_move_into_engine_custody
- id: MH-MIG-003
name: A scan row names the provider it belongs to without ever carrying a plaintext credential
status: covered
@@ -758,7 +758,7 @@ scenarios:
test: "ui/src/components/onboarding/ImportKeysNotice.test.tsx::MH-MIG-004: submits only the rows still ticked"
related_tests:
- ui/src/components/settings/models/migrationScan.test.ts::counts an OpenCode key, which never arrives as kind api_key
- - ui/src/components/settings/models/MigrationDialog.test.tsx::applies a keep_native row — it is a real action here, not a leftover
+ - ui/src/components/settings/models/MigrationDialog.test.tsx::applies only complete backend groups with one migration action
- id: MH-TAKEOVER-001
name: Recoverable failures walk the configured route and exhaust only at its end
status: covered
@@ -1089,17 +1089,19 @@ scenarios:
layer: e2e-auto
test: tests/e2e/test_model_hub_usage_events.py::test_e3_event_feed_paginates_and_never_persists_credentials
- id: F1
- name: Native scan produces the copy-only migration action matrix
- status: xfail
+ name: Native scan groups complete custody and visible blockers
+ status: assert
kind: migration
layer: e2e-auto
- test: tests/e2e/test_model_hub_migration.py::test_f1_unsupported_opencode_provider_ids_are_noted
+ test: tests/e2e/test_model_hub_migration.py::test_f1_native_scan_returns_the_grouped_full_custody_action_matrix
+ related_tests:
+ - tests/e2e/test_model_hub_migration.py::test_f1_unsupported_opencode_provider_ids_remain_visible_blockers
- id: F2
- name: Migration copies original API-key bytes without changing native files
+ name: Migration takes over a complete API key and preserves blocked native material
status: assert
kind: migration
layer: e2e-auto
- test: tests/e2e/test_model_hub_migration.py::test_f2_apply_is_copy_only_and_places_native_login_before_keys
+ test: tests/e2e/test_model_hub_migration.py::test_f2_apply_takes_over_selected_key_and_preserves_blocked_native_material
- id: F3
name: First Model Hub visit surfaces importable native configuration
status: skip
@@ -1166,6 +1168,5 @@ next_priority:
- B8
- B9
- D1
- - F1
- G2
- G3
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index 058cdf6ed..c05145912 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
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import json
+from contextlib import nullcontext
from datetime import datetime, timezone
from pathlib import Path
@@ -821,6 +822,12 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_
)
)
service = service_for(tmp_path, store, adapter)
+ service.migration_home = native_home
+
+ async def verify_fixture_idle():
+ return None
+
+ 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]))
diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
index d5f4f3bdf..7bc03b8cf 100644
--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -3,9 +3,10 @@ from __future__ import annotations
import asyncio
import hashlib
import json
-import threading
+from contextlib import nullcontext
from datetime import datetime, timezone
from pathlib import Path
+from typing import Mapping
import pytest
from jsonschema import Draft7Validator
@@ -18,6 +19,9 @@ from config.v2_config import (
)
from core.handlers.model_hub.adapter import (
DiscoveredModel,
+ EngineEnsureResult,
+ EngineHealth,
+ EngineStatus,
ObservationDiscovery,
ObservationOutcome,
SourceObservation,
@@ -30,9 +34,7 @@ from core.handlers.model_hub.service import (
ModelHubError,
ModelHubService,
_mask_credential,
- create_default_service,
)
-from core.services.settings import default_config
from tests.ui_server_test_helpers import csrf_headers
from vibe import ui_server
from vibe.ui_server import app
@@ -64,6 +66,7 @@ class MemoryStore:
class MigrationAdapter:
def __init__(self) -> None:
self.provisioned: list[tuple[str, int, str]] = []
+ self.oauth_provisioned: list[tuple[str, str, dict[str, object]]] = []
self.revoked: list[str] = []
self.transient_refs: list[str] = []
self.transient_revoked: list[str] = []
@@ -78,14 +81,36 @@ class MigrationAdapter:
self.synced: list[tuple[object, ...]] = []
self.fail_revoke_refs: set[str] = set()
self.fail_sync_count = 0
+ self.activated: list[str] = []
+ self.validated: list[str] = []
+ self.keys: dict[str, tuple[str, str, str, str | None]] = {}
+
+ async def start(self):
+ return EngineStatus(EngineHealth.OK, "fixture", True, "127.0.0.1", 32199, None)
+
+ async def ensure_installed(self, **kwargs):
+ return EngineEnsureResult(await self.start(), False)
+
+ async def activate_oauth_credential(self, credential_ref):
+ self.activated.append(credential_ref)
+
+ async def validate_oauth_credential(self, credential_ref):
+ assert credential_ref in self.activated
+ self.validated.append(credential_ref)
+
+ async def matches_api_key_credential(self, credential_ref, vendor, protocol, secret, base_url):
+ return self.keys.get(credential_ref) == (vendor, protocol, secret, base_url)
async def provision_transient_credential(
self,
vendor: str,
secret: str,
base_url: str | None,
+ *, on_reserved=None,
) -> str:
credential_ref = f"cred_observation_{len(self.transient_refs) + 1}"
+ if on_reserved:
+ on_reserved(credential_ref)
self.transient_refs.append(credential_ref)
return credential_ref
@@ -121,9 +146,26 @@ class MigrationAdapter:
protocol: str,
secret: str,
base_url: str | None,
+ *, on_reserved=None,
) -> str:
credential_ref = f"cred_migration_{len(self.provisioned) + 1}"
+ if on_reserved:
+ on_reserved(credential_ref)
self.provisioned.append((vendor, len(secret), credential_ref))
+ self.keys[credential_ref] = (vendor, protocol, secret, base_url)
+ return credential_ref
+
+ async def provision_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ material: Mapping[str, object],
+ *, on_reserved=None,
+ ) -> str:
+ credential_ref = f"cred_oauth_migration_{len(self.oauth_provisioned) + 1}"
+ if on_reserved:
+ on_reserved(credential_ref)
+ self.oauth_provisioned.append((source_id, vendor, dict(material)))
return credential_ref
async def discover_models(
@@ -150,16 +192,24 @@ class MigrationAdapter:
self.revoked.append(credential_ref)
-def _service(tmp_path: Path) -> tuple[ModelHubService, MemoryStore, MigrationAdapter]:
+def _service(
+ tmp_path: Path, *, migration_home: Path | None = None,
+) -> tuple[ModelHubService, MemoryStore, MigrationAdapter]:
store = MemoryStore()
adapter = MigrationAdapter()
state = tmp_path / "avibe-state"
+
+ async def verify_fixture_idle():
+ return None
+
service = ModelHubService(
store=store,
adapter=adapter,
events=BoundedEventLog(state / "events.json"),
oauth_flows=OAuthFlowRegistry(state / "oauth.json"),
revocations=CredentialRevocationJournal(state / "revocations.json"),
+ migration_home=migration_home or tmp_path / "native-home",
+ migration_guard=lambda backends: nullcontext(verify_fixture_idle),
now=lambda: datetime(2026, 7, 23, 13, 30, tzinfo=timezone.utc),
)
return service, store, adapter
@@ -221,7 +271,6 @@ def _assert_sources_validated_before_commit(
def _write_claude(home: Path, *, malformed: bool = False) -> None:
if malformed:
_write(home / ".claude" / "settings.json", "{not-json")
- _write(home / ".claude" / ".credentials.json", "[]")
return
_write(
home / ".claude" / "settings.json",
@@ -237,16 +286,31 @@ def _write_claude(home: Path, *, malformed: bool = False) -> None:
)
+ "\n",
)
+
_write(
home / ".claude" / ".credentials.json",
- json.dumps({"claudeAiOauth": {"accessToken": "claude-oauth-token"}}),
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "claude-oauth-token",
+ "refreshToken": "claude-refresh-token",
+ }
+ }
+ ),
)
def _write_claude_oauth(home: Path) -> None:
_write(
home / ".claude" / ".credentials.json",
- json.dumps({"claudeAiOauth": {"accessToken": "claude-oauth-token"}}),
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "claude-oauth-token",
+ "refreshToken": "claude-refresh-token",
+ }
+ }
+ ),
)
@@ -259,7 +323,11 @@ def _write_codex(home: Path, *, malformed: bool = False) -> None:
else json.dumps(
{
"OPENAI_API_KEY": "sk-openai-test-123456",
- "tokens": {"access_token": "codex-access-123456"},
+ "tokens": {
+ "access_token": "codex-access-123456",
+ "refresh_token": "codex-refresh-123456",
+ "account_id": "acct_codex_test",
+ },
}
)
),
@@ -283,7 +351,11 @@ def _write_codex_oauth(home: Path) -> None:
json.dumps(
{
"auth_mode": "chatgpt",
- "tokens": {"access_token": "codex-access-123456"},
+ "tokens": {
+ "access_token": "codex-access-123456",
+ "refresh_token": "codex-refresh-123456",
+ "account_id": "acct_codex_test",
+ },
}
),
)
@@ -373,8 +445,8 @@ def _translation_value(payload: dict, key: str) -> object:
def test_native_config_parsers_cover_valid_malformed_and_absent(tmp_path: Path) -> None:
cases = (
- ("claude", _write_claude, 1),
- ("codex", _write_codex, 1),
+ ("claude", _write_claude, 2),
+ ("codex", _write_codex, 2),
("opencode", _write_opencode, 2),
)
for backend, writer, expected in cases:
@@ -405,13 +477,17 @@ def test_native_config_parsers_cover_valid_malformed_and_absent(tmp_path: Path)
malformed_home = tmp_path / f"{backend}-malformed"
writer(malformed_home, malformed=True)
- assert (
- scan_native_configs(
- ModelHubConfig(),
- home=malformed_home,
- mask_credential=_mask_credential,
- )
- == []
+ malformed = scan_native_configs(
+ ModelHubConfig(),
+ home=malformed_home,
+ mask_credential=_mask_credential,
+ )
+ assert malformed
+ assert {item.backend for item in malformed} == {backend}
+ assert all(
+ item.proposed_action in {"keep_native", "reauth"}
+ and item.selected is False
+ for item in malformed
)
absent_home = tmp_path / f"{backend}-absent"
@@ -422,21 +498,15 @@ def test_native_config_parsers_cover_valid_malformed_and_absent(tmp_path: Path)
)
assert absent == []
- keychain_home = tmp_path / "claude-keychain"
- keychain_items = scan_native_configs(
- ModelHubConfig(),
- home=keychain_home,
- mask_credential=_mask_credential,
- claude_oauth_probe=lambda: True,
- )
- assert [(item.backend, item.kind, item.proposed_action) for item in keychain_items] == [
- ("claude", "oauth_native", "keep_native")
- ]
-
-
-def test_claude_settings_env_suppresses_stale_oauth_store(tmp_path: Path) -> None:
+def test_claude_settings_and_dormant_oauth_store_are_both_visible(
+ tmp_path: Path,
+) -> None:
native_home = tmp_path / "native-home"
_write_claude(native_home)
+ _write(
+ native_home / ".claude" / ".credentials.json",
+ json.dumps({"claudeAiOauth": {"accessToken": "access-only-token"}}),
+ )
items = scan_native_configs(
ModelHubConfig(),
@@ -445,24 +515,29 @@ def test_claude_settings_env_suppresses_stale_oauth_store(tmp_path: Path) -> Non
)
assert [(item.kind, item.proposed_action) for item in items] == [
- ("api_key", "import")
+ ("api_key", "import"),
+ ("oauth_native", "keep_native"),
]
@pytest.mark.parametrize(
- ("auth_mode", "expected_kind"),
- (("chatgpt", "oauth_native"), ("apikey", "api_key")),
+ "auth_mode",
+ ("chatgpt", "apikey"),
)
-def test_codex_scan_respects_explicit_auth_mode(
+def test_codex_scan_imports_dormant_auth_and_settings_keys(
tmp_path: Path,
auth_mode: str,
- expected_kind: str,
) -> None:
native_home = tmp_path / auth_mode
_write_codex(native_home)
auth_path = native_home / ".codex" / "auth.json"
auth = json.loads(auth_path.read_text(encoding="utf-8"))
auth["auth_mode"] = auth_mode
+ auth["tokens"] = {
+ "access_token": "codex-access-123456",
+ "refresh_token": "codex-refresh-123456",
+ "account_id": "acct_codex_test",
+ }
auth_path.write_text(json.dumps(auth), encoding="utf-8")
items = scan_native_configs(
@@ -471,14 +546,21 @@ def test_codex_scan_respects_explicit_auth_mode(
mask_credential=_mask_credential,
)
- assert [item.kind for item in items] == [expected_kind]
+ assert [(item.kind, item.proposed_action) for item in items] == [
+ ("oauth_native", "import"),
+ ("api_key", "import"),
+ ]
-def test_codex_scan_treats_tokens_as_stale_when_key_has_no_auth_mode(
+def test_codex_scan_keeps_access_only_oauth_visible_alongside_api_key(
tmp_path: Path,
) -> None:
native_home = tmp_path / "native-home"
_write_codex(native_home)
+ auth_path = native_home / ".codex" / "auth.json"
+ auth = json.loads(auth_path.read_text(encoding="utf-8"))
+ auth["tokens"] = {"access_token": "codex-access-123456"}
+ auth_path.write_text(json.dumps(auth), encoding="utf-8")
items = scan_native_configs(
ModelHubConfig(),
@@ -486,16 +568,23 @@ def test_codex_scan_treats_tokens_as_stale_when_key_has_no_auth_mode(
mask_credential=_mask_credential,
)
- assert [item.kind for item in items] == ["api_key"]
+ assert [(item.kind, item.proposed_action) for item in items] == [
+ ("oauth_native", "keep_native"),
+ ("api_key", "import"),
+ ]
@pytest.mark.parametrize("credential_store", (None, "keyring"))
-def test_codex_scan_keeps_native_oauth_but_skips_key_outside_file_store(
+def test_codex_scan_respects_the_configured_native_store(
tmp_path: Path,
credential_store: str | None,
) -> None:
native_home = tmp_path / (credential_store or "auto")
_write_codex(native_home)
+ auth_path = native_home / ".codex" / "auth.json"
+ auth = json.loads(auth_path.read_text(encoding="utf-8"))
+ auth["tokens"] = {"access_token": "codex-access-123456"}
+ auth_path.write_text(json.dumps(auth), encoding="utf-8")
config_path = native_home / ".codex" / "config.toml"
config = config_path.read_text(encoding="utf-8")
replacement = (
@@ -514,9 +603,12 @@ def test_codex_scan_keeps_native_oauth_but_skips_key_outside_file_store(
mask_credential=_mask_credential,
)
- assert [(item.kind, item.proposed_action) for item in items] == [
- ("oauth_native", "keep_native")
- ]
+ expected = (
+ [("oauth_native", "keep_native"), ("api_key", "import")]
+ if credential_store is None
+ else []
+ )
+ assert [(item.kind, item.proposed_action) for item in items] == expected
def test_migration_note_keys_resolve_in_both_ui_locales(tmp_path: Path) -> None:
@@ -544,7 +636,7 @@ def test_migration_note_keys_resolve_in_both_ui_locales(tmp_path: Path) -> None:
)
-def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
+def test_mh_mig_001_api_apply_takes_over_credentials_and_cleans_native_auth(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -572,7 +664,7 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
assert scan_response.status_code == 200
scan = scan_response.get_json()["scan"]
_validate_scan(scan)
- assert len(scan["items"]) == 4
+ assert len(scan["items"]) == 6
apply_response = client.post(
"/api/models/migration/apply",
@@ -582,20 +674,33 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
)
assert apply_response.status_code == 200
body = apply_response.get_json()
- assert body["applied"] == 4
- assert len(body["sources"]) == 4
- assert len(store.config.sources) == 4
+ assert body["applied"] == 6
+ assert len(body["sources"]) == 6
+ assert len(store.config.sources) == 6
assert len(adapter.provisioned) == 4
+ assert len(adapter.oauth_provisioned) == 2
assert adapter.revoked == []
assert adapter.transient_revoked == adapter.transient_refs
assert len(adapter.observed) == len(adapter.transient_refs)
- assert before == _tree_digest(native_home)
- reloaded = _assert_canonical_round_trip(store.config)
- assert all(
- model.reasoning_efforts == []
- for source in reloaded.sources
- for model in source.models
+ assert before != _tree_digest(native_home)
+ claude_settings = json.loads(
+ (native_home / ".claude" / "settings.json").read_text(encoding="utf-8")
)
+ assert claude_settings["env"] == {}
+ assert claude_settings["permissions"] == {"allow": ["Read"]}
+ assert not (native_home / ".claude" / ".credentials.json").exists()
+ assert not (native_home / ".codex" / "auth.json").exists()
+ codex_config = (native_home / ".codex" / "config.toml").read_text(encoding="utf-8")
+ assert "\nmodel_provider =" not in f"\n{codex_config}"
+ assert "[model_providers.Relay]" in codex_config
+ assert 'wire_api = "chat"' in codex_config
+ opencode_config = (
+ native_home / ".config" / "opencode" / "opencode.json"
+ ).read_text(encoding="utf-8")
+ # The unset reference is an auth hook, not an unrelated preference. Its
+ # auth.json fallback was migrated; no direct override should remain.
+ assert "{env:OPENROUTER_API_KEY}" not in opencode_config
+ reloaded = _assert_canonical_round_trip(store.config)
by_id = {source.id: source for source in store.config.sources}
imported_ids = set(by_id)
for backend in ("claude", "codex", "opencode"):
@@ -637,7 +742,9 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
for secret in (
"sk-ant-test-123456789",
"claude-oauth-token",
+ "claude-refresh-token",
"codex-access-123456",
+ "codex-refresh-123456",
"sk-openai-test-123456",
"sk-openrouter-123456",
"sk-zhipu-123456",
@@ -646,7 +753,7 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
@pytest.mark.parametrize("discovery", (ObservationDiscovery.SUCCEEDED, ObservationDiscovery.FAILED))
-def test_mh_mig_001_long_manual_inventory_is_copy_only_even_when_discovery_fails(
+def test_mh_mig_001_long_manual_inventory_survives_takeover_even_when_discovery_fails(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, discovery: ObservationDiscovery,
) -> None:
"""MH-MIG-001: new manual imports share admission without rewriting native files."""
@@ -683,13 +790,21 @@ def test_mh_mig_001_long_manual_inventory_is_copy_only_even_when_discovery_fails
manual = [model for model in source.models if model.provenance == "manual"]
assert [(model.id, model.display_name) for model in manual] == [(identity, "Long manual")]
assert all(model.id not in invalid for model in source.models)
- assert source.state.status == ("error" if discovery is ObservationDiscovery.FAILED else "standby")
- assert _tree_digest(native_home) == before
+ assert source.state.status == "standby"
+ assert _tree_digest(native_home) != before
+ config_payload = json.loads(
+ (native_home / ".config" / "opencode" / "opencode.json").read_text(
+ encoding="utf-8"
+ )
+ )
+ provider = config_payload["provider"]["openrouter"]
+ assert "apiKey" not in provider.get("options", {})
+ assert provider["models"][" " + identity + " "] == {"name": "Long manual"}
assert adapter.transient_revoked == adapter.transient_refs
assert "sk-fabricated-never-persist-this" not in json.dumps(result)
-def test_mh_mig_002_oauth_defaults_to_native_sources(
+def test_mh_mig_002_oauth_grants_move_into_engine_custody(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -705,7 +820,7 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(
scan = service.migration_scan()["items"]
oauth_items = [item for item in scan if item["kind"] == "oauth_native"]
assert {item["backend"] for item in oauth_items} == {"claude", "codex"}
- assert {item["proposed_action"] for item in oauth_items} == {"keep_native"}
+ assert {item["proposed_action"] for item in oauth_items} == {"import"}
result = asyncio.run(service.migration_apply([item["id"] for item in oauth_items]))
assert result["applied"] == 2
@@ -713,31 +828,25 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(
source.id for source in store.config.sources
}
assert {
- (source.vendor, source.kind, source.supply_channel, source.credential_ref) for source in store.config.sources
+ (source.vendor, source.kind, source.supply_channel, bool(source.credential_ref))
+ for source in store.config.sources
} == {
- ("anthropic", "subscription", "native_cli", None),
- ("openai", "subscription", "native_cli", None),
+ ("anthropic", "subscription", "hub", True),
+ ("openai", "subscription", "hub", True),
}
assert adapter.provisioned == []
- from vibe.backend_model_catalog import (
- bundled_catalog_reasoning_efforts_for_model,
- )
-
- for source in store.config.sources:
- assert source.models
- for model in source.models:
- assert model.reasoning_efforts_source == "catalog"
- assert tuple(model.reasoning_efforts) == (
- bundled_catalog_reasoning_efforts_for_model(model.id)
- )
- reloaded = _assert_canonical_round_trip(store.config)
- assert {
- (source.vendor, source.kind, source.supply_channel, source.credential_ref)
- for source in reloaded.sources
- } == {
- ("anthropic", "subscription", "native_cli", None),
- ("openai", "subscription", "native_cli", None),
+ assert {vendor for _source_id, vendor, _material in adapter.oauth_provisioned} == {
+ "anthropic",
+ "openai",
}
+ assert {
+ material["refresh_token"]
+ for _source_id, _vendor, material in adapter.oauth_provisioned
+ } == {"claude-refresh-token", "codex-refresh-123456"}
+ assert not (native_home / ".claude" / ".credentials.json").exists()
+ assert not (native_home / ".codex" / "auth.json").exists()
+ reloaded = _assert_canonical_round_trip(store.config)
+ assert all(source.credential_ref for source in reloaded.sources)
@pytest.mark.parametrize(
@@ -747,7 +856,7 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(
(_write_codex_oauth, "openai", "openai_responses"),
),
)
-def test_scan_suppresses_existing_native_subscription_semantically(
+def test_scan_reuses_existing_native_subscription_source_identity(
tmp_path: Path,
writer,
vendor: str,
@@ -771,17 +880,16 @@ def test_scan_suppresses_existing_native_subscription_semantically(
]
)
- assert (
- scan_native_configs(
- config,
- home=native_home,
- mask_credential=_mask_credential,
- )
- == []
+ [item] = scan_native_configs(
+ config,
+ home=native_home,
+ mask_credential=_mask_credential,
)
+ assert item.proposed_action == "import"
+ assert item.source_id == "src_existing_native"
-def test_opencode_auth_only_custom_provider_without_base_url_is_not_importable(
+def test_opencode_auth_only_custom_provider_without_base_url_is_visible_blocker(
tmp_path: Path,
) -> None:
native_home = tmp_path / "native-home"
@@ -790,14 +898,13 @@ def test_opencode_auth_only_custom_provider_without_base_url_is_not_importable(
json.dumps({"custom-provider": {"type": "api", "key": "sk-custom-123456"}}),
)
- assert (
- scan_native_configs(
- ModelHubConfig(),
- home=native_home,
- mask_credential=_mask_credential,
- )
- == []
+ [item] = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
)
+ assert item.proposed_action == "reauth"
+ assert item.selected is False
def test_claude_auth_token_requires_reauth_without_changing_header_semantics(
@@ -822,7 +929,7 @@ def test_claude_auth_token_requires_reauth_without_changing_header_semantics(
[item] = service.migration_scan()["items"]
assert item["proposed_action"] == "reauth"
assert item["selected"] is False
- assert item["notes_key"] == "settings.models.source.customEndpoint"
+ assert item["notes_key"] == "settings.models.migration.blocked.credential"
assert "bearer-test-123456" not in json.dumps(item)
with pytest.raises(ModelHubError) as error:
@@ -879,7 +986,7 @@ def test_codex_wire_protocol_change_invalidates_scanned_item(
assert store.config.sources == []
-def test_opencode_unsupported_native_sdk_is_not_guessed_as_compatible(tmp_path: Path) -> None:
+def test_opencode_unsupported_native_sdk_is_visible_blocker(tmp_path: Path) -> None:
native_home = tmp_path / "native-home"
_write(
native_home / ".config" / "opencode" / "opencode.json",
@@ -901,14 +1008,13 @@ def test_opencode_unsupported_native_sdk_is_not_guessed_as_compatible(tmp_path:
json.dumps({"google": {"id": "google", "npm": "@ai-sdk/google"}}),
)
- assert (
- scan_native_configs(
- ModelHubConfig(),
- home=native_home,
- mask_credential=_mask_credential,
- )
- == []
+ [item] = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
)
+ assert item.proposed_action == "reauth"
+ assert item.selected is False
def test_opencode_builtin_provider_is_importable_without_catalog_cache(
@@ -943,7 +1049,7 @@ def test_opencode_builtin_provider_is_importable_without_catalog_cache(
@pytest.mark.parametrize("provider_id", ("alibaba-cn", "poe"))
-def test_opencode_native_provider_without_stable_identifier_is_not_imported(
+def test_opencode_native_provider_without_stable_identifier_is_visible_blocker(
tmp_path: Path,
provider_id: str,
) -> None:
@@ -975,17 +1081,16 @@ def test_opencode_native_provider_without_stable_identifier_is_not_imported(
),
)
- assert (
- scan_native_configs(
- ModelHubConfig(),
- home=native_home,
- mask_credential=_mask_credential,
- )
- == []
+ [item] = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
)
+ assert item.proposed_action == "reauth"
+ assert item.selected is False
-def test_scan_skips_invalid_endpoint_without_blocking_valid_items(
+def test_scan_keeps_invalid_endpoint_visible_while_valid_backend_items_remain_usable(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -1006,17 +1111,23 @@ def test_scan_skips_invalid_endpoint_without_blocking_valid_items(
service, store, _ = _service(tmp_path)
scan = service.migration_scan()["items"]
- assert {item["backend"] for item in scan} == {"opencode"}
- result = asyncio.run(service.migration_apply([item["id"] for item in scan]))
+ assert {item["backend"] for item in scan} == {"claude", "opencode"}
+ claude_blockers = [item for item in scan if item["backend"] == "claude"]
+ assert len(claude_blockers) == 1
+ assert claude_blockers[0]["proposed_action"] == "reauth"
+ assert claude_blockers[0]["selected"] is False
+ opencode_items = [item for item in scan if item["backend"] == "opencode"]
+ result = asyncio.run(service.migration_apply([item["id"] for item in opencode_items]))
assert result["applied"] == 2
- assert all(source.verification_pending for source in store.config.sources)
assert {source.vendor for source in store.config.sources} == {
"openrouter",
"zhipuai",
}
-def test_opencode_env_placeholder_without_auth_fallback_is_not_importable(tmp_path: Path) -> None:
+def test_opencode_env_placeholder_without_auth_fallback_is_visible_blocker(
+ tmp_path: Path,
+) -> None:
native_home = tmp_path / "native-home"
_write(
native_home / ".config" / "opencode" / "opencode.json",
@@ -1043,63 +1154,13 @@ def test_opencode_env_placeholder_without_auth_fallback_is_not_importable(tmp_pa
),
)
- assert (
- scan_native_configs(
- ModelHubConfig(),
- home=native_home,
- mask_credential=_mask_credential,
- )
- == []
- )
-
-
-def test_apply_scans_claude_oauth_off_the_event_loop(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- native_home = tmp_path / "native-home"
- _isolate_native_home(monkeypatch, native_home)
- service, _, _ = _service(tmp_path)
- probe_threads: list[int] = []
- service.migration_claude_oauth_probe = lambda: (probe_threads.append(threading.get_ident()) or True)
- item_id = service.migration_scan()["items"][0]["id"]
- probe_threads.clear()
- event_loop_thread = threading.get_ident()
-
- asyncio.run(service.migration_apply([item_id]))
-
- assert probe_threads
- assert all(thread_id != event_loop_thread for thread_id in probe_threads)
-
-
-def test_default_service_claude_probe_uses_safe_runtime_cwd(
- monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
-) -> None:
- native_home = tmp_path / "native-home"
- _isolate_native_home(monkeypatch, native_home)
- config = default_config()
- config.runtime.default_cwd = str(tmp_path / "runtime")
- monkeypatch.setattr(
- "core.handlers.model_hub.service.V2Config.load",
- classmethod(lambda _cls: config),
- )
- monkeypatch.setattr(
- "core.handlers.model_hub.service.paths.get_state_dir",
- lambda: tmp_path / "state",
+ [item] = scan_native_configs(
+ ModelHubConfig(),
+ home=native_home,
+ mask_credential=_mask_credential,
)
-
- def fake_probe(_cli_path, *, env, cwd):
- assert env is not None
- assert cwd == str(tmp_path / "runtime")
- return True
-
- monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", fake_probe)
- service = create_default_service()
-
- assert service.migration_claude_oauth_probe is not None
- assert service.migration_claude_oauth_probe() is True
- assert (tmp_path / "runtime").is_dir()
+ assert item.proposed_action == "reauth"
+ assert item.selected is False
def test_failed_batch_revokes_every_provisioned_credential(
@@ -1166,13 +1227,12 @@ def test_failed_persist_sync_restores_config_and_revokes_credentials(
with pytest.raises(ModelHubError) as error:
asyncio.run(service.migration_apply(item_ids))
- assert error.value.code == "engine_down"
- assert adapter.revoked == ["cred_migration_2", "cred_migration_1"]
- assert store.config.sources == []
- assert all(agent.sources.order == [] for agent in store.config.agents.values())
+ assert error.value.code == "migration_recovery_pending"
+ assert store.config.sources
+ assert service.migration_journal.load()["phase"] == "exposed"
-def test_failed_revoke_survives_retry_with_same_source_id(
+def test_migration_requires_grouped_backend_selection_before_provisioning(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -1180,27 +1240,14 @@ def test_failed_revoke_survives_retry_with_same_source_id(
_write_opencode(native_home)
_isolate_native_home(monkeypatch, native_home)
service, store, adapter = _service(tmp_path)
- item_id = service.migration_scan()["items"][0]["id"]
- adapter.fail_sync_count = 1
- adapter.fail_revoke_refs.add("cred_migration_1")
+ item_ids = [item["id"] for item in service.migration_scan()["items"]]
with pytest.raises(ModelHubError) as error:
- asyncio.run(service.migration_apply([item_id]))
- assert error.value.code == "engine_down"
- [pending] = service.revocations.list()
- assert ":migration:" in pending.source_id
- assert pending.credential_ref == "cred_migration_1"
-
- adapter.fail_revoke_refs.clear()
- result = asyncio.run(service.migration_apply([item_id]))
- assert result["applied"] == 1
- [active] = store.config.sources
- assert active.id != pending.source_id
- assert active.credential_ref == "cred_migration_2"
-
- asyncio.run(service._ensure_engine_synced())
- assert adapter.revoked == ["cred_migration_1"]
- assert service.revocations.list() == []
+ asyncio.run(service.migration_apply([item_ids[0]]))
+ assert error.value.code == "migration_item_conflict"
+ assert adapter.provisioned == []
+ assert adapter.revoked == []
+ assert store.config.sources == []
def test_apply_rejects_a_credential_changed_after_scan(
@@ -1299,14 +1346,30 @@ def _write_key_sources(home: Path) -> None:
def _write_oauth_sources(home: Path) -> None:
- """The subscription shapes, which carry no credential of their own."""
+ """The subscription shapes with complete refresh-capable grants."""
_write(
home / ".claude" / ".credentials.json",
- json.dumps({"claudeAiOauth": {"accessToken": "claude-oauth-meta-token"}}),
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "claude-oauth-meta-token",
+ "refreshToken": "claude-refresh-meta-token",
+ }
+ }
+ ),
)
_write(
home / ".codex" / "auth.json",
- json.dumps({"auth_mode": "chatgpt", "tokens": {"access_token": "codex-oauth-meta-token"}}),
+ json.dumps(
+ {
+ "auth_mode": "chatgpt",
+ "tokens": {
+ "access_token": "codex-oauth-meta-token",
+ "refresh_token": "codex-refresh-meta-token",
+ "account_id": "acct_codex_meta",
+ },
+ }
+ ),
)
_write(home / ".codex" / "config.toml", 'cli_auth_credentials_store = "file"\n')
@@ -1339,7 +1402,11 @@ def test_mh_mig_003_scan_rows_name_their_provider_without_exposing_plaintext(
for row in payload["items"]:
assert row["vendor"], row
assert row["display_name"], row
- assert row["masked_credential"], row
+ if row["masked_credential"] is None:
+ assert row["proposed_action"] == "reauth", row
+ assert row["masked_detail"] == "", row
+ else:
+ assert row["masked_credential"], row
serialized = json.dumps(payload)
for secret in _ALL_PLAINTEXT:
@@ -1366,7 +1433,10 @@ def test_masked_credential_is_the_same_masking_the_detail_already_showed(
assert row["masked_detail"] == f"{row['vendor']} · {row['masked_credential']}"
else:
# Claude and Codex show the masked key alone, so the two agree exactly.
- assert row["masked_detail"] == row["masked_credential"]
+ if row["masked_credential"] is None:
+ assert row["masked_detail"] == ""
+ else:
+ assert row["masked_detail"] == row["masked_credential"]
for plaintext in (_KEY_FROM_OPENCODE_CONFIG, _KEY_FROM_OPENCODE_AUTH, _CLAUDE_KEY):
masked = _mask_credential(plaintext)
@@ -1386,8 +1456,8 @@ def test_subscription_rows_carry_a_name_but_no_credential(tmp_path: Path) -> Non
_validate_scan({"items": rows})
assert {(row["backend"], row["kind"], row["proposed_action"]) for row in rows} == {
- ("claude", "oauth_native", "keep_native"),
- ("codex", "oauth_native", "keep_native"),
+ ("claude", "oauth_native", "import"),
+ ("codex", "oauth_native", "import"),
}
for row in rows:
assert row["vendor"] and row["display_name"]
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index 049cfafd2..5f0e5dfb4 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -35,6 +35,12 @@ class _IsolatedClaudeConfigDirMixin:
self._avibe_home_tmp = tempfile.TemporaryDirectory()
self._previous_avibe_home = os.environ.get("AVIBE_HOME")
os.environ["AVIBE_HOME"] = self._avibe_home_tmp.name
+ from config.v2_config import V2Config
+
+ config = V2Config.default()
+ for supply in config.model_hub.agents.values():
+ supply.mode = "direct"
+ config.save()
def tearDown(self):
if self._previous_claude_config_dir is None:
@@ -507,9 +513,13 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
controller = _StubController()
service = AgentAuthService(controller)
context = MessageContext(user_id="U1", channel_id="C1")
- mock_client = SimpleNamespace()
+ mock_client = SimpleNamespace(disconnect=AsyncMock())
service._start_claude_control_flow = AsyncMock(return_value=(mock_client, "https://platform.claude.com/oauth/code", None))
- service._wait_for_claude_completion = AsyncMock()
+
+ async def pending_flow(_flow):
+ await asyncio.Event().wait()
+
+ service._wait_for_claude_completion = pending_flow
await service.start_setup(context, backend="claude", force_reset=True, claude_login_method="console")
@@ -517,6 +527,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
context,
force_reset=True,
login_with_claude_ai=False,
+ owner_flow=ANY,
)
self.assertEqual(len(controller.im_client.sent_messages), 2)
self.assertIn("https://platform.claude.com/oauth/code", controller.im_client.sent_messages[1][1])
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index 138ce8076..7410ec359 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -2,14 +2,46 @@
from __future__ import annotations
import asyncio
+import json
+import subprocess
+import threading
+from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
-from config.v2_config import V2Config
+from config.v2_config import (
+ ModelHubRouteConfig,
+ ModelHubRouteHopConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+ V2Config,
+)
from vibe import api, internal_client, runtime, ui_server
+_REAL_GET_CLAUDE_AUTH = api.get_claude_auth
+_REAL_CLAUDE_STATUS_PROBE = api._read_claude_cli_oauth_signed_in
+
+
[email protected](autouse=True)
+def native_safety(monkeypatch, _isolate_vibe_remote_home):
+ import subprocess
+
+ import psutil
+
+ from vibe import native_oauth_store
+
+ def forbidden(*_args, **_kwargs):
+ raise AssertionError("Connection tests must not inspect or launch real native processes")
+
+ monkeypatch.setattr(subprocess, "run", forbidden)
+ monkeypatch.setattr(subprocess.Popen, "__init__", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_shell", forbidden)
+ monkeypatch.setattr(psutil, "process_iter", forbidden)
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
+
@pytest.fixture
def connection(monkeypatch, tmp_path):
@@ -17,9 +49,12 @@ def connection(monkeypatch, tmp_path):
config.agents.claude.enabled = True
config.agents.codex.enabled = True
config.agents.opencode.enabled = True
+ for supply in config.model_hub.agents.values():
+ supply.mode = "direct"
+ config.save()
monkeypatch.setattr(api, "load_config", lambda: config)
monkeypatch.setattr(api, "resolve_cli_path", lambda _: str(tmp_path / "助手 cli"))
- monkeypatch.setattr(api, "get_claude_auth", lambda: {"ok": True, "active_auth_mode": "api_key"})
+ monkeypatch.setattr(api, "get_claude_auth", lambda **_: {"ok": True, "active_auth_mode": "api_key"})
monkeypatch.setattr(api, "get_codex_auth", lambda: {"ok": True, "active_auth_mode": "oauth"})
monkeypatch.setattr(api, "_backend_apply_receipts", {})
probe = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "state": "applied"}})
@@ -35,6 +70,7 @@ def test_application_is_consumed_instead_of_acceptance(connection, state, ready)
assert observed["ready"] is ready
assert observed["entry_eligible"] is ready
assert observed["auth"] == "api_key"
+ assert observed["supply_mode"] == "direct"
def test_stopped_entry_is_distinct_from_running_broken_ipc(connection, monkeypatch):
@@ -111,6 +147,7 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
config = V2Config.default()
for name in ("claude", "codex", "opencode"):
getattr(config.agents, name).enabled = True
+ config.model_hub.agents[name].mode = "direct"
getattr(config.agents, backend).cli_path = "/old/missing-cli"
config.save()
installed_path = str(tmp_path / "安装 后端/bin" / backend)
@@ -119,7 +156,7 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
communicate=lambda **_: ("fixture installed", ""), returncode=0,
))
monkeypatch.setattr(api, "install_agent", lambda name: api._run_install_command(name, ["fixture-installer"], lambda value: value))
- monkeypatch.setattr(api, "get_claude_auth", lambda: {"ok": True, "active_auth_mode": "api_key"})
+ monkeypatch.setattr(api, "get_claude_auth", lambda **_: {"ok": True, "active_auth_mode": "api_key"})
monkeypatch.setattr(api, "get_codex_auth", lambda: {"ok": True, "active_auth_mode": "api_key"})
monkeypatch.setattr(api, "_read_opencode_config_api_key_provider_ids", AsyncMock(return_value={"fixture"}))
monkeypatch.setattr(opencode_config, "read_opencode_provider_auth_entries", lambda **_: {})
@@ -210,11 +247,14 @@ def test_disabled_applied_configuration_stays_saved_without_readiness(monkeypatc
config = V2Config.default()
for name in ("claude", "codex", "opencode"):
getattr(config.agents, name).enabled = name == backend
+ config.model_hub.agents[name].mode = "direct"
config.save()
monkeypatch.setattr(api, "resolve_cli_path", lambda _: "/fixture/bin/assistant")
monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", lambda *a, **kw: False)
- monkeypatch.setattr(api, "_get_oauth_service", lambda: SimpleNamespace())
- monkeypatch.setattr(api, "_clear_claude_oauth_credentials_after_api_key_save", lambda *_: {"ok": True})
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: SimpleNamespace(
+ _recover_interrupted_claude_oauth_settings_backup=Mock(),
+ ))
+ monkeypatch.setattr(api, "_clear_claude_oauth_credentials_after_api_key_save", lambda *_, **kw: {"ok": True})
monkeypatch.setattr(api, "_refresh_opencode_provider_catalog_async", AsyncMock(return_value={"ok": True}))
monkeypatch.setattr(api, "_backend_apply_receipts", {})
monkeypatch.setattr(runtime, "service_process_running", lambda: True)
@@ -324,3 +364,528 @@ def test_permission_read_policy_consumes_real_file_without_overwriting(connectio
assert not asyncio.run(api.get_backend_connection("opencode"))["ready"]
connection.probe.return_value["body"]["state"] = "applied"
assert asyncio.run(api.get_backend_connection("claude"))["ready"]
+
+
+def hub_connection(connection, monkeypatch):
+ """Persist Hub custody; any unconfigured native credential read is a bug."""
+ for supply in connection.config.model_hub.agents.values():
+ supply.mode = "hub"
+ connection.config.save()
+ monkeypatch.setattr(api, "load_config", V2Config.load)
+
+ def native_read(*_args, **_kwargs):
+ raise AssertionError("Hub-owned supply must not read dormant native credentials")
+
+ connection.native_read = Mock(side_effect=native_read)
+ monkeypatch.setattr(api, "get_claude_auth", connection.native_read)
+ monkeypatch.setattr(api, "get_codex_auth", connection.native_read)
+ monkeypatch.setattr(api, "_read_opencode_config_api_key_provider_ids", AsyncMock(side_effect=native_read))
+ monkeypatch.setattr(api, "opencode_permission_status", lambda: {"ok": True, "permission_allowed": True})
+ return connection
+
+
+def _hub_source(*, kind="api_key", source_id="src_takeover01", channel="hub", vendor="openai"):
+ return ModelHubSourceConfig(
+ id=source_id, kind=kind, vendor=vendor,
+ display_name="Migrated account", protocol="openai_responses" if vendor == "openai" else "anthropic",
+ supply_channel=channel, billing="metered" if kind == "api_key" else "monthly",
+ state=ModelHubSourceStateConfig(status="standby"), models=[],
+ credential_ref="cred_current01" if channel == "hub" else None,
+ account_label="[email protected]",
+ )
+
+
+def _place_hub_source(connection, backend, source):
+ if source.supply_channel == "hub":
+ _store_hub_credential(source)
+ connection.config.model_hub.sources.append(source)
+ connection.config.model_hub.agents[backend].sources.order.append(source.id)
+ connection.config.save()
+
+
+def _store_hub_credential(source):
+ from config import paths
+ from vibe.model_hub_runtime.state import EngineStateStore
+
+ store = EngineStateStore(paths.get_runtime_dir() / "model-hub" / "state")
+ if source.kind == "api_key":
+ source.credential_ref = store.store_api_key(
+ "fixture-secret-not-for-response", vendor=source.vendor, protocol=source.protocol, base_url=source.base_url,
+ )
+ else:
+ source.credential_ref = store.bind_oauth_credential(source.id, source.vendor, f"{source.id}.json")
+ return store
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("kind", ["api_key", "subscription"])
+def test_hub_takeover_connection_uses_current_source_not_cleared_native_store(hub_connection, backend, kind):
+ source = _hub_source(kind=kind)
+ source.verification_pending = "vp_" + "a" * 32
+ _place_hub_source(hub_connection, backend, source)
+ assert source.models == [] # Connection observation is not model entitlement.
+
+ state = asyncio.run(api.get_backend_connection(backend))
+ assert state["supply_mode"] == "hub"
+ assert state["auth"] == ("api_key" if kind == "api_key" else "subscription")
+ assert state["ready"] and state["entry_eligible"]
+ assert state["application"] == "applied"
+ assert source.credential_ref not in json.dumps(state)
+ assert source.account_label not in json.dumps(state)
+ hub_connection.native_read.assert_not_called()
+
+ # Retained source identity survives a credential rotation; readers must not
+ # cache the prior ref or attempt to recover it from native residue.
+ old_ref = source.credential_ref
+ source.credential_ref = "cred_missing02"
+ hub_connection.config.save()
+ missing = asyncio.run(api.get_backend_connection(backend))
+ assert missing["auth"] == "none" and not missing["entry_eligible"]
+ store = _store_hub_credential(source)
+ if kind == "subscription":
+ # bind_oauth_credential deliberately reuses one auth-name identity.
+ source.credential_ref = store.bind_oauth_credential(source.id, source.vendor, "rotated.json")
+ assert source.credential_ref != old_ref
+ hub_connection.config.save()
+ assert asyncio.run(api.get_backend_connection(backend))["ready"]
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("condition", ["missing", "missing_credential", "unselected", "runtime_disabled", "needs_action", "error"])
+def test_unusable_hub_supply_never_borrows_unrelated_native_auth(hub_connection, backend, condition):
+ source = _hub_source()
+ if condition != "missing":
+ _place_hub_source(hub_connection, backend, source)
+ if condition == "unselected":
+ hub_connection.config.model_hub.agents[backend].sources.order = []
+ elif condition == "runtime_disabled":
+ hub_connection.config.model_hub.enabled = False
+ elif condition == "missing_credential":
+ source.credential_ref = "cred_missing02"
+ elif condition == "needs_action":
+ source.state = ModelHubSourceStateConfig(
+ status="needs_action", detail_key="models.source.needs_action.credential_revoked",
+ )
+ elif condition == "error":
+ source.state = ModelHubSourceStateConfig(status="error", detail_key="models.source.error.unclassified")
+ hub_connection.config.save()
+ state = asyncio.run(api.get_backend_connection(backend))
+ assert state["supply_mode"] == "hub"
+ assert state["auth"] == "none"
+ assert not state["ready"] and not state["entry_eligible"]
+ hub_connection.native_read.assert_not_called()
+
+
+def test_hub_explicit_route_reference_is_configured_supply_without_model_resolution(hub_connection):
+ source = _hub_source()
+ _store_hub_credential(source)
+ hub_connection.config.model_hub.sources = [source]
+ backend_model = hub_connection.config.model_hub.agents["claude"].models[0].id
+ hub_connection.config.model_hub.agents["claude"].routes[backend_model] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(source.id, "unobserved-model"),),
+ )
+ hub_connection.config.save()
+ assert hub_connection.config.model_hub.effective_source_order("claude") == []
+ assert asyncio.run(api.get_backend_connection("claude"))["ready"]
+ assert not asyncio.run(api.get_backend_connection("codex"))["entry_eligible"]
+
+
+def test_hub_connection_does_not_create_missing_state_or_accept_staged_grant(hub_connection):
+ from config import paths
+
+ source = _hub_source(kind="subscription")
+ hub_connection.config.model_hub.sources = [source]
+ hub_connection.config.model_hub.agents["claude"].sources.order = [source.id]
+ hub_connection.config.save()
+ state_root = paths.get_runtime_dir() / "model-hub" / "state"
+ assert not state_root.exists()
+ assert not asyncio.run(api.get_backend_connection("claude"))["entry_eligible"]
+ assert not state_root.exists()
+
+ store = _store_hub_credential(source)
+ record = store.root / "credentials" / f"{source.credential_ref}.json"
+ payload = json.loads(record.read_text())
+ payload["activation_state"] = "staged"
+ record.write_text(json.dumps(payload))
+ hub_connection.config.save()
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["auth"] == "none" and not state["ready"]
+ assert not store.auth_dir.exists()
+
+
[email protected]("expired", [False, True])
+def test_hub_cooldown_uses_existing_retry_time_not_model_entitlement(hub_connection, expired):
+ source = _hub_source()
+ source.state = ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at=(datetime.now(timezone.utc) + timedelta(hours=-1 if expired else 1)).isoformat(),
+ detail_key="models.source.cooldown.rate_limited",
+ )
+ _place_hub_source(hub_connection, "claude", source)
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["ready"] is expired and state["entry_eligible"] is expired
+
+
[email protected]("backend,vendor", [("claude", "anthropic"), ("codex", "openai")])
[email protected]("recovered_cooldown", [False, True])
+def test_retained_native_subscription_uses_only_its_explicit_owner(
+ hub_connection, monkeypatch, backend, vendor, recovered_cooldown,
+):
+ from modules.agents.model_hub import ModelHubRuntimeRouter
+
+ source = _hub_source(kind="subscription", channel="native_cli", vendor=vendor)
+ source.state.status = "active"
+ if recovered_cooldown:
+ source.state = ModelHubSourceStateConfig(
+ status="cooldown", retry_at=(datetime.now(timezone.utc) - timedelta(hours=1)).isoformat(),
+ detail_key="models.source.cooldown.rate_limited",
+ )
+ _place_hub_source(hub_connection, backend, source)
+ native_ready = Mock(return_value=True)
+ monkeypatch.setattr(ModelHubRuntimeRouter, "_default_native_cli_ready", native_ready)
+ state = asyncio.run(api.get_backend_connection(backend))
+ assert state["supply_mode"] == "hub" and state["auth"] == "subscription"
+ assert state["ready"]
+ native_ready.assert_called_once_with(backend, verified_oauth=backend == "codex")
+ hub_connection.native_read.assert_not_called()
+
+ native_ready.reset_mock()
+ other = "codex" if backend == "claude" else "claude"
+ assert not asyncio.run(api.get_backend_connection(other))["entry_eligible"]
+ native_ready.assert_not_called()
+ native_ready.return_value = False # Existing readiness rejects a conflicting key/endpoint.
+ assert not asyncio.run(api.get_backend_connection(backend))["entry_eligible"]
+ hub_connection.config.model_hub.agents[backend].sources.order = []
+ hub_connection.config.save()
+ native_ready.reset_mock()
+ assert not asyncio.run(api.get_backend_connection(backend))["entry_eligible"]
+ native_ready.assert_not_called()
+
+
+def test_api_key_connection_does_not_need_claude_status_probe(connection, monkeypatch):
+ from vibe.claude_config import read_claude_settings_env
+
+ # Exercise the real getter, not the fixture's public-auth stub.
+ monkeypatch.setattr(api, "get_claude_auth", _REAL_GET_CLAUDE_AUTH)
+ probe = Mock(side_effect=AssertionError("read-only connection launched Claude"))
+ monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", probe)
+ connection.config.agents.claude.auth_mode = "api_key"
+ connection.config.agents.claude.api_key = "fixture-legacy-key"
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["auth"] == "api_key" and state["ready"]
+ assert "fixture-legacy-key" not in json.dumps(state)
+ assert not read_claude_settings_env()
+ probe.assert_not_called()
+
+
+def claude_native_observation(connection, monkeypatch):
+ """Exercise the native resolver with an opaque, non-interactive fake store."""
+ from vibe import native_oauth_store
+
+ forbidden = Mock(side_effect=AssertionError("readiness must not read or mutate Keychain values"))
+ keychain = SimpleNamespace(
+ metadata=Mock(return_value=native_oauth_store._KeychainMetadata("not_found", "fixture-absent")),
+ read=forbidden, write=forbidden, delete=forbidden,
+ )
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)
+ monkeypatch.setattr(native_oauth_store, "sys", SimpleNamespace(platform="darwin"))
+ monkeypatch.setattr(native_oauth_store.getpass, "getuser", lambda: "fixture-user")
+ monkeypatch.setattr(api, "get_claude_auth", _REAL_GET_CLAUDE_AUTH)
+ probe = Mock(return_value=None)
+ keychain.status_probe = probe
+ monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", probe)
+ yield keychain
+ forbidden.assert_not_called()
+
+
+ "status,expected",
+ [
+ ({"loggedIn": True, "authMethod": "claude.ai"}, "subscription"),
+ ({"loggedIn": True, "authMethod": "setup-token"}, "subscription"),
+ ({"loggedIn": True, "authMethod": "api-key"}, "none"),
+ ({"loggedIn": False}, "none"),
+ ({"loggedIn": True}, "unknown"),
+ ({}, "unknown"),
+ ],
+)
+def test_direct_claude_keychain_status_restores_readiness_without_secret_read(
+ connection, claude_native_observation, monkeypatch, status, expected,
+):
+ from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError
+ from vibe import native_oauth_store
+ from vibe.claude_config import get_claude_credentials_paths
+
+ claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
+ "found", "fixture-revision",
+ )
+ assert not any(path.exists() for path in get_claude_credentials_paths())
+
+ def run(command, **kwargs):
+ assert command[1:] == ["auth", "status", "--json"]
+ assert kwargs["timeout"] == 3
+ assert kwargs["stdin"] == subprocess.DEVNULL
+ assert not kwargs["check"]
+ # An independent migration owner cannot enter while status is reading.
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ NativeCredentialLease(("claude",)).acquire(recovery=True)
+ return subprocess.CompletedProcess(command, 0, json.dumps(status), "")
+
+ process = Mock(side_effect=run)
+ monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", _REAL_CLAUDE_STATUS_PROBE)
+ monkeypatch.setattr(subprocess, "run", process)
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["auth"] == expected
+ assert state["ready"] is (expected == "subscription")
+ assert state["entry_eligible"] is state["ready"]
+ process.assert_called_once()
+ if expected != "unknown":
+ claude_native_observation.metadata.assert_not_called()
+ with NativeCredentialLease(("claude",)):
+ pass
+
+
+def test_direct_claude_status_cancellation_joins_worker_before_releasing_lease(
+ connection, claude_native_observation, monkeypatch,
+):
+ from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError
+
+ async def scenario():
+ started = asyncio.Event()
+ release = threading.Event()
+ loop = asyncio.get_running_loop()
+
+ def status(*_args, **_kwargs):
+ loop.call_soon_threadsafe(started.set)
+ assert release.wait(3), "fixture did not release the status reader"
+ return True
+
+ monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", status)
+ task = asyncio.create_task(api.get_backend_connection("claude"))
+ try:
+ await asyncio.wait_for(started.wait(), 3)
+ for _ in range(2):
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done()
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ NativeCredentialLease(("claude",)).acquire(recovery=True)
+ finally:
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, 3)
+ with NativeCredentialLease(("claude",)):
+ pass
+
+ asyncio.run(scenario())
+
+
[email protected]("change", ["hub", "hub_disabled", "pending", "busy", "corrupt_config"])
+def test_direct_claude_rechecks_custody_after_async_application_wait(
+ connection, claude_native_observation, monkeypatch, change,
+):
+ from config import paths
+ from core.backend_restart import NativeCredentialLease
+
+ lease = None
+
+ async def application(_backend):
+ nonlocal lease
+ if change in {"hub", "hub_disabled"}:
+ persisted = V2Config.load()
+ persisted.model_hub.agents["claude"].mode = "hub"
+ persisted.model_hub.enabled = change != "hub_disabled"
+ persisted.save()
+ elif change == "pending":
+ journal = paths.get_state_dir() / "native-takeover" / "current.json"
+ journal.parent.mkdir(parents=True, exist_ok=True)
+ journal.write_text(json.dumps({"version": 1, "phase": "prepared", "backends": ["claude"]}))
+ elif change == "corrupt_config":
+ paths.get_config_path().write_text("{invalid")
+ else:
+ lease = NativeCredentialLease(("claude",)).acquire()
+ return {"status_code": 200, "body": {"ok": True, "state": "applied"}}
+
+ monkeypatch.setattr(internal_client, "backend_application", application)
+ try:
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["auth"] == "unknown"
+ assert not state["ready"] and not state["entry_eligible"]
+ claude_native_observation.status_probe.assert_not_called()
+ claude_native_observation.metadata.assert_not_called()
+ finally:
+ if lease is not None:
+ lease.release()
+
+
[email protected]("error", [subprocess.TimeoutExpired("fixture-cli", 3), OSError("fixture-native-detail")])
+def test_direct_claude_status_failure_is_uncertain_and_releases_lease(
+ connection, claude_native_observation, monkeypatch, error,
+):
+ from core.backend_restart import NativeCredentialLease
+ from vibe import native_oauth_store
+
+ claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
+ "found", "fixture-revision",
+ )
+ monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", _REAL_CLAUDE_STATUS_PROBE)
+ monkeypatch.setattr(subprocess, "run", Mock(side_effect=error))
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["auth"] == "unknown" and not state["entry_eligible"]
+ assert "fixture-" not in json.dumps(state)
+ with NativeCredentialLease(("claude",)):
+ pass
+
+
[email protected]("payload_kind", ["claude_oauth", "mcp_only"])
+def test_claude_keychain_container_is_unknown_not_logged_out_or_proven_oauth(
+ connection, claude_native_observation, payload_kind,
+):
+ from vibe import native_oauth_store
+
+ # Both secret contents have exactly the same safe Keychain metadata. The
+ # observer must not inspect either payload or infer Claude OAuth from it.
+ claude_native_observation.stored_payload = {
+ "claude_oauth": {"claudeAiOauth": {"accessToken": "fixture-oauth-secret"}},
+ "mcp_only": {"mcpOAuth": {"provider": {"accessToken": "fixture-mcp-secret"}}},
+ }[payload_kind]
+ claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
+ "found", "fixture-revision", {"svce": "Claude Code-credentials", "acct": "fixture-user"},
+ )
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["auth"] == "unknown"
+ assert not state["ready"] and not state["entry_eligible"]
+ assert state["application"] == "applied"
+ assert state["supply_mode"] == "direct"
+ assert "fixture-" not in json.dumps(state)
+ claude_native_observation.metadata.assert_called_once()
+
+
[email protected]("metadata_state", ["not_found", "permission_needed", "found"])
[email protected]("file_oauth", [False, True])
+def test_claude_native_observation_respects_selected_store(
+ connection, claude_native_observation, metadata_state, file_oauth,
+):
+ from vibe import native_oauth_store
+ from vibe.claude_config import get_claude_credentials_path
+
+ claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
+ metadata_state, "fixture-revision",
+ )
+ if file_oauth:
+ path = get_claude_credentials_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({"claudeAiOauth": {"accessToken": "fixture-file-secret"}}))
+ state = asyncio.run(api.get_backend_connection("claude"))
+ expected_auth = (
+ "unknown" if metadata_state != "not_found" else "subscription" if file_oauth else "none"
+ )
+ assert state["auth"] == expected_auth
+ assert state["ready"] is (expected_auth == "subscription")
+ assert state["entry_eligible"] is state["ready"]
+ assert "fixture-file-secret" not in json.dumps(state)
+
+
[email protected]("key_var", ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"])
[email protected]("source", ["settings", "legacy_env", "explicit_oauth_env"])
+def test_claude_connection_observes_launch_key_precedence(
+ connection, claude_native_observation, monkeypatch, key_var, source,
+):
+ from vibe import native_oauth_store
+ from vibe.claude_config import get_claude_settings_path
+
+ claude_native_observation.metadata.return_value = native_oauth_store._KeychainMetadata(
+ "found", "fixture-revision",
+ )
+ connection.config.agents.claude.auth_mode = "oauth"
+ connection.config.agents.claude.auth_mode_set = source != "legacy_env"
+ if source == "settings":
+ path = get_claude_settings_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({"env": {key_var: "fixture-settings-secret"}}))
+ else:
+ monkeypatch.setenv(key_var, "fixture-inherited-secret")
+ state = asyncio.run(api.get_backend_connection("claude"))
+ key_selected = source != "explicit_oauth_env"
+ assert state["auth"] == ("api_key" if key_selected else "unknown")
+ assert state["ready"] is key_selected
+ assert "fixture-" not in json.dumps(state)
+ if key_selected:
+ claude_native_observation.metadata.assert_not_called()
+
+
[email protected]("gate", ["backend_disabled", "not_installed", "draining", "permission"])
+def test_hub_supply_keeps_existing_application_install_and_permission_gates(hub_connection, monkeypatch, gate):
+ _place_hub_source(hub_connection, "opencode", _hub_source())
+ if gate == "backend_disabled":
+ hub_connection.config.agents.opencode.enabled = False
+ hub_connection.config.save()
+ elif gate == "not_installed":
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _: None)
+ elif gate == "draining":
+ hub_connection.probe.return_value["body"]["state"] = "draining"
+ else:
+ monkeypatch.setattr(api, "opencode_permission_status", lambda: {"ok": True, "permission_allowed": False})
+ state = asyncio.run(api.get_backend_connection("opencode"))
+ assert state["supply_mode"] == "hub"
+ assert not state["ready"] and not state["entry_eligible"]
+ if gate == "permission":
+ assert state["permission_required"]
+
+
[email protected]("running", [True, False])
[email protected]("phase", ["prepared", "withdrawn", "exposed", "reverting", "corrupt"])
+def test_pending_takeover_blocks_connection_even_without_controller(hub_connection, monkeypatch, phase, running):
+ from config import paths
+
+ for backend in ("claude", "codex"):
+ _place_hub_source(hub_connection, backend, _hub_source(source_id=f"src_{backend}0001"))
+ if not running:
+ hub_connection.probe.side_effect = internal_client.InternalServerUnavailable()
+ monkeypatch.setattr(runtime, "service_process_running", lambda: False)
+ journal = paths.get_state_dir() / "native-takeover" / "current.json"
+ journal.parent.mkdir(parents=True)
+ journal.write_text(
+ "{broken" if phase == "corrupt"
+ else json.dumps({"version": 1, "phase": phase, "backends": ["claude"]}),
+ )
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["supply_mode"] == "hub"
+ assert not state["ready"] and not state["entry_eligible"]
+ sibling = asyncio.run(api.get_backend_connection("codex"))
+ assert sibling["entry_eligible"] is (phase != "corrupt")
+
+
+def test_hub_connection_mode_survives_stopped_runtime_and_missing_native_auth(hub_connection, monkeypatch):
+ _place_hub_source(hub_connection, "claude", _hub_source())
+ hub_connection.probe.side_effect = internal_client.InternalServerUnavailable()
+ monkeypatch.setattr(runtime, "service_process_running", lambda: False)
+ state = asyncio.run(api.get_backend_connection("claude"))
+ assert state["supply_mode"] == "hub" and state["application"] == "stopped"
+ assert state["entry_eligible"] and not state["ready"]
+ hub_connection.config.model_hub.enabled = False
+ hub_connection.config.save()
+ disabled = asyncio.run(api.get_backend_connection("claude"))
+ assert disabled["supply_mode"] == "hub"
+ assert not disabled["entry_eligible"] and not disabled["ready"]
+
+
+def test_hub_connection_route_preserves_auth_boundary_and_redacts_owner_data(hub_connection, monkeypatch):
+ source = _hub_source(kind="subscription")
+ _place_hub_source(hub_connection, "claude", source)
+ observe = AsyncMock(wraps=api.get_backend_connection)
+ monkeypatch.setattr(api, "get_backend_connection", observe)
+ client = ui_server.app.test_client()
+ response = client.get("/api/backend/claude/connection")
+ assert response.status_code == 200
+ assert response.get_json()["supply_mode"] == "hub"
+ assert response.get_json()["entry_eligible"]
+ assert response.headers["Cache-Control"] == "private, no-store"
+ assert source.credential_ref not in response.text and source.account_label not in response.text
+ observe.reset_mock()
+ denied = client.get("/api/backend/claude/connection", environ_base={"REMOTE_ADDR": "203.0.113.44"})
+ assert denied.status_code in {401, 403, 503}
+ observe.assert_not_called()
+ assert "auth" not in denied.get_json() and "supply_mode" not in denied.get_json()
diff --git a/tests/test_codex_api_auth.py b/tests/test_codex_api_auth.py
index 31509f5c4..32178e817 100644
--- a/tests/test_codex_api_auth.py
+++ b/tests/test_codex_api_auth.py
@@ -17,11 +17,22 @@ import sys
import types
from pathlib import Path
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vibe import api # noqa: E402
[email protected](autouse=True)
+def direct_native_auth():
+ from config.v2_config import V2Config
+
+ config = V2Config.default()
+ config.model_hub.agents["codex"].mode = "direct"
+ config.save()
+
+
def _seed_disk(home: Path, *, api_key: str | None, store: str | None) -> None:
codex_home = home / ".codex"
codex_home.mkdir(parents=True, exist_ok=True)
@@ -42,6 +53,7 @@ def _seed_v2_codex(monkeypatch, tmp_path: Path, **codex_fields) -> None:
from config.v2_config import V2Config
cfg = V2Config.default()
+ cfg.model_hub.agents["codex"].mode = "direct"
for key, value in codex_fields.items():
setattr(cfg.agents.codex, key, value)
cfg.save()
diff --git a/tests/test_core_services_settings.py b/tests/test_core_services_settings.py
index 1a5010f8e..31ba477b6 100644
--- a/tests/test_core_services_settings.py
+++ b/tests/test_core_services_settings.py
@@ -59,11 +59,11 @@ def test_default_config_is_fresh_and_needs_setup():
# default leaking in and persisting a phantom Slack transport on skip.
assert config.platforms.enabled == []
assert config.platforms.primary == "avibe"
- assert {agent.mode for agent in config.model_hub.agents.values()} == {"direct"}
+ assert {agent.mode for agent in config.model_hub.agents.values()} == {"hub"}
from vibe.runtime import default_config as runtime_default_config
- assert {agent.mode for agent in runtime_default_config().model_hub.agents.values()} == {"direct"}
+ assert {agent.mode for agent in runtime_default_config().model_hub.agents.values()} == {"hub"}
def test_load_config_or_default_returns_default_without_persisting(isolated_state, tmp_path):
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 230abbddf..a77c017a3 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -9,6 +9,7 @@ import json
import re
import textwrap
import threading
+from contextlib import asynccontextmanager
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote
@@ -415,6 +416,7 @@ def _service(tmp_path, adapter=None):
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
requested_model_override=lambda backend: store.requested_model(backend),
+ migration_home=tmp_path / "native-home",
)
return service, store, adapter
@@ -968,7 +970,7 @@ def test_runtime_status_observes_engine_without_starting_it(tmp_path):
assert adapter.start_calls == 0
assert adapter.status_calls == 1
- assert runtime["enabled"] is False
+ assert runtime["enabled"] is True
assert runtime["status"]["health"] == "ok"
assert runtime["status"]["verified"] is True
@@ -1029,21 +1031,22 @@ def test_runtime_stop_returns_explicit_not_started_state(tmp_path):
_assert_valid("runtime-dependency.schema.json", runtime)
-def test_runtime_recovery_starts_only_for_persisted_user_intent(tmp_path):
+def test_runtime_recovery_respects_the_persisted_default_on_intent(tmp_path):
service, store, adapter = _service(tmp_path)
asyncio.run(service.recover_runtime_intent())
- assert adapter.start_calls == 0
- assert adapter.ensure_calls == []
+ assert adapter.start_calls == 1
+ assert adapter.ensure_calls == [False]
- store.config.enabled = True
+ store.config.enabled = False
restarted = ModelHubService(
store=store,
adapter=adapter,
events=BoundedEventLog(tmp_path / "restarted-events.json"),
oauth_flows=OAuthFlowRegistry(tmp_path / "restarted-oauth-flows.json"),
revocations=CredentialRevocationJournal(tmp_path / "restarted-revocations.json"),
+ migration_home=tmp_path / "restarted-native-home",
)
asyncio.run(restarted.recover_runtime_intent())
@@ -1487,7 +1490,7 @@ def test_runtime_dependency_ensure_is_allowlisted_without_starting_engine(tmp_pa
)
assert runtime["changed"] is True
- assert runtime["enabled"] is False
+ assert runtime["enabled"] is True
assert runtime["status"]["installed_version"] == "v7.2.149"
assert adapter.ensure_calls == [True]
assert adapter.ensure_offline_calls == [True]
@@ -4173,33 +4176,36 @@ def test_agents_endpoint_projects_each_enabled_named_agent_live(tmp_path):
}
-def test_direct_to_hub_atomically_adopts_recognized_native_login(tmp_path):
+@asynccontextmanager
+async def _idle_mode_guard(backends):
+ async def verify_idle():
+ pass
+ yield verify_idle
+
+
+def test_direct_to_hub_changes_only_mode(tmp_path):
service, store, _adapter = _service(tmp_path)
service.migration_home = tmp_path / "native-home"
- service.migration_claude_oauth_probe = lambda: True
+ service.migration_guard = _idle_mode_guard
store.config.agents["claude"].mode = "direct"
- adopted = asyncio.run(service.set_agent_mode("claude", "hub"))
+ switched = asyncio.run(service.set_agent_mode("claude", "hub"))
- assert adopted["mode"] == "hub"
- assert len(store.config.sources) == 1
- native = store.config.sources[0]
- assert native.supply_channel == "native_cli"
- assert native.vendor == "anthropic"
- assert store.config.agents["claude"].sources.order[0] == native.id
+ assert switched["mode"] == "hub"
+ assert store.config.sources == []
+ assert store.config.agents["claude"].sources.order == []
assert store.config.agents["claude"].routes == {}
- assert service.agent_chain("claude", "claude-opus-4-6")["chain"][0]["source_id"] == native.id
repeated = asyncio.run(service.set_agent_mode("claude", "hub"))
assert repeated["mode"] == "hub"
- assert [source.id for source in store.config.sources] == [native.id]
+ assert store.config.sources == []
def test_direct_to_hub_without_recognized_login_changes_only_mode(tmp_path):
service, store, adapter = _service(tmp_path)
service.migration_home = tmp_path / "native-home"
- service.migration_claude_oauth_probe = lambda: False
+ service.migration_guard = _idle_mode_guard
store.config.agents["claude"].mode = "direct"
switched = asyncio.run(service.set_agent_mode("claude", "hub"))
@@ -4387,12 +4393,13 @@ def test_direct_to_hub_adoption_does_not_leak_partial_state_on_save_failure(tmp_
oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
migration_home=tmp_path / "native-home",
- migration_claude_oauth_probe=lambda: True,
+ migration_guard=_idle_mode_guard,
)
- with pytest.raises(OSError, match="persist failed"):
+ with pytest.raises(ModelHubError) as failure:
asyncio.run(service.set_agent_mode("claude", "hub"))
+ assert failure.value.code == "mode_switch_blocked"
assert store.config.agents["claude"].mode == "direct"
assert store.config.sources == []
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 9656f857a..f52be4e58 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -1580,6 +1580,11 @@ def _legacy_model_hub_payload(current: dict) -> dict:
}
+def _recovery_model_hub_payload() -> dict:
+ """The safe Model Hub section used by malformed-config recovery."""
+ return ModelHubConfig.from_payload({"enabled": False}).to_payload()
+
+
def test_config_reload_rejects_pre_v4_opencode_shape_on_invalid_config_path(
monkeypatch,
tmp_path,
@@ -1618,7 +1623,7 @@ def test_config_reload_rejects_pre_v4_opencode_shape_on_invalid_config_path(
loaded = V2Config.load(config_path=config_path)
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
assert config_path.read_text(encoding="utf-8") == original
backups = list(config_path.parent.glob("config.json.bak-recovery-*"))
@@ -1651,7 +1656,7 @@ def test_config_reload_recovers_malformed_legacy_collections(monkeypatch, tmp_pa
loaded = V2Config.load(config_path=config_path)
assert loaded.show_duration is True
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
assert config_path.read_text(encoding="utf-8") == original
@@ -2069,7 +2074,7 @@ def test_config_reload_recovers_dangling_legacy_custom_source_order(monkeypatch,
loaded = V2Config.load(config_path=config_path)
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
assert config_path.read_text(encoding="utf-8") == original
@@ -2097,7 +2102,7 @@ def test_config_reload_recovers_backend_ineligible_legacy_custom_source_order(
loaded = V2Config.load(config_path=config_path)
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
assert config_path.read_text(encoding="utf-8") == original
@@ -2282,7 +2287,7 @@ def test_config_reload_recovers_inner_model_hub_invariant_only(
loaded = V2Config.load(config_path=config_path)
assert loaded.show_duration is True
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
persisted = json.loads(config_path.read_text(encoding="utf-8"))["model_hub"]
if invalid_invariant == "opencode-identity":
@@ -2354,8 +2359,14 @@ def test_config_reload_does_not_overwrite_config_changed_during_migration(
assert loaded.show_duration is True
persisted = json.loads(config_path.read_text(encoding="utf-8"))
assert persisted["show_duration"] is True
- assert set(persisted["model_hub"]) == {"enabled", "sources", "agents"}
- assert persisted["model_hub"]["enabled"] is False
+ assert set(persisted["model_hub"]) == {
+ "enabled",
+ "runtime_default_applied",
+ "sources",
+ "agents",
+ }
+ assert persisted["model_hub"]["enabled"] is True
+ assert persisted["model_hub"]["runtime_default_applied"] is True
assert loaded.load_warnings and "changed during load" in loaded.load_warnings[0]
@@ -2387,8 +2398,14 @@ def test_config_reload_does_not_overwrite_config_changed_before_replace(
assert loaded.show_duration is True
persisted = json.loads(config_path.read_text(encoding="utf-8"))
assert persisted["show_duration"] is True
- assert set(persisted["model_hub"]) == {"enabled", "sources", "agents"}
- assert persisted["model_hub"]["enabled"] is False
+ assert set(persisted["model_hub"]) == {
+ "enabled",
+ "runtime_default_applied",
+ "sources",
+ "agents",
+ }
+ assert persisted["model_hub"]["enabled"] is True
+ assert persisted["model_hub"]["runtime_default_applied"] is True
assert loaded.load_warnings and "before replacement" in " ".join(loaded.load_warnings)
backups = list(config_path.parent.glob("config.json.bak-model-hub-migration-*"))
assert backups and any(backup.read_text(encoding="utf-8") == original for backup in backups)
@@ -2406,7 +2423,7 @@ def test_config_reload_recovers_invalid_optional_section_without_overwriting_fil
loaded = V2Config.load(config_path=config_path)
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
recovery = api.client_config_payload(loaded)["config_recovery"]
assert recovery["required"] is True
@@ -2446,7 +2463,7 @@ def test_config_reload_recovers_non_scalar_model_hub_enums(monkeypatch, tmp_path
loaded = V2Config.load(config_path=config_path)
assert loaded.show_duration is True
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
@@ -2480,7 +2497,7 @@ def test_config_reload_recovers_malformed_reasoning_tier_provenance_only(
assert loaded.platforms.enabled == ["slack"]
assert loaded.agents.codex.enabled is True
assert loaded.agents.codex.cli_path == "/preserved/codex"
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.recovered_sections == ("model_hub",)
assert loaded.whole_config_recovery is False
assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
@@ -2644,7 +2661,7 @@ def test_config_reload_does_not_infer_malformed_legacy_source_order(
loaded = V2Config.load(config_path=config_path)
- assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.model_hub.to_payload() == _recovery_model_hub_payload()
assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
assert config_path.read_text(encoding="utf-8") == original
assert list(config_path.parent.glob("config.json.bak-recovery-*"))
@@ -2741,13 +2758,15 @@ def test_config_reload_recovers_invalid_encoding_with_backup(monkeypatch, tmp_pa
assert list(config_path.parent.glob("config.json.bak-invalid-encoding-*"))
-def test_legacy_and_fresh_configs_both_default_direct():
+def test_legacy_configs_stay_direct_while_fresh_configs_default_to_gateway():
payload = api.config_to_payload(default_config(), include_secrets=True)
payload.pop("model_hub")
legacy = V2Config.from_payload(payload)
assert {agent.mode for agent in legacy.model_hub.agents.values()} == {"direct"}
- assert {agent.mode for agent in default_config().model_hub.agents.values()} == {"direct"}
+ assert {agent.mode for agent in default_config().model_hub.agents.values()} == {"hub"}
+ assert default_config().model_hub.enabled is True
+ assert default_config().model_hub.runtime_default_applied is True
@pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes", "on"])
@@ -2804,14 +2823,28 @@ def test_final_config_rejects_retired_global_priority_key():
ModelHubConfig.from_payload(payload)
-def test_model_hub_enabled_defaults_off_for_older_configs():
+def test_markerless_model_hub_config_applies_the_one_time_gateway_default():
payload = ModelHubConfig().to_payload()
payload.pop("enabled")
+ payload.pop("runtime_default_applied")
+
+ loaded = ModelHubConfig.from_payload(payload)
+
+ assert loaded.enabled is True
+ assert loaded.runtime_default_applied is True
+ assert loaded.to_payload()["enabled"] is True
+ assert loaded.to_payload()["runtime_default_applied"] is True
+
+
+def test_explicit_stop_after_default_upgrade_remains_disabled():
+ payload = ModelHubConfig().to_payload()
+ payload["enabled"] = False
+ payload["runtime_default_applied"] = True
loaded = ModelHubConfig.from_payload(payload)
assert loaded.enabled is False
- assert loaded.to_payload()["enabled"] is False
+ assert loaded.runtime_default_applied is True
@pytest.mark.parametrize("value", [None, 0, 1, "false"])
diff --git a/tests/test_model_hub_connection_credentials.py b/tests/test_model_hub_connection_credentials.py
new file mode 100644
index 000000000..c3422a0d7
--- /dev/null
+++ b/tests/test_model_hub_connection_credentials.py
@@ -0,0 +1,170 @@
+"""Connection ownership reads never repair engine state or disclose credentials."""
+from __future__ import annotations
+
+import json
+import stat
+from pathlib import Path
+
+import pytest
+
+from vibe.model_hub_runtime.state import EngineStateStore
+
+
+def _target(kind="api_key"):
+ return {
+ "source_id": "src_connection01", "kind": kind, "vendor": "openai",
+ "protocol": "openai_responses", "base_url": None,
+ }
+
+
+def _seed(store, kind):
+ if kind == "api_key":
+ return store.store_api_key("fixture-private-key", vendor="openai", protocol="openai_responses")
+ return store.bind_oauth_credential("src_connection01", "openai", "fixture.json")
+
+
[email protected]("kind", ["api_key", "subscription"])
+def test_owned_record_returns_only_bool_without_reading_oauth_auth_or_repairing(tmp_path, monkeypatch, caplog, kind):
+ store = EngineStateStore(tmp_path / "engine-state")
+ credential_ref = _seed(store, kind)
+ before = {path: (path.stat().st_mode, path.read_bytes()) for path in store.root.rglob("*") if path.is_file()}
+
+ def forbidden(*_args, **_kwargs):
+ raise AssertionError("Read-only ownership must not repair or open the OAuth grant")
+
+ monkeypatch.setattr(store, "_ensure_private_dir", forbidden)
+ monkeypatch.setattr(store, "credential_metadata_if_present", forbidden)
+ monkeypatch.setattr(store, "_decode_oauth_payload", forbidden)
+ monkeypatch.setattr(Path, "mkdir", forbidden)
+ monkeypatch.setattr(Path, "chmod", forbidden)
+ result = store.has_current_source_credential(credential_ref, **_target(kind))
+ assert result is True
+ assert {path: (path.stat().st_mode, path.read_bytes()) for path in before} == before
+ assert not store.auth_dir.exists()
+ assert "fixture-private-key" not in caplog.text
+
+
+def test_missing_record_does_not_create_engine_directories(tmp_path):
+ store = EngineStateStore(tmp_path / "absent" / "engine-state")
+ assert store.has_current_source_credential("cred_missing01", **_target()) is False
+ assert not (tmp_path / "absent").exists()
+
+
[email protected]("kind", ["api_key", "subscription"])
[email protected]("field,value", [
+ ("vendor", "anthropic"), ("kind", "custom"), ("source_id", "../escape"),
+ ("protocol", "invalid"), ("base_url", "file:///outside"),
+])
+def test_invalid_or_mismatched_source_cannot_borrow_record(tmp_path, kind, field, value):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, kind)
+ assert store.has_current_source_credential(credential_ref, **{**_target(kind), field: value}) is False
+
+
[email protected]("changes", [
+ {"kind": "subscription"},
+ {"protocol": "openai_chat"},
+ {"base_url": "https://other.example"},
+])
+def test_api_key_binding_requires_exact_kind_protocol_and_endpoint(tmp_path, changes):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, "api_key")
+ assert store.has_current_source_credential(credential_ref, **{**_target(), **changes}) is False
+
+
[email protected]("changes", [
+ {"kind": "api_key"},
+ {"source_id": "src_other0001"},
+ {"base_url": "https://other.example"},
+])
+def test_oauth_binding_requires_its_source_identity(tmp_path, changes):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, "subscription")
+ assert store.has_current_source_credential(credential_ref, **{**_target("subscription"), **changes}) is False
+
+
[email protected]("credential_ref", ["../outside", "cred_../../outside", "", "cred_short", None, []])
+def test_reference_is_confined_without_creating_any_path(tmp_path, credential_ref):
+ store = EngineStateStore(tmp_path / "absent")
+ assert store.has_current_source_credential(credential_ref, **_target()) is False
+ assert not store.root.exists()
+
+
[email protected]("payload", [
+ "{invalid", "[]", "null", "{}",
+ '{"kind":"api_key","vendor":"openai","protocol":"openai_responses","base_url":null,"value":""}',
+ '{"kind":"api_key","vendor":"openai","protocol":"openai_responses","base_url":null,"value":[]}',
+ '{"kind":"api_key","vendor":"anthropic","protocol":"openai_responses","base_url":null,"value":"fixture-private-key"}',
+])
+def test_bad_record_is_false_and_is_not_repaired_or_logged(tmp_path, caplog, payload):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, "api_key")
+ path = store.root / "credentials" / f"{credential_ref}.json"
+ path.write_text(payload)
+ before = path.stat()
+ assert store.has_current_source_credential(credential_ref, **_target()) is False
+ assert path.read_text() == payload and path.stat().st_mtime_ns == before.st_mtime_ns
+ assert "fixture-private-key" not in caplog.text
+ assert list(path.parent.iterdir()) == [path]
+
+
[email protected]("location", ["root", "credentials", "record"])
[email protected]("unsafe", ["permissions", "symlink"])
+def test_unsafe_record_or_parent_is_not_followed_or_repaired(tmp_path, location, unsafe):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, "api_key")
+ target = {
+ "root": store.root,
+ "credentials": store.root / "credentials",
+ "record": store.root / "credentials" / f"{credential_ref}.json",
+ }[location]
+ if unsafe == "permissions":
+ target.chmod(0o755 if target.is_dir() else 0o644)
+ before = target.stat().st_mode
+ else:
+ parked = target.with_name(target.name + "-parked")
+ target.rename(parked)
+ target.symlink_to(parked, target_is_directory=parked.is_dir())
+ assert store.has_current_source_credential(credential_ref, **_target()) is False
+ if unsafe == "permissions":
+ assert target.stat().st_mode == before
+ else:
+ assert target.is_symlink()
+
+
[email protected]("state,ready", [(None, True), ("active", True), ("staged", False), ("unknown", False)])
+def test_oauth_binding_is_not_ready_while_staged(tmp_path, state, ready):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, "subscription")
+ path = store.root / "credentials" / f"{credential_ref}.json"
+ payload = json.loads(path.read_text())
+ if state is not None:
+ payload["activation_state"] = state
+ path.write_text(json.dumps(payload))
+ assert store.has_current_source_credential(credential_ref, **_target("subscription")) is ready
+ assert not store.auth_dir.exists()
+ assert stat.S_IMODE(path.stat().st_mode) == 0o600
+
+
[email protected]("auth_name", ["../outside.json", "/absolute.json", "not-json", "", None, []])
+def test_oauth_binding_requires_safe_auth_name_but_does_not_open_it(tmp_path, auth_name):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, "subscription")
+ path = store.root / "credentials" / f"{credential_ref}.json"
+ payload = json.loads(path.read_text())
+ payload["auth_name"] = auth_name
+ path.write_text(json.dumps(payload))
+ assert store.has_current_source_credential(credential_ref, **_target("subscription")) is False
+ assert not store.auth_dir.exists()
+
+
+def test_credential_read_error_is_a_secret_free_false(tmp_path, monkeypatch, caplog):
+ store = EngineStateStore(tmp_path / "engine")
+ credential_ref = _seed(store, "api_key")
+
+ def denied(*_args, **_kwargs):
+ raise PermissionError("fixture-private-key")
+
+ monkeypatch.setattr(store, "_read_private_bytes", denied)
+ assert store.has_current_source_credential(credential_ref, **_target()) is False
+ assert "fixture-private-key" not in caplog.text
diff --git a/tests/test_model_hub_migration_auth_mirror.py b/tests/test_model_hub_migration_auth_mirror.py
new file mode 100644
index 000000000..e84670a00
--- /dev/null
+++ b/tests/test_model_hub_migration_auth_mirror.py
@@ -0,0 +1,408 @@
+"""Native takeover's persisted authentication must reach every live consumer.
+
+TestTakeoverMirrorConsumers uses the real migration transaction, not fixture
+insertions of the mirror callback. It is intentionally red on the lane's base
+until the separately owned migration.py call sites are integrated.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import copy
+import subprocess
+from dataclasses import dataclass
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import psutil
+import pytest
+
+from config import paths
+from config.v2_compat import to_app_config
+from config.v2_config import V2Config
+from core.agent_auth_service import AgentAuthService
+from core.backend_restart import NativeMigrationBlockedError
+from core.handlers.model_hub.adapter import EngineEnsureResult, EngineHealth, EngineStatus
+from core.handlers.model_hub.service import V2ModelHubConfigStore
+from modules.agents.claude_agent import ClaudeAgent
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home,
+ _service,
+)
+from tests.test_native_takeover_lifecycle import controller_fixture
+from vibe import native_oauth_store
+from vibe.claude_config import build_claude_subprocess_env
+
+
+def _forbidden(*args, **kwargs):
+ raise AssertionError("native process, HTTP, or broad runtime refresh is forbidden")
+
+
[email protected](autouse=True)
+def _fixture_boundaries(monkeypatch):
+ monkeypatch.setattr(subprocess, "run", _forbidden)
+ monkeypatch.setattr(subprocess.Popen, "__init__", _forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_shell", _forbidden)
+ monkeypatch.setattr(psutil, "process_iter", _forbidden)
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+
+
+def _config():
+ config = V2Config.default()
+ for backend in ("claude", "codex"):
+ native = getattr(config.agents, backend)
+ native.enabled = True
+ native.auth_mode = "api_key"
+ native.api_key = f"fixture-{backend}-旧-key"
+ native.base_url = "https://fixture-relay.example"
+ config.model_hub.agents[backend].mode = "direct"
+ config.agents.claude.auth_mode_set = True
+ config.agents.codex.oauth_relay_marker = {"base_url": "https://fixture-relay.example"}
+ return config
+
+
+def persisted_config(monkeypatch, tmp_path):
+ _isolate_native_home(monkeypatch, tmp_path / "native")
+ monkeypatch.setattr(paths, "get_config_path", lambda: tmp_path / "config.json")
+ config = _config()
+ config.save()
+ return config
+
+
+def _snapshot(config):
+ return {
+ backend: {name: copy.deepcopy(getattr(getattr(config.agents, backend), name)) for name in names}
+ for backend, names in V2ModelHubConfigStore._NATIVE_AUTH_FIELDS.items()
+ }
+
+
+def _cleared(config):
+ clean = copy.deepcopy(config)
+ for backend in ("claude", "codex"):
+ target = getattr(clean.agents, backend)
+ target.auth_mode = "oauth"
+ target.api_key = target.base_url = None
+ clean.agents.claude.auth_mode_set = True
+ clean.agents.codex.oauth_relay_marker = None
+ return _snapshot(clean)
+
+
+def _runtime(config, *, raw=False):
+ controller, coordinator, admissions, turns = controller_fixture()
+ controller.config = copy.deepcopy(config) if raw else to_app_config(config)
+ configs = [controller.config]
+ for name in ("command_handler", "settings_handler", "message_handler", "session_handler"):
+ detached = copy.deepcopy(controller.config)
+ setattr(controller, name, SimpleNamespace(config=detached))
+ configs.append(detached)
+ claude_config = config.agents.claude if raw else controller.config.claude
+ controller.claude_client = SimpleNamespace(config=copy.deepcopy(claude_config))
+ for backend, agent in controller.agent_service.agents.items():
+ agent.config = copy.deepcopy(controller.config)
+ configs.append(agent.config)
+ agent.refresh_runtime_config = _forbidden
+ agent.refresh_auth_state = _forbidden
+ agent._get_server = _forbidden
+ if backend == "claude":
+ # Exercise real strict retirement; the fixture owns no SDK process.
+ agent.session_handler = controller.session_handler
+ agent.claude_sessions = {}
+ agent.claude_client = SimpleNamespace(config=copy.deepcopy(claude_config))
+ agent.retire_for_native_migration = lambda agent=agent: ClaudeAgent.retire_for_native_migration(agent)
+ if backend == "codex":
+ agent.codex_config = copy.deepcopy(config.agents.codex if raw else controller.config.codex)
+ controller.agent_service.is_backend_ready = lambda backend: backend not in admissions
+ controller.session_turns._draining_backends = turns
+ controller.agent_service.refresh_runtime_config = _forbidden
+ controller.agent_service.register = _forbidden
+ controller.agent_service.release_runtime_turn_tokens = _forbidden
+ owner = AgentAuthService(controller)
+ owner._apply_backend_runtime_refresh = _forbidden
+ owner._refresh_backend_runtime = _forbidden
+ owner._refresh_opencode_server = _forbidden
+ controller.agent_auth_service = owner
+ return SimpleNamespace(
+ controller=controller, coordinator=coordinator, owner=owner,
+ admissions=admissions, turns=turns, configs=configs,
+ )
+
+
+def _targets(runtime, backend):
+ targets = []
+ for config in runtime.configs:
+ target = getattr(config, backend, None)
+ if target is not None:
+ targets.append(target)
+ target = getattr(getattr(config, "agents", None), backend, None)
+ if target is not None:
+ targets.append(target)
+ agent = runtime.controller.agent_service.agents[backend]
+ if backend == "claude":
+ targets.extend((runtime.controller.claude_client.config, agent.claude_client.config))
+ if backend == "codex":
+ targets.append(agent.codex_config)
+ return targets
+
+
+def _assert_mirrored(runtime, snapshot):
+ for backend, values in snapshot.items():
+ for target in _targets(runtime, backend):
+ for name, value in values.items():
+ if hasattr(target, name):
+ assert getattr(target, name) == value
+
+
[email protected]("raw", [False, True])
+def test_mapper_updates_all_existing_aliases_without_runtime_or_disk_io(monkeypatch, raw):
+ config = _config()
+ runtime = _runtime(config, raw=raw)
+ snapshot = _cleared(config)
+ targets = [(backend, target, copy.deepcopy(vars(target))) for backend in snapshot for target in _targets(runtime, backend)]
+ aliases = [id(target) for _, target, _ in targets]
+ monkeypatch.setattr(V2Config, "load", _forbidden)
+ monkeypatch.setattr(V2Config, "save", _forbidden)
+ runtime.owner.reconcile_native_auth_snapshot(snapshot)
+ _assert_mirrored(runtime, snapshot)
+ assert [id(target) for backend in snapshot for target in _targets(runtime, backend)] == aliases
+ for backend, target, before in targets:
+ after = vars(target)
+ assert set(after) == set(before)
+ assert {key: value for key, value in after.items() if key not in snapshot[backend]} == {
+ key: value for key, value in before.items() if key not in snapshot[backend]
+ }
+ assert not runtime.admissions and not runtime.turns
+
+
+def test_mapper_retained_native_values_and_rollback_follow_snapshot_not_hub_mode():
+ config = _config()
+ for agent in config.model_hub.agents.values():
+ agent.mode = "hub"
+ config.model_hub.enabled = False
+ runtime = _runtime(config, raw=True)
+ original = _snapshot(config)
+ runtime.owner.reconcile_native_auth_snapshot(_cleared(config))
+ runtime.owner.reconcile_native_auth_snapshot(original)
+ _assert_mirrored(runtime, original)
+ original["codex"]["oauth_relay_marker"]["base_url"] = "https://changed-fixture.example"
+ assert runtime.controller.config.agents.codex.oauth_relay_marker["base_url"] == "https://fixture-relay.example"
+ assert runtime.controller.config.model_hub.enabled is False
+ assert runtime.controller.config.model_hub.agents["claude"].mode == "hub"
+
+
[email protected]("invalid", [
+ {"opencode": {"api_key": "fixture-secret"}},
+ {"claude": {"enabled": False}},
+ {"claude": []},
+])
+def test_mapper_rejects_non_auth_fields_before_mutating(invalid):
+ config = _config()
+ runtime = _runtime(config)
+ snapshot = _cleared(config)
+ snapshot.update(invalid)
+ with pytest.raises(ValueError) as error:
+ runtime.owner.reconcile_native_auth_snapshot(snapshot)
+ assert "fixture-secret" not in str(error.value)
+ _assert_mirrored(runtime, _snapshot(config))
+
+
[email protected]("frozen", [False, True])
+def test_mapper_preflights_every_target_before_changing_any_alias(frozen):
+ config = _config()
+ runtime = _runtime(config)
+ if frozen:
+ @dataclass(frozen=True)
+ class Unwritable:
+ auth_mode: str = "api_key"
+ api_key: str = "fixture-secret"
+ base_url: str = "https://fixture-relay.example"
+ auth_mode_set: bool = True
+ target = Unwritable()
+ else:
+ class Unwritable:
+ def __init__(self):
+ self.auth_mode = "api_key"
+ self.base_url = "https://fixture-relay.example"
+ self.auth_mode_set = True
+
+ @property
+ def api_key(self):
+ return "fixture-secret"
+ target = Unwritable()
+ runtime.controller.claude_client.config = target
+ with pytest.raises(ValueError) as error:
+ runtime.owner.reconcile_native_auth_snapshot(_cleared(config))
+ assert "fixture-secret" not in str(error.value)
+ assert target.auth_mode == "api_key"
+ assert runtime.controller.config.claude.api_key == config.agents.claude.api_key
+ assert runtime.controller.agent_service.agents["codex"].codex_config.auth_mode == "api_key"
+
+
+def test_service_reads_current_store_snapshot_and_allows_standalone_fixture(monkeypatch, tmp_path):
+ path = tmp_path / "fixture-config.json"
+ monkeypatch.setattr(paths, "get_config_path", lambda: path)
+ config = _config()
+ config.save(config_path=path)
+ service, _, _ = _service(tmp_path)
+ service._reconcile_native_auth(("claude",))
+ service.store = V2ModelHubConfigStore()
+ observed = []
+ service.migration_reconcile_auth = observed.append
+ service._reconcile_native_auth(("claude",))
+ config.agents.claude.api_key = "fixture-current-key"
+ config.save(config_path=path)
+ service._reconcile_native_auth(("claude",))
+ assert observed == [{"claude": _snapshot(_config())["claude"]}, {"claude": _snapshot(config)["claude"]}]
+ service.migration_reconcile_auth = Mock(side_effect=RuntimeError("fixture mirror failed"))
+ with pytest.raises(RuntimeError, match="fixture mirror failed"):
+ service._reconcile_native_auth(("claude",))
+
+
+async def test_coordinator_rejects_unowned_wrong_backend_and_cross_task_calls(persisted_config):
+ config = persisted_config
+ runtime = _runtime(config)
+ coordinator = runtime.coordinator
+ snapshot = {"claude": _cleared(config)["claude"]}
+ for value in (snapshot, {}):
+ with pytest.raises(NativeMigrationBlockedError):
+ coordinator.reconcile_migration_auth(value)
+ async with coordinator.migration_guard(("claude",)):
+ with pytest.raises(NativeMigrationBlockedError):
+ coordinator.reconcile_migration_auth({"codex": _cleared(config)["codex"]})
+
+ async def unrelated_task():
+ with pytest.raises(NativeMigrationBlockedError):
+ coordinator.reconcile_migration_auth(snapshot)
+ await asyncio.create_task(unrelated_task())
+ coordinator.reconcile_migration_auth(snapshot)
+ _assert_mirrored(runtime, snapshot)
+ assert runtime.admissions == runtime.turns == {"claude"}
+ with pytest.raises(NativeMigrationBlockedError):
+ coordinator.reconcile_migration_auth(snapshot)
+ assert not runtime.admissions and not runtime.turns
+
+
[email protected]("opened", ["runtime", "turns"])
+async def test_coordinator_refuses_a_guard_with_an_opened_admission(opened, persisted_config):
+ config = persisted_config
+ runtime = _runtime(config)
+ async with runtime.coordinator.migration_guard(("claude",)):
+ gate = runtime.admissions if opened == "runtime" else runtime.turns
+ gate.discard("claude")
+ try:
+ with pytest.raises(NativeMigrationBlockedError):
+ runtime.coordinator.reconcile_migration_auth({"claude": _cleared(config)["claude"]})
+ _assert_mirrored(runtime, _snapshot(config))
+ finally:
+ gate.add("claude")
+
+
+def test_coordinator_refuses_calls_without_an_event_loop():
+ runtime = _runtime(_config())
+ with pytest.raises(NativeMigrationBlockedError):
+ runtime.coordinator.reconcile_migration_auth({})
+
+
+async def test_coordinator_rechecks_the_existing_native_lease(persisted_config):
+ config = persisted_config
+ runtime = _runtime(config)
+ async with runtime.coordinator.migration_guard(("claude",)):
+ _, lease = runtime.coordinator._migration_auth_owners["claude"]
+ lease.release()
+ with pytest.raises(NativeMigrationBlockedError):
+ runtime.coordinator.reconcile_migration_auth({"claude": _cleared(config)["claude"]})
+ _assert_mirrored(runtime, _snapshot(config))
+
+
+async def test_owned_snapshot_seam_updates_v2_consumers_before_queue_admission(monkeypatch, tmp_path):
+ """Unit-level seam exercise, not a substitute for the transaction consumer."""
+ service, _, runtime, _ = _migration_fixture(monkeypatch, tmp_path)
+ config = V2Config.load()
+ config.agents.claude.auth_mode = "oauth"
+ config.agents.claude.api_key = config.agents.claude.base_url = None
+ config.save()
+ expected = service.store.native_auth_snapshot(("claude",))
+ resumed = []
+
+ async def resume(backend, **kwargs):
+ _assert_mirrored(runtime, expected)
+ assert backend not in runtime.admissions
+ runtime.turns.discard(backend)
+ resumed.append(backend)
+ runtime.controller.session_turns.end_backend_drain.side_effect = resume
+ async with runtime.coordinator.migration_guard(("claude",)):
+ service._reconcile_native_auth(("claude",))
+ _assert_mirrored(runtime, expected)
+ assert runtime.admissions == runtime.turns == {"claude"}
+ assert resumed == ["claude"]
+
+
+async def test_coordinator_releases_reconciliation_ownership_on_cancellation(persisted_config):
+ runtime = _runtime(persisted_config)
+ reconcile = runtime.coordinator.reconcile_migration_auth
+ entered = asyncio.Event()
+
+ async def work():
+ async with runtime.coordinator.migration_guard(("opencode",)):
+ reconcile({})
+ entered.set()
+ await asyncio.Future()
+ task = asyncio.create_task(work())
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ with pytest.raises(NativeMigrationBlockedError):
+ runtime.coordinator.reconcile_migration_auth({})
+ assert not runtime.admissions and not runtime.turns
+
+
+def _migration_fixture(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ path = tmp_path / "fixture-config.json"
+ monkeypatch.setattr(paths, "get_config_path", lambda: path)
+ config = _config()
+ config.save(config_path=path)
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ service.store = V2ModelHubConfigStore()
+ runtime = _runtime(V2Config.load())
+ runtime.controller.model_hub_service = service
+ service.migration_guard = runtime.coordinator.migration_guard
+ service.migration_reconcile_auth = runtime.coordinator.reconcile_migration_auth
+ healthy = EngineStatus(EngineHealth.OK, "fixture", True, "127.0.0.1", 32199, None)
+
+ async def install(**kwargs):
+ return EngineEnsureResult(healthy, False)
+ adapter.ensure_installed = install
+ return service, adapter, runtime, home
+
+
+class TestTakeoverMirrorConsumers:
+ """Durable consuming coverage; requires the main-owned migration call sites."""
+
+ def test_success_then_direct_never_resurrects_legacy_key(self, monkeypatch, tmp_path):
+ service, _, runtime, _ = _migration_fixture(monkeypatch, tmp_path)
+ save = service.migration_journal.save
+
+ def save_checked(record):
+ if record["phase"] == "exposed":
+ _assert_mirrored(runtime, record["native_after"])
+ 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 service.migration_journal.load() is None
+ assert not runtime.admissions and not runtime.turns
+ _assert_mirrored(runtime, service.store.native_auth_snapshot(("claude",)))
+ asyncio.run(service.set_agent_mode("claude", "direct"))
+ env = build_claude_subprocess_env(runtime.controller.session_handler.config.claude, base_env={})
+ assert not env.get("ANTHROPIC_API_KEY") and not env.get("ANTHROPIC_BASE_URL")
+ assert V2Config.load().agents.claude.api_key is None
diff --git a/tests/test_model_hub_migration_auth_recovery.py b/tests/test_model_hub_migration_auth_recovery.py
new file mode 100644
index 000000000..6713c99e9
--- /dev/null
+++ b/tests/test_model_hub_migration_auth_recovery.py
@@ -0,0 +1,211 @@
+"""Persistent takeover direction also owns the in-memory authentication mirror."""
+
+import asyncio
+import subprocess
+from copy import deepcopy
+
+import psutil
+import pytest
+
+from config import paths
+from config.v2_config import V2Config
+from core.handlers.model_hub.adapter import OAuthCredentialRejectedError
+from core.handlers.model_hub.migration import recover_native_migration
+from core.handlers.model_hub.service import ModelHubError, V2ModelHubConfigStore
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home,
+ _service,
+ _write_claude_oauth,
+)
+from tests.test_model_hub_migration_auth_mirror import _assert_mirrored, _forbidden, _runtime
+
+
[email protected](autouse=True)
+def _native_boundaries(monkeypatch):
+ monkeypatch.setattr(subprocess, "run", _forbidden)
+ monkeypatch.setattr(subprocess.Popen, "__init__", _forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_shell", _forbidden)
+ monkeypatch.setattr(psutil, "process_iter", _forbidden)
+
+
+def _persistent_takeover(monkeypatch, tmp_path, *, oauth=False):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ config_path = tmp_path / "config.json"
+ monkeypatch.setattr(paths, "get_config_path", lambda: config_path)
+ config = V2Config.default()
+ config.model_hub.agents["claude"].mode = "direct"
+ if oauth:
+ _write_claude_oauth(home)
+ else:
+ config.agents.claude.auth_mode = "api_key"
+ config.agents.claude.api_key = "fixture-old-key"
+ config.agents.claude.base_url = "https://fixture.example"
+ config.agents.claude.auth_mode_set = True
+ config.save(config_path=config_path)
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ service.store = V2ModelHubConfigStore()
+ runtime = _runtime(config)
+ runtime.controller.model_hub_service = service
+ service.migration_guard = runtime.coordinator.migration_guard
+ before = service.store.native_auth_snapshot(("claude",))
+ live = deepcopy(before)
+ observations = []
+
+ def mirror(snapshot):
+ assert service._mutation_lock.locked()
+ record = service.migration_journal.load()
+ assert record is not None # Never drop durable ownership first.
+ assert snapshot == service.store.native_auth_snapshot(("claude",))
+ assert runtime.admissions == runtime.turns == {"claude"}
+ runtime.coordinator.reconcile_migration_auth(snapshot)
+ _assert_mirrored(runtime, snapshot)
+ observations.append((record["phase"], deepcopy(snapshot)))
+ live.clear()
+ live.update(deepcopy(snapshot))
+
+ service.migration_reconcile_auth = mirror
+
+ async def resume(backend, **kwargs):
+ _assert_mirrored(runtime, service.store.native_auth_snapshot(("claude",)))
+ assert backend not in runtime.admissions
+ runtime.turns.discard(backend)
+
+ runtime.controller.session_turns.end_backend_drain.side_effect = resume
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ return service, adapter, before, live, observations, ids, runtime
+
+
+def test_live_auth_is_mirrored_before_publication_and_completed_receipt(monkeypatch, tmp_path):
+ service, adapter, before, live, observations, ids, runtime = _persistent_takeover(monkeypatch, tmp_path)
+ sync = adapter.sync_sources
+ complete = service.migration_journal.complete
+
+ def assert_after():
+ assert live == service.store.native_auth_snapshot(("claude",))
+ assert live["claude"]["api_key"] is None
+ assert live["claude"]["base_url"] is None
+ assert live != before
+
+ async def checked_sync(bindings):
+ assert_after()
+ await sync(bindings)
+
+ def checked_complete(record):
+ assert_after()
+ complete(record)
+
+ adapter.sync_sources = checked_sync
+ service.migration_journal.complete = checked_complete
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1
+ assert [phase for phase, _ in observations] == ["withdrawn", "exposed"]
+ assert service.migration_journal.load() is None
+ assert not runtime.admissions and not runtime.turns
+
+
[email protected]("persistent", [False, True])
+def test_preexposure_mirror_failure_recovers_the_restored_direction(monkeypatch, tmp_path, persistent):
+ service, adapter, before, live, observations, ids, runtime = _persistent_takeover(monkeypatch, tmp_path)
+ mirror = service.migration_reconcile_auth
+ calls = []
+
+ def fail(snapshot):
+ calls.append(True)
+ if persistent or len(calls) == 1:
+ # A partial mirror must be repairable in the same persistent direction.
+ live["claude"]["api_key"] = None
+ runtime.controller.config.claude.api_key = None
+ raise OSError("fixture mirror failure")
+ mirror(snapshot)
+
+ service.migration_reconcile_auth = fail
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert service.store.native_auth_snapshot(("claude",)) == before
+ assert not adapter.synced
+ assert not adapter.activated
+ if persistent:
+ assert service.migration_journal.load()["phase"] == "reverting"
+ assert service.migration_blocked_backends == {"claude"}
+ assert runtime.admissions == runtime.turns == {"claude"}
+ service.migration_reconcile_auth = mirror
+ # Finishing a reversal rejects the old consent, but releases its owner.
+ with pytest.raises(ValueError):
+ asyncio.run(recover_native_migration(service))
+ assert live == before
+ assert observations[-1][0] == "reverting"
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends
+ _assert_mirrored(runtime, before)
+ assert not runtime.admissions and not runtime.turns
+
+
+def test_exposed_mirror_failure_keeps_current_ref_and_forward_only_recovery(monkeypatch, tmp_path):
+ service, adapter, before, live, observations, ids, runtime = _persistent_takeover(monkeypatch, tmp_path)
+ mirror = service.migration_reconcile_auth
+
+ def fail_before_receipt(snapshot):
+ if service.migration_journal.load()["phase"] == "exposed":
+ raise OSError("fixture mirror completion failure")
+ mirror(snapshot)
+
+ service.migration_reconcile_auth = fail_before_receipt
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ record = service.migration_journal.load()
+ assert record["phase"] == "exposed"
+ ref = service.store.load().sources[0].credential_ref
+ assert not adapter.revoked
+ assert service.store.native_auth_snapshot(("claude",)) != before
+ assert service.migration_blocked_backends == {"claude"}
+ assert runtime.admissions == runtime.turns == {"claude"}
+ # Reopened consumers must converge even though persisted Hub config is equal.
+ live.clear()
+ live.update(deepcopy(before))
+ runtime.owner.reconcile_native_auth_snapshot(before)
+ service.migration_reconcile_auth = mirror
+ asyncio.run(recover_native_migration(service))
+ assert live == service.store.native_auth_snapshot(("claude",))
+ assert live["claude"]["api_key"] is None
+ assert observations[-1][0] == "exposed"
+ assert len(adapter.provisioned) == 1
+ assert service.store.load().sources[0].credential_ref == ref
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends
+ _assert_mirrored(runtime, service.store.native_auth_snapshot(("claude",)))
+ assert not runtime.admissions and not runtime.turns
+
+
+def test_terminal_oauth_recovery_mirrors_before_releasing_custody(monkeypatch, tmp_path):
+ service, adapter, _, live, _, ids, runtime = _persistent_takeover(monkeypatch, tmp_path, oauth=True)
+ mirror = service.migration_reconcile_auth
+
+ async def rejected(ref):
+ raise OAuthCredentialRejectedError()
+
+ def fail_terminal(snapshot):
+ if service.migration_journal.load().get("terminal"):
+ raise OSError("fixture terminal mirror failure")
+ mirror(snapshot)
+
+ adapter.validate_oauth_credential = rejected
+ service.migration_reconcile_auth = fail_terminal
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert service.migration_journal.load()["terminal"]["invalid_source_ids"]
+ assert service.migration_journal.completed() is None
+ assert service.migration_blocked_backends == {"claude"}
+ assert runtime.admissions == runtime.turns == {"claude"}
+ ref = service.store.load().sources[0].credential_ref
+ activated = list(adapter.activated)
+ service.migration_reconcile_auth = mirror
+ asyncio.run(recover_native_migration(service))
+ assert live == service.store.native_auth_snapshot(("claude",))
+ assert adapter.activated == activated # Terminal retry cannot republish old OAuth.
+ assert not adapter.revoked
+ assert service.store.load().sources[0].credential_ref == ref
+ assert service.store.load().sources[0].state.status == "needs_action"
+ assert service.migration_journal.completed()["outcome"] == "needs_auth"
+ assert service.migration_journal.load() is None
+ assert not runtime.admissions and not runtime.turns
diff --git a/tests/test_model_hub_migration_source_identity.py b/tests/test_model_hub_migration_source_identity.py
new file mode 100644
index 000000000..842f74b12
--- /dev/null
+++ b/tests/test_model_hub_migration_source_identity.py
@@ -0,0 +1,334 @@
+"""Takeover identity is a credential target, not a file path or placement."""
+
+import asyncio
+import json
+
+import pytest
+
+from config.v2_config import (
+ ModelHubBackendModelConfig,
+ ModelHubModelConfig,
+ ModelHubRouteConfig,
+ ModelHubRouteHopConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+)
+from core.handlers.model_hub.migration import scan_native_configs
+from core.handlers.model_hub.migration_files import plan_native_cleanup
+from core.handlers.model_hub.migration_journal import NativeFileEdit, TakeoverStateError
+from core.handlers.model_hub.service import ModelHubError
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home,
+ _service,
+ _write,
+ _write_claude_oauth,
+ _write_codex_oauth,
+)
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("placement", ["absent", "default", "manual"])
+def test_reused_credential_remains_available_to_consented_backend(
+ monkeypatch, tmp_path, backend, placement,
+):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ vendor = "anthropic" if backend == "claude" else "openai"
+ for key in ("fixture-selected", "fixture-unrelated"):
+ asyncio.run(service.create_source({
+ "kind": "api_key", "vendor": vendor, "key": key,
+ "display_name": key,
+ }))
+ selected, unrelated = store.config.sources
+ agent = store.config.agents[backend]
+ agent.mode = "direct"
+ if placement != "default":
+ agent.sources.order.remove(selected.id)
+ # Existing explicit intent must not be rewritten by default placement.
+ if backend == "opencode":
+ agent.models = [ModelHubBackendModelConfig(
+ id="fixture/model", origin="manual", native_protocol="openai_responses",
+ )]
+ menu_model = agent.models[0].id
+ agent.routes[menu_model] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(
+ selected.id if placement == "manual" else unrelated.id, "manual-target",
+ ),),
+ )
+ if backend == "claude":
+ native = home / ".claude/settings.json"
+ content = {"env": {"ANTHROPIC_API_KEY": "fixture-selected"}}
+ elif backend == "codex":
+ native = home / ".codex/auth.json"
+ content = {"OPENAI_API_KEY": "fixture-selected"}
+ else:
+ native = home / ".config/opencode/opencode.json"
+ content = {"provider": {"openai": {"options": {"apiKey": "fixture-selected"}}}}
+ _write(native, json.dumps(content))
+ store.config = service._clone_config(store.config)
+ before = store.config.to_payload()
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1
+
+ after = store.config.to_payload()
+ assert after["sources"] == before["sources"]
+ assert len(adapter.provisioned) == 2
+ assert after["agents"][backend]["routes"] == before["agents"][backend]["routes"]
+ expected = before["agents"][backend]["sources"]["order"]
+ if placement == "absent":
+ expected = [*expected, selected.id]
+ assert store.config.effective_source_order(backend) == expected
+ for other in {"claude", "codex", "opencode"} - {backend}:
+ assert after["agents"][other] == before["agents"][other]
+ assert store.config.agents[backend].mode == "hub"
+ assert not native.exists() or "fixture-selected" not in native.read_text()
+ assert service.migration_journal.load() is None
+
+
+def _shared_opencode(monkeypatch, tmp_path, *, different_target=False, shadow_keys=False):
+ home, project = tmp_path / "native", tmp_path / "project"
+ _isolate_native_home(monkeypatch, home)
+ paths = [
+ home / ".config/opencode/opencode.json",
+ project / ".opencode/opencode.json",
+ ]
+ for index, path in enumerate(paths):
+ options = {"baseURL": "https://fixture.example/v1"}
+ if different_target and index:
+ options["baseURL"] = "https://different.example/v1"
+ if shadow_keys:
+ options["apiKey"] = f"fixture-shadow-{index}"
+ _write(path, json.dumps({
+ "provider": {"openai": {
+ "options": options,
+ "models": {f"manual-{index}": {"name": f"模型 {index}"}},
+ "name": "保留",
+ }},
+ "mcp": {"unrelated": True},
+ }))
+ auth = home / ".local/share/opencode/auth.json"
+ _write(auth, json.dumps({"openai": {"type": "api", "key": "fixture-shared"}}))
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ service.migration_project_roots = lambda: (project,)
+ return service, store, adapter, paths, auth
+
+
[email protected]("different_target,shadow_keys,expected", [
+ (False, False, 1),
+ (True, False, 2),
+ (False, True, 3),
+])
+def test_shared_auth_is_one_source_per_credential_target_not_config_path(
+ monkeypatch, tmp_path, different_target, shadow_keys, expected,
+):
+ service, store, adapter, paths, auth = _shared_opencode(
+ monkeypatch, tmp_path, different_target=different_target, shadow_keys=shadow_keys,
+ )
+ rows = service.migration_scan()["items"]
+ assert len(rows) == expected
+ assert rows == service.migration_scan()["items"]
+ assert asyncio.run(service.migration_apply([row["id"] for row in rows]))["applied"] == expected
+ assert len(adapter.provisioned) == expected
+ assert len(store.config.sources) == expected
+ assert len(store.config.agents["opencode"].sources.order) == expected
+ shared = [source for source in store.config.sources
+ if adapter.keys[source.credential_ref][2] == "fixture-shared"]
+ assert len(shared) == (2 if different_target else 1)
+ if not different_target:
+ assert {
+ (model.id, model.display_name)
+ for model in shared[0].models if model.provenance == "manual"
+ } == {("manual-0", "模型 0"), ("manual-1", "模型 1")}
+ for path in paths:
+ result = json.loads(path.read_text())
+ assert result["provider"]["openai"]["name"] == "保留"
+ assert "options" not in result["provider"]["openai"]
+ 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 len(adapter.provisioned) == expected
+
+
[email protected]("change", ["model", "target", "key"])
+def test_shared_credential_consent_binds_every_contributing_config(monkeypatch, tmp_path, change):
+ service, _, adapter, paths, auth = _shared_opencode(monkeypatch, tmp_path)
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ assert len(ids) == 1
+ payload = json.loads(paths[1].read_text())
+ provider = payload["provider"]["openai"]
+ if change == "model":
+ provider["models"]["manual-new"] = {"name": "新模型"}
+ elif change == "target":
+ provider["options"]["baseURL"] = "https://new.example/v1"
+ else:
+ provider["options"]["apiKey"] = "fixture-new-login"
+ 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))
+ assert error.value.code == "migration_item_conflict"
+ assert not adapter.provisioned
+ assert {path: path.read_bytes() for path in before} == before
+ assert service.migration_journal.load() is None
+
+
[email protected]("backend,vendor,protocol,writer", [
+ ("claude", "anthropic", "anthropic", _write_claude_oauth),
+ ("codex", "openai", "openai_responses", _write_codex_oauth),
+])
+def test_existing_native_source_conversion_also_restores_missing_placement(
+ monkeypatch, tmp_path, backend, vendor, protocol, writer,
+):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ writer(home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ store.config.sources.append(ModelHubSourceConfig(
+ id="src_existingnative", kind="subscription", vendor=vendor,
+ protocol=protocol, display_name="既有订阅", supply_channel="native_cli",
+ billing="monthly", state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id="fixture-existing", provenance="manual", display_name="保留模型")],
+ ))
+ store.config.agents[backend].mode = "direct"
+ 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
+
+ source, = store.config.sources
+ assert source.id == "src_existingnative"
+ assert source.supply_channel == "hub"
+ assert [model.to_payload() for model in source.models] == before["sources"][0]["models"]
+ assert store.config.effective_source_order(backend) == [source.id]
+ assert len(adapter.oauth_provisioned) == 1
+ for other in {"claude", "codex", "opencode"} - {backend}:
+ assert store.config.to_payload()["agents"][other] == before["agents"][other]
+
+
+def test_deduplicated_auth_reversal_restores_every_physical_config(monkeypatch, tmp_path):
+ service, store, adapter, paths, auth = _shared_opencode(monkeypatch, tmp_path)
+ before = {path: path.read_bytes() for path in [*paths, auth]}
+ previous = store.config.to_payload()
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ assert len(ids) == 1
+ apply = NativeFileEdit.apply
+ cleaned = []
+
+ def fail_second(edit, *, reverse=False):
+ if not reverse:
+ cleaned.append(edit.path)
+ if len(cleaned) == 2:
+ raise OSError("fixture interrupted native cleanup")
+ return apply(edit, reverse=reverse)
+
+ monkeypatch.setattr(NativeFileEdit, "apply", fail_second)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert len(adapter.provisioned) == 1
+ assert len(adapter.revoked) == 1
+ assert store.config.to_payload() == previous
+ assert {path: path.read_bytes() for path in before} == before
+ assert service.migration_journal.load() is None
+
+
+def test_deduplication_keeps_blocked_config_layers_visible(monkeypatch, tmp_path):
+ service, _, adapter, paths, auth = _shared_opencode(monkeypatch, tmp_path)
+ paths[1].write_text('{"provider":{"openai":{"options":{"apiKey":"{file:private}"}}}}')
+ rows = service.migration_scan()["items"]
+ assert len(rows) == 2
+ assert {row["proposed_action"] for row in rows} == {"import", "reauth"}
+ before = auth.read_bytes()
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(
+ [row["id"] for row in rows if row["proposed_action"] == "import"],
+ ))
+ assert not adapter.provisioned
+ assert auth.read_bytes() == before
+
+
+def _model_only_opencode(monkeypatch, tmp_path):
+ service, store, adapter, paths, auth = _shared_opencode(monkeypatch, tmp_path)
+ for path in paths:
+ payload = json.loads(path.read_text())
+ payload["provider"]["openai"].pop("options")
+ path.write_text(json.dumps(payload))
+ return service, store, adapter, paths, auth
+
+
[email protected]("change", ["model", "credential", "new_layer"])
+def test_cleanup_guards_model_only_and_absent_layers(monkeypatch, tmp_path, change):
+ service, store, _, paths, auth = _model_only_opencode(monkeypatch, tmp_path)
+ items = scan_native_configs(
+ store.load(), home=service.migration_home,
+ project_roots=service.migration_project_roots(), mask_credential=lambda _: "***",
+ )
+ assert len(items) == 1
+ edits = plan_native_cleanup(
+ items, home=service.migration_home, project_roots=service.migration_project_roots(),
+ )
+ changed_path = paths[1] if change != "new_layer" else paths[1].with_suffix(".jsonc")
+ payload = json.loads(paths[1].read_text())
+ if change == "model":
+ payload["provider"]["openai"]["models"]["manual-1"]["name"] = "变化"
+ else:
+ payload["provider"]["openai"]["options"] = {"apiKey": "fixture-new-login"}
+ changed_path.write_text(json.dumps(payload))
+ with pytest.raises(TakeoverStateError):
+ for edit in edits:
+ edit.check()
+ assert "fixture-shared" in auth.read_text()
+
+
+def test_model_only_cleanup_preserves_bytes_and_guards_through_recovery(monkeypatch, tmp_path):
+ service, store, _, paths, _ = _model_only_opencode(monkeypatch, tmp_path)
+ before = {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in paths}
+ items = scan_native_configs(
+ store.load(), home=service.migration_home,
+ project_roots=service.migration_project_roots(), mask_credential=lambda _: "***",
+ )
+ edits = [
+ NativeFileEdit.from_payload(edit.to_payload())
+ for edit in plan_native_cleanup(
+ items, home=service.migration_home, project_roots=service.migration_project_roots(),
+ )
+ ]
+ assert set(paths) <= {edit.path for edit in edits if edit.before == edit.after}
+ for edit in edits:
+ edit.check()
+ edit.apply()
+ edit.check(applied=True)
+ edit.apply(reverse=True)
+ edit.check()
+ assert {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in paths} == before
+
+
[email protected]("change", ["model", "credential", "new_layer"])
+def test_async_provision_cannot_hide_changed_model_only_layer(monkeypatch, tmp_path, change):
+ service, store, adapter, paths, auth = _model_only_opencode(monkeypatch, tmp_path)
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ before = store.config.to_payload()
+ original_auth = auth.read_bytes()
+ provision = adapter.provision_credential
+ changed_path = paths[1] if change != "new_layer" else paths[1].with_suffix(".jsonc")
+
+ async def change_after_plan(*args, **kwargs):
+ ref = await provision(*args, **kwargs)
+ payload = json.loads(paths[1].read_text())
+ if change == "model":
+ payload["provider"]["openai"]["models"]["manual-1"]["name"] = "变化"
+ else:
+ payload["provider"]["openai"]["options"] = {"apiKey": "fixture-new-login"}
+ changed_path.write_text(json.dumps(payload))
+ return ref
+
+ adapter.provision_credential = change_after_plan
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply(ids))
+ assert error.value.code == "migration_configuration_blocked"
+ assert store.config.to_payload() == before
+ assert auth.read_bytes() == original_auth
+ assert len(adapter.provisioned) == len(adapter.revoked) == 1
+ assert service.migration_journal.load() is None
diff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.py
new file mode 100644
index 000000000..be4e7c640
--- /dev/null
+++ b/tests/test_model_hub_native_takeover.py
@@ -0,0 +1,520 @@
+"""Ownership-boundary tests use only synthetic homes and engine doubles."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from contextlib import asynccontextmanager, nullcontext
+
+import pytest
+
+from core.handlers.model_hub.migration_journal import NativeFileEdit, NativeTakeoverJournal
+from core.handlers.model_hub.service import EngineUnavailableError, ModelHubError
+from config.v2_config import ModelHubConfig
+from core.handlers.model_hub.adapter import (
+ OAuthCredentialRejectedError,
+ OAuthFlowState,
+ RuntimePlatformUnsupportedError,
+)
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home,
+ _service,
+ _write,
+ _write_claude_oauth,
+ _write_codex_oauth,
+)
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("native_present", [False, True])
[email protected]("boundary", ["entry", "verify"])
+def test_mode_only_adoption_checks_native_absence_inside_guard(
+ monkeypatch, tmp_path, backend, native_present, boundary,
+):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ store.config.agents[backend].mode = "direct"
+ assert service.migration_scan()["items"] == []
+ checks = []
+
+ def login():
+ if native_present:
+ if backend == "claude":
+ _write_claude_oauth(home)
+ elif backend == "codex":
+ _write_codex_oauth(home)
+ else:
+ _write(home / ".local/share/opencode/auth.json",
+ '{"openai":{"type":"api","key":"fixture-key"}}')
+
+ @asynccontextmanager
+ async def guard(backends):
+ assert backends == (backend,)
+ assert not service._mutation_lock.locked()
+ if boundary == "entry":
+ login()
+ async def verify():
+ checks.append(True)
+ if boundary == "verify":
+ login()
+ yield verify
+
+ service.migration_guard = guard
+ if native_present:
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(service.set_agent_mode(backend, "hub"))
+ assert failure.value.code == "mode_switch_blocked"
+ assert store.config.agents[backend].mode == "direct"
+ assert service.migration_scan()["items"]
+ else:
+ assert asyncio.run(service.set_agent_mode(backend, "hub"))["mode"] == "hub"
+ assert checks
+ assert not store.config.sources
+ assert not adapter.provisioned and not adapter.oauth_provisioned
+ assert service.migration_journal.load() is None
+
+
+def test_oauth_is_not_exposed_until_native_cleanup_and_mode_commit(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _write_claude_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ store.config.agents["claude"].mode = "direct"
+ item_ids = [item["id"] for item in service.migration_scan()["items"]]
+ activate = adapter.activate_oauth_credential
+ synced = adapter.sync_sources
+
+ async def checked_sync(bindings):
+ assert service.migration_journal.load()["phase"] == "exposed"
+ assert adapter.activated
+ await synced(bindings)
+
+ adapter.sync_sources = checked_sync
+
+ async def checked_activate(ref):
+ assert not (home / ".claude/.credentials.json").exists()
+ assert store.config.agents["claude"].mode == "hub"
+ assert service.migration_journal.load()["phase"] == "exposed"
+ await activate(ref)
+
+ adapter.activate_oauth_credential = checked_activate
+ result = asyncio.run(service.migration_apply(item_ids))
+ assert result["applied"] == 1
+ assert adapter.validated == adapter.activated
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends
+ assert asyncio.run(service.migration_apply(item_ids))["applied"] == 1
+ assert len(adapter.oauth_provisioned) == 1
+ assert "refresh_token" not in service.migration_journal.path.with_name("last-completed.json").read_text()
+
+
+def test_failure_after_possible_rotation_retains_current_owner_and_retries(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _write_codex_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ store.config.agents["codex"].mode = "direct"
+ item_ids = [item["id"] for item in service.migration_scan()["items"]]
+ activate = adapter.activate_oauth_credential
+ rotated = {}
+
+ async def activate_then_fail(ref):
+ await activate(ref)
+ rotated[ref] = "synthetic-current-refresh-token"
+ raise RuntimeError("synthetic transport failure after rotation")
+
+ adapter.activate_oauth_credential = activate_then_fail
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(item_ids))
+ assert service.migration_journal.load()["phase"] == "exposed"
+ assert store.config.agents["codex"].mode == "hub"
+ assert not (home / ".codex/auth.json").exists()
+ assert adapter.revoked == []
+ assert service.migration_blocked_backends == {"codex"}
+ assert [item["id"] for item in service.migration_scan()["items"]] == item_ids
+
+ async def resume(ref):
+ assert rotated[ref] == "synthetic-current-refresh-token"
+ await activate(ref)
+
+ adapter.activate_oauth_credential = resume
+ assert asyncio.run(service.migration_apply(item_ids))["applied"] == 1
+ assert len(adapter.oauth_provisioned) == 1
+ assert service.migration_journal.load() is None
+
+
+ "error,code",
+ [(EngineUnavailableError, "engine_down"),
+ (RuntimePlatformUnsupportedError, "runtime_platform_unsupported")],
+)
+def test_unavailable_runtime_preserves_native_oauth_before_custody(monkeypatch, tmp_path, error, code):
+ home = tmp_path / "native"
+ _write_codex_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ native = home / ".codex/auth.json"
+ before = native.read_bytes()
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ store.config.agents["codex"].mode = "direct"
+ previous = store.config.to_payload()
+ item_ids = [item["id"] for item in service.migration_scan()["items"]]
+
+ async def unavailable(**kwargs):
+ raise error()
+
+ adapter.ensure_installed = unavailable
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(service.migration_apply(item_ids))
+ assert failure.value.code == code
+ assert native.read_bytes() == before
+ assert store.config.to_payload() == previous
+ assert not adapter.activated
+ assert not adapter.synced
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends
+
+
[email protected]("backend", ["opencode", "codex", "claude"])
+def test_completed_receipt_recleans_resurrected_credentials_without_reimport(
+ monkeypatch, tmp_path, backend,
+):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ if backend == "opencode":
+ native = home / ".config/opencode/opencode.json"
+ _write(native, json.dumps({
+ "provider": {"openai": {"options": {"apiKey": "fixture-old-key"}}},
+ "mcp": {"keep": True},
+ }))
+ elif backend == "codex":
+ _write_codex_oauth(home)
+ native = home / ".codex/auth.json"
+ else:
+ _write_claude_oauth(home)
+ native = home / ".claude/.credentials.json"
+ 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
+ current = store.config.to_payload()
+ provisions = (len(adapter.provisioned), len(adapter.oauth_provisioned))
+
+ # This is an external native writer, not an Avibe-owned auth operation.
+ native.write_bytes(original)
+ assert [row["id"] for row in service.migration_scan()["items"]] == ids
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1
+ assert service.migration_scan()["items"] == []
+ assert store.config.to_payload() == current
+ assert (len(adapter.provisioned), len(adapter.oauth_provisioned)) == provisions
+ assert service.migration_journal.load() is None
+ assert adapter.revoked == []
+
+
+def test_completed_receipt_does_not_authorize_new_unconsented_native_key(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ native = home / ".config/opencode/opencode.json"
+ _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))
+ changed = '{"provider":{"openai":{"options":{"apiKey":"fixture-new"}}}}'
+ native.write_text(changed)
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(service.migration_apply(ids))
+ assert failure.value.code == "migration_item_conflict"
+ assert native.read_text() == changed
+ assert len(adapter.provisioned) == 1
+
+
+def test_restart_recovers_exposed_handoff_without_native_tokens(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _write_claude_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ first, store, adapter = _service(tmp_path, migration_home=home)
+ ids = [item["id"] for item in first.migration_scan()["items"]]
+ validate = adapter.validate_oauth_credential
+
+ async def offline(ref):
+ raise RuntimeError("synthetic network outage")
+
+ adapter.validate_oauth_credential = offline
+ with pytest.raises(ModelHubError):
+ asyncio.run(first.migration_apply(ids))
+ second, _, _ = _service(tmp_path, migration_home=home)
+ second.store = store
+ second.adapter = adapter
+ adapter.validate_oauth_credential = validate
+ asyncio.run(second.recover_runtime_intent())
+ assert not second.migration_blocked_backends
+ assert second.migration_journal.load() is None
+ assert len(adapter.oauth_provisioned) == 1
+
+
+def test_caller_cancellation_does_not_abandon_credential_custody(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _write_claude_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ ids = [item["id"] for item in service.migration_scan()["items"]]
+
+ async def exercise():
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ activate = adapter.activate_oauth_credential
+
+ async def paused(ref):
+ entered.set()
+ await release.wait()
+ await activate(ref)
+
+ adapter.activate_oauth_credential = paused
+ task = asyncio.create_task(service.migration_apply(ids))
+ await entered.wait()
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done()
+ release.set()
+ assert (await task)["applied"] == 1
+
+ asyncio.run(exercise())
+ assert service.migration_journal.load() is None
+ assert adapter.revoked == []
+
+
+def test_native_compare_and_swap_does_not_erase_a_concurrent_login(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _write_claude_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ ids = [item["id"] for item in service.migration_scan()["items"]]
+ path = home / ".claude/.credentials.json"
+ concurrent = '{"claudeAiOauth":{"accessToken":"different-user","refreshToken":"different-grant"}}'
+
+ async def changed_during_preparation():
+ path.write_text(concurrent)
+
+ service.migration_guard = lambda backends: nullcontext(changed_during_preparation)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert path.read_text() == concurrent
+ assert adapter.activated == []
+ assert service.migration_journal.load()["phase"] == "reverting"
+
+
+def test_journal_roundtrip_and_file_edits_are_private_and_replayable(tmp_path):
+ path = tmp_path / "credentials.json"
+ _write(path, '{"login":"synthetic","mcp":{"name":"保留"}}')
+ before = path.read_bytes()
+ after = b'{"mcp":{"name":"\\u4fdd\\u7559"}}'
+ edit = NativeFileEdit.plan(path, after)
+ journal = NativeTakeoverJournal(tmp_path / "takeover/current.json")
+ journal.save({
+ "version": 1, "phase": "prepared", "items": [],
+ "backends": ["claude"], "files": [edit.to_payload()],
+ "source_ids": [], "credentials": [],
+ "previous": ModelHubConfig().to_payload(),
+ "updated": ModelHubConfig().to_payload(),
+ })
+ assert journal.path.stat().st_mode & 0o777 == 0o600
+ loaded = NativeFileEdit.from_payload(journal.load()["files"][0])
+ loaded.apply()
+ loaded.apply()
+ assert path.read_bytes() == after
+ loaded.apply(reverse=True)
+ assert path.read_bytes() == before
+
+
+def test_invalid_journal_does_not_start_engine_or_admit_native_backends(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ home.mkdir()
+ _isolate_native_home(monkeypatch, home)
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ path = service.migration_journal.path
+ path.parent.mkdir(parents=True, mode=0o700)
+ path.write_text("not-json")
+ path.chmod(0o600)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.recover_runtime_intent())
+ assert service.migration_blocked_backends == {"claude", "codex", "opencode"}
+ assert adapter.activated == []
+
+
+def test_rejected_refresh_finishes_custody_without_claiming_success(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _write_claude_oauth(home)
+ _write_codex_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ ids = [item["id"] for item in service.migration_scan()["items"]]
+ validate = adapter.validate_oauth_credential
+
+ async def reject_claude(ref):
+ await validate(ref)
+ claude = next(source for source in store.config.sources if source.vendor == "anthropic")
+ if ref == claude.credential_ref:
+ raise OAuthCredentialRejectedError()
+
+ adapter.validate_oauth_credential = reject_claude
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(service.migration_apply(ids))
+ assert failure.value.code == "migration_credentials_invalid"
+ assert len(adapter.validated) == 2
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends
+ assert not (home / ".claude/.credentials.json").exists()
+ assert not (home / ".codex/auth.json").exists()
+ assert adapter.revoked == []
+ 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 claude.state.status == "needs_action"
+ 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))
+ assert repeated.value.code == "migration_credentials_invalid"
+ assert len(adapter.validated) == 2
+ # Normal Hub config/auth repair is not trapped behind the migration gate.
+ service._save_config(service._clone_config(store.config))
+
+
[email protected]("crash_before_receipt", [False, True])
+def test_explicit_hub_reauth_can_repair_inconclusive_exposed_takeover(
+ monkeypatch, tmp_path, crash_before_receipt,
+):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write_codex_oauth(home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ ids = [item["id"] for item in service.migration_scan()["items"]]
+
+ async def inconclusive(ref):
+ adapter.validated.append(ref)
+ raise RuntimeError("fixture CPA status: token expired; no refresh provenance")
+
+ adapter.validate_oauth_credential = inconclusive
+ with pytest.raises(ModelHubError) as pending:
+ asyncio.run(service.migration_apply(ids))
+ assert pending.value.code == "migration_recovery_pending"
+ source = store.config.sources[0]
+ retained_ref = source.credential_ref
+ starts = []
+
+ async def start(source_id, vendor):
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends
+ assert store.config.sources[0].credential_ref == retained_ref
+ starts.append(source_id)
+ 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
+ # The escape is an existing explicitly acknowledged reauthentication, not
+ # an implicit interpretation of a 401/503 or a migration cancellation.
+ with pytest.raises(ModelHubError) as unacknowledged:
+ asyncio.run(service.reauth_source(source.id, {}))
+ assert unacknowledged.value.code == "reauth_confirmation_required"
+ assert service.migration_journal.load()["phase"] == "exposed"
+
+ complete = service.migration_journal.complete
+ if crash_before_receipt:
+ def disk_unavailable(record):
+ raise OSError("fixture crash before receipt")
+
+ service.migration_journal.complete = disk_unavailable
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))
+ assert service.migration_journal.load()["terminal"]["reason"] == "reauth_requested"
+ assert starts == []
+ service.migration_journal.complete = complete
+ asyncio.run(service.recover_runtime_intent())
+ result = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))
+ assert result["flow"]["channel"] == "hub"
+ assert result["flow"]["intent"] == "reauth"
+ assert starts == [source.id]
+ assert service.migration_journal.completed()["outcome"] == "reauth_requested"
+ assert adapter.revoked == []
+ assert len(adapter.validated) == 1
+ 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))
+ assert replay.value.code != "migration_credentials_invalid"
+
+
+def test_explicit_reauth_keeps_verified_sibling_usable(monkeypatch, tmp_path):
+ from core.handlers.model_hub.migration import prepare_takeover_reauthentication
+
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write_claude_oauth(home)
+ _write_codex_oauth(home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+
+ async def validate(ref):
+ source = next(source for source in store.config.sources if source.credential_ref == ref)
+ adapter.validated.append(ref)
+ if source.vendor == "openai":
+ raise RuntimeError("fixture inconclusive validation")
+
+ adapter.validate_oauth_credential = validate
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ 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]
+ asyncio.run(prepare_takeover_reauthentication(service, codex.id))
+ assert store.config.sources[0].state.status == claude.state.status == "standby"
+ assert next(source for source in store.config.sources if source.id == codex.id).state.status == "needs_action"
+ assert len(adapter.validated) == 2
+ assert adapter.revoked == []
+
+
[email protected]("boundary", ["terminal_config", "receipt"])
+def test_rejected_grant_terminal_decision_recovers_after_crash(monkeypatch, tmp_path, boundary):
+ home = tmp_path / "native"
+ _write_claude_oauth(home)
+ _isolate_native_home(monkeypatch, home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ ids = [item["id"] for item in service.migration_scan()["items"]]
+
+ async def rejected(ref):
+ adapter.validated.append(ref)
+ raise OAuthCredentialRejectedError()
+
+ adapter.validate_oauth_credential = rejected
+ save = store.save
+ complete = service.migration_journal.complete
+
+ def fail_terminal(config):
+ if any(source.state.status == "needs_action" for source in config.sources):
+ raise OSError("synthetic persistence failure")
+ save(config)
+
+ def fail_receipt(record):
+ raise OSError("synthetic receipt failure")
+
+ if boundary == "terminal_config":
+ store.save = fail_terminal
+ else:
+ service.migration_journal.complete = fail_receipt
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ record = service.migration_journal.load()
+ assert record["phase"] == "exposed"
+ assert record["terminal"]["invalid_source_ids"]
+ assert service.migration_blocked_backends == {"claude"}
+ store.save = save
+ service.migration_journal.complete = complete
+ asyncio.run(service.recover_runtime_intent())
+ assert len(adapter.validated) == 1
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends
+ assert store.config.sources[0].state.status == "needs_action"
+ assert adapter.revoked == []
diff --git a/tests/test_model_hub_oauth_takeover.py b/tests/test_model_hub_oauth_takeover.py
new file mode 100644
index 000000000..e06fc1c03
--- /dev/null
+++ b/tests/test_model_hub_oauth_takeover.py
@@ -0,0 +1,688 @@
+from __future__ import annotations
+
+import json
+import errno
+import os
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import vibe.model_hub_runtime.adapter as runtime_adapter
+from core.handlers.model_hub.adapter import OAuthCredentialRejectedError
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore
+
+
+def _oauth_material(kind: str = "codex") -> dict[str, str]:
+ return {
+ "type": kind,
+ "access_token": "access-token-fixture",
+ "refresh_token": "refresh-token-fixture",
+ "account_id": "account-fixture",
+ }
+
+
+def test_oauth_stage_binds_prefix_and_accepts_cpa_rotation(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ ref = store.stage_oauth_credential(
+ "src_fixture123",
+ "openai",
+ "avibe-migration-fixture.json",
+ _oauth_material(),
+ )
+
+ assert not (store.auth_dir / "avibe-migration-fixture.json").exists()
+ assert (store.oauth_staging_dir / f"{ref}.json").exists()
+ staged = json.loads((store.oauth_staging_dir / f"{ref}.json").read_text())
+ prefix = str(store.credential_metadata(ref)["prefix"])
+ assert staged["prefix"] == prefix
+
+ auth_name, payload, activated_prefix, already_active = store.activate_oauth_auth_file(ref)
+ assert auth_name == "avibe-migration-fixture.json"
+ assert payload["type"] == "codex"
+ assert activated_prefix == prefix
+ assert payload["prefix"] == prefix
+ assert already_active is False
+ assert not (store.oauth_staging_dir / f"{ref}.json").exists()
+
+ store.mark_oauth_engine_published(ref)
+ store.mark_oauth_prefix_published(ref)
+ live_path = store.auth_dir / auth_name
+ rotated_payload = {
+ "type": "codex",
+ "access_token": "rotated-access-fixture",
+ "refresh_token": "rotated-refresh-fixture",
+ "prefix": prefix,
+ }
+ rotated = (json.dumps(rotated_payload, sort_keys=True) + "\n").encode()
+ live_path.write_bytes(rotated)
+ live_path.chmod(0o600)
+
+ _, current, _, already_active = store.activate_oauth_auth_file(ref)
+ assert already_active is True
+ assert current == rotated_payload
+ assert live_path.read_bytes() == rotated
+
+
+def test_matches_api_key_checks_target_and_keeps_unreadable_ref_fail_closed(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ ref = store.store_api_key(
+ "密钥-fixture",
+ vendor="anthropic",
+ protocol="anthropic",
+ base_url=None,
+ )
+
+ assert store.matches_api_key_credential(
+ ref,
+ "anthropic",
+ "anthropic",
+ "密钥-fixture",
+ None,
+ )
+ assert not store.matches_api_key_credential(
+ ref,
+ "anthropic",
+ "anthropic",
+ "other-fixture",
+ None,
+ )
+ assert not store.matches_api_key_credential(
+ ref,
+ "anthropic",
+ "openai_chat",
+ "密钥-fixture",
+ None,
+ )
+
+ with pytest.raises(EngineStateError, match="unavailable"):
+ store.matches_api_key_credential(
+ "cred_" + "f" * 32,
+ "anthropic",
+ "anthropic",
+ "密钥-fixture",
+ None,
+ )
+
+
+class _FakeEngineClient:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, str]] = []
+ self.files: list[dict[str, Any]] = []
+ self.api_call_payloads: list[dict[str, Any]] = []
+ self.api_call_response = '{"plan_type":"pro"}'
+ self.api_call_status_code = 200
+ self.on_restart: Any = None
+ self.on_inventory: Any = None
+
+ def management_request(
+ self,
+ method: str,
+ path: str,
+ *,
+ query: dict[str, Any] | None = None,
+ payload: dict[str, Any] | None = None,
+ timeout: float | None = None,
+ ) -> dict[str, Any]:
+ del timeout
+ self.calls.append((method, path))
+ if method == "GET" and path == "/auth-files":
+ if self.on_inventory is not None:
+ callback, self.on_inventory = self.on_inventory, None
+ callback()
+ return {"files": list(self.files)}
+ if method == "POST" and path == "/auth-files":
+ raise AssertionError("OAuth activation must not re-upload a watched file")
+ if method == "POST" and path == "/api-call":
+ assert payload is not None
+ self.api_call_payloads.append(payload)
+ return {
+ "status_code": self.api_call_status_code,
+ "body": self.api_call_response,
+ }
+ if method == "PATCH" and path == "/auth-files/fields":
+ return {"status": "ok"}
+ raise AssertionError((method, path, payload))
+
+
+class _FakeSupervisor:
+ def __init__(self, store: EngineStateStore, client: _FakeEngineClient) -> None:
+ self.state_store = store
+ self.client_value = client
+
+ def client_if_running(self) -> _FakeEngineClient:
+ return self.client_value
+
+ def client(self) -> _FakeEngineClient:
+ return self.client_value
+
+ def restart_if_running(self) -> None:
+ if self.client_value.on_restart is not None:
+ self.client_value.on_restart()
+ return
+ auth_files = list(self.state_store.auth_dir.glob("*.json"))
+ if len(auth_files) != 1:
+ return
+ payload = json.loads(auth_files[0].read_text())
+ self.client_value.files = [
+ {
+ "id": auth_files[0].name,
+ "name": auth_files[0].name,
+ "provider": payload["type"],
+ "auth_index": "0",
+ "id_token": {"chatgpt_account_id": payload.get("account_id")},
+ }
+ ]
+
+
+async def test_adapter_activation_is_idempotent_and_does_not_reupload(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ def reconcile_from_watched_file() -> None:
+ auth_files = list(store.auth_dir.glob("*.json"))
+ assert len(auth_files) == 1
+ payload = json.loads(auth_files[0].read_text())
+ client.files = [
+ {
+ "id": auth_files[0].name,
+ "name": auth_files[0].name,
+ "provider": payload["type"],
+ "auth_index": "0",
+ "id_token": {"chatgpt_account_id": payload.get("account_id")},
+ }
+ ]
+ client.on_restart = reconcile_from_watched_file
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ assert not list(store.auth_dir.glob("*.json"))
+ await adapter.activate_oauth_credential(ref)
+ first_calls = list(client.calls)
+ assert first_calls == [
+ ("GET", "/auth-files"),
+ ("GET", "/auth-files"),
+ ]
+
+ await adapter.activate_oauth_credential(ref)
+ assert client.calls == first_calls + [("GET", "/auth-files")]
+
+ auth_name = str(store.credential_metadata(ref)["auth_name"])
+ live_path = store.auth_dir / auth_name
+ prefix = str(store.credential_metadata(ref)["prefix"])
+ rotated = (
+ json.dumps(
+ {
+ "type": "codex",
+ "refresh_token": "rotated-fixture",
+ "prefix": prefix,
+ },
+ sort_keys=True,
+ )
+ + "\n"
+ ).encode()
+ live_path.write_bytes(rotated)
+ live_path.chmod(0o600)
+ await adapter.activate_oauth_credential(ref)
+ assert client.calls == first_calls + [("GET", "/auth-files")] * 2
+ assert live_path.read_bytes() == rotated
+
+
+async def test_adapter_does_not_claim_same_name_for_a_different_provider(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ auth_name = str(store.credential_metadata(ref)["auth_name"])
+ client.files = [
+ {
+ "id": auth_name,
+ "name": auth_name,
+ "provider": "claude",
+ "auth_index": "0",
+ }
+ ]
+
+ with pytest.raises(EngineStateError, match="auth record conflicts"):
+ await adapter.activate_oauth_credential(ref)
+ assert client.calls == [("GET", "/auth-files")]
+ assert store.credential_metadata(ref)["engine_published"] is False
+
+
+async def test_activation_retry_after_rotation_keeps_live_r1_and_never_reuploads(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ rotate_and_fail = True
+
+ def reconcile_with_failure() -> None:
+ nonlocal rotate_and_fail
+ if rotate_and_fail:
+ rotate_and_fail = False
+ auth_path = next(store.auth_dir.glob("*.json"))
+ prefix = str(store.credential_metadata(ref)["prefix"])
+ auth_path.write_text(
+ json.dumps(
+ {
+ "type": "codex",
+ "access_token": "r1-access",
+ "refresh_token": "r1-refresh",
+ "prefix": prefix,
+ },
+ sort_keys=True,
+ )
+ + "\n"
+ )
+ auth_path.chmod(0o600)
+ raise RuntimeError("simulated reconcile uncertainty")
+ auth_path = next(store.auth_dir.glob("*.json"))
+ payload = json.loads(auth_path.read_text())
+ client.files = [
+ {
+ "id": auth_path.name,
+ "name": auth_path.name,
+ "provider": payload["type"],
+ "auth_index": "0",
+ "id_token": {"chatgpt_account_id": payload.get("account_id")},
+ }
+ ]
+
+ client.on_restart = reconcile_with_failure
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+
+ with pytest.raises(EngineStateError, match="could not reconcile engine"):
+ await adapter.activate_oauth_credential(ref)
+
+ live_path = next(store.auth_dir.glob("*.json"))
+ r1 = live_path.read_bytes()
+ await adapter.activate_oauth_credential(ref)
+
+ assert live_path.read_bytes() == r1
+ assert all(path != "/auth-files" or method != "POST" for method, path in client.calls)
+ assert store.credential_metadata(ref)["engine_published"] is True
+
+
+async def test_rotation_during_engine_binding_is_accepted_by_identity(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ auth_name, payload, _, _ = store.activate_oauth_auth_file(ref)
+ client.files = [
+ {
+ "id": auth_name,
+ "name": auth_name,
+ "provider": payload["type"],
+ "auth_index": "0",
+ "id_token": {"chatgpt_account_id": payload.get("account_id")},
+ }
+ ]
+
+ def rotate_live_file() -> None:
+ auth_path = next(store.auth_dir.glob("*.json"))
+ prefix = str(store.credential_metadata(ref)["prefix"])
+ auth_path.write_text(
+ json.dumps(
+ {
+ "type": "codex",
+ "access_token": "r1-access",
+ "refresh_token": "r1-refresh",
+ "prefix": prefix,
+ },
+ sort_keys=True,
+ )
+ + "\n"
+ )
+ auth_path.chmod(0o600)
+
+ client.on_inventory = rotate_live_file
+ await adapter.activate_oauth_credential(ref)
+ assert json.loads((store.auth_dir / str(store.credential_metadata(ref)["auth_name"])).read_text())[
+ "refresh_token"
+ ] == "r1-refresh"
+
+
+async def test_startup_retry_reconciles_published_file_without_stale_upload(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ supervisor = _FakeSupervisor(store, client)
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store) # type: ignore[arg-type]
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ auth_name, _, _, _ = store.activate_oauth_auth_file(ref)
+ live_path = store.auth_dir / auth_name
+ prefix = str(store.credential_metadata(ref)["prefix"])
+ live_path.write_text(
+ json.dumps(
+ {
+ "type": "codex",
+ "access_token": "r1-access",
+ "refresh_token": "r1-refresh",
+ "prefix": prefix,
+ },
+ sort_keys=True,
+ )
+ + "\n"
+ )
+ live_path.chmod(0o600)
+
+ def reconcile_from_watched_file() -> None:
+ payload = json.loads(live_path.read_text())
+ client.files = [
+ {
+ "id": auth_name,
+ "name": auth_name,
+ "provider": payload["type"],
+ "auth_index": "0",
+ "id_token": {"chatgpt_account_id": payload.get("account_id")},
+ }
+ ]
+
+ client.on_restart = reconcile_from_watched_file
+ await adapter.activate_oauth_credential(ref)
+
+ assert live_path.read_text() == (
+ json.dumps(
+ {
+ "type": "codex",
+ "access_token": "r1-access",
+ "refresh_token": "r1-refresh",
+ "prefix": prefix,
+ },
+ sort_keys=True,
+ )
+ + "\n"
+ )
+ assert ("POST", "/auth-files") not in client.calls
+
+
[email protected]("vendor", ["openai", "anthropic"])
+ "body",
+ [
+ '{"object":"response"}',
+ '{"type":"message"}',
+ '{"error":{"message":"model is required"}}',
+ '{"account":{"uuid":"account-fixture"},"plan_type":"plus","error":null}',
+ '{"account":{"uuid":true},"plan_type":true}',
+ '{"account":{"uuid":5},"plan_type":5}',
+ '{"account":{"uuid":null},"plan_type":null}',
+ '{"account":{"uuid":" "},"plan_type":" "}',
+ 'null',
+ '200',
+ ],
+)
+def test_control_plane_witness_never_accepts_inference_or_malformed_identity(vendor, body):
+ assert not runtime_adapter._parse_oauth_control_plane_witness(vendor, 200, body)
+
+
+async def test_validate_uses_credential_specific_control_plane_witness(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ await adapter.activate_oauth_credential(ref)
+
+ observed: list[tuple[str, str]] = []
+
+ def probe(**kwargs: Any) -> None:
+ observed.append((kwargs["auth"].auth_index, kwargs["vendor"]))
+
+ monkeypatch.setattr(runtime_adapter, "_probe_oauth_control_plane_witness", probe)
+ await adapter.validate_oauth_credential(ref)
+
+ assert observed == [("0", "openai")]
+ assert ("GET", "/auth-files/models") not in client.calls
+
+
+async def test_validate_rejects_staged_or_denied_grants_without_secret_details(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ with pytest.raises(EngineStateError, match="not active"):
+ await adapter.validate_oauth_credential(ref)
+
+ await adapter.activate_oauth_credential(ref)
+
+ def reject(**_kwargs: Any) -> None:
+ raise runtime_adapter.EngineClientError(
+ "fixture control-plane unavailable",
+ status_code=401,
+ )
+
+ monkeypatch.setattr(runtime_adapter, "_probe_oauth_control_plane_witness", reject)
+ with pytest.raises(
+ EngineStateError,
+ match="OAuth credential validation failed",
+ ) as caught:
+ await adapter.validate_oauth_credential(ref)
+ assert "refresh-token-fixture" not in str(caught.value)
+
+
+ ("vendor", "material_type", "url", "response", "expected_header"),
+ (
+ (
+ "openai",
+ "codex",
+ "https://chatgpt.com/backend-api/wham/usage",
+ '{"plan_type":"future-plan","rate_limit":{"allowed":false}}',
+ ("ChatGPT-Account-ID", "account-fixture"),
+ ),
+ (
+ "anthropic",
+ "claude",
+ "https://api.anthropic.com/api/oauth/profile",
+ '{"account":{"uuid":"fixture-account-uuid"}}',
+ (None, None),
+ ),
+ ),
+)
+async def test_validate_sends_model_free_control_plane_management_probe(
+ tmp_path: Path,
+ vendor: str,
+ material_type: str,
+ url: str,
+ response: str,
+ expected_header: tuple[str | None, str | None],
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ client.api_call_response = response
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ vendor,
+ _oauth_material(material_type),
+ )
+ await adapter.activate_oauth_credential(ref)
+
+ await adapter.validate_oauth_credential(ref)
+
+ assert len(client.api_call_payloads) == 1
+ probe = client.api_call_payloads[0]
+ assert probe["auth_index"] == "0"
+ assert probe["method"] == "GET"
+ assert probe["url"] == url
+ assert probe["header"]["Authorization"] == "Bearer $TOKEN$"
+ assert "data" not in probe
+ assert "access-token-fixture" not in json.dumps(probe)
+ assert "refresh-token-fixture" not in json.dumps(probe)
+ if expected_header[0] is not None:
+ assert probe["header"][expected_header[0]] == expected_header[1]
+ assert probe["header"]["User-Agent"] == "codex-cli"
+ else:
+ assert probe["header"]["User-Agent"] == "axios/1.15.2"
+ assert probe["header"]["Cache-Control"] == "no-cache"
+ assert ("GET", "/auth-files/models") not in client.calls
+
+
+ ("status", "response"),
+ (
+ (200, '{"error":{"type":"invalid_token"}}'),
+ (200, '{"plan_type":""}'),
+ (200, '{"account":{}}'),
+ (200, '["plan_type","pro"]'),
+ (200, "not-json"),
+ (True, '{"plan_type":"pro"}'),
+ (None, '{"plan_type":"pro"}'),
+ (401, '{"error":{"type":"invalid_token"}}'),
+ (403, '{"error":{"type":"permission_error"}}'),
+ (503, '{"error":{"type":"unavailable"}}'),
+ ),
+)
+async def test_validate_rejects_non_witness_control_plane_shapes(
+ tmp_path: Path,
+ status: Any,
+ response: str,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ client.api_call_status_code = status
+ client.api_call_response = response
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ await adapter.activate_oauth_credential(ref)
+
+ with pytest.raises(
+ EngineStateError,
+ match="^OAuth credential validation failed$",
+ ):
+ await adapter.validate_oauth_credential(ref)
+
+
[email protected]("status_message", [
+ "token expired",
+ "unauthorized",
+ "invalid_grant",
+ 'token refresh failed with status 400: {"error":"invalid_grant","code":"refresh_token_reused"}',
+ 'bad response status code 400, message: {"error":"invalid_grant"}',
+])
+async def test_inventory_without_refresh_provenance_cannot_terminalize(
+ tmp_path: Path, status_message: str,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ client = _FakeEngineClient()
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_FakeSupervisor(store, client), # type: ignore[arg-type]
+ state_store=store,
+ )
+ ref = await adapter.provision_oauth_credential(
+ "src_fixture123",
+ "openai",
+ _oauth_material(),
+ )
+ await adapter.activate_oauth_credential(ref)
+ client.files[0].update(
+ {
+ "status": "error",
+ "status_message": status_message,
+ "unavailable": True,
+ }
+ )
+
+ client.api_call_status_code = 401
+ client.api_call_response = '{"error":{"type":"invalid_token"}}'
+ with pytest.raises(EngineStateError) as caught:
+ await adapter.validate_oauth_credential(ref)
+ assert not isinstance(caught.value, OAuthCredentialRejectedError)
+ assert "refresh-token-fixture" not in str(caught.value)
+
+
[email protected](not getattr(os, "O_DIRECTORY", 0), reason="platform has no directory fsync")
+def test_publication_directory_sync_error_cannot_be_reported_as_success(tmp_path, monkeypatch):
+ def unavailable(_descriptor):
+ raise OSError(errno.EIO, "fixture disk error")
+
+ monkeypatch.setattr(os, "fsync", unavailable)
+ with pytest.raises(OSError) as failure:
+ EngineStateStore._fsync_directory(tmp_path)
+ assert failure.value.errno == errno.EIO
diff --git a/tests/test_model_hub_provisional_ownership.py b/tests/test_model_hub_provisional_ownership.py
new file mode 100644
index 000000000..7c596d78a
--- /dev/null
+++ b/tests/test_model_hub_provisional_ownership.py
@@ -0,0 +1,237 @@
+"""Write-ahead takeover ownership, using fixture homes and engine doubles."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from core.handlers.model_hub.service import ModelHubError
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home,
+ _service,
+ _write,
+ _write_claude_oauth,
+)
+
+
+def _native(monkeypatch, tmp_path, kind):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ if kind == "oauth":
+ _write_claude_oauth(home)
+ path = home / ".claude/.credentials.json"
+ else:
+ path = home / ".config/opencode/opencode.json"
+ _write(path, '{"provider":{"openai":{"options":{"apiKey":"fixture-密钥"}}}}')
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ rows = service.migration_scan()["items"]
+ assert len(rows) == 1
+ store.config.agents[rows[0]["backend"]].mode = "direct"
+ return service, store, adapter, path, [rows[0]["id"]]
+
+
[email protected]("kind", ["oauth", "api_key", "observation"])
+def test_provision_failure_before_return_keeps_durable_cleanup_owner(monkeypatch, tmp_path, kind):
+ service, store, adapter, native, ids = _native(monkeypatch, tmp_path, kind)
+ original = native.read_bytes()
+ method = {
+ "oauth": "provision_oauth_credential",
+ "api_key": "provision_credential",
+ "observation": "provision_transient_credential",
+ }[kind]
+ provision = getattr(adapter, method)
+ observed = []
+
+ async def write_then_lose_return(*args, on_reserved):
+ def reserve(ref):
+ on_reserved(ref)
+ entry, = service.revocations.list()
+ assert entry.credential_ref == ref
+ if kind == "observation":
+ assert entry.source_id == "observation"
+ elif kind == "oauth":
+ assert entry.source_id == args[0]
+ else:
+ assert entry.source_id.startswith("src_")
+ assert ":migration:" not in entry.source_id
+ assert service.migration_journal.load() is None
+ observed.append(entry)
+ ref = await provision(*args, on_reserved=reserve)
+ adapter.fail_revoke_refs.add(ref)
+ # The engine wrote the secret, but its caller never received the ref.
+ raise RuntimeError("fixture connection lost before provision returned")
+
+ setattr(adapter, method, write_then_lose_return)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert len(observed) == 1
+ assert service.revocations.list() == observed
+ assert not store.config.sources
+ assert native.read_bytes() == original
+ assert service.migration_journal.load() is None
+ assert not adapter.activated
+ # A fresh service discovers the opaque ref without the lost in-memory list.
+ recovered, _, _ = _service(tmp_path, migration_home=tmp_path / "native")
+ recovered.store, recovered.adapter = store, adapter
+ adapter.fail_revoke_refs.clear()
+ asyncio.run(recovered._ensure_engine_synced())
+ assert recovered.revocations.list() == []
+ assert observed[0].credential_ref in adapter.revoked + adapter.transient_revoked
+ assert native.read_bytes() == original
+
+
[email protected]("kind", ["oauth", "api_key"])
+def test_failed_journal_durability_prevents_secret_provision(monkeypatch, tmp_path, kind):
+ service, store, adapter, native, ids = _native(monkeypatch, tmp_path, kind)
+ original = native.read_bytes()
+
+ def fail_flush():
+ raise OSError("fixture directory fsync failed")
+
+ monkeypatch.setattr(service.revocations, "_sync_directory", fail_flush)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert not adapter.provisioned and not adapter.oauth_provisioned and not adapter.transient_refs
+ assert not store.config.sources
+ assert native.read_bytes() == original
+ assert service.migration_journal.load() is None
+ # A durable row may exist after rename, but no secret has been written.
+ assert "fixture-密钥" not in service.revocations.path.read_text()
+
+
+def test_directory_flush_is_retried_for_an_existing_provisional_owner(monkeypatch, tmp_path):
+ from core.handlers.model_hub.revocations import CredentialRevocationJournal
+
+ journal = CredentialRevocationJournal(tmp_path / "revocations.json")
+ flushed = []
+
+ def fail_once():
+ flushed.append(True)
+ if len(flushed) == 1:
+ raise OSError("fixture directory failure")
+
+ monkeypatch.setattr(journal, "_sync_directory", fail_once)
+ with pytest.raises(OSError):
+ journal.add("src_fixture", "cred_fixture")
+ journal.add("src_fixture", "cred_fixture")
+ assert len(flushed) == 2
+ assert len(journal.list()) == 1
+
+
+def test_exposed_grant_is_owned_by_its_current_source_during_revocation_replay(monkeypatch, tmp_path):
+ service, store, adapter, native, ids = _native(monkeypatch, tmp_path, "oauth")
+
+ async def validation_pending(ref):
+ raise RuntimeError("fixture upstream witness unavailable")
+
+ adapter.validate_oauth_credential = validation_pending
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ record = service.migration_journal.load()
+ assert record["phase"] == "exposed"
+ source, = store.config.sources
+ entry, = service.revocations.list()
+ assert (entry.source_id, entry.credential_ref) == (source.id, source.credential_ref)
+ assert not native.exists()
+ asyncio.run(service._ensure_engine_synced())
+ assert not adapter.revoked
+ assert service.revocations.list() == []
+ assert service.migration_journal.load()["phase"] == "exposed"
+ # The remaining transaction owns forward recovery, never old-native restore.
+ assert json.loads(service.migration_journal.path.read_text())["credentials"][0]["credential_ref"] == source.credential_ref
+
+
[email protected]("kind", ["oauth", "api_key"])
+def test_prepared_save_uncertain_outcome_keeps_its_provisional_grant(
+ monkeypatch, tmp_path, kind,
+):
+ service, store, adapter, native, ids = _native(monkeypatch, tmp_path, kind)
+ before = native.read_bytes()
+ save = service.migration_journal.save
+
+ def committed_then_failed(record):
+ save(record)
+ raise OSError("fixture failure after journal replacement")
+
+ monkeypatch.setattr(service.migration_journal, "save", committed_then_failed)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ pending = service.migration_journal.load()
+ assert pending["phase"] == "prepared"
+ assert not adapter.revoked
+ assert native.read_bytes() == before
+ assert not store.config.sources
+ # The prepared record may be durable even though save raised. Recovery
+ # owns these refs; a local finally must not revoke them from underneath it.
+ refs = {item["credential_ref"] for item in pending["credentials"]}
+ assert refs <= {entry.credential_ref for entry in service.revocations.list()}
+ # Another Hub consumer may reconcile before explicit migration recovery.
+ # It must not treat a prepared transaction's not-yet-bound refs as orphans.
+ asyncio.run(service._ensure_engine_synced())
+ assert not adapter.revoked
+ assert refs <= {entry.credential_ref for entry in service.revocations.list()}
+ recovered, _, _ = _service(tmp_path, migration_home=tmp_path / "native")
+ recovered.store, recovered.adapter = store, adapter
+ asyncio.run(recovered.recover_runtime_intent())
+ assert recovered.migration_journal.load() is None
+ assert not recovered.revocations.list()
+ assert {source.credential_ref for source in store.config.sources} == refs
+ assert not adapter.revoked
+
+
[email protected]("kind", ["oauth", "api_key"])
+def test_real_engine_material_is_recovered_without_a_prepared_takeover_record(
+ monkeypatch, tmp_path, kind,
+):
+ from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+ from vibe.model_hub_runtime.state import EngineStateStore
+
+ service, store, adapter, native, ids = _native(monkeypatch, tmp_path, kind)
+ original = native.read_bytes()
+ state = EngineStateStore(tmp_path / "engine")
+ runtime = CLIProxyEngineAdapter(
+ supervisor=SimpleNamespace(
+ state_store=state, invalidate_configs=lambda: None,
+ client_if_running=lambda: None,
+ ),
+ state_store=state,
+ )
+ for method in ("provision_credential", "provision_transient_credential", "provision_oauth_credential"):
+ setattr(adapter, method, getattr(runtime, method))
+
+ async def unavailable_cleanup(ref):
+ # Simulate process loss: no in-process cleanup can reclaim these bytes.
+ raise RuntimeError("fixture cleanup unavailable until restart")
+
+ adapter.revoke_credential = unavailable_cleanup
+
+ def fail_prepared(record):
+ assert record["phase"] == "prepared"
+ for credential in record["credentials"]:
+ assert (state.root / "credentials" / f'{credential["credential_ref"]}.json').is_file()
+ if kind == "oauth":
+ assert list(state.oauth_staging_dir.glob("*.json"))
+ raise OSError("fixture process loss before prepared journal replacement")
+
+ monkeypatch.setattr(service.migration_journal, "save", fail_prepared)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert native.read_bytes() == original
+ assert not store.config.sources
+ assert service.migration_journal.load() is None
+ assert service.revocations.list()
+ assert list((state.root / "credentials").glob("*.json"))
+ assert not list(state.auth_dir.glob("*.json"))
+ recovered, _, recovered_adapter = _service(tmp_path, migration_home=tmp_path / "native")
+ recovered.store = store
+ recovered_adapter.revoke_credential = runtime.revoke_credential
+ asyncio.run(recovered._ensure_engine_synced())
+ assert not recovered.revocations.list()
+ assert not list((state.root / "credentials").iterdir())
+ if state.oauth_staging_dir.exists():
+ assert not list(state.oauth_staging_dir.iterdir())
+ assert not list(state.auth_dir.glob("*.json"))
+ assert native.read_bytes() == original
diff --git a/tests/test_model_hub_provisional_ownership_engine.py b/tests/test_model_hub_provisional_ownership_engine.py
new file mode 100644
index 000000000..fe19aee6a
--- /dev/null
+++ b/tests/test_model_hub_provisional_ownership_engine.py
@@ -0,0 +1,350 @@
+from __future__ import annotations
+
+import asyncio
+import errno
+import json
+import os
+import stat
+import threading
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import vibe.model_hub_runtime.state as state_module
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore
+
+
+class _ProvisionSupervisor:
+ def __init__(self, state_store: EngineStateStore) -> None:
+ self.state_store = state_store
+
+
+def _oauth_material() -> dict[str, str]:
+ return {
+ "type": "codex",
+ "access_token": "oauth-access-fixture",
+ "refresh_token": "oauth-refresh-fixture",
+ "account_id": "oauth-account-fixture",
+ }
+
+
+def _namespace_paths(
+ store: EngineStateStore,
+ credential_ref: str,
+) -> tuple[Path, Path, Path, Path]:
+ return store._credential_namespace_paths(credential_ref)
+
+
+def _assert_no_secret_bytes(paths: tuple[Path, ...], *secrets: str) -> None:
+ for path in paths:
+ if path.exists():
+ contents = path.read_bytes()
+ for secret in secrets:
+ assert secret.encode() not in contents
+
+
+def test_api_key_callback_is_before_secret_and_releases_oauth_namespace(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ observed: list[tuple[str, tuple[Path, ...]]] = []
+
+ def on_reserved(ref: str) -> None:
+ paths = _namespace_paths(store, ref)
+ observed.append((ref, paths))
+ assert all(path.exists() for path in paths)
+ for path in paths:
+ assert json.loads(path.read_text()) == {
+ "credential_ref": ref,
+ "kind": "reservation",
+ }
+ _assert_no_secret_bytes(paths, "api-secret-fixture")
+
+ ref = store.store_api_key(
+ "api-secret-fixture",
+ vendor="openai",
+ protocol="openai_chat",
+ base_url="https://api.example.test/v1",
+ on_reserved=on_reserved,
+ )
+
+ assert len(observed) == 1
+ assert observed[0][0] == ref
+ assert store.read_api_key(ref) == "api-secret-fixture"
+ credential_path, credential_tmp, stage_path, stage_tmp = _namespace_paths(store, ref)
+ assert credential_path.exists()
+ assert not credential_tmp.exists()
+ assert not stage_path.exists()
+ assert not stage_tmp.exists()
+
+
+def test_oauth_callback_is_before_any_grant_bytes(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ observed: list[tuple[str, tuple[Path, ...]]] = []
+
+ def on_reserved(ref: str) -> None:
+ paths = _namespace_paths(store, ref)
+ observed.append((ref, paths))
+ assert all(path.exists() for path in paths)
+ for path in paths:
+ assert json.loads(path.read_text()) == {
+ "credential_ref": ref,
+ "kind": "reservation",
+ }
+ _assert_no_secret_bytes(
+ paths,
+ "oauth-access-fixture",
+ "oauth-refresh-fixture",
+ )
+
+ ref = store.stage_oauth_credential(
+ "src_fixture123",
+ "openai",
+ "fixture-auth.json",
+ _oauth_material(),
+ on_reserved=on_reserved,
+ )
+
+ assert observed == [(ref, observed[0][1])]
+ metadata = store.credential_metadata(ref)
+ assert metadata["activation_state"] == "staged"
+ stage_path = _namespace_paths(store, ref)[2]
+ assert json.loads(stage_path.read_text())["refresh_token"] == "oauth-refresh-fixture"
+ assert not list(store.auth_dir.glob("*.json"))
+
+
[email protected]("kind", ["api", "oauth"])
+def test_callback_failure_leaves_no_provisional_material(
+ tmp_path: Path,
+ kind: str,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+
+ def fail(_ref: str) -> None:
+ raise RuntimeError("fixture reservation callback failed")
+
+ if kind == "api":
+ with pytest.raises(RuntimeError, match="callback failed"):
+ store.store_api_key("api-secret-fixture", on_reserved=fail)
+ else:
+ with pytest.raises(EngineStateError, match="unable to stage OAuth credential"):
+ store.stage_oauth_credential(
+ "src_fixture123",
+ "openai",
+ "fixture-auth.json",
+ _oauth_material(),
+ on_reserved=fail,
+ )
+
+ assert not list((store.root / "credentials").glob("*"))
+ assert not list(store.oauth_staging_dir.glob("*"))
+
+
+def test_api_key_ref_collision_in_orphaned_oauth_namespace_is_before_callback(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fixed_token = "a" * 32
+ monkeypatch.setattr(state_module.secrets, "token_hex", lambda _length: fixed_token)
+ store = EngineStateStore(tmp_path / "engine")
+ ref = f"cred_{fixed_token}"
+ stage_path = _namespace_paths(store, ref)[2]
+ stage_path.parent.mkdir(parents=True, exist_ok=True)
+ old_stage = b'{"refresh_token":"old-stage-fixture"}\n'
+ stage_path.write_bytes(old_stage)
+ stage_path.chmod(0o600)
+ callback_called = False
+
+ def on_reserved(_ref: str) -> None:
+ nonlocal callback_called
+ callback_called = True
+
+ with pytest.raises(EngineStateError, match="reference collision"):
+ store.store_api_key("new-api-secret-fixture", on_reserved=on_reserved)
+
+ assert not callback_called
+ assert stage_path.read_bytes() == old_stage
+ credential_path, credential_tmp, _, stage_tmp = _namespace_paths(store, ref)
+ assert not credential_path.exists()
+ assert not credential_tmp.exists()
+ assert not stage_tmp.exists()
+
+
+def test_revoke_missing_metadata_removes_exact_secret_temps_only(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ ref = "cred_" + "b" * 32
+ paths = _namespace_paths(store, ref)
+ for path in paths:
+ store._reserve_path(path, ref)
+ paths[1].write_bytes(b'{"value":"orphan-api-secret-fixture"}\n')
+ paths[1].chmod(0o600)
+ paths[3].write_bytes(b'{"refresh_token":"orphan-oauth-secret-fixture"}\n')
+ paths[3].chmod(0o600)
+ unrelated = paths[0].with_name("cred_other.json")
+ unrelated.write_bytes(b'{"value":"unrelated-fixture"}\n')
+ unrelated.chmod(0o600)
+
+ store.revoke_credential(ref)
+
+ assert all(not path.exists() for path in paths)
+ assert unrelated.exists()
+
+
+def test_replace_failure_leaves_deterministic_temp_for_exact_recovery(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ ref = "cred_" + "e" * 32
+ credential_path, credential_tmp, stage_path, stage_tmp = _namespace_paths(store, ref)
+ for path in (credential_path, credential_tmp, stage_path, stage_tmp):
+ store._reserve_path(path, ref)
+
+ def fail_replace(_source: str | bytes | os.PathLike[str], _target: str | bytes | os.PathLike[str]) -> None:
+ raise OSError(errno.EIO, "fixture rename failure")
+
+ monkeypatch.setattr(state_module.os, "replace", fail_replace)
+ with pytest.raises(OSError, match="fixture rename failure"):
+ store._write_reserved_json(
+ credential_path,
+ {"kind": "api_key", "value": "rename-window-secret-fixture"},
+ temporary_path=credential_tmp,
+ credential_ref=ref,
+ )
+
+ assert credential_tmp.exists()
+ assert b"rename-window-secret-fixture" in credential_tmp.read_bytes()
+ store.revoke_credential(ref)
+ assert all(not path.exists() for path in (credential_path, credential_tmp, stage_path, stage_tmp))
+
+
+async def test_orphan_cleanup_does_not_touch_watched_files(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ ref = "cred_" + "c" * 32
+ paths = _namespace_paths(store, ref)
+ for path in paths:
+ store._reserve_path(path, ref)
+ paths[1].write_bytes(b'{"value":"orphan-secret-fixture"}\n')
+ paths[1].chmod(0o600)
+ store.audit_auth_permissions()
+ watched = store.auth_dir / "unrelated-auth.json"
+ watched.write_text('{"type":"codex","refresh_token":"keep-fixture"}\n')
+ watched.chmod(0o600)
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_ProvisionSupervisor(store), # type: ignore[arg-type]
+ state_store=store,
+ )
+
+ assert await adapter.cleanup_orphaned_oauth_material(ref) is True
+ assert watched.exists()
+ assert all(not path.exists() for path in paths)
+
+
+async def test_transient_provision_forwards_write_ahead_callback(
+ tmp_path: Path,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_ProvisionSupervisor(store), # type: ignore[arg-type]
+ state_store=store,
+ )
+ observed: list[str] = []
+
+ def on_reserved(ref: str) -> None:
+ observed.append(ref)
+ _assert_no_secret_bytes(
+ _namespace_paths(store, ref),
+ "transient-secret-fixture",
+ )
+
+ ref = await adapter.provision_transient_credential(
+ "openai",
+ "transient-secret-fixture",
+ None,
+ on_reserved=on_reserved,
+ )
+
+ assert observed == [ref]
+ assert store.read_api_key(ref) == "transient-secret-fixture"
+
+
+async def test_owned_provision_worker_joins_after_cancellation(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ adapter = CLIProxyEngineAdapter(
+ supervisor=_ProvisionSupervisor(store), # type: ignore[arg-type]
+ state_store=store,
+ )
+ original_store_api_key = store.store_api_key
+ started = threading.Event()
+ release = threading.Event()
+ callback_refs: list[str] = []
+
+ def delayed_store_api_key(*args: Any, **kwargs: Any) -> str:
+ started.set()
+ assert release.wait(2)
+ return original_store_api_key(*args, **kwargs)
+
+ monkeypatch.setattr(store, "store_api_key", delayed_store_api_key)
+ task = asyncio.create_task(
+ adapter.provision_credential(
+ "openai",
+ "openai_chat",
+ "owned-secret-fixture",
+ None,
+ on_reserved=callback_refs.append,
+ )
+ )
+ assert await asyncio.to_thread(started.wait, 2)
+ task.cancel()
+ release.set()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert len(callback_refs) == 1
+ assert store.read_api_key(callback_refs[0]) == "owned-secret-fixture"
+
+
+async def test_cleanup_retries_directory_fsync_after_unlink_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ store = EngineStateStore(tmp_path / "engine")
+ ref = "cred_" + "d" * 32
+ paths = _namespace_paths(store, ref)
+ for path in paths:
+ store._reserve_path(path, ref)
+ original_fsync = state_module.os.fsync
+ failed = False
+
+ def fail_once(descriptor: int) -> None:
+ nonlocal failed
+ if not failed and stat.S_ISDIR(os.fstat(descriptor).st_mode):
+ failed = True
+ raise OSError(errno.EIO, "fixture directory flush failure")
+ original_fsync(descriptor)
+
+ monkeypatch.setattr(state_module.os, "fsync", fail_once)
+ with pytest.raises(EngineStateError, match="unable to remove engine state file"):
+ store.revoke_credential(ref)
+ assert failed
+ assert not paths[2].exists()
+
+ monkeypatch.setattr(state_module.os, "fsync", original_fsync)
+ store.revoke_credential(ref)
+ assert all(not path.exists() for path in paths)
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index b7f66447b..a97d3fa3f 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -1934,14 +1934,13 @@ def test_source_admission_uses_explicit_owners_and_keeps_verified_paths_proven()
assert "_require_proven_source_payload" in calls(
service_functions["create_source"]
)
- assert "_require_proven_source_payload" in calls(
- migration_functions["apply_native_migration"]
- )
+ assert "_prepare_takeover" in calls(migration_functions["apply_native_migration"])
+ assert "_require_proven_source_payload" in calls(migration_functions["_prepare_takeover"])
oauth_calls = calls(service_functions["_create_oauth_source"])
assert "_observe_provisioned_credential" in oauth_calls
assert "_mark_source_unverified" in oauth_calls
assert "_mark_source_unverified" in calls(service_functions["create_source"])
- assert "_mark_source_unverified" in calls(migration_functions["apply_native_migration"])
+ assert "_mark_source_unverified" in calls(migration_functions["_prepare_takeover"])
def test_manual_model_delete_ignores_preexisting_unrelated_gap(tmp_path):
diff --git a/tests/test_model_hub_runtime_default_upgrade.py b/tests/test_model_hub_runtime_default_upgrade.py
new file mode 100644
index 000000000..00d7b8149
--- /dev/null
+++ b/tests/test_model_hub_runtime_default_upgrade.py
@@ -0,0 +1,352 @@
+"""One-time gateway runtime default upgrade, without native custody changes."""
+
+from __future__ import annotations
+
+import asyncio
+import copy
+import json
+import stat
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from config import v2_config
+from config.v2_config import MODEL_HUB_BACKENDS, ModelHubConfig, V2Config, update_config_fields
+
+
+def legacy_payload(tmp_path, *, enabled=False):
+ fixture_path = tmp_path / "fixture-default.json"
+ V2Config.default().save(config_path=fixture_path)
+ payload = read_config(fixture_path)
+ payload["model_hub"].pop("runtime_default_applied")
+ payload["model_hub"]["enabled"] = enabled
+ for backend in MODEL_HUB_BACKENDS:
+ payload["model_hub"]["agents"][backend]["mode"] = "direct"
+ # Synthetic state proves the upgrade does not clear credentials or change
+ # launch auth mode. No native credential stores are ever opened.
+ payload["agents"]["claude"].update(auth_mode="api_key", api_key="fixture-key", base_url="https://relay.invalid")
+ payload["agents"]["codex"].update(auth_mode="oauth", api_key=None)
+ payload["runtime"]["default_cwd"] = "/fixture/旧工作区"
+ payload["unrelated_sentinel"] = {"keep": "配置"}
+ return payload
+
+
+def write_config(tmp_path, payload):
+ path = tmp_path / "升级目录" / "config.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ return path, path.read_bytes()
+
+
+def read_config(path):
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def assert_no_native_change(original, upgraded):
+ assert upgraded["agents"] == original["agents"]
+ assert upgraded["model_hub"]["agents"] == original["model_hub"]["agents"]
+ assert upgraded["model_hub"]["sources"] == original["model_hub"]["sources"]
+ assert {key: value for key, value in upgraded.items() if key != "model_hub"} == {
+ key: value for key, value in original.items() if key != "model_hub"
+ }
+
+
+def test_fresh_install_stamps_default_and_keeps_hub_backend_modes(tmp_path):
+ config = V2Config.default()
+ assert config.model_hub.enabled is True
+ assert config.model_hub.runtime_default_applied is True
+ assert all(agent.mode == "hub" for agent in config.model_hub.agents.values())
+ path = tmp_path / "config.json"
+ config.save(config_path=path)
+ original = path.read_bytes()
+ loaded = V2Config.load(config_path=path)
+ assert loaded.model_hub.to_payload() == config.model_hub.to_payload()
+ assert path.read_bytes() == original
+ assert not list(tmp_path.glob("config.json.bak-*"))
+
+
[email protected]("enabled", [False, True])
[email protected]("marker", ["absent", False])
+def test_old_install_promotes_once_and_backs_up_exact_snapshot(tmp_path, enabled, marker):
+ original = legacy_payload(tmp_path, enabled=enabled)
+ if marker is False:
+ original["model_hub"]["runtime_default_applied"] = False
+ path, raw = write_config(tmp_path, original)
+
+ loaded = V2Config.load(config_path=path)
+
+ assert loaded.load_warnings == ()
+ assert loaded.model_hub.enabled is True
+ assert loaded.model_hub.runtime_default_applied is True
+ upgraded = read_config(path)
+ assert upgraded["model_hub"]["enabled"] is True
+ assert upgraded["model_hub"]["runtime_default_applied"] is True
+ assert_no_native_change(original, upgraded)
+ [backup] = path.parent.glob("config.json.bak-model-hub-migration-*")
+ assert backup.read_bytes() == raw
+ assert stat.S_IMODE(backup.stat().st_mode) == 0o600
+
+ persisted = path.read_bytes()
+ assert V2Config.load(config_path=path).model_hub.to_payload() == loaded.model_hub.to_payload()
+ assert path.read_bytes() == persisted
+ assert len(list(path.parent.glob("config.json.bak-*"))) == 1
+
+
[email protected]("already_applied", [False, True])
+def test_default_upgrade_composes_with_existing_shape_migration(tmp_path, already_applied):
+ payload = legacy_payload(tmp_path)
+ if already_applied:
+ payload["model_hub"]["runtime_default_applied"] = True
+ payload["model_hub"]["priority_order"] = []
+ path, original = write_config(tmp_path, payload)
+
+ loaded = V2Config.load(config_path=path)
+
+ assert loaded.load_warnings == ()
+ assert loaded.model_hub.enabled is (not already_applied)
+ assert loaded.model_hub.runtime_default_applied is True
+ assert "priority_order" not in read_config(path)["model_hub"]
+ assert read_config(path)["agents"] == payload["agents"]
+ [backup] = path.parent.glob("config.json.bak-model-hub-migration-*")
+ assert backup.read_bytes() == original
+
+
[email protected]("shape", ["missing", "null", "empty", "missing-backend"])
+def test_legacy_omissions_never_consent_to_native_takeover(tmp_path, shape):
+ original = legacy_payload(tmp_path)
+ if shape == "missing":
+ original.pop("model_hub")
+ elif shape == "null":
+ original["model_hub"] = None
+ elif shape == "empty":
+ original["model_hub"] = {}
+ else:
+ original["model_hub"]["agents"].pop("codex")
+ original["model_hub"]["agents"]["claude"]["mode"] = "hub"
+ path, _ = write_config(tmp_path, original)
+
+ loaded = V2Config.load(config_path=path)
+
+ assert loaded.load_warnings == ()
+ assert loaded.model_hub.enabled is True
+ assert loaded.model_hub.runtime_default_applied is True
+ expected = {"claude": "hub", "codex": "direct", "opencode": "direct"} if shape == "missing-backend" else {
+ name: "direct" for name in MODEL_HUB_BACKENDS
+ }
+ assert {name: agent.mode for name, agent in loaded.model_hub.agents.items()} == expected
+ assert read_config(path)["agents"] == original["agents"]
+
+
+def test_runtime_stop_after_upgrade_survives_subsequent_loads(tmp_path):
+ path, _ = write_config(tmp_path, legacy_payload(tmp_path))
+ V2Config.load(config_path=path)
+ # This is the real narrow config transaction used by the Model Hub store.
+ stopped = update_config_fields(
+ lambda cfg: setattr(cfg.model_hub, "enabled", False),
+ config_path=path,
+ )
+ assert stopped.model_hub.runtime_default_applied is True
+ persisted = path.read_bytes()
+ for _ in range(3):
+ loaded = V2Config.load(config_path=path)
+ assert loaded.model_hub.enabled is False
+ assert loaded.model_hub.runtime_default_applied is True
+ assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert path.read_bytes() == persisted
+ assert len(list(path.parent.glob("config.json.bak-*"))) == 1
+
+
+def test_service_runtime_stop_round_trips_real_store_with_fake_runtime(tmp_path, monkeypatch):
+ from core.handlers.model_hub.adapter import EngineHealth, EngineStatus
+ from core.handlers.model_hub.events import BoundedEventLog
+ from core.handlers.model_hub.service import ModelHubService, V2ModelHubConfigStore
+
+ payload = legacy_payload(tmp_path)
+ path, _ = write_config(tmp_path, payload)
+ monkeypatch.setattr(v2_config.paths, "get_config_path", lambda: path)
+ stop = AsyncMock(return_value=EngineStatus(
+ health=EngineHealth.NOT_STARTED,
+ installed_version=None,
+ verified=False,
+ listen_host="127.0.0.1",
+ listen_port=None,
+ last_check_iso=None,
+ ))
+ service = ModelHubService(
+ store=V2ModelHubConfigStore(),
+ adapter=SimpleNamespace(stop_runtime=stop),
+ events=BoundedEventLog(tmp_path / "events.json"),
+ )
+
+ runtime = asyncio.run(service.runtime_stop())
+
+ stop.assert_awaited_once()
+ assert runtime["enabled"] is False
+ assert runtime["status"]["health"] == "not_started"
+ persisted = path.read_bytes()
+ for _ in range(3):
+ loaded = V2Config.load(config_path=path)
+ assert loaded.load_warnings == ()
+ assert loaded.model_hub.enabled is False
+ assert loaded.model_hub.runtime_default_applied is True
+ assert path.read_bytes() == persisted
+ assert read_config(path)["agents"] == payload["agents"]
+ assert read_config(path)["model_hub"]["agents"] == payload["model_hub"]["agents"]
+
+
+def test_new_explicit_stop_is_not_reinterpreted_as_old_default(tmp_path):
+ config = V2Config.default()
+ config.model_hub.enabled = False
+ path = tmp_path / "config.json"
+ config.save(config_path=path)
+ raw = path.read_bytes()
+ assert V2Config.load(config_path=path).model_hub.enabled is False
+ assert path.read_bytes() == raw
+ assert not list(tmp_path.glob("config.json.bak-*"))
+
+
+def test_write_parser_does_not_perform_the_disk_upgrade():
+ parsed = ModelHubConfig.from_payload({"enabled": False})
+ assert parsed.enabled is False
+ assert parsed.runtime_default_applied is True
+ assert parsed.to_payload()["runtime_default_applied"] is True
+
+
[email protected]("marker", [None, 0, 1, "true", [], {}])
+def test_invalid_marker_is_strict_and_disk_recovery_does_not_activate(tmp_path, marker):
+ payload = legacy_payload(tmp_path)
+ payload["model_hub"]["runtime_default_applied"] = marker
+ with pytest.raises(ValueError, match="runtime_default_applied"):
+ ModelHubConfig.from_payload(payload["model_hub"])
+ path, original = write_config(tmp_path, payload)
+
+ loaded = V2Config.load(config_path=path)
+
+ assert loaded.model_hub.enabled is False
+ assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert "model_hub" in loaded.recovered_sections
+ assert loaded.load_warnings
+ assert path.read_bytes() == original
+ [backup] = path.parent.glob("config.json.bak-recovery-*")
+ assert backup.read_bytes() == original
+
+
[email protected]("bad_hub", [
+ "not-an-object",
+ {"enabled": "false"},
+ {"enabled": False, "sources": "invalid"},
+ {"enabled": False, "agents": {"claude": {"mode": "hub"}}},
+])
+def test_malformed_optional_section_is_not_upgraded_or_rewritten(tmp_path, bad_hub):
+ payload = legacy_payload(tmp_path)
+ payload["model_hub"] = bad_hub
+ path, original = write_config(tmp_path, payload)
+ loaded = V2Config.load(config_path=path)
+ assert loaded.model_hub.enabled is False
+ assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert loaded.load_warnings and not loaded.whole_config_recovery
+ assert path.read_bytes() == original
+
+
[email protected]("raw", [b'{"mode":', b"\xff\xfe", b"[]"])
+def test_whole_config_recovery_does_not_apply_fresh_install_defaults(tmp_path, raw):
+ path = tmp_path / "config.json"
+ path.write_bytes(raw)
+ loaded = V2Config.load(config_path=path)
+ assert loaded.whole_config_recovery
+ assert loaded.model_hub.enabled is False
+ assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert loaded.load_warnings
+ assert path.read_bytes() == raw
+
+
[email protected]("shape", ["false", "true", "missing-enabled", "missing-hub"])
+def test_unrelated_recovery_defers_old_default_upgrade(tmp_path, shape):
+ payload = legacy_payload(tmp_path)
+ if shape == "true":
+ payload["model_hub"]["enabled"] = True
+ elif shape == "missing-enabled":
+ payload["model_hub"].pop("enabled")
+ elif shape == "missing-hub":
+ payload.pop("model_hub")
+ payload["runtime"] = "invalid"
+ path, original = write_config(tmp_path, payload)
+ loaded = V2Config.load(config_path=path)
+ assert loaded.model_hub.enabled is (shape == "true")
+ assert loaded.load_warnings
+ assert path.read_bytes() == original
+
+
+def test_read_only_preview_does_not_persist_or_create_upgrade_backup(tmp_path):
+ path, original = write_config(tmp_path, legacy_payload(tmp_path))
+ loaded = V2Config.load(config_path=path, persist_migrations=False)
+ assert loaded.model_hub.enabled is True
+ assert loaded.model_hub.runtime_default_applied is True
+ assert path.read_bytes() == original
+ assert not list(path.parent.glob("config.json.bak-*"))
+
+
+def test_both_fields_are_written_in_one_compare_and_swap(tmp_path, monkeypatch):
+ path, original = write_config(tmp_path, legacy_payload(tmp_path))
+ write = v2_config._write_config_payload_if_unchanged
+ calls = []
+
+ def capture(target, upgraded, expected_raw):
+ assert target.read_bytes() == original
+ assert upgraded["model_hub"]["enabled"] is True
+ assert upgraded["model_hub"]["runtime_default_applied"] is True
+ calls.append(copy.deepcopy(upgraded))
+ return write(target, upgraded, expected_raw)
+
+ monkeypatch.setattr(v2_config, "_write_config_payload_if_unchanged", capture)
+ V2Config.load(config_path=path)
+ assert len(calls) == 1
+ assert read_config(path) == calls[0]
+
+
[email protected]("failure", ["backup", "replace"])
[email protected]("shape", ["false", "missing-enabled", "missing-hub"])
+def test_failed_persistence_does_not_activate_or_stamp_the_upgrade(tmp_path, monkeypatch, failure, shape):
+ payload = legacy_payload(tmp_path)
+ if shape == "missing-enabled":
+ payload["model_hub"].pop("enabled")
+ elif shape == "missing-hub":
+ payload.pop("model_hub")
+ path, original = write_config(tmp_path, payload)
+ if failure == "backup":
+ monkeypatch.setattr(v2_config, "_backup_config_file", lambda *a, **kw: None)
+ else:
+ monkeypatch.setattr(v2_config, "_persist_migrated_config_payload", Mock(side_effect=OSError("fixture refusal")))
+ loaded = V2Config.load(config_path=path)
+ assert loaded.model_hub.enabled is False
+ assert loaded.model_hub.runtime_default_applied is False
+ assert loaded.load_warnings
+ assert path.read_bytes() == original
+
+
+def test_concurrent_new_stop_wins_over_upgrade_snapshot(tmp_path, monkeypatch):
+ payload = legacy_payload(tmp_path)
+ path, _ = write_config(tmp_path, payload)
+ winner = copy.deepcopy(payload)
+ winner["model_hub"].update(enabled=False, runtime_default_applied=True)
+ winner["show_duration"] = True
+ persist = v2_config._persist_migrated_config_payload
+ called = False
+
+ def concurrent_save(target, expected_raw, upgraded):
+ nonlocal called
+ assert not called
+ called = True
+ target.write_text(json.dumps(winner), encoding="utf-8")
+ return persist(target, expected_raw, upgraded)
+
+ monkeypatch.setattr(v2_config, "_persist_migrated_config_payload", concurrent_save)
+ loaded = V2Config.load(config_path=path)
+ assert loaded.model_hub.enabled is False
+ assert loaded.model_hub.runtime_default_applied is True
+ assert loaded.show_duration is True
+ assert loaded.load_warnings and "file changed" in " ".join(loaded.load_warnings)
+ assert read_config(path) == winner
+ assert not list(path.parent.glob("config.json.bak-*"))
diff --git a/tests/test_model_hub_scenario_adapter.py b/tests/test_model_hub_scenario_adapter.py
new file mode 100644
index 000000000..b83066570
--- /dev/null
+++ b/tests/test_model_hub_scenario_adapter.py
@@ -0,0 +1,77 @@
+"""Write-ahead credential contract for the shared Model Hub scenario fake."""
+
+from __future__ import annotations
+
+import asyncio
+from functools import partial
+
+import pytest
+
+from tests.scenario_harness.model_hub import ModelHubScenarioAdapter
+
+
[email protected](params=["permanent", "transient"])
+def provisioning(request):
+ adapter = ModelHubScenarioAdapter()
+ kwargs = {
+ "vendor": "custom",
+ "secret": "scenario-only-secret",
+ "base_url": "https://upstream.example/v1",
+ }
+ if request.param == "permanent":
+ kwargs["protocol"] = "openai_chat"
+ provision = partial(adapter.provision_credential, **kwargs)
+ ledger = adapter.provisioned
+ else:
+ provision = partial(adapter.provision_transient_credential, **kwargs)
+ ledger = adapter.provisioned_transient
+ return adapter, provision, ledger
+
+
+async def test_reservation_callback_precedes_material_and_receives_returned_ref(provisioning):
+ adapter, provision, ledger = provisioning
+ existing_ref = await provision()
+ before = (list(adapter.provisioned), list(adapter.provisioned_transient))
+ reservations = []
+
+ def on_reserved(credential_ref: str) -> None:
+ assert (adapter.provisioned, adapter.provisioned_transient) == before
+ assert credential_ref != existing_ref
+ reservations.append(credential_ref)
+
+ returned_ref = await provision(on_reserved=on_reserved)
+
+ assert reservations == [returned_ref]
+ assert ledger == [existing_ref, returned_ref]
+
+
[email protected]("error_type", [RuntimeError, asyncio.CancelledError])
+async def test_reservation_callback_failure_preserves_provisioned_material(provisioning, error_type):
+ adapter, provision, _ledger = provisioning
+ await provision()
+ before = (list(adapter.provisioned), list(adapter.provisioned_transient))
+ reservations = []
+ failure = error_type("reservation was not made durable")
+
+ def on_reserved(credential_ref: str) -> None:
+ assert (adapter.provisioned, adapter.provisioned_transient) == before
+ reservations.append(credential_ref)
+ raise failure
+
+ with pytest.raises(error_type) as caught:
+ await provision(on_reserved=on_reserved)
+
+ assert caught.value is failure
+ assert len(reservations) == 1
+ assert (adapter.provisioned, adapter.provisioned_transient) == before
+
+
[email protected]("options", [{}, {"on_reserved": None}], ids=["omitted", "explicit-none"])
+async def test_provisioning_without_reservation_callback_remains_supported(provisioning, options):
+ _adapter, provision, ledger = provisioning
+
+ first = await provision(**options)
+ second = await provision(**options)
+
+ assert first != second
+ assert ledger == [first, second]
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index ed94cf9c4..ab57e237f 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -1207,7 +1207,6 @@ def test_reasoning_tier_resolver_call_inventory_requires_batch_indexes() -> None
("service.py", "create_source"): True,
("service.py", "_apply_reasoning_tier_ladder"): False,
("migration.py", "_validated_source"): True,
- ("migration.py", "apply_native_migration"): True,
}
calls_by_owner: dict[tuple[str, str | None], list[ast.Call]] = {}
for path in (SERVICE, MIGRATION):
diff --git a/tests/test_model_hub_takeover_integration.py b/tests/test_model_hub_takeover_integration.py
new file mode 100644
index 000000000..fc3b3b0c2
--- /dev/null
+++ b/tests/test_model_hub_takeover_integration.py
@@ -0,0 +1,191 @@
+"""Controller/adapter/store/HTTP boundary tests, with synthetic credentials only."""
+
+from __future__ import annotations
+
+import json
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+
+import pytest
+from aiohttp import web
+
+from config.atomic_io import write_atomic
+from core.handlers.model_hub.adapter import EngineEnsureResult
+from core.handlers.model_hub.service import ModelHubError
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home,
+ _service,
+ _write_claude_oauth,
+ _write_codex_oauth,
+)
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+from vibe.model_hub_runtime.client import EngineClient, EngineConnection
+from vibe.model_hub_runtime.state import EngineStateStore
+
+
+class FixtureSupervisor:
+ """Replace OS process management only; keep the real engine HTTP client."""
+
+ def __init__(self, state, origin):
+ self.state_store = state
+ self.connection = EngineConnection(origin, "fixture-management", "fixture-gateway")
+
+ def client_if_running(self):
+ return EngineClient(self.connection)
+
+ def client(self):
+ return self.client_if_running()
+
+ def ensure_running(self):
+ return self.connection
+
+ def restart_if_running(self):
+ pass
+
+ def status(self):
+ return {"status": {
+ "health": "ok", "installed_version": "fixture", "verified": True,
+ "listening": {"host": "127.0.0.1", "port": int(self.connection.base_url.rsplit(":", 1)[1])},
+ "last_check": None,
+ }}
+
+
+def real_adapter(state, origin):
+ adapter = CLIProxyEngineAdapter(
+ supervisor=FixtureSupervisor(state, origin), state_store=state,
+ )
+
+ async def installed(**kwargs):
+ # Installation is outside this test: never download or spawn CPA.
+ return EngineEnsureResult(await adapter.status(), False)
+
+ adapter.ensure_installed = installed
+ adapter.recover_installation = adapter.status
+ return adapter
+
+
+@asynccontextmanager
+async def management_fixture(state, service, native_path, backend):
+ fixture = SimpleNamespace(
+ calls=[], probes=[], violations=[], fail_validation=True, rotated=False,
+ )
+
+ def inventory():
+ rows = []
+ for path in state.auth_dir.glob("*.json"):
+ payload = json.loads(path.read_text())
+ if native_path.exists():
+ fixture.violations.append("native credential still exists at publication")
+ if service.store.load().agents[backend].mode != "hub":
+ fixture.violations.append("mode not committed before publication")
+ pending = service.migration_journal.load()
+ if pending is not None and pending["phase"] != "exposed":
+ fixture.violations.append("ownership intent not durable before publication")
+ if not payload.get("prefix"):
+ fixture.violations.append("watched publication missing Source prefix")
+ if not fixture.rotated:
+ payload["refresh_token"] = "fixture-current-R1"
+ payload["access_token"] = "fixture-current-A1"
+ write_atomic(path, json.dumps(payload))
+ fixture.rotated = True
+ rows.append({
+ "name": path.name, "id": path.name, "provider": payload["type"],
+ "auth_index": path.name, "prefix": payload.get("prefix", ""),
+ "status": "active",
+ "id_token": {"chatgpt_account_id": payload.get("account_id")},
+ })
+ return rows
+
+ async def handle(request):
+ fixture.calls.append((request.method, request.path))
+ if request.headers.get("X-Management-Key") != "fixture-management":
+ return web.json_response({}, status=401)
+ if request.method == "GET" and request.path == "/v0/management/auth-files":
+ return web.json_response({"files": inventory()})
+ if request.method == "POST" and request.path == "/v0/management/api-call":
+ payload = await request.json()
+ fixture.probes.append(payload)
+ assert payload["header"]["Authorization"] == "Bearer $TOKEN$"
+ assert payload["method"] == "GET"
+ assert payload["url"] == (
+ "https://chatgpt.com/backend-api/wham/usage"
+ if backend == "codex"
+ else "https://api.anthropic.com/api/oauth/profile"
+ )
+ assert "data" not in payload
+ serialized = json.dumps(payload)
+ for secret in (
+ "claude-oauth-token",
+ "claude-refresh-token",
+ "codex-access-123456",
+ "codex-refresh-123456",
+ ):
+ assert secret not in serialized
+ status = 503 if fixture.fail_validation else 200
+ body = {"error": {"type": "unavailable"}} if status == 503 else (
+ {"plan_type": "future-plan", "rate_limit": {"allowed": False}}
+ if backend == "codex"
+ else {"account": {"uuid": "fixture-account-uuid"}}
+ )
+ return web.json_response({"status_code": status, "body": json.dumps(body)})
+ fixture.violations.append("unexpected management mutation or model request")
+ return web.json_response({}, status=500)
+
+ app = web.Application()
+ app.router.add_route("*", "/{path:.*}", handle)
+ runner = web.AppRunner(app)
+ await runner.setup()
+ site = web.TCPSite(runner, "127.0.0.1", 0)
+ await site.start()
+ fixture.origin = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}"
+ try:
+ yield fixture
+ finally:
+ await runner.cleanup()
+
+
[email protected]("backend", ["codex", "claude"])
+async def test_real_store_http_takeover_recovers_rotated_grant(monkeypatch, tmp_path, backend):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ if backend == "codex":
+ _write_codex_oauth(home)
+ native_path = home / ".codex/auth.json"
+ else:
+ _write_claude_oauth(home)
+ native_path = home / ".claude/.credentials.json"
+ service, config_store, _ = _service(tmp_path, migration_home=home)
+ config_store.config.agents[backend].mode = "direct"
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ state = EngineStateStore(tmp_path / "engine")
+
+ 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)
+ assert failure.value.code == "migration_recovery_pending"
+ assert service.migration_journal.load()["phase"] == "exposed"
+ assert not native_path.exists()
+ [live_path] = state.auth_dir.glob("*.json")
+ assert json.loads(live_path.read_text())["refresh_token"] == "fixture-current-R1"
+
+ # Reopen both persistence layers, discarding process-local adapter state.
+ restarted, _, _ = _service(tmp_path, migration_home=home)
+ restarted.store = config_store
+ reopened = EngineStateStore(tmp_path / "engine")
+ restarted.adapter = real_adapter(reopened, fixture.origin)
+ fixture.fail_validation = False
+ result = await restarted.migration_apply(ids)
+
+ assert result["applied"] == 1
+ assert not restarted.migration_blocked_backends
+ assert restarted.migration_journal.load() is None
+ assert not native_path.exists()
+ current = json.loads(live_path.read_text())
+ assert current["refresh_token"] == "fixture-current-R1"
+ assert current["prefix"] == reopened.list_sources()[0].prefix
+ assert not list(reopened.oauth_staging_dir.glob("*.json"))
+ assert len(fixture.probes) == 2
+ assert fixture.violations == []
+ assert ("POST", "/v0/management/auth-files") not in fixture.calls
diff --git a/tests/test_model_hub_takeover_inventory.py b/tests/test_model_hub_takeover_inventory.py
new file mode 100644
index 000000000..f5f0eb12f
--- /dev/null
+++ b/tests/test_model_hub_takeover_inventory.py
@@ -0,0 +1,559 @@
+"""Takeover discovers and cleans all supported precedence layers as one unit."""
+
+import asyncio
+import hashlib
+import json
+from contextlib import asynccontextmanager
+
+import pytest
+
+from config import paths
+from config.v2_config import V2Config
+from core.handlers.model_hub.migration import MigrationConflictError
+from core.handlers.model_hub.service import ModelHubError, V2ModelHubConfigStore
+from vibe.native_oauth_store import NativeOAuthSnapshot
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home,
+ _service,
+ _write,
+ _write_claude_oauth,
+)
+
+
+def test_global_and_project_keys_are_all_imported_and_unrelated_data_survives(monkeypatch, tmp_path):
+ home, project = tmp_path / "native", tmp_path / "project"
+ _isolate_native_home(monkeypatch, home)
+ global_path = home / ".config/opencode/opencode.jsonc"
+ project_path = project / ".opencode/opencode.json"
+ for path, key in ((global_path, "fixture-global-key"), (project_path, "fixture-project-key")):
+ _write(path, json.dumps({
+ "provider": {"openai": {"options": {"apiKey": key}, "name": "保留"}},
+ "mcp": {"notes": {"command": ["fixture"]}},
+ }))
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ service.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 len(adapter.provisioned) == 2
+ assert store.config.agents["opencode"].mode == "hub"
+ for path in (global_path, project_path):
+ remaining = json.loads(path.read_text())
+ assert remaining["provider"]["openai"] == {"name": "保留"}
+ assert remaining["mcp"]["notes"]["command"] == ["fixture"]
+
+
+def test_shadowed_opencode_auth_key_is_not_silently_deleted(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write(home / ".config/opencode/opencode.json", json.dumps({
+ "provider": {"openai": {"options": {"apiKey": "fixture-config-key"}}},
+ }))
+ auth_path = home / ".local/share/opencode/auth.json"
+ _write(auth_path, json.dumps({"openai": {"type": "api", "key": "fixture-auth-key"}}))
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ ids = [item["id"] for item in service.migration_scan()["items"]]
+ assert len(ids) == 2
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids[:1]))
+ assert adapter.provisioned == []
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 2
+ assert len(adapter.keys) == 2
+ assert json.loads(auth_path.read_text()) == {}
+
+
+def test_keychain_takeover_preserves_mcp_without_offering_it_as_a_new_login(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)
+ monkeypatch.setenv("USER", "fixture-user")
+ keychain = FakeKeychain()
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)
+ locator = ("Claude Code-credentials", "fixture-user")
+ material = {
+ "claudeAiOauth": {
+ "accessToken": "fixture-access", "refreshToken": "fixture-refresh",
+ "expiresAt": 1893456000000,
+ },
+ "mcpOAuth": {"provider": "preserved"},
+ }
+ keychain.items[locator] = (json.dumps(material), "fixture-original")
+ path = home / ".claude/.credentials.json"
+ _write(path, json.dumps(material))
+ service, _, 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 len(adapter.oauth_provisioned) == 1
+ assert 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
+ # 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 service.migration_scan()["items"] == []
+ assert len(keychain.read_calls) == reads_after_takeover
+ # A changed metadata revision is never suppressed by that receipt.
+ keychain.items[locator] = (json.dumps(material), "fixture-new-login")
+ keychain.mdates[locator] += 1
+ assert [row["backend"] for row in service.migration_scan()["items"]] == ["claude"]
+ assert len(keychain.read_calls) == reads_after_takeover
+
+
[email protected]("backend", ["claude", "codex"])
+def test_unchanged_unrelated_keychain_container_completes_without_import(monkeypatch, tmp_path, backend):
+ from tests.test_native_oauth_store import FakeKeychain
+ from vibe import native_oauth_store
+
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ monkeypatch.setenv("USER", "fixture-user")
+ keychain = FakeKeychain()
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)
+ if backend == "claude":
+ locator = ("Claude Code-credentials", "fixture-user")
+ else:
+ _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] = ('{"mcpOAuth":{"unrelated":"保留"}}', "fixture-original")
+ original = dict(keychain.items)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ store.config.agents[backend].mode = "direct"
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ assert len(ids) == 1
+ assert not keychain.read_calls
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1
+ assert store.config.agents[backend].mode == "hub"
+ assert not store.config.sources
+ assert not adapter.provisioned and not adapter.oauth_provisioned
+ assert keychain.items == original
+ assert not keychain.write_calls and not keychain.delete_calls
+ reads = len(keychain.read_calls)
+ assert reads > 0
+ assert service.migration_scan()["items"] == []
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1
+ assert len(keychain.read_calls) == reads
+ keychain.items[locator] = (original[locator][0], "fixture-new-revision")
+ keychain.mdates[locator] += 1
+ assert len(service.migration_scan()["items"]) == 1
+
+
[email protected]("with_api_key", [False, True])
+def test_empty_codex_container_never_authorizes_deleting_dormant_file_grant(
+ monkeypatch, tmp_path, with_api_key,
+):
+ 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)
+ config = 'cli_auth_credentials_store = "keyring"\n'
+ if with_api_key:
+ config += (
+ 'model_provider = "fixture"\n[model_providers.fixture]\n'
+ 'base_url = "https://fixture.example/v1"\n'
+ 'experimental_bearer_token = "fixture-key"\n'
+ )
+ _write(home / ".codex/config.toml", config)
+ account = "cli|" + hashlib.sha256(str((home / ".codex").resolve()).encode()).hexdigest()[:16]
+ locator = ("Codex Auth", account)
+ keychain.items[locator] = ('{"mcpOAuth":{"keep":"保留"}}', "fixture-original")
+ dormant = home / ".codex/auth.json"
+ payload = {"tokens": {"access_token": "fixture-dormant", "refresh_token": "fixture-dormant-refresh"}}
+ if with_api_key:
+ payload["OPENAI_API_KEY"] = "fixture-key"
+ _write(dormant, json.dumps(payload))
+ before = dormant.read_bytes()
+ 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"]]
+ if with_api_key:
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert store.config.agents["codex"].mode == "direct"
+ else:
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1
+ assert store.config.agents["codex"].mode == "hub"
+ assert dormant.read_bytes() == before
+ assert not store.config.sources
+ assert not adapter.provisioned and not adapter.oauth_provisioned
+ assert not keychain.delete_calls and not keychain.write_calls
+ assert service.migration_journal.load() is None
+
+
[email protected]("boundary", ["permission", "install", "start"])
+def test_empty_container_evidence_cannot_hide_denial_or_an_intervening_login(
+ monkeypatch, tmp_path, boundary,
+):
+ from tests.test_native_oauth_store import FakeKeychain
+ from vibe import native_oauth_store
+ from core.handlers.model_hub.adapter import EngineEnsureResult, EngineHealth, EngineStatus
+
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ monkeypatch.setenv("USER", "fixture-user")
+ keychain = FakeKeychain()
+ monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", keychain)
+ locator = ("Claude Code-credentials", "fixture-user")
+ keychain.items[locator] = ('{"mcpOAuth":{"keep":"保留"}}', "fixture-original")
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ store.config.agents["claude"].mode = "direct"
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ assert len(ids) == 1
+ status = EngineStatus(EngineHealth.OK, "fixture", True, "127.0.0.1", 32199, None)
+
+ def login():
+ keychain.items[locator] = (json.dumps({
+ "claudeAiOauth": {"accessToken": "fixture-new", "refreshToken": "fixture-refresh"},
+ "mcpOAuth": {"keep": "保留"},
+ }), "fixture-new-login")
+ keychain.mdates[locator] += 1
+
+ async def install(**kwargs):
+ if boundary == "install":
+ login()
+ return EngineEnsureResult(status, False)
+
+ async def start():
+ if boundary == "start":
+ login()
+ return status
+
+ adapter.ensure_installed = install
+ adapter.start = start
+ keychain.read_denied = boundary == "permission"
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply(ids))
+ assert not store.config.sources
+ assert not adapter.oauth_provisioned and not adapter.provisioned
+ assert not keychain.delete_calls and not keychain.write_calls
+ assert service.migration_journal.completed() is None
+ assert service.migration_journal.load() is None
+ assert store.config.agents["claude"].mode == "direct"
+ assert not service.migration_blocked_backends
+ if boundary != "permission":
+ assert "fixture-new" in keychain.items[locator][0]
+ new_ids = [row["id"] for row in service.migration_scan()["items"]]
+ assert new_ids != ids
+ # 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 len(adapter.oauth_provisioned) == 1
+ assert service.migration_journal.load() is None
+
+
+async def _return_async(value):
+ return value
+
+
+def test_unsupported_provider_blocks_only_its_cli_before_any_cleanup(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ path = home / ".local/share/opencode/auth.json"
+ _write(path, json.dumps({
+ "openai": {"type": "api", "key": "fixture-key"},
+ "github-copilot": {"type": "oauth", "refresh": "fixture-refresh"},
+ }))
+ before = path.read_bytes()
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ rows = service.migration_scan()["items"]
+ assert {row["proposed_action"] for row in rows} == {"import", "reauth"}
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.migration_apply([row["id"] for row in rows if row["proposed_action"] == "import"]))
+ assert path.read_bytes() == before
+ assert adapter.provisioned == []
+
+
+def test_project_key_changed_after_consent_refuses_without_import(monkeypatch, tmp_path):
+ home, project = tmp_path / "native", tmp_path / "project"
+ _isolate_native_home(monkeypatch, home)
+ path = project / ".claude/settings.local.json"
+ _write(path, json.dumps({"env": {"ANTHROPIC_API_KEY": "fixture-first"}}))
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ service.migration_project_roots = lambda: (project,)
+ ids = [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))
+ assert adapter.provisioned == []
+ assert json.loads(path.read_text())["env"]["ANTHROPIC_API_KEY"] == "fixture-second"
+
+
+def test_keychain_container_consent_also_binds_routing_after_drain(monkeypatch, tmp_path):
+ from core.handlers.model_hub import migration
+
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ path = home / ".codex/config.toml"
+ config = '''
+model_provider = "fixture"
+[model_providers.fixture]
+name = "Fixture"
+base_url = "https://first.example/v1"
+wire_api = "responses"
+'''
+ _write(path, config)
+
+ def read(backend, *, home, allow_secret=False):
+ if backend != "codex":
+ return None
+ return NativeOAuthSnapshot(
+ backend="codex", revision="fixture-unchanged-container",
+ payload={"OPENAI_API_KEY": "fixture-key"} if allow_secret else {
+ "store": "keychain", "status": "metadata_only",
+ },
+ exportable=allow_secret,
+ )
+
+ monkeypatch.setattr(migration, "read_native_oauth", read)
+ 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 len(ids) == 1
+
+ @asynccontextmanager
+ async def guard(backends):
+ path.write_text(config.replace("first.example", "other.example"))
+
+ async def verify():
+ pass
+
+ yield verify
+
+ service.migration_guard = guard
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(service.migration_apply(ids))
+ assert failure.value.code == "migration_item_conflict"
+ assert not adapter.provisioned and not adapter.oauth_provisioned
+ assert store.config.agents["codex"].mode == "direct"
+ assert "other.example" in path.read_text()
+ assert service.migration_journal.load() is None
+
+
+def test_existing_hub_key_still_clears_legacy_auth_when_hub_config_is_unchanged(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write(home / ".claude/settings.json", json.dumps({
+ "env": {"ANTHROPIC_API_KEY": "fixture-key"},
+ }))
+ 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))
+ config_path = tmp_path / "avibe-config.json"
+ monkeypatch.setattr(paths, "get_config_path", lambda: config_path)
+ config = V2Config.default()
+ config.model_hub = memory.config
+ config.agents.claude.auth_mode = "api_key"
+ config.agents.claude.api_key = "fixture-key"
+ config.save(config_path=config_path)
+ previous_hub = config.model_hub.to_payload()
+ service.store = V2ModelHubConfigStore()
+
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ assert len(ids) == 1
+ result = asyncio.run(service.migration_apply(ids))
+
+ assert result["applied"] == 1
+ loaded = V2Config.load(config_path=config_path)
+ assert loaded.model_hub.to_payload() == previous_hub
+ assert loaded.agents.claude.api_key is None
+ assert loaded.agents.claude.auth_mode == "oauth"
+ assert len(adapter.provisioned) == 1 # No duplicate credential or Source.
+ assert service.migration_journal.load() is None
+
+
[email protected]("accepted", [False, True])
+def test_reused_hub_key_requires_current_proof_before_native_cleanup(monkeypatch, tmp_path, accepted):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ service, store, adapter = _service(tmp_path, migration_home=home)
+ asyncio.run(service.create_source({
+ "kind": "api_key", "vendor": "anthropic", "key": "fixture-key",
+ "display_name": "Existing source",
+ }))
+ store.config.agents["claude"].mode = "direct"
+ native = home / ".claude/settings.json"
+ _write(native, '{"env":{"ANTHROPIC_API_KEY":"fixture-key"},"mcp":{"keep":true}}')
+ before = native.read_bytes()
+ previous = store.config.to_payload()
+ observed = len(adapter.observed)
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+ if not accepted:
+ adapter.unproven_observation_vendor = "anthropic"
+ with pytest.raises(ModelHubError) as failure:
+ asyncio.run(service.migration_apply(ids))
+ assert failure.value.code == "migration_item_conflict"
+ assert native.read_bytes() == before
+ assert store.config.to_payload() == previous
+ else:
+ assert asyncio.run(service.migration_apply(ids))["applied"] == 1
+ assert store.config.to_payload()["sources"] == previous["sources"]
+ assert json.loads(native.read_text()) == {"env": {}, "mcp": {"keep": True}}
+ assert len(adapter.observed) == observed + 1
+ assert len(adapter.provisioned) == 1
+ assert service.migration_journal.load() is None
+
+
+def test_config_takeover_cas_preserves_a_concurrent_hub_edit(monkeypatch, tmp_path):
+ config_path = tmp_path / "avibe-config.json"
+ monkeypatch.setattr(paths, "get_config_path", lambda: config_path)
+ config = V2Config.default()
+ config.save(config_path=config_path)
+ expected = config.model_hub.to_payload()
+ config.model_hub.agents["codex"].mode = "direct"
+ config.save(config_path=config_path)
+ concurrent = config_path.read_bytes()
+ store = V2ModelHubConfigStore()
+ with pytest.raises(MigrationConflictError):
+ store.save_takeover(config.model_hub, {}, {}, expected_hub=(expected,))
+ assert config_path.read_bytes() == concurrent
+
+
+def test_interrupted_claude_auth_backup_is_imported_and_cannot_restore_old_key(monkeypatch, tmp_path):
+ from vibe.claude_config import (
+ get_claude_oauth_settings_backup_path,
+ read_claude_oauth_settings_backup,
+ write_claude_oauth_settings_backup,
+ )
+
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write_claude_oauth(home)
+ _write(home / ".claude/settings.json", json.dumps({
+ "env": {"ANTHROPIC_API_KEY": "fixture-active-key"},
+ "mcp": {"keep": "保留"},
+ }))
+ write_claude_oauth_settings_backup(
+ {"ANTHROPIC_API_KEY": "fixture-recovery-key"},
+ home=home,
+ )
+ service, _, 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]))
+ assert result["applied"] == 3
+ assert len(adapter.oauth_provisioned) == 1
+ assert {target[2] for target in adapter.keys.values()} == {
+ "fixture-active-key", "fixture-recovery-key",
+ }
+ assert not get_claude_oauth_settings_backup_path(home).exists()
+ assert read_claude_oauth_settings_backup(home) is None
+ assert json.loads((home / ".claude/settings.json").read_text()) == {
+ "env": {}, "mcp": {"keep": "保留"},
+ }
+
+
[email protected]("metadata", [
+ {"client_id": "fixture-custom-client"},
+ {"scopes": ["user:inference"]},
+ {"scope": "user:profile user:inference"},
+ {"scopes": None},
+])
+def test_explicit_incompatible_native_grant_is_blocked_before_custody(monkeypatch, tmp_path, metadata):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write_claude_oauth(home)
+ path = home / ".claude/.credentials.json"
+ payload = json.loads(path.read_text())
+ payload["claudeAiOauth"].update(metadata)
+ path.write_text(json.dumps(payload))
+ original = path.read_bytes()
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ rows = 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"]]))
+ assert path.read_bytes() == original
+ assert not adapter.oauth_provisioned
+
+
+def test_ordinary_native_grant_with_extra_scopes_remains_importable(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write_claude_oauth(home)
+ path = home / ".claude/.credentials.json"
+ payload = json.loads(path.read_text())
+ payload["claudeAiOauth"].update({
+ "clientId": "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
+ "scopes": [
+ "user:profile", "user:inference", "user:sessions:claude_code",
+ "user:mcp_servers", "user:file_upload", "user:plugins",
+ ],
+ })
+ path.write_text(json.dumps(payload))
+ service, _, _ = _service(tmp_path, migration_home=home)
+ assert service.migration_scan()["items"][0]["proposed_action"] == "import"
+
+
+def test_codex_embedded_bearer_key_is_migrated_without_deleting_provider_preferences(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ path = home / ".codex/config.toml"
+ _write(path, '''
+model_provider = "fixture"
+[model_providers.fixture]
+name = "Private relay"
+base_url = "https://relay.example/v1"
+wire_api = "responses"
+experimental_bearer_token = "fixture-bearer-key"
+request_max_retries = 3
+''')
+ service, _, 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 len(adapter.provisioned) == 1
+ content = path.read_text()
+ assert "fixture-bearer-key" not in content
+ assert "base_url" not in content
+ assert 'name = "Private relay"' in content
+ assert "request_max_retries = 3" in content
+
+
+def test_duplicate_apply_joins_owned_operation_and_shutdown_waits(monkeypatch, tmp_path):
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ _write(home / ".claude/settings.json", json.dumps({"env": {"ANTHROPIC_API_KEY": "fixture-key"}}))
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ ids = [row["id"] for row in service.migration_scan()["items"]]
+
+ async def exercise():
+ entered, release = asyncio.Event(), asyncio.Event()
+ original_sync = adapter.sync_sources
+ stopped = []
+
+ async def paused_sync(bindings):
+ entered.set()
+ await release.wait()
+ await original_sync(bindings)
+
+ async def stop():
+ assert release.is_set()
+ stopped.append(True)
+
+ adapter.sync_sources, adapter.stop = paused_sync, stop
+ first = asyncio.create_task(service.migration_apply(ids))
+ await entered.wait()
+ second = asyncio.create_task(service.migration_apply(ids))
+ shutdown = asyncio.create_task(service.stop())
+ await asyncio.sleep(0)
+ assert not second.done() and not shutdown.done()
+ release.set()
+ assert (await first)["applied"] == (await second)["applied"] == 1
+ await shutdown
+ assert stopped == [True]
+
+ asyncio.run(exercise())
+ assert len(adapter.provisioned) == 1
diff --git a/tests/test_native_login_single_flight.py b/tests/test_native_login_single_flight.py
index 30755cdee..f64253570 100644
--- a/tests/test_native_login_single_flight.py
+++ b/tests/test_native_login_single_flight.py
@@ -15,9 +15,42 @@ from core.agent_auth_service import (
WebAuthFlow,
)
from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter
+from config.v2_config import V2Config
from modules.im import MessageContext
+class _SyntheticProcess:
+ """A hermetic subprocess double with the lifecycle used by cleanup."""
+
+ def __init__(self, *, returncode: int | None = 0) -> None:
+ self.stdout = None
+ self.returncode = returncode
+
+ def terminate(self) -> None:
+ self.returncode = 0
+
+ def kill(self) -> None:
+ self.returncode = -9
+
+ async def wait(self) -> int | None:
+ return self.returncode
+
+
+def _synthetic_claude_client() -> SimpleNamespace:
+ return SimpleNamespace(disconnect=AsyncMock())
+
+
[email protected](autouse=True)
+def _direct_native_auth_config(monkeypatch, tmp_path) -> None:
+ """Give native-login tests explicit Direct custody in isolated state."""
+ home = tmp_path / "avibe-home"
+ monkeypatch.setenv("AVIBE_HOME", str(home))
+ config = V2Config.default()
+ for agent in config.model_hub.agents.values():
+ agent.mode = "direct"
+ config.save(config_path=home / "config" / "config.json")
+
+
class _IMClient:
def __init__(self) -> None:
self.sent: list[str] = []
@@ -53,12 +86,12 @@ async def test_every_web_backend_publishes_deadline_after_startup_with_waiter(
async def start_codex(**_kwargs):
nonlocal startup_finished
startup_finished = datetime.now(timezone.utc)
- return SimpleNamespace(stdout=None, returncode=None)
+ return _SyntheticProcess()
async def start_claude(_context, **_kwargs):
nonlocal startup_finished
startup_finished = datetime.now(timezone.utc)
- return object(), "https://claude.ai/oauth/authorize", None
+ return _synthetic_claude_client(), "https://claude.ai/oauth/authorize", None
async def start_provider_oauth(*_args, **_kwargs):
nonlocal startup_finished
@@ -100,7 +133,7 @@ async def test_every_im_native_backend_publishes_deadline_after_startup_with_wai
"""Drive the backend catalog through the shared IM flow contract."""
service = AgentAuthService(_Controller())
startup_finished: datetime | None = None
- process = SimpleNamespace(stdout=None, returncode=None)
+ process = _SyntheticProcess()
async def start_codex(**_kwargs):
nonlocal startup_finished
@@ -110,7 +143,7 @@ async def test_every_im_native_backend_publishes_deadline_after_startup_with_wai
async def start_claude(_context, **_kwargs):
nonlocal startup_finished
startup_finished = datetime.now(timezone.utc)
- return object(), "https://claude.ai/oauth/authorize", None
+ return _synthetic_claude_client(), "https://claude.ai/oauth/authorize", None
async def start_opencode(_context, **_kwargs):
nonlocal startup_finished
@@ -176,7 +209,8 @@ async def test_single_service_fixture_routes_all_callers_to_the_same_registry()
"""
controller = _Controller()
service = AgentAuthService(controller)
- process = SimpleNamespace(stdout=object(), returncode=0)
+ process = _SyntheticProcess(returncode=0)
+ process.stdout = object()
service._start_codex_process = AsyncMock(return_value=process)
service._read_codex_output = AsyncMock()
service._wait_for_completion = AsyncMock()
@@ -211,11 +245,15 @@ async def test_single_service_fixture_routes_all_callers_to_the_same_registry()
async def test_model_hub_drives_the_shared_web_flow_through_submit_and_cancel() -> None:
"""Model Hub delegates one Web flow lifecycle within a service instance."""
service = AgentAuthService(_Controller())
- client = object()
+ client = _synthetic_claude_client()
service._start_claude_control_flow = AsyncMock(
return_value=(client, "https://claude.ai/oauth/authorize", None)
)
- service._wait_for_claude_completion_web = AsyncMock()
+
+ async def wait_for_cancel(_flow) -> None:
+ await asyncio.Future()
+
+ service._wait_for_claude_completion_web = wait_for_cancel
service._send_claude_callback = AsyncMock()
service._terminate_web_flow = AsyncMock()
adapter = AgentAuthNativeOAuthAdapter(
@@ -235,6 +273,7 @@ async def test_model_hub_drives_the_shared_web_flow_through_submit_and_cancel()
assert service._flows_by_id[state.flow_id] is flow
await adapter.cancel_oauth(state.flow_id)
+ await asyncio.sleep(0)
service._terminate_web_flow.assert_awaited_once_with(
flow, final_state="cancelled"
)
@@ -244,17 +283,19 @@ async def test_model_hub_drives_the_shared_web_flow_through_submit_and_cancel()
@pytest.mark.asyncio
async def test_cancel_keeps_native_claim_until_termination_settles() -> None:
service = AgentAuthService(_Controller())
- process = SimpleNamespace(stdout=None, returncode=None)
+ process = _SyntheticProcess(returncode=None)
service._start_codex_process = AsyncMock(return_value=process)
service._read_codex_output_web = AsyncMock()
service._wait_for_codex_completion_web = AsyncMock()
flow = await service.start_web_setup("codex", force_reset=False)
termination_started = asyncio.Event()
finish_termination = asyncio.Event()
+ real_terminate = service._terminate_web_flow
- async def terminate(_flow, **_kwargs) -> None:
+ async def terminate(flow, **kwargs) -> None:
termination_started.set()
await finish_termination.wait()
+ await real_terminate(flow, **kwargs)
service._terminate_web_flow = terminate
cancel_task = asyncio.create_task(service.cancel_web_flow(flow.flow_id))
@@ -272,18 +313,26 @@ async def test_cancel_keeps_native_claim_until_termination_settles() -> None:
@pytest.mark.asyncio
-async def test_cancel_releases_native_claim_when_termination_raises() -> None:
+async def test_cancel_retains_native_claim_when_termination_raises() -> None:
service = AgentAuthService(_Controller())
- process = SimpleNamespace(stdout=None, returncode=None)
+ process = _SyntheticProcess(returncode=None)
service._start_codex_process = AsyncMock(return_value=process)
service._read_codex_output_web = AsyncMock()
service._wait_for_codex_completion_web = AsyncMock()
flow = await service.start_web_setup("codex", force_reset=False)
+ # Keep the lease owned by this flow while the injected termination error
+ # is reported. A real waiter would otherwise race the failure with its
+ # independent cleanup path.
+ flow.waiter_task = None
service._terminate_web_flow = AsyncMock(side_effect=RuntimeError("terminate failed"))
with pytest.raises(RuntimeError, match="terminate failed"):
await service.cancel_web_flow(flow.flow_id)
- assert flow.flow_id not in service._flows_by_id
- replacement = await service.start_web_setup("codex", force_reset=False)
- assert replacement.flow_id in service._flows_by_id
+ assert flow.flow_id in service._flows_by_id
+ with pytest.raises(BackendLoginInProgressError):
+ await service.start_web_setup("codex", force_reset=False)
+ if flow.native_lease is not None:
+ flow.native_lease.release()
+ flow.native_lease = None
+ service._flow_registry.drop(flow)
diff --git a/tests/test_native_login_structure_guards.py b/tests/test_native_login_structure_guards.py
index 0beddef1a..439b0dec2 100644
--- a/tests/test_native_login_structure_guards.py
+++ b/tests/test_native_login_structure_guards.py
@@ -257,7 +257,11 @@ def test_every_discovered_spawn_site_is_reachable_from_shared_start_path() -> No
for function_name in (reaches_spawn & guarded_region) - {"_start_auth_flow"}:
assert reverse_graph[function_name] <= guarded_region
- start = functions["_start_auth_flow"]
+ # Native ownership moved into the owned task so cancellation can wait for
+ # startup and cleanup without dropping the lease early. Keep the guard
+ # anchored to that real call chain: the claim must still precede every
+ # provider start reached from the shared entry point.
+ start = functions["_start_auth_flow_owned"]
claim_lines = [
call.lineno
for call in ast.walk(start)
@@ -268,7 +272,7 @@ def test_every_discovered_spawn_site_is_reachable_from_shared_start_path() -> No
call.lineno
for call in ast.walk(start)
if isinstance(call, ast.Call)
- and _call_name(call) in reaches_spawn - {"_start_auth_flow"}
+ and _call_name(call) in reaches_spawn - {"_start_auth_flow_owned"}
]
assert guarded_entry_lines
assert claim_lines[0] < min(guarded_entry_lines)
diff --git a/tests/test_native_oauth_store.py b/tests/test_native_oauth_store.py
new file mode 100644
index 000000000..4c9f3a7a9
--- /dev/null
+++ b/tests/test_native_oauth_store.py
@@ -0,0 +1,2001 @@
+from __future__ import annotations
+
+import asyncio
+import ctypes
+import ctypes.util
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+from vibe import native_oauth_store as store
+
+
+class FakeKeychain:
+ def __init__(self) -> None:
+ self.items: dict[tuple[str, str], tuple[str, str]] = {}
+ self.mdates: dict[tuple[str, str], float] = {}
+ self.metadata_denied = False
+ self.read_denied = False
+ self.delete_denied = False
+ self.fail_on_delete_accounts: set[str] = set()
+ self.metadata_calls: list[tuple[str, str]] = []
+ self.read_calls: list[tuple[str, str]] = []
+ self.write_calls: list[tuple[str, str, str]] = []
+ self.delete_calls: list[tuple[str, str]] = []
+
+ def metadata(self, service: str, account: str) -> store._KeychainMetadata:
+ self.metadata_calls.append((service, account))
+ if self.metadata_denied:
+ return store._KeychainMetadata("permission_needed", "denied")
+ item = self.items.get((service, account))
+ if item is None:
+ return store._KeychainMetadata("not_found", "absent")
+ mdate = self.mdates.setdefault((service, account), 1.0)
+ return store._KeychainMetadata(
+ "found",
+ item[1],
+ {"acct": account, "svce": service, "mdat": mdate},
+ f"fake:{service}:{account}",
+ mdate,
+ )
+
+ def read(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: store._KeychainRead | None = None,
+ ) -> store._KeychainRead:
+ self.read_calls.append((service, account))
+ if self.read_denied:
+ raise store._KeychainDenied("denied")
+ item = self.items.get((service, account))
+ if item is None:
+ raise store._KeychainNotFound("missing")
+ mdate = self.mdates.setdefault((service, account), 1.0)
+ if expected is not None and (
+ expected.persistent_reference != f"fake:{service}:{account}"
+ or expected.modification_date != mdate
+ ):
+ raise store._KeychainNotFound("changed")
+ return store._KeychainRead(
+ item[0],
+ item[1],
+ f"fake:{service}:{account}",
+ mdate,
+ )
+
+ def write(
+ self,
+ service: str,
+ account: str,
+ value: str,
+ *,
+ expected: store._KeychainRead | None = None,
+ ) -> None:
+ current = self.items.get((service, account))
+ mdate = self.mdates.setdefault((service, account), 1.0)
+ if expected is not None and (
+ current is None
+ or expected.persistent_reference != f"fake:{service}:{account}"
+ or expected.modification_date != mdate
+ ):
+ raise store._KeychainNotFound("changed")
+ self.write_calls.append((service, account, value))
+ self.items[(service, account)] = (value, f"write-{len(self.write_calls)}")
+ self.mdates[(service, account)] = mdate + 1
+
+ def delete(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: store._KeychainRead,
+ ) -> None:
+ self.delete_calls.append((service, account))
+ if self.delete_denied or account in self.fail_on_delete_accounts:
+ raise store._KeychainDenied("denied")
+ current = self.items.get((service, account))
+ mdate = self.mdates.setdefault((service, account), 1.0)
+ if (
+ current is None
+ or expected.persistent_reference != f"fake:{service}:{account}"
+ or expected.modification_date != mdate
+ ):
+ raise store._KeychainNotFound("changed")
+ self.items.pop((service, account), None)
+ self.mdates.pop((service, account), None)
+
+
+class FakeCoreFoundation:
+ def __init__(self) -> None:
+ self.objects: dict[int, tuple[str, object]] = {}
+ self.buffers: list[object] = []
+ self.next_ref = 1
+
+ def ref(self, kind: str, value: object) -> int:
+ result = self.next_ref
+ self.next_ref += 1
+ self.objects[result] = (kind, value)
+ return result
+
+ @staticmethod
+ def key(ref: int | ctypes.c_void_p) -> int:
+ return int(ref.value) if isinstance(ref, ctypes.c_void_p) else ref
+
+ def get(self, ref: int | ctypes.c_void_p) -> object:
+ return self.objects[self.key(ref)][1]
+
+ def kind(self, ref: int | ctypes.c_void_p) -> str:
+ return self.objects[self.key(ref)][0]
+
+ def CFRelease(self, _ref: int) -> None:
+ return None
+
+ def CFStringCreateWithBytes(
+ self,
+ _allocator,
+ buffer,
+ length,
+ _encoding,
+ _is_external_representation,
+ ) -> int:
+ return self.ref("string", bytes(buffer[:length]).decode("utf-8"))
+
+ def CFStringGetTypeID(self) -> int:
+ return 1
+
+ def CFStringGetLength(self, ref: int) -> int:
+ return len(self.get(ref))
+
+ def CFStringGetMaximumSizeForEncoding(self, length: int, _encoding) -> int:
+ return length * 4
+
+ def CFStringGetCString(self, ref: int, buffer, _size, _encoding) -> bool:
+ buffer.value = self.get(ref).encode("utf-8")
+ return True
+
+ def CFDataGetTypeID(self) -> int:
+ return 2
+
+ def CFDataGetLength(self, ref: int) -> int:
+ return len(self.get(ref))
+
+ def CFDataGetBytePtr(self, ref: int):
+ raw = self.get(ref)
+ buffer = (ctypes.c_ubyte * len(raw)).from_buffer_copy(raw)
+ self.buffers.append(buffer)
+ return buffer
+
+ def CFDataCreate(self, _allocator, buffer, length) -> int:
+ return self.ref("data", bytes(buffer[:length]))
+
+ def CFDateCreate(self, _allocator, value) -> int:
+ return self.ref("date", float(value))
+
+ def CFDateGetTypeID(self) -> int:
+ return 3
+
+ def CFDateGetAbsoluteTime(self, ref: int) -> float:
+ return float(self.get(ref))
+
+ def CFNumberGetTypeID(self) -> int:
+ return 4
+
+ def CFNumberGetValue(self, *_args) -> bool:
+ return False
+
+ def CFBooleanGetTypeID(self) -> int:
+ return 5
+
+ def CFBooleanGetValue(self, ref: int) -> bool:
+ return bool(self.get(ref))
+
+ def CFGetTypeID(self, ref: int) -> int:
+ return {
+ "string": 1,
+ "data": 2,
+ "date": 3,
+ "number": 4,
+ "boolean": 5,
+ "dictionary": 6,
+ "array": 7,
+ }[self.kind(ref)]
+
+ def CFDictionaryCreateMutable(self, _allocator, _capacity, _keys, _values) -> int:
+ return self.ref("dictionary", {})
+
+ def CFDictionarySetValue(self, dictionary: int, key: int, value: int) -> None:
+ self.get(dictionary)[key] = value
+
+ def CFDictionaryGetValue(self, dictionary: int, key: int) -> int | None:
+ return self.get(dictionary).get(key)
+
+ def CFDictionaryGetTypeID(self) -> int:
+ return 6
+
+ def CFArrayCreate(self, _allocator, values, length, _callbacks) -> int:
+ return self.ref("array", [self.key(values[index]) for index in range(length)])
+
+ def CFArrayGetCount(self, array: int) -> int:
+ return len(self.get(array))
+
+ def CFArrayGetValueAtIndex(self, array: int, index: int) -> int:
+ return self.get(array)[index]
+
+
+class FakeSecurityBindings:
+ def __init__(self) -> None:
+ self.cf = FakeCoreFoundation()
+ self.security = self
+ self.key_callbacks = store._CFDictionaryKeyCallbacks()
+ self.value_callbacks = store._CFDictionaryValueCallbacks()
+ self.array_callbacks = store._CFArrayCallbacks()
+ self.constants = {
+ name: self.cf.ref("string", name)
+ for name in (
+ "kCFAllocatorDefault",
+ "kCFBooleanFalse",
+ "kCFBooleanTrue",
+ "kSecAttrAccount",
+ "kSecAttrCreationDate",
+ "kSecAttrModificationDate",
+ "kSecAttrPersistentReference",
+ "kSecAttrService",
+ "kSecClass",
+ "kSecClassGenericPassword",
+ "kSecMatchItemList",
+ "kSecMatchLimit",
+ "kSecMatchLimitOne",
+ "kSecReturnAttributes",
+ "kSecReturnData",
+ "kSecReturnPersistentRef",
+ "kSecUseAuthenticationUI",
+ "kSecUseAuthenticationUIAllow",
+ "kSecUseAuthenticationUIFail",
+ "kSecValuePersistentRef",
+ "kSecValueData",
+ )
+ }
+ self.cf.objects[self.constants["kCFBooleanFalse"]] = ("boolean", False)
+ self.cf.objects[self.constants["kCFBooleanTrue"]] = ("boolean", True)
+ self.items: dict[tuple[str, str], dict[int, int]] = {}
+ self.queries: list[int] = []
+ self.interaction_allowed = True
+ self.interaction_calls: list[bool] = []
+ self.native_call_lock_states: list[bool] = []
+
+ def _record_native_call(self) -> None:
+ is_owned = getattr(store._KEYCHAIN_INTERACTION_LOCK, "_is_owned", None)
+ self.native_call_lock_states.append(bool(is_owned and is_owned()))
+
+ def constant(self, name: str) -> int:
+ return self.constants[name]
+
+ def add_item(self, service: str, account: str, value: str, mdat: float) -> None:
+ attrs = {
+ self.constant("kSecAttrService"): self.cf.ref("string", service),
+ self.constant("kSecAttrAccount"): self.cf.ref("string", account),
+ self.constant("kSecAttrCreationDate"): self.cf.ref("date", mdat - 1),
+ self.constant("kSecAttrModificationDate"): self.cf.ref("date", mdat),
+ self.constant("kSecValuePersistentRef"): self.cf.ref(
+ "data",
+ f"persistent:{service}:{account}".encode(),
+ ),
+ self.constant("kSecValueData"): self.cf.ref("data", value.encode()),
+ }
+ self.items[(service, account)] = attrs
+
+ def _locator(self, query: int) -> tuple[str, str]:
+ values = self.cf.get(query)
+ service = self.cf.get(values[self.constant("kSecAttrService")])
+ account = self.cf.get(values[self.constant("kSecAttrAccount")])
+ item = self.items.get((service, account))
+ item_list = values.get(self.constant("kSecMatchItemList"))
+ if item_list is not None:
+ references = self.cf.get(item_list)
+ item_persistent = (
+ item.get(self.constant("kSecValuePersistentRef")) if item else None
+ )
+ if (
+ item is None
+ or not references
+ or item_persistent is None
+ or self.cf.get(item_persistent) != self.cf.get(references[0])
+ ):
+ return service, f"{account}:stale"
+ expected_date = values.get(self.constant("kSecAttrModificationDate"))
+ if expected_date is not None and (
+ item is None
+ or self.cf.get(item[self.constant("kSecAttrModificationDate")])
+ != self.cf.get(expected_date)
+ ):
+ return service, f"{account}:stale"
+ return service, account
+
+ def SecItemCopyMatching(self, query: int, output) -> int:
+ self._record_native_call()
+ self.queries.append(query)
+ item = self.items.get(self._locator(query))
+ if item is None:
+ return -25300
+ query_values = self.cf.get(query)
+ result_values = {
+ key: value
+ for key, value in item.items()
+ if key != self.constant("kSecValueData")
+ }
+ return_data = query_values.get(self.constant("kSecReturnData"))
+ if return_data is not None and self.cf.get(return_data):
+ result_values[self.constant("kSecValueData")] = item[
+ self.constant("kSecValueData")
+ ]
+ result = self.cf.ref("dictionary", result_values)
+ output._obj.value = result
+ return 0
+
+ def SecItemUpdate(self, query: int, attributes: int) -> int:
+ self._record_native_call()
+ item = self.items.get(self._locator(query))
+ if item is None:
+ return -25300
+ item[self.constant("kSecValueData")] = self.cf.get(attributes)[
+ self.constant("kSecValueData")
+ ]
+ current = self.cf.get(item[self.constant("kSecAttrModificationDate")])
+ item[self.constant("kSecAttrModificationDate")] = self.cf.ref("date", current + 1)
+ return 0
+
+ def SecItemAdd(self, item: int, _result) -> int:
+ self._record_native_call()
+ values = self.cf.get(item)
+ service = self.cf.get(values[self.constant("kSecAttrService")])
+ account = self.cf.get(values[self.constant("kSecAttrAccount")])
+ if (service, account) in self.items:
+ return -25299
+ now = 20.0 + len(self.items)
+ values = dict(values)
+ values.setdefault(
+ self.constant("kSecAttrCreationDate"),
+ self.cf.ref("date", now),
+ )
+ values.setdefault(
+ self.constant("kSecAttrModificationDate"),
+ self.cf.ref("date", now),
+ )
+ values.setdefault(
+ self.constant("kSecValuePersistentRef"),
+ self.cf.ref("data", f"persistent:{service}:{account}".encode()),
+ )
+ self.items[(service, account)] = values
+ return 0
+
+ def SecItemDelete(self, query: int) -> int:
+ self._record_native_call()
+ locator = self._locator(query)
+ if locator not in self.items:
+ return -25300
+ self.items.pop(locator)
+ return 0
+
+ def SecKeychainGetUserInteractionAllowed(self, output) -> int:
+ self._record_native_call()
+ self.interaction_calls.append(True)
+ output._obj.value = self.interaction_allowed
+ return 0
+
+ def SecKeychainSetUserInteractionAllowed(self, value) -> int:
+ self._record_native_call()
+ self.interaction_calls.append(bool(value))
+ self.interaction_allowed = bool(value)
+ return 0
+
+
+def fake_keychain(monkeypatch: pytest.MonkeyPatch) -> FakeKeychain:
+ fake = FakeKeychain()
+ monkeypatch.setattr(store, "_KEYCHAIN_STORE", fake)
+ return fake
+
+
+def fake_security_bindings(monkeypatch: pytest.MonkeyPatch) -> FakeSecurityBindings:
+ fake = FakeSecurityBindings()
+ monkeypatch.setattr(store, "_security_bindings", lambda: fake)
+ return fake
+
+
+def _codex_payload() -> dict:
+ return {
+ "auth_mode": "chatgpt",
+ "tokens": {
+ "access_token": "access-secret",
+ "refresh_token": "refresh-secret",
+ "id_token": "id-secret",
+ },
+ "last_refresh": "2026-09-20T00:00:00Z",
+ "unrelated": {"keep": "yes"},
+ }
+
+
+def _claude_payload() -> dict:
+ return {
+ "claudeAiOauth": {
+ "accessToken": "access-secret",
+ "refreshToken": "refresh-secret",
+ "expiresAt": 123,
+ "accountUuid": "account-1",
+ },
+ "mcpOAuth": {"provider": "keep-me"},
+ }
+
+
[email protected](autouse=True)
+def no_real_keychain(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(store, "_KEYCHAIN_STORE", store._DEFAULT_KEYCHAIN_STORE)
+ monkeypatch.setattr(
+ store, "_security_bindings", lambda: pytest.fail("real OS credentials are forbidden")
+ )
+
+
[email protected]("root_mode", ["fixture", "default", "config", "secure", "empty_secure"])
+def test_claude_all_paths_share_the_resolved_secure_root(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, root_mode: str,
+) -> None:
+ from vibe.claude_config import get_claude_credentials_paths
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.delenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", raising=False)
+ home = None
+ expected_root = tmp_path / ".claude"
+ if root_mode == "fixture":
+ home = tmp_path
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "ignored-config"))
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", str(tmp_path / "ignored-secure"))
+ elif root_mode in {"config", "secure", "empty_secure"}:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "config"))
+ expected_root = tmp_path / "config"
+ if root_mode == "secure":
+ expected_root = tmp_path / "secure"
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", str(expected_root))
+ elif root_mode == "empty_secure":
+ expected_root = tmp_path / ".claude"
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", "")
+
+ paths = store.native_credentials_paths("claude", home)
+ assert paths == (
+ expected_root / ".credentials.json",
+ expected_root / "credentials.json",
+ )
+ # Keep the shipped legacy-layout contract without borrowing its settings root.
+ assert [path.name for path in paths] == [
+ path.name for path in get_claude_credentials_paths(tmp_path)
+ ]
+
+
[email protected]("filename", [".credentials.json", "credentials.json"])
[email protected]("flat", [False, True])
[email protected]("unrelated", [False, True])
+def test_claude_each_supported_file_is_inventoried_and_reversibly_cleaned(
+ tmp_path: Path, no_real_keychain: None, filename: str, flat: bool, unrelated: bool,
+) -> None:
+ root = tmp_path / ".claude"
+ root.mkdir()
+ payload = _claude_payload()
+ if flat:
+ payload = {"access_token": "fixture-access", "refresh_token": "fixture-refresh",
+ "mcpOAuth": {"保留": "🚀"}}
+ if not unrelated:
+ payload.pop("mcpOAuth")
+ path = root / filename
+ original = json.dumps(payload, ensure_ascii=False) + "\n"
+ path.write_text(original, encoding="utf-8")
+
+ scan = store.read_native_oauth("claude", home=tmp_path)
+ secret = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+ assert scan is not None and secret is not None
+ assert scan.exportable and secret.exportable
+ assert scan.payload == secret.payload == payload
+ assert scan.revision == secret.revision
+ assert scan.keychain_edit is None
+ assert secret.keychain_edit["selection_revision"] == scan.revision
+ assert {op["path"] for op in secret.keychain_edit["operations"]} == {
+ str(root / ".credentials.json"), str(root / "credentials.json"),
+ }
+ store.check_keychain_edit(secret.keychain_edit)
+ store.apply_keychain_edit(secret.keychain_edit)
+ store.apply_keychain_edit(secret.keychain_edit)
+ store.check_keychain_edit(secret.keychain_edit, applied=True)
+ if unrelated:
+ assert json.loads(path.read_text()) == {"mcpOAuth": payload["mcpOAuth"]}
+ else:
+ assert not path.exists()
+ store.apply_keychain_edit(secret.keychain_edit, reverse=True)
+ store.apply_keychain_edit(secret.keychain_edit, reverse=True)
+ assert path.read_text() == original
+ other = root / ("credentials.json" if filename.startswith(".") else ".credentials.json")
+ assert not other.exists()
+
+
[email protected]("with_keychain", [False, True])
[email protected]("evidence", ["identical", "same_grant", "same_account", "conflict", "no_identity"])
+def test_claude_all_stores_precedence_and_conflicts(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+ with_keychain: bool, evidence: str,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ root = tmp_path / ".claude"
+ root.mkdir()
+ primary = _claude_payload()
+ legacy = _claude_payload()
+ if evidence in {"same_grant", "no_identity"}:
+ primary["claudeAiOauth"].pop("accountUuid")
+ legacy["claudeAiOauth"].pop("accountUuid")
+ if evidence != "identical":
+ legacy["claudeAiOauth"]["accessToken"] = "fixture-older-access"
+ if evidence in {"same_account", "no_identity"}:
+ legacy["claudeAiOauth"]["refreshToken"] = "fixture-older-refresh"
+ if evidence == "conflict":
+ legacy["claudeAiOauth"]["accountUuid"] = "other-account"
+ legacy["mcpOAuth"] = {"legacy": "保留🚀"}
+ paths = [root / ".credentials.json", root / "credentials.json"]
+ originals = [json.dumps(payload) + "\n" for payload in (primary, legacy)]
+ for path, raw in zip(paths, originals):
+ path.write_text(raw, encoding="utf-8")
+ keychain_payload = json.loads(json.dumps(primary))
+ keychain_payload["claudeAiOauth"]["accessToken"] = "fixture-keychain-access"
+ locator = ("Claude Code-credentials", "fixture-user")
+ if with_keychain:
+ fake_keychain.items[locator] = (json.dumps(keychain_payload), "fixture-v1")
+
+ scan = store.read_native_oauth("claude", home=tmp_path)
+ assert fake_keychain.read_calls == []
+ secret = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+ assert scan is not None and secret is not None
+ assert scan.revision == secret.revision
+ if evidence in {"conflict", "no_identity"}:
+ assert not scan.exportable and scan.payload["status"] == "conflict"
+ assert not secret.exportable and secret.payload["status"] == "conflict"
+ assert scan.keychain_edit is secret.keychain_edit is None
+ else:
+ assert secret.exportable
+ assert secret.payload == (keychain_payload if with_keychain else primary)
+ if with_keychain:
+ assert not scan.exportable and scan.payload["status"] == "metadata_only"
+ else:
+ assert scan.exportable and scan.payload == primary
+ operations = secret.keychain_edit["operations"]
+ assert [op["kind"] for op in operations] == (
+ (["keychain"] if with_keychain else []) + ["file", "file"]
+ )
+ store.apply_keychain_edit(secret.keychain_edit)
+ assert json.loads(paths[0].read_text()) == {"mcpOAuth": primary["mcpOAuth"]}
+ assert json.loads(paths[1].read_text()) == {"mcpOAuth": legacy["mcpOAuth"]}
+ if with_keychain:
+ assert json.loads(fake_keychain.items[locator][0]) == {"mcpOAuth": primary["mcpOAuth"]}
+ store.apply_keychain_edit(secret.keychain_edit, reverse=True)
+ assert [path.read_text() for path in paths] == originals
+ if with_keychain:
+ assert json.loads(fake_keychain.items[locator][0]) == keychain_payload
+
+
+def test_claude_compares_fallbacks_even_when_keychain_lacks_identity(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ payload = _claude_payload()
+ payload["claudeAiOauth"].pop("accountUuid")
+ fake_keychain.items[("Claude Code-credentials", "fixture-user")] = (
+ json.dumps(payload), "fixture-v1",
+ )
+ root = tmp_path / ".claude"
+ root.mkdir()
+ for name, identity in ((".credentials.json", "account-a"), ("credentials.json", "account-b")):
+ payload["claudeAiOauth"]["accountUuid"] = identity
+ (root / name).write_text(json.dumps(payload), encoding="utf-8")
+ for allow_secret in (False, True):
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=allow_secret)
+ assert snapshot is not None and not snapshot.exportable
+ assert snapshot.payload["status"] == "conflict"
+ assert snapshot.keychain_edit is None
+
+
[email protected]("with_keychain", [False, True])
[email protected]("filename", [".credentials.json", "credentials.json"])
[email protected]("failure", ["invalid", "permission_needed"])
+def test_claude_unreadable_supported_file_blocks_all_cleanup(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+ with_keychain: bool, filename: str, failure: str,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ root = tmp_path / ".claude"
+ root.mkdir()
+ for name in (".credentials.json", "credentials.json"):
+ (root / name).write_text(json.dumps(_claude_payload()), encoding="utf-8")
+ if with_keychain:
+ fake_keychain.items[("Claude Code-credentials", "fixture-user")] = (
+ json.dumps(_claude_payload()), "fixture-v1",
+ )
+ if failure == "invalid":
+ (root / filename).write_text("{invalid", encoding="utf-8")
+ else:
+ read_text = Path.read_text
+
+ def denied(path, *args, **kwargs):
+ if path == root / filename:
+ raise PermissionError("fixture denial")
+ return read_text(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", denied)
+ for allow_secret in (False, True):
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=allow_secret)
+ assert snapshot is not None and not snapshot.exportable
+ assert snapshot.payload["status"] == failure
+ assert snapshot.keychain_edit is None
+ assert fake_keychain.write_calls == fake_keychain.delete_calls == []
+
+
[email protected]("with_keychain", [False, True])
[email protected]("change", ["appear", "disappear", "content", "move", "root"])
+def test_claude_selection_revision_binds_every_file_and_locator(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+ with_keychain: bool, change: str,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ root = tmp_path / ".claude"
+ root.mkdir()
+ primary, legacy = root / ".credentials.json", root / "credentials.json"
+ raw = json.dumps(_claude_payload())
+ primary.write_text(raw, encoding="utf-8")
+ if change in {"disappear", "content"}:
+ legacy.write_text(raw, encoding="utf-8")
+ if with_keychain:
+ fake_keychain.items[("Claude Code-credentials", "fixture-user")] = (raw, "fixture-v1")
+ before = store.read_native_oauth("claude", home=tmp_path)
+ if change == "appear":
+ legacy.write_text(raw, encoding="utf-8")
+ elif change == "disappear":
+ legacy.unlink()
+ elif change == "content":
+ legacy.write_text(raw + "\n", encoding="utf-8")
+ elif change == "move":
+ primary.rename(legacy)
+ home = tmp_path
+ if change == "root":
+ home = tmp_path / "other"
+ (home / ".claude").mkdir(parents=True)
+ (home / ".claude/.credentials.json").write_text(raw, encoding="utf-8")
+ after = store.read_native_oauth("claude", home=home)
+ secret = store.read_native_oauth("claude", home=home, allow_secret=True)
+ assert before is not None and after is not None and secret is not None
+ assert before.revision != after.revision
+ assert after.revision == secret.revision
+ assert secret.keychain_edit["selection_revision"] == after.revision
+
+
[email protected]("initial", ["absent", "unrelated"])
[email protected]("with_keychain", [False, True])
+def test_claude_all_file_states_are_guarded_before_any_cleanup(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+ initial: str, with_keychain: bool,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ root = tmp_path / ".claude"
+ root.mkdir()
+ primary, legacy = root / ".credentials.json", root / "credentials.json"
+ raw = json.dumps(_claude_payload())
+ primary.write_text(raw, encoding="utf-8")
+ if initial == "unrelated":
+ legacy.write_text('{"mcpOAuth":{"keep":"unchanged"}}', encoding="utf-8")
+ locator = ("Claude Code-credentials", "fixture-user")
+ if with_keychain:
+ fake_keychain.items[locator] = (raw, "fixture-v1")
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+ assert snapshot is not None and snapshot.exportable
+ operations = snapshot.keychain_edit["operations"]
+ guards = [op for op in operations if op.get("path") == str(legacy)]
+ assert len(guards) == 1 and guards[0]["before"] == guards[0]["after"]
+ legacy.write_text(raw, encoding="utf-8")
+ with pytest.raises(store.NativeOAuthRevisionError):
+ store.check_keychain_edit(snapshot.keychain_edit)
+ with pytest.raises(store.NativeOAuthRevisionError):
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ assert primary.read_text() == legacy.read_text() == raw
+ assert fake_keychain.write_calls == fake_keychain.delete_calls == []
+
+
+ "identity", ["matching_alias", "conflicting_alias", "organization_only", "internal_conflict"],
+)
+def test_claude_legacy_identity_evidence_is_account_specific(
+ tmp_path: Path, identity: str,
+) -> None:
+ root = tmp_path / ".claude"
+ root.mkdir()
+ primary = _claude_payload()
+ legacy = {
+ "access_token": "fixture-legacy-access",
+ "refresh_token": primary["claudeAiOauth"]["refreshToken"],
+ "account_uuid": "account-1" if identity == "matching_alias" else "account-2",
+ }
+ if identity == "matching_alias":
+ legacy["refresh_token"] = "fixture-older-grant"
+ elif identity == "internal_conflict":
+ primary["account_uuid"] = legacy["account_uuid"]
+ if identity == "organization_only":
+ primary["claudeAiOauth"].pop("accountUuid")
+ legacy.pop("account_uuid")
+ primary["claudeAiOauth"]["organizationUuid"] = "shared-organization"
+ legacy["organizationUuid"] = "shared-organization"
+ legacy["refresh_token"] = "fixture-different-grant"
+ (root / ".credentials.json").write_text(json.dumps(primary), encoding="utf-8")
+ (root / "credentials.json").write_text(json.dumps(legacy), encoding="utf-8")
+ for allow_secret in (False, True):
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=allow_secret)
+ assert snapshot is not None
+ if identity == "matching_alias":
+ assert snapshot.exportable and snapshot.payload == primary
+ else:
+ assert not snapshot.exportable and snapshot.payload["status"] == "conflict"
+ assert snapshot.keychain_edit is None
+
+
+def test_claude_legacy_fallback_preserves_unrelated_primary_and_reads_each_file_once(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ root = tmp_path / ".claude"
+ root.mkdir()
+ primary, legacy = root / ".credentials.json", root / "credentials.json"
+ untouched = '{"mcpOAuth": {"保留": "🚀"}}\n'
+ original = json.dumps(_claude_payload()) + "\n"
+ primary.write_text(untouched, encoding="utf-8")
+ legacy.write_text(original, encoding="utf-8")
+ read_text = Path.read_text
+ reads: list[Path] = []
+
+ def once(path, *args, **kwargs):
+ reads.append(path)
+ assert reads.count(path) == 1
+ return read_text(path, *args, **kwargs)
+
+ with monkeypatch.context() as reading:
+ reading.setattr(Path, "read_text", once)
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+ assert reads == [primary, legacy]
+ assert snapshot is not None and snapshot.payload == _claude_payload()
+ operations = snapshot.keychain_edit["operations"]
+ assert operations[0]["before"] == operations[0]["after"] == {"exists": True, "raw": untouched}
+ assert operations[1]["before"] == {"exists": True, "raw": original}
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ assert primary.read_text() == untouched
+ assert json.loads(legacy.read_text()) == {"mcpOAuth": {"provider": "keep-me"}}
+
+
[email protected]("denied", ["metadata", "read"])
+def test_claude_keychain_denial_never_selects_legacy_fallback(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch, denied: str,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ root = tmp_path / ".claude"
+ root.mkdir()
+ raw = json.dumps(_claude_payload())
+ (root / "credentials.json").write_text(raw, encoding="utf-8")
+ fake_keychain.items[("Claude Code-credentials", "fixture-user")] = (raw, "fixture-v1")
+ setattr(fake_keychain, f"{denied}_denied", True)
+ scan = store.read_native_oauth("claude", home=tmp_path)
+ assert fake_keychain.read_calls == []
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+ assert scan is not None and snapshot is not None
+ assert snapshot.revision == scan.revision
+ assert not snapshot.exportable and snapshot.payload["status"] == "permission_needed"
+ assert snapshot.keychain_edit is None
+
+
[email protected]("with_keychain", [False, True])
+def test_claude_legacy_snapshots_keep_selection_and_coalesced_file_guards(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+ with_keychain: bool,
+) -> None:
+ from core.handlers.model_hub.migration import _native_store_items
+ from core.handlers.model_hub.migration_files import plan_native_cleanup
+ from core.handlers.model_hub.migration_journal import TakeoverStateError
+
+ monkeypatch.setenv("USER", "fixture-user")
+ root = tmp_path / ".claude"
+ root.mkdir()
+ primary, legacy = root / ".credentials.json", root / "credentials.json"
+ raw = json.dumps(_claude_payload())
+ legacy.write_text(raw, encoding="utf-8")
+ if with_keychain:
+ fake_keychain.items[("Claude Code-credentials", "fixture-user")] = (raw, "fixture-v1")
+
+ def items(allow_secret=False):
+ return _native_store_items(
+ "claude", store.read_native_oauth("claude", home=tmp_path, allow_secret=allow_secret),
+ mask_credential=lambda _: "masked-fixture",
+ )
+
+ scanned, expanded = items(), items(True)
+ assert len(scanned) == len(expanded) == 1
+ assert scanned[0].id == expanded[0].id
+ assert expanded[0].proposed_action == "import"
+ assert expanded[0].oauth_material["refresh_token"] == "refresh-secret"
+ edits = plan_native_cleanup(expanded, home=tmp_path, project_roots=())
+ assert {edit.path for edit in edits} == {primary, legacy}
+ [guard] = [edit for edit in edits if edit.path == primary]
+ assert guard.before is guard.after is None
+ for edit in edits:
+ edit.check()
+ edit.apply()
+ edit.check(applied=True)
+ assert not primary.exists()
+ assert json.loads(legacy.read_text()) == {"mcpOAuth": {"provider": "keep-me"}}
+ for edit in edits:
+ edit.apply(reverse=True)
+ assert legacy.read_text() == raw
+ primary.write_text(raw, encoding="utf-8")
+ assert items()[0].id != scanned[0].id
+ with pytest.raises(TakeoverStateError):
+ guard.check()
+
+
[email protected]("filenames", [
+ (".credentials.json",), ("credentials.json",), (".credentials.json", "credentials.json"),
+])
[email protected]("keychain_payload", [{}, {"mcpOAuth": {"保留": "🚀"}}])
+def test_claude_noncredential_keychain_keeps_fallback_selection_and_noop_evidence(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+ filenames: tuple[str, ...], keychain_payload: dict,
+) -> None:
+ from core.handlers.model_hub.migration import _native_store_items
+
+ monkeypatch.setenv("USER", "fixture-user")
+ locator = ("Claude Code-credentials", "fixture-user")
+ keychain_raw = json.dumps(keychain_payload, ensure_ascii=False) + "\n"
+ fake_keychain.items[locator] = (keychain_raw, "fixture-mcp")
+ root = tmp_path / ".claude"
+ root.mkdir()
+ for name in filenames:
+ (root / name).write_text(json.dumps(_claude_payload()), encoding="utf-8")
+
+ scanned = store.read_native_oauth("claude", home=tmp_path)
+ assert scanned is not None and not scanned.exportable
+ assert scanned.payload["status"] == "metadata_only"
+ assert scanned.payload["store"] == "keychain"
+ assert fake_keychain.read_calls == []
+ expanded = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+ assert expanded is not None and expanded.exportable
+ assert expanded.revision == scanned.revision
+ assert expanded.payload == _claude_payload()
+ before_item = _native_store_items("claude", scanned, mask_credential=lambda _: "fixture")[0]
+ after_item = _native_store_items("claude", expanded, mask_credential=lambda _: "fixture")[0]
+ assert before_item.id == after_item.id
+ assert before_item.native_store_revision == after_item.native_store_revision
+ assert before_item.native_store_placeholder and not after_item.native_store_placeholder
+ assert after_item.proposed_action == "import"
+
+ edit = expanded.keychain_edit
+ assert edit is not None and edit["selection_revision"] == scanned.revision
+ [guard] = [op for op in edit["operations"] if op["kind"] == "keychain"]
+ assert guard["before"] == guard["after"] == {
+ "exists": True, "value": keychain_raw, "revision": "fixture-mcp",
+ }
+ assert guard["persistent_reference"] and guard["modification_date"] == 1.0
+ store.check_keychain_edit(edit)
+ store.apply_keychain_edit(edit)
+ store.apply_keychain_edit(edit)
+ store.check_keychain_edit(edit, applied=True)
+ for name in filenames:
+ assert json.loads((root / name).read_text()) == {"mcpOAuth": {"provider": "keep-me"}}
+ store.apply_keychain_edit(edit, reverse=True)
+ store.apply_keychain_edit(edit, reverse=True)
+ store.check_keychain_edit(edit, applied=True, reverse=True)
+ for name in filenames:
+ assert json.loads((root / name).read_text()) == _claude_payload()
+ assert fake_keychain.items[locator] == (keychain_raw, "fixture-mcp")
+ assert fake_keychain.write_calls == fake_keychain.delete_calls == []
+ assert fake_keychain.mdates[locator] == 1.0
+
+
[email protected]("change", ["new_login", "metadata_only"])
+def test_claude_noncredential_keychain_guard_rejects_concurrent_change(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch, change: str,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ locator = ("Claude Code-credentials", "fixture-user")
+ keychain_raw = '{"mcpOAuth":{"preserve":"unchanged"}}'
+ fake_keychain.items[locator] = (keychain_raw, "fixture-mcp")
+ path = tmp_path / ".claude/credentials.json"
+ path.parent.mkdir()
+ raw = json.dumps(_claude_payload())
+ path.write_text(raw, encoding="utf-8")
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+ assert snapshot is not None and snapshot.keychain_edit is not None
+ changed = raw if change == "new_login" else keychain_raw
+ fake_keychain.items[locator] = (changed, "fixture-concurrent")
+ fake_keychain.mdates[locator] += 1
+ for applied in (False, True):
+ keychain_only = {
+ **snapshot.keychain_edit,
+ "operations": [
+ op for op in snapshot.keychain_edit["operations"] if op["kind"] == "keychain"
+ ],
+ }
+ with pytest.raises(store.NativeOAuthRevisionError):
+ store.check_keychain_edit(keychain_only, applied=applied)
+ with pytest.raises(store.NativeOAuthRevisionError):
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ assert path.read_text() == raw
+ assert fake_keychain.items[locator] == (changed, "fixture-concurrent")
+ assert fake_keychain.write_calls == fake_keychain.delete_calls == []
+
+
[email protected]("filenames", [
+ (".credentials.json",), ("credentials.json",), (".credentials.json", "credentials.json"),
+])
+def test_claude_mcp_only_keychain_and_file_oauth_complete_real_consumer_flow(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+ filenames: tuple[str, ...],
+) -> None:
+ from tests.scenarios.model_hub.test_model_hub_migration_scenarios import (
+ _isolate_native_home, _service, _write,
+ )
+
+ home = tmp_path / "native"
+ _isolate_native_home(monkeypatch, home)
+ monkeypatch.setenv("USER", "fixture-user")
+ locator = ("Claude Code-credentials", "fixture-user")
+ keychain_raw = '{"mcpOAuth":{"保留":"🚀"}}\n'
+ fake_keychain.items[locator] = (keychain_raw, "fixture-mcp")
+ raw = json.dumps({"claudeAiOauth": _claude_payload()["claudeAiOauth"]})
+ for name in filenames:
+ _write(home / ".claude" / name, raw)
+ service, _, adapter = _service(tmp_path, migration_home=home)
+ [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 len(adapter.oauth_provisioned) == 1
+ assert service.migration_journal.load() is None
+ for name in filenames:
+ assert not (home / ".claude" / name).exists()
+ assert fake_keychain.items[locator] == (keychain_raw, "fixture-mcp")
+ assert fake_keychain.write_calls == fake_keychain.delete_calls == []
+ reads = list(fake_keychain.read_calls)
+ 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 len(adapter.oauth_provisioned) == 1
+ fake_keychain.items[locator] = (raw, "fixture-new-login")
+ fake_keychain.mdates[locator] += 1
+ assert len(service.migration_scan()["items"]) == 1
+
+
+def test_claude_noncredential_keychain_without_file_oauth_is_not_exportable(
+ tmp_path: Path, fake_keychain: FakeKeychain, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("USER", "fixture-user")
+ fake_keychain.items[("Claude Code-credentials", "fixture-user")] = (
+ '{"mcpOAuth":{"keep":"unchanged"}}', "fixture-mcp",
+ )
+ scanned = store.read_native_oauth("claude", home=tmp_path)
+ assert scanned is not None and scanned.payload["status"] == "metadata_only"
+ assert store.read_native_oauth("claude", home=tmp_path, allow_secret=True) is None
+ assert fake_keychain.write_calls == fake_keychain.delete_calls == []
+
+
+def test_codex_file_scan_is_exportable_and_cleanup_preserves_unrelated_fields(tmp_path: Path) -> None:
+ auth_path = tmp_path / ".codex" / "auth.json"
+ auth_path.parent.mkdir()
+ auth_path.write_text(json.dumps(_codex_payload()), encoding="utf-8")
+
+ scanned = store.read_native_oauth("codex", home=tmp_path)
+
+ assert scanned is not None
+ assert scanned.exportable is True
+ assert scanned.keychain_edit is None
+ assert scanned.payload == _codex_payload()
+
+ secret_snapshot = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+ assert secret_snapshot is not None
+ assert secret_snapshot.keychain_edit is not None
+ store.apply_keychain_edit(secret_snapshot.keychain_edit)
+
+ remaining = json.loads(auth_path.read_text(encoding="utf-8"))
+ assert remaining == {"unrelated": {"keep": "yes"}}
+
+
+def test_codex_default_store_is_file_and_keyring_does_not_fallback_to_stale_file(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ auth_path = tmp_path / ".codex" / "auth.json"
+ auth_path.parent.mkdir()
+ auth_path.write_text(json.dumps(_codex_payload()), encoding="utf-8")
+
+ default_snapshot = store.read_native_oauth("codex", home=tmp_path)
+ assert default_snapshot is not None
+ assert default_snapshot.payload == _codex_payload()
+
+ (auth_path.parent / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ keyring_snapshot = store.read_native_oauth("codex", home=tmp_path)
+ assert keyring_snapshot is None
+ assert fake_keychain.metadata_calls
+
+
[email protected]("mode", ["auto", "keyring"])
+def test_codex_keychain_metadata_scan_never_reads_secret(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+ mode: str,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(_codex_payload()),
+ "native-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ f'cli_auth_credentials_store = "{mode}"\n',
+ encoding="utf-8",
+ )
+
+ metadata_snapshot = store.read_native_oauth("codex", home=tmp_path)
+
+ assert metadata_snapshot is not None
+ assert metadata_snapshot.exportable is False
+ assert metadata_snapshot.payload["status"] == "metadata_only"
+ assert metadata_snapshot.revision == store._keychain_revision(
+ "codex", "Codex Auth", account, "native-v1"
+ )
+ assert fake_keychain.read_calls == []
+
+ secret_snapshot = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+ assert secret_snapshot is not None
+ assert secret_snapshot.exportable is True
+ assert fake_keychain.read_calls == [("Codex Auth", account)]
+ assert secret_snapshot.revision == metadata_snapshot.revision
+
+
+def test_fixture_home_never_selects_real_keychain(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(store, "_KEYCHAIN_STORE", store._DEFAULT_KEYCHAIN_STORE)
+ monkeypatch.setattr(
+ store,
+ "_security_bindings",
+ lambda: pytest.fail("fixture home selected the real Keychain"),
+ )
+
+ assert store.read_native_oauth("codex", home=tmp_path) is None
+
+
[email protected]("platform", ["linux", "win32"])
[email protected]("allow_secret", [False, True])
[email protected]("exists", [False, True])
[email protected]("filename", [".credentials.json", "credentials.json"])
+def test_claude_non_macos_production_selection_uses_file_without_keychain(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ platform: str,
+ allow_secret: bool,
+ exists: bool,
+ filename: str,
+) -> None:
+ secure_root = tmp_path / "isolated-claude"
+ secure_root.mkdir()
+ path = secure_root / filename
+ payload = _claude_payload()
+ if exists:
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(secure_root))
+ monkeypatch.delenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(sys, "platform", platform)
+ monkeypatch.setattr(
+ store,
+ "_keychain_for",
+ lambda *_: pytest.fail("non-macOS Claude must not probe Keychain"),
+ )
+
+ snapshot = store.read_native_oauth("claude", allow_secret=allow_secret)
+
+ if not exists:
+ assert snapshot is None
+ return
+ assert snapshot is not None and snapshot.exportable
+ assert snapshot.payload == payload
+ if allow_secret:
+ assert snapshot.keychain_edit is not None
+ operations = snapshot.keychain_edit["operations"]
+ assert len(operations) == 2
+ [operation] = [op for op in operations if op["path"] == str(path)]
+ assert operation["kind"] == "file"
+ assert operation["path"] == str(path)
+ assert json.loads(operation["after"]["raw"]) == {"mcpOAuth": payload["mcpOAuth"]}
+ else:
+ assert snapshot.keychain_edit is None
+ assert json.loads(path.read_text()) == payload
+
+
+def test_secret_keychain_read_denial_is_permission_placeholder(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(_codex_payload()),
+ "native-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ metadata = store.read_native_oauth("codex", home=tmp_path)
+ fake_keychain.read_denied = True
+
+ secret = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+
+ assert metadata is not None
+ assert secret is not None
+ assert secret.exportable is False
+ assert secret.revision == metadata.revision
+ assert secret.payload["status"] == "permission_needed"
+
+
+def test_secret_read_returns_changed_placeholder_when_scan_revision_is_stale(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(_codex_payload()),
+ "native-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ original_metadata = fake_keychain.metadata
+ metadata_values: list[store._KeychainMetadata] = []
+
+ def metadata_then_change(service: str, item_account: str) -> store._KeychainMetadata:
+ metadata_value = original_metadata(service, item_account)
+ metadata_values.append(metadata_value)
+ fake_keychain.items[(service, item_account)] = (
+ json.dumps(_codex_payload()),
+ "native-v2",
+ )
+ return metadata_value
+
+ monkeypatch.setattr(fake_keychain, "metadata", metadata_then_change)
+
+ secret = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+
+ assert secret is not None
+ assert secret.exportable is False
+ assert secret.revision != store._keychain_revision(
+ "codex",
+ "Codex Auth",
+ account,
+ metadata_values[0].revision,
+ )
+ assert secret.payload["status"] == "changed"
+
+
+def test_denied_keychain_read_returns_permission_placeholder(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ fake_keychain.metadata_denied = True
+
+ snapshot = store.read_native_oauth("codex", home=tmp_path)
+
+ assert snapshot is not None
+ assert snapshot.exportable is False
+ assert snapshot.payload == {
+ "status": "permission_needed",
+ "store": "keychain",
+ "service": "Codex Auth",
+ "account": snapshot.payload["account"],
+ }
+
+
+def test_security_framework_keychain_uses_metadata_without_data_and_tracks_mdat(
+ fake_security_bindings: FakeSecurityBindings,
+) -> None:
+ fake_security_bindings.add_item(
+ "Codex Auth",
+ "account",
+ json.dumps(_codex_payload()),
+ mdat=10.0,
+ )
+ native = store._SecurityKeychainStore()
+
+ metadata = native.metadata("Codex Auth", "account")
+ read = native.read("Codex Auth", "account")
+
+ assert metadata.state == "found"
+ assert metadata.attributes["mdat"] == 10.0
+ assert metadata.persistent_reference is not None
+ assert read.value == json.dumps(_codex_payload())
+ assert read.revision == metadata.revision
+ assert read.persistent_reference == metadata.persistent_reference
+ metadata_query = fake_security_bindings.cf.get(fake_security_bindings.queries[0])
+ read_query = fake_security_bindings.cf.get(fake_security_bindings.queries[1])
+ assert fake_security_bindings.cf.get(
+ metadata_query[fake_security_bindings.constant("kSecReturnAttributes")]
+ )
+ assert fake_security_bindings.constant("kSecReturnData") not in metadata_query
+ assert (
+ fake_security_bindings.cf.get(
+ metadata_query[fake_security_bindings.constant("kSecUseAuthenticationUI")]
+ )
+ == fake_security_bindings.cf.get(
+ fake_security_bindings.constant("kSecUseAuthenticationUIFail")
+ )
+ )
+ assert (
+ fake_security_bindings.cf.get(
+ read_query[fake_security_bindings.constant("kSecUseAuthenticationUI")]
+ )
+ == fake_security_bindings.cf.get(
+ fake_security_bindings.constant("kSecUseAuthenticationUIAllow")
+ )
+ )
+ assert fake_security_bindings.interaction_calls == [True, False, True]
+ assert fake_security_bindings.native_call_lock_states
+ assert all(fake_security_bindings.native_call_lock_states)
+ assert fake_security_bindings.cf.get(
+ read_query[fake_security_bindings.constant("kSecReturnData")]
+ )
+
+ fake_security_bindings.items[("Codex Auth", "account")][
+ fake_security_bindings.constant("kSecAttrModificationDate")
+ ] = fake_security_bindings.cf.ref("date", 11.0)
+ changed = native.metadata("Codex Auth", "account")
+ assert changed.revision != metadata.revision
+
+
+def test_security_framework_update_preserves_unrelated_attributes_and_delete(
+ fake_security_bindings: FakeSecurityBindings,
+) -> None:
+ fake_security_bindings.add_item("Codex Auth", "account", "before", mdat=10.0)
+ unrelated_key = fake_security_bindings.cf.ref("string", "unrelated")
+ unrelated_value = fake_security_bindings.cf.ref("string", "preserve")
+ fake_security_bindings.items[("Codex Auth", "account")][unrelated_key] = unrelated_value
+ native = store._SecurityKeychainStore()
+
+ metadata = native.metadata("Codex Auth", "account")
+ assert metadata.persistent_reference is not None
+ native.write(
+ "Codex Auth",
+ "account",
+ "after",
+ expected=native.read("Codex Auth", "account"),
+ )
+ update_query = fake_security_bindings.cf.get(fake_security_bindings.queries[-1])
+ assert (
+ fake_security_bindings.cf.get(
+ update_query[fake_security_bindings.constant("kSecUseAuthenticationUI")]
+ )
+ == fake_security_bindings.cf.get(
+ fake_security_bindings.constant("kSecUseAuthenticationUIAllow")
+ )
+ )
+
+ item = fake_security_bindings.items[("Codex Auth", "account")]
+ assert fake_security_bindings.cf.get(item[unrelated_key]) == "preserve"
+ assert fake_security_bindings.cf.get(item[fake_security_bindings.constant("kSecValueData")]) == (
+ b"after"
+ )
+ native.delete(
+ "Codex Auth",
+ "account",
+ expected=native.read("Codex Auth", "account"),
+ )
+ delete_query = fake_security_bindings.cf.get(fake_security_bindings.queries[-1])
+ assert (
+ fake_security_bindings.cf.get(
+ delete_query[fake_security_bindings.constant("kSecUseAuthenticationUI")]
+ )
+ == fake_security_bindings.cf.get(
+ fake_security_bindings.constant("kSecUseAuthenticationUIAllow")
+ )
+ )
+ assert all(fake_security_bindings.native_call_lock_states)
+ assert ("Codex Auth", "account") not in fake_security_bindings.items
+
+
+def test_security_framework_reverse_restore_after_delete_is_idempotent(
+ fake_security_bindings: FakeSecurityBindings,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fake_security_bindings.add_item("Codex Auth", "account", "before", mdat=10.0)
+ native = store._SecurityKeychainStore()
+ monkeypatch.setattr(store, "_KEYCHAIN_STORE", native)
+ metadata = native.metadata("Codex Auth", "account")
+ assert metadata.persistent_reference is not None
+ edit = {
+ "version": 1,
+ "operations": [
+ {
+ "kind": "keychain",
+ "service": "Codex Auth",
+ "account": "account",
+ "persistent_reference": metadata.persistent_reference,
+ "modification_date": 10.0,
+ "before": {
+ "exists": True,
+ "value": "before",
+ "revision": metadata.revision,
+ },
+ "after": {"exists": False},
+ }
+ ],
+ }
+
+ store.apply_keychain_edit(edit)
+ assert ("Codex Auth", "account") not in fake_security_bindings.items
+ store.apply_keychain_edit(edit, reverse=True)
+ store.apply_keychain_edit(edit, reverse=True)
+ assert (
+ fake_security_bindings.cf.get(
+ fake_security_bindings.items[("Codex Auth", "account")][
+ fake_security_bindings.constant("kSecValueData")
+ ]
+ )
+ == b"before"
+ )
+
+
+def test_apply_rechecks_each_operation_immediately_before_mutation(
+ fake_keychain: FakeKeychain,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fake_keychain.items[("service", "first")] = ("first", "v1")
+ fake_keychain.items[("service", "second")] = ("second", "v2")
+ edit = {
+ "version": 1,
+ "operations": [
+ {
+ "kind": "keychain",
+ "service": "service",
+ "account": "first",
+ "before": {"exists": True, "value": "first", "revision": "v1"},
+ "after": {"exists": True, "value": "first-new"},
+ },
+ {
+ "kind": "keychain",
+ "service": "service",
+ "account": "second",
+ "before": {"exists": True, "value": "second", "revision": "v2"},
+ "after": {"exists": True, "value": "second-new"},
+ },
+ ],
+ }
+ original_live = store._live_keychain_state
+ calls = 0
+
+ def live_with_concurrent_login(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 3:
+ fake_keychain.items[("service", "second")] = ("new-login", "v2-new")
+ return original_live(*args, **kwargs)
+
+ monkeypatch.setattr(store, "_live_keychain_state", live_with_concurrent_login)
+
+ with pytest.raises(store.NativeOAuthRevisionError):
+ store.apply_keychain_edit(edit)
+
+ assert fake_keychain.items[("service", "first")][0] == "first-new"
+ assert fake_keychain.items[("service", "second")] == ("new-login", "v2-new")
+
+
[email protected](sys.platform != "darwin", reason="CoreFoundation smoke requires macOS")
+def test_production_security_binding_cf_smoke_without_security_item_access() -> None:
+ security_path = ctypes.util.find_library("Security") or (
+ "/System/Library/Frameworks/Security.framework/Security"
+ )
+ foundation_path = ctypes.util.find_library("CoreFoundation") or (
+ "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
+ )
+ security = ctypes.CDLL(security_path)
+ foundation = ctypes.CDLL(foundation_path)
+ bindings = store._SecurityBindings(security, foundation)
+
+ def forbidden_sec_call(*_args):
+ raise AssertionError("CoreFoundation smoke called a Sec* API")
+
+ for name in (
+ "SecItemCopyMatching",
+ "SecItemAdd",
+ "SecItemUpdate",
+ "SecItemDelete",
+ "SecKeychainGetUserInteractionAllowed",
+ "SecKeychainSetUserInteractionAllowed",
+ ):
+ setattr(bindings.security, name, forbidden_sec_call)
+
+ unicode_ref = store._cf_string(bindings, "服务🚀")
+ data_ref = store._cf_data(bindings, "opaque-test-data")
+ key_ref = store._cf_string(bindings, "key")
+ dictionary = store._cf_dictionary(bindings, {key_ref: unicode_ref})
+ query, owned = store._keychain_query(
+ bindings,
+ "服务",
+ "账户",
+ return_attributes=True,
+ return_data=False,
+ )
+ interactive_query, interactive_owned = store._keychain_query(
+ bindings,
+ "服务",
+ "账户",
+ return_attributes=False,
+ return_data=True,
+ allow_interaction=True,
+ )
+ bound_query = None
+ bound_owned: list[int] = []
+ try:
+ found = bindings.cf.CFDictionaryGetValue(dictionary, key_ref)
+ assert store._cf_string_value(bindings, found) == "服务🚀"
+ found_query_service = bindings.cf.CFDictionaryGetValue(
+ query,
+ bindings.constant("kSecAttrService"),
+ )
+ assert store._cf_string_value(bindings, found_query_service) == "服务"
+ assert (
+ bindings.cf.CFDictionaryGetValue(
+ query,
+ bindings.constant("kSecUseAuthenticationUI"),
+ )
+ == bindings.constant("kSecUseAuthenticationUIFail")
+ )
+ assert (
+ bindings.cf.CFDictionaryGetValue(
+ interactive_query,
+ bindings.constant("kSecUseAuthenticationUI"),
+ )
+ == bindings.constant("kSecUseAuthenticationUIAllow")
+ )
+ data_length = bindings.cf.CFDataGetLength(data_ref)
+ data_pointer = bindings.cf.CFDataGetBytePtr(data_ref)
+ assert bytes(data_pointer[:data_length]) == b"opaque-test-data"
+ observed = store._KeychainRead(
+ value="",
+ revision="",
+ persistent_reference=store._persistent_reference_from_cf_data(
+ bindings,
+ data_ref,
+ ),
+ modification_date=123.0,
+ )
+ bound_query, bound_owned = store._keychain_query(
+ bindings,
+ "服务",
+ "账户",
+ return_attributes=False,
+ return_data=False,
+ expected=observed,
+ )
+ match_list = bindings.cf.CFDictionaryGetValue(
+ bound_query,
+ bindings.constant("kSecMatchItemList"),
+ )
+ assert bindings.cf.CFArrayGetCount(match_list) == 1
+ assert bindings.cf.CFDataGetLength(
+ bindings.cf.CFArrayGetValueAtIndex(match_list, 0),
+ ) == len(b"opaque-test-data")
+ assert bindings.cf.CFDictionaryGetValue(
+ bound_query,
+ bindings.constant("kSecAttrModificationDate"),
+ )
+ finally:
+ store._release(
+ bindings,
+ dictionary,
+ query,
+ interactive_query,
+ bound_query,
+ unicode_ref,
+ data_ref,
+ key_ref,
+ *owned,
+ *interactive_owned,
+ *bound_owned,
+ )
+
+
+def test_codex_secrets_backend_is_unsupported_and_does_not_use_stale_file(
+ tmp_path: Path,
+) -> None:
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(json.dumps(_codex_payload()), encoding="utf-8")
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "auto"\nsecret_auth_storage = "managed"\n',
+ encoding="utf-8",
+ )
+
+ snapshot = store.read_native_oauth("codex", home=tmp_path)
+
+ assert snapshot is not None
+ assert snapshot.exportable is False
+ assert snapshot.payload == {"status": "unsupported_store", "store": "secret_auth_storage"}
+
+
+def test_codex_malformed_config_fails_closed_without_stale_file_fallback(tmp_path: Path) -> None:
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(json.dumps(_codex_payload()), encoding="utf-8")
+ (codex_home / "config.toml").write_text("cli_auth_credentials_store = [\n", encoding="utf-8")
+
+ snapshot = store.read_native_oauth("codex", home=tmp_path)
+
+ assert snapshot is not None
+ assert snapshot.exportable is False
+ assert snapshot.payload == {
+ "status": "unsupported_store",
+ "store": "invalid_config",
+ }
+
+
+def test_codex_keychain_api_key_is_exportable_and_removed_without_losing_unrelated_fields(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ api_only = {
+ "OPENAI_API_KEY": "sk-secret",
+ "unrelated": {"keep": "yes"},
+ }
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(api_only),
+ "native-api-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+
+ metadata = store.read_native_oauth("codex", home=tmp_path)
+ secret = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+
+ assert metadata is not None
+ assert metadata.exportable is False
+ assert secret is not None
+ assert secret.exportable is True
+ assert secret.payload == api_only
+ assert secret.revision == metadata.revision
+ assert secret.keychain_edit is not None
+ store.apply_keychain_edit(secret.keychain_edit)
+ assert json.loads(fake_keychain.items[("Codex Auth", account)][0]) == {
+ "unrelated": {"keep": "yes"},
+ }
+
+
+def test_codex_ephemeral_ignores_existing_file(tmp_path: Path) -> None:
+ codex_home = tmp_path / ".codex"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(json.dumps(_codex_payload()), encoding="utf-8")
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "ephemeral"\n',
+ encoding="utf-8",
+ )
+
+ assert store.read_native_oauth("codex", home=tmp_path) is None
+
+
+def test_claude_keychain_and_file_cleanup_preserve_unrelated_fields(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("USER", "test-user")
+ claude_home = tmp_path / ".claude"
+ claude_home.mkdir()
+ credentials_path = claude_home / ".credentials.json"
+ credentials_path.write_text(json.dumps(_claude_payload()), encoding="utf-8")
+ account = "test-user"
+ fake_keychain.items[("Claude Code-credentials", account)] = (
+ json.dumps(_claude_payload()),
+ "claude-v1",
+ )
+
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+
+ assert snapshot is not None
+ assert snapshot.exportable is True
+ assert snapshot.keychain_edit is not None
+ assert len(snapshot.keychain_edit["operations"]) == 3
+ guard = snapshot.keychain_edit["operations"][-1]
+ assert guard["path"] == str(claude_home / "credentials.json")
+ assert guard["before"] == guard["after"] == {"exists": False}
+
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ store.apply_keychain_edit(snapshot.keychain_edit)
+
+ keychain_after = json.loads(fake_keychain.items[("Claude Code-credentials", account)][0])
+ file_after = json.loads(credentials_path.read_text(encoding="utf-8"))
+ assert keychain_after == {"mcpOAuth": {"provider": "keep-me"}}
+ assert file_after == {"mcpOAuth": {"provider": "keep-me"}}
+
+ store.apply_keychain_edit(snapshot.keychain_edit, reverse=True)
+ store.apply_keychain_edit(snapshot.keychain_edit, reverse=True)
+ assert json.loads(fake_keychain.items[("Claude Code-credentials", account)][0]) == _claude_payload()
+ assert json.loads(credentials_path.read_text(encoding="utf-8")) == _claude_payload()
+
+
+def test_claude_locator_uses_secure_root_suffix_and_sanitized_account(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ secure_root = (tmp_path / "secure-root").resolve()
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", str(secure_root))
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setenv("USER", "bad/user")
+
+ resolved_root, service, account = store._claude_locator(None)
+
+ assert resolved_root == secure_root
+ assert service == "Claude Code-credentials"
+ assert account == "claude-code-user"
+
+
+def test_claude_empty_secure_env_keeps_unsuffixed_service(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", "")
+ monkeypatch.setenv("USER", "valid.user-1")
+
+ _, service, account = store._claude_locator(None)
+
+ assert service == "Claude Code-credentials"
+ assert account == "valid.user-1"
+
+
+def test_claude_no_config_env_keeps_unsuffixed_service(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", raising=False)
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+
+ _, service, _ = store._claude_locator(None)
+
+ assert service == "Claude Code-credentials"
+
+
+def test_claude_config_env_adds_suffix_when_secure_env_is_absent(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ config_root = (tmp_path / "config-root").resolve()
+ monkeypatch.delenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", raising=False)
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(config_root))
+
+ resolved_root, service, _ = store._claude_locator(None)
+
+ assert resolved_root == config_root
+ assert service == f"Claude Code-credentials-{store._sha256(str(config_root).encode())[:8]}"
+
+
+def test_claude_nonempty_secure_env_hashes_when_config_env_is_present(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ secure_root = (tmp_path / "secure-root").resolve()
+ config_root = (tmp_path / "config-root").resolve()
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", str(secure_root))
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(config_root))
+
+ resolved_root, service, _ = store._claude_locator(None)
+
+ assert resolved_root == secure_root
+ assert service == f"Claude Code-credentials-{store._sha256(str(secure_root).encode())[:8]}"
+
+
+def test_claude_empty_secure_env_suppresses_suffix_even_when_config_is_present(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ config_root = (tmp_path / "config-root").resolve()
+ monkeypatch.setenv("CLAUDE_SECURESTORAGE_CONFIG_DIR", "")
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(config_root))
+
+ _, service, _ = store._claude_locator(None)
+
+ assert service == "Claude Code-credentials"
+
+
[email protected]("filename", [".credentials.json", "credentials.json"])
+def test_claude_keychain_and_different_fallback_account_are_not_exportable(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+ monkeypatch: pytest.MonkeyPatch,
+ filename: str,
+) -> None:
+ monkeypatch.setenv("USER", "test-user")
+ claude_home = tmp_path / ".claude"
+ claude_home.mkdir()
+ credentials_path = claude_home / filename
+ fallback = _claude_payload()
+ fallback["claudeAiOauth"]["accountUuid"] = "different-account"
+ credentials_path.write_text(json.dumps(fallback), encoding="utf-8")
+ fake_keychain.items[("Claude Code-credentials", "test-user")] = (
+ json.dumps(_claude_payload()),
+ "claude-v1",
+ )
+
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+
+ assert snapshot is not None
+ assert snapshot.exportable is False
+ assert snapshot.keychain_edit is None
+ assert snapshot.payload == {
+ "status": "conflict",
+ "store": "keychain+file",
+ "service": "Claude Code-credentials",
+ "account": "test-user",
+ }
+ assert json.loads(credentials_path.read_text(encoding="utf-8")) == fallback
+
+
[email protected]("filename", [".credentials.json", "credentials.json"])
+def test_claude_keychain_and_fallback_same_refresh_grant_without_identity_are_exportable(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+ monkeypatch: pytest.MonkeyPatch,
+ filename: str,
+) -> None:
+ monkeypatch.setenv("USER", "test-user")
+ claude_home = tmp_path / ".claude"
+ claude_home.mkdir()
+ keychain_payload = _claude_payload()
+ fallback_payload = _claude_payload()
+ keychain_payload["claudeAiOauth"].pop("accountUuid")
+ fallback_payload["claudeAiOauth"].pop("accountUuid")
+ credentials_path = claude_home / filename
+ credentials_path.write_text(json.dumps(fallback_payload), encoding="utf-8")
+ fake_keychain.items[("Claude Code-credentials", "test-user")] = (
+ json.dumps(keychain_payload),
+ "claude-v1",
+ )
+
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+
+ assert snapshot is not None
+ assert snapshot.exportable is True
+ assert snapshot.keychain_edit is not None
+ assert len(snapshot.keychain_edit["operations"]) == 3
+ [guard] = [
+ op for op in snapshot.keychain_edit["operations"]
+ if op["kind"] == "file" and op["path"] != str(credentials_path)
+ ]
+ assert guard["before"] == guard["after"] == {"exists": False}
+
+
+def test_claude_keychain_and_different_refresh_grants_without_identity_conflict(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("USER", "test-user")
+ claude_home = tmp_path / ".claude"
+ claude_home.mkdir()
+ keychain_payload = _claude_payload()
+ fallback_payload = _claude_payload()
+ keychain_payload["claudeAiOauth"].pop("accountUuid")
+ fallback_payload["claudeAiOauth"].pop("accountUuid")
+ fallback_payload["claudeAiOauth"]["refreshToken"] = "different-refresh"
+ credentials_path = claude_home / ".credentials.json"
+ credentials_path.write_text(json.dumps(fallback_payload), encoding="utf-8")
+ fake_keychain.items[("Claude Code-credentials", "test-user")] = (
+ json.dumps(keychain_payload),
+ "claude-v1",
+ )
+
+ snapshot = store.read_native_oauth("claude", home=tmp_path, allow_secret=True)
+
+ assert snapshot is not None
+ assert snapshot.exportable is False
+ assert snapshot.payload["status"] == "conflict"
+
+
+def test_changed_keychain_revision_blocks_cleanup_without_mutation(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(_codex_payload()),
+ "native-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ snapshot = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+ assert snapshot is not None and snapshot.keychain_edit is not None
+
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps({**_codex_payload(), "changed": True}),
+ "native-v2",
+ )
+ with pytest.raises(store.NativeOAuthRevisionError):
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ assert fake_keychain.delete_calls == []
+
+
+def test_check_keychain_edit_exposes_before_and_after_cas_checks(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(_codex_payload()),
+ "native-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ snapshot = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+ assert snapshot is not None and snapshot.keychain_edit is not None
+
+ assert store.check_keychain_edit(snapshot.keychain_edit) is True
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ assert store.check_keychain_edit(snapshot.keychain_edit, reverse=True) is True
+ assert store.check_keychain_edit(snapshot.keychain_edit, applied=True) is True
+ store.apply_keychain_edit(snapshot.keychain_edit, reverse=True)
+ assert store.check_keychain_edit(
+ snapshot.keychain_edit,
+ applied=True,
+ reverse=True,
+ ) is True
+
+
+def test_apply_does_not_rollback_prior_operations_when_a_later_one_fails(
+ fake_keychain: FakeKeychain,
+) -> None:
+ fake_keychain.items[("service", "first")] = ("first", "v1")
+ fake_keychain.items[("service", "second")] = ("second", "v2")
+ fake_keychain.fail_on_delete_accounts.add("second")
+ edit = {
+ "version": 1,
+ "operations": [
+ {
+ "kind": "keychain",
+ "service": "service",
+ "account": "first",
+ "before": {"exists": True, "value": "first", "revision": "v1"},
+ "after": {"exists": False},
+ },
+ {
+ "kind": "keychain",
+ "service": "service",
+ "account": "second",
+ "before": {"exists": True, "value": "second", "revision": "v2"},
+ "after": {"exists": False},
+ },
+ ],
+ }
+
+ with pytest.raises(store.NativeOAuthPermissionError):
+ store.apply_keychain_edit(edit)
+
+ assert ("service", "first") not in fake_keychain.items
+ assert ("service", "second") in fake_keychain.items
+
+
+def test_file_secret_snapshot_uses_the_original_read_for_before_state(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ auth_path = tmp_path / ".codex" / "auth.json"
+ auth_path.parent.mkdir()
+ auth_path.write_text(json.dumps(_codex_payload()), encoding="utf-8")
+ monkeypatch.setattr(
+ store,
+ "_json_file_state",
+ lambda _path: pytest.fail("file snapshot reread"),
+ )
+
+ snapshot = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+
+ assert snapshot is not None and snapshot.keychain_edit is not None
+
+
+def test_denied_keychain_delete_is_sanitized(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ oauth_only = {
+ "tokens": _codex_payload()["tokens"],
+ "last_refresh": "2026-09-20T00:00:00Z",
+ }
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(oauth_only),
+ "native-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ snapshot = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+ assert snapshot is not None and snapshot.keychain_edit is not None
+ fake_keychain.delete_denied = True
+
+ with pytest.raises(store.NativeOAuthPermissionError) as error:
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ assert "access-secret" not in str(error.value)
+ assert "refresh-secret" not in str(error.value)
+
+
+def test_apply_is_idempotent_after_keychain_cleanup(
+ tmp_path: Path,
+ fake_keychain: FakeKeychain,
+) -> None:
+ codex_home = (tmp_path / ".codex").resolve()
+ account = f"cli|{store._sha256(str(codex_home).encode('utf-8'))[:16]}"
+ oauth_only = {
+ "tokens": _codex_payload()["tokens"],
+ "last_refresh": "2026-09-20T00:00:00Z",
+ }
+ fake_keychain.items[("Codex Auth", account)] = (
+ json.dumps(oauth_only),
+ "native-v1",
+ )
+ (codex_home / "config.toml").parent.mkdir()
+ (codex_home / "config.toml").write_text(
+ 'cli_auth_credentials_store = "keyring"\n',
+ encoding="utf-8",
+ )
+ snapshot = store.read_native_oauth("codex", home=tmp_path, allow_secret=True)
+ assert snapshot is not None and snapshot.keychain_edit is not None
+
+ store.apply_keychain_edit(snapshot.keychain_edit)
+ store.apply_keychain_edit(snapshot.keychain_edit)
+
+ assert fake_keychain.delete_calls == [("Codex Auth", account)]
+
+
+def test_keychain_backend_has_no_security_cli_secret_path() -> None:
+ assert not hasattr(store, "_run_security")
+ assert "security" not in store.__dict__
diff --git a/tests/test_native_process_inventory.py b/tests/test_native_process_inventory.py
new file mode 100644
index 000000000..81ae2a8cb
--- /dev/null
+++ b/tests/test_native_process_inventory.py
@@ -0,0 +1,304 @@
+"""Configured script identities must survive interpreter and config wrappers."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import psutil
+import pytest
+
+from config import paths
+from config.v2_compat import to_app_config
+from config.v2_config import V2Config
+from core.agent_auth_service import AgentAuthService
+from core.backend_restart import (
+ NativeMigrationBlockedError,
+ _native_process_backend,
+ native_cli_processes,
+)
+from core.handlers.model_hub.service import ModelHubError, V2ModelHubConfigStore
+from tests.scenarios.model_hub.test_model_hub_migration_scenarios import _isolate_native_home, _service
+from tests.test_native_takeover_lifecycle import controller_fixture
+
+
+def _forbidden(*args, **kwargs):
+ raise AssertionError("real native process or credential access is forbidden")
+
+
[email protected](autouse=True)
+def native_boundary(monkeypatch, tmp_path):
+ _isolate_native_home(monkeypatch, tmp_path / "native")
+ monkeypatch.setattr(subprocess, "run", _forbidden)
+ monkeypatch.setattr(subprocess.Popen, "__init__", _forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_shell", _forbidden)
+ monkeypatch.setattr(psutil, "process_iter", _forbidden)
+ monkeypatch.setattr(psutil.Process, "kill", _forbidden)
+ monkeypatch.setattr(psutil.Process, "terminate", _forbidden)
+ monkeypatch.setattr(paths, "get_config_path", lambda: tmp_path / "config.json")
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("prefix", [
+ ["python"], ["/usr/bin/python3"], ["python3.12"], ["pypy3"],
+ ["python3", "-I", "-u"], ["python3", "-X", "dev"],
+ ["python3", "-W", "ignore", "-Xdev"],
+ ["python3", "--check-hash-based-pycs", "always", "--"],
+ ["/bin/bash"], ["sh"], ["dash"], ["zsh"], ["ksh"],
+ ["bash", "-"], ["zsh", "-"],
+ ["bash", "-eu"], ["bash", "--noprofile", "--norc"],
+ ["bash", "-o", "pipefail", "-O", "extglob"],
+ ["bash", "--rcfile", "/fixture/rc", "--"],
+ ["node"], ["node", "--require", "/fixture/bootstrap.js"],
+ ["node", "--import", "/fixture/bootstrap.mjs", "--"],
+ ["node", "--watch-path", "/fixture/watch"],
+ ["bun", "--preload", "/fixture/bootstrap.js"],
+ ["bun", "run", "--"],
+])
+def test_configured_script_is_the_executed_entrypoint(backend, prefix):
+ script = f"/fixture/custom-{backend}"
+ assert _native_process_backend([*prefix, script, "--prompt", "other"], {backend: script}) == backend
+
+
[email protected]("command", [
+ ["python", "/fixture/other.py", "SCRIPT"],
+ ["python", "-c", "pass", "SCRIPT"],
+ ["python", "-Ic", "pass", "SCRIPT"],
+ ["python", "-m", "unrelated.module", "SCRIPT"],
+ ["python", "-Imunrelated.module", "SCRIPT"],
+ ["python", "-", "SCRIPT"],
+ ["python", "-X", "SCRIPT", "/fixture/other.py"],
+ ["python", "-W", "SCRIPT", "/fixture/other.py"],
+ ["bash", "/fixture/other.sh", "SCRIPT"],
+ ["bash", "-c", "echo ordinary", "SCRIPT"],
+ ["bash", "-lc", "echo ordinary", "SCRIPT"],
+ ["sh", "-s", "SCRIPT"],
+ ["node", "/fixture/other.js", "SCRIPT"],
+ ["node", "-e", "codex", "SCRIPT"],
+ ["node", "--eval=codex", "SCRIPT"],
+ ["node", "-p", "codex", "SCRIPT"],
+ ["node", "--require", "/fixture/bootstrap.js", "/fixture/other.js", "SCRIPT"],
+ ["node", "-", "SCRIPT"],
+ ["/bin/echo", "SCRIPT"],
+])
+def test_prompt_data_and_non_script_modes_are_not_executable_identity(command):
+ script = "/fixture/custom-codex"
+ command = [script if value == "SCRIPT" else value for value in command]
+ assert _native_process_backend(command, {"codex": script}) is None
+
+
[email protected]("interpreter", ["python.exe", "pythonw.exe", "node.exe", "bash.exe"])
+def test_windows_style_interpreter_paths_keep_configured_script(interpreter):
+ script = r"C:\fixture\custom-codex"
+ assert _native_process_backend(
+ [rf"C:\runtime\{interpreter}", script], {"codex": script},
+ ) == "codex"
+
+
+def test_ambiguous_interpreter_options_cannot_certify_native_absence():
+ script = "/fixture/custom-codex"
+ with pytest.raises(NativeMigrationBlockedError, match="process_inventory_unavailable"):
+ _native_process_backend(["python", "--unknown-option", "value", script], {"codex": script})
+ assert _native_process_backend(
+ ["python", "--unknown-option", "value", "/fixture/unrelated.py"], {"codex": script},
+ ) is None
+
+
+def _configured_owner(config):
+ controller, coordinator, admissions, turns = controller_fixture()
+ controller.config = config
+ controller.agent_auth_service = AgentAuthService(controller)
+ return controller, coordinator, admissions, turns
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("shape", ["raw", "enabled-compat", "disabled-compat"])
+def test_inventory_uses_existing_configured_binary_owner(backend, shape):
+ config = V2Config.default()
+ native = getattr(config.agents, backend)
+ native.cli_path = f"/fixture/custom-{backend}"
+ native.enabled = shape != "disabled-compat"
+ config.save()
+ _, coordinator, _, _ = _configured_owner(config if shape == "raw" else to_app_config(config))
+ assert coordinator._native_binaries((backend,)) == {backend: native.cli_path}
+
+
+def _row(command, *, pid=123):
+ return SimpleNamespace(info={
+ "pid": pid, "uids": SimpleNamespace(real=os.getuid()),
+ "name": Path(command[0]).name, "cmdline": command, "status": "running",
+ })
+
+
[email protected]("boundary", ["entry", "final_idle"])
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("enabled", [False, True])
[email protected]("prefix", [
+ ["python3", "-X", "dev"], ["bash", "-eu"], ["bash", "-"], ["zsh", "-"],
+ ["node", "--require", "/fixture/preload.js"], ["bun", "run"],
+ ["python", "--unknown-option", "value"],
+])
+def test_real_guard_blocks_wrapped_cli_before_takeover(monkeypatch, tmp_path, backend, boundary, enabled, prefix):
+ config = V2Config.default()
+ native = getattr(config.agents, backend)
+ native.cli_path = f"/fixture/custom-{backend}"
+ native.enabled = enabled
+ config.model_hub.agents[backend].mode = "direct"
+ if backend != "opencode":
+ native.auth_mode = "api_key"
+ native.api_key = "fixture-native-key"
+ native.base_url = "https://fixture.example"
+ else:
+ auth = Path.home() / ".config/opencode/opencode.json"
+ auth.parent.mkdir(parents=True)
+ auth.write_text('{"provider":{"openai":{"options":{"apiKey":"fixture-native-key"}}}}')
+ config.save()
+ service, _, adapter = _service(tmp_path, migration_home=Path.home())
+ service.store = V2ModelHubConfigStore()
+ controller, coordinator, admissions, turns = _configured_owner(to_app_config(config))
+ if not enabled:
+ controller.agent_service.agents.pop(backend)
+ controller.model_hub_service = service
+ coordinator._process_inventory = native_cli_processes
+ service.migration_guard = coordinator.migration_guard
+ calls = []
+
+ def inventory(attrs):
+ calls.append(tuple(attrs))
+ assert "environ" not in attrs
+ if boundary == "final_idle" and len(calls) == 1:
+ return []
+ return [_row([*prefix, native.cli_path])]
+
+ monkeypatch.setattr(psutil, "process_iter", inventory)
+ before = paths.get_config_path().read_bytes()
+ ids = [row["id"] for row in service.migration_scan()["items"] if row["backend"] == backend]
+ assert ids
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(service.migration_apply(ids))
+ assert error.value.code == "migration_native_busy"
+ assert len(calls) == (1 if boundary == "entry" else 2)
+ assert paths.get_config_path().read_bytes() == before
+ assert service.migration_journal.load() is None
+ assert not service.migration_blocked_backends and not admissions and not turns
+ if boundary == "entry":
+ assert not adapter.provisioned
+ else:
+ assert len(adapter.provisioned) == len(adapter.revoked) == 1
+ if backend == "opencode":
+ assert "fixture-native-key" in auth.read_text()
+ controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
+ assert isinstance(coordinator._refresh, Mock)
+ coordinator._refresh.assert_not_awaited()
+
+
[email protected]("backend", ["codex", "opencode"])
[email protected]("boundary", ["entry", "final_idle"])
[email protected]("failure", ["read-error", "recovery-defaults", "binary-recovery"])
+async def test_real_guard_refuses_unreadable_disabled_binary_config(monkeypatch, backend, boundary, failure):
+ config = V2Config.default()
+ native = getattr(config.agents, backend)
+ native.enabled = False
+ native.cli_path = f"/fixture/custom-{backend}"
+ config.save()
+ controller, coordinator, admissions, turns = _configured_owner(to_app_config(config))
+ coordinator._process_inventory = native_cli_processes
+ inventory = Mock(return_value=[])
+ monkeypatch.setattr(psutil, "process_iter", inventory)
+
+ def fail_load(*args, **kwargs):
+ if failure == "read-error":
+ raise OSError("fixture-sensitive-path")
+ recovered = V2Config.default()
+ if failure == "recovery-defaults":
+ recovered.whole_config_recovery = True
+ else:
+ recovered.recovered_sections = (f"agents.{backend}.cli_path",)
+ return recovered
+
+ if boundary == "entry":
+ monkeypatch.setattr(V2Config, "load", fail_load)
+ with pytest.raises(NativeMigrationBlockedError, match="^process_inventory_unavailable$") as error:
+ async with coordinator.migration_guard((backend,)) as verify_idle:
+ monkeypatch.setattr(V2Config, "load", fail_load)
+ inventory.return_value = [_row([native.cli_path])]
+ await verify_idle()
+ assert error.value.backends == (backend,)
+ assert inventory.call_count == (0 if boundary == "entry" else 1)
+ assert not admissions and not turns
+ controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
+
+
[email protected]("backend", ["codex", "opencode"])
+def test_settings_binary_resolution_retains_best_effort_default(monkeypatch, backend):
+ config = V2Config.default()
+ getattr(config.agents, backend).enabled = False
+ controller, _, _, _ = _configured_owner(to_app_config(config))
+ monkeypatch.setattr(V2Config, "load", Mock(side_effect=OSError("fixture-unreadable")))
+ assert controller.agent_auth_service._get_cli_binary(backend) == backend
+
+
+def test_strict_binary_resolution_keeps_unrelated_recovery_out_of_scope(monkeypatch):
+ config = V2Config.default()
+ config.agents.codex.enabled = False
+ config.agents.codex.cli_path = "/fixture/custom-codex"
+ config.recovered_sections = ("agents.claude", "logging")
+ _, coordinator, _, _ = _configured_owner(to_app_config(config))
+ load = Mock(return_value=config)
+ monkeypatch.setattr(V2Config, "load", load)
+ assert coordinator._native_binaries(("codex",)) == {"codex": "/fixture/custom-codex"}
+ load.assert_called_once_with(persist_migrations=False)
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("shape", ["raw", "compat"])
+async def test_real_guard_refuses_recovered_live_config_identity(monkeypatch, backend, shape):
+ recovered = V2Config._recover_payload({"mode": "self_host", "agents": "invalid"})
+ assert "agents" in recovered.recovered_sections
+ controller, coordinator, admissions, turns = _configured_owner(
+ recovered if shape == "raw" else to_app_config(recovered),
+ )
+ load = Mock(return_value=recovered)
+ monkeypatch.setattr(V2Config, "load", load)
+ inventory = Mock(return_value=[_row([f"/fixture/custom-{backend}"])])
+ monkeypatch.setattr(psutil, "process_iter", inventory)
+ coordinator._process_inventory = native_cli_processes
+ with pytest.raises(NativeMigrationBlockedError, match="^process_inventory_unavailable$"):
+ async with coordinator.migration_guard((backend,)):
+ pytest.fail("recovered live config must not certify native absence")
+ load.assert_called_once_with(persist_migrations=False)
+ inventory.assert_not_called()
+ assert not admissions and not turns
+ controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
+
+
[email protected]("command", [
+ ["node", "--eval=0", "SCRIPT"], ["node", "-", "SCRIPT"],
+ ["python3", "-m", "unrelated", "SCRIPT"],
+ ["bash", "-lc", "echo ordinary", "SCRIPT"],
+ ["python3", "/fixture/other.py", "SCRIPT"],
+])
+async def test_real_guard_does_not_confuse_data_with_a_configured_script(monkeypatch, command):
+ config = V2Config.default()
+ config.agents.codex.enabled = False
+ config.agents.codex.cli_path = script = "/fixture/custom-codex"
+ config.save()
+ controller, coordinator, admissions, turns = _configured_owner(to_app_config(config))
+ command = [script if value == "SCRIPT" else value for value in command]
+ inventory = Mock(return_value=[_row(command)])
+ monkeypatch.setattr(psutil, "process_iter", inventory)
+ coordinator._process_inventory = native_cli_processes
+ async with coordinator.migration_guard(("codex",)) as verify_idle:
+ await verify_idle()
+ assert admissions == turns == {"codex"}
+ assert inventory.call_count == 2
+ assert not admissions and not turns
+ controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
diff --git a/tests/test_native_takeover_lifecycle.py b/tests/test_native_takeover_lifecycle.py
new file mode 100644
index 000000000..835117af4
--- /dev/null
+++ b/tests/test_native_takeover_lifecycle.py
@@ -0,0 +1,667 @@
+"""Hermetic credential ownership, admission and strict retirement contracts."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import subprocess
+import sys
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from config.paths import get_state_dir
+from core.backend_restart import (
+ BackendRestartCoordinator,
+ NativeCredentialLease,
+ NativeMigrationBlockedError,
+ finish_native_operation,
+ native_cli_processes,
+ pending_native_backends,
+)
+
+
+def controller_fixture(*, backends=("claude", "codex", "opencode"), busy=False):
+ admissions = set()
+ turns = set()
+ service = SimpleNamespace(
+ agents={name: SimpleNamespace(retire_for_native_migration=AsyncMock()) for name in backends},
+ begin_backend_drain=Mock(side_effect=admissions.add),
+ end_backend_drain=Mock(side_effect=admissions.discard),
+ prepare_backend_restart=AsyncMock(),
+ runtime_turn_tokens_for_backend=Mock(return_value={}),
+ backend_runtime_active=Mock(return_value=busy),
+ force_cancel_backend_turns=AsyncMock(),
+ force_end_backend_activities=Mock(),
+ )
+ controller = SimpleNamespace(
+ agent_service=service,
+ session_turns=SimpleNamespace(
+ begin_backend_drain=Mock(side_effect=turns.add),
+ end_backend_drain=AsyncMock(side_effect=lambda backend, **kw: turns.discard(backend)),
+ ),
+ model_hub_service=SimpleNamespace(
+ migration_blocked_backends=set(), events=SimpleNamespace(path=get_state_dir() / "events.jsonl")
+ ),
+ config=SimpleNamespace(),
+ )
+ coordinator = BackendRestartCoordinator(
+ controller, AsyncMock(), process_inventory=Mock(return_value=()), drain_timeout=0.01, poll_interval=0.001,
+ )
+ controller.backend_restart_coordinator = coordinator
+ return controller, coordinator, admissions, turns
+
+
+def test_independent_leases_are_not_reentrant_on_same_thread(tmp_path):
+ with NativeCredentialLease(("codex",), state_dir=tmp_path):
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ NativeCredentialLease(("codex",), state_dir=tmp_path).acquire()
+ with NativeCredentialLease(("claude",), state_dir=tmp_path):
+ pass
+ with NativeCredentialLease(("codex",), state_dir=tmp_path):
+ pass
+
+
+def test_lease_excludes_an_independent_process_and_releases_on_error(tmp_path):
+ program = (
+ "from pathlib import Path; import sys; "
+ "from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError\n"
+ "try:\n"
+ " with NativeCredentialLease(('codex',),state_dir=Path(sys.argv[1])): pass\n"
+ "except NativeMigrationBlockedError: sys.exit(17)\n"
+ )
+ with pytest.raises(RuntimeError):
+ with NativeCredentialLease(("codex",), state_dir=tmp_path):
+ result = subprocess.run([sys.executable, "-c", program, str(tmp_path)], check=False)
+ assert result.returncode == 17
+ raise RuntimeError("owned operation failed")
+ assert subprocess.run([sys.executable, "-c", program, str(tmp_path)], check=False).returncode == 0
+
+
+def test_partial_multi_backend_acquire_releases_earlier_locks(tmp_path):
+ with NativeCredentialLease(("codex",), state_dir=tmp_path):
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("claude", "codex"), state_dir=tmp_path).acquire()
+ with NativeCredentialLease(("claude",), state_dir=tmp_path):
+ pass
+
+
+ None, [], {}, {"version": 1, "phase": "prepared", "backends": [{}]},
+ {"version": 2, "phase": "prepared", "backends": ["codex"]},
+ {"version": 1, "phase": [], "backends": ["codex"]},
+])
+def test_corrupt_journal_blocks_all_native_writers(tmp_path, data):
+ directory = tmp_path / "native-takeover"
+ directory.mkdir()
+ (directory / "current.json").write_text("invalid" if data is None else json.dumps(data))
+ assert pending_native_backends(directory) == {"claude", "codex", "opencode"}
+ for backend in ("claude", "codex", "opencode"):
+ with pytest.raises(NativeMigrationBlockedError, match="migration_recovery_pending"):
+ NativeCredentialLease((backend,), state_dir=tmp_path).acquire()
+ lease = NativeCredentialLease(("codex",), state_dir=tmp_path).acquire(recovery=True)
+ lease.release()
+
+
+def test_pending_journal_only_blocks_affected_backend(tmp_path):
+ directory = tmp_path / "native-takeover"
+ directory.mkdir()
+ (directory / "current.json").write_text(json.dumps({
+ "version": 1, "phase": "exposed", "backends": ["codex"],
+ }))
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("codex",), state_dir=tmp_path).acquire()
+ with NativeCredentialLease(("claude",), state_dir=tmp_path):
+ pass
+
+
+async def test_guard_closes_both_admissions_before_retirement_and_retains_only_blocked():
+ controller, coordinator, admissions, turns = controller_fixture()
+
+ async def retire():
+ assert admissions == turns == {"claude", "codex"}
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("codex",)).acquire()
+
+ controller.agent_service.agents["codex"].retire_for_native_migration.side_effect = retire
+ async with coordinator.migration_guard(("codex", "claude")):
+ assert admissions == turns == {"claude", "codex"}
+ controller.model_hub_service.migration_blocked_backends.add("codex")
+ with pytest.raises(NativeMigrationBlockedError):
+ await coordinator.request_restart("claude")
+ assert admissions == turns == {"codex"}
+ controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
+
+
+async def test_busy_guard_never_cancels_or_yields():
+ controller, coordinator, admissions, turns = controller_fixture(busy=True)
+ with pytest.raises(NativeMigrationBlockedError, match="native_runtime_busy"):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("Mutation admitted while busy")
+ assert admissions == turns == set()
+ controller.agent_service.force_cancel_backend_turns.assert_not_awaited()
+ controller.agent_service.agents["codex"].retire_for_native_migration.assert_not_awaited()
+
+
+async def test_guard_drains_active_work_naturally():
+ controller, coordinator, admissions, turns = controller_fixture(busy=True)
+ coordinator._drain_timeout = 1
+ ready = asyncio.Event()
+
+ async def transaction():
+ async with coordinator.migration_guard(("codex",)):
+ ready.set()
+ task = asyncio.create_task(transaction())
+ while not admissions:
+ await asyncio.sleep(0)
+ assert not ready.is_set()
+ controller.agent_service.backend_runtime_active.return_value = False
+ await task
+ assert ready.is_set()
+ assert not admissions and not turns
+
+
[email protected]("failure", ["missing_hook", "retire_failure", "external"])
+async def test_failed_retirement_or_external_process_never_yields(failure):
+ controller, coordinator, admissions, turns = controller_fixture()
+ if failure == "missing_hook":
+ controller.agent_service.agents["codex"] = object()
+ elif failure == "retire_failure":
+ controller.agent_service.agents["codex"].retire_for_native_migration.side_effect = RuntimeError("stop failed")
+ else:
+ coordinator._process_inventory.return_value = (123,)
+ with pytest.raises(NativeMigrationBlockedError):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("unsafe migration admission")
+ assert not admissions and not turns
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
+async def test_disabled_backend_still_requires_process_inventory():
+ _, coordinator, _, _ = controller_fixture(backends=())
+ coordinator._process_inventory.return_value = (999,)
+ with pytest.raises(NativeMigrationBlockedError, match="external_native_processes"):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("unmanaged process bypass")
+
+
+async def test_verify_idle_rechecks_external_processes_before_each_cutover():
+ _, coordinator, admissions, turns = controller_fixture()
+ async with coordinator.migration_guard(("codex",)) as verify_idle:
+ await verify_idle()
+ coordinator._process_inventory.return_value = (123,)
+ with pytest.raises(NativeMigrationBlockedError, match="external_native_processes"):
+ await verify_idle()
+ assert admissions == turns == {"codex"}
+ with pytest.raises(RuntimeError, match="no ownership"):
+ await verify_idle()
+
+
+async def test_live_auth_lease_refuses_migration_before_admission_closes():
+ _, coordinator, admissions, turns = controller_fixture()
+ with NativeCredentialLease(("codex",)):
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("overlapping native writers")
+ assert not admissions and not turns
+
+
+async def test_restart_task_and_migration_have_one_owner():
+ controller, coordinator, admissions, turns = controller_fixture(busy=True)
+ coordinator._drain_timeout = 1
+ assert await coordinator.request_restart("codex") == "draining"
+ with pytest.raises(NativeMigrationBlockedError, match="backend_restart_in_progress"):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("competing restart")
+ controller.agent_service.backend_runtime_active.return_value = False
+ await coordinator.wait("codex")
+ assert not admissions and not turns
+
+
+async def test_cancelled_guard_waits_for_strict_retirement_before_reopening():
+ controller, coordinator, admissions, turns = controller_fixture()
+ entered = asyncio.Event()
+ finish = asyncio.Event()
+
+ async def retire():
+ entered.set()
+ await finish.wait()
+ controller.agent_service.agents["codex"].retire_for_native_migration.side_effect = retire
+
+ async def transaction():
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("cancelled mutation")
+ task = asyncio.create_task(transaction())
+ await entered.wait()
+ task.cancel()
+ await asyncio.sleep(0)
+ assert admissions == turns == {"codex"}
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("codex",)).acquire()
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert not admissions and not turns
+
+
+async def test_recovery_error_applies_pending_blocks_before_other_producers():
+ from core.controller import Controller
+
+ fake, coordinator, admissions, turns = controller_fixture()
+ controller = Controller.__new__(Controller)
+ controller.__dict__.update(fake.__dict__)
+ coordinator.controller = controller
+ directory = get_state_dir() / "native-takeover"
+ directory.mkdir(parents=True)
+ (directory / "current.json").write_text("corrupt envelope")
+ controller.model_hub_service.recover_runtime_intent = AsyncMock(side_effect=RuntimeError("recovery failed"))
+
+ async def producer(**kwargs):
+ assert admissions == turns == {"claude", "codex", "opencode"}
+ return []
+ controller.session_turns.recover_durable_delivery_state = AsyncMock(side_effect=producer)
+ controller.session_turns.recover_persisted_agent_run_queue = AsyncMock(side_effect=producer)
+ controller.scheduled_task_service = SimpleNamespace(recover_processing_requests=Mock())
+ controller.runtime_work_supervisor = SimpleNamespace(activate=AsyncMock(side_effect=producer))
+ controller._delivery_recovery_complete = asyncio.Event()
+ await controller._recover_runtime_owners()
+ assert controller._delivery_recovery_complete.is_set()
+
+
[email protected]("command,matched", [
+ (["/opt/bin/codex", "login"], True),
+ (["codex", "app-server"], True),
+ (["claude"], True),
+ (["/usr/bin/node", "/npm/@anthropic-ai/claude-code/cli.js", "--resume", "fake"], True),
+ (["/usr/bin/node", "/npm/@openai/codex/bin/codex.js"], True),
+ (["opencode", "serve", "--port", "1234"], True),
+ (["python", "test.py", "claude"], False),
+ (["/bin/echo", "codex"], False),
+])
+def test_process_inventory_matches_executables_not_prompt_arguments(monkeypatch, command, matched):
+ import psutil
+
+ monkeypatch.setattr(psutil, "process_iter", lambda attrs: [
+ SimpleNamespace(info={
+ "pid": 123, "uids": SimpleNamespace(real=os.getuid()), "status": "running",
+ "cmdline": command, "name": Path(command[0]).name,
+ }),
+ SimpleNamespace(info={
+ "pid": 456, "uids": SimpleNamespace(real=os.getuid() + 1), "status": "running",
+ "cmdline": ["codex"], "name": "codex",
+ }),
+ ])
+ assert native_cli_processes(dict.fromkeys(("claude", "codex", "opencode"), "")) == ((123,) if matched else ())
+
+
+def test_incomplete_same_user_inventory_refuses(monkeypatch):
+ import psutil
+
+ monkeypatch.setattr(psutil, "process_iter", lambda attrs: [SimpleNamespace(info={
+ "pid": 123, "uids": SimpleNamespace(real=os.getuid()), "status": "running", "cmdline": None,
+ })])
+ with pytest.raises(NativeMigrationBlockedError, match="process_inventory_unavailable"):
+ native_cli_processes({"codex": "codex"})
+
+
+async def test_cancelled_thread_writer_keeps_lease_until_worker_finishes():
+ started = threading.Event()
+ finish = threading.Event()
+
+ def writer():
+ started.set()
+ assert finish.wait(5)
+
+ async def operation():
+ with NativeCredentialLease(("codex",)):
+ await finish_native_operation(asyncio.to_thread(writer))
+ task = asyncio.create_task(operation())
+ while not started.is_set():
+ await asyncio.sleep(0)
+ task.cancel()
+ await asyncio.sleep(0)
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("codex",)).acquire()
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
+def auth_service(monkeypatch):
+ from core.agent_auth_service import AgentAuthService
+ from config.v2_config import V2Config
+
+ config = V2Config.default()
+ for supply in config.model_hub.agents.values():
+ supply.mode = "direct"
+ config.save()
+ monkeypatch.setattr(AgentAuthService, "_recover_interrupted_claude_oauth_settings_backup", lambda self: None)
+ return AgentAuthService(SimpleNamespace(config=SimpleNamespace()))
+
+
+async def test_auth_flow_cross_instance_exclusion_through_terminal_cleanup(monkeypatch):
+ from core.agent_auth_service import BackendLoginInProgressError
+
+ first = auth_service(monkeypatch)
+ second = auth_service(monkeypatch)
+ waiting = asyncio.Event()
+ terminal = asyncio.Event()
+ cleaning = asyncio.Event()
+ clean = asyncio.Event()
+ process = SimpleNamespace(returncode=0)
+ first._start_codex_process = AsyncMock(return_value=process)
+ first._read_codex_output_web = AsyncMock()
+
+ async def waiter(flow):
+ waiting.set()
+ await terminal.wait()
+ flow.state = "success"
+ original_cleanup = first._cleanup_native_flow
+
+ async def cleanup(flow):
+ cleaning.set()
+ await clean.wait()
+ await original_cleanup(flow)
+ first._wait_for_codex_completion_web = waiter
+ first._cleanup_native_flow = cleanup
+ second._start_codex_process = AsyncMock()
+ flow = await first._start_auth_flow("codex")
+ await waiting.wait()
+ with pytest.raises(BackendLoginInProgressError):
+ await second._start_auth_flow("codex")
+ second._start_codex_process.assert_not_awaited()
+ terminal.set()
+ await cleaning.wait()
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("codex",)).acquire()
+ clean.set()
+ await flow.waiter_task
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
+async def test_start_failure_releases_native_lease(monkeypatch):
+ service = auth_service(monkeypatch)
+ service._start_codex_process = AsyncMock(side_effect=RuntimeError("spawn failed"))
+ with pytest.raises(RuntimeError, match="spawn failed"):
+ await service._start_auth_flow("codex")
+ assert not service._flows_by_id
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
+async def test_flow_cancel_releases_after_process_wait(monkeypatch):
+ service = auth_service(monkeypatch)
+ stopped = asyncio.Event()
+ process = SimpleNamespace(returncode=None, terminate=Mock(), kill=Mock())
+
+ async def wait():
+ await stopped.wait()
+ process.returncode = -15
+ process.wait = wait
+ service._start_codex_process = AsyncMock(return_value=process)
+ service._read_codex_output_web = AsyncMock()
+ running = asyncio.Event()
+
+ async def waiter(flow):
+ running.set()
+ await asyncio.Event().wait()
+ service._wait_for_codex_completion_web = waiter
+ flow = await service._start_auth_flow("codex")
+ await running.wait()
+ cancel = asyncio.create_task(service.cancel_web_flow(flow.flow_id))
+ while not process.terminate.called:
+ await asyncio.sleep(0)
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("codex",)).acquire()
+ stopped.set()
+ await cancel
+ assert not service._flows_by_id
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
+async def test_flow_cleanup_failure_retains_ownership(monkeypatch):
+ service = auth_service(monkeypatch)
+ from core.agent_auth_service import WebAuthFlow
+
+ flow = WebAuthFlow("fake", "claude", native_lease=NativeCredentialLease(("claude",)).acquire())
+ flow.claude_client = SimpleNamespace(disconnect=AsyncMock(side_effect=RuntimeError("disconnect failed")))
+ service._flow_registry.put(flow)
+ service._arm_flow_waiter(flow, asyncio.sleep(0))
+ with pytest.raises(RuntimeError, match="disconnect failed"):
+ await flow.waiter_task
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("claude",)).acquire()
+ assert service._flows_by_id["fake"] is flow
+ flow.claude_client.disconnect.side_effect = None
+ await service._cleanup_native_flow(flow)
+
+
+async def test_api_writers_do_not_reach_native_files_under_other_owner(monkeypatch):
+ from vibe import api
+
+ monkeypatch.setattr(api, "_config_recovery_message", Mock(side_effect=AssertionError("writer reached")))
+ with NativeCredentialLease(("claude", "codex", "opencode")):
+ assert api.save_codex_auth({})["error"] == "native_auth_in_progress"
+ assert api.save_claude_auth({})["error"] == "native_auth_in_progress"
+ assert api.remove_backend_api_key("codex")["error"] == "native_auth_in_progress"
+ assert (await api.save_opencode_provider_auth_async("openai", {}))["error"] == "native_auth_in_progress"
+ assert (await api.delete_opencode_provider_auth_async("openai"))["error"] == "native_auth_in_progress"
+ assert (await api.save_opencode_custom_provider_async({}))["error"] == "native_auth_in_progress"
+ assert (await api.delete_opencode_custom_provider_async("fake"))["error"] == "native_auth_in_progress"
+
+
+def test_unsupported_native_writer_preserves_api_validation():
+ from vibe import api
+
+ assert api.remove_backend_api_key("") == {"ok": False, "error": "unsupported_backend"}
+
+
+async def test_api_cancel_waits_for_writer_before_releasing():
+ from vibe.api import _native_auth_write
+
+ started = asyncio.Event()
+ complete = asyncio.Event()
+
+ @_native_auth_write("opencode", authentication=False)
+ async def write():
+ started.set()
+ await complete.wait()
+ task = asyncio.create_task(write())
+ await started.wait()
+ task.cancel()
+ await asyncio.sleep(0)
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("opencode",)).acquire()
+ complete.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ with NativeCredentialLease(("opencode",)):
+ pass
+
+
+async def test_explicit_nested_claude_cleanup_uses_outer_lease(monkeypatch):
+ service = auth_service(monkeypatch)
+ service._clear_claude_oauth_credentials_owned = AsyncMock(return_value={"ok": True})
+ with NativeCredentialLease(("claude",)) as lease:
+ assert await service.clear_claude_oauth_credentials_only(lease=lease) == {"ok": True}
+ with pytest.raises(NativeMigrationBlockedError):
+ NativeCredentialLease(("claude",)).acquire()
+ with pytest.raises(RuntimeError, match="no ownership"):
+ await service.clear_claude_oauth_credentials_only(lease=lease)
+
+
+async def test_utility_failure_awaits_process_exit_before_return(monkeypatch):
+ service = auth_service(monkeypatch)
+ process = SimpleNamespace(
+ returncode=None, terminate=Mock(), kill=Mock(),
+ communicate=AsyncMock(side_effect=asyncio.TimeoutError),
+ )
+ async def wait():
+ process.returncode = -15
+ process.wait = wait
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
+ ok, _ = await service._run_utility_command("fake-native-cli", "logout")
+ assert not ok
+ process.terminate.assert_called_once()
+ assert process.returncode == -15
+
+
+async def test_cancelled_unstarted_waiter_still_releases_lease(monkeypatch):
+ from core.agent_auth_service import WebAuthFlow
+
+ service = auth_service(monkeypatch)
+ flow = WebAuthFlow("not-started", "codex", native_lease=NativeCredentialLease(("codex",)).acquire())
+ flow.waiter_task = asyncio.create_task(asyncio.sleep(100))
+ # A cancelled task can skip its coroutine's finally block entirely.
+ flow.waiter_task.cancel()
+ await service._terminate_web_flow(flow, final_state="cancelled")
+ assert flow.native_lease is None
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
+async def test_terminal_ttl_does_not_drop_failed_cleanup_owner(monkeypatch):
+ from core.agent_auth_service import WebAuthFlow
+
+ service = auth_service(monkeypatch)
+ flow = WebAuthFlow(
+ "failed-cleanup", "codex", state="failed", terminal_at=0,
+ native_lease=NativeCredentialLease(("codex",)).acquire(),
+ )
+ service._flow_registry.put(flow)
+ service.get_web_flow_status(flow.flow_id)
+ assert service._flows_by_id[flow.flow_id] is flow
+ await service._cleanup_native_flow(flow)
+
+
+async def test_codex_strict_retirement_propagates_stop_failure():
+ from modules.agents.codex.agent import CodexAgent
+
+ transport = SimpleNamespace()
+ agent = CodexAgent.__new__(CodexAgent)
+ agent._transports = {"cwd": transport}
+ agent._transport_locks = {}
+ agent._stop_and_detach_transport_generation = AsyncMock(side_effect=RuntimeError("stop failed"))
+ agent._session_mgr = SimpleNamespace(all_base_sessions=Mock(return_value=["session"]), invalidate_thread=Mock())
+ with pytest.raises(RuntimeError, match="stop failed"):
+ await agent.retire_for_native_migration()
+ assert agent._transports["cwd"] is transport
+ agent._session_mgr.invalidate_thread.assert_not_called()
+
+
+async def test_codex_strict_retirement_checks_exit_before_detaching():
+ from modules.agents.codex.agent import CodexAgent
+
+ process = SimpleNamespace(returncode=None, wait=AsyncMock())
+ transport = SimpleNamespace(_process=process, stop=AsyncMock())
+ agent = CodexAgent.__new__(CodexAgent)
+ agent._reserve_transport_retirement = Mock(return_value="generation")
+ agent._finish_transport_retirement = Mock(return_value=True)
+ agent._detach_transport_bookkeeping = Mock(return_value=True)
+ with pytest.raises(RuntimeError, match="did not exit"):
+ await agent._stop_and_detach_transport_generation("cwd", transport, require_process_exit=True)
+ agent._finish_transport_retirement.assert_called_once_with("generation", retire=False)
+ agent._detach_transport_bookkeeping.assert_not_called()
+
+
+async def test_claude_retirement_never_uses_broad_reaper_or_swallows_disconnect():
+ from modules.agents.claude_agent import ClaudeAgent
+
+ process = SimpleNamespace(returncode=None, wait=AsyncMock())
+ client = SimpleNamespace(_transport=SimpleNamespace(_process=process), disconnect=AsyncMock())
+ handler = SimpleNamespace(
+ active_sessions=set(), _claude_runtime_generation_lock=lambda key: asyncio.Lock(),
+ _retire_claude_runtime_activation=Mock(return_value=True),
+ clear_session_tracking=Mock(), _retire_model_hub_process_scope=Mock(),
+ cleanup_session=AsyncMock(side_effect=AssertionError("broad cleanup is unsafe")),
+ )
+ agent = ClaudeAgent.__new__(ClaudeAgent)
+ agent.session_handler = handler
+ agent.claude_sessions = {"key": client}
+ agent.receiver_tasks = {}
+ agent._native_session_ids = {}
+ agent._last_assistant_text = {}
+ agent._pending_assistant_message = {}
+ agent._retire_steering_state = Mock()
+ agent._stop_receiver_task = AsyncMock()
+ with pytest.raises(RuntimeError, match="did not exit"):
+ await agent.retire_for_native_migration()
+ assert agent.claude_sessions["key"] is client
+ handler.clear_session_tracking.assert_not_called()
+ process.returncode = 0
+ await agent.retire_for_native_migration()
+ assert not agent.claude_sessions
+ handler.cleanup_session.assert_not_awaited()
+
+
+async def test_opencode_unproven_pid_file_is_blocker_not_kill_target():
+ from modules.agents.opencode.server import OpenCodeServerManager
+
+ server = OpenCodeServerManager.__new__(OpenCodeServerManager)
+ server._get_lock = lambda: asyncio.Lock()
+ server._active_requests = 0
+ server._has_active_run_sessions = Mock(return_value=False)
+ server._runtime_activation_retire = Mock(return_value=True)
+ server._process = None
+ server._read_pid_file = Mock(return_value={"pid": 123})
+ server._pid_exists = Mock(return_value=True)
+ server._terminate_pid_tree_sync = Mock(side_effect=AssertionError("must not kill"))
+ server._clear_pid_file = Mock()
+ with pytest.raises(RuntimeError, match="ownership cannot be proven"):
+ await server.retire_for_native_migration()
+ server._terminate_pid_tree_sync.assert_not_called()
+ server._clear_pid_file.assert_not_called()
+
+
+async def test_opencode_strict_stop_failure_retains_tracking():
+ from modules.agents.opencode.server import OpenCodeServerManager
+
+ server = OpenCodeServerManager.__new__(OpenCodeServerManager)
+ server._get_lock = lambda: asyncio.Lock()
+ server._active_requests = 0
+ server._has_active_run_sessions = Mock(return_value=False)
+ server._runtime_activation_retire = Mock(return_value=True)
+ process = SimpleNamespace(pid=123, returncode=None, wait=AsyncMock())
+ server._process = process
+ server._read_pid_file = Mock(return_value={"pid": 123})
+ server._terminate_pid_tree_sync = Mock(return_value=False)
+ server._clear_pid_file = Mock()
+ with pytest.raises(RuntimeError, match="did not exit"):
+ await server.retire_for_native_migration()
+ assert server._process is process
+ server._clear_pid_file.assert_not_called()
diff --git a/tests/test_native_writer_custody.py b/tests/test_native_writer_custody.py
new file mode 100644
index 000000000..9e361139a
--- /dev/null
+++ b/tests/test_native_writer_custody.py
@@ -0,0 +1,416 @@
+"""Persisted native custody and whole-document writer exclusion, fixture only."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import subprocess
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import psutil
+import pytest
+
+from config import paths
+from config.v2_config import ModelHubSourceConfig, ModelHubSourceStateConfig, V2Config
+from core.agent_auth_service import AgentAuthService, BackendLoginInProgressError
+from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError
+from modules.im import MessageContext
+from tests.test_native_takeover_lifecycle import controller_fixture
+from vibe import api, claude_config, opencode_config
+
+
[email protected](autouse=True)
+def no_live_operations(monkeypatch):
+ def forbidden(*args, **kwargs):
+ raise AssertionError("This custody test must not reach a live operation")
+
+ monkeypatch.setattr(subprocess, "run", forbidden)
+ monkeypatch.setattr(subprocess, "Popen", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
+ monkeypatch.setattr(psutil, "process_iter", forbidden)
+ monkeypatch.setattr(api, "restart_backend", Mock(return_value={"ok": True}))
+ monkeypatch.setattr(api, "_opencode_get_server", AsyncMock(return_value=None))
+ monkeypatch.setattr(api, "_config_recovery_message", lambda: None)
+
+
+def saved_config(*, mode="hub", enabled=True, source=None):
+ config = V2Config.default()
+ config.model_hub.enabled = enabled
+ for supply in config.model_hub.agents.values():
+ supply.mode = mode
+ if source is not None:
+ config.model_hub.sources = [source]
+ config.save()
+ return config
+
+
+def native_source(*, vendor="openai", channel="native_cli"):
+ return ModelHubSourceConfig(
+ id="src_retained1",
+ kind="subscription",
+ vendor=vendor,
+ display_name="Fixture subscription",
+ protocol="anthropic" if vendor == "anthropic" else "openai_responses",
+ supply_channel=channel,
+ billing="monthly",
+ state=ModelHubSourceStateConfig(),
+ models=[],
+ credential_ref="fixture-ref" if channel == "hub" else None,
+ )
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("enabled", [True, False])
+def test_custody_follows_persisted_mode_not_runtime_switch(backend, enabled):
+ saved_config(mode="direct", enabled=enabled)
+ with NativeCredentialLease((backend,)) as lease:
+ lease.assert_auth_custody(backend)
+ saved_config(enabled=enabled)
+ with NativeCredentialLease((backend,)) as lease:
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):
+ lease.assert_auth_custody(backend)
+
+
+def test_missing_config_is_new_hub_custody_and_malformed_is_fail_closed():
+ with NativeCredentialLease(("codex",)) as lease:
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):
+ lease.assert_auth_custody("codex")
+ config_path = paths.get_config_path()
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text("{bad-json")
+ with pytest.raises(NativeMigrationBlockedError, match="config_recovery"):
+ lease.assert_auth_custody("codex")
+
+
+def test_legacy_missing_backend_config_keeps_direct_custody():
+ saved_config()
+ payload = json.loads(paths.get_config_path().read_text())
+ payload.pop("model_hub")
+ paths.get_config_path().write_text(json.dumps(payload))
+ with NativeCredentialLease(("codex",)) as lease:
+ lease.assert_auth_custody("codex")
+
+
[email protected]("backend,vendor", [("codex", "openai"), ("claude", "anthropic")])
+def test_retained_subscription_requires_matching_source_binding(backend, vendor):
+ source = native_source(vendor=vendor)
+ saved_config(source=source, enabled=False)
+ with NativeCredentialLease((backend,)) as lease:
+ lease.assert_auth_custody(backend, source_id=source.id)
+ for source_id in (None, "src_different"):
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):
+ lease.assert_auth_custody(backend, source_id=source_id)
+ source.supply_channel = "hub"
+ source.credential_ref = "fixture-ref"
+ saved_config(source=source)
+ with NativeCredentialLease((backend,)) as lease:
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):
+ lease.assert_auth_custody(backend, source_id=source.id)
+
+
+def test_other_vendor_source_cannot_authorize_backend():
+ saved_config(source=native_source(vendor="anthropic"))
+ with NativeCredentialLease(("codex",)) as lease:
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):
+ lease.assert_auth_custody("codex", source_id="src_retained1")
+
+
+async def test_stale_controller_cannot_spawn_native_login_after_takeover():
+ stale = saved_config(mode="direct")
+ service = AgentAuthService(SimpleNamespace(config=stale))
+ saved_config(enabled=False)
+ service._start_codex_process = AsyncMock()
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_hub_owned"):
+ await service.start_web_setup("codex")
+ service._start_codex_process.assert_not_awaited()
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
+ "language,expected",
+ [("en", "Manage Codex authentication in Model Hub."),
+ ("zh", "请在模型网关中管理 Codex 的认证。")],
+)
+async def test_im_native_setup_after_takeover_directs_to_hub_without_reset(language, expected):
+ config = saved_config()
+ config.language = language
+ service = AgentAuthService(SimpleNamespace(config=config, _get_settings_key=lambda _: "fixture"))
+ service._send_message = AsyncMock()
+ service._send_setup_start_failure = AsyncMock()
+ service._start_codex_process = AsyncMock()
+ context = SimpleNamespace(channel_id="fixture", user_id="fixture", platform="slack")
+
+ await service.start_setup(context, backend="codex")
+
+ assert service._send_message.await_args.args[1].casefold() == expected.casefold()
+ service._send_setup_start_failure.assert_not_awaited()
+ service._start_codex_process.assert_not_awaited()
+ assert service._flows == {}
+
+
+async def test_bound_native_source_keeps_lease_until_terminal_cleanup():
+ source = native_source()
+ config = saved_config(source=source)
+ first = AgentAuthService(SimpleNamespace(config=config))
+ second = AgentAuthService(SimpleNamespace(config=config))
+ first._start_codex_process = AsyncMock(return_value=SimpleNamespace(returncode=0))
+ first._read_codex_output_web = AsyncMock()
+ waiting = asyncio.Event()
+
+ async def wait(flow):
+ waiting.set()
+ await asyncio.Event().wait()
+
+ first._wait_for_codex_completion_web = wait
+ flow = await first.start_web_setup("codex", owner_ref=source.id)
+ await asyncio.wait_for(waiting.wait(), 2)
+ try:
+ with pytest.raises(BackendLoginInProgressError):
+ await second.start_web_setup("codex", owner_ref=source.id)
+ _, coordinator, admissions, _ = controller_fixture()
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ async with coordinator.migration_guard(("codex",)):
+ pytest.fail("native flow overlapped takeover")
+ assert not admissions
+ finally:
+ await first.cancel_web_flow(flow.flow_id)
+ with NativeCredentialLease(("codex",)):
+ pass
+
+
[email protected]("mode,retained", [("direct", False), ("hub", False), ("hub", True)])
+def test_constructor_only_restores_backup_under_direct_custody(mode, retained):
+ config = saved_config(
+ mode=mode, source=native_source(vendor="anthropic") if retained else None,
+ )
+ claude_config.write_claude_oauth_settings_backup({"ANTHROPIC_API_KEY": "fixture-old-key"})
+ backup = claude_config.get_claude_oauth_settings_backup_path()
+ before = backup.read_bytes()
+ AgentAuthService(SimpleNamespace(config=config))
+ if mode == "direct":
+ assert not backup.exists()
+ assert claude_config.read_claude_settings_env()["ANTHROPIC_API_KEY"] == "fixture-old-key"
+ else:
+ assert backup.read_bytes() == before
+ assert not claude_config.read_claude_settings_env()
+
+
+async def test_all_generic_auth_api_writers_refuse_hub_and_point_to_hub(monkeypatch):
+ saved_config(enabled=False)
+ writer = Mock(side_effect=AssertionError("Native writer reached"))
+ monkeypatch.setattr(claude_config, "apply_claude_auth", writer)
+ from vibe import codex_config
+ monkeypatch.setattr(codex_config, "apply_codex_auth", writer)
+ monkeypatch.setattr(opencode_config, "upsert_opencode_custom_provider", writer)
+ monkeypatch.setattr(opencode_config, "upsert_opencode_provider_api_key", writer)
+ service = AgentAuthService(SimpleNamespace(config=V2Config.default()))
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: service)
+ results = [
+ api.save_codex_auth({"auth_mode": "api_key", "api_key": "fixture"}),
+ api.save_claude_auth({"auth_mode": "api_key", "api_key": "fixture"}),
+ api.remove_backend_api_key("codex"),
+ api.remove_backend_api_key("claude"),
+ await api.save_opencode_provider_auth_async("openai", {"api_key": "fixture"}),
+ await api.delete_opencode_provider_auth_async("openai"),
+ await api.save_opencode_custom_provider_async({}),
+ await api.delete_opencode_custom_provider_async("fixture"),
+ await api.start_oauth_web_async("codex"),
+ await api.start_oauth_web_async("claude"),
+ await api.start_oauth_web_async("opencode", provider_id="openai"),
+ await api.remove_backend_auth_async("codex"),
+ await api.remove_claude_oauth_credentials_async(),
+ await api.test_backend_auth_async("claude"),
+ await api.test_opencode_provider_async("openai"),
+ ]
+ for result in results:
+ assert result["ok"] is False
+ assert result["error"] == "native_auth_hub_owned"
+ assert result["reauth_channel"] == "hub"
+ writer.assert_not_called()
+ with NativeCredentialLease(("claude", "codex", "opencode")):
+ pass
+
+
+async def non_auth_write(kind):
+ if kind == "permission":
+ return await asyncio.to_thread(api.setup_opencode_permission)
+ if kind == "add":
+ return await api.save_opencode_provider_model_async(
+ "openai", {"model_id": "fixture-model", "api_key": "must-not-be-used"},
+ )
+ return await api.delete_opencode_provider_model_async("openai", "fixture-model")
+
+
+def opencode_fixture():
+ path = opencode_config.get_opencode_config_paths(Path.home())[0]
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({
+ "provider": {"openai": {"options": {"apiKey": "fixture-existing"}}},
+ }))
+ opencode_config.upsert_opencode_provider_model("openai", "fixture-model")
+ return path
+
+
[email protected]("kind", ["permission", "add", "delete"])
[email protected]("blocker", ["lease", "journal"])
+async def test_non_auth_rmw_is_excluded_before_first_read(monkeypatch, kind, blocker):
+ saved_config()
+ path = opencode_fixture()
+ before = path.read_bytes()
+ lease = NativeCredentialLease(("opencode",))
+ if blocker == "lease":
+ lease.acquire()
+ else:
+ lease.directory.mkdir(parents=True, exist_ok=True)
+ (lease.directory / "current.json").write_text(json.dumps({
+ "version": 1, "phase": "exposed", "backends": ["opencode"],
+ }))
+ try:
+ result = await non_auth_write(kind)
+ assert result["error"] == (
+ "native_auth_in_progress" if blocker == "lease" else "migration_recovery_pending"
+ )
+ assert path.read_bytes() == before
+ api._opencode_get_server.assert_not_awaited()
+ finally:
+ lease.release()
+
+
[email protected]("kind", ["permission", "add", "delete"])
+async def test_non_auth_rmw_remains_allowed_in_hub_without_introducing_key(kind):
+ saved_config(enabled=False)
+ path = opencode_fixture()
+ opencode_config.remove_opencode_provider_api_key("openai")
+ assert (await non_auth_write(kind))["ok"]
+ assert "apiKey" not in path.read_text()
+ assert "must-not-be-used" not in path.read_text()
+
+
[email protected]("kind", ["permission", "add", "delete"])
+async def test_rmw_cancellation_tail_cannot_overlap_takeover(monkeypatch, kind):
+ saved_config()
+ path = opencode_fixture()
+ started, finish, settled = threading.Event(), threading.Event(), threading.Event()
+ original = Path.write_text if kind == "permission" else opencode_config._write_opencode_config
+
+ def slow_write(*args, **kwargs):
+ started.set()
+ try:
+ assert finish.wait(5)
+ return original(*args, **kwargs)
+ finally:
+ settled.set()
+
+ if kind == "permission":
+ monkeypatch.setattr(Path, "write_text", slow_write)
+ else:
+ monkeypatch.setattr(opencode_config, "_write_opencode_config", slow_write)
+ task = asyncio.create_task(non_auth_write(kind))
+ try:
+ assert await asyncio.to_thread(started.wait, 2)
+ task.cancel()
+ await asyncio.sleep(0)
+ _, coordinator, admissions, _ = controller_fixture()
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ async with coordinator.migration_guard(("opencode",)):
+ pytest.fail("A stale credential writer crossed native withdrawal")
+ assert not admissions
+ finally:
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert await asyncio.to_thread(settled.wait, 2)
+ # The synchronous request thread can still be returning after write_text.
+ for _ in range(200):
+ try:
+ lease = NativeCredentialLease(("opencode",)).acquire()
+ lease.release()
+ break
+ except NativeMigrationBlockedError:
+ await asyncio.sleep(0.005)
+ else:
+ pytest.fail("Completed writer did not release its lease")
+ async with coordinator.migration_guard(("opencode",)) as verify_idle:
+ await verify_idle()
+ opencode_config.remove_opencode_provider_api_key("openai")
+ assert "apiKey" not in path.read_text()
+
+
+async def test_recovery_pending_propagates_without_becoming_login_busy():
+ config = saved_config(mode="direct")
+ service = AgentAuthService(SimpleNamespace(config=config))
+ directory = paths.get_state_dir() / "native-takeover"
+ (directory / "current.json").write_text(json.dumps({
+ "version": 1, "phase": "reverting", "backends": ["codex"],
+ }))
+ with pytest.raises(NativeMigrationBlockedError, match="migration_recovery_pending"):
+ await service.start_web_setup("codex")
+
+
[email protected]("surface", ["im_api_key", "web_redirect"])
+async def test_concurrent_cancel_joins_request_owned_writer_before_releasing(monkeypatch, surface):
+ from core.agent_auth_service import WebAuthFlow
+
+ config = saved_config(mode="direct")
+ service = AgentAuthService(SimpleNamespace(config=config))
+ started, finish = asyncio.Event(), asyncio.Event()
+ written = []
+
+ async def write(*args):
+ started.set()
+ await finish.wait()
+ opencode_config.upsert_opencode_provider_api_key("openai", "fixture-new")
+ written.append(True)
+ return {"ok": True}
+
+ if surface == "im_api_key":
+ context = MessageContext(user_id="fixture", channel_id="fixture")
+ service._get_settings_key = lambda _: "fixture"
+ service._resolve_opencode_provider = AsyncMock(return_value="opencode")
+ service._install_opencode_api_key = write
+ service._refresh_backend_runtime = AsyncMock()
+ service._clear_backend_sessions_for_context = AsyncMock()
+ service._send_message = AsyncMock()
+ flow = await service._start_auth_flow("opencode", context=context)
+ assert not flow.native_cli
+ submit = asyncio.create_task(service.submit_code(context, "fixture-new", "opencode"))
+ terminate = lambda: service._terminate_flow(flow)
+ else:
+ flow = WebAuthFlow(
+ "redirect", "opencode", state="awaiting_code", provider="openai", callback_kind="redirect",
+ native_lease=service._acquire_native_lease("opencode"),
+ )
+ service._flow_registry.put(flow)
+ service._submit_opencode_callback_url = write
+ submit = asyncio.create_task(service.submit_web_code(flow.flow_id, "fixture-callback"))
+ terminate = lambda: service._terminate_web_flow(flow, final_state="cancelled")
+ await asyncio.wait_for(started.wait(), 2)
+ submit.cancel()
+ cleanup = asyncio.create_task(terminate())
+ try:
+ await asyncio.sleep(0)
+ assert not cleanup.done()
+ with pytest.raises(NativeMigrationBlockedError, match="native_auth_in_progress"):
+ NativeCredentialLease(("opencode",)).acquire()
+ assert not written
+ finally:
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(submit, 2)
+ await asyncio.wait_for(cleanup, 2)
+ assert written
+ with NativeCredentialLease(("opencode",)):
+ pass
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 8a5ff7bab..113b6cdd4 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -157,7 +157,11 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
config_home = self.enterContext(tempfile.TemporaryDirectory(prefix="opencode-server-test-"))
self.enterContext(patch.dict(os.environ, {"AVIBE_HOME": config_home}))
- default_config().save()
+ config = default_config()
+ # These server lifecycle cases exercise native Direct launches.
+ # Hub-specific cases explicitly supply the Controller-owned overlay.
+ config.model_hub.agents["opencode"].mode = "direct"
+ config.save()
def test_managed_runtime_config_accepts_jsonc_and_disables_native_skill(self):
content = SERVER_MODULE._managed_runtime_config_content(
diff --git a/tests/test_save_opencode_provider_auth.py b/tests/test_save_opencode_provider_auth.py
index d097657eb..55e435734 100644
--- a/tests/test_save_opencode_provider_auth.py
+++ b/tests/test_save_opencode_provider_auth.py
@@ -23,6 +23,15 @@ import pytest
from vibe import api
[email protected](autouse=True)
+def direct_native_auth():
+ from config.v2_config import V2Config
+
+ config = V2Config.default()
+ config.model_hub.agents["opencode"].mode = "direct"
+ config.save()
+
+
class _FakeServer:
"""Stand-in for the OpenCode HTTP daemon used by the save flow.
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index 944842d57..8781e8e41 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -31,6 +31,20 @@ import pytest
from vibe.codex_config import read_codex_auth_state
+def _direct_config(**kwargs):
+ from config.v2_config import V2Config
+
+ config = V2Config(**kwargs) if kwargs else V2Config.default()
+ for supply in config.model_hub.agents.values():
+ supply.mode = "direct"
+ return config
+
+
[email protected](autouse=True)
+def direct_native_auth():
+ _direct_config().save()
+
+
def test_codex_reads_base_url_from_user_titlecase_provider(tmp_path: Path) -> None:
"""When the user points Codex at a relay via ``[model_providers.OpenAI]``
(matching their on-disk config.toml literally), the Settings UI must
@@ -138,6 +152,7 @@ def claude_restart_calls(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
return {"ok": True, "message": "refreshed"}
monkeypatch.setattr("vibe.api.restart_backend", restart_backend)
+ monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda *a, **kw: None)
return calls
@@ -601,13 +616,13 @@ def test_save_claude_explicit_auth_token_clears_v2_secret(
cleanup_calls: list[bool] = []
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
- lambda _service=None: cleanup_calls.append(True) or {"ok": True},
+ lambda _service=None, **_ownership: cleanup_calls.append(True) or {"ok": True},
)
from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
from vibe.api import get_claude_auth, save_claude_auth
- cfg = V2Config(
+ cfg = _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -666,7 +681,7 @@ def test_save_claude_auth_reports_partial_when_oauth_cleanup_fails(
monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
- lambda _service=None: {
+ lambda _service=None, **_ownership: {
"ok": True,
"partial": True,
"warning": "oauth_cleanup_failed",
@@ -677,7 +692,7 @@ def test_save_claude_auth_reports_partial_when_oauth_cleanup_fails(
from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
from vibe.api import save_claude_auth
- V2Config(
+ _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -729,7 +744,7 @@ def test_save_claude_auth_restores_pending_oauth_backup_before_writing_new_key(
}
)
- V2Config(
+ _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -740,7 +755,7 @@ def test_save_claude_auth_restores_pending_oauth_backup_before_writing_new_key(
cleanup_calls: list[object] = []
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
- lambda service=None: cleanup_calls.append(service) or {"ok": True},
+ lambda service=None, **_ownership: cleanup_calls.append(service) or {"ok": True},
)
result = save_claude_auth(
@@ -780,13 +795,13 @@ def test_save_claude_explicit_api_key_is_independent_from_base_url(
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
- lambda _service=None: {"ok": True},
+ lambda _service=None, **_ownership: {"ok": True},
)
from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
from vibe.api import save_claude_auth
- V2Config(
+ _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -830,7 +845,7 @@ def test_save_claude_base_url_update_preserves_credential_type(
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
- lambda _service=None: {"ok": True},
+ lambda _service=None, **_ownership: {"ok": True},
)
_write_claude_settings(tmp_path, {"ANTHROPIC_API_KEY": "sk-ant-preserved"})
@@ -838,7 +853,7 @@ def test_save_claude_base_url_update_preserves_credential_type(
from vibe.api import save_claude_auth
from vibe.claude_config import read_claude_settings_env
- config = V2Config(
+ config = _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -885,7 +900,7 @@ def test_save_claude_credential_type_switch_reuses_stored_value(
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
monkeypatch.setattr(
"vibe.api._clear_claude_oauth_credentials_after_api_key_save",
- lambda _service=None: {"ok": True},
+ lambda _service=None, **_ownership: {"ok": True},
)
_write_claude_settings(
tmp_path,
@@ -899,7 +914,7 @@ def test_save_claude_credential_type_switch_reuses_stored_value(
from vibe.api import save_claude_auth
from vibe.claude_config import read_claude_settings_env
- config = V2Config(
+ config = _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -963,7 +978,7 @@ def test_save_claude_auth_keeps_settings_token_over_legacy_v2_key(
from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
from vibe.api import save_claude_auth
- cfg = V2Config(
+ cfg = _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -1011,7 +1026,7 @@ def test_remove_claude_api_key_refreshes_cached_runtime(
from vibe.api import remove_backend_api_key
from vibe.claude_config import read_claude_settings_env
- config = V2Config(
+ config = _direct_config(
mode="self_host",
version="v2",
slack=SlackConfig(bot_token=""),
@@ -1081,6 +1096,7 @@ def test_save_claude_auth_fails_without_overwriting_malformed_settings(
) -> None:
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
+ _direct_config().save()
monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)
claude_dir = tmp_path / ".claude"
claude_dir.mkdir()
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 5f635cd54..6f56bc82a 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -359,6 +359,7 @@ def test_opencode_options_rereads_hub_mode_at_launch_boundary(monkeypatch):
agents=AgentsConfig(),
runtime=RuntimeConfig(default_cwd="."),
)
+ direct_config.model_hub.agents["opencode"].mode = "direct"
hub_config.model_hub.agents["opencode"].mode = "hub"
configs = iter((direct_config, hub_config))
monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
diff --git a/tests/test_watches.py b/tests/test_watches.py
index fc54f383a..feee93ccc 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -56,6 +56,21 @@ TEST_MARKER = "test-watch-worker"
TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)
+class _ControlledWatchClock:
+ """Clock double for the wall-time cooldown branch in the real wait loop."""
+
+ def __init__(self, current: datetime) -> None:
+ self.current = current
+
+ def now(self, tz=None) -> datetime:
+ if tz is None:
+ return self.current.replace(tzinfo=None)
+ return self.current.astimezone(tz)
+
+ def fromisoformat(self, value: str) -> datetime:
+ return datetime.fromisoformat(value)
+
+
def _quiet_waiter_command(summary: str = "") -> list[str]:
"""A waiter that ends a cycle the way the no-event protocol asks it to.
@@ -1694,25 +1709,40 @@ def test_forever_watch_waits_for_previous_follow_up_before_rearming(
monkeypatch.setattr(service, "_run_cycle", fake_run_cycle)
monkeypatch.setattr(watches_module, "WATCH_MIN_REARM_SECONDS", 0.1)
- monkeypatch.setattr(watches_module, "WATCH_FOLLOW_UP_POLL_SECONDS", 0.005)
+ # The production fence uses wall time for the cooldown and polls for both
+ # unsettled Runs and the cooldown boundary. Drive that clock explicitly and
+ # use zero-delay yields so the test never infers elapsed time from a loaded
+ # runner's sleep duration.
+ clock = _ControlledWatchClock(datetime.now(timezone.utc))
+ monkeypatch.setattr(watches_module, "datetime", clock)
+ monkeypatch.setattr(watches_module, "WATCH_FOLLOW_UP_POLL_SECONDS", 0)
service._running = True
service._requires_service_lease = False
async def _run() -> None:
task = asyncio.create_task(service._run_watch(watch.id))
- for _ in range(100):
- if request_store.list_pending():
- break
- await asyncio.sleep(0.01)
+ async def wait_for_pending() -> None:
+ while not request_store.list_pending():
+ await asyncio.sleep(0)
+
+ await asyncio.wait_for(wait_for_pending(), timeout=1)
assert calls == 1
- await asyncio.sleep(0.05)
- assert calls == 1, "an unfinished event Run must hold the waiter closed"
+ for _ in range(8):
+ await asyncio.sleep(0)
+ assert calls == 1, "an unfinished event Run must hold the waiter closed"
request = request_store.list_pending()[0]
claimed = request_store.claim(request.id)
assert claimed is not None
request_store.complete(claimed, ok=True)
- await asyncio.sleep(0.03)
- assert calls == 1, "the post-Run re-arm delay must hold the waiter closed"
+ settled = request_store.get_run(request.id)
+ assert settled is not None
+ assert settled["status"] == "succeeded"
+ completed_at = datetime.fromisoformat(settled["completed_at"])
+ clock.current = completed_at + timedelta(seconds=0.099)
+ for _ in range(8):
+ await asyncio.sleep(0)
+ assert calls == 1, "the cooldown must hold the waiter closed"
+ clock.current = completed_at + timedelta(seconds=0.101)
await asyncio.wait_for(task, timeout=2)
asyncio.run(_run())
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index a314b5d58..32ba12bb4 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -40,6 +40,15 @@ from vibe.claude_config import (
)
+def _direct_config():
+ from config.v2_config import V2Config
+
+ config = V2Config.default()
+ for supply in config.model_hub.agents.values():
+ supply.mode = "direct"
+ return config
+
+
class _Backend:
cli_path = "/usr/bin/echo" # any binary that exists is fine
@@ -74,6 +83,7 @@ def isolated_claude_config_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch)
# resolves config.json from AVIBE_HOME — isolate it so no test
# touches the developer's real ~/.avibe.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))
+ _direct_config().save()
@pytest.fixture
@@ -775,7 +785,7 @@ class _FakeOpencodeServer:
def __init__(self) -> None:
self.next_authorize: dict = {}
self.auth_map: dict = {}
- self.wait_future: asyncio.Future = asyncio.get_event_loop_policy().new_event_loop().create_future()
+ self.wait_future: asyncio.Future | None = None
self.start_calls: list[tuple[str, int, dict]] = []
self.wait_calls: list[tuple[str, int, dict]] = []
self.catalog: dict = {}
@@ -835,6 +845,8 @@ class _FakeOpencodeServer:
async def wait_provider_oauth(self, provider_id, *, method, prompt_answers, timeout):
self.wait_calls.append((provider_id, method, prompt_answers))
+ if self.wait_future is None:
+ self.wait_future = asyncio.get_running_loop().create_future()
return await self.wait_future
@@ -1928,7 +1940,7 @@ def test_nonreset_claude_cancel_and_failed_start_restore_real_credential_files(s
credentials = home / ".credentials.json"
credentials.write_text('{"claudeAiOauth":{"accessToken":"test-old-oauth"}}')
original = credentials.read_bytes()
- V2Config.default().save()
+ _direct_config().save()
logout = AsyncMock(side_effect=AssertionError("non-reset login must not log out"))
monkeypatch.setattr(service, "_run_utility_command", logout)
monkeypatch.setattr(service, "_create_claude_control_client", AsyncMock(return_value=SimpleNamespace()))
@@ -1964,7 +1976,7 @@ def test_nonreset_claude_cancel_and_failed_start_restore_real_credential_files(s
def test_claude_committed_credentials_survive_apply_failure_and_cancel(service, monkeypatch):
from config.v2_config import V2Config
- V2Config.default().save()
+ _direct_config().save()
old = {"ANTHROPIC_API_KEY": "old-test-key"}
restore_claude_settings_env(old)
monkeypatch.setattr(service, "_post_web_success_hook", lambda _backend: (_ for _ in ()).throw(RuntimeError("apply failed")))
@@ -1990,7 +2002,7 @@ def test_claude_committed_credentials_survive_apply_failure_and_cancel(service,
def test_cancel_waits_for_irreversible_commit_before_new_flow_can_start(service, monkeypatch):
from config.v2_config import V2Config
- V2Config.default().save()
+ _direct_config().save()
restore_claude_settings_env({"ANTHROPIC_API_KEY": "test-old"})
async def run():
diff --git a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
new file mode 100644
index 000000000..8d1099330
--- /dev/null
+++ b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
@@ -0,0 +1,158 @@
+import { expect, test } from '@playwright/test';
+import { ORIGIN, serveProduct } from './support';
+
+// Exercise the actual App/AuthGuard/Settings overlay/Wizard boundary. All
+// server responses are fixture-owned; the Vite server has a dead backend.
+// The Python connection tests separately establish the readiness producer.
+for (const width of [1200, 390]) {
+ test(`Hub takeover returns to the same setup step and permits completion at ${width}px`, async ({ page }, info) => {
+ await page.setViewportSize({ width, height: 844 });
+ const denied = await serveProduct(page);
+ const nativeRequests: string[] = [];
+ const writes: string[] = [];
+ const applied: string[][] = [];
+ const observedReady: boolean[] = [];
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ let migrated = false;
+ let completed = false;
+ const source = {
+ id: 'src_fixture_claude', kind: 'api_key', vendor: 'anthropic',
+ display_name: 'Migrated Claude', protocol: 'anthropic', base_url: null,
+ supply_channel: 'hub', billing: 'metered', masked_credential: 'sk-…fixture',
+ state: { status: 'standby', retry_at: null, detail_key: null },
+ models: [], last_discovered_at: null,
+ };
+ const config = () => ({
+ mode: 'v2', setup_completed: completed, setup_state: { needs_setup: !completed },
+ capabilities: { model_hub: { enabled: true } },
+ platforms: { enabled: [] },
+ agents: Object.fromEntries(['claude', 'codex', 'opencode'].map((backend) => [
+ backend, { enabled: backend === 'claude', cli_path: backend },
+ ])),
+ agent: { default_cwd: '/fixture/work' },
+ model_hub: { enabled: true, runtime_default_applied: true },
+ });
+ const supply = () => ({
+ backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed',
+ sources: { order: migrated ? [source.id] : [], eligibility: [] },
+ routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null,
+ model_supply: [], supply_status: migrated ? 'ok' : 'unavailable',
+ });
+ const items = () => migrated ? [] : [{
+ id: 'mig_claude_fixture', backend: 'claude', kind: 'api_key',
+ masked_detail: 'sk-…fixture', proposed_action: 'import', selected: true,
+ notes_key: null, vendor: 'anthropic', display_name: 'Anthropic',
+ masked_credential: 'sk-…fixture',
+ }];
+ await page.addInitScript(() => localStorage.setItem('i18nextLng', 'en'));
+ await page.route(`${ORIGIN}/api/**`, async (route) => {
+ const request = route.request();
+ const path = new URL(request.url()).pathname;
+ const answer = (json: unknown) => route.fulfill({ json });
+ if (request.method() !== 'GET') writes.push(`${request.method()} ${path}`);
+ if (/\/backend\/[^/]+\/auth(?:\/|$)/.test(path)) {
+ nativeRequests.push(`${request.method()} ${path}`);
+ return answer({ ok: false, error: 'native_auth_hub_owned', reauth_channel: 'hub' });
+ }
+ if (path === '/api/config') {
+ if (request.method() === 'POST') {
+ const body = request.postDataJSON();
+ if (body.setup_completed === true) completed = true;
+ }
+ return answer(config());
+ }
+ if (path === '/api/session') return answer({ remote: false, instance_kind: 'personal' });
+ if (path === '/api/csrf-token') return answer({ csrf_token: 'fixture-token' });
+ if (path === '/api/version') return answer({
+ current: '1.0.0', latest: '1.0.0', has_update: false, error: null,
+ });
+ if (path === '/api/models/sources') return answer({ ok: true, sources: migrated ? [source] : [] });
+ if (path === '/api/models/agents') return answer({ ok: true, agents: [supply()] });
+ if (path === '/api/models/agents/claude/sources') return answer({ ok: true, agent: supply() });
+ if (path === '/api/models/agents/claude/chains') return answer({ ok: true, chains: [] });
+ if (path === '/api/models/runtime/status') return answer({
+ ok: true,
+ runtime: {
+ contract_version: 10, enabled: true, host_platform: 'linux',
+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'a'.repeat(40), assets: [] },
+ status: { installed_version: 'fixture', verified: true, health: 'ok' },
+ },
+ });
+ if (path === '/api/models/events') return answer({ ok: true, events: [] });
+ if (path === '/api/models/migration/scan') return answer({ ok: true, scan: { items: items() } });
+ if (path === '/api/models/migration/apply') {
+ const ids = request.postDataJSON().item_ids;
+ applied.push(ids);
+ migrated = true;
+ return answer({ ok: true, applied: ids.length, sources: [source] });
+ }
+ if (/\/api\/backend\/[^/]+\/connection$/.test(path)) {
+ const backend = path.split('/')[3];
+ const ready = backend === 'claude' && migrated;
+ if (backend === 'claude') observedReady.push(ready);
+ return answer({
+ ok: true, backend, installed: true, enabled: backend === 'claude',
+ supply_mode: 'hub', auth: ready ? 'api_key' : 'none',
+ application: 'applied', ready, entry_eligible: ready,
+ });
+ }
+ if (path === '/api/agents') return answer({
+ ok: true, default_agent_name: 'claude', agents: [{
+ id: 'fixture-agent', name: 'claude', backend: 'claude', enabled: true,
+ archived: false, description: '', model: null,
+ }],
+ });
+ // These unrelated app-shell reads are empty, not live-service fallbacks.
+ if (path === '/api/memory/status') return answer({ ok: true, enabled: false });
+ if (path === '/api/projects') return answer({ ok: true, projects: [] });
+ if (path === '/api/scopes') return answer({ ok: true, scopes: [] });
+ if (path === '/api/inbox') return answer({
+ sessions: [], next_cursor: null, unread_by_session: {},
+ unread_total: 0, unread_sessions: 0,
+ });
+ if (path === '/api/events') return route.fulfill({ status: 204 });
+ return route.fallback();
+ });
+
+ await page.goto('/setup');
+ await page.getByRole('button', { name: 'Get started', exact: true }).click();
+ const enter = page.getByRole('button', { name: 'Enter workspace', exact: true });
+ await expect(enter).toBeDisabled();
+ await expect.poll(() => observedReady.length).toBeGreaterThan(0);
+ const wizard = await page.locator('.onboarding-assistants').elementHandle();
+ const claude = page.getByLabel('Claude Code', { exact: true });
+ await expect(claude.getByRole('button', { name: 'Add API Key', exact: true })).toHaveCount(0);
+ await claude.getByRole('button', { name: 'Open Model Hub', exact: true }).click();
+ await expect(page).toHaveURL(/\/settings\/models$/);
+ await page.getByRole('button', { name: 'Migrate configuration', exact: true }).click();
+ const migration = page.getByRole('dialog').filter({ has: page.getByRole('heading', { name: 'Migrate to the Model Hub', exact: true }) });
+ await expect(migration).toBeVisible();
+ await migration.getByRole('button', { name: 'Start migration', exact: true }).click();
+ await expect.poll(() => applied).toEqual([['mig_claude_fixture']]);
+ await expect(migration).toHaveCount(0);
+ await page.screenshot({ path: info.outputPath(`hub-migrated-${width}.png`) });
+
+ // Actual browser history closes both the desktop sheet and mobile surface.
+ await page.goBack();
+ await expect(page).toHaveURL(/\/setup$/);
+ await expect(page.locator('.onboarding-assistants')).toBeVisible();
+ expect(await wizard!.evaluate((node) => node.isConnected)).toBe(true);
+ await expect(enter).toBeEnabled();
+ await expect(page.getByRole('button', { name: 'Review and migrate', exact: true })).toHaveCount(0);
+ expect(observedReady).toContain(true);
+ await page.screenshot({ path: info.outputPath(`setup-hub-ready-${width}.png`), fullPage: true });
+ await enter.click();
+ await expect.poll(() => completed).toBe(true);
+ await expect(page).toHaveURL(`${ORIGIN}/`);
+ expect(pageErrors).toEqual([]);
+ expect(nativeRequests).toEqual([]);
+ expect(writes.filter((write) => !write.endsWith('/api/models/migration/scan'))).toEqual([
+ 'POST /api/models/migration/apply',
+ 'POST /api/config',
+ ]);
+ // Initial/return flow must never need a running backend. App-shell reads
+ // after completion are not part of this test's connection contract.
+ expect(denied.filter((request) => /\/backend\/.*\/auth/.test(request))).toEqual([]);
+ });
+}
diff --git a/ui/src/App.remoteAuth.test.tsx b/ui/src/App.remoteAuth.test.tsx
index 112140373..061f8cb64 100644
--- a/ui/src/App.remoteAuth.test.tsx
+++ b/ui/src/App.remoteAuth.test.tsx
@@ -203,6 +203,27 @@ describe('AuthGuard setup-bypass authorization', () => {
expect(await screen.findByText('diagnostics-page')).toBeTruthy();
expect(screen.queryByText('workbench-home')).toBeNull();
});
+
+ it('lets an authenticated owner open Model Hub before setup without completing setup', async () => {
+ api.getAuthSession.mockResolvedValue(localOwnerSession);
+ api.getConfig.mockResolvedValue({
+ mode: 'v2',
+ setup_state: { needs_setup: true },
+ capabilities: { model_hub: { enabled: true } },
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/settings/models']}>
+ <AuthGuard>
+ <div>model-hub-page</div>
+ </AuthGuard>
+ </MemoryRouter>,
+ );
+
+ expect(await screen.findByText('model-hub-page')).toBeTruthy();
+ expect(api.getConfig).toHaveBeenCalledOnce();
+ expect(api.mutateConfig).not.toHaveBeenCalled();
+ });
});
describe('AuthGuard setup access parity (AUTH-SETUP-405)', () => {
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 6eaf8bcb2..64bc3abc3 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -92,6 +92,8 @@ const SettingsModelsPage = lazy(() =>
import('./components/settings/models/SettingsModelsPage').then((m) => ({ default: m.SettingsModelsPage })),
);
import { ModelHubCapabilityGate } from './components/settings/models/ModelHubCapabilityGate';
+import { MODEL_HUB_SETTINGS_PATH } from './components/settings/models/modelHubRoutes';
+import { settingsOverlayOriginFromState } from './lib/settingsOverlay';
import { hasConfiguredPlatformCredentials } from './lib/platforms';
import { isIosDevice, isStandalonePwa } from './lib/platform';
import {
@@ -283,6 +285,7 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
const [authCheckVersion, setAuthCheckVersion] = useState(0);
const [authorizationSession, setAuthorizationSession] = useState<SessionInfo | null>(null);
const [authorizationUnavailable, setAuthorizationUnavailable] = useState(false);
+ const [setupModelHubAllowed, setSetupModelHubAllowed] = useState(false);
const authorizationUnavailableRef = useRef(false);
const bypassSetupGuard = isSetupCheckBypassed(location.pathname);
// Re-validate only when crossing the setup boundary, not on every
@@ -290,7 +293,11 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
// off /setup; that pathname flip re-runs the effect so the stale
// `needs-setup` status refreshes to `ready` instead of bouncing the
// user straight back to /setup.
- const isSetupRoute = location.pathname === '/setup';
+ // Model Hub opened over the wizard is still the same setup visit. Keep the
+ // wizard mounted so closing Settings returns to its current step.
+ const isSetupRoute = location.pathname === '/setup'
+ || (location.pathname === MODEL_HUB_SETTINGS_PATH
+ && settingsOverlayOriginFromState(location.state)?.location.pathname === '/setup');
const previousIsSetupRouteRef = useRef(isSetupRoute);
useEffect(() => {
@@ -356,6 +363,7 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
// the fresh config resolves. Showing Loading for that single
// transition is fine — it's the setup boundary, not every nav.
setGuardStatus('loading');
+ setSetupModelHubAllowed(false);
checkRemoteAuthForPath(location.pathname, getAuthSession).then(({ session, loginRequired, checkSetup }) => {
if (cancelled) return;
@@ -396,6 +404,10 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
}
return getConfig().then(config => {
if (cancelled) return;
+ // Only successful config/session reads can grant this narrow
+ // setup repair route. Unlike Diagnostics it is not a bypass.
+ setSetupModelHubAllowed(Boolean(config?.mode
+ && 'capabilities' in session && session.capabilities?.can_manage_instance));
const setupState = config?.setup_state;
const setupReady = typeof setupState?.needs_setup === 'boolean'
? setupState.needs_setup === false
@@ -489,7 +501,8 @@ export const AuthGuard = ({ children }: { children: ReactNode }) => {
return <AccessBlocked code={blockedCode} />;
}
if (guardStatus === 'needs-setup' && !bypassSetupGuard) {
- if (location.pathname === '/setup' && authorizationSession) {
+ if (authorizationSession && (location.pathname === '/setup'
+ || (location.pathname === MODEL_HUB_SETTINGS_PATH && setupModelHubAllowed))) {
return <InstanceAuthorizationProvider session={authorizationSession}>{children}</InstanceAuthorizationProvider>;
}
// A wizard finish navigates from /setup to / before the re-validation
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index d89cee92e..05d111c1c 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -295,8 +295,15 @@ export const AppShell: React.FC = () => {
return <Navigate to="/" replace />;
}
- if (location.pathname === '/setup') {
- return <><ConfigRecoveryNotice config={config} /><Outlet /></>;
+ if (location.pathname === '/setup' || settingsOverlayOrigin?.location.pathname === '/setup') {
+ return (
+ <>
+ <ConfigRecoveryNotice config={config} />
+ <SettingsOverlayNavigationBoundary desktop={isDesktop}>
+ <Outlet />
+ </SettingsOverlayNavigationBoundary>
+ </>
+ );
}
// Workbench mobile tabs flatten the (desktop-only) WorkbenchSidebar into a
diff --git a/ui/src/components/onboarding/AssistantRow.tsx b/ui/src/components/onboarding/AssistantRow.tsx
index 6b2a65752..3be6e6e18 100644
--- a/ui/src/components/onboarding/AssistantRow.tsx
+++ b/ui/src/components/onboarding/AssistantRow.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react';
-import { Check, Download, RefreshCw, Sliders } from 'lucide-react';
+import { Check, Download, ExternalLink, RefreshCw, Sliders } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { BackendIcon } from '../visual';
import { Button } from '../ui/button';
@@ -25,7 +25,7 @@ export interface AssistantRowProps {
connectionError?: string;
configuringDisabled?: boolean;
/** Presentation only. The connection owner must supply confirmed state. */
- connection?: 'subscription' | 'api_key';
+ connection?: 'subscription' | 'api_key' | 'hub';
}
/**
@@ -67,7 +67,8 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
</div>
<div className="onboarding-assistant-body">
<p className="onboarding-assistant-note" title={t(`onboarding.setup.${backend}Description`)}>
- {t(connection ? `onboarding.setup.${connection}` : `onboarding.setup.${backend}Description`)}
+ {connection === 'hub' ? t('settings.backends.nativeAuthHubOwned')
+ : t(connection ? `onboarding.setup.${connection}` : `onboarding.setup.${backend}Description`)}
</p>
<div className="onboarding-assistant-actions">
{status === 'missing' && <Button variant="secondary" size="sm" className="h-[34px]" onClick={onInstall} disabled={installing || detecting}>
@@ -76,8 +77,9 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
</Button>}
{status === 'unknown' && !detecting && <Button variant="secondary" size="sm" onClick={onDetect}><RefreshCw size={14} />{t('common.retry')}</Button>}
<Button variant="secondary" size="sm" className="h-[34px]" onClick={onConfigure} disabled={configuringDisabled || installing || detecting}>
- {connection ? <Check size={14} className="text-mint-ink" /> : <Sliders size={14} />}
- {t(connection ? `onboarding.setup.${connection}Connected` : 'onboarding.connection.addSubscription')}
+ {connection === 'hub' ? <ExternalLink size={14} /> : connection ? <Check size={14} className="text-mint-ink" /> : <Sliders size={14} />}
+ {connection === 'hub' ? t('settings.backends.openModelHub')
+ : t(connection ? `onboarding.setup.${connection}Connected` : 'onboarding.connection.addSubscription')}
</Button>
{!connection && onAddKey && <Button variant="secondary" size="sm" className="h-[34px]" onClick={onAddKey} disabled={configuringDisabled || installing || detecting}>{t('onboarding.connection.addKey')}</Button>}
</div>
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index 6bcdb927b..5978b5aab 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -2,12 +2,13 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { createInstance } from 'i18next';
import { I18nextProvider } from 'react-i18next';
-import { MemoryRouter } from 'react-router-dom';
+import { MemoryRouter, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentDetection } from '../steps/AgentDetection';
import { AssistantRow } from './AssistantRow';
import en from '../../i18n/en.json';
import type { BackendConnectionState } from '../../context/ApiContext';
+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
const mock = vi.hoisted(() => ({ api: {
detectCli: vi.fn(), installAgent: vi.fn(), getConfig: vi.fn(), getBackendRuntime: vi.fn(), getBackendConnection: vi.fn(), mutateConfig: vi.fn(), getClaudeAuth: vi.fn(), getCodexAuth: vi.fn(), getOpencodeProviders: vi.fn(),
@@ -19,7 +20,8 @@ vi.mock('../settings/shared/useOpencodePermission', () => ({ useOpencodePermissi
vi.mock('../settings/providers/BackendProviderConfig', () => ({ BackendProviderConfig: ({ backend }: { backend: string }) => <div>Existing provider: {backend}</div> }));
const i18n = createInstance();
await i18n.init({ lng: 'en', resources: { en: { translation: en } }, interpolation: { escapeValue: false } });
-const wrap = (node: React.ReactNode) => <MemoryRouter><I18nextProvider i18n={i18n}>{node}</I18nextProvider></MemoryRouter>;
+const LocationProbe = () => <span data-testid="location">{useLocation().pathname}</span>;
+const wrap = (node: React.ReactNode, active = true) => <MemoryRouter><I18nextProvider i18n={i18n}><RouteSurfaceActiveContext.Provider value={active}>{node}</RouteSurfaceActiveContext.Provider><LocationProbe /></I18nextProvider></MemoryRouter>;
const data = () => ({ __onboardingDetected: true, agents: Object.fromEntries(['claude', 'codex', 'opencode'].map((name) => [name, { enabled: true, cli_path: name, status: 'missing' }])) });
const row = (name: string) => within(screen.getByLabelText(name));
beforeEach(() => {
@@ -84,6 +86,55 @@ describe('assistant installation presentation', () => {
fireEvent.click(row('Claude Code').getByRole('button', { name: /Add subscription|API Key connected|Subscription connected/ }));
expect(await screen.findByRole('dialog')).toBeTruthy();
});
+ it('refreshes connection readiness when a retained settings surface returns', async () => {
+ const saved = data(); saved.agents.claude.status = 'ok';
+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({
+ ok: true,
+ backend,
+ installed: true,
+ enabled: true,
+ auth: 'none',
+ application: 'applied',
+ ready: false,
+ entry_eligible: false,
+ }));
+ const view = render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />, false));
+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(3));
+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({
+ ok: true,
+ backend,
+ installed: true,
+ enabled: true,
+ auth: 'api_key',
+ application: 'applied',
+ ready: true,
+ entry_eligible: true,
+ }));
+ view.rerender(wrap(<AgentDetection data={saved} onNext={vi.fn()} />, true));
+ await waitFor(() => expect(mock.api.getBackendConnection).toHaveBeenCalledTimes(6));
+ expect(await row('Claude Code').findByRole('button', { name: 'API Key connected' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);
+ });
+ it('opens Model Hub directly when the backend is already Hub-owned', async () => {
+ const saved = data(); saved.agents.claude.status = 'ok';
+ mock.api.getBackendConnection.mockImplementation(async (backend) => ({
+ ok: true,
+ backend,
+ installed: true,
+ enabled: true,
+ auth: 'none',
+ application: 'applied',
+ ready: false,
+ entry_eligible: false,
+ supply_mode: 'hub',
+ }));
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ const action = await row('Claude Code').findByRole('button', { name: en.settings.backends.openModelHub });
+ fireEvent.click(action);
+ await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/settings/models'));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(true);
+ });
it('an available update keeps Continue and configuration usable', async () => {
const saved = data(); saved.agents.claude.status = 'ok';
mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: true, current_version: '1', latest_version: '2' });
diff --git a/ui/src/components/onboarding/BackendConnection.test.tsx b/ui/src/components/onboarding/BackendConnection.test.tsx
index 1f665fe87..e13d5ad89 100644
--- a/ui/src/components/onboarding/BackendConnection.test.tsx
+++ b/ui/src/components/onboarding/BackendConnection.test.tsx
@@ -329,6 +329,7 @@ describe('shared Settings and onboarding connection owner', () => {
const stale = deferred<CodexAuthState>();
mock.api.getCodexAuth.mockReturnValueOnce(stale.promise);
view.rerender(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" connectionRevision={1} />));
+ await waitFor(() => expect(mock.api.getCodexAuth).toHaveBeenCalledTimes(2));
fireEvent.change(screen.getByLabelText(en.onboarding.connection.baseUrl), { target: { value: 'https://draft.invalid' } });
mock.api.getCodexAuth.mockResolvedValue(codexNative({ active_auth_mode: 'none', has_api_key: false, has_chatgpt_tokens: false }));
view.rerender(wrap(<BackendConnectionForm backend="codex" initialMethod="api_key" connectionRevision={2} />));
@@ -378,8 +379,8 @@ describe('shared Settings and onboarding connection owner', () => {
const application = deferred<BackendConnectionState>();
mock.api.getBackendConnection.mockReturnValue(application.promise);
fireEvent.click(cleanupButton);
- await screen.findByText('sk-•••old');
await act(async () => application.resolve(connection({ application: 'failed', ready: false, entry_eligible: false, message: 'fixture apply failed' })));
+ await screen.findByText('sk-•••old');
expect((await screen.findByRole('alert')).textContent).toContain('fixture apply failed');
expect(screen.queryByRole('button', { name: en.settings.backends.oauthCleanStoredCredentials })).toBeNull();
await waitFor(() => expect(mock.toast.mock.calls.some(([message, kind]) => kind === 'warning' && message.includes('fixture cleanup warning'))).toBe(true));
diff --git a/ui/src/components/onboarding/ImportKeysNotice.test.tsx b/ui/src/components/onboarding/ImportKeysNotice.test.tsx
index 6291cc1ae..8448f0885 100644
--- a/ui/src/components/onboarding/ImportKeysNotice.test.tsx
+++ b/ui/src/components/onboarding/ImportKeysNotice.test.tsx
@@ -17,6 +17,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import type { MigrationItem } from '@/components/settings/models/types';
+import { RouteSurfaceActiveContext } from '@/lib/routeSurfaceActivity';
const showToast = vi.hoisted(() => vi.fn());
const capability = vi.hoisted(() => ({ value: true as boolean | null }));
@@ -127,7 +128,7 @@ const renderNotice = (onApplied?: (applied: number) => void) =>
);
const openDialog = async (user: ReturnType<typeof userEvent.setup>) => {
- await user.click(await screen.findByRole('button', { name: 'Review and import' }));
+ await user.click(await screen.findByRole('button', { name: 'Review and migrate' }));
return screen.findByRole('dialog');
};
@@ -145,12 +146,32 @@ afterEach(() => {
});
describe('ImportKeysNotice', () => {
+ it('rescans on return from Settings without remounting the setup notice', async () => {
+ serve([CLAUDE_KEY]);
+ const notice = (active: boolean) => (
+ <I18nextProvider i18n={i18n}>
+ <RouteSurfaceActiveContext.Provider value={active}>
+ <ImportKeysNotice />
+ </RouteSurfaceActiveContext.Provider>
+ </I18nextProvider>
+ );
+ const view = render(notice(true));
+ expect(await screen.findByText('Found 1 API key to import into Model Hub')).toBeTruthy();
+ view.rerender(notice(false));
+ stored = [];
+ expect(modelsApi.scanMigration).toHaveBeenCalledTimes(1);
+ view.rerender(notice(true));
+ await waitFor(() => expect(modelsApi.scanMigration).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Review and migrate' })).toBeNull());
+ expect(modelsApi.applyMigration).not.toHaveBeenCalled();
+ });
+
it('counts the importable keys — not the rows the scan returned', async () => {
serve(FULL_SCAN);
renderNotice();
// Three of five: the subscription and the reauth row are not offers.
- expect(await screen.findByText('Found 3 API keys to import into Model Gateway')).toBeTruthy();
+ expect(await screen.findByText('Found 3 API keys to import into Model Hub')).toBeTruthy();
});
it('offers exactly the rows it counted, and no subscription or reauth row', async () => {
@@ -160,17 +181,19 @@ describe('ImportKeysNotice', () => {
const dialog = await openDialog(user);
- expect(within(dialog).getByText('Anthropic')).toBeTruthy();
+ expect(within(dialog).getAllByText('Anthropic').length).toBeGreaterThan(0);
// `display_name` was only the provider id; the shared brand mapping names it.
expect(within(dialog).getByText('Zhipu AI')).toBeTruthy();
// No metadata at all: the composed detail stays the title rather than a
// provider guessed from the backend that held the key.
expect(within(dialog).getByText('自建中转 · sk-…abcd')).toBeTruthy();
- expect(within(dialog).queryByText('Claude 账号登录(OAuth)')).toBeNull();
- expect(within(dialog).queryByText(/Keep native/)).toBeNull();
+ expect(within(dialog).getByText(/Claude 账号登录/)).toBeTruthy();
+ expect(
+ (within(dialog).getByRole('checkbox', { name: /Claude 账号登录/ }) as HTMLButtonElement).disabled,
+ ).toBe(true);
expect(within(dialog).queryByText(/Re-authorize/)).toBeNull();
- expect(within(dialog).getByRole('button', { name: /Import 3 items/ })).toBeTruthy();
+ expect(within(dialog).getByRole('button', { name: 'Start migration' })).toBeTruthy();
});
it('MH-MIG-004: submits only the rows still ticked', async () => {
@@ -180,8 +203,8 @@ describe('ImportKeysNotice', () => {
const user = userEvent.setup();
const dialog = await openDialog(user);
- await user.click(within(dialog).getByRole('checkbox', { name: /Anthropic/ }));
- await user.click(within(dialog).getByRole('button', { name: /Import 2 items/ }));
+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…dd3c/ }));
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
await waitFor(() => expect(applied).toHaveLength(1));
expect(applied[0]).toEqual(['mig_opencode_zhipu', 'mig_opencode_legacy']);
@@ -194,27 +217,32 @@ describe('ImportKeysNotice', () => {
const user = userEvent.setup();
const dialog = await openDialog(user);
- await user.click(within(dialog).getByRole('checkbox', { name: /Anthropic/ }));
- await user.click(within(dialog).getByRole('button', { name: /Import 2 items/ }));
+ await user.click(within(dialog).getByRole('checkbox', { name: /sk-…dd3c/ }));
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
// The remainder is the server's answer after the rescan, not a subtraction.
- expect(await screen.findByText('Imported 2 · 1 API key still available')).toBeTruthy();
+ expect(await screen.findByText('Migrated 2 · 1 API key still available')).toBeTruthy();
// A partial selection can still be finished from here.
- expect(screen.getByRole('button', { name: 'Review and import' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Review and migrate' })).toBeTruthy();
});
- it('reports a finished import with no review action left', async () => {
+ it('keeps a blocked CLI group available after importing independent keys', async () => {
serve(FULL_SCAN);
renderNotice();
const user = userEvent.setup();
const dialog = await openDialog(user);
- await user.click(within(dialog).getByRole('button', { name: /Import 3 items/ }));
-
- expect(await screen.findByText('Imported 3 API keys into Model Gateway')).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'Review and import' })).toBeNull();
- // The subscription and the reauth row are still on this machine, untouched.
- expect(stored.map((i) => i.id)).toEqual(['mig_claude_oauth', 'mig_codex_reauth']);
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+
+ expect(await screen.findByText('Migrated 2 · 1 API key still available')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Review and migrate' })).toBeTruthy();
+ // The blocked Claude group remains on this machine, including its import
+ // row, and the unrelated reauth row is untouched.
+ expect(stored.map((i) => i.id)).toEqual([
+ 'mig_claude_key',
+ 'mig_claude_oauth',
+ 'mig_codex_reauth',
+ ]);
});
it('remembers a dismissal so the same keys do not ask again', async () => {
@@ -243,7 +271,7 @@ describe('ImportKeysNotice', () => {
stored = [...stored, { ...CLAUDE_KEY, id: 'mig_claude_key_2', masked_detail: 'sk-…7a10' }];
renderNotice();
- expect(await screen.findByText('Found 4 API keys to import into Model Gateway')).toBeTruthy();
+ expect(await screen.findByText('Found 4 API keys to import into Model Hub')).toBeTruthy();
});
it('says nothing when there is nothing to import', async () => {
diff --git a/ui/src/components/onboarding/ImportKeysNotice.tsx b/ui/src/components/onboarding/ImportKeysNotice.tsx
index a4f0441ba..ced74757a 100644
--- a/ui/src/components/onboarding/ImportKeysNotice.tsx
+++ b/ui/src/components/onboarding/ImportKeysNotice.tsx
@@ -1,13 +1,11 @@
// Setup's API-key import offer: one line under the assistant list saying how many
-// keys already on this machine the Model Gateway can take over, with a way to look
+// keys already on this machine Model Hub can take over, with a way to look
// at them before anything happens.
//
-// It is deliberately narrower than the settings migration. That surface legitimately
-// offers native OAuth rows and `keep_native`, which is a real applied action there;
-// this one is about keys and only keys, so the sentence, the rows in the dialog, the
-// batch submitted and the count left afterwards all read the single
-// `isImportableKey` predicate. A number produced by a different rule than the rows
-// behind it is the failure this shape exists to make impossible.
+// It is deliberately narrower than the settings migration: this entry is about
+// keys only, while OAuth takeover and re-authentication stay in Settings. The
+// sentence, the rows in the dialog, the batch submitted and the count left
+// afterwards all read the single `isImportableKey` predicate.
//
// It stays visible after an import to say what happened and what is left, so a
// partial selection can be finished without hunting for the entry again.
@@ -22,6 +20,7 @@ import { importableKeys, isImportableKey, scanMigrationWhenEnabled } from '@/com
import type { MigrationItem } from '@/components/settings/models/types';
import { useModelHubCapability } from '@/components/settings/models/useModelHubCapability';
import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';
+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
export const ImportKeysNotice: React.FC<{
/** Bubble the applied count so the host step can refresh assistants/sources. */
@@ -29,6 +28,7 @@ export const ImportKeysNotice: React.FC<{
}> = ({ onApplied }) => {
const { t } = useTranslation();
const modelHubEnabled = useModelHubCapability();
+ const routeSurfaceActive = useRouteSurfaceActive();
const [candidates, setCandidates] = React.useState<MigrationItem[]>([]);
const [imported, setImported] = React.useState(0);
@@ -48,6 +48,9 @@ export const ImportKeysNotice: React.FC<{
setCandidates([]);
return;
}
+ // Settings retains the wizard. Refresh its offer when it becomes visible
+ // again, including migrations performed outside this notice's dialog.
+ if (!routeSurfaceActive) return;
let cancelled = false;
scanMigrationWhenEnabled(true)
.then((scan) => {
@@ -67,7 +70,7 @@ export const ImportKeysNotice: React.FC<{
return () => {
cancelled = true;
};
- }, [modelHubEnabled, scanToken]);
+ }, [modelHubEnabled, routeSurfaceActive, scanToken]);
const remaining = candidates.length;
if (modelHubEnabled !== true || dismissed) return null;
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index f1c00ad4c..2a01ef25a 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -9,7 +9,9 @@ import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from './oauth/OAuthF
import { useApi, type OAuthWebMutationResult } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { surfaceBackendNotices } from './shared/surfaceBackendNotices';
+import { HubOwnedAuthNotice } from './shared/HubOwnedAuthNotice';
import { errorMessage } from '@/lib/errorMessage';
+import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';
type Backend = 'claude' | 'codex' | 'opencode';
@@ -88,9 +90,10 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
const { showToast } = useToast();
const { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError,
- startFlow, cancelFlow, submitCallback, resetToIdle, copyUrl, copyDeviceCode, isActive } =
+ startFlow, cancelFlow, submitCallback, resetToIdle, copyUrl, copyDeviceCode, isActive, hubOwnedAuth } =
useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFailure, onCancel, onActiveChange });
const [removing, setRemoving] = useState(false);
+ const [removeHubOwnedAuth, setRemoveHubOwnedAuth] = useState(false);
const removalOwner = useRef({ mounted: true, busy: false });
useEffect(() => {
const owner = removalOwner.current; owner.mounted = true;
@@ -107,6 +110,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
if (removalOwner.current.busy) return;
removalOwner.current.busy = true;
setRemoving(true);
+ setRemoveHubOwnedAuth(false);
onActiveChange?.(true);
setError(null);
try {
@@ -116,6 +120,11 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
: await api.removeBackendAuth(backend);
if (!removalOwner.current.mounted) return;
if (!result.ok) {
+ if (isNativeAuthHubOwned(result)) {
+ setRemoveHubOwnedAuth(true);
+ await onActiveChange?.(false);
+ return;
+ }
showToast(
t('settings.backends.oauthRemoveFailed', {
detail: result.error || result.detail || 'unknown',
@@ -218,7 +227,9 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
</div>
)}
- {error && (
+ {(hubOwnedAuth || removeHubOwnedAuth) && <HubOwnedAuthNotice onNavigate={onCancel} />}
+
+ {error && !hubOwnedAuth && !removeHubOwnedAuth && (
<div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/[0.08] px-3 py-2">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0 text-destructive-ink" />
<p className="text-[12px] leading-relaxed text-destructive-ink">
@@ -312,7 +323,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
type="button"
variant="brand"
size="default"
- onClick={() => void startFlow()}
+ onClick={() => { setRemoveHubOwnedAuth(false); void startFlow(); }}
disabled={starting || removing}
>
<LogIn className="size-3.5" />
diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsx
index bb4f4a3b2..7f81018c6 100644
--- a/ui/src/components/settings/BackendTestPanel.tsx
+++ b/ui/src/components/settings/BackendTestPanel.tsx
@@ -10,6 +10,8 @@ import { useApi } from '@/context/ApiContext';
import type { BackendAuthTestResult } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { errorMessage } from '@/lib/errorMessage';
+import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';
+import { HubOwnedAuthNotice } from './shared/HubOwnedAuthNotice';
type Backend = 'claude' | 'codex';
@@ -100,7 +102,7 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
t('settings.backends.testConnectionSuccessToast', { ms: result.duration_ms ?? '?' }),
'success',
);
- } else {
+ } else if (!isNativeAuthHubOwned(result)) {
showToast(failureSentence(result), 'error');
}
} catch (err) {
@@ -114,6 +116,7 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
const resultLine = (() => {
if (!lastResult) return null;
+ if (isNativeAuthHubOwned(lastResult)) return null;
if (lastResult.ok) {
return t('settings.backends.testConnectionLastOk', {
ms: lastResult.duration_ms ?? '?',
@@ -187,6 +190,8 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
</div>
</div>
+ {lastResult && isNativeAuthHubOwned(lastResult) && <HubOwnedAuthNotice />}
+
{/* Show what the model actually said on success — without this the
user only sees "ok · 312 ms" and has to trust us that the
round-trip went through. The excerpt is server-side trimmed to
@@ -207,7 +212,7 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
user at a non-clickable toast. Previously the i18n copy said
"click the toast to see raw output" but no such affordance
existed. */}
- {lastResult && !lastResult.ok && lastResult.detail && (
+ {lastResult && !lastResult.ok && !isNativeAuthHubOwned(lastResult) && lastResult.detail && (
<details className="rounded-md border border-destructive/30 bg-destructive/[0.04] px-3 py-2 [&[open]>summary]:mb-2">
<summary className="cursor-pointer font-mono text-[11px] uppercase tracking-wide text-destructive-ink">
{t('settings.backends.testConnectionRawOutputLabel')}
diff --git a/ui/src/components/settings/OpencodeProviderTestPanel.tsx b/ui/src/components/settings/OpencodeProviderTestPanel.tsx
index 4c556ab3c..83f9b0bf0 100644
--- a/ui/src/components/settings/OpencodeProviderTestPanel.tsx
+++ b/ui/src/components/settings/OpencodeProviderTestPanel.tsx
@@ -10,6 +10,8 @@ import { useApi } from '@/context/ApiContext';
import type { BackendAuthTestResult } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { errorMessage } from '@/lib/errorMessage';
+import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';
+import { HubOwnedAuthNotice } from './shared/HubOwnedAuthNotice';
export type OpencodeProviderTestPanelProps = {
providerId: string;
@@ -86,7 +88,7 @@ export const OpencodeProviderTestPanel: React.FC<OpencodeProviderTestPanelProps>
t('settings.backends.testConnectionSuccessToast', { ms: result.duration_ms ?? '?' }),
'success',
);
- } else {
+ } else if (!isNativeAuthHubOwned(result)) {
showToast(failureSentence(result), 'error');
}
} catch (err) {
@@ -103,6 +105,7 @@ export const OpencodeProviderTestPanel: React.FC<OpencodeProviderTestPanelProps>
const resultLine = (() => {
if (!lastResult) return null;
+ if (isNativeAuthHubOwned(lastResult)) return null;
if (lastResult.ok) {
return t('settings.backends.testConnectionLastOk', {
ms: lastResult.duration_ms ?? '?',
@@ -159,6 +162,7 @@ export const OpencodeProviderTestPanel: React.FC<OpencodeProviderTestPanelProps>
{testing ? t('common.testing') : t('settings.backends.testConnectionRun')}
</Button>
</div>
+ {lastResult && isNativeAuthHubOwned(lastResult) && <HubOwnedAuthNotice />}
{resultLine && (
<p
className={clsx(
@@ -179,7 +183,7 @@ export const OpencodeProviderTestPanel: React.FC<OpencodeProviderTestPanelProps>
</p>
</div>
)}
- {lastResult && !lastResult.ok && lastResult.detail && (
+ {lastResult && !lastResult.ok && !isNativeAuthHubOwned(lastResult) && lastResult.detail && (
<details className="rounded-md border border-destructive/30 bg-destructive/[0.04] px-3 py-2 [&[open]>summary]:mb-2">
<summary className="cursor-pointer font-mono text-[10px] uppercase tracking-wide text-destructive-ink">
{t('settings.backends.testConnectionRawOutputLabel')}
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index 279ab74f7..17d1e1b3d 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -234,6 +234,7 @@ export const SettingsLayout: React.FC = () => {
const location = useLocation();
const navigate = useNavigate();
const isDesktop = useIsDesktop();
+ const setupOrigin = useSettingsOverlayContext()?.location.pathname === '/setup';
const [modelHubVisible, setModelHubVisible] = useState(false);
const [memoryVisible, setMemoryVisible] = useState(false);
const [channelSettingsVisible, setChannelSettingsVisible] = useState(false);
@@ -324,19 +325,19 @@ export const SettingsLayout: React.FC = () => {
}, [location.pathname]);
const mobileBackTarget = useMemo(() => {
- if (atRoot) return '/';
+ if (atRoot || setupOrigin) return '/';
const activeSection = activeTrail.at(-1);
if (!activeSection) return '/settings';
return normalizedSettingsPath(location.pathname) === normalizedSettingsPath(activeSection.path)
? '/settings'
: activeSection.path;
- }, [activeTrail, atRoot, location.pathname]);
+ }, [activeTrail, atRoot, location.pathname, setupOrigin]);
// One class string for both branches below, so the touch target and the
// chevron cannot drift apart depending on where the control points.
const mobileBackClassName = '-ml-2 grid size-11 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:hidden';
- const mobileBackLabel = mobileBackTarget === '/'
+ const mobileBackLabel = setupOrigin ? t('common.back') : mobileBackTarget === '/'
? t('settings.backToWorkbench')
: mobileBackTarget === '/settings'
? t('settings.backToSections')
diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx
index 9f9e0dca2..d297b070c 100644
--- a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx
+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx
@@ -170,6 +170,8 @@ const ChatProbe = () => {
);
};
+const SetupProbe = () => <Link to="/settings/models">open-model-hub</Link>;
+
const SettingsFrame = () => {
const location = useLocation();
const navigate = useNavigate();
@@ -199,6 +201,7 @@ const SettingsFrame = () => {
const settingsRoute = () => (
<Route path="/settings" element={<SettingsFrame />}>
<Route path="replies" element={<div>replies-settings</div>} />
+ <Route path="models" element={<div>models-settings</div>} />
<Route path="advanced" element={<div>advanced-settings</div>} />
<Route path="diagnostics" element={<div>diagnostics-settings</div>} />
</Route>
@@ -225,6 +228,7 @@ const Harness = ({ desktop }: { desktop: boolean }) => (
<SettingsOverlayNavigationBoundary desktop={desktop}>
<SettingsToggle />
<SettingsOverlayRouteSurface fallbackElement={<Navigate to="/" replace />}>
+ <Route path="/setup" element={<SetupProbe />} />
<Route path="/chat/:sessionId" element={<ChatProbe />} />
<Route path="/escaped" element={<div>escaped-route</div>} />
{settingsRoute()}
@@ -267,6 +271,22 @@ afterEach(() => {
});
describe('SettingsOverlayRouteSurface', () => {
+ it('opens Model Hub over setup on mobile and closes back to the wizard', async () => {
+ const user = userEvent.setup();
+ render(
+ <MemoryRouter initialEntries={['/setup']}>
+ <RoutedHarness desktop={false} />
+ </MemoryRouter>,
+ );
+
+ await user.click(screen.getByRole('link', { name: 'open-model-hub' }));
+ expect(screen.getByText('models-settings')).toBeTruthy();
+ expect(screen.getByRole('dialog')).toBeTruthy();
+
+ await user.click(screen.getByRole('button', { name: 'close-settings' }));
+ expect(screen.getByRole('link', { name: 'open-model-hub' })).toBeTruthy();
+ });
+
it('preserves the Chat route with a data router', async () => {
const user = userEvent.setup();
const router = createMemoryRouter([
diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.tsx
index a16473911..513917912 100644
--- a/ui/src/components/settings/models/BackendSupplyModeCard.tsx
+++ b/ui/src/components/settings/models/BackendSupplyModeCard.tsx
@@ -16,6 +16,7 @@ import { createAgentCollectionReadAuthority } from './collectionReadAuthority';
import { useToast } from '@/context/ToastContext';
import { modelsApi } from './modelsApi';
import { MigrationDialog } from './MigrationDialog';
+import { resumeGatewayAdoption } from './gatewayAdoption';
import { connectOutcome, isSupplyWarning } from './sufficiency';
import type { AgentBackend, AgentMode, AgentSupply, MigrationItem } from './types';
@@ -119,8 +120,18 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac
if (!agent || agent.mode === mode || switching) return;
setSwitching(mode);
try {
- const next = await modelsApi.setAgentMode(backend, mode);
- if (!aliveRef.current) return;
+ const next = mode === 'hub'
+ ? await (async () => {
+ const result = await resumeGatewayAdoption(modelsApi, agentReads, backend);
+ if (!result.ok) throw new Error(result.failure.reason);
+ if (result.candidates.length > 0) {
+ if (aliveRef.current) setMigrateOpen(true);
+ return null;
+ }
+ return modelsApi.setAgentMode(backend, 'hub');
+ })()
+ : await modelsApi.setAgentMode(backend, mode);
+ if (!aliveRef.current || !next) return;
setAgent(next);
if (mode === 'direct') {
showToast(t('settings.models.supplyMode.switchedDirect') as string, 'success');
@@ -148,10 +159,9 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac
const mode = agent.mode;
const hubOutcome = connectOutcome(agent, null);
- // Only surface the import strip for configs the migration dialog can actually
- // apply — a reauth-only scan would open a dead-end dialog (reauth rows are
- // disabled and excluded from apply), so those don't count as importable.
- const importable = detected.filter((i) => i.proposed_action !== 'reauth');
+ // The strip advertises an actionable import row. A blocked-only native
+ // configuration is still handled by the Direct → Hub migration dialog.
+ const importable = detected.filter((i) => i.proposed_action === 'import');
const detectItem = importable.find((i) => i.kind === 'api_key' || i.kind === 'opencode_provider') ?? importable[0] ?? null;
return (
@@ -242,8 +252,10 @@ export const BackendSupplyModeCard: React.FC<{ backend: AgentBackend }> = ({ bac
<MigrationDialog
open={migrateOpen}
+ eligible={(item) => item.backend === backend}
onClose={() => setMigrateOpen(false)}
onApplied={() => {
+ setMigrateOpen(false);
void load();
void scan();
}}
diff --git a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
deleted file mode 100644
index 895f69417..000000000
--- a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-// @vitest-environment jsdom
-import { cleanup, render, screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { I18nextProvider } from 'react-i18next';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import i18n from '@/i18n';
-import { createAgentCollectionReadAuthority } from './collectionReadAuthority';
-import { EnableGatewayDialog } from './EnableGatewayDialog';
-import { modelsApi } from './modelsApi';
-import { failRegionRead, readyRegion, unreadRegion, type RegionRead } from './regionRead';
-import type { AgentSupply, RuntimeDependency } from './types';
-
-const direct: AgentSupply = {
- backend: 'claude',
- cli_present: true,
- mode: 'direct',
- menu_kind: 'fixed',
- sources: { order: [], eligibility: [] },
-};
-
-const runtime = (
- health: RuntimeDependency['status']['health'],
- withAsset = false,
- hostPlatform?: string,
-): RuntimeDependency => {
- const assets = withAsset ? [{
- platform: 'darwin-arm64',
- url: 'https://example.invalid/runtime',
- size_bytes: 1,
- sha256: '0'.repeat(64),
- } as const] : [];
- const resolution = !withAsset
- ? 'unresolved' as const
- : hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
- return {
- contract_version: 10,
- ...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
- manifest: resolution === 'unresolved'
- ? { name: 'cliproxyapi', resolution, assets: [] }
- : { name: 'cliproxyapi', resolution, version: '1', source_sha: 'a'.repeat(40), assets },
- status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },
- };
-};
-
-const renderDialog = (runtimeValue: RegionRead<RuntimeDependency>, props: Partial<React.ComponentProps<typeof EnableGatewayDialog>> = {}) => render(
- <I18nextProvider i18n={i18n}>
- <EnableGatewayDialog
- agent={direct}
- runtime={runtimeValue}
- agentReads={createAgentCollectionReadAuthority(modelsApi)}
- onClose={vi.fn()}
- onAdopted={vi.fn()}
- onRuntime={vi.fn()}
- trackWrite={async (work) => work()}
- {...props}
- />
- </I18nextProvider>,
-);
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-describe('EnableGatewayDialog', () => {
- it('names the dependency and changes the primary when runtime is missing', () => {
- renderDialog(readyRegion(runtime('not_installed', true)));
-
- expect(screen.getByText(/cliproxyapi/)).toBeTruthy();
- expect(screen.getByRole('button', { name: 'Install and switch' })).toBeTruthy();
- });
-
- it('keeps installation reachable while a remote manifest is uncached', () => {
- renderDialog(readyRegion(runtime('not_installed')));
-
- expect(screen.getByRole('button', { name: 'Install and switch' })).toBeTruthy();
- });
-
- it('shares the server manifest resolution with the runtime pill', () => {
- renderDialog(readyRegion(runtime('not_installed', true, 'linux-amd64')));
-
- expect(screen.queryByRole('button', { name: 'Install and switch' })).toBeNull();
- expect((screen.getByRole('button', { name: 'Switch to gateway' }) as HTMLButtonElement).disabled).toBe(true);
- });
-
- it('keeps the dialog open with cause-neutral failure copy and a retryable primary', async () => {
- const user = userEvent.setup();
- vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([direct]);
- vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime('ok'));
- vi.spyOn(modelsApi, 'setAgentMode').mockRejectedValue(new TypeError('offline'));
- const onClose = vi.fn();
- renderDialog(readyRegion(runtime('ok')), { onClose });
-
- await user.click(screen.getByRole('button', { name: 'Switch to gateway' }));
-
- expect(await screen.findByText('The switch to the gateway did not go through')).toBeTruthy();
- expect(screen.getByText(/PATCH \/api\/models\/agents\/claude\/mode · The gateway could not be reached/)).toBeTruthy();
- expect(screen.getByRole('button', { name: 'Switch to gateway' })).toBeTruthy();
- expect(onClose).not.toHaveBeenCalled();
- });
-
- it('keeps adoption disabled while runtime status is unread', async () => {
- const user = userEvent.setup();
- const setMode = vi.spyOn(modelsApi, 'setAgentMode');
- renderDialog(unreadRegion<RuntimeDependency>());
-
- const confirm = screen.getByRole('button', { name: 'Switch to gateway' }) as HTMLButtonElement;
- expect(confirm.disabled).toBe(true);
- expect(screen.getByText('Gateway status unavailable')).toBeTruthy();
-
- await user.click(confirm);
- expect(setMode).not.toHaveBeenCalled();
- });
-
- it('does not use a retained runtime value to choose an adoption action', () => {
- renderDialog(failRegionRead(readyRegion(runtime('not_installed', true))));
-
- expect(screen.queryByRole('button', { name: 'Install and switch' })).toBeNull();
- expect((screen.getByRole('button', { name: 'Switch to gateway' }) as HTMLButtonElement).disabled).toBe(true);
- expect(screen.getByText('Gateway status unavailable')).toBeTruthy();
- });
-});
diff --git a/ui/src/components/settings/models/EnableGatewayDialog.tsx b/ui/src/components/settings/models/EnableGatewayDialog.tsx
deleted file mode 100644
index 89672dbc2..000000000
--- a/ui/src/components/settings/models/EnableGatewayDialog.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import * as React from 'react';
-import * as DialogPrimitive from '@radix-ui/react-dialog';
-import { Check, CircleX, LoaderCircle, X } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-
-import { Button } from '@/components/ui/button';
-import type { CollectionReadAuthority } from './collectionReadAuthority';
-import { resumeGatewayAdoption, type GatewayAdoptionFailure } from './gatewayAdoption';
-import { modelsApi } from './modelsApi';
-import { foldRegionRead, readyRegion, type RegionRead } from './regionRead';
-import { runtimeCanAttemptInstall } from './runtimeLifecycle';
-import type { AgentSupply, RuntimeDependency } from './types';
-import { BACKEND_ADOPTION_VENDOR_KEY } from './vendorMeta';
-
-const Bullet: React.FC<{ children: React.ReactNode }> = ({ children }) => (
- <p className="model-hub-adopt-bullet">
- <Check aria-hidden />
- <span>{children}</span>
- </p>
-);
-
-export const EnableGatewayDialog: React.FC<{
- agent: AgentSupply;
- runtime: RegionRead<RuntimeDependency>;
- agentReads: CollectionReadAuthority<AgentSupply[]>;
- onClose: () => void;
- onAdopted: (agent: AgentSupply) => void | Promise<void>;
- onRuntime: (runtime: RuntimeDependency) => void;
- trackWrite: (work: () => Promise<void>) => Promise<void>;
-}> = ({ agent, runtime, agentReads, onClose, onAdopted, onRuntime, trackWrite }) => {
- const { t } = useTranslation();
- const [busy, setBusy] = React.useState(false);
- const [runtimeView, setRuntimeView] = React.useState(runtime);
- const [failure, setFailure] = React.useState<GatewayAdoptionFailure | null>(null);
- const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend });
- const vendor = t(`settings.models.adopt.vendor.${BACKEND_ADOPTION_VENDOR_KEY[agent.backend]}`);
- const runtimeDecision = foldRegionRead<RuntimeDependency, { kind: 'ready'; runtime: RuntimeDependency } | { kind: 'unavailable' }>(runtimeView, {
- loading: () => ({ kind: 'unavailable' }),
- ready: (value) => ({ kind: 'ready', runtime: value }),
- unread: () => ({ kind: 'unavailable' }),
- degraded: () => ({ kind: 'unavailable' }),
- });
- const runtimeValue = runtimeDecision.kind === 'ready' ? runtimeDecision.runtime : null;
- const runtimeUnavailable = runtimeValue === null;
- const needsInstall = runtimeValue?.status.health === 'not_installed';
- const missing = Boolean(needsInstall && runtimeValue && runtimeCanAttemptInstall(runtimeValue));
- const installUnsupported = Boolean(needsInstall && !missing);
- const effectKeys = agent.backend === 'opencode'
- ? ['1.opencode', '2.opencode', '3', '4'] as const
- : ['1', '2', '3', '4'] as const;
-
- React.useEffect(() => {
- if (!busy) setRuntimeView(runtime);
- }, [busy, runtime]);
-
- const commit = () => {
- if (busy || runtimeUnavailable || installUnsupported) return;
- setBusy(true);
- setFailure(null);
- void trackWrite(async () => {
- try {
- const result = await resumeGatewayAdoption(modelsApi, agentReads, agent.backend);
- if (result.runtime) {
- setRuntimeView(readyRegion(result.runtime));
- onRuntime(result.runtime);
- }
- if (!result.ok) {
- setFailure(result.failure);
- return;
- }
- await Promise.resolve(onAdopted(result.agent)).catch(() => {});
- onClose();
- } finally {
- setBusy(false);
- }
- });
- };
-
- const reason = failure ? t(`settings.models.adopt.fail.reason.${failure.reason}`) : '';
- const failureDetail = failure?.step === 'install'
- ? t('settings.models.install.fail.detail')
- : failure?.request && failure.responseStatus
- ? t('settings.models.adopt.fail.detail', {
- request: failure.request,
- status: failure.responseStatus,
- reason,
- })
- : failure
- ? [failure.request, failure.responseStatus, reason].filter((slot) => slot !== undefined && slot !== '').join(' · ')
- : '';
-
- return (
- <DialogPrimitive.Root open onOpenChange={(open) => !open && !busy && onClose()}>
- <DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="model-hub-adopt-overlay fixed inset-0 z-50" />
- <DialogPrimitive.Content
- className="model-hub-adopt-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden bg-surface outline-none"
- onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}
- onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}
- >
- <header className="model-hub-adopt-head">
- <div className="flex items-center justify-between gap-3">
- <DialogPrimitive.Title className="model-hub-adopt-title text-foreground">
- {t('settings.models.adopt.title', { backend })}
- </DialogPrimitive.Title>
- <DialogPrimitive.Close asChild>
- <Button type="button" variant="ghost" size="icon" className="model-hub-adopt-close" disabled={busy} aria-label={t('settings.models.adopt.cancel')}>
- <X />
- </Button>
- </DialogPrimitive.Close>
- </div>
- <DialogPrimitive.Description className="model-hub-adopt-subtitle">
- {t('settings.models.adopt.subtitle', { backend })}
- </DialogPrimitive.Description>
- </header>
-
- <div className="model-hub-adopt-body">
- {failure && (
- <div className="model-hub-adopt-failure" role="alert">
- <CircleX aria-hidden />
- <span className="min-w-0">
- <strong>{t('settings.models.adopt.fail.title')}</strong>
- <span>{failureDetail}</span>
- </span>
- </div>
- )}
- {runtimeUnavailable && !failure && (
- <div className="model-hub-adopt-failure" role="status">
- <CircleX aria-hidden />
- <span className="min-w-0"><strong>{t('settings.models.shell.unread')}</strong></span>
- </div>
- )}
- <section className="model-hub-adopt-section">
- <h3>{t('settings.models.adopt.section.effects')}</h3>
- {missing && (
- <Bullet>{t('settings.models.adopt.effects.install', {
- component: runtimeValue?.manifest.name,
- duration: t('settings.models.install.duration'),
- })}</Bullet>
- )}
- {effectKeys.map((key) => (
- <Bullet key={key}>{t(`settings.models.adopt.effects.${key}`, { backend, vendor })}</Bullet>
- ))}
- </section>
- <section className="model-hub-adopt-section">
- <h3>{t('settings.models.adopt.section.undo')}</h3>
- {(['1', '2', '3'] as const).map((key) => (
- <Bullet key={key}>{t(`settings.models.adopt.undo.${key}`, { backend })}</Bullet>
- ))}
- </section>
- </div>
-
- <footer className="model-hub-adopt-foot">
- <Button type="button" variant="outline" className="model-hub-adopt-action" onClick={onClose} disabled={busy}>
- {t('settings.models.adopt.cancel')}
- </Button>
- <Button type="button" variant="brand" className="model-hub-adopt-action" onClick={commit} disabled={busy || runtimeUnavailable || installUnsupported}>
- {busy && <LoaderCircle className="animate-spin" />}
- {missing ? t('settings.models.adopt.confirm.install') : t('settings.models.adopt.confirm')}
- </Button>
- </footer>
- </DialogPrimitive.Content>
- </DialogPrimitive.Portal>
- </DialogPrimitive.Root>
- );
-};
-
-export default EnableGatewayDialog;
diff --git a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
deleted file mode 100644
index c0131d2fc..000000000
--- a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-// @vitest-environment jsdom
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { I18nextProvider } from 'react-i18next';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import i18n from '@/i18n';
-import { InstallGatewayDialog } from './InstallGatewayDialog';
-import { modelsApi } from './modelsApi';
-import type { RuntimeDependency } from './types';
-
-const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 10,
- manifest: {
- name: 'cliproxyapi',
- resolution: 'resolved',
- version: '1',
- source_sha: 'sha',
- assets: [{ platform: 'darwin-arm64', url: 'https://example.invalid/runtime', size_bytes: 1, sha256: '0'.repeat(64) }],
- },
- status: { installed_version: null, verified: false, listening: null, health, last_check: null },
-});
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-describe('InstallGatewayDialog', () => {
- it('holds install-and-start through both proven steps before closing', async () => {
- const installed = runtime('not_started');
- const running = runtime('ok');
- const install = vi.spyOn(modelsApi, 'installRuntime').mockResolvedValueOnce(installed);
- const start = vi.spyOn(modelsApi, 'startRuntime').mockResolvedValueOnce(running);
- const onRuntime = vi.fn();
- const onClose = vi.fn();
- render(
- <I18nextProvider i18n={i18n}>
- <InstallGatewayDialog runtime={runtime('not_installed')} onClose={onClose} onRuntime={onRuntime} />
- </I18nextProvider>,
- );
-
- await userEvent.click(screen.getByRole('button', { name: /Install and start|安装并启动/i }));
-
- await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
- expect(install).toHaveBeenCalledOnce();
- expect(start).toHaveBeenCalledOnce();
- expect(install.mock.invocationCallOrder[0]).toBeLessThan(start.mock.invocationCallOrder[0]);
- expect(onRuntime).toHaveBeenNthCalledWith(1, installed);
- expect(onRuntime).toHaveBeenNthCalledWith(2, running);
- });
-
- it('keeps the dialog open and offers retry when a background install fails', async () => {
- let settleInstall: ((value: RuntimeDependency) => void) | undefined;
- vi.spyOn(modelsApi, 'installRuntime').mockImplementation(() => new Promise((resolve) => { settleInstall = resolve; }));
- const onClose = vi.fn();
- const view = render(
- <I18nextProvider i18n={i18n}>
- <InstallGatewayDialog runtime={runtime('not_installed')} onClose={onClose} onRuntime={vi.fn()} />
- </I18nextProvider>,
- );
- await userEvent.click(screen.getByRole('button', { name: /Install and start|安装并启动/i }));
- view.rerender(<I18nextProvider i18n={i18n}><InstallGatewayDialog runtime={runtime('installing')} onClose={onClose} onRuntime={vi.fn()} /></I18nextProvider>);
- // #1326 runtime-dependency shape: the server supplies this optional failure key.
- view.rerender(<I18nextProvider i18n={i18n}><InstallGatewayDialog runtime={{ ...runtime('not_installed'), status: { ...runtime('not_installed').status, error_key: 'settings.models.install.fail.detail' } }} onClose={onClose} onRuntime={vi.fn()} /></I18nextProvider>);
-
- expect(await screen.findByRole('alert')).toBeTruthy();
- expect(screen.getByRole('button', { name: /Try again|重试/i })).toBeTruthy();
- expect(onClose).not.toHaveBeenCalled();
- settleInstall?.(runtime('not_installed'));
- });
-
- it('renders a persisted install failure immediately after reload', () => {
- const failed = runtime('not_installed');
- failed.status.error_key = 'settings.models.install.fail.detail';
-
- render(
- <I18nextProvider i18n={i18n}>
- <InstallGatewayDialog runtime={failed} onClose={vi.fn()} onRuntime={vi.fn()} />
- </I18nextProvider>,
- );
-
- expect(screen.getByRole('alert')).toBeTruthy();
- expect(screen.getByRole('button', { name: /Try again|重试/i })).toBeTruthy();
- });
-});
diff --git a/ui/src/components/settings/models/InstallGatewayDialog.tsx b/ui/src/components/settings/models/InstallGatewayDialog.tsx
deleted file mode 100644
index b5856c22d..000000000
--- a/ui/src/components/settings/models/InstallGatewayDialog.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import * as React from 'react';
-import * as DialogPrimitive from '@radix-ui/react-dialog';
-import { Check, CircleX, LoaderCircle, X } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-
-import { Button } from '@/components/ui/button';
-import { modelsApi } from './modelsApi';
-import { resumeInstallAndStartRuntime, runtimeIsRunning } from './runtimeLifecycle';
-import type { RuntimeDependency } from './types';
-
-const Bullet: React.FC<{ children: React.ReactNode }> = ({ children }) => (
- <p className="model-hub-adopt-bullet"><Check aria-hidden /><span>{children}</span></p>
-);
-
-export const InstallGatewayDialog: React.FC<{
- runtime: RuntimeDependency;
- onClose: () => void;
- onRuntime: (runtime: RuntimeDependency | null) => void;
-}> = ({ runtime, onClose, onRuntime }) => {
- const { t } = useTranslation();
- const [requesting, setRequesting] = React.useState(false);
- const installErrorKey = 'error_key' in runtime.status ? runtime.status.error_key : null;
- const [failed, setFailed] = React.useState(
- runtime.status.health === 'not_installed' && Boolean(installErrorKey),
- );
- const initiated = React.useRef(false);
- const installing = requesting || runtime.status.health === 'installing';
-
- React.useEffect(() => {
- if (runtime.status.health === 'not_installed' && installErrorKey) {
- setRequesting(false);
- setFailed(true);
- return;
- }
- if (initiated.current && runtimeIsRunning(runtime)) {
- onClose();
- }
- }, [installErrorKey, onClose, runtime.status.health]);
-
- const install = () => {
- if (installing) return;
- initiated.current = true;
- setRequesting(true);
- setFailed(false);
- void resumeInstallAndStartRuntime(modelsApi, runtime, onRuntime)
- .then((result) => {
- if (result.failedStep) setFailed(true);
- else onClose();
- })
- .finally(() => setRequesting(false));
- };
-
- return (
- <DialogPrimitive.Root open onOpenChange={(open) => !open && !installing && onClose()}>
- <DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="model-hub-adopt-overlay fixed inset-0 z-50" />
- <DialogPrimitive.Content
- className="model-hub-adopt-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden bg-surface outline-none"
- onEscapeKeyDown={(event) => { if (installing) event.preventDefault(); }}
- onPointerDownOutside={(event) => { if (installing) event.preventDefault(); }}
- >
- <header className="model-hub-adopt-head">
- <div className="flex items-center justify-between gap-3">
- <DialogPrimitive.Title className="model-hub-adopt-title text-foreground">
- {t('settings.models.install.title')}
- </DialogPrimitive.Title>
- <DialogPrimitive.Close asChild>
- <Button type="button" variant="ghost" size="icon" className="model-hub-adopt-close" disabled={installing} aria-label={t('settings.models.install.cancel')}>
- <X />
- </Button>
- </DialogPrimitive.Close>
- </div>
- <DialogPrimitive.Description className="model-hub-adopt-subtitle">
- {t('settings.models.install.subtitle')}
- </DialogPrimitive.Description>
- </header>
- <div className="model-hub-adopt-body">
- {failed && (
- <div className="model-hub-adopt-failure" role="alert">
- <CircleX aria-hidden />
- <span className="min-w-0">
- <strong>{t('settings.models.install.fail.title')}</strong>
- <span>{t('settings.models.install.fail.detail')}</span>
- </span>
- </div>
- )}
- <section className="model-hub-adopt-section">
- <h3>{t('settings.models.install.section.effects')}</h3>
- <Bullet>{t('settings.models.install.effects.1', {
- component: runtime.manifest.name,
- duration: t('settings.models.install.duration'),
- })}</Bullet>
- <Bullet>{t('settings.models.install.effects.2')}</Bullet>
- <Bullet>{t('settings.models.install.effects.3')}</Bullet>
- </section>
- </div>
- <footer className="model-hub-adopt-foot">
- <Button type="button" variant="outline" className="model-hub-adopt-action" onClick={onClose} disabled={installing}>
- {t('settings.models.install.cancel')}
- </Button>
- <Button type="button" variant="brand" className="model-hub-adopt-action" onClick={install} disabled={installing}>
- {installing && <LoaderCircle className="animate-spin" />}
- {installing
- ? t('settings.models.install.progress')
- : failed
- ? t('settings.models.install.retry')
- : t('settings.models.install.confirm')}
- </Button>
- </footer>
- </DialogPrimitive.Content>
- </DialogPrimitive.Portal>
- </DialogPrimitive.Root>
- );
-};
-
-export default InstallGatewayDialog;
diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsx
index aefd92494..4ec7cfdb8 100644
--- a/ui/src/components/settings/models/MigrationDialog.test.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx
@@ -1,12 +1,9 @@
// @vitest-environment jsdom
//
-// The settings migration, which is deliberately broader than setup's key-import
-// entry. `keep_native` is a real applied action here — it files the native CLI
-// login as a native_cli-channel source — so narrowing the dialog for one caller
-// must not quietly narrow it for this one. That, and the row's own presentation
-// rules: a provider name only when the server sent the metadata for it, never
-// one inferred from whichever backend happened to hold the key.
-import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
+// The settings migration and setup's key-import entry share the same takeover
+// dialog. A backend is one custody boundary: unsupported rows stay visible and
+// block that CLI, while a complete backend can still migrate independently.
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { I18nextProvider } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -19,14 +16,14 @@ vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast }) }));
import { MigrationDialog } from './MigrationDialog';
import { isImportableKey } from './migrationScan';
-import { modelsApi } from './modelsApi';
+import { ApiCallError, modelsApi } from './modelsApi';
const SUBSCRIPTION: MigrationItem = {
id: 'mig_claude_oauth',
backend: 'claude',
kind: 'oauth_native',
masked_detail: 'Claude 账号登录(OAuth)',
- proposed_action: 'keep_native',
+ proposed_action: 'import',
selected: true,
notes_key: null,
vendor: 'anthropic',
@@ -34,6 +31,12 @@ const SUBSCRIPTION: MigrationItem = {
masked_credential: null,
};
+const SUBSCRIPTION_2: MigrationItem = {
+ ...SUBSCRIPTION,
+ id: 'mig_claude_oauth_2',
+ masked_detail: 'Claude 账号登录(OAuth)· 第二账号',
+};
+
const CODEX_KEY: MigrationItem = {
id: 'mig_codex_key',
backend: 'codex',
@@ -47,7 +50,7 @@ const CODEX_KEY: MigrationItem = {
masked_credential: 'sk-…9f21',
};
-// Pre-selected by the scan, and still never batchable: it needs the browser flow.
+// Pre-selected by the scan, but not batchable: it needs the browser flow.
const REAUTH: MigrationItem = {
id: 'mig_claude_reauth',
backend: 'claude',
@@ -103,55 +106,239 @@ afterEach(() => {
});
describe('MigrationDialog — the settings default', () => {
- it('shows every scanned row, subscriptions included', async () => {
+ it('shows blocked native rows and keeps a complete backend actionable', async () => {
serve();
renderDialog();
const dialog = await screen.findByRole('dialog');
await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
expect(within(dialog).getByText(/Claude 账号登录/)).toBeTruthy();
- expect(within(dialog).getByText('Keep native')).toBeTruthy();
- expect(within(dialog).getByText(/Re-authorize/)).toBeTruthy();
+ expect((within(dialog).getByRole('checkbox', { name: /sk-ant-…4b7e/ }) as HTMLButtonElement).disabled).toBe(true);
+ expect(within(dialog).getByText('Use the existing Add flow for this CLI, then scan again.')).toBeTruthy();
+ expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(false);
});
- it('applies a keep_native row — it is a real action here, not a leftover', async () => {
+ it('applies only complete backend groups with one migration action', async () => {
serve();
renderDialog();
const user = userEvent.setup();
const dialog = await screen.findByRole('dialog');
await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
- // Three of the four: everything except the reauth row.
- await user.click(within(dialog).getByRole('button', { name: /Import 3 items/ }));
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+
+ await waitFor(() => expect(applied).toHaveLength(1));
+ expect(applied[0]).toEqual(['mig_codex_key', 'mig_opencode_legacy']);
+ expect(applied[0]).not.toContain('mig_claude_oauth');
+ });
+
+ it('selects and submits every import candidate for a backend as one group', async () => {
+ serve([SUBSCRIPTION, SUBSCRIPTION_2, CODEX_KEY, LEGACY]);
+ renderDialog();
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ const claudeRows = within(dialog).getAllByRole('checkbox').slice(0, 2);
+ expect(claudeRows).toHaveLength(2);
+ await user.click(claudeRows[0]);
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
await waitFor(() => expect(applied).toHaveLength(1));
- expect(applied[0]).toContain('mig_claude_oauth');
- expect(applied[0]).toEqual(['mig_claude_oauth', 'mig_codex_key', 'mig_opencode_legacy']);
+ expect(applied[0]).toEqual(['mig_codex_key', 'mig_opencode_legacy']);
+ expect(applied[0]).not.toContain('mig_claude_oauth');
+ expect(applied[0]).not.toContain('mig_claude_oauth_2');
});
- it('never submits a reauth row, even pre-selected', async () => {
+ it('shows but never submits a reauth row, even when it is pre-selected', async () => {
serve();
renderDialog();
const user = userEvent.setup();
const dialog = await screen.findByRole('dialog');
await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
- expect(within(dialog).getByRole('checkbox', { name: /sk-ant-…4b7e/ })).toHaveProperty('disabled', true);
- await user.click(within(dialog).getByRole('button', { name: /Import 3 items/ }));
+ expect((within(dialog).getByRole('checkbox', { name: /sk-ant-…4b7e/ }) as HTMLButtonElement).disabled).toBe(true);
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
await waitFor(() => expect(applied).toHaveLength(1));
expect(applied[0]).not.toContain('mig_claude_reauth');
});
- it('narrows to a caller-supplied predicate without changing its own default', async () => {
+ it('uses eligible as a backend scope without hiding blocked rows in that backend', async () => {
+ const claudeKey: MigrationItem = {
+ ...CODEX_KEY,
+ id: 'mig_claude_key',
+ backend: 'claude',
+ masked_detail: 'sk-ant-…1234',
+ vendor: 'anthropic',
+ display_name: 'Anthropic',
+ masked_credential: 'sk-ant-…1234',
+ };
+ serve([claudeKey, SUBSCRIPTION, REAUTH]);
+ renderDialog({ eligible: (item) => item.backend === 'claude' && isImportableKey(item) });
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getAllByText('Anthropic').length).toBeGreaterThan(0));
+ expect(within(dialog).getByText(/Claude 账号登录/)).toBeTruthy();
+ expect((within(dialog).getByRole('checkbox', { name: /sk-ant-…4b7e/ }) as HTMLButtonElement).disabled).toBe(true);
+ expect(within(dialog).getByRole('button', { name: 'Start migration' })).toBeTruthy();
+ });
+
+ it('closes without applying when the user chooses Not now', async () => {
serve();
- renderDialog({ eligible: isImportableKey });
+ const onClose = vi.fn();
+ renderDialog({ onClose });
+ const user = userEvent.setup();
const dialog = await screen.findByRole('dialog');
await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
- expect(within(dialog).queryByText(/Claude 账号登录/)).toBeNull();
- expect(within(dialog).queryByText(/Re-authorize/)).toBeNull();
- expect(within(dialog).getByRole('button', { name: /Import 2 items/ })).toBeTruthy();
+ await user.click(within(dialog).getByRole('button', { name: 'Later' }));
+
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(applied).toEqual([]);
+ });
+
+ it('keeps the selection after an apply failure and allows retry', async () => {
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
+ vi.spyOn(modelsApi, 'applyMigration')
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce({ applied: 1, sources: [] });
+ const onClose = vi.fn();
+ renderDialog({ onClose });
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ const start = within(dialog).getByRole('button', { name: 'Start migration' });
+ await user.click(start);
+
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith('Migration failed, please retry', 'error'));
+ expect(onClose).not.toHaveBeenCalled();
+ expect((start as HTMLButtonElement).disabled).toBe(false);
+
+ await user.click(start);
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(modelsApi.applyMigration).toHaveBeenCalledTimes(2);
+ });
+
+ it('shows the migrating state while apply is waiting', async () => {
+ const pending = new Promise<{ applied: number; sources: never[] }>(() => {});
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
+ vi.spyOn(modelsApi, 'applyMigration').mockReturnValue(pending);
+ renderDialog();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+
+ await waitFor(() => expect((within(dialog).getByRole('button', { name: 'Migrating…' }) as HTMLButtonElement).disabled).toBe(true));
+ });
+
+ it.each([
+ ['migration_native_busy', 'Close the CLI or finish its tasks, then retry.'],
+ ['migration_permission_needed', 'Allow credential access, then retry.'],
+ ['migration_recovery_pending', 'Migration is unfinished. Retry to continue.'],
+ ['migration_item_conflict', 'The native configuration changed. Scan again.'],
+ ['migration_configuration_blocked', 'Adjust the native configuration, then scan again.'],
+ ] as const)('maps %s to concise localized copy', async (code, message) => {
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
+ vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(new ApiCallError(code));
+ renderDialog();
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith(message, 'error'));
+ });
+
+ it.each([
+ ['en', 'Authentication has expired. Sign in again in Model Hub.'],
+ ['zh', '认证已过期,请在模型网关中重新登录。'],
+ ] as const)('maps expired migration credentials to the %s Hub reauthentication action', async (language, message) => {
+ await i18n.changeLanguage(language);
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
+ vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(new ApiCallError('migration_credentials_invalid'));
+ renderDialog();
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ await user.click(within(dialog).getByRole('button', { name: language === 'en' ? 'Start migration' : '开始迁移' }));
+
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith(message, 'error'));
+ });
+
+ it('refreshes through onApplied and closes after terminal credential settlement', async () => {
+ const onApplied = vi.fn();
+ const onClose = vi.fn();
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
+ vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(new ApiCallError('migration_credentials_invalid'));
+ renderDialog({ onApplied, onClose });
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith(
+ 'Authentication has expired. Sign in again in Model Hub.',
+ 'error',
+ ));
+ expect(onApplied).toHaveBeenCalledWith(0);
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(showToast).not.toHaveBeenCalledWith('Migration complete', 'success');
+ });
+
+ it('keeps the dialog open while recovery is still pending', async () => {
+ const onApplied = vi.fn();
+ const onClose = vi.fn();
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [{ ...CODEX_KEY }] });
+ vi.spyOn(modelsApi, 'applyMigration').mockRejectedValue(new ApiCallError('migration_recovery_pending'));
+ renderDialog({ onApplied, onClose });
+ const user = userEvent.setup();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));
+
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith(
+ 'Migration is unfinished. Retry to continue.',
+ 'error',
+ ));
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(onApplied).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['settings.models.migration.blocked.config', "Adjust this CLI's configuration, then scan again."],
+ ['settings.models.migration.blocked.environment', 'Remove this CLI’s environment-based credentials, then retry.'],
+ ['settings.models.migration.blocked.credential', 'Allow credential access, then retry.'],
+ ['settings.models.migration.blocked.unknown', 'Use the existing Add flow for this CLI, then scan again.'],
+ ] as const)('maps blocked note %s to actionable copy', async (notes_key, message) => {
+ const blocked = { ...REAUTH, notes_key };
+ serve([CODEX_KEY, blocked]);
+ renderDialog();
+
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());
+ expect((within(dialog).getByRole('status') as HTMLElement).textContent).toContain(message);
+ });
+});
+
+describe('MigrationDialog — approved copy', () => {
+ it.each([
+ ['en', 'After migration, CLI authentication will be fully managed by Model Hub.'],
+ ['zh', '迁移后,CLI的认证信息将完全交由模型网关管理'],
+ ] as const)('renders the %s consequence sentence exactly', async (language, sentence) => {
+ await i18n.changeLanguage(language);
+ serve([CODEX_KEY]);
+ renderDialog();
+
+ const dialog = await screen.findByRole('dialog');
+ expect(within(dialog).getByText(sentence)).toBeTruthy();
});
});
diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsx
index 168a8cc40..d826245be 100644
--- a/ui/src/components/settings/models/MigrationDialog.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.tsx
@@ -1,15 +1,9 @@
-import type { TranslationKey } from '@/i18n/types';
-// 迁移对话框 · 接入模型中枢 (frame 03). Non-destructive: a per-backend checklist of
-// detected native configs. Actions follow migration-scan.schema (spec v1.1,
-// Option 1): API keys / base URLs → import; subscription OAuth → keep_native.
-// controlled_import is reserved and not applicable in v3. Originals are never
-// modified or deleted.
-// Scans via POST /migration/scan; applies the selection via /migration/apply.
+// One-click native credential takeover. Each backend is one custody boundary:
+// unsupported native rows stay visible and block that backend as a group.
import * as React from 'react';
-import { ArrowDownToLine, Bot, KeyRound, ShieldCheck, Sparkles } from 'lucide-react';
+import { ArrowDownToLine, Bot, KeyRound, Loader2, Sparkles } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
@@ -21,12 +15,13 @@ import {
} from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
import { useToast } from '@/context/ToastContext';
+import type { TranslationKey } from '@/i18n/types';
import { providerLabel, providerVendorId } from '../providers/providerIdentity';
-import { modelsApi } from './modelsApi';
+import { apiFailure, modelsApi } from './modelsApi';
import { serverText } from './serverCopy';
import { VendorGlyph } from './vendorGlyph';
import { ACCENT_ICON, ACCENT_TILE, type Accent } from './vendorMeta';
-import type { AgentBackend, MigrationItem, MigrationAction } from './types';
+import type { AgentBackend, MigrationItem } from './types';
const BACKEND_ORDER: AgentBackend[] = ['claude', 'codex', 'opencode'];
@@ -59,26 +54,14 @@ function migrationVisual(item: MigrationItem): { Icon: React.ComponentType<{ siz
return { Icon: KeyRound, accent };
}
-const ActionBadge: React.FC<{ action: MigrationAction }> = ({ action }) => {
- const { t } = useTranslation();
- const map: Record<MigrationAction, { variant: 'success' | 'warning' | 'secondary'; key: TranslationKey }> = {
- import: { variant: 'success', key: 'settings.models.migration.action.import' },
- controlled_import: { variant: 'warning', key: 'settings.models.migration.action.controlledImport' },
- keep_native: { variant: 'secondary', key: 'settings.models.migration.action.keepNative' },
- reauth: { variant: 'warning', key: 'settings.models.migration.action.reauth' },
- };
- const { variant, key } = map[action];
- return (
- <Badge variant={variant} className="shrink-0 rounded-lg px-2.5 py-1 text-[12px] font-medium">
- {t(key)}
- </Badge>
- );
-};
-
-const ItemRow: React.FC<{ item: MigrationItem; onToggle: () => void; selectable: boolean }> = ({ item, onToggle, selectable }) => {
+const ItemRow: React.FC<{
+ item: MigrationItem;
+ checked: boolean;
+ onToggle: () => void;
+ selectable: boolean;
+}> = ({ item, checked, onToggle, selectable }) => {
const { t } = useTranslation();
const { Icon, accent } = migrationVisual(item);
- const note = serverText(t, item.notes_key);
const provider = migrationProvider(item);
const vendor = item.vendor?.trim();
// The masked key and the source it came from are the two things that tell two
@@ -89,19 +72,14 @@ const ItemRow: React.FC<{ item: MigrationItem; onToggle: () => void; selectable:
const origin = t(SOURCE_KEY[item.backend]);
const detail = [maskedKey, origin].filter(Boolean).join(' · ');
return (
- // The action badge is nowrap and shrink-0 (up to ~151px), so beside the
- // detail column it pushed this row's min-content to 374px — wider than the
- // sheet's 348px content box, which grew the dialog's grid track and spilled
- // the header, footnote and footer button off-screen. On phones the badge
- // moves to its own line under the detail.
<div
className={cn(
'flex flex-col gap-2 rounded-xl border px-3.5 py-3 sm:flex-row sm:items-center sm:gap-3',
- item.selected ? 'border-mint/40 bg-mint-soft/40' : 'border-border',
+ checked ? 'border-mint/40 bg-mint-soft/40' : 'border-border',
)}
>
<div className="flex min-w-0 flex-1 items-center gap-3">
- <Checkbox checked={item.selected} onCheckedChange={onToggle} disabled={!selectable} label={detail ? `${title} · ${detail}` : title} />
+ <Checkbox checked={checked} onCheckedChange={onToggle} disabled={!selectable} label={detail ? `${title} · ${detail}` : title} />
<span className={cn('flex size-9 shrink-0 items-center justify-center rounded-[10px]', ACCENT_TILE[accent])}>
{vendor
? <VendorGlyph vendor={providerVendorId(vendor)} className={cn('h-[14px] w-auto shrink-0 aspect-[10/7]', ACCENT_ICON[accent])} />
@@ -110,31 +88,47 @@ const ItemRow: React.FC<{ item: MigrationItem; onToggle: () => void; selectable:
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="truncate text-[14px] font-semibold text-foreground">{title}</span>
{detail && <span className="truncate text-[12px] text-muted">{detail}</span>}
- {/* `notes_key` is runtime-declared and optional, so an entry this
- bundle doesn't carry drops the line instead of printing the key. */}
- {note && <span className="truncate text-[12px] text-muted">{note}</span>}
</div>
</div>
- <div className="shrink-0 pl-[46px] sm:pl-0">
- <ActionBadge action={item.proposed_action} />
- </div>
</div>
);
};
-// The broad settings migration: everything the scan returned, minus the reauth
-// rows that need the interactive browser flow and so cannot be bulk-applied.
-const DEFAULT_ELIGIBLE = (item: MigrationItem) => item.proposed_action !== 'reauth';
+const DEFAULT_SCOPE = () => true;
+const isImportable = (item: MigrationItem) => item.proposed_action === 'import';
+const MIGRATION_ERROR_KEYS: Record<string, TranslationKey> = {
+ migration_native_busy: 'settings.models.migration.errors.nativeBusy',
+ migration_permission_needed: 'settings.models.migration.errors.permissionNeeded',
+ migration_recovery_pending: 'settings.models.migration.errors.recoveryPending',
+ migration_item_conflict: 'settings.models.migration.errors.itemConflict',
+ migration_configuration_blocked: 'settings.models.migration.errors.configurationBlocked',
+ migration_credentials_invalid: 'settings.models.migration.errors.credentialsInvalid',
+};
+const BLOCKED_NOTE_KEYS = new Set([
+ 'settings.models.migration.blocked.config',
+ 'settings.models.migration.blocked.environment',
+ 'settings.models.migration.blocked.credential',
+]);
+const BLOCKED_FALLBACK_KEY = 'settings.models.migration.blocked.fallback' satisfies TranslationKey;
+
+function blockedMessage(
+ t: ReturnType<typeof useTranslation>['t'],
+ rows: MigrationItem[],
+): string {
+ const noteKey = rows
+ .map((item) => item.notes_key)
+ .find((key): key is string => Boolean(key && BLOCKED_NOTE_KEYS.has(key)));
+ return serverText(t, noteKey, BLOCKED_FALLBACK_KEY) ?? '';
+}
export const MigrationDialog: React.FC<{
open: boolean;
onClose: () => void;
/** Fired after a successful apply so callers can refresh sources/agents. */
onApplied?: (applied: number) => void;
- /** Narrows the dialog to one entry's candidates — the rows shown, the rows
- * selectable and the ids submitted all come from this one predicate, so a
- * caller's count can never describe a different set than the dialog applies.
- * Defaults to the broad settings migration. */
+ /** Scopes the dialog to backends represented by an entry point. It never
+ * hides other native rows from those backends: a blocked row must remain
+ * visible so the whole CLI cannot be partially migrated. */
eligible?: (item: MigrationItem) => boolean;
}> = ({ open, onClose, onApplied, eligible }) => {
const { t } = useTranslation();
@@ -143,6 +137,8 @@ export const MigrationDialog: React.FC<{
const [items, setItems] = React.useState<MigrationItem[]>([]);
const [loading, setLoading] = React.useState(true);
const [applying, setApplying] = React.useState(false);
+ const eligibleRef = React.useRef(eligible);
+ eligibleRef.current = eligible;
const aliveRef = React.useRef(true);
React.useEffect(() => {
aliveRef.current = true;
@@ -162,7 +158,33 @@ export const MigrationDialog: React.FC<{
.scanMigration()
.then((scan) => {
if (cancelled) return;
- setItems(scan.items);
+ const scopePredicate = eligibleRef.current ?? DEFAULT_SCOPE;
+ const scopedBackends = new Set(
+ scan.items.filter(scopePredicate).map((item) => item.backend),
+ );
+ const importable = scan.items.filter(
+ (item) => scopedBackends.has(item.backend) && isImportable(item),
+ );
+ const blockedBackends = new Set(
+ scan.items
+ .filter((item) => scopedBackends.has(item.backend) && !isImportable(item))
+ .map((item) => item.backend),
+ );
+ const backendSelection = new Map<AgentBackend, boolean>();
+ for (const backend of BACKEND_ORDER) {
+ const rows = importable.filter((item) => item.backend === backend);
+ if (rows.length > 0) {
+ backendSelection.set(
+ backend,
+ !blockedBackends.has(backend) && rows.every((item) => item.selected),
+ );
+ }
+ }
+ setItems(scan.items.map((item) => (
+ scopedBackends.has(item.backend) && isImportable(item)
+ ? { ...item, selected: backendSelection.get(item.backend) ?? false }
+ : item
+ )));
setLoading(false);
})
.catch(() => {
@@ -175,15 +197,46 @@ export const MigrationDialog: React.FC<{
};
}, [open, showToast, t]);
- const toggle = (id: string) =>
- setItems((prev) => prev.map((i) => (i.id === id ? { ...i, selected: !i.selected } : i)));
-
- // One predicate decides what this dialog shows, what a person can tick, and
- // what gets submitted — a row that fails it is never counted and never sent,
- // even if the scan returned it pre-selected.
- const isEligible = eligible ?? DEFAULT_ELIGIBLE;
- const candidates = eligible ? items.filter(isEligible) : items;
- const appliable = candidates.filter((i) => i.selected && isEligible(i));
+ const scopePredicate = eligible ?? DEFAULT_SCOPE;
+ const scopedBackends = new Set(
+ items.filter(scopePredicate).map((item) => item.backend),
+ );
+ const candidates = items.filter((item) => scopedBackends.has(item.backend));
+ const grouped = BACKEND_ORDER.map((backend) => {
+ const rows = candidates.filter((item) => item.backend === backend);
+ const importRows = rows.filter(isImportable);
+ const blockedRows = rows.filter((item) => !isImportable(item));
+ return {
+ backend,
+ rows,
+ importRows,
+ blockedRows,
+ blocked: blockedRows.length > 0,
+ };
+ }).filter((group) => group.rows.length > 0);
+ const selectedBackends = new Set(
+ grouped
+ .filter((group) => (
+ !group.blocked
+ && group.importRows.length > 0
+ && group.importRows.every((item) => item.selected)
+ ))
+ .map((group) => group.backend)
+ );
+ const toggle = (backend: AgentBackend) =>
+ setItems((prev) => {
+ const group = grouped.find((item) => item.backend === backend);
+ if (!group || group.blocked || group.importRows.length === 0) return prev;
+ const selected = group.importRows.every((item) => item.selected);
+ return prev.map((item) => (
+ item.backend === backend && isImportable(item)
+ ? { ...item, selected: !selected }
+ : item
+ ));
+ });
+ const appliable = items.filter(
+ (item) => selectedBackends.has(item.backend) && isImportable(item),
+ );
const selectedCount = appliable.length;
const apply = async () => {
@@ -196,18 +249,23 @@ export const MigrationDialog: React.FC<{
showToast(t('settings.models.migration.applied', { count: result.applied }) as string, 'success');
onApplied?.(result.applied);
onClose();
- } catch {
- if (aliveRef.current) showToast(t('settings.models.migration.applyFailed') as string, 'error');
+ } catch (error) {
+ if (aliveRef.current) {
+ const code = apiFailure(error)?.code;
+ const key =
+ MIGRATION_ERROR_KEYS[code ?? ''] ??
+ 'settings.models.migration.applyFailed';
+ showToast(t(key) as string, 'error');
+ if (code === 'migration_credentials_invalid') {
+ onApplied?.(0);
+ onClose();
+ }
+ }
} finally {
if (aliveRef.current) setApplying(false);
}
};
- const grouped = BACKEND_ORDER.map((backend) => ({
- backend,
- rows: candidates.filter((i) => i.backend === backend),
- })).filter((g) => g.rows.length > 0);
-
return (
<Dialog open={open} onOpenChange={(v) => !v && !applying && onClose()}>
<DialogContent className="max-w-[640px] gap-5">
@@ -232,26 +290,35 @@ export const MigrationDialog: React.FC<{
<span className="px-1 font-mono text-[11px] font-semibold uppercase tracking-normal text-muted">
{t(`settings.models.backends.${group.backend}`, { defaultValue: group.backend })}
</span>
+ {group.blocked && (
+ <div
+ role="status"
+ className="rounded-lg border border-gold/40 bg-gold/[0.08] px-3 py-2 text-[12px] leading-relaxed text-foreground"
+ >
+ {blockedMessage(t, group.blockedRows)}
+ </div>
+ )}
{group.rows.map((item) => (
- <ItemRow key={item.id} item={item} selectable={isEligible(item)} onToggle={() => toggle(item.id)} />
+ <ItemRow
+ key={item.id}
+ item={item}
+ checked={!group.blocked && selectedBackends.has(group.backend)}
+ selectable={!group.blocked && isImportable(item)}
+ onToggle={() => toggle(group.backend)}
+ />
))}
</div>
))}
</div>
)}
- <p className="model-hub-ink-mint flex items-start gap-2 text-[12px] leading-relaxed">
- <ShieldCheck className="mt-0.5 size-4 shrink-0" />
- {t('settings.models.migration.nonDestructive')}
- </p>
-
<div className="flex items-center justify-end gap-2 border-t border-border pt-4">
<Button variant="outline" size="sm" className="h-10 sm:h-9" onClick={onClose} disabled={applying}>
{t('settings.models.migration.later')}
</Button>
<Button variant="brand" size="sm" className="h-10 sm:h-9" onClick={() => void apply()} disabled={selectedCount === 0 || applying}>
- <ArrowDownToLine className="size-4" />
- {t('settings.models.migration.apply', { count: selectedCount })}
+ {applying ? <Loader2 className="size-4 animate-spin" /> : <ArrowDownToLine className="size-4" />}
+ {t(applying ? 'settings.models.migration.applying' : 'settings.models.migration.apply')}
</Button>
</div>
</DialogContent>
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 5a642cb8c..48473e04a 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -16,7 +16,7 @@ import { ApiCallError, modelsApi } from './modelsApi';
import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';
import { SettingsModelsPage } from './SettingsModelsPage';
import { hasNativeSubscriptionCustody, SUBSCRIPTION_VENDORS } from './subscriptionOptions';
-import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type RuntimeDependency, type RuntimeManifest, type Source, type UsageSummary } from './types';
+import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type MigrationItem, type RuntimeDependency, type RuntimeManifest, type Source, type UsageSummary } from './types';
const directAgent = (backend: AgentBackend): AgentSupply => ({
backend,
@@ -62,6 +62,26 @@ const nativeSubscription: Source = {
display_name: 'Claude native login',
};
+const migrationCandidate: MigrationItem = {
+ id: 'mig_claude_oauth',
+ backend: 'claude',
+ kind: 'oauth_native',
+ masked_detail: 'Claude native login',
+ proposed_action: 'import',
+ selected: true,
+ notes_key: null,
+ vendor: 'anthropic',
+ display_name: 'Anthropic',
+ masked_credential: null,
+};
+
+const blockedMigrationCandidate: MigrationItem = {
+ ...migrationCandidate,
+ id: 'mig_claude_keychain',
+ masked_detail: 'Claude native login',
+ proposed_action: 'keep_native',
+};
+
/** The row every re-auth journey starts from: a subscription that stopped. */
const blockedSubscription: Source = {
...nativeSubscription,
@@ -126,14 +146,18 @@ const deferred = <T,>() => {
return { promise, resolve };
};
-const renderPage = (sources: Source[], agents?: AgentSupply[]) => {
+const renderPage = (
+ sources: Source[],
+ agents?: AgentSupply[],
+ runtimeValue: RuntimeDependency = runtime,
+) => {
vi.spyOn(modelsApi, 'listSources').mockResolvedValue(sources);
vi.spyOn(modelsApi, 'listAgents').mockResolvedValue(agents ?? [
directAgent('claude'),
directAgent('codex'),
directAgent('opencode'),
]);
- vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtimeValue);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
vi.spyOn(modelsApi, 'getUsageSummary').mockResolvedValue(usageSummary);
return render(
@@ -166,6 +190,86 @@ afterEach(() => {
});
describe('SettingsModelsPage surface branches', () => {
+ it('opens the consent dialog before Direct-to-Hub takeover and leaves Direct unchanged on cancel', async () => {
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [migrationCandidate] });
+ const apply = vi.spyOn(modelsApi, 'applyMigration');
+ const setMode = vi.spyOn(modelsApi, 'setAgentMode').mockResolvedValue({ ...directAgent('claude'), mode: 'hub' });
+ renderPage([], [directAgent('claude')]);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Switch to gateway|切换到模型网关/i }));
+ const dialog = await screen.findByRole('dialog');
+ expect(within(dialog).getByRole('checkbox', { name: /Claude native login/ })).toBeTruthy();
+ expect(within(dialog).getByText(/After migration|迁移后/)).toBeTruthy();
+
+ await userEvent.click(within(dialog).getByRole('button', { name: /Later|稍后/i }));
+
+ expect(apply).not.toHaveBeenCalled();
+ expect(setMode).not.toHaveBeenCalled();
+ });
+
+ it('uses the ordinary mode switch when Direct has no migration candidates', async () => {
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [] });
+ const apply = vi.spyOn(modelsApi, 'applyMigration');
+ const setMode = vi.spyOn(modelsApi, 'setAgentMode')
+ .mockResolvedValue({ ...directAgent('claude'), mode: 'hub' });
+ renderPage([], [directAgent('claude')]);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Switch to gateway|切换到模型网关/i }));
+ await waitFor(() => expect(setMode).toHaveBeenCalledWith('claude', 'hub'));
+ expect(apply).not.toHaveBeenCalled();
+ });
+
+ it('keeps Direct mode and blocks migration when only unsupported native auth exists', async () => {
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [blockedMigrationCandidate] });
+ const setMode = vi.spyOn(modelsApi, 'setAgentMode')
+ .mockResolvedValue({ ...directAgent('claude'), mode: 'hub' });
+ renderPage([], [directAgent('claude')]);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Switch to gateway|切换到模型网关/i }));
+ const dialog = await screen.findByRole('dialog');
+ expect(within(dialog).getByText(/Use the existing Add flow|现有的添加流程/)).toBeTruthy();
+ expect(
+ (within(dialog).getByRole('button', { name: /Start migration|开始迁移/i }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+ expect(setMode).not.toHaveBeenCalled();
+ });
+
+ it('opens the same migration dialog from an existing Hub user entry', async () => {
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([]);
+ vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [migrationCandidate] });
+ const apply = vi.spyOn(modelsApi, 'applyMigration');
+ renderPage([retainedSource], [{
+ ...directAgent('claude'),
+ mode: 'hub',
+ sources: { order: [], eligibility: [] },
+ }]);
+
+ await userEvent.click(await screen.findByRole('button', { name: /Migrate configuration|迁移配置/i }));
+ const dialog = await screen.findByRole('dialog');
+ expect(within(dialog).getByRole('checkbox', { name: /Claude native login/ })).toBeTruthy();
+ await userEvent.click(within(dialog).getByRole('button', { name: /Later|稍后/i }));
+
+ expect(apply).not.toHaveBeenCalled();
+ });
+
+ it('installs and starts the runtime inline without an install confirmation dialog', async () => {
+ const notInstalled = {
+ ...runtime,
+ status: { ...runtime.status, installed_version: null, verified: false, health: 'not_installed' as const },
+ };
+ const install = vi.spyOn(modelsApi, 'installRuntime').mockResolvedValue({
+ ...notInstalled,
+ status: { ...notInstalled.status, installed_version: '1', verified: true, health: 'not_started' as const },
+ });
+ const start = vi.spyOn(modelsApi, 'startRuntime').mockResolvedValue(runtime);
+ renderPage([], [directAgent('claude')], notInstalled);
+
+ await userEvent.click(await screen.findByRole('switch', { name: /Turn model gateway on|开启模型网关/i }));
+ await waitFor(() => expect(install).toHaveBeenCalledOnce());
+ await waitFor(() => expect(start).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
it.each(['automatic', 'passthrough', 'manual'] as const)('renders %s relations from the actual chain collection for all backends', async (origin) => {
const agents = (['claude', 'codex', 'opencode'] as const).map((backend): AgentSupply => ({
...takeoverAgent, backend, sources: { order: [retainedSource.id], eligibility: [] },
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index a3cd85bba..6798af361 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';
+import { ArrowDownToLine, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Badge } from '@/components/ui/badge';
@@ -13,9 +13,8 @@ import { ToggleSwitch } from '../SettingsPrimitives';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { BackendModelCatalogDialog } from './BackendModelCatalogDialog';
import { OAuthConnectDialog } from './OAuthConnectDialog';
-import { EnableGatewayDialog } from './EnableGatewayDialog';
import { GatewayModule } from './GatewayModule';
-import { InstallGatewayDialog } from './InstallGatewayDialog';
+import { MigrationDialog } from './MigrationDialog';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { RecentSwitchesCard } from './RecentSwitchesCard';
import { RouteChainDialog, type RouteCollectionObservation, type RouteCommitReconciliation, type RouteReport } from './RouteChainDialog';
@@ -62,10 +61,11 @@ import {
unreadRegion,
type RegionRead,
} from './regionRead';
-import { freshRuntimeProjection, pollRuntimeStatus, runtimeCanAttemptInstall, runtimeIsRunning, startRuntimeWithStatusRefresh } from './runtimeLifecycle';
+import { freshRuntimeProjection, pollRuntimeStatus, resumeInstallAndStartRuntime, runtimeCanAttemptInstall, runtimeIsRunning } from './runtimeLifecycle';
import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';
import { useSourceMutationReport } from './useSourceMutationReport';
import { handOffProviderTab } from './providerTab';
+import { resumeGatewayAdoption } from './gatewayAdoption';
import { SUBSCRIPTION_MENU_ROWS, hasNativeSubscriptionCustody } from './subscriptionOptions';
import { VendorGlyph } from './vendorGlyph';
import { backendVisual } from './vendorMeta';
@@ -363,7 +363,8 @@ export const SettingsModelsPage: React.FC = () => {
const [startingRuntime, setStartingRuntime] = React.useState(false);
const [stoppingRuntime, setStoppingRuntime] = React.useState(false);
const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);
- const [installOpen, setInstallOpen] = React.useState(false);
+ const [migrationOpen, setMigrationOpen] = React.useState(false);
+ const [migrationBackend, setMigrationBackend] = React.useState<AgentBackend | null>(null);
const [apiKeyOpen, setApiKeyOpen] = React.useState(false);
const [subscriptionPickerOpen, setSubscriptionPickerOpen] = React.useState(false);
const [subscriptionPickerIndex, setSubscriptionPickerIndex] = React.useState(0);
@@ -837,6 +838,41 @@ export const SettingsModelsPage: React.FC = () => {
}
});
};
+ const switchToGateway = (agent: AgentSupply) => {
+ if (agentWrites.has(agent.backend)) return;
+ setAdoptAgent(agent);
+ setSwitchFailures((previous) => {
+ const next = new Set(previous);
+ next.delete(agent.backend);
+ return next;
+ });
+ void agentWriteRegistry.track(agent.backend, async () => {
+ try {
+ const result = await resumeGatewayAdoption(modelsApi, agentCollectionReads, agent.backend);
+ if (result.runtime) setRuntimeRead(readyRegion(result.runtime));
+ if (!result.ok) {
+ setSwitchFailures((previous) => new Set(previous).add(agent.backend));
+ return;
+ }
+ if (result.candidates.length > 0) {
+ setMigrationBackend(agent.backend);
+ setMigrationOpen(true);
+ return;
+ }
+ const echoed = await modelsApi.setAgentMode(agent.backend, 'hub');
+ setSwitchFailures((previous) => {
+ const next = new Set(previous);
+ next.delete(agent.backend);
+ return next;
+ });
+ await agentSaved(echoed);
+ } catch {
+ setSwitchFailures((previous) => new Set(previous).add(agent.backend));
+ } finally {
+ if (aliveRef.current) setAdoptAgent(null);
+ }
+ });
+ };
const loadOlderEvents = React.useCallback(async () => {
const cursor = feedTailCursor(feed);
if (!cursor) return;
@@ -861,12 +897,24 @@ export const SettingsModelsPage: React.FC = () => {
if (startingRuntime || stoppingRuntime) return;
setStartingRuntime(true);
try {
- const result = await startRuntimeWithStatusRefresh(modelsApi);
+ if (!retainedRuntime) {
+ setRuntimeRead(failRegionRead);
+ setRuntimeRecoveryPending(true);
+ showToast(t('settings.models.errors.startFailed') as string, 'error');
+ return;
+ }
+ const result = await resumeInstallAndStartRuntime(
+ modelsApi,
+ retainedRuntime,
+ (nextRuntime) => {
+ if (aliveRef.current) setRuntimeRead(readyRegion(nextRuntime));
+ },
+ );
setRuntimeRead((previous) => result.runtime === null
? failRegionRead(previous)
: readyRegion(result.runtime));
- setRuntimeRecoveryPending(result.runtime === null);
- if (result.failed) showToast(t('settings.models.errors.startFailed') as string, 'error');
+ setRuntimeRecoveryPending(result.runtime === null || result.failedStep !== null);
+ if (result.failedStep) showToast(t('settings.models.errors.startFailed') as string, 'error');
} finally {
setStartingRuntime(false);
}
@@ -916,8 +964,6 @@ export const SettingsModelsPage: React.FC = () => {
if (runtimeSwitchDisabled) return;
if (runtimeEnabled) {
void stopRuntime();
- } else if (runtimeHealth === 'not_installed') {
- setInstallOpen(true);
} else {
void startRuntime();
}
@@ -1223,6 +1269,18 @@ export const SettingsModelsPage: React.FC = () => {
stopping={stoppingRuntime}
directCount={directEmpty ? installedAgents.length : undefined}
/>
+ {runtimeConfigurationVisible && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-8 gap-1.5 rounded-lg px-2.5 text-[11px] font-semibold"
+ onClick={() => setMigrationOpen(true)}
+ >
+ <ArrowDownToLine className="size-3.5" aria-hidden="true" />
+ {t('settings.models.migration.open')}
+ </Button>
+ )}
{runtimeConfigurationVisible && !directEmpty && <TakeoverPill count={takeoverCount} />}
{runtimeConfigurationVisible && <Button
type="button"
@@ -1257,7 +1315,7 @@ export const SettingsModelsPage: React.FC = () => {
<HubTabs tab={tab} onChange={setTab} />
{tab === 'usage' ? <UsageTab usage={usageRead} windowDays={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
: tab === 'logs' ? <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />
- : directEmpty ? <DirectHome agents={installedAgents} onSwitch={setAdoptAgent} />
+ : directEmpty ? <DirectHome agents={installedAgents} onSwitch={switchToGateway} />
: <div className="model-hub-overview">
<div className="model-hub-overview-body">
<div ref={overviewRef} className="model-hub-overview-grid relative flex flex-col gap-4">
@@ -1360,7 +1418,7 @@ export const SettingsModelsPage: React.FC = () => {
</PopoverContent>
</Popover>
<div className="hidden xl:block" aria-hidden="true" />
- <GatewayModule supply={installedSupplyRead} readFailureCopy={routeCommitStatus?.failed.has('agents') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => routeCommitStatus?.failed.has('agents') ? retryRouteCommit() : void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={setAdoptAgent} onSwitchDirect={switchToDirect} onOpenModels={(agent) => setMenuBackend(agent.backend)} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />
+ <GatewayModule supply={installedSupplyRead} readFailureCopy={routeCommitStatus?.failed.has('agents') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => routeCommitStatus?.failed.has('agents') ? retryRouteCommit() : void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={switchToGateway} onSwitchDirect={switchToDirect} onOpenModels={(agent) => setMenuBackend(agent.backend)} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />
<SupplyGraph containerRef={overviewRef} relations={supplyRelations} />
</div>
<SupplyLegend relations={supplyRelations} />
@@ -1484,28 +1542,22 @@ export const SettingsModelsPage: React.FC = () => {
})();
}}
/>
- {adoptAgent && (
- <EnableGatewayDialog
- key={adoptAgent.backend}
- agent={adoptAgent}
- runtime={runtimeRead}
- agentReads={agentCollectionReads}
- onClose={() => setAdoptAgent(null)}
- onAdopted={agentSaved}
- onRuntime={(next) => {
- setRuntimeRead((previous) => next === null ? failRegionRead(previous) : readyRegion(next));
- }}
- trackWrite={(work) => agentWriteRegistry.track(adoptAgent.backend, work)}
- />
- )}
</>}
- {installOpen && retainedRuntime && (
- <InstallGatewayDialog
- runtime={retainedRuntime}
- onClose={() => setInstallOpen(false)}
- onRuntime={(next) => {
- setRuntimeRead((previous) => next === null ? failRegionRead(previous) : readyRegion(next));
- setRuntimeRecoveryPending(next === null);
+ {migrationOpen && (
+ <MigrationDialog
+ open
+ eligible={migrationBackend
+ ? (item) => item.backend === migrationBackend
+ : undefined}
+ onClose={() => {
+ setMigrationOpen(false);
+ setMigrationBackend(null);
+ }}
+ onApplied={() => {
+ setMigrationOpen(false);
+ setMigrationBackend(null);
+ void refresh();
+ void refreshAgentPresence();
}}
/>
)}
diff --git a/ui/src/components/settings/models/copyAgreement.test.ts b/ui/src/components/settings/models/copyAgreement.test.ts
index b37e6ff53..9a111eef2 100644
--- a/ui/src/components/settings/models/copyAgreement.test.ts
+++ b/ui/src/components/settings/models/copyAgreement.test.ts
@@ -16,12 +16,10 @@
// 2. every `{{count}}` key under `settings.models` belongs to a complete
// `_one`/`_other` family. Both locale files carry both leaves; zh deliberately
// repeats the value so locale parity remains a plain set equality.
-import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import en from '../../../i18n/en.json';
import zh from '../../../i18n/zh.json';
-import { BACKEND_ADOPTION_VENDOR_KEY } from './vendorMeta';
/** Placeholders a join can fill with more than one item. */
const LIST_PLACEHOLDER = /\{\{(?:names|models|agents|sources|backends|list|skipped)\}\}/;
@@ -83,15 +81,4 @@ describe('English copy agrees with the number of things it interpolates', () =>
expect(broken.map((leaf) => `${leaf.key}: ${leaf.text}`)).toEqual([]);
});
- it('resolves gateway-adoption vendor interpolation through locale keys', () => {
- const component = readFileSync(new URL('./EnableGatewayDialog.tsx', import.meta.url), 'utf8');
- const vendorKeys = new Set(Object.values(BACKEND_ADOPTION_VENDOR_KEY));
- expect(component).toContain('BACKEND_ADOPTION_VENDOR_KEY[agent.backend]');
- expect(new Set(Object.keys(en.settings.models.adopt.vendor))).toEqual(vendorKeys);
- expect(new Set(Object.keys(zh.settings.models.adopt.vendor))).toEqual(vendorKeys);
- for (const key of vendorKeys) {
- expect(en.settings.models.adopt.vendor[key]).toBeTruthy();
- expect(zh.settings.models.adopt.vendor[key]).toBeTruthy();
- }
- });
});
diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.ts
index 2eba9a156..961d667ae 100644
--- a/ui/src/components/settings/models/gatewayAdoption.test.ts
+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts
@@ -19,13 +19,18 @@ const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependen
status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },
});
-type GatewayClient = Pick<ModelsApi, 'listAgents' | 'getRuntimeStatus' | 'installRuntime' | 'startRuntime' | 'setAgentMode'>;
+type GatewayClient = Pick<
+ ModelsApi,
+ 'listAgents' | 'getRuntimeStatus' | 'installRuntime' | 'startRuntime' | 'scanMigration' | 'applyMigration' | 'setAgentMode'
+>;
const api = (overrides: Partial<GatewayClient> = {}): GatewayClient => ({
listAgents: vi.fn().mockResolvedValue([agent('direct')]),
getRuntimeStatus: vi.fn().mockResolvedValue(runtime('ok')),
installRuntime: vi.fn().mockResolvedValue(runtime('not_started')),
startRuntime: vi.fn().mockResolvedValue(runtime('ok')),
+ scanMigration: vi.fn().mockResolvedValue({ items: [] }),
+ applyMigration: vi.fn().mockResolvedValue({ applied: 0, sources: [] }),
setAgentMode: vi.fn().mockResolvedValue(agent('hub')),
...overrides,
});
@@ -36,46 +41,57 @@ const adopt = (
) => resumeGatewayAdoption(client, createAgentCollectionReadAuthority(client), 'claude', intervalMs);
describe('resumeGatewayAdoption', () => {
- it('treats degraded as already started and goes straight to the mode PATCH', async () => {
+ it('treats degraded as already started without changing backend mode', async () => {
const client = api({ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('degraded')) });
await expect(adopt(client)).resolves.toMatchObject({ ok: true });
expect(client.startRuntime).not.toHaveBeenCalled();
- expect(client.setAgentMode).toHaveBeenCalledWith('claude', 'hub');
+ expect(client.scanMigration).toHaveBeenCalledOnce();
+ expect(client.applyMigration).not.toHaveBeenCalled();
+ expect(client.setAgentMode).not.toHaveBeenCalled();
});
- it('returns the mode PATCH AgentSupply with its newly materialized native source', async () => {
- const adopted = { ...agent('hub'), sources: { order: ['src_native'], eligibility: [] } };
- const client = api({ setAgentMode: vi.fn().mockResolvedValue(adopted) });
+ it('returns every detected native row for the selection dialog', async () => {
+ const client = api({
+ scanMigration: vi.fn().mockResolvedValue({
+ items: [
+ { id: 'oauth', backend: 'claude', kind: 'oauth_native', masked_detail: 'OAuth', proposed_action: 'import', selected: true },
+ { id: 'keep', backend: 'claude', kind: 'oauth_native', masked_detail: 'Native', proposed_action: 'keep_native', selected: true },
+ { id: 'other', backend: 'codex', kind: 'api_key', masked_detail: 'Key', proposed_action: 'import', selected: true },
+ ],
+ }),
+ });
await expect(adopt(client)).resolves.toMatchObject({
ok: true,
- agent: { mode: 'hub', sources: { order: ['src_native'] } },
+ candidates: [{ id: 'oauth' }, { id: 'keep' }],
});
+ expect(client.applyMigration).not.toHaveBeenCalled();
+ expect(client.setAgentMode).not.toHaveBeenCalled();
});
- it('starts an idle runtime before switching the one backend', async () => {
+ it('starts an idle runtime before scanning the one backend', async () => {
const client = api({ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('not_started')) });
await expect(adopt(client)).resolves.toMatchObject({ ok: true });
expect(client.startRuntime).toHaveBeenCalledOnce();
- expect(client.setAgentMode).toHaveBeenCalledWith('claude', 'hub');
+ expect(client.scanMigration).toHaveBeenCalledOnce();
});
- it('installs, starts, and switches in the order of the first unproven step', async () => {
+ it('installs, starts, and scans in the order of the first unproven step', async () => {
const calls: string[] = [];
const client = api({
getRuntimeStatus: vi.fn().mockResolvedValue(runtime('not_installed')),
installRuntime: vi.fn().mockImplementation(async () => { calls.push('install'); return runtime('not_started'); }),
startRuntime: vi.fn().mockImplementation(async () => { calls.push('start'); return runtime('ok'); }),
- setAgentMode: vi.fn().mockImplementation(async () => { calls.push('mode'); return agent('hub'); }),
+ scanMigration: vi.fn().mockImplementation(async () => { calls.push('scan'); return { items: [] }; }),
});
await expect(adopt(client, 0)).resolves.toMatchObject({ ok: true });
- expect(calls).toEqual(['install', 'start', 'mode']);
+ expect(calls).toEqual(['install', 'start', 'scan']);
});
it('keeps a terminal install failure in the install step and never sends the mode PATCH', async () => {
@@ -94,29 +110,16 @@ describe('resumeGatewayAdoption', () => {
expect(client.setAgentMode).not.toHaveBeenCalled();
});
- it('re-reads agents after a lost mode response and accepts the committed hub mode', async () => {
+ it('keeps Direct mode when the migration scan fails', async () => {
const client = api({
- listAgents: vi.fn()
- .mockResolvedValueOnce([agent('direct')])
- .mockResolvedValueOnce([agent('hub')]),
- setAgentMode: vi.fn().mockRejectedValue(new TypeError('response lost')),
+ scanMigration: vi.fn().mockRejectedValue(new TypeError('response lost')),
});
await expect(adopt(client)).resolves.toMatchObject({
- ok: true,
- agent: { mode: 'hub' },
+ ok: false,
+ failure: { step: 'scan' },
});
-
- expect(client.listAgents).toHaveBeenCalledTimes(2);
- });
-
- it('closes an already-committed retry without touching runtime or mode', async () => {
- const client = api({ listAgents: vi.fn().mockResolvedValue([agent('hub')]) });
-
- await expect(adopt(client)).resolves.toMatchObject({ ok: true });
-
- expect(client.getRuntimeStatus).not.toHaveBeenCalled();
- expect(client.startRuntime).not.toHaveBeenCalled();
+ expect(client.applyMigration).not.toHaveBeenCalled();
expect(client.setAgentMode).not.toHaveBeenCalled();
});
});
diff --git a/ui/src/components/settings/models/gatewayAdoption.ts b/ui/src/components/settings/models/gatewayAdoption.ts
index df9c3094e..c4c2af5b1 100644
--- a/ui/src/components/settings/models/gatewayAdoption.ts
+++ b/ui/src/components/settings/models/gatewayAdoption.ts
@@ -1,17 +1,17 @@
import { apiFailure, type ModelsApi } from './modelsApi';
import type { CollectionReadAuthority } from './collectionReadAuthority';
import { resumeInstallAndStartRuntime } from './runtimeLifecycle';
-import type { AgentBackend, AgentSupply, RuntimeDependency } from './types';
+import type { AgentBackend, AgentSupply, MigrationItem, RuntimeDependency } from './types';
export type GatewayAdoptionFailure = {
- step: 'install' | 'start' | 'mode' | 'read';
+ step: 'install' | 'start' | 'scan' | 'read';
request?: string;
responseStatus?: number;
reason: 'transport' | 'refused' | 'notReady' | 'unknown';
};
export type GatewayAdoptionResult =
- | { ok: true; agent: AgentSupply; runtime: RuntimeDependency | null }
+ | { ok: true; agent: AgentSupply; runtime: RuntimeDependency | null; candidates: MigrationItem[] }
| { ok: false; failure: GatewayAdoptionFailure; runtime: RuntimeDependency | null };
const classifiedFailure = (
@@ -42,12 +42,12 @@ const backendRow = (agents: AgentSupply[], backend: AgentBackend): AgentSupply |
agents.find((agent) => agent.backend === backend) ?? null;
/**
- * Reconciles before every attempt, so retry resumes at the first unproven step.
- * Installation, startup, and mode adoption are separate proven steps. A retry
- * resumes at the first step the server state has not already confirmed.
+ * Prepares a Direct backend for adoption without changing authentication or
+ * routing. A caller opens the shared migration dialog whenever any native row
+ * exists; the dialog decides whether the backend is fully importable.
*/
export async function resumeGatewayAdoption(
- api: Pick<ModelsApi, 'getRuntimeStatus' | 'installRuntime' | 'startRuntime' | 'setAgentMode'>,
+ api: Pick<ModelsApi, 'getRuntimeStatus' | 'installRuntime' | 'startRuntime' | 'scanMigration'>,
agentReads: CollectionReadAuthority<AgentSupply[]>,
backend: AgentBackend,
installPollIntervalMs = 2_000,
@@ -67,7 +67,7 @@ export async function resumeGatewayAdoption(
runtime: null,
};
}
- if (current.mode === 'hub') return { ok: true, agent: current, runtime: null };
+ if (current.mode === 'hub') return { ok: true, agent: current, runtime: null, candidates: [] };
let runtime: RuntimeDependency;
try {
@@ -96,19 +96,13 @@ export async function resumeGatewayAdoption(
}
try {
- const agent = await api.setAgentMode(backend, 'hub');
- return { ok: true, agent, runtime };
+ const scan = await api.scanMigration();
+ const candidates = scan.items.filter((item) => item.backend === backend);
+ return { ok: true, agent: current, runtime, candidates };
} catch (error) {
- try {
- agents = await agentReads.readValue();
- const reconciled = backendRow(agents, backend);
- if (reconciled?.mode === 'hub') return { ok: true, agent: reconciled, runtime };
- } catch {
- // The write failure remains the best evidence; retry will run both reads.
- }
return {
ok: false,
- failure: classifiedFailure(error, 'mode', `PATCH /api/models/agents/${backend}/mode`),
+ failure: classifiedFailure(error, 'scan', 'POST /api/models/migration/scan'),
runtime,
};
}
diff --git a/ui/src/components/settings/models/migrationScan.ts b/ui/src/components/settings/models/migrationScan.ts
index bf9806610..e3f292f83 100644
--- a/ui/src/components/settings/models/migrationScan.ts
+++ b/ui/src/components/settings/models/migrationScan.ts
@@ -8,9 +8,9 @@
// all read `isImportableKey` — a number that came from a different rule than the
// rows behind it is the bug this exists to prevent.
//
-// It is NOT the settings migration's rule. The broader surface legitimately
-// applies `keep_native` (that path creates a native_cli-channel source, see
-// `migration.py`) and shows `reauth` rows for context; this entry copies neither.
+// It is intentionally narrower than the server's complete migration matrix:
+// only API-key-like rows can be handled by the setup notice. OAuth takeover and
+// re-authentication stay in the settings migration flow.
import { modelsApi } from './modelsApi';
import type { MigrationItem, MigrationKind } from './types';
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 5eefaac5c..934af7287 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -1872,136 +1872,6 @@
font-weight: 600;
}
-.model-hub-adopt-overlay {
- background: var(--model-hub-scrim);
-}
-
-.model-hub-adopt-dialog {
- --model-hub-adopt-width: 560px;
- --model-hub-adopt-radius: 14px;
- --model-hub-adopt-shadow: var(--model-hub-dialog-shadow);
- width: min(var(--model-hub-adopt-width), calc(100vw - 32px));
- max-width: var(--model-hub-adopt-width);
- max-height: calc(100dvh - 32px);
- border: 1px solid var(--border-strong);
- border-radius: var(--model-hub-adopt-radius);
- box-shadow: var(--model-hub-adopt-shadow);
-}
-.model-hub-adopt-head {
- --model-hub-adopt-head-gap: 4px;
- --model-hub-adopt-head-padding-x: 20px;
- --model-hub-adopt-head-padding-y: 16px;
- padding: var(--model-hub-adopt-head-padding-y) var(--model-hub-adopt-head-padding-x);
- display: flex;
- flex-direction: column;
- gap: var(--model-hub-adopt-head-gap);
- border-bottom: 1px solid var(--border);
-}
-.model-hub-adopt-title {
- --model-hub-adopt-title-size: 15px;
- font-size: var(--model-hub-adopt-title-size);
- font-weight: 700;
-}
-.model-hub-adopt-close {
- --model-hub-adopt-close-size: 15px;
- width: 27px;
- height: 27px;
- color: var(--model-hub-ink-59);
-}
-.model-hub-adopt-close svg { width: var(--model-hub-adopt-close-size); height: var(--model-hub-adopt-close-size); }
-.model-hub-adopt-subtitle {
- --model-hub-adopt-subtitle-size: 11.5px;
- color: var(--model-hub-muted-b3);
- font-family: 'JetBrains Mono', monospace;
- font-size: var(--model-hub-adopt-subtitle-size);
-}
-.model-hub-adopt-body {
- --model-hub-adopt-body-gap: 16px;
- --model-hub-adopt-body-padding: 20px;
- padding: var(--model-hub-adopt-body-padding);
- display: flex;
- flex-direction: column;
- gap: var(--model-hub-adopt-body-gap);
- overflow-y: auto;
-}
-.model-hub-adopt-section {
- --model-hub-adopt-section-size: 11.5px;
- --model-hub-adopt-section-gap: 8px;
- display: flex;
- flex-direction: column;
- gap: var(--model-hub-adopt-section-gap);
-}
-.model-hub-adopt-section h3 {
- color: var(--model-hub-ink-8c);
- font-size: var(--model-hub-adopt-section-size);
- font-weight: 600;
-}
-.model-hub-adopt-bullet {
- --model-hub-adopt-bullet-line: 20px;
- --model-hub-adopt-bullet-size: 12.5px;
- --model-hub-adopt-bullet-icon: 13px;
- --model-hub-adopt-bullet-gap: 9px;
- display: flex;
- align-items: flex-start;
- gap: var(--model-hub-adopt-bullet-gap);
- color: var(--foreground);
- font-size: var(--model-hub-adopt-bullet-size);
- line-height: var(--model-hub-adopt-bullet-line);
-}
-.model-hub-adopt-bullet svg {
- width: var(--model-hub-adopt-bullet-icon);
- height: var(--model-hub-adopt-bullet-icon);
- margin-top: 3px;
- flex: none;
- color: var(--mint-ink);
-}
-.model-hub-adopt-failure {
- padding: 11px 13px;
- display: flex;
- align-items: flex-start;
- gap: 10px;
- border: 1px solid var(--model-hub-danger-border);
- border-radius: 9px;
- background: var(--model-hub-danger-fill);
-}
-.model-hub-adopt-failure > svg {
- width: 16px;
- height: 16px;
- flex: none;
- color: var(--model-hub-danger-ink);
-}
-.model-hub-adopt-failure strong { display: block; font-size: 12px; font-weight: 600; }
-.model-hub-adopt-failure span span {
- margin-top: 3px;
- display: block;
- color: var(--muted);
- font-family: 'JetBrains Mono', monospace;
- font-size: 10.5px;
-}
-.model-hub-adopt-foot {
- --model-hub-adopt-foot-padding-x: 20px;
- --model-hub-adopt-foot-padding-y: 14px;
- --model-hub-adopt-foot-fill: var(--model-hub-wash-05);
- padding: var(--model-hub-adopt-foot-padding-y) var(--model-hub-adopt-foot-padding-x);
- display: flex;
- align-items: center;
- justify-content: flex-end;
- gap: 8px;
- border-top: 1px solid var(--border);
- background: var(--model-hub-adopt-foot-fill);
-}
-.model-hub-adopt-action {
- --model-hub-adopt-action-size: 12px;
- --model-hub-adopt-action-radius: 7px;
- --model-hub-adopt-action-padding-x: 14px;
- --model-hub-adopt-action-padding-y: 8px;
- min-height: 33px;
- padding: var(--model-hub-adopt-action-padding-y) var(--model-hub-adopt-action-padding-x);
- border-radius: var(--model-hub-adopt-action-radius);
- font-size: var(--model-hub-adopt-action-size);
- font-weight: 600;
-}
-
/* 用量 tab.
*
* design.pen has no frame for this tab on the local surface, so the geometry is
diff --git a/ui/src/components/settings/models/regionRead.test.ts b/ui/src/components/settings/models/regionRead.test.ts
index 1bd6b283e..c85f6b7ff 100644
--- a/ui/src/components/settings/models/regionRead.test.ts
+++ b/ui/src/components/settings/models/regionRead.test.ts
@@ -97,14 +97,6 @@ describe('RegionRead', () => {
expect(violations).toEqual([]);
});
- it('keeps adoption decisions on the tagged runtime read', () => {
- const dialog = readFileSync(join(__dirname, 'EnableGatewayDialog.tsx'), 'utf8');
-
- expect(dialog).toMatch(/runtime: RegionRead<RuntimeDependency>/);
- expect(dialog).toMatch(/foldRegionRead<RuntimeDependency,[\s\S]*?degraded: \(\) => \(\{ kind: 'unavailable' \}\)/);
- expect(dialog).not.toMatch(/runtime: RuntimeDependency \| null/);
- });
-
it('routes overview collections and exact chain reads through the per-backend latest authority', () => {
const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
const definitionStart = page.indexOf('const readChainRequests');
diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.ts
index 5bddef3c3..7c977f997 100644
--- a/ui/src/components/settings/models/serverCopy.ts
+++ b/ui/src/components/settings/models/serverCopy.ts
@@ -11,8 +11,8 @@ import type { TranslationKey } from '@/i18n/types';
// at runtime — a new adapter rev is enough.
//
// i18next's default for a missing key is the key itself, so the honest failure
-// mode without this helper is a machine string ("models.migration.keep_native.
-// sanctioned") rendered to a user as if it were a sentence. This turns that into
+// mode without this helper is a machine string ("models.migration.some_future_code")
+// rendered to a user as if it were a sentence. This turns that into
// the generic copy the surrounding UI already has for the same situation.
//
// Not in format.ts on purpose: that module is deliberately i18n-free (its callers
diff --git a/ui/src/components/settings/models/supplyCopyRedline.test.ts b/ui/src/components/settings/models/supplyCopyRedline.test.ts
index a775ba07a..04d8c2416 100644
--- a/ui/src/components/settings/models/supplyCopyRedline.test.ts
+++ b/ui/src/components/settings/models/supplyCopyRedline.test.ts
@@ -34,10 +34,6 @@ const FALLBACK = /回退|切回|退回|改用|回到|继续用|fall ?back|revert
const CLASSIFIED: Record<string, string> = {
'direct.note.perBackend': 'The user is choosing one backend at a time on the all-direct screen.',
'gateway.fail.switchToDirect': 'Reports a failed user-triggered switch; it does not promise an automatic fallback.',
- 'adopt.undo.1': 'Names the manual, user-triggered undo promised by the adoption dialog.',
- 'adopt.undo.2': 'Names the exact location of that manual undo control.',
- 'migration.nonDestructive':
- 'Describes a manual switch the user may make on the Backends page, not something the Hub does on their behalf.',
};
type Leaf = { key: string; text: string };
diff --git a/ui/src/components/settings/models/vendorMeta.ts b/ui/src/components/settings/models/vendorMeta.ts
index 1e9dc5c71..9b2a6a4df 100644
--- a/ui/src/components/settings/models/vendorMeta.ts
+++ b/ui/src/components/settings/models/vendorMeta.ts
@@ -75,12 +75,6 @@ export const BACKEND_IDENTITY_ACCENT = {
opencode: 'violet',
} as const satisfies Record<AgentBackend, Accent>;
-export const BACKEND_ADOPTION_VENDOR_KEY = {
- claude: 'claude',
- codex: 'chatgpt',
- opencode: 'chatgpt',
-} as const satisfies Record<AgentBackend, string>;
-
const BACKEND_ICON: Record<AgentBackend, IconType> = {
claude: Sparkles,
codex: Bot,
diff --git a/ui/src/components/settings/nativeAuthOwnership.test.tsx b/ui/src/components/settings/nativeAuthOwnership.test.tsx
new file mode 100644
index 000000000..4fa0032d4
--- /dev/null
+++ b/ui/src/components/settings/nativeAuthOwnership.test.tsx
@@ -0,0 +1,252 @@
+// @vitest-environment jsdom
+import { I18nextProvider } from 'react-i18next';
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import { BackendConnectionForm } from './providers/BackendConnectionForm';
+import { BackendOAuthPanel } from './BackendOAuthPanel';
+import { BackendTestPanel } from './BackendTestPanel';
+import { OpencodeProviderTestPanel } from './OpencodeProviderTestPanel';
+
+const mock = vi.hoisted(() => ({
+ api: {
+ getClaudeAuth: vi.fn(),
+ getCodexAuth: vi.fn(),
+ getOpencodeProviders: vi.fn(),
+ getBackendConnection: vi.fn(),
+ saveClaudeAuth: vi.fn(),
+ saveCodexAuth: vi.fn(),
+ setOpencodeProviderAuth: vi.fn(),
+ startOAuthWeb: vi.fn(),
+ startOAuthWebForOpencodeProvider: vi.fn(),
+ getOAuthWebStatus: vi.fn(),
+ submitOAuthWebCode: vi.fn(),
+ cancelOAuthWeb: vi.fn(),
+ removeClaudeOAuthCredentials: vi.fn(),
+ removeBackendAuth: vi.fn(),
+ removeBackendApiKey: vi.fn(),
+ deleteOpencodeProviderAuth: vi.fn(),
+ claudeModels: vi.fn(),
+ codexModels: vi.fn(),
+ testBackendAuth: vi.fn(),
+ testOpencodeProvider: vi.fn(),
+ },
+ toast: vi.fn(),
+}));
+
+vi.mock('@/context/ApiContext', () => ({ useApi: () => mock.api }));
+vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast: mock.toast }) }));
+
+const i18n = createInstance();
+await i18n.init({
+ lng: 'en',
+ fallbackLng: false,
+ resources: { en: { translation: en }, zh: { translation: zh } },
+});
+
+const connection = (backend: 'claude' | 'codex' | 'opencode' = 'claude') => ({
+ ok: true,
+ backend,
+ installed: true,
+ enabled: true,
+ auth: 'api_key',
+ application: 'applied',
+ ready: true,
+ entry_eligible: true,
+});
+
+const claudeAuth = () => ({
+ ok: true,
+ auth_mode: 'api_key',
+ active_auth_mode: 'api_key',
+ has_api_key: true,
+ api_key_length: 20,
+ api_key_masked: 'sk-•••old',
+ base_url: 'https://old.example',
+ credential_type: 'api_key',
+ has_oauth_credentials: true,
+ settings_path: '/fixture/settings.json',
+ settings_exists: true,
+ settings_env_has_key: true,
+ settings_env_key_length: 20,
+ settings_env_key_var: 'ANTHROPIC_API_KEY',
+ settings_env_base_url: 'https://old.example',
+ settings_conflict: false,
+});
+
+const LocationProbe = () => {
+ const location = useLocation();
+ return <span data-testid="location">{location.pathname}</span>;
+};
+
+const renderInRouter = (node: React.ReactNode, initialPath = '/setup') =>
+ render(
+ <MemoryRouter initialEntries={[initialPath]}>
+ <I18nextProvider i18n={i18n}>
+ {node}
+ <LocationProbe />
+ </I18nextProvider>
+ </MemoryRouter>,
+ );
+
+beforeEach(async () => {
+ await i18n.changeLanguage('en');
+ vi.resetAllMocks();
+ mock.api.getClaudeAuth.mockResolvedValue(claudeAuth());
+ mock.api.getCodexAuth.mockResolvedValue({
+ ...claudeAuth(),
+ has_chatgpt_tokens: true,
+ credentials_store: 'file',
+ file_store_active: true,
+ });
+ mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [] });
+ mock.api.getBackendConnection.mockImplementation(async (backend: 'claude' | 'codex' | 'opencode') => connection(backend));
+ mock.api.saveClaudeAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.saveCodexAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.setOpencodeProviderAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
+ mock.api.cancelOAuthWeb.mockResolvedValue({ ok: true });
+ mock.api.claudeModels.mockResolvedValue({ ok: true, models: [] });
+ mock.api.codexModels.mockResolvedValue({ ok: true, models: [] });
+});
+
+afterEach(() => cleanup());
+
+describe('native authentication ownership presentation', () => {
+ it('uses Hub supply mode before touching native auth stores', async () => {
+ mock.api.getBackendConnection.mockResolvedValue({
+ ...connection('claude'),
+ supply_mode: 'hub',
+ ready: false,
+ entry_eligible: false,
+ auth: 'none',
+ });
+ renderInRouter(
+ <BackendConnectionForm
+ backend="claude"
+ compact
+ initialMethod="api_key"
+ onCancel={vi.fn()}
+ />,
+ );
+
+ expect(await screen.findByText(en.settings.backends.nativeAuthHubOwned)).toBeTruthy();
+ expect(mock.api.getClaudeAuth).not.toHaveBeenCalled();
+ });
+
+ it('shows the localized compact onboarding notice and navigates to Model Hub', async () => {
+ const onCancel = vi.fn();
+ mock.api.saveClaudeAuth.mockResolvedValue({
+ ok: false,
+ error: 'native_auth_hub_owned',
+ reauth_channel: 'hub',
+ });
+ renderInRouter(
+ <BackendConnectionForm
+ backend="claude"
+ compact
+ initialMethod="api_key"
+ onCancel={onCancel}
+ />,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.saveConnect }));
+ expect(await screen.findByText(en.settings.backends.nativeAuthHubOwned)).toBeTruthy();
+ expect(screen.queryByText('native_auth_hub_owned')).toBeNull();
+
+ fireEvent.click(screen.getByRole('link', { name: en.settings.backends.openModelHub }));
+ expect(onCancel).toHaveBeenCalledOnce();
+ expect(screen.getByTestId('location').textContent).toBe('/settings/models');
+ });
+
+ it('shows the same ownership notice in Settings in Chinese without exposing the code', async () => {
+ await i18n.changeLanguage('zh');
+ mock.api.saveClaudeAuth.mockResolvedValue({
+ ok: false,
+ error: 'native_auth_hub_owned',
+ reauth_channel: 'hub',
+ });
+ renderInRouter(
+ <BackendConnectionForm backend="claude" initialMethod="api_key" />,
+ '/settings/backends/claude',
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: zh.common.save }));
+ expect(await screen.findByText(zh.settings.backends.nativeAuthHubOwned)).toBeTruthy();
+ expect(screen.getByRole('link', { name: zh.settings.backends.openModelHub })).toBeTruthy();
+ expect(screen.queryByText('native_auth_hub_owned')).toBeNull();
+ });
+
+ it('classifies an OAuth start refusal before requiring a flow id', async () => {
+ const onCancel = vi.fn();
+ mock.api.startOAuthWeb.mockResolvedValue({
+ ok: false,
+ error: 'native_auth_hub_owned',
+ reauth_channel: 'hub',
+ });
+ renderInRouter(
+ <BackendConnectionForm backend="claude" compact onCancel={onCancel} />,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: en.onboarding.connection.claudeSignIn }));
+ expect(await screen.findByText(en.settings.backends.nativeAuthHubOwned)).toBeTruthy();
+ expect(screen.queryByText('native_auth_hub_owned')).toBeNull();
+ expect(mock.api.saveClaudeAuth).not.toHaveBeenCalled();
+ });
+
+ it('maps OAuth removal refusal to the existing Model Hub action', async () => {
+ mock.api.removeBackendAuth.mockResolvedValue({
+ ok: false,
+ error: 'native_auth_hub_owned',
+ reauth_channel: 'hub',
+ });
+ renderInRouter(
+ <BackendOAuthPanel
+ backend="claude"
+ signedIn
+ canRemoveAuth
+ title="Claude"
+ subtitle="Fixture"
+ />,
+ '/settings/backends/claude',
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.oauthRemove }));
+ expect(await screen.findByText(en.settings.backends.nativeAuthHubOwned)).toBeTruthy();
+ expect(screen.getByRole('link', { name: en.settings.backends.openModelHub })).toBeTruthy();
+ expect(screen.queryByText('native_auth_hub_owned')).toBeNull();
+ });
+
+ it.each([
+ ['Claude', BackendTestPanel, undefined],
+ ['OpenCode', OpencodeProviderTestPanel, 'provider'],
+ ] as const)('maps %s probe refusal without a raw error code', async (_name, Panel, providerId) => {
+ if (providerId) {
+ mock.api.testOpencodeProvider.mockResolvedValue({
+ ok: false,
+ error: 'native_auth_hub_owned',
+ reauth_channel: 'hub',
+ });
+ renderInRouter(
+ <Panel providerId="fixture" providerName="Fixture" models={['model']} />,
+ '/settings/backends/opencode',
+ );
+ fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.testConnectionRun }));
+ } else {
+ mock.api.testBackendAuth.mockResolvedValue({
+ ok: false,
+ error: 'native_auth_hub_owned',
+ reauth_channel: 'hub',
+ });
+ renderInRouter(<Panel backend="claude" />, '/settings/backends/claude');
+ fireEvent.click(await screen.findByRole('button', { name: en.settings.backends.testConnectionRun }));
+ }
+
+ expect(await screen.findByText(en.settings.backends.nativeAuthHubOwned)).toBeTruthy();
+ expect(screen.getByRole('link', { name: en.settings.backends.openModelHub })).toBeTruthy();
+ expect(screen.queryByText('native_auth_hub_owned')).toBeNull();
+ });
+});
diff --git a/ui/src/components/settings/oauth/useBackendOAuth.ts b/ui/src/components/settings/oauth/useBackendOAuth.ts
index 131b6fa07..d83e9c077 100644
--- a/ui/src/components/settings/oauth/useBackendOAuth.ts
+++ b/ui/src/components/settings/oauth/useBackendOAuth.ts
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { useApi, type OAuthWebStartResult, type OAuthWebState } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { errorMessage } from '@/lib/errorMessage';
+import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';
export type OAuthBackend = 'claude' | 'codex' | 'opencode';
const POLL_INTERVAL_MS = 2000;
@@ -31,6 +32,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
const [submitting, setSubmitting] = useState(false);
const [starting, setStarting] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [hubOwnedAuth, setHubOwnedAuth] = useState(false);
const owner = useRef({ generation: 0, mounted: true, flowId: '', busy: false, submitting: false, deadline: 0 });
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const callbacks = useRef({ onSuccess, onFailure, onCancel, onActiveChange, onPendingChange });
@@ -79,13 +81,33 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
owner.current.flowId = '';
owner.current.busy = false;
owner.current.submitting = false;
- setState('idle'); setUrl(null); setDeviceCode(null); setCode(''); setError(null);
+ setState('idle'); setUrl(null); setDeviceCode(null); setCode(''); setError(null); setHubOwnedAuth(false);
setStarting(false); setSubmitting(false);
callbacks.current.onActiveChange?.(false);
};
+ const settleHubOwnedAuth = (generation: number) => {
+ stopPolling();
+ owner.current.generation += 1;
+ owner.current.flowId = '';
+ owner.current.busy = false;
+ owner.current.submitting = false;
+ setStarting(false);
+ setSubmitting(false);
+ setHubOwnedAuth(true);
+ setError(null);
+ setState('failed');
+ settled(generation);
+ callbacks.current.onActiveChange?.(false);
+ };
const accept = async (data: OAuthWebStartResult, generation: number) => {
if (!current(generation)) return;
- if (!data.ok) throw new Error(data.detail || data.error || 'flow_not_found');
+ if (!data.ok) {
+ if (isNativeAuthHubOwned(data)) {
+ settleHubOwnedAuth(generation);
+ return;
+ }
+ throw new Error(data.detail || data.error || 'flow_not_found');
+ }
if (data.callback_kind) setCallbackKind(data.callback_kind);
if (data.url) setUrl(data.url);
if (data.device_code) setDeviceCode(data.device_code);
@@ -104,6 +126,10 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
return;
}
if (data.state === 'failed' || data.state === 'cancelled') {
+ if (data.state === 'failed' && isNativeAuthHubOwned(data)) {
+ settleHubOwnedAuth(generation);
+ return;
+ }
if (data.state === 'failed') await callbacks.current.onFailure?.(data.error || data.state);
if (!current(generation)) return;
throw new Error(data.error || data.state);
@@ -115,6 +141,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
const fail = (err: unknown, generation: number) => {
if (!current(generation)) return;
stopPolling();
+ setHubOwnedAuth(false);
setError(errorMessage(err) || 'auth_failed'); setState('failed');
// Cancel a failed local polling attempt as well; it must not finish later
// behind a newly selected method. Server cancellation never logs out.
@@ -138,7 +165,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
callbacks.current.onPendingChange?.(true);
owner.current.busy = true;
owner.current.deadline = Date.now() + POLL_DEADLINE_MS;
- setStarting(true); setState('starting'); setError(null); setCode(''); setUrl(null); setDeviceCode(null); setCallbackKind(null);
+ setStarting(true); setState('starting'); setError(null); setHubOwnedAuth(false); setCode(''); setUrl(null); setDeviceCode(null); setCallbackKind(null);
callbacks.current.onActiveChange?.(true);
try {
const result = backend === 'opencode'
@@ -150,7 +177,12 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
return;
}
owner.current.flowId = result.flow_id || '';
- if (!result.flow_id) throw new Error(result.detail || result.error || 'start_failed');
+ // Terminal ownership refusals do not create a local OAuth flow. Let the
+ // shared response consumer classify that payload before applying the
+ // ordinary missing-flow failure.
+ if (!result.flow_id && !isNativeAuthHubOwned(result)) {
+ throw new Error(result.detail || result.error || 'start_failed');
+ }
await accept(result, generation);
} catch (err) { if (current(generation)) fail(err, generation); else settled(generation); }
finally { if (current(generation)) setStarting(false); }
@@ -180,7 +212,13 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
try {
const result = await api.submitOAuthWebCode(backend, owner.current.flowId, code.trim());
if (!current(generation)) return;
- if (!result.ok) throw new Error(result.detail || result.error || 'submit_failed');
+ if (!result.ok) {
+ if (isNativeAuthHubOwned(result)) {
+ settleHubOwnedAuth(generation);
+ return;
+ }
+ throw new Error(result.detail || result.error || 'submit_failed');
+ }
setState('verifying');
} catch (err) { if (current(generation)) setError(errorMessage(err) || 'submit_failed'); }
finally {
@@ -194,7 +232,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFail
catch { showToast(t('common.copyFailed'), 'error'); }
};
const isActive = state === 'starting' || state === 'awaiting_code' || state === 'verifying';
- return { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError,
+ return { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError, hubOwnedAuth,
isActive, startFlow, cancelFlow, submitCallback, resetToIdle,
copyUrl: (e?: React.MouseEvent) => copy(url, e), copyDeviceCode: (e?: React.MouseEvent) => copy(deviceCode, e) };
}
diff --git a/ui/src/components/settings/providers/BackendConnectionForm.tsx b/ui/src/components/settings/providers/BackendConnectionForm.tsx
index 32c16ac54..1b88cb65c 100644
--- a/ui/src/components/settings/providers/BackendConnectionForm.tsx
+++ b/ui/src/components/settings/providers/BackendConnectionForm.tsx
@@ -4,10 +4,12 @@ import { CheckCircle2, ExternalLink, Eye, EyeOff, KeyRound, LoaderCircle, Pencil
import { useApi, type ClaudeAuthState, type CodexAuthState, type OpencodeProvider, type OAuthWebMutationResult } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { errorMessage } from '@/lib/errorMessage';
+import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { MethodRadio } from './MethodRadio';
+import { HubOwnedAuthNotice } from '../shared/HubOwnedAuthNotice';
import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';
import { useBackendOAuth, type OAuthBackend } from '../oauth/useBackendOAuth';
import { BackendOAuthPanel } from '../BackendOAuthPanel';
@@ -141,6 +143,7 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
const [active, setActive] = useState(false);
const [applyPending, setApplyPending] = useState(false);
const [authReadable, setAuthReadable] = useState(false);
+ const [hubOwnedAuth, setHubOwnedAuth] = useState(false);
const observation = useRef(0);
const touched = useRef(new Set<Editable>());
/**
@@ -197,6 +200,26 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
const token = ++observation.current;
const current = () => lifetime.current.mounted && token === observation.current;
setConnected(false); setSavedDisabled(false); setError(receiptError);
+ const [application] = await Promise.allSettled([api.getBackendConnection(backend)]);
+ if (!current()) return false;
+ const messages = receiptError ? [receiptError] : [];
+ const connection = application.status === 'fulfilled' ? application.value : null;
+ const applied = connection?.ok && ['applied', 'stopped'].includes(connection.application);
+ if (!applied) messages.push(application.status === 'rejected' ? errorMessage(application.reason) || t('onboarding.connection.readFailed') : connection?.message || t('onboarding.connection.applyPending'));
+ const supplyMode = connection?.ok === true ? connection.supply_mode : undefined;
+ setHubOwnedAuth(supplyMode === 'hub');
+ if (supplyMode === 'hub') {
+ setLoading(false);
+ setAuthReadable(false);
+ setNative(null);
+ setCurrentProvider(provider);
+ setError([...new Set(messages)].join(' '));
+ setApplyPending(messages.length > 0);
+ setConnected(false);
+ setSavedDisabled(false);
+ return messages.length === 0;
+ }
+
const pristine = () => touched.current.size === 0;
const nativeRead = read().then((fresh) => {
if (current()) {
@@ -215,13 +238,9 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
if (current()) setAuthReadable(false);
throw cause;
});
- const [auth, application] = await Promise.allSettled([nativeRead, api.getBackendConnection(backend)]);
+ const [auth] = await Promise.allSettled([nativeRead]);
if (!current()) return false;
setLoading(false);
- const messages = receiptError ? [receiptError] : [];
- const connection = application.status === 'fulfilled' ? application.value : null;
- const applied = connection?.ok && ['applied', 'stopped'].includes(connection.application);
- if (!applied) messages.push(application.status === 'rejected' ? errorMessage(application.reason) || t('onboarding.connection.readFailed') : connection?.message || t('onboarding.connection.applyPending'));
let hasAuth = false;
let keylessSettings = false;
if (auth.status === 'rejected') messages.push(errorMessage(auth.reason) || t('onboarding.connection.readFailed'));
@@ -316,6 +335,12 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
};
const removed = async (result: OAuthWebMutationResult) => {
pendingConfirmation.current = null;
+ if (isNativeAuthHubOwned(result)) {
+ setHubOwnedAuth(true);
+ setError('');
+ setApplyPending(false);
+ return false;
+ }
return observe({ receiptError: !result.ok ? result.error || result.detail || t('onboarding.connection.saveFailed')
: result.restart?.ok === false ? result.restart.message || t('onboarding.connection.applyFailed') : '' });
};
@@ -337,10 +362,10 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
try { const url = new URL(baseUrl.trim()); return ['http:', 'https:'].includes(url.protocol) && Boolean(url.hostname); }
catch { return false; }
})();
- const canSave = !loading && authReadable && !busy && urlValid && Boolean(key.trim() || (hasKey && !editing) || (!compact && currentProvider?.custom && currentProvider.configured && !editing));
+ const canSave = !loading && !hubOwnedAuth && authReadable && !busy && urlValid && Boolean(key.trim() || (hasKey && !editing) || (!compact && currentProvider?.custom && currentProvider.configured && !editing));
const save = async () => {
if (!canSave || lifetime.current.busy) return;
- lifetime.current.busy = true; observation.current += 1; writeState.current?.(true); setSaving(true); setError(''); setConnected(false); setSavedDisabled(false);
+ lifetime.current.busy = true; observation.current += 1; writeState.current?.(true); setSaving(true); setError(''); setConnected(false); setSavedDisabled(false); setHubOwnedAuth(false);
// What this write carries, decided here rather than when the receipt lands: by
// then the visible type may be the other one, and the draft or the address may
// be newer work than the one that went out. `sent` follows the payload exactly
@@ -352,7 +377,15 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
: backend === 'codex' ? await api.saveCodexAuth(payload)
: await api.setOpencodeProviderAuth(provider!.id, payload.api_key, payload.base_url);
if (!lifetime.current.mounted) return;
- if (!result.ok) throw new Error(result.message || t('onboarding.connection.saveFailed'));
+ if (!result.ok) {
+ if (isNativeAuthHubOwned(result)) {
+ pendingConfirmation.current = null;
+ setHubOwnedAuth(true);
+ setApplyPending(false);
+ return;
+ }
+ throw new Error(result.message || t('onboarding.connection.saveFailed'));
+ }
if ('notices' in result) surfaceBackendNotices(result.notices, showToast, t);
if ('partial' in result && result.partial) showToast(result.detail || result.warning || t('onboarding.connection.partial'), 'warning');
await confirm(submitted, result.restart?.ok === false ? result.restart.message || t('onboarding.connection.applyFailed') : '');
@@ -366,12 +399,20 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
};
const remove = async (onlyKey: boolean) => {
if (lifetime.current.busy || !window.confirm(t('onboarding.connection.removeConfirm'))) return;
- lifetime.current.busy = true; observation.current += 1; writeState.current?.(true); setSaving(true); setError(''); setConnected(false); setSavedDisabled(false);
+ lifetime.current.busy = true; observation.current += 1; writeState.current?.(true); setSaving(true); setError(''); setConnected(false); setSavedDisabled(false); setHubOwnedAuth(false);
try {
const result = backend === 'opencode' ? await api.deleteOpencodeProviderAuth(provider!.id)
: onlyKey ? await api.removeBackendApiKey(backend) : await api.removeBackendAuth(backend);
if (!lifetime.current.mounted) return;
- if (!result.ok) throw new Error(('message' in result ? result.message : 'detail' in result ? result.detail : undefined) || t('onboarding.connection.saveFailed'));
+ if (!result.ok) {
+ if (isNativeAuthHubOwned(result)) {
+ pendingConfirmation.current = null;
+ setHubOwnedAuth(true);
+ setApplyPending(false);
+ return;
+ }
+ throw new Error(('message' in result ? result.message : 'detail' in result ? result.detail : undefined) || t('onboarding.connection.saveFailed'));
+ }
if ('notices' in result) surfaceBackendNotices(result.notices, showToast, t);
await removed(result);
} catch (err) {
@@ -400,7 +441,7 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
// their own rows of the dialog grid, which is what keeps the heading, tabs and
// footer still while the body changes underneath them.
return <div className="backend-connection-form">
- {!(compact && active && backend !== 'codex') && (backend !== 'opencode' || (!compact && provider?.oauth_available)) && <MethodRadio
+ {!hubOwnedAuth && !(compact && active && backend !== 'codex') && (backend !== 'opencode' || (!compact && provider?.oauth_available)) && <MethodRadio
value={method} onChange={(value) => { if (!busy && !loading) { pendingConfirmation.current = null; touched.current.add('method'); setMethod(value); setError(''); setConnected(false); } }} disabled={busy || loading}
ariaLabel={t('onboarding.connection.method')}
options={[{ id: 'oauth', label: backend === 'claude' ? t('onboarding.connection.claudeLogin') : backend === 'codex' ? t('onboarding.connection.codexSignIn') : t('onboarding.connection.subscription') },
@@ -409,12 +450,13 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
{loading && <div className="connection-loading" role="status"><LoaderCircle className="animate-spin" size={16} />{t('common.loading')}</div>}
{/* The method's own instructions live here, not in the dialog heading: the
heading and description are anchored and method-independent. */}
- {!loading && compact && <p className="connection-intro">{t(method === 'api_key'
+ {!loading && !hubOwnedAuth && compact && <p className="connection-intro">{t(method === 'api_key'
? backend === 'claude' ? 'onboarding.connection.claudeKeyIntro' : backend === 'codex' ? 'onboarding.connection.codexKeyIntro' : 'onboarding.connection.providerKeyIntro'
: backend === 'claude' ? active ? 'onboarding.connection.claudeCompleteIntro' : 'onboarding.connection.claudeIntro'
: backend === 'codex' ? active ? 'onboarding.connection.codexCompleteIntro' : 'onboarding.connection.codexIntro'
: 'onboarding.connection.providerIntro', { name: provider?.name })}</p>}
- {!loading && <>
+ {!loading && hubOwnedAuth && <HubOwnedAuthNotice onNavigate={compact ? onCancel : undefined} />}
+ {!loading && !hubOwnedAuth && <>
{uncertain && <p className="connection-notice">{t('onboarding.connection.uncertain')}</p>}
{native && 'file_store_active' in native && method === 'api_key' && !native.file_store_active && !uncertain && <p className="connection-notice">{t('settings.backends.codexCredentialsStoreKeyringWarn', { store: native.credentials_store })}</p>}
{native && 'settings_conflict' in native && native.settings_conflict && <p className="connection-notice">{t('settings.backends.claudeSettingsConflictTitle')}: {t('settings.backends.claudeSettingsConflictBody', { var: native.settings_env_key_var || 'ANTHROPIC_API_KEY', path: native.settings_path })}</p>}
@@ -426,7 +468,8 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
title={title} subtitle={hint} hideRemove={backend === 'opencode'} onSuccess={confirmOAuth} onRemoved={removed} onFailure={observeOAuthFailure} onCancel={() => { pendingConfirmation.current = null; observation.current += 1; }} onActiveChange={setActive}
canRemoveAuth={authReadable && Boolean(native && ('has_oauth_credentials' in native ? native.has_oauth_credentials : native.has_chatgpt_tokens))}
signedInDetail={native && 'chatgpt_account' in native && native.chatgpt_account ? [native.chatgpt_account.email, native.chatgpt_account.plan_type, (native.chatgpt_account.organizations?.find((org) => org.is_default) || native.chatgpt_account.organizations?.[0])?.title].filter(Boolean).join(' · ') : undefined} /> : <>
- {oauth.error && <p className="connection-error" role="alert">{oauth.error}</p>}
+ {oauth.hubOwnedAuth && <HubOwnedAuthNotice onNavigate={onCancel} />}
+ {oauth.error && !oauth.hubOwnedAuth && <p className="connection-error" role="alert">{oauth.error}</p>}
{!oauth.isActive ? <div className="connection-account"><h3>{title}</h3><p>{hint}</p>
{signedIn && <p className="connection-confirmed">{t('onboarding.connection.savedSubscription')}</p>}
<div><Button variant="brand" onClick={() => void oauth.startFlow()} disabled={oauth.starting}><ExternalLink size={15} />{startLabel}</Button></div>
@@ -458,11 +501,11 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut
</>}
</>}
</div>
- {(compact || method === 'api_key') && <div className="connection-actions">
+ {(compact || (!hubOwnedAuth && method === 'api_key')) && <div className="connection-actions">
{compact && <Button variant="secondary" onClick={onCancel}>{t('common.cancel')}</Button>}
- {!compact && hasKey && method === 'api_key' && <Button variant="ghost" disabled={busy} onClick={() => void remove(true)}>{t('settings.backends.claudeApiKeyRemove')}</Button>}
- {method === 'api_key' && <Button variant="brand" disabled={!canSave} onClick={() => void save()}>{saving ? t(compact ? 'onboarding.connection.connecting' : 'common.saving') : t(compact ? 'onboarding.connection.saveConnect' : 'common.save')}</Button>}
- {compact && needsCode && <Button variant="brand" disabled={!oauth.code.trim() || oauth.submitting} onClick={() => void oauth.submitCallback()}>{oauth.submitting ? t('onboarding.connection.connecting') : t('onboarding.connection.finishConnect')}</Button>}
+ {!hubOwnedAuth && !compact && hasKey && method === 'api_key' && <Button variant="ghost" disabled={busy} onClick={() => void remove(true)}>{t('settings.backends.claudeApiKeyRemove')}</Button>}
+ {!hubOwnedAuth && method === 'api_key' && <Button variant="brand" disabled={!canSave} onClick={() => void save()}>{saving ? t(compact ? 'onboarding.connection.connecting' : 'common.saving') : t(compact ? 'onboarding.connection.saveConnect' : 'common.save')}</Button>}
+ {!hubOwnedAuth && compact && needsCode && <Button variant="brand" disabled={!oauth.code.trim() || oauth.submitting} onClick={() => void oauth.submitCallback()}>{oauth.submitting ? t('onboarding.connection.connecting') : t('onboarding.connection.finishConnect')}</Button>}
</div>}
</div>;
}
diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
index 878b94a54..dbb528fe6 100644
--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
@@ -42,7 +42,9 @@ import type {
} from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { errorMessage } from '@/lib/errorMessage';
+import { isNativeAuthHubOwned } from '@/lib/nativeAuthOwnership';
import { EFFORT_BY_BACKEND, sortEffortsByVocabulary } from '@/lib/effortOptions';
+import { HubOwnedAuthNotice } from '../shared/HubOwnedAuthNotice';
type FilterMode = 'all' | 'configured' | 'oauth' | 'local';
type CustomProviderAdapter = 'openai-compatible' | 'anthropic-compatible';
@@ -60,6 +62,7 @@ type ProviderEditState = {
removing: boolean;
deletingProvider: boolean;
error: string | null;
+ hubOwnedAuth: boolean;
// Mirrors the Codex / Claude pattern: false = show ``api_key_masked``
// read-only with a Replace button; true = empty editable input ready
// for a fresh key. Toggled by the pencil button next to the masked
@@ -76,6 +79,7 @@ type CustomProviderDraft = {
apiKey: string;
saving: boolean;
error: string | null;
+ hubOwnedAuth: boolean;
};
const BACKEND_ID = 'opencode';
@@ -111,6 +115,7 @@ const emptyEdit = (): ProviderEditState => ({
removing: false,
deletingProvider: false,
error: null,
+ hubOwnedAuth: false,
editingKey: false,
});
@@ -128,6 +133,7 @@ const emptyCustomProviderDraft = (): CustomProviderDraft => ({
apiKey: '',
saving: false,
error: null,
+ hubOwnedAuth: false,
});
const slugProviderId = (value: string): string =>
@@ -407,7 +413,7 @@ export const OpencodeProviderConfig: React.FC<{
return;
}
- updateCustomProviderDraft({ saving: true, error: null });
+ updateCustomProviderDraft({ saving: true, error: null, hubOwnedAuth: false });
try {
const result = await api.saveOpencodeCustomProvider({
provider_id: providerId,
@@ -417,6 +423,10 @@ export const OpencodeProviderConfig: React.FC<{
...(apiKey ? { api_key: apiKey } : {}),
});
if (!result.ok) {
+ if (isNativeAuthHubOwned(result)) {
+ updateCustomProviderDraft({ saving: false, error: null, hubOwnedAuth: true });
+ return;
+ }
updateCustomProviderDraft({
saving: false,
error: result.message || (t('settings.backends.opencodeCustomProviderSaveFailed') as string),
@@ -483,10 +493,14 @@ export const OpencodeProviderConfig: React.FC<{
t(confirmKey, { name: provider.name }) as string,
);
if (!confirmed) return;
- updateEdit(provider.id, { removing: true, error: null });
+ updateEdit(provider.id, { removing: true, error: null, hubOwnedAuth: false });
try {
const result = await api.deleteOpencodeProviderAuth(provider.id);
if (!result.ok) {
+ if (isNativeAuthHubOwned(result)) {
+ updateEdit(provider.id, { removing: false, error: null, hubOwnedAuth: true });
+ return;
+ }
updateEdit(provider.id, {
removing: false,
error: result.message || (t('settings.backends.opencodeProviderRemoveFailed') as string),
@@ -951,6 +965,7 @@ export const OpencodeProviderConfig: React.FC<{
{customProviderDraft.error}
</div>
)}
+ {customProviderDraft.hubOwnedAuth && <div className="mt-3"><HubOwnedAuthNotice /></div>}
<div className="mt-3 flex justify-end">
<Button
type="button"
@@ -1286,6 +1301,7 @@ export const OpencodeProviderConfig: React.FC<{
</span>
)}
</div>
+ {edit.hubOwnedAuth && <HubOwnedAuthNotice />}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="flex flex-col gap-3">
diff --git a/ui/src/components/settings/shared/HubOwnedAuthNotice.tsx b/ui/src/components/settings/shared/HubOwnedAuthNotice.tsx
new file mode 100644
index 000000000..9b96ab042
--- /dev/null
+++ b/ui/src/components/settings/shared/HubOwnedAuthNotice.tsx
@@ -0,0 +1,31 @@
+import { ArrowRight, ShieldCheck } from 'lucide-react';
+import { Link } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+
+import { MODEL_HUB_SETTINGS_PATH } from '../models/modelHubRoutes';
+
+export function HubOwnedAuthNotice({ onNavigate }: { onNavigate?: () => void }) {
+ const { t } = useTranslation();
+
+ return (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-md border border-border bg-surface-2/60 px-3 py-2"
+ >
+ <ShieldCheck className="mt-0.5 size-3.5 shrink-0 text-muted" />
+ <div className="flex min-w-0 flex-col gap-1">
+ <p className="text-[12px] leading-relaxed text-foreground">
+ {t('settings.backends.nativeAuthHubOwned')}
+ </p>
+ <Link
+ to={MODEL_HUB_SETTINGS_PATH}
+ onClick={onNavigate}
+ className="inline-flex w-fit items-center gap-1 text-[12px] font-medium text-cyan-ink hover:text-cyan-ink/80"
+ >
+ {t('settings.backends.openModelHub')}
+ <ArrowRight className="size-3" aria-hidden="true" />
+ </Link>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index 8bedf41e5..f972aa0cb 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -9,7 +9,7 @@ import {
RefreshCw,
Sliders,
} from 'lucide-react';
-import { Link } from 'react-router-dom';
+import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
@@ -30,6 +30,8 @@ import type { BackendId as RuntimeBackendId } from '../settings/shared/useBacken
import { useOpencodePermission } from '../settings/shared/useOpencodePermission';
import { Button } from '../ui/button';
import { DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/agentBackends';
+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
+import { MODEL_HUB_SETTINGS_PATH } from '../settings/models/modelHubRoutes';
interface AgentDetectionProps {
data: any;
@@ -78,6 +80,8 @@ const normalizeAgents = (source: any): Record<string, AgentState> => {
export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave, completionRecovery }) => {
const { t } = useTranslation();
const api = useApi();
+ const navigate = useNavigate();
+ const routeSurfaceActive = useRouteSurfaceActive();
const modelHubEnabled = useModelHubCapability();
const [agents, setAgents] = useState<Record<string, AgentState>>(normalizeAgents(data));
const permission = useOpencodePermission({ autoFetchStatus: true });
@@ -95,6 +99,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const [entering, setEntering] = useState(false);
const [entryError, setEntryError] = useState('');
const connectionTokens = useRef<Partial<Record<RuntimeBackendId, number>>>({});
+ const previousRouteSurfaceActive = useRef(routeSurfaceActive);
const enableQueue = useRef(Promise.resolve());
const enableIntent = useRef<Partial<Record<RuntimeBackendId, number>>>({});
const pendingEnable = useRef<Partial<Record<RuntimeBackendId, number>>>({});
@@ -135,6 +140,13 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
enableIntent.current[name] = (enableIntent.current[name] || 0) + 1;
} };
}, [refreshConnection, isPage]);
+ useEffect(() => {
+ const returnedToSurface = routeSurfaceActive && !previousRouteSurfaceActive.current;
+ previousRouteSurfaceActive.current = routeSurfaceActive;
+ if (!isPage && returnedToSurface) {
+ for (const name of ASSISTANT_ORDER) void refreshConnection(name);
+ }
+ }, [isPage, refreshConnection, routeSurfaceActive]);
const isAnyInstalling = Object.values(installingAgents).some(Boolean);
@@ -516,9 +528,25 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
return <AssistantRow key={name} backend={name} status={agent.status || 'unknown'}
installing={!!installingAgents[name]} detecting={!!detectingAgents[name]} error={error}
onInstall={() => void installAgent(name)} onDetect={() => void detect(name, agent.cli_path)}
- onConfigure={() => setProviderModal({ backend: name, method: 'oauth' })}
- onAddKey={() => setProviderModal({ backend: name, method: 'api_key' })}
- connection={!connectionErrors[name] && connections[name]?.ready ? (connections[name]?.auth === 'subscription' ? 'subscription' : 'api_key') : undefined}
+ onConfigure={() => {
+ if (connections[name]?.supply_mode === 'hub') {
+ navigate(MODEL_HUB_SETTINGS_PATH);
+ return;
+ }
+ setProviderModal({ backend: name, method: 'oauth' });
+ }}
+ onAddKey={() => {
+ if (connections[name]?.supply_mode === 'hub') {
+ navigate(MODEL_HUB_SETTINGS_PATH);
+ return;
+ }
+ setProviderModal({ backend: name, method: 'api_key' });
+ }}
+ connection={connections[name]?.supply_mode === 'hub'
+ ? 'hub'
+ : !connectionErrors[name] && connections[name]?.ready
+ ? (connections[name]?.auth === 'subscription' ? 'subscription' : 'api_key')
+ : undefined}
connectionPending={connectionPending[name]}
connectionError={connectionErrors[name] || connections[name]?.message}
onRefreshConnection={() => void refreshConnection(name)}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index d5d4a37bf..29d4bef28 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -2262,6 +2262,8 @@ export type BackendConnectionState = {
application: 'applied' | 'draining' | 'failed' | 'stopped' | 'unknown';
ready: boolean;
entry_eligible: boolean;
+ /** Which credential owner supplies this backend; omitted responses remain direct-compatible. */
+ supply_mode?: 'direct' | 'hub';
permission_required?: boolean;
message?: string;
};
@@ -2360,6 +2362,8 @@ export type BackendNotice = {
export type CodexAuthSaveResult = CodexAuthState & {
restart?: BackendRestartResult;
notices?: BackendNotice[];
+ error?: string;
+ reauth_channel?: 'hub';
};
export type ClaudeAuthMode = 'oauth' | 'api_key';
@@ -2410,6 +2414,8 @@ export type ClaudeAuthSaveResult = ClaudeAuthState & {
partial?: boolean;
warning?: string;
detail?: string;
+ error?: string;
+ reauth_channel?: 'hub';
};
// One entry in the OpenCode provider grid. The full catalog is built
@@ -2436,6 +2442,7 @@ export type OAuthWebStartResult = {
callback_kind?: 'code' | 'device' | 'redirect' | null;
error?: string;
detail?: string;
+ reauth_channel?: 'hub';
};
export type OAuthWebStatus = {
@@ -2448,12 +2455,14 @@ export type OAuthWebStatus = {
awaiting_code?: boolean;
callback_kind?: 'code' | 'device' | 'redirect' | null;
error?: string | null;
+ reauth_channel?: 'hub';
};
export type OAuthWebMutationResult = {
ok: boolean;
error?: string;
detail?: string;
+ reauth_channel?: 'hub';
notices?: BackendNotice[];
restart?: BackendRestartResult;
// ``partial: true`` rides on ``ok: true`` when the V2Config side of
@@ -2473,6 +2482,7 @@ export type BackendAuthTestResult = {
exit_code?: number;
error?: string;
detail?: string;
+ reauth_channel?: 'hub';
};
export type OpencodeProvider = {
@@ -2546,6 +2556,9 @@ export type OpencodeMutationResult = {
ok: boolean;
restart?: BackendRestartResult;
message?: string;
+ error?: string;
+ detail?: string;
+ reauth_channel?: 'hub';
default_provider?: string;
provider_id?: string;
model_id?: string;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b4cf4c1fb..2f4d20207 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -558,6 +558,8 @@
"oauthRemoved": "Credentials removed.",
"oauthRemoveFailed": "Could not remove credentials: {{detail}}",
"oauthRemovePartial": "Credentials cleared from Avibe, but the backend CLI logout reported a problem: {{detail}}. The CLI's own files may still be present.",
+ "nativeAuthHubOwned": "Authentication is managed by Model Hub.",
+ "openModelHub": "Open Model Hub",
"oauthFlowLockedToast": "OAuth login is in progress — finish or cancel it before switching auth mode.",
"testConnectionTitle": "Test connection",
"testConnectionSubtitle": "Send a one-token \"Hi\" prompt to verify the session, the model, and any custom Base URL.",
@@ -862,66 +864,6 @@
"install": "Install a backend CLI, then reload this page."
}
},
- "adopt": {
- "title": "Switch {{backend}} to the gateway",
- "subtitle": "Affects {{backend}} only; the other backends are unchanged.",
- "vendor": {
- "claude": "Claude",
- "chatgpt": "ChatGPT"
- },
- "section": {
- "effects": "What will happen",
- "undo": "You can undo this"
- },
- "effects": {
- "1": "Your current {{vendor}} login becomes the first source and keeps priority",
- "2": "Once you add other sources, it moves to them when this login is exhausted",
- "1.opencode": "OpenCode's own model configuration is kept as it is; this switch does not change it",
- "2.opencode": "Its models are supplied from the sources on this page; if there are none yet, add one first",
- "3": "The model menu does not change",
- "4": "Conversations in progress are unaffected; the change applies from the next request",
- "install": "The gateway component ({{component}}, about {{duration}}) is installed first, then the switch happens"
- },
- "undo": {
- "1": "You can switch back to direct at any time",
- "2": "Where to undo: the {{backend}} card on this page → Switch to direct",
- "3": "If you switch back, the sources you added stay; they just stop supplying {{backend}}"
- },
- "cancel": "Cancel",
- "confirm": "Switch to gateway",
- "confirm.install": "Install and switch",
- "fail": {
- "title": "The switch to the gateway did not go through",
- "detail": "{{request}} · {{status}} · {{reason}}",
- "reason": {
- "transport": "The gateway could not be reached",
- "refused": "The gateway did not accept the switch",
- "notReady": "The gateway started but did not become ready",
- "unknown": "No reason was given"
- }
- }
- },
- "install": {
- "duration": "1 minute",
- "title": "Install the gateway component",
- "subtitle": "Installs the component only; the backends keep working the way they do now",
- "section": {
- "effects": "What will happen"
- },
- "effects": {
- "1": "{{component}} is downloaded and installed, about {{duration}}",
- "2": "The gateway starts automatically once it is installed",
- "3": "No backend is switched and the model menu does not change"
- },
- "confirm": "Install and start",
- "cancel": "Cancel",
- "progress": "Installing…",
- "fail": {
- "title": "The install did not finish",
- "detail": "The install did not finish, and the component may be left incomplete. Retrying installs it again from scratch."
- },
- "retry": "Try again"
- },
"gateway": {
"heading": "Gateway routes",
"infoLabel": "What gateway routes are",
@@ -1645,34 +1587,42 @@
"title": "Gateway mode",
"recommended": "Recommended · default",
"openModels": "Open Models page",
- "description": "Sign-ins, API keys and per-model Routes are managed in Settings → Models. {{backend}}'s native config is left untouched, and you can switch away anytime."
+ "description": "Sign-ins, API keys and per-model Routes are managed in Settings → Models."
},
"direct": {
"title": "Direct mode",
- "description": "{{backend}} uses its own native config (settings.json / CLI sign-in); Avibe only launches the process and doesn't manage models. Good for troubleshooting or fully self-managed setups.",
+ "description": "{{backend}} uses its own configuration. Avibe does not manage its credentials or model routes.",
"detected": "Existing direct config detected: {{detail}} — import it into the gateway in one click",
"import": "Import to gateway…"
},
"fixHint": "Add or enable a source on the Models page to bring it back."
},
"migration": {
- "title": "Connect to the model gateway",
- "subtitle": "Move your existing sign-ins and API keys into the gateway in one pass — each Agent then keeps its own sources and order.",
- "empty": "No native configuration detected to migrate.",
+ "open": "Migrate configuration",
+ "title": "Migrate to the Model Hub",
+ "subtitle": "After migration, CLI authentication will be fully managed by Model Hub.",
+ "empty": "No configuration found to migrate.",
"scanFailed": "Couldn't scan native configs, please retry",
- "applyFailed": "Import failed, please retry",
- "applied_one": "Imported {{count}} item",
- "applied_other": "Imported {{count}} items",
- "later": "Maybe later",
- "apply_one": "Import {{count}} item and enable the gateway",
- "apply_other": "Import {{count}} items and enable the gateway",
- "nonDestructive": "Non-destructive: native configs are never changed or deleted — importing only copies them; you can switch back to Direct on the Backends page anytime.",
- "action": {
- "import": "Import as source",
- "controlledImport": "Controlled import · reserved",
- "keepNative": "Keep native",
- "reauth": "Re-authorize · one-click in browser"
+ "applyFailed": "Migration failed, please retry",
+ "blocked": {
+ "config": "Adjust this CLI's configuration, then scan again.",
+ "environment": "Remove this CLI’s environment-based credentials, then retry.",
+ "credential": "Allow credential access, then retry.",
+ "fallback": "Use the existing Add flow for this CLI, then scan again."
+ },
+ "applying": "Migrating…",
+ "errors": {
+ "nativeBusy": "Close the CLI or finish its tasks, then retry.",
+ "permissionNeeded": "Allow credential access, then retry.",
+ "recoveryPending": "Migration is unfinished. Retry to continue.",
+ "itemConflict": "The native configuration changed. Scan again.",
+ "configurationBlocked": "Adjust the native configuration, then scan again.",
+ "credentialsInvalid": "Authentication has expired. Sign in again in Model Hub."
},
+ "applied_one": "Migration complete",
+ "applied_other": "Migration complete",
+ "later": "Later",
+ "apply": "Start migration",
"notes": {
"customBaseUrl": "Includes a custom Base URL",
"keepNativeSanctioned": "Stays in the CLI's own store (sanctioned)",
@@ -1915,16 +1865,16 @@
"failed": "Couldn't do that, please retry"
},
"importNotice": {
- "found_one": "Found {{count}} API key to import into Model Gateway",
- "found_other": "Found {{count}} API keys to import into Model Gateway",
- "review": "Review and import",
- "help": "What is Model Gateway?",
- "helpBody": "Model Gateway keeps your API keys and model connections in one place, so every AI assistant has a single way in. Importing only copies the keys you select; your existing configuration is left as it is.",
+ "found_one": "Found {{count}} API key to import into Model Hub",
+ "found_other": "Found {{count}} API keys to import into Model Hub",
+ "review": "Review and migrate",
+ "help": "What is Model Hub?",
+ "helpBody": "Model Hub manages the credentials you select and supplies them to your AI assistants.",
"dismiss": "Dismiss import notice",
- "imported_one": "Imported {{count}} API key into Model Gateway",
- "imported_other": "Imported {{count}} API keys into Model Gateway",
- "importedRemaining_one": "Imported {{imported}} · {{count}} API key still available",
- "importedRemaining_other": "Imported {{imported}} · {{count}} API keys still available"
+ "imported_one": "Migrated {{count}} API key into Model Hub",
+ "imported_other": "Migrated {{count}} API keys into Model Hub",
+ "importedRemaining_one": "Migrated {{imported}} · {{count}} API key still available",
+ "importedRemaining_other": "Migrated {{imported}} · {{count}} API keys still available"
}
}
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index e6c718b44..99eba1de8 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -439,8 +439,8 @@
"detail": "Vault 托管核心 —— 本地 Vault 操作的必需依赖。"
},
"model-hub-engine": {
- "label": "Model Hub 引擎(CPA)",
- "detail": "Model Hub 使用的固定版本 CLIProxyAPI 运行时。"
+ "label": "模型网关引擎(CPA)",
+ "detail": "模型网关使用的固定版本 CLIProxyAPI 运行时。"
},
"show-runtime": {
"label": "Show Page 运行时",
@@ -558,6 +558,8 @@
"oauthRemoved": "已移除凭据。",
"oauthRemoveFailed": "移除凭据失败:{{detail}}",
"oauthRemovePartial": "已清除 Avibe 内的凭据,但 CLI logout 返回错误:{{detail}}。CLI 自己的凭据文件可能仍在磁盘上。",
+ "nativeAuthHubOwned": "认证由模型网关管理。",
+ "openModelHub": "打开模型网关",
"oauthFlowLockedToast": "OAuth 登录进行中——请先完成或取消,再切换验证方式。",
"testConnectionTitle": "测试连通性",
"testConnectionSubtitle": "发送一条 \"Hi\" 测试 prompt,用来验证账号、模型和自定义 Base URL 是否可用。",
@@ -862,66 +864,6 @@
"install": "安装一个后端 CLI,然后重新加载这一页。"
}
},
- "adopt": {
- "title": "把 {{backend}} 切换到模型网关",
- "subtitle": "只影响 {{backend}},其余后端保持原样。",
- "vendor": {
- "claude": "Claude",
- "chatgpt": "ChatGPT"
- },
- "section": {
- "effects": "会发生什么",
- "undo": "可以撤回"
- },
- "effects": {
- "1": "你现在的 {{vendor}} 登录成为第一个供应商,继续优先使用",
- "2": "添加其他供应商后,这个登录用满时会自动切换",
- "1.opencode": "OpenCode 自己的模型配置原样保留,这次切换不改动它",
- "2.opencode": "它的模型从此使用这一页上的供应商;还没有供应商时,先添加一个",
- "3": "模型菜单不变",
- "4": "正在进行的对话不受影响,下一次请求开始生效",
- "install": "先安装网关组件({{component}},约 {{duration}}),再切换"
- },
- "undo": {
- "1": "随时可以切换回直连",
- "2": "回退入口:这一页的 {{backend}} 卡片 → 切到直连",
- "3": "切回后,你添加的供应商会保留,只是不再由 {{backend}} 使用"
- },
- "cancel": "取消",
- "confirm": "切换到模型网关",
- "confirm.install": "安装并切换",
- "fail": {
- "title": "没能切换到模型网关",
- "detail": "{{request}} · {{status}} · {{reason}}",
- "reason": {
- "transport": "没能连接模型网关",
- "refused": "模型网关没有接受这次切换",
- "notReady": "模型网关已经启动,但没有就绪",
- "unknown": "没有给出原因"
- }
- }
- },
- "install": {
- "duration": "1 分钟",
- "title": "安装模型网关组件",
- "subtitle": "只安装组件,后端保持现在的方式",
- "section": {
- "effects": "会发生什么"
- },
- "effects": {
- "1": "下载并安装 {{component}},约 {{duration}}",
- "2": "装好后模型网关自动启动",
- "3": "没有后端会被切换,模型菜单不变"
- },
- "confirm": "安装并启动",
- "cancel": "取消",
- "progress": "正在安装…",
- "fail": {
- "title": "安装没有完成",
- "detail": "这次安装没有完成,组件可能处于未完成状态。重试会重新装一遍。"
- },
- "retry": "重试"
- },
"gateway": {
"heading": "路由",
"infoLabel": "什么是路由",
@@ -1645,34 +1587,42 @@
"title": "模型网关 · Gateway",
"recommended": "推荐 · 默认",
"openModels": "打开模型页",
- "description": "登录、API Key 和模型路由都在「设置 → 模型」中管理。不改动 {{backend}} 自己的配置,随时可切换。"
+ "description": "登录、API Key 和模型路由都在「设置 → 模型」中管理。"
},
"direct": {
"title": "直连模式 · Direct",
- "description": "{{backend}} 使用自己的配置(settings.json / CLI 登录),Avibe 仅负责启动进程、不管理模型。适合排查问题,或想完全自行管理配置的用户。",
+ "description": "{{backend}} 使用自己的配置,Avibe 不接管认证和模型路由。",
"detected": "检测到现有直连配置:{{detail}},可一键导入模型网关",
"import": "导入模型网关…"
},
"fixHint": "去「模型」页添加或启用供应商即可恢复。"
},
"migration": {
- "title": "接入模型网关",
- "subtitle": "把现有登录和 API Key 一次导入模型网关;导入后每个 Agent 各自选择供应商和优先级。",
- "empty": "没有检测到可导入的 Agent 配置。",
+ "open": "迁移配置",
+ "title": "迁移到模型网关",
+ "subtitle": "迁移后,CLI的认证信息将完全交由模型网关管理",
+ "empty": "没有检测到可迁移的配置。",
"scanFailed": "扫描 Agent 配置失败,请重试",
- "applyFailed": "导入失败,请重试",
- "applied_one": "已导入 {{count}} 项",
- "applied_other": "已导入 {{count}} 项",
- "later": "稍后再说",
- "apply_one": "导入 {{count}} 项并启用模型网关",
- "apply_other": "导入 {{count}} 项并启用模型网关",
- "nonDestructive": "导入只会复制配置,不会改动或删除 Agent 自己的配置;随时可在「后端」页切回直连。",
- "action": {
- "import": "导入为模型供应商",
- "controlledImport": "受控导入 · 预留",
- "keepNative": "保留给 Agent 管理",
- "reauth": "需重新授权 · 浏览器一键"
+ "applyFailed": "迁移失败,请重试",
+ "blocked": {
+ "config": "请先调整此 CLI 的配置,再重新扫描。",
+ "environment": "请先清除该 CLI 的环境变量认证配置,再重试。",
+ "credential": "请允许访问凭据,再重试。",
+ "fallback": "请先用现有的添加流程处理此 CLI,再重新扫描。"
+ },
+ "applying": "迁移中…",
+ "errors": {
+ "nativeBusy": "请先关闭 CLI 或完成任务,再重试。",
+ "permissionNeeded": "请允许访问凭据,再重试。",
+ "recoveryPending": "迁移尚未完成,请重试以继续。",
+ "itemConflict": "原生配置已变化,请重新扫描。",
+ "configurationBlocked": "请先调整原生配置,再重新扫描。",
+ "credentialsInvalid": "认证已过期,请在模型网关中重新登录。"
},
+ "applied_one": "迁移完成",
+ "applied_other": "迁移完成",
+ "later": "稍后",
+ "apply": "开始迁移",
"notes": {
"customBaseUrl": "含自定义 Base URL",
"keepNativeSanctioned": "保留在 Agent 自己的凭据库(受官方认可)",
@@ -1917,14 +1867,14 @@
"importNotice": {
"found_one": "发现 {{count}} 个可导入模型网关的 API Key",
"found_other": "发现 {{count}} 个可导入模型网关的 API Key",
- "review": "查看并导入",
+ "review": "查看并迁移",
"help": "什么是模型网关?",
- "helpBody": "模型网关集中管理 API Key 和模型连接,为 AI 助手提供统一的模型入口。导入只会复制你选中的 API Key,原有配置会保留。",
+ "helpBody": "模型网关管理你选择的认证信息,并为 AI 助手提供统一的模型入口。",
"dismiss": "关闭导入提示",
- "imported_one": "已导入 {{count}} 个 API Key 到模型网关",
- "imported_other": "已导入 {{count}} 个 API Key 到模型网关",
- "importedRemaining_one": "已导入 {{imported}} 个 · 还有 {{count}} 个可导入",
- "importedRemaining_other": "已导入 {{imported}} 个 · 还有 {{count}} 个可导入"
+ "imported_one": "已迁移 {{count}} 个 API Key 到模型网关",
+ "imported_other": "已迁移 {{count}} 个 API Key 到模型网关",
+ "importedRemaining_one": "已迁移 {{imported}} 个 · 还有 {{count}} 个可迁移",
+ "importedRemaining_other": "已迁移 {{imported}} 个 · 还有 {{count}} 个可迁移"
}
}
},
diff --git a/ui/src/lib/nativeAuthOwnership.ts b/ui/src/lib/nativeAuthOwnership.ts
new file mode 100644
index 000000000..a76260803
--- /dev/null
+++ b/ui/src/lib/nativeAuthOwnership.ts
@@ -0,0 +1,12 @@
+export const NATIVE_AUTH_HUB_OWNED = 'native_auth_hub_owned';
+
+type NativeAuthOwnershipPayload = {
+ error?: unknown;
+ reauth_channel?: unknown;
+};
+
+export function isNativeAuthHubOwned(value: unknown): boolean {
+ if (!value || typeof value !== 'object') return false;
+ const payload = value as NativeAuthOwnershipPayload;
+ return payload.error === NATIVE_AUTH_HUB_OWNED && payload.reauth_channel === 'hub';
+}
diff --git a/ui/src/lib/settingsOverlay.test.ts b/ui/src/lib/settingsOverlay.test.ts
index 74efe0d79..f62df27ec 100644
--- a/ui/src/lib/settingsOverlay.test.ts
+++ b/ui/src/lib/settingsOverlay.test.ts
@@ -127,6 +127,23 @@ describe('Settings overlay navigation ownership', () => {
expect(navigate).toHaveBeenCalledWith(-2);
});
+ it('retains the setup wizard behind mobile Model Hub and returns to it', () => {
+ const setup = location('/setup');
+ const state = settingsOverlayNavigationState({
+ destinationPathname: '/settings/models',
+ desktop: false,
+ historyState: { idx: 4 },
+ source: setup,
+ targetState: undefined,
+ });
+
+ expect(settingsOverlayOriginFromState(state)).toEqual({ historyIndex: 4, location: setup });
+
+ const navigate = vi.fn();
+ closeSettingsOverlay(navigate, settingsOverlayOriginFromState(state)!, { idx: 5 });
+ expect(navigate).toHaveBeenCalledWith(-1);
+ });
+
it('keeps the origin across a retired-alias redirect', () => {
const opened = settingsOverlayNavigationState({
destinationPathname: '/settings/appearance',
diff --git a/ui/src/lib/settingsOverlay.ts b/ui/src/lib/settingsOverlay.ts
index 04cffa22e..2fa8a5a32 100644
--- a/ui/src/lib/settingsOverlay.ts
+++ b/ui/src/lib/settingsOverlay.ts
@@ -97,7 +97,7 @@ export const settingsOverlayStateForOrigin = (
* route keeps its ordinary unmount-on-navigate lifecycle, and a direct Settings
* link still invents no origin.
*/
-const retainsOriginOnMobile = (pathname: string): boolean => pathname === '/';
+const retainsOriginOnMobile = (pathname: string): boolean => pathname === '/' || pathname === '/setup';
export const settingsOverlayNavigationState = ({
destinationPathname,
diff --git a/vibe/api.py b/vibe/api.py
index b5537bfa8..ff1f0b361 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -54,6 +54,7 @@ from config.v2_settings import (
from config.v2_sessions import SessionsStore
from config.platform_registry import get_platform_descriptor
from core import latest_version_cache
+from core.backend_restart import NativeCredentialLease, NativeMigrationBlockedError, finish_native_operation
from core.memory_loader import probe_memory_runtime_entrypoint
from config.memory_operation_lock import MemoryOperationBusy, MemoryOperationLease
from core.install_integrity import verify_python_environment
@@ -136,6 +137,71 @@ _PLATFORM_SECRET_FIELDS: dict[str, tuple[str, ...]] = {
_GATEWAY_SECRET_FIELDS = ("workspace_token", "client_secret")
+def _native_write_blocked(error: NativeMigrationBlockedError) -> dict:
+ result = {"ok": False, "error": error.reason}
+ if error.backends:
+ result["backends"] = list(error.backends)
+ if error.reason == "native_auth_hub_owned":
+ result["reauth_channel"] = "hub"
+ return result
+
+
+def _native_auth_write(
+ backend: str | None = None, *, pass_lease: bool = False, authentication: bool = True
+):
+ """Own the whole native RMW and its cancellation tail across instances.
+
+ Model/permission-only edits need the same lease: rewriting a stale document
+ can resurrect credentials after takeover. Only auth writers require native
+ custody; non-auth edits remain usable with Hub routing.
+ """
+ from functools import wraps
+
+ def decorate(function):
+ def acquire(args, kwargs):
+ target = str(backend or kwargs.get("backend") or (args[0] if args else "")).strip().lower()
+ if target not in {"claude", "codex", "opencode"}:
+ raise NativeMigrationBlockedError("unsupported_backend", ())
+ lease = NativeCredentialLease((target,)).acquire()
+ try:
+ if authentication:
+ lease.assert_auth_custody(target)
+ return lease
+ except BaseException:
+ lease.release()
+ raise
+
+ if asyncio.iscoroutinefunction(function):
+ @wraps(function)
+ async def asynchronous(*args, **kwargs):
+ try:
+ lease = acquire(args, kwargs)
+ except NativeMigrationBlockedError as error:
+ return _native_write_blocked(error)
+ try:
+ if pass_lease:
+ kwargs["_native_lease"] = lease
+ return await finish_native_operation(function(*args, **kwargs))
+ finally:
+ lease.release()
+ return asynchronous
+
+ @wraps(function)
+ def synchronous(*args, **kwargs):
+ try:
+ lease = acquire(args, kwargs)
+ except NativeMigrationBlockedError as error:
+ return _native_write_blocked(error)
+ try:
+ if pass_lease:
+ kwargs["_native_lease"] = lease
+ return function(*args, **kwargs)
+ finally:
+ lease.release()
+ return synchronous
+ return decorate
+
+
def _parse_agent_import_file(path: Path, *, backend: str):
try:
return parse_agent_file(path, backend=backend)
@@ -6637,6 +6703,7 @@ def opencode_permission_status() -> dict:
}
+@_native_auth_write("opencode", authentication=False)
def setup_opencode_permission() -> dict:
"""Set OpenCode permission to 'allow' in config file.
@@ -10671,8 +10738,65 @@ def _codex_process_status(resolved_binary: str | None) -> str:
return "running" if _codex_processes(resolved_binary) else "stopped"
+def _hub_backend_connection_auth(config: V2Config, backend: str) -> str:
+ """Observe only configured supply owners; never resolve or invoke a model."""
+ from core.handlers.model_hub.resolver import (
+ source_after_cooldown_recovery,
+ source_eligible_for_backend,
+ source_runnable,
+ )
+ from vibe.model_hub_runtime.state import EngineStateStore
+
+ hub = config.model_hub
+ if not hub.enabled:
+ return "none"
+ source_ids = list(dict.fromkeys([
+ *hub.effective_source_order(backend),
+ *(hop.source_id for route in hub.agents[backend].routes.values() for hop in route.hops),
+ ]))
+ by_id = {source.id: source for source in hub.sources}
+ now = datetime.now(timezone.utc)
+ credentials = EngineStateStore(paths.get_runtime_dir() / "model-hub" / "state")
+ for source_id in source_ids:
+ source = by_id.get(source_id)
+ if source is None or not source_eligible_for_backend(source, backend) or not source_runnable(source, now=now):
+ continue
+ if source.supply_channel == "hub":
+ if credentials.has_current_source_credential(
+ source.credential_ref,
+ source_id=source.id,
+ kind=source.kind,
+ vendor=source.vendor,
+ protocol=source.protocol,
+ base_url=source.base_url,
+ ):
+ return "api_key" if source.kind == "api_key" else "subscription"
+ elif source.supply_channel == "native_cli" and source.kind == "subscription":
+ from modules.agents.model_hub import ModelHubRuntimeRouter
+
+ # The retained Source is the explicit subscription owner. Reuse
+ # its launch checks, including native key/endpoint conflicts;
+ # an arbitrary dormant native login cannot supply another Source.
+ recovered = source_after_cooldown_recovery(source, now)
+ if ModelHubRuntimeRouter._default_native_cli_ready(
+ backend, verified_oauth=backend == "codex" and recovered.state.status == "active",
+ ):
+ return "subscription"
+ return "none"
+
+
+def _direct_claude_connection_auth() -> dict:
+ """Keep the bounded native status reader inside the takeover exclusion."""
+ with NativeCredentialLease(("claude",)) as lease:
+ # The caller's config may predate an await or a completed takeover.
+ # acquire() checks pending recovery; custody must be reread under lease.
+ lease.assert_auth_custody("claude")
+ return get_claude_auth(connection_observation=True)
+
+
async def get_backend_connection(name: str) -> dict:
- """Observe native launch auth and controller application, without a model call."""
+ """Observe persisted credential custody and application, without a model call."""
+ from core.backend_restart import pending_native_backends
from vibe import internal_client, runtime
if not is_agent_backend(name):
@@ -10680,9 +10804,11 @@ async def get_backend_connection(name: str) -> dict:
config = await asyncio.to_thread(load_config)
backend_config = getattr(config.agents, name)
enabled = bool(backend_config.enabled)
+ supply_mode = config.model_hub.agents[name].mode
installed = await asyncio.to_thread(resolve_cli_path, backend_config.cli_path or name) is not None
result = {
"ok": True, "backend": name, "installed": installed, "enabled": enabled,
+ "supply_mode": supply_mode,
"auth": "unknown", "application": "unknown", "ready": False,
"entry_eligible": False,
}
@@ -10712,10 +10838,14 @@ async def get_backend_connection(name: str) -> dict:
if receipt and not receipt.get("ok") and result["application"] != "stopped":
result["application"] = "failed"
result["message"] = receipt.get("message") or receipt.get("error")
- if not installed:
+ if not installed or config.load_warnings:
+ return result
+ if name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):
return result
try:
- if name == "opencode":
+ if supply_mode == "hub":
+ result["auth"] = await asyncio.to_thread(_hub_backend_connection_auth, config, name)
+ elif name == "opencode":
if not enabled:
return result
# Read the same persisted launch sources as the provider catalog.
@@ -10728,16 +10858,28 @@ async def get_backend_connection(name: str) -> dict:
modes.update({pid: "api" for pid in key_ids})
effective = next((mode for mode in modes.values() if mode in {"api", "oauth"}), None)
result["auth"] = {"api": "api_key", "oauth": "subscription"}.get(effective, "none")
- permission = await asyncio.to_thread(opencode_permission_status)
- result["permission_required"] = bool(permission.get("ok")) and not permission.get("permission_allowed", False)
else:
- auth = await asyncio.to_thread(get_claude_auth if name == "claude" else get_codex_auth)
+ if name == "claude":
+ # Cancelling to_thread does not stop its native status process.
+ # Join the worker and retain its lease through the entire tail.
+ auth = await finish_native_operation(asyncio.to_thread(_direct_claude_connection_auth))
+ else:
+ auth = await asyncio.to_thread(get_codex_auth)
if not auth.get("ok") or auth.get("auth_mode_uncertain"):
return result
result["auth"] = {"oauth": "subscription", "api_key": "api_key", "none": "none"}.get(auth.get("active_auth_mode"), "unknown")
+ if name == "opencode" and enabled:
+ permission = await asyncio.to_thread(opencode_permission_status)
+ result["permission_required"] = bool(permission.get("ok")) and not permission.get("permission_allowed", False)
+ except NativeMigrationBlockedError:
+ return result
except Exception as exc:
result["message"] = str(exc)
return result
+ # An ownership transition may have started while the observation awaited
+ # IPC or native read-only checks. Do not admit against a pending journal.
+ if name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):
+ return result
credential_ready = enabled and result["auth"] in {"subscription", "api_key"} and not result.get("permission_required")
result["ready"] = credential_ready and result["application"] == "applied"
result["entry_eligible"] = credential_ready and result["application"] in {"applied", "stopped"}
@@ -11237,6 +11379,8 @@ async def start_oauth_web_async(
backend=backend,
),
}
+ except NativeMigrationBlockedError as exc:
+ return _native_write_blocked(exc)
except Exception as exc: # noqa: BLE001
logger.error("Web OAuth start failed for %s: %s", backend, exc, exc_info=True)
return {"ok": False, "error": "start_failed", "detail": str(exc)}
@@ -11302,6 +11446,8 @@ async def remove_backend_auth_async(backend: str) -> dict:
service = _get_oauth_service()
try:
return await service.remove_web_auth(backend)
+ except NativeMigrationBlockedError as exc:
+ return _native_write_blocked(exc)
except Exception as exc: # noqa: BLE001
logger.error("Web auth remove failed for %s: %s", backend, exc, exc_info=True)
return {"ok": False, "error": "remove_failed", "detail": str(exc)}
@@ -11315,6 +11461,8 @@ async def remove_claude_oauth_credentials_async() -> dict:
service = _get_oauth_service()
try:
return await service.clear_claude_oauth_credentials_only()
+ except NativeMigrationBlockedError as exc:
+ return _native_write_blocked(exc)
except Exception as exc: # noqa: BLE001
logger.error("Claude OAuth credentials cleanup failed: %s", exc, exc_info=True)
return {"ok": False, "error": "remove_failed", "detail": str(exc)}
@@ -11324,14 +11472,17 @@ def remove_claude_oauth_credentials() -> dict:
return _submit_oauth_coro(remove_claude_oauth_credentials_async(), timeout=30.0)
-def _clear_claude_oauth_credentials_after_api_key_save(service=None) -> dict:
+def _clear_claude_oauth_credentials_after_api_key_save(service=None, *, lease=None) -> dict:
service = service or _get_oauth_service()
return _submit_oauth_coro(
- service.clear_claude_oauth_credentials_only(),
- timeout=30.0,
+ service.clear_claude_oauth_credentials_only(**({"lease": lease} if lease is not None else {})),
+ # The outer writer owns this explicit lease until cleanup truly exits;
+ # a Future.result timeout would leave that writer running unprotected.
+ timeout=None if lease is not None else 30.0,
)
+@_native_auth_write()
def remove_backend_api_key(backend: str) -> dict:
"""Clear the stored API key for Claude / Codex without touching OAuth.
@@ -11464,6 +11615,8 @@ async def test_backend_auth_async(backend: str, model: Optional[str] = None) ->
service = _get_oauth_service()
try:
return await service.test_web_auth(backend, model=model)
+ except NativeMigrationBlockedError as exc:
+ return _native_write_blocked(exc)
except Exception as exc: # noqa: BLE001
logger.error("Web auth test failed for %s: %s", backend, exc, exc_info=True)
return {"ok": False, "error": "test_failed", "detail": str(exc)}
@@ -11488,6 +11641,8 @@ async def test_opencode_provider_async(provider_id: str, model: Optional[str] =
service = _get_oauth_service()
try:
return await service.test_opencode_provider(provider_id, model=model)
+ except NativeMigrationBlockedError as exc:
+ return _native_write_blocked(exc)
except Exception as exc: # noqa: BLE001
logger.error(
"OpenCode provider test failed for %s: %s",
@@ -11626,6 +11781,7 @@ def get_codex_auth() -> dict:
}
+@_native_auth_write("codex")
def save_codex_auth(payload: dict) -> dict:
"""Persist Codex auth: V2Config + ``~/.codex/{config.toml,auth.json}``.
@@ -11880,7 +12036,7 @@ def save_codex_auth(payload: dict) -> dict:
return state
-def get_claude_auth() -> dict:
+def get_claude_auth(*, connection_observation: bool = False) -> dict:
"""Return the user-facing Claude auth state for the Settings UI.
Claude differs from Codex in two structural ways:
@@ -11895,6 +12051,10 @@ def get_claude_auth() -> dict:
Legacy V2Config keys are read only as a migration fallback so old
installs still render their current state before the next save moves
the key into Claude's own settings file.
+
+ ``connection_observation`` is the leased Direct connection projection:
+ use actual launch-key precedence and explicit uncertainty if neither the
+ bounded status query nor the selected native store proves OAuth.
"""
from vibe.claude_config import (
read_claude_auth_state,
@@ -11904,7 +12064,7 @@ def get_claude_auth() -> dict:
)
disk_state = read_claude_auth_state()
- disk_oauth_signed_in = read_claude_oauth_signed_in()
+ disk_oauth_signed_in = False if connection_observation else read_claude_oauth_signed_in()
settings_env = read_claude_settings_env()
settings_key = settings_env.get("ANTHROPIC_API_KEY") or settings_env.get("ANTHROPIC_AUTH_TOKEN") or ""
settings_base = settings_env.get("ANTHROPIC_BASE_URL") or ""
@@ -11926,6 +12086,14 @@ def get_claude_auth() -> dict:
configured_key = configured_key.strip() if isinstance(configured_key, str) else ""
configured_base = configured_base.strip() if isinstance(configured_base, str) else ""
+ if connection_observation:
+ # Settings are applied by Claude after Avibe's launch environment.
+ # Reuse its composition so explicit OAuth masks inherited keys while
+ # legacy environment keys and persisted settings still take precedence.
+ launch_env = build_claude_subprocess_env(cfg if "cfg" in locals() else None)
+ launch_env.update(settings_env)
+ if launch_env.get("ANTHROPIC_API_KEY") or launch_env.get("ANTHROPIC_AUTH_TOKEN"):
+ return {"ok": True, "active_auth_mode": "api_key"}
try:
claude_status_env = _build_claude_status_probe_env(
build_claude_subprocess_env(
@@ -11935,11 +12103,31 @@ def get_claude_auth() -> dict:
)
except Exception:
claude_status_env = None
+ # Direct connection observation owns the native lease through this bounded
+ # status query. Hub observations never call this native reader.
cli_oauth_signed_in = _read_claude_cli_oauth_signed_in(
configured_cli_path if isinstance(configured_cli_path, str) else None,
env=claude_status_env,
cwd=status_probe_cwd,
)
+ if connection_observation:
+ if cli_oauth_signed_in is not None:
+ return {"ok": True, "active_auth_mode": "oauth" if cli_oauth_signed_in else "none"}
+ from vibe.native_oauth_store import read_native_oauth
+
+ try:
+ snapshot = read_native_oauth("claude", allow_secret=False)
+ except Exception:
+ # An unavailable observer is not proof of logout. Do not expose
+ # native errors or metadata in the public connection response.
+ return {"ok": True, "auth_mode_uncertain": True}
+ if snapshot is None:
+ return {"ok": True, "active_auth_mode": "none"}
+ if snapshot.exportable:
+ return {"ok": True, "active_auth_mode": "oauth"}
+ # Keychain attributes describe a container, which may hold only MCP
+ # credentials. Neither that presence nor denied access proves OAuth.
+ return {"ok": True, "auth_mode_uncertain": True}
oauth_signed_in = (
cli_oauth_signed_in if cli_oauth_signed_in is not None else disk_oauth_signed_in
)
@@ -12007,7 +12195,8 @@ def get_claude_auth() -> dict:
}
-def save_claude_auth(payload: dict) -> dict:
+@_native_auth_write("claude", pass_lease=True)
+def save_claude_auth(payload: dict, *, _native_lease=None) -> dict:
"""Persist Claude auth into Claude Code's own ``settings.json``.
V2Config records only non-secret intent/legacy cleanup state. It must
@@ -12066,6 +12255,12 @@ def save_claude_auth(payload: dict) -> dict:
if recovery_message:
return {"ok": False, "error": "config_recovery", "message": recovery_message}
+ oauth_cleanup_service = _get_oauth_service() if auth_mode == "api_key" else None
+ if oauth_cleanup_service is not None:
+ # Construction may defer recovery because this outer operation already
+ # owns the lease. Adopt it explicitly before reading/writing new settings.
+ oauth_cleanup_service._recover_interrupted_claude_oauth_settings_backup(lease=_native_lease)
+
settings_env: dict[str, str] = {}
existing_credential_type: str | None = None
existing_credential: str | None = None
@@ -12115,8 +12310,6 @@ def save_claude_auth(payload: dict) -> dict:
except Exception:
effective_base_url = None
- oauth_cleanup_service = _get_oauth_service() if auth_mode == "api_key" else None
-
from vibe.claude_config import apply_claude_auth
try:
@@ -12161,7 +12354,7 @@ def save_claude_auth(payload: dict) -> dict:
if auth_mode == "api_key":
try:
oauth_cleanup_result = _clear_claude_oauth_credentials_after_api_key_save(
- oauth_cleanup_service
+ oauth_cleanup_service, lease=_native_lease,
)
except Exception as exc: # noqa: BLE001
logger.warning("Failed to clear Claude OAuth credentials after API-key save: %s", exc)
@@ -12930,6 +13123,7 @@ def _normalize_custom_provider_payload(payload: dict) -> tuple[str, str, str, st
return provider_id.strip(), name.strip(), adapter.strip(), base_url.strip(), api_key_value
+@_native_auth_write("opencode")
async def save_opencode_custom_provider_async(payload: dict) -> dict:
try:
provider_id, name, adapter, base_url, api_key = _normalize_custom_provider_payload(payload)
@@ -13033,6 +13227,7 @@ def save_opencode_custom_provider(payload: dict) -> dict:
return run_coroutine_blocking(save_opencode_custom_provider_async(payload))
+@_native_auth_write("opencode")
async def delete_opencode_custom_provider_async(provider_id: str) -> dict:
if not isinstance(provider_id, str) or not provider_id.strip():
return {"ok": False, "message": "provider_id is required"}
@@ -13104,6 +13299,7 @@ def delete_opencode_custom_provider(provider_id: str) -> dict:
return run_coroutine_blocking(delete_opencode_custom_provider_async(provider_id))
+@_native_auth_write("opencode", authentication=False)
async def save_opencode_provider_model_async(provider_id: str, payload: dict) -> dict:
"""Add or update a user-managed OpenCode model under one provider."""
@@ -13198,6 +13394,7 @@ def delete_opencode_provider_model(provider_id: str, model_id: str) -> dict:
return run_coroutine_blocking(delete_opencode_provider_model_async(provider_id, model_id))
+@_native_auth_write("opencode", authentication=False)
async def delete_opencode_provider_model_async(provider_id: str, model_id: str) -> dict:
if not isinstance(provider_id, str) or not provider_id.strip():
return {"ok": False, "message": "provider_id is required"}
@@ -13357,6 +13554,7 @@ def save_opencode_provider_auth(provider_id: str, payload: dict) -> dict:
return run_coroutine_blocking(save_opencode_provider_auth_async(provider_id, payload))
+@_native_auth_write("opencode")
async def save_opencode_provider_auth_async(provider_id: str, payload: dict) -> dict:
"""Persist a single OpenCode provider's API key (and optional base URL).
@@ -13517,6 +13715,7 @@ def delete_opencode_provider_auth(provider_id: str) -> dict:
return run_coroutine_blocking(delete_opencode_provider_auth_async(provider_id))
+@_native_auth_write("opencode")
async def delete_opencode_provider_auth_async(provider_id: str) -> dict:
"""Drop a single provider's stored credentials.
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 56d700605..229e422cc 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -698,6 +698,7 @@
"timedOut": "{backend} setup timed out. Start setup again to retry.",
"success": "{backend} login is active again.",
"loginInProgress": "A {vendor} login for {backend} is already in progress. Finish or cancel it before starting another.",
+ "hubOwned": "Manage {backend} authentication in Model Hub.",
"failed": "{backend} setup failed: {detail}",
"unknownFailure": "Unknown login failure."
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 49dfacb8d..9c0cd4d8d 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -698,6 +698,7 @@
"timedOut": "{backend} 登录修复已超时,请重新发起 setup 再试一次。",
"success": "{backend} 已重新登录,可继续使用。",
"loginInProgress": "{vendor}({backend})登录正在进行中,请先完成或取消后再重新发起。",
+ "hubOwned": "请在模型网关中管理 {backend} 的认证。",
"failed": "{backend} 登录修复失败:{detail}",
"unknownFailure": "未知登录失败。"
},
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index ca296e30f..06e74c178 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -233,6 +233,16 @@ _REQUEST_ERROR_IDENTIFIERS = frozenset(
)
_MODEL_ERROR_IDENTIFIERS = frozenset({"model_not_found", "not_found_error"})
_AUTHENTICATION_ERROR_IDENTIFIERS = frozenset({"authentication_error", "invalid_api_key", "permission_error"})
+_REFRESH_INVALIDATION_IDENTIFIERS = frozenset(
+ {
+ "invalid_grant",
+ "refresh_token_expired",
+ "refresh_token_invalid",
+ "refresh_token_invalidated",
+ "refresh_token_revoked",
+ "refresh_token_reused",
+ }
+)
_SERVER_ERROR_IDENTIFIERS = frozenset({"api_error", "internal_error", "overloaded", "overloaded_error", "server_error"})
_RATE_LIMIT_ERROR_IDENTIFIERS = frozenset({"rate_limit_error", "rate_limit_exceeded"})
@@ -481,6 +491,30 @@ def _request_error_rejects_credential(
)
+def _oauth_rejection_is_definitive(
+ status: int,
+ payload: Mapping[str, Any],
+) -> bool:
+ """Recognize refresh-invalidating words, but not access-token expiry.
+
+ This helper is intentionally not sufficient on its own for takeover
+ validation: the protocol probe is an upstream request, not a refresh
+ endpoint. The pinned CPA inventory does not expose refresh provenance and
+ cannot turn these words into an authoritative grant-rejection verdict.
+ """
+
+ if status not in {*_REQUEST_ERROR_STATUSES, *_AUTHENTICATION_ERROR_STATUSES}:
+ return False
+ identifiers = set(_payload_identifiers(payload))
+ error = payload.get("error")
+ if isinstance(error, dict):
+ identifiers.update(_error_identifiers(error))
+ message = _normalized_identifier(str(error.get("message") or ""))
+ if any(token in message for token in _REFRESH_INVALIDATION_IDENTIFIERS):
+ return True
+ return not _REFRESH_INVALIDATION_IDENTIFIERS.isdisjoint(identifiers)
+
+
def _payload_is_structured(payload: Mapping[str, Any]) -> bool:
return (
isinstance(payload.get("error"), dict)
@@ -561,6 +595,7 @@ def _parse_protocol_authenticated_evidence(
*,
vendor: str | None = None,
request_root: str | None = None,
+ oauth: bool = False,
) -> _ProtocolEvidence:
"""Classify protocol shape without treating schema validation as login.
@@ -595,8 +630,19 @@ def _parse_protocol_authenticated_evidence(
shape=_default_unproven_shape(status=status),
)
+ if oauth and _oauth_rejection_is_definitive(status, payload):
+ return evidence(
+ protocol=_ProtocolProof.UNPROVEN,
+ # The management probe is not CPA's refresh endpoint. Even an
+ # ``invalid_grant``-shaped upstream response is inconclusive. The
+ # pinned inventory also has no refresh-specific error provenance.
+ authentication=_AuthenticationEvidence.UNKNOWN,
+ )
+
top_level_identifiers = _payload_identifiers(payload)
if (
+ not oauth
+ and
status in _AUTHENTICATION_ERROR_STATUSES
and not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(top_level_identifiers)
):
@@ -605,7 +651,7 @@ def _parse_protocol_authenticated_evidence(
authentication=_AuthenticationEvidence.REJECTED,
)
error = payload.get("error")
- if _request_error_rejects_credential(status, error):
+ if not oauth and _request_error_rejects_credential(status, error):
return evidence(
protocol=_ProtocolProof.UNPROVEN,
authentication=_AuthenticationEvidence.REJECTED,
@@ -619,7 +665,7 @@ def _parse_protocol_authenticated_evidence(
authentication=_AuthenticationEvidence.UNKNOWN,
shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,
)
- if wrapperless == "rejected":
+ if wrapperless == "rejected" and not oauth:
return evidence(
protocol=_ProtocolProof.UNPROVEN,
authentication=_AuthenticationEvidence.REJECTED,
@@ -632,6 +678,8 @@ def _parse_protocol_authenticated_evidence(
taxonomy = _PROTOCOL_OBSERVATION_TAXONOMY.get(protocol)
for rule in taxonomy.evidence_rules if taxonomy is not None else ():
+ if oauth and rule.authentication is _AuthenticationEvidence.REJECTED:
+ continue
if rule.matches(status, payload):
return evidence(
protocol=rule.protocol,
@@ -734,6 +782,9 @@ class _AuthRecord:
provider: str
fingerprint: str
account_id: str | None = None
+ status: str = ""
+ status_message: str = ""
+ unavailable: bool = False
def _response_shape_proves_protocol(
@@ -1038,12 +1089,102 @@ def _probe_oauth_protocol_response(
)
body = payload.get("body")
return _parse_protocol_authenticated_evidence(
- protocol, status, body if isinstance(body, str) else "", vendor=vendor,
+ protocol,
+ status,
+ body if isinstance(body, str) else "",
+ vendor=vendor,
+ oauth=True,
)
return request(headers)
+_OAUTH_CONTROL_PLANE_URLS = {
+ "anthropic": "https://api.anthropic.com/api/oauth/profile",
+ "openai": "https://chatgpt.com/backend-api/wham/usage",
+ "codex": "https://chatgpt.com/backend-api/wham/usage",
+}
+
+
+def _parse_oauth_control_plane_witness(
+ vendor: str,
+ status: object,
+ body: object,
+) -> bool:
+ """Accept only the provider's model-free account/control-plane shape."""
+
+ if not isinstance(status, int) or isinstance(status, bool) or status not in _SUCCESS_STATUSES:
+ return False
+ if not isinstance(body, (str, bytes, bytearray)):
+ return False
+ try:
+ payload = json.loads(body)
+ except (TypeError, UnicodeDecodeError, ValueError):
+ return False
+ if not isinstance(payload, dict) or "error" in payload:
+ return False
+
+ if vendor == "anthropic":
+ account = payload.get("account")
+ uuid_value = account.get("uuid") if isinstance(account, dict) else None
+ return isinstance(uuid_value, str) and bool(uuid_value.strip())
+ if vendor in {"openai", "codex"}:
+ plan_type = payload.get("plan_type")
+ return isinstance(plan_type, str) and bool(plan_type.strip())
+ return False
+
+
+def _probe_oauth_control_plane_witness(
+ *,
+ client: EngineClient,
+ auth: _AuthRecord,
+ vendor: str,
+) -> None:
+ """Use CPA's current auth record for a bodyless control-plane GET."""
+
+ normalized_vendor = vendor.strip().lower()
+ url = _OAUTH_CONTROL_PLANE_URLS.get(normalized_vendor)
+ if url is None:
+ raise EngineClientError("unsupported OAuth control-plane witness")
+
+ headers = {
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ "Authorization": "Bearer $TOKEN$",
+ }
+ if normalized_vendor == "anthropic":
+ headers.update(
+ {
+ "User-Agent": "axios/1.15.2",
+ "Cache-Control": "no-cache",
+ }
+ )
+ else:
+ headers["User-Agent"] = "codex-cli"
+ if auth.account_id:
+ headers["ChatGPT-Account-ID"] = auth.account_id
+
+ payload = client.management_request(
+ "POST",
+ "/api-call",
+ payload={
+ "auth_index": auth.auth_index,
+ "method": "GET",
+ "url": url,
+ "header": headers,
+ },
+ )
+ if not _parse_oauth_control_plane_witness(
+ normalized_vendor,
+ payload.get("status_code"),
+ payload.get("body"),
+ ):
+ raise EngineClientError(
+ "OAuth control-plane witness was inconclusive",
+ error_type="invalid_response",
+ )
+
+
@dataclass
class _OAuthFlow:
flow_id: str
@@ -1582,13 +1723,187 @@ class CLIProxyEngineAdapter:
protocol: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
- return await asyncio.to_thread(
+ return await run_owned_in_thread(
self.state_store.store_api_key,
secret,
vendor=vendor,
protocol=protocol,
base_url=base_url,
+ on_reserved=on_reserved,
+ )
+
+ async def provision_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ material: Mapping[str, object],
+ *,
+ on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
+ normalized_vendor = vendor.strip().lower()
+ auth_type = {"anthropic": "claude", "openai": "codex"}.get(normalized_vendor)
+ if auth_type is None:
+ raise EngineStateError("native OAuth vendor is unsupported")
+ if not isinstance(material, Mapping):
+ raise EngineStateError("native OAuth material is invalid")
+ payload = dict(material)
+ payload["type"] = auth_type
+ auth_name = f"avibe-migration-{uuid.uuid4().hex}.json"
+ return await run_owned_in_thread(
+ self.state_store.stage_oauth_credential,
+ source_id,
+ normalized_vendor,
+ auth_name,
+ payload,
+ on_reserved=on_reserved,
+ )
+
+ async def activate_oauth_credential(self, credential_ref: str) -> None:
+ """Publish a staged grant without replacing a live auth file."""
+
+ async with self._routing_lock:
+ await self._transports_idle.wait()
+ auth_name, payload, _prefix, _already_active = await run_owned_in_thread(
+ self.state_store.activate_oauth_auth_file,
+ credential_ref,
+ )
+ client = await asyncio.to_thread(self.supervisor.client_if_running)
+ if client is None:
+ # The next ordered lifecycle step starts CPA. The atomically
+ # published watched file is the source of truth; no management
+ # upload is needed while the engine is down.
+ return
+
+ expected_provider = str(payload.get("type") or "").strip().lower()
+ try:
+ inventory = await run_owned_in_thread(_auth_inventory, client)
+ except EngineClientError as exc:
+ raise EngineStateError(
+ "OAuth activation could not inspect the engine"
+ ) from exc
+ matching = [
+ auth
+ for auth in inventory.values()
+ if auth.name == auth_name or auth.identity == auth_name
+ ]
+ if len(matching) > 1:
+ raise EngineStateError("OAuth activation auth record is ambiguous")
+ if matching:
+ if matching[0].provider != expected_provider:
+ raise EngineStateError("OAuth activation auth record conflicts")
+ await run_owned_in_thread(
+ self.state_store.mark_oauth_engine_published,
+ credential_ref,
+ )
+ return
+
+ # The local file is already visible. A GET followed by POST is
+ # unsafe: CPA's watcher can register/rotate the file between those
+ # calls, after which POST would re-upload stale R0 bytes. Use the
+ # supervisor's existing watched-file reconcile path instead.
+ restart_if_running = getattr(self.supervisor, "restart_if_running", None)
+ if not callable(restart_if_running):
+ raise EngineStateError("OAuth activation could not reconcile engine")
+ try:
+ await run_owned_in_thread(restart_if_running)
+ except Exception as exc:
+ raise EngineStateError("OAuth activation could not reconcile engine") from exc
+
+ client = await asyncio.to_thread(self.supervisor.client_if_running)
+ if client is None:
+ raise EngineStateError("OAuth activation could not reconcile engine")
+ try:
+ inventory = await run_owned_in_thread(_auth_inventory, client)
+ except EngineClientError as exc:
+ raise EngineStateError(
+ "OAuth activation could not inspect the engine"
+ ) from exc
+ matching = [
+ auth
+ for auth in inventory.values()
+ if auth.name == auth_name or auth.identity == auth_name
+ ]
+ if len(matching) > 1:
+ raise EngineStateError("OAuth activation auth record is ambiguous")
+ if not matching:
+ raise EngineStateError("OAuth activation could not reconcile engine")
+ if matching[0].provider != expected_provider:
+ raise EngineStateError("OAuth activation auth record conflicts")
+ await run_owned_in_thread(
+ self.state_store.mark_oauth_engine_published,
+ credential_ref,
+ )
+
+ return
+
+ async def validate_oauth_credential(self, credential_ref: str) -> None:
+ """Require an upstream authentication witness without inference."""
+
+ async with self._routing_lock:
+ await self._transports_idle.wait()
+ metadata = await asyncio.to_thread(
+ self.state_store.credential_metadata,
+ credential_ref,
+ )
+ if metadata.get("kind") != "oauth":
+ raise EngineStateError("OAuth credential is unavailable")
+ if metadata.get("activation_state") == "staged":
+ raise EngineStateError("OAuth credential is not active")
+ normalized_vendor = str(metadata.get("vendor") or "").strip().lower()
+ expected_provider = {
+ "anthropic": "claude",
+ "openai": "codex",
+ }.get(normalized_vendor)
+ if expected_provider is None:
+ raise EngineStateError("OAuth credential validation is unsupported")
+ client = await run_owned_in_thread(self.supervisor.client)
+ try:
+ inventory = await run_owned_in_thread(_auth_inventory, client)
+ except EngineClientError as exc:
+ raise EngineStateError(
+ "OAuth credential validation could not inspect the engine"
+ ) from exc
+ auth_name = str(metadata.get("auth_name") or "")
+ matches = [
+ auth
+ for auth in inventory.values()
+ if (auth.name == auth_name or auth.identity == auth_name)
+ and auth.provider == expected_provider
+ and auth.auth_index
+ ]
+ if len(matches) != 1:
+ raise EngineStateError("OAuth credential validation is inconclusive")
+ # CPA v7.2.149 loses refresh failure details ("token expired") and
+ # also puts request failures in status_message. None of those
+ # inventory strings proves that a refresh grant was rejected.
+ try:
+ await run_owned_in_thread(
+ _probe_oauth_control_plane_witness,
+ client=client,
+ auth=matches[0],
+ vendor=normalized_vendor,
+ )
+ except (EngineClientError, OSError) as exc:
+ raise EngineStateError("OAuth credential validation failed") from exc
+
+ async def matches_api_key_credential(
+ self,
+ credential_ref: str,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> bool:
+ return await asyncio.to_thread(
+ self.state_store.matches_api_key_credential,
+ credential_ref,
+ vendor,
+ protocol,
+ secret,
+ base_url,
)
async def retarget_api_key_credential(
@@ -1633,6 +1948,8 @@ class CLIProxyEngineAdapter:
vendor: str,
secret: str,
base_url: str | None,
+ *,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
"""Store an unbound observation key until the observation settles.
@@ -1642,12 +1959,13 @@ class CLIProxyEngineAdapter:
marker as a protocol conclusion.
"""
- return await asyncio.to_thread(
+ return await run_owned_in_thread(
self.state_store.store_api_key,
secret,
vendor=vendor,
protocol="openai_chat",
base_url=base_url,
+ on_reserved=on_reserved,
)
async def revoke_credential(self, credential_ref: str) -> None:
@@ -1656,25 +1974,38 @@ class CLIProxyEngineAdapter:
credential_ref,
)
metadata = await asyncio.to_thread(
- self.state_store.credential_metadata,
+ self.state_store.credential_metadata_if_present,
credential_ref,
)
- auth_name = metadata.get("auth_name") if metadata["kind"] == "oauth" else None
+ auth_name = (
+ metadata.get("auth_name")
+ if metadata is not None and metadata.get("kind") == "oauth"
+ else None
+ )
if auth_name:
- client = await asyncio.to_thread(self.supervisor.client_if_running)
- if client is not None:
- try:
- await asyncio.to_thread(
- client.management_request,
- "DELETE",
- "/auth-files",
- query={"name": str(auth_name)},
- timeout=1.0,
- )
- except EngineClientError:
- pass
- await asyncio.to_thread(self.state_store.delete_oauth_auth_file, str(auth_name))
- await asyncio.to_thread(self.state_store.audit_auth_permissions, enforce=True)
+ if metadata.get("activation_state") != "staged":
+ client = await asyncio.to_thread(self.supervisor.client_if_running)
+ if client is not None:
+ try:
+ await asyncio.to_thread(
+ client.management_request,
+ "DELETE",
+ "/auth-files",
+ query={"name": str(auth_name)},
+ timeout=1.0,
+ )
+ except EngineClientError as exc:
+ raise EngineStateError(
+ "unable to remove OAuth auth file"
+ ) from exc
+ await asyncio.to_thread(
+ self.state_store.delete_oauth_auth_file,
+ str(auth_name),
+ )
+ await asyncio.to_thread(
+ self.state_store.audit_auth_permissions,
+ enforce=True,
+ )
await asyncio.to_thread(self.supervisor.invalidate_configs)
await asyncio.to_thread(self.state_store.revoke_credential, credential_ref)
@@ -1694,8 +2025,26 @@ class CLIProxyEngineAdapter:
# absent ref proves cleanup already converged, including never-created
# refs whose postcondition held vacuously.
if metadata is None:
+ try:
+ await asyncio.to_thread(
+ self.state_store.revoke_credential,
+ credential_ref,
+ )
+ except EngineStateError:
+ return False
+ return True
+ if metadata.get("kind") != "oauth":
+ return False
+ if metadata.get("activation_state") == "staged":
+ try:
+ await asyncio.to_thread(
+ self.state_store.revoke_credential,
+ credential_ref,
+ )
+ except EngineStateError:
+ return False
return True
- auth_name = metadata.get("auth_name") if metadata["kind"] == "oauth" else None
+ auth_name = metadata.get("auth_name")
if not isinstance(auth_name, str) or not auth_name:
return False
client = await asyncio.to_thread(self.supervisor.client_if_running)
@@ -2512,6 +2861,9 @@ def _auth_inventory(client: EngineClient) -> dict[str, _AuthRecord]:
provider=provider,
fingerprint=fingerprint,
account_id=account_id,
+ status=str(item.get("status") or "").strip().lower(),
+ status_message=str(item.get("status_message") or "").strip(),
+ unavailable=bool(item.get("unavailable")),
)
return inventory
diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.py
index 5a3a81d77..a5235de34 100644
--- a/vibe/model_hub_runtime/state.py
+++ b/vibe/model_hub_runtime/state.py
@@ -1,7 +1,10 @@
from __future__ import annotations
+import hashlib
+import hmac
import json
import logging
+import os
import re
import secrets
import shutil
@@ -9,7 +12,7 @@ import stat
import threading
from dataclasses import asdict, dataclass
from pathlib import Path
-from typing import Any, Sequence
+from typing import Any, Callable, Sequence
from config.atomic_io import write_atomic
from config.v2_config import normalize_model_hub_base_url
@@ -106,6 +109,10 @@ class EngineStateStore:
def auth_dir(self) -> Path:
return self.root / "auth"
+ @property
+ def oauth_staging_dir(self) -> Path:
+ return self.root / "oauth-staging"
+
def prepare_instance(self, install_id: str, *, rotate: bool = False) -> tuple[Path, RuntimeSecrets]:
with self._lock:
self._ensure_private_dir(self.root)
@@ -157,6 +164,7 @@ class EngineStateStore:
vendor: str = "custom",
protocol: str = "openai_chat",
base_url: str | None = None,
+ on_reserved: Callable[[str], None] | None = None,
) -> str:
if not isinstance(value, str) or not value:
raise EngineStateError("credential is empty")
@@ -168,16 +176,31 @@ class EngineStateStore:
normalized_base_url = _validated_base_url(base_url)
with self._lock:
credential_ref = f"cred_{secrets.token_hex(16)}"
- self._secure_write_json(
- self._credential_path(credential_ref),
- {
- "kind": "api_key",
- "vendor": normalized_vendor,
- "protocol": protocol,
- "base_url": normalized_base_url,
- "value": value,
- },
+ credential_path, credential_tmp, stage_path, stage_tmp = (
+ self._reserve_credential_namespace(credential_ref)
)
+ try:
+ if on_reserved is not None:
+ on_reserved(credential_ref)
+ self._write_reserved_json(
+ credential_path,
+ {
+ "kind": "api_key",
+ "vendor": normalized_vendor,
+ "protocol": protocol,
+ "base_url": normalized_base_url,
+ "value": value,
+ },
+ temporary_path=credential_tmp,
+ credential_ref=credential_ref,
+ )
+ self._remove_private_file_if_present(stage_path)
+ self._remove_private_file_if_present(stage_tmp)
+ except BaseException:
+ self._cleanup_private_paths(
+ (credential_path, credential_tmp, stage_path, stage_tmp)
+ )
+ raise
return credential_ref
def bind_oauth_credential(self, source_id: str, vendor: str, auth_name: str) -> str:
@@ -213,6 +236,234 @@ class EngineStateStore:
)
return credential_ref
+ def stage_oauth_credential(
+ self,
+ source_id: str,
+ vendor: str,
+ auth_name: str,
+ payload: dict[str, Any],
+ on_reserved: Callable[[str], None] | None = None,
+ ) -> str:
+ """Persist an OAuth grant outside the engine's watched auth directory."""
+
+ _validated_source_id(source_id)
+ normalized_vendor = vendor.strip().lower()
+ normalized_auth_name = _validated_oauth_auth_name(auth_name)
+ if not normalized_vendor:
+ raise EngineStateError("OAuth credential binding is incomplete")
+ if not isinstance(payload, dict) or not isinstance(payload.get("type"), str):
+ raise EngineStateError("invalid OAuth auth payload")
+ with self._lock:
+ self._ensure_private_dir(self.root)
+ self._ensure_private_dir(self.oauth_staging_dir)
+ credential_ref = f"cred_{secrets.token_hex(16)}"
+ prefix = f"avibe-{secrets.token_hex(12)}"
+ staged_payload = {
+ **payload,
+ # CPA's file synthesizer reads the prefix from the auth JSON.
+ # It must be part of the fully-written staged bytes before the
+ # file can become visible in the watched auth directory.
+ "prefix": prefix,
+ }
+ expected_provider = _oauth_provider_for_vendor(normalized_vendor)
+ if str(staged_payload.get("type") or "").strip().lower() != expected_provider:
+ raise EngineStateError("OAuth auth payload provider does not match vendor")
+ credential_path, credential_tmp, stage_path, stage_tmp = (
+ self._reserve_credential_namespace(credential_ref)
+ )
+ try:
+ if on_reserved is not None:
+ on_reserved(credential_ref)
+ self._write_reserved_json(
+ stage_path,
+ staged_payload,
+ temporary_path=stage_tmp,
+ credential_ref=credential_ref,
+ )
+ stage_revision = self._file_revision(stage_path)
+ self._write_reserved_json(
+ credential_path,
+ {
+ "kind": "oauth",
+ "source_id": source_id,
+ "vendor": normalized_vendor,
+ "auth_name": normalized_auth_name,
+ "prefix": prefix,
+ "activation_state": "staged",
+ "engine_published": False,
+ "prefix_published": False,
+ "stage_revision": stage_revision,
+ "published_revision": None,
+ "published_identity": None,
+ },
+ temporary_path=credential_tmp,
+ credential_ref=credential_ref,
+ )
+ except BaseException as exc:
+ self._cleanup_private_paths(
+ (credential_path, credential_tmp, stage_path, stage_tmp)
+ )
+ raise EngineStateError("unable to stage OAuth credential") from exc
+ return credential_ref
+
+ def write_oauth_auth_file(self, auth_name: str, payload: dict[str, Any]) -> None:
+ """Write an imported OAuth grant into the engine auth directory."""
+ normalized = _validated_oauth_auth_name(auth_name)
+ if not isinstance(payload, dict) or not isinstance(payload.get("type"), str):
+ raise EngineStateError("invalid OAuth auth payload")
+ with self._lock:
+ self.audit_auth_permissions(enforce=True)
+ self._secure_write_json(self.auth_dir / normalized, payload)
+
+ def activate_oauth_auth_file(
+ self,
+ credential_ref: str,
+ ) -> tuple[str, dict[str, Any], str, bool]:
+ """Publish one staged grant without replacing an existing live file.
+
+ The watched path is the durable owner after publication. CPA may rotate
+ the access and refresh tokens in that same file at any time, so retries
+ validate only the opaque file identity (name, provider, prefix), never
+ the bytes or a token hash captured before publication.
+ """
+
+ with self._lock:
+ metadata = self.credential_metadata(credential_ref)
+ if metadata.get("kind") != "oauth":
+ raise EngineStateError("OAuth credential is unavailable")
+ auth_name = _validated_oauth_auth_name(str(metadata.get("auth_name") or ""))
+ target = self.auth_dir / auth_name
+ self.audit_auth_permissions(enforce=True)
+
+ # A live watched file always wins over private staging. This is the
+ # crash/refresh recovery rule: never re-publish stale R0 bytes after
+ # CPA has already observed or rotated the file.
+ if target.exists():
+ payload = self._decode_oauth_payload(target)
+ identity = self._assert_oauth_auth_file_owned_locked(metadata, target, payload)
+ updated = {
+ **metadata,
+ "activation_state": "active",
+ "prefix_published": True,
+ "published_identity": identity,
+ }
+ self._secure_write_json(self._credential_path(credential_ref), updated)
+ self._remove_oauth_stage_if_present(credential_ref)
+ return auth_name, payload, identity["prefix"], metadata.get("activation_state") == "active"
+
+ stage_path = self._oauth_stage_path(credential_ref)
+ staged_bytes = self._read_private_bytes(
+ stage_path,
+ "OAuth staging file is unsafe",
+ )
+ stage_revision = metadata.get("stage_revision")
+ actual_stage_revision = hashlib.sha256(staged_bytes).hexdigest()
+ if isinstance(stage_revision, str) and actual_stage_revision != stage_revision:
+ raise EngineStateError("OAuth staging record is inconsistent")
+ staged_payload = self._decode_oauth_payload(stage_path)
+ self._assert_oauth_payload_identity(metadata, auth_name, staged_payload)
+ try:
+ self._publish_staged_no_replace(stage_path, target)
+ except FileExistsError:
+ # The watcher or another retry won the publication race. Read
+ # that winner and bind to it; do not upload stale staged bytes.
+ if not target.exists():
+ raise EngineStateError("OAuth auth file publication is inconclusive") from None
+ payload = self._decode_oauth_payload(target)
+ identity = self._assert_oauth_auth_file_owned_locked(metadata, target, payload)
+ else:
+ payload = self._decode_oauth_payload(target)
+ identity = self._assert_oauth_auth_file_owned_locked(metadata, target, payload)
+
+ updated = {
+ **metadata,
+ "activation_state": "active",
+ "prefix_published": True,
+ "published_identity": identity,
+ }
+ self._secure_write_json(self._credential_path(credential_ref), updated)
+ self._remove_oauth_stage_if_present(credential_ref)
+ return auth_name, payload, identity["prefix"], False
+
+ def mark_oauth_engine_published(self, credential_ref: str) -> None:
+ with self._lock:
+ metadata = self.credential_metadata(credential_ref)
+ if metadata.get("kind") != "oauth":
+ raise EngineStateError("OAuth credential is unavailable")
+ auth_name = _validated_oauth_auth_name(str(metadata.get("auth_name") or ""))
+ identity = self._assert_oauth_auth_file_owned_locked(
+ metadata,
+ self.auth_dir / auth_name,
+ )
+ self._secure_write_json(
+ self._credential_path(credential_ref),
+ {
+ **metadata,
+ "activation_state": "active",
+ "engine_published": True,
+ "prefix_published": True,
+ "published_identity": identity,
+ },
+ )
+
+ def assert_oauth_auth_file_unchanged(self, credential_ref: str) -> None:
+ """Backward-compatible name for the post-publication ownership check."""
+
+ with self._lock:
+ metadata = self.credential_metadata(credential_ref)
+ if metadata.get("kind") != "oauth":
+ raise EngineStateError("OAuth credential is unavailable")
+ auth_name = _validated_oauth_auth_name(str(metadata.get("auth_name") or ""))
+ self._assert_oauth_auth_file_owned_locked(metadata, self.auth_dir / auth_name)
+
+ def mark_oauth_prefix_published(self, credential_ref: str) -> None:
+ with self._lock:
+ metadata = self.credential_metadata(credential_ref)
+ if metadata.get("kind") != "oauth":
+ raise EngineStateError("OAuth credential is unavailable")
+ auth_name = _validated_oauth_auth_name(str(metadata.get("auth_name") or ""))
+ identity = self._assert_oauth_auth_file_owned_locked(
+ metadata,
+ self.auth_dir / auth_name,
+ )
+ self._secure_write_json(
+ self._credential_path(credential_ref),
+ {
+ **metadata,
+ "activation_state": "active",
+ "prefix_published": True,
+ "published_identity": identity,
+ },
+ )
+
+ def matches_api_key_credential(
+ self,
+ credential_ref: str,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> bool:
+ """Compare transient native material with an engine-owned API key."""
+
+ metadata = self.credential_metadata(credential_ref)
+ if metadata.get("kind") != "api_key":
+ return False
+ normalized_base_url = _validated_base_url(base_url)
+ if (
+ metadata.get("vendor") != vendor.strip().lower()
+ or metadata.get("protocol") != protocol
+ or metadata.get("base_url") != normalized_base_url
+ ):
+ return False
+ if not isinstance(secret, str):
+ return False
+ stored = self.read_api_key(credential_ref)
+ return hmac.compare_digest(
+ stored.encode("utf-8"),
+ secret.encode("utf-8"),
+ )
+
def sync_sources(self, bindings: Sequence[Any]) -> list[SourceRecord]:
"""Atomically replace the engine projection using opaque credential refs."""
with self._lock:
@@ -354,10 +605,72 @@ class EngineStateStore:
raise EngineStateError("credential permissions are unsafe")
payload = self._read_json(path)
kind = payload.get("kind") if payload else None
+ if kind == "reservation" and payload.get("credential_ref") == credential_ref:
+ return None
if kind not in {"api_key", "oauth"}:
raise EngineStateError("credential is unavailable")
return payload
+ def has_current_source_credential(
+ self,
+ credential_ref: str,
+ *,
+ source_id: str,
+ kind: str,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ ) -> bool:
+ """Observe a Source's current credential binding without repair or secrets.
+
+ Unlike credential_metadata(), this read never creates directories or
+ fixes permissions. It proves local ownership/existence, not upstream
+ authentication, refreshability, or model entitlement. OAuth auth files
+ remain entirely engine-owned and are not opened by this observation.
+ """
+ try:
+ if not isinstance(credential_ref, str) or _CREDENTIAL_REF_RE.fullmatch(credential_ref) is None:
+ return False
+ _validated_source_id(source_id)
+ credential_kind = {"api_key": "api_key", "subscription": "oauth"}.get(kind)
+ if credential_kind is None or not isinstance(vendor, str) or protocol not in _PROTOCOLS:
+ return False
+ normalized_vendor = vendor.strip().lower()
+ normalized_base_url = _validated_base_url(base_url)
+ _validate_source_target(
+ normalized_vendor, protocol, normalized_base_url, credential_kind=credential_kind,
+ )
+ credentials_dir = self.root / "credentials"
+ for directory in (self.root, credentials_dir):
+ mode = directory.lstat().st_mode
+ if not stat.S_ISDIR(mode) or stat.S_IMODE(mode) != 0o700:
+ return False
+ payload = json.loads(self._read_private_bytes(
+ credentials_dir / f"{credential_ref}.json",
+ "credential path is unsafe",
+ ))
+ if not isinstance(payload, dict) or (
+ payload.get("kind") != credential_kind or payload.get("vendor") != normalized_vendor
+ ):
+ return False
+ if credential_kind == "api_key":
+ return (
+ payload.get("protocol") == protocol
+ and payload.get("base_url") == normalized_base_url
+ and isinstance(payload.get("value"), str)
+ and bool(payload["value"].strip())
+ )
+ auth_name = payload.get("auth_name")
+ return (
+ normalized_base_url is None
+ and payload.get("source_id") == source_id
+ and payload.get("activation_state") in {None, "active"}
+ and isinstance(auth_name, str)
+ and bool(_validated_oauth_auth_name(auth_name))
+ )
+ except (OSError, ValueError, TypeError, EngineStateError):
+ return False
+
def validate_api_key_target(
self,
credential_ref: str,
@@ -384,11 +697,14 @@ class EngineStateStore:
def revoke_credential(self, credential_ref: str) -> None:
with self._lock:
self.assert_credential_unbound(credential_ref)
- path = self._credential_path(credential_ref)
- if not path.exists():
- return
- self.credential_metadata(credential_ref)
- path.unlink()
+ path, temporary_path, stage_path, stage_temporary_path = (
+ self._credential_namespace_paths(credential_ref)
+ )
+ self.credential_metadata_if_present(credential_ref)
+ self._remove_private_file_if_present(stage_path)
+ self._remove_private_file_if_present(stage_temporary_path)
+ self._remove_private_file_if_present(temporary_path)
+ self._remove_private_file_if_present(path)
def clear_runtime_configs(self) -> None:
"""Remove persisted engine configs after any credential is revoked."""
@@ -437,25 +753,10 @@ class EngineStateStore:
def delete_oauth_auth_file(self, auth_name: str) -> None:
"""Delete one managed OAuth file without requiring a running engine."""
- normalized = auth_name.strip()
- if (
- not normalized
- or "\x00" in normalized
- or "\\" in normalized
- or Path(normalized).name != normalized
- or not normalized.lower().endswith(".json")
- ):
- raise EngineStateError("invalid OAuth auth file name")
+ normalized = _validated_oauth_auth_name(auth_name)
with self._lock:
self.audit_auth_permissions(enforce=True)
- path = self.auth_dir / normalized
- try:
- mode = path.lstat().st_mode
- except FileNotFoundError:
- return
- if not stat.S_ISREG(mode):
- raise EngineStateError("engine auth credential path is unsafe")
- path.unlink()
+ self._remove_private_file_if_present(self.auth_dir / normalized)
def audit_auth_permissions(self, *, enforce: bool = False) -> None:
self._ensure_private_dir(self.root)
@@ -484,6 +785,47 @@ class EngineStateStore:
self._ensure_private_dir(credentials_dir)
return credentials_dir / f"{credential_ref}.json"
+ def _credential_namespace_paths(
+ self,
+ credential_ref: str,
+ ) -> tuple[Path, Path, Path, Path]:
+ credential_path = self._credential_path(credential_ref)
+ stage_path = self._oauth_stage_path(credential_ref)
+ return (
+ credential_path,
+ credential_path.with_name(f".{credential_path.name}.tmp"),
+ stage_path,
+ stage_path.with_name(f".{stage_path.name}.tmp"),
+ )
+
+ def _reserve_credential_namespace(
+ self,
+ credential_ref: str,
+ ) -> tuple[Path, Path, Path, Path]:
+ paths = self._credential_namespace_paths(credential_ref)
+ reserved: list[Path] = []
+ try:
+ for path in paths:
+ self._reserve_path(path, credential_ref)
+ reserved.append(path)
+ except BaseException:
+ try:
+ self._cleanup_private_paths(tuple(reserved))
+ except BaseException:
+ logger.warning(
+ "Unable to discard provisional credential reservations for %s",
+ credential_ref,
+ exc_info=True,
+ )
+ raise
+ return paths
+
+ def _oauth_stage_path(self, credential_ref: str) -> Path:
+ if _CREDENTIAL_REF_RE.fullmatch(credential_ref) is None:
+ raise EngineStateError("invalid credential reference")
+ self._ensure_private_dir(self.oauth_staging_dir)
+ return self.oauth_staging_dir / f"{credential_ref}.json"
+
def _oauth_credentials(self) -> list[tuple[str, dict[str, Any]]]:
self._ensure_private_dir(self.root)
credentials_dir = self.root / "credentials"
@@ -564,6 +906,194 @@ class EngineStateStore:
cls._ensure_private_dir(path.parent)
write_atomic(path, json.dumps(payload, sort_keys=True) + "\n")
+ @classmethod
+ def _reserve_path(cls, path: Path, credential_ref: str) -> None:
+ """Create a no-secret, no-replace reservation for one exact path."""
+
+ cls._ensure_private_dir(path.parent)
+ payload = json.dumps(
+ {"kind": "reservation", "credential_ref": credential_ref},
+ sort_keys=True,
+ ).encode("utf-8") + b"\n"
+ try:
+ descriptor = os.open(
+ path,
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,
+ 0o600,
+ )
+ except FileExistsError as exc:
+ raise EngineStateError("credential reference collision") from exc
+ try:
+ with os.fdopen(descriptor, "wb") as handle:
+ descriptor = -1
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ cls._fsync_directory(path.parent)
+ finally:
+ if descriptor >= 0:
+ os.close(descriptor)
+
+ @classmethod
+ def _write_reserved_json(
+ cls,
+ path: Path,
+ payload: dict[str, Any],
+ *,
+ temporary_path: Path,
+ credential_ref: str,
+ ) -> None:
+ """Write complete bytes to a deterministic per-ref temp before rename."""
+
+ cls._ensure_private_dir(path.parent)
+ serialized = json.dumps(payload, sort_keys=True).encode("utf-8") + b"\n"
+ reservation = {"credential_ref": credential_ref, "kind": "reservation"}
+ if cls._read_json(path) != reservation or cls._read_json(temporary_path) != reservation:
+ raise EngineStateError("credential reference collision")
+ descriptor = -1
+ try:
+ descriptor = os.open(temporary_path, os.O_WRONLY | os.O_TRUNC)
+ with os.fdopen(descriptor, "wb") as handle:
+ descriptor = -1
+ handle.write(serialized)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temporary_path, path)
+ cls._fsync_directory(path.parent)
+ finally:
+ if descriptor >= 0:
+ os.close(descriptor)
+
+ @classmethod
+ def _remove_private_file_if_present(cls, path: Path) -> bool:
+ try:
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError:
+ # A prior unlink may have succeeded before its directory fsync
+ # failed. Retrying an absent path must still establish the
+ # directory durability boundary before cleanup can converge.
+ cls._fsync_directory(path.parent)
+ return False
+ if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600:
+ raise EngineStateError("engine state path is unsafe")
+ path.unlink()
+ cls._fsync_directory(path.parent)
+ return True
+ except EngineStateError:
+ raise
+ except OSError as exc:
+ raise EngineStateError("unable to remove engine state file") from exc
+
+ @classmethod
+ def _cleanup_private_paths(cls, paths: Sequence[Path]) -> None:
+ first_error: BaseException | None = None
+ for path in paths:
+ try:
+ cls._remove_private_file_if_present(path)
+ except BaseException as exc:
+ if first_error is None:
+ first_error = exc
+ if first_error is not None:
+ raise first_error
+
+ @staticmethod
+ def _file_revision(path: Path) -> str:
+ return hashlib.sha256(
+ EngineStateStore._read_private_bytes(
+ path,
+ "engine auth credential path is unsafe",
+ )
+ ).hexdigest()
+
+ @staticmethod
+ def _read_private_bytes(path: Path, message: str) -> bytes:
+ try:
+ mode = path.lstat().st_mode
+ except FileNotFoundError as exc:
+ raise EngineStateError("OAuth credential is unavailable") from exc
+ if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o600:
+ raise EngineStateError(message)
+ try:
+ return path.read_bytes()
+ except OSError as exc:
+ raise EngineStateError("OAuth credential is unavailable") from exc
+
+ @staticmethod
+ def _decode_oauth_payload(path: Path) -> dict[str, Any]:
+ payload = EngineStateStore._read_json(path)
+ if not isinstance(payload, dict) or not isinstance(payload.get("type"), str):
+ raise EngineStateError("OAuth credential is unavailable")
+ return payload
+
+ @staticmethod
+ def _publish_staged_no_replace(stage_path: Path, target: Path) -> None:
+ """Atomically expose a complete staged file without replacing a target.
+
+ ``link`` adds the fully-written staging inode to the watched directory
+ as one directory-entry operation. It is intentionally followed by
+ directory fsyncs and only then removes the private staging name.
+ """
+
+ try:
+ os.link(stage_path, target, follow_symlinks=False)
+ except FileExistsError:
+ raise
+ except OSError as exc:
+ raise EngineStateError("unable to publish OAuth auth file") from exc
+ try:
+ EngineStateStore._fsync_directory(target.parent)
+ stage_path.unlink()
+ EngineStateStore._fsync_directory(stage_path.parent)
+ except OSError as exc:
+ raise EngineStateError("unable to finalize OAuth staging") from exc
+
+ @staticmethod
+ def _fsync_directory(path: Path) -> None:
+ flags = getattr(os, "O_DIRECTORY", 0)
+ if not flags:
+ return
+ descriptor = os.open(path, flags | os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
+ def _assert_oauth_auth_file_owned_locked(
+ self,
+ metadata: dict[str, Any],
+ path: Path,
+ payload: dict[str, Any] | None = None,
+ ) -> dict[str, str]:
+ auth_name = _validated_oauth_auth_name(str(metadata.get("auth_name") or ""))
+ current = payload if payload is not None else self._decode_oauth_payload(path)
+ return self._assert_oauth_payload_identity(metadata, auth_name, current)
+
+ @staticmethod
+ def _assert_oauth_payload_identity(
+ metadata: dict[str, Any],
+ auth_name: str,
+ payload: dict[str, Any],
+ ) -> dict[str, str]:
+ expected_provider = _oauth_provider_for_vendor(str(metadata.get("vendor") or ""))
+ actual_provider = str(payload.get("type") or "").strip().lower()
+ expected_prefix = str(metadata.get("prefix") or "").strip()
+ actual_prefix = str(payload.get("prefix") or "").strip().strip("/")
+ if (
+ actual_provider != expected_provider
+ or not expected_prefix
+ or actual_prefix != expected_prefix
+ ):
+ raise EngineStateError("OAuth auth file ownership is unavailable")
+ return {
+ "auth_name": auth_name,
+ "provider": expected_provider,
+ "prefix": expected_prefix,
+ }
+
+ def _remove_oauth_stage_if_present(self, credential_ref: str) -> None:
+ self._remove_private_file_if_present(self._oauth_stage_path(credential_ref))
+
@staticmethod
def _ensure_private_dir(path: Path) -> None:
if path.exists():
@@ -583,6 +1113,32 @@ class EngineStateStore:
raise EngineStateError(message)
+def _validated_oauth_auth_name(value: str) -> str:
+ normalized = value.strip()
+ if (
+ not normalized
+ or "\x00" in normalized
+ or "\\" in normalized
+ or Path(normalized).name != normalized
+ or not normalized.lower().endswith(".json")
+ ):
+ raise EngineStateError("invalid OAuth auth file name")
+ return normalized
+
+
+def _oauth_provider_for_vendor(vendor: str) -> str:
+ normalized = vendor.strip().lower()
+ provider = {
+ "anthropic": "claude",
+ "claude": "claude",
+ "openai": "codex",
+ "codex": "codex",
+ }.get(normalized)
+ if provider is None:
+ raise EngineStateError("native OAuth vendor is unsupported")
+ return provider
+
+
def _safe_identifier(value: str) -> str:
cleaned = "".join(character if character.isalnum() or character in "._-" else "_" for character in value)
return cleaned or "unknown"
diff --git a/vibe/native_oauth_store.py b/vibe/native_oauth_store.py
new file mode 100644
index 000000000..f06a7de8c
--- /dev/null
+++ b/vibe/native_oauth_store.py
@@ -0,0 +1,2047 @@
+"""Read and mutate Codex and Claude Code native OAuth stores.
+
+The migration scanner calls :func:`read_native_oauth` without
+``allow_secret``. That path may read fixture files, or safe Keychain
+attributes, but it never reads a Keychain value. The caller must perform the
+user confirmation and native admission drain before calling the secret-bearing
+path.
+
+``keychain_edit`` is deliberately private data. It contains the exact
+before/after credential states needed for a compare-and-swap cleanup or
+reverse, so callers must keep it in the migration journal and never put it on
+the scan response.
+
+Claude selection covers its Keychain and both supported credential filenames
+under the same secure root. Newest-layout files take precedence over legacy
+files, but every credential-bearing copy must have same-account evidence.
+The selection revision binds all file states, including absence. Journal file
+operations include unchanged states as guards; callers must retain them when
+coalescing edits so a newly appeared fallback login cannot escape cleanup.
+A Claude Keychain containing only unrelated data also remains a no-op guard
+when OAuth is imported from a file. Its observed metadata revision remains in
+the selection and its exact value is retained for the journal's clean-store
+check; it is never exported as the credential payload.
+
+Metadata scans use ``kSecUseAuthenticationUIFail`` and temporarily disable the
+legacy process-wide Keychain interaction switch. The explicit-consent
+``allow_secret`` read and subsequent mutations use
+``kSecUseAuthenticationUIAllow`` so the OS can complete its normal approval
+flow. Fixture homes never select the real OS Keychain.
+
+Mutations require the caller's cooperative credential lease and external CLI
+drain. They recheck immediately, bind the observed item and modification date,
+and read back. Apple's SecItem API is not an atomic value-CAS against an
+uncooperative writer updating the same item inside its query/update window.
+Recovery belongs to the durable controller journal, not this module.
+"""
+
+from __future__ import annotations
+
+import base64
+import ctypes
+import ctypes.util
+import getpass
+import hmac
+import hashlib
+import json
+import math
+import os
+import re
+import sys
+import threading
+from contextlib import contextmanager
+from dataclasses import dataclass, field, replace
+from pathlib import Path
+from typing import Any, Mapping, Protocol
+
+from config.atomic_io import write_atomic
+from vibe.codex_config import get_codex_home
+
+__all__ = [
+ "NativeOAuthError",
+ "NativeOAuthPermissionError",
+ "NativeOAuthRevisionError",
+ "NativeOAuthSnapshot",
+ "apply_keychain_edit",
+ "check_keychain_edit",
+ "native_credentials_paths",
+ "read_native_oauth",
+]
+
+_CODEX_STORES = frozenset({"file", "keyring", "auto", "ephemeral"})
+_CLAUDE_OAUTH_KEYS = frozenset(
+ {
+ "access_token",
+ "accessToken",
+ "refresh_token",
+ "refreshToken",
+ }
+)
+_CLAUDE_OAUTH_METADATA_KEYS = frozenset(
+ {
+ "expiresAt",
+ "expires_at",
+ "scopes",
+ "subscriptionType",
+ "rateLimitTier",
+ "tokenType",
+ "accountUuid",
+ "account_uuid",
+ "organizationUuid",
+ "organization_uuid",
+ }
+)
+_CLAUDE_IDENTITY_KEYS = {
+ "accountUuid": "account_uuid",
+ "account_uuid": "account_uuid",
+ "accountId": "account_id",
+ "account_id": "account_id",
+ "email": "email",
+ "emailAddress": "email",
+ "accountEmail": "email",
+ "organizationUuid": "organization_uuid",
+ "organization_uuid": "organization_uuid",
+ "organizationId": "organization_id",
+ "organization_id": "organization_id",
+}
+_SAFE_CLAUDE_ACCOUNT = re.compile(r"^[A-Za-z0-9._-]+$")
+
+
+class NativeOAuthError(RuntimeError):
+ """Base class for native OAuth store failures."""
+
+
+class NativeOAuthPermissionError(NativeOAuthError):
+ """The native store denied a read or mutation."""
+
+
+class NativeOAuthRevisionError(NativeOAuthError):
+ """The live native store no longer matches the migration journal."""
+
+
+@dataclass(frozen=True)
+class NativeOAuthSnapshot:
+ """A native OAuth candidate and its stable selection revision."""
+
+ backend: str
+ revision: str
+ payload: dict[str, Any] | None = field(default=None, repr=False)
+ exportable: bool = False
+ keychain_edit: dict[str, Any] | None = field(default=None, repr=False)
+
+
+@dataclass(frozen=True)
+class _KeychainMetadata:
+ state: str
+ revision: str
+ attributes: dict[str, Any] = field(default_factory=dict)
+ persistent_reference: str | None = None
+ modification_date: float | None = None
+
+
+@dataclass(frozen=True)
+class _KeychainRead:
+ value: str = field(repr=False)
+ revision: str
+ persistent_reference: str | None = None
+ modification_date: float | None = None
+
+
+class _KeychainStore(Protocol):
+ def metadata(self, service: str, account: str) -> _KeychainMetadata:
+ ...
+
+ def read(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: _KeychainRead | None = None,
+ ) -> _KeychainRead:
+ ...
+
+ def write(
+ self,
+ service: str,
+ account: str,
+ value: str,
+ *,
+ expected: _KeychainRead | None,
+ ) -> None:
+ ...
+
+ def delete(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: _KeychainRead,
+ ) -> None:
+ ...
+
+
+class _KeychainNotFound(NativeOAuthError):
+ pass
+
+
+class _KeychainUnavailable(NativeOAuthError):
+ pass
+
+
+class _KeychainDenied(NativeOAuthPermissionError):
+ pass
+
+
+def _sha256(value: bytes) -> str:
+ return hashlib.sha256(value).hexdigest()
+
+
+def _locator_revision(backend: str, kind: str, locator: str, detail: str = "") -> str:
+ material = "\x00".join((backend, kind, locator, detail))
+ return f"{backend}:{kind}:{_sha256(material.encode('utf-8'))}"
+
+
+def _path_revision(backend: str, path: Path) -> str:
+ try:
+ locator = str(path.resolve())
+ except OSError:
+ locator = str(path.absolute())
+ return _locator_revision(backend, "file", locator)
+
+
+def _keychain_revision(backend: str, service: str, account: str, native_revision: str) -> str:
+ return _locator_revision(backend, "keychain", f"{service}\x00{account}", native_revision)
+
+
+def _read_toml(path: Path) -> tuple[str, dict[str, Any] | None]:
+ try:
+ try:
+ import tomllib # type: ignore[attr-defined]
+ except ImportError: # pragma: no cover - Python 3.10 fallback
+ import tomli as tomllib # type: ignore[no-redef]
+ value = tomllib.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return "missing", {}
+ except (OSError, UnicodeError):
+ return "permission_needed", None
+ except (ValueError, TypeError):
+ return "invalid", None
+ return ("ok", value) if isinstance(value, dict) else ("invalid", None)
+
+
+def _read_json_file(path: Path) -> tuple[str, dict[str, Any] | None, str | None]:
+ """Return ``(status, payload, raw)`` without exposing errors."""
+
+ try:
+ raw = path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return "missing", None, None
+ except (OSError, UnicodeError):
+ return "permission_needed", None, None
+ try:
+ payload = json.loads(raw)
+ except (TypeError, ValueError):
+ return "invalid", None, raw
+ if not isinstance(payload, dict):
+ return "invalid", None, raw
+ return "ok", payload, raw
+
+
+def _json_file_state(path: Path) -> dict[str, Any]:
+ try:
+ raw = path.read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return {"exists": False}
+ except (OSError, UnicodeError) as exc:
+ raise NativeOAuthPermissionError("native credential file could not be read") from exc
+ return {"exists": True, "raw": raw}
+
+
+def _json_file_state_from_raw(raw: str | None) -> dict[str, Any]:
+ if raw is None:
+ return {"exists": False}
+ return {"exists": True, "raw": raw}
+
+
+def _json_after_state(payload: dict[str, Any], original_raw: str) -> dict[str, Any]:
+ rendered = json.dumps(payload, ensure_ascii=False, indent=2)
+ if original_raw.endswith("\n"):
+ rendered += "\n"
+ return {"exists": True, "raw": rendered}
+
+
+def _placeholder(
+ backend: str,
+ revision: str,
+ status: str,
+ *,
+ store: str,
+ service: str | None = None,
+ account: str | None = None,
+) -> NativeOAuthSnapshot:
+ payload: dict[str, Any] = {"status": status, "store": store}
+ if service is not None:
+ payload["service"] = service
+ if account is not None:
+ payload["account"] = account
+ return NativeOAuthSnapshot(backend=backend, revision=revision, payload=payload)
+
+
+def _has_nonempty_string(mapping: Mapping[str, Any], keys: set[str] | frozenset[str]) -> bool:
+ return any(isinstance(mapping.get(key), str) and bool(mapping[key].strip()) for key in keys)
+
+
+def _codex_has_oauth(payload: Mapping[str, Any]) -> bool:
+ tokens = payload.get("tokens")
+ return isinstance(tokens, dict) and _has_nonempty_string(
+ tokens,
+ {"access_token", "refresh_token", "id_token"},
+ )
+
+
+def _codex_has_credential(payload: Mapping[str, Any]) -> bool:
+ return _codex_has_oauth(payload) or (
+ isinstance(payload.get("OPENAI_API_KEY"), str)
+ and bool(payload["OPENAI_API_KEY"].strip())
+ )
+
+
+def _claude_oauth_payload(payload: Mapping[str, Any]) -> dict[str, Any] | None:
+ nested = payload.get("claudeAiOauth")
+ if isinstance(nested, dict) and _has_nonempty_string(nested, _CLAUDE_OAUTH_KEYS):
+ return nested
+ if _has_nonempty_string(payload, _CLAUDE_OAUTH_KEYS):
+ return dict(payload)
+ return None
+
+
+def _claude_identity(payload: Mapping[str, Any]) -> dict[str, set[str]]:
+ nested = payload.get("claudeAiOauth")
+ sources: list[Mapping[str, Any]] = [payload]
+ if isinstance(nested, dict):
+ sources.insert(0, nested)
+ identity: dict[str, set[str]] = {}
+ for source in sources:
+ for key, canonical in _CLAUDE_IDENTITY_KEYS.items():
+ value = source.get(key)
+ if isinstance(value, str) and value.strip():
+ identity.setdefault(canonical, set()).add(value.strip())
+ return identity
+
+
+def _claude_same_account(
+ primary: Mapping[str, Any],
+ fallback: Mapping[str, Any],
+) -> bool:
+ primary_identity = _claude_identity(primary)
+ fallback_identity = _claude_identity(fallback)
+ if any(
+ len(values) != 1
+ for identity in (primary_identity, fallback_identity)
+ for values in identity.values()
+ ):
+ return False
+ shared_keys = primary_identity.keys() & fallback_identity.keys()
+ if any(primary_identity[key] != fallback_identity[key] for key in shared_keys):
+ return False
+ # An organization can contain multiple accounts. Its identity can disprove
+ # compatibility, but cannot prove that two different grants share an owner.
+ if shared_keys & {"account_uuid", "account_id", "email"}:
+ return True
+
+ def refresh_grant(payload: Mapping[str, Any]) -> str | None:
+ nested = payload.get("claudeAiOauth")
+ sources: list[Mapping[str, Any]] = [payload]
+ if isinstance(nested, dict):
+ sources.insert(0, nested)
+ for source in sources:
+ for key in ("refresh_token", "refreshToken"):
+ value = source.get(key)
+ if isinstance(value, str) and value.strip():
+ return value
+ return None
+
+ primary_refresh = refresh_grant(primary)
+ fallback_refresh = refresh_grant(fallback)
+ return bool(
+ primary_refresh
+ and fallback_refresh
+ and hmac.compare_digest(primary_refresh.encode("utf-8"), fallback_refresh.encode("utf-8"))
+ )
+
+
+def _remove_codex_oauth(payload: Mapping[str, Any]) -> dict[str, Any]:
+ result = dict(payload)
+ result.pop("tokens", None)
+ result.pop("last_refresh", None)
+ result.pop("OPENAI_API_KEY", None)
+ if result.get("auth_mode") == "chatgpt":
+ result.pop("auth_mode", None)
+ return result
+
+
+def _remove_claude_oauth(payload: Mapping[str, Any]) -> dict[str, Any]:
+ result = dict(payload)
+ if isinstance(result.get("claudeAiOauth"), dict):
+ result.pop("claudeAiOauth", None)
+ return result
+ for key in _CLAUDE_OAUTH_KEYS | _CLAUDE_OAUTH_METADATA_KEYS:
+ result.pop(key, None)
+ return result
+
+
+def _state_for_json_payload(payload: dict[str, Any], original_raw: str) -> dict[str, Any]:
+ if not payload:
+ return {"exists": False}
+ return _json_after_state(payload, original_raw)
+
+
+def _edit(
+ backend: str,
+ revision: str,
+ operations: list[dict[str, Any]],
+) -> dict[str, Any]:
+ return {
+ "version": 1,
+ "backend": backend,
+ "selection_revision": revision,
+ "operations": operations,
+ }
+
+
+def _file_operation(
+ path: Path,
+ before: dict[str, Any],
+ after: dict[str, Any],
+) -> dict[str, Any]:
+ return {
+ "kind": "file",
+ "path": str(path),
+ "before": before,
+ "after": after,
+ }
+
+
+def _keychain_operation(
+ service: str,
+ account: str,
+ before: dict[str, Any],
+ after: dict[str, Any],
+ *,
+ isolated: bool,
+ persistent_reference: str | None = None,
+ modification_date: float | None = None,
+) -> dict[str, Any]:
+ operation = {
+ "kind": "keychain",
+ "service": service,
+ "account": account,
+ "before": before,
+ "after": after,
+ "store_scope": "fixture" if isolated else "native",
+ }
+ if persistent_reference is not None:
+ operation["persistent_reference"] = persistent_reference
+ if modification_date is not None:
+ operation["modification_date"] = modification_date
+ return operation
+
+
+def _codex_home(home: Path | None) -> Path:
+ return get_codex_home(home)
+
+
+def native_credentials_paths(
+ backend: str,
+ home: Path | None = None,
+) -> tuple[Path, ...]:
+ """Return all supported native credential files, in precedence order."""
+
+ normalized = str(backend or "").strip().lower()
+ if normalized == "codex":
+ return (_codex_home(home) / "auth.json",)
+ if normalized == "claude":
+ secure_root = _claude_locator(home)[0]
+ return (
+ secure_root / ".credentials.json",
+ secure_root / "credentials.json",
+ )
+ return ()
+
+
+def _claude_locator(home: Path | None) -> tuple[Path, str, str]:
+ """Return ``(secure_root, service, account)`` for Claude Code 2.1.273."""
+
+ if home is not None:
+ secure_root = (Path(home).expanduser().resolve() / ".claude").resolve()
+ suffix = ""
+ else:
+ secure_env_defined = "CLAUDE_SECURESTORAGE_CONFIG_DIR" in os.environ
+ secure_env = os.environ.get("CLAUDE_SECURESTORAGE_CONFIG_DIR", "")
+ if secure_env_defined:
+ secure_root = (
+ Path(secure_env).expanduser().resolve()
+ if secure_env
+ else (Path.home() / ".claude").resolve()
+ )
+ suffix = (
+ ""
+ if not secure_env or "CLAUDE_CONFIG_DIR" not in os.environ
+ else f"-{_sha256(str(secure_root).encode('utf-8'))[:8]}"
+ )
+ else:
+ config_defined = "CLAUDE_CONFIG_DIR" in os.environ
+ config_env = os.environ.get("CLAUDE_CONFIG_DIR", "")
+ secure_root = (
+ Path(config_env).expanduser().resolve()
+ if config_env
+ else (Path.home() / ".claude").resolve()
+ )
+ suffix = (
+ ""
+ if not config_defined
+ else f"-{_sha256(str(secure_root).encode('utf-8'))[:8]}"
+ )
+
+ raw_user = os.environ.get("USER") or ""
+ if not raw_user:
+ try:
+ raw_user = os.userInfo().username # type: ignore[attr-defined]
+ except (AttributeError, OSError):
+ try:
+ raw_user = getpass.getuser()
+ except OSError:
+ raw_user = ""
+ account = raw_user if _SAFE_CLAUDE_ACCOUNT.fullmatch(raw_user) else "claude-code-user"
+ return secure_root, f"Claude Code-credentials{suffix}", account
+
+
+def _codex_store_config(codex_home: Path) -> tuple[str, str | None]:
+ config_status, config = _read_toml(codex_home / "config.toml")
+ if config_status in {"permission_needed", "invalid"} or config is None:
+ return "unsupported", f"{config_status}_config"
+ if _secret_auth_storage_enabled(config):
+ return "unsupported", "secret_auth_storage"
+ raw_store = config.get("cli_auth_credentials_store", "file")
+ if not isinstance(raw_store, str):
+ return "unsupported", "invalid_store"
+ store = raw_store.strip().lower()
+ if store not in _CODEX_STORES:
+ return "unsupported", "unknown_store"
+ return store, None
+
+
+def _secret_auth_storage_enabled(value: object) -> bool:
+ if isinstance(value, Mapping):
+ for key, child in value.items():
+ normalized = str(key).strip().lower()
+ if normalized == "secret_auth_storage":
+ if isinstance(child, bool):
+ if child:
+ return True
+ elif child is not None and str(child).strip().lower() not in {
+ "",
+ "false",
+ "off",
+ "disabled",
+ "none",
+ }:
+ return True
+ if normalized in {"auth_keyring_backend", "keyring_backend"} and str(child).strip().lower() in {
+ "secret",
+ "secrets",
+ "managed",
+ }:
+ return True
+ if _secret_auth_storage_enabled(child):
+ return True
+ return False
+
+
+_CFIndex = ctypes.c_long
+_CFTypeRef = ctypes.c_void_p
+_CFStringEncoding = ctypes.c_uint32
+_CFDictionaryCallback = ctypes.c_void_p
+
+
+class _CFDictionaryKeyCallbacks(ctypes.Structure):
+ _fields_ = [
+ ("version", _CFIndex),
+ ("retain", _CFDictionaryCallback),
+ ("release", _CFDictionaryCallback),
+ ("copy_description", _CFDictionaryCallback),
+ ("equal", _CFDictionaryCallback),
+ ("hash", _CFDictionaryCallback),
+ ]
+
+
+class _CFDictionaryValueCallbacks(ctypes.Structure):
+ _fields_ = [
+ ("version", _CFIndex),
+ ("retain", _CFDictionaryCallback),
+ ("release", _CFDictionaryCallback),
+ ("copy_description", _CFDictionaryCallback),
+ ("equal", _CFDictionaryCallback),
+ ]
+
+
+class _CFArrayCallbacks(ctypes.Structure):
+ _fields_ = _CFDictionaryValueCallbacks._fields_
+
+
+class _SecurityBindings:
+ """SDK-typed bindings; construction loads symbols but calls no Sec* API.
+
+ ABI reference: Apple's CFString.h, CFDictionary.h, CFArray.h, SecItem.h
+ and SecKeychain.h. Opaque handles are Python integers (or None for NULL),
+ never c_void_p objects used as Python dictionary keys.
+ """
+
+ def __init__(self, security: Any, core_foundation: Any) -> None:
+ self.security = security
+ self.cf = core_foundation
+ self.constants = {
+ name: ctypes.c_void_p.in_dll(library, name).value
+ for library, names in (
+ (
+ core_foundation,
+ (
+ "kCFAllocatorDefault",
+ "kCFBooleanFalse",
+ "kCFBooleanTrue",
+ ),
+ ),
+ (
+ security,
+ (
+ "kSecAttrAccount",
+ "kSecAttrCreationDate",
+ "kSecAttrModificationDate",
+ "kSecAttrService",
+ "kSecClass",
+ "kSecClassGenericPassword",
+ "kSecMatchLimit",
+ "kSecMatchLimitOne",
+ "kSecMatchItemList",
+ "kSecReturnAttributes",
+ "kSecReturnData",
+ "kSecReturnPersistentRef",
+ "kSecUseAuthenticationUI",
+ "kSecUseAuthenticationUIAllow",
+ "kSecUseAuthenticationUIFail",
+ "kSecValuePersistentRef",
+ "kSecValueData",
+ ),
+ ),
+ )
+ for name in names
+ }
+ self.key_callbacks = _CFDictionaryKeyCallbacks.in_dll(
+ core_foundation,
+ "kCFTypeDictionaryKeyCallBacks",
+ )
+ self.value_callbacks = _CFDictionaryValueCallbacks.in_dll(
+ core_foundation,
+ "kCFTypeDictionaryValueCallBacks",
+ )
+ self.array_callbacks = _CFArrayCallbacks.in_dll(core_foundation, "kCFTypeArrayCallBacks")
+ self._configure()
+
+ def _configure(self) -> None:
+ cf = self.cf
+ cf.CFRelease.argtypes = [_CFTypeRef]
+ cf.CFRelease.restype = None
+ cf.CFGetTypeID.argtypes = [_CFTypeRef]
+ cf.CFGetTypeID.restype = ctypes.c_ulong
+ cf.CFStringCreateWithBytes.argtypes = [
+ _CFTypeRef,
+ ctypes.POINTER(ctypes.c_ubyte),
+ _CFIndex,
+ _CFStringEncoding,
+ ctypes.c_ubyte,
+ ]
+ cf.CFStringCreateWithBytes.restype = _CFTypeRef
+ cf.CFStringGetTypeID.argtypes = []
+ cf.CFStringGetTypeID.restype = ctypes.c_ulong
+ cf.CFStringGetLength.argtypes = [_CFTypeRef]
+ cf.CFStringGetLength.restype = _CFIndex
+ cf.CFStringGetMaximumSizeForEncoding.argtypes = [
+ _CFIndex,
+ _CFStringEncoding,
+ ]
+ cf.CFStringGetMaximumSizeForEncoding.restype = _CFIndex
+ cf.CFStringGetCString.argtypes = [
+ _CFTypeRef,
+ ctypes.c_char_p,
+ _CFIndex,
+ _CFStringEncoding,
+ ]
+ cf.CFStringGetCString.restype = ctypes.c_bool
+ cf.CFDataGetTypeID.argtypes = []
+ cf.CFDataGetTypeID.restype = ctypes.c_ulong
+ cf.CFDataGetLength.argtypes = [_CFTypeRef]
+ cf.CFDataGetLength.restype = _CFIndex
+ cf.CFDataGetBytePtr.argtypes = [_CFTypeRef]
+ cf.CFDataGetBytePtr.restype = ctypes.POINTER(ctypes.c_ubyte)
+ cf.CFDataCreate.argtypes = [
+ _CFTypeRef,
+ ctypes.POINTER(ctypes.c_ubyte),
+ _CFIndex,
+ ]
+ cf.CFDataCreate.restype = _CFTypeRef
+ cf.CFDateGetTypeID.argtypes = []
+ cf.CFDateGetTypeID.restype = ctypes.c_ulong
+ cf.CFDateGetAbsoluteTime.argtypes = [_CFTypeRef]
+ cf.CFDateGetAbsoluteTime.restype = ctypes.c_double
+ cf.CFDateCreate.argtypes = [_CFTypeRef, ctypes.c_double]
+ cf.CFDateCreate.restype = _CFTypeRef
+ cf.CFNumberGetTypeID.argtypes = []
+ cf.CFNumberGetTypeID.restype = ctypes.c_ulong
+ cf.CFNumberGetValue.argtypes = [
+ _CFTypeRef,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ ]
+ cf.CFNumberGetValue.restype = ctypes.c_bool
+ cf.CFBooleanGetTypeID.argtypes = []
+ cf.CFBooleanGetTypeID.restype = ctypes.c_ulong
+ cf.CFBooleanGetValue.argtypes = [_CFTypeRef]
+ cf.CFBooleanGetValue.restype = ctypes.c_bool
+ cf.CFDictionaryCreateMutable.argtypes = [
+ _CFTypeRef,
+ _CFIndex,
+ ctypes.POINTER(_CFDictionaryKeyCallbacks),
+ ctypes.POINTER(_CFDictionaryValueCallbacks),
+ ]
+ cf.CFDictionaryCreateMutable.restype = _CFTypeRef
+ cf.CFDictionarySetValue.argtypes = [
+ _CFTypeRef,
+ _CFTypeRef,
+ _CFTypeRef,
+ ]
+ cf.CFDictionarySetValue.restype = None
+ cf.CFDictionaryGetValue.argtypes = [_CFTypeRef, _CFTypeRef]
+ cf.CFDictionaryGetValue.restype = _CFTypeRef
+ cf.CFDictionaryGetTypeID.argtypes = []
+ cf.CFDictionaryGetTypeID.restype = ctypes.c_ulong
+ cf.CFArrayCreate.argtypes = [
+ _CFTypeRef, ctypes.POINTER(_CFTypeRef), _CFIndex,
+ ctypes.POINTER(_CFArrayCallbacks),
+ ]
+ cf.CFArrayCreate.restype = _CFTypeRef
+ cf.CFArrayGetCount.argtypes = [_CFTypeRef]
+ cf.CFArrayGetCount.restype = _CFIndex
+ cf.CFArrayGetValueAtIndex.argtypes = [_CFTypeRef, _CFIndex]
+ cf.CFArrayGetValueAtIndex.restype = _CFTypeRef
+ self.security.SecItemCopyMatching.argtypes = [
+ _CFTypeRef,
+ ctypes.POINTER(_CFTypeRef),
+ ]
+ self.security.SecItemCopyMatching.restype = ctypes.c_int32
+ self.security.SecItemAdd.argtypes = [_CFTypeRef, ctypes.POINTER(_CFTypeRef)]
+ self.security.SecItemAdd.restype = ctypes.c_int32
+ self.security.SecItemUpdate.argtypes = [_CFTypeRef, _CFTypeRef]
+ self.security.SecItemUpdate.restype = ctypes.c_int32
+ self.security.SecItemDelete.argtypes = [_CFTypeRef]
+ self.security.SecItemDelete.restype = ctypes.c_int32
+ self.security.SecKeychainGetUserInteractionAllowed.argtypes = [ctypes.POINTER(ctypes.c_ubyte)]
+ self.security.SecKeychainGetUserInteractionAllowed.restype = ctypes.c_int32
+ self.security.SecKeychainSetUserInteractionAllowed.argtypes = [ctypes.c_ubyte]
+ self.security.SecKeychainSetUserInteractionAllowed.restype = ctypes.c_int32
+
+ def constant(self, name: str) -> int | None:
+ return self.constants[name]
+
+
+_SECURITY_BINDINGS: _SecurityBindings | None = None
+_ERR_SEC_SUCCESS = 0
+_ERR_SEC_ITEM_NOT_FOUND = -25300
+_ERR_SEC_DUPLICATE_ITEM = -25299
+_UTF8 = 0x08000100
+_CF_NUMBER_DOUBLE = 6
+_KEYCHAIN_INTERACTION_LOCK = threading.RLock()
+
+
+def _security_bindings() -> _SecurityBindings:
+ global _SECURITY_BINDINGS
+ if _SECURITY_BINDINGS is not None:
+ return _SECURITY_BINDINGS
+ if sys.platform != "darwin":
+ raise _KeychainUnavailable("native keychain is unavailable")
+ try:
+ security_path = ctypes.util.find_library("Security") or (
+ "/System/Library/Frameworks/Security.framework/Security"
+ )
+ foundation_path = ctypes.util.find_library("CoreFoundation") or (
+ "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
+ )
+ security = ctypes.CDLL(security_path)
+ core_foundation = ctypes.CDLL(foundation_path)
+ _SECURITY_BINDINGS = _SecurityBindings(security, core_foundation)
+ except (OSError, AttributeError, KeyError) as exc:
+ raise _KeychainUnavailable("native keychain is unavailable") from exc
+ return _SECURITY_BINDINGS
+
+
+def _cf_string(bindings: _SecurityBindings, value: str) -> _CFTypeRef:
+ raw = value.encode("utf-8")
+ buffer = (ctypes.c_ubyte * len(raw)).from_buffer_copy(raw)
+ result = bindings.cf.CFStringCreateWithBytes(
+ bindings.constant("kCFAllocatorDefault"),
+ buffer,
+ len(raw),
+ _UTF8,
+ False,
+ )
+ if not result:
+ raise _KeychainUnavailable("native keychain string allocation failed")
+ return result.value if isinstance(result, ctypes.c_void_p) else result
+
+
+def _cf_data(bindings: _SecurityBindings, value: str) -> _CFTypeRef:
+ raw = value.encode("utf-8") if isinstance(value, str) else value
+ buffer = (ctypes.c_ubyte * len(raw)).from_buffer_copy(raw)
+ result = bindings.cf.CFDataCreate(
+ bindings.constant("kCFAllocatorDefault"),
+ buffer,
+ len(raw),
+ )
+ if not result:
+ raise _KeychainUnavailable("native keychain data allocation failed")
+ return result.value if isinstance(result, ctypes.c_void_p) else result
+
+
+def _cf_dictionary(
+ bindings: _SecurityBindings,
+ values: Mapping[_CFTypeRef, _CFTypeRef],
+) -> _CFTypeRef:
+ dictionary = bindings.cf.CFDictionaryCreateMutable(
+ bindings.constant("kCFAllocatorDefault"),
+ 0,
+ ctypes.byref(bindings.key_callbacks),
+ ctypes.byref(bindings.value_callbacks),
+ )
+ if not dictionary:
+ raise _KeychainUnavailable("native keychain query allocation failed")
+ try:
+ for key, value in values.items():
+ bindings.cf.CFDictionarySetValue(dictionary, key, value)
+ except BaseException:
+ bindings.cf.CFRelease(dictionary)
+ raise
+ return dictionary.value if isinstance(dictionary, ctypes.c_void_p) else dictionary
+
+
+def _release(bindings: _SecurityBindings, *objects: _CFTypeRef) -> None:
+ for value in objects:
+ if value:
+ bindings.cf.CFRelease(value)
+
+
+def _cf_string_value(bindings: _SecurityBindings, value: _CFTypeRef) -> str:
+ if not value or bindings.cf.CFGetTypeID(value) != bindings.cf.CFStringGetTypeID():
+ raise _KeychainUnavailable("native keychain returned invalid attributes")
+ length = bindings.cf.CFStringGetLength(value)
+ maximum = bindings.cf.CFStringGetMaximumSizeForEncoding(length, _UTF8) + 1
+ buffer = ctypes.create_string_buffer(maximum)
+ if not bindings.cf.CFStringGetCString(value, buffer, maximum, _UTF8):
+ raise _KeychainUnavailable("native keychain returned invalid attributes")
+ return buffer.value.decode("utf-8")
+
+
+def _cf_safe_value(bindings: _SecurityBindings, value: _CFTypeRef) -> Any:
+ type_id = bindings.cf.CFGetTypeID(value)
+ if type_id == bindings.cf.CFStringGetTypeID():
+ return _cf_string_value(bindings, value)
+ if type_id == bindings.cf.CFDateGetTypeID():
+ return bindings.cf.CFDateGetAbsoluteTime(value)
+ if type_id == bindings.cf.CFNumberGetTypeID():
+ number = ctypes.c_double()
+ if bindings.cf.CFNumberGetValue(value, _CF_NUMBER_DOUBLE, ctypes.byref(number)):
+ return number.value
+ if type_id == bindings.cf.CFBooleanGetTypeID():
+ return bool(bindings.cf.CFBooleanGetValue(value))
+ if type_id == bindings.cf.CFDataGetTypeID():
+ length = bindings.cf.CFDataGetLength(value)
+ pointer = bindings.cf.CFDataGetBytePtr(value)
+ raw = bytes(pointer[:length]) if pointer and length else b""
+ return f"sha256:{_sha256(raw)}"
+ return f"cf-type-{type_id}"
+
+
+def _cf_data_bytes(bindings: _SecurityBindings, value: _CFTypeRef) -> bytes:
+ if not value or bindings.cf.CFGetTypeID(value) != bindings.cf.CFDataGetTypeID():
+ raise _KeychainUnavailable("native keychain returned invalid data")
+ length = bindings.cf.CFDataGetLength(value)
+ pointer = bindings.cf.CFDataGetBytePtr(value)
+ return bytes(pointer[:length]) if pointer and length else b""
+
+
+def _persistent_reference_from_cf_data(
+ bindings: _SecurityBindings,
+ value: _CFTypeRef | None,
+) -> str | None:
+ if not value:
+ return None
+ raw = _cf_data_bytes(bindings, value)
+ return base64.urlsafe_b64encode(raw).decode("ascii") if raw else None
+
+
+def _persistent_reference_to_cf_data(
+ bindings: _SecurityBindings,
+ value: str,
+) -> _CFTypeRef:
+ try:
+ raw = base64.b64decode(value.encode("ascii"), altchars=b"-_", validate=True)
+ except (ValueError, UnicodeError):
+ raise ValueError("invalid keychain persistent reference") from None
+ if not raw:
+ raise ValueError("invalid keychain persistent reference")
+ return _cf_data(bindings, raw)
+
+
+def _keychain_query(
+ bindings: _SecurityBindings,
+ service: str,
+ account: str,
+ *,
+ return_attributes: bool,
+ return_data: bool,
+ expected: _KeychainRead | None = None,
+ allow_interaction: bool = False,
+) -> tuple[_CFTypeRef, list[_CFTypeRef]]:
+ owned: list[int] = []
+ try:
+ owned.append(_cf_string(bindings, service))
+ owned.append(_cf_string(bindings, account))
+ values = {
+ bindings.constant("kSecClass"): bindings.constant("kSecClassGenericPassword"),
+ bindings.constant("kSecAttrService"): owned[0],
+ bindings.constant("kSecAttrAccount"): owned[1],
+ bindings.constant("kSecUseAuthenticationUI"): bindings.constant(
+ "kSecUseAuthenticationUIAllow"
+ if allow_interaction
+ else "kSecUseAuthenticationUIFail"
+ ),
+ }
+ if return_attributes or return_data:
+ values[bindings.constant("kSecMatchLimit")] = bindings.constant("kSecMatchLimitOne")
+ if return_attributes:
+ values[bindings.constant("kSecReturnAttributes")] = bindings.constant("kCFBooleanTrue")
+ values[bindings.constant("kSecReturnPersistentRef")] = bindings.constant("kCFBooleanTrue")
+ if return_data:
+ values[bindings.constant("kSecReturnData")] = bindings.constant("kCFBooleanTrue")
+ query = _cf_dictionary(bindings, values)
+ try:
+ if expected is not None:
+ _bind_observed_item(bindings, query, expected)
+ except BaseException:
+ _release(bindings, query)
+ raise
+ return query, owned
+ except BaseException:
+ _release(bindings, *owned)
+ raise
+
+
+def _bind_observed_item(
+ bindings: _SecurityBindings,
+ query: int,
+ observed: _KeychainRead,
+) -> None:
+ """macOS SecItem.h requires kSecMatchItemList for persistent references."""
+
+ if not observed.persistent_reference or observed.modification_date is None:
+ raise _KeychainUnavailable("native keychain mutation requires item metadata")
+ owned: list[int] = []
+ try:
+ reference = _persistent_reference_to_cf_data(bindings, observed.persistent_reference)
+ owned.append(reference)
+ array = bindings.cf.CFArrayCreate(
+ None, (_CFTypeRef * 1)(reference), 1, ctypes.byref(bindings.array_callbacks),
+ )
+ if not array:
+ raise _KeychainUnavailable("native keychain query allocation failed")
+ owned.append(array)
+ date = bindings.cf.CFDateCreate(None, observed.modification_date)
+ if not date:
+ raise _KeychainUnavailable("native keychain query allocation failed")
+ owned.append(date)
+ bindings.cf.CFDictionarySetValue(query, bindings.constant("kSecMatchItemList"), array)
+ bindings.cf.CFDictionarySetValue(query, bindings.constant("kSecAttrModificationDate"), date)
+ finally:
+ _release(bindings, *reversed(owned))
+
+
+def _metadata_from_result(
+ bindings: _SecurityBindings,
+ result: _CFTypeRef,
+ *,
+ service: str,
+ account: str,
+) -> _KeychainMetadata:
+ if bindings.cf.CFGetTypeID(result) != bindings.cf.CFDictionaryGetTypeID():
+ raise _KeychainUnavailable("native keychain returned invalid attributes")
+ safe_attributes: dict[str, Any] = {}
+ for name, key in (
+ ("acct", "kSecAttrAccount"),
+ ("svce", "kSecAttrService"),
+ ("cdat", "kSecAttrCreationDate"),
+ ("mdat", "kSecAttrModificationDate"),
+ ):
+ value = bindings.cf.CFDictionaryGetValue(result, bindings.constant(key))
+ if name in {"acct", "svce"}:
+ safe_attributes[name] = _cf_string_value(bindings, value)
+ elif value and bindings.cf.CFGetTypeID(value) == bindings.cf.CFDateGetTypeID():
+ date = bindings.cf.CFDateGetAbsoluteTime(value)
+ if not math.isfinite(date):
+ raise _KeychainUnavailable("native keychain returned invalid timestamps")
+ safe_attributes[name] = date
+ else:
+ raise _KeychainUnavailable("native keychain returned incomplete timestamps")
+ if safe_attributes["acct"] != account or safe_attributes["svce"] != service:
+ raise _KeychainUnavailable("native keychain returned a different item")
+ persistent_reference = _persistent_reference_from_cf_data(
+ bindings,
+ bindings.cf.CFDictionaryGetValue(
+ result,
+ bindings.constant("kSecValuePersistentRef"),
+ ),
+ )
+ if persistent_reference is None:
+ raise _KeychainUnavailable("native keychain returned no item reference")
+ safe_attributes["pref"] = persistent_reference
+ native_revision = _sha256(
+ json.dumps(
+ safe_attributes,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ )
+ attributes = {
+ key: value
+ for key, value in safe_attributes.items()
+ if key != "pref"
+ }
+ attributes.setdefault("acct", account)
+ attributes.setdefault("svce", service)
+ return _KeychainMetadata(
+ "found",
+ native_revision,
+ attributes,
+ persistent_reference,
+ safe_attributes["mdat"],
+ )
+
+
+def _keychain_status(status: int, *, action: str) -> NativeOAuthError:
+ if status == _ERR_SEC_ITEM_NOT_FOUND:
+ return _KeychainNotFound("native keychain item was not found")
+ if status == _ERR_SEC_DUPLICATE_ITEM:
+ return NativeOAuthRevisionError("native keychain item already exists")
+ if status in {-25293, -25308, -25291, -25292}:
+ return _KeychainDenied(f"native keychain {action} was denied")
+ return _KeychainUnavailable(f"native keychain {action} failed")
+
+
+@contextmanager
+def _keychain_call_lock():
+ with _KEYCHAIN_INTERACTION_LOCK:
+ yield
+
+
+@contextmanager
+def _without_keychain_ui(bindings: _SecurityBindings):
+ """Legacy macOS Keychain also needs its documented interaction switch.
+
+ kSecUseAuthenticationUIFail alone is not implemented by every legacy path.
+ Serialize our callers and restore the process setting on every exit.
+ """
+
+ with _keychain_call_lock():
+ previous = ctypes.c_ubyte()
+ status = bindings.security.SecKeychainGetUserInteractionAllowed(ctypes.byref(previous))
+ if status != _ERR_SEC_SUCCESS:
+ raise _keychain_status(status, action="interaction check")
+ status = bindings.security.SecKeychainSetUserInteractionAllowed(False)
+ if status != _ERR_SEC_SUCCESS:
+ raise _keychain_status(status, action="interaction control")
+ try:
+ yield
+ finally:
+ status = bindings.security.SecKeychainSetUserInteractionAllowed(previous.value)
+ if status != _ERR_SEC_SUCCESS:
+ raise _keychain_status(status, action="interaction restore") from None
+
+
+class _SecurityKeychainStore:
+ def _copy_matching(
+ self,
+ service: str,
+ account: str,
+ *,
+ return_attributes: bool,
+ return_data: bool,
+ expected: _KeychainRead | None = None,
+ allow_interaction: bool = False,
+ ) -> tuple[_SecurityBindings, _CFTypeRef]:
+ bindings = _security_bindings()
+ query, owned = _keychain_query(
+ bindings,
+ service,
+ account,
+ return_attributes=return_attributes,
+ return_data=return_data,
+ expected=expected,
+ allow_interaction=allow_interaction,
+ )
+ result = _CFTypeRef()
+ try:
+ if allow_interaction:
+ with _keychain_call_lock():
+ status = bindings.security.SecItemCopyMatching(
+ query,
+ ctypes.byref(result),
+ )
+ else:
+ with _without_keychain_ui(bindings):
+ status = bindings.security.SecItemCopyMatching(query, ctypes.byref(result))
+ finally:
+ _release(bindings, query, *owned)
+ if status != _ERR_SEC_SUCCESS:
+ _release(bindings, result)
+ raise _keychain_status(status, action="read")
+ if not result:
+ raise _KeychainUnavailable("native keychain returned no result")
+ return bindings, result
+
+ def metadata(self, service: str, account: str) -> _KeychainMetadata:
+ try:
+ bindings, result = self._copy_matching(
+ service,
+ account,
+ return_attributes=True,
+ return_data=False,
+ )
+ except _KeychainNotFound:
+ return _KeychainMetadata("not_found", "absent")
+ except _KeychainDenied:
+ return _KeychainMetadata("permission_needed", "permission")
+ except _KeychainUnavailable:
+ raise
+ try:
+ return _metadata_from_result(
+ bindings,
+ result,
+ service=service,
+ account=account,
+ )
+ finally:
+ _release(bindings, result)
+
+ def read(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: _KeychainRead | None = None,
+ ) -> _KeychainRead:
+ bindings, result = self._copy_matching(
+ service,
+ account,
+ return_attributes=True,
+ return_data=True,
+ expected=expected,
+ allow_interaction=True,
+ )
+ try:
+ metadata = _metadata_from_result(
+ bindings,
+ result,
+ service=service,
+ account=account,
+ )
+ data = bindings.cf.CFDictionaryGetValue(
+ result,
+ bindings.constant("kSecValueData"),
+ )
+ if not data:
+ raise _KeychainDenied("native keychain value was unavailable")
+ raw = _cf_data_bytes(bindings, data)
+ if not raw:
+ raise _KeychainDenied("native keychain value was empty")
+ try:
+ value = raw.decode("utf-8")
+ except UnicodeError as exc:
+ raise _KeychainDenied("native keychain value was not UTF-8") from exc
+ return _KeychainRead(
+ value=value,
+ revision=metadata.revision,
+ persistent_reference=metadata.persistent_reference,
+ modification_date=metadata.modification_date,
+ )
+ finally:
+ _release(bindings, result)
+
+ def write(
+ self,
+ service: str,
+ account: str,
+ value: str,
+ *,
+ expected: _KeychainRead | None = None,
+ ) -> None:
+ bindings = _security_bindings()
+ query: _CFTypeRef | None = None
+ query_owned: list[int] = []
+ data: _CFTypeRef | None = None
+ attributes: _CFTypeRef | None = None
+ item: _CFTypeRef | None = None
+ item_owned: list[int] = []
+ try:
+ data = _cf_data(bindings, value)
+ if expected is None:
+ service_ref = _cf_string(bindings, service)
+ item_owned.append(service_ref)
+ account_ref = _cf_string(bindings, account)
+ item_owned.append(account_ref)
+ item = _cf_dictionary(
+ bindings,
+ {
+ bindings.constant("kSecClass"): bindings.constant(
+ "kSecClassGenericPassword"
+ ),
+ bindings.constant("kSecAttrService"): service_ref,
+ bindings.constant("kSecAttrAccount"): account_ref,
+ bindings.constant("kSecValueData"): data,
+ },
+ )
+ with _keychain_call_lock():
+ status = bindings.security.SecItemAdd(item, None)
+ else:
+ query, query_owned = _keychain_query(
+ bindings,
+ service,
+ account,
+ return_attributes=False,
+ return_data=False,
+ expected=expected,
+ allow_interaction=True,
+ )
+ attributes = _cf_dictionary(
+ bindings,
+ {bindings.constant("kSecValueData"): data},
+ )
+ with _keychain_call_lock():
+ status = bindings.security.SecItemUpdate(query, attributes)
+ if status != _ERR_SEC_SUCCESS:
+ raise _keychain_status(status, action="write")
+ finally:
+ _release(
+ bindings,
+ query,
+ attributes,
+ data,
+ item,
+ *query_owned,
+ *item_owned,
+ )
+
+ def delete(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: _KeychainRead,
+ ) -> None:
+ if expected is None:
+ raise ValueError("native keychain delete requires an observed item")
+ bindings = _security_bindings()
+ query, owned = _keychain_query(
+ bindings,
+ service,
+ account,
+ return_attributes=False,
+ return_data=False,
+ expected=expected,
+ allow_interaction=True,
+ )
+ try:
+ with _keychain_call_lock():
+ status = bindings.security.SecItemDelete(query)
+ finally:
+ _release(bindings, query, *owned)
+ if status not in {_ERR_SEC_SUCCESS, _ERR_SEC_ITEM_NOT_FOUND}:
+ raise _keychain_status(status, action="delete")
+
+
+class _FixtureKeychainStore:
+ """A no-op store used whenever a caller supplies a fixture home."""
+
+ def metadata(self, service: str, account: str) -> _KeychainMetadata:
+ return _KeychainMetadata("not_found", "fixture-absent")
+
+ def read(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: _KeychainRead | None = None,
+ ) -> _KeychainRead:
+ raise _KeychainNotFound("fixture keychain item was not found")
+
+ def write(
+ self,
+ service: str,
+ account: str,
+ value: str,
+ *,
+ expected: _KeychainRead | None = None,
+ ) -> None:
+ raise _KeychainUnavailable("fixture keychain is not writable")
+
+ def delete(
+ self,
+ service: str,
+ account: str,
+ *,
+ expected: _KeychainRead,
+ ) -> None:
+ raise _KeychainUnavailable("fixture keychain is not writable")
+
+
+_DEFAULT_KEYCHAIN_STORE: _KeychainStore = _SecurityKeychainStore()
+_KEYCHAIN_STORE: _KeychainStore = _DEFAULT_KEYCHAIN_STORE
+
+
+def _keychain_for(home: Path | None) -> tuple[_KeychainStore, bool]:
+ if _KEYCHAIN_STORE is not _DEFAULT_KEYCHAIN_STORE:
+ return _KEYCHAIN_STORE, False
+ if home is not None:
+ return _FixtureKeychainStore(), True
+ return _KEYCHAIN_STORE, False
+
+
+def _read_keychain_snapshot(
+ backend: str,
+ service: str,
+ account: str,
+ *,
+ store: _KeychainStore,
+ isolated: bool,
+ allow_secret: bool,
+) -> NativeOAuthSnapshot | None:
+ fallback_revision = _keychain_revision(backend, service, account, "permission")
+ try:
+ metadata = store.metadata(service, account)
+ except (_KeychainDenied, _KeychainUnavailable):
+ return _placeholder(
+ backend,
+ fallback_revision,
+ "permission_needed",
+ store="keychain",
+ service=service,
+ account=account,
+ )
+ revision = _keychain_revision(backend, service, account, metadata.revision)
+ if metadata.state == "not_found":
+ return None
+ if metadata.state != "found":
+ return _placeholder(
+ backend,
+ revision,
+ "permission_needed",
+ store="keychain",
+ service=service,
+ account=account,
+ )
+ if not allow_secret:
+ return NativeOAuthSnapshot(
+ backend=backend,
+ revision=revision,
+ payload={
+ "status": "metadata_only",
+ "store": "keychain",
+ "service": service,
+ "account": account,
+ "attributes": dict(metadata.attributes),
+ },
+ )
+
+ try:
+ read = store.read(
+ service,
+ account,
+ expected=_KeychainRead(
+ value="",
+ revision=metadata.revision,
+ persistent_reference=metadata.persistent_reference,
+ modification_date=metadata.modification_date,
+ ),
+ )
+ except _KeychainNotFound:
+ return _placeholder(
+ backend,
+ revision,
+ "changed",
+ store="keychain",
+ service=service,
+ account=account,
+ )
+ except (_KeychainDenied, _KeychainUnavailable):
+ return _placeholder(
+ backend,
+ revision,
+ "permission_needed",
+ store="keychain",
+ service=service,
+ account=account,
+ )
+ if read.revision != metadata.revision:
+ return _placeholder(
+ backend,
+ _keychain_revision(backend, service, account, read.revision),
+ "changed",
+ store="keychain",
+ service=service,
+ account=account,
+ )
+ try:
+ payload = json.loads(read.value)
+ except (TypeError, ValueError):
+ return _placeholder(
+ backend,
+ revision,
+ "unsupported_credentials",
+ store="keychain",
+ service=service,
+ account=account,
+ )
+ if not isinstance(payload, dict):
+ return _placeholder(
+ backend,
+ revision,
+ "unsupported_credentials",
+ store="keychain",
+ service=service,
+ account=account,
+ )
+ if backend == "codex":
+ supported = _codex_has_credential(payload)
+ after_payload = _remove_codex_oauth(payload)
+ else:
+ supported = _claude_oauth_payload(payload) is not None
+ after_payload = _remove_claude_oauth(payload)
+ if not supported and backend != "claude":
+ return None
+
+ before_state = {"exists": True, "value": read.value, "revision": metadata.revision}
+ if supported:
+ after_value = json.dumps(after_payload, ensure_ascii=False, indent=2)
+ after_state: dict[str, Any] = (
+ {"exists": False} if not after_payload else {"exists": True, "value": after_value}
+ )
+ else:
+ # Keep an inspected, non-OAuth Claude container as evidence for a file
+ # fallback. Neither reserialize it nor lose its selection revision.
+ # The Claude resolver excludes this payload from credential candidates.
+ after_state = dict(before_state)
+ operation = _keychain_operation(
+ service,
+ account,
+ before_state,
+ after_state,
+ isolated=isolated,
+ persistent_reference=(
+ read.persistent_reference
+ if read.persistent_reference is not None
+ else metadata.persistent_reference
+ ),
+ modification_date=(
+ read.modification_date
+ if read.modification_date is not None
+ else metadata.modification_date
+ ),
+ )
+ return NativeOAuthSnapshot(
+ backend=backend,
+ revision=revision,
+ payload=payload,
+ exportable=True,
+ keychain_edit=_edit(backend, revision, [operation]),
+ )
+
+
+def _read_codex_file(
+ auth_path: Path,
+ *,
+ allow_secret: bool,
+) -> NativeOAuthSnapshot | None:
+ revision = _path_revision("codex", auth_path)
+ status, payload, raw = _read_json_file(auth_path)
+ if status == "missing":
+ return None
+ if status in {"permission_needed", "invalid"} or payload is None:
+ return _placeholder("codex", revision, status, store="file")
+ if not _codex_has_credential(payload):
+ return None
+ if not allow_secret:
+ return NativeOAuthSnapshot(
+ backend="codex",
+ revision=f"codex:file:{_sha256((raw or '').encode('utf-8'))}",
+ payload=payload,
+ exportable=True,
+ )
+ before = _json_file_state_from_raw(raw)
+ after_payload = _remove_codex_oauth(payload)
+ after = _state_for_json_payload(after_payload, raw or "")
+ operation = _file_operation(auth_path, before, after)
+ file_revision = f"codex:file:{_sha256((raw or '').encode('utf-8'))}"
+ return NativeOAuthSnapshot(
+ backend="codex",
+ revision=file_revision,
+ payload=payload,
+ exportable=True,
+ keychain_edit=_edit("codex", file_revision, [operation]),
+ )
+
+
+def _read_claude_files(
+ credentials_paths: tuple[Path, ...],
+ *,
+ allow_secret: bool,
+ keychain_snapshot: NativeOAuthSnapshot | None = None,
+ service: str | None = None,
+ account: str | None = None,
+) -> NativeOAuthSnapshot | None:
+ # One original read supplies the revision, payload and journal before-image.
+ files = [(path, *_read_json_file(path)) for path in credentials_paths]
+ revision = _locator_revision(
+ "claude",
+ "keychain" if keychain_snapshot is not None else "file",
+ json.dumps({
+ "keychain": keychain_snapshot.revision if keychain_snapshot is not None else None,
+ "files": [
+ [str(path), status, _sha256(raw.encode("utf-8")) if raw is not None else None]
+ for path, status, _, raw in files
+ ],
+ }, ensure_ascii=True, separators=(",", ":")),
+ )
+ for _, status, _, _ in files:
+ if status in {"permission_needed", "invalid"}:
+ # A hidden/invalid fallback cannot be certified free of credentials.
+ return _placeholder("claude", revision, status, store="file")
+
+ payloads = [
+ payload for _, _, payload, _ in files
+ if payload is not None and _claude_oauth_payload(payload) is not None
+ ]
+ if keychain_snapshot is not None and keychain_snapshot.exportable:
+ if (
+ keychain_snapshot.payload is not None
+ and _claude_oauth_payload(keychain_snapshot.payload) is not None
+ ):
+ payloads.insert(0, keychain_snapshot.payload)
+ # Compare every pair: a primary lacking identity must not hide contradictory
+ # identity evidence between two fallback files sharing its refresh grant.
+ if any(
+ not _claude_same_account(primary, fallback)
+ for index, primary in enumerate(payloads)
+ for fallback in payloads[index + 1:]
+ ):
+ return _placeholder(
+ "claude", revision, "conflict",
+ store="keychain+file" if keychain_snapshot is not None else "file",
+ service=service if keychain_snapshot is not None else None,
+ account=account if keychain_snapshot is not None else None,
+ )
+ if keychain_snapshot is not None and not keychain_snapshot.exportable:
+ # Preserve metadata-only/permission semantics, never choose a file over
+ # an unread Keychain. File changes invalidate this same consent revision.
+ return replace(keychain_snapshot, revision=revision)
+ if not payloads:
+ return None
+
+ edit = None
+ if allow_secret:
+ operations = (
+ list(keychain_snapshot.keychain_edit["operations"])
+ if keychain_snapshot is not None and keychain_snapshot.keychain_edit else []
+ )
+ for path, _, payload, raw in files:
+ before = _json_file_state_from_raw(raw)
+ after = (
+ _state_for_json_payload(_remove_claude_oauth(payload), raw or "")
+ if payload is not None and _claude_oauth_payload(payload) is not None
+ else before
+ )
+ operations.append(_file_operation(path, before, after))
+ edit = _edit("claude", revision, operations)
+ return NativeOAuthSnapshot(
+ backend="claude",
+ revision=revision,
+ payload=payloads[0],
+ exportable=True,
+ keychain_edit=edit,
+ )
+
+
+def _read_codex(home: Path | None, *, allow_secret: bool) -> NativeOAuthSnapshot | None:
+ codex_home = _codex_home(home)
+ store_mode, unsupported = _codex_store_config(codex_home)
+ auth_path = native_credentials_paths("codex", home)[0]
+ if unsupported is not None:
+ revision = _locator_revision("codex", "unsupported", str(codex_home), unsupported)
+ return _placeholder("codex", revision, "unsupported_store", store=unsupported)
+ if store_mode == "ephemeral":
+ return None
+ if store_mode == "file":
+ return _read_codex_file(auth_path, allow_secret=allow_secret)
+
+ service = "Codex Auth"
+ canonical_home = codex_home.resolve()
+ account = f"cli|{_sha256(str(canonical_home).encode('utf-8'))[:16]}"
+ store, isolated = _keychain_for(home)
+ keychain_snapshot = _read_keychain_snapshot(
+ "codex",
+ service,
+ account,
+ store=store,
+ isolated=isolated,
+ allow_secret=allow_secret,
+ )
+ if store_mode == "keyring":
+ return keychain_snapshot
+ if keychain_snapshot is not None:
+ return keychain_snapshot
+ return _read_codex_file(auth_path, allow_secret=allow_secret)
+
+
+def _read_claude(home: Path | None, *, allow_secret: bool) -> NativeOAuthSnapshot | None:
+ credentials_paths = native_credentials_paths("claude", home)
+ # Claude uses the file store off macOS. An unavailable Security framework
+ # there is not a Keychain permission request. Explicit fixture homes may
+ # still exercise a fake macOS store on any test host.
+ if home is None and sys.platform != "darwin":
+ return _read_claude_files(credentials_paths, allow_secret=allow_secret)
+ _, service, account = _claude_locator(home)
+ store, isolated = _keychain_for(home)
+ keychain_snapshot = _read_keychain_snapshot(
+ "claude",
+ service,
+ account,
+ store=store,
+ isolated=isolated,
+ allow_secret=allow_secret,
+ )
+ return _read_claude_files(
+ credentials_paths, allow_secret=allow_secret, keychain_snapshot=keychain_snapshot,
+ service=service, account=account,
+ )
+
+
+def read_native_oauth(
+ backend: str,
+ *,
+ home: Path | None = None,
+ allow_secret: bool = False,
+) -> NativeOAuthSnapshot | None:
+ """Resolve the effective native OAuth store for ``backend``.
+
+ ``home`` is a fixture root. Supplying it disables access to the real OS
+ Keychain; tests may replace the module's private ``_KEYCHAIN_STORE`` with
+ a fake store when exercising Keychain behavior.
+ """
+
+ normalized = str(backend or "").strip().lower()
+ if normalized == "codex":
+ return _read_codex(home, allow_secret=allow_secret)
+ if normalized == "claude":
+ return _read_claude(home, allow_secret=allow_secret)
+ return None
+
+
+def _state_value(state: Mapping[str, Any]) -> tuple[bool, str | dict[str, Any] | None]:
+ exists = bool(state.get("exists"))
+ if not exists:
+ return False, None
+ if "raw" in state:
+ value = state["raw"]
+ else:
+ value = state.get("value")
+ if isinstance(value, (str, dict)):
+ return True, value
+ return True, None
+
+
+def _state_matches(live: Mapping[str, Any], expected: Mapping[str, Any]) -> bool:
+ expected_revision = expected.get("revision")
+ if expected_revision is not None and live.get("revision") != expected_revision:
+ return False
+ live_exists, live_value = _state_value(live)
+ expected_exists, expected_value = _state_value(expected)
+ if live_exists != expected_exists:
+ return False
+ if not live_exists:
+ return True
+ if live_value == expected_value:
+ return True
+ if isinstance(live_value, str) and isinstance(expected_value, dict):
+ try:
+ return json.loads(live_value) == expected_value
+ except (TypeError, ValueError):
+ return False
+ if isinstance(live_value, dict) and isinstance(expected_value, str):
+ try:
+ return live_value == json.loads(expected_value)
+ except (TypeError, ValueError):
+ return False
+ return False
+
+
+def _state_without_revision(state: Mapping[str, Any]) -> dict[str, Any]:
+ result = dict(state)
+ result.pop("revision", None)
+ return result
+
+
+def _desired_state_matches(
+ live: Mapping[str, Any],
+ desired: Mapping[str, Any],
+ *,
+ reverse: bool,
+) -> bool:
+ if _state_matches(live, desired):
+ return True
+ return reverse and _state_matches(live, _state_without_revision(desired))
+
+
+def _live_keychain_state(
+ store: _KeychainStore,
+ operation: Mapping[str, Any],
+ *,
+ bind_persistent_reference: bool = True,
+) -> dict[str, Any]:
+ service = operation.get("service")
+ account = operation.get("account")
+ if not isinstance(service, str) or not isinstance(account, str):
+ raise ValueError("invalid keychain edit locator")
+ persistent_reference = (
+ operation.get("persistent_reference") if bind_persistent_reference else None
+ )
+ if persistent_reference is not None and not isinstance(persistent_reference, str):
+ raise ValueError("invalid keychain edit persistent reference")
+ modification_date = operation.get("modification_date")
+ if modification_date is not None and not isinstance(modification_date, (int, float)):
+ raise ValueError("invalid keychain edit modification date")
+ expected = None
+ if bind_persistent_reference and persistent_reference is not None:
+ if modification_date is None:
+ raise ValueError("native keychain edit is missing modification date")
+ expected = _KeychainRead(
+ value="",
+ revision="",
+ persistent_reference=persistent_reference,
+ modification_date=float(modification_date),
+ )
+ try:
+ read = store.read(
+ service,
+ account,
+ expected=expected,
+ )
+ except _KeychainNotFound:
+ return {"exists": False}
+ except (_KeychainDenied, _KeychainUnavailable) as exc:
+ raise NativeOAuthPermissionError("native keychain could not be read") from exc
+ return {
+ "exists": True,
+ "value": read.value,
+ "revision": read.revision,
+ "persistent_reference": read.persistent_reference,
+ "modification_date": read.modification_date,
+ }
+
+
+def _live_keychain_state_for_apply(
+ store: _KeychainStore,
+ operation: Mapping[str, Any],
+ *,
+ reverse: bool,
+) -> dict[str, Any]:
+ if reverse:
+ # The cleanup mutation may have changed mdat. Reverse therefore reads
+ # by the stable service/account locator, then binds the mutation to
+ # the exact item and fresh metadata returned by this read.
+ return _live_keychain_state(
+ store,
+ operation,
+ bind_persistent_reference=False,
+ )
+ live = _live_keychain_state(store, operation)
+ if not live.get("exists") and operation.get("persistent_reference"):
+ # A successful prior update changes mdat, so its original bound query
+ # is intentionally stale on an idempotent retry. Re-read by locator
+ # only to distinguish the desired post-state from a replacement item;
+ # any mutation below is still bound to the fresh observation.
+ locator_live = _live_keychain_state(
+ store,
+ operation,
+ bind_persistent_reference=False,
+ )
+ if locator_live.get("exists"):
+ return locator_live
+ return live
+
+
+def _live_file_state(operation: Mapping[str, Any]) -> dict[str, Any]:
+ raw_path = operation.get("path")
+ if not isinstance(raw_path, str) or not raw_path:
+ raise ValueError("invalid file edit locator")
+ return _json_file_state(Path(raw_path))
+
+
+def _apply_file_state(operation: Mapping[str, Any], desired: Mapping[str, Any]) -> None:
+ raw_path = operation.get("path")
+ if not isinstance(raw_path, str) or not raw_path:
+ raise ValueError("invalid file edit locator")
+ path = Path(raw_path)
+ exists, value = _state_value(desired)
+ if not exists:
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ return
+ except OSError as exc:
+ raise NativeOAuthPermissionError("native credential file could not be removed") from exc
+ return
+ if not isinstance(value, str):
+ raise ValueError("invalid file edit state")
+ try:
+ write_atomic(path, value)
+ except OSError as exc:
+ raise NativeOAuthPermissionError("native credential file could not be written") from exc
+
+
+def _apply_keychain_state(
+ store: _KeychainStore,
+ operation: Mapping[str, Any],
+ desired: Mapping[str, Any],
+ *,
+ observed: Mapping[str, Any],
+) -> None:
+ service = operation.get("service")
+ account = operation.get("account")
+ if not isinstance(service, str) or not isinstance(account, str):
+ raise ValueError("invalid keychain edit locator")
+ exists, value = _state_value(desired)
+ observed_exists = bool(observed.get("exists"))
+ observed_read = None
+ if observed_exists:
+ persistent_reference = observed.get("persistent_reference")
+ modification_date = observed.get("modification_date")
+ if not isinstance(persistent_reference, str) or not isinstance(
+ modification_date,
+ (int, float),
+ ):
+ raise NativeOAuthRevisionError("native keychain item metadata was incomplete")
+ observed_read = _KeychainRead(
+ value=str(observed.get("value", "")),
+ revision=str(observed.get("revision", "")),
+ persistent_reference=persistent_reference,
+ modification_date=float(modification_date),
+ )
+ try:
+ if exists:
+ if not isinstance(value, str):
+ raise ValueError("invalid keychain edit state")
+ store.write(
+ service,
+ account,
+ value,
+ expected=observed_read,
+ )
+ else:
+ if observed_read is None:
+ raise NativeOAuthRevisionError("native keychain item disappeared")
+ store.delete(
+ service,
+ account,
+ expected=observed_read,
+ )
+ except _KeychainNotFound as exc:
+ raise NativeOAuthRevisionError("native keychain item changed") from exc
+ except (_KeychainDenied, _KeychainUnavailable) as exc:
+ raise NativeOAuthPermissionError("native keychain mutation was denied") from exc
+ live = _live_keychain_state(
+ store,
+ operation,
+ bind_persistent_reference=False,
+ )
+ readback_expected = dict(desired)
+ readback_expected.pop("revision", None)
+ if not _state_matches(live, readback_expected):
+ raise NativeOAuthRevisionError("native keychain mutation did not read back")
+
+
+def _normalize_operations(edit: Mapping[str, Any]) -> list[dict[str, Any]]:
+ raw_operations = edit.get("operations")
+ if isinstance(raw_operations, list):
+ operations = raw_operations
+ elif all(key in edit for key in ("service", "account", "before", "after")):
+ operations = [
+ {
+ "kind": "keychain",
+ "service": edit["service"],
+ "account": edit["account"],
+ "before": edit["before"],
+ "after": edit["after"],
+ "store_scope": edit.get("store_scope", "native"),
+ }
+ ]
+ else:
+ raise ValueError("invalid native OAuth edit")
+ if not operations or not all(isinstance(operation, dict) for operation in operations):
+ raise ValueError("invalid native OAuth edit")
+ return operations
+
+
+def _check_edit(
+ edit: Mapping[str, Any],
+ *,
+ target_key: str,
+ reverse: bool,
+) -> bool:
+ operations = _normalize_operations(edit)
+ keychain_store = _KEYCHAIN_STORE
+ for operation in operations:
+ kind = operation.get("kind")
+ if kind == "keychain":
+ if operation.get("store_scope") == "fixture" and keychain_store is _DEFAULT_KEYCHAIN_STORE:
+ raise NativeOAuthPermissionError("fixture keychain is not available")
+ live = _live_keychain_state(
+ keychain_store,
+ operation,
+ bind_persistent_reference=(
+ not reverse and target_key == "before"
+ ),
+ )
+ elif kind == "file":
+ live = _live_file_state(operation)
+ else:
+ raise ValueError("invalid native OAuth edit operation")
+ expected = operation.get(target_key)
+ if not isinstance(expected, dict):
+ raise ValueError("invalid native OAuth edit state")
+ matches = (
+ _desired_state_matches(live, expected, reverse=True)
+ if reverse
+ else _state_matches(live, expected)
+ )
+ if not matches:
+ raise NativeOAuthRevisionError("native OAuth store changed")
+ return True
+
+
+def check_keychain_edit(
+ edit: dict[str, Any],
+ *,
+ applied: bool = False,
+ reverse: bool = False,
+) -> bool:
+ """Check a journal edit before or after forward/reverse recovery."""
+
+ if not isinstance(edit, dict) or edit.get("version") not in {None, 1}:
+ raise ValueError("invalid native OAuth edit")
+ if reverse:
+ target_key = "before" if applied else "after"
+ else:
+ target_key = "after" if applied else "before"
+ return _check_edit(edit, target_key=target_key, reverse=reverse)
+
+
+def apply_keychain_edit(edit: dict[str, Any], *, reverse: bool = False) -> None:
+ """Compare-and-swap a native cleanup edit, or apply its reverse.
+
+ The live state is read and checked for every operation before any
+ operation mutates. A live state that already equals the desired side is
+ accepted as an idempotent retry. Any other state is a stale revision and
+ aborts without mutation. This function only changes local stores; it
+ never performs remote logout or token revocation.
+ """
+
+ if not isinstance(edit, dict) or edit.get("version") not in {None, 1}:
+ raise ValueError("invalid native OAuth edit")
+ operations = _normalize_operations(edit)
+ keychain_store = _KEYCHAIN_STORE
+ planned: list[tuple[dict[str, Any], dict[str, Any], dict[str, Any], bool]] = []
+
+ for operation in operations:
+ kind = operation.get("kind")
+ if kind == "keychain":
+ if operation.get("store_scope") == "fixture" and keychain_store is _DEFAULT_KEYCHAIN_STORE:
+ raise NativeOAuthPermissionError("fixture keychain is not available")
+ live = _live_keychain_state_for_apply(
+ keychain_store,
+ operation,
+ reverse=reverse,
+ )
+ is_keychain = True
+ elif kind == "file":
+ live = _live_file_state(operation)
+ is_keychain = False
+ else:
+ raise ValueError("invalid native OAuth edit operation")
+ expected_key = "after" if reverse else "before"
+ desired_key = "before" if reverse else "after"
+ expected = operation.get(expected_key)
+ desired = operation.get(desired_key)
+ if not isinstance(expected, dict) or not isinstance(desired, dict):
+ raise ValueError("invalid native OAuth edit state")
+ if _desired_state_matches(live, desired, reverse=reverse):
+ planned.append((operation, desired, expected, is_keychain))
+ continue
+ matches = (
+ _desired_state_matches(live, expected, reverse=True)
+ if reverse
+ else _state_matches(live, expected)
+ )
+ if not matches:
+ raise NativeOAuthRevisionError("native OAuth store changed")
+ planned.append((operation, desired, expected, is_keychain))
+
+ try:
+ for operation, desired, expected, is_keychain in planned:
+ if is_keychain:
+ live = _live_keychain_state_for_apply(
+ keychain_store,
+ operation,
+ reverse=reverse,
+ )
+ else:
+ live = _live_file_state(operation)
+ if _desired_state_matches(live, desired, reverse=reverse):
+ continue
+ matches = (
+ _desired_state_matches(live, expected, reverse=True)
+ if reverse
+ else _state_matches(live, expected)
+ )
+ if not matches:
+ raise NativeOAuthRevisionError("native OAuth store changed")
+ if is_keychain:
+ _apply_keychain_state(
+ keychain_store,
+ operation,
+ desired,
+ observed=live,
+ )
+ else:
+ _apply_file_state(operation, desired)
+ if not _state_matches(_live_file_state(operation), desired):
+ raise NativeOAuthRevisionError("native file mutation did not read back")
+ except (NativeOAuthError, OSError, ValueError) as exc:
+ if isinstance(exc, NativeOAuthError):
+ raise
+ raise NativeOAuthError("native OAuth edit could not be applied") from exc