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): honor CODEX_HOME and reuse auth.json key for Codex saves

cyh75f331371ec0
diff --git a/tests/test_codex_config.py b/tests/test_codex_config.py
index d00b55dd9..7ea5a9580 100644
--- a/tests/test_codex_config.py
+++ b/tests/test_codex_config.py
@@ -9,6 +9,7 @@ round-trip behavior of the emitter.
from __future__ import annotations
+import datetime as _dt
import json
import sys
from pathlib import Path
@@ -96,6 +97,61 @@ def test_apply_api_key_mode_preserves_unrelated_blocks(tmp_path: Path) -> None:
assert auth["OPENAI_API_KEY"] == "sk-test-1234567890"
+def test_round_trip_datetime_scalars() -> None:
+ """``tomllib`` returns datetime/date/time for temporal TOML values; the
+ emitter must round-trip them unquoted instead of crashing on the
+ JSON fallback (datetimes are not JSON-serializable)."""
+ data = {
+ "created_at": _dt.datetime(2024, 1, 15, 9, 30, 0),
+ "expires_on": _dt.date(2025, 12, 31),
+ "daily_window": _dt.time(9, 0, 0),
+ }
+ parsed = _round_trip(data)
+ assert parsed == data
+
+
+def test_get_codex_home_honors_env(monkeypatch, tmp_path: Path) -> None:
+ """``CODEX_HOME`` points directly at the Codex data dir (matches the
+ rest of the integration in modules/agents/codex/agent.py)."""
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "alt"))
+ assert codex_config.get_codex_home() == tmp_path / "alt"
+ monkeypatch.delenv("CODEX_HOME", raising=False)
+ # When ``home`` is injected (test fixture path), CODEX_HOME must not
+ # override it — fixture isolation has to win.
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "ignored"))
+ assert codex_config.get_codex_home(tmp_path) == tmp_path / ".codex"
+
+
+def test_apply_codex_auth_respects_codex_home(monkeypatch, tmp_path: Path) -> None:
+ """End-to-end: with CODEX_HOME set, apply_codex_auth writes there and
+ leaves ``~/.codex`` untouched. This is the bug the live Codex process
+ would otherwise hit — saved key in one dir, read from another."""
+ alt_home = tmp_path / "alt-codex"
+ monkeypatch.setenv("CODEX_HOME", str(alt_home))
+ # Sanity: the real $HOME/.codex must not exist or, if it does, we
+ # leave the test environment alone — we only assert against alt_home.
+ codex_config.apply_codex_auth(auth_mode="api_key", api_key="sk-env", base_url=None)
+ assert (alt_home / "auth.json").exists()
+ assert (alt_home / "config.toml").exists()
+ auth = json.loads((alt_home / "auth.json").read_text(encoding="utf-8"))
+ assert auth["OPENAI_API_KEY"] == "sk-env"
+
+
+def test_read_codex_api_key_returns_stored_value(tmp_path: Path) -> None:
+ """The base-URL-only update path in vibe/api.py depends on this."""
+ home = tmp_path
+ codex_home = home / ".codex"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(
+ json.dumps({"OPENAI_API_KEY": "sk-from-disk"}), encoding="utf-8"
+ )
+ assert codex_config.read_codex_api_key(home=home) == "sk-from-disk"
+
+
+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_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/vibe/api.py b/vibe/api.py
index 72c2c516e..043ac3247 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2141,6 +2141,11 @@ def save_codex_auth(payload: dict) -> dict:
if auth_mode == "api_key" and not api_key:
# Allow callers to PATCH base_url alone by reusing the stored key.
+ # Try V2Config first (typical case after a save via this endpoint),
+ # then fall back to ``~/.codex/auth.json`` for keys written outside
+ # our flow (e.g. ``codex login --with-api-key`` or pre-Settings
+ # installs); the live Codex process reads from there too, so a
+ # base-URL-only update must succeed if either source has the key.
with CONFIG_LOCK:
try:
existing = load_config()
@@ -2148,6 +2153,13 @@ def save_codex_auth(payload: dict) -> dict:
api_key = getattr(stored, "api_key", None) or None
except Exception:
api_key = None
+ if not api_key:
+ try:
+ from vibe.codex_config import read_codex_api_key
+
+ api_key = read_codex_api_key()
+ except Exception:
+ api_key = None
if not api_key:
return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
index ab72d2797..cfea4f9b5 100644
--- a/vibe/codex_config.py
+++ b/vibe/codex_config.py
@@ -16,6 +16,7 @@ changes via ``restart_backend('codex')``.
from __future__ import annotations
+import datetime as _dt
import json
import logging
import os
@@ -38,7 +39,20 @@ MANAGED_PROVIDER_ID = "openai"
def get_codex_home(home: Path | None = None) -> Path:
- return (home or Path.home()) / ".codex"
+ """Resolve the directory Codex actually reads ``config.toml`` from.
+
+ Codex respects the ``CODEX_HOME`` environment variable (unlike most
+ tools, this points directly at the data directory — *not* HOME).
+ ``modules/agents/codex/agent.py`` already treats it as authoritative,
+ so we mirror that here; otherwise "Save and restart Codex" can report
+ success while the live process keeps reading a different directory.
+ """
+ if home is not None:
+ return home / ".codex"
+ env_home = os.environ.get("CODEX_HOME")
+ if env_home:
+ return Path(env_home).expanduser()
+ return Path.home() / ".codex"
def get_codex_config_paths(home: Path | None = None) -> tuple[Path, Path]:
@@ -109,6 +123,17 @@ def _dump_toml_value(value: Any) -> str:
return repr(value)
if isinstance(value, str):
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
+ # TOML temporal scalars: ``tomllib`` parses ``2024-01-15T09:30:00`` as a
+ # ``datetime``, dates as ``date``, times as ``time``. Their ``isoformat``
+ # output is exactly the RFC3339-ish form TOML expects, and they are
+ # emitted *unquoted* (a quoted version would round-trip as a string,
+ # silently corrupting the user's config).
+ if isinstance(value, _dt.datetime):
+ return value.isoformat()
+ if isinstance(value, _dt.date):
+ return value.isoformat()
+ if isinstance(value, _dt.time):
+ return value.isoformat()
if isinstance(value, list):
return "[" + ", ".join(_dump_toml_value(item) for item in value) + "]"
# Fallback: serialize as JSON-ish string (best-effort for unexpected types).
@@ -269,6 +294,21 @@ def apply_codex_auth(
_atomic_write(config_path, _dump_toml(toml_data), mode=0o600)
+def read_codex_api_key(home: Path | None = None) -> Optional[str]:
+ """Return the API key currently stored in ``auth.json``, if any.
+
+ Used as a fallback when the UI sends a base-URL-only update: the
+ V2Config cache may not have the key (e.g. ``codex login --with-api-key``
+ wrote it directly to ``auth.json`` outside our flow), but the live
+ Codex process still reads it from disk, so we must too.
+ """
+ _, auth_path = get_codex_config_paths(home)
+ raw = _load_auth(auth_path).get("OPENAI_API_KEY")
+ if isinstance(raw, str) and raw.strip():
+ return raw
+ return None
+
+
def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
"""Return the user-visible auth state for the Settings UI.