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): keep relay base_url across auth-mode switches (#1443)
Call Whiteed02d67604d8
diff --git a/config/v2_config.py b/config/v2_config.pyindex ddc048cc3..3f6b52d97 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -1999,6 +1999,18 @@ class CodexConfig:auth_mode: Literal["oauth", "api_key"] = "oauth"api_key: Optional[str] = Nonebase_url: Optional[str] = None+ # Relay recovery marker captured at an OAuth transition:+ # ``{"provider_id": str, "base_url": str}`` recorded from the live+ # ``config.toml`` immediately BEFORE the OAuth cleanup clears the+ # provider pointer and drops the managed section (the only moment+ # the relay's identity is observable — Settings-created managed+ # relays and hand-rolled sections are both visible then). Consumed+ # verbatim, with no ambient-state inference, by the Settings read+ # and the next API-key save; cleared only by an explicit API-key+ # save or sign-out. Repeated OAuth transitions retain it. Older+ # configs load with ``None`` (unknown JSON keys are filtered), so+ # the field degrades safely across releases.+ oauth_relay_marker: Optional[dict] = None@dataclassdiff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 5db5c08da..a119139f5 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -2423,6 +2423,12 @@ class AgentAuthService:# override, sending OAuth requests to a relay# that only accepts API keys (401).target.base_url = None+ # Sign-out is a full reset of saved codex auth+ # state — the OAuth-transition relay marker goes+ # with it (Codex-only field; setattr no-ops on+ # backends without it via the getattr guard).+ if backend == "codex":+ target.oauth_relay_marker = None# Sign out is an explicit user choice — flip# the marker so ``build_claude_subprocess_env``# honors ``auth_mode == "oauth"`` strictly@@ -2436,6 +2442,8 @@ class AgentAuthService:target.auth_mode = "oauth"target.api_key = Nonetarget.base_url = None+ if backend == "codex":+ target.oauth_relay_marker = Noneif backend == "claude":target.auth_mode_set = Truesaver()@@ -3494,6 +3502,44 @@ class AgentAuthService:except Exception as err: # noqa: BLE001logger.warning("post_web_success_hook failed for %s: %s", backend, err)+ def _capture_codex_relay_for_oauth(self) -> tuple[dict | None, bool]:+ """Read the live relay identity before OAuth cleanup.++ Called immediately before ``_clear_codex_api_key_for_oauth``+ clears the provider pointer and drops the managed section; after+ that cleanup the relay is invisible on disk (Settings-created+ managed relays are deleted outright), so this is the only moment+ its identity is observable. Returns+ ``(marker, observed_api_key_auth)``:++ - ``marker`` — ``{"provider_id": str, "base_url": str}`` when a+ live relay is chain-readable (pointer or managed/legacy+ section), else ``None``.+ - ``observed_api_key_auth`` — True when the disk shows an active+ API key WITHOUT any relay. That combination is the+ official-key transition (e.g. ``codex login --with-api-key``+ to the default endpoint): the user deliberately left relay+ auth, so any earlier marker is stale and must be cleared+ rather than retained for a future switch-back.++ Failures degrade to ``(None, False)`` — a capture miss only+ costs relay recovery on switch-back, never the OAuth flow.+ """+ try:+ from vibe.codex_config import read_codex_auth_state++ state = read_codex_auth_state()+ except Exception: # noqa: BLE001+ return None, False+ base_url = state.get("base_url")+ if isinstance(base_url, str) and base_url.strip():+ provider_id = state.get("active_provider_id")+ return {+ "base_url": base_url.strip(),+ "provider_id": provider_id if isinstance(provider_id, str) and provider_id.strip() else "",+ }, False+ return None, bool(state.get("has_api_key"))+async def _clear_claude_settings_env_for_oauth(self) -> None:try:from vibe.claude_config import apply_claude_auth@@ -3797,9 +3843,23 @@ class AgentAuthService:async def _persist_backend_auth_mode(self, backend: str, auth_mode: str) -> None:"""Persist V2Config.agents.<backend>.auth_mode for web and IM flows."""+ captured_codex_relay: dict | None = None+ observed_codex_api_key_auth = Falseif backend == "claude" and auth_mode == "oauth":await self._clear_claude_settings_env_for_oauth()if backend == "codex" and auth_mode == "oauth":+ # Capture the live relay identity BEFORE the OAuth pass runs+ # its cleanup: the pointer clear / managed-section drop is+ # correct for OAuth runtime (ChatGPT tokens must hit OpenAI's+ # official endpoint) but it also destroys the only on-disk+ # evidence of the relay the user had. The explicit+ # ``oauth_relay_marker`` recorded here is what lets the+ # Settings form and the next API-key save restore the relay+ # instead of silently rerouting the key to+ # ``api.openai.com`` (401s).+ captured_codex_relay, observed_codex_api_key_auth = (+ self._capture_codex_relay_for_oauth()+ )await self._clear_codex_api_key_for_oauth()try:config = getattr(self.controller, "config", None)@@ -3831,8 +3891,25 @@ class AgentAuthService:and (bool(getattr(target, "api_key", None))or bool(getattr(target, "base_url", None))+ or getattr(target, "oauth_relay_marker", None) is not None+ or captured_codex_relay is not None+ or observed_codex_api_key_auth))+ # Relay-marker retention semantics for the OAuth transition:+ # fresh capture → overwrite (latest relay wins)+ # official-key transition → clear (the user deliberately+ # left relay auth; a stale marker+ # would resurface and reroute a+ # future key to the old relay)+ # repeated pure-OAuth → retain (nothing new observed;+ # the earlier capture stays valid)+ if captured_codex_relay is not None:+ resolved_codex_relay_marker: dict | None = captured_codex_relay+ elif observed_codex_api_key_auth:+ resolved_codex_relay_marker = None+ else:+ resolved_codex_relay_marker = getattr(target, "oauth_relay_marker", None)if not needs_mode_write and not needs_marker_write and not needs_codex_oauth_cleanup:returntry:@@ -3845,7 +3922,16 @@ class AgentAuthService:target.auth_mode_set = Trueif needs_codex_oauth_cleanup:target.api_key = None+ # ``base_url`` returns to plain "last saved+ # preference" semantics (the live relay is gone+ # for OAuth); the explicit ``oauth_relay_marker``+ # carries the recovery record instead. A repeated+ # OAuth transition captures nothing (the pointer+ # is already gone), so retain any existing marker+ # — only an explicit API-key save or sign-out+ # clears it.target.base_url = None+ target.oauth_relay_marker = resolved_codex_relay_markersaver()except ImportError:if needs_mode_write:@@ -3855,6 +3941,7 @@ class AgentAuthService:if needs_codex_oauth_cleanup:target.api_key = Nonetarget.base_url = None+ target.oauth_relay_marker = resolved_codex_relay_markersaver()if loaded_config is not None and config is not None:compat_target = getattr(config, backend, None)@@ -3866,6 +3953,7 @@ class AgentAuthService:if needs_codex_oauth_cleanup:setattr(compat_target, "api_key", None)setattr(compat_target, "base_url", None)+ setattr(compat_target, "oauth_relay_marker", resolved_codex_relay_marker)except Exception as err: # noqa: BLE001logger.warning("Failed to persist auth_mode=%s after web flow for %s: %s",diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 0bb1bd37c..5bb646e89 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -99,6 +99,13 @@ scenarios:layer: scenariobackend: sharedtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_reauth_requires_acknowledgement_and_reaches_consistent_terminal+ - id: AUTH-SETUP-110+ name: Codex OAuth round trip keeps the relay base URL through settings save and relaunch config+ status: covered+ kind: happy_path+ layer: scenario+ backend: codex+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_codex_oauth_api_key_relay_round_trip_scenario- id: AUTH-SETUP-201name: Re-entering setup replaces the active flowstatus: covereddiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex da4d02fab..ac89b48a1 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -2264,5 +2264,201 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):ScenarioExpect.step_history(runner, ["start_setup"])+class CodexRelayRoundTripScenarioTests(unittest.IsolatedAsyncioTestCase):+ """Scenario: AUTH-SETUP-110.++ Closed loop for the reported regression: a relay user completes the+ OAuth transition (Settings web flow success hook), reloads Settings,+ saves API-key auth exactly the way the React form does (explicit+ ``base_url`` from the reloaded state), and the on-disk launch config+ the next ``codex app-server`` reads must point back at the relay —+ not at ``api.openai.com`` with a relay key (the 401 trap).++ Runs against BOTH relay shapes a real install can be in: a+ hand-rolled ``[model_providers.OpenAI]`` section, and the+ ``openai-managed`` provider the Settings API-key save itself creates+ (the OAuth cleanup deletes the managed section outright, which is+ why recovery rides the explicit ``oauth_relay_marker``).+ """++ def _seed_hand_rolled_relay(self) -> None:+ # The file credential store pin comes from the API-key save+ # that configured the relay (or codex's own login) and survives+ # the OAuth transition — the marker gate requires it.+ (self.home / ".codex" / "config.toml").write_text(+ "\n".join(+ [+ 'model_provider = "OpenAI"',+ 'cli_auth_credentials_store = "file"',+ "",+ "[model_providers.OpenAI]",+ 'name = "OpenAI"',+ 'base_url = "https://relay.example/v1"',+ 'wire_api = "responses"',+ ]+ ),+ encoding="utf-8",+ )++ def _seed_managed_relay(self) -> None:+ # The shape ``apply_codex_auth(api_key, base_url=...)`` writes:+ # pointer at our managed section. The OAuth pass later deletes+ # the whole section, leaving no on-disk relay evidence at all.+ (self.home / ".codex" / "config.toml").write_text(+ "\n".join(+ [+ 'model_provider = "openai-managed"',+ 'cli_auth_credentials_store = "file"',+ "",+ "[model_providers.openai-managed]",+ 'name = "OpenAI"',+ 'wire_api = "responses"',+ 'requires_openai_auth = true',+ 'base_url = "https://relay.example/v1"',+ "supports_websockets = false",+ ]+ ),+ encoding="utf-8",+ )++ def setUp(self) -> None:+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ self.home = Path(state_dir.name)+ codex_home = self.home / ".codex"+ codex_home.mkdir(parents=True)+ self._codex_home_env = patch.dict(os.environ, {"CODEX_HOME": str(codex_home)})+ self._codex_home_env.start()+ self.addCleanup(self._codex_home_env.stop)++ # Seed the pre-OAuth state: API-key auth against a relay.+ (codex_home / "auth.json").write_text(+ json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": "sk-relay"}),+ encoding="utf-8",+ )+ self._seed_hand_rolled_relay()++ self.harness = AuthSetupScenarioHarness()+ self.codex_cfg = SimpleNamespace(+ auth_mode="api_key",+ api_key="sk-relay",+ base_url=None,+ oauth_relay_marker=None,+ )+ self.harness.controller.config.agents.codex = self.codex_cfg+ self.harness.controller.config.save = lambda: None++ def _api_module(self):+ from vibe import api as vibe_api++ return vibe_api++ def _reload_settings(self, api) -> None:+ with patch.object(api, "load_config", lambda: self.harness.controller.config):+ self._settings_state = api.get_codex_auth()++ def _save_api_key(self, api, base_url: str) -> dict:+ with (+ patch.object(api, "load_config", lambda: self.harness.controller.config),+ patch.object(api, "restart_backend", lambda name, **kwargs: {"ok": True}),+ ):+ return api.save_codex_auth(+ {+ "auth_mode": "api_key",+ "api_key": "sk-relay-2",+ "base_url": base_url,+ }+ )++ async def _run_round_trip(self, runner, api) -> None:+ # Step 1 — OAuth transition: the web flow's success hook runs the+ # real persistence path (relay identity capture → pointer clear /+ # managed-section drop → V2Config marker write), exactly as after+ # a Settings "Sign in" completes.+ await runner.run(+ ScenarioStep(+ "oauth_transition",+ lambda h: h.service._invoke_post_web_success_hook("codex"),+ ),+ )++ toml = (self.home / ".codex" / "config.toml").read_text(encoding="utf-8")+ top_level_pointer = [+ line for line in toml.splitlines() if line.startswith("model_provider")+ ]+ self.assertEqual(top_level_pointer, [])+ self.assertEqual(self.codex_cfg.auth_mode, "oauth")+ self.assertEqual(+ self.codex_cfg.oauth_relay_marker,+ {"provider_id": self._expected_provider_id, "base_url": "https://relay.example/v1"},+ )++ # Step 2 — Settings reload: the Settings page refetches auth+ # state to pre-populate the form (marker-backed while the disk+ # chain is empty).+ await runner.run(+ ScenarioStep(+ "settings_reload",+ lambda h: self._reload_settings(api),+ )+ )+ state = self._settings_state+ self.assertTrue(state["ok"])+ self.assertEqual(state["base_url"], "https://relay.example/v1")++ # Step 3 — API-key save the way the React form sends it: the+ # Base URL input carries the reloaded value, so the payload+ # includes it explicitly (null here would mean "clear").+ await runner.run(+ ScenarioStep(+ "api_key_save",+ lambda h: self._save_api_key(api, state["base_url"]),+ )+ )++ # Step 4 — launch config: the next ``codex app-server`` process+ # reads these files. The captured provider identity is restored:+ # the hand-rolled section keeps its own settings and the pointer;+ # the managed shape rebuilds the managed provider. Either way+ # the relay URL survives, and the one-shot marker is consumed.+ toml = (self.home / ".codex" / "config.toml").read_text(encoding="utf-8")+ auth = json.loads((self.home / ".codex" / "auth.json").read_text(encoding="utf-8"))+ self.assertEqual(auth["OPENAI_API_KEY"], "sk-relay-2")+ self.assertEqual(auth["auth_mode"], "apikey")+ if self._expected_provider_id == "openai-managed":+ self.assertIn('model_provider = "openai-managed"', toml)+ self.assertIn('base_url = "https://relay.example/v1"', toml)+ self.assertIn("supports_websockets = false", toml)+ else:+ pointer = [line for line in toml.splitlines() if line.startswith("model_provider")]+ self.assertEqual(pointer, ['model_provider = "OpenAI"'])+ self.assertIn('base_url = "https://relay.example/v1"', toml)+ # The user's provider settings survive the round trip.+ self.assertIn('wire_api = "responses"', toml)+ self.assertNotIn("[model_providers.openai-managed]", toml)+ self.assertIsNone(self.codex_cfg.oauth_relay_marker)++ ScenarioExpect.step_history(+ runner, ["oauth_transition", "settings_reload", "api_key_save"]+ )++ _expected_provider_id = "OpenAI"++ async def test_codex_oauth_api_key_relay_round_trip_scenario(self) -> None:+ runner = ScenarioRunner(self.harness)+ api = self._api_module()+ await self._run_round_trip(runner, api)++ async def test_codex_oauth_api_key_round_trip_managed_provider_shape(self) -> None:+ """Same loop starting from the Settings-created managed relay —+ the shape whose on-disk evidence the OAuth cleanup deletes."""+ self._seed_managed_relay()+ self._expected_provider_id = "openai-managed"+ self.codex_cfg.base_url = "https://relay.example/v1"+ runner = ScenarioRunner(self.harness)+ api = self._api_module()+ await self._run_round_trip(runner, api)++if __name__ == "__main__":unittest.main()diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 78a62e2d0..e65e32b54 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -1089,6 +1089,29 @@ def test_full_config_serializers_cover_every_config_field(monkeypatch, tmp_path)_assert_complete("V2Config.save", json.loads(paths.get_config_path().read_text(encoding="utf-8")))+def test_save_config_strips_codex_relay_marker_from_generic_patch(monkeypatch, tmp_path):+ """The relay marker is auth-owned state like ``api_key``: a generic+ Settings save that round-trips a stale full-config snapshot (loaded+ before an OAuth transition captured the marker) must not null the+ fresh marker."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ original = api.save_config(_full_config_payload())+ original.agents.codex.oauth_relay_marker = {+ "provider_id": "OpenAI",+ "base_url": "https://relay.example/v1",+ }+ original.save()++ # Stale snapshot still carrying a null marker (the pre-transition view).+ updated = api.save_config({"agents": {"codex": {"oauth_relay_marker": None}}})++ assert updated.agents.codex.oauth_relay_marker == {+ "provider_id": "OpenAI",+ "base_url": "https://relay.example/v1",+ }++def test_non_owner_config_keeps_asr_and_pairing_without_host_secrets(tmp_path, monkeypatch):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = V2Config.from_payload(_full_config_payload())diff --git a/tests/test_codex_api_auth.py b/tests/test_codex_api_auth.pyindex fad89e1fe..60e6313dc 100644--- a/tests/test_codex_api_auth.py+++ b/tests/test_codex_api_auth.py@@ -115,6 +115,240 @@ def test_save_codex_auth_falls_back_to_v2config_when_disk_empty(assert auth["OPENAI_API_KEY"] == "sk-from-cache"+def test_save_codex_auth_rescues_disk_base_url_when_cache_empty(+ monkeypatch, tmp_path: Path+) -> None:+ """Auth-mode round-trip regression. The oauth pass clears the+ managed relay pointer, and installs that configured their relay+ directly in ``config.toml`` never carry a ``base_url`` in V2Config.+ A later api_key save without ``base_url`` in the payload must keep+ using the disk relay URL — dropping it sends the relay key to+ ``api.openai.com`` and every turn 401s until the user repairs+ ``config.toml`` by hand. Disk must win over an empty cache.++ The orphaned variant (OAuth flow cleared the ``model_provider``+ pointer too, so the relay section is unpointed) is recovered by the+ same read path — see the sibling tests in+ ``test_settings_disk_fallback.py``."""+ 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")+ (codex_home / "config.toml").write_text(+ 'model_provider = "OpenAI"\n'+ "[model_providers.OpenAI]\n"+ 'name = "OpenAI"\n'+ 'base_url = "https://relay.example/v1"\n',+ encoding="utf-8",+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key", api_key="sk-any", base_url=None+ )+ fake_agents = types.SimpleNamespace(codex=fake_codex)+ fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": True})++ # No base_url in the payload: the disk relay URL must survive.+ payload = {"auth_mode": "api_key", "api_key": "sk-relay"}+ result = api.save_codex_auth(payload)+ assert result.get("ok") is True++ toml = (codex_home / "config.toml").read_text(encoding="utf-8")+ assert 'base_url = "https://relay.example/v1"' in toml+ # The rescued value is also mirrored into the V2Config cache so the+ # next save (and the Settings form) starts from it.+ assert fake_codex.base_url == "https://relay.example/v1"+++def test_save_codex_auth_prefers_disk_base_url_over_stale_cache(+ monkeypatch, tmp_path: Path+) -> None:+ """A relay URL hand-edited in ``config.toml`` outranks a stale+ V2Config cache, mirroring the api-key disk-first contract."""+ 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")+ (codex_home / "config.toml").write_text(+ 'model_provider = "OpenAI"\n'+ "[model_providers.OpenAI]\n"+ 'name = "OpenAI"\n'+ 'base_url = "https://fresh.example/v1"\n',+ encoding="utf-8",+ )++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key", api_key="sk-any", base_url="https://stale.example/v1"+ )+ fake_agents = types.SimpleNamespace(codex=fake_codex)+ fake_config = types.SimpleNamespace(agents=fake_agents, 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")+ assert 'base_url = "https://fresh.example/v1"' in toml+ assert fake_codex.base_url == "https://fresh.example/v1"+++def test_save_codex_auth_restores_relay_from_oauth_marker(+ monkeypatch, tmp_path: Path+) -> None:+ """Post-OAuth recovery via the explicit transition marker. The OAuth+ transition cleared the provider pointer and dropped the managed+ section (disk chain empty) but recorded the relay identity in+ ``oauth_relay_marker``. An api_key save omitting ``base_url`` must+ restore the relay from the marker — this is the exact Settings+ round-trip that used to 401 — and consume (clear) the 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({"tokens": {"id_token": "x"}, "auth_mode": "chatgpt"}),+ encoding="utf-8",+ )+ # Pointer cleared by the OAuth pass; the relay section survives+ # orphaned so the restore can re-point at it. The file credential+ # store is pinned by the API-key save that configured the relay and+ # survives the OAuth transition — without it the live mode is+ # unknowable and the marker is gated off.+ (codex_home / "config.toml").write_text(+ '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="oauth",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://relay.example/v1"},+ )+ fake_agents = types.SimpleNamespace(codex=fake_codex)+ fake_config = types.SimpleNamespace(agents=fake_agents, 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++ # The captured user-owned provider is restored (pointer + its own+ # settings survive); the one-shot recovery record is spent.+ 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 = "OpenAI"']+ assert 'base_url = "https://relay.example/v1"' in toml+ assert fake_codex.oauth_relay_marker is None+ assert fake_codex.base_url == "https://relay.example/v1"+++def test_save_codex_auth_ignores_marker_after_external_api_key_switch(+ monkeypatch, tmp_path: Path+) -> None:+ """``codex login --with-api-key`` outside Avibe puts a live API key+ on disk; from that moment the live disk configuration is+ authoritative and a leftover OAuth marker must not reroute the+ freshly logged-in key to the relay it remembers."""+ 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")++ 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_agents = types.SimpleNamespace(codex=fake_codex)+ fake_config = types.SimpleNamespace(agents=fake_agents, 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://relay.example/v1" not in toml+++def test_get_codex_auth_uses_oauth_marker_when_disk_chain_empty(+ monkeypatch, tmp_path: Path+) -> None:+ """The Settings form pre-populates from ``get_codex_auth``; after an+ OAuth transition the disk chain is empty, so the explicit marker is+ what keeps the Base URL field (and therefore the next explicit save+ payload) carrying the 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("{}", 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-managed", "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)++ state = api.get_codex_auth()+ assert state["base_url"] == "https://relay.example/v1"++ # No marker → dormant sections and stale caches surface nothing.+ fake_codex.oauth_relay_marker = None+ monkeypatch.setattr(api, "load_config", lambda: fake_config)+ state = api.get_codex_auth()+ assert state["base_url"] is None+++def test_get_codex_auth_ignores_stale_cache_without_marker(+ monkeypatch, tmp_path: Path+) -> None:+ """A plain cached ``base_url`` is a preference, not a recovery+ record: when the disk no longer carries the relay the cache must not+ resurrect it. Only the explicit OAuth-transition marker recovers."""+ 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")+ (codex_home / "config.toml").write_text('model = "gpt-5.4"\n', encoding="utf-8")++ fake_codex = types.SimpleNamespace(+ auth_mode="oauth",+ api_key=None,+ base_url="https://removed.example/v1",+ 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)++ state = api.get_codex_auth()+ assert state["base_url"] is None++def test_save_codex_auth_blocks_recovery_before_external_mutation(monkeypatch) -> None:fake_config = types.SimpleNamespace(load_warnings=("recovery required",), language="zh")monkeypatch.setattr(api, "load_config", lambda: fake_config)@@ -151,3 +385,76 @@ def test_remove_codex_api_key_blocks_recovery_before_external_mutation(monkeypat"message": "Config was loaded with recovery warnings; repair the backed-up config before changing backend credentials",}assert applied == []+++def test_remove_backend_api_key_clears_codex_relay_marker(+ monkeypatch, tmp_path: Path+) -> None:+ """Remove key is an explicit OAuth choice: the relay marker must go+ with the key, or the next Settings refresh repopulates the abandoned+ relay and a freshly entered official key gets rerouted to it."""+ 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")++ fake_codex = types.SimpleNamespace(+ auth_mode="api_key",+ api_key="sk-official",+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},+ )+ fake_agents = types.SimpleNamespace(codex=fake_codex)+ fake_config = types.SimpleNamespace(agents=fake_agents, save=lambda: None)+ 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 fake_codex.api_key is None+ assert fake_codex.oauth_relay_marker is None+++def test_marker_ignored_when_credentials_may_live_in_keyring(+ monkeypatch, tmp_path: Path+) -> None:+ """With ``cli_auth_credentials_store`` at ``auto``/``keyring`` an+ external official-key switch leaves no ``OPENAI_API_KEY`` in+ ``auth.json`` (it lives in the OS keychain), so the file-only+ ``has_api_key`` gate can't see it. The marker must not be consumed+ while the store hides the live mode — otherwise Settings+ pre-populates the abandoned relay and sends a pasted official key+ to it."""+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / ".codex"))+ codex_home = tmp_path / ".codex"+ codex_home.mkdir(parents=True, exist_ok=True)+ # Keyring store: no file key, no tokens — live mode unknowable.+ (codex_home / "auth.json").write_text("{}", encoding="utf-8")+ (codex_home / "config.toml").write_text(+ 'cli_auth_credentials_store = "auto"\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 tomldiff --git a/tests/test_codex_config.py b/tests/test_codex_config.pyindex c029bed8f..1431577c9 100644--- a/tests/test_codex_config.py+++ b/tests/test_codex_config.py@@ -489,3 +489,70 @@ def test_apply_oauth_leaves_user_owned_pointer_when_no_base_url(tmp_path: Path)parsed = tomllib.loads((codex_home / "config.toml").read_text(encoding="utf-8"))assert parsed["model_provider"] == "CustomLabel"assert result["notices"] == []+++def test_read_codex_relay_marker_requires_provider_identity() -> None:+ """A truncated/corrupted marker (URL without provider identity) is+ not a valid recovery record — it degrades to "no marker" instead of+ steering credentials at an unverifiable URL."""+ from vibe.codex_config import read_codex_relay_marker++ assert read_codex_relay_marker(None) is None+ assert read_codex_relay_marker("https://relay.example/v1") is None+ assert read_codex_relay_marker({"base_url": "https://relay.example/v1"}) is None+ assert read_codex_relay_marker({"base_url": "https://relay.example/v1", "provider_id": ""}) is None+ assert read_codex_relay_marker({"base_url": "https://relay.example/v1", "provider_id": 7}) is None+ assert read_codex_relay_marker({"provider_id": "OpenAI"}) is None+ assert read_codex_relay_marker(+ {"base_url": "https://relay.example/v1", "provider_id": "OpenAI"}+ ) == {"base_url": "https://relay.example/v1", "provider_id": "OpenAI"}+++def test_apply_api_key_restores_captured_user_provider(tmp_path: Path) -> None:+ """The OAuth-transition round trip restores the captured user-owned+ provider (pointer + its own wire_api), not a rebuilt managed one."""+ codex_config.apply_codex_auth(+ auth_mode="api_key",+ api_key="sk-relay",+ base_url=None,+ home=tmp_path,+ )+ # Seed the post-OAuth shape: pointer cleared, relay orphaned.+ config_path = tmp_path / ".codex" / "config.toml"+ config_path.write_text(+ "[model_providers.OpenAI]\n"+ 'name = "OpenAI"\n'+ 'base_url = "https://relay.example/v1"\n'+ 'wire_api = "responses"\n',+ encoding="utf-8",+ )+ codex_config.apply_codex_auth(+ auth_mode="api_key",+ api_key="sk-relay-2",+ base_url="https://relay.example/v1",+ restore_provider_id="OpenAI",+ home=tmp_path,+ )+ toml = config_path.read_text(encoding="utf-8")+ pointer = [line for line in toml.splitlines() if line.startswith("model_provider")]+ assert pointer == ['model_provider = "OpenAI"']+ assert 'wire_api = "responses"' in toml+ assert "openai-managed" not in toml+ state = codex_config.read_codex_auth_state(home=tmp_path)+ assert state["base_url"] == "https://relay.example/v1"+++def test_apply_api_key_restore_falls_back_when_provider_gone(tmp_path: Path) -> None:+ """Restore is only honored while the captured section still exists+ with the same URL; otherwise the managed rebuild applies."""+ codex_config.apply_codex_auth(+ auth_mode="api_key",+ api_key="sk-relay",+ base_url="https://relay.example/v1",+ restore_provider_id="OpenAI",+ home=tmp_path,+ )+ config_path = tmp_path / ".codex" / "config.toml"+ toml = config_path.read_text(encoding="utf-8")+ assert 'model_provider = "openai-managed"' in toml+ assert 'base_url = "https://relay.example/v1"' in tomldiff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 15db57e15..7dbf8b71e 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -2197,6 +2197,32 @@ def test_config_reload_recovers_invalid_codex_agent_with_disabled_default(monkeyassert config_path.read_text(encoding="utf-8") == original+def test_config_load_degrades_codex_relay_marker_shapes(monkeypatch, tmp_path):+ """Persisted-shape rule for the new ``oauth_relay_marker`` field:+ a config written before the field existed loads with ``None``+ (released-shape compatibility), a well-formed marker round-trips,+ and a corrupt value is filtered out at consumption+ (``read_codex_relay_marker``) rather than breaking startup."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)+ payload["agents"]["codex"].pop("oauth_relay_marker", None)+ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps(payload), encoding="utf-8")++ legacy = V2Config.load(config_path=config_path)+ assert legacy.agents.codex.oauth_relay_marker is None++ legacy.agents.codex.oauth_relay_marker = {"provider_id": "OpenAI", "base_url": "https://relay.example/v1"}+ legacy.save()+ # ``save()`` persists to the canonical AVIBE_HOME config; reload from+ # the same place to prove the marker round-trips through JSON.+ reloaded = V2Config.load()+ assert reloaded.agents.codex.oauth_relay_marker == {+ "provider_id": "OpenAI",+ "base_url": "https://relay.example/v1",+ }++def test_config_reload_recovers_invalid_agents_with_canonical_defaults(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.pyindex d3446a996..944842d57 100644--- a/tests/test_settings_disk_fallback.py+++ b/tests/test_settings_disk_fallback.py@@ -89,6 +89,33 @@ def test_codex_no_base_url_when_neither_section_has_one(tmp_path: Path) -> None:assert state["base_url"] is None+def test_codex_ignores_dormant_relay_section_without_oauth_capture_marker(+ tmp_path: Path,+) -> None:+ """A provider section the user never activated is not proof of a+ prior relay. After the OAuth flows clear ``model_provider``, any+ surviving section is unpointed; treating the unique one as "the+ relay" would silently reroute a freshly saved API key to an+ unrelated endpoint. Disk reads must stay chain-only (active →+ managed → legacy); recovery lives in the V2Config capture written at+ the OAuth transition, merged in by ``get_codex_auth``."""+ 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]",+ 'name = "OpenAI"',+ 'base_url = "https://never-activated.example/v1"',+ ]+ ),+ 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()diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex a95ea32f0..749f20c62 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -338,6 +338,7 @@ def test_codex_oauth_success_clears_api_key_state(auth_mode="api_key",api_key="sk-old",base_url="https://relay.example/v1",+ oauth_relay_marker=None,)service.controller.config = SimpleNamespace(language="en",@@ -351,11 +352,69 @@ def test_codex_oauth_success_clears_api_key_state(assert auth["auth_mode"] == "chatgpt"assert auth["tokens"] == {"id_token": "abc"}assert "OPENAI_API_KEY" not in auth+ # The provider pointer is cleared for OAuth runtime…+ toml = (codex_home / "config.toml").read_text(encoding="utf-8")+ assert not [line for line in toml.splitlines() if line.startswith("model_provider")]+ # …but the relay identity is captured into the explicit+ # ``oauth_relay_marker`` so the Settings form and the next API-key+ # save can restore it instead of silently rerouting the key to+ # api.openai.com.assert codex_cfg.auth_mode == "oauth"assert codex_cfg.api_key is Noneassert codex_cfg.base_url is None+ assert codex_cfg.oauth_relay_marker == {+ "provider_id": "OpenAI",+ "base_url": "https://relay.example/v1",+ }assert saves == ["saved"]+ # A repeated OAuth transition captures nothing (the pointer is+ # already gone) and must RETAIN the marker rather than erase it —+ # erasing would lose the relay for the eventual switch-back.+ _run(service._invoke_post_web_success_hook("codex"))+ assert codex_cfg.oauth_relay_marker == {+ "provider_id": "OpenAI",+ "base_url": "https://relay.example/v1",+ }+++def test_codex_oauth_after_official_key_transition_clears_stale_marker(+ service: AgentAuthService,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """Official-key transition: the user ran ``codex login+ --with-api-key`` against the default endpoint (active key, no relay)+ and then signed in via OAuth. The pre-OAuth capture observes the+ key-without-relay state, so the stale relay marker must be CLEARED —+ retaining it would resurface the abandoned relay after OAuth removes+ the key and reroute a future API-key save to it."""+ codex_home = tmp_path / ".codex"+ codex_home.mkdir()+ monkeypatch.setenv("CODEX_HOME", str(codex_home))+ # External official-key shape: API key, no relay anywhere.+ (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")++ codex_cfg = SimpleNamespace(+ auth_mode="api_key",+ api_key=None,+ base_url=None,+ oauth_relay_marker={"provider_id": "OpenAI", "base_url": "https://stale.example/v1"},+ )+ service.controller.config = SimpleNamespace(+ language="en",+ agents=SimpleNamespace(codex=codex_cfg),+ save=lambda: None,+ )++ _run(service._invoke_post_web_success_hook("codex"))++ assert codex_cfg.oauth_relay_marker is None+def test_post_web_success_hook_swallows_exceptions(service: AgentAuthService,diff --git a/vibe/api.py b/vibe/api.pyindex 50804e6f8..a7b317e4f 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -713,7 +713,7 @@ def _deep_merge_dicts(base: dict, patch: dict) -> dict:return merged-_AGENT_AUTH_FIELDS = ("auth_mode", "api_key", "base_url")+_AGENT_AUTH_FIELDS = ("auth_mode", "api_key", "base_url", "oauth_relay_marker")def _strip_agent_auth_fields(payload: dict) -> dict:@@ -9740,6 +9740,12 @@ def remove_backend_api_key(backend: str) -> dict:# OAuth), the OAuth credentials would still be routed# to the api-key-only relay and silently 401.target.base_url = None+ # Remove key is an explicit OAuth choice — the relay+ # marker goes with it, or a later refresh would+ # repopulate the abandoned relay and reroute a freshly+ # entered official key to it (Codex-only field).+ if backend == "codex":+ target.oauth_relay_marker = None# User explicitly chose OAuth by clicking Remove key —# mark the flag so legacy env-var fallback in# ``build_claude_subprocess_env`` is bypassed and the@@ -9855,8 +9861,35 @@ def get_codex_auth() -> dict:config = load_config()cfg = getattr(getattr(config, "agents", None), "codex", None)configured_mode = getattr(cfg, "auth_mode", None)+ raw_relay_marker = getattr(cfg, "oauth_relay_marker", None)except Exception:configured_mode = None+ raw_relay_marker = None+ from vibe.codex_config import read_codex_relay_marker++ # Disk-first with the explicit OAuth-transition marker as fallback.+ # The disk chain (active provider → managed → legacy) is what a live+ # Codex launch would use. The marker (captured by+ # ``AgentAuthService._persist_backend_auth_mode`` before the OAuth+ # 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+ # 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.+ relay_marker = None+ if not disk_state.get("has_api_key") and disk_state.get("file_store_active"):+ 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"]+ else:+ effective_base_url = disk_state.get("base_url")# Disk wins when it carries unambiguous evidence of API-key auth: an# ``OPENAI_API_KEY`` in ``~/.codex/auth.json`` is a concrete artefact@@ -9894,7 +9927,7 @@ def get_codex_auth() -> dict:"has_api_key": has_api_key_live,"api_key_length": int(disk_state.get("api_key_length") or 0),"api_key_masked": _mask_api_key(disk_state.get("api_key_raw")),- "base_url": disk_state.get("base_url"),+ "base_url": effective_base_url,"has_chatgpt_tokens": has_chatgpt_live,"chatgpt_account": disk_state.get("chatgpt_account"),# Forward the live Codex credentials-store status so the UI can@@ -9987,24 +10020,78 @@ def save_codex_auth(payload: dict) -> dict:return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}# Resolve the effective base_url: explicit payload wins, otherwise- # preserve whatever V2Config currently has.- if base_url_present:- effective_base_url = base_url_change- else:+ # prefer the value Codex actually reads on disk, falling back to the+ # V2Config cache. Disk-first mirrors the api-key resolution above:+ # the live ``config.toml`` is what Codex reads at launch, so a relay+ # ``base_url`` hand-edited there (or left behind by an oauth pass+ # that cleared our managed section) must outrank a possibly-stale+ # cache. Trusting the cache alone either reverts hand edits or, when+ # the cache is empty, drops the relay entirely — sending a relay API+ # key to ``api.openai.com`` and surfacing as a confusing 401 after+ # an auth-mode switch.+ # Explicit OAuth-transition marker: the relay identity recorded when+ # 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+ # ``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.+ marker = None+ try:+ from vibe.codex_config import read_codex_auth_state, read_codex_relay_marker++ codex_disk_state = read_codex_auth_state()with CONFIG_LOCK:try:- existing_cfg = load_config()- stored_codex = getattr(getattr(existing_cfg, "agents", None), "codex", None)- effective_base_url = getattr(stored_codex, "base_url", None) or None+ marker_cfg = load_config()+ marker_codex = getattr(getattr(marker_cfg, "agents", None), "codex", None)+ raw_marker = getattr(marker_codex, "oauth_relay_marker", None)except Exception:- effective_base_url = None+ raw_marker = None+ if not codex_disk_state.get("has_api_key") and codex_disk_state.get("file_store_active"):+ marker = read_codex_relay_marker(raw_marker)+ except Exception:+ logger.debug("Codex relay marker read failed", exc_info=True)+ marker = None++ if base_url_present:+ effective_base_url = base_url_change+ else:+ effective_base_url = None+ try:+ from vibe.codex_config import read_codex_auth_state++ disk_base_url = read_codex_auth_state().get("base_url")+ if isinstance(disk_base_url, str) and disk_base_url.strip():+ effective_base_url = disk_base_url.strip()+ except Exception:+ logger.debug("Codex disk base_url read failed", exc_info=True)+ 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.+ restore_provider_id: Optional[str] = None+ if marker is not None and effective_base_url == marker["base_url"]:+ restore_provider_id = marker["provider_id"]from vibe.codex_config import apply_codex_authnotices: list = []try:result = apply_codex_auth(- auth_mode=auth_mode, api_key=api_key, base_url=effective_base_url+ auth_mode=auth_mode,+ api_key=api_key,+ base_url=effective_base_url,+ restore_provider_id=restore_provider_id,)if isinstance(result, dict):raw_notices = result.get("notices")@@ -10024,6 +10111,12 @@ 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.+ if auth_mode == "api_key":+ config.agents.codex.oauth_relay_marker = Noneconfig.save()restart_result = restart_backend(@@ -11584,7 +11677,7 @@ async def save_opencode_provider_auth_async(provider_id: str, payload: dict) ->``base_url`` override is also persisted into ``opencode.json``.``base_url`` field semantics in the payload:- * absent → leave the stored value untouched+ * absent → resolve from disk first, then the stored value* empty / whitespace → clear the stored value* non-empty string → upsert (must start with http:// or https://)"""diff --git a/vibe/codex_config.py b/vibe/codex_config.pyindex af4fa11d6..1e4b2eefd 100644--- a/vibe/codex_config.py+++ b/vibe/codex_config.py@@ -275,6 +275,7 @@ def apply_codex_auth(auth_mode: str,api_key: Optional[str],base_url: Optional[str],+ restore_provider_id: Optional[str] = None,home: Path | None = None,) -> Dict[str, Any]:"""Persist the requested auth mode into Codex's on-disk config files.@@ -283,14 +284,19 @@ def apply_codex_auth(optionally set ``[model_providers.openai-managed].base_url`` if anon-default URL was supplied, and pin top-level ``model_provider``to the managed entry so Codex actually uses the keyed provider.+ When ``restore_provider_id`` names a still-existing user-owned+ provider section carrying the same ``base_url``, the pointer is+ restored to that section instead — the OAuth-transition round+ trip then preserves the user's own ``wire_api`` / provider+ settings rather than rebuilding a managed provider.- ``oauth`` mode: drop ``OPENAI_API_KEY`` from ``auth.json``, leave any``tokens`` blob in place, and clear our managed ``base_url`` so thenext launch goes back to OpenAI's default endpoint.Returns ``{"notices": [{code, ...}, ...]}`` — non-fatal warnings thecaller may want to surface in the UI (e.g. "we cleared a custom- relay pointer that won't accept OAuth tokens"). An empty list means- the save was a no-op transformation.+ relay pointer that won't accept OAuth tokens"). An empty list means+ the save was a no-op transformation."""if auth_mode not in {"oauth", "api_key"}:raise ValueError(f"Unsupported codex auth_mode: {auth_mode!r}")@@ -304,6 +310,31 @@ def apply_codex_auth(if not isinstance(providers, dict):providers = {}toml_data["model_providers"] = providers++ restored_user_provider = False+ if (+ auth_mode == "api_key"+ and isinstance(restore_provider_id, str)+ and restore_provider_id.strip()+ and restore_provider_id not in {MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS}+ ):+ section = providers.get(restore_provider_id)+ section_url = section.get("base_url") if isinstance(section, dict) else None+ if (+ isinstance(section, dict)+ and isinstance(section_url, str)+ and base_url+ and section_url.strip() == base_url.strip()+ ):+ # The captured user-owned relay section survived the OAuth+ # window and still points at the same relay: restore the+ # pointer instead of rebuilding a managed provider, so the+ # user's own provider settings (wire_api etc.) survive the+ # auth-mode round trip. Managed/legacy ids never take this+ # path — they are ours to rewrite.+ toml_data["model_provider"] = restore_provider_id+ restored_user_provider = True+managed = providers.setdefault(MANAGED_PROVIDER_ID, {})if not isinstance(managed, dict):managed = {}@@ -332,10 +363,14 @@ def apply_codex_auth(# managed names. If the user has aimed it at a hand-rolled# provider (e.g. their ``[model_providers.OpenAI]`` relay# section), keep their pointer — overriding it would silently- # bypass their custom base_url + wire_api config.+ # bypass their custom base_url + wire_api config. A restored+ # user-owned provider (``restored_user_provider``) already has+ # the pointer set above and must not be steered away.current_mp = toml_data.get("model_provider")managed_known = {MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS, ""}- if not isinstance(current_mp, str) or current_mp in managed_known:+ if not restored_user_provider and (+ not isinstance(current_mp, str) or current_mp in managed_known+ ):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@@ -343,39 +378,47 @@ def apply_codex_auth(# 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")- # Match the wire_api the modern Codex CLI uses internally for- # api_key requests. Without explicitly setting this, the CLI- # may fall back to the legacy ``chat`` shape — fine against- # ``api.openai.com`` (which serves both endpoints) but the- # common custom relays (e.g. ai-relay.chainbot.io) only speak- # the Responses API and return 404 / wire-shape errors.- managed.setdefault("wire_api", "responses")- # Ensure the Bearer header is sent when the request travels- # through the user's relay. The default is reasonable but- # being explicit avoids a class of failures where Codex omits- # auth on custom providers (silent 401 on the relay).- managed.setdefault("requires_openai_auth", True)- if base_url:- managed["base_url"] = base_url- # Custom relays almost never speak Codex's bespoke responses-- # over-WebSocket protocol — they reverse-proxy HTTPS to OpenAI- # but don't accept the WSS upgrade Codex expects on- # ``/responses``. Codex 0.130+ gates that transport on this- # field (``codex-rs/core/src/client.rs::responses_websocket_enabled``);- # pinning it to false routes turns through the HTTP responses- # path, which honors our ``base_url``. Leaving it absent lets- # newer Codex versions dispatch WSS via the built-in OpenAI- # provider's default (``wss://api.openai.com/v1/responses``),- # silently bypassing the user's relay and producing 401s on- # whatever account-bound key the relay handed out.- managed["supports_websockets"] = False+ if restored_user_provider:+ # The user's own section carries the provider settings; drop+ # any stale managed section we wrote in an earlier api_key+ # era so only one candidate shape remains in the file.+ providers.pop(MANAGED_PROVIDER_ID, None)+ if not providers:+ toml_data.pop("model_providers", None)else:- managed.pop("base_url", None)- # No custom base_url → user is on the built-in OpenAI endpoint- # where WSS works the way Codex expects. Drop our override so- # Codex's own default-on behavior applies.- managed.pop("supports_websockets", None)+ managed.setdefault("name", "OpenAI")+ # Match the wire_api the modern Codex CLI uses internally for+ # api_key requests. Without explicitly setting this, the CLI+ # may fall back to the legacy ``chat`` shape — fine against+ # ``api.openai.com`` (which serves both endpoints) but the+ # common custom relays (e.g. ai-relay.chainbot.io) only speak+ # the Responses API and return 404 / wire-shape errors.+ managed.setdefault("wire_api", "responses")+ # Ensure the Bearer header is sent when the request travels+ # through the user's relay. The default is reasonable but+ # being explicit avoids a class of failures where Codex omits+ # auth on custom providers (silent 401 on the relay).+ managed.setdefault("requires_openai_auth", True)+ if base_url:+ managed["base_url"] = base_url+ # Custom relays almost never speak Codex's bespoke responses-+ # over-WebSocket protocol — they reverse-proxy HTTPS to OpenAI+ # but don't accept the WSS upgrade Codex expects on+ # ``/responses``. Codex 0.130+ gates that transport on this+ # field (``codex-rs/core/src/client.rs::responses_websocket_enabled``);+ # pinning it to false routes turns through the HTTP responses+ # path, which honors our ``base_url``. Leaving it absent lets+ # newer Codex versions dispatch WSS via the built-in OpenAI+ # provider's default (``wss://api.openai.com/v1/responses``),+ # silently bypassing the user's relay and producing 401s on+ # whatever account-bound key the relay handed out.+ managed["supports_websockets"] = False+ else:+ managed.pop("base_url", None)+ # No custom base_url → user is on the built-in OpenAI endpoint+ # where WSS works the way Codex expects. Drop our override so+ # Codex's own default-on behavior applies.+ managed.pop("supports_websockets", None)else: # oauthauth_data.pop("OPENAI_API_KEY", None)# Flip auth_mode back to chatgpt when OAuth tokens still exist@@ -441,6 +484,31 @@ def apply_codex_auth(return {"notices": notices}+def read_codex_relay_marker(marker: object) -> Optional[Dict[str, str]]:+ """Normalize a persisted ``oauth_relay_marker`` value for consumption.++ The marker is the explicit OAuth-transition record+ (``{"provider_id": str, "base_url": str}``) captured by+ ``AgentAuthService._persist_backend_auth_mode`` immediately before+ the OAuth cleanup clears the provider pointer / managed section.+ Because the marker *is* the provenance, it is consumed verbatim —+ no ambient-state inference. Shape validation: both fields must be+ non-empty strings (every legitimate capture with a relay URL also+ resolves a non-empty ``active_provider_id``), so a truncated or+ corrupted marker degrades to "no marker" — disabling recovery —+ rather than steering credentials at an unverifiable URL.+ """+ if not isinstance(marker, dict):+ return None+ base_url = marker.get("base_url")+ provider_id = marker.get("provider_id")+ if not isinstance(base_url, str) or not base_url.strip():+ return None+ if not isinstance(provider_id, str) or not provider_id.strip():+ return None+ return {"base_url": base_url.strip(), "provider_id": provider_id.strip()}++def read_codex_api_key(home: Path | None = None) -> Optional[str]:"""Return the API key currently stored in ``auth.json``, if any.@@ -542,6 +610,7 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:providers = toml_data.get("model_providers")base_url: Optional[str] = Nonewire_api: Optional[str] = None+ active_provider_id: Optional[str] = Noneif isinstance(providers, dict):# Codex's runtime selects the provider named by top-level# ``model_provider``. When that's a user-defined section (e.g.@@ -554,8 +623,10 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:active_section: Optional[dict] = Noneif isinstance(active_provider, str) and isinstance(providers.get(active_provider), dict):active_section = providers[active_provider]+ active_provider_id = active_providerelif isinstance(providers.get(MANAGED_PROVIDER_ID), dict):active_section = providers[MANAGED_PROVIDER_ID]+ active_provider_id = MANAGED_PROVIDER_IDelse:# Legacy fallback: older releases wrote our managed shape# under ``[model_providers.openai]``. New Codex rejects that@@ -565,6 +636,7 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:legacy_section = providers.get(legacy_id)if isinstance(legacy_section, dict):active_section = legacy_section+ active_provider_id = legacy_idbreakif isinstance(active_section, dict):raw = active_section.get("base_url")@@ -574,6 +646,17 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:if isinstance(raw_wire_api, str) and raw_wire_api.strip():wire_api = raw_wire_api.strip()+ # NOTE: no orphaned-section recovery here. After the OAuth flows+ # clear ``model_provider``, a surviving user relay section is+ # unpointed — but its mere presence is not proof it was the+ # active relay (a never-used dormant provider would be picked up+ # and silently reroute a freshly saved API key to an unintended+ # endpoint). Recovery is driven exclusively by the explicit+ # ``oauth_relay_marker`` captured at the OAuth transition+ # (``AgentAuthService._persist_backend_auth_mode`` → V2Config+ # ``agents.codex.oauth_relay_marker``); the Settings read merges+ # that in (``vibe.api.get_codex_auth``).+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);@@ -602,6 +685,12 @@ def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:"api_key_raw": api_key if isinstance(api_key, str) and api_key else None,"base_url": base_url,"wire_api": wire_api,+ # Provider id the chain above resolved to (``model_provider``+ # pointer, our managed id, or a legacy managed id). ``None`` when+ # no provider section matched. Consumed by the OAuth-transition+ # capture so the recovery marker records *which* section carried+ # the relay, not just its URL.+ "active_provider_id": active_provider_id,"has_chatgpt_tokens": has_chatgpt_tokens,# ``chatgpt_account``: best-effort identity from the OAuth JWT in# ``auth.json`` so the Settings page can show "Signed in as