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): unified OpenCode per-provider OAuth web flow

cyhf1ca417cb9f1
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 3371d289d..1d253f826 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -1356,9 +1356,26 @@ class AgentAuthService:
# and read by a polling endpoint.
# ------------------------------------------------------------------
- WEB_BACKENDS = {"claude", "codex"}
-
- async def start_web_setup(self, backend: str, *, force_reset: bool = True) -> WebAuthFlow:
+ WEB_BACKENDS = {"claude", "codex", "opencode"}
+
+ # OpenCode OAuth providers route through the daemon's HTTP API rather
+ # than a CLI subprocess. The Settings UI hands us the provider_id and
+ # we pick the friendliest method index — see
+ # ``_resolve_opencode_oauth_method`` for the heuristic.
+ _OPENCODE_OAUTH_PROMPT_ANSWERS: dict[str, dict[str, Any]] = {
+ # github-copilot's first prompt is a deployment-type select. We
+ # ship github.com support out of the box; enterprise users can
+ # still configure via terminal until we surface a select in the UI.
+ "github-copilot": {"deploymentType": "github.com"},
+ }
+
+ async def start_web_setup(
+ self,
+ backend: str,
+ *,
+ force_reset: bool = True,
+ provider_id: Optional[str] = None,
+ ) -> WebAuthFlow:
"""Start an OAuth flow initiated from the Settings page.
Returns the freshly-created ``WebAuthFlow``. For Codex the caller
@@ -1366,13 +1383,19 @@ class AgentAuthService:
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``.
+ callback code via ``submit_web_code``. For OpenCode the caller
+ must pass ``provider_id``; the URL (and optional device code) are
+ surfaced via ``WebAuthFlow.url`` / ``WebAuthFlow.device_code`` and
+ completion is auto-detected by OpenCode's daemon — no code submit
+ from the user.
"""
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
@@ -1382,7 +1405,7 @@ class AgentAuthService:
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
+ elif backend == "claude":
client, manual_url = await self._start_claude_control_flow(
context=None,
force_reset=force_reset,
@@ -1393,6 +1416,10 @@ class AgentAuthService:
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())
except Exception as err: # noqa: BLE001
logger.error("Web auth start failed for %s: %s", backend, err, exc_info=True)
flow.state = "failed"
@@ -1450,7 +1477,10 @@ class AgentAuthService:
flips ``auth_mode`` back to ``oauth`` so the next "Sign in" click
starts clean. Idempotent — repeated calls return ``ok: true``.
"""
- if backend not in self.WEB_BACKENDS:
+ # remove_web_auth and test_web_auth are claude / codex specific
+ # (single-backend subprocess invocations). OpenCode uses the
+ # per-provider DELETE / dedicated probe endpoints elsewhere.
+ if backend not in {"claude", "codex"}:
return {"ok": False, "error": "unsupported_backend"}
binary = self._get_cli_binary(backend)
@@ -1500,7 +1530,10 @@ class AgentAuthService:
``codex exec "Hi"``. Returns elapsed milliseconds + a short
response excerpt on success; surfaces stderr on failure.
"""
- if backend not in self.WEB_BACKENDS:
+ # remove_web_auth and test_web_auth are claude / codex specific
+ # (single-backend subprocess invocations). OpenCode uses the
+ # per-provider DELETE / dedicated probe endpoints elsewhere.
+ if backend not in {"claude", "codex"}:
return {"ok": False, "error": "unsupported_backend"}
binary = self._get_cli_binary(backend)
@@ -1602,6 +1635,138 @@ class AgentAuthService:
await self._terminate_web_flow(flow, final_state="cancelled")
return {"ok": True}
+ async def _opencode_server(self):
+ """Lazy lookup of the live OpenCode server client.
+
+ The web auth service runs in the UI process (no controller-level
+ ``agent_service``), so we go through ``OpenCodeServer.get_instance``
+ rather than ``self.controller.agent_service.agents['opencode']``.
+ Falls back to ``None`` if OpenCode is disabled in V2Config — the
+ caller then surfaces a ``failed`` flow state with a clear reason.
+ """
+ try:
+ from modules.agents.opencode.server import OpenCodeServer
+ except ImportError:
+ return None
+ config = getattr(self.controller, "config", None)
+ agents_cfg = getattr(config, "agents", None) if config is not None else None
+ opencode_cfg = getattr(agents_cfg, "opencode", None) if agents_cfg is not None else None
+ if opencode_cfg is None or not getattr(opencode_cfg, "enabled", False):
+ return None
+ try:
+ return await OpenCodeServer.get_instance(opencode_cfg)
+ except Exception as err: # noqa: BLE001
+ logger.warning("OpenCodeServer.get_instance failed for web OAuth: %s", err)
+ return None
+
+ async def _resolve_opencode_oauth_method(
+ self, server, provider_id: str
+ ) -> tuple[int, dict[str, Any]]:
+ """Pick the friendliest OAuth method index for a provider.
+
+ OpenCode's ``/provider/auth`` exposes an ordered list of methods
+ per provider. We prefer the **last** ``oauth`` entry — for OpenAI
+ that's the headless device-auth flow (better for remote sessions
+ than the localhost-callback browser flow). For providers with a
+ single oauth method (github-copilot, gitlab, poe) it returns
+ that one. Errors fall back to method 0.
+ """
+ prompt_answers = self._OPENCODE_OAUTH_PROMPT_ANSWERS.get(provider_id, {})
+ try:
+ auth_map = await server.get_provider_auth()
+ except Exception: # noqa: BLE001
+ return 0, prompt_answers
+ methods = auth_map.get(provider_id) if isinstance(auth_map, dict) else None
+ if not isinstance(methods, list):
+ return 0, prompt_answers
+ # Walk in reverse so the last oauth method wins. For OpenAI this
+ # picks "ChatGPT Pro/Plus (headless)" over the browser variant.
+ chosen = 0
+ for idx in range(len(methods) - 1, -1, -1):
+ entry = methods[idx]
+ if isinstance(entry, dict) and entry.get("type") == "oauth":
+ chosen = idx
+ break
+ return chosen, prompt_answers
+
+ # Matches OpenCode's ``"Enter code: AB1C-D2E3"`` instructions line so
+ # we can surface device codes inline rather than asking the user to
+ # squint at a copy-pasted URL.
+ _OPENCODE_DEVICE_CODE_RE = re.compile(r"Enter code:\s*([A-Za-z0-9-]+)")
+
+ async def _start_opencode_oauth_web(self, flow: WebAuthFlow, provider_id: str) -> None:
+ server = await self._opencode_server()
+ if server is None:
+ raise RuntimeError("opencode_server_unavailable")
+ method_index, prompt_answers = await self._resolve_opencode_oauth_method(
+ server, provider_id
+ )
+ flow.last_status_text = None
+ authorize = await server.start_provider_oauth(
+ provider_id,
+ method=method_index,
+ prompt_answers=prompt_answers,
+ )
+ url = authorize.get("url") if isinstance(authorize, dict) else None
+ instructions = authorize.get("instructions") if isinstance(authorize, dict) else None
+ if not isinstance(url, str) or not url.strip():
+ raise RuntimeError("opencode_authorize_missing_url")
+ flow.url = url.strip()
+ if isinstance(instructions, str):
+ match = self._OPENCODE_DEVICE_CODE_RE.search(instructions)
+ if match:
+ flow.device_code = match.group(1)
+ 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.
+ flow.awaiting_code = False
+ flow.waiter_task = asyncio.create_task(
+ self._wait_for_opencode_oauth_web(
+ flow,
+ provider_id,
+ method_index,
+ prompt_answers,
+ )
+ )
+
+ async def _wait_for_opencode_oauth_web(
+ self,
+ flow: WebAuthFlow,
+ provider_id: str,
+ method_index: int,
+ prompt_answers: dict[str, Any],
+ ) -> None:
+ try:
+ server = await self._opencode_server()
+ if server is None:
+ raise RuntimeError("opencode_server_unavailable")
+ await server.wait_provider_oauth(
+ provider_id,
+ method=method_index,
+ prompt_answers=prompt_answers,
+ timeout=self.setup_timeout_seconds,
+ )
+ flow.state = "verifying"
+ # OpenCode persists into auth.json itself; no extra subprocess
+ # verifier needed. We still ping the controller-refresh hook so
+ # the running OpenCode agent (and the Settings page on the
+ # next poll) sees the new auth state.
+ await self._invoke_post_web_success_hook(flow.backend)
+ flow.state = "success"
+ except asyncio.TimeoutError:
+ flow.state = "failed"
+ flow.error = "timed_out"
+ except asyncio.CancelledError:
+ raise
+ except Exception as err: # noqa: BLE001
+ logger.error(
+ "Web OpenCode OAuth flow failed for %s: %s", provider_id, err, exc_info=True
+ )
+ 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.
@@ -1729,7 +1894,12 @@ class AgentAuthService:
# intentionally do not touch ``api_key`` here: the user may have
# configured one earlier and we should preserve it for the moment
# they decide to switch back via Remove auth.
- await self._persist_web_auth_mode(backend, "oauth")
+ #
+ # Skipped for opencode: ``OpenCodeConfig`` has no ``auth_mode``
+ # field (auth is per-provider, not global), so persisting one
+ # would add a stray attribute and could mislead future readers.
+ if backend != "opencode":
+ await self._persist_web_auth_mode(backend, "oauth")
hook = self._post_web_success_hook
if not callable(hook):
return
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index de821c369..f07dea946 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -850,6 +850,82 @@ class OpenCodeServerManager:
logger.warning(f"Failed to get OpenCode providers: {e}")
return {}
+ async def start_provider_oauth(
+ self,
+ provider_id: str,
+ *,
+ method: int = 0,
+ prompt_answers: Optional[Dict[str, Any]] = None,
+ ) -> Dict[str, Any]:
+ """Kick off a per-provider OAuth authorize via OpenCode's HTTP API.
+
+ OpenCode 1.14 exposes ``POST /provider/<id>/oauth/authorize`` with
+ ``{method, ...prompt_answers}`` (the method index is the position
+ in ``/provider/auth[provider_id]``) and returns
+ ``{url, method, instructions}``. ``instructions`` carries the
+ user-facing device code for device-auth flows (e.g.
+ ``"Enter code: AB1C-D2E3"``); browser-redirect flows omit it.
+
+ For providers with prompts (e.g. github-copilot's deployment
+ type), ``prompt_answers`` is merged into the body so the caller
+ can pre-answer (e.g. ``{"deploymentType": "github.com"}``).
+ """
+ await self.ensure_running()
+ payload = {"method": method}
+ if prompt_answers:
+ payload.update(prompt_answers)
+ async with self._request_scope():
+ session = await self._get_http_session()
+ async with session.post(
+ f"{self.base_url}/provider/{provider_id}/oauth/authorize",
+ json=payload,
+ ) as resp:
+ text = await resp.text()
+ if resp.status != 200:
+ raise RuntimeError(
+ f"OpenCode authorize failed for {provider_id}: {resp.status} {text}"
+ )
+ try:
+ return await resp.json()
+ except Exception: # pragma: no cover - parse-defensive
+ return json.loads(text) if text else {}
+
+ async def wait_provider_oauth(
+ self,
+ provider_id: str,
+ *,
+ method: int = 0,
+ prompt_answers: Optional[Dict[str, Any]] = None,
+ timeout: float = 900.0,
+ ) -> Dict[str, Any]:
+ """Block until ``POST /provider/<id>/oauth/callback`` resolves.
+
+ OpenCode polls the provider's token endpoint (device flow) or
+ catches the local HTTP callback (browser flow) and returns when
+ the credentials have been minted and persisted into auth.json.
+ We bound the wait at 900 s — same as the IM ``/setup`` timeout.
+ """
+ await self.ensure_running()
+ payload = {"method": method}
+ if prompt_answers:
+ payload.update(prompt_answers)
+ async with self._request_scope():
+ session = await self._get_http_session()
+ async with session.post(
+ f"{self.base_url}/provider/{provider_id}/oauth/callback",
+ json=payload,
+ timeout=aiohttp.ClientTimeout(total=timeout),
+ ) as resp:
+ text = await resp.text()
+ if resp.status != 200:
+ raise RuntimeError(
+ f"OpenCode callback failed for {provider_id}: {resp.status} {text}"
+ )
+ try:
+ return await resp.json()
+ except Exception: # pragma: no cover - parse-defensive
+ return json.loads(text) if text else {}
+
async def get_provider_auth(self) -> Dict[str, Any]:
"""Fetch the per-provider auth-method index from OpenCode.
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 9bf84ed9a..aaf5e9157 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -53,7 +53,17 @@ def _run(coro):
def test_unsupported_backend_raises(service: AgentAuthService) -> None:
with pytest.raises(ValueError, match="unsupported_backend"):
- _run(service.start_web_setup("opencode"))
+ _run(service.start_web_setup("gemini"))
+
+
+def test_opencode_requires_provider_id(service: AgentAuthService) -> None:
+ """OpenCode auth is per-provider; ``start_web_setup`` must reject a
+ bare backend name with no ``provider_id`` rather than crash deep in
+ the OAuth bootstrap. (The error is surfaced as a failed flow record
+ so the UI can render a clear sentence.)"""
+ flow = _run(service.start_web_setup("opencode"))
+ assert flow.state == "failed"
+ assert flow.error == "opencode_provider_id_required"
def test_status_for_unknown_flow_returns_flow_not_found(service: AgentAuthService) -> None:
@@ -199,9 +209,132 @@ def test_post_web_success_hook_unset_is_safe(service: AgentAuthService) -> None:
_run(service._invoke_post_web_success_hook("claude"))
+# ---------------------------------------------------------------------------
+# OpenCode per-provider OAuth web flow
+# ---------------------------------------------------------------------------
+
+
+class _FakeOpencodeServer:
+ """In-memory stub of ``OpenCodeServer`` for the OAuth path.
+
+ ``start_provider_oauth`` returns the authorize-stub the test sets up
+ via ``next_authorize``; ``wait_provider_oauth`` blocks on a future
+ the test resolves manually so we can drive completion deterministically.
+ """
+
+ def __init__(self) -> None:
+ self.next_authorize: dict = {}
+ self.auth_map: dict = {}
+ self.wait_future: asyncio.Future = asyncio.get_event_loop_policy().new_event_loop().create_future()
+ self.start_calls: list[tuple[str, int, dict]] = []
+ self.wait_calls: list[tuple[str, int, dict]] = []
+
+ async def get_provider_auth(self):
+ return self.auth_map
+
+ async def start_provider_oauth(self, provider_id, *, method, prompt_answers):
+ self.start_calls.append((provider_id, method, prompt_answers))
+ return self.next_authorize
+
+ async def wait_provider_oauth(self, provider_id, *, method, prompt_answers, timeout):
+ self.wait_calls.append((provider_id, method, prompt_answers))
+ return await self.wait_future
+
+
+def test_start_web_setup_opencode_extracts_url_and_device_code(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = _FakeOpencodeServer()
+ fake.auth_map = {
+ "openai": [
+ {"type": "oauth", "label": "ChatGPT Pro/Plus (browser)"},
+ {"type": "oauth", "label": "ChatGPT Pro/Plus (headless)"},
+ {"type": "api", "label": "Manually enter API Key"},
+ ]
+ }
+ fake.next_authorize = {
+ "url": "https://auth.openai.com/codex/device",
+ "instructions": "Enter code: YR8I-QJJUH",
+ }
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+
+ flow = _run(service.start_web_setup("opencode", provider_id="openai"))
+
+ # Headless variant (index 1) wins because the resolver walks the
+ # auth list in reverse — important for remote sessions where the
+ # localhost-callback "browser" variant (index 0) can't complete.
+ assert fake.start_calls == [("openai", 1, {})]
+ assert flow.state == "awaiting_code"
+ assert flow.url == "https://auth.openai.com/codex/device"
+ assert flow.device_code == "YR8I-QJJUH"
+ # OpenCode device flow auto-completes; UI must not show a code-submit input.
+ assert flow.awaiting_code is False
+
+
+def test_start_web_setup_opencode_github_copilot_passes_prompt_answer(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """github-copilot's first method has a ``deploymentType`` prompt; the
+ resolver pre-fills ``github.com`` so the user doesn't have to pick
+ enterprise vs public on first sign-in."""
+ fake = _FakeOpencodeServer()
+ fake.auth_map = {
+ "github-copilot": [
+ {"type": "oauth", "label": "Login with GitHub Copilot"},
+ ]
+ }
+ fake.next_authorize = {
+ "url": "https://github.com/login/device",
+ "instructions": "Enter code: 335B-09BE",
+ }
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+
+ _run(service.start_web_setup("opencode", provider_id="github-copilot"))
+
+ assert fake.start_calls == [
+ ("github-copilot", 0, {"deploymentType": "github.com"}),
+ ]
+
+
+def test_start_web_setup_opencode_url_only_flow_has_no_device_code(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Browser-redirect flows (gitlab, poe) return ``url`` only — no
+ "Enter code: XXX" line. ``device_code`` must stay ``None`` so the UI
+ skips the device-code block."""
+ fake = _FakeOpencodeServer()
+ fake.auth_map = {"gitlab": [{"type": "oauth", "label": "GitLab OAuth"}]}
+ fake.next_authorize = {
+ "url": "https://gitlab.com/oauth/authorize?...",
+ "instructions": "Your browser will open for authentication.",
+ }
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+
+ flow = _run(service.start_web_setup("opencode", provider_id="gitlab"))
+ assert flow.state == "awaiting_code"
+ assert flow.url is not None
+ assert flow.device_code is None
+
+
+def test_start_web_setup_opencode_surfaces_server_failure(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """When the OpenCode daemon isn't reachable, the flow lands in
+ ``failed`` with a typed error string so the UI can render an
+ actionable sentence rather than ``cli_failed``."""
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=None))
+ flow = _run(service.start_web_setup("opencode", provider_id="openai"))
+ assert flow.state == "failed"
+ assert flow.error == "opencode_server_unavailable"
+
+
def test_remove_web_auth_rejects_unsupported_backend(service: AgentAuthService) -> None:
- result = _run(service.remove_web_auth("opencode"))
- assert result == {"ok": False, "error": "unsupported_backend"}
+ # OpenCode joined ``WEB_BACKENDS`` for OAuth, but ``remove_web_auth``
+ # is claude / codex specific — opencode providers use the
+ # per-provider DELETE endpoint instead. Both ``opencode`` and any
+ # other name are rejected here.
+ assert _run(service.remove_web_auth("opencode")) == {"ok": False, "error": "unsupported_backend"}
+ assert _run(service.remove_web_auth("gemini")) == {"ok": False, "error": "unsupported_backend"}
def test_remove_web_auth_runs_logout_and_returns_ok(
@@ -235,8 +368,10 @@ def test_remove_web_auth_codex_uses_logout_subcommand(
def test_test_web_auth_rejects_unsupported_backend(service: AgentAuthService) -> None:
- result = _run(service.test_web_auth("opencode"))
- assert result == {"ok": False, "error": "unsupported_backend"}
+ # OpenCode joins ``WEB_BACKENDS`` for OAuth start; ``test_web_auth``
+ # still rejects it (probe is run by the OpenCode daemon itself).
+ assert _run(service.test_web_auth("opencode")) == {"ok": False, "error": "unsupported_backend"}
+ assert _run(service.test_web_auth("gemini")) == {"ok": False, "error": "unsupported_backend"}
def test_test_web_auth_surfaces_cli_not_found(
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index aee190852..fd4992adb 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -10,7 +10,7 @@ import { useApi } from '@/context/ApiContext';
import type { OAuthWebState } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
-type Backend = 'claude' | 'codex';
+type Backend = 'claude' | 'codex' | 'opencode';
type LocalState = 'idle' | OAuthWebState;
@@ -23,6 +23,10 @@ const POLL_DEADLINE_MS = 16 * 60 * 1000;
export type BackendOAuthPanelProps = {
backend: Backend;
+ /** Required when ``backend === "opencode"``; the OpenCode daemon needs
+ * to know which provider's OAuth flow to kick off (each provider has
+ * its own authorize endpoint). Ignored for claude / codex. */
+ opencodeProviderId?: string;
/** When ``true`` the user is already signed in (read from the backend's
* ``get*Auth`` endpoint). We still render a "re-authenticate" button so
* rotating credentials without dropping to a terminal stays one click. */
@@ -36,6 +40,9 @@ export type BackendOAuthPanelProps = {
* ``null`` / undefined the banner shows only the generic "signed in"
* copy. Plaintext only — never leak tokens here. */
signedInDetail?: string | null;
+ /** Hide the Sign out / Remove auth button (e.g. OpenCode providers
+ * expose their own DELETE-credentials affordance inline). */
+ hideRemove?: boolean;
/** Optional callback fired once after the flow lands on ``state === "success"``.
* The parent typically re-reads ``getClaudeAuth`` / ``getCodexAuth`` here so
* the on-screen "signed in" indicators move. */
@@ -57,10 +64,12 @@ export type BackendOAuthPanelProps = {
*/
export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
backend,
+ opencodeProviderId,
signedIn,
title,
subtitle,
signedInDetail,
+ hideRemove,
onSuccess,
}) => {
const { t } = useTranslation();
@@ -155,7 +164,10 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
setError(null);
setCode('');
try {
- const result = await api.startOAuthWeb(backend, true);
+ const result =
+ backend === 'opencode'
+ ? await api.startOAuthWebForOpencodeProvider(opencodeProviderId || '', true)
+ : await api.startOAuthWeb(backend, true);
if (!result.ok || !result.flow_id) {
setError(result.error || result.detail || 'start_failed');
setState('failed');
@@ -193,6 +205,12 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
const submitCallback = async () => {
if (!flowId) return;
+ if (backend === 'opencode') {
+ // OpenCode flows never ask for a user-submitted code (device or
+ // localhost callback handle completion). Guard so the type system
+ // for ``api.submitOAuthWebCode`` (claude/codex only) is honoured.
+ return;
+ }
const trimmed = code.trim();
if (!trimmed) return;
setSubmitting(true);
@@ -215,6 +233,12 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
};
const removeAuth = async () => {
+ if (backend === 'opencode') {
+ // OpenCode providers expose their own Remove-key affordance inline
+ // on the parent page (DELETE /backend/opencode/provider/<id>/auth);
+ // the OAuth panel just shouldn't render this button there.
+ return;
+ }
setRemoving(true);
setError(null);
try {
@@ -264,11 +288,21 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
const isActive = state !== 'idle' && state !== 'success' && state !== 'failed' && state !== 'cancelled';
const showStartButton = state === 'idle' || state === 'success' || state === 'failed' || state === 'cancelled';
const claudeAwaitingCode = backend === 'claude' && state === 'awaiting_code';
+ // OpenCode device flows (openai headless, github-copilot) carry the
+ // user-facing code in the same payload as Codex; reuse the same UI
+ // affordance. Browser-redirect flows (gitlab, poe, openai browser)
+ // don't surface a code — only the URL.
const codexShowDevice = backend === 'codex' && state === 'awaiting_code' && url && deviceCode;
+ const opencodeShowDevice = backend === 'opencode' && state === 'awaiting_code' && url && deviceCode;
+ const showDeviceBlock = codexShowDevice || opencodeShowDevice;
const startLabel = signedIn
? t('settings.backends.oauthReauthenticate')
- : t(`settings.backends.${backend === 'claude' ? 'claudeSignInButton' : 'codexSignInButton'}`);
+ : (() => {
+ if (backend === 'claude') return t('settings.backends.claudeSignInButton');
+ if (backend === 'codex') return t('settings.backends.codexSignInButton');
+ return t('settings.backends.opencodeProviderSignIn');
+ })();
return (
<div className="flex flex-col gap-4 rounded-lg border border-border bg-surface-2/60 p-4">
@@ -282,7 +316,11 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
<CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-mint" />
<div className="flex flex-col gap-0.5">
<p className="text-[12px] text-mint">
- {t(`settings.backends.${backend === 'claude' ? 'claudeOauthSignedIn' : 'codexOauthSignedIn'}`)}
+ {(() => {
+ if (backend === 'claude') return t('settings.backends.claudeOauthSignedIn');
+ if (backend === 'codex') return t('settings.backends.codexOauthSignedIn');
+ return t('settings.backends.opencodeProviderOauthSignedIn');
+ })()}
</p>
{signedInDetail && (
<p className="font-mono text-[11px] text-mint/80">{signedInDetail}</p>
@@ -342,7 +380,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
</div>
)}
- {codexShowDevice && (
+ {showDeviceBlock && (
<div className="flex flex-col gap-2 rounded-md border border-border bg-background px-3 py-2.5">
<Label className="text-[11px] font-medium uppercase tracking-wide text-muted">
{t('settings.backends.codexDeviceCodeLabel')}
@@ -412,7 +450,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
{t('settings.backends.oauthInProgress')}
</span>
)}
- {(signedIn || state === 'success') && state !== 'starting' && state !== 'awaiting_code' && state !== 'verifying' && (
+ {!hideRemove && (signedIn || state === 'success') && state !== 'starting' && state !== 'awaiting_code' && state !== 'verifying' && (
<Button
type="button"
variant="ghost"
diff --git a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
index 0102e2f3f..836cd8cd7 100644
--- a/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsOpencodeProviderPage.tsx
@@ -33,6 +33,7 @@ import { Label } from '../ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { SettingsPageShell } from './SettingsPageShell';
import { BackendLifecycleChip } from './BackendLifecycleChip';
+import { BackendOAuthPanel } from './BackendOAuthPanel';
import { ToggleSwitch } from './SettingsPrimitives';
import { useApi } from '@/context/ApiContext';
import type { OpencodeProvider } from '@/context/ApiContext';
@@ -1099,16 +1100,31 @@ export const SettingsOpencodeProviderPage: React.FC = () => {
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="flex flex-col gap-3">
{provider.oauth_available && (
- <div className="rounded-md border border-cyan/30 bg-cyan/[0.06] px-3 py-2">
- <p className="text-[11px] font-medium text-cyan">
- {t('settings.backends.opencodeProviderOauthAvailable')}
- </p>
- <p className="text-[11px] leading-relaxed text-muted">
- {t('settings.backends.opencodeProviderOauthHint', {
- id: provider.id,
- })}
- </p>
- </div>
+ // In-card OAuth panel: reuses the
+ // same component Claude / Codex use,
+ // configured for OpenCode's
+ // per-provider HTTP flow. Drives the
+ // ``/backend/opencode/provider/<id>/auth/oauth/start``
+ // endpoint and polls for completion
+ // — no terminal commands required.
+ <BackendOAuthPanel
+ backend="opencode"
+ opencodeProviderId={provider.id}
+ signedIn={provider.configured}
+ title={t('settings.backends.opencodeProviderOauthPanelTitle', {
+ name: provider.name,
+ })}
+ subtitle={t('settings.backends.opencodeProviderOauthPanelSubtitle')}
+ hideRemove
+ onSuccess={() => {
+ // Refresh the providers list so
+ // the just-authorised provider
+ // flips to "configured" and the
+ // masked-key block (if any)
+ // appears.
+ void loadProviders();
+ }}
+ />
)}
<div className="flex flex-col gap-1.5">
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 997c24783..fbdadf617 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -26,13 +26,23 @@ export type ApiContextType = {
getClaudeAuth: () => Promise<ClaudeAuthState>;
saveClaudeAuth: (payload: ClaudeAuthPayload) => Promise<ClaudeAuthSaveResult>;
startOAuthWeb: (backend: 'claude' | 'codex', forceReset?: boolean) => Promise<OAuthWebStartResult>;
- getOAuthWebStatus: (backend: 'claude' | 'codex', flowId: string) => Promise<OAuthWebStatus>;
+ startOAuthWebForOpencodeProvider: (
+ providerId: string,
+ forceReset?: boolean,
+ ) => Promise<OAuthWebStartResult>;
+ getOAuthWebStatus: (
+ backend: 'claude' | 'codex' | 'opencode',
+ flowId: string,
+ ) => Promise<OAuthWebStatus>;
submitOAuthWebCode: (
backend: 'claude' | 'codex',
flowId: string,
code: string,
) => Promise<OAuthWebMutationResult>;
- cancelOAuthWeb: (backend: 'claude' | 'codex', flowId: string) => Promise<OAuthWebMutationResult>;
+ cancelOAuthWeb: (
+ backend: 'claude' | 'codex' | 'opencode',
+ flowId: string,
+ ) => Promise<OAuthWebMutationResult>;
removeBackendAuth: (backend: 'claude' | 'codex') => Promise<OAuthWebMutationResult>;
testBackendAuth: (backend: 'claude' | 'codex') => Promise<BackendAuthTestResult>;
getOpencodeProviders: () => Promise<OpencodeProviderListResult>;
@@ -442,6 +452,11 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/start`, {
force_reset: forceReset,
}),
+ startOAuthWebForOpencodeProvider: (providerId, forceReset = true) =>
+ postJson(
+ `/backend/opencode/provider/${encodeURIComponent(providerId)}/auth/oauth/start`,
+ { force_reset: forceReset },
+ ),
getOAuthWebStatus: (backend, flowId) =>
getJson(
`/backend/${encodeURIComponent(backend)}/auth/oauth/status/${encodeURIComponent(flowId)}`,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 60798b0a3..aa2f4a8d2 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -203,6 +203,10 @@
"activeAuthApiKey": "Active: API Key",
"activeAuthNone": "Not signed in",
"replaceApiKey": "Replace",
+ "opencodeProviderSignIn": "Sign in",
+ "opencodeProviderOauthSignedIn": "OAuth credentials stored.",
+ "opencodeProviderOauthPanelTitle": "Sign in to {{name}}",
+ "opencodeProviderOauthPanelSubtitle": "Open the URL, complete login in your browser; the OpenCode daemon detects completion automatically.",
"opencodeProvidersTitle": "Providers",
"opencodeProvidersSubtitle": "Lazy-loaded from the OpenCode server · auth handled via API key or OAuth sign-in",
"opencodeProvidersCount": "{{configured}}/{{total}} configured",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b2717cbb4..21063bb1d 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -203,6 +203,10 @@
"activeAuthApiKey": "当前:API Key",
"activeAuthNone": "未登录",
"replaceApiKey": "替换",
+ "opencodeProviderSignIn": "登录",
+ "opencodeProviderOauthSignedIn": "OAuth 凭据已保存。",
+ "opencodeProviderOauthPanelTitle": "登录 {{name}}",
+ "opencodeProviderOauthPanelSubtitle": "打开链接并在浏览器里完成登录,OpenCode 守护进程会自动检测完成状态。",
"opencodeProvidersTitle": "服务商",
"opencodeProvidersSubtitle": "从 OpenCode Server 实时拉取 · 通过 API Key 或 OAuth 登录完成授权",
"opencodeProvidersCount": "已配置 {{configured}}/{{total}}",
diff --git a/vibe/api.py b/vibe/api.py
index 40b81a426..46b1265ec 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2177,17 +2177,27 @@ def _serialize_web_flow_status(payload: dict) -> dict:
return payload
-_WEB_OAUTH_BACKENDS = {"claude", "codex"}
+_WEB_OAUTH_BACKENDS = {"claude", "codex", "opencode"}
-def start_oauth_web(backend: str, force_reset: bool = True) -> dict:
+def start_oauth_web(
+ backend: str,
+ force_reset: bool = True,
+ provider_id: Optional[str] = None,
+) -> dict:
backend = (backend or "").strip().lower()
if backend not in _WEB_OAUTH_BACKENDS:
return {"ok": False, "error": "unsupported_backend"}
+ if backend == "opencode" and not (isinstance(provider_id, str) and provider_id.strip()):
+ return {"ok": False, "error": "opencode_provider_id_required"}
service = _get_oauth_service()
try:
flow = _submit_oauth_coro(
- service.start_web_setup(backend, force_reset=force_reset),
+ service.start_web_setup(
+ backend,
+ force_reset=force_reset,
+ provider_id=(provider_id.strip() if isinstance(provider_id, str) else None),
+ ),
timeout=60.0,
)
except Exception as exc: # noqa: BLE001
@@ -2208,6 +2218,7 @@ def start_oauth_web(backend: str, force_reset: bool = True) -> dict:
"url": flow.url,
"device_code": flow.device_code,
"awaiting_code": flow.awaiting_code,
+ "provider": flow.provider,
}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 7fcb4cacf..803074ac1 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1691,6 +1691,24 @@ def backend_opencode_providers():
return jsonify(api.get_opencode_providers())
+ "/backend/opencode/provider/<provider_id>/auth/oauth/start",
+ methods=["POST"],
+)
+def backend_opencode_provider_oauth_start(provider_id: str):
+ """Kick off a Settings → Backends OAuth flow for a single OpenCode provider.
+
+ Body: ``{force_reset?: bool}``. Returns ``{flow_id, state, url?,
+ device_code?}``. The status/cancel endpoints are the same generic
+ ``/backend/opencode/auth/oauth/status/<flow_id>`` etc.
+ """
+ from vibe import api
+
+ payload = request.json or {}
+ force_reset = bool(payload.get("force_reset", True))
+ return jsonify(api.start_oauth_web("opencode", force_reset=force_reset, provider_id=provider_id))
+
+
@app.route("/backend/opencode/provider/<provider_id>/auth", methods=["POST"])
def backend_opencode_provider_auth_post(provider_id: str):
"""Persist an API key for a single OpenCode provider.