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(agents): evict idle claude and codex runtimes

cyh890adc55f709
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 2ff6cfde6..f9f544722 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -11,6 +11,7 @@ class ClaudeCompatConfig:
system_prompt: Optional[str] = None
default_model: Optional[str] = None
cli_path: Optional[str] = None
+ idle_timeout_seconds: int = 600
def __post_init__(self) -> None:
self.permission_mode = str(self.permission_mode)
@@ -24,6 +25,7 @@ class CodexCompatConfig:
binary: str
extra_args: list[str]
default_model: Optional[str] = None
+ idle_timeout_seconds: int = 600
@dataclass
@@ -68,6 +70,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
system_prompt=None,
default_model=v2.agents.claude.default_model,
cli_path=v2.agents.claude.cli_path,
+ idle_timeout_seconds=v2.agents.claude.idle_timeout_seconds,
)
codex = None
if v2.agents.codex.enabled:
@@ -75,6 +78,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
binary=v2.agents.codex.cli_path,
extra_args=[],
default_model=v2.agents.codex.default_model,
+ idle_timeout_seconds=v2.agents.codex.idle_timeout_seconds,
)
opencode = None
if v2.agents.opencode.enabled:
diff --git a/config/v2_config.py b/config/v2_config.py
index aceaf7e40..86c27ad8f 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -133,6 +133,7 @@ class ClaudeConfig:
enabled: bool = True
cli_path: str = "claude"
default_model: Optional[str] = None
+ idle_timeout_seconds: int = 600
@dataclass
@@ -140,6 +141,7 @@ class CodexConfig:
enabled: bool = True
cli_path: str = "codex"
default_model: Optional[str] = None
+ idle_timeout_seconds: int = 600
@dataclass
diff --git a/core/controller.py b/core/controller.py
index 713c6ef7f..67cdebebe 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -48,6 +48,8 @@ class Controller:
self.claude_sessions: Dict[str, Any] = {}
self.receiver_tasks: Dict[str, asyncio.Task] = {}
self.stored_session_mappings: Dict[str, str] = {}
+ self.session_last_activity: Dict[str, float] = {}
+ self.claude_active_sessions: set[str] = set()
# Initialize core modules
self._init_modules()
@@ -399,6 +401,13 @@ class Controller:
except Exception as e:
logger.error("Failed to start watch service: %s", e, exc_info=True)
+ claude_timeout = int(max(0, getattr(self.config.claude, "idle_timeout_seconds", 600) or 0))
+ codex_timeout = int(max(0, getattr(getattr(self.config, "codex", None), "idle_timeout_seconds", 600) or 0))
+ if (claude_timeout > 0 or codex_timeout > 0) and (
+ self.cleanup_task is None or self.cleanup_task.done()
+ ):
+ self.cleanup_task = asyncio.create_task(self.periodic_cleanup())
+
# Utility methods used by handlers
def get_cwd(self, context: MessageContext) -> str:
@@ -584,9 +593,42 @@ class Controller:
self._loop = None
async def periodic_cleanup(self):
- """[Deprecated] Periodic cleanup is disabled in favor of safe on-demand cleanup"""
- logger.info("periodic_cleanup is deprecated and not scheduled.")
- return
+ """Sweep idle backend runtime state without interrupting active work."""
+ claude_timeout = int(max(0, getattr(self.config.claude, "idle_timeout_seconds", 600) or 0))
+ codex_timeout = int(max(0, getattr(getattr(self.config, "codex", None), "idle_timeout_seconds", 600) or 0))
+ enabled_timeouts = [timeout for timeout in (claude_timeout, codex_timeout) if timeout > 0]
+ if not enabled_timeouts:
+ logger.info("Idle cleanup disabled for Claude and Codex.")
+ return
+
+ sweep_interval = max(min(enabled_timeouts) // 6, 60)
+ logger.info(
+ "Starting idle cleanup loop (interval=%ss, claude_timeout=%ss, codex_timeout=%ss)",
+ sweep_interval,
+ claude_timeout,
+ codex_timeout,
+ )
+
+ try:
+ while True:
+ await asyncio.sleep(sweep_interval)
+
+ if claude_timeout > 0:
+ try:
+ await self.session_handler.evict_idle_sessions(claude_timeout)
+ except Exception as e:
+ logger.error("Claude idle cleanup failed: %s", e, exc_info=True)
+
+ if codex_timeout > 0:
+ codex_agent = self.agent_service.agents.get("codex")
+ if codex_agent and hasattr(codex_agent, "evict_idle_transports"):
+ try:
+ await codex_agent.evict_idle_transports(codex_timeout)
+ except Exception as e:
+ logger.error("Codex idle cleanup failed: %s", e, exc_info=True)
+ except asyncio.CancelledError:
+ logger.info("Idle cleanup loop stopped.")
+ raise
def cleanup_sync(self):
"""Best-effort synchronous cleanup without cross-loop awaits"""
@@ -618,9 +660,26 @@ class Controller:
except Exception as e:
logger.debug(f"Update checker cleanup skipped: {e}")
+ async def _cancel_cleanup_task() -> None:
+ if self.cleanup_task and not self.cleanup_task.done():
+ self.cleanup_task.cancel()
+ try:
+ await self.cleanup_task
+ except asyncio.CancelledError:
+ pass
+ self.cleanup_task = None
+
+ _stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")
_stop_loop_coroutine(self.scheduled_task_service.stop(), "Scheduled task service")
_stop_loop_coroutine(self.watch_service.stop(), "Watch service")
+ try:
+ codex_agent = self.agent_service.agents.get("codex")
+ if codex_agent and hasattr(codex_agent, "shutdown_runtime"):
+ _stop_loop_coroutine(codex_agent.shutdown_runtime(), "Codex runtime")
+ except Exception as e:
+ logger.debug(f"Codex runtime cleanup skipped: {e}")
+
# Cancel receiver tasks without awaiting (they may belong to other loops)
try:
for session_id, task in list(self.receiver_tasks.items()):
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index a9a6f1cc5..8b2e94296 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -2,6 +2,7 @@
import logging
import os
+import time
from typing import Optional, Dict, Any, Tuple
from uuid import uuid4
from modules.im import MessageContext
@@ -23,6 +24,33 @@ class SessionHandler(BaseHandler):
self.claude_sessions = controller.claude_sessions
self.receiver_tasks = controller.receiver_tasks
self.stored_session_mappings = controller.stored_session_mappings
+ self.session_last_activity = getattr(controller, "session_last_activity", {})
+ self.active_sessions = getattr(controller, "claude_active_sessions", set())
+ controller.session_last_activity = self.session_last_activity
+ controller.claude_active_sessions = self.active_sessions
+
+ def touch_session_activity(self, composite_key: str) -> None:
+ if composite_key:
+ self.session_last_activity[composite_key] = time.monotonic()
+
+ def mark_session_active(self, composite_key: str) -> None:
+ if not composite_key:
+ return
+ self.active_sessions.add(composite_key)
+ self.touch_session_activity(composite_key)
+
+ def mark_session_idle(self, composite_key: str) -> None:
+ if not composite_key:
+ return
+ self.active_sessions.discard(composite_key)
+ if composite_key in self.claude_sessions:
+ self.touch_session_activity(composite_key)
+
+ def clear_session_tracking(self, composite_key: str) -> None:
+ if not composite_key:
+ return
+ self.active_sessions.discard(composite_key)
+ self.session_last_activity.pop(composite_key, None)
def get_base_session_id(self, context: MessageContext, source: str = "human") -> str:
"""Get base session ID based on platform and context (without path)"""
@@ -353,6 +381,7 @@ class SessionHandler(BaseHandler):
logger.info(
f"Using existing Claude SDK client for {base_session_id} at {working_path} (model={current_model})"
)
+ self.touch_session_activity(composite_key)
return client
if effective_agent:
@@ -380,6 +409,7 @@ class SessionHandler(BaseHandler):
working_path,
explicit_model,
)
+ self.touch_session_activity(cached_key)
return client
# Always use agent-specific key when effective_agent is set
# This ensures session continuity even on first use
@@ -531,6 +561,7 @@ class SessionHandler(BaseHandler):
await client.connect()
self.claude_sessions[composite_key] = client
+ self.touch_session_activity(composite_key)
logger.info(f"Created new Claude SDK client for {base_session_id} at {working_path}")
return client
@@ -705,6 +736,32 @@ class SessionHandler(BaseHandler):
del self.claude_sessions[composite_key]
logger.info(f"Cleaned up Claude session {composite_key}")
+ self.clear_session_tracking(composite_key)
+
+ async def evict_idle_sessions(self, idle_timeout: float) -> int:
+ """Disconnect Claude sessions that have been idle beyond the timeout."""
+ if idle_timeout <= 0:
+ return 0
+
+ now = time.monotonic()
+ expired: list[tuple[str, float]] = []
+
+ for composite_key, last_activity in list(self.session_last_activity.items()):
+ if composite_key not in self.claude_sessions:
+ self.session_last_activity.pop(composite_key, None)
+ self.active_sessions.discard(composite_key)
+ continue
+ if composite_key in self.active_sessions:
+ continue
+ if now - last_activity >= idle_timeout:
+ expired.append((composite_key, now - last_activity))
+
+ for composite_key, idle_for in expired:
+ logger.info("Evicting idle Claude session %s after %.1fs idle", composite_key, idle_for)
+ await self.cleanup_session(composite_key)
+
+ return len(expired)
+
async def handle_session_error(self, composite_key: str, context: MessageContext, error: Exception):
"""Handle session-related errors"""
error_msg = str(error)
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index b99e140ba..66ec00f32 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -65,6 +65,9 @@ class ClaudeAgent(BaseAgent):
subagent_model=request.subagent_model,
subagent_reasoning_effort=request.subagent_reasoning_effort,
)
+ mark_session_active = getattr(self.session_handler, "mark_session_active", None)
+ if callable(mark_session_active):
+ mark_session_active(request.composite_session_id)
# Queue reaction BEFORE sending query to avoid race condition where
# a fast result arrives before the reaction is queued
@@ -93,6 +96,9 @@ class ClaudeAgent(BaseAgent):
)
except Exception as e:
logger.error(f"Error processing Claude message: {e}", exc_info=True)
+ mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
+ if callable(mark_session_idle):
+ mark_session_idle(request.composite_session_id)
# Clean up the specific reaction for this request (not FIFO)
await self._remove_specific_pending_reaction(request.composite_session_id, context, request)
self._remove_pending_request(request.composite_session_id, request)
@@ -157,6 +163,9 @@ class ClaudeAgent(BaseAgent):
self._pending_assistant_message.pop(composite_id, None)
self._pending_reactions.pop(composite_id, None)
self._pending_requests.pop(composite_id, None)
+ clear_tracking = getattr(self.session_handler, "clear_session_tracking", None)
+ if callable(clear_tracking):
+ clear_tracking(composite_id)
# Legacy session manager cleanup (best-effort)
await self.session_manager.clear_session(session_key)
@@ -192,6 +201,9 @@ class ClaudeAgent(BaseAgent):
self._pending_assistant_message.pop(composite_id, None)
self._pending_reactions.pop(composite_id, None)
self._pending_requests.pop(composite_id, None)
+ clear_tracking = getattr(self.session_handler, "clear_session_tracking", None)
+ if callable(clear_tracking):
+ clear_tracking(composite_id)
logger.info("Refreshed Claude auth state across %d runtime session(s)", len(session_ids))
@@ -233,6 +245,9 @@ class ClaudeAgent(BaseAgent):
if not preserve_pending_request_state:
self._pending_reactions.pop(composite_key, None)
self._pending_requests.pop(composite_key, None)
+ clear_tracking = getattr(self.session_handler, "clear_session_tracking", None)
+ if callable(clear_tracking):
+ clear_tracking(composite_key)
async def handle_stop(self, request: AgentRequest) -> bool:
composite_key = request.composite_session_id
@@ -285,6 +300,9 @@ class ClaudeAgent(BaseAgent):
async for message in client.receive_messages():
try:
+ touch_session_activity = getattr(self.session_handler, "touch_session_activity", None)
+ if callable(touch_session_activity):
+ touch_session_activity(composite_key)
claude_session_id = self._maybe_capture_session_id(message, base_session_id, session_key)
if claude_session_id:
logger.info(f"Captured Claude session id {claude_session_id} for {base_session_id}")
@@ -330,6 +348,9 @@ class ClaudeAgent(BaseAgent):
"error" if auth_failure_assistant else "",
auth_failure_text if auth_failure_assistant else assistant_text,
):
+ mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
+ if callable(mark_session_idle):
+ mark_session_idle(composite_key)
await self._clear_pending_reactions(composite_key, context)
self._last_assistant_text.pop(composite_key, None)
self._pending_assistant_message.pop(composite_key, None)
@@ -396,6 +417,9 @@ class ClaudeAgent(BaseAgent):
getattr(message, "subtype", "") or "",
formatted_message,
):
+ mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
+ if callable(mark_session_idle):
+ mark_session_idle(composite_key)
await self._clear_pending_reactions(composite_key, context)
continue
if formatted_message and formatted_message.strip():
@@ -423,6 +447,9 @@ class ClaudeAgent(BaseAgent):
getattr(message, "subtype", "") or "",
result_text,
):
+ mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
+ if callable(mark_session_idle):
+ mark_session_idle(composite_key)
await self._clear_pending_reactions(composite_key, context)
self._last_assistant_text.pop(composite_key, None)
self._pending_assistant_message.pop(composite_key, None)
@@ -447,6 +474,9 @@ class ClaudeAgent(BaseAgent):
self._discard_pending_reaction(composite_key)
self._last_assistant_text.pop(composite_key, None)
+ mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
+ if callable(mark_session_idle):
+ mark_session_idle(composite_key)
session = await self.session_manager.get_or_create_session(context.user_id, context.channel_id)
if session:
session.session_active[f"{base_session_id}:{working_path}"] = False
@@ -462,11 +492,17 @@ class ClaudeAgent(BaseAgent):
# or a new message replacing the session). Clean up reactions
# because this receiver will never process another result.
composite_key = f"{base_session_id}:{working_path}"
+ mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
+ if callable(mark_session_idle):
+ mark_session_idle(composite_key)
logger.info("Claude receiver cancelled for session %s", composite_key)
await self._clear_pending_reactions(composite_key, context)
raise
except Exception as e:
composite_key = f"{base_session_id}:{working_path}"
+ mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
+ if callable(mark_session_idle):
+ mark_session_idle(composite_key)
logger.error(
f"Error in Claude receiver for session {composite_key}: {e}",
exc_info=True,
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 713bad901..06df8c426 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 time
from pathlib import Path
from typing import Any, Dict, Optional
@@ -34,6 +35,7 @@ class CodexAgent(BaseAgent):
# cwd → CodexTransport (one persistent process per working dir)
self._transports: Dict[str, CodexTransport] = {}
self._transport_locks: Dict[str, asyncio.Lock] = {}
+ self._transport_last_activity: Dict[str, float] = {}
self._session_mgr = CodexSessionManager()
self._turn_registry = CodexTurnRegistry()
@@ -78,6 +80,7 @@ class CodexAgent(BaseAgent):
# Track session_key and cwd for scoped invalidation
self._session_mgr.set_session_key(request.base_session_id, request.session_key)
self._session_mgr.set_cwd(request.base_session_id, request.working_path)
+ self._touch_transport_activity(request.working_path)
await self._delete_ack(request)
@@ -207,8 +210,11 @@ class CodexAgent(BaseAgent):
async def refresh_auth_state(self) -> None:
"""Drop app-server runtime state so future turns pick up fresh auth."""
+ if not hasattr(self, "_transport_last_activity"):
+ self._transport_last_activity = {}
transports = list(self._transports.values())
self._transports.clear()
+ self._transport_last_activity.clear()
for transport in transports:
try:
@@ -222,6 +228,82 @@ class CodexAgent(BaseAgent):
logger.info("Refreshed Codex auth state across %d transport(s)", len(transports))
+ async def shutdown_runtime(self) -> None:
+ """Stop all app-server transports during vibe-remote shutdown."""
+ if not hasattr(self, "_transport_last_activity"):
+ self._transport_last_activity = {}
+ if not hasattr(self, "_transport_locks"):
+ self._transport_locks = {}
+ if not hasattr(self, "_session_locks"):
+ self._session_locks = {}
+ transports = list(self._transports.values())
+ self._transports.clear()
+ self._transport_last_activity.clear()
+ self._transport_locks.clear()
+
+ for transport in transports:
+ try:
+ await transport.stop()
+ except Exception as exc:
+ logger.warning("Failed to stop Codex transport during shutdown: %s", exc)
+
+ for base_session_id in list(self._session_mgr.all_base_sessions()):
+ 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.clear()
+ logger.info("Stopped Codex runtime across %d transport(s)", len(transports))
+
+ async def evict_idle_transports(self, idle_timeout: float) -> int:
+ """Stop idle Codex transports and invalidate stale thread mappings."""
+ if idle_timeout <= 0:
+ return 0
+ if not hasattr(self, "_transport_last_activity"):
+ self._transport_last_activity = {}
+ if not hasattr(self, "_transport_locks"):
+ self._transport_locks = {}
+ if not hasattr(self, "_session_locks"):
+ self._session_locks = {}
+
+ now = time.monotonic()
+ evicted = 0
+
+ for cwd, last_activity in list(self._transport_last_activity.items()):
+ transport = self._transports.get(cwd)
+ if transport is None:
+ self._transport_last_activity.pop(cwd, None)
+ continue
+ if self._has_active_turns_for_cwd(cwd):
+ continue
+ idle_for = now - 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)
+
+ 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)
+
+ evicted += 1
+
+ return evicted
+
# ------------------------------------------------------------------
# Transport management
# ------------------------------------------------------------------
@@ -230,6 +312,7 @@ class CodexAgent(BaseAgent):
"""Return an initialized transport for the given working directory."""
existing = self._transports.get(cwd)
if existing and existing.is_initialized:
+ self._touch_transport_activity(cwd)
return existing
# Serialize creation per cwd
@@ -240,6 +323,7 @@ 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
# Stop stale transport if any
@@ -271,6 +355,7 @@ class CodexAgent(BaseAgent):
await transport.start()
self._transports[cwd] = transport
+ self._touch_transport_activity(cwd)
return transport
# ------------------------------------------------------------------
@@ -517,6 +602,7 @@ class CodexAgent(BaseAgent):
)
return
+ self._touch_transport_activity(request.working_path)
await self._event_handler.handle_notification(method, params, request)
async def _on_server_request(
@@ -604,3 +690,15 @@ class CodexAgent(BaseAgent):
logger.debug("Could not delete ack message: %s", err)
finally:
request.ack_message_id = None
+
+ def _touch_transport_activity(self, cwd: str) -> None:
+ if not hasattr(self, "_transport_last_activity"):
+ self._transport_last_activity = {}
+ if cwd:
+ self._transport_last_activity[cwd] = time.monotonic()
+
+ def _has_active_turns_for_cwd(self, cwd: str) -> bool:
+ for base_session_id in self._session_mgr.sessions_for_cwd(cwd):
+ if self._turn_registry.get_active_turn(base_session_id):
+ return True
+ return False
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 3aaf3a2df..1fbf8888b 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -88,6 +88,15 @@ def _run_session(handler: SessionHandler, context: MessageContext):
return asyncio.run(handler.get_or_create_claude_session(context))
+class _StubClaudeAgentOptions:
+ def __init__(self, **kwargs: Any) -> None:
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+ if not hasattr(self, "cli_path"):
+ self.cli_path = None
+ self.continue_conversation = False
+
+
def test_to_app_config_preserves_claude_cli_path() -> None:
v2 = V2Config(
mode="self_host",
@@ -112,6 +121,7 @@ def test_session_handler_passes_configured_claude_cli_path(monkeypatch, tmp_path
async def connect(self) -> None:
captured["connected"] = True
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
controller = _Controller(tmp_path)
@@ -135,6 +145,7 @@ def test_session_handler_keeps_sdk_default_for_default_claude_binary(monkeypatch
async def connect(self) -> None:
captured["connected"] = True
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
controller = _Controller(tmp_path)
@@ -158,6 +169,7 @@ def test_session_handler_passes_non_default_claude_command_name(monkeypatch, tmp
async def connect(self) -> None:
captured["connected"] = True
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
controller = _Controller(tmp_path)
@@ -181,6 +193,7 @@ def test_session_handler_expands_tilde_in_claude_cli_path(monkeypatch, tmp_path:
async def connect(self) -> None:
captured["connected"] = True
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
controller = _Controller(tmp_path)
@@ -192,3 +205,73 @@ def test_session_handler_expands_tilde_in_claude_cli_path(monkeypatch, tmp_path:
assert captured["connected"] is True
assert captured["options"].cli_path == str(Path("~/bin/claude").expanduser())
+
+
+def test_session_handler_evicts_idle_claude_session(monkeypatch, tmp_path: Path) -> None:
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+ captured["disconnects"] = 0
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ async def disconnect(self) -> None:
+ captured["disconnects"] += 1
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ _run_session(handler, context)
+
+ composite_key = f"slack_C123:{tmp_path}"
+ handler.session_last_activity[composite_key] = 0.0
+
+ evicted = asyncio.run(handler.evict_idle_sessions(600))
+
+ assert evicted == 1
+ assert captured["disconnects"] == 1
+ assert composite_key not in controller.claude_sessions
+ assert composite_key not in handler.session_last_activity
+
+
+def test_session_handler_keeps_active_claude_session(monkeypatch, tmp_path: Path) -> None:
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+ captured["disconnects"] = 0
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ async def disconnect(self) -> None:
+ captured["disconnects"] += 1
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ _run_session(handler, context)
+
+ composite_key = f"slack_C123:{tmp_path}"
+ handler.session_last_activity[composite_key] = 0.0
+ handler.active_sessions.add(composite_key)
+
+ evicted = asyncio.run(handler.evict_idle_sessions(600))
+
+ assert evicted == 0
+ assert captured["disconnects"] == 0
+ assert composite_key in controller.claude_sessions
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index ddc3f1fcb..fb287e2cb 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -1,3 +1,4 @@
+import asyncio
import importlib.util
import sys
import types
@@ -284,6 +285,69 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(invalidated, ["session-1", "session-2"])
self.assertEqual(cleared_sessions, ["session-1", "session-2"])
+ async def test_evict_idle_transports_stops_idle_codex_runtime(self):
+ agent = object.__new__(CodexAgent)
+ stop_calls = []
+ cleared_sessions = []
+ cleared_turns = []
+
+ async def stop_transport():
+ stop_calls.append("stop")
+
+ agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}
+ agent._transport_last_activity = {"/tmp/work": 0.0}
+ agent._transport_locks = {"/tmp/work": asyncio.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: cleared_sessions.append(base_session_id),
+ )
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=lambda base_session_id: None,
+ clear_session=lambda base_session_id: cleared_turns.append(base_session_id),
+ )
+ 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):
+ evicted = await agent.evict_idle_transports(600)
+
+ self.assertEqual(evicted, 1)
+ self.assertEqual(stop_calls, ["stop"])
+ self.assertEqual(cleared_sessions, ["session-1"])
+ self.assertEqual(cleared_turns, ["session-1"])
+ agent.sessions.clear_agent_session_mapping.assert_called_once_with("scope-1", "codex", "session-1")
+ self.assertEqual(agent._transports, {})
+ self.assertEqual(agent._transport_last_activity, {})
+
+ async def test_evict_idle_transports_keeps_active_codex_runtime(self):
+ agent = object.__new__(CodexAgent)
+
+ async def stop_transport():
+ raise AssertionError("active transport should not be stopped")
+
+ agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}
+ agent._transport_last_activity = {"/tmp/work": 0.0}
+ agent._transport_locks = {"/tmp/work": asyncio.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: "turn-1",
+ 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):
+ evicted = await agent.evict_idle_transports(600)
+
+ self.assertEqual(evicted, 0)
+ self.assertIn("/tmp/work", agent._transports)
+ agent.sessions.clear_agent_session_mapping.assert_not_called()
+
class _HandleMessageTurnRegistry:
def __init__(self, active_turn: str | None):