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
fix(model-hub): persist API key create nonce (#1430)
Call Whiteb1d383003968
diff --git a/config/v2_config.py b/config/v2_config.pyindex 8efd3a6e0..2a0b14c29 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -1237,6 +1237,18 @@ def _validate_model_hub_base_url(value: object) -> Optional[str]:return normalize_model_hub_base_url(value)+_MODEL_HUB_SOURCE_CLIENT_NONCE_PATTERN = re.compile(r"^scn_[a-z0-9]{16,64}$")+++def validate_model_hub_source_client_nonce(value: object) -> str:+ if (+ not isinstance(value, str)+ or _MODEL_HUB_SOURCE_CLIENT_NONCE_PATTERN.fullmatch(value) is None+ ):+ raise ValueError("Config 'model_hub.sources.client_nonce' is invalid")+ return value++def _filter_dataclass_fields(dc_class, payload: dict) -> dict:"""Filter payload to only include fields defined in dataclass."""valid_fields = {f.name for f in fields(dc_class)}@@ -1948,6 +1960,7 @@ class ModelHubSourceConfig:state: ModelHubSourceStateConfigmodels: list[ModelHubModelConfig]created_at: str = MODEL_HUB_LEGACY_CREATED_AT+ client_nonce: Optional[str] = Nonelast_discovered_at: Optional[str] = Nonebase_url: Optional[str] = Noneusage: Optional[ModelHubSourceUsageConfig] = None@@ -1962,6 +1975,7 @@ class ModelHubSourceConfig:allowed_fields = {"id","created_at",+ "client_nonce","last_discovered_at","kind","vendor",@@ -2019,6 +2033,11 @@ class ModelHubSourceConfig:account_label = payload.get("account_label")masked_credential = payload.get("masked_credential")created_at = payload.get("created_at")+ client_nonce = (+ validate_model_hub_source_client_nonce(payload.get("client_nonce"))+ if "client_nonce" in payload+ else None+ )last_discovered_at = payload.get("last_discovered_at")base_url = _validate_model_hub_base_url(base_url)if credential_ref is not None and not isinstance(credential_ref, str):@@ -2056,6 +2075,7 @@ class ModelHubSourceConfig:)or MODEL_HUB_LEGACY_CREATED_AT),+ client_nonce=client_nonce,last_discovered_at=_validate_optional_datetime(last_discovered_at,"model_hub.sources.last_discovered_at",@@ -2085,6 +2105,8 @@ class ModelHubSourceConfig:"account_label": self.account_label,"masked_credential": self.masked_credential,}+ if self.client_nonce is not None:+ payload["client_nonce"] = self.client_nonceif self.usage is not None:payload["usage"] = self.usage.to_payload()return payload@@ -2334,6 +2356,13 @@ class ModelHubConfig:source_ids = [source.id for source in sources]if len(set(source_ids)) != len(source_ids):raise ValueError("Config 'model_hub.sources' contains duplicate ids")+ source_nonces = [+ source.client_nonce+ for source in sources+ if source.client_nonce is not None+ ]+ if len(set(source_nonces)) != len(source_nonces):+ raise ValueError("Config 'model_hub.sources' contains duplicate client nonces")for backend in MODEL_HUB_BACKENDS:native_sources = [sourcediff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex aa6d61056..0897ca79d 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -31,6 +31,7 @@ from config.v2_config import (canonical_opencode_menu_identity,normalize_model_hub_base_url,normalize_model_hub_vendor_id,+ validate_model_hub_source_client_nonce,)from core.agent_auth_service import BackendLoginInProgressErrorfrom core.services.settings import default_config@@ -152,6 +153,11 @@ class ModelHubError(Exception):self.turn_outcome = turn_outcome+class CredentialCleanupUnsettledError(ModelHubError):+ def __init__(self):+ super().__init__("engine_down", status=503)++class EngineUnavailableError(RuntimeError):pass@@ -442,7 +448,7 @@ async def _require_credential_cleanup("""Refuse to settle when cleanup is neither complete nor durable."""if not await service._rollback_credential(source_id, credential_ref):- raise ModelHubError("engine_down", status=503)+ raise CredentialCleanupUnsettledErrorasync def _rollback_replacement_before_settling(@@ -588,6 +594,7 @@ class ModelHubService:self._oauth_start_tasks: dict[tuple[str, str, OAuthChannel], asyncio.Task[dict]] = {}+ self._source_create_nonces: set[str] = set()self._next_settlement_generation = PRE_ATTEMPT_SETTLEMENT_GENERATIONself._latest_source_attempt_generation: dict[str, int] = {}self._engine_synced = False@@ -758,6 +765,16 @@ class ModelHubService:if callable(ensure_writable):ensure_writable()+ def _claim_source_create_nonce_locked(self, client_nonce: str) -> None:+ if any(+ source.client_nonce == client_nonce+ for source in self.store.load().sources+ ):+ raise ModelHubError("source_nonce_conflict", status=409)+ if client_nonce in self._source_create_nonces:+ raise ModelHubError("source_create_in_progress", status=409)+ self._source_create_nonces.add(client_nonce)+async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None:bindings = self._bindings(config)has_hub_sources = any(@@ -2152,6 +2169,7 @@ class ModelHubService:"key","oauth_flow_ref","protocol_order",+ "client_nonce",}:raise ModelHubError("discovery_failed")forbidden = {@@ -2208,6 +2226,14 @@ class ModelHubService:credential_value = payload.get("key")oauth_ref = payload.get("oauth_flow_ref")+ try:+ client_nonce = (+ validate_model_hub_source_client_nonce(payload.get("client_nonce"))+ if "client_nonce" in payload+ else None+ )+ except ValueError:+ raise ModelHubError("discovery_failed") from Noneif credential_value is not None:if not isinstance(credential_value, str):raise ModelHubError("discovery_failed")@@ -2220,6 +2246,11 @@ class ModelHubService:raise ModelHubError("discovery_failed")if kind == "api_key" and not credential_value:raise ModelHubError("discovery_failed")+ if kind != "api_key" and client_nonce is not None:+ raise ModelHubError("discovery_failed")+ protocol_order: tuple[str, ...] | None = None+ if kind == "api_key":+ protocol_order = self._observation_protocol_order(payload)if oauth_ref:return self._source_creation_result(@@ -2236,87 +2267,124 @@ class ModelHubService:if kind == "subscription":raise ModelHubError("flow_not_found", status=404)- observation = await self._require_proven_source_payload(- {- "vendor": vendor,- "base_url": base_url,- "key": credential_value,- "protocol_order": payload.get("protocol_order"),- }- )- source = ModelHubSourceConfig(- id=_source_id(),- kind=kind,- vendor=vendor,- display_name=display_name,- protocol=cast(Literal["anthropic", "openai_responses", "openai_chat"], observation.protocol),- base_url=base_url,- supply_channel=channel,- billing=billing,- state=ModelHubSourceStateConfig(status="standby"),- usage=ModelHubSourceUsageConfig(),- models=manual_models,- created_at=self.now().isoformat(),- credential_ref="cred_preflight",- )- if observation.discovery is ObservationDiscovery.SUCCEEDED:- self._apply_discovered_models(- source,- manual_models,- list(observation.model_ids),- allow_empty=True,- )- elif observation.discovery is ObservationDiscovery.FAILED:- source.state = ModelHubSourceStateConfig(- status="error",- detail_key="models.source.error.unclassified",- )-- # AC-29 requires the canonical Source validator to run before any- # permanent credential is provisioned. The placeholder is never saved.+ assert protocol_order is not None+ # Validate the complete client-controlled Source shape before nonce+ # state can mask a malformed request. Probe results replace only the+ # provisional protocol and server-derived model state below.try:- source = ModelHubSourceConfig.from_payload(source.to_payload())+ source = ModelHubSourceConfig.from_payload(+ ModelHubSourceConfig(+ id=_source_id(),+ kind=kind,+ vendor=vendor,+ display_name=display_name,+ protocol=cast(+ Literal["anthropic", "openai_responses", "openai_chat"],+ protocol_order[0],+ ),+ base_url=base_url,+ supply_channel=channel,+ billing=billing,+ state=ModelHubSourceStateConfig(status="standby"),+ usage=ModelHubSourceUsageConfig(),+ models=manual_models,+ created_at=self.now().isoformat(),+ client_nonce=client_nonce,+ credential_ref="cred_preflight",+ ).to_payload()+ )except (TypeError, ValueError):raise ModelHubError("discovery_failed") from None- rollback_credential_ref = await self._engine_call(- self.adapter.provision_credential(- vendor,- source.protocol,- cast(str, credential_value),- source.base_url,- )- )- source.credential_ref = rollback_credential_ref- source.masked_credential = _mask_credential(cast(str, credential_value))- source = ModelHubSourceConfig.from_payload(source.to_payload())- persisted = False+ nonce_claimed = False+ release_nonce = Truetry:- async with self._mutation_lock:- await self._commit_new_source_locked(source)- persisted = True- return self._source_creation_result(source.to_payload())- except asyncio.CancelledError:- persisted = self._persisted_credential(- self.store.load(),- source.id,- rollback_credential_ref,+ if client_nonce is not None:+ async with self._mutation_lock:+ self._claim_source_create_nonce_locked(client_nonce)+ nonce_claimed = True+ if self.revocations.list():+ await self._ensure_engine_synced()+ observation = await self._require_proven_source_payload(+ {+ "vendor": vendor,+ "base_url": base_url,+ "key": credential_value,+ "protocol_order": payload.get("protocol_order"),+ }+ )+ source.protocol = cast(+ Literal["anthropic", "openai_responses", "openai_chat"],+ observation.protocol,)- if not persisted:- await _rollback_credential_before_settling(+ if observation.discovery is ObservationDiscovery.SUCCEEDED:+ self._apply_discovered_models(+ source,+ manual_models,+ list(observation.model_ids),+ allow_empty=True,+ )+ elif observation.discovery is ObservationDiscovery.FAILED:+ source.state = ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ )++ # AC-29 requires the canonical Source validator to run before any+ # permanent credential is provisioned. The placeholder is never saved.+ try:+ source = ModelHubSourceConfig.from_payload(source.to_payload())+ except (TypeError, ValueError):+ raise ModelHubError("discovery_failed") from None++ rollback_credential_ref = await (+ _acquire_credential_ref_with_cancellation_ownership(self,+ self.adapter.provision_credential(+ vendor,+ source.protocol,+ cast(str, credential_value),+ source.base_url,+ ),source.id,- rollback_credential_ref,)- raise- except Exception:- if not persisted:- await _require_credential_cleanup(- self,+ )+ source.credential_ref = rollback_credential_ref+ source.masked_credential = _mask_credential(cast(str, credential_value))+ source = ModelHubSourceConfig.from_payload(source.to_payload())+ persisted = False+ try:+ async with self._mutation_lock:+ await self._commit_new_source_locked(source)+ persisted = True+ return self._source_creation_result(source.to_payload())+ except asyncio.CancelledError:+ persisted = self._persisted_credential(+ self.store.load(),source.id,rollback_credential_ref,)+ if not persisted:+ await _rollback_credential_before_settling(+ self,+ source.id,+ rollback_credential_ref,+ )+ raise+ except Exception:+ if not persisted:+ await _require_credential_cleanup(+ self,+ source.id,+ rollback_credential_ref,+ )+ raise+ except CredentialCleanupUnsettledError:+ release_nonce = Falseraise+ finally:+ if nonce_claimed and release_nonce:+ self._source_create_nonces.discard(cast(str, client_nonce))async def replace_credential(self, source_id: str, payload: object) -> dict:if (diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 57420cca2..d196c2d95 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -712,6 +712,460 @@ def test_discovery_probe_failure_is_not_reported_as_engine_down(tmp_path):assert store.config.sources == []+def test_api_key_create_route_persists_client_nonce_for_list_reconciliation(+ monkeypatch,+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ request_body = {+ "kind": "api_key",+ "vendor": "custom",+ "display_name": "Relay",+ "base_url": "https://relay.example/v1",+ "key": "sk-test-source-create-nonce",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ }++ response = client.post(+ "/api/models/sources",+ json=request_body,+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert response.status_code == 201+ body = response.get_json()+ _assert_envelope(body)+ assert body["source"]["client_nonce"] == request_body["client_nonce"]+ _assert_valid("source.schema.json", body["source"])+ assert store.config.sources[0].client_nonce == request_body["client_nonce"]+ assert adapter.secret_lengths == [+ len(request_body["key"]),+ len(request_body["key"]),+ ]+ assert request_body["key"] not in json.dumps(body)++ listed = client.get("/api/models/sources", base_url=base_url).get_json()+ assert [source["client_nonce"] for source in listed["sources"]] == [+ request_body["client_nonce"]+ ]+++ "client_nonce",+ [None, "scn_short", "SCN_01j5w8z7p4n6q2rt", "scn_01j5w8z7p4n6q2r!"],+)+def test_source_create_rejects_invalid_client_nonce_before_upstream(+ tmp_path,+ client_nonce,+):+ service, store, adapter = _service(tmp_path)++ with pytest.raises(ModelHubError) as rejected:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "custom",+ "key": "sk-test-invalid-source-create-nonce",+ "client_nonce": client_nonce,+ }+ )+ )++ assert rejected.value.code == "discovery_failed"+ assert adapter.secret_lengths == []+ assert store.config.sources == []+++def test_source_create_nonce_covers_in_flight_committed_and_deleted_states(tmp_path):+ async def scenario():+ class BlockingObservationAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.observation_started = asyncio.Event()+ self.release_observation = asyncio.Event()+ self.block_once = True++ async def observe_source(+ self,+ vendor,+ base_url,+ credential_ref,+ protocol_order,+ ):+ if self.block_once:+ self.block_once = False+ self.observation_started.set()+ await self.release_observation.wait()+ return await super().observe_source(+ vendor,+ base_url,+ credential_ref,+ protocol_order,+ )++ store = MemoryStore()+ adapter = BlockingObservationAdapter()+ service = ModelHubService(+ store=store,+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )+ payload = {+ "kind": "api_key",+ "vendor": "custom",+ "display_name": "Relay",+ "base_url": "https://relay.example/v1",+ "key": "sk-test-source-create-state-machine",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ }++ first = asyncio.create_task(service.create_source(payload))+ await adapter.observation_started.wait()+ before_retry_work = list(adapter.secret_lengths)+ with pytest.raises(ModelHubError) as in_flight:+ await service.create_source(payload)+ assert in_flight.value.code == "source_create_in_progress"+ assert in_flight.value.status == 409+ assert adapter.secret_lengths == before_retry_work++ adapter.release_observation.set()+ committed = await first+ after_commit_work = list(adapter.secret_lengths)+ with pytest.raises(ModelHubError) as conflict:+ await service.create_source(payload)+ assert conflict.value.code == "source_nonce_conflict"+ assert conflict.value.status == 409+ assert adapter.secret_lengths == after_commit_work+ assert [+ source["client_nonce"]+ for source in service.list_sources()+ if source.get("client_nonce") == payload["client_nonce"]+ ] == [payload["client_nonce"]]++ await service.delete_source(committed["source"]["id"], force=True)+ recreated = await service.create_source(payload)+ assert recreated["source"]["id"] != committed["source"]["id"]+ assert recreated["source"]["client_nonce"] == payload["client_nonce"]++ asyncio.run(scenario())+++ "malformed_fields",+ [+ pytest.param({"protocol_order": ["anthropic"]}, id="protocol-order"),+ pytest.param({"billing": "credits"}, id="billing"),+ pytest.param(+ {+ "models": [+ {+ "id": "duplicate-model",+ "origin": "manual",+ "reasoning_efforts": [],+ },+ {+ "id": "duplicate-model",+ "origin": "manual",+ "reasoning_efforts": [],+ },+ ]+ },+ id="duplicate-models",+ ),+ ],+)+def test_source_create_validates_all_fields_before_every_nonce_state(+ tmp_path,+ malformed_fields,+):+ async def scenario():+ class BlockingObservationAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.observation_started = asyncio.Event()+ self.release_observation = asyncio.Event()+ self.block_once = True++ async def observe_source(+ self,+ vendor,+ base_url,+ credential_ref,+ protocol_order,+ ):+ if self.block_once:+ self.block_once = False+ self.observation_started.set()+ await self.release_observation.wait()+ return await super().observe_source(+ vendor,+ base_url,+ credential_ref,+ protocol_order,+ )++ adapter = BlockingObservationAdapter()+ service = ModelHubService(+ store=MemoryStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth-flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )+ payload = {+ "kind": "api_key",+ "vendor": "custom",+ "key": "sk-test-source-create-probe-order",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ }+ malformed = {**payload, **malformed_fields}++ unclaimed_work = list(adapter.secret_lengths)+ with pytest.raises(ModelHubError) as unclaimed:+ await service.create_source(+ {+ **malformed,+ "client_nonce": "scn_01j5w8z7p4n6q2ru",+ }+ )+ assert unclaimed.value.code == "discovery_failed"+ assert adapter.secret_lengths == unclaimed_work++ first = asyncio.create_task(service.create_source(payload))+ await adapter.observation_started.wait()+ in_flight_work = list(adapter.secret_lengths)+ with pytest.raises(ModelHubError) as in_flight:+ await service.create_source(malformed)+ assert in_flight.value.code == "discovery_failed"+ assert adapter.secret_lengths == in_flight_work++ adapter.release_observation.set()+ await first+ committed_work = list(adapter.secret_lengths)+ with pytest.raises(ModelHubError) as committed:+ await service.create_source(malformed)+ assert committed.value.code == "discovery_failed"+ assert adapter.secret_lengths == committed_work++ recreated = await service.create_source(+ {+ **payload,+ "client_nonce": "scn_01j5w8z7p4n6q2ru",+ }+ )+ assert recreated["source"]["client_nonce"] == "scn_01j5w8z7p4n6q2ru"++ asyncio.run(scenario())+++def test_source_create_nonce_releases_only_after_credential_cleanup(tmp_path):+ async def scenario():+ adapter = FakeAdapter()+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ service = ModelHubService(+ store=MemoryStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )+ payload = {+ "kind": "api_key",+ "vendor": "custom",+ "key": "sk-test-source-create-retry",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ }++ with pytest.raises(ModelHubError) as rejected:+ await service.create_source(payload)+ assert rejected.value.code == "discovery_failed"+ assert adapter.revoked == ["cred_test001"]++ adapter.observation = None+ created = await service.create_source(payload)+ assert created["source"]["client_nonce"] == payload["client_nonce"]++ asyncio.run(scenario())+++def test_source_create_nonce_retains_unsettled_cleanup_until_restart(tmp_path):+ async def scenario():+ class CleanupFailingAdapter(FakeAdapter):+ async def revoke_credential(self, credential_ref):+ raise RuntimeError("cleanup unavailable")++ class UnwritableRevocations(CredentialRevocationJournal):+ def add(self, source_id, credential_ref, *, operation="revoke_credential"):+ raise OSError("journal unavailable")++ store = MemoryStore()+ adapter = CleanupFailingAdapter()+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ service = ModelHubService(+ store=store,+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=UnwritableRevocations(tmp_path / "revocations.json"),+ )+ payload = {+ "kind": "api_key",+ "vendor": "custom",+ "key": "sk-test-source-create-cleanup",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ }++ with pytest.raises(ModelHubError) as cleanup_failed:+ await service.create_source(payload)+ assert cleanup_failed.value.code == "engine_down"+ upstream_work = list(adapter.secret_lengths)++ with pytest.raises(ModelHubError) as retained:+ await service.create_source(payload)+ assert retained.value.code == "source_create_in_progress"+ assert adapter.secret_lengths == upstream_work++ restarted_adapter = FakeAdapter()+ restarted = ModelHubService(+ store=store,+ adapter=restarted_adapter,+ events=BoundedEventLog(tmp_path / "restarted-events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "restarted-oauth-flows.json"),+ revocations=CredentialRevocationJournal(+ tmp_path / "restarted-revocations.json"+ ),+ )+ created = await restarted.create_source(payload)+ assert created["source"]["client_nonce"] == payload["client_nonce"]++ asyncio.run(scenario())+++def test_source_create_nonce_reconciles_pending_revocations_before_retry(tmp_path):+ async def scenario():+ class OrderedAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.operations = []++ async def sync_sources(self, bindings):+ self.operations.append("sync")+ await super().sync_sources(bindings)++ async def revoke_credential(self, credential_ref):+ self.operations.append(f"revoke:{credential_ref}")+ await super().revoke_credential(credential_ref)++ async def provision_transient_credential(self, vendor, secret, base_url):+ self.operations.append("provision_transient")+ return await super().provision_transient_credential(+ vendor,+ secret,+ base_url,+ )++ journal_path = tmp_path / "revocations.json"+ journal = CredentialRevocationJournal(journal_path)+ journal.add("src_failed01", "cred_orphaned")+ adapter = OrderedAdapter()+ service = ModelHubService(+ store=MemoryStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth-flows.json"),+ revocations=CredentialRevocationJournal(journal_path),+ )++ created = await service.create_source(+ {+ "kind": "api_key",+ "vendor": "custom",+ "key": "sk-test-source-create-reconcile",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ }+ )++ assert created["source"]["client_nonce"] == "scn_01j5w8z7p4n6q2rt"+ assert adapter.operations[:3] == [+ "sync",+ "revoke:cred_orphaned",+ "provision_transient",+ ]+ assert service.revocations.list() == []++ asyncio.run(scenario())+++def test_source_create_nonce_owns_permanent_credential_through_cancellation(tmp_path):+ async def scenario():+ class BlockingProvisionAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.provision_started = asyncio.Event()+ self.release_provision = asyncio.Event()++ async def provision_credential(self, vendor, protocol, secret, base_url):+ self.provision_started.set()+ await self.release_provision.wait()+ return await super().provision_credential(+ vendor,+ protocol,+ secret,+ base_url,+ )++ adapter = BlockingProvisionAdapter()+ service = ModelHubService(+ store=MemoryStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth-flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )+ payload = {+ "kind": "api_key",+ "vendor": "custom",+ "key": "sk-test-source-create-cancel",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",+ }++ create = asyncio.create_task(service.create_source(payload))+ await adapter.provision_started.wait()+ revoked_before_cancel = list(adapter.revoked)+ create.cancel()+ adapter.release_provision.set()+ with pytest.raises(asyncio.CancelledError):+ await create++ assert adapter.revoked == [*revoked_before_cancel, "cred_test002"]+ assert service.revocations.list() == []+ recreated = await service.create_source(payload)+ assert recreated["source"]["client_nonce"] == payload["client_nonce"]++ asyncio.run(scenario())++def test_agents_endpoint_projects_builtin_models_and_standard_vendors(tmp_path):"""Integration (2026-07-24): list_agents() carries the read-only builtin_models /standard_vendors projections straight from the backend modules, so the UI neverdiff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 593c9eea4..15db57e15 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -441,6 +441,30 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():_assert_valid("agent-supply.schema.json", serialized)+def test_source_client_nonce_round_trips_and_is_unique():+ first_payload = copy.deepcopy(_schema("source.schema.json")["examples"][1])+ first_payload["client_nonce"] = "scn_01j5w8z7p4n6q2rt"+ first = ModelHubSourceConfig.from_payload(first_payload)++ assert first.client_nonce == first_payload["client_nonce"]+ assert first.to_payload()["client_nonce"] == first_payload["client_nonce"]+ _assert_valid("source.schema.json", first.to_payload())++ for invalid in (None, "scn_short", "SCN_01j5w8z7p4n6q2rt", "scn_01j5w8z7p4n6q2r!"):+ with pytest.raises(ValueError, match="client_nonce"):+ ModelHubSourceConfig.from_payload(+ {**first_payload, "client_nonce": invalid}+ )++ second_payload = copy.deepcopy(first_payload)+ second_payload["id"] = "src_relay9c2x"+ duplicate = ModelHubConfig(+ sources=[first, ModelHubSourceConfig.from_payload(second_payload)]+ )+ with pytest.raises(ValueError, match="duplicate client nonces"):+ ModelHubConfig.from_payload(duplicate.to_payload())++def test_every_frozen_schema_example_is_valid_and_json_round_trips():for path in sorted(CONTRACTS.glob("*.schema.json")):schema = json.loads(path.read_text(encoding="utf-8"))@@ -1233,6 +1257,7 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm**_schema("source.schema.json")["examples"][0],"supply_channel": "hub","credential_ref": "cred_serializer_test",+ "client_nonce": "scn_01j5w8z7p4n6q2rt",}hub_payload = {"sources": [source_example],