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): symmetric 'Remove Key' for Claude + Codex (keep OAuth intact)

cyhd32ec7984b31
diff --git a/ui/src/components/settings/SettingsClaudeProviderPage.tsx b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
index b6c10356d..6fc81fa92 100644
--- a/ui/src/components/settings/SettingsClaudeProviderPage.tsx
+++ b/ui/src/components/settings/SettingsClaudeProviderPage.tsx
@@ -16,6 +16,7 @@ import {
Save,
Search,
Sparkles,
+ Trash2,
} from 'lucide-react';
import clsx from 'clsx';
@@ -101,6 +102,7 @@ export const SettingsClaudeProviderPage: React.FC = () => {
const [authState, setAuthState] = useState<ClaudeAuthState | null>(null);
const [authLoading, setAuthLoading] = useState(true);
const [authSaving, setAuthSaving] = useState(false);
+ const [removingKey, setRemovingKey] = useState(false);
const [authMode, setAuthMode] = useState<ClaudeAuthMode>('oauth');
const [apiKey, setApiKey] = useState('');
// ``editingKey`` mirrors the Codex page convention: false = show the
@@ -245,6 +247,43 @@ export const SettingsClaudeProviderPage: React.FC = () => {
? t('settings.backends.claudeApiKeyConfigured', { length: authState.api_key_length })
: t('settings.backends.claudeApiKeyMissing');
+ const onRemoveApiKey = async () => {
+ // Drop just the API key from V2Config; leaves any OAuth tokens in
+ // ``~/.claude/credentials.json`` (or the OS keychain) alone. Lets
+ // the user clear a stale key without having to also re-do OAuth.
+ const confirmed = window.confirm(
+ t('settings.backends.claudeApiKeyRemoveConfirm') as string,
+ );
+ if (!confirmed) return;
+ setRemovingKey(true);
+ try {
+ const result = await api.removeBackendApiKey('claude');
+ if (!result.ok) {
+ showToast(
+ t('settings.backends.claudeApiKeyRemoveFailed', {
+ detail: result.error || result.detail || 'unknown',
+ }),
+ 'error',
+ );
+ return;
+ }
+ const fresh = await api.getClaudeAuth();
+ setAuthState(fresh);
+ setBaseUrl(fresh.base_url || '');
+ setSavedBaseUrl(fresh.base_url || '');
+ setApiKey('');
+ setEditingKey(false);
+ showToast(t('settings.backends.claudeApiKeyRemoved'), 'success');
+ } catch (err: any) {
+ showToast(
+ t('settings.backends.claudeApiKeyRemoveFailed', { detail: err?.message || 'unknown' }),
+ 'error',
+ );
+ } finally {
+ setRemovingKey(false);
+ }
+ };
+
const onSaveAuth = async () => {
setAuthSaving(true);
try {
@@ -555,10 +594,30 @@ export const SettingsClaudeProviderPage: React.FC = () => {
setEditingKey(true);
setApiKey('');
}}
+ disabled={removingKey}
>
<Pencil className="size-3" />
{t('settings.backends.replaceApiKey')}
</Button>
+ {/* Symmetric to OpenCode's Remove affordance:
+ clear the saved API key while leaving OAuth
+ tokens in ``~/.claude/credentials.json`` /
+ keychain intact. Without this, a stuck key
+ keeps forcing the env-var path even after
+ the user signed in via OAuth. */}
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => void onRemoveApiKey()}
+ disabled={removingKey || editingKey}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <Trash2 className="size-3" />
+ {removingKey
+ ? t('common.removing')
+ : t('settings.backends.claudeApiKeyRemove')}
+ </Button>
</div>
) : (
<div className="relative">
diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsx
index 87f27c17c..13b57271a 100644
--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx
+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
-import { ArrowLeft, CheckCircle2, Info, KeyRound, Pencil, RotateCcw, Save } from 'lucide-react';
+import { ArrowLeft, CheckCircle2, Info, KeyRound, Pencil, RotateCcw, Save, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -60,6 +60,7 @@ export const SettingsCodexProviderPage: React.FC = () => {
const [state, setState] = useState<CodexAuthState | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
+ const [removingKey, setRemovingKey] = useState(false);
const [authMode, setAuthMode] = useState<CodexAuthMode>('oauth');
const [apiKey, setApiKey] = useState('');
// ``editingKey`` distinguishes "showing the saved masked key" (false,
@@ -129,6 +130,44 @@ export const SettingsCodexProviderPage: React.FC = () => {
? t('settings.backends.codexApiKeyConfigured', { length: state.api_key_length })
: t('settings.backends.codexApiKeyMissing');
+ const onRemoveApiKey = async () => {
+ // Drop just the API key (V2Config + auth.json's OPENAI_API_KEY),
+ // leave OAuth tokens intact. Codex's CLI prefers the API key when
+ // both are present — without this affordance a stale/invalid key
+ // keeps forcing 401s even after the user signed in via OAuth.
+ const confirmed = window.confirm(
+ t('settings.backends.codexApiKeyRemoveConfirm') as string,
+ );
+ if (!confirmed) return;
+ setRemovingKey(true);
+ try {
+ const result = await api.removeBackendApiKey('codex');
+ if (!result.ok) {
+ showToast(
+ t('settings.backends.codexApiKeyRemoveFailed', {
+ detail: result.error || result.detail || 'unknown',
+ }),
+ 'error',
+ );
+ return;
+ }
+ const fresh = await api.getCodexAuth();
+ setState(fresh);
+ setBaseUrl(fresh.base_url || '');
+ setSavedBaseUrl(fresh.base_url || '');
+ setApiKey('');
+ setEditingKey(false);
+ showToast(t('settings.backends.codexApiKeyRemoved'), 'success');
+ } catch (err: any) {
+ showToast(
+ t('settings.backends.codexApiKeyRemoveFailed', { detail: err?.message || 'unknown' }),
+ 'error',
+ );
+ } finally {
+ setRemovingKey(false);
+ }
+ };
+
const onSave = async () => {
setSaving(true);
try {
@@ -319,10 +358,31 @@ export const SettingsCodexProviderPage: React.FC = () => {
setEditingKey(true);
setApiKey('');
}}
+ disabled={removingKey}
>
<Pencil className="size-3" />
{t('settings.backends.replaceApiKey')}
</Button>
+ {/* Symmetric to OpenCode's Remove affordance: lets
+ the user drop a stale / invalid key without
+ re-signing in. Important for Codex specifically
+ because the CLI prefers ``OPENAI_API_KEY`` when
+ both api_key and OAuth tokens live in
+ ``auth.json`` — a stuck key keeps forcing 401s
+ even after a successful OAuth sign-in. */}
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() => void onRemoveApiKey()}
+ disabled={removingKey || editingKey}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <Trash2 className="size-3" />
+ {removingKey
+ ? t('common.removing')
+ : t('settings.backends.codexApiKeyRemove')}
+ </Button>
</div>
) : (
<div className="relative">
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index c4851bc68..d774ac68e 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -44,6 +44,12 @@ export type ApiContextType = {
flowId: string,
) => Promise<OAuthWebMutationResult>;
removeBackendAuth: (backend: 'claude' | 'codex') => Promise<OAuthWebMutationResult>;
+ // Selectively clear just the stored API key — leave OAuth credentials
+ // intact. Symmetric to OpenCode's per-provider DELETE: lets the user
+ // drop a stale key without re-signing in. Codex also restarts its
+ // persistent daemon so the cleared key takes effect on the next
+ // request.
+ removeBackendApiKey: (backend: 'claude' | 'codex') => Promise<OAuthWebMutationResult>;
testBackendAuth: (
backend: 'claude' | 'codex',
options?: { model?: string },
@@ -481,6 +487,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}),
removeBackendAuth: (backend) =>
postJson(`/backend/${encodeURIComponent(backend)}/auth/oauth/remove`, {}),
+ removeBackendApiKey: (backend) =>
+ postJson(`/backend/${encodeURIComponent(backend)}/auth/api-key/remove`, {}),
testBackendAuth: (backend, options) =>
postJson(`/backend/${encodeURIComponent(backend)}/auth/test`, {
...(options?.model ? { model: options.model } : {}),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 38ffb4673..285ce587e 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -206,6 +206,14 @@
"activeAuthApiKey": "Active: API Key",
"activeAuthNone": "Not signed in",
"replaceApiKey": "Replace",
+ "claudeApiKeyRemove": "Remove key",
+ "claudeApiKeyRemoveConfirm": "Remove the stored Anthropic API key? OAuth credentials are left untouched.",
+ "claudeApiKeyRemoved": "Stored Anthropic API key removed.",
+ "claudeApiKeyRemoveFailed": "Could not remove API key: {{detail}}",
+ "codexApiKeyRemove": "Remove key",
+ "codexApiKeyRemoveConfirm": "Remove the stored OpenAI API key from auth.json? Codex will fall back to OAuth tokens if present, or sit unconfigured if not.",
+ "codexApiKeyRemoved": "Stored OpenAI API key removed.",
+ "codexApiKeyRemoveFailed": "Could not remove API key: {{detail}}",
"opencodeProviderSignIn": "Sign in",
"opencodeProviderOauthSignedIn": "OAuth credentials stored.",
"opencodeProviderOauthPanelTitle": "Sign in to {{name}}",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 005684326..81ea61800 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -206,6 +206,14 @@
"activeAuthApiKey": "当前:API Key",
"activeAuthNone": "未登录",
"replaceApiKey": "替换",
+ "claudeApiKeyRemove": "移除 Key",
+ "claudeApiKeyRemoveConfirm": "确定要移除已保存的 Anthropic API Key 吗?OAuth 凭据不会受影响。",
+ "claudeApiKeyRemoved": "已移除 Anthropic API Key。",
+ "claudeApiKeyRemoveFailed": "移除 API Key 失败:{{detail}}",
+ "codexApiKeyRemove": "移除 Key",
+ "codexApiKeyRemoveConfirm": "确定要从 auth.json 移除已保存的 OpenAI API Key 吗?如果有 OAuth 凭据,Codex 会回落到 OAuth;否则会变成未配置状态。",
+ "codexApiKeyRemoved": "已移除 OpenAI API Key。",
+ "codexApiKeyRemoveFailed": "移除 API Key 失败:{{detail}}",
"opencodeProviderSignIn": "登录",
"opencodeProviderOauthSignedIn": "OAuth 凭据已保存。",
"opencodeProviderOauthPanelTitle": "登录 {{name}}",
diff --git a/vibe/api.py b/vibe/api.py
index 8e20571e1..188c7b18e 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2258,6 +2258,74 @@ def remove_backend_auth(backend: str) -> dict:
return {"ok": False, "error": "remove_failed", "detail": str(exc)}
+def remove_backend_api_key(backend: str) -> dict:
+ """Clear the stored API key for Claude / Codex without touching OAuth.
+
+ Mirrors OpenCode's "Remove key" vs "Sign out" split: Claude and
+ Codex can both carry ``api_key`` *and* OAuth credentials at the
+ same time, and the CLI picks api_key when both are present. Without
+ a way to drop just the API key, a stale or rejected key keeps
+ forcing 401s even after the user signed in via OAuth.
+
+ - **Codex**: re-applies ``apply_codex_auth(auth_mode='oauth')``
+ which pops ``OPENAI_API_KEY`` from ``~/.codex/auth.json`` and
+ keeps any ``tokens`` blob intact. V2Config's
+ ``agents.codex.api_key`` is also cleared and ``auth_mode`` is
+ flipped to ``oauth``. Triggers ``restart_backend('codex')`` so
+ the persistent daemon reloads.
+ - **Claude**: V2Config is the sole writer; we clear
+ ``agents.claude.api_key`` + ``base_url`` and flip ``auth_mode``
+ to ``oauth``. ``~/.claude/credentials.json`` (the OAuth token
+ file) is left alone. No daemon to restart — Claude relaunches
+ per request.
+ """
+ backend = (backend or "").strip().lower()
+ if backend not in {"claude", "codex"}:
+ return {"ok": False, "error": "unsupported_backend"}
+
+ if backend == "codex":
+ from vibe.codex_config import apply_codex_auth
+
+ try:
+ apply_codex_auth(auth_mode="oauth", api_key=None, base_url=None)
+ except Exception as exc: # noqa: BLE001
+ logger.error("apply_codex_auth(oauth) during remove-key failed: %s", exc, exc_info=True)
+ return {"ok": False, "error": "remove_failed", "detail": str(exc)}
+
+ # Clear V2Config api_key for both backends.
+ try:
+ with CONFIG_LOCK:
+ try:
+ config = load_config()
+ except FileNotFoundError:
+ config = V2Config()
+ target = getattr(getattr(config, "agents", None), backend, None)
+ if target is not None:
+ target.auth_mode = "oauth"
+ target.api_key = None
+ if backend == "codex":
+ target.base_url = None
+ config.save()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("V2Config clear during remove-key failed for %s: %s", backend, exc)
+
+ # Codex has a persistent daemon — refresh it so the cleared key
+ # actually takes effect on the next request. Claude is one-shot per
+ # request so a synthetic restart is enough.
+ restart: dict
+ if backend == "codex":
+ try:
+ restart = restart_backend("codex")
+ except Exception as exc: # noqa: BLE001
+ restart = {"ok": False, "message": str(exc)}
+ else:
+ restart = {
+ "ok": True,
+ "message": "Claude relaunches per request; the next message uses the new auth.",
+ }
+ return {"ok": True, "restart": restart}
+
+
def test_backend_auth(backend: str, model: Optional[str] = None) -> dict:
"""Send a single-token ``Hi`` probe through the backend CLI.
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index e469934b3..f1c31bf57 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1670,6 +1670,16 @@ def backend_oauth_web_remove(backend: str):
return jsonify(api.remove_backend_auth(backend))
[email protected]("/backend/<backend>/auth/api-key/remove", methods=["POST"])
+def backend_auth_api_key_remove(backend: str):
+ """Clear the stored API key (V2Config + Codex auth.json) without
+ touching OAuth credentials. Per-backend symmetry of OpenCode's
+ per-provider DELETE."""
+ from vibe import api
+
+ return jsonify(api.remove_backend_api_key(backend))
+
+
@app.route("/backend/<backend>/auth/test", methods=["POST"])
def backend_auth_test(backend: str):
"""Send a single-token probe through the backend CLI to verify auth."""