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): finalize OAuth custody and native import (#1385)
Call Whitef65a323923f8
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex fde63bba6..66ecf6b31 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -16,8 +16,6 @@ from config.v2_config import (ModelHubConfig,ModelHubModelConfig,ModelHubSourceConfig,- ModelHubSourceStateConfig,- ModelHubSourceUsageConfig,)from core.handlers.model_hub.adapter import (ObservationDiscovery,@@ -590,44 +588,56 @@ def scan_native_configs(]-def _new_source(+def _validated_source(item: NativeMigrationItem,*,now: datetime,protocol: Literal["anthropic", "openai_responses", "openai_chat"],validate_base_url: Callable[[object], Optional[str]],+ credential_ref: str | None = None,+ masked_credential: str | None = None,) -> ModelHubSourceConfig:keep_native = item.proposed_action == "keep_native"controlled = item.proposed_action == "controlled_import"discovered_at = now.isoformat()models = ([- ModelHubModelConfig(- id=model_id,- provenance="discovered",- discovered_at=discovered_at,- )+ {+ "id": model_id,+ "display_name": None,+ "origin": "discovered",+ "reasoning_efforts": [],+ "discovered_at": discovered_at,+ }for model_id in _native_model_ids(item.backend)]if keep_nativeelse [])- return ModelHubSourceConfig(- 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",- 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",- state=ModelHubSourceStateConfig(status="standby"),- usage=ModelHubSourceUsageConfig(),- models=models,- account_label=item.account_label,- )+ payload: dict[str, object] = {+ "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",+ "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",+ "state": {"status": "standby", "retry_at": None, "detail_key": None},+ "usage": {+ "cycle_used_pct": None,+ "month_spend_cents": None,+ "currency": None,+ "projected_exhaust_at": None,+ },+ "models": models,+ "credential_ref": credential_ref,+ "account_label": item.account_label,+ "masked_credential": masked_credential,+ }+ return ModelHubSourceConfig.from_payload(payload)def _migration_rollback_id(source_id: str, credential_ref: str) -> str:@@ -699,50 +709,81 @@ async def apply_native_migration(],observation.protocol,)- source = _new_source(- item,- now=host.now(),- protocol=protocol,- validate_base_url=validate_base_url,- )if item.proposed_action == "import":assert item.secret is not Noneassert observation is not Nonecredential_ref = await host._engine_call(host.adapter.provision_credential(item.vendor,- source.protocol,+ protocol,item.secret,- source.base_url,+ validate_base_url(item.base_url),))- provisioned.append((source.id, credential_ref))- source.credential_ref = credential_ref- source.masked_credential = mask_credential(item.secret)- manual_models = [- ModelHubModelConfig(- id=model.id,- display_name=model.display_name,- provenance="manual",+ provisioned.append((item.source_id, credential_ref))+ try:+ 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),)- for model in item.manual_models- ]- if observation.discovery is ObservationDiscovery.SUCCEEDED:- host._apply_discovered_models(- source,- manual_models,- list(observation.model_ids),- allow_empty=True,+ 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+ ]+ if observation.discovery is ObservationDiscovery.SUCCEEDED:+ host._apply_discovered_models(+ source,+ manual_models,+ list(observation.model_ids),+ allow_empty=True,+ )+ 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+ )+ source = ModelHubSourceConfig.from_payload(+ source.to_payload())- else:- source.models = manual_models- source.state = ModelHubSourceStateConfig(- status="error",- detail_key="models.source.error.unclassified",+ except (TypeError, ValueError):+ raise MigrationConflictError from None+ else:+ try:+ source = _validated_source(+ item,+ now=host.now(),+ protocol=protocol,+ validate_base_url=validate_base_url,)+ except (TypeError, ValueError):+ raise MigrationConflictError from Noneupdated.sources.append(source)host._apply_source_placement(updated, source)+ try:+ updated = ModelHubConfig.from_payload(updated.to_payload())+ except (TypeError, ValueError):+ raise MigrationConflictError from Noneawait host._commit_synced(previous, updated)persisted = Trueadded_to = [diff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.pyindex 5e20cea71..4edd71e74 100644--- a/core/handlers/model_hub/oauth.py+++ b/core/handlers/model_hub/oauth.py@@ -2,17 +2,22 @@from __future__ import annotations+import asyncioimport jsonimport os+import reimport tempfileimport threadingfrom dataclasses import dataclass+from datetime import datetime, timezonefrom pathlib import Path-from typing import Callable, Literal, Optional, Protocol+from typing import Callable, Literal, Optional, Protocol, get_argsfrom .adapter import OAuthFlowStateOAuthChannel = Literal["native_cli", "hub"]+OAuthNonceStatus = Literal["released", "in_flight", "committed"]+_CLIENT_NONCE_PATTERN = re.compile(r"^ofn_[a-z0-9]{16,64}$")NATIVE_OAUTH_SIGNED_OUT_DETAIL_KEY = "settings.models.source.oauthSignedOut"@@ -21,11 +26,35 @@ class OAuthFlowBinding:channel: OAuthChannelsource_id: Optional[str]vendor: Optional[str]- experimental_consent: bool = Falseintent: Literal["create", "reauth"] = "create"completed: bool = Falserecovered: bool | None = Noneinterrupted_pairs: tuple[dict[str, object], ...] = ()+ client_nonce: str | None = None+ expires_at_iso: str | None = None+ terminal_state: Literal["cancelled"] | None = None+++@dataclass(frozen=True)+class OAuthNonceClaim:+ """The result of claiming one exact OAuth-start nonce tuple."""++ client_nonce: str+ vendor: str+ channel: OAuthChannel+ status: OAuthNonceStatus+ flow_id: str | None = None+ owner: bool = False+++@dataclass+class _PendingNonceClaim:+ client_nonce: str+ vendor: str+ channel: OAuthChannel+ event: threading.Event+ status: OAuthNonceStatus = "in_flight"+ flow_id: str | None = Noneclass OAuthAdapter(Protocol):@@ -95,12 +124,74 @@ class UnavailableNativeOAuthAdapter:class OAuthFlowRegistry:- """Persist non-secret source identity, consent, and completion state."""+ """Persist non-secret OAuth identity and own nonce claim transitions."""- def __init__(self, path: Path, *, max_entries: int = 100):+ def __init__(+ self,+ path: Path,+ *,+ max_entries: int = 100,+ now: Callable[[], datetime] | None = None,+ ):self.path = pathself.max_entries = max_entries+ self._now = now or (lambda: datetime.now(timezone.utc))self._lock = threading.RLock()+ self._pending_nonces: dict[tuple[str, str, OAuthChannel], _PendingNonceClaim] = {}++ @staticmethod+ def _nonce_key(+ client_nonce: str,+ vendor: str,+ channel: OAuthChannel,+ ) -> tuple[str, str, OAuthChannel]:+ if not isinstance(client_nonce, str) or not _CLIENT_NONCE_PATTERN.fullmatch(client_nonce):+ raise ValueError("invalid OAuth client nonce")+ if not isinstance(vendor, str) or not vendor:+ raise ValueError("invalid OAuth vendor")+ if channel not in get_args(OAuthChannel):+ raise ValueError("invalid OAuth channel")+ return client_nonce, vendor, channel++ def _expired(self, expires_at_iso: str | None) -> bool:+ if expires_at_iso is None:+ return False+ expires_at = datetime.fromisoformat(expires_at_iso)+ if expires_at.tzinfo is None:+ expires_at = expires_at.replace(tzinfo=timezone.utc)+ return expires_at <= self._now()++ def _latest_nonce_binding_locked(+ self,+ flows: dict[str, OAuthFlowBinding],+ key: tuple[str, str, OAuthChannel],+ ) -> tuple[str, OAuthFlowBinding] | None:+ for flow_id, binding in reversed(tuple(flows.items())):+ if (+ binding.client_nonce,+ binding.vendor,+ binding.channel,+ ) != key:+ continue+ if binding.expires_at_iso is not None and self._expired(binding.expires_at_iso):+ continue+ return flow_id, binding+ return None++ def _finish_pending_locked(+ self,+ key: tuple[str, str, OAuthChannel],+ *,+ status: OAuthNonceStatus,+ flow_id: str | None,+ ) -> None:+ pending = self._pending_nonces.get(key)+ if pending is None:+ return+ pending.status = status+ pending.flow_id = flow_id+ pending.event.set()+ self._pending_nonces.pop(key, None)def _read(self) -> dict[str, OAuthFlowBinding]:if not self.path.exists():@@ -115,39 +206,62 @@ class OAuthFlowRegistry:for flow_id, value in payload.items():if not isinstance(flow_id, str):continue- if isinstance(value, str) and value in {"native_cli", "hub"}:- flows[flow_id] = OAuthFlowBinding(value, None, None)- continueif not isinstance(value, dict):continue+ if set(value) != {+ "channel",+ "source_id",+ "vendor",+ "intent",+ "completed",+ "recovered",+ "interrupted_pairs",+ "client_nonce",+ "expires_at_iso",+ "terminal_state",+ }:+ continuechannel = value.get("channel")source_id = value.get("source_id")vendor = value.get("vendor")- experimental_consent = value.get("experimental_consent", False)- intent = value.get("intent", "create")- completed = value.get("completed", False)+ intent = value.get("intent")+ completed = value.get("completed")recovered = value.get("recovered")- interrupted_pairs = value.get("interrupted_pairs", [])+ interrupted_pairs = value.get("interrupted_pairs")+ client_nonce = value.get("client_nonce")+ expires_at_iso = value.get("expires_at_iso")+ terminal_state = value.get("terminal_state")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 intent in {"create", "reauth"}and isinstance(completed, bool)and (recovered is None or isinstance(recovered, bool))and isinstance(interrupted_pairs, list)and all(isinstance(item, dict) for item in interrupted_pairs)+ and (+ client_nonce is None+ or (+ isinstance(client_nonce, str)+ and _CLIENT_NONCE_PATTERN.fullmatch(client_nonce)+ )+ )+ and (expires_at_iso is None or isinstance(expires_at_iso, str))+ and terminal_state in {None, "cancelled"}+ and not (client_nonce and expires_at_iso is None)):flows[flow_id] = OAuthFlowBinding(channel=channel,source_id=source_id,vendor=vendor,- experimental_consent=experimental_consent,intent=intent,completed=completed,recovered=recovered,interrupted_pairs=tuple(interrupted_pairs),+ client_nonce=client_nonce,+ expires_at_iso=expires_at_iso,+ terminal_state=terminal_state,)return flows@@ -160,11 +274,13 @@ class OAuthFlowRegistry:"channel": binding.channel,"source_id": binding.source_id,"vendor": binding.vendor,- "experimental_consent": binding.experimental_consent,"intent": binding.intent,"completed": binding.completed,"recovered": binding.recovered,"interrupted_pairs": list(binding.interrupted_pairs),+ "client_nonce": binding.client_nonce,+ "expires_at_iso": binding.expires_at_iso,+ "terminal_state": binding.terminal_state,}for flow_id, binding in bounded.items()},@@ -186,13 +302,28 @@ class OAuthFlowRegistry:source_id: str,vendor: str,*,- experimental_consent: bool = False,intent: Literal["create", "reauth"] = "create",recovered: bool | None = None,replace_flow_id: str | None = None,+ client_nonce: str | None = None,+ expires_at_iso: str | None = None,) -> None:with self._lock:flows = self._read()+ nonce_key = (+ self._nonce_key(client_nonce, vendor, channel)+ if client_nonce is not None+ else None+ )+ if client_nonce is not None and expires_at_iso is None:+ raise ValueError("nonce-bound OAuth flow requires an expiry")+ if nonce_key is not None:+ existing = self._latest_nonce_binding_locked(flows, nonce_key)+ if existing is not None and existing[0] not in {+ flow_id,+ replace_flow_id,+ }:+ raise ValueError("OAuth client nonce is already committed")if replace_flow_id is not None:flows.pop(replace_flow_id, None)flows.pop(flow_id, None)@@ -200,11 +331,18 @@ class OAuthFlowRegistry:channel=channel,source_id=source_id,vendor=vendor,- experimental_consent=experimental_consent,intent=intent,recovered=recovered,+ client_nonce=client_nonce,+ expires_at_iso=expires_at_iso,)self._write(flows)+ if nonce_key is not None:+ self._finish_pending_locked(+ nonce_key,+ status="committed",+ flow_id=flow_id,+ )def complete(self,@@ -222,14 +360,132 @@ class OAuthFlowRegistry:channel=binding.channel,source_id=binding.source_id,vendor=binding.vendor,- experimental_consent=binding.experimental_consent,intent=binding.intent,completed=True,recovered=recovered,interrupted_pairs=tuple(interrupted_pairs or ()),+ client_nonce=binding.client_nonce,+ expires_at_iso=binding.expires_at_iso,+ terminal_state=binding.terminal_state,)self._write(flows)+ def retain_cancelled(self, flow_id: str) -> None:+ """Keep a nonce-bound flow replayable after explicit cancellation."""++ with self._lock:+ flows = self._read()+ binding = flows.get(flow_id)+ if binding is None:+ raise KeyError(flow_id)+ if binding.client_nonce is None:+ flows.pop(flow_id, None)+ else:+ flows[flow_id] = OAuthFlowBinding(+ channel=binding.channel,+ source_id=binding.source_id,+ vendor=binding.vendor,+ intent=binding.intent,+ completed=binding.completed,+ recovered=binding.recovered,+ interrupted_pairs=binding.interrupted_pairs,+ client_nonce=binding.client_nonce,+ expires_at_iso=binding.expires_at_iso,+ terminal_state="cancelled",+ )+ self._write(flows)++ def claim_nonce(+ self,+ client_nonce: str,+ vendor: str,+ channel: OAuthChannel,+ ) -> OAuthNonceClaim:+ """Atomically claim an OAuth-start tuple before provider work."""++ key = self._nonce_key(client_nonce, vendor, channel)+ with self._lock:+ flows = self._read()+ committed = self._latest_nonce_binding_locked(flows, key)+ if committed is not None:+ return OAuthNonceClaim(+ client_nonce,+ vendor,+ channel,+ "committed",+ flow_id=committed[0],+ )+ pending = self._pending_nonces.get(key)+ if pending is not None:+ return OAuthNonceClaim(+ client_nonce,+ vendor,+ channel,+ pending.status,+ flow_id=pending.flow_id,+ )+ self._pending_nonces[key] = _PendingNonceClaim(+ client_nonce,+ vendor,+ channel,+ threading.Event(),+ )+ return OAuthNonceClaim(+ client_nonce,+ vendor,+ channel,+ "in_flight",+ owner=True,+ )++ async def wait_for_nonce(self, claim: OAuthNonceClaim) -> OAuthNonceClaim:+ """Await the owner settling an in-flight nonce claim."""++ key = self._nonce_key(claim.client_nonce, claim.vendor, claim.channel)+ with self._lock:+ pending = self._pending_nonces.get(key)+ if pending is None:+ flows = self._read()+ committed = self._latest_nonce_binding_locked(flows, key)+ return OAuthNonceClaim(+ claim.client_nonce,+ claim.vendor,+ claim.channel,+ "committed" if committed is not None else "released",+ flow_id=committed[0] if committed else None,+ )+ event = pending.event+ await asyncio.to_thread(event.wait)+ with self._lock:+ flows = self._read()+ committed = self._latest_nonce_binding_locked(flows, key)+ if committed is not None:+ return OAuthNonceClaim(+ claim.client_nonce,+ claim.vendor,+ claim.channel,+ "committed",+ flow_id=committed[0],+ )+ return OAuthNonceClaim(+ claim.client_nonce,+ claim.vendor,+ claim.channel,+ "released",+ )++ def release_nonce(+ self,+ client_nonce: str,+ vendor: str,+ channel: OAuthChannel,+ ) -> None:+ """Release a failed or cancelled pre-flow claim after cleanup."""++ key = self._nonce_key(client_nonce, vendor, channel)+ with self._lock:+ self._finish_pending_locked(key, status="released", flow_id=None)+def channel(self, flow_id: str) -> OAuthChannel | None:binding = self.binding(flow_id)return binding.channel if binding is not None else Nonediff --git a/core/handlers/model_hub/revocations.py b/core/handlers/model_hub/revocations.pyindex 821067fab..023ee2fa4 100644--- a/core/handlers/model_hub/revocations.py+++ b/core/handlers/model_hub/revocations.py@@ -8,17 +8,18 @@ import tempfileimport threadingfrom dataclasses import dataclassfrom pathlib import Path-from typing import Literal+from typing import Literal, cast, get_argsRevocationOperation = Literal["revoke_credential","cleanup_orphaned_oauth_material",]-_REVOCATION_OPERATIONS = {- "revoke_credential",- "cleanup_orphaned_oauth_material",-}+_REVOCATION_OPERATIONS = frozenset(get_args(RevocationOperation))+++def _invalid_journal() -> OSError:+ return OSError("invalid credential revocation journal")@dataclass(frozen=True)@@ -40,23 +41,43 @@ class CredentialRevocationJournal:return []try:payload = json.loads(self.path.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- return []+ except json.JSONDecodeError:+ raise _invalid_journal() from Noneif not isinstance(payload, list):- return []- return [- PendingCredentialRevocation(- source_id=item["source_id"],- credential_ref=item["credential_ref"],- operation=item.get("operation", "revoke_credential"),+ raise _invalid_journal()+ entries: list[PendingCredentialRevocation] = []+ identities: set[tuple[str, str]] = set()+ for item in payload:+ if not isinstance(item, dict) or set(item) != {+ "source_id",+ "credential_ref",+ "operation",+ }:+ raise _invalid_journal()+ source_id = item["source_id"]+ credential_ref = item["credential_ref"]+ operation = item["operation"]+ if (+ not isinstance(source_id, str)+ or not source_id+ or not isinstance(credential_ref, str)+ or not credential_ref+ or not isinstance(operation, str)+ or operation not in _REVOCATION_OPERATIONS+ ):+ raise _invalid_journal()+ identity = (source_id, credential_ref)+ if identity in identities:+ raise _invalid_journal()+ identities.add(identity)+ entries.append(+ PendingCredentialRevocation(+ source_id=source_id,+ credential_ref=credential_ref,+ operation=cast(RevocationOperation, operation),+ ))- for item in payload- if isinstance(item, dict)- and isinstance(item.get("source_id"), str)- and isinstance(item.get("credential_ref"), str)- and item.get("operation", "revoke_credential")- in _REVOCATION_OPERATIONS- ]+ return entriesdef _write(self, entries: list[PendingCredentialRevocation]) -> None:self.path.parent.mkdir(parents=True, exist_ok=True)@@ -85,17 +106,37 @@ class CredentialRevocationJournal:operation: RevocationOperation = "revoke_credential",) -> None:with self._lock:+ if (+ not isinstance(source_id, str)+ or not source_id+ or not isinstance(credential_ref, str)+ or not credential_ref+ or not isinstance(operation, str)+ or operation not in _REVOCATION_OPERATIONS+ ):+ raise ValueError("invalid credential revocation entry")entries = self._read()entry = PendingCredentialRevocation(source_id,credential_ref,operation,)+ existing = next(+ (+ pending+ for pending in entries+ if pending.source_id == source_id+ and pending.credential_ref == credential_ref+ ),+ None,+ )+ if existing is not None and existing.operation != operation:+ raise ValueError("credential revocation entry has conflicting operation")if entry not in entries:entries.append(entry)self._write(entries)- def remove(self, source_id: str, credential_ref: str | None = None) -> None:+ def remove(self, source_id: str, credential_ref: str) -> None:with self._lock:entries = self._read()remaining = [@@ -103,10 +144,7 @@ class CredentialRevocationJournal:for entry in entriesif not (entry.source_id == source_id- and (- credential_ref is None- or entry.credential_ref == credential_ref- )+ and entry.credential_ref == credential_ref)]if len(remaining) != len(entries):diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex f68a82f83..548a370d9 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -85,6 +85,21 @@ scenarios:layer: scenariobackend: claudetest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_native_reauth_reuses_a_pending_flow_and_cancel_commits_a_finished_one+ - id: AUTH-SETUP-108+ name: Duplicate native Source is rejected before another CLI login starts+ status: covered+ kind: negative_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_duplicate_native_source_is_rejected_before_login_starts+ - id: AUTH-SETUP-109+ name: Hub re-auth requires acknowledgement and converges its repaired Source projection+ status: partial+ missing_layer: service+ kind: negative_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_reauth_requires_acknowledgement_and_reaches_consistent_terminal- id: AUTH-SETUP-201name: Re-entering setup replaces the active flowstatus: covered@@ -225,6 +240,14 @@ scenarios:layer: scenariobackend: show_page_emailtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::ShowPageEmailAccessScenarioTests::test_exact_email_login_is_confined_to_its_signed_show_page+ - id: AUTH-SETUP-210+ name: Lost Model Hub OAuth start response converges on one provider flow+ status: partial+ missing_layer: service+ kind: retry+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_lost_model_hub_oauth_start_response_reuses_nonce_flow- id: AUTH-SETUP-901name: Codex setup success refreshes runtime before the next turnstatus: covereddiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex a76d0b5a4..0e41b69ae 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -11,6 +11,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, patchimport httpx+import pytestROOT = Path(__file__).resolve().parents[3]sys.path.insert(0, str(ROOT))@@ -41,6 +42,10 @@ from tests.scenario_harness.organization_management import ()from tests.scenario_harness.show_page_email_access import ShowPageEmailAccessScenarioHarnessfrom vibe import cloud_management+from tests.scenario_harness.model_hub_native_oauth import (+ HubOAuthScenarioHarness,+ NativeOAuthScenarioHarness,+)from vibe.api import (get_claude_auth,save_claude_auth,@@ -1137,6 +1142,10 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):harness.store.config.sources[0].state.status,"needs_action",)+ self.assertEqual(+ harness.store.config.sources[0].state.detail_key,+ "models.source.needs_action.oauth_expired",+ )self.assertEqual(harness.store.config.sources[0].models, [])harness.agent_auth.timeout(flow_id)@@ -1241,6 +1250,217 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):"ok",)+ async def test_duplicate_native_source_is_rejected_before_login_starts(self):+ """Scenario: AUTH-SETUP-108"""+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ harness = NativeOAuthScenarioHarness(Path(state_dir.name))+ source = ModelHubSourceConfig.from_payload(+ {+ "id": "src_native0001",+ "created_at": "2026-07-25T00:00:00+00:00",+ "last_discovered_at": "2026-07-25T00:00:00+00:00",+ "kind": "subscription",+ "vendor": "anthropic",+ "display_name": "Claude subscription",+ "protocol": "anthropic",+ "base_url": None,+ "supply_channel": "native_cli",+ "billing": "monthly",+ "state": {+ "status": "standby",+ "retry_at": None,+ "detail_key": None,+ },+ "usage": {+ "cycle_used_pct": None,+ "month_spend_cents": None,+ "currency": None,+ "projected_exhaust_at": None,+ },+ "models": [+ {+ "id": "claude-opus-4-6",+ "display_name": None,+ "origin": "discovered",+ "reasoning_efforts": [],+ "discovered_at": "2026-07-25T00:00:00+00:00",+ }+ ],+ "credential_ref": None,+ "account_label": None,+ "masked_credential": None,+ }+ )+ harness.store.config.sources.append(source)++ with self.assertRaises(ModelHubError) as refused:+ await harness.service.oauth_start(+ {"vendor": "anthropic", "channel": "native_cli"}+ )++ self.assertEqual(refused.exception.code, "native_source_already_exists")+ self.assertEqual(+ refused.exception.data,+ {"existing_source_id": source.id},+ )+ self.assertEqual(harness.agent_auth.start_calls, [])++ started = await harness.service.oauth_start(+ {"vendor": "openai", "channel": "native_cli"}+ )+ self.assertEqual(started["flow"]["channel"], "native_cli")+ self.assertEqual(harness.agent_auth.start_calls, [("codex", False)])++ @pytest.mark.xfail(+ strict=True,+ reason="AC-52: awaiting I7 service.py wiring for the Hub re-auth gate",+ )+ async def test_hub_reauth_requires_acknowledgement_and_reaches_consistent_terminal(self):+ """Scenario: AUTH-SETUP-109.++ Prewritten against merged #1326 head ea26ee6a0; recheck at implementation head.+ """+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ harness = HubOAuthScenarioHarness(Path(state_dir.name))+ source = ModelHubSourceConfig.from_payload(+ {+ "id": "src_hubreauth01",+ "created_at": "2026-07-25T00:00:00+00:00",+ "last_discovered_at": "2026-07-25T00:00:00+00:00",+ "kind": "subscription",+ "vendor": "anthropic",+ "display_name": "Claude Hub subscription",+ "protocol": "anthropic",+ "base_url": None,+ "supply_channel": "hub",+ "billing": "monthly",+ "state": {+ "status": "needs_action",+ "retry_at": None,+ "detail_key": "models.source.needs_action.oauth_expired",+ },+ "usage": {+ "cycle_used_pct": None,+ "month_spend_cents": None,+ "currency": None,+ "projected_exhaust_at": None,+ },+ "models": [+ {+ "id": "claude-opus-4-6",+ "display_name": None,+ "origin": "discovered",+ "reasoning_efforts": [],+ "discovered_at": "2026-07-25T00:00:00+00:00",+ }+ ],+ "credential_ref": "cred_hubold01",+ "account_label": None,+ "masked_credential": None,+ }+ )+ harness.store.config.sources.append(source)+ harness.store.config.agents["claude"].sources.order.append(source.id)+ harness.store.config.agents["claude"].routes["claude-opus-4-6"] = (+ ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),+ )+ )+ )++ for acknowledgement in ({}, {"acknowledge_irreversible": False}):+ with self.assertRaises(ModelHubError) as refused:+ await harness.service.reauth_source(source.id, acknowledgement)+ self.assertEqual(refused.exception.code, "reauth_confirmation_required")+ self.assertEqual(harness.adapter.flows, {})+ self.assertEqual(harness.store.config.sources[0].state.status, "needs_action")++ started = await harness.service.reauth_source(+ source.id,+ {"acknowledge_irreversible": True},+ )+ self.assertEqual(started["flow"]["channel"], "hub")+ self.assertEqual(started["flow"]["intent"], "reauth")+ self.assertEqual(len(harness.adapter.flows), 1)++ flow_id = started["flow"]["flow_id"]+ harness.adapter.complete(flow_id)+ terminal = await harness.service.oauth_status(flow_id)++ self.assertEqual(terminal["flow"]["state"], "success")+ self.assertEqual(terminal["flow"]["intent"], "reauth")+ self.assertEqual(terminal["source"], harness.service.list_sources()[0])+ self.assertEqual(terminal["source"]["id"], source.id)+ self.assertEqual(terminal["source"]["credential_ref"], "cred_consent01")+ self.assertEqual(terminal["source"]["state"]["status"], "standby")+ self.assertIn(+ "claude-opus-4-6",+ [model["id"] for model in terminal["source"]["models"]],+ )+ agent = harness.service.get_agent_sources("claude")+ self.assertEqual(agent["sources"]["order"], [source.id])+ self.assertEqual(agent["supply_status"], "ok")++ @pytest.mark.xfail(+ strict=True,+ reason="AC-48: awaiting I7 service.py wiring for OAuth nonce coalescing",+ )+ async def test_lost_model_hub_oauth_start_response_reuses_nonce_flow(self):+ """Scenario: AUTH-SETUP-210.++ Prewritten against merged #1326 head ea26ee6a0; recheck at implementation head.+ """+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ harness = NativeOAuthScenarioHarness(Path(state_dir.name))+ start_request = {+ "vendor": "anthropic",+ "channel": "native_cli",+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",+ }++ provider_started = asyncio.Event()+ retry_started = asyncio.Event()+ release_provider = asyncio.Event()+ provider_calls = 0+ original_start = harness.agent_auth.start_web_setup++ async def blocked_provider_start(*args, **kwargs):+ nonlocal provider_calls+ provider_calls += 1+ provider_started.set()+ await release_provider.wait()+ return await original_start(*args, **kwargs)++ harness.agent_auth.start_web_setup = blocked_provider_start+ first_task = asyncio.create_task(harness.service.oauth_start(start_request))+ await asyncio.wait_for(provider_started.wait(), timeout=1)++ async def retry_after_lost_response():+ retry_started.set()+ return await harness.service.oauth_start(dict(start_request))++ retry_task = asyncio.create_task(retry_after_lost_response())+ await asyncio.wait_for(retry_started.wait(), timeout=1)+ await asyncio.sleep(0)+ self.assertFalse(retry_task.done())++ release_provider.set()+ lost_response, recovered_response = await asyncio.gather(+ first_task,+ retry_task,+ )++ lost_flow = lost_response["flow"]+ recovered_flow = recovered_response["flow"]+ self.assertEqual(lost_flow["client_nonce"], start_request["client_nonce"])+ self.assertEqual(recovered_flow["client_nonce"], start_request["client_nonce"])+ self.assertEqual(recovered_flow, lost_flow)+ self.assertEqual(provider_calls, 1)+async def test_codex_failure_scenario_emits_reset_path(self):"""Scenario: AUTH-SETUP-202"""harness = AuthSetupScenarioHarness()diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.pyindex d7f9b958c..b4e1faf65 100644--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py@@ -178,6 +178,42 @@ def _write(path: Path, content: str) -> None:path.write_text(content, encoding="utf-8")+def _assert_canonical_round_trip(config: ModelHubConfig) -> ModelHubConfig:+ serialized = json.dumps(config.to_payload())+ reloaded = ModelHubConfig.from_payload(json.loads(serialized))+ assert reloaded.to_payload() == config.to_payload()+ return reloaded+++def _assert_sources_validated_before_commit(+ monkeypatch: pytest.MonkeyPatch,+ service: ModelHubService,+) -> None:+ original_validator = ModelHubSourceConfig.from_payload.__func__+ validated_source_ids: set[str] = set()++ def tracked_validator(cls, payload):+ source = original_validator(cls, payload)+ validated_source_ids.add(source.id)+ return source++ original_commit = service._commit_synced++ async def checked_commit(previous, updated):+ new_source_ids = {+ source.id for source in updated.sources+ } - {source.id for source in previous.sources}+ assert new_source_ids <= validated_source_ids+ await original_commit(previous, updated)++ monkeypatch.setattr(+ ModelHubSourceConfig,+ "from_payload",+ classmethod(tracked_validator),+ )+ monkeypatch.setattr(service, "_commit_synced", checked_commit)++def _write_claude(home: Path, *, malformed: bool = False) -> None:if malformed:_write(home / ".claude" / "settings.json", "{not-json")@@ -518,6 +554,7 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(before = _tree_digest(native_home)service, store, adapter = _service(tmp_path)+ _assert_sources_validated_before_commit(monkeypatch, service)monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)client = app.test_client()base_url = "http://127.0.0.1:15131"@@ -549,6 +586,12 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(assert adapter.transient_revoked == adapter.transient_refsassert 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+ )by_id = {source.id: source for source in store.config.sources}imported_ids = set(by_id)for backend in ("claude", "codex", "opencode"):@@ -609,6 +652,7 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(_write_codex_oauth(native_home)_isolate_native_home(monkeypatch, native_home)service, store, adapter = _service(tmp_path)+ _assert_sources_validated_before_commit(monkeypatch, service)scan = service.migration_scan()["items"]oauth_items = [item for item in scan if item["kind"] == "oauth_native"]@@ -627,6 +671,14 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(("openai", "subscription", "native_cli", None),}assert adapter.provisioned == []+ 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),+ }@pytest.mark.parametrize(@@ -1010,6 +1062,37 @@ def test_failed_batch_revokes_every_provisioned_credential(assert all(agent.sources.order == [] for agent in store.config.agents.values())+def test_canonical_source_rejection_aborts_batch_and_revokes_credentials(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ native_home = tmp_path / "native-home"+ _write_opencode(native_home)+ _isolate_native_home(monkeypatch, native_home)+ service, store, adapter = _service(tmp_path)+ item_ids = [item["id"] for item in service.migration_scan()["items"]]+ original_validator = ModelHubSourceConfig.from_payload.__func__++ def reject_one_source(cls, payload):+ if payload.get("vendor") == "zhipuai":+ raise ValueError("injected canonical rejection")+ return original_validator(cls, payload)++ monkeypatch.setattr(+ ModelHubSourceConfig,+ "from_payload",+ classmethod(reject_one_source),+ )++ with pytest.raises(ModelHubError) as error:+ asyncio.run(service.migration_apply(item_ids))++ assert error.value.code == "migration_item_conflict"+ 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())++def test_failed_persist_sync_restores_config_and_revokes_credentials(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/test_model_hub_oauth.py b/tests/test_model_hub_oauth.pyindex 5dc84e037..0f1d6ab09 100644--- a/tests/test_model_hub_oauth.py+++ b/tests/test_model_hub_oauth.py@@ -1,36 +1,53 @@from __future__ import annotations+import asyncioimport json+from datetime import datetime, timezone++import pytestfrom core.handlers.model_hub.native_oauth import _signed_infrom core.handlers.model_hub.oauth import OAuthFlowRegistry+from core.handlers.model_hub.revocations import (+ CredentialRevocationJournal,+ PendingCredentialRevocation,+)-def test_flow_registry_persists_experimental_consent(tmp_path):+def test_flow_registry_persists_final_binding_shape(tmp_path):path = tmp_path / "oauth_flows.json"registry = OAuthFlowRegistry(path)registry.remember(- "oaf_consent01",+ "oaf_registry01","hub",- "src_consent01",+ "src_oauth01","anthropic",- experimental_consent=True,)- binding = OAuthFlowRegistry(path).binding("oaf_consent01")+ binding = OAuthFlowRegistry(path).binding("oaf_registry01")assert binding is not None- assert binding.experimental_consent is Trueassert binding.completed is False- assert json.loads(path.read_text(encoding="utf-8"))["oaf_consent01"]["experimental_consent"] is True+ assert set(json.loads(path.read_text(encoding="utf-8"))["oaf_registry01"]) == {+ "channel",+ "source_id",+ "vendor",+ "intent",+ "completed",+ "recovered",+ "interrupted_pairs",+ "client_nonce",+ "expires_at_iso",+ "terminal_state",+ }- OAuthFlowRegistry(path).complete("oaf_consent01")- completed = OAuthFlowRegistry(path).binding("oaf_consent01")+ OAuthFlowRegistry(path).complete("oaf_registry01")+ completed = OAuthFlowRegistry(path).binding("oaf_registry01")assert completed is not Noneassert completed.completed is True-def test_flow_registry_defaults_legacy_bindings_to_no_consent(tmp_path):+def test_flow_registry_rejects_legacy_binding_shapes(tmp_path):path = tmp_path / "oauth_flows.json"path.write_text(json.dumps(@@ -45,10 +62,86 @@ def test_flow_registry_defaults_legacy_bindings_to_no_consent(tmp_path):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+ assert OAuthFlowRegistry(path).binding("oaf_legacy01") is None+++def test_flow_registry_claims_exact_nonce_tuple_and_replays_committed_flow(tmp_path):+ now = [datetime(2026, 7, 25, tzinfo=timezone.utc)]+ registry = OAuthFlowRegistry(tmp_path / "oauth_flows.json", now=lambda: now[0])+ nonce = "ofn_01j5w8z7p4n6q2rt"++ owner = registry.claim_nonce(nonce, "anthropic", "hub")+ follower = registry.claim_nonce(nonce, "anthropic", "hub")+ assert owner.owner is True+ assert owner.status == follower.status == "in_flight"+ assert follower.owner is False++ registry.remember(+ "oaf_nonce01",+ "hub",+ "src_nonce01",+ "anthropic",+ client_nonce=nonce,+ expires_at_iso="2026-07-25T00:15:00+00:00",+ )+ committed = registry.claim_nonce(nonce, "anthropic", "hub")+ assert committed.status == "committed"+ assert committed.flow_id == "oaf_nonce01"+++def test_flow_registry_releases_failed_claim_and_keeps_tuples_independent(tmp_path):+ registry = OAuthFlowRegistry(tmp_path / "oauth_flows.json")+ nonce = "ofn_01j5w8z7p4n6q2rt"+ registry.claim_nonce(nonce, "anthropic", "hub")+ registry.release_nonce(nonce, "anthropic", "hub")++ fresh = registry.claim_nonce(nonce, "anthropic", "hub")+ other_vendor = registry.claim_nonce(nonce, "openai", "hub")+ other_channel = registry.claim_nonce(nonce, "anthropic", "native_cli")+ assert fresh.owner is True+ assert other_vendor.owner is True+ assert other_channel.owner is True+++def test_flow_registry_retains_nonce_cancel_until_expiry_then_releases(tmp_path):+ current = [datetime(2026, 7, 25, tzinfo=timezone.utc)]+ registry = OAuthFlowRegistry(+ tmp_path / "oauth_flows.json",+ now=lambda: current[0],+ )+ nonce = "ofn_01j5w8z7p4n6q2rt"+ registry.remember(+ "oaf_cancel01",+ "hub",+ "src_cancel01",+ "anthropic",+ client_nonce=nonce,+ expires_at_iso="2026-07-25T00:15:00+00:00",+ )+ registry.retain_cancelled("oaf_cancel01")+ assert registry.binding("oaf_cancel01").terminal_state == "cancelled"+ assert registry.claim_nonce(nonce, "anthropic", "hub").status == "committed"++ current[0] = datetime(2026, 7, 25, 0, 15, tzinfo=timezone.utc)+ released = registry.claim_nonce(nonce, "anthropic", "hub")+ assert released.owner is True+++def test_flow_registry_coalesced_waiter_observes_release(tmp_path):+ registry = OAuthFlowRegistry(tmp_path / "oauth_flows.json")+ nonce = "ofn_01j5w8z7p4n6q2rt"+ owner = registry.claim_nonce(nonce, "anthropic", "hub")+ follower = registry.claim_nonce(nonce, "anthropic", "hub")++ async def wait_for_release():+ task = asyncio.create_task(registry.wait_for_nonce(follower))+ await asyncio.sleep(0)+ registry.release_nonce(nonce, "anthropic", "hub")+ return await task++ result = asyncio.run(wait_for_release())+ assert owner.owner is True+ assert result.status == "released"def test_flow_registry_returns_latest_pending_reauth_for_source(tmp_path):@@ -122,3 +215,92 @@ def test_native_status_does_not_override_explicit_claude_api_key_mode():},)assert _signed_in("claude", {"has_oauth_credentials": True})+++def test_revocation_journal_round_trips_final_entries_across_instances(tmp_path):+ path = tmp_path / "revocations.json"+ journal = CredentialRevocationJournal(path)++ journal.add("src_cleanup001", "cred_old001")+ journal.add(+ "src_cleanup002",+ "cred_oauth002",+ operation="cleanup_orphaned_oauth_material",+ )++ reconstructed = CredentialRevocationJournal(path)+ assert reconstructed.list() == [+ PendingCredentialRevocation(+ source_id="src_cleanup001",+ credential_ref="cred_old001",+ operation="revoke_credential",+ ),+ PendingCredentialRevocation(+ source_id="src_cleanup002",+ credential_ref="cred_oauth002",+ operation="cleanup_orphaned_oauth_material",+ ),+ ]++ reconstructed.remove("src_cleanup001", "cred_old001")+ assert CredentialRevocationJournal(path).list() == [+ PendingCredentialRevocation(+ source_id="src_cleanup002",+ credential_ref="cred_oauth002",+ operation="cleanup_orphaned_oauth_material",+ )+ ]+++ "payload",+ (+ {},+ [{"source_id": "src_cleanup001", "credential_ref": "cred_old001"}],+ [+ {+ "source_id": "src_cleanup001",+ "credential_ref": "cred_old001",+ "operation": "revoke_credential",+ "unexpected": True,+ }+ ],+ [+ {+ "source_id": "src_cleanup001",+ "credential_ref": "cred_old001",+ "operation": "revoke_credential",+ },+ {+ "source_id": "src_cleanup001",+ "credential_ref": "cred_old001",+ "operation": "revoke_credential",+ },+ ],+ ),+)+def test_revocation_journal_rejects_noncanonical_state_without_overwriting(+ tmp_path,+ payload,+):+ path = tmp_path / "revocations.json"+ original = json.dumps(payload)+ path.write_text(original, encoding="utf-8")+ journal = CredentialRevocationJournal(path)++ with pytest.raises(OSError, match="invalid credential revocation journal"):+ journal.add("src_new0001", "cred_new001")++ assert path.read_text(encoding="utf-8") == original+++def test_revocation_journal_rejects_conflicting_cleanup_operations(tmp_path):+ journal = CredentialRevocationJournal(tmp_path / "revocations.json")+ journal.add("src_cleanup001", "cred_old001")++ with pytest.raises(ValueError, match="conflicting operation"):+ journal.add(+ "src_cleanup001",+ "cred_old001",+ operation="cleanup_orphaned_oauth_material",+ )