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.

fix(backends): pin Codex credentials store to file when writing api_key

cyhfdc2af9c9c07
diff --git a/tests/test_codex_config.py b/tests/test_codex_config.py
index 7ea5a9580..743c9fec5 100644
--- a/tests/test_codex_config.py
+++ b/tests/test_codex_config.py
@@ -152,6 +152,52 @@ def test_read_codex_api_key_missing_returns_none(tmp_path: Path) -> None:
assert codex_config.read_codex_api_key(home=tmp_path) is None
+def test_apply_api_key_pins_credentials_store_to_file(tmp_path: Path) -> None:
+ """Codex's default ``cli_auth_credentials_store`` is ``auto`` (keyring-
+ preferred). When the UI writes an API key, the live process must
+ actually read from ``auth.json`` — pin it to ``file`` explicitly."""
+ home = tmp_path
+ codex_config.apply_codex_auth(
+ auth_mode="api_key",
+ api_key="sk-test",
+ base_url=None,
+ home=home,
+ )
+ parsed = tomllib.loads((home / ".codex" / "config.toml").read_text(encoding="utf-8"))
+ assert parsed[codex_config.CREDENTIALS_STORE_KEY] == codex_config.CREDENTIALS_STORE_FILE
+
+ state = codex_config.read_codex_auth_state(home=home)
+ assert state["credentials_store"] == "file"
+ assert state["file_store_active"] is True
+
+
+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."""
+ home = tmp_path
+ codex_home = home / ".codex"
+ codex_home.mkdir()
+ (codex_home / "config.toml").write_text(
+ f'{codex_config.CREDENTIALS_STORE_KEY} = "keyring"\n', encoding="utf-8"
+ )
+ (codex_home / "auth.json").write_text(
+ json.dumps({"OPENAI_API_KEY": "sk-old"}), encoding="utf-8"
+ )
+ codex_config.apply_codex_auth(auth_mode="oauth", api_key=None, base_url=None, home=home)
+ parsed = tomllib.loads((codex_home / "config.toml").read_text(encoding="utf-8"))
+ assert parsed[codex_config.CREDENTIALS_STORE_KEY] == "keyring"
+
+
+def test_read_state_reports_default_store_as_auto(tmp_path: Path) -> None:
+ """Absent ``cli_auth_credentials_store`` means Codex's documented
+ ``auto`` default; the UI gate on ``file_store_active`` depends on
+ this being reported faithfully rather than silently masked as
+ ``file``."""
+ state = codex_config.read_codex_auth_state(home=tmp_path)
+ assert state["credentials_store"] == "auto"
+ assert state["file_store_active"] is False
+
+
def test_apply_oauth_mode_clears_managed_base_url(tmp_path: Path) -> None:
"""Switching back to oauth strips the managed base_url and api_key."""
home = tmp_path
diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsx
index 090f9c379..ff472e3f0 100644
--- a/ui/src/components/settings/SettingsCodexProviderPage.tsx
+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx
@@ -176,6 +176,15 @@ export const SettingsCodexProviderPage: React.FC = () => {
{t('settings.backends.codexHasChatgptTokens')}
</p>
)}
+ {authMode === 'api_key' && state && !state.file_store_active && (
+ // Codex's documented default is ``auto`` (keyring-preferred), so
+ // the API-key UX is honest about what saving will do: we pin
+ // ``cli_auth_credentials_store = "file"`` on save, otherwise
+ // Codex would ignore ``auth.json`` and keep reading the keychain.
+ <p className="text-[12px] text-gold">
+ {t('settings.backends.codexCredentialsStoreKeyringWarn', { store: state.credentials_store })}
+ </p>
+ )}
</div>
{authMode === 'api_key' && (
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 82b5e76ab..d875e3bd9 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -121,6 +121,13 @@ export type BackendRestartResult = {
export type CodexAuthMode = 'oauth' | 'api_key';
+// Mirrors Codex CLI's ``cli_auth_credentials_store`` setting. ``auto`` is
+// Codex's documented default and is treated as keyring-preferred — when
+// the live store is not ``file`` the on-disk ``auth.json`` may not be
+// the source of truth, so the UI must not interpret ``has_api_key=false``
+// as "no key configured" in that case.
+export type CodexCredentialsStore = 'file' | 'keyring' | 'auto' | (string & {});
+
export type CodexAuthState = {
ok: boolean;
auth_mode: CodexAuthMode;
@@ -128,6 +135,8 @@ export type CodexAuthState = {
api_key_length: number;
base_url: string | null;
has_chatgpt_tokens: boolean;
+ credentials_store: CodexCredentialsStore;
+ file_store_active: boolean;
message?: string;
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b814050bb..e252133eb 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -108,6 +108,7 @@
"codexBaseUrlHint": "Leave empty to use OpenAI's default endpoint. Compatible relays (e.g. Azure OpenAI, OpenRouter) accept their own URL here.",
"codexBaseUrlReset": "Reset to default",
"codexHasChatgptTokens": "Codex has cached ChatGPT credentials from a previous `codex login`.",
+ "codexCredentialsStoreKeyringWarn": "Codex is currently set to store credentials in the OS keychain ({{store}}). Saving here will switch it to file storage so Vibe Remote can manage the API key directly.",
"codexInfoHint": "Saving here writes `~/.codex/auth.json` and `~/.codex/config.toml`, then restarts the persistent app-server so the next request uses the new settings.",
"codexSave": "Save and restart Codex",
"codexSaving": "Saving…",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 3e04e0262..1f344cb65 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -108,6 +108,7 @@
"codexBaseUrlHint": "留空则使用 OpenAI 默认接口。兼容网关(如 Azure OpenAI、OpenRouter)可填入各自的 URL。",
"codexBaseUrlReset": "重置为默认",
"codexHasChatgptTokens": "检测到上一次 `codex login` 缓存的 ChatGPT 凭据。",
+ "codexCredentialsStoreKeyringWarn": "Codex 当前设置为把凭据存储在系统钥匙串中({{store}})。保存后将切换为文件存储,Vibe Remote 才能直接读写 API key。",
"codexInfoHint": "保存会写入 `~/.codex/auth.json` 与 `~/.codex/config.toml`,并重启常驻 app-server 以加载新配置。",
"codexSave": "保存并重启 Codex",
"codexSaving": "保存中…",
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
index cfea4f9b5..cca4dc164 100644
--- a/vibe/codex_config.py
+++ b/vibe/codex_config.py
@@ -37,6 +37,16 @@ _BARE_KEY_RE = re.compile(r"^[A-Za-z0-9_-]+$")
# leave their fields alone except for ``base_url`` when one is supplied.
MANAGED_PROVIDER_ID = "openai"
+# Codex's top-level ``cli_auth_credentials_store`` controls where the CLI
+# reads/writes cached credentials: ``file`` → ``~/.codex/auth.json``,
+# ``keyring`` → OS keychain, ``auto`` → keyring-preferred. The Settings
+# UI manages key material through ``auth.json`` exclusively (we have no
+# cross-platform keyring backend), so we pin this to ``file`` whenever
+# we write an API key — otherwise Codex would silently look in the
+# keychain and behave as if no key was configured.
+CREDENTIALS_STORE_KEY = "cli_auth_credentials_store"
+CREDENTIALS_STORE_FILE = "file"
+
def get_codex_home(home: Path | None = None) -> Path:
"""Resolve the directory Codex actually reads ``config.toml`` from.
@@ -272,6 +282,12 @@ def apply_codex_auth(
raise ValueError("api_key is required when auth_mode='api_key'")
auth_data["OPENAI_API_KEY"] = api_key
toml_data["model_provider"] = MANAGED_PROVIDER_ID
+ # Pin Codex to file-based credentials so it actually reads the
+ # ``OPENAI_API_KEY`` we just wrote. Without this, the documented
+ # default (``auto``) prefers the OS keychain, and Codex would
+ # behave as if no key was configured even though ``auth.json``
+ # has one. See CREDENTIALS_STORE_KEY for the rationale.
+ toml_data[CREDENTIALS_STORE_KEY] = CREDENTIALS_STORE_FILE
managed.setdefault("name", "OpenAI")
if base_url:
managed["base_url"] = base_url
@@ -279,9 +295,10 @@ def apply_codex_auth(
managed.pop("base_url", None)
else: # oauth
auth_data.pop("OPENAI_API_KEY", None)
- # Leave model_provider as-is — switching back to ChatGPT/OAuth is
- # the user's responsibility via ``codex login``; we just stop
- # pinning the keyed provider's overrides.
+ # Leave model_provider and cli_auth_credentials_store as-is —
+ # switching back to ChatGPT/OAuth is the user's responsibility
+ # via ``codex login`` (which may legitimately want keyring
+ # storage); we just stop pinning the keyed provider's overrides.
managed.pop("base_url", None)
# If our managed entry is now empty, drop it entirely so we don't
# leave a noisy ``[model_providers.openai]`` table behind.
@@ -315,6 +332,13 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
Reads both files and reports back what the user would see — no
secrets in the response (the UI receives the key length, never the
plaintext key).
+
+ ``credentials_store`` reflects Codex's current ``cli_auth_credentials_store``
+ setting; when it is not ``"file"``, the live key may live in the OS
+ keychain and ``has_api_key`` is a file-only signal. Callers that
+ need to surface the "we can't see your key, it's in the keyring"
+ case should branch on this field rather than treating
+ ``has_api_key=false`` as definitive.
"""
config_path, auth_path = get_codex_config_paths(home)
auth_data = _load_auth(auth_path)
@@ -331,6 +355,13 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
if isinstance(raw, str) and raw.strip():
base_url = raw.strip()
+ store_raw = toml_data.get(CREDENTIALS_STORE_KEY)
+ credentials_store = store_raw if isinstance(store_raw, str) else None
+ # Codex's default when the key is absent is ``auto`` (keyring-preferred);
+ # report that explicitly so the UI doesn't have to know the default.
+ effective_store = credentials_store or "auto"
+ file_store_active = effective_store == CREDENTIALS_STORE_FILE
+
inferred_mode = "api_key" if isinstance(api_key, str) and api_key else "oauth"
return {
"auth_mode": inferred_mode,
@@ -338,4 +369,6 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
"api_key_length": len(api_key) if isinstance(api_key, str) else 0,
"base_url": base_url,
"has_chatgpt_tokens": has_chatgpt_tokens,
+ "credentials_store": effective_store,
+ "file_store_active": file_store_active,
}