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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(auth): keep backend auth modes mutually exclusive (#609)
Call White3031e8c4436f
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 326437081..d4a4b4c11 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -1127,7 +1127,11 @@ class AgentAuthService:os.close(slave_fd)return process, master_fd, provider- async def _run_utility_command(self, *cmd: str) -> tuple[bool, str | None]:+ async def _run_utility_command(+ self,+ *cmd: str,+ env: dict[str, str] | None = None,+ ) -> tuple[bool, str | None]:"""Run a short CLI side-call. Returns ``(ok, error_excerpt)``.Callers that don't care about the outcome (setup preflight)@@ -1138,6 +1142,7 @@ class AgentAuthService:try:process = await asyncio.create_subprocess_exec(*cmd,+ env=env,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,)@@ -1292,6 +1297,8 @@ class AgentAuthService:await flow.reader_taskok, detail = await self._verify_login(flow)if ok:+ if flow.backend == "codex":+ await self._persist_backend_auth_mode(flow.backend, "oauth")await self._refresh_backend_runtime(flow.backend)await self._send_message(flow.context,@@ -1958,8 +1965,17 @@ class AgentAuthService:if backend == "codex":logout_ok, logout_error = await self._run_utility_command(binary, "logout")else:- logout_ok, logout_error = await self._run_utility_command(binary, "auth", "logout")settings_cleanup_error = await self._clear_claude_settings_env_for_logout()+ if settings_cleanup_error:+ logout_ok = False+ logout_error = settings_cleanup_error+ else:+ logout_ok, logout_error = await self._run_utility_command(+ binary,+ "auth",+ "logout",+ env=self._build_claude_full_subprocess_env(force_oauth=True),+ )try:config = getattr(self.controller, "config", None)@@ -2015,19 +2031,19 @@ class AgentAuthService:# 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:+ if backend == "claude" and settings_cleanup_error:return {"ok": True,"partial": True,- "warning": "logout_failed",- "detail": logout_error or "logout subprocess exited non-zero",+ "warning": "settings_cleanup_failed",+ "detail": settings_cleanup_error,}- if backend == "claude" and settings_cleanup_error:+ if not logout_ok:return {"ok": True,"partial": True,- "warning": "settings_cleanup_failed",- "detail": settings_cleanup_error,+ "warning": "logout_failed",+ "detail": logout_error or "logout subprocess exited non-zero",}return {"ok": True}@@ -2768,10 +2784,11 @@ class AgentAuthService:# 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.+ # than waiting for the user to click an extra Save button. The+ # persist helper also removes backend-specific API-key state when+ # OAuth is now the active mode, keeping the two auth sources+ # mutually exclusive on disk instead of relying on CLI logout side+ # effects.## Skipped for opencode: ``OpenCodeConfig`` has no ``auth_mode``# field (auth is per-provider, not global), so persisting one@@ -2802,6 +2819,22 @@ class AgentAuthService:"stale ANTHROPIC_* values may still override OAuth.") from err+ async def _clear_codex_api_key_for_oauth(self) -> None:+ try:+ from vibe.codex_config import apply_codex_auth++ await asyncio.to_thread(+ apply_codex_auth,+ auth_mode="oauth",+ api_key=None,+ base_url=None,+ )+ except Exception as err: # noqa: BLE001+ raise RuntimeError(+ "Failed to clear Codex API-key state after OAuth flow; "+ "stale OPENAI_API_KEY or base_url values may still override OAuth."+ ) from err+async def _read_pending_claude_oauth_settings_backup(self,) -> dict[str, str] | None:@@ -2995,10 +3028,88 @@ class AgentAuthService:return str(err)return None+ async def clear_claude_oauth_credentials_only(self) -> dict[str, Any]:+ """Remove Claude Code account tokens without changing API-key mode.++ Claude Code reapplies ``settings.json`` env values at startup. To make+ ``claude auth logout`` target stored account credentials instead of the+ just-saved API key, temporarily clear Anthropic env overrides, run the+ logout command, then restore the API-key settings exactly.+ """+ async with self._claude_oauth_lock:+ from vibe.claude_config import (+ clear_claude_oauth_credentials_files,+ read_claude_settings_env,+ )++ try:+ settings_backup = await asyncio.to_thread(read_claude_settings_env)+ except Exception as err: # noqa: BLE001+ detail = (+ "Failed to read Claude Code settings before clearing OAuth "+ f"credentials: {err}"+ )+ logger.warning(detail)+ return {+ "ok": True,+ "partial": True,+ "warning": "oauth_cleanup_failed",+ "detail": detail,+ }++ settings_cleanup_error = await self._clear_claude_settings_env_for_logout()+ logout_ok = False+ logout_error = None+ if not settings_cleanup_error:+ logout_env = self._build_claude_full_subprocess_env(force_oauth=True)+ logout_ok, logout_error = await self._run_utility_command(+ self._get_cli_binary("claude"),+ "auth",+ "logout",+ env=logout_env,+ )+ try:+ await asyncio.to_thread(clear_claude_oauth_credentials_files)+ except Exception as err: # noqa: BLE001+ logout_ok = False+ logout_error = str(err)+ restore_ok = await self._restore_claude_settings_env_after_oauth_failure(+ settings_backup or None+ )++ if settings_cleanup_error:+ return {+ "ok": True,+ "partial": True,+ "warning": "oauth_cleanup_failed",+ "detail": settings_cleanup_error,+ }+ if not restore_ok:+ return {+ "ok": True,+ "partial": True,+ "warning": "oauth_cleanup_failed",+ "detail": "Claude API-key settings were saved, but Avibe could not restore them after the OAuth cleanup probe.",+ }+ if not logout_ok:+ return {+ "ok": True,+ "partial": True,+ "warning": "oauth_cleanup_failed",+ "detail": logout_error or "claude auth logout exited non-zero",+ }+ return {"ok": True}++ async def clear_claude_oauth_for_api_key_mode(self) -> dict[str, Any]:+ """Backward-compatible name for API-key save cleanup."""+ return await self.clear_claude_oauth_credentials_only()+async def _persist_backend_auth_mode(self, backend: str, auth_mode: str) -> None:"""Persist V2Config.agents.<backend>.auth_mode for web and IM flows."""if backend == "claude" and auth_mode == "oauth":await self._clear_claude_settings_env_for_oauth()+ if backend == "codex" and auth_mode == "oauth":+ await self._clear_codex_api_key_for_oauth()try:config = getattr(self.controller, "config", None)target = getattr(getattr(config, "agents", None), backend, None)@@ -3023,7 +3134,15 @@ class AgentAuthService:backend == "claude"and not bool(getattr(target, "auth_mode_set", False)))- if not needs_mode_write and not needs_marker_write:+ needs_codex_oauth_cleanup = (+ backend == "codex"+ and auth_mode == "oauth"+ and (+ bool(getattr(target, "api_key", None))+ or bool(getattr(target, "base_url", None))+ )+ )+ if not needs_mode_write and not needs_marker_write and not needs_codex_oauth_cleanup:returntry:from config.v2_config import CONFIG_LOCK@@ -3033,12 +3152,18 @@ class AgentAuthService:target.auth_mode = auth_modeif needs_marker_write:target.auth_mode_set = True+ if needs_codex_oauth_cleanup:+ target.api_key = None+ target.base_url = Nonesaver()except ImportError:if needs_mode_write:target.auth_mode = auth_modeif needs_marker_write:target.auth_mode_set = True+ if needs_codex_oauth_cleanup:+ target.api_key = None+ target.base_url = Nonesaver()if loaded_config is not None and config is not None:compat_target = getattr(config, backend, None)@@ -3047,6 +3172,9 @@ class AgentAuthService:setattr(compat_target, "auth_mode", auth_mode)if needs_marker_write:setattr(compat_target, "auth_mode_set", True)+ if needs_codex_oauth_cleanup:+ setattr(compat_target, "api_key", None)+ setattr(compat_target, "base_url", None)except Exception as err: # noqa: BLE001logger.warning("Failed to persist auth_mode=%s after web flow for %s: %s",diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex f9970ed5d..b725fcc3d 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -146,6 +146,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):harness.service._read_codex_output = AsyncMock(return_value=None)harness.service._verify_login = AsyncMock(return_value=(True, "Logged in using ChatGPT"))harness.service._refresh_backend_runtime = AsyncMock()+ harness.service._persist_backend_auth_mode = AsyncMock()await runner.run(ScenarioStep(@@ -175,6 +176,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):fake_process.finish(0)await flow.waiter_task+ harness.service._persist_backend_auth_mode.assert_awaited_once_with("codex", "oauth")harness.service._refresh_backend_runtime.assert_awaited_once_with("codex")ScenarioExpect.step_history(runner, ["start_setup", "emit_device_url", "emit_device_code"])ScenarioExpect.text_contains(harness, "starting codex", index=0)diff --git a/tests/test_codex_config.py b/tests/test_codex_config.pyindex 92b0ef2a7..c029bed8f 100644--- a/tests/test_codex_config.py+++ b/tests/test_codex_config.py@@ -318,6 +318,36 @@ def test_apply_api_key_pins_credentials_store_to_file(tmp_path: Path) -> None:assert state["file_store_active"] is True+def test_apply_api_key_mode_drops_oauth_tokens(tmp_path: Path) -> None:+ """API-key mode is mutually exclusive with ChatGPT OAuth tokens."""+ home = tmp_path+ codex_home = home / ".codex"+ codex_home.mkdir()+ (codex_home / "auth.json").write_text(+ json.dumps(+ {+ "auth_mode": "chatgpt",+ "tokens": {"id_token": "abc"},+ "last_refresh": "2026-01-01T00:00:00Z",+ }+ ),+ encoding="utf-8",+ )++ codex_config.apply_codex_auth(+ auth_mode="api_key",+ api_key="sk-test",+ base_url=None,+ home=home,+ )++ auth = json.loads((codex_home / "auth.json").read_text(encoding="utf-8"))+ assert auth["auth_mode"] == "apikey"+ assert auth["OPENAI_API_KEY"] == "sk-test"+ assert "tokens" not in auth+ assert "last_refresh" not in auth++def test_apply_oauth_leaves_credentials_store_untouched(tmp_path: Path) -> None:"""Switching back to OAuth must not flip the user's chosen store —``codex login`` may legitimately want keyring storage."""diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.pyindex 5d5481afc..d3bb1fce4 100644--- a/tests/test_settings_disk_fallback.py+++ b/tests/test_settings_disk_fallback.py@@ -401,6 +401,63 @@ def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(assert state["settings_conflict"] is False+def test_claude_api_key_mode_wins_over_stale_oauth_credentials(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """API-key mode is mutually exclusive in Avibe's active auth state.++ Claude Code may keep account tokens in its own credentials file after+ the user switches Avibe to API-key mode. That raw token signal must not+ make the Settings UI or runtime treat OAuth as the active source.+ """+ _write_claude_settings(+ tmp_path,+ {+ "ANTHROPIC_API_KEY": "sk-ant-active-settings-key",+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",+ },+ )+ claude_dir = tmp_path / ".claude"+ (claude_dir / ".credentials.json").write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "stale-oauth",+ "refreshToken": "stale-refresh",+ }+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_dir))+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)+ monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)++ class _FakeAgent:+ auth_mode = "api_key"+ api_key = None+ base_url = None+ cli_path = "claude"++ class _FakeAgents:+ claude = _FakeAgent()++ class _FakeConfig:+ agents = _FakeAgents()++ monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())++ from vibe.api import get_claude_auth++ state = get_claude_auth()++ assert state["auth_mode"] == "api_key"+ assert state["active_auth_mode"] == "api_key"+ assert state["has_api_key"] is True+ assert state["has_oauth_credentials"] is True++def test_claude_settings_json_takes_precedence_over_legacy_v2config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -446,6 +503,11 @@ def test_save_claude_auth_writes_settings_json_and_clears_v2_secret(monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)+ cleanup_calls: list[bool] = []+ monkeypatch.setattr(+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",+ lambda _service=None: cleanup_calls.append(True) or {"ok": True},+ )from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Configfrom vibe.api import get_claude_auth, save_claude_auth@@ -485,6 +547,105 @@ def test_save_claude_auth_writes_settings_json_and_clears_v2_secret(state = get_claude_auth()assert state["api_key_source"] == "settings_json"assert state["base_url"] == "https://relay.example.invalid"+ assert cleanup_calls == [True]+++def test_save_claude_auth_reports_partial_when_oauth_cleanup_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)+ monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)+ monkeypatch.setattr(+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",+ lambda _service=None: {+ "ok": True,+ "partial": True,+ "warning": "oauth_cleanup_failed",+ "detail": "claude auth logout exited non-zero",+ },+ )++ from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config+ from vibe.api import save_claude_auth++ V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ).save()++ result = save_claude_auth(+ {+ "auth_mode": "api_key",+ "api_key": "sk-ant-new-settings-key",+ "base_url": "https://relay.example.invalid",+ }+ )++ assert result["ok"] is True+ assert result["active_auth_mode"] == "api_key"+ assert result["partial"] is True+ assert result["warning"] == "oauth_cleanup_failed"+ assert "logout" in result["detail"]+ settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())+ assert settings["env"]["ANTHROPIC_API_KEY"] == "sk-ant-new-settings-key"+ assert settings["env"]["ANTHROPIC_BASE_URL"] == "https://relay.example.invalid"+++def test_save_claude_auth_restores_pending_oauth_backup_before_writing_new_key(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)+ monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)++ from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config+ from vibe.api import save_claude_auth+ from vibe.claude_config import (+ read_claude_settings_env,+ write_claude_oauth_settings_backup,+ )++ write_claude_oauth_settings_backup(+ {+ "ANTHROPIC_API_KEY": "sk-old-backup",+ "ANTHROPIC_BASE_URL": "https://old-backup.example.invalid",+ }+ )++ V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ).save()++ cleanup_calls: list[object] = []+ monkeypatch.setattr(+ "vibe.api._clear_claude_oauth_credentials_after_api_key_save",+ lambda service=None: cleanup_calls.append(service) or {"ok": True},+ )++ result = save_claude_auth(+ {+ "auth_mode": "api_key",+ "api_key": "sk-new-key",+ "base_url": "https://new-relay.example.invalid",+ }+ )++ assert result["ok"] is True+ assert cleanup_calls and cleanup_calls[0] is not None+ assert read_claude_settings_env() == {+ "ANTHROPIC_API_KEY": "sk-new-key",+ "ANTHROPIC_BASE_URL": "https://new-relay.example.invalid",+ }def test_save_claude_auth_keeps_settings_token_over_legacy_v2_key(diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex 1ea559ddf..1bb51f06e 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -15,6 +15,7 @@ import contextlibimport jsonimport osfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import AsyncMockimport pytest@@ -28,6 +29,8 @@ from core.agent_auth_service import (from modules.agents.opencode.message_processor import extract_opencode_response_textfrom vibe.claude_config import (MANAGED_ENV_VALUES,+ clear_claude_oauth_credentials_files,+ get_claude_credentials_path,read_claude_oauth_settings_backup,read_claude_settings_env,restore_claude_settings_env,@@ -233,6 +236,7 @@ def test_cancel_removes_flow_and_marks_state(service: AgentAuthService) -> None:def test_post_web_success_hook_invocation_when_set(service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,) -> None:"""Hook fires once after a successful flow; absence is a no-op."""calls: list[str] = []@@ -240,11 +244,63 @@ def test_post_web_success_hook_invocation_when_set(def hook(backend: str) -> None:calls.append(backend)+ persist = AsyncMock()+ monkeypatch.setattr(service, "_persist_backend_auth_mode", persist)service._post_web_success_hook = hook_run(service._invoke_post_web_success_hook("codex"))+ persist.assert_awaited_once_with("codex", "oauth")assert calls == ["codex"]+def test_codex_oauth_success_clears_api_key_state(+ service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ codex_home = tmp_path / ".codex"+ codex_home.mkdir()+ monkeypatch.setenv("CODEX_HOME", str(codex_home))+ (codex_home / "auth.json").write_text(+ json.dumps(+ {+ "auth_mode": "apikey",+ "OPENAI_API_KEY": "sk-old",+ "tokens": {"id_token": "abc"},+ }+ ),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text(+ 'model_provider = "OpenAI"\n'+ "\n"+ "[model_providers.OpenAI]\n"+ 'base_url = "https://relay.example/v1"\n',+ encoding="utf-8",+ )+ saves: list[str] = []+ codex_cfg = SimpleNamespace(+ auth_mode="api_key",+ api_key="sk-old",+ base_url="https://relay.example/v1",+ )+ service.controller.config = SimpleNamespace(+ language="en",+ agents=SimpleNamespace(codex=codex_cfg),+ save=lambda: saves.append("saved"),+ )++ _run(service._invoke_post_web_success_hook("codex"))++ auth = json.loads((codex_home / "auth.json").read_text(encoding="utf-8"))+ assert auth["auth_mode"] == "chatgpt"+ assert auth["tokens"] == {"id_token": "abc"}+ assert "OPENAI_API_KEY" not in auth+ assert codex_cfg.auth_mode == "oauth"+ assert codex_cfg.api_key is None+ assert codex_cfg.base_url is None+ assert saves == ["saved"]++def test_post_web_success_hook_swallows_exceptions(service: AgentAuthService,monkeypatch: pytest.MonkeyPatch,@@ -254,7 +310,7 @@ def test_post_web_success_hook_swallows_exceptions(def hook(_backend: str) -> None:raise RuntimeError("boom")- monkeypatch.setattr("vibe.claude_config.apply_claude_auth", lambda **_kwargs: None)+ monkeypatch.setattr(service, "_persist_backend_auth_mode", AsyncMock())service._post_web_success_hook = hook# Should NOT raise._run(service._invoke_post_web_success_hook("claude"))@@ -467,7 +523,7 @@ def test_post_web_success_hook_unset_is_safe(service: AgentAuthService,monkeypatch: pytest.MonkeyPatch,) -> None:- monkeypatch.setattr("vibe.claude_config.apply_claude_auth", lambda **_kwargs: None)+ monkeypatch.setattr(service, "_persist_backend_auth_mode", AsyncMock())service._post_web_success_hook = None_run(service._invoke_post_web_success_hook("claude"))@@ -765,6 +821,91 @@ def test_remove_web_auth_surfaces_claude_settings_cleanup_failure(assert "Failed to clear Claude Code settings env" in result["detail"]+def test_clear_claude_oauth_for_api_key_mode_restores_key_settings(+ service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ restore_claude_settings_env(+ {+ "ANTHROPIC_API_KEY": "sk-active",+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",+ }+ )+ credentials_path = get_claude_credentials_path()+ credentials_path.write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "stale-oauth",+ "refreshToken": "stale-refresh",+ }+ }+ ),+ encoding="utf-8",+ )+ run_cmd = AsyncMock(return_value=(True, None))+ monkeypatch.setattr(service, "_run_utility_command", run_cmd)+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-shell-should-not-leak")+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "bearer-shell-should-not-leak")+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://shell.example.invalid")++ result = _run(service.clear_claude_oauth_for_api_key_mode())++ assert result == {"ok": True}+ run_cmd.assert_awaited_once()+ args = run_cmd.call_args.args+ kwargs = run_cmd.call_args.kwargs+ assert "auth" in args and "logout" in args+ assert "ANTHROPIC_API_KEY" not in kwargs["env"]+ assert "ANTHROPIC_AUTH_TOKEN" not in kwargs["env"]+ assert "ANTHROPIC_BASE_URL" not in kwargs["env"]+ assert read_claude_settings_env() == {+ "ANTHROPIC_API_KEY": "sk-active",+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",+ }+ assert not credentials_path.exists()+++def test_clear_claude_oauth_credentials_only_preserves_api_key_config(+ service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ restore_claude_settings_env(+ {+ "ANTHROPIC_API_KEY": "sk-active",+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",+ }+ )+ run_cmd = AsyncMock(return_value=(True, None))+ monkeypatch.setattr(service, "_run_utility_command", run_cmd)++ result = _run(service.clear_claude_oauth_credentials_only())++ assert result == {"ok": True}+ assert read_claude_settings_env() == {+ "ANTHROPIC_API_KEY": "sk-active",+ "ANTHROPIC_BASE_URL": "https://relay.example.invalid",+ }+++def test_clear_claude_oauth_credentials_files_removes_known_token_files(+ tmp_path: Path,+) -> None:+ claude_home = tmp_path / ".claude"+ claude_home.mkdir()+ current = claude_home / ".credentials.json"+ legacy = claude_home / "credentials.json"+ current.write_text("{}", encoding="utf-8")+ legacy.write_text("{}", encoding="utf-8")++ removed = clear_claude_oauth_credentials_files(tmp_path)++ assert str(current) in removed+ assert str(legacy) in removed+ assert not current.exists()+ assert not legacy.exists()++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.tsxindex b4b3614f8..07667e407 100644--- a/ui/src/components/settings/BackendOAuthPanel.tsx+++ b/ui/src/components/settings/BackendOAuthPanel.tsx@@ -31,6 +31,9 @@ export type BackendOAuthPanelProps = {* ``get*Auth`` endpoint). We still render a "re-authenticate" button so* rotating credentials without dropping to a terminal stays one click. */signedIn: boolean;+ /** When ``true`` render a Claude-only cleanup affordance for stale OAuth+ * tokens that are not the currently active auth source. */+ canRemoveAuth?: boolean;/** Heading text shown on the panel (e.g. "Claude account login"). */title: string;/** Short paragraph under the heading describing what login does. */@@ -74,6 +77,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({backend,opencodeProviderId,signedIn,+ canRemoveAuth,title,subtitle,signedInDetail,@@ -262,7 +266,10 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({setRemoving(true);setError(null);try {- const result = await api.removeBackendAuth(backend);+ const result =+ backend === 'claude' && canRemoveAuth && !signedIn+ ? await api.removeClaudeOAuthCredentials()+ : await api.removeBackendAuth(backend);if (!result.ok) {showToast(t('settings.backends.oauthRemoveFailed', {@@ -357,6 +364,11 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({if (backend === 'codex') return t('settings.backends.codexSignInButton');return t('settings.backends.opencodeProviderSignIn');})();+ const showRemoveAuth = (canRemoveAuth ?? signedIn) || state === 'success';+ const removeLabel =+ backend === 'claude' && canRemoveAuth && !signedIn+ ? t('settings.backends.oauthCleanStoredCredentials')+ : t('settings.backends.oauthRemove');return (<div className="flex flex-col gap-4 rounded-lg border border-border bg-surface-2/60 p-4">@@ -537,7 +549,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({{t('settings.backends.oauthInProgress')}</span>)}- {!hideRemove && (signedIn || state === 'success') && state !== 'starting' && state !== 'awaiting_code' && state !== 'verifying' && (+ {!hideRemove && showRemoveAuth && state !== 'starting' && state !== 'awaiting_code' && state !== 'verifying' && (<Buttontype="button"variant="ghost"@@ -547,7 +559,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({className="text-destructive hover:bg-destructive/10 hover:text-destructive"><Trash2 className="size-3.5" />- {removing ? t('common.removing') : t('settings.backends.oauthRemove')}+ {removing ? t('common.removing') : removeLabel}</Button>)}{isActive && (diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsxindex e45151770..6518769c7 100644--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx@@ -185,7 +185,14 @@ export const ClaudeProviderConfig: React.FC<{setEditingKey(false);// Claude restart is synthetic (one-shot CLI) so result.restart.ok// is always true; treat any falsy state defensively just in case.- if (result.restart?.ok === false) {+ if (result.partial) {+ showToast(+ t('settings.backends.claudeSavePartial', {+ detail: result.detail || result.warning || 'oauth_cleanup_failed',+ }),+ 'warning',+ );+ } else if (result.restart?.ok === false) {showToast(result.restart.message || t('settings.backends.claudeSaveSuccess'), 'warning');} else {showToast(t('settings.backends.claudeSaveSuccess'), 'success');@@ -258,10 +265,12 @@ export const ClaudeProviderConfig: React.FC<{{authMode === 'oauth' && (<BackendOAuthPanelbackend={BACKEND_ID}- // ``has_oauth_credentials`` is derived from Claude Code's- // own auth status when available, with file-based detection- // as a fallback for Linux/Docker.- signedIn={!!authState?.has_oauth_credentials}+ // Claude Code may still have account tokens in its own+ // store after the user switches Avibe to API-key mode.+ // The Settings UI should show OAuth as signed in only when+ // OAuth is the currently effective Avibe auth source.+ signedIn={authState?.active_auth_mode === 'oauth'}+ canRemoveAuth={!!authState?.has_oauth_credentials}title={t('settings.backends.claudeOauthPanelTitle')}subtitle={t('settings.backends.claudeOauthPanelSubtitle')}onActiveChange={setOauthFlowActive}diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsxindex 3b07b3504..af80d67f9 100644--- a/ui/src/components/settings/providers/CodexProviderConfig.tsx+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx@@ -285,7 +285,7 @@ export const CodexProviderConfig: React.FC<{{authMode === 'oauth' && (<BackendOAuthPanelbackend="codex"- signedIn={!!state?.has_chatgpt_tokens}+ signedIn={state?.active_auth_mode === 'oauth'}signedInDetail={(() => {// Compose a single-line identity (``email · plan ·// org``) from the JWT-decoded ``chatgpt_account``diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 87b9a07a1..b9de7c47a 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -74,6 +74,7 @@ export type ApiContextType = {flowId: string,) => Promise<OAuthWebMutationResult>;removeBackendAuth: (backend: 'claude' | 'codex') => Promise<OAuthWebMutationResult>;+ removeClaudeOAuthCredentials: () => 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@@ -973,6 +974,9 @@ export type ClaudeAuthState = {api_key_length: number;api_key_masked: string | null;api_key_source?: ClaudeApiKeySource;+ // Raw Claude Code account-token signal. This may remain true while Avibe+ // is actively using API-key mode, so UI "signed in" indicators should use+ // active_auth_mode instead.has_oauth_credentials: boolean;base_url: string | null;settings_path: string | null;@@ -993,6 +997,9 @@ export type ClaudeAuthPayload = {export type ClaudeAuthSaveResult = ClaudeAuthState & {restart?: BackendRestartResult;+ partial?: boolean;+ warning?: string;+ detail?: string;};// One entry in the OpenCode provider grid. The full catalog is built@@ -1599,6 +1606,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}),removeBackendAuth: (backend) =>postJson(`/api/backend/${encodeURIComponent(backend)}/auth/oauth/remove`, {}),+ removeClaudeOAuthCredentials: () =>+ postJson('/api/backend/claude/auth/oauth/credentials/remove', {}),removeBackendApiKey: (backend) =>postJson(`/api/backend/${encodeURIComponent(backend)}/auth/api-key/remove`, {}),testBackendAuth: (backend, options) =>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex fcfdab5b0..e33f58f84 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -274,6 +274,7 @@"claudeSaving": "Saving…","claudeSaveSuccess": "Claude auth saved","claudeSaveFailed": "Could not save Claude auth",+ "claudeSavePartial": "API key saved, but old Claude account credentials were not fully cleared: {{detail}}","oauthAuthUrlLabel": "Authorization URL","oauthInProgress": "Login in progress…","oauthStarting": "Starting OAuth flow…",@@ -285,6 +286,7 @@"oauthDeviceCodeCopied": "Device code copied to clipboard.","oauthReauthenticate": "Re-authenticate","oauthRemove": "Sign out",+ "oauthCleanStoredCredentials": "Clear account credentials","oauthRemoved": "Credentials removed.","oauthRemoveFailed": "Could not remove credentials: {{detail}}","oauthRemovePartial": "Credentials cleared from Avibe, but the backend CLI logout reported a problem: {{detail}}. The CLI's own files may still be present.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 486b7e69c..d97df14fa 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -274,6 +274,7 @@"claudeSaving": "保存中…","claudeSaveSuccess": "Claude 认证已保存","claudeSaveFailed": "保存 Claude 认证失败",+ "claudeSavePartial": "API Key 已保存,但旧 Claude 账号凭据未清理干净:{{detail}}","oauthAuthUrlLabel": "授权链接","oauthInProgress": "登录进行中…","oauthStarting": "正在启动 OAuth 流程…",@@ -285,6 +286,7 @@"oauthDeviceCodeCopied": "设备码已复制到剪贴板。","oauthReauthenticate": "重新登录","oauthRemove": "退出登录",+ "oauthCleanStoredCredentials": "清理账号凭据","oauthRemoved": "已移除凭据。","oauthRemoveFailed": "移除凭据失败:{{detail}}","oauthRemovePartial": "已清除 Avibe 内的凭据,但 CLI logout 返回错误:{{detail}}。CLI 自己的凭据文件可能仍在磁盘上。",diff --git a/vibe/api.py b/vibe/api.pyindex 240f74dc6..cf854d5fd 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -4423,6 +4423,28 @@ async def remove_backend_auth_async(backend: str) -> dict:return {"ok": False, "error": "remove_failed", "detail": str(exc)}+async def remove_claude_oauth_credentials_async() -> dict:+ """Clear only Claude Code OAuth credentials, preserving API-key auth."""+ service = _get_oauth_service()+ try:+ return await service.clear_claude_oauth_credentials_only()+ except Exception as exc: # noqa: BLE001+ logger.error("Claude OAuth credentials cleanup failed: %s", exc, exc_info=True)+ return {"ok": False, "error": "remove_failed", "detail": str(exc)}+++def remove_claude_oauth_credentials() -> dict:+ return _submit_oauth_coro(remove_claude_oauth_credentials_async(), timeout=30.0)+++def _clear_claude_oauth_credentials_after_api_key_save(service=None) -> dict:+ service = service or _get_oauth_service()+ return _submit_oauth_coro(+ service.clear_claude_oauth_credentials_only(),+ timeout=30.0,+ )++def remove_backend_api_key(backend: str) -> dict:"""Clear the stored API key for Claude / Codex without touching OAuth.@@ -5006,6 +5028,8 @@ def save_claude_auth(payload: dict) -> dict:except Exception:effective_base_url = None+ oauth_cleanup_service = _get_oauth_service() if auth_mode == "api_key" else None+from vibe.claude_config import apply_claude_authtry:@@ -5039,6 +5063,21 @@ def save_claude_auth(payload: dict) -> dict:config.agents.claude.base_url = Noneconfig.save()+ oauth_cleanup_result: dict | None = None+ if auth_mode == "api_key":+ try:+ oauth_cleanup_result = _clear_claude_oauth_credentials_after_api_key_save(+ oauth_cleanup_service+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("Failed to clear Claude OAuth credentials after API-key save: %s", exc)+ oauth_cleanup_result = {+ "ok": True,+ "partial": True,+ "warning": "oauth_cleanup_failed",+ "detail": str(exc),+ }+# Claude is one-shot per request — no daemon to restart. Return a# synthetic restart result so the UI handles the same response shape# as Codex / OpenCode and the toast wording can stay consistent.@@ -5047,6 +5086,10 @@ def save_claude_auth(payload: dict) -> dict:"ok": True,"message": "Claude relaunches per request; the next message uses the new auth.",}+ if isinstance(oauth_cleanup_result, dict) and oauth_cleanup_result.get("partial"):+ state["partial"] = True+ state["warning"] = oauth_cleanup_result.get("warning") or "oauth_cleanup_failed"+ state["detail"] = oauth_cleanup_result.get("detail")return statediff --git a/vibe/claude_config.py b/vibe/claude_config.pyindex 8ec7a94ec..a9a4d43f4 100644--- a/vibe/claude_config.py+++ b/vibe/claude_config.py@@ -91,6 +91,20 @@ def get_claude_credentials_path(home: Path | None = None) -> Path:return get_claude_credentials_paths(home)[0]+def clear_claude_oauth_credentials_files(home: Path | None = None) -> list[str]:+ """Remove known file-backed Claude Code OAuth credential stores."""+ removed: list[str] = []+ for path in get_claude_credentials_paths(home):+ try:+ path.unlink()+ removed.append(str(path))+ except FileNotFoundError:+ continue+ except OSError as exc:+ raise OSError(f"Failed to remove Claude OAuth credentials file {path}: {exc}") from exc+ return removed++def get_claude_oauth_settings_backup_path(home: Path | None = None) -> Path:"""Return Avibe's durable rollback file for Claude OAuth setup."""return get_claude_home(home) / OAUTH_SETTINGS_ENV_BACKUP_NAMEdiff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex dd2ee1990..d7b2baaaf 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3588,6 +3588,14 @@ async def backend_oauth_web_remove(backend: str):return jsonify(await api.remove_backend_auth_async(backend))[email protected]("/api/backend/claude/auth/oauth/credentials/remove", methods=["POST"])+async def claude_oauth_credentials_remove():+ """Clear Claude OAuth credentials without touching API-key auth."""+ from vibe import api++ return jsonify(await api.remove_claude_oauth_credentials_async())++@app.route("/api/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