Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(model-hub): wire oauth subscription activation (#1387)

Call White56e9127d4db6
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index f34fd4266..c617f31f3 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -478,8 +478,10 @@ def _oauth_payload(
*,
channel: str,
intent: Literal["create", "reauth"] = "create",
+ client_nonce: str | None = None,
+ expires_at_iso: str | None = None,
) -> dict:
- return {
+ payload = {
"flow_id": flow.flow_id,
"intent": intent,
"source_id": flow.source_id,
@@ -493,8 +495,15 @@ def _oauth_payload(
"instructions_key": flow.instructions_key,
},
"error_key": flow.error_key,
- "expires_at": flow.expires_at_iso,
+ "expires_at": (
+ expires_at_iso
+ if client_nonce is not None
+ else flow.expires_at_iso
+ ),
}
+ if client_nonce is not None:
+ payload["client_nonce"] = client_nonce
+ return payload
def _runtime_payload(status: EngineStatus) -> dict:
@@ -544,7 +553,10 @@ class ModelHubService:
paths.get_state_dir() / "model_hub_turn_provenance.json"
)
self.native_oauth_adapter = native_oauth_adapter or UnavailableNativeOAuthAdapter()
- self.oauth_flows = oauth_flows or OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json")
+ self.oauth_flows = oauth_flows or OAuthFlowRegistry(
+ paths.get_state_dir() / "model_hub_oauth_flows.json",
+ now=now,
+ )
self.revocations = revocations or CredentialRevocationJournal(
paths.get_state_dir() / "model_hub_pending_revocations.json"
)
@@ -557,6 +569,9 @@ class ModelHubService:
lambda _backend, _source: True
)
self._mutation_lock = asyncio.Lock()
+ self._oauth_start_tasks: dict[
+ tuple[str, str, OAuthChannel], asyncio.Task[dict]
+ ] = {}
self._next_settlement_generation = PRE_ATTEMPT_SETTLEMENT_GENERATION
self._latest_source_attempt_generation: dict[str, int] = {}
self._engine_synced = False
@@ -851,6 +866,73 @@ class ModelHubService:
flow_id=flow_id,
)
+ @staticmethod
+ def _cancelled_oauth_flow(
+ flow_id: str,
+ binding: OAuthFlowBinding,
+ ) -> OAuthFlowState:
+ if binding.source_id is None or binding.vendor is None:
+ raise ModelHubError("flow_not_found", status=404)
+ return OAuthFlowState(
+ flow_id=flow_id,
+ source_id=binding.source_id,
+ vendor=binding.vendor,
+ state="cancelled",
+ auth_url=None,
+ device_code=None,
+ expects="none",
+ instructions_key=None,
+ error_key=None,
+ expires_at_iso=binding.expires_at_iso,
+ credential_ref=None,
+ channel=binding.channel,
+ )
+
+ @staticmethod
+ def _flow_payload(
+ flow: OAuthFlowState,
+ binding: OAuthFlowBinding,
+ ) -> dict:
+ return _oauth_payload(
+ flow,
+ channel=binding.channel,
+ intent=binding.intent,
+ client_nonce=binding.client_nonce,
+ expires_at_iso=binding.expires_at_iso,
+ )
+
+ async def _replay_nonce_flow(self, flow_id: str) -> dict:
+ binding = self._oauth_binding(flow_id)
+ if binding.terminal_state == "cancelled":
+ flow = self._cancelled_oauth_flow(flow_id, binding)
+ else:
+ flow = await self._oauth_status(flow_id, binding.channel)
+ self._raise_if_flow_expired(flow_id, flow)
+ flow, repair_result = await self._materialize_completed_oauth(
+ flow_id,
+ binding,
+ flow,
+ )
+ if repair_result is not None:
+ return {
+ "flow": self._flow_payload(flow, binding),
+ **repair_result,
+ }
+ return self._oauth_result(flow_id, flow)
+
+ async def _discard_started_oauth_flow(
+ self,
+ flow: OAuthFlowState,
+ channel: OAuthChannel,
+ ) -> None:
+ if channel == "hub":
+ await self._discard_unbound_hub_flow(flow)
+ return
+ try:
+ await self.native_oauth_adapter.cancel_oauth(flow.flow_id)
+ except Exception:
+ pass
+
async def _discover(self, source: ModelHubSourceConfig) -> list[str]:
if not source.credential_ref:
return [model.id for model in source.models]
@@ -3518,10 +3600,7 @@ class ModelHubService:
if (
not isinstance(payload, dict)
or set(payload) - {"acknowledge_irreversible"}
- or (
- "acknowledge_irreversible" in payload
- and payload.get("acknowledge_irreversible") is not True
- )
+ or payload.get("acknowledge_irreversible") is not True
):
raise ModelHubError("reauth_confirmation_required", status=409)
@@ -3530,11 +3609,6 @@ class ModelHubService:
source = self._source(config, source_id)
if source.kind != "subscription":
raise ModelHubError("discovery_failed")
- if (
- source.supply_channel == "native_cli"
- and payload.get("acknowledge_irreversible") is not True
- ):
- raise ModelHubError("reauth_confirmation_required", status=409)
replace_pending_flow_id: str | None = None
pending = self.oauth_flows.pending_reauth(source.id)
@@ -3659,7 +3733,19 @@ class ModelHubService:
async def oauth_start(self, payload: dict) -> dict:
vendor = payload.get("vendor") if isinstance(payload, dict) else None
channel = payload.get("channel") if isinstance(payload, dict) else None
- if not isinstance(vendor, str) or channel not in {"native_cli", "hub"}:
+ client_nonce = (
+ payload.get("client_nonce") if isinstance(payload, dict) else None
+ )
+ if (
+ not isinstance(payload, dict)
+ or not isinstance(vendor, str)
+ or channel not in {"native_cli", "hub"}
+ or set(payload) - {"vendor", "channel", "client_nonce"}
+ or (
+ "client_nonce" in payload
+ and not isinstance(client_nonce, str)
+ )
+ ):
raise ModelHubError("flow_not_found", status=400)
try:
vendor = normalize_model_hub_vendor_id(vendor)
@@ -3685,35 +3771,102 @@ class ModelHubService:
status=409,
data={"existing_source_id": existing.id},
)
- pending_source_id = _source_id()
- flow = await self._oauth_call(
- self._oauth_adapter(oauth_channel).start_oauth(pending_source_id, vendor)
- )
- 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,
- )
- return {"flow": _oauth_payload(flow, channel=channel)}
+
+ nonce_key: tuple[str, str, OAuthChannel] | None = None
+ if client_nonce is not None:
+ try:
+ nonce_claim = self.oauth_flows.claim_nonce(
+ client_nonce,
+ vendor,
+ oauth_channel,
+ )
+ except ValueError:
+ raise ModelHubError("flow_not_found", status=400) from None
+ nonce_key = (client_nonce, vendor, oauth_channel)
+ if not nonce_claim.owner:
+ if nonce_claim.status == "committed":
+ if nonce_claim.flow_id is None:
+ raise ModelHubError("flow_not_found", status=404)
+ return await self._replay_nonce_flow(nonce_claim.flow_id)
+ task = self._oauth_start_tasks.get(nonce_key)
+ if task is None:
+ raise ModelHubError("engine_down", status=503)
+ return await asyncio.shield(task)
+
+ async def start_and_remember() -> dict:
+ pending_source_id = _source_id()
+ flow: OAuthFlowState | None = None
+ flow_cleanup_done = False
+ try:
+ flow = await self._oauth_call(
+ self._oauth_adapter(oauth_channel).start_oauth(
+ pending_source_id,
+ vendor,
+ )
+ )
+ if flow.source_id != pending_source_id or flow.vendor != vendor:
+ await self._discard_started_oauth_flow(flow, oauth_channel)
+ flow_cleanup_done = True
+ raise ModelHubError("flow_not_found", status=502)
+ if client_nonce is not None and flow.expires_at_iso is None:
+ await self._discard_started_oauth_flow(flow, oauth_channel)
+ flow_cleanup_done = True
+ raise ModelHubError("flow_not_found", status=502)
+ self.oauth_flows.remember(
+ flow.flow_id,
+ oauth_channel,
+ pending_source_id,
+ vendor,
+ client_nonce=client_nonce,
+ expires_at_iso=(
+ flow.expires_at_iso if client_nonce is not None else None
+ ),
+ )
+ except BaseException as error:
+ try:
+ if flow is not None and not flow_cleanup_done:
+ await self._discard_started_oauth_flow(
+ flow,
+ oauth_channel,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ if not isinstance(error, asyncio.CancelledError):
+ raise ModelHubError("engine_down", status=503) from None
+ finally:
+ if client_nonce is not None:
+ try:
+ self.oauth_flows.release_nonce(
+ client_nonce,
+ vendor,
+ oauth_channel,
+ )
+ except (OSError, ValueError):
+ pass
+ raise
+ binding = self._oauth_binding(flow.flow_id)
+ return {"flow": self._flow_payload(flow, binding)}
+
+ if nonce_key is None:
+ return await start_and_remember()
+ task = asyncio.create_task(start_and_remember())
+ self._oauth_start_tasks[nonce_key] = task
+
+ def forget_settled_start(completed: asyncio.Task[dict]) -> None:
+ if self._oauth_start_tasks.get(nonce_key) is completed:
+ self._oauth_start_tasks.pop(nonce_key, None)
+
+ task.add_done_callback(forget_settled_start)
+ return await task
def _oauth_result(
self,
flow_id: str,
flow: OAuthFlowState,
- *,
- channel: OAuthChannel,
) -> dict:
binding = self._oauth_binding(flow_id)
- result = {
- "flow": _oauth_payload(
- flow,
- channel=channel,
- intent=binding.intent,
- )
- }
+ result = {"flow": self._flow_payload(flow, binding)}
if flow.state != "success":
return result
source = self._completed_oauth_source(binding)
@@ -3733,13 +3886,14 @@ class ModelHubService:
async def oauth_status(self, flow_id: str) -> dict:
binding = self._oauth_binding(flow_id)
- completed = self._completed_oauth_flow(flow_id, binding)
- if completed is not None:
+ if binding.terminal_state == "cancelled":
return self._oauth_result(
flow_id,
- completed,
- channel=binding.channel,
+ self._cancelled_oauth_flow(flow_id, binding),
)
+ completed = self._completed_oauth_flow(flow_id, binding)
+ if completed is not None:
+ return self._oauth_result(flow_id, completed)
flow = await self._oauth_status(flow_id, binding.channel)
self._raise_if_flow_expired(flow_id, flow)
flow, repair_result = await self._materialize_completed_oauth(
@@ -3749,14 +3903,10 @@ class ModelHubService:
)
if repair_result is not None:
return {
- "flow": _oauth_payload(
- flow,
- channel=binding.channel,
- intent="reauth",
- ),
+ "flow": self._flow_payload(flow, binding),
**repair_result,
}
- return self._oauth_result(flow_id, flow, channel=binding.channel)
+ return self._oauth_result(flow_id, flow)
async def oauth_submit(self, payload: dict) -> dict:
flow_id = payload.get("flow_id") if isinstance(payload, dict) else None
@@ -3765,13 +3915,14 @@ class ModelHubService:
raise ModelHubError("flow_not_found", status=404)
self._ensure_config_writable()
binding = self._oauth_binding(flow_id)
- completed = self._completed_oauth_flow(flow_id, binding)
- if completed is not None:
+ if binding.terminal_state == "cancelled":
return self._oauth_result(
flow_id,
- completed,
- channel=binding.channel,
+ self._cancelled_oauth_flow(flow_id, binding),
)
+ completed = self._completed_oauth_flow(flow_id, binding)
+ if completed is not None:
+ return self._oauth_result(flow_id, completed)
current = await self._oauth_status(flow_id, binding.channel)
self._raise_if_flow_expired(flow_id, current)
flow = await self._oauth_call(
@@ -3785,14 +3936,10 @@ class ModelHubService:
)
if repair_result is not None:
return {
- "flow": _oauth_payload(
- flow,
- channel=binding.channel,
- intent="reauth",
- ),
+ "flow": self._flow_payload(flow, binding),
**repair_result,
}
- return self._oauth_result(flow_id, flow, channel=binding.channel)
+ return self._oauth_result(flow_id, flow)
async def oauth_cancel(self, flow_id: object) -> None:
if not isinstance(flow_id, str):
@@ -3800,6 +3947,8 @@ class ModelHubService:
terminal: tuple[OAuthFlowBinding, OAuthFlowState] | None = None
async with self._mutation_lock:
binding = self._oauth_binding(flow_id)
+ if binding.terminal_state == "cancelled":
+ return
completed = self._completed_oauth_flow(flow_id, binding)
if completed is not None:
return
@@ -3831,7 +3980,10 @@ class ModelHubService:
else:
self.oauth_flows.forget(flow_id)
else:
- self.oauth_flows.forget(flow_id)
+ if binding.client_nonce is not None:
+ self.oauth_flows.retain_cancelled(flow_id)
+ else:
+ self.oauth_flows.forget(flow_id)
if terminal is not None:
binding, flow = terminal
await self._materialize_completed_oauth(
@@ -3842,7 +3994,10 @@ class ModelHubService:
if flow.state != "success":
async with self._mutation_lock:
try:
- self.oauth_flows.forget(flow_id)
+ if binding.client_nonce is not None:
+ self.oauth_flows.retain_cancelled(flow_id)
+ else:
+ self.oauth_flows.forget(flow_id)
except OSError:
raise ModelHubError("engine_down", status=503) from None
diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.py
index 766806092..4367a34e5 100644
--- a/tests/scenario_harness/model_hub_native_oauth.py
+++ b/tests/scenario_harness/model_hub_native_oauth.py
@@ -133,7 +133,10 @@ class NativeOAuthScenarioHarness:
adapter=UnavailableEngineAdapter(),
events=BoundedEventLog(state_dir / "events.json"),
native_oauth_adapter=self.adapter,
- oauth_flows=OAuthFlowRegistry(state_dir / "oauth_flows.json"),
+ oauth_flows=OAuthFlowRegistry(
+ state_dir / "oauth_flows.json",
+ now=lambda: datetime(2026, 7, 25, 0, 0, tzinfo=timezone.utc),
+ ),
revocations=CredentialRevocationJournal(state_dir / "revocations.json"),
now=lambda: datetime(2026, 7, 25, 0, 0, tzinfo=timezone.utc),
requested_model_override=self.store.requested_model,
@@ -190,7 +193,11 @@ class HubOAuthScenarioHarness:
store=self.store,
adapter=self.adapter,
events=BoundedEventLog(state_dir / "hub-events.json"),
- oauth_flows=OAuthFlowRegistry(state_dir / "hub-oauth-flows.json"),
+ oauth_flows=OAuthFlowRegistry(
+ state_dir / "hub-oauth-flows.json",
+ now=lambda: datetime(2026, 7, 25, 0, 0, tzinfo=timezone.utc),
+ ),
revocations=CredentialRevocationJournal(state_dir / "hub-revocations.json"),
now=lambda: datetime(2026, 7, 25, 0, 0, tzinfo=timezone.utc),
+ requested_model_override=self.store.requested_model,
)
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 548a370d9..29abb5fa6 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -94,8 +94,7 @@ scenarios:
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
+ status: covered
kind: negative_path
layer: scenario
backend: shared
@@ -242,8 +241,7 @@ scenarios:
test: 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
+ status: covered
kind: retry
layer: scenario
backend: shared
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 0e41b69ae..84692ee00 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -1312,10 +1312,6 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
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.
@@ -1404,10 +1400,6 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
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.
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 93b11a4fe..99342de6e 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -297,7 +297,10 @@ def _service(tmp_path, adapter=None):
adapter=adapter,
events=BoundedEventLog(tmp_path / "events.json"),
native_oauth_adapter=adapter,
- oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ oauth_flows=OAuthFlowRegistry(
+ tmp_path / "oauth_flows.json",
+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
+ ),
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
requested_model_override=lambda backend: store.requested_model(backend),
@@ -1018,6 +1021,34 @@ def test_oauth_start_normalizes_vendor_before_singleton_and_adapter(tmp_path):
assert adapter.oauth_start_calls == [(flow["source_id"], "anthropic")]
+ "payload",
+ [
+ None,
+ {"vendor": "anthropic", "channel": "hub", "client_nonce": None},
+ {
+ "vendor": "anthropic",
+ "channel": "hub",
+ "client_nonce": "invalid",
+ },
+ {
+ "vendor": "anthropic",
+ "channel": "hub",
+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",
+ "unexpected": True,
+ },
+ ],
+)
+def test_oauth_start_rejects_invalid_nonce_payload_before_provider(tmp_path, payload):
+ service, _, adapter = _service(tmp_path)
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.oauth_start(payload))
+
+ assert exc_info.value.code == "flow_not_found"
+ assert adapter.oauth_start_calls == []
+
+
def test_model_hub_oauth_blocks_recovery_before_external_auth(tmp_path):
service, store, adapter = _service(tmp_path)
flow = asyncio.run(
@@ -1759,7 +1790,7 @@ def test_native_reauth_logout_spawn_failure_restores_prior_supply(tmp_path):
)
-def test_hub_reauth_is_transactional_without_native_acknowledgement(tmp_path):
+def test_hub_reauth_requires_acknowledgement_then_materializes(tmp_path):
service, store, adapter = _service(tmp_path)
source = ModelHubSourceConfig(
id="src_huboauth01",
@@ -1784,7 +1815,18 @@ def test_hub_reauth_is_transactional_without_native_acknowledgement(tmp_path):
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ for acknowledgement in ({}, {"acknowledge_irreversible": False}):
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.reauth_source(source.id, acknowledgement))
+ assert exc_info.value.code == "reauth_confirmation_required"
+ assert adapter.oauth_start_calls == []
+
+ flow = asyncio.run(
+ service.reauth_source(
+ source.id,
+ {"acknowledge_irreversible": True},
+ )
+ )["flow"]
assert flow["intent"] == "reauth"
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
@@ -1826,7 +1868,7 @@ def test_hub_reauth_replaces_pending_flow_unknown_to_restarted_adapter(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- first = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ first = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
async def restarted_adapter_does_not_know_flow(_flow_id):
raise RuntimeError("OAuth flow is unknown after restart")
@@ -1842,7 +1884,7 @@ def test_hub_reauth_replaces_pending_flow_unknown_to_restarted_adapter(
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
)
- second = asyncio.run(restarted.reauth_source(source.id, {}))["flow"]
+ second = asyncio.run(restarted.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
assert first["flow_id"] in adapter.flows
assert second["flow_id"] in restarted_adapter.flows
@@ -1880,7 +1922,7 @@ def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -1919,7 +1961,7 @@ def test_completed_hub_reauth_blocks_recovery_before_discovery(tmp_path):
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -1991,7 +2033,7 @@ def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = (await service.reauth_source(source.id, {}))["flow"]
+ flow = (await service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -2062,7 +2104,7 @@ def test_hub_reauth_irreversible_dispositions_fail_closed(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -2137,7 +2179,7 @@ def test_failed_hub_reauth_non_owned_material_preserves_prior_state(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -2191,7 +2233,7 @@ def test_failed_hub_reauth_orphan_is_journaled_and_retried_by_ref(tmp_path):
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -2492,7 +2534,7 @@ def test_hub_reauth_retry_materializes_pending_flow(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- first = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ first = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[first["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[first["flow_id"]].__dict__,
@@ -2504,7 +2546,7 @@ def test_hub_reauth_retry_materializes_pending_flow(
}
)
- second = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ second = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
persisted = store.config.sources[0]
assert [model.id for model in persisted.models] == ["manual-model"]
@@ -2541,7 +2583,7 @@ def test_hub_reauth_returns_terminal_tail_when_registry_completion_fails(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -2596,7 +2638,7 @@ def test_failed_same_handle_hub_reauth_requires_user_action(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -2743,7 +2785,7 @@ def test_failed_hub_reauth_preserves_prior_source_and_revokes_replacement(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -2800,7 +2842,7 @@ def test_completed_hub_reauth_revokes_replacement_after_source_disappears(
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
asyncio.run(service.delete_source(source.id, force=True))
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
@@ -2843,7 +2885,7 @@ def test_failed_hub_reauth_rolls_back_when_old_journal_cleanup_fails(tmp_path):
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -3143,6 +3185,141 @@ def test_failed_oauth_cancel_keeps_flow_retryable(tmp_path):
assert adapter.cancelled == [flow_id, flow_id]
+def test_nonce_oauth_start_replays_cancelled_flow_until_expiry(tmp_path):
+ current = [datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc)]
+ store = MemoryStore()
+ adapter = FakeAdapter()
+ service = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ native_oauth_adapter=adapter,
+ oauth_flows=OAuthFlowRegistry(
+ tmp_path / "oauth_flows.json",
+ now=lambda: current[0],
+ ),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ now=lambda: current[0],
+ requested_model_override=store.requested_model,
+ )
+ request = {
+ "vendor": "anthropic",
+ "channel": "native_cli",
+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",
+ }
+
+ first = asyncio.run(service.oauth_start(request))["flow"]
+ asyncio.run(service.oauth_cancel(first["flow_id"]))
+ retained = asyncio.run(service.oauth_start(request))["flow"]
+
+ assert retained == {
+ **first,
+ "state": "cancelled",
+ "presentation": {
+ "auth_url": None,
+ "device_code": None,
+ "expects": "none",
+ "instructions_key": None,
+ },
+ }
+ assert retained["expires_at"] == first["expires_at"]
+ assert adapter.oauth_start_calls == [
+ (first["source_id"], "anthropic")
+ ]
+
+ current[0] = datetime(2026, 7, 23, 4, 15, tzinfo=timezone.utc)
+ fresh = asyncio.run(service.oauth_start(request))["flow"]
+
+ assert fresh["flow_id"] != first["flow_id"]
+ assert len(adapter.oauth_start_calls) == 2
+
+
+def test_nonce_oauth_start_coalesces_provider_failure_then_retries(tmp_path):
+ async def run_failure_and_retry():
+ service, _, adapter = _service(tmp_path)
+ request = {
+ "vendor": "anthropic",
+ "channel": "native_cli",
+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",
+ }
+ provider_started = asyncio.Event()
+ release_provider = asyncio.Event()
+ original_start = adapter.start_oauth
+ provider_calls = 0
+
+ async def failing_start(source_id, vendor):
+ nonlocal provider_calls
+ provider_calls += 1
+ provider_started.set()
+ await release_provider.wait()
+ raise RuntimeError("provider start failed")
+
+ adapter.start_oauth = failing_start
+ first = asyncio.create_task(service.oauth_start(request))
+ await provider_started.wait()
+ second = asyncio.create_task(service.oauth_start(dict(request)))
+ await asyncio.sleep(0)
+ assert second.done() is False
+ release_provider.set()
+ results = await asyncio.gather(first, second, return_exceptions=True)
+
+ assert all(isinstance(result, ModelHubError) for result in results)
+ assert [result.code for result in results] == [
+ "engine_down",
+ "engine_down",
+ ]
+ assert provider_calls == 1
+
+ adapter.start_oauth = original_start
+ fresh = await service.oauth_start(request)
+ return fresh, provider_calls, adapter
+
+ fresh, failed_calls, adapter = asyncio.run(run_failure_and_retry())
+
+ assert fresh["flow"]["client_nonce"] == "ofn_01j5w8z7p4n6q2rt"
+ assert failed_calls == 1
+ assert len(adapter.oauth_start_calls) == 1
+
+
+def test_nonce_oauth_start_owner_cancellation_releases_waiter_and_tuple(tmp_path):
+ async def run_cancellation_and_retry():
+ service, _, adapter = _service(tmp_path)
+ request = {
+ "vendor": "anthropic",
+ "channel": "native_cli",
+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",
+ }
+ provider_started = asyncio.Event()
+ original_start = adapter.start_oauth
+ provider_calls = 0
+
+ async def blocked_start(source_id, vendor):
+ nonlocal provider_calls
+ provider_calls += 1
+ provider_started.set()
+ await asyncio.Event().wait()
+
+ adapter.start_oauth = blocked_start
+ owner = asyncio.create_task(service.oauth_start(request))
+ await provider_started.wait()
+ waiter = asyncio.create_task(service.oauth_start(dict(request)))
+ await asyncio.sleep(0)
+ owner.cancel()
+ results = await asyncio.gather(owner, waiter, return_exceptions=True)
+
+ assert all(isinstance(result, asyncio.CancelledError) for result in results)
+ assert provider_calls == 1
+
+ adapter.start_oauth = original_start
+ fresh = await service.oauth_start(request)
+ return fresh, adapter
+
+ fresh, adapter = asyncio.run(run_cancellation_and_retry())
+
+ assert fresh["flow"]["client_nonce"] == "ofn_01j5w8z7p4n6q2rt"
+ assert len(adapter.oauth_start_calls) == 1
+
+
def test_cancel_materializes_terminal_successful_hub_reauth(tmp_path):
service, store, adapter = _service(tmp_path)
source = ModelHubSourceConfig(
@@ -3167,7 +3344,7 @@ def test_cancel_materializes_terminal_successful_hub_reauth(tmp_path):
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -3215,7 +3392,7 @@ def test_cancel_materializes_terminal_failed_hub_reauth(tmp_path):
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -3262,7 +3439,7 @@ def test_cancel_materializes_post_cancel_unknown_hub_reauth(tmp_path):
)
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
- flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]
+ flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,