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.

refactor(auth): unify native login flow ownership (#1417)

Call Whitef4e3ed5fbe6d
diff --git a/AGENTS.md b/AGENTS.md
index 0d464a2ee..ed0902c5d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -40,6 +40,11 @@ Decision checklist before writing code:
- `main.py` - entry point wiring `config.V2Config` into `core/controller.py`
- `core/controller.py` - orchestration and dependency wiring
+- `vibe/ui_server.py` and `vibe/api.py` run in a separate process from the
+ controller and reach controller-owned state over the internal socket;
+ `vibe/api.py` builds its own `AgentAuthService`. In-memory registries therefore
+ cannot span IM and Web surfaces: cross-surface exclusion needs an explicit IPC
+ hop or a documented per-instance scope. See PR #1417's Known-by-design ledger.
- `core/handlers/` - platform/backend-agnostic business workflows
- `core/message_dispatcher.py` - outbound message routing and reply enhancement flow
- `core/reply_enhancer.py` - file-link and quick-reply prompt injection helpers
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 016d290cb..5db5c08da 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -12,7 +12,8 @@ import signal
import time
import uuid
from dataclasses import dataclass, field
-from typing import Any, Callable, Optional
+from datetime import datetime, timedelta, timezone
+from typing import Any, Callable, Coroutine, Optional
from core.backend_failure import terminal_backend_failure_output
from core.delivery_evidence import DeliveryEvidence, STAGE_PERSIST, STAGE_SEND
@@ -61,6 +62,26 @@ CLAUDE_PROBE_DISCONNECT_TIMEOUT_SECONDS = 3.0
CLAUDE_PROBE_PROCESS_EXIT_GRACE_SECONDS = 0.2
+class BackendLoginInProgressError(RuntimeError):
+ """Raised when a native credential already has a live login owner."""
+
+ code = "native_login_in_progress"
+
+ def __init__(
+ self,
+ vendor: str,
+ backend: str,
+ *,
+ owner_ref: str | None = None,
+ flow_id: str | None = None,
+ ) -> None:
+ self.vendor = vendor
+ self.backend = backend
+ self.owner_ref = owner_ref
+ self.flow_id = flow_id
+ super().__init__(self.code)
+
+
def _pick_probe_response_excerpt(stdout_text: str) -> str:
"""Return the first content-bearing line from a backend probe response.
@@ -307,8 +328,8 @@ class AgentAuthFlow:
initiator_user_id: str
context: MessageContext
process: asyncio.subprocess.Process | None
- reader_task: asyncio.Task[None]
- waiter_task: asyncio.Task[None]
+ reader_task: asyncio.Task[None] | None
+ waiter_task: asyncio.Task[None] | None
claude_client: ClaudeSDKClient | None = None
pty_master_fd: int | None = None
awaiting_code: bool = False
@@ -320,6 +341,8 @@ class AgentAuthFlow:
last_status_text: str | None = None
force_oauth: bool = False
claude_oauth_attempt: "ClaudeOAuthAttempt | None" = None
+ native_cli: bool = False
+ expires_at_iso: str | None = None
@property
def flow_key(self) -> str:
@@ -382,6 +405,37 @@ class WebAuthFlow:
# TTL so the dict doesn't grow unboundedly across sign-in
# attempts on a long-lived UI server.
terminal_at: float | None = None
+ # Shared flow metadata used by IM, Web Settings, and Model Hub callers.
+ # Keeping the binding on the owning flow avoids a second Model Hub runtime
+ # registry keyed by the same flow id.
+ source_id: str | None = None
+ vendor: str | None = None
+ expires_at_iso: str | None = None
+ source_signed_in: bool | None = None
+ source_account_label: str | None = None
+ native_cli: bool = False
+
+
+class AuthFlowRegistry:
+ """Single in-memory registry for every IM and Web auth flow.
+
+ ``by_key`` is an IM lookup index; ``by_id`` is the owning flow collection.
+ Web and Model Hub callers use the same ``by_id`` records as IM setup.
+ """
+
+ def __init__(self) -> None:
+ self.by_key: dict[str, AgentAuthFlow] = {}
+ self.by_id: dict[str, AgentAuthFlow | WebAuthFlow] = {}
+
+ def put(self, flow: AgentAuthFlow | WebAuthFlow, *, flow_key: str | None = None) -> None:
+ self.by_id[flow.flow_id] = flow
+ if flow_key is not None:
+ self.by_key[flow_key] = flow
+
+ def drop(self, flow: AgentAuthFlow | WebAuthFlow) -> None:
+ self.by_id.pop(flow.flow_id, None)
+ if isinstance(flow, AgentAuthFlow) and self.by_key.get(flow.flow_key) is flow:
+ self.by_key.pop(flow.flow_key, None)
class AgentAuthService:
@@ -389,14 +443,9 @@ class AgentAuthService:
def __init__(self, controller):
self.controller = controller
- self._flows: dict[str, AgentAuthFlow] = {}
- self._flows_by_id: dict[str, AgentAuthFlow] = {}
+ self._flow_registry = AuthFlowRegistry()
self._flow_lock = asyncio.Lock()
self.setup_timeout_seconds = 900.0
- # Web-initiated OAuth flows are keyed by ``flow_id`` only; no IM
- # context exists for them, so they cannot live in ``_flows``.
- self._web_flows: dict[str, WebAuthFlow] = {}
- self._web_flow_lock = asyncio.Lock()
self._claude_oauth_attempt_counter = 0
self._claude_oauth_batch: ClaudeOAuthBatch | None = None
self._claude_oauth_lock = asyncio.Lock()
@@ -408,13 +457,23 @@ class AgentAuthService:
# and runs in a worker thread to avoid blocking the auth event loop.
self._post_web_success_hook: Optional[Any] = None
+ @property
+ def _flows(self) -> dict[str, AgentAuthFlow]:
+ """Compatibility view of the IM lookup index."""
+ return self._flow_registry.by_key
+
+ @property
+ def _flows_by_id(self) -> dict[str, AgentAuthFlow | WebAuthFlow]:
+ return self._flow_registry.by_id
+
+ @property
+ def _web_flows(self) -> dict[str, AgentAuthFlow | WebAuthFlow]:
+ """Compatibility view; Web and IM flows share one registry by id."""
+ return self._flow_registry.by_id
+
def _active_claude_auth_clients(self) -> list[Any]:
clients: list[Any] = []
- for flow in list(self._flows.values()):
- if flow.backend != "claude" or flow.claude_client is None:
- continue
- clients.append(flow.claude_client)
- for flow in list(self._web_flows.values()):
+ for flow in self._flows_by_id.values():
if flow.backend != "claude" or flow.claude_client is None:
continue
clients.append(flow.claude_client)
@@ -720,114 +779,52 @@ class AgentAuthService:
await self._prompt_claude_login_method(context)
return
- async with self._flow_lock:
- flow_key = self._make_flow_key(context, resolved_backend)
- existing = self._flows.get(flow_key)
- if existing:
- await self._terminate_flow(existing)
+ await self._send_message(
+ context,
+ f"⏳ {self._t('command.setup.starting', backend=resolved_backend)}",
+ )
+ try:
+ flow = await self._start_auth_flow(
+ resolved_backend,
+ context=context,
+ force_reset=force_reset,
+ claude_login_method=claude_login_method,
+ )
+ except BackendLoginInProgressError as err:
+ logger.info(
+ "Agent auth setup already in progress for %s/%s",
+ err.vendor,
+ err.backend,
+ )
+ await self._send_setup_start_failure(
+ context,
+ resolved_backend,
+ self._t(
+ "command.setup.loginInProgress",
+ vendor=err.vendor,
+ backend=resolved_backend,
+ ),
+ )
+ return
+ except Exception as err: # noqa: BLE001
+ logger.error("Agent auth setup failed to start for %s: %s", resolved_backend, err, exc_info=True)
+ await self._send_setup_start_failure(context, resolved_backend, str(err))
+ return
+ if resolved_backend == "claude":
await self._send_message(
context,
- f"⏳ {self._t('command.setup.starting', backend=resolved_backend)}",
+ self._t("command.setup.claudeInstructions", url=flow.url),
+ )
+ elif resolved_backend == "opencode" and not flow.native_cli:
+ await self._send_message(
+ context,
+ self._t(
+ "command.setup.opencodeInstructions",
+ provider=flow.provider or "opencode",
+ url=flow.url or self._get_opencode_setup_url(flow.provider),
+ ),
)
-
- try:
- if resolved_backend == "codex":
- process = await self._start_codex_process(force_reset=force_reset)
- flow = AgentAuthFlow(
- flow_id=uuid.uuid4().hex[:12],
- backend=resolved_backend,
- settings_key=self._get_settings_key(context),
- initiator_user_id=context.user_id,
- context=context,
- process=process,
- reader_task=asyncio.create_task(asyncio.sleep(0)),
- waiter_task=asyncio.create_task(asyncio.sleep(0)),
- )
- elif resolved_backend == "claude":
- client, manual_url, attempt = await self._start_claude_control_flow(
- context,
- force_reset=force_reset,
- login_with_claude_ai=claude_login_method != "console",
- )
- flow = AgentAuthFlow(
- flow_id=uuid.uuid4().hex[:12],
- backend=resolved_backend,
- settings_key=self._get_settings_key(context),
- initiator_user_id=context.user_id,
- context=context,
- process=None,
- reader_task=asyncio.create_task(asyncio.sleep(0)),
- waiter_task=asyncio.create_task(asyncio.sleep(0)),
- claude_client=client,
- login_prompt_sent=True,
- url=manual_url,
- claude_oauth_attempt=attempt,
- )
- else:
- provider = await self._resolve_opencode_provider(context)
- if self._supports_direct_opencode_api_key_setup(provider):
- flow = AgentAuthFlow(
- flow_id=uuid.uuid4().hex[:12],
- backend=resolved_backend,
- settings_key=self._get_settings_key(context),
- initiator_user_id=context.user_id,
- context=context,
- process=None,
- reader_task=asyncio.create_task(asyncio.sleep(0)),
- waiter_task=asyncio.create_task(asyncio.sleep(0)),
- provider=provider,
- awaiting_code=True,
- login_prompt_sent=True,
- code_prompt_sent=True,
- url=self._get_opencode_setup_url(provider),
- )
- else:
- process, master_fd, provider = await self._start_opencode_process(context, force_reset=force_reset)
- flow = AgentAuthFlow(
- flow_id=uuid.uuid4().hex[:12],
- backend=resolved_backend,
- settings_key=self._get_settings_key(context),
- initiator_user_id=context.user_id,
- context=context,
- process=process,
- reader_task=asyncio.create_task(asyncio.sleep(0)),
- waiter_task=asyncio.create_task(asyncio.sleep(0)),
- pty_master_fd=master_fd,
- provider=provider,
- )
- except Exception as err: # noqa: BLE001
- logger.error("Agent auth setup failed to start for %s: %s", resolved_backend, err, exc_info=True)
- await self._send_setup_start_failure(context, resolved_backend, str(err))
- return
-
- self._flows[flow_key] = flow
- self._flows_by_id[flow.flow_id] = flow
- if resolved_backend == "codex":
- flow.reader_task = asyncio.create_task(self._read_codex_output(process, context, resolved_backend))
- flow.waiter_task = asyncio.create_task(self._wait_for_completion(flow))
- elif resolved_backend == "claude":
- flow.waiter_task = asyncio.create_task(self._wait_for_claude_completion(flow))
- await self._send_message(
- flow.context,
- self._t("command.setup.claudeInstructions", url=manual_url),
- )
- else:
- if self._supports_direct_opencode_api_key_setup(flow.provider):
- await self._send_message(
- flow.context,
- self._t(
- "command.setup.opencodeInstructions",
- provider=flow.provider or "opencode",
- url=flow.url or self._get_opencode_setup_url(flow.provider),
- ),
- )
- else:
- assert flow.pty_master_fd is not None
- flow.reader_task = asyncio.create_task(
- self._read_pty_output(process, flow.pty_master_fd, context, resolved_backend)
- )
- flow.waiter_task = asyncio.create_task(self._wait_for_completion(flow))
async def submit_code(self, context: MessageContext, code: str, backend_hint: str | None = None) -> None:
"""Submit follow-up code to an active auth flow."""
@@ -1077,6 +1074,186 @@ class AgentAuthService:
fallback_text = self._t("command.setup.claudeMethodFallback")
await self._send_message_with_keyboard(context, text, keyboard, fallback_text=fallback_text)
+ @staticmethod
+ def _native_vendor_for_flow(backend: str, provider: str | None = None) -> str:
+ if backend == "codex":
+ return "openai"
+ if backend == "claude":
+ return "anthropic"
+ return (provider or "opencode").strip().lower()
+
+ def _claim_shared_native_flow(
+ self,
+ backend: str,
+ *,
+ provider: str | None = None,
+ owner_ref: str | None = None,
+ ) -> None:
+ """Claim the one shared native-login path before any provider spawn."""
+ vendor = self._native_vendor_for_flow(backend, provider)
+ for flow in self._flows_by_id.values():
+ if (
+ getattr(flow, "native_cli", False)
+ and getattr(flow, "state", "starting") not in {"success", "failed", "cancelled"}
+ and flow.backend == backend
+ and (backend != "opencode" or flow.provider == provider)
+ ):
+ raise BackendLoginInProgressError(
+ vendor,
+ backend,
+ owner_ref=getattr(flow, "source_id", None),
+ flow_id=flow.flow_id,
+ )
+
+ def _arm_flow_waiter(
+ self,
+ flow: AgentAuthFlow | WebAuthFlow,
+ waiter: Coroutine[Any, Any, None],
+ ) -> None:
+ """Publish and enforce one deadline from the waiter's start boundary."""
+ flow.expires_at_iso = (
+ datetime.now(timezone.utc) + timedelta(seconds=self.setup_timeout_seconds)
+ ).isoformat()
+ flow.waiter_task = asyncio.create_task(waiter)
+
+ def _remaining_flow_timeout(self, flow: AgentAuthFlow | WebAuthFlow) -> float:
+ """Return the time left on the deadline advertised by this flow."""
+ if flow.expires_at_iso is None:
+ return self.setup_timeout_seconds
+ try:
+ expires_at = datetime.fromisoformat(flow.expires_at_iso)
+ return max(
+ 0.0,
+ (expires_at - datetime.now(timezone.utc)).total_seconds(),
+ )
+ except (TypeError, ValueError):
+ return self.setup_timeout_seconds
+
+ async def _start_auth_flow(
+ self,
+ backend: str,
+ *,
+ context: MessageContext | None = None,
+ provider_id: str | None = None,
+ force_reset: bool = True,
+ owner_ref: str | None = None,
+ claude_login_method: str | None = None,
+ on_irreversible_start: Callable[[], Callable[[], None] | None] | None = None,
+ ) -> AgentAuthFlow | WebAuthFlow:
+ """Create and start the shared native-login flow used by every caller."""
+ if backend not in self.WEB_BACKENDS:
+ raise ValueError(f"unsupported_backend:{backend}")
+ flow_key = self._make_flow_key(context, backend) if context is not None else None
+ async with self._flow_lock:
+ if flow_key is not None:
+ existing = self._flows.get(flow_key)
+ if existing is not None:
+ await self._terminate_flow(existing)
+
+ provider = provider_id
+ if backend == "opencode" and context is not None:
+ provider = await self._resolve_opencode_provider(context)
+ native_cli = backend != "opencode" or not (
+ context is not None and self._supports_direct_opencode_api_key_setup(provider)
+ )
+ if native_cli:
+ self._claim_shared_native_flow(
+ backend,
+ provider=provider,
+ owner_ref=owner_ref,
+ )
+
+ flow_id = uuid.uuid4().hex[:12]
+ if context is None:
+ flow: AgentAuthFlow | WebAuthFlow = WebAuthFlow(
+ flow_id=flow_id,
+ backend=backend,
+ provider=provider,
+ source_id=owner_ref,
+ vendor=self._native_vendor_for_flow(backend, provider),
+ native_cli=native_cli,
+ )
+ else:
+ flow = AgentAuthFlow(
+ flow_id=flow_id,
+ backend=backend,
+ settings_key=self._get_settings_key(context),
+ initiator_user_id=context.user_id,
+ context=context,
+ process=None,
+ reader_task=None,
+ waiter_task=None,
+ provider=provider,
+ native_cli=native_cli,
+ )
+ self._flow_registry.put(flow, flow_key=flow_key)
+ try:
+ if backend == "codex":
+ if on_irreversible_start is None:
+ process = await self._start_codex_process(force_reset=force_reset)
+ else:
+ process = await self._start_codex_process(
+ force_reset=force_reset,
+ on_irreversible_start=on_irreversible_start,
+ )
+ flow.process = process
+ if context is None:
+ flow.reader_task = asyncio.create_task(self._read_codex_output_web(flow))
+ self._arm_flow_waiter(
+ flow,
+ self._wait_for_codex_completion_web(flow),
+ )
+ else:
+ flow.reader_task = asyncio.create_task(self._read_codex_output(process, context, backend))
+ self._arm_flow_waiter(flow, self._wait_for_completion(flow))
+ elif backend == "claude":
+ claude_kwargs = {
+ "force_reset": force_reset,
+ "login_with_claude_ai": claude_login_method != "console",
+ }
+ if on_irreversible_start is not None:
+ claude_kwargs["on_irreversible_start"] = on_irreversible_start
+ client, manual_url, attempt = await self._start_claude_control_flow(
+ context,
+ **claude_kwargs,
+ )
+ flow.claude_client = client
+ flow.claude_oauth_attempt = attempt
+ flow.url = manual_url
+ flow.awaiting_code = True
+ flow.login_prompt_sent = True
+ flow.state = "awaiting_code"
+ self._arm_flow_waiter(
+ flow,
+ self._wait_for_claude_completion_web(flow)
+ if context is None
+ else self._wait_for_claude_completion(flow),
+ )
+ else:
+ if context is not None and not native_cli:
+ flow.awaiting_code = True
+ flow.login_prompt_sent = True
+ flow.code_prompt_sent = True
+ flow.url = self._get_opencode_setup_url(provider)
+ elif context is None:
+ await self._start_opencode_oauth_web(flow, provider_id or provider or "opencode")
+ else:
+ process, master_fd, provider = await self._start_opencode_process(
+ context,
+ force_reset=force_reset,
+ )
+ flow.process = process
+ flow.pty_master_fd = master_fd
+ flow.provider = provider
+ flow.reader_task = asyncio.create_task(
+ self._read_pty_output(process, master_fd, context, backend)
+ )
+ self._arm_flow_waiter(flow, self._wait_for_completion(flow))
+ except BaseException:
+ self._flow_registry.drop(flow)
+ raise
+ return flow
+
async def _start_codex_process(
self,
*,
@@ -1487,8 +1664,12 @@ class AgentAuthService:
async def _wait_for_completion(self, flow: AgentAuthFlow) -> None:
try:
assert flow.process is not None
- await asyncio.wait_for(flow.process.wait(), timeout=self.setup_timeout_seconds)
- await flow.reader_task
+ await asyncio.wait_for(
+ flow.process.wait(),
+ timeout=self._remaining_flow_timeout(flow),
+ )
+ if flow.reader_task is not None:
+ await flow.reader_task
ok, detail = await self._verify_login(flow)
if ok:
if flow.backend == "codex":
@@ -1532,13 +1713,14 @@ class AgentAuthService:
if flow.claude_client is None:
raise RuntimeError("Claude auth flow is missing its SDK client")
+ timeout = self._remaining_flow_timeout(flow)
await asyncio.wait_for(
self._send_claude_control_request(
flow.claude_client,
{"subtype": "claude_oauth_wait_for_completion"},
- timeout=self.setup_timeout_seconds,
+ timeout=timeout,
),
- timeout=self.setup_timeout_seconds,
+ timeout=timeout,
)
flow.force_oauth = True
ok, detail = await self._verify_login(flow)
@@ -1984,9 +2166,7 @@ class AgentAuthService:
await flow.process.wait()
def _drop_flow(self, flow: AgentAuthFlow) -> None:
- if self._flows.get(flow.flow_key) is flow:
- self._flows.pop(flow.flow_key, None)
- self._flows_by_id.pop(flow.flow_id, None)
+ self._flow_registry.drop(flow)
# ------------------------------------------------------------------
# Web Settings → Backends OAuth flows
@@ -2019,6 +2199,7 @@ class AgentAuthService:
*,
force_reset: bool = True,
provider_id: Optional[str] = None,
+ owner_ref: str | None = None,
on_irreversible_start: Callable[
[], Callable[[], None] | None
] | None = None,
@@ -2038,46 +2219,39 @@ class AgentAuthService:
"""
if backend not in self.WEB_BACKENDS:
raise ValueError(f"unsupported_backend:{backend}")
-
- flow_id = uuid.uuid4().hex[:12]
- flow = WebAuthFlow(flow_id=flow_id, backend=backend, state="starting")
- if backend == "opencode":
- flow.provider = provider_id
-
- async with self._web_flow_lock:
- self._web_flows[flow_id] = flow
-
+ if backend == "opencode" and (not isinstance(provider_id, str) or not provider_id.strip()):
+ flow = WebAuthFlow(
+ flow_id=uuid.uuid4().hex[:12],
+ backend=backend,
+ state="failed",
+ error="opencode_provider_id_required",
+ )
+ self._flow_registry.put(flow)
+ return flow
try:
- if backend == "codex":
- flow.process = await self._start_codex_process(
- force_reset=force_reset,
- on_irreversible_start=on_irreversible_start,
- )
- flow.reader_task = asyncio.create_task(self._read_codex_output_web(flow))
- flow.waiter_task = asyncio.create_task(self._wait_for_codex_completion_web(flow))
- elif backend == "claude":
- client, manual_url, attempt = await self._start_claude_control_flow(
- context=None,
- force_reset=force_reset,
- login_with_claude_ai=True,
- on_irreversible_start=on_irreversible_start,
- )
- flow.claude_client = client
- flow.claude_oauth_attempt = attempt
- flow.url = manual_url
- flow.awaiting_code = True
- flow.state = "awaiting_code"
- flow.waiter_task = asyncio.create_task(self._wait_for_claude_completion_web(flow))
- else: # opencode
- if not isinstance(provider_id, str) or not provider_id.strip():
- raise ValueError("opencode_provider_id_required")
- await self._start_opencode_oauth_web(flow, provider_id.strip())
+ flow = await self._start_auth_flow(
+ backend,
+ provider_id=provider_id,
+ force_reset=force_reset,
+ owner_ref=owner_ref,
+ on_irreversible_start=on_irreversible_start,
+ )
+ except asyncio.CancelledError:
+ raise
+ except BackendLoginInProgressError:
+ raise
except Exception as err: # noqa: BLE001
logger.error("Web auth start failed for %s: %s", backend, err, exc_info=True)
- if backend == "claude":
- await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)
- flow.state = "failed"
- flow.error = str(err)
+ flow = WebAuthFlow(
+ flow_id=uuid.uuid4().hex[:12],
+ backend=backend,
+ provider=provider_id,
+ source_id=owner_ref,
+ vendor=self._native_vendor_for_flow(backend, provider_id),
+ state="failed",
+ error=str(err),
+ )
+ self._flow_registry.put(flow)
return flow
async def submit_web_code(self, flow_id: str, code: str) -> dict[str, Any]:
@@ -2132,6 +2306,8 @@ class AgentAuthService:
now = time.time()
stale: list[str] = []
for fid, flow in self._web_flows.items():
+ if not isinstance(flow, WebAuthFlow):
+ continue
if flow.state not in self._WEB_FLOW_TERMINAL_STATES:
continue
if flow.terminal_at is None:
@@ -2157,7 +2333,7 @@ class AgentAuthService:
and flow.terminal_at is None
):
flow.terminal_at = time.time()
- return {
+ result = {
"ok": True,
"flow_id": flow_id,
"backend": flow.backend,
@@ -2167,6 +2343,36 @@ class AgentAuthService:
"awaiting_code": flow.awaiting_code,
"error": flow.error,
}
+ if any(
+ getattr(flow, name, None) is not None
+ for name in ("source_id", "vendor", "expires_at_iso")
+ ):
+ result.update(
+ {
+ "source_id": getattr(flow, "source_id", None),
+ "vendor": getattr(flow, "vendor", None),
+ "expires_at_iso": getattr(flow, "expires_at_iso", None),
+ "source_status": {
+ "signed_in": getattr(flow, "source_signed_in", None),
+ "account_label": getattr(flow, "source_account_label", None),
+ },
+ }
+ )
+ return result
+
+ def set_flow_source_status(
+ self,
+ flow_id: str,
+ *,
+ signed_in: bool,
+ account_label: str | None,
+ ) -> None:
+ """Attach non-secret source metadata to the owning shared flow."""
+ flow = self._flows_by_id.get(flow_id)
+ if not isinstance(flow, WebAuthFlow):
+ raise KeyError(flow_id)
+ flow.source_signed_in = signed_in
+ flow.source_account_label = account_label
async def remove_web_auth(self, backend: str) -> dict[str, Any]:
"""Drop the stored credentials for a Claude/Codex backend.
@@ -2904,11 +3110,15 @@ class AgentAuthService:
await server.mark_run_inactive(session_id)
async def cancel_web_flow(self, flow_id: str) -> dict[str, Any]:
- async with self._web_flow_lock:
- flow = self._web_flows.pop(flow_id, None)
+ async with self._flow_lock:
+ flow = self._web_flows.get(flow_id)
if flow is None:
return {"ok": False, "error": "flow_not_found"}
- await self._terminate_web_flow(flow, final_state="cancelled")
+ try:
+ await self._terminate_web_flow(flow, final_state="cancelled")
+ finally:
+ async with self._flow_lock:
+ self._flow_registry.drop(flow)
return {"ok": True}
async def _opencode_server(self):
@@ -3009,16 +3219,16 @@ class AgentAuthService:
flow.last_status_text = instructions
flow.state = "awaiting_code"
# OpenCode auto-detects completion (device poll or local callback);
- # no user-submitted code to enter. The waiter long-polls the
- # daemon's /callback endpoint and flips ``state`` when done.
+ # no user-submitted code to enter. The waiter long-polls the daemon.
flow.awaiting_code = False
- flow.waiter_task = asyncio.create_task(
+ self._arm_flow_waiter(
+ flow,
self._wait_for_opencode_oauth_web(
flow,
provider_id,
method_index,
prompt_answers,
- )
+ ),
)
async def _submit_opencode_callback_url(self, flow: WebAuthFlow, code: str) -> dict[str, Any]:
@@ -3082,7 +3292,7 @@ class AgentAuthService:
provider_id,
method=method_index,
prompt_answers=prompt_answers,
- timeout=self.setup_timeout_seconds,
+ timeout=self._remaining_flow_timeout(flow),
)
flow.state = "verifying"
# OpenCode persists into auth.json itself. Clear any Vibe-managed
@@ -3104,7 +3314,6 @@ class AgentAuthService:
)
flow.state = "failed"
flow.error = str(err)
-
async def _read_codex_output_web(self, flow: WebAuthFlow) -> None:
"""Parse ``codex login --device-auth`` stdout for URL + device code.
@@ -3140,7 +3349,10 @@ class AgentAuthService:
async def _wait_for_codex_completion_web(self, flow: WebAuthFlow) -> None:
try:
assert flow.process is not None
- await asyncio.wait_for(flow.process.wait(), timeout=self.setup_timeout_seconds)
+ await asyncio.wait_for(
+ flow.process.wait(),
+ timeout=self._remaining_flow_timeout(flow),
+ )
if flow.reader_task and not flow.reader_task.done():
try:
await flow.reader_task
@@ -3181,18 +3393,18 @@ class AgentAuthService:
logger.error("Web Codex auth flow failed: %s", err, exc_info=True)
flow.state = "failed"
flow.error = str(err)
-
async def _wait_for_claude_completion_web(self, flow: WebAuthFlow) -> None:
try:
if flow.claude_client is None:
raise RuntimeError("missing_sdk_client")
+ timeout = self._remaining_flow_timeout(flow)
await asyncio.wait_for(
self._send_claude_control_request(
flow.claude_client,
{"subtype": "claude_oauth_wait_for_completion"},
- timeout=self.setup_timeout_seconds,
+ timeout=timeout,
),
- timeout=self.setup_timeout_seconds,
+ timeout=timeout,
)
flow.state = "verifying"
ok, detail = await self._verify_web_login(
diff --git a/core/handlers/model_hub/native_oauth.py b/core/handlers/model_hub/native_oauth.py
index 773f816d5..ce2f6d98c 100644
--- a/core/handlers/model_hub/native_oauth.py
+++ b/core/handlers/model_hub/native_oauth.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import asyncio
import re
from dataclasses import dataclass
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timezone
from typing import Any, Callable, Mapping, Protocol
from .adapter import OAuthFlowState, RetainedMaterialDisposition
@@ -19,7 +19,6 @@ _INSTRUCTIONS_KEYS = {
}
_TIMEOUT_ERROR_KEY = "settings.models.oauth.error.timeout"
_GENERIC_ERROR_KEY = "settings.models.oauth.error.generic"
-_MAX_FLOWS = 100
class AgentAuthService(Protocol):
@@ -30,6 +29,7 @@ class AgentAuthService(Protocol):
backend: str,
*,
force_reset: bool = True,
+ owner_ref: str | None = None,
on_irreversible_start: Callable[
[], Callable[[], None] | None
] | None = None,
@@ -41,14 +41,13 @@ class AgentAuthService(Protocol):
async def cancel_web_flow(self, flow_id: str) -> dict[str, Any]: ...
-
-@dataclass
-class _FlowBinding:
- source_id: str
- vendor: str
- backend: str
- expires_at_iso: str
- source_status: NativeOAuthSourceStatus | None = None
+ def set_flow_source_status(
+ self,
+ flow_id: str,
+ *,
+ signed_in: bool,
+ account_label: str | None,
+ ) -> None: ...
def _utc_now() -> datetime:
@@ -126,7 +125,6 @@ class AgentAuthNativeOAuthAdapter:
self._agent_auth_service = agent_auth_service
self._auth_status_reader = auth_status_reader
self._now = now
- self._flows: dict[str, _FlowBinding] = {}
async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:
return await self._start_oauth(
@@ -168,41 +166,31 @@ class AgentAuthNativeOAuthAdapter:
flow = await self._agent_auth_service.start_web_setup(
backend,
force_reset=force_reset,
+ owner_ref=source_id,
on_irreversible_start=on_irreversible_start,
)
flow_id = getattr(flow, "flow_id", None)
if not isinstance(flow_id, str) or not flow_id:
raise NativeOAuthUnavailableError
- expires_at = self._now() + timedelta(seconds=self._agent_auth_service.setup_timeout_seconds)
- self._remember(
- flow_id,
- _FlowBinding(
- source_id=source_id,
- vendor=vendor,
- backend=backend,
- expires_at_iso=expires_at.isoformat(),
- ),
- )
return await self._state_from_payload(flow_id, self._flow_payload(flow))
async def oauth_status(self, flow_id: str) -> OAuthFlowState:
- binding = self._binding(flow_id)
payload = self._agent_auth_service.get_web_flow_status(flow_id)
if payload.get("ok") is not True:
if payload.get("error") == "flow_not_found":
- self._flows.pop(flow_id, None)
raise KeyError(flow_id)
raise NativeOAuthUnavailableError
- return await self._state_from_payload(flow_id, payload, binding=binding)
+ return await self._state_from_payload(flow_id, payload)
async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:
- binding = self._binding(flow_id)
- if binding.vendor != "anthropic":
+ current = self._agent_auth_service.get_web_flow_status(flow_id)
+ if current.get("ok") is not True:
+ raise KeyError(flow_id)
+ if current.get("vendor") != "anthropic":
raise NativeOAuthUnavailableError
result = await self._agent_auth_service.submit_web_code(flow_id, value)
if result.get("ok") is not True:
if result.get("error") == "flow_not_found":
- self._flows.pop(flow_id, None)
raise KeyError(flow_id)
# AgentAuthService leaves malformed/failed Claude submissions
# retryable. Return its current declaration so the dialog stays on
@@ -211,32 +199,27 @@ class AgentAuthNativeOAuthAdapter:
return await self.oauth_status(flow_id)
async def cancel_oauth(self, flow_id: str) -> None:
- self._binding(flow_id)
result = await self._agent_auth_service.cancel_web_flow(flow_id)
if result.get("ok") is not True:
if result.get("error") == "flow_not_found":
- self._flows.pop(flow_id, None)
raise KeyError(flow_id)
raise NativeOAuthUnavailableError
- self._flows.pop(flow_id, None)
def completed_source_status(self, flow_id: str) -> NativeOAuthSourceStatus:
- status = self._binding(flow_id).source_status
- if status is None:
+ payload = self._agent_auth_service.get_web_flow_status(flow_id)
+ if payload.get("ok") is not True or payload.get("state") != "success":
raise KeyError(flow_id)
- return status
-
- def _binding(self, flow_id: str) -> _FlowBinding:
- try:
- return self._flows[flow_id]
- except KeyError:
- raise KeyError(flow_id) from None
-
- def _remember(self, flow_id: str, binding: _FlowBinding) -> None:
- self._flows.pop(flow_id, None)
- self._flows[flow_id] = binding
- while len(self._flows) > _MAX_FLOWS:
- self._flows.pop(next(iter(self._flows)))
+ status = payload.get("source_status")
+ if not isinstance(status, Mapping):
+ raise KeyError(flow_id)
+ signed_in = status.get("signed_in")
+ if not isinstance(signed_in, bool):
+ signed_in = True
+ account_label = status.get("account_label")
+ return NativeOAuthSourceStatus(
+ signed_in=signed_in,
+ account_label=account_label if isinstance(account_label, str) else None,
+ )
@staticmethod
def _flow_payload(flow: Any) -> dict[str, Any]:
@@ -247,16 +230,24 @@ class AgentAuthNativeOAuthAdapter:
"url": getattr(flow, "url", None),
"device_code": getattr(flow, "device_code", None),
"error": getattr(flow, "error", None),
+ "source_id": getattr(flow, "source_id", None),
+ "vendor": getattr(flow, "vendor", None),
+ "expires_at_iso": getattr(flow, "expires_at_iso", None),
+ "source_status": {
+ "signed_in": getattr(flow, "source_signed_in", None),
+ "account_label": getattr(flow, "source_account_label", None),
+ },
}
async def _state_from_payload(
self,
flow_id: str,
payload: Mapping[str, Any],
- *,
- binding: _FlowBinding | None = None,
) -> OAuthFlowState:
- binding = binding or self._binding(flow_id)
+ source_id = payload.get("source_id")
+ vendor = payload.get("vendor")
+ if not isinstance(source_id, str) or not isinstance(vendor, str):
+ raise KeyError(flow_id)
state = {
"awaiting_code": "awaiting_action",
"starting": "starting",
@@ -265,9 +256,20 @@ class AgentAuthNativeOAuthAdapter:
"failed": "failed",
"cancelled": "cancelled",
}.get(str(payload.get("state")), "failed")
- if state == "success" and binding.source_status is None:
- binding.source_status = await self._read_source_status(binding.backend)
-
+ source_status = payload.get("source_status")
+ if (
+ state == "success"
+ and (
+ not isinstance(source_status, Mapping)
+ or not isinstance(source_status.get("signed_in"), bool)
+ )
+ ):
+ resolved = await self._read_source_status(_VENDOR_BACKENDS[vendor])
+ self._agent_auth_service.set_flow_source_status(
+ flow_id,
+ signed_in=resolved.signed_in,
+ account_label=resolved.account_label,
+ )
error_key = None
if state == "failed":
error_key = _TIMEOUT_ERROR_KEY if payload.get("error") == "timed_out" else _GENERIC_ERROR_KEY
@@ -276,15 +278,19 @@ class AgentAuthNativeOAuthAdapter:
return OAuthFlowState(
flow_id=flow_id,
- source_id=binding.source_id,
- vendor=binding.vendor,
+ source_id=source_id,
+ vendor=vendor,
state=state,
auth_url=payload.get("url") if isinstance(payload.get("url"), str) else None,
device_code=(payload.get("device_code") if isinstance(payload.get("device_code"), str) else None),
- expects="paste_code" if binding.vendor == "anthropic" else "none",
- instructions_key=_INSTRUCTIONS_KEYS[binding.vendor],
+ expects="paste_code" if vendor == "anthropic" else "none",
+ instructions_key=_INSTRUCTIONS_KEYS[vendor],
error_key=error_key,
- expires_at_iso=binding.expires_at_iso,
+ expires_at_iso=(
+ payload.get("expires_at_iso")
+ if isinstance(payload.get("expires_at_iso"), str)
+ else self._now().isoformat()
+ ),
credential_ref=None,
channel="native_cli",
retained_material_disposition=RetainedMaterialDisposition.NONE,
@@ -297,9 +303,6 @@ class AgentAuthNativeOAuthAdapter:
if not isinstance(status, Mapping):
raise TypeError("invalid auth status")
except Exception: # noqa: BLE001
- # AgentAuthService reached success only after its own CLI status
- # probe. Preserve that verified signal when the display-status read
- # is temporarily unavailable; account identity can remain absent.
return NativeOAuthSourceStatus(signed_in=True, account_label=None)
return NativeOAuthSourceStatus(
signed_in=_signed_in(backend, status),
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 280a6ae6e..aa6d61056 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -32,6 +32,7 @@ from config.v2_config import (
normalize_model_hub_base_url,
normalize_model_hub_vendor_id,
)
+from core.agent_auth_service import BackendLoginInProgressError
from core.services.settings import default_config
from storage.db import get_cached_sqlite_engine
from storage.models import agent_sessions, messages
@@ -675,6 +676,12 @@ class ModelHubService:
raise ModelHubError("flow_not_found", status=404) from None
except (EngineUnavailableError, NativeOAuthUnavailableError):
raise ModelHubError("engine_down", status=503) from None
+ except BackendLoginInProgressError as error:
+ raise ModelHubError(
+ error.code,
+ status=409,
+ detail="modelHub.errors.native_login_in_progress",
+ ) from None
except ModelHubError:
raise
except Exception:
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 6d3f0c8bd..a8672714d 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1025,12 +1025,15 @@ Minimum v5 set:
`source_in_route_chain`,
`source_model_in_route_chain`, `mode_switch_blocked`, `engine_down`,
`runtime_platform_unsupported`, `reauth_confirmation_required`,
-`native_source_already_exists`,
+`native_source_already_exists`, `native_login_in_progress`,
`migration_item_conflict`, `turn_not_found`,
`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.
`native_source_already_exists` is an API-boundary refusal for native OAuth start;
its structured sibling is `{existing_source_id}` and the adapter is not invoked.
+`native_login_in_progress` is a distinct transient `409` from the shared native-login
+owner. It means another login currently owns the same credential; retry remains on the
+native channel and the response does not assert that a native Source already exists.
Boundary-only action-refusal values cover operations the UI already does not offer but
a script or regression can call directly. `reauth_confirmation_required` is API/test-
diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.py
index 4367a34e5..77b6ca21e 100644
--- a/tests/scenario_harness/model_hub_native_oauth.py
+++ b/tests/scenario_harness/model_hub_native_oauth.py
@@ -4,12 +4,12 @@ import uuid
from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
-from typing import Any
+from typing import Any, Mapping
from config.v2_config import ModelHubAgentSupplyConfig, ModelHubConfig
from core.handlers.model_hub.adapter import OAuthFlowState
from core.handlers.model_hub.events import BoundedEventLog
-from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter
+from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter, _account_label, _signed_in
from core.handlers.model_hub.oauth import OAuthFlowRegistry
from core.handlers.model_hub.revocations import CredentialRevocationJournal
from core.handlers.model_hub.service import ModelHubService, UnavailableEngineAdapter
@@ -43,6 +43,7 @@ class FakeAgentAuthService:
def __init__(self):
self.flows: dict[str, SimpleNamespace] = {}
+ self.auth_status: dict[str, Mapping[str, Any]] = {}
self.submissions: list[tuple[str, str]] = []
self.cancelled: list[str] = []
self.start_calls: list[tuple[str, bool]] = []
@@ -52,6 +53,7 @@ class FakeAgentAuthService:
backend: str,
*,
force_reset: bool = True,
+ owner_ref: str | None = None,
on_irreversible_start=None,
):
if force_reset and on_irreversible_start is not None:
@@ -65,6 +67,10 @@ class FakeAgentAuthService:
url=("https://claude.ai/oauth/authorize?test=true" if backend == "claude" else None),
device_code=None,
error=None,
+ source_id=owner_ref,
+ vendor={"claude": "anthropic", "codex": "openai"}.get(backend, "opencode"),
+ expires_at_iso="2026-07-25T00:15:00+00:00",
+ source_status={"signed_in": None, "account_label": None},
)
self.flows[flow_id] = flow
return flow
@@ -81,6 +87,10 @@ class FakeAgentAuthService:
"url": flow.url,
"device_code": flow.device_code,
"error": flow.error,
+ "source_id": flow.source_id,
+ "vendor": flow.vendor,
+ "expires_at_iso": flow.expires_at_iso,
+ "source_status": flow.source_status,
}
async def submit_web_code(self, flow_id: str, code: str) -> dict[str, Any]:
@@ -100,6 +110,18 @@ class FakeAgentAuthService:
self.cancelled.append(flow_id)
return {"ok": True}
+ def set_flow_source_status(
+ self,
+ flow_id: str,
+ *,
+ signed_in: bool,
+ account_label: str | None,
+ ) -> None:
+ self.flows[flow_id].source_status = {
+ "signed_in": signed_in,
+ "account_label": account_label,
+ }
+
def expose_codex_device_flow(self, flow_id: str) -> None:
flow = self.flows[flow_id]
flow.url = "https://auth.openai.com/codex/device"
@@ -107,7 +129,13 @@ class FakeAgentAuthService:
flow.state = "awaiting_code"
def complete(self, flow_id: str) -> None:
- self.flows[flow_id].state = "success"
+ flow = self.flows[flow_id]
+ flow.state = "success"
+ status = self.auth_status.get(flow.backend, {})
+ flow.source_status = {
+ "signed_in": _signed_in(flow.backend, status),
+ "account_label": _account_label(status),
+ }
def timeout(self, flow_id: str) -> None:
flow = self.flows[flow_id]
@@ -122,6 +150,7 @@ class NativeOAuthScenarioHarness:
"claude": {"active_auth_mode": "oauth"},
"codex": {"active_auth_mode": "oauth"},
}
+ self.agent_auth.auth_status = self.auth_status
self.adapter = AgentAuthNativeOAuthAdapter(
self.agent_auth,
auth_status_reader=lambda backend: self.auth_status[backend],
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 29abb5fa6..0bb1bd37c 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -246,6 +246,14 @@ scenarios:
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-211
+ name: Same-service-instance native login conflict returns a localized recovery path
+ status: covered
+ kind: negative_path
+ layer: scenario
+ backend: shared
+ scope: same_service_instance
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_same_service_instance_native_login_conflict_is_localized
- id: AUTH-SETUP-901
name: Codex setup success refreshes runtime before the next turn
status: covered
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 84692ee00..da4d02fab 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -1453,6 +1453,29 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(recovered_flow, lost_flow)
self.assertEqual(provider_calls, 1)
+ async def test_same_service_instance_native_login_conflict_is_localized(self):
+ """Scenario: AUTH-SETUP-211; both callers share one service instance."""
+ harness = AuthSetupScenarioHarness()
+ harness.controller.config.language = "zh"
+ process = FakeProcess()
+ harness.service._start_codex_process = AsyncMock(return_value=process)
+ harness.service._read_codex_output_web = AsyncMock()
+ harness.service._wait_for_codex_completion_web = AsyncMock()
+
+ web_flow = await harness.service.start_web_setup(
+ "codex",
+ force_reset=False,
+ )
+ await harness.service.start_setup(
+ harness.context,
+ backend="codex",
+ force_reset=False,
+ )
+
+ self.assertEqual(harness.service._start_codex_process.await_count, 1)
+ ScenarioExpect.text_contains(harness, "登录正在进行中")
+ await harness.service.cancel_web_flow(web_flow.flow_id)
+
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_native_oauth_scenarios.py b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
index 5eb54ea55..63964b8d4 100644
--- a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
@@ -92,7 +92,6 @@ def test_mh_oauth_native_001_claude_paste_code_happy_path(monkeypatch, tmp_path)
assert sources[0]["account_label"] is None
assert sources[0]["credential_ref"] is None
assert harness.store.config.sources[0].id == started["source_id"]
- harness.adapter._flows.clear()
harness.agent_auth.flows.clear()
repeated = client.get(
f"/api/models/oauth/status/{started['flow_id']}",
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index 1b00b1bdb..4ee7cf57c 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -14,6 +14,7 @@ sys.path.insert(0, str(ROOT))
from core.agent_auth_service import (
AgentAuthFlow,
AgentAuthService,
+ BackendLoginInProgressError,
classify_auth_error,
verify_opencode_auth_list_output,
)
@@ -532,7 +533,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
waiter_task=done_task,
claude_client=_client(501),
)
- service._flows[im_flow.flow_key] = im_flow
+ service._flow_registry.put(im_flow, flow_key=im_flow.flow_key)
service._web_flows["web-flow"] = SimpleNamespace(
backend="claude",
claude_client=_client(502),
@@ -561,7 +562,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
waiter_task=done_task,
claude_client=SimpleNamespace(),
)
- service._flows[flow.flow_key] = flow
+ service._flow_registry.put(flow, flow_key=flow.flow_key)
self.assertEqual(service.active_claude_auth_client_pids(), set())
self.assertTrue(service.has_active_claude_auth_client_with_unknown_pid())
@@ -584,6 +585,26 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
self.assertEqual(keyboard.buttons[0][0].callback_data, "auth_setup:claude")
self.assertNotIn("C1:claude", service._flows)
+ async def test_start_setup_localizes_native_login_conflict(self):
+ controller = _StubController()
+ controller._get_lang = lambda: "zh"
+ service = AgentAuthService(controller)
+ context = MessageContext(user_id="U1", channel_id="C1")
+ service._start_auth_flow = AsyncMock(
+ side_effect=BackendLoginInProgressError("anthropic", "claude")
+ )
+
+ await service.start_setup(
+ context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ )
+
+ _, text, _keyboard = controller.im_client.sent_button_messages[0]
+ self.assertIn("登录正在进行中", text)
+ self.assertNotIn("native_login_in_progress", text)
+
async def test_start_claude_control_flow_restores_settings_on_auth_start_failure(self):
controller = _StubController()
service = AgentAuthService(controller)
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 709985774..57420cca2 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -20,6 +20,7 @@ from config.v2_config import (
ModelHubSourceConfig,
ModelHubSourceStateConfig,
)
+from core.agent_auth_service import BackendLoginInProgressError
from core.handlers.model_hub.adapter import (
EngineHealth,
EngineStatus,
@@ -1060,6 +1061,22 @@ def test_native_oauth_rejects_duplicate_source_before_adapter(tmp_path):
assert adapter.oauth_start_calls == []
+def test_native_oauth_preserves_transient_login_conflict_identity(tmp_path):
+ class LoginInProgressAdapter(FakeAdapter):
+ async def start_oauth(self, source_id, vendor):
+ raise BackendLoginInProgressError(vendor, "claude")
+
+ service, _, _ = _service(tmp_path, LoginInProgressAdapter())
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))
+
+ assert exc_info.value.status == 409
+ assert exc_info.value.code == "native_login_in_progress"
+ assert exc_info.value.detail == "modelHub.errors.native_login_in_progress"
+ assert exc_info.value.data == {}
+
+
def test_nonce_oauth_start_replays_committed_flow_before_native_slot_conflict(tmp_path):
service, store, adapter = _service(tmp_path)
request = {
diff --git a/tests/test_native_login_single_flight.py b/tests/test_native_login_single_flight.py
new file mode 100644
index 000000000..30755cdee
--- /dev/null
+++ b/tests/test_native_login_single_flight.py
@@ -0,0 +1,289 @@
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from core.agent_auth_service import (
+ OPENCODE_DIRECT_SETUP_URLS,
+ AgentAuthFlow,
+ AgentAuthService,
+ BackendLoginInProgressError,
+ WebAuthFlow,
+)
+from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter
+from modules.im import MessageContext
+
+
+class _IMClient:
+ def __init__(self) -> None:
+ self.sent: list[str] = []
+
+ async def send_message(self, _context, text: str) -> None:
+ self.sent.append(text)
+
+
+class _Controller:
+ def __init__(self) -> None:
+ self.im_client = _IMClient()
+ self.config = SimpleNamespace(language="en")
+
+ def resolve_agent_for_context(self, _context) -> str:
+ return "codex"
+
+ def _get_settings_key(self, context) -> str:
+ return context.channel_id or "channel"
+
+ def _get_lang(self) -> str:
+ return "en"
+
+
[email protected]("backend", sorted(AgentAuthService.WEB_BACKENDS))
+async def test_every_web_backend_publishes_deadline_after_startup_with_waiter(
+ backend: str,
+) -> None:
+ """Drive the backend catalog so every usable Web flow shares the invariant."""
+ service = AgentAuthService(_Controller())
+ startup_finished: datetime | None = None
+
+ async def start_codex(**_kwargs):
+ nonlocal startup_finished
+ startup_finished = datetime.now(timezone.utc)
+ return SimpleNamespace(stdout=None, returncode=None)
+
+ async def start_claude(_context, **_kwargs):
+ nonlocal startup_finished
+ startup_finished = datetime.now(timezone.utc)
+ return object(), "https://claude.ai/oauth/authorize", None
+
+ async def start_provider_oauth(*_args, **_kwargs):
+ nonlocal startup_finished
+ startup_finished = datetime.now(timezone.utc)
+ return {"url": "https://provider.example/oauth"}
+
+ server = SimpleNamespace(
+ get_provider_auth=AsyncMock(return_value={}),
+ start_provider_oauth=start_provider_oauth,
+ )
+ service._start_codex_process = start_codex
+ service._start_claude_control_flow = start_claude
+ service._opencode_server = AsyncMock(return_value=server)
+ service._wait_for_codex_completion_web = AsyncMock()
+ service._wait_for_claude_completion_web = AsyncMock()
+ service._wait_for_opencode_oauth_web = AsyncMock()
+
+ flow = await service.start_web_setup(
+ backend,
+ force_reset=False,
+ provider_id="opencode" if backend == "opencode" else None,
+ )
+
+ assert isinstance(flow, WebAuthFlow)
+ assert startup_finished is not None
+ assert flow.waiter_task is not None
+ assert flow.expires_at_iso is not None
+ assert datetime.fromisoformat(flow.expires_at_iso) >= startup_finished + timedelta(
+ seconds=service.setup_timeout_seconds
+ )
+ await flow.waiter_task
+
+
[email protected]("backend", sorted(AgentAuthService.WEB_BACKENDS))
+async def test_every_im_native_backend_publishes_deadline_after_startup_with_waiter(
+ backend: str,
+) -> None:
+ """Drive the backend catalog through the shared IM flow contract."""
+ service = AgentAuthService(_Controller())
+ startup_finished: datetime | None = None
+ process = SimpleNamespace(stdout=None, returncode=None)
+
+ async def start_codex(**_kwargs):
+ nonlocal startup_finished
+ startup_finished = datetime.now(timezone.utc)
+ return process
+
+ async def start_claude(_context, **_kwargs):
+ nonlocal startup_finished
+ startup_finished = datetime.now(timezone.utc)
+ return object(), "https://claude.ai/oauth/authorize", None
+
+ async def start_opencode(_context, **_kwargs):
+ nonlocal startup_finished
+ startup_finished = datetime.now(timezone.utc)
+ return process, 1, "oauth-provider"
+
+ service._resolve_opencode_provider = AsyncMock(return_value="oauth-provider")
+ service._start_codex_process = start_codex
+ service._start_claude_control_flow = start_claude
+ service._start_opencode_process = start_opencode
+ service._read_codex_output = AsyncMock()
+ service._read_pty_output = AsyncMock()
+ service._wait_for_completion = AsyncMock()
+ service._wait_for_claude_completion = AsyncMock()
+
+ flow = await service._start_auth_flow(
+ backend,
+ context=MessageContext(user_id="user", channel_id=backend),
+ force_reset=False,
+ claude_login_method="claudeai",
+ )
+
+ assert isinstance(flow, AgentAuthFlow)
+ assert startup_finished is not None
+ assert flow.waiter_task is not None
+ assert flow.expires_at_iso is not None
+ assert datetime.fromisoformat(flow.expires_at_iso) >= startup_finished + timedelta(
+ seconds=service.setup_timeout_seconds
+ )
+ await flow.waiter_task
+
+
+async def test_failed_and_waiterless_flows_do_not_advertise_deadlines() -> None:
+ service = AgentAuthService(_Controller())
+ service._start_codex_process = AsyncMock(side_effect=RuntimeError("spawn failed"))
+
+ failed = await service.start_web_setup("codex", force_reset=False)
+
+ assert failed.state == "failed"
+ assert failed.waiter_task is None
+ assert failed.expires_at_iso is None
+
+ provider = next(iter(OPENCODE_DIRECT_SETUP_URLS))
+ service._resolve_opencode_provider = AsyncMock(return_value=provider)
+ direct = await service._start_auth_flow(
+ "opencode",
+ context=MessageContext(user_id="user", channel_id="direct"),
+ force_reset=False,
+ )
+
+ assert isinstance(direct, AgentAuthFlow)
+ assert direct.waiter_task is None
+ assert direct.expires_at_iso is None
+
+
+async def test_single_service_fixture_routes_all_callers_to_the_same_registry() -> None:
+ """Prove in-instance reuse, not cross-process production exclusion.
+
+ Production intentionally constructs separate AgentAuthService instances in
+ the controller and UI-server processes.
+ """
+ controller = _Controller()
+ service = AgentAuthService(controller)
+ process = SimpleNamespace(stdout=object(), returncode=0)
+ service._start_codex_process = AsyncMock(return_value=process)
+ service._read_codex_output = AsyncMock()
+ service._wait_for_completion = AsyncMock()
+
+ context = MessageContext(user_id="user", channel_id="channel")
+ await service.start_setup(context, backend="codex", force_reset=False)
+ im_flow = service._flows["channel:codex"]
+
+ assert service._web_flows is service._flows_by_id
+ assert service._web_flows[im_flow.flow_id] is im_flow
+
+ adapter = AgentAuthNativeOAuthAdapter(
+ service,
+ auth_status_reader=lambda _backend: {"active_auth_mode": "oauth"},
+ )
+ with pytest.raises(BackendLoginInProgressError) as adapter_conflict:
+ await adapter.start_oauth("source", "openai")
+ assert adapter_conflict.value.code == "native_login_in_progress"
+
+ with pytest.raises(BackendLoginInProgressError):
+ await service.start_web_setup("codex", force_reset=False, owner_ref="source")
+
+ service._drop_flow(im_flow)
+ web_flow = await service.start_web_setup("codex", force_reset=False, owner_ref="source")
+ assert service._flows_by_id[web_flow.flow_id] is web_flow
+
+ assert (await adapter.oauth_status(web_flow.flow_id)).flow_id == web_flow.flow_id
+ await adapter.cancel_oauth(web_flow.flow_id)
+
+
+async def test_model_hub_drives_the_shared_web_flow_through_submit_and_cancel() -> None:
+ """Model Hub delegates one Web flow lifecycle within a service instance."""
+ service = AgentAuthService(_Controller())
+ client = object()
+ service._start_claude_control_flow = AsyncMock(
+ return_value=(client, "https://claude.ai/oauth/authorize", None)
+ )
+ service._wait_for_claude_completion_web = AsyncMock()
+ service._send_claude_callback = AsyncMock()
+ service._terminate_web_flow = AsyncMock()
+ adapter = AgentAuthNativeOAuthAdapter(
+ service,
+ auth_status_reader=lambda _backend: {"active_auth_mode": "oauth"},
+ )
+
+ state = await adapter.start_oauth("source", "anthropic")
+ flow = service._flows_by_id[state.flow_id]
+ assert (await adapter.oauth_status(state.flow_id)).flow_id == flow.flow_id
+
+ submitted = await adapter.submit_oauth(state.flow_id, "authorization#state")
+ assert submitted.state == "verifying"
+ service._send_claude_callback.assert_awaited_once_with(
+ client, "authorization", "state"
+ )
+ assert service._flows_by_id[state.flow_id] is flow
+
+ await adapter.cancel_oauth(state.flow_id)
+ service._terminate_web_flow.assert_awaited_once_with(
+ flow, final_state="cancelled"
+ )
+ assert state.flow_id not in service._flows_by_id
+
+
+async def test_cancel_keeps_native_claim_until_termination_settles() -> None:
+ service = AgentAuthService(_Controller())
+ process = SimpleNamespace(stdout=None, returncode=None)
+ service._start_codex_process = AsyncMock(return_value=process)
+ service._read_codex_output_web = AsyncMock()
+ service._wait_for_codex_completion_web = AsyncMock()
+ flow = await service.start_web_setup("codex", force_reset=False)
+ termination_started = asyncio.Event()
+ finish_termination = asyncio.Event()
+
+ async def terminate(_flow, **_kwargs) -> None:
+ termination_started.set()
+ await finish_termination.wait()
+
+ service._terminate_web_flow = terminate
+ cancel_task = asyncio.create_task(service.cancel_web_flow(flow.flow_id))
+ await termination_started.wait()
+
+ try:
+ with pytest.raises(BackendLoginInProgressError):
+ await service.start_web_setup("codex", force_reset=False)
+ finally:
+ finish_termination.set()
+ assert await cancel_task == {"ok": True}
+
+ replacement = await service.start_web_setup("codex", force_reset=False)
+ assert replacement.flow_id in service._flows_by_id
+
+
+async def test_cancel_releases_native_claim_when_termination_raises() -> None:
+ service = AgentAuthService(_Controller())
+ process = SimpleNamespace(stdout=None, returncode=None)
+ service._start_codex_process = AsyncMock(return_value=process)
+ service._read_codex_output_web = AsyncMock()
+ service._wait_for_codex_completion_web = AsyncMock()
+ flow = await service.start_web_setup("codex", force_reset=False)
+ service._terminate_web_flow = AsyncMock(side_effect=RuntimeError("terminate failed"))
+
+ with pytest.raises(RuntimeError, match="terminate failed"):
+ await service.cancel_web_flow(flow.flow_id)
+
+ assert flow.flow_id not in service._flows_by_id
+ replacement = await service.start_web_setup("codex", force_reset=False)
+ assert replacement.flow_id in service._flows_by_id
diff --git a/tests/test_native_login_structure_guards.py b/tests/test_native_login_structure_guards.py
new file mode 100644
index 000000000..0beddef1a
--- /dev/null
+++ b/tests/test_native_login_structure_guards.py
@@ -0,0 +1,427 @@
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+from modules.agents.catalog import WEB_OAUTH_BACKENDS
+
+
+ROOT = Path(__file__).parents[1]
+SERVICE = ROOT / "core" / "agent_auth_service.py"
+CONTROLLER = ROOT / "core" / "controller.py"
+NATIVE_ADAPTER = ROOT / "core" / "handlers" / "model_hub" / "native_oauth.py"
+WEB_API = ROOT / "vibe" / "api.py"
+
+
+def _functions(tree: ast.AST) -> list[ast.FunctionDef | ast.AsyncFunctionDef]:
+ return [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ ]
+
+
+def _call_name(call: ast.Call) -> str | None:
+ if isinstance(call.func, ast.Name):
+ return call.func.id
+ if isinstance(call.func, ast.Attribute):
+ return call.func.attr
+ return None
+
+
+def _assigned_value_before(
+ function: ast.FunctionDef | ast.AsyncFunctionDef,
+ name: str,
+ before_line: int,
+) -> ast.AST | None:
+ candidates: list[tuple[int, ast.AST]] = []
+ for node in ast.walk(function):
+ if getattr(node, "lineno", before_line) >= before_line:
+ continue
+ if isinstance(node, ast.Assign) and any(
+ isinstance(target, ast.Name) and target.id == name
+ for target in node.targets
+ ):
+ candidates.append((node.lineno, node.value))
+ elif (
+ isinstance(node, ast.AnnAssign)
+ and isinstance(node.target, ast.Name)
+ and node.target.id == name
+ and node.value is not None
+ ):
+ candidates.append((node.lineno, node.value))
+ return max(candidates, default=(0, None), key=lambda item: item[0])[1]
+
+
+def _literal_strings(
+ function: ast.FunctionDef | ast.AsyncFunctionDef,
+ expression: ast.AST,
+ *,
+ before_line: int | None = None,
+ resolving: frozenset[str] = frozenset(),
+) -> set[str]:
+ """Resolve literals used directly or through a local command variable."""
+ if isinstance(expression, ast.Constant) and isinstance(expression.value, str):
+ return {expression.value}
+ if isinstance(expression, ast.Name) and expression.id not in resolving:
+ line = before_line or getattr(expression, "lineno", function.end_lineno or 0)
+ assigned = _assigned_value_before(function, expression.id, line)
+ if assigned is not None:
+ return _literal_strings(
+ function,
+ assigned,
+ before_line=getattr(assigned, "lineno", line),
+ resolving=resolving | {expression.id},
+ )
+ return {
+ literal
+ for child in ast.iter_child_nodes(expression)
+ for literal in _literal_strings(
+ function,
+ child,
+ before_line=before_line,
+ resolving=resolving,
+ )
+ }
+
+
+def _spawn_sites(tree: ast.Module) -> list[tuple[str, str, ast.Call]]:
+ """Find every provider login operation instead of enumerating today's sites."""
+ sites: list[tuple[str, str, ast.Call]] = []
+ for function in _functions(tree):
+ for call in ast.walk(function):
+ if not isinstance(call, ast.Call):
+ continue
+ name = _call_name(call)
+ literals = _literal_strings(
+ function,
+ call,
+ before_line=call.lineno,
+ )
+ is_process_login = name == "create_subprocess_exec" and (
+ "--device-auth" in literals or {"auth", "login"} <= literals
+ )
+ is_control_login = name in {
+ "_create_claude_control_client",
+ "start_provider_oauth",
+ }
+ if not (is_process_login or is_control_login):
+ continue
+ backend_matches = {
+ backend
+ for backend in WEB_OAUTH_BACKENDS
+ if backend in literals or backend in function.name.split("_")
+ }
+ assert len(backend_matches) == 1, (
+ f"cannot associate {function.name}:{call.lineno} with one supported backend"
+ )
+ sites.append((function.name, backend_matches.pop(), call))
+ return sites
+
+
+def _exception_mentions(handler: ast.ExceptHandler, exception_name: str) -> bool:
+ return handler.type is not None and any(
+ (isinstance(node, ast.Name) and node.id == exception_name)
+ or (isinstance(node, ast.Attribute) and node.attr == exception_name)
+ for node in ast.walk(handler.type)
+ )
+
+
+def _caught_code(expression: ast.AST, caught_name: str) -> bool:
+ return (
+ isinstance(expression, ast.Attribute)
+ and expression.attr == "code"
+ and isinstance(expression.value, ast.Name)
+ and expression.value.id == caught_name
+ )
+
+
+def _internal_call_graph(
+ functions: dict[str, ast.FunctionDef | ast.AsyncFunctionDef],
+) -> dict[str, set[str]]:
+ return {
+ name: {
+ called
+ for call in ast.walk(function)
+ if isinstance(call, ast.Call)
+ if (called := _call_name(call)) in functions
+ }
+ for name, function in functions.items()
+ }
+
+
+def _reachable(graph: dict[str, set[str]], root: str) -> set[str]:
+ reached = {root}
+ pending = [root]
+ while pending:
+ current = pending.pop()
+ for called in graph[current] - reached:
+ reached.add(called)
+ pending.append(called)
+ return reached
+
+
+def test_all_callers_reuse_the_shared_start_path() -> None:
+ tree = ast.parse(SERVICE.read_text(encoding="utf-8"))
+ functions = {function.name: function for function in _functions(tree)}
+ assert "_start_auth_flow" in functions
+
+ for public_name in ("start_setup", "start_web_setup"):
+ calls = [
+ call
+ for call in ast.walk(functions[public_name])
+ if isinstance(call, ast.Call) and _call_name(call) == "_start_auth_flow"
+ ]
+ assert calls, f"{public_name} bypasses the shared start path"
+
+ assignments = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Assign)
+ and any(
+ isinstance(target, ast.Attribute)
+ and target.attr in {"_flows", "_web_flows", "_flows_by_id"}
+ for target in node.targets
+ )
+ ]
+ assert not assignments, "a second flow registry was reintroduced"
+
+ adapter = ast.parse(NATIVE_ADAPTER.read_text(encoding="utf-8"))
+ adapter_starts = [
+ call
+ for function in _functions(adapter)
+ for call in ast.walk(function)
+ if isinstance(call, ast.Call) and _call_name(call) == "start_web_setup"
+ ]
+ assert adapter_starts, "Model Hub does not route through the shared start path"
+
+
+def test_web_api_owns_a_separate_service_instance_by_design() -> None:
+ """Record the production boundary: Web and controller registries are distinct."""
+ web_tree = ast.parse(WEB_API.read_text(encoding="utf-8"))
+ web_functions = {function.name: function for function in _functions(web_tree)}
+ web_constructors = [
+ call
+ for call in ast.walk(web_functions["_get_oauth_service"])
+ if isinstance(call, ast.Call) and _call_name(call) == "AgentAuthService"
+ ]
+ controller_tree = ast.parse(CONTROLLER.read_text(encoding="utf-8"))
+ controller_constructors = [
+ call
+ for call in ast.walk(controller_tree)
+ if isinstance(call, ast.Call) and _call_name(call) == "AgentAuthService"
+ ]
+ assert len(web_constructors) == 1
+ assert len(controller_constructors) == 1
+
+
+def test_every_discovered_spawn_site_is_reachable_from_shared_start_path() -> None:
+ tree = ast.parse(SERVICE.read_text(encoding="utf-8"))
+ functions = {function.name: function for function in _functions(tree)}
+ graph = _internal_call_graph(functions)
+ sites = _spawn_sites(tree)
+ assert sites
+ spawn_functions = {function_name for function_name, _backend, _spawn in sites}
+ spawn_backends = {backend for _function_name, backend, _spawn in sites}
+ assert spawn_backends == set(WEB_OAUTH_BACKENDS)
+ backend_start_subprocesses = {
+ function.name
+ for function in functions.values()
+ if function.name.startswith("_start_")
+ if set(function.name.split("_")) & set(WEB_OAUTH_BACKENDS)
+ if any(
+ isinstance(call, ast.Call)
+ and _call_name(call) == "create_subprocess_exec"
+ for call in ast.walk(function)
+ )
+ }
+ assert backend_start_subprocesses <= spawn_functions
+ guarded_region = _reachable(graph, "_start_auth_flow")
+ assert spawn_functions <= guarded_region
+
+ reverse_graph = {name: set() for name in functions}
+ for caller, callees in graph.items():
+ for callee in callees:
+ reverse_graph[callee].add(caller)
+ reaches_spawn = set(spawn_functions)
+ pending = list(spawn_functions)
+ while pending:
+ current = pending.pop()
+ for caller in reverse_graph[current] - reaches_spawn:
+ reaches_spawn.add(caller)
+ pending.append(caller)
+
+ # The shared start is the only entry into the internal region that can
+ # reach a provider spawn. A new side caller of any helper in that region
+ # therefore fails without this test knowing the helper's name.
+ for function_name in (reaches_spawn & guarded_region) - {"_start_auth_flow"}:
+ assert reverse_graph[function_name] <= guarded_region
+
+ start = functions["_start_auth_flow"]
+ claim_lines = [
+ call.lineno
+ for call in ast.walk(start)
+ if isinstance(call, ast.Call) and _call_name(call) == "_claim_shared_native_flow"
+ ]
+ assert len(claim_lines) == 1
+ guarded_entry_lines = [
+ call.lineno
+ for call in ast.walk(start)
+ if isinstance(call, ast.Call)
+ and _call_name(call) in reaches_spawn - {"_start_auth_flow"}
+ ]
+ assert guarded_entry_lines
+ assert claim_lines[0] < min(guarded_entry_lines)
+
+
+def test_native_login_in_progress_identity_reaches_every_payload_unchanged() -> None:
+ """Every discovered conflict handler preserves the owner's stable code."""
+ production_trees: list[tuple[Path, ast.Module]] = []
+ for source_root in (ROOT / "core", ROOT / "vibe"):
+ for path in source_root.rglob("*.py"):
+ source = path.read_text(encoding="utf-8")
+ if "BackendLoginInProgressError" in source:
+ production_trees.append((path, ast.parse(source)))
+
+ definitions = [
+ node
+ for _path, tree in production_trees
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ClassDef)
+ and node.name == "BackendLoginInProgressError"
+ ]
+ assert len(definitions) == 1
+ codes = {
+ value.value
+ for definition in definitions
+ for node in definition.body
+ if isinstance(node, ast.Assign)
+ for target in node.targets
+ if isinstance(target, ast.Name) and target.id == "code"
+ if isinstance((value := node.value), ast.Constant)
+ and isinstance(value.value, str)
+ }
+ assert codes == {"native_login_in_progress"}
+
+ raise_sites = [
+ (path, node)
+ for path, tree in production_trees
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Raise)
+ and isinstance(node.exc, ast.Call)
+ and _call_name(node.exc) == "BackendLoginInProgressError"
+ ]
+ assert raise_sites
+
+ payload_handlers = 0
+ for path, tree in production_trees:
+ for handler in (
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ExceptHandler)
+ and _exception_mentions(node, "BackendLoginInProgressError")
+ ):
+ literals = {
+ node.value
+ for node in ast.walk(handler)
+ if isinstance(node, ast.Constant) and isinstance(node.value, str)
+ }
+ assert "native_source_already_exists" not in literals, path
+
+ caught_name = handler.name
+ payload_codes: list[ast.AST] = []
+ for node in ast.walk(handler):
+ if (
+ isinstance(node, ast.Raise)
+ and isinstance(node.exc, ast.Call)
+ and _call_name(node.exc) == "ModelHubError"
+ and node.exc.args
+ ):
+ payload_codes.append(node.exc.args[0])
+ elif isinstance(node, ast.Dict):
+ payload_codes.extend(
+ value
+ for key, value in zip(node.keys, node.values)
+ if isinstance(key, ast.Constant) and key.value == "error"
+ )
+ elif (
+ isinstance(node, ast.Raise)
+ and node.exc is not None
+ and isinstance(node.exc, ast.Call)
+ ):
+ raise AssertionError(
+ f"{path}:{node.lineno} rewraps the native-login conflict"
+ )
+
+ if payload_codes:
+ payload_handlers += 1
+ assert caught_name is not None
+ assert all(_caught_code(code, caught_name) for code in payload_codes), path
+
+ assert payload_handlers >= 2
+
+
+def test_published_flow_deadline_is_owned_by_its_enforcing_waiter() -> None:
+ """One boundary must publish and enforce every auth-flow deadline."""
+ tree = ast.parse(SERVICE.read_text(encoding="utf-8"))
+ functions = {function.name: function for function in _functions(tree)}
+
+ deadline_writers = {
+ function.name
+ for function in functions.values()
+ for node in ast.walk(function)
+ if isinstance(node, ast.Assign)
+ if any(
+ isinstance(target, ast.Attribute)
+ and target.attr == "expires_at_iso"
+ for target in node.targets
+ )
+ }
+ constructor_deadlines = [
+ keyword
+ for call in ast.walk(tree)
+ if isinstance(call, ast.Call)
+ for keyword in call.keywords
+ if keyword.arg == "expires_at_iso"
+ ]
+ assert deadline_writers == {"_arm_flow_waiter"}
+ assert not constructor_deadlines
+
+ waiter_writers = {
+ function.name
+ for function in functions.values()
+ for node in ast.walk(function)
+ if isinstance(node, ast.Assign)
+ if any(
+ isinstance(target, ast.Attribute)
+ and target.attr == "waiter_task"
+ for target in node.targets
+ )
+ }
+ assert waiter_writers == {"_arm_flow_waiter"}
+
+ armed_waiters = {
+ _call_name(waiter_call)
+ for call in ast.walk(tree)
+ if isinstance(call, ast.Call) and _call_name(call) == "_arm_flow_waiter"
+ for argument in call.args[1:]
+ for waiter_call in ast.walk(argument)
+ if isinstance(waiter_call, ast.Call)
+ and (_call_name(waiter_call) or "").startswith("_wait_for_")
+ }
+ assert armed_waiters
+ for waiter_name in armed_waiters:
+ assert waiter_name is not None
+ timeout_reads = [
+ call
+ for call in ast.walk(functions[waiter_name])
+ if isinstance(call, ast.Call)
+ and _call_name(call) == "_remaining_flow_timeout"
+ ]
+ assert timeout_reads, f"{waiter_name} does not enforce the published deadline"
+
+
+def test_model_hub_adapter_has_no_live_flow_registry_or_slot_api() -> None:
+ source = NATIVE_ADAPTER.read_text(encoding="utf-8")
+ assert "self._flows" not in source
+ assert "release_login_slot" not in source
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index d92f33e03..4038b3574 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1320,6 +1320,26 @@ def test_start_oauth_web_blocks_recovery_before_service_mutation(monkeypatch):
assert service_calls == []
+def test_start_oauth_web_localizes_native_login_conflict(monkeypatch):
+ from core.agent_auth_service import BackendLoginInProgressError
+
+ service = SimpleNamespace(
+ start_web_setup=AsyncMock(
+ side_effect=BackendLoginInProgressError("openai", "codex")
+ )
+ )
+ monkeypatch.setattr(api, "load_config", lambda: SimpleNamespace(language="zh"))
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: service)
+
+ result = asyncio.run(api.start_oauth_web_async("codex"))
+
+ assert result == {
+ "ok": False,
+ "error": "native_login_in_progress",
+ "detail": "openai(codex)登录正在进行中,请先完成或取消后再重新发起。",
+ }
+
+
def test_submit_oauth_web_code_rechecks_recovery_before_service_mutation(monkeypatch):
fake_config = SimpleNamespace(load_warnings=("recovery required",), language="zh")
service_calls = []
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 9410004ab..a95ea32f0 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -255,6 +255,39 @@ def test_cancel_removes_flow_and_marks_state(service: AgentAuthService) -> None:
assert result == {"ok": True}
assert "any" not in service._web_flows
assert flow.state == "cancelled"
+ assert _run(service.cancel_web_flow("any")) == {
+ "ok": False,
+ "error": "flow_not_found",
+ }
+
+
+def test_concurrent_double_cancel_is_idempotent(service: AgentAuthService) -> None:
+ flow = WebAuthFlow(flow_id="double", backend="codex", state="awaiting_code")
+ service._web_flows[flow.flow_id] = flow
+ terminate = service._terminate_web_flow
+ both_entered = asyncio.Event()
+ entered = 0
+
+ async def terminate_together(target: WebAuthFlow, **kwargs) -> None:
+ nonlocal entered
+ entered += 1
+ if entered == 2:
+ both_entered.set()
+ await both_entered.wait()
+ await terminate(target, **kwargs)
+
+ async def cancel_twice() -> list[dict[str, object]]:
+ return await asyncio.gather(
+ service.cancel_web_flow(flow.flow_id),
+ service.cancel_web_flow(flow.flow_id),
+ )
+
+ service._terminate_web_flow = terminate_together
+ results = _run(cancel_twice())
+
+ assert results == [{"ok": True}, {"ok": True}]
+ assert flow.flow_id not in service._web_flows
+ assert flow.state == "cancelled"
def test_post_web_success_hook_invocation_when_set(
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index bd753778f..b3c789d7c 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -195,7 +195,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
? await api.startOAuthWebForOpencodeProvider(opencodeProviderId || '', true)
: await api.startOAuthWeb(backend, true);
if (!result.ok || !result.flow_id) {
- setError(result.error || result.detail || 'start_failed');
+ setError(result.detail || result.error || 'start_failed');
setState('failed');
return;
}
diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.ts
index bd9ed8f63..0e2eb5f9e 100644
--- a/ui/src/components/settings/models/serverCopy.test.ts
+++ b/ui/src/components/settings/models/serverCopy.test.ts
@@ -11,7 +11,13 @@ import { describe, expect, it } from 'vitest';
import en from '../../../i18n/en.json';
import zh from '../../../i18n/zh.json';
-import { NATIVE_SUBSCRIPTION_EXISTS_FAILURE, oauthFailureKey, oauthStartFailureKey, serverText } from './serverCopy';
+import {
+ NATIVE_LOGIN_IN_PROGRESS_FAILURE,
+ NATIVE_SUBSCRIPTION_EXISTS_FAILURE,
+ oauthFailureKey,
+ oauthStartFailureKey,
+ serverText,
+} from './serverCopy';
const t = (lng: 'en' | 'zh'): TFunction => {
const i18n = createInstance();
@@ -127,6 +133,13 @@ describe('oauthStartFailureKey', () => {
);
});
+ it('keeps a transient native login conflict retryable on its current channel', () => {
+ const key = oauthStartFailureKey(NATIVE_LOGIN_IN_PROGRESS_FAILURE);
+ expect(key).toBe('settings.models.addSub.error.loginInProgress');
+ expect(t('en')(key)).toMatch(/already in progress/i);
+ expect(t('zh')(key)).toContain('正在进行中');
+ });
+
it('keeps unknown start failures retryable without inventing a cause', () => {
expect(oauthStartFailureKey(undefined)).toBe('settings.models.addSub.error.startFailed');
});
diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.ts
index 0f74e520e..5d38e89c0 100644
--- a/ui/src/components/settings/models/serverCopy.ts
+++ b/ui/src/components/settings/models/serverCopy.ts
@@ -89,10 +89,13 @@ export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney)
/** Start-route failures have not reached provider authorization yet. */
export const NATIVE_SUBSCRIPTION_EXISTS_FAILURE = 'modelHub.errors.native_subscription_exists';
+export const NATIVE_LOGIN_IN_PROGRESS_FAILURE = 'modelHub.errors.native_login_in_progress';
export const oauthStartFailureKey = (code: string | undefined): string =>
code === NATIVE_SUBSCRIPTION_EXISTS_FAILURE
? 'settings.models.addSub.error.alreadyBound'
+ : code === NATIVE_LOGIN_IN_PROGRESS_FAILURE
+ ? 'settings.models.addSub.error.loginInProgress'
: code === 'engine_down' || code === 'modelHub.errors.engine_down'
? 'settings.models.addSub.error.engineDown'
: 'settings.models.addSub.error.startFailed';
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 17de83ca6..3c41962c3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1155,6 +1155,7 @@
"oauthFailed": "Sign-in did not complete. You can retry.",
"startFailed": "Could not confirm the sign-in started — you can retry",
"engineDown": "The gateway is not responding. Please retry.",
+ "loginInProgress": "Another native login is already in progress. Finish or cancel it, then retry.",
"alreadyBound": "This backend's native login slot is already taken. Add it as a gateway-held source instead."
}
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 200f01639..e2931d406 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1155,6 +1155,7 @@
"oauthFailed": "登录没有完成。可以重试。",
"startFailed": "没能确认登录已经开始,可以重试",
"engineDown": "网关没有响应,请重试",
+ "loginInProgress": "另一个原生登录正在进行中,请先完成或取消后再重试。",
"alreadyBound": "这个后端的原生登录位已经被占用了。改用网关托管添加。"
}
},
diff --git a/vibe/api.py b/vibe/api.py
index 846735d62..627587557 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -9395,6 +9395,8 @@ async def start_oauth_web_async(
recovery_message = _config_recovery_message()
if recovery_message:
return {"ok": False, "error": "config_recovery", "message": recovery_message}
+ from core.agent_auth_service import BackendLoginInProgressError
+
service = _get_oauth_service()
try:
flow = await service.start_web_setup(
@@ -9402,6 +9404,21 @@ async def start_oauth_web_async(
force_reset=force_reset,
provider_id=(provider_id.strip() if isinstance(provider_id, str) else None),
)
+ except BackendLoginInProgressError as exc:
+ try:
+ lang = load_config().language
+ except Exception: # noqa: BLE001
+ lang = "en"
+ return {
+ "ok": False,
+ "error": exc.code,
+ "detail": backend_t(
+ "command.setup.loginInProgress",
+ lang,
+ vendor=exc.vendor,
+ backend=backend,
+ ),
+ }
except Exception as exc: # noqa: BLE001
logger.error("Web OAuth start failed for %s: %s", backend, exc, exc_info=True)
return {"ok": False, "error": "start_failed", "detail": str(exc)}
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 5e72e4215..2c874f80b 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -614,6 +614,7 @@
"opencodeCodeRetryPrompt": "OpenCode is still waiting for the `{provider}` API key. The previous value may not have been accepted. Reply with the key directly in this chat.",
"timedOut": "{backend} setup timed out. Start setup again to retry.",
"success": "{backend} login is active again.",
+ "loginInProgress": "A {vendor} login for {backend} is already in progress. Finish or cancel it before starting another.",
"failed": "{backend} setup failed: {detail}",
"unknownFailure": "Unknown login failure."
},
@@ -798,6 +799,7 @@
"authentication_failed": "Authentication failed. Check whether the API key is valid.",
"observation_failed": "Connected, but the response did not prove a valid model interface.",
"adapter_error": "We could not confirm whether the service is reachable. Retry the connection.",
+ "native_login_in_progress": "Another native login is already in progress. Finish or cancel it, then retry.",
"native_subscription_exists": "This vendor already has a native subscription source.",
"source_timeout": "The connection timed out. Check the network and retry.",
"invalid_source_order": "The source order contains an unavailable, ineligible, or duplicate source.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 7debe5be9..80b36fb5a 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -614,6 +614,7 @@
"opencodeCodeRetryPrompt": "OpenCode 仍在等待 `{provider}` 的 API key,上一条值可能没有被接受。请直接在当前聊天里回复 key。",
"timedOut": "{backend} 登录修复已超时,请重新发起 setup 再试一次。",
"success": "{backend} 已重新登录,可继续使用。",
+ "loginInProgress": "{vendor}({backend})登录正在进行中,请先完成或取消后再重新发起。",
"failed": "{backend} 登录修复失败:{detail}",
"unknownFailure": "未知登录失败。"
},
@@ -798,6 +799,7 @@
"authentication_failed": "鉴权失败,请检查 API Key 是否有效。",
"observation_failed": "已连接,但无法确认服务返回的是有效模型接口。",
"adapter_error": "无法确认服务是否可连接,请重试。",
+ "native_login_in_progress": "另一个原生登录正在进行中,请先完成或取消后再重试。",
"native_subscription_exists": "该厂商已经有一个原生订阅来源。",
"source_timeout": "连接超时,请检查网络后重试。",
"invalid_source_order": "来源顺序包含不可用、不适用或重复的来源。",