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.

fix(backends): OpenCode OAuth disconnect + manual callback-URL paste

cyh536ecc4fa12f
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index ae8750d92..383689f88 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -1430,6 +1430,8 @@ class AgentAuthService:
flow = self._web_flows.get(flow_id)
if flow is None:
return {"ok": False, "error": "flow_not_found"}
+ if flow.backend == "opencode":
+ return await self._submit_opencode_callback_url(flow, code)
if flow.backend != "claude":
return {"ok": False, "error": "code_not_supported"}
if not flow.awaiting_code or flow.claude_client is None:
@@ -1742,6 +1744,38 @@ class AgentAuthService:
)
)
+ async def _submit_opencode_callback_url(self, flow: WebAuthFlow, code: str) -> dict[str, Any]:
+ """Forward a manually-pasted 127.0.0.1 callback URL to OpenCode.
+
+ Browser-redirect flows (poe, gitlab, openai-browser) leave the
+ user staring at ``http://127.0.0.1:<port>/callback?code=...`` in
+ their address bar — but that loopback belongs to the container,
+ not their machine, so the redirect can't complete on its own.
+ The Settings UI exposes a paste box; we GET the URL from inside
+ the container so OpenCode's own listener consumes it.
+ """
+ callback_url = (code or "").strip()
+ if not callback_url.lower().startswith(("http://127.0.0.1", "http://localhost")):
+ return {"ok": False, "error": "invalid_callback_url"}
+ provider_id = flow.provider
+ if not provider_id:
+ return {"ok": False, "error": "flow_missing_provider"}
+ server = await self._opencode_server()
+ if server is None:
+ return {"ok": False, "error": "opencode_server_unavailable"}
+ try:
+ await server.forward_oauth_redirect(provider_id, callback_url)
+ except Exception as err: # noqa: BLE001
+ logger.error(
+ "Failed to forward OpenCode OAuth callback for %s: %s",
+ provider_id, err, exc_info=True,
+ )
+ return {"ok": False, "error": "forward_failed", "detail": str(err)}
+ # The blocking ``wait_provider_oauth`` task observes completion
+ # on its own — the flow's state will flip to ``verifying`` then
+ # ``success`` within seconds.
+ return {"ok": True}
+
async def _wait_for_opencode_oauth_web(
self,
flow: WebAuthFlow,
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index f07dea946..5858288be 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -11,6 +11,7 @@ import signal
import socket
import subprocess
import time
+import urllib.parse
import threading
from asyncio.subprocess import Process
from typing import Any, Dict, List, Optional
@@ -904,13 +905,26 @@ class OpenCodeServerManager:
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.
+
+ Uses a dedicated short-lived ``ClientSession`` rather than the
+ shared ``_get_http_session()`` cache. Any other code path that
+ runs on a different event loop (e.g. a Flask request hitting
+ ``_get_opencode_providers_async`` via ``asyncio.run``) would
+ otherwise notice the cached session is bound to a stale loop,
+ close it, and recreate — which would mid-flight disconnect the
+ long-poll on the OAuth event loop with
+ ``aiohttp.ServerDisconnectedError``.
"""
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()
+ # Skip ``_request_scope`` (the per-call semaphore) too — it
+ # serialises all OpenCode HTTP calls behind a single lock, so
+ # holding it for 15 minutes would block every other UI request
+ # (provider list, save, restart, ...). The OAuth callback is
+ # idempotent server-side and safe to run concurrently.
+ async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/provider/{provider_id}/oauth/callback",
json=payload,
@@ -926,6 +940,52 @@ class OpenCodeServerManager:
except Exception: # pragma: no cover - parse-defensive
return json.loads(text) if text else {}
+ async def forward_oauth_redirect(
+ self,
+ provider_id: str,
+ callback_url: str,
+ *,
+ timeout: float = 15.0,
+ ) -> None:
+ """Forward a manually-pasted callback URL to OpenCode's listener.
+
+ Browser-redirect OAuth flows (poe, gitlab, openai-browser) end
+ with the provider redirecting to ``http://127.0.0.1:<port>/callback?...``
+ — a port OpenCode opens fresh per flow. From a *local* browser
+ that's automatic; from a remote browser (Vibe Remote regression
+ env, vibe_cloud tunnel, …) that URL is unreachable because the
+ loopback address belongs to the daemon's host, not the user's
+ machine.
+
+ This helper takes the URL the user pastes, validates that it
+ targets a 127.0.0.1 callback (don't blindly fetch external
+ URLs), and replays it from inside the container so OpenCode's
+ listener consumes it. ``wait_provider_oauth`` then returns
+ success on its own thread.
+ """
+ parsed = urllib.parse.urlparse(callback_url)
+ if parsed.hostname not in {"127.0.0.1", "localhost"}:
+ raise ValueError(
+ f"callback_url must target 127.0.0.1, got host={parsed.hostname!r}"
+ )
+ # ``provider_id`` isn't part of the OpenCode-managed URL — keep
+ # the parameter so the caller doesn't need to special-case
+ # which provider matches the loopback port. Forwarding any
+ # 127.0.0.1/<path> URL to OpenCode is safe because only the
+ # listener bound by ``authorize`` will accept it.
+ _ = provider_id # noqa: F841 — kept for symmetry / future routing
+ async with aiohttp.ClientSession() as session:
+ async with session.get(
+ callback_url,
+ timeout=aiohttp.ClientTimeout(total=timeout),
+ allow_redirects=False,
+ ) as resp:
+ # OpenCode replies with 200 + HTML on success or 4xx on
+ # bad state; we don't try to interpret the body — the
+ # blocking ``wait_provider_oauth`` will surface the real
+ # outcome via flow state.
+ _ = await resp.read()
+
async def get_provider_auth(self) -> Dict[str, Any]:
"""Fetch the per-provider auth-method index from OpenCode.
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index fd4992adb..3cc2be7b0 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -205,17 +205,15 @@ 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);
setError(null);
try {
+ // Claude → ``code#state`` (Anthropic's callback fragment).
+ // OpenCode browser-redirect → ``http://127.0.0.1:<port>/callback?...``
+ // (the URL the provider redirected to). Both flow through the
+ // same endpoint; the server side dispatches by backend type.
const result = await api.submitOAuthWebCode(backend, flowId, trimmed);
if (!result.ok) {
setError(result.error || result.detail || 'submit_failed');
@@ -288,6 +286,14 @@ 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 browser-redirect providers (poe, gitlab, openai-browser)
+ // return only ``url`` with no device code — the provider then redirects
+ // to ``http://127.0.0.1:<port>/callback?…``. From a remote browser
+ // that loopback is unreachable, so we ask the user to paste the URL
+ // their browser landed on; the backend replays it from inside the
+ // container so OpenCode's listener consumes it.
+ const opencodeAwaitingCallback =
+ backend === 'opencode' && state === 'awaiting_code' && url && !deviceCode;
// 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)
@@ -433,6 +439,39 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
</div>
)}
+ {opencodeAwaitingCallback && (
+ <div className="flex flex-col gap-2">
+ <Label htmlFor={`oauth-code-${backend}`} className="text-xs font-medium uppercase text-muted">
+ {t('settings.backends.opencodeCallbackUrlLabel')}
+ </Label>
+ <div className="flex gap-2">
+ <Input
+ id={`oauth-code-${backend}`}
+ type="text"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder="http://127.0.0.1:..../callback?code=..."
+ value={code}
+ onChange={(e) => setCode(e.target.value)}
+ className="font-mono"
+ disabled={submitting}
+ />
+ <Button
+ type="button"
+ variant="brand"
+ size="sm"
+ onClick={() => void submitCallback()}
+ disabled={submitting || !code.trim()}
+ >
+ {submitting ? t('common.submitting') : t('common.submit')}
+ </Button>
+ </div>
+ <p className="text-[12px] leading-relaxed text-muted">
+ {t('settings.backends.opencodeCallbackUrlHint')}
+ </p>
+ </div>
+ )}
+
<div className="flex items-center justify-between gap-2">
{showStartButton ? (
<Button
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 5fde6260c..95acb7897 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -35,7 +35,7 @@ export type ApiContextType = {
flowId: string,
) => Promise<OAuthWebStatus>;
submitOAuthWebCode: (
- backend: 'claude' | 'codex',
+ backend: 'claude' | 'codex' | 'opencode',
flowId: string,
code: string,
) => Promise<OAuthWebMutationResult>;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7f2911d06..b57b4dd94 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -207,6 +207,8 @@
"opencodeProviderOauthSignedIn": "OAuth credentials stored.",
"opencodeProviderOauthPanelTitle": "Sign in to {{name}}",
"opencodeProviderOauthPanelSubtitle": "Open the URL, complete login in your browser; the OpenCode daemon detects completion automatically.",
+ "opencodeCallbackUrlLabel": "Callback URL",
+ "opencodeCallbackUrlHint": "After authorizing, your browser will land on `http://127.0.0.1:<port>/callback?code=...` — copy that exact URL from the address bar and paste it here. Vibe Remote replays it inside the container so OpenCode's listener receives the credential.",
"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 573c36a12..db9586f49 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -207,6 +207,8 @@
"opencodeProviderOauthSignedIn": "OAuth 凭据已保存。",
"opencodeProviderOauthPanelTitle": "登录 {{name}}",
"opencodeProviderOauthPanelSubtitle": "打开链接并在浏览器里完成登录,OpenCode 守护进程会自动检测完成状态。",
+ "opencodeCallbackUrlLabel": "回调链接",
+ "opencodeCallbackUrlHint": "授权后浏览器会跳到 `http://127.0.0.1:<port>/callback?code=...`。从地址栏复制完整 URL 并粘贴到这里,Vibe Remote 会在容器内替你重放,让 OpenCode 的本地监听器收到凭据。",
"opencodeProvidersTitle": "服务商",
"opencodeProvidersSubtitle": "从 OpenCode Server 实时拉取 · 通过 API Key 或 OAuth 登录完成授权",
"opencodeProvidersCount": "已配置 {{configured}}/{{total}}",