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(cleanup): harden idle eviction races
cyh0d31bfd7c1c3
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 853771c14..5fb1f337a 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -1,5 +1,6 @@"""Session management handlers for Claude SDK sessions"""+import asyncioimport loggingimport osimport time@@ -729,6 +730,8 @@ class SessionHandler(BaseHandler):task.cancel()try:await task+ except asyncio.CancelledError:+ passexcept Exception:passdel self.receiver_tasks[composite_key]diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 7e89ea501..25bff4a48 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -282,26 +282,40 @@ class CodexAgent(BaseAgent):if idle_for < idle_timeout:continue- logger.info("Evicting idle Codex transport for cwd=%s after %.1fs idle", cwd, idle_for)- try:- await transport.stop()- except Exception as exc:- logger.warning("Failed to stop idle Codex transport for cwd=%s: %s", cwd, exc)- continue+ lock = self._transport_locks.setdefault(cwd, asyncio.Lock())+ async with lock:+ current_transport = self._transports.get(cwd)+ current_last_activity = self._transport_last_activity.get(cwd)+ if current_transport is None or current_transport is not transport:+ continue+ if self._has_active_turns_for_cwd(cwd):+ continue+ if current_last_activity is None:+ continue+ idle_for = time.monotonic() - current_last_activity+ if idle_for < idle_timeout:+ continue++ logger.info("Evicting idle Codex transport for cwd=%s after %.1fs idle", cwd, idle_for)+ try:+ await transport.stop()+ except Exception as exc:+ logger.warning("Failed to stop idle Codex transport for cwd=%s: %s", cwd, exc)+ continue- self._transports.pop(cwd, None)- self._transport_last_activity.pop(cwd, None)- self._transport_locks.pop(cwd, None)+ self._transports.pop(cwd, None)+ self._transport_last_activity.pop(cwd, None)+ self._transport_locks.pop(cwd, None)- for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):- session_key = self._session_mgr.get_session_key(base_session_id)- if session_key:- self.sessions.clear_agent_session_mapping(session_key, self.name, base_session_id)- self._session_mgr.clear(base_session_id)- self._turn_registry.clear_session(base_session_id)- self._session_locks.pop(base_session_id, None)+ for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):+ session_key = self._session_mgr.get_session_key(base_session_id)+ if session_key:+ self.sessions.clear_agent_session_mapping(session_key, self.name, base_session_id)+ self._session_mgr.clear(base_session_id)+ self._turn_registry.clear_session(base_session_id)+ self._session_locks.pop(base_session_id, None)- evicted += 1+ evicted += 1return evicteddiff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex e10a3cec0..7c7e32830 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -277,3 +277,38 @@ def test_session_handler_keeps_active_claude_session(monkeypatch, tmp_path: Pathassert evicted == 0assert captured["disconnects"] == 0assert composite_key in controller.claude_sessions+++def test_cleanup_session_swallows_cancelled_receiver_task(monkeypatch, tmp_path: Path) -> None:+ class _StubClaudeSDKClient:+ def __init__(self, options):+ self.disconnects = 0++ async def connect(self) -> None:+ return None++ async def disconnect(self) -> None:+ self.disconnects += 1++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)++ controller = _Controller(tmp_path)+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")+ client = _run_session(handler, context)+ composite_key = f"slack_C123:{tmp_path}"++ async def _exercise_cleanup() -> None:+ async def _receiver():+ await asyncio.Future()++ controller.receiver_tasks[composite_key] = asyncio.create_task(_receiver())+ await asyncio.sleep(0)+ await handler.cleanup_session(composite_key)++ asyncio.run(_exercise_cleanup())++ assert client.disconnects == 1+ assert composite_key not in controller.receiver_tasks+ assert composite_key not in controller.claude_sessionsdiff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 7914817bf..f741178b5 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -414,6 +414,44 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(cleared_turns, [])agent.sessions.clear_agent_session_mapping.assert_not_called()+ async def test_evict_idle_transports_revalidates_activity_before_stop(self):+ agent = object.__new__(CodexAgent)+ stop_calls = []++ async def stop_transport():+ stop_calls.append("stop")++ lock = asyncio.Lock()+ await lock.acquire()+ agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}+ agent._transport_last_activity = {"/tmp/work": 0.0}+ agent._transport_locks = {"/tmp/work": lock}+ agent._session_mgr = SimpleNamespace(+ sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],+ get_session_key=lambda base_session_id: "scope-1",+ clear=lambda base_session_id: None,+ )+ agent._turn_registry = SimpleNamespace(+ get_active_turn=lambda base_session_id: None,+ has_pending_turn_start=lambda base_session_id: False,+ clear_session=lambda base_session_id: None,+ )+ agent._session_locks = {"session-1": asyncio.Lock()}+ agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())++ with patch.object(_MODULE.time, "monotonic", return_value=1000.0):+ eviction_task = asyncio.create_task(agent.evict_idle_transports(600))+ await asyncio.sleep(0)+ agent._transport_last_activity["/tmp/work"] = 950.0+ lock.release()+ evicted = await eviction_task++ self.assertEqual(evicted, 0)+ self.assertEqual(stop_calls, [])+ self.assertIn("/tmp/work", agent._transports)+ self.assertEqual(agent._transport_last_activity["/tmp/work"], 950.0)+ agent.sessions.clear_agent_session_mapping.assert_not_called()+class _HandleMessageTurnRegistry:def __init__(self, active_turn: str | None):