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): add Sign out + Test connection to web OAuth UX

cyh59a768608970
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 9cb0082ba..819f54fa7 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -1352,6 +1352,149 @@ class AgentAuthService:
"error": flow.error,
}
+ async def remove_web_auth(self, backend: str) -> dict[str, Any]:
+ """Drop the stored credentials for a Claude/Codex backend.
+
+ Runs the backend's own ``logout`` subcommand so the on-disk state
+ is in sync, then clears the V2Config ``api_key`` / ``base_url`` and
+ 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:
+ return {"ok": False, "error": "unsupported_backend"}
+
+ binary = self._get_cli_binary(backend)
+ if backend == "codex":
+ await self._run_utility_command(binary, "logout")
+ else:
+ await self._run_utility_command(binary, "auth", "logout")
+
+ try:
+ config = getattr(self.controller, "config", None)
+ target = getattr(getattr(config, "agents", None), backend, None)
+ saver = getattr(config, "save", None) if config is not None else None
+ if target is not None and callable(saver):
+ try:
+ from config.v2_config import CONFIG_LOCK
+
+ with CONFIG_LOCK:
+ target.auth_mode = "oauth"
+ target.api_key = None
+ saver()
+ except ImportError:
+ target.auth_mode = "oauth"
+ target.api_key = None
+ saver()
+ except Exception as err: # noqa: BLE001
+ # Disk state has already been cleared; surface the V2Config
+ # write failure but report partial success so the UI shows
+ # the auth as removed (which is the user-visible truth).
+ logger.warning("Failed to clear V2Config after remove for %s: %s", backend, err)
+
+ # Notify the live controller — reuse the same hook path the
+ # OAuth-success flow uses, but skip the auth_mode persistence
+ # since we just rewrote those fields ourselves.
+ hook = self._post_web_success_hook
+ if callable(hook):
+ try:
+ 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)
+ return {"ok": True}
+
+ async def test_web_auth(self, backend: str, *, timeout: float = 45.0) -> dict[str, Any]:
+ """Send a 1-token probe ("Hi") through the backend CLI.
+
+ Validates both the credentials and the endpoint (when ``base_url``
+ is configured) by running ``claude --print "Hi"`` /
+ ``codex exec "Hi"``. Returns elapsed milliseconds + a short
+ response excerpt on success; surfaces stderr on failure.
+ """
+ if backend not in self.WEB_BACKENDS:
+ return {"ok": False, "error": "unsupported_backend"}
+
+ binary = self._get_cli_binary(backend)
+ prompt = "Hi"
+ if backend == "claude":
+ # ``-p`` switches Claude Code into non-interactive print mode
+ # and exits after the first complete reply. ``--bare`` strips
+ # the launch-time scaffolding (hooks, MCP, CLAUDE.md
+ # auto-discovery) so the probe never fails on environment
+ # quirks; we only care that the auth + endpoint round-trip
+ # works.
+ cmd = [binary, "-p", "--bare", prompt]
+ env_override = dict(os.environ)
+ # Layer V2Config-driven env on top so the test reflects what
+ # the live IM session would do at launch.
+ try:
+ from vibe.claude_config import build_claude_subprocess_env
+
+ env_override.update(
+ build_claude_subprocess_env(
+ getattr(self.controller.config, "claude", None),
+ base_env=env_override,
+ )
+ )
+ except Exception:
+ pass
+ else:
+ # Codex single-shot mode. ``-q`` would silence the rendered
+ # response — we want stdout so the UI can show a one-line
+ # excerpt as proof the round-trip succeeded.
+ cmd = [binary, "exec", prompt]
+ env_override = dict(os.environ)
+
+ started = time.monotonic()
+ try:
+ process = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=env_override,
+ )
+ try:
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
+ except asyncio.TimeoutError:
+ process.kill()
+ await process.wait()
+ return {
+ "ok": False,
+ "error": "timed_out",
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ }
+ except FileNotFoundError:
+ return {"ok": False, "error": "cli_not_found", "detail": binary}
+ except Exception as err: # noqa: BLE001
+ return {"ok": False, "error": "spawn_failed", "detail": str(err)}
+
+ duration_ms = int((time.monotonic() - started) * 1000)
+ stdout_text = (stdout or b"").decode("utf-8", errors="replace").strip()
+ stderr_text = (stderr or b"").decode("utf-8", errors="replace").strip()
+
+ if process.returncode != 0:
+ return {
+ "ok": False,
+ "error": "cli_failed",
+ "exit_code": process.returncode,
+ "detail": (stderr_text or stdout_text)[:600],
+ "duration_ms": duration_ms,
+ }
+
+ # Trim the response to a one-line excerpt — chunked output (Codex
+ # in particular emits multi-line markdown) would overflow the
+ # toast and isn't the point of the probe.
+ excerpt = ""
+ for line in stdout_text.splitlines():
+ line = line.strip()
+ if line:
+ excerpt = line[:240]
+ break
+ return {
+ "ok": True,
+ "duration_ms": duration_ms,
+ "excerpt": excerpt,
+ }
+
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)
@@ -1480,6 +1623,14 @@ class AgentAuthService:
task.cancel()
async def _invoke_post_web_success_hook(self, backend: str) -> None:
+ # OAuth completed via the web UI implies the user wants
+ # ``auth_mode = "oauth"``. Persist it before the controller-refresh
+ # hook fires so the live agent reloads with the right mode rather
+ # than waiting for the user to click an extra Save button. We
+ # 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")
hook = self._post_web_success_hook
if not callable(hook):
return
@@ -1488,6 +1639,34 @@ class AgentAuthService:
except Exception as err: # noqa: BLE001
logger.warning("post_web_success_hook failed for %s: %s", backend, err)
+ async def _persist_web_auth_mode(self, backend: str, auth_mode: str) -> None:
+ """Update V2Config.agents.<backend>.auth_mode if the controller has
+ a writable config. Skipped silently in test contexts where the
+ stub controller exposes a non-savable config object.
+ """
+ try:
+ config = getattr(self.controller, "config", None)
+ target = getattr(getattr(config, "agents", None), backend, None)
+ saver = getattr(config, "save", None) if config is not None else None
+ if target is None or not callable(saver):
+ return
+ if getattr(target, "auth_mode", None) == auth_mode:
+ return
+ try:
+ from config.v2_config import CONFIG_LOCK
+
+ with CONFIG_LOCK:
+ target.auth_mode = auth_mode
+ saver()
+ except ImportError:
+ target.auth_mode = auth_mode
+ saver()
+ except Exception as err: # noqa: BLE001
+ logger.warning(
+ "Failed to persist auth_mode=%s after web flow for %s: %s",
+ auth_mode, backend, err,
+ )
+
async def _terminate_web_flow(
self,
flow: WebAuthFlow,
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 9b5e95b4d..1f2638234 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -197,3 +197,96 @@ def test_post_web_success_hook_swallows_exceptions(service: AgentAuthService) ->
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"))
+
+
+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"}
+
+
+def test_remove_web_auth_runs_logout_and_returns_ok(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run_cmd = AsyncMock()
+ monkeypatch.setattr(service, "_run_utility_command", run_cmd)
+ hook_calls: list[str] = []
+ service._post_web_success_hook = lambda b: hook_calls.append(b)
+
+ result = _run(service.remove_web_auth("claude"))
+ assert result == {"ok": True}
+ # Claude logout subcommand is ``claude auth logout``.
+ run_cmd.assert_awaited_once()
+ args = run_cmd.call_args.args
+ assert "auth" in args and "logout" in args
+ # Hook fires so the live controller can refresh.
+ assert hook_calls == ["claude"]
+
+
+def test_remove_web_auth_codex_uses_logout_subcommand(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ run_cmd = AsyncMock()
+ monkeypatch.setattr(service, "_run_utility_command", run_cmd)
+ result = _run(service.remove_web_auth("codex"))
+ assert result == {"ok": True}
+ # Codex uses just ``codex logout`` (no nested ``auth`` subcommand).
+ args = run_cmd.call_args.args
+ assert "logout" in args and "auth" not in args
+
+
+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"}
+
+
+def test_test_web_auth_surfaces_cli_not_found(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _spawn(*_args, **_kwargs):
+ raise FileNotFoundError("no such cli")
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ result = _run(service.test_web_auth("codex"))
+ assert result["ok"] is False
+ assert result["error"] == "cli_not_found"
+
+
+def test_test_web_auth_happy_path_returns_excerpt(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A passing probe surfaces the first non-blank stdout line + duration."""
+
+ class _FakeProcess:
+ returncode = 0
+
+ async def communicate(self):
+ return (b"\nHello from the model\nmore text", b"")
+
+ async def _spawn(*_args, **_kwargs):
+ return _FakeProcess()
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ result = _run(service.test_web_auth("codex"))
+ assert result["ok"] is True
+ assert result["excerpt"] == "Hello from the model"
+ assert isinstance(result["duration_ms"], int)
+
+
+def test_test_web_auth_failure_surfaces_stderr(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ class _FakeProcess:
+ returncode = 7
+
+ async def communicate(self):
+ return (b"", b"Authentication failed: no credentials configured")
+
+ async def _spawn(*_args, **_kwargs):
+ return _FakeProcess()
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)
+ result = _run(service.test_web_auth("claude"))
+ assert result["ok"] is False
+ assert result["error"] == "cli_failed"
+ assert result["exit_code"] == 7
+ assert "Authentication failed" in (result.get("detail") or "")
diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsx
index cadad6833..713921255 100644
--- a/ui/src/components/settings/BackendOAuthPanel.tsx
+++ b/ui/src/components/settings/BackendOAuthPanel.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { AlertTriangle, CheckCircle2, Copy, ExternalLink, LogIn, X } from 'lucide-react';
+import { AlertTriangle, CheckCircle2, Copy, ExternalLink, LogIn, Trash2, X } from 'lucide-react';
import clsx from 'clsx';
import { Button } from '../ui/button';
@@ -68,6 +68,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
const [code, setCode] = useState('');
const [submitting, setSubmitting] = useState(false);
const [starting, setStarting] = useState(false);
+ const [removing, setRemoving] = useState(false);
const [error, setError] = useState<string | null>(null);
const pollTimer = useRef<number | null>(null);
const pollDeadlineRef = useRef<number | null>(null);
@@ -207,6 +208,33 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
}
};
+ const removeAuth = async () => {
+ setRemoving(true);
+ setError(null);
+ try {
+ const result = await api.removeBackendAuth(backend);
+ if (!result.ok) {
+ showToast(
+ t('settings.backends.oauthRemoveFailed', {
+ detail: result.error || result.detail || 'unknown',
+ }),
+ 'error',
+ );
+ return;
+ }
+ resetToIdle();
+ showToast(t('settings.backends.oauthRemoved'), 'success');
+ onSuccessRef.current?.();
+ } catch (err: any) {
+ showToast(
+ t('settings.backends.oauthRemoveFailed', { detail: err?.message || 'unknown' }),
+ 'error',
+ );
+ } finally {
+ setRemoving(false);
+ }
+ };
+
const copyUrl = async () => {
if (!url) return;
try {
@@ -363,7 +391,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
variant="brand"
size="default"
onClick={() => void startFlow()}
- disabled={starting}
+ disabled={starting || removing}
>
<LogIn className="size-3.5" />
{starting ? t('common.loading') : startLabel}
@@ -373,6 +401,19 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({
{t('settings.backends.oauthInProgress')}
</span>
)}
+ {(signedIn || state === 'success') && state !== 'starting' && state !== 'awaiting_code' && state !== 'verifying' && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => void removeAuth()}
+ disabled={removing || starting}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <Trash2 className="size-3.5" />
+ {removing ? t('common.removing') : t('settings.backends.oauthRemove')}
+ </Button>
+ )}
{isActive && (
<Button
type="button"
diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsx
new file mode 100644
index 000000000..77137c3cf
--- /dev/null
+++ b/ui/src/components/settings/BackendTestPanel.tsx
@@ -0,0 +1,113 @@
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Play, Zap } from 'lucide-react';
+import clsx from 'clsx';
+
+import { Button } from '../ui/button';
+import { useApi } from '@/context/ApiContext';
+import type { BackendAuthTestResult } from '@/context/ApiContext';
+import { useToast } from '@/context/ToastContext';
+
+type Backend = 'claude' | 'codex';
+
+export type BackendTestPanelProps = {
+ backend: Backend;
+};
+
+/**
+ * Settings → Backends connectivity probe. Mirrors the ``cdTest2`` /
+ * ``cxTest`` panels in ``design.pen``: sends a single ``Hi`` prompt
+ * through the backend CLI so the user can confirm both the credentials
+ * and the endpoint (Base URL) round-trip end-to-end. Works in both
+ * OAuth and API-Key modes — the underlying CLI uses whichever auth
+ * source is configured at launch.
+ */
+export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [testing, setTesting] = useState(false);
+ const [lastResult, setLastResult] = useState<BackendAuthTestResult | null>(null);
+
+ const runTest = async () => {
+ setTesting(true);
+ try {
+ const result = await api.testBackendAuth(backend);
+ setLastResult(result);
+ if (result.ok) {
+ showToast(
+ t('settings.backends.testConnectionSuccessToast', { ms: result.duration_ms ?? '?' }),
+ 'success',
+ );
+ } else {
+ showToast(
+ t('settings.backends.testConnectionFailedToast', {
+ detail: result.error || result.detail || 'unknown',
+ }),
+ 'error',
+ );
+ }
+ } catch (err: any) {
+ const fallback = { ok: false, error: err?.message || 'test_failed' } as BackendAuthTestResult;
+ setLastResult(fallback);
+ showToast(t('settings.backends.testConnectionFailedToast', { detail: fallback.error }), 'error');
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ const resultLine = (() => {
+ if (!lastResult) return null;
+ if (lastResult.ok) {
+ return t('settings.backends.testConnectionLastOk', {
+ ms: lastResult.duration_ms ?? '?',
+ });
+ }
+ const detail = lastResult.error || lastResult.detail || 'unknown';
+ return t('settings.backends.testConnectionLastFail', { detail });
+ })();
+
+ return (
+ <div
+ className={clsx(
+ 'flex items-center justify-between gap-4 rounded-xl border border-border bg-foreground/[0.025] p-5',
+ )}
+ >
+ <div className="flex items-center gap-3">
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-[10px] border border-mint/30 bg-mint-soft">
+ <Zap size={18} className="text-mint" />
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <p className="text-[14px] font-bold text-foreground">
+ {t('settings.backends.testConnectionTitle')}
+ </p>
+ <p className="text-[12px] text-muted">
+ {t('settings.backends.testConnectionSubtitle')}
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-3">
+ {resultLine && (
+ <span
+ className={clsx(
+ 'font-mono text-[11px] font-semibold',
+ lastResult?.ok ? 'text-mint' : 'text-destructive',
+ )}
+ >
+ {resultLine}
+ </span>
+ )}
+ <Button
+ type="button"
+ variant="brand"
+ size="sm"
+ onClick={() => void runTest()}
+ disabled={testing}
+ >
+ <Play className="size-3" />
+ {testing ? t('common.testing') : t('settings.backends.testConnectionRun')}
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
index a38fcd676..481651c18 100644
--- a/ui/src/components/settings/SettingsClaudeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
@@ -24,6 +24,7 @@ import { Label } from '../ui/label';
import { SettingsPageShell } from './SettingsPageShell';
import { BackendLifecycleChip } from './BackendLifecycleChip';
import { BackendOAuthPanel } from './BackendOAuthPanel';
+import { BackendTestPanel } from './BackendTestPanel';
import { ToggleSwitch } from './SettingsPrimitives';
import { useApi } from '@/context/ApiContext';
import type { ClaudeAuthMode, ClaudeAuthState } from '@/context/ApiContext';
@@ -560,15 +561,27 @@ export const SettingsClaudeProviderPage: React.FC = () => {
</p>
</div>
- <div className="flex justify-end">
- <Button variant="brand" size="default" onClick={onSaveAuth} disabled={authSaving}>
- <Save className="size-3.5" />
- {authSaving ? t('settings.backends.claudeSaving') : t('settings.backends.claudeSave')}
- </Button>
- </div>
+ {/* OAuth mode persists ``auth_mode=oauth`` automatically on
+ successful sign-in (see ``_invoke_post_web_success_hook``),
+ so the Save button only needs to surface in API-key mode
+ where the user still has to commit the key / Base URL. */}
+ {authMode === 'api_key' && (
+ <div className="flex justify-end">
+ <Button variant="brand" size="default" onClick={onSaveAuth} disabled={authSaving}>
+ <Save className="size-3.5" />
+ {authSaving ? t('settings.backends.claudeSaving') : t('settings.backends.claudeSave')}
+ </Button>
+ </div>
+ )}
</CardContent>
</Card>
)}
+
+ {/* Connectivity probe — matches design.pen cdTest2 panel.
+ Works in both OAuth and API-key modes because the underlying
+ ``claude -p "Hi"`` subprocess inherits whichever auth source
+ V2Config selects at launch. */}
+ {!authLoading && <BackendTestPanel backend={BACKEND_ID} />}
</div>
)}
</SettingsPageShell>
diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsx
index a5a3ccb8c..affe05c3b 100644
--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx
+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx
@@ -12,6 +12,7 @@ import { useApi } from '@/context/ApiContext';
import type { CodexAuthMode, CodexAuthState } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { BackendOAuthPanel } from './BackendOAuthPanel';
+import { BackendTestPanel } from './BackendTestPanel';
import { SettingsPageShell } from './SettingsPageShell';
// Mirrors the segmented-radio pattern in shared/RoutingConfigPanel.tsx so
@@ -283,15 +284,25 @@ export const SettingsCodexProviderPage: React.FC = () => {
</p>
</div>
- <div className="flex justify-end">
- <Button variant="brand" size="default" onClick={onSave} disabled={saving}>
- <Save className="size-3.5" />
- {saving ? t('settings.backends.codexSaving') : t('settings.backends.codexSave')}
- </Button>
- </div>
+ {/* OAuth mode persists ``auth_mode=oauth`` automatically on
+ successful sign-in, so the Save button only surfaces for
+ api_key mode. */}
+ {authMode === 'api_key' && (
+ <div className="flex justify-end">
+ <Button variant="brand" size="default" onClick={onSave} disabled={saving}>
+ <Save className="size-3.5" />
+ {saving ? t('settings.backends.codexSaving') : t('settings.backends.codexSave')}
+ </Button>
+ </div>
+ )}
</CardContent>
</Card>
)}
+ {!loading && (
+ <div className="mt-4">
+ <BackendTestPanel backend="codex" />
+ </div>
+ )}
</SettingsPageShell>
);
};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 06ede5d49..24c18f768 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -33,6 +33,8 @@ export type ApiContextType = {
code: string,
) => Promise<OAuthWebMutationResult>;
cancelOAuthWeb: (backend: 'claude' | 'codex', flowId: string) => Promise<OAuthWebMutationResult>;
+ removeBackendAuth: (backend: 'claude' | 'codex') => Promise<OAuthWebMutationResult>;
+ testBackendAuth: (backend: 'claude' | 'codex') => Promise<BackendAuthTestResult>;
getOpencodeProviders: () => Promise<OpencodeProviderListResult>;
setOpencodeProviderAuth: (
providerId: string,
@@ -250,6 +252,15 @@ export type OAuthWebMutationResult = {
detail?: string;
};
+export type BackendAuthTestResult = {
+ ok: boolean;
+ duration_ms?: number;
+ excerpt?: string;
+ exit_code?: number;
+ error?: string;
+ detail?: string;
+};
+
export type OpencodeProvider = {
id: string;
name: string;
@@ -390,6 +401,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/cancel`, {
flow_id: flowId,
}),
+ removeBackendAuth: (backend) =>
+ postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/remove`, {}),
+ testBackendAuth: (backend) =>
+ postJson(`/backend/${encodeURIComponent(backend)}/auth/test`, {}),
getOpencodeProviders: () => getJson('/backend/opencode/providers'),
setOpencodeProviderAuth: (providerId, apiKey, baseUrl) =>
// Forward ``base_url`` only when the caller passed something
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index bdec7fd3a..e62fc0b6d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -43,7 +43,12 @@
"close": "Close",
"submit": "Submit",
"submitting": "Submitting…",
+ "copy": "Copy",
"copyFailed": "Copy failed, please copy it manually",
+ "remove": "Remove",
+ "removing": "Removing…",
+ "test": "Test",
+ "testing": "Testing…",
"themeSystem": "System theme",
"themeLight": "Light theme",
"themeDark": "Dark theme",
@@ -173,6 +178,16 @@
"oauthUrlCopied": "URL copied to clipboard.",
"oauthDeviceCodeCopied": "Device code copied to clipboard.",
"oauthReauthenticate": "Re-authenticate",
+ "oauthRemove": "Sign out",
+ "oauthRemoved": "Credentials removed.",
+ "oauthRemoveFailed": "Could not remove credentials: {{detail}}",
+ "testConnectionTitle": "Test connection",
+ "testConnectionSubtitle": "Send a one-token \"Hi\" prompt to verify the session, the model, and any custom Base URL.",
+ "testConnectionRun": "Run test",
+ "testConnectionLastOk": "Last run: ok · {{ms}} ms",
+ "testConnectionLastFail": "Last run failed: {{detail}}",
+ "testConnectionSuccessToast": "Backend reachable · {{ms}} ms",
+ "testConnectionFailedToast": "Backend test failed: {{detail}}",
"opencodeProvidersTitle": "Providers",
"opencodeProvidersSubtitle": "Lazy-loaded from the OpenCode server · auth handled via API key or `opencode auth login`",
"opencodeProvidersCount": "{{configured}}/{{total}} configured",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index a73a7ac3d..6a392a67b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -43,7 +43,12 @@
"close": "关闭",
"submit": "提交",
"submitting": "提交中…",
+ "copy": "复制",
"copyFailed": "复制失败,请手动复制",
+ "remove": "移除",
+ "removing": "移除中…",
+ "test": "测试",
+ "testing": "测试中…",
"themeSystem": "跟随系统主题",
"themeLight": "浅色主题",
"themeDark": "深色主题",
@@ -173,6 +178,16 @@
"oauthUrlCopied": "链接已复制到剪贴板。",
"oauthDeviceCodeCopied": "设备码已复制到剪贴板。",
"oauthReauthenticate": "重新登录",
+ "oauthRemove": "退出登录",
+ "oauthRemoved": "已移除凭据。",
+ "oauthRemoveFailed": "移除凭据失败:{{detail}}",
+ "testConnectionTitle": "测试连通性",
+ "testConnectionSubtitle": "发送一条 \"Hi\" 测试 prompt,用来验证账号、模型和自定义 Base URL 是否可用。",
+ "testConnectionRun": "运行测试",
+ "testConnectionLastOk": "上次:成功 · {{ms}} ms",
+ "testConnectionLastFail": "上次失败:{{detail}}",
+ "testConnectionSuccessToast": "后端可达 · {{ms}} ms",
+ "testConnectionFailedToast": "后端测试失败:{{detail}}",
"opencodeProvidersTitle": "服务商",
"opencodeProvidersSubtitle": "从 OpenCode Server 实时拉取 · 通过 API Key 或 `opencode auth login` 完成授权",
"opencodeProvidersCount": "已配置 {{configured}}/{{total}}",
diff --git a/vibe/api.py b/vibe/api.py
index 3348fb7eb..e79193c6a 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2210,6 +2210,32 @@ def submit_oauth_web_code(flow_id: str, code: str) -> dict:
return {"ok": False, "error": "submit_failed", "detail": str(exc)}
+def remove_backend_auth(backend: str) -> dict:
+ """Clear stored credentials for Claude or Codex (web Settings)."""
+ backend = (backend or "").strip().lower()
+ if backend not in _WEB_OAUTH_BACKENDS:
+ return {"ok": False, "error": "unsupported_backend"}
+ service = _get_oauth_service()
+ try:
+ return _submit_oauth_coro(service.remove_web_auth(backend), timeout=30.0)
+ except Exception as exc: # noqa: BLE001
+ logger.error("Web auth remove failed for %s: %s", backend, exc, exc_info=True)
+ return {"ok": False, "error": "remove_failed", "detail": str(exc)}
+
+
+def test_backend_auth(backend: str) -> dict:
+ """Send a single-token ``Hi`` probe through the backend CLI."""
+ backend = (backend or "").strip().lower()
+ if backend not in _WEB_OAUTH_BACKENDS:
+ return {"ok": False, "error": "unsupported_backend"}
+ service = _get_oauth_service()
+ try:
+ return _submit_oauth_coro(service.test_web_auth(backend), timeout=60.0)
+ except Exception as exc: # noqa: BLE001
+ logger.error("Web auth test failed for %s: %s", backend, exc, exc_info=True)
+ return {"ok": False, "error": "test_failed", "detail": str(exc)}
+
+
def cancel_oauth_web(flow_id: str) -> dict:
flow_id = (flow_id or "").strip()
if not flow_id:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index df4ec2f46..7fcb4cacf 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1662,6 +1662,22 @@ def backend_oauth_web_cancel(backend: str):
return jsonify(api.cancel_oauth_web(flow_id))
[email protected]("/backend/<backend>/auth/oauth/remove", methods=["POST"])
+def backend_oauth_web_remove(backend: str):
+ """Clear stored credentials for a Claude/Codex backend."""
+ from vibe import api
+
+ return jsonify(api.remove_backend_auth(backend))
+
+
[email protected]("/backend/<backend>/auth/test", methods=["POST"])
+def backend_auth_test(backend: str):
+ """Send a single-token probe through the backend CLI to verify auth."""
+ from vibe import api
+
+ return jsonify(api.test_backend_auth(backend))
+
+
@app.route("/backend/opencode/providers", methods=["GET"])
def backend_opencode_providers():
"""Return the merged OpenCode provider catalog for the Settings UI.