Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): bridge native OAuth to CLI login (#995)
Call Whitee3236607be7e
diff --git a/core/handlers/model_hub/native_oauth.py b/core/handlers/model_hub/native_oauth.pynew file mode 100644index 000000000..ef9ab25d8--- /dev/null+++ b/core/handlers/model_hub/native_oauth.py@@ -0,0 +1,278 @@+"""Bridge Model Hub native subscription OAuth to the existing CLI login flows."""++from __future__ import annotations++import asyncio+import re+from dataclasses import dataclass+from datetime import datetime, timedelta, timezone+from typing import Any, Callable, Mapping, Protocol++from .adapter import OAuthFlowState+from .events import contains_credential_material+from .oauth import NativeOAuthSourceStatus, NativeOAuthUnavailableError++_VENDOR_BACKENDS = {"anthropic": "claude", "openai": "codex"}+_INSTRUCTIONS_KEYS = {+ "anthropic": "settings.models.oauth.pasteCode.hint",+ "openai": "settings.models.oauth.deviceCode.hint",+}+_TIMEOUT_ERROR_KEY = "settings.models.oauth.error.timeout"+_GENERIC_ERROR_KEY = "settings.models.oauth.error.generic"+_MAX_FLOWS = 100+++class AgentAuthService(Protocol):+ setup_timeout_seconds: float++ async def start_web_setup(self, backend: str, *, force_reset: bool = True) -> Any: ...++ def get_web_flow_status(self, flow_id: str) -> dict[str, Any]: ...++ async def submit_web_code(self, flow_id: str, code: str) -> dict[str, Any]: ...++ async def cancel_web_flow(self, flow_id: str) -> dict[str, Any]: ...+++@dataclass+class _FlowBinding:+ source_id: str+ vendor: str+ backend: str+ expires_at_iso: str+ source_status: NativeOAuthSourceStatus | None = None+++def _utc_now() -> datetime:+ return datetime.now(timezone.utc)+++def _safe_label_part(value: object, *, email: bool = False) -> str | None:+ if not isinstance(value, str):+ return None+ candidate = value.strip()+ if (+ not candidate+ or len(candidate) > 64+ or any(ord(character) < 32 for character in candidate)+ or (email and re.fullmatch(r"[^@\s]+@[^@\s]+", candidate) is None)+ or contains_credential_material(candidate)+ ):+ return None+ return candidate+++def _account_label(status: Mapping[str, Any]) -> str | None:+ account = status.get("chatgpt_account")+ explicit = _safe_label_part(status.get("account_label"))+ if explicit is not None:+ return explicit++ email = _safe_label_part(status.get("email"), email=True)+ if isinstance(account, Mapping):+ email = email or _safe_label_part(account.get("email"), email=True)+ plan_type = _safe_label_part(account.get("plan_type"))+ organizations = account.get("organizations")+ organization = None+ if isinstance(organizations, list):+ candidates = [item for item in organizations if isinstance(item, Mapping)]+ selected = next((item for item in candidates if item.get("is_default") is True), None)+ selected = selected or next(iter(candidates), None)+ if selected is not None:+ organization = _safe_label_part(selected.get("title"))+ parts = [part for part in (email, plan_type, organization) if part is not None]+ if parts:+ label = " \u00b7 ".join(parts)+ return label if len(label) <= 192 else email+ return email+++def _signed_in(backend: str, status: Mapping[str, Any]) -> bool:+ active_auth_mode = status.get("active_auth_mode")+ if active_auth_mode == "oauth":+ return True+ if active_auth_mode not in {None, "none"}:+ return False+ if backend == "claude":+ if active_auth_mode == "none":+ return False+ return status.get("has_oauth_credentials") is True+ if backend == "codex":+ # AgentAuthService reports success only after its own Codex CLI probe.+ # The Settings status reader cannot see tokens in the default keyring,+ # so an otherwise non-API-key completion must trust that probe.+ return True+ return False+++class AgentAuthNativeOAuthAdapter:+ """Translate Model Hub OAuth flows to AgentAuthService web-login flows."""++ def __init__(+ self,+ agent_auth_service: AgentAuthService,+ *,+ auth_status_reader: Callable[[str], Mapping[str, Any]],+ now: Callable[[], datetime] = _utc_now,+ ):+ self._agent_auth_service = agent_auth_service+ self._auth_status_reader = auth_status_reader+ self._now = now+ self._flows: dict[str, _FlowBinding] = {}++ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:+ backend = _VENDOR_BACKENDS.get(vendor)+ if backend is None:+ raise NativeOAuthUnavailableError++ flow = await self._agent_auth_service.start_web_setup(backend, force_reset=False)+ flow_id = getattr(flow, "flow_id", None)+ if not isinstance(flow_id, str) or not flow_id:+ raise NativeOAuthUnavailableError+ expires_at = self._now() + timedelta(seconds=self._agent_auth_service.setup_timeout_seconds)+ self._remember(+ flow_id,+ _FlowBinding(+ source_id=source_id,+ vendor=vendor,+ backend=backend,+ expires_at_iso=expires_at.isoformat(),+ ),+ )+ return await self._state_from_payload(flow_id, self._flow_payload(flow))++ async def oauth_status(self, flow_id: str) -> OAuthFlowState:+ binding = self._binding(flow_id)+ payload = self._agent_auth_service.get_web_flow_status(flow_id)+ if payload.get("ok") is not True:+ if payload.get("error") == "flow_not_found":+ self._flows.pop(flow_id, None)+ raise KeyError(flow_id)+ raise NativeOAuthUnavailableError+ return await self._state_from_payload(flow_id, payload, binding=binding)++ async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:+ binding = self._binding(flow_id)+ if binding.vendor != "anthropic":+ raise NativeOAuthUnavailableError+ result = await self._agent_auth_service.submit_web_code(flow_id, value)+ if result.get("ok") is not True:+ if result.get("error") == "flow_not_found":+ self._flows.pop(flow_id, None)+ raise KeyError(flow_id)+ # AgentAuthService leaves malformed/failed Claude submissions+ # retryable. Return its current declaration so the dialog stays on+ # the paste-code form instead of turning a typo into engine_down.+ return await self.oauth_status(flow_id)+ return await self.oauth_status(flow_id)++ async def cancel_oauth(self, flow_id: str) -> None:+ self._binding(flow_id)+ result = await self._agent_auth_service.cancel_web_flow(flow_id)+ if result.get("ok") is not True:+ if result.get("error") == "flow_not_found":+ self._flows.pop(flow_id, None)+ raise KeyError(flow_id)+ raise NativeOAuthUnavailableError+ self._flows.pop(flow_id, None)++ def completed_source_status(self, flow_id: str) -> NativeOAuthSourceStatus:+ status = self._binding(flow_id).source_status+ if status is None:+ raise KeyError(flow_id)+ return status++ def _binding(self, flow_id: str) -> _FlowBinding:+ try:+ return self._flows[flow_id]+ except KeyError:+ raise KeyError(flow_id) from None++ def _remember(self, flow_id: str, binding: _FlowBinding) -> None:+ self._flows.pop(flow_id, None)+ self._flows[flow_id] = binding+ while len(self._flows) > _MAX_FLOWS:+ self._flows.pop(next(iter(self._flows)))++ @staticmethod+ def _flow_payload(flow: Any) -> dict[str, Any]:+ return {+ "ok": True,+ "flow_id": getattr(flow, "flow_id", None),+ "state": getattr(flow, "state", None),+ "url": getattr(flow, "url", None),+ "device_code": getattr(flow, "device_code", None),+ "error": getattr(flow, "error", None),+ }++ async def _state_from_payload(+ self,+ flow_id: str,+ payload: Mapping[str, Any],+ *,+ binding: _FlowBinding | None = None,+ ) -> OAuthFlowState:+ binding = binding or self._binding(flow_id)+ state = {+ "awaiting_code": "awaiting_action",+ "starting": "starting",+ "verifying": "verifying",+ "success": "success",+ "failed": "failed",+ "cancelled": "cancelled",+ }.get(str(payload.get("state")), "failed")+ if state == "success" and binding.source_status is None:+ binding.source_status = await self._read_source_status(binding.backend)++ error_key = None+ if state == "failed":+ error_key = _TIMEOUT_ERROR_KEY if payload.get("error") == "timed_out" else _GENERIC_ERROR_KEY+ elif state == "cancelled":+ error_key = _GENERIC_ERROR_KEY++ return OAuthFlowState(+ flow_id=flow_id,+ source_id=binding.source_id,+ vendor=binding.vendor,+ state=state,+ auth_url=payload.get("url") if isinstance(payload.get("url"), str) else None,+ device_code=(payload.get("device_code") if isinstance(payload.get("device_code"), str) else None),+ expects="paste_code" if binding.vendor == "anthropic" else "none",+ instructions_key=_INSTRUCTIONS_KEYS[binding.vendor],+ error_key=error_key,+ expires_at_iso=binding.expires_at_iso,+ credential_ref=None,+ )++ async def _read_source_status(self, backend: str) -> NativeOAuthSourceStatus:+ try:+ status = await asyncio.to_thread(self._auth_status_reader, backend)+ if not isinstance(status, Mapping):+ raise TypeError("invalid auth status")+ except Exception: # noqa: BLE001+ # AgentAuthService reached success only after its own CLI status+ # probe. Preserve that verified signal when the display-status read+ # is temporarily unavailable; account identity can remain absent.+ return NativeOAuthSourceStatus(signed_in=True, account_label=None)+ return NativeOAuthSourceStatus(+ signed_in=_signed_in(backend, status),+ account_label=_account_label(status),+ )+++def create_native_oauth_adapter() -> AgentAuthNativeOAuthAdapter:+ """Resolve the shared web-login service and sanctioned auth status readers."""++ from vibe import api++ def read_auth_status(backend: str) -> Mapping[str, Any]:+ if backend == "claude":+ return api.get_claude_auth()+ if backend == "codex":+ return api.get_codex_auth()+ raise NativeOAuthUnavailableError++ return AgentAuthNativeOAuthAdapter(+ api._get_oauth_service(),+ auth_status_reader=read_auth_status,+ )diff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.pyindex c565f1409..171bcaf37 100644--- a/core/handlers/model_hub/oauth.py+++ b/core/handlers/model_hub/oauth.py@@ -13,6 +13,7 @@ from typing import Literal, Optional, Protocolfrom .adapter import OAuthFlowStateOAuthChannel = Literal["native_cli", "hub"]+NATIVE_OAUTH_SIGNED_OUT_DETAIL_KEY = "settings.models.source.oauthSignedOut"@dataclass(frozen=True)@@ -20,6 +21,8 @@ class OAuthFlowBinding:channel: OAuthChannelsource_id: Optional[str]vendor: Optional[str]+ experimental_consent: bool = False+ completed: bool = Falseclass OAuthAdapter(Protocol):@@ -32,6 +35,18 @@ class OAuthAdapter(Protocol):async def cancel_oauth(self, flow_id: str) -> None: ...+@dataclass(frozen=True)+class NativeOAuthSourceStatus:+ """Non-secret native source metadata resolved after CLI login succeeds."""++ signed_in: bool+ account_label: str | None+++class NativeOAuthAdapter(OAuthAdapter, Protocol):+ def completed_source_status(self, flow_id: str) -> NativeOAuthSourceStatus: ...++class NativeOAuthUnavailableError(RuntimeError):pass@@ -51,9 +66,12 @@ class UnavailableNativeOAuthAdapter:async def cancel_oauth(self, flow_id: str) -> None:raise NativeOAuthUnavailableError+ def completed_source_status(self, flow_id: str) -> NativeOAuthSourceStatus:+ raise NativeOAuthUnavailableError+class OAuthFlowRegistry:- """Persist the non-secret source identity associated with each in-flight flow."""+ """Persist non-secret source identity, consent, and completion state."""def __init__(self, path: Path, *, max_entries: int = 100):self.path = path@@ -81,12 +99,22 @@ class OAuthFlowRegistry:channel = value.get("channel")source_id = value.get("source_id")vendor = value.get("vendor")+ experimental_consent = value.get("experimental_consent", False)+ completed = value.get("completed", False)if (channel in {"native_cli", "hub"}and (source_id is None or (isinstance(source_id, str) and source_id))and (vendor is None or (isinstance(vendor, str) and vendor))+ and isinstance(experimental_consent, bool)+ and isinstance(completed, bool)):- flows[flow_id] = OAuthFlowBinding(channel, source_id, vendor)+ flows[flow_id] = OAuthFlowBinding(+ channel,+ source_id,+ vendor,+ experimental_consent,+ completed,+ )return flowsdef _write(self, payload: dict[str, OAuthFlowBinding]) -> None:@@ -98,6 +126,8 @@ class OAuthFlowRegistry:"channel": binding.channel,"source_id": binding.source_id,"vendor": binding.vendor,+ "experimental_consent": binding.experimental_consent,+ "completed": binding.completed,}for flow_id, binding in bounded.items()},@@ -112,11 +142,39 @@ class OAuthFlowRegistry:os.chmod(temp_name, 0o600)os.replace(temp_name, self.path)- def remember(self, flow_id: str, channel: OAuthChannel, source_id: str, vendor: str) -> None:+ def remember(+ self,+ flow_id: str,+ channel: OAuthChannel,+ source_id: str,+ vendor: str,+ *,+ experimental_consent: bool = False,+ ) -> None:with self._lock:flows = self._read()flows.pop(flow_id, None)- flows[flow_id] = OAuthFlowBinding(channel, source_id, vendor)+ flows[flow_id] = OAuthFlowBinding(+ channel,+ source_id,+ vendor,+ experimental_consent,+ )+ self._write(flows)++ def complete(self, flow_id: str) -> None:+ with self._lock:+ flows = self._read()+ binding = flows.get(flow_id)+ if binding is None:+ raise KeyError(flow_id)+ flows[flow_id] = OAuthFlowBinding(+ binding.channel,+ binding.source_id,+ binding.vendor,+ binding.experimental_consent,+ True,+ )self._write(flows)def channel(self, flow_id: str) -> OAuthChannel | None:diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 85aaef4d2..be5d1abe8 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -57,6 +57,8 @@ from .migration import (scan_native_configs,)from .oauth import (+ NATIVE_OAUTH_SIGNED_OUT_DETAIL_KEY,+ NativeOAuthAdapter,NativeOAuthUnavailableError,OAuthAdapter,OAuthChannel,@@ -350,7 +352,7 @@ class ModelHubService:store: ModelHubConfigStore,adapter: EngineAdapter,events: BoundedEventLog,- native_oauth_adapter: Optional[OAuthAdapter] = None,+ native_oauth_adapter: Optional[NativeOAuthAdapter] = None,oauth_flows: Optional[OAuthFlowRegistry] = None,revocations: Optional[CredentialRevocationJournal] = None,migration_claude_oauth_probe: Optional[Callable[[], bool]] = None,@@ -577,6 +579,8 @@ class ModelHubService:channel: Literal["native_cli", "hub"],vendor: str,consented: bool,+ completed_flow: Optional[OAuthFlowState] = None,+ idempotent: bool = False,) -> dict:# Claim and consume a completed flow under the aggregate lock. This# prevents a duplicate browser retry from revoking the winning source's@@ -588,7 +592,12 @@ class ModelHubService:binding = self._oauth_binding(oauth_ref)if binding.channel != channel:raise ModelHubError("flow_not_found", status=404)- flow = await self._oauth_status(oauth_ref, binding.channel)+ if binding.completed:+ existing = self._completed_oauth_source(binding)+ if idempotent and existing is not None:+ return existing.to_payload()+ raise ModelHubError("flow_not_found", status=404)+ flow = completed_flow or await self._oauth_status(oauth_ref, binding.channel)if flow.state != "success" or (channel == "hub" and not flow.credential_ref):raise ModelHubError("flow_not_found", status=404)if (@@ -600,11 +609,36 @@ class ModelHubService:source.id = flow.source_idprevious = self.store.load()- if any(item.id == source.id for item in previous.sources):+ existing = next((item for item in previous.sources if item.id == source.id), None)+ if idempotent and existing is not None and self._source_matches_binding(existing, binding):+ try:+ self.oauth_flows.complete(oauth_ref)+ except (KeyError, OSError):+ pass+ return existing.to_payload()+ if existing is not None:raise ModelHubError("migration_item_conflict", status=409)if channel == "hub":source.credential_ref = cast(str, flow.credential_ref)rollback_credential_ref = source.credential_ref+ else:+ try:+ source_status = self.native_oauth_adapter.completed_source_status(oauth_ref)+ except KeyError:+ raise ModelHubError("flow_not_found", status=404) from None+ except NativeOAuthUnavailableError:+ raise ModelHubError("engine_down", status=503) from None+ except Exception:+ raise ModelHubError("engine_down", status=503) from None+ source.account_label = source_status.account_label+ source.state = (+ ModelHubSourceStateConfig(status="active")+ if source_status.signed_in+ else ModelHubSourceStateConfig(+ status="error",+ detail_key=NATIVE_OAUTH_SIGNED_OUT_DETAIL_KEY,+ )+ )discovered = (await self._discover(source)@@ -621,8 +655,8 @@ class ModelHubService:)persisted = Truetry:- self.oauth_flows.forget(oauth_ref)- except OSError:+ self.oauth_flows.complete(oauth_ref)+ except (KeyError, OSError):passreturn source.to_payload()except Exception:@@ -634,6 +668,115 @@ class ModelHubService:passraise+ @staticmethod+ def _source_matches_binding(+ source: ModelHubSourceConfig,+ binding: OAuthFlowBinding,+ ) -> bool:+ return (+ source.kind == "subscription"+ and source.supply_channel == binding.channel+ and source.vendor == binding.vendor+ )++ def _completed_oauth_source(+ self,+ binding: OAuthFlowBinding,+ ) -> ModelHubSourceConfig | None:+ if binding.source_id is None:+ return None+ source = next(+ (item for item in self.store.load().sources if item.id == binding.source_id),+ None,+ )+ if source is None or not self._source_matches_binding(source, binding):+ return None+ return source++ def _completed_oauth_flow(+ self,+ flow_id: str,+ binding: OAuthFlowBinding,+ ) -> OAuthFlowState | None:+ source = self._completed_oauth_source(binding)+ if source is None:+ if binding.completed:+ try:+ self.oauth_flows.forget(flow_id)+ except OSError:+ pass+ raise ModelHubError("flow_not_found", status=404)+ return None+ if not binding.completed:+ try:+ self.oauth_flows.complete(flow_id)+ except (KeyError, OSError):+ pass+ failed = source.state.status == "error"+ return OAuthFlowState(+ flow_id=flow_id,+ source_id=source.id,+ vendor=source.vendor,+ state="failed" if failed else "success",+ auth_url=None,+ device_code=None,+ expects="none",+ instructions_key=None,+ error_key=(+ source.state.detail_key or "settings.models.oauth.error.generic"+ if failed+ else None+ ),+ expires_at_iso=None,+ credential_ref=source.credential_ref,+ )++ async def _materialize_completed_oauth(+ self,+ flow_id: str,+ binding: OAuthFlowBinding,+ flow: OAuthFlowState,+ ) -> OAuthFlowState:+ if flow.state != "success":+ return flow+ if binding.source_id is None or binding.vendor is None:+ raise ModelHubError("flow_not_found", status=404)+ if binding.channel == "hub" and not binding.experimental_consent:+ raise ModelHubError("consent_required", status=409)++ source = ModelHubSourceConfig(+ id=binding.source_id,+ kind="subscription",+ vendor=binding.vendor,+ display_name=binding.vendor,+ protocol=_default_protocol(binding.vendor),+ base_url=None,+ supply_channel=binding.channel,+ experimental_consent_at=(+ self.now().isoformat()+ if binding.channel == "hub" and binding.experimental_consent+ else None+ ),+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ usage=ModelHubSourceUsageConfig(),+ models=[],+ )+ await self._create_oauth_source(+ source,+ [],+ oauth_ref=flow_id,+ channel=binding.channel,+ vendor=binding.vendor,+ consented=binding.experimental_consent,+ completed_flow=flow,+ idempotent=True,+ )+ completed = self._completed_oauth_flow(flow_id, binding)+ if completed is None:+ raise ModelHubError("flow_not_found", status=404)+ return completed+def list_sources(self) -> list[dict]:config = self.store.load()by_id = {source.id: source for source in config.sources}@@ -1088,7 +1231,13 @@ class ModelHubService:)if flow.source_id != pending_source_id or flow.vendor != vendor:raise ModelHubError("flow_not_found", status=502)- self.oauth_flows.remember(flow.flow_id, oauth_channel, pending_source_id, vendor)+ self.oauth_flows.remember(+ flow.flow_id,+ oauth_channel,+ pending_source_id,+ vendor,+ experimental_consent=consented,+ )if channel == "hub" and consented:async with self._mutation_lock:config = self.store.load()@@ -1097,24 +1246,32 @@ class ModelHubService:return _oauth_payload(flow, channel=channel)async def oauth_status(self, flow_id: str) -> dict:- channel = self._oauth_channel(flow_id)- flow = await self._oauth_status(flow_id, channel)+ binding = self._oauth_binding(flow_id)+ completed = self._completed_oauth_flow(flow_id, binding)+ if completed is not None:+ return _oauth_payload(completed, channel=binding.channel)+ flow = await self._oauth_status(flow_id, binding.channel)self._raise_if_flow_expired(flow_id, flow)- return _oauth_payload(flow, channel=channel)+ flow = await self._materialize_completed_oauth(flow_id, binding, flow)+ return _oauth_payload(flow, channel=binding.channel)async def oauth_submit(self, payload: dict) -> dict:flow_id = payload.get("flow_id") if isinstance(payload, dict) else Nonevalue = payload.get("value") if isinstance(payload, dict) else Noneif not isinstance(flow_id, str) or not isinstance(value, str):raise ModelHubError("flow_not_found", status=404)- channel = self._oauth_channel(flow_id)- current = await self._oauth_status(flow_id, channel)+ binding = self._oauth_binding(flow_id)+ completed = self._completed_oauth_flow(flow_id, binding)+ if completed is not None:+ return _oauth_payload(completed, channel=binding.channel)+ current = await self._oauth_status(flow_id, binding.channel)self._raise_if_flow_expired(flow_id, current)flow = await self._oauth_call(- self._oauth_adapter(channel).submit_oauth(flow_id, value),+ self._oauth_adapter(binding.channel).submit_oauth(flow_id, value),flow_id=flow_id,)- return _oauth_payload(flow, channel=channel)+ flow = await self._materialize_completed_oauth(flow_id, binding, flow)+ return _oauth_payload(flow, channel=binding.channel)async def oauth_cancel(self, flow_id: object) -> None:if not isinstance(flow_id, str):@@ -1191,7 +1348,9 @@ class ModelHubService:retry_at = self.now() + timedelta(days=1)if retry_at > self.now():continue- source.state = ModelHubSourceStateConfig(status="standby")+ source.state = ModelHubSourceStateConfig(+ status=("active" if source.supply_channel == "native_cli" else "standby")+ )config_changed = Trueself._record_event(agent=cast(EventAgent, backend),@@ -1425,13 +1584,18 @@ class ModelHubService:def create_default_service(*,adapter: Optional[EngineAdapter] = None,- native_oauth_adapter: Optional[OAuthAdapter] = None,+ native_oauth_adapter: Optional[NativeOAuthAdapter] = None,) -> ModelHubService:if adapter is None:from vibe.model_hub_runtime import get_model_hub_engine_adapteradapter = get_model_hub_engine_adapter()+ if native_oauth_adapter is None:+ from .native_oauth import create_native_oauth_adapter++ native_oauth_adapter = create_native_oauth_adapter()+def claude_oauth_probe() -> bool:from vibe.api import (_build_claude_status_probe_env,diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex 7c5e9cbb7..222a8493b 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -263,11 +263,16 @@ class ModelHubRuntimeRouter:self.service = serviceself.turn_gateway = turn_gatewayself.overlay_path = overlay_path or paths.get_runtime_dir() / "model-hub" / "opencode-overlay.json"+ self._uses_default_native_cli_ready = native_cli_ready is Noneself.native_cli_ready = native_cli_ready or self._default_native_cli_readyself._last_launch: dict[tuple[BackendName, str], ModelHubLaunch] = {}@staticmethod- def _default_native_cli_ready(backend: BackendName) -> bool:+ def _default_native_cli_ready(+ backend: BackendName,+ *,+ verified_oauth: bool = False,+ ) -> bool:if backend == "claude":from vibe.claude_config import read_claude_settings_env@@ -283,7 +288,11 @@ class ModelHubRuntimeRouter:if any(os.environ.get(key) for key in conflicts):return Falsestate = read_codex_auth_state()- if state.get("has_api_key") or not state.get("has_chatgpt_tokens") or state.get("base_url"):+ if (+ state.get("has_api_key")+ or (not state.get("has_chatgpt_tokens") and not verified_oauth)+ or state.get("base_url")+ ):return Falseconfig_path, _ = get_codex_config_paths()try:@@ -300,6 +309,18 @@ class ModelHubRuntimeRouter:provider = config.get("model_provider") if isinstance(config, dict) else Nonereturn provider is None or provider == "openai"+ def _native_source_ready(+ self,+ backend: BackendName,+ source: ModelHubSourceConfig,+ ) -> bool:+ if not self._uses_default_native_cli_ready:+ return self.native_cli_ready(backend)+ return self._default_native_cli_ready(+ backend,+ verified_oauth=backend == "codex" and source.state.status == "active",+ )+@staticmethoddef _route_key(launch: ModelHubLaunch) -> tuple[BackendName, str]:return launch.backend, launch.target_model@@ -519,7 +540,8 @@ class ModelHubRuntimeRouter:(candidatefor candidate in candidates- if candidate.supply_channel != "native_cli" or self.native_cli_ready(backend)+ if candidate.supply_channel != "native_cli"+ or self._native_source_ready(backend, candidate)),None,)diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.pynew file mode 100644index 000000000..dac31716f--- /dev/null+++ b/tests/scenario_harness/model_hub_native_oauth.py@@ -0,0 +1,177 @@+from __future__ import annotations++import uuid+from datetime import datetime, timezone+from pathlib import Path+from types import SimpleNamespace+from typing import Any++from config.v2_config import ModelHubConfig+from core.handlers.model_hub.adapter import OAuthFlowState+from core.handlers.model_hub.events import BoundedEventLog+from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter+from core.handlers.model_hub.oauth import OAuthFlowRegistry+from core.handlers.model_hub.revocations import CredentialRevocationJournal+from core.handlers.model_hub.service import ModelHubService, UnavailableEngineAdapter+++class MemoryStore:+ def __init__(self, *, experimental: bool = False):+ self.config = ModelHubConfig.fresh()+ self.config.subscription_hub_experimental = experimental++ def load(self) -> ModelHubConfig:+ return self.config++ def save(self, config: ModelHubConfig) -> None:+ self.config = config+++class FakeAgentAuthService:+ """AgentAuthService boundary fake; the native adapter remains real."""++ setup_timeout_seconds = 900.0++ def __init__(self):+ self.flows: dict[str, SimpleNamespace] = {}+ self.submissions: list[tuple[str, str]] = []+ self.cancelled: list[str] = []++ async def start_web_setup(self, backend: str, *, force_reset: bool = True):+ assert force_reset is False+ flow_id = f"web_{uuid.uuid4().hex[:8]}"+ flow = SimpleNamespace(+ flow_id=flow_id,+ backend=backend,+ state="awaiting_code" if backend == "claude" else "starting",+ url=("https://claude.ai/oauth/authorize?test=true" if backend == "claude" else None),+ device_code=None,+ error=None,+ )+ self.flows[flow_id] = flow+ return flow++ def get_web_flow_status(self, flow_id: str) -> dict[str, Any]:+ flow = self.flows.get(flow_id)+ if flow is None:+ return {"ok": False, "error": "flow_not_found"}+ return {+ "ok": True,+ "flow_id": flow.flow_id,+ "backend": flow.backend,+ "state": flow.state,+ "url": flow.url,+ "device_code": flow.device_code,+ "error": flow.error,+ }++ async def submit_web_code(self, flow_id: str, code: str) -> dict[str, Any]:+ flow = self.flows.get(flow_id)+ if flow is None:+ return {"ok": False, "error": "flow_not_found"}+ if "#" not in code:+ return {"ok": False, "error": "invalid_format"}+ self.submissions.append((flow_id, code))+ flow.state = "verifying"+ return {"ok": True}++ async def cancel_web_flow(self, flow_id: str) -> dict[str, Any]:+ flow = self.flows.pop(flow_id, None)+ if flow is None:+ return {"ok": False, "error": "flow_not_found"}+ self.cancelled.append(flow_id)+ return {"ok": True}++ def expose_codex_device_flow(self, flow_id: str) -> None:+ flow = self.flows[flow_id]+ flow.url = "https://auth.openai.com/codex/device"+ flow.device_code = "T74L-XU61D"+ flow.state = "awaiting_code"++ def complete(self, flow_id: str) -> None:+ self.flows[flow_id].state = "success"++ def timeout(self, flow_id: str) -> None:+ flow = self.flows[flow_id]+ flow.state = "failed"+ flow.error = "timed_out"+++class NativeOAuthScenarioHarness:+ def __init__(self, state_dir: Path):+ self.agent_auth = FakeAgentAuthService()+ self.auth_status = {+ "claude": {"active_auth_mode": "oauth"},+ "codex": {"active_auth_mode": "oauth"},+ }+ self.adapter = AgentAuthNativeOAuthAdapter(+ self.agent_auth,+ auth_status_reader=lambda backend: self.auth_status[backend],+ now=lambda: datetime(2026, 7, 25, 0, 0, tzinfo=timezone.utc),+ )+ self.store = MemoryStore()+ self.service = ModelHubService(+ store=self.store,+ adapter=UnavailableEngineAdapter(),+ events=BoundedEventLog(state_dir / "events.json"),+ native_oauth_adapter=self.adapter,+ oauth_flows=OAuthFlowRegistry(state_dir / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(state_dir / "revocations.json"),+ now=lambda: datetime(2026, 7, 25, 0, 0, tzinfo=timezone.utc),+ )+++class FakeHubOAuthAdapter(UnavailableEngineAdapter):+ def __init__(self):+ self.flows: dict[str, OAuthFlowState] = {}+ self.synced = []++ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:+ flow = OAuthFlowState(+ flow_id=f"hub_{uuid.uuid4().hex[:8]}",+ source_id=source_id,+ vendor=vendor,+ state="awaiting_action",+ auth_url="https://example.test/oauth",+ device_code=None,+ expects="paste_code",+ instructions_key="settings.models.oauth.pasteCode.hint",+ error_key=None,+ expires_at_iso="2026-07-25T00:15:00+00:00",+ credential_ref=None,+ )+ self.flows[flow.flow_id] = flow+ return flow++ async def oauth_status(self, flow_id: str) -> OAuthFlowState:+ return self.flows[flow_id]++ async def sync_sources(self, bindings) -> None:+ self.synced.append(tuple(bindings))++ async def discover_models(self, vendor, protocol, base_url, credential_ref):+ return ("claude-opus-4-6",)++ def complete(self, flow_id: str) -> None:+ flow = self.flows[flow_id]+ self.flows[flow_id] = OAuthFlowState(+ **{+ **flow.__dict__,+ "state": "success",+ "credential_ref": "cred_consent01",+ }+ )+++class HubOAuthScenarioHarness:+ def __init__(self, state_dir: Path):+ self.adapter = FakeHubOAuthAdapter()+ self.store = MemoryStore(experimental=True)+ self.service = ModelHubService(+ store=self.store,+ adapter=self.adapter,+ events=BoundedEventLog(state_dir / "hub-events.json"),+ oauth_flows=OAuthFlowRegistry(state_dir / "hub-oauth-flows.json"),+ revocations=CredentialRevocationJournal(state_dir / "hub-revocations.json"),+ now=lambda: datetime(2026, 7, 25, 0, 0, tzinfo=timezone.utc),+ )diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 8436e1e1c..01d0d149b 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -15,6 +15,7 @@ capabilities:observations: tests/scenarios/model_hub/observations.yamlscenario_tests:- tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+ - tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.pyunit_or_contract_tests:- tests/test_model_hub_api.py- tests/test_model_hub_config.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 7ac756d1e..6054f4f4f 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -7,6 +7,7 @@ capability:- tests/test_model_hub_config.py- tests/test_model_hub_resolution.py- tests/test_model_hub_injection.py+ - tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py- tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pystatus_legend:covered: closed-loop scenario coverage exists@@ -137,6 +138,30 @@ scenarios:kind: timeout_cancellayer: contracttest: tests/test_model_hub_api.py::test_model_hub_rest_api_contract+ - id: MH-OAUTH-NATIVE-001+ name: Claude native CLI paste-code login persists an active Source+ status: covered+ kind: oauth+ layer: scenario+ test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_001_claude_paste_code_happy_path+ - id: MH-OAUTH-NATIVE-002+ name: Codex native CLI device-code login self-completes and persists its account Source+ status: covered+ kind: oauth+ layer: scenario+ test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_002_codex_device_code_self_completes+ - id: MH-OAUTH-NATIVE-003+ name: Native CLI OAuth cancel, timeout, and signed-out state terminate safely+ status: covered+ kind: timeout_cancel+ layer: scenario+ test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly+ - id: MH-OAUTH-CONSENT-001+ name: Experimental hub OAuth requires and persists explicit consent before Source creation+ status: covered+ kind: oauth_consent+ layer: scenario+ test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_consent_001_is_required_and_persistednext_priority:- MH-RES-001- MH-PRI-001@@ -153,3 +178,7 @@ next_priority:- MH-OAUTH-B-001- MH-OAUTH-C-001- MH-OAUTH-ERR-001+ - MH-OAUTH-NATIVE-001+ - MH-OAUTH-NATIVE-002+ - MH-OAUTH-NATIVE-003+ - MH-OAUTH-CONSENT-001diff --git a/tests/scenarios/model_hub/observations.yaml b/tests/scenarios/model_hub/observations.yamlindex 4fd666c7c..7b29f539d 100644--- a/tests/scenarios/model_hub/observations.yaml+++ b/tests/scenarios/model_hub/observations.yaml@@ -18,3 +18,12 @@ observations:- MH-OAUTH-A-001- MH-OAUTH-B-001- MH-OAUTH-C-001+ - MH-OAUTH-NATIVE-001+ - MH-OAUTH-NATIVE-002+ - id: MH-OBS-004+ source: model-hub-completeness-audit+ summary: A successful OAuth status response must atomically materialize the bound Source; no second create request exists in the live UI path.+ affects:+ - MH-OAUTH-NATIVE-001+ - MH-OAUTH-NATIVE-002+ - MH-OAUTH-CONSENT-001diff --git a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.pynew file mode 100644index 000000000..fa603e750--- /dev/null+++ b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py@@ -0,0 +1,258 @@+from __future__ import annotations++from tests.scenario_harness.model_hub_native_oauth import (+ HubOAuthScenarioHarness,+ NativeOAuthScenarioHarness,+)+from tests.ui_server_test_helpers import csrf_headers+from vibe import ui_server+from vibe.ui_server import app++BASE_URL = "http://127.0.0.1:15131"+++def _client(monkeypatch, service):+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ return client, csrf_headers(client, BASE_URL)+++def test_mh_oauth_native_001_claude_paste_code_happy_path(monkeypatch, tmp_path):+ """Scenario: MH-OAUTH-NATIVE-001."""++ harness = NativeOAuthScenarioHarness(tmp_path)+ harness.auth_status["claude"] = {"active_auth_mode": "oauth"}+ client, headers = _client(monkeypatch, harness.service)++ started = client.post(+ "/api/models/oauth/start",+ json={"vendor": "anthropic", "channel": "native_cli"},+ headers=headers,+ base_url=BASE_URL,+ ).get_json()["flow"]+ assert started["state"] == "awaiting_action"+ assert started["presentation"] == {+ "auth_url": "https://claude.ai/oauth/authorize?test=true",+ "device_code": None,+ "expects": "paste_code",+ "instructions_key": "settings.models.oauth.pasteCode.hint",+ }++ invalid = client.post(+ "/api/models/oauth/submit",+ json={"flow_id": started["flow_id"], "value": "not-a-callback"},+ headers=headers,+ base_url=BASE_URL,+ )+ assert invalid.status_code == 200+ assert invalid.get_json()["flow"]["state"] == "awaiting_action"+ assert harness.agent_auth.submissions == []++ submitted = client.post(+ "/api/models/oauth/submit",+ json={"flow_id": started["flow_id"], "value": "code-value#state-value"},+ headers=headers,+ base_url=BASE_URL,+ ).get_json()["flow"]+ assert submitted["state"] == "verifying"+ assert harness.agent_auth.submissions == [(started["flow_id"], "code-value#state-value")]++ harness.agent_auth.complete(started["flow_id"])+ completed = client.get(+ f"/api/models/oauth/status/{started['flow_id']}",+ base_url=BASE_URL,+ ).get_json()["flow"]+ sources = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"]++ assert completed["state"] == "success"+ assert len(sources) == 1+ assert sources[0]["id"] == started["source_id"]+ assert sources[0]["state"] == {"status": "active", "retry_at": None, "detail_key": None}+ assert sources[0]["account_label"] is None+ assert sources[0]["credential_ref"] is None+ assert harness.store.config.sources[0].id == started["source_id"]+ harness.adapter._flows.clear()+ harness.agent_auth.flows.clear()+ repeated = client.get(+ f"/api/models/oauth/status/{started['flow_id']}",+ base_url=BASE_URL,+ )+ assert repeated.status_code == 200+ assert repeated.get_json()["flow"]["state"] == "success"+ assert len(client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"]) == 1+ claude = next(+ agent+ for agent in client.get("/api/models/agents", base_url=BASE_URL).get_json()["agents"]+ if agent["backend"] == "claude"+ )+ assert claude["current"]["source_id"] == started["source_id"]+++def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_path):+ """Scenario: MH-OAUTH-NATIVE-002."""++ harness = NativeOAuthScenarioHarness(tmp_path)+ harness.auth_status["codex"] = {+ "active_auth_mode": "oauth",+ "chatgpt_account": {+ "email": "[email protected]",+ "plan_type": "plus",+ "organizations": [{"title": "Example Org", "is_default": True}],+ },+ }+ client, headers = _client(monkeypatch, harness.service)++ started = client.post(+ "/api/models/oauth/start",+ json={"vendor": "openai", "channel": "native_cli"},+ headers=headers,+ base_url=BASE_URL,+ ).get_json()["flow"]+ assert started["state"] == "starting"+ assert started["presentation"]["expects"] == "none"++ harness.agent_auth.expose_codex_device_flow(started["flow_id"])+ awaiting = client.get(+ f"/api/models/oauth/status/{started['flow_id']}",+ base_url=BASE_URL,+ ).get_json()["flow"]+ assert awaiting["state"] == "awaiting_action"+ assert awaiting["presentation"]["auth_url"] == "https://auth.openai.com/codex/device"+ assert awaiting["presentation"]["device_code"] == "T74L-XU61D"+ assert awaiting["presentation"]["expects"] == "none"++ harness.agent_auth.complete(started["flow_id"])+ completed = client.get(+ f"/api/models/oauth/status/{started['flow_id']}",+ base_url=BASE_URL,+ ).get_json()["flow"]+ source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]++ assert completed["state"] == "success"+ assert harness.agent_auth.submissions == []+ assert source["state"]["status"] == "active"+ assert source["account_label"] == "[email protected] \u00b7 plus \u00b7 Example Org"+ assert source["credential_ref"] is None+++def test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly(monkeypatch, tmp_path):+ """Scenario: MH-OAUTH-NATIVE-003."""++ harness = NativeOAuthScenarioHarness(tmp_path)+ client, headers = _client(monkeypatch, harness.service)++ timed = client.post(+ "/api/models/oauth/start",+ json={"vendor": "anthropic", "channel": "native_cli"},+ headers=headers,+ base_url=BASE_URL,+ ).get_json()["flow"]+ harness.agent_auth.timeout(timed["flow_id"])+ timed_out = client.get(+ f"/api/models/oauth/status/{timed['flow_id']}",+ base_url=BASE_URL,+ ).get_json()["flow"]+ assert timed_out["state"] == "failed"+ assert timed_out["error_key"] == "settings.models.oauth.error.timeout"+ assert client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"] == []++ signed_out = client.post(+ "/api/models/oauth/start",+ json={"vendor": "anthropic", "channel": "native_cli"},+ headers=headers,+ base_url=BASE_URL,+ ).get_json()["flow"]+ harness.auth_status["claude"] = {"active_auth_mode": "none"}+ harness.agent_auth.complete(signed_out["flow_id"])+ signed_out_response = client.get(+ f"/api/models/oauth/status/{signed_out['flow_id']}",+ base_url=BASE_URL,+ )+ assert signed_out_response.get_json()["flow"]["state"] == "failed"+ assert (+ signed_out_response.get_json()["flow"]["error_key"]+ == "settings.models.source.oauthSignedOut"+ )+ source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]+ assert source["state"] == {+ "status": "error",+ "retry_at": None,+ "detail_key": "settings.models.source.oauthSignedOut",+ }+ claude = next(+ agent+ for agent in client.get("/api/models/agents", base_url=BASE_URL).get_json()["agents"]+ if agent["backend"] == "claude"+ )+ assert claude["current"] is None++ cancelled = client.post(+ "/api/models/oauth/start",+ json={"vendor": "openai", "channel": "native_cli"},+ headers=headers,+ base_url=BASE_URL,+ ).get_json()["flow"]+ response = client.post(+ "/api/models/oauth/cancel",+ json={"flow_id": cancelled["flow_id"]},+ headers=headers,+ base_url=BASE_URL,+ )+ assert response.status_code == 200+ assert harness.agent_auth.cancelled == [cancelled["flow_id"]]+ assert client.get(+ f"/api/models/oauth/status/{cancelled['flow_id']}",+ base_url=BASE_URL,+ ).status_code == 404+++def test_mh_oauth_consent_001_is_required_and_persisted(monkeypatch, tmp_path):+ """Scenario: MH-OAUTH-CONSENT-001."""++ harness = HubOAuthScenarioHarness(tmp_path)+ client, headers = _client(monkeypatch, harness.service)++ rejected = client.post(+ "/api/models/oauth/start",+ json={"vendor": "anthropic", "channel": "hub"},+ headers=headers,+ base_url=BASE_URL,+ )+ assert rejected.status_code == 409+ assert rejected.get_json()["error"] == "consent_required"+ assert harness.adapter.flows == {}++ started = client.post(+ "/api/models/oauth/start",+ json={+ "vendor": "anthropic",+ "channel": "hub",+ "experimental_consent": True,+ },+ headers=headers,+ base_url=BASE_URL,+ ).get_json()["flow"]+ binding = harness.service.oauth_flows.binding(started["flow_id"])+ assert binding is not None+ assert binding.experimental_consent is True++ harness.adapter.complete(started["flow_id"])+ completed = client.get(+ f"/api/models/oauth/status/{started['flow_id']}",+ base_url=BASE_URL,+ ).get_json()["flow"]+ source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]++ assert completed["state"] == "success"+ assert source["id"] == started["source_id"]+ assert source["supply_channel"] == "hub"+ assert source["experimental_consent_at"] == "2026-07-25T00:00:00+00:00"++ harness.adapter.flows.clear()+ repeated = client.get(+ f"/api/models/oauth/status/{started['flow_id']}",+ base_url=BASE_URL,+ )+ assert repeated.status_code == 200+ assert repeated.get_json()["flow"]["state"] == "success"+ assert len(client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"]) == 1diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 819e4640b..e6fae378c 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -22,7 +22,7 @@ from core.handlers.model_hub.adapter import ()from core.handlers.model_hub.errors import ModelDiscoveryErrorfrom core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent-from core.handlers.model_hub.oauth import OAuthFlowRegistry+from core.handlers.model_hub.oauth import NativeOAuthSourceStatus, OAuthFlowRegistryfrom core.handlers.model_hub.revocations import CredentialRevocationJournalfrom core.handlers.model_hub.service import ModelHubError, ModelHubService, create_default_servicefrom vibe.model_hub_client import ModelHubRemoteService, _decode@@ -82,6 +82,8 @@ class FakeAdapter:self.flows = {}self.fail_sync = Falseself.fail_cancel = False+ self.native_signed_in = True+ self.native_account_label = Noneasync def ensure_installed(self):return await self.status()@@ -168,6 +170,14 @@ class FakeAdapter:if self.fail_cancel:raise RuntimeError("temporary engine failure")+ def completed_source_status(self, flow_id):+ if flow_id not in self.flows:+ raise KeyError(flow_id)+ return NativeOAuthSourceStatus(+ signed_in=self.native_signed_in,+ account_label=self.native_account_label,+ )+def _service(tmp_path):store = MemoryStore()@@ -198,12 +208,26 @@ def test_default_service_uses_real_engine_adapter(monkeypatch, tmp_path):monkeypatch.setattr(runtime_adapter, "_adapter", None)monkeypatch.setattr(runtime_supervisor, "_supervisor", None)- service = create_default_service()+ service = create_default_service(native_oauth_adapter=FakeAdapter())assert isinstance(service.adapter, CLIProxyEngineAdapter)assert service.adapter.supervisor.state_store.root.is_relative_to(tmp_path)+def test_default_service_uses_real_native_oauth_adapter(monkeypatch, tmp_path):+ from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter+ from vibe import api++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))+ agent_auth_service = object()+ monkeypatch.setattr(api, "_get_oauth_service", lambda: agent_auth_service)++ service = create_default_service(adapter=FakeAdapter())++ assert isinstance(service.native_oauth_adapter, AgentAuthNativeOAuthAdapter)+ assert service.native_oauth_adapter._agent_auth_service is agent_auth_service++def test_runtime_status_starts_engine_before_reporting_health(tmp_path):class LifecycleAdapter(FakeAdapter):def __init__(self):@@ -594,7 +618,9 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):consented_source = response.get_json()["source"]_assert_valid("source.schema.json", consented_source)assert consented_source["experimental_consent_at"] == "2026-07-23T03:00:00+00:00"- assert service.oauth_flows.channel(hub_flow["flow_id"]) is None+ completed_binding = service.oauth_flows.binding(hub_flow["flow_id"])+ assert completed_binding is not None+ assert completed_binding.completed is Truescan = client.post("/api/models/migration/scan", headers=headers, base_url=base_url).get_json()_assert_valid("migration-scan.schema.json", {"items": scan["items"]})diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 57e8ce18b..120caeb53 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -489,6 +489,69 @@ def test_mh_chan_001_codex_native_runtime_requires_chatgpt_oauth()assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False+ auth_path.write_text("{}")+ assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False+ assert (+ ModelHubRuntimeRouter._default_native_cli_ready(+ "codex",+ verified_oauth=True,+ )+ is True+ )+++def test_mh_chan_001_verified_codex_keyring_source_remains_routable(+ tmp_path: Path,+ monkeypatch,+) -> None:+ clock = {"now": datetime(2026, 7, 25, tzinfo=timezone.utc)}+ codex_home = tmp_path / "codex-keyring-home"+ codex_home.mkdir()+ (codex_home / "auth.json").write_text("{}")+ (codex_home / "config.toml").write_text('cli_auth_credentials_store = "keyring"\n')+ monkeypatch.setenv("CODEX_HOME", str(codex_home))+ for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE", "CODEX_API_KEY"):+ monkeypatch.delenv(key, raising=False)++ native = _source(+ "src_native_keyring",+ kind="subscription",+ vendor="openai",+ protocol="openai_responses",+ channel="native_cli",+ model_ids=("gpt-5",),+ state="active",+ )+ service = _service(+ tmp_path,+ ModelHubConfig(+ sources=[native],+ priority_order=[native.id],+ agents=_agents(),+ ),+ LaunchAdapter({}),+ now=lambda: clock["now"],+ )+ router = ModelHubRuntimeRouter(+ service=service,+ overlay_path=tmp_path / "overlay.json",+ )++ launch = asyncio.run(router.resolve("codex", "gpt-5"))++ assert (launch.channel, launch.source_id) == ("native_cli", native.id)++ context = SimpleNamespace()+ bind_launch(context, launch)+ assert asyncio.run(router.record_native_failure(context, "usage limit reached")) is True+ assert native.state.status == "cooldown"++ clock["now"] += timedelta(seconds=301)+ recovered = asyncio.run(router.resolve("codex", "gpt-5"))++ assert (recovered.channel, recovered.source_id) == ("native_cli", native.id)+ assert native.state.status == "active"+def test_mh_chan_001_persisted_launch_identity_is_non_secret_and_restorable() -> None:launch = ModelHubLaunch(diff --git a/tests/test_model_hub_oauth.py b/tests/test_model_hub_oauth.pynew file mode 100644index 000000000..bfa046957--- /dev/null+++ b/tests/test_model_hub_oauth.py@@ -0,0 +1,80 @@+from __future__ import annotations++import json++from core.handlers.model_hub.native_oauth import _signed_in+from core.handlers.model_hub.oauth import OAuthFlowRegistry+++def test_flow_registry_persists_experimental_consent(tmp_path):+ path = tmp_path / "oauth_flows.json"+ registry = OAuthFlowRegistry(path)++ registry.remember(+ "oaf_consent01",+ "hub",+ "src_consent01",+ "anthropic",+ experimental_consent=True,+ )++ binding = OAuthFlowRegistry(path).binding("oaf_consent01")+ assert binding is not None+ assert binding.experimental_consent is True+ assert binding.completed is False+ assert json.loads(path.read_text(encoding="utf-8"))["oaf_consent01"]["experimental_consent"] is True++ OAuthFlowRegistry(path).complete("oaf_consent01")+ completed = OAuthFlowRegistry(path).binding("oaf_consent01")+ assert completed is not None+ assert completed.completed is True+++def test_flow_registry_defaults_legacy_bindings_to_no_consent(tmp_path):+ path = tmp_path / "oauth_flows.json"+ path.write_text(+ json.dumps(+ {+ "oaf_legacy01": {+ "channel": "hub",+ "source_id": "src_legacy01",+ "vendor": "anthropic",+ }+ }+ ),+ encoding="utf-8",+ )++ binding = OAuthFlowRegistry(path).binding("oaf_legacy01")+ assert binding is not None+ assert binding.experimental_consent is False+ assert binding.completed is False+++def test_native_status_trusts_codex_keyring_success_but_not_active_api_keys():+ assert _signed_in(+ "codex",+ {+ "active_auth_mode": "none",+ "has_chatgpt_tokens": False,+ "auth_mode_uncertain": False,+ },+ )+ assert not _signed_in(+ "codex",+ {+ "active_auth_mode": "api_key",+ "has_chatgpt_tokens": True,+ },+ )+++def test_native_status_does_not_override_explicit_claude_api_key_mode():+ assert not _signed_in(+ "claude",+ {+ "active_auth_mode": "api_key",+ "has_oauth_credentials": True,+ },+ )+ assert _signed_in("claude", {"has_oauth_credentials": True})diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9900bf426..bd69185a8 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -624,6 +624,7 @@"customEndpoint": "Custom endpoint","retryIn": "retry in {{minutes}} min","reorder": "Reorder",+ "oauthSignedOut": "CLI subscription is signed out","cooldown": {"timeout": "Repeated timeouts"}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 5dddc72ba..9de4d19bf 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -624,6 +624,7 @@"customEndpoint": "自定义地址","retryIn": "{{minutes}} 分后重试","reorder": "拖动排序",+ "oauthSignedOut": "CLI 订阅未登录","cooldown": {"timeout": "连续超时"}