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(auth): close Codex probe lifecycle boundaries
cyh9570e4776945
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 16c6f9166..f812ad19b 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -505,8 +505,8 @@ class AgentAuthService:cli_path = getattr(backend_cfg, "cli_path", None) or getattr(backend_cfg, "binary", None)return cli_path or backend- def _resolve_backend_probe_cwd(self, backend: str) -> str:- """Return the default runtime cwd for an isolated backend Agent probe."""+ def _resolve_backend_probe_cwd(self, backend: str, *, prepare: bool = False) -> str:+ """Resolve the configured runtime cwd without mutating it by default."""config = getattr(getattr(self, "controller", None), "config", None)candidates = (getattr(self._resolve_backend_config(backend), "cwd", None),@@ -516,6 +516,8 @@ class AgentAuthService:for raw in candidates:if isinstance(raw, str) and raw.strip():path = os.path.abspath(os.path.expanduser(raw.strip()))+ if not prepare:+ return pathtry:os.makedirs(path, exist_ok=True)return path@@ -2248,7 +2250,10 @@ class AgentAuthService:return {"ok": False, "error": "unsupported_backend"}binary = self._get_cli_binary(backend)- probe_cwd = self._resolve_backend_probe_cwd(backend)+ probe_cwd = self._resolve_backend_probe_cwd(+ backend,+ prepare=backend == "claude",+ )auth_mode = Noneif backend == "claude":backend_cfg = self._resolve_backend_config("claude")@@ -2452,9 +2457,13 @@ class AgentAuthService:on_diagnostic: Callable[[str], None] | None = None,) -> str:"""Reuse a matching direct runtime, or own a temporary direct runtime."""+ from config import pathsfrom config.v2_compat import CodexCompatConfigfrom config.v2_config import DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS- from modules.agents.codex import CodexConnectionProbeRuntimeMismatchError+ from modules.agents.codex import (+ CODEX_CONNECTION_PROBE_DIR,+ CodexConnectionProbeRuntimeMismatchError,+ )backend_cfg = self._resolve_backend_config("codex")runtime_config = CodexCompatConfig(@@ -2495,9 +2504,10 @@ class AgentAuthService:passprobe_agent = self._create_codex_probe_agent(runtime_config)+ isolated_cwd = str(paths.get_runtime_dir() / CODEX_CONNECTION_PROBE_DIR)try:return await probe_agent.probe_connection(- cwd,+ isolated_cwd,model=model,on_diagnostic=on_diagnostic,)diff --git a/modules/agents/codex/__init__.py b/modules/agents/codex/__init__.pyindex 7985e7c1f..c4fe30b57 100644--- a/modules/agents/codex/__init__.py+++ b/modules/agents/codex/__init__.py@@ -1,5 +1,13 @@"""Codex agent package — persistent app-server mode."""-from .agent import CodexAgent, CodexConnectionProbeRuntimeMismatchError+from .agent import (+ CODEX_CONNECTION_PROBE_DIR,+ CodexAgent,+ CodexConnectionProbeRuntimeMismatchError,+)-__all__ = ["CodexAgent", "CodexConnectionProbeRuntimeMismatchError"]+__all__ = [+ "CODEX_CONNECTION_PROBE_DIR",+ "CodexAgent",+ "CodexConnectionProbeRuntimeMismatchError",+]diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 6da074a83..b832e9741 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -202,12 +202,13 @@ class CodexAgent(BaseAgent):return lambda: self._transport_alive(transport)def can_reuse_direct_connection_probe(self, cwd: str) -> bool:- """Return whether a live transport is suitable for direct-auth testing."""+ """Return whether a cached transport can test direct credentials."""transport = self._transports.get(cwd)- return not (+ return bool(transport is not None- and getattr(transport, "runtime_fingerprint", "direct") != "direct"+ and getattr(transport, "runtime_fingerprint", "direct") == "direct"+ and os.path.isdir(cwd))async def probe_connection(@@ -226,20 +227,21 @@ class CodexAgent(BaseAgent):thread_id = ""closed_task: asyncio.Task[None] | None = Noneprobe_cwds = self._connection_probe_cwds- probe_cwds[cwd] = probe_cwds.get(cwd, 0) + 1+ owns_probe_cwd = Falsetry:- transport = self._transports.get(cwd)if (- transport is not None- and getattr(transport, "runtime_fingerprint", "direct") != "direct"+ getattr(self, "_registered_runtime", True)+ and not self.can_reuse_direct_connection_probe(cwd)):raise CodexConnectionProbeRuntimeMismatchError(- "The cached Codex transport does not use direct credentials"+ "No cached direct Codex transport is available for the probe")- if transport is None or not transport.is_initialized:- transport = await self._get_or_create_transport(cwd)- else:- self._touch_transport_activity(cwd)+ transport = await self._get_or_create_transport(+ cwd,+ allow_runtime_replacement=False,+ )+ probe_cwds[cwd] = probe_cwds.get(cwd, 0) + 1+ owns_probe_cwd = Truethread_response = await transport.send_request("thread/start",@@ -330,11 +332,12 @@ class CodexAgent(BaseAgent):if closed_task is not None:closed_task.cancel()await asyncio.gather(closed_task, return_exceptions=True)- remaining = probe_cwds.get(cwd, 0) - 1- if remaining > 0:- probe_cwds[cwd] = remaining- else:- probe_cwds.pop(cwd, None)+ if owns_probe_cwd:+ remaining = probe_cwds.get(cwd, 0) - 1+ if remaining > 0:+ probe_cwds[cwd] = remaining+ else:+ probe_cwds.pop(cwd, None)async def _record_model_hub_native_failure(self, context: Any, diagnostic: str) -> bool:router = getattr(self.controller, "model_hub_runtime", None)@@ -1503,6 +1506,8 @@ class CodexAgent(BaseAgent):self,cwd: str,launch: "ModelHubLaunch | None" = None,+ *,+ allow_runtime_replacement: bool = True,) -> CodexTransport:"""Return an initialized transport for the given working directory."""# Serialize creation per cwd@@ -1517,6 +1522,10 @@ class CodexAgent(BaseAgent):desired_fingerprint = launch.fingerprint if launch is not None else "direct"existing_fingerprint = getattr(existing, "runtime_fingerprint", "direct")runtime_changed = existing_fingerprint != desired_fingerprint+ if existing is not None and runtime_changed and not allow_runtime_replacement:+ raise CodexConnectionProbeRuntimeMismatchError(+ "The cached Codex transport does not use direct credentials"+ )if existing and existing.is_initialized:# Reuse only while the directory the app-server was spawned in# is still the SAME directory (#561): after a delete (+ possiblediff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.pyindex 38b5d6b9a..b596ea91d 100644--- a/modules/agents/codex/transport.py+++ b/modules/agents/codex/transport.py@@ -120,9 +120,15 @@ class CodexTransport:logger.info("Codex app-server initialized: %s", resp)await self.send_notification("initialized")self._initialized = True- except Exception:- logger.exception("Codex app-server handshake failed, cleaning up")- await self.stop()+ except BaseException as exc:+ if isinstance(exc, asyncio.CancelledError):+ logger.info("Codex app-server handshake cancelled, cleaning up")+ else:+ logger.exception("Codex app-server handshake failed, cleaning up")+ try:+ await self.stop()+ except Exception:+ logger.exception("Failed to clean up Codex app-server after handshake failure")raiseasync def stop(self) -> None:diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 025ca732f..1c5907ee0 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -400,6 +400,9 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):agent._connection_probes = {}agent._connection_probe_turns = {}agent._connection_probe_cwds = {}+ agent._get_or_create_transport = AsyncMock(+ return_value=agent._transports[str(home)]+ )controller.agent_service = SimpleNamespace(agents={"codex": agent})service = AgentAuthService(controller)@@ -426,6 +429,10 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):self.assertTrue(harness.test_result["ok"])self.assertEqual(harness.test_result["excerpt"], "codex-probe-ok")+ agent._get_or_create_transport.assert_awaited_once_with(+ str(home),+ allow_runtime_replacement=False,+ )self.assertEqual(requests,[diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex f7737f625..3d9b66671 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -275,8 +275,28 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):agent._connection_probes = {}agent._connection_probe_turns = {}agent._connection_probe_cwds = {}+ agent.can_reuse_direct_connection_probe = Mock(+ return_value=getattr(transport, "runtime_fingerprint", "direct") == "direct"+ )+ agent._get_or_create_transport = AsyncMock(return_value=transport)return agent+ def test_live_probe_requires_a_cached_direct_transport_and_existing_cwd(self):+ agent = object.__new__(CodexAgent)+ agent._transports = {}+ with tempfile.TemporaryDirectory() as cwd:+ self.assertFalse(agent.can_reuse_direct_connection_probe(cwd))++ direct = SimpleNamespace(runtime_fingerprint="direct")+ agent._transports[cwd] = direct+ self.assertTrue(agent.can_reuse_direct_connection_probe(cwd))++ direct.runtime_fingerprint = "hub:openai/gpt-5.4-mini"+ self.assertFalse(agent.can_reuse_direct_connection_probe(cwd))++ direct.runtime_fingerprint = "direct"+ self.assertFalse(agent.can_reuse_direct_connection_probe(cwd))+async def test_reuses_existing_transport_with_isolated_ephemeral_thread(self):requests = []cwd = "/tmp/user-project"@@ -313,9 +333,13 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):transport = _Transport()agent = self._agent(cwd, transport)diagnostics = []- agent._get_or_create_transport = AsyncMock(- side_effect=AssertionError("existing transport should be reused")- )++ async def acquire_transport(_cwd, *, allow_runtime_replacement):+ self.assertEqual(agent._connection_probe_cwds, {})+ self.assertFalse(allow_runtime_replacement)+ return transport++ agent._get_or_create_transport = AsyncMock(side_effect=acquire_transport)with patch.object(_MODULE.paths,@@ -329,7 +353,10 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):)self.assertEqual(result, "hello")- agent._get_or_create_transport.assert_not_awaited()+ agent._get_or_create_transport.assert_awaited_once_with(+ cwd,+ allow_runtime_replacement=False,+ )self.assertEqual(requests[0][0], "thread/start")self.assertEqual(requests[0][1],@@ -509,6 +536,23 @@ class CodexAgentConnectionProbeTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent._connection_probe_cwds, {})+ async def test_runtime_fingerprint_race_does_not_replace_model_hub_transport(self):+ cwd = "/tmp/user-project"+ transport = SimpleNamespace(is_initialized=True, runtime_fingerprint="direct")+ agent = self._agent(cwd, transport)+ agent._get_or_create_transport = AsyncMock(+ side_effect=CodexConnectionProbeRuntimeMismatchError("runtime changed")+ )++ with self.assertRaises(CodexConnectionProbeRuntimeMismatchError):+ await agent.probe_connection(cwd)++ agent._get_or_create_transport.assert_awaited_once_with(+ cwd,+ allow_runtime_replacement=False,+ )+ self.assertEqual(agent._connection_probe_cwds, {})+async def test_unregistered_probe_runtime_preserves_live_activation(self):cwd = "/tmp/user-project"activation = RuntimeActivationRegistry()@@ -3851,6 +3895,28 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):cached.stop.assert_not_awaited()ctor.assert_not_called()+ async def test_probe_validation_does_not_replace_incompatible_runtime(self):+ import tempfile++ agent = self._agent()+ with tempfile.TemporaryDirectory() as cwd:+ cached = SimpleNamespace(+ is_initialized=True,+ runtime_fingerprint="hub:openai/gpt-5.4-mini",+ stop=AsyncMock(),+ )+ agent._transports[cwd] = cached+ agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino++ with self.assertRaises(CodexConnectionProbeRuntimeMismatchError):+ await agent._get_or_create_transport(+ cwd,+ allow_runtime_replacement=False,+ )++ cached.stop.assert_not_awaited()+ self.assertIs(agent._transports[cwd], cached)+async def test_untracked_legacy_entry_reuses_without_inode(self):import tempfilediff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.pyindex e09d19373..0a7817c9b 100644--- a/tests/test_codex_transport.py+++ b/tests/test_codex_transport.py@@ -3,6 +3,7 @@ import sysimport unittestfrom pathlib import Pathfrom types import SimpleNamespace+from unittest.mock import AsyncMock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -10,6 +11,48 @@ from modules.agents.codex.transport import CodexTransport, STREAM_BUFFER_LIMITclass CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):+ async def test_cancelled_initialize_stops_unpublished_transport(self):+ initialize_started = asyncio.Event()++ class _Stream:+ async def readline(self):+ await asyncio.Event().wait()++ process = SimpleNamespace(+ pid=123,+ returncode=None,+ stdin=None,+ stdout=_Stream(),+ stderr=_Stream(),+ )+ transport = CodexTransport(binary="codex", cwd="/tmp")++ async def wait_for_initialize(_method, _params):+ initialize_started.set()+ await asyncio.Event().wait()++ async def stop_transport():+ transport._cleanup_tasks()++ transport.send_request = AsyncMock(side_effect=wait_for_initialize)+ transport.stop = AsyncMock(side_effect=stop_transport)++ with (+ patch(+ "modules.agents.codex.transport.asyncio.create_subprocess_exec",+ new=AsyncMock(return_value=process),+ ),+ patch("modules.agents.codex.transport.process_identity", return_value={}),+ patch("modules.agents.codex.transport.log_process_snapshot"),+ ):+ task = asyncio.create_task(transport.start())+ await initialize_started.wait()+ task.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await task++ transport.stop.assert_awaited_once_with()+async def test_reader_task_failure_marks_transport_not_alive(self):transport = CodexTransport(binary="codex", cwd="/tmp")transport._process = SimpleNamespace(returncode=None)diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex b200c472c..9410004ab 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -1416,6 +1416,7 @@ def test_test_web_auth_happy_path_returns_excerpt(def test_test_web_auth_codex_uses_owned_runtime_when_backend_is_disabled(service: AgentAuthService,+ tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:probe = AsyncMock(return_value="Hello from temporary Codex")@@ -1425,7 +1426,16 @@ def test_test_web_auth_codex_uses_owned_runtime_when_backend_is_disabled(shutdown_runtime=shutdown,)captured = []+ configured_cwd = tmp_path / "user-runtime"+ probe_runtime = tmp_path / "avibe-runtime"service.controller.agent_service = SimpleNamespace(agents={})+ monkeypatch.setattr(+ _Config,+ "runtime",+ SimpleNamespace(default_cwd=str(configured_cwd)),+ raising=False,+ )+ monkeypatch.setattr("config.paths.get_runtime_dir", lambda: probe_runtime)monkeypatch.setattr(service, "_get_cli_binary", lambda _backend: "codex-custom")monkeypatch.setattr(service,@@ -1438,11 +1448,12 @@ def test_test_web_auth_codex_uses_owned_runtime_when_backend_is_disabled(assert result["ok"] is Trueassert captured[0].binary == "codex-custom"probe.assert_awaited_once_with(- os.getcwd(),+ str(probe_runtime / "codex-connection-probe"),model=None,on_diagnostic=ANY,)shutdown.assert_awaited_once_with()+ assert not configured_cwd.exists()def test_disabled_backend_probe_uses_persisted_codex_binary(@@ -1462,6 +1473,7 @@ def test_disabled_backend_probe_uses_persisted_codex_binary(def test_test_web_auth_codex_does_not_probe_model_hub_transport(service: AgentAuthService,+ tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:live_probe = AsyncMock(@@ -1477,6 +1489,8 @@ def test_test_web_auth_codex_does_not_probe_model_hub_transport(shutdown_runtime=AsyncMock(),)service.controller.agent_service = SimpleNamespace(agents={"codex": live_agent})+ probe_runtime = tmp_path / "avibe-runtime"+ monkeypatch.setattr("config.paths.get_runtime_dir", lambda: probe_runtime)monkeypatch.setattr(service,"_create_codex_probe_agent",@@ -1488,7 +1502,7 @@ def test_test_web_auth_codex_does_not_probe_model_hub_transport(assert result["ok"] is Truelive_probe.assert_not_awaited()temp_probe.assert_awaited_once_with(- os.getcwd(),+ str(probe_runtime / "codex-connection-probe"),model=None,on_diagnostic=ANY,)