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(codex): close relay marker follow-ups 1449-1451 and 1453 (#1455)
Call White8a6c77a8e901
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex a119139f5..ca1cfd3e6 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -3860,6 +3860,23 @@ class AgentAuthService:captured_codex_relay, observed_codex_api_key_auth = (self._capture_codex_relay_for_oauth())+ # Durability (#1450): a fresh capture — or the official-key+ # transition's clear (``None`` marker) — is persisted BEFORE+ # the cleanup below destroys the on-disk relay evidence. If+ # the owning V2Config write later fails, the transition state+ # has already landed; a failed pre-persist only costs relay+ # recovery, never the OAuth flow itself.+ if captured_codex_relay is not None or observed_codex_api_key_auth:+ try:+ from vibe.codex_config import persist_codex_relay_marker++ if not persist_codex_relay_marker(captured_codex_relay):+ logger.warning(+ "Codex relay marker pre-persist failed; "+ "switch-back recovery may be lost"+ )+ except Exception: # noqa: BLE001+ logger.warning("Codex relay marker pre-persist raised", exc_info=True)await self._clear_codex_api_key_for_oauth()try:config = getattr(self.controller, "config", None)diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex ac89b48a1..1d06ed7b3 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -2331,9 +2331,17 @@ class CodexRelayRoundTripScenarioTests(unittest.IsolatedAsyncioTestCase):self._codex_home_env.start()self.addCleanup(self._codex_home_env.stop)- # Seed the pre-OAuth state: API-key auth against a relay.+ # Seed the pre-OAuth state: API-key auth against a relay. The+ # token blob makes the post-OAuth state carry live OAuth+ # credentials — the marker gate requires them.(codex_home / "auth.json").write_text(- json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": "sk-relay"}),+ json.dumps(+ {+ "auth_mode": "apikey",+ "OPENAI_API_KEY": "sk-relay",+ "tokens": {"id_token": "seed"},+ }+ ),encoding="utf-8",)self._seed_hand_rolled_relay()diff --git a/tests/test_codex_api_auth.py b/tests/test_codex_api_auth.pyindex 60e6313dc..b32dc37f2 100644--- a/tests/test_codex_api_auth.py+++ b/tests/test_codex_api_auth.py@@ -296,7 +296,12 @@ def test_get_codex_auth_uses_oauth_marker_when_disk_chain_empty(monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))codex_home = tmp_path / ".codex"codex_home.mkdir(parents=True, exist_ok=True)- (codex_home / "auth.json").write_text("{}", encoding="utf-8")+ # Live OAuth credentials on disk (file store): the marker gate+ # requires them.+ (codex_home / "auth.json").write_text(+ json.dumps({"tokens": {"id_token": "x"}, "auth_mode": "chatgpt"}),+ encoding="utf-8",+ )(codex_home / "config.toml").write_text('cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8")@@ -458,3 +463,396 @@ def test_marker_ignored_when_credentials_may_live_in_keyring(assert result.get("ok") is Truetoml = (codex_home / "config.toml").read_text(encoding="utf-8")assert "https://stale.example/v1" not in toml+++def test_marker_ignored_after_external_logout_clears_tokens(+ monkeypatch, tmp_path: Path+) -> None:+ """#1453: ``codex logout`` during the OAuth window clears the tokens;+ with no key and no tokens on disk the user has signed out of the+ relay entirely, and the marker must surface nothing in either+ consumer."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ # Signed out: no key, no tokens; file store still pinned.+ (codex_home / "auth.json").write_text("{}", encoding="utf-8")+ (codex_home / "config.toml").write_text(+ 'cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n',+ encoding="utf-8",+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="oauth",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ state = api.get_codex_auth()+ assert state["base_url"] is None++ result = api.save_codex_auth({"auth_mode": "api_key", "api_key": "sk-official"})+ assert result.get("ok") is True+ toml = (codex_home / "config.toml").read_text(encoding="utf-8")+ assert "https://stale.example/v1" not in toml+++def test_save_codex_auth_oauth_captures_relay_marker(+ monkeypatch, tmp_path: Path+) -> None:+ """#1449: an ``auth_mode="oauth"`` save through the Settings API+ (the non-React client path) captures the live relay identity before+ the cleanup destroys it, with controller-path retention semantics."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": "sk-relay"}),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text(+ 'model_provider = "OpenAI"\n'+ 'cli_auth_credentials_store = "file"\n'+ "\n"+ "[model_providers.OpenAI]\n"+ 'name = "OpenAI"\n'+ 'base_url = "https://relay.example/v1"\n'+ 'wire_api = "responses"\n',+ encoding="utf-8",+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key", api_key="sk-relay", base_url=None, oauth_relay_marker=None+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})+ persisted: list[dict | None] = []+ import vibe.codex_config as codex_config_module++ monkeypatch.setattr(+ codex_config_module,+ "persist_codex_relay_marker",+ lambda marker: persisted.append(marker) or True,+ )++ result = api.save_codex_auth({"auth_mode": "oauth"})+ assert result.get("ok") is True++ # Durable pre-persist fired before the cleanup…+ assert persisted == [{"provider_id": "OpenAI", "base_url": "https://relay.example/v1"}]+ # …and the owning V2Config write mirrors it.+ assert fake_codex.oauth_relay_marker == {+ "provider_id": "OpenAI",+ "base_url": "https://relay.example/v1",+ }+ # The cleanup did run (pointer cleared).+ toml = (codex_home / "config.toml").read_text(encoding="utf-8")+ assert not [line for line in toml.splitlines() if line.startswith("model_provider")]+++def test_save_codex_auth_oauth_official_key_transition_clears_marker(+ monkeypatch, tmp_path: Path+) -> None:+ """Retention semantics on the direct path: an OAuth save while the+ disk shows an official API key with no relay clears the stale+ marker."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": "sk-official"}),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text(+ 'cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8"+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ result = api.save_codex_auth({"auth_mode": "oauth"})+ assert result.get("ok") is True+ assert fake_codex.oauth_relay_marker is None+++def test_save_codex_auth_keeps_live_provider_when_urls_match_marker(+ monkeypatch, tmp_path: Path+) -> None:+ """Same-URL provider swap: the user activates provider B (same relay+ URL as the marker's A) during the OAuth window. The disk chain+ supplies the URL, so the restore hint must NOT fire — B's pointer+ and settings stay."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"tokens": {"id_token": "x"}, "auth_mode": "chatgpt"}),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text(+ 'model_provider = "ProviderB"\n'+ 'cli_auth_credentials_store = "file"\n'+ "\n"+ "[model_providers.ProviderB]\n"+ 'name = "B"\n'+ 'base_url = "https://relay.example/v1"\n'+ 'wire_api = "chat"\n'+ "\n"+ "[model_providers.OpenAI]\n"+ 'name = "OpenAI"\n'+ 'base_url = "https://relay.example/v1"\n'+ 'wire_api = "responses"\n',+ encoding="utf-8",+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="oauth",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://relay.example/v1"},+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ result = api.save_codex_auth({"auth_mode": "api_key", "api_key": "sk-relay"})+ assert result.get("ok") is True+ toml = (codex_home / "config.toml").read_text(encoding="utf-8")+ pointer = [line for line in toml.splitlines() if line.startswith("model_provider")]+ assert pointer == ['model_provider = "ProviderB"']+++def test_remove_backend_api_key_reports_v2_clear_failure(+ monkeypatch, tmp_path: Path+) -> None:+ """#1451: when the post-removal V2Config save fails, the response+ must say so instead of silently claiming a clean wipe."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": "sk-official"}),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text('model = "gpt-5.4"\n', encoding="utf-8")++ def boom():+ raise OSError("disk full")++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key", api_key="sk-official", base_url=None, oauth_relay_marker=None+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=boom+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ result = api.remove_backend_api_key("codex")+ assert result.get("ok") is True+ assert result["notices"][0]["code"] == "v2_clear_failed"+ assert "disk full" in result["notices"][0]["detail"]+ # The disk key removal itself did happen.+ auth = json.loads((codex_home / "auth.json").read_text(encoding="utf-8"))+ assert "OPENAI_API_KEY" not in auth+++def test_empty_token_bag_is_not_live_oauth_evidence(+ monkeypatch, tmp_path: Path+) -> None:+ """An empty ``tokens`` bag means signed out — the marker gate must+ not treat it as live OAuth evidence and resurrect the stale relay."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"tokens": {}, "auth_mode": "chatgpt"}), encoding="utf-8"+ )+ (codex_home / "config.toml").write_text(+ 'cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8"+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="oauth",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)++ state = api.get_codex_auth()+ assert state["base_url"] is None+++def test_unusable_token_bag_is_not_live_oauth_evidence(+ monkeypatch, tmp_path: Path+) -> None:+ """A bag with only blank strings / unrelated metadata is signed out+ (migration-scanner predicate) — the marker must not be consumed."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"tokens": {"id_token": "", "meta": "x"}, "auth_mode": "chatgpt"}),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text(+ 'cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8"+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="oauth",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=lambda: None+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)++ state = api.get_codex_auth()+ assert state["base_url"] is None+++def test_official_key_oauth_save_prepersists_marker_clear(+ monkeypatch, tmp_path: Path+) -> None:+ """Durability symmetry: the official-key transition's marker CLEAR+ is pre-persisted (as ``None``) before the destructive cleanup, so a+ later V2Config failure cannot resurrect the abandoned relay."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": "sk-official"}),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text(+ 'cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8"+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},+ )++ def failing_save():+ raise OSError("config.json unwritable")++ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=failing_save+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})+ persisted: list[dict | None] = []+ import vibe.codex_config as codex_config_module++ monkeypatch.setattr(+ codex_config_module,+ "persist_codex_relay_marker",+ lambda marker: persisted.append(marker) or True,+ )++ result = api.save_codex_auth({"auth_mode": "oauth"})+ assert result.get("ok") is True+ # The clear was durably recorded even though the owning save failed.+ assert persisted == [None]+++def test_save_codex_auth_reports_v2_mirror_failure(+ monkeypatch, tmp_path: Path+) -> None:+ """A failed V2Config mirror write surfaces a partial-failure notice+ instead of a silent success while runtime reconciliation would see+ the stale config."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"tokens": {"id_token": "x"}, "auth_mode": "chatgpt"}),+ encoding="utf-8",+ )+ (codex_home / "config.toml").write_text(+ 'cli_auth_credentials_store = "file"\nmodel = "gpt-5.4"\n', encoding="utf-8"+ )++ def failing_save():+ raise OSError("config.json unwritable")++ fake_codex = types.SimpleNamespace(+ auth_mode="oauth", api_key=None, base_url=None, oauth_relay_marker=None+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=failing_save+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ result = api.save_codex_auth({"auth_mode": "api_key", "api_key": "sk-new"})+ assert result.get("ok") is True+ codes = [n["code"] for n in (result.get("notices") or [])]+ assert "v2_mirror_save_failed" in codes+++def test_remove_backend_api_key_appends_v2_clear_failure_notice(+ monkeypatch, tmp_path: Path+) -> None:+ """An earlier ``cleared_custom_relay_pointer`` notice survives a+ later V2Config clear failure — both facts are true and both must+ reach the client."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ (codex_home / "auth.json").write_text(+ json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": "sk-relay"}),+ encoding="utf-8",+ )+ # User-owned relay pointer: remove-key clears it (notice) first.+ (codex_home / "config.toml").write_text(+ 'model_provider = "OpenAI"\n\n[model_providers.OpenAI]\nbase_url = "https://relay.example/v1"\n',+ encoding="utf-8",+ )++ def failing_save():+ raise OSError("disk full")++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key", api_key="sk-relay", base_url=None, oauth_relay_marker=None+ )+ fake_config = types.SimpleNamespace(+ agents=types.SimpleNamespace(codex=fake_codex), save=failing_save+ )+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ result = api.remove_backend_api_key("codex")+ assert result.get("ok") is True+ codes = [n["code"] for n in (result.get("notices") or [])]+ assert "cleared_custom_relay_pointer" in codes+ assert "v2_clear_failed" in codesdiff --git a/vibe/api.py b/vibe/api.pyindex a7b317e4f..4e88e074f 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -9755,6 +9755,20 @@ def remove_backend_api_key(backend: str) -> dict:config.save()except Exception as exc: # noqa: BLE001logger.warning("V2Config clear during remove-key failed for %s: %s", backend, exc)+ # The disk key is already gone (the user-visible truth — report+ # success), but the persisted V2Config copy (cached key/base_url/+ # relay marker) may still hold stale auth state (#1451). Surface+ # it as a notice so the UI can say "removed, but saved settings+ # may be stale" instead of silently claiming a clean wipe.+ # Append: an earlier ``cleared_custom_relay_pointer`` notice from+ # ``apply_codex_auth`` is still true and must survive.+ notices = notices + [+ {+ "code": "v2_clear_failed",+ "backend": backend,+ "detail": str(exc),+ }+ ]# Both backends keep runtime state in the controller. Codex owns a# persistent app-server; Claude owns cached SDK sessions and a loaded@@ -9874,17 +9888,23 @@ def get_codex_auth() -> dict:# cleanup destroys the on-disk evidence) is the only recovery# source: it is consumed verbatim, with no ambient-state inference —# dormant sections and stale caches surface nothing. The marker is- # only consulted while the disk shows OAuth as the live mode AND the+ # only consulted while the disk shows live OAuth credentials AND the# credential store actually exposes the live state to us: once an# API key exists in ``auth.json`` (e.g. the user ran ``codex login# --with-api-key`` outside Avibe) the live disk configuration is- # authoritative, and when ``cli_auth_credentials_store`` is- # ``auto``/``keyring`` the key may live in the OS keychain instead —- # ``has_api_key`` is a file-only signal there, so an external- # official-key switch is indistinguishable from OAuth and a leftover- # marker must not reroute a pasted key to the relay it remembers.+ # authoritative; when ``cli_auth_credentials_store`` is+ # ``auto``/``keyring`` the key may live in the OS keychain instead+ # (file-only ``has_api_key`` can't see it); and when the tokens are+ # gone too (e.g. ``codex logout`` during the OAuth window) the user+ # has signed out of the relay entirely (#1453) — in all three cases+ # the leftover marker must not surface or reroute a pasted key to+ # the relay it remembers.relay_marker = None- if not disk_state.get("has_api_key") and disk_state.get("file_store_active"):+ if (+ not disk_state.get("has_api_key")+ and disk_state.get("file_store_active")+ and disk_state.get("has_chatgpt_tokens")+ ):relay_marker = read_codex_relay_marker(raw_relay_marker)if relay_marker:effective_base_url: str | None = disk_state.get("base_url") or relay_marker["base_url"]@@ -10033,14 +10053,22 @@ def save_codex_auth(payload: dict) -> dict:# the OAuth cleanup destroyed the on-disk evidence. Consumed# verbatim — a plain cached ``base_url`` is NOT a recovery source# (it is only the user's last saved preference and may be stale).- # Gated on the live state being knowable AND OAuth: an API key in+ # Gated on live OAuth credentials being observable: an API key in# ``auth.json`` (e.g. ``codex login --with-api-key`` outside Avibe)- # means the live disk configuration already won, and a non-file- # credential store (``auto``/``keyring``) hides the key in the OS- # keychain where our file-only ``has_api_key`` can't see it — either- # way the leftover marker must not reroute a pasted key to the relay- # it remembers.+ # means the live disk configuration already won; a non-file+ # credential store hides the key in the OS keychain; and cleared+ # tokens (``codex logout`` in the OAuth window) mean the user signed+ # out of the relay (#1453). In all three cases the leftover marker+ # must not reroute a pasted key to the relay it remembers.+ #+ # ``#1449``: an ``auth_mode="oauth"`` save through this endpoint is+ # itself an OAuth transition for non-React clients — capture the+ # live relay identity before ``apply_codex_auth`` destroys it, with+ # the same retention semantics as the controller path.marker = None+ captured_oauth_relay: Optional[dict] = None+ observed_api_key_auth = False+ codex_disk_state: dict = {}try:from vibe.codex_config import read_codex_auth_state, read_codex_relay_marker@@ -10052,12 +10080,46 @@ def save_codex_auth(payload: dict) -> dict:raw_marker = getattr(marker_codex, "oauth_relay_marker", None)except Exception:raw_marker = None- if not codex_disk_state.get("has_api_key") and codex_disk_state.get("file_store_active"):+ if (+ not codex_disk_state.get("has_api_key")+ and codex_disk_state.get("file_store_active")+ and codex_disk_state.get("has_chatgpt_tokens")+ ):marker = read_codex_relay_marker(raw_marker)+ if auth_mode == "oauth":+ live_base_url = codex_disk_state.get("base_url")+ if isinstance(live_base_url, str) and live_base_url.strip():+ live_provider_id = codex_disk_state.get("active_provider_id")+ captured_oauth_relay = {+ "base_url": live_base_url.strip(),+ "provider_id": live_provider_id+ if isinstance(live_provider_id, str) and live_provider_id.strip()+ else "",+ }+ else:+ observed_api_key_auth = bool(codex_disk_state.get("has_api_key"))except Exception:logger.debug("Codex relay marker read failed", exc_info=True)marker = None+ # Durability (#1450): a fresh capture — or the official-key+ # transition's clear — is persisted BEFORE ``apply_codex_auth(oauth)``+ # destroys the on-disk relay evidence, so a later V2Config failure+ # cannot lose the transition state. A failed pre-persist only costs+ # switch-back recovery, never the save.+ if auth_mode == "oauth" and (captured_oauth_relay is not None or observed_api_key_auth):+ try:+ from vibe.codex_config import persist_codex_relay_marker++ # ``None`` here is deliberate for the official-key case: the+ # pre-persist records the transition's marker-clear.+ if not persist_codex_relay_marker(captured_oauth_relay):+ logger.warning(+ "Codex relay marker pre-persist failed; switch-back recovery may be lost"+ )+ except Exception:+ logger.warning("Codex relay marker pre-persist raised", exc_info=True)+if base_url_present:effective_base_url = base_url_changeelse:@@ -10073,14 +10135,20 @@ def save_codex_auth(payload: dict) -> dict:if not effective_base_url and marker:effective_base_url = marker["base_url"]- # Provider-identity restore hint: when the resolved relay matches the- # marker (explicit form value pre-populated from it, or the omitted- # fallback) and the captured provider section still exists on disk- # with the same URL, ``apply_codex_auth`` re-points ``model_provider``- # at that section instead of rebuilding a managed provider — the- # user's own ``wire_api`` / provider settings survive the round trip.+ # Provider-identity restore hint: only when the marker actually+ # SUPPLIED the resolved URL — the omitted-``base_url`` fallback, or+ # an explicit form value pre-populated from the marker-backed state+ # while the disk chain itself carries no URL. When the disk chain+ # resolved the same URL (the user activated a different provider+ # section with an identical relay during the OAuth window), the+ # live pointer wins and must not be re-pointed at the marker's+ # provider.restore_provider_id: Optional[str] = None- if marker is not None and effective_base_url == marker["base_url"]:+ if (+ marker is not None+ and effective_base_url == marker["base_url"]+ and codex_disk_state.get("base_url") != effective_base_url+ ):restore_provider_id = marker["provider_id"]from vibe.codex_config import apply_codex_auth@@ -10111,13 +10179,34 @@ def save_codex_auth(payload: dict) -> dict:config.agents.codex.auth_mode = auth_modeconfig.agents.codex.api_key = api_key if auth_mode == "api_key" else Noneconfig.agents.codex.base_url = effective_base_url- # An explicit API-key save consumes the OAuth-transition marker:- # the user just chose their endpoint (restored from the marker or- # typed fresh), so the one-shot recovery record is spent. OAuth- # saves keep it — a later switch-back still needs the recovery.+ # Marker lifecycle on save: an explicit API-key save consumes+ # the OAuth-transition marker (the user just chose their+ # endpoint — restored, typed fresh, or official-only); an OAuth+ # save applies the same retention semantics as the controller+ # path (#1449): fresh capture overwrites, the official-key+ # transition clears, a repeated pure-OAuth save retains.+ # A failed save here only loses the V2Config mirror — the+ # durable marker state was already recorded by the pre-persist+ # above, and the on-disk codex files are authoritative.if auth_mode == "api_key":config.agents.codex.oauth_relay_marker = None- config.save()+ elif captured_oauth_relay is not None:+ config.agents.codex.oauth_relay_marker = captured_oauth_relay+ elif observed_api_key_auth:+ config.agents.codex.oauth_relay_marker = None+ try:+ config.save()+ except Exception:+ # The on-disk codex files are authoritative and the durable+ # marker state was pre-persisted, but the V2Config mirror+ # (auth_mode / base_url intent the controller reloads via+ # ``_load_backend_runtime_config``) did NOT land — surface a+ # partial-failure notice instead of silently reporting+ # success while runtime reconciliation sees stale config.+ logger.warning("V2Config mirror write failed during codex auth save", exc_info=True)+ notices = notices + [+ {"code": "v2_mirror_save_failed", "detail": "saved to codex files but not to Avibe config"}+ ]restart_result = restart_backend("codex",diff --git a/vibe/codex_config.py b/vibe/codex_config.pyindex 1e4b2eefd..59d1ba9e3 100644--- a/vibe/codex_config.py+++ b/vibe/codex_config.py@@ -509,6 +509,49 @@ def read_codex_relay_marker(marker: object) -> Optional[Dict[str, str]]:return {"base_url": base_url.strip(), "provider_id": provider_id.strip()}+def _tokens_bag_is_usable(tokens: object) -> bool:+ """True when the OAuth token bag carries at least one usable token.++ Mirrors the migration scanner's predicate (any non-blank+ ``access_token`` / ``refresh_token`` / ``id_token``), so a bag with+ only blank strings or unrelated metadata reads as signed out —+ matching how ``apply_codex_auth`` treats it.+ """+ if not isinstance(tokens, dict) or not tokens:+ return False+ return any(+ isinstance(tokens.get(field), str) and tokens[field].strip()+ for field in ("access_token", "refresh_token", "id_token")+ )+++def persist_codex_relay_marker(marker: Optional[Dict[str, str]]) -> bool:+ """Durably record (or clear) the OAuth-transition relay marker in V2Config.++ Split out so both OAuth write paths — the controller's+ ``AgentAuthService._persist_backend_auth_mode`` and the Settings API+ ``save_codex_auth`` — can persist a fresh capture BEFORE the+ destructive ``apply_codex_auth(oauth)`` cleanup destroys the on-disk+ relay evidence (#1450). A later V2Config failure in the owning flow+ then cannot lose the capture. Returns ``True`` when the write+ landed; ``False`` (never raises) so callers can degrade to "recovery+ lost, OAuth proceeds".+ """+ from config.v2_config import CONFIG_LOCK, V2Config++ try:+ with CONFIG_LOCK:+ try:+ config = V2Config.load()+ except FileNotFoundError:+ config = V2Config.default()+ config.agents.codex.oauth_relay_marker = marker+ config.save()+ return True+ except Exception: # noqa: BLE001+ return False++def read_codex_api_key(home: Path | None = None) -> Optional[str]:"""Return the API key currently stored in ``auth.json``, if any.@@ -604,7 +647,14 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:auth_data = _load_auth(auth_path)toml_data = _load_toml(config_path)api_key = auth_data.get("OPENAI_API_KEY")- has_chatgpt_tokens = isinstance(auth_data.get("tokens"), dict)+ # An unusable token bag is "signed out", not live OAuth evidence:+ # the predicate mirrors the migration scanner (at least one of+ # access_token / refresh_token / id_token non-blank), and+ # ``apply_codex_auth`` treats a bag without usable tokens as+ # unsigned-in. The marker gates rely on this field to mean "OAuth+ # credentials are actually present".+ tokens_bag = auth_data.get("tokens")+ has_chatgpt_tokens = _tokens_bag_is_usable(tokens_bag)chatgpt_account = _extract_chatgpt_account(auth_data) if has_chatgpt_tokens else Noneproviders = toml_data.get("model_providers")