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(backends): web OAuth flow plumbing for Claude + Codex

cyhacb72af63ba4
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index fde7240df..9cb0082ba 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -9,8 +9,9 @@ import logging
import os
import re
import signal
+import time
import uuid
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from typing import Any, Optional
from modules.claude_sdk_compat import (
@@ -151,6 +152,30 @@ class AgentAuthFlow:
return f"{self.settings_key}:{self.backend}"
+# Web Settings → Backends OAuth flows live alongside the IM ``AgentAuthFlow``
+# but share none of its IM coupling: no MessageContext, no ``_send_message``,
+# no settings_key. State is exposed to the browser via a polling endpoint, so
+# every transition the UI needs to render lives in plain fields here.
+WebFlowState = str # "starting" | "awaiting_code" | "verifying" | "success" | "failed" | "cancelled"
+
+
+@dataclass
+class WebAuthFlow:
+ flow_id: str
+ backend: str # "claude" | "codex"
+ state: WebFlowState = "starting"
+ process: asyncio.subprocess.Process | None = None
+ reader_task: asyncio.Task[None] | None = None
+ waiter_task: asyncio.Task[None] | None = None
+ claude_client: ClaudeSDKClient | None = None
+ url: str | None = None
+ device_code: str | None = None
+ awaiting_code: bool = False
+ error: str | None = None
+ last_status_text: str | None = None
+ created_at: float = field(default_factory=time.time)
+
+
class AgentAuthService:
"""Manage backend-specific login flows triggered through IM."""
@@ -160,6 +185,15 @@ class AgentAuthService:
self._flows_by_id: dict[str, AgentAuthFlow] = {}
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()
+ # Optional callable invoked after a successful *web* auth flow so
+ # the UI-server process can ask the long-running controller to
+ # reload V2Config-backed credentials. The hook receives ``(backend,)``
+ # and runs in a worker thread to avoid blocking the auth event loop.
+ self._post_web_success_hook: Optional[Any] = None
def _t(self, key: str, **kwargs) -> str:
lang = getattr(self.controller, "_get_lang", lambda: getattr(self.controller.config, "language", "en"))()
@@ -598,7 +632,7 @@ class AgentAuthService:
async def _start_claude_control_flow(
self,
- context: MessageContext,
+ context: Optional[MessageContext] = None,
*,
force_reset: bool,
login_with_claude_ai: bool,
@@ -628,12 +662,17 @@ class AgentAuthService:
raise RuntimeError("Claude auth flow did not return a manual login URL")
return client, manual_url
- async def _create_claude_control_client(self, context: MessageContext) -> ClaudeSDKClient:
+ async def _create_claude_control_client(
+ self, context: Optional[MessageContext] = None
+ ) -> ClaudeSDKClient:
session_handler = getattr(self.controller, "session_handler", None)
- get_working_path = getattr(session_handler, "get_working_path", None)
- if callable(get_working_path):
+ get_working_path = getattr(session_handler, "get_working_path", None) if session_handler else None
+ if context is not None and callable(get_working_path):
working_path = get_working_path(context)
else:
+ # Web-initiated flows do not have an IM session; fall back to the
+ # process cwd so the SDK client still has a stable cwd to attach
+ # its OAuth callback transport to.
working_path = os.getcwd()
if not os.path.exists(working_path):
@@ -1214,3 +1253,272 @@ class AgentAuthService:
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)
+
+ # ------------------------------------------------------------------
+ # Web Settings → Backends OAuth flows
+ #
+ # These methods power ``Settings → Backends → {Claude,Codex} → Sign in``
+ # in the browser. They reuse the same subprocess / SDK plumbing the IM
+ # ``/setup`` command uses (``_start_codex_process``,
+ # ``_start_claude_control_flow``, ``_verify_login``,
+ # ``_refresh_backend_runtime``) but never call ``_send_message`` — every
+ # piece of state the UI needs is parked on the ``WebAuthFlow`` record
+ # and read by a polling endpoint.
+ # ------------------------------------------------------------------
+
+ WEB_BACKENDS = {"claude", "codex"}
+
+ async def start_web_setup(self, backend: str, *, force_reset: bool = True) -> WebAuthFlow:
+ """Start an OAuth flow initiated from the Settings page.
+
+ Returns the freshly-created ``WebAuthFlow``. For Codex the caller
+ should poll ``get_web_flow_status`` until ``state == "awaiting_code"``
+ appears (URL + device code surfaced) and then again until the user
+ completes the device auth on OpenAI's side. For Claude the call
+ returns once the manual URL is available; the user then submits the
+ callback code via ``submit_web_code``.
+ """
+ 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")
+
+ async with self._web_flow_lock:
+ self._web_flows[flow_id] = flow
+
+ try:
+ if backend == "codex":
+ flow.process = await self._start_codex_process(force_reset=force_reset)
+ 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))
+ else: # claude
+ client, manual_url = await self._start_claude_control_flow(
+ context=None,
+ force_reset=force_reset,
+ login_with_claude_ai=True,
+ )
+ flow.claude_client = client
+ 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))
+ except Exception as err: # noqa: BLE001
+ logger.error("Web auth start failed for %s: %s", backend, err, exc_info=True)
+ flow.state = "failed"
+ flow.error = str(err)
+ return flow
+
+ async def submit_web_code(self, flow_id: str, code: str) -> dict[str, Any]:
+ flow = self._web_flows.get(flow_id)
+ if flow is None:
+ return {"ok": False, "error": "flow_not_found"}
+ if flow.backend != "claude":
+ return {"ok": False, "error": "code_not_supported"}
+ if not flow.awaiting_code or flow.claude_client is None:
+ return {"ok": False, "error": "not_awaiting_code"}
+
+ raw = (code or "").strip()
+ if "#" not in raw:
+ return {"ok": False, "error": "invalid_format"}
+ auth_code, state_val = raw.split("#", 1)
+ auth_code = auth_code.strip()
+ state_val = state_val.strip()
+ if not auth_code or not state_val:
+ return {"ok": False, "error": "invalid_format"}
+
+ try:
+ await self._send_claude_callback(flow.claude_client, auth_code, state_val)
+ except Exception as err: # noqa: BLE001
+ logger.error("Web Claude callback submit failed: %s", err, exc_info=True)
+ return {"ok": False, "error": "submit_failed", "detail": str(err)}
+
+ flow.awaiting_code = False
+ flow.state = "verifying"
+ return {"ok": True}
+
+ def get_web_flow_status(self, flow_id: str) -> dict[str, Any]:
+ flow = self._web_flows.get(flow_id)
+ if flow is None:
+ return {"ok": False, "error": "flow_not_found"}
+ return {
+ "ok": True,
+ "flow_id": flow_id,
+ "backend": flow.backend,
+ "state": flow.state,
+ "url": flow.url,
+ "device_code": flow.device_code,
+ "awaiting_code": flow.awaiting_code,
+ "error": flow.error,
+ }
+
+ 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)
+ if flow is None:
+ return {"ok": False, "error": "flow_not_found"}
+ await self._terminate_web_flow(flow, final_state="cancelled")
+ return {"ok": True}
+
+ async def _read_codex_output_web(self, flow: WebAuthFlow) -> None:
+ """Parse ``codex login --device-auth`` stdout for URL + device code.
+
+ Mirrors ``_read_codex_output`` but writes the parsed fields onto the
+ ``WebAuthFlow`` instead of pushing an IM message.
+ """
+ process = flow.process
+ if process is None or process.stdout is None:
+ return
+ try:
+ while True:
+ line = await process.stdout.readline()
+ if not line:
+ break
+ text = line.decode("utf-8", errors="replace")
+ clean = sanitize_process_output(text)
+ if not clean:
+ continue
+ flow.last_status_text = clean
+ maybe_url = CODEX_URL_RE.search(clean)
+ if maybe_url:
+ flow.url = maybe_url.group(0)
+ maybe_code = CODEX_DEVICE_CODE_RE.search(clean)
+ if maybe_code:
+ flow.device_code = maybe_code.group(0)
+ if flow.url and flow.device_code and flow.state == "starting":
+ flow.state = "awaiting_code"
+ except asyncio.CancelledError:
+ raise
+ except Exception as err: # noqa: BLE001
+ logger.warning("Codex web reader stopped: %s", err)
+
+ 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)
+ if flow.reader_task and not flow.reader_task.done():
+ try:
+ await flow.reader_task
+ except asyncio.CancelledError:
+ pass
+ flow.state = "verifying"
+ ok, detail = await self._verify_web_login(flow.backend)
+ if ok:
+ await self._refresh_backend_runtime(flow.backend)
+ await self._invoke_post_web_success_hook(flow.backend)
+ flow.state = "success"
+ else:
+ flow.state = "failed"
+ flow.error = detail or "unknown_failure"
+ except asyncio.TimeoutError:
+ await self._terminate_web_flow(flow, final_state="failed", error="timed_out")
+ except asyncio.CancelledError:
+ raise
+ except Exception as err: # noqa: BLE001
+ 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")
+ await asyncio.wait_for(
+ self._send_claude_control_request(
+ flow.claude_client,
+ {"subtype": "claude_oauth_wait_for_completion"},
+ timeout=self.setup_timeout_seconds,
+ ),
+ timeout=self.setup_timeout_seconds,
+ )
+ flow.state = "verifying"
+ ok, detail = await self._verify_web_login(flow.backend)
+ if ok:
+ await self._refresh_backend_runtime(flow.backend)
+ await self._invoke_post_web_success_hook(flow.backend)
+ flow.state = "success"
+ else:
+ flow.state = "failed"
+ flow.error = detail or "unknown_failure"
+ except asyncio.TimeoutError:
+ flow.state = "failed"
+ flow.error = "timed_out"
+ except asyncio.CancelledError:
+ raise
+ except Exception as err: # noqa: BLE001
+ logger.error("Web Claude auth flow failed: %s", err, exc_info=True)
+ flow.state = "failed"
+ flow.error = str(err)
+ finally:
+ if flow.claude_client is not None:
+ await self._disconnect_claude_client(flow.claude_client)
+ flow.claude_client = None
+
+ async def _verify_web_login(self, backend: str) -> tuple[bool, str]:
+ """Re-run the same CLI status probes ``_verify_login`` uses for IM.
+
+ Builds a temporary IM-shaped ``AgentAuthFlow`` shell so the existing
+ verifier can run unchanged — the only fields it touches are
+ ``backend`` and the controller binary lookup, so the placeholder
+ process / context / tasks are safe to leave as ``None``-ish stubs.
+ """
+ dummy = AgentAuthFlow(
+ flow_id="web-verify",
+ backend=backend,
+ settings_key="web",
+ initiator_user_id="web",
+ context=None, # type: ignore[arg-type]
+ process=None,
+ reader_task=asyncio.create_task(asyncio.sleep(0)),
+ waiter_task=asyncio.create_task(asyncio.sleep(0)),
+ )
+ try:
+ return await self._verify_login(dummy)
+ finally:
+ for task in (dummy.reader_task, dummy.waiter_task):
+ if task and not task.done():
+ task.cancel()
+
+ async def _invoke_post_web_success_hook(self, backend: str) -> None:
+ hook = self._post_web_success_hook
+ if not callable(hook):
+ return
+ try:
+ await asyncio.to_thread(hook, backend)
+ except Exception as err: # noqa: BLE001
+ logger.warning("post_web_success_hook failed for %s: %s", backend, err)
+
+ async def _terminate_web_flow(
+ self,
+ flow: WebAuthFlow,
+ *,
+ final_state: WebFlowState,
+ error: str | None = None,
+ ) -> None:
+ if flow.reader_task and not flow.reader_task.done():
+ flow.reader_task.cancel()
+ try:
+ await flow.reader_task
+ except asyncio.CancelledError:
+ pass
+ if flow.waiter_task and not flow.waiter_task.done():
+ flow.waiter_task.cancel()
+ try:
+ await flow.waiter_task
+ except asyncio.CancelledError:
+ pass
+ if flow.process is not None and flow.process.returncode is None:
+ try:
+ flow.process.terminate()
+ await asyncio.wait_for(flow.process.wait(), timeout=5)
+ except asyncio.TimeoutError:
+ flow.process.kill()
+ await flow.process.wait()
+ except ProcessLookupError:
+ pass
+ if flow.claude_client is not None:
+ await self._disconnect_claude_client(flow.claude_client)
+ flow.claude_client = None
+ flow.state = final_state
+ if error:
+ flow.error = error
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
new file mode 100644
index 000000000..9b5e95b4d
--- /dev/null
+++ b/tests/test_web_oauth_flow.py
@@ -0,0 +1,199 @@
+"""Regression tests for the Settings → Backends web OAuth flow.
+
+Pins the public surface added in PR #282 R5 so the Claude/Codex Settings
+page can drive OAuth from the browser instead of asking users to copy a
+``claude login`` command into a terminal. The state machine itself
+(``WebAuthFlow``) and the four web methods on ``AgentAuthService`` are
+exercised without spawning real subprocesses by injecting stub flows
+into ``_web_flows`` and mocking ``_send_claude_callback``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import AsyncMock
+
+import pytest
+
+from core.agent_auth_service import AgentAuthService, WebAuthFlow
+
+
+class _Backend:
+ cli_path = "/usr/bin/echo" # any binary that exists is fine
+
+
+class _Agents:
+ claude = _Backend
+ codex = _Backend
+ opencode = _Backend
+
+
+class _Config:
+ agents = _Agents()
+ language = "en"
+
+
+class _StubController:
+ """Minimal controller stand-in (see ``vibe/api.py::_WebControllerStub``)."""
+
+ agent_service = None
+ session_handler = None
+ im_client = None
+ config = _Config()
+
+
+def service() -> AgentAuthService:
+ return AgentAuthService(_StubController())
+
+
+def _run(coro):
+ return asyncio.get_event_loop_policy().new_event_loop().run_until_complete(coro)
+
+
+def test_unsupported_backend_raises(service: AgentAuthService) -> None:
+ with pytest.raises(ValueError, match="unsupported_backend"):
+ _run(service.start_web_setup("opencode"))
+
+
+def test_status_for_unknown_flow_returns_flow_not_found(service: AgentAuthService) -> None:
+ result = service.get_web_flow_status("nonexistent")
+ assert result == {"ok": False, "error": "flow_not_found"}
+
+
+def test_submit_code_unknown_flow(service: AgentAuthService) -> None:
+ result = _run(service.submit_web_code("nonexistent", "abc#def"))
+ assert result == {"ok": False, "error": "flow_not_found"}
+
+
+def test_submit_code_rejected_for_codex(service: AgentAuthService) -> None:
+ # Codex device-auth never asks for a code; submitting one is a UI bug.
+ flow = WebAuthFlow(flow_id="cdx1", backend="codex", state="awaiting_code", awaiting_code=True)
+ service._web_flows[flow.flow_id] = flow
+ result = _run(service.submit_web_code("cdx1", "abc#def"))
+ assert result == {"ok": False, "error": "code_not_supported"}
+
+
+def test_submit_code_rejected_when_not_awaiting(service: AgentAuthService) -> None:
+ flow = WebAuthFlow(flow_id="cl1", backend="claude", state="verifying", awaiting_code=False)
+ service._web_flows[flow.flow_id] = flow
+ result = _run(service.submit_web_code("cl1", "abc#def"))
+ assert result == {"ok": False, "error": "not_awaiting_code"}
+
+
+def test_submit_code_invalid_format(service: AgentAuthService) -> None:
+ flow = WebAuthFlow(
+ flow_id="cl2",
+ backend="claude",
+ state="awaiting_code",
+ awaiting_code=True,
+ claude_client=object(), # presence-check only
+ )
+ service._web_flows[flow.flow_id] = flow
+
+ # Missing separator.
+ assert _run(service.submit_web_code("cl2", "no-hash-here")) == {
+ "ok": False,
+ "error": "invalid_format",
+ }
+ # Empty left half.
+ assert _run(service.submit_web_code("cl2", "#statehere")) == {
+ "ok": False,
+ "error": "invalid_format",
+ }
+ # Empty right half.
+ assert _run(service.submit_web_code("cl2", "code#")) == {
+ "ok": False,
+ "error": "invalid_format",
+ }
+
+
+def test_submit_code_happy_path_transitions_to_verifying(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ mock_send = AsyncMock()
+ monkeypatch.setattr(service, "_send_claude_callback", mock_send)
+
+ fake_client = object()
+ flow = WebAuthFlow(
+ flow_id="cl3",
+ backend="claude",
+ state="awaiting_code",
+ awaiting_code=True,
+ claude_client=fake_client,
+ url="https://claude.ai/oauth/authorize?...",
+ )
+ service._web_flows[flow.flow_id] = flow
+
+ result = _run(service.submit_web_code("cl3", " authcode # state-token "))
+ assert result == {"ok": True}
+ mock_send.assert_awaited_once_with(fake_client, "authcode", "state-token")
+ assert flow.state == "verifying"
+ assert flow.awaiting_code is False
+
+
+def test_status_returns_serializable_snapshot(service: AgentAuthService) -> None:
+ flow = WebAuthFlow(
+ flow_id="cdx2",
+ backend="codex",
+ state="awaiting_code",
+ url="https://auth.openai.com/codex/device",
+ device_code="ABCD-EFGH",
+ awaiting_code=False,
+ )
+ service._web_flows[flow.flow_id] = flow
+ result = service.get_web_flow_status("cdx2")
+ assert result == {
+ "ok": True,
+ "flow_id": "cdx2",
+ "backend": "codex",
+ "state": "awaiting_code",
+ "url": "https://auth.openai.com/codex/device",
+ "device_code": "ABCD-EFGH",
+ "awaiting_code": False,
+ "error": None,
+ }
+
+
+def test_cancel_unknown_flow(service: AgentAuthService) -> None:
+ result = _run(service.cancel_web_flow("nope"))
+ assert result == {"ok": False, "error": "flow_not_found"}
+
+
+def test_cancel_removes_flow_and_marks_state(service: AgentAuthService) -> None:
+ flow = WebAuthFlow(flow_id="any", backend="codex", state="awaiting_code")
+ service._web_flows[flow.flow_id] = flow
+ result = _run(service.cancel_web_flow("any"))
+ assert result == {"ok": True}
+ assert "any" not in service._web_flows
+ assert flow.state == "cancelled"
+
+
+def test_post_web_success_hook_invocation_when_set(
+ service: AgentAuthService,
+) -> None:
+ """Hook fires once after a successful flow; absence is a no-op."""
+ calls: list[str] = []
+
+ def hook(backend: str) -> None:
+ calls.append(backend)
+
+ service._post_web_success_hook = hook
+ _run(service._invoke_post_web_success_hook("codex"))
+ assert calls == ["codex"]
+
+
+def test_post_web_success_hook_swallows_exceptions(service: AgentAuthService) -> None:
+ """A misbehaving hook must not surface into the flow waiter."""
+
+ def hook(_backend: str) -> None:
+ raise RuntimeError("boom")
+
+ service._post_web_success_hook = hook
+ # Should NOT raise.
+ _run(service._invoke_post_web_success_hook("claude"))
+
+
+def test_post_web_success_hook_unset_is_safe(service: AgentAuthService) -> None:
+ service._post_web_success_hook = None
+ _run(service._invoke_post_web_success_hook("claude"))
diff --git a/vibe/api.py b/vibe/api.py
index 510456d0d..2fad7570b 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -6,6 +6,7 @@ import re
import shutil
import subprocess
import sys
+import threading
import time
import urllib.request
import uuid
@@ -2059,6 +2060,168 @@ def restart_backend(name: str) -> dict:
_VALID_AUTH_MODES = {"oauth", "api_key"}
+# ---------------------------------------------------------------------------
+# Web Settings → Backends OAuth flow plumbing
+#
+# Mirrors the IM ``/setup`` flow but runs in the UI server's own process.
+# OAuth subprocess + Claude SDK client require a long-lived event loop —
+# Flask routes are sync, so we host one on a dedicated thread and bridge
+# every call with ``run_coroutine_threadsafe``. On success we drop a
+# ``restart-<backend>.cmd`` marker so the live controller refreshes its
+# in-process agent state (mirroring what ``_refresh_backend_runtime`` does
+# in-process for IM-driven flows).
+# ---------------------------------------------------------------------------
+
+
+class _WebControllerStub:
+ """Minimal ``Controller``-shaped facade for the web OAuth flow service.
+
+ ``AgentAuthService`` only touches ``controller.config`` (for
+ ``cli_path``) and gracefully no-ops when ``agent_service`` /
+ ``session_handler`` are absent. The stub re-reads V2Config from disk on
+ every access so a freshly-saved ``cli_path`` is picked up on the next
+ flow without restarting the UI server.
+ """
+
+ @property
+ def config(self):
+ return load_config()
+
+ # The following attributes are inspected via ``getattr(..., None)`` in
+ # ``AgentAuthService`` and gate platform-specific paths that web flows
+ # never traverse (IM message dispatch, session lookup, agent refresh).
+ agent_service = None
+ session_handler = None
+ im_client = None
+
+
+_oauth_service_lock = threading.Lock()
+_oauth_service: Any = None
+_oauth_loop: Any = None
+_oauth_loop_thread: Any = None
+
+
+def _start_oauth_event_loop() -> Any:
+ loop = asyncio.new_event_loop()
+
+ def _runner() -> None:
+ asyncio.set_event_loop(loop)
+ loop.run_forever()
+
+ thread = threading.Thread(target=_runner, daemon=True, name="vibe-oauth-loop")
+ thread.start()
+ return loop, thread
+
+
+def _on_web_auth_success(backend: str) -> None:
+ """Tell the live controller to refresh its agent after web OAuth success."""
+ try:
+ handled, err = _request_controller_restart(backend, timeout=4.0)
+ if handled and err:
+ logger.warning("Controller refresh after web auth reported error: %s", err)
+ elif not handled:
+ logger.info("Controller did not pick up web-auth refresh marker for %s", backend)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Failed to notify controller after web auth: %s", exc)
+
+
+def _get_oauth_service() -> Any:
+ """Lazily build the (singleton) AgentAuthService for web flows."""
+ global _oauth_service, _oauth_loop, _oauth_loop_thread
+ with _oauth_service_lock:
+ if _oauth_service is not None:
+ return _oauth_service
+ from core.agent_auth_service import AgentAuthService
+
+ _oauth_loop, _oauth_loop_thread = _start_oauth_event_loop()
+ controller = _WebControllerStub()
+ _oauth_service = AgentAuthService(controller)
+ _oauth_service._post_web_success_hook = _on_web_auth_success
+ return _oauth_service
+
+
+def _submit_oauth_coro(coro, *, timeout: float = 30.0):
+ service = _get_oauth_service() # ensures loop # noqa: F841
+ future = asyncio.run_coroutine_threadsafe(coro, _oauth_loop)
+ return future.result(timeout=timeout)
+
+
+def _serialize_web_flow_status(payload: dict) -> dict:
+ """Strip server-only keys before returning to the browser."""
+ if not isinstance(payload, dict):
+ return {"ok": False, "error": "invalid_payload"}
+ return payload
+
+
+_WEB_OAUTH_BACKENDS = {"claude", "codex"}
+
+
+def start_oauth_web(backend: str, force_reset: bool = True) -> dict:
+ backend = (backend or "").strip().lower()
+ if backend not in _WEB_OAUTH_BACKENDS:
+ return {"ok": False, "error": "unsupported_backend"}
+ service = _get_oauth_service()
+ try:
+ flow = _submit_oauth_coro(
+ service.start_web_setup(backend, force_reset=force_reset),
+ timeout=60.0,
+ )
+ 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)}
+
+ if flow.state == "failed":
+ return {
+ "ok": False,
+ "error": flow.error or "start_failed",
+ "flow_id": flow.flow_id,
+ }
+ return {
+ "ok": True,
+ "flow_id": flow.flow_id,
+ "backend": flow.backend,
+ "state": flow.state,
+ "url": flow.url,
+ "device_code": flow.device_code,
+ "awaiting_code": flow.awaiting_code,
+ }
+
+
+def get_oauth_web_status(flow_id: str) -> dict:
+ flow_id = (flow_id or "").strip()
+ if not flow_id:
+ return {"ok": False, "error": "missing_flow_id"}
+ service = _get_oauth_service()
+ return _serialize_web_flow_status(service.get_web_flow_status(flow_id))
+
+
+def submit_oauth_web_code(flow_id: str, code: str) -> dict:
+ flow_id = (flow_id or "").strip()
+ if not flow_id:
+ return {"ok": False, "error": "missing_flow_id"}
+ service = _get_oauth_service()
+ try:
+ return _submit_oauth_coro(
+ service.submit_web_code(flow_id, code or ""),
+ timeout=30.0,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.error("Web OAuth code submit failed: %s", exc, exc_info=True)
+ return {"ok": False, "error": "submit_failed", "detail": str(exc)}
+
+
+def cancel_oauth_web(flow_id: str) -> dict:
+ flow_id = (flow_id or "").strip()
+ if not flow_id:
+ return {"ok": False, "error": "missing_flow_id"}
+ service = _get_oauth_service()
+ try:
+ return _submit_oauth_coro(service.cancel_web_flow(flow_id), timeout=15.0)
+ except Exception as exc: # noqa: BLE001
+ logger.error("Web OAuth cancel failed: %s", exc, exc_info=True)
+ return {"ok": False, "error": "cancel_failed", "detail": str(exc)}
+
+
def get_codex_auth() -> dict:
"""Return the user-facing Codex auth state for the Settings UI.
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 188e61c94..df4ec2f46 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1615,6 +1615,53 @@ def backend_claude_auth_post():
return jsonify(api.save_claude_auth(payload))
[email protected]("/backend/<backend>/auth/oauth/start", methods=["POST"])
+def backend_oauth_web_start(backend: str):
+ """Kick off a Settings → Backends OAuth flow for Claude or Codex.
+
+ Body: ``{force_reset?: bool}``. Returns ``{flow_id, state, url?,
+ device_code?, awaiting_code?}``. The caller polls ``GET .../status/<flow_id>``
+ while the user completes login externally.
+ """
+ from vibe import api
+
+ payload = request.json or {}
+ force_reset = bool(payload.get("force_reset", True))
+ return jsonify(api.start_oauth_web(backend, force_reset=force_reset))
+
+
[email protected]("/backend/<backend>/auth/oauth/status/<flow_id>", methods=["GET"])
+def backend_oauth_web_status(backend: str, flow_id: str):
+ """Poll an in-flight Settings OAuth flow."""
+ from vibe import api
+
+ _ = backend # backend is encoded in the flow itself; path arg kept for symmetry
+ return jsonify(api.get_oauth_web_status(flow_id))
+
+
[email protected]("/backend/<backend>/auth/oauth/submit-code", methods=["POST"])
+def backend_oauth_web_submit_code(backend: str):
+ """Submit the Claude OAuth callback code (Codex device-auth ignores this)."""
+ from vibe import api
+
+ _ = backend
+ payload = request.json or {}
+ flow_id = str(payload.get("flow_id") or "").strip()
+ code = str(payload.get("code") or "")
+ return jsonify(api.submit_oauth_web_code(flow_id, code))
+
+
[email protected]("/backend/<backend>/auth/oauth/cancel", methods=["POST"])
+def backend_oauth_web_cancel(backend: str):
+ """Cancel an in-flight Settings OAuth flow."""
+ from vibe import api
+
+ _ = backend
+ payload = request.json or {}
+ flow_id = str(payload.get("flow_id") or "").strip()
+ return jsonify(api.cancel_oauth_web(flow_id))
+
+
@app.route("/backend/opencode/providers", methods=["GET"])
def backend_opencode_providers():
"""Return the merged OpenCode provider catalog for the Settings UI.