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): lock auth-mode radio mid-OAuth, allow base-URL-only OpenCode saves, surface logout failures

cyhc1c06aa72dc1
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index c89d54602..1c7710ac8 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -960,16 +960,34 @@ class AgentAuthService:
os.close(slave_fd)
return process, master_fd, provider
- async def _run_utility_command(self, *cmd: str) -> None:
+ async def _run_utility_command(self, *cmd: str) -> tuple[bool, str | None]:
+ """Run a short CLI side-call. Returns ``(ok, error_excerpt)``.
+
+ Callers that don't care about the outcome (setup preflight)
+ can ignore the return; ``remove_web_auth`` uses it to surface
+ ``codex logout`` / ``claude auth logout`` failures so the UI
+ doesn't lie about a partial sign-out.
+ """
try:
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
)
- await asyncio.wait_for(process.communicate(), timeout=20)
+ stdout, _ = await asyncio.wait_for(process.communicate(), timeout=20)
+ if process.returncode == 0:
+ return True, None
+ output = (stdout or b"").decode("utf-8", errors="replace").strip()
+ logger.info(
+ "Utility command failed (exit=%s) for %s: %s",
+ process.returncode,
+ " ".join(cmd),
+ output[:400] or "<no output>",
+ )
+ return False, output[:400] or f"exit {process.returncode}"
except Exception as err: # noqa: BLE001
- logger.info("Ignoring setup preflight command failure for %s: %s", " ".join(cmd), err)
+ logger.info("Utility command raised for %s: %s", " ".join(cmd), err)
+ return False, str(err)
async def _read_codex_output(
self,
@@ -1566,9 +1584,9 @@ class AgentAuthService:
binary = self._get_cli_binary(backend)
if backend == "codex":
- await self._run_utility_command(binary, "logout")
+ logout_ok, logout_error = await self._run_utility_command(binary, "logout")
else:
- await self._run_utility_command(binary, "auth", "logout")
+ logout_ok, logout_error = await self._run_utility_command(binary, "auth", "logout")
try:
config = getattr(self.controller, "config", None)
@@ -1609,6 +1627,18 @@ class AgentAuthService:
await asyncio.to_thread(hook, backend)
except Exception as err: # noqa: BLE001
logger.warning("post_web_success_hook failed after remove for %s: %s", backend, err)
+ # Surface logout failures even though V2Config was cleared. The
+ # on-disk credentials may still be intact (e.g. ``codex logout``
+ # missing, exited non-zero, or timed out), and the user needs
+ # to know about that partial sign-out rather than seeing a
+ # green toast and assuming the backend is fully signed out.
+ if not logout_ok:
+ return {
+ "ok": True,
+ "partial": True,
+ "warning": "logout_failed",
+ "detail": logout_error or "logout subprocess exited non-zero",
+ }
return {"ok": True}
async def test_web_auth(
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index aaf5e9157..3f63e1d92 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -340,7 +340,11 @@ def test_remove_web_auth_rejects_unsupported_backend(service: AgentAuthService)
def test_remove_web_auth_runs_logout_and_returns_ok(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- run_cmd = AsyncMock()
+ # ``_run_utility_command`` now returns ``(ok, error_excerpt)`` so
+ # ``remove_web_auth`` can surface a partial failure when ``codex
+ # logout`` / ``claude auth logout`` exits non-zero. The success
+ # path mocks must yield ``(True, None)``.
+ run_cmd = AsyncMock(return_value=(True, None))
monkeypatch.setattr(service, "_run_utility_command", run_cmd)
hook_calls: list[str] = []
service._post_web_success_hook = lambda b: hook_calls.append(b)
@@ -358,7 +362,7 @@ def test_remove_web_auth_runs_logout_and_returns_ok(
def test_remove_web_auth_codex_uses_logout_subcommand(
service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
) -> None:
- run_cmd = AsyncMock()
+ run_cmd = AsyncMock(return_value=(True, None))
monkeypatch.setattr(service, "_run_utility_command", run_cmd)
result = _run(service.remove_web_auth("codex"))
assert result == {"ok": True}
@@ -367,6 +371,24 @@ def test_remove_web_auth_codex_uses_logout_subcommand(
assert "logout" in args and "auth" not in args
+def test_remove_web_auth_surfaces_logout_failure(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Codex P2: a failed ``logout`` previously got swallowed and the
+ # API returned ``ok: true``, misleading the UI into showing a
+ # green sign-out toast while the backend creds remained intact.
+ # Now the failure rides back as ``partial`` + ``warning`` so the
+ # frontend can show a warning toast and the on-disk state can be
+ # cleaned up manually.
+ run_cmd = AsyncMock(return_value=(False, "exit 1: not logged in"))
+ monkeypatch.setattr(service, "_run_utility_command", run_cmd)
+ result = _run(service.remove_web_auth("claude"))
+ assert result["ok"] is True
+ assert result["partial"] is True
+ assert result["warning"] == "logout_failed"
+ assert "exit 1" in result["detail"]
+
+
def test_test_web_auth_rejects_unsupported_backend(service: AgentAuthService) -> None:
# OpenCode joins ``WEB_BACKENDS`` for OAuth start; ``test_web_auth``
# still rejects it (probe is run by the OpenCode daemon itself).
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index c89f7f4a0..6cab7024a 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -47,6 +47,14 @@ export type BackendOAuthPanelProps = {
* The parent typically re-reads ``getClaudeAuth`` / ``getCodexAuth`` here so
* the on-screen "signed in" indicators move. */
onSuccess?: () => void;
+ /** Fires whenever the panel's internal flow is mid-handshake
+ * (``state`` ∈ {starting, awaiting_code, verifying}). The parent
+ * uses this to disable auth-mode switching: on iOS Safari the
+ * device-code "Copy" tap was bouncing the surrounding OAuth /
+ * API-Key radio, which would tear down the in-progress flow. The
+ * callback keeps the source of truth here in the panel and lets
+ * the parent freeze the tab without duplicating state. */
+ onActiveChange?: (active: boolean) => void;
};
/**
@@ -71,6 +79,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
signedInDetail,
hideRemove,
onSuccess,
+ onActiveChange,
}) => {
const { t } = useTranslation();
const api = useApi();
@@ -108,6 +117,19 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
setError(null);
};
+ // Broadcast in-progress flow state to the parent so it can lock the
+ // auth-mode segmented radio. On iOS Safari the device-code "Copy" tap
+ // was bouncing that radio mid-flow — we can't reproduce the exact
+ // event path in code, but freezing the radio while in-flight makes
+ // the bug impossible to trigger regardless of how the rogue event
+ // gets there.
+ const onActiveChangeRef = useRef(onActiveChange);
+ onActiveChangeRef.current = onActiveChange;
+ useEffect(() => {
+ const active = state === 'starting' || state === 'awaiting_code' || state === 'verifying';
+ onActiveChangeRef.current?.(active);
+ }, [state]);
+
// Poll the status endpoint until the flow lands on a terminal state.
// The server holds the flow alive across requests on its own event loop,
// so dropping the timer on success/failure is safe — we'll never miss a
diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
index 6fc81fa92..9ea2333a7 100644
--- a/ui/src/components/settings/SettingsClaudeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
@@ -48,11 +48,16 @@ const SegmentedRadio: React.FC<{
onChange: (next: ClaudeAuthMode) => void;
options: ReadonlyArray<{ id: ClaudeAuthMode; label: string }>;
ariaLabel: string;
-}> = ({ value, onChange, options, ariaLabel }) => (
+ disabled?: boolean;
+}> = ({ value, onChange, options, ariaLabel, disabled }) => (
<div
role="radiogroup"
aria-label={ariaLabel}
- className="flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5"
+ aria-disabled={disabled || undefined}
+ className={clsx(
+ 'flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5',
+ disabled && 'opacity-60',
+ )}
>
{options.map((opt) => {
const active = value === opt.id;
@@ -62,12 +67,14 @@ const SegmentedRadio: React.FC<{
type="button"
role="radio"
aria-checked={active}
+ disabled={disabled}
onClick={() => onChange(opt.id)}
className={clsx(
'flex-1 rounded-[4px] px-3 text-[12px] transition-colors',
active
? 'border border-mint/30 bg-mint-soft font-bold text-mint'
- : 'font-medium text-muted hover:text-foreground'
+ : 'font-medium text-muted hover:text-foreground',
+ disabled && 'cursor-not-allowed',
)}
>
{opt.label}
@@ -115,6 +122,10 @@ export const SettingsClaudeProviderPage: React.FC = () => {
// Save buttons are noise).
const [savedAuthMode, setSavedAuthMode] = useState<ClaudeAuthMode>('oauth');
const [savedBaseUrl, setSavedBaseUrl] = useState('');
+ // Freeze the auth-mode segmented radio while the OAuth panel is mid-
+ // handshake. Same iOS Safari issue as the Codex page: a Copy tap
+ // can bounce the radio and tear down the in-flight login.
+ const [oauthFlowActive, setOauthFlowActive] = useState(false);
useEffect(() => {
let cancelled = false;
@@ -526,6 +537,7 @@ export const SettingsClaudeProviderPage: React.FC = () => {
onChange={setAuthMode}
options={modeOptions}
ariaLabel={t('settings.backends.claudeAuthModeLabel') as string}
+ disabled={oauthFlowActive}
/>
<p className="text-[12px] leading-relaxed text-muted">
{authMode === 'api_key'
@@ -545,6 +557,7 @@ export const SettingsClaudeProviderPage: React.FC = () => {
signedIn={!!authState?.has_oauth_credentials}
title={t('settings.backends.claudeOauthPanelTitle')}
subtitle={t('settings.backends.claudeOauthPanelSubtitle')}
+ onActiveChange={setOauthFlowActive}
onSuccess={() => {
// Re-fetch the auth state so the "Signed in" pill and
// any masked-key indicators reflect the fresh login
diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsx
index 87a790d05..f1180f793 100644
--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx
+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx
@@ -23,11 +23,16 @@ const SegmentedRadio: React.FC<{
onChange: (next: CodexAuthMode) => void;
options: ReadonlyArray<{ id: CodexAuthMode; label: string }>;
ariaLabel: string;
-}> = ({ value, onChange, options, ariaLabel }) => (
+ disabled?: boolean;
+}> = ({ value, onChange, options, ariaLabel, disabled }) => (
<div
role="radiogroup"
aria-label={ariaLabel}
- className="flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5"
+ aria-disabled={disabled || undefined}
+ className={clsx(
+ 'flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5',
+ disabled && 'opacity-60',
+ )}
>
{options.map((opt) => {
const active = value === opt.id;
@@ -37,12 +42,14 @@ const SegmentedRadio: React.FC<{
type="button"
role="radio"
aria-checked={active}
+ disabled={disabled}
onClick={() => onChange(opt.id)}
className={clsx(
'flex-1 rounded-[4px] px-3 text-[12px] transition-colors',
active
? 'border border-mint/30 bg-mint-soft font-bold text-mint'
- : 'font-medium text-muted hover:text-foreground'
+ : 'font-medium text-muted hover:text-foreground',
+ disabled && 'cursor-not-allowed',
)}
>
{opt.label}
@@ -75,6 +82,11 @@ export const SettingsCodexProviderPage: React.FC = () => {
// button that never has a no-op state is noisy and confusing.
const [savedAuthMode, setSavedAuthMode] = useState<CodexAuthMode>('oauth');
const [savedBaseUrl, setSavedBaseUrl] = useState('');
+ // When the OAuth panel is mid-flow (device code visible, polling),
+ // freeze the auth-mode segmented radio. Without this lock, an
+ // accidental tap (iOS Safari emits one after the "Copy" tap in
+ // testing) tears down the in-progress login.
+ const [oauthFlowActive, setOauthFlowActive] = useState(false);
useEffect(() => {
let cancelled = false;
@@ -291,6 +303,7 @@ export const SettingsCodexProviderPage: React.FC = () => {
onChange={setAuthMode}
options={modeOptions}
ariaLabel={t('settings.backends.codexAuthModeLabel') as string}
+ disabled={oauthFlowActive}
/>
<p className="text-[12px] leading-relaxed text-muted">
{authMode === 'api_key'
@@ -339,6 +352,7 @@ export const SettingsCodexProviderPage: React.FC = () => {
})()}
title={t('settings.backends.codexOauthPanelTitle')}
subtitle={t('settings.backends.codexOauthPanelSubtitle')}
+ onActiveChange={setOauthFlowActive}
onSuccess={() => {
// Re-read Codex auth state so the "ChatGPT tokens detected"
// line and any keychain hints catch up with the freshly
diff --git a/vibe/api.py b/vibe/api.py
index 39c3d0b4c..cce277b1d 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -3225,7 +3225,7 @@ _BASE_URL_UNCHANGED: object = object()
async def _save_opencode_provider_auth_async(
provider_id: str,
- api_key: str,
+ api_key: str | None,
base_url: Any = _BASE_URL_UNCHANGED,
) -> dict:
server = await _opencode_get_server()
@@ -3233,7 +3233,12 @@ async def _save_opencode_provider_auth_async(
return {"ok": False, "message": "OpenCode is disabled in V2Config"}
request_loop = asyncio.get_running_loop()
try:
- await server.set_api_key_auth(provider_id, api_key)
+ # Only upsert auth when the caller provided a fresh key. The
+ # base-URL-only edit path reuses the existing key on disk
+ # (already validated upstream), so re-PUTting it would be
+ # redundant and could even churn the daemon's connected cache.
+ if api_key:
+ await server.set_api_key_auth(provider_id, api_key)
finally:
await server.close_http_session(loop=request_loop)
@@ -3309,9 +3314,30 @@ def save_opencode_provider_auth(provider_id: str, payload: dict) -> dict:
if not isinstance(payload, dict):
return {"ok": False, "message": "Payload must be an object"}
raw_key = payload.get("api_key")
- if not isinstance(raw_key, str) or not raw_key.strip():
- return {"ok": False, "message": "api_key is required"}
- api_key = raw_key.strip()
+ # ``api_key`` is optional when the provider is already configured: the
+ # UI's "Replace" flow hides the plaintext and only sends ``base_url``
+ # for relay-URL fixes. Without this, base-URL-only edits fail unless
+ # the user retypes the secret. We detect "already configured" by
+ # consulting OpenCode's own auth store (``~/.local/share/opencode/
+ # auth.json``) — same source the provider catalog reads, so an empty
+ # api_key here matches the UX state where the masked key is shown.
+ api_key: str | None = raw_key.strip() if isinstance(raw_key, str) and raw_key.strip() else None
+ has_existing_key = False
+ if api_key is None:
+ try:
+ from vibe.opencode_config import read_opencode_provider_keys
+
+ existing_keys = read_opencode_provider_keys(logger_instance=logger)
+ has_existing_key = bool(existing_keys.get(provider_id.strip()))
+ except Exception as exc: # noqa: BLE001
+ logger.debug(
+ "OpenCode auth lookup failed during base-url-only save for %s: %s",
+ provider_id,
+ exc,
+ )
+ has_existing_key = False
+ if not has_existing_key:
+ return {"ok": False, "message": "api_key is required"}
base_url: Any = _BASE_URL_UNCHANGED
if "base_url" in payload: