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(backends): surface pre-existing on-disk Settings auth in the UI
cyhcd56afbc6b3f
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.pynew file mode 100644index 000000000..5fdb4f405--- /dev/null+++ b/tests/test_settings_disk_fallback.py@@ -0,0 +1,171 @@+"""Regression tests for the Settings → Backends disk-fallback reads.++Page-feedback fix for PR #282: the user configured their Claude /+Codex relay by hand-editing ``~/.claude/settings.json`` /+``~/.codex/config.toml`` (or a prior tool did), but the Settings UI+rendered the API Key input as empty and the Base URL as the default.+The fixes:++1. ``vibe.codex_config.read_codex_auth_state`` now honours the+ top-level ``model_provider`` key when looking up ``base_url`` — a+ user-defined ``[model_providers.OpenAI]`` section is no longer+ ignored just because the key happens to be TitleCase rather than+ our managed lowercase ``openai``.++2. ``vibe.api.get_claude_auth`` falls back to+ ``~/.claude/settings.json`` env values (``ANTHROPIC_API_KEY`` /+ ``ANTHROPIC_AUTH_TOKEN`` / ``ANTHROPIC_BASE_URL``) when V2Config is+ empty, surfacing the live state via ``api_key_masked`` /+ ``base_url`` and tagging the source as ``settings_json``.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from vibe.codex_config import read_codex_auth_state+++def test_codex_reads_base_url_from_user_titlecase_provider(tmp_path: Path) -> None:+ """When the user points Codex at a relay via ``[model_providers.OpenAI]``+ (matching their on-disk config.toml literally), the Settings UI must+ pick up that ``base_url`` rather than reporting the default.+ """+ codex_dir = tmp_path / ".codex"+ codex_dir.mkdir()+ (codex_dir / "auth.json").write_text("{}", encoding="utf-8")+ (codex_dir / "config.toml").write_text(+ "\n".join(+ [+ 'model_provider = "OpenAI"',+ "",+ "[model_providers.OpenAI]",+ 'name = "OpenAI"',+ 'base_url = "https://ai-relay.chainbot.io"',+ 'wire_api = "responses"',+ "requires_openai_auth = true",+ ]+ ),+ encoding="utf-8",+ )+ state = read_codex_auth_state(home=tmp_path)+ assert state["base_url"] == "https://ai-relay.chainbot.io"+++def test_codex_falls_back_to_managed_section_when_no_active_provider(tmp_path: Path) -> None:+ """If ``model_provider`` is unset but our managed ``openai`` section+ has a ``base_url`` (the shape we write via ``apply_codex_auth``),+ surface that. Preserves the pre-fix behaviour for vibe-initiated+ saves that never touched the top-level ``model_provider`` key.+ """+ codex_dir = tmp_path / ".codex"+ codex_dir.mkdir()+ (codex_dir / "auth.json").write_text("{}", encoding="utf-8")+ (codex_dir / "config.toml").write_text(+ "\n".join(+ [+ "[model_providers.openai]",+ 'base_url = "https://vibe-managed.example.io"',+ ]+ ),+ encoding="utf-8",+ )+ state = read_codex_auth_state(home=tmp_path)+ assert state["base_url"] == "https://vibe-managed.example.io"+++def test_codex_no_base_url_when_neither_section_has_one(tmp_path: Path) -> None:+ codex_dir = tmp_path / ".codex"+ codex_dir.mkdir()+ (codex_dir / "auth.json").write_text("{}", encoding="utf-8")+ (codex_dir / "config.toml").write_text("model = \"gpt-5.4\"\n", encoding="utf-8")+ state = read_codex_auth_state(home=tmp_path)+ assert state["base_url"] is None+++def _write_claude_settings(home: Path, env: dict) -> None:+ claude_dir = home / ".claude"+ claude_dir.mkdir()+ (claude_dir / "settings.json").write_text(+ json.dumps({"env": env}), encoding="utf-8"+ )+++def test_claude_settings_json_auth_token_surfaces_in_get_claude_auth(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Claude's get_claude_auth must report a masked key + base URL when+ V2Config is empty but ``settings.json`` carries them. Mirrors the+ regression env where the user pre-configured a relay via the env+ block before our Settings UI existed.+ """+ _write_claude_settings(+ tmp_path,+ {+ "ANTHROPIC_AUTH_TOKEN": "sk-9c552_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_738a",+ "ANTHROPIC_BASE_URL": "https://ai-relay.chainbot.io",+ },+ )+ # Pin Claude's home + V2Config home to the temp dir so the readers+ # find our fake settings.json and the V2Config load returns defaults+ # (i.e. ``api_key=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)++ from vibe.api import get_claude_auth++ state = get_claude_auth()+ assert state["has_api_key"] is True+ assert state["api_key_source"] == "settings_json"+ masked = state["api_key_masked"]+ assert masked is not None+ assert masked.endswith("738a")+ assert "xxxxxxxx" not in masked # plaintext middle must not leak+ assert state["base_url"] == "https://ai-relay.chainbot.io"+ assert state["active_auth_mode"] == "api_key"+ # settings.json alone is not a *conflict*; it's only a conflict when+ # BOTH V2Config and settings.json carry a key.+ assert state["settings_conflict"] is False+++def test_claude_v2config_takes_precedence_over_settings_json(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """When V2Config also has a key, that wins for display purposes+ (it's what we'd inject at launch). settings.json being present+ elevates ``settings_conflict`` so the UI can warn the user."""+ _write_claude_settings(+ tmp_path,+ {"ANTHROPIC_API_KEY": "sk-stale-key-from-settings"},+ )+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / ".claude"))+ monkeypatch.setattr("config.paths._home", lambda: tmp_path, raising=False)++ # Inject a V2Config with a fresh key by patching load_config.+ class _FakeAgent:+ auth_mode = "api_key"+ api_key = "sk-fresh-key-from-v2config"+ base_url = "https://v2config.example.io"++ 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["api_key_source"] == "v2config"+ masked = state["api_key_masked"]+ assert masked is not None+ # Mask preserves the trailing 4 characters of the V2Config key.+ assert masked.endswith("nfig")+ assert state["base_url"] == "https://v2config.example.io"+ assert state["settings_conflict"] is Truediff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 47b20e24f..c4cf74df7 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -195,6 +195,14 @@ export type ClaudeAuthMode = 'oauth' | 'api_key';// inspect ``~/.claude/settings.json`` so the UI can warn when a// hand-edited ``env`` block would override the V2Config-injected key at// launch (Claude Code layers settings.json env on top of inherited env).+// Which on-disk source the live API key came from. ``v2config`` means+// the user (or a prior save) put it in Vibe Remote's V2Config and we+// inject it as ``ANTHROPIC_API_KEY`` at launch. ``settings_json`` means+// ``~/.claude/settings.json``'s ``env`` block already carries the key —+// the live CLI reads it directly and our V2Config is empty (typically a+// pre-existing setup that predates our Settings UI). ``null`` = no key.+export type ClaudeApiKeySource = 'v2config' | 'settings_json' | null;+export type ClaudeAuthState = {ok: boolean;auth_mode: ClaudeAuthMode;@@ -205,6 +213,7 @@ export type ClaudeAuthState = {has_api_key: boolean;api_key_length: number;api_key_masked: string | null;+ api_key_source?: ClaudeApiKeySource;has_oauth_credentials: boolean;base_url: string | null;settings_path: string | null;diff --git a/vibe/api.py b/vibe/api.pyindex 2dfc94951..3bf41467e 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -2483,10 +2483,18 @@ def get_claude_auth() -> dict:env). The UI surfaces a warning so users aren't confused by stalekeys silently overriding what they just saved."""- from vibe.claude_config import read_claude_auth_state, read_claude_oauth_signed_in+ from vibe.claude_config import (+ read_claude_auth_state,+ read_claude_oauth_signed_in,+ read_claude_settings_env,+ )disk_state = read_claude_auth_state()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 ""+try:config = load_config()cfg = getattr(getattr(config, "agents", None), "claude", None)@@ -2501,45 +2509,63 @@ def get_claude_auth() -> dict:configured_key = configured_key.strip() if isinstance(configured_key, str) else ""configured_base = configured_base.strip() if isinstance(configured_base, str) else ""- has_api_key = bool(configured_key)+ # Effective values surface to the UI. V2Config wins when populated+ # (that's what we'd write next), else fall back to whatever the+ # running CLI actually inherits from ``settings.json``. This is the+ # difference between "no key configured" (truly empty) and "key lives+ # in settings.json from a hand-edit or older tool" (looks empty in+ # V2Config but actually drives the live CLI).+ effective_key = configured_key or settings_key+ effective_base = configured_base or settings_base+ has_api_key = bool(effective_key)+if configured_mode in _VALID_AUTH_MODES:auth_mode = configured_mode+ elif effective_key:+ auth_mode = "api_key"else:- auth_mode = "api_key" if has_api_key else "oauth"+ auth_mode = "oauth"- # When settings.json also defines a key, the live CLI uses that one- # rather than the V2Config-injected one. Flag the conflict so the- # UI can warn the user before they assume their newly-saved key is- # in effect.- settings_conflict = bool(disk_state.get("settings_env_has_key")) and has_api_key+ # ``settings_conflict`` keeps the original meaning: BOTH V2Config and+ # settings.json have a key, in which case settings.json wins at launch+ # (Claude Code layers ``env`` on top of inherited env). The new+ # "settings.json is sole source" case is not a conflict — it's just+ # the effective value and we now render it instead of blanking out.+ settings_conflict = bool(disk_state.get("settings_env_has_key")) and bool(configured_key)# ``active_auth_mode`` reflects what the running CLI is actually using- # at launch — separate from ``auth_mode`` (the user's saved intent).- # V2Config drives ``build_claude_subprocess_env``: api_key mode injects- # ``ANTHROPIC_API_KEY`` and strips OAuth-related env vars; oauth mode- # leaves those keys alone and relies on ``~/.claude/credentials.json``- # / the OS keychain. So in api_key mode the key wins; in oauth mode- # the credentials file is what counts.- if auth_mode == "api_key" and has_api_key:+ # at launch.+ if effective_key and auth_mode == "api_key":active_auth_mode = "api_key"- elif auth_mode == "oauth" and oauth_signed_in:+ elif oauth_signed_in and auth_mode == "oauth":active_auth_mode = "oauth"- elif has_api_key:+ elif effective_key:active_auth_mode = "api_key"elif oauth_signed_in:active_auth_mode = "oauth"else:active_auth_mode = "none"+ # Which storage the live API key came from — helps the UI explain the+ # state ("Key configured in settings.json"). Plaintext never leaves+ # the server; only the mask is forwarded.+ if configured_key:+ api_key_source = "v2config"+ elif settings_key:+ api_key_source = "settings_json"+ else:+ api_key_source = None+return {"ok": True,"auth_mode": auth_mode,"active_auth_mode": active_auth_mode,"has_api_key": has_api_key,- "api_key_length": len(configured_key),- "api_key_masked": _mask_api_key(configured_key),+ "api_key_length": len(effective_key),+ "api_key_masked": _mask_api_key(effective_key),+ "api_key_source": api_key_source,"has_oauth_credentials": oauth_signed_in,- "base_url": configured_base or None,+ "base_url": effective_base or None,"settings_path": disk_state.get("settings_path"),"settings_exists": bool(disk_state.get("settings_exists")),"settings_env_has_key": bool(disk_state.get("settings_env_has_key")),diff --git a/vibe/codex_config.py b/vibe/codex_config.pyindex 45d9e1678..b3ae609af 100644--- a/vibe/codex_config.py+++ b/vibe/codex_config.py@@ -371,9 +371,21 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:providers = toml_data.get("model_providers")base_url: Optional[str] = Noneif isinstance(providers, dict):- managed = providers.get(MANAGED_PROVIDER_ID)- if isinstance(managed, dict):- raw = managed.get("base_url")+ # Codex's runtime selects the provider named by top-level+ # ``model_provider``. When that's a user-defined section (e.g.+ # ``[model_providers.OpenAI]`` for a relay), our managed-id+ # lookup would miss the user's actual ``base_url``. Prefer the+ # active provider's section; fall back to the managed id we+ # ourselves write so the UI still reflects a vibe-initiated+ # save before the user customises ``config.toml`` by hand.+ active_provider = toml_data.get("model_provider")+ active_section: Optional[dict] = None+ if isinstance(active_provider, str) and isinstance(providers.get(active_provider), dict):+ active_section = providers[active_provider]+ elif isinstance(providers.get(MANAGED_PROVIDER_ID), dict):+ active_section = providers[MANAGED_PROVIDER_ID]+ if isinstance(active_section, dict):+ raw = active_section.get("base_url")if isinstance(raw, str) and raw.strip():base_url = raw.strip()