Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(codex): evict cached app-server when its cwd inode changes; treat config-load failure as recoverable (#561)

cyh86ade49e0ce5
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index c09063e96..b795ed013 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import logging
+import os
import time
from pathlib import Path
from typing import Any, Dict, Optional
@@ -57,6 +58,13 @@ class CodexAgent(BaseAgent):
self._transports: Dict[str, CodexTransport] = {}
self._transport_locks: Dict[str, asyncio.Lock] = {}
self._transport_last_activity: Dict[str, float] = {}
+ # cwd inode at app-server spawn time, keyed like ``_transports``. A
+ # cached app-server whose directory was deleted (even if re-created
+ # with the same path) sits in a dead inode and fails every
+ # ``thread/start`` with a misleading "failed to load configuration:
+ # No such file or directory" (#561); the inode comparison detects
+ # that staleness BEFORE paying a failed RPC.
+ self._transport_cwd_inodes: Dict[str, Optional[int]] = {}
self._session_mgr = CodexSessionManager()
self._turn_registry = CodexTurnRegistry()
@@ -415,6 +423,7 @@ class CodexAgent(BaseAgent):
self._transports.pop(cwd, None)
self._transport_last_activity.pop(cwd, None)
+ self._cwd_inodes().pop(cwd, None)
for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):
# Keep the persisted thread mapping so a later transport restart
@@ -443,6 +452,11 @@ class CodexAgent(BaseAgent):
"transport is not available",
"stdout closed",
"timed out after 120s",
+ # codex resolves configuration against its process cwd at
+ # thread/start; a cwd deleted out from under the app-server
+ # surfaces as this RPC error (#561). A restart respawns the
+ # process in the (re-created) directory.
+ "failed to load configuration",
)
)
@@ -460,6 +474,7 @@ class CodexAgent(BaseAgent):
if current is transport:
self._transports.pop(cwd, None)
self._transport_last_activity.pop(cwd, None)
+ self._cwd_inodes().pop(cwd, None)
try:
await transport.stop()
except Exception as exc:
@@ -487,8 +502,19 @@ class CodexAgent(BaseAgent):
# Double-check after acquiring lock
existing = self._transports.get(cwd)
if existing and existing.is_initialized:
- self._touch_transport_activity(cwd)
- return existing
+ # Reuse only while the directory the app-server was spawned in
+ # is still the SAME directory (#561): after a delete (+ possible
+ # re-create) the cached process sits in a dead inode and every
+ # thread/start fails. Untracked legacy entries reuse as before.
+ spawned_ino = self._cwd_inodes().get(cwd)
+ stale_cwd = spawned_ino is not None and self._cwd_inode(cwd) != spawned_ino
+ if not stale_cwd:
+ self._touch_transport_activity(cwd)
+ return existing
+ logger.warning(
+ "Codex transport cwd was replaced under the cached app-server; restarting transport for cwd=%s",
+ cwd,
+ )
# Stop stale transport if any
if existing:
@@ -520,6 +546,7 @@ class CodexAgent(BaseAgent):
await transport.start()
self._transports[cwd] = transport
+ self._cwd_inodes()[cwd] = self._cwd_inode(cwd)
self._touch_transport_activity(cwd)
return transport
@@ -1045,6 +1072,18 @@ class CodexAgent(BaseAgent):
finally:
request.ack_message_id = None
+ def _cwd_inodes(self) -> Dict[str, Optional[int]]:
+ if not hasattr(self, "_transport_cwd_inodes"):
+ self._transport_cwd_inodes = {}
+ return self._transport_cwd_inodes
+
+ @staticmethod
+ def _cwd_inode(cwd: str) -> Optional[int]:
+ try:
+ return os.stat(cwd).st_ino
+ except OSError:
+ return None
+
def _touch_transport_activity(self, cwd: str) -> None:
if not hasattr(self, "_transport_last_activity"):
self._transport_last_activity = {}
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 31b11394a..677c553c6 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -1761,5 +1761,86 @@ class CodexTransportCommandTests(unittest.IsolatedAsyncioTestCase):
)
+class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
+ """#561: a cached app-server whose spawn directory was deleted (and possibly
+ re-created at the same path) sits in a dead inode and fails every
+ thread/start with "failed to load configuration"."""
+
+ def _agent(self):
+ agent = object.__new__(CodexAgent)
+ agent._transports = {}
+ agent._transport_locks = {}
+ agent._transport_last_activity = {}
+ agent._transport_cwd_inodes = {}
+ agent._session_locks = {}
+ agent._session_mgr = SimpleNamespace(sessions_for_cwd=lambda cwd: [])
+ agent.codex_config = SimpleNamespace(binary="codex", extra_args=[])
+ return agent
+
+ async def test_cached_transport_evicted_when_cwd_inode_changes(self):
+ import tempfile
+
+ agent = self._agent()
+ with tempfile.TemporaryDirectory() as cwd:
+ stale = SimpleNamespace(is_initialized=True, stop=AsyncMock())
+ agent._transports[cwd] = stale
+ # Simulate "spawned in a directory that was since replaced": the
+ # recorded spawn-time inode differs from the current one.
+ agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino + 1
+
+ fresh = SimpleNamespace(
+ is_initialized=True,
+ start=AsyncMock(),
+ on_notification=Mock(),
+ on_server_request=Mock(),
+ )
+ with patch.object(_MODULE, "CodexTransport", return_value=fresh):
+ result = await agent._get_or_create_transport(cwd)
+
+ stale.stop.assert_awaited_once()
+ self.assertIs(result, fresh)
+ fresh.start.assert_awaited_once()
+ # The new spawn re-records the CURRENT inode.
+ self.assertEqual(agent._transport_cwd_inodes[cwd], os.stat(cwd).st_ino)
+
+ async def test_cached_transport_reused_while_cwd_unchanged(self):
+ import tempfile
+
+ agent = self._agent()
+ with tempfile.TemporaryDirectory() as cwd:
+ cached = SimpleNamespace(is_initialized=True, stop=AsyncMock())
+ agent._transports[cwd] = cached
+ agent._transport_cwd_inodes[cwd] = os.stat(cwd).st_ino
+
+ with patch.object(_MODULE, "CodexTransport") as ctor:
+ result = await agent._get_or_create_transport(cwd)
+
+ self.assertIs(result, cached)
+ cached.stop.assert_not_awaited()
+ ctor.assert_not_called()
+
+ async def test_untracked_legacy_entry_reuses_without_inode(self):
+ import tempfile
+
+ agent = self._agent()
+ with tempfile.TemporaryDirectory() as cwd:
+ cached = SimpleNamespace(is_initialized=True, stop=AsyncMock())
+ agent._transports[cwd] = cached
+ # No recorded inode (legacy entry) -> reuse as before, no eviction.
+ with patch.object(_MODULE, "CodexTransport") as ctor:
+ result = await agent._get_or_create_transport(cwd)
+ self.assertIs(result, cached)
+ ctor.assert_not_called()
+
+ def test_config_load_failure_is_recoverable(self):
+ agent = object.__new__(CodexAgent)
+ err = RuntimeError(
+ "Codex RPC error: {'code': -32600, 'message': "
+ "'failed to load configuration: No such file or directory (os error 2)'}"
+ )
+ self.assertTrue(agent._is_recoverable_transport_error(err))
+
+
+
if __name__ == "__main__":
unittest.main()