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(claude): align OAuth status and test probe (#603)
Call White5a817be5f06c
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 059fad31e..65f4ca738 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -105,7 +105,10 @@ def _classify_test_failure(stdout: str, stderr: str) -> str:if not text.strip():return "cli_failed"- # Auth-side rejections (key wrong / revoked / not present).+ if "not logged in" in text:+ return "not_logged_in"++ # Auth-side rejections (key wrong / revoked / rejected).auth_needles = ("401","unauthorized",@@ -114,7 +117,6 @@ def _classify_test_failure(stdout: str, stderr: str) -> str:"api key not valid","authentication","auth failed",- "not logged in","missing api key","no api key",)@@ -429,6 +431,29 @@ class AgentAuthService:cli_path = getattr(backend_cfg, "cli_path", None) or getattr(backend_cfg, "binary", None)return cli_path or backend+ def _resolve_claude_probe_cwd(self) -> str:+ """Return the cwd that a Settings Claude probe should execute in.++ Plain ``claude -p`` loads project hooks, MCP config, and CLAUDE.md from+ the process cwd. Use the same default runtime cwd as live Agent turns so+ the Settings test reflects the actual Claude runtime instead of the UI+ server launch directory.+ """+ config = getattr(getattr(self, "controller", None), "config", None)+ candidates = (+ getattr(self._resolve_backend_config("claude"), "cwd", None),+ getattr(getattr(config, "runtime", None), "default_cwd", None),+ )+ for raw in candidates:+ if isinstance(raw, str) and raw.strip():+ path = os.path.abspath(os.path.expanduser(raw.strip()))+ try:+ os.makedirs(path, exist_ok=True)+ return path+ except OSError as exc:+ logger.warning("Failed to prepare Claude Settings probe cwd=%s: %s", path, exc)+ return os.getcwd()+def _build_claude_full_subprocess_env(self, *, force_oauth: bool = False) -> dict[str, str]:"""Return a complete environment for direct Claude CLI subprocesses.@@ -2077,14 +2102,19 @@ class AgentAuthService:binary = self._get_cli_binary(backend)prompt = "Hi"+ probe_cwd = Noneif backend == "claude":+ probe_cwd = self._resolve_claude_probe_cwd()# ``-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"]+ # and exits after the first complete reply. Deliberately do+ # not pass ``--bare`` here: recent Claude Code builds document+ # that bare mode skips OAuth/keychain reads and only accepts+ # API-key auth. This Settings probe should answer the user's+ # real question: whether the current Avibe Claude setup can+ # run an Agent turn. It follows the normal print-mode launch+ # path used by live Claude sessions.+ cmd = [binary]+ cmd.append("-p")if isinstance(model, str) and model.strip():cmd.extend(["--model", model.strip()])cmd.append(prompt)@@ -2144,6 +2174,7 @@ class AgentAuthService:stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,env=env_override,+ cwd=probe_cwd,)try:stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.pyindex b79d77314..5d5481afc 100644--- a/tests/test_settings_disk_fallback.py+++ b/tests/test_settings_disk_fallback.py@@ -22,6 +22,7 @@ The fixes:from __future__ import annotationsimport json+import subprocessimport threadingfrom pathlib import Path@@ -95,6 +96,272 @@ def _write_claude_settings(home: Path, env: dict) -> None:)+def _assert_claude_managed_env(env: dict) -> None:+ assert env["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"] == "1"+ assert env["CLAUDE_CODE_ATTRIBUTION_HEADER"] == "0"+++def test_claude_oauth_state_reads_current_dot_credentials_file(tmp_path: Path) -> None:+ """Claude Code 2.x writes OAuth tokens to ``.credentials.json`` on Linux.++ The Settings page must treat that as a real OAuth login; otherwise the+ user sees "Not signed in" immediately after a successful OAuth flow.+ """+ claude_dir = tmp_path / ".claude"+ claude_dir.mkdir()+ (claude_dir / ".credentials.json").write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "access-token",+ "refreshToken": "refresh-token",+ }+ }+ ),+ encoding="utf-8",+ )++ from vibe.claude_config import read_claude_oauth_signed_in++ assert read_claude_oauth_signed_in(home=tmp_path) is True+++def test_get_claude_auth_prefers_cli_oauth_status(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The Settings page should trust Claude Code's own auth status first.++ This covers keychain-backed installs and avoids depending solely on the+ exact credentials filename used by a specific Claude Code release.+ """+ _write_claude_settings(tmp_path, {})+ 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)++ class _FakeAgent:+ auth_mode = "oauth"+ api_key = None+ base_url = None+ cli_path = "claude"++ class _FakeAgents:+ claude = _FakeAgent()++ class _FakeRuntime:+ default_cwd = str(tmp_path / "runtime")++ class _FakeConfig:+ agents = _FakeAgents()+ runtime = _FakeRuntime()++ monkeypatch.setenv("PATH", "/fake/bin")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-stale-shell")+ monkeypatch.setattr("vibe.api.resolve_cli_path", lambda _binary: None)++ def fake_run(cmd, **kwargs):+ assert cmd == ["claude", "auth", "status", "--json"]+ env = kwargs.get("env") or {}+ assert env.get("PATH") == "/fake/bin"+ assert "ANTHROPIC_API_KEY" not in env+ assert kwargs.get("cwd") == str(tmp_path / "runtime")+ return subprocess.CompletedProcess(+ cmd,+ 0,+ stdout='{"loggedIn": true, "authMethod": "claude.ai"}',+ stderr="",+ )++ monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())+ monkeypatch.setattr("vibe.api.subprocess.run", fake_run)++ from vibe.api import get_claude_auth++ state = get_claude_auth()++ assert state["has_oauth_credentials"] is True+ assert state["active_auth_mode"] == "oauth"+ assert (tmp_path / "runtime").is_dir()+++def test_get_claude_auth_resolves_default_claude_cli_before_status_probe(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_claude_settings(tmp_path, {})+ 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)++ resolved_cli = tmp_path / ".claude" / "local" / "claude"+ resolved_cli.parent.mkdir(parents=True)+ resolved_cli.write_text("#!/bin/sh\n", encoding="utf-8")+ resolved_cli.chmod(0o755)++ class _FakeAgent:+ auth_mode = "oauth"+ api_key = None+ base_url = None+ cli_path = "claude"++ class _FakeAgents:+ claude = _FakeAgent()++ class _FakeConfig:+ agents = _FakeAgents()++ def fake_run(cmd, **_kwargs):+ assert cmd == [str(resolved_cli), "auth", "status", "--json"]+ return subprocess.CompletedProcess(+ cmd,+ 0,+ stdout='{"loggedIn": true, "authMethod": "claude.ai"}',+ stderr="",+ )++ monkeypatch.setattr("vibe.api.Path.home", lambda: tmp_path)+ monkeypatch.setattr("vibe.api.shutil.which", lambda _binary: None)+ monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())+ monkeypatch.setattr("vibe.api.subprocess.run", fake_run)++ from vibe.api import get_claude_auth++ state = get_claude_auth()++ assert state["has_oauth_credentials"] is True+ assert state["active_auth_mode"] == "oauth"+++def test_get_claude_auth_ignores_cli_api_key_status_for_oauth(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_claude_settings(tmp_path, {})+ 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)++ class _FakeAgent:+ auth_mode = "oauth"+ api_key = None+ base_url = None+ cli_path = "claude"++ class _FakeAgents:+ claude = _FakeAgent()++ class _FakeConfig:+ agents = _FakeAgents()++ def fake_run(cmd, **_kwargs):+ return subprocess.CompletedProcess(+ cmd,+ 0,+ stdout='{"loggedIn": true, "authMethod": "api-key"}',+ stderr="",+ )++ monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())+ monkeypatch.setattr("vibe.api.subprocess.run", fake_run)++ from vibe.api import get_claude_auth++ state = get_claude_auth()++ assert state["has_oauth_credentials"] is False+ assert state["active_auth_mode"] == "none"+++def test_get_claude_auth_suppresses_stale_disk_oauth_for_concrete_non_oauth_status(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_claude_settings(tmp_path, {})+ claude_dir = tmp_path / ".claude"+ (claude_dir / ".credentials.json").write_text(+ json.dumps(+ {+ "claudeAiOauth": {+ "accessToken": "stale-oauth",+ "refreshToken": "stale-refresh",+ "expiresAt": 4_102_444_800_000,+ "scopes": ["user:inference"],+ }+ }+ ),+ 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)++ class _FakeAgent:+ auth_mode = "oauth"+ api_key = None+ base_url = None+ cli_path = "claude"++ class _FakeAgents:+ claude = _FakeAgent()++ class _FakeConfig:+ agents = _FakeAgents()++ def fake_run(cmd, **_kwargs):+ return subprocess.CompletedProcess(+ cmd,+ 0,+ stdout='{"loggedIn": true, "authMethod": "third_party"}',+ stderr="",+ )++ monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())+ monkeypatch.setattr("vibe.api.subprocess.run", fake_run)++ from vibe.api import get_claude_auth++ state = get_claude_auth()++ assert state["has_oauth_credentials"] is False+ assert state["active_auth_mode"] == "none"+++def test_get_claude_auth_treats_setup_token_status_as_oauth(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ _write_claude_settings(tmp_path, {})+ 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)++ class _FakeAgent:+ auth_mode = "oauth"+ api_key = None+ base_url = None+ cli_path = "claude"++ class _FakeAgents:+ claude = _FakeAgent()++ class _FakeConfig:+ agents = _FakeAgents()++ def fake_run(cmd, **_kwargs):+ return subprocess.CompletedProcess(+ cmd,+ 0,+ stdout='{"loggedIn": true, "authMethod": "oauth_token"}',+ stderr="",+ )++ monkeypatch.setattr("vibe.api.load_config", lambda: _FakeConfig())+ monkeypatch.setattr("vibe.api.subprocess.run", fake_run)++ from vibe.api import get_claude_auth++ state = get_claude_auth()++ assert state["has_oauth_credentials"] is True+ assert state["active_auth_mode"] == "oauth"++def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -116,6 +383,7 @@ def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(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 vibe.api import get_claude_auth@@ -144,6 +412,7 @@ def test_claude_settings_json_takes_precedence_over_legacy_v2config()monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)+ monkeypatch.setattr("vibe.api._read_claude_cli_oauth_signed_in", lambda _path, **_kwargs: None)# Inject a V2Config with a fresh key by patching load_config.class _FakeAgent:@@ -176,6 +445,7 @@ def test_save_claude_auth_writes_settings_json_and_clears_v2_secret(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, V2Configfrom vibe.api import get_claude_auth, save_claude_auth@@ -204,6 +474,7 @@ def test_save_claude_auth_writes_settings_json_and_clears_v2_secret(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"+ _assert_claude_managed_env(settings["env"])saved = V2Config.load()assert saved.agents.claude.api_key is None@@ -258,6 +529,34 @@ def test_save_claude_auth_keeps_settings_token_over_legacy_v2_key(assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == "token-from-settings"assert "ANTHROPIC_API_KEY" not in settings["env"]assert settings["env"]["ANTHROPIC_BASE_URL"] == "https://new-relay.example.invalid"+ _assert_claude_managed_env(settings["env"])+++def test_apply_claude_auth_oauth_removes_auth_env_but_keeps_managed_defaults(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)+ _write_claude_settings(+ tmp_path,+ {+ "ANTHROPIC_API_KEY": "sk-stale",+ "ANTHROPIC_BASE_URL": "https://stale-relay.example.invalid",+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "0",+ "CLAUDE_CODE_ATTRIBUTION_HEADER": "1",+ "CUSTOM_FLAG": "keep-me",+ },+ )++ from vibe.claude_config import apply_claude_auth++ apply_claude_auth(auth_mode="oauth", api_key=None, base_url=None)++ settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())+ assert "ANTHROPIC_API_KEY" not in settings["env"]+ assert "ANTHROPIC_BASE_URL" not in settings["env"]+ assert settings["env"]["CUSTOM_FLAG"] == "keep-me"+ _assert_claude_managed_env(settings["env"])def test_save_claude_auth_fails_without_overwriting_malformed_settings(@@ -315,3 +614,4 @@ def test_apply_claude_auth_uses_unique_temp_files_for_concurrent_writes(assert errors == []settings = json.loads((tmp_path / ".claude" / "settings.json").read_text())assert settings["env"]["ANTHROPIC_API_KEY"].startswith("sk-key-")+ _assert_claude_managed_env(settings["env"])diff --git a/tests/test_test_failure_classifier.py b/tests/test_test_failure_classifier.pyindex dbd332d4a..3a98cd9b8 100644--- a/tests/test_test_failure_classifier.py+++ b/tests/test_test_failure_classifier.py@@ -19,7 +19,7 @@ from core.agent_auth_service import _classify_test_failure("Error: 401 Unauthorized", "invalid_credentials"),("invalid api key", "invalid_credentials"),("Authentication failed: no credentials configured", "invalid_credentials"),- ("not logged in", "invalid_credentials"),+ ("not logged in", "not_logged_in"),("403 Forbidden", "forbidden"),("Access denied for organization", "forbidden"),("Model not found: gpt-9.0", "model_not_found"),diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex bab07629a..1ea559ddf 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import jsonimport osfrom pathlib import Pathfrom unittest.mock import AsyncMock@@ -26,6 +27,7 @@ from core.agent_auth_service import ()from modules.agents.opencode.message_processor import extract_opencode_response_textfrom vibe.claude_config import (+ MANAGED_ENV_VALUES,read_claude_oauth_settings_backup,read_claude_settings_env,restore_claude_settings_env,@@ -45,6 +47,7 @@ class _Agents:class _Config:agents = _Agents()language = "en"+ runtime = Noneclass _StubController:@@ -356,6 +359,9 @@ def test_claude_oauth_begin_persists_backup_before_clearing_settings(assert attempt.settings_backup == backupassert read_claude_settings_env() == {}+ settings = json.loads((claude_home / "settings.json").read_text())+ for key, value in MANAGED_ENV_VALUES.items():+ assert settings["env"][key] == valueassert read_claude_oauth_settings_backup() == backup@@ -375,10 +381,16 @@ def test_claude_oauth_restarts_restore_interrupted_durable_backup(_run(service._begin_claude_oauth_attempt())assert read_claude_settings_env() == {}+ settings = json.loads((claude_home / "settings.json").read_text())+ for key, value in MANAGED_ENV_VALUES.items():+ assert settings["env"][key] == valueAgentAuthService(_StubController())assert read_claude_settings_env() == backup+ settings = json.loads((claude_home / "settings.json").read_text())+ for key, value in MANAGED_ENV_VALUES.items():+ assert settings["env"][key] == valueassert read_claude_oauth_settings_backup() is None@@ -881,7 +893,8 @@ def test_test_web_auth_claude_oauth_env_removes_stale_anthropic_vars(async def communicate(self):return (b"Hello from Claude", b"")- async def _spawn(*_args, **kwargs):+ async def _spawn(*args, **kwargs):+ captured["args"] = argscaptured["env"] = kwargs.get("env") or {}return _FakeProcess()@@ -895,11 +908,48 @@ def test_test_web_auth_claude_oauth_env_removes_stale_anthropic_vars(result = _run(service.test_web_auth("claude"))assert result["ok"] is True+ assert captured["args"][:2] == ("/usr/bin/echo", "-p")+ assert "--bare" not in captured["args"]assert "ANTHROPIC_API_KEY" not in captured["env"]assert "ANTHROPIC_AUTH_TOKEN" not in captured["env"]assert "ANTHROPIC_BASE_URL" not in captured["env"]+def test_test_web_auth_claude_runs_in_runtime_cwd(+ service: AgentAuthService,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Plain Claude print mode reads project config from cwd; the Settings+ probe must use the same runtime cwd as live Agent turns.+ """++ runtime_cwd = tmp_path / "agent-workdir"+ captured: dict = {}++ class _Runtime:+ default_cwd = str(runtime_cwd)++ class _FakeProcess:+ returncode = 0++ async def communicate(self):+ return (b"Hello from Claude", b"")++ async def _spawn(*_args, **kwargs):+ captured["cwd"] = kwargs.get("cwd")+ return _FakeProcess()++ monkeypatch.setattr(_Config, "runtime", _Runtime(), raising=False)+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)++ result = _run(service.test_web_auth("claude"))++ assert result["ok"] is True+ assert captured["cwd"] == str(runtime_cwd)+ assert runtime_cwd.is_dir()++def test_test_web_auth_claude_oauth_reports_settings_cleanup_failure(service: AgentAuthService, monkeypatch: pytest.MonkeyPatch) -> None:@@ -942,3 +992,25 @@ def test_test_web_auth_failure_surfaces_stderr(assert result["error"] == "invalid_credentials"assert result["exit_code"] == 7assert "Authentication failed" in (result.get("detail") or "")+++def test_test_web_auth_not_logged_in_has_specific_error_code(+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch+) -> None:+ class _FakeProcess:+ returncode = 1++ async def communicate(self):+ return (b"Not logged in \xc2\xb7 Please run /login", b"")++ 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"] == "not_logged_in"+ assert result["exit_code"] == 1+ assert "Not logged in" in (result.get("detail") or "")diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsxindex 2afb51fbd..2a5448a45 100644--- a/ui/src/components/settings/BackendTestPanel.tsx+++ b/ui/src/components/settings/BackendTestPanel.tsx@@ -76,6 +76,7 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =cli_not_found: 'settings.backends.testFailureCliNotFound',spawn_failed: 'settings.backends.testFailureSpawnFailed',timed_out: 'settings.backends.testFailureTimedOut',+ not_logged_in: 'settings.backends.testFailureNotLoggedIn',cli_failed: 'settings.backends.testFailureCliFailed',};const key = map[code];diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsxindex 0971c7527..e45151770 100644--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx@@ -122,9 +122,9 @@ export const ClaudeProviderConfig: React.FC<{: 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.+ // Drop just the API key from V2Config; leaves Claude Code's own OAuth+ // token store 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,);@@ -258,11 +258,9 @@ export const ClaudeProviderConfig: React.FC<{{authMode === 'oauth' && (<BackendOAuthPanelbackend={BACKEND_ID}- // ``has_oauth_credentials`` flips when ``~/.claude/credentials.json``- // carries a usable token bundle — that's a real signal we can- // trust on Linux/Docker. macOS keychain installs still report- // false, but a successful in-session login flips the panel's- // own state anyway.+ // ``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}title={t('settings.backends.claudeOauthPanelTitle')}subtitle={t('settings.backends.claudeOauthPanelSubtitle')}@@ -323,10 +321,9 @@ export const ClaudeProviderConfig: React.FC<{</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. */}+ token store intact. Without this, a stuck key+ keeps forcing the env-var path even after the+ user signed in via OAuth. */}<Buttontype="button"variant="ghost"diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 4469ae2ab..52e42bbbf 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -967,7 +967,7 @@ export type ClaudeAuthState = {auth_mode: ClaudeAuthMode;// Live source the CLI is actually inheriting at launch (api_key when// V2Config injects ``ANTHROPIC_API_KEY`` and strips OAuth env vars,- // oauth when ``~/.claude/credentials.json`` has a usable token).+ // oauth when Claude Code reports or stores a usable first-party login).active_auth_mode: ActiveAuthMode;has_api_key: boolean;api_key_length: number;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 95c07905b..6cdd1984e 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -309,6 +309,7 @@"testFailureCliNotFound": "The backend CLI binary was not found. Check the Path on the runtime card.","testFailureSpawnFailed": "Could not launch the backend CLI: {{detail}}","testFailureTimedOut": "The CLI did not respond within the test timeout.",+ "testFailureNotLoggedIn": "The backend CLI did not find a signed-in account. Sign in again, then rerun the test.","testFailureCliFailed": "The CLI exited with an error. Expand the raw output below to see what it said.","testConnectionRawOutputLabel": "Raw output","activeAuthOauth": "Active: OAuth",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex e7f809d12..fd363df96 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -309,6 +309,7 @@"testFailureCliNotFound": "未找到后端 CLI 二进制。检查 Runtime 卡片上的路径。","testFailureSpawnFailed": "无法启动后端 CLI:{{detail}}","testFailureTimedOut": "CLI 在测试超时时间内没有响应。",+ "testFailureNotLoggedIn": "后端 CLI 没有读取到已登录账号。请重新登录后再运行测试。","testFailureCliFailed": "CLI 退出失败。展开下方原始输出查看详情。","testConnectionRawOutputLabel": "原始输出","activeAuthOauth": "当前:OAuth",diff --git a/vibe/api.py b/vibe/api.pyindex 3f373b487..ed15cf58a 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -4139,6 +4139,106 @@ def _mask_api_key(api_key: str | None) -> str | None:return f"{'•' * 6}{last4}"+def _read_claude_cli_oauth_signed_in(+ cli_path: str | None,+ *,+ env: dict[str, str] | None = None,+ cwd: str | None = None,+) -> bool | None:+ """Ask Claude Code whether a first-party OAuth account is signed in.++ This is the most accurate Settings signal because it covers both+ keychain-backed installs and Linux/Docker's on-disk credentials file.+ Keep it best-effort and quiet: if Claude is missing, slow, or emits an+ unexpected shape, callers fall back to disk inspection.+ """+ configured = (cli_path or "claude").strip() or "claude"+ binary = resolve_cli_path(configured) or configured+ try:+ result = subprocess.run(+ [binary, "auth", "status", "--json"],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=3,+ check=False,+ env=env,+ cwd=cwd,+ )+ except (FileNotFoundError, OSError, subprocess.SubprocessError):+ return None+ text = (result.stdout or "").strip()+ if not text:+ return None+ try:+ payload = json.loads(text)+ except json.JSONDecodeError:+ return None+ if not isinstance(payload, dict):+ return None+ logged_in = payload.get("loggedIn")+ if logged_in is False:+ return False+ if logged_in is not True:+ return None++ # ``auth status`` reports Claude Code's overall auth state. API-key+ # sources can also be "logged in", so only treat it as OAuth when the+ # CLI identifies the source as Claude.ai / first-party OAuth.+ saw_concrete_source = False+ for key in ("authMethod", "authProvider", "provider", "source"):+ raw = payload.get(key)+ if isinstance(raw, str):+ normalized = re.sub(r"[\s_]+", "-", raw.strip().lower())+ if not normalized:+ continue+ saw_concrete_source = True+ if normalized in {+ "claude.ai",+ "claude-ai",+ "oauth",+ "oauth-token",+ "setup-token",+ "claude-code-oauth-token",+ "subscription",+ "claude-subscription",+ }:+ return True+ if any(token in normalized for token in ("api-key", "apikey", "api key", "auth-token", "apihelper", "api-helper")):+ return False+ if saw_concrete_source:+ return False+ return None+++def _resolve_claude_status_probe_cwd(config: Any | None) -> str | None:+ candidates = (+ getattr(getattr(config, "claude", None), "cwd", None),+ getattr(getattr(config, "runtime", None), "default_cwd", None),+ )+ for raw in candidates:+ if isinstance(raw, str) and raw.strip():+ path = os.path.abspath(os.path.expanduser(raw.strip()))+ try:+ os.makedirs(path, exist_ok=True)+ return path+ except OSError as exc:+ logger.warning("Failed to prepare Claude auth status cwd=%s: %s", path, exc)+ return None+++def _build_claude_status_probe_env(claude_env: dict[str, str] | None) -> dict[str, str] | None:+ if claude_env is None:+ return None+ env = dict(os.environ)+ for key in list(env):+ if key.startswith("ANTHROPIC_") or key.startswith("CLAUDE_"):+ env.pop(key, None)+ env.update(claude_env)+ return env++# ---------------------------------------------------------------------------# Web Settings → Backends OAuth flow plumbing.#@@ -4351,7 +4451,7 @@ def remove_backend_api_key(backend: str) -> dict:- **Claude**: remove Anthropic env overrides from Claude's``settings.json``, clear legacy V2Config ``api_key`` / ``base_url``cache fields, and flip ``auth_mode`` to ``oauth``.- ``~/.claude/credentials.json`` (the OAuth token file) is left alone.+ Claude Code's OAuth token store is left alone."""backend = (backend or "").strip().lower()if backend not in {"claude", "codex"}:@@ -4715,10 +4815,9 @@ def get_claude_auth() -> dict:1. ``~/.claude/settings.json`` is the source of truth for API-keyenv overrides because Claude Code layers that file on top of theinherited process env at launch.- 2. OAuth tokens minted by ``claude login`` live in the OS keychain,- which we cannot portably inspect. The "OAuth signed in" signal is- therefore inferred from "no API key is configured" — the UI shows- a hint pointing users at ``claude login`` if they need to switch.+ 2. OAuth state is owned by Claude Code, so we first ask+ ``claude auth status --json``. If that probe is unavailable, fall+ back to the Linux/Docker credentials file signal.Legacy V2Config keys are read only as a migration fallback so oldinstalls still render their current state before the next save moves@@ -4728,10 +4827,11 @@ def get_claude_auth() -> dict:read_claude_auth_state,read_claude_oauth_signed_in,read_claude_settings_env,+ build_claude_subprocess_env,)disk_state = read_claude_auth_state()- oauth_signed_in = read_claude_oauth_signed_in()+ disk_oauth_signed_in = read_claude_oauth_signed_in()settings_env = read_claude_settings_env()settings_key = settings_env.get("ANTHROPIC_API_KEY") or settings_env.get("ANTHROPIC_AUTH_TOKEN") or ""settings_base = settings_env.get("ANTHROPIC_BASE_URL") or ""@@ -4742,13 +4842,34 @@ def get_claude_auth() -> dict:configured_mode = getattr(cfg, "auth_mode", None)configured_key = getattr(cfg, "api_key", None) or ""configured_base = getattr(cfg, "base_url", None) or ""+ configured_cli_path = getattr(cfg, "cli_path", None)+ status_probe_cwd = _resolve_claude_status_probe_cwd(config)except Exception:configured_mode = Noneconfigured_key = ""configured_base = ""+ configured_cli_path = None+ status_probe_cwd = Noneconfigured_key = configured_key.strip() if isinstance(configured_key, str) else ""configured_base = configured_base.strip() if isinstance(configured_base, str) else ""+ try:+ claude_status_env = _build_claude_status_probe_env(+ build_claude_subprocess_env(+ cfg if "cfg" in locals() else None,+ force_oauth=True,+ )+ )+ except Exception:+ claude_status_env = None+ cli_oauth_signed_in = _read_claude_cli_oauth_signed_in(+ configured_cli_path if isinstance(configured_cli_path, str) else None,+ env=claude_status_env,+ cwd=status_probe_cwd,+ )+ oauth_signed_in = (+ cli_oauth_signed_in if cli_oauth_signed_in is not None else disk_oauth_signed_in+ )# settings.json wins: it is the file Claude Code itself layers on top# of inherited env. V2Config is a legacy fallback only.diff --git a/vibe/claude_config.py b/vibe/claude_config.pyindex 24230528c..8ec7a94ec 100644--- a/vibe/claude_config.py+++ b/vibe/claude_config.py@@ -8,14 +8,14 @@ instead of storing secrets in V2Config and hoping env injection wins.This module owns the narrow settings.json mutation surface:- ``apply_claude_auth(...)`` upserts or removes Anthropic env vars in- ``settings.json``.+ ``settings.json`` while preserving Avibe-managed Claude Code defaults.- ``read_claude_settings_env(...)`` reports the live on-disk state withoutleaking secrets beyond the current process.-OAuth tokens minted by ``claude login`` live in the macOS keychain (or-the OS-specific equivalent), not on disk. We have no portable way to-inspect them, so the OAuth-signed-in signal is purely an inference from-"no API key is configured" plus "the CLI is reachable".+OAuth tokens minted by ``claude login`` may live in an OS keychain or in+Claude Code's own credential file depending on platform/version. The Settings+UI prefers ``claude auth status --json`` and uses the on-disk credential file+as a fallback signal."""from __future__ import annotations@@ -29,6 +29,14 @@ from typing import Any, Dict, Optionallogger = logging.getLogger(__name__)+# Keys Avibe always keeps in ``~/.claude/settings.json`` for Claude Code.+# They are not auth credentials, so they intentionally stay outside+# ``RELEVANT_ENV_KEYS`` and survive OAuth/API-key mode switches.+MANAGED_ENV_VALUES = {+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",+ "CLAUDE_CODE_ATTRIBUTION_HEADER": "0",+}+# Keys we recognise inside ``~/.claude/settings.json``'s ``env`` block.# ``ANTHROPIC_API_KEY`` is the SDK's documented variable; relay setups# (e.g. Cloudflare-fronted gateways like ai-relay) prefer@@ -63,16 +71,24 @@ def get_claude_settings_path(home: Path | None = None) -> Path:return get_claude_home(home) / "settings.json"-def get_claude_credentials_path(home: Path | None = None) -> Path:- """Return the absolute path to ``~/.claude/credentials.json``.+def get_claude_credentials_paths(home: Path | None = None) -> tuple[Path, ...]:+ """Return Claude Code OAuth credential paths, newest layout first.- The Claude CLI writes OAuth tokens here on platforms that lack a- usable keychain (notably Linux/Docker, including the regression- container). The Settings UI uses presence + a token field as a- best-effort signal for "Claude is signed in via OAuth" since the- macOS keychain is not portably introspectable.+ Claude Code currently writes OAuth tokens to+ ``~/.claude/.credentials.json`` on Linux/Docker. Older Avibe builds+ looked for ``credentials.json`` based on earlier CLI behavior, so keep+ both paths readable for existing installs and tests."""- return get_claude_home(home) / "credentials.json"+ claude_home = get_claude_home(home)+ return (+ claude_home / ".credentials.json",+ claude_home / "credentials.json",+ )+++def get_claude_credentials_path(home: Path | None = None) -> Path:+ """Return the primary Claude Code OAuth credentials path."""+ return get_claude_credentials_paths(home)[0]def get_claude_oauth_settings_backup_path(home: Path | None = None) -> Path:@@ -83,31 +99,31 @@ def get_claude_oauth_settings_backup_path(home: Path | None = None) -> Path:def read_claude_oauth_signed_in(home: Path | None = None) -> bool:"""Best-effort probe for whether Claude has a usable OAuth session.- True iff ``~/.claude/credentials.json`` exists and carries something+ True iff Claude's on-disk credentials file exists and carries somethingthat looks like an OAuth token bundle. We don't attempt to introspectkeychain-backed installs (macOS) — those return False here but the UIcan still light up the OAuth banner after a successful in-app login."""- path = get_claude_credentials_path(home)- if not path.exists():- return False- try:- data = json.loads(path.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- return False- if not isinstance(data, dict):- return False- # Claude writes nested ``claudeAiOauth`` payloads in newer builds; flat- # ``access_token``/``refresh_token`` keys also occur. Accept either.- nested = data.get("claudeAiOauth") if isinstance(data.get("claudeAiOauth"), dict) else None- if nested and any(- isinstance(nested.get(field), str) and nested.get(field)- for field in ("access_token", "refresh_token", "accessToken", "refreshToken")- ):- return True- for field in ("access_token", "refresh_token", "accessToken", "refreshToken"):- if isinstance(data.get(field), str) and data.get(field):+ for path in get_claude_credentials_paths(home):+ if not path.exists():+ continue+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ if not isinstance(data, dict):+ continue+ # Claude writes nested ``claudeAiOauth`` payloads in newer builds; flat+ # ``access_token``/``refresh_token`` keys also occur. Accept either.+ nested = data.get("claudeAiOauth") if isinstance(data.get("claudeAiOauth"), dict) else None+ if nested and any(+ isinstance(nested.get(field), str) and nested.get(field)+ for field in ("access_token", "refresh_token", "accessToken", "refreshToken")+ ):return True+ for field in ("access_token", "refresh_token", "accessToken", "refreshToken"):+ if isinstance(data.get(field), str) and data.get(field):+ return Truereturn False@@ -168,6 +184,11 @@ def _clean_relevant_env_values(env_values: Dict[str, str]) -> Dict[str, str]:return out+def _ensure_managed_env_values(env_block: Dict[str, Any]) -> None:+ """Upsert Avibe-managed, non-secret Claude Code env defaults."""+ env_block.update(MANAGED_ENV_VALUES)++def write_claude_oauth_settings_backup(env_values: Dict[str, str], home: Path | None = None) -> None:@@ -235,7 +256,8 @@ def apply_claude_auth(``api_key`` mode writes ``env.ANTHROPIC_API_KEY`` and removes``ANTHROPIC_AUTH_TOKEN`` so header semantics cannot conflict. ``oauth``mode removes all Anthropic credential/base-url overrides from the env- block and leaves Claude's OAuth credentials untouched.+ block and leaves Claude's OAuth credentials untouched. Both modes upsert+ Avibe's non-secret Claude Code env defaults."""if auth_mode not in {"oauth", "api_key"}:raise ValueError(f"Unsupported claude auth_mode: {auth_mode!r}")@@ -263,8 +285,8 @@ def apply_claude_auth(else:for key in RELEVANT_ENV_KEYS:env_block.pop(key, None)- if not env_block:- settings.pop("env", None)++ _ensure_managed_env_values(env_block)_atomic_write(path, json.dumps(settings, indent=2) + "\n", mode=0o600)return {"settings_path": str(path)}@@ -310,6 +332,8 @@ def restore_claude_settings_env(env_values: Dict[str, str], home: Path | None =if isinstance(raw, str) and raw.strip():env_block[key] = raw.strip()+ _ensure_managed_env_values(env_block)+if not env_block:settings.pop("env", None)@@ -390,7 +414,7 @@ def build_claude_subprocess_env(The ``auth_mode`` toggle is the load-bearing piece — if a user picksOAuth in Settings but their shell exports ``ANTHROPIC_API_KEY``, theClaude CLI silently keeps API-key auth and never reaches- ``~/.claude/credentials.json``. Stripping both ``ANTHROPIC_API_KEY``+ Claude Code's OAuth credential store. Stripping both ``ANTHROPIC_API_KEY``and ``ANTHROPIC_AUTH_TOKEN`` (header-semantics switch) in OAuth modemakes the Settings toggle authoritative.@@ -443,7 +467,7 @@ def build_claude_subprocess_env(# it IS the OAuth setup flow. Strip every inherited# Anthropic credential header: an ambient# ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` would- # suppress ``~/.claude/credentials.json``, and an ambient+ # suppress Claude Code's OAuth credential store, and an ambient# ``ANTHROPIC_BASE_URL`` (typically a stale relay URL from# the shell) would route OAuth traffic through an# api-key-only gateway. Both leaks have to be plugged for