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(claude): backstop stuck-active sessions safely (#629)
Call Whitea2e955911ed7
diff --git a/config/v2_config.py b/config/v2_config.pyindex 02d288096..fb45134a2 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -48,6 +48,28 @@ DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS = 600DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER = 3DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800+# Absolute-age backstop for idle eviction. A Claude session that is still+# flagged ``active`` (its per-turn receiver never released the flag, e.g. a+# long-lived receiver blocked on ``receive_messages`` with no stream EOF) is+# force-evicted once its ``last_activity`` is older than+# ``max(idle_timeout * STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER, FLOOR_SECONDS)``.+# This decouples eviction from the receiver's flag-release logic, so a+# stuck-active session can no longer pin its ~220MB ``claude`` subprocess until+# the next service restart. A genuine in-flight turn keeps touching+# ``last_activity`` (assistant/tool messages), so it normally stays well under+# this cap. Set the multiplier to 0 to disable the backstop.+#+# Trade-off: ``last_activity`` is only refreshed when an SDK message arrives.+# Because a stuck (blocked-receiver) session and a session running a single+# silent tool call are indistinguishable from ``last_activity`` alone, a real+# turn whose ONE tool invocation runs silently for longer than+# the cap would be force-evicted mid-turn. The default cap is at least 30min+# because Claude Code's Bash tool caps at 10min, so a single 30min-silent turn+# is not expected in practice; raise the multiplier if your deployment runs+# longer silent tools (e.g. long builds via custom/MCP tools that emit no+# intermediate messages).+DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER = 3+DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800DEFAULT_OPENCODE_ERROR_RETRY_LIMIT = 1DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX = 14MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 08d880996..463ce2c6a 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -20,6 +20,12 @@ from modules.claude_sdk_compat import (ClaudeAgentOptions,ClaudeSDKClient,)+from modules.agents.claude_process_reaper import (+ AVIBE_CLAUDE_AUTH_OWNER,+ AVIBE_CLAUDE_PROCESS_OWNER_ENV,+ get_claude_client_pid,+ register_claude_owned_process,+)from modules.agents.catalog import WEB_OAUTH_BACKENDSfrom modules.agents.opencode.message_processor import (extract_opencode_response_text,@@ -375,6 +381,7 @@ class AgentAuthService:self._claude_oauth_attempt_counter = 0self._claude_oauth_batch: ClaudeOAuthBatch | None = Noneself._claude_oauth_lock = asyncio.Lock()+ self._claude_control_flow_starts_in_flight = 0self._recover_interrupted_claude_oauth_settings_backup()# Optional callable invoked after a successful *web* auth flow so# the UI-server process can ask the long-running controller to@@ -382,6 +389,33 @@ class AgentAuthService:# and runs in a worker thread to avoid blocking the auth event loop.self._post_web_success_hook: Optional[Any] = None+ def _active_claude_auth_clients(self) -> list[Any]:+ clients: list[Any] = []+ for flow in list(self._flows.values()):+ if flow.backend != "claude" or flow.claude_client is None:+ continue+ clients.append(flow.claude_client)+ for flow in list(self._web_flows.values()):+ if flow.backend != "claude" or flow.claude_client is None:+ continue+ clients.append(flow.claude_client)+ return clients++ def active_claude_auth_client_pids(self) -> set[int]:+ """Return Claude SDK client pids owned by in-progress auth flows."""+ pids: set[int] = set()+ for client in self._active_claude_auth_clients():+ pid = get_claude_client_pid(client)+ if pid:+ pids.add(pid)+ return pids++ def has_active_claude_auth_client_with_unknown_pid(self) -> bool:+ """Whether an in-progress Claude auth flow owns a client with no exposed pid."""+ if self._claude_control_flow_starts_in_flight > 0:+ return True+ return any(get_claude_client_pid(client) is None for client in self._active_claude_auth_clients())+def _t(self, key: str, **kwargs) -> str:lang = getattr(self.controller, "_get_lang", lambda: getattr(self.controller.config, "language", "en"))()return i18n_t(key, lang, **kwargs)@@ -972,8 +1006,10 @@ class AgentAuthService:# client or follow-up probes launch.attempt = await self._begin_claude_oauth_attempt()client = None+ self._claude_control_flow_starts_in_flight += 1try:client = await self._create_claude_control_client(context)+ register_claude_owned_process(client, owner=AVIBE_CLAUDE_AUTH_OWNER)response = await self._send_claude_control_request(client,{@@ -986,6 +1022,11 @@ class AgentAuthService:if client is not None:await self._disconnect_claude_client(client)raise+ finally:+ self._claude_control_flow_starts_in_flight = max(+ 0,+ self._claude_control_flow_starts_in_flight - 1,+ )manual_url = str(response.get("manualUrl") or "").strip()if not manual_url:@@ -1028,6 +1069,7 @@ class AgentAuthService:self._resolve_backend_config("claude"),force_oauth=True,)+ claude_env[AVIBE_CLAUDE_PROCESS_OWNER_ENV] = AVIBE_CLAUDE_AUTH_OWNERshould_mark_isolated = getattr(session_handler, "_should_mark_claude_isolated_env", None)if callable(should_mark_isolated) and should_mark_isolated():diff --git a/core/controller.py b/core/controller.pyindex 289a2e6ac..86406f79a 100644--- a/core/controller.py+++ b/core/controller.py@@ -1249,6 +1249,13 @@ class Controller:await self.session_handler.evict_idle_sessions(claude_timeout)except Exception as e:logger.error("Claude idle cleanup failed: %s", e, exc_info=True)+ try:+ # Defense-in-depth: reconcile live claude subprocesses+ # against tracked sessions and reap orphans (no-owner /+ # cross-restart) the idle-eviction path cannot see.+ await self.session_handler.reap_orphaned_claude_sessions()+ except Exception as e:+ logger.error("Claude orphan reaper failed: %s", e, exc_info=True)if codex_timeout > 0:codex_agent = self.agent_service.agents.get("codex")diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex bd059ad80..2742866c3 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -18,8 +18,16 @@ from modules.claude_sdk_compat import ()from modules.agents.native_sessions.base import build_resume_previewfrom modules.agents.claude_process_reaper import (+ AVIBE_CLAUDE_PROCESS_OWNER_ENV,+ AVIBE_CLAUDE_SESSION_OWNER,get_claude_client_pid,+ register_claude_owned_process,reap_duplicate_claude_resume_processes,+ reap_orphaned_claude_processes,+)+from config.v2_config import (+ DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS,+ DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,)from core.avibe_cloud import avibe_cloud_url_availablefrom core.services.session_fork import pending_native_fork_source@@ -102,6 +110,11 @@ class SessionHandler(BaseHandler):setattr(client, "_vibe_runtime_session_key", composite_key)if native_session_id:setattr(client, "_vibe_native_session_id", native_session_id)+ register_claude_owned_process(+ client,+ native_session_id=native_session_id,+ owner=AVIBE_CLAUDE_SESSION_OWNER,+ )async def _set_claude_model_if_needed(self, client: ClaudeSDKClient, desired_model: Optional[str]) -> None:unknown = object()@@ -795,6 +808,7 @@ class SessionHandler(BaseHandler):from vibe.claude_config import build_claude_subprocess_envclaude_env = build_claude_subprocess_env(getattr(self.config, "claude", None))+ claude_env[AVIBE_CLAUDE_PROCESS_OWNER_ENV] = AVIBE_CLAUDE_SESSION_OWNERif self._should_mark_claude_isolated_env():claude_env["IS_SANDBOX"] = "1"logger.info("Detected Claude bypassPermissions running as root; marking Claude subprocess as isolated")@@ -1234,11 +1248,40 @@ class SessionHandler(BaseHandler):if exc is not None:logger.warning("Claude receiver ended with error during cleanup: %s", exc)- async def evict_idle_sessions(self, idle_timeout: float) -> int:- """Disconnect Claude sessions that have been idle beyond the timeout."""+ async def evict_idle_sessions(+ self,+ idle_timeout: float,+ stuck_active_multiplier: float = DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,+ stuck_active_floor_seconds: float = DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS,+ ) -> int:+ """Disconnect Claude sessions that have been idle beyond the timeout.++ A session is normally exempt from eviction while it is flagged+ ``active`` (a turn is in flight). That veto is **not** absolute: if the+ receiver coroutine never releases the flag (e.g. it stays alive but+ blocked on ``receive_messages`` with no stream EOF), the session would+ otherwise be pinned forever and its ``claude`` subprocess would survive+ until the next service restart. As an independent backstop, a session+ that is ``active`` but whose ``last_activity`` is older than+ ``max(idle_timeout * stuck_active_multiplier,+ stuck_active_floor_seconds)`` is force-evicted regardless of why the+ flag was not cleared. A genuine in-flight turn keeps touching+ ``last_activity`` via assistant/tool messages, so it normally stays well+ under this cap. Pass ``stuck_active_multiplier <= 0`` to disable the+ backstop. Caveat: a real turn whose single tool call runs silently for+ longer than the cap is indistinguishable from a stuck session and would+ be force-evicted — see ``DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER``.+ """if idle_timeout <= 0:return 0+ stuck_threshold = None+ if stuck_active_multiplier > 0:+ stuck_threshold = max(+ idle_timeout * stuck_active_multiplier,+ max(0.0, stuck_active_floor_seconds),+ )+now = time.monotonic()expired: list[tuple[str, float]] = []@@ -1247,10 +1290,14 @@ class SessionHandler(BaseHandler):self.session_last_activity.pop(composite_key, None)self.active_sessions.discard(composite_key)continue+ idle_for = now - last_activityif composite_key in self.active_sessions:+ # Stuck-active backstop: only evict once well past the cap.+ if stuck_threshold is not None and idle_for >= stuck_threshold:+ expired.append((composite_key, idle_for))continue- if now - last_activity >= idle_timeout:- expired.append((composite_key, now - last_activity))+ if idle_for >= idle_timeout:+ expired.append((composite_key, idle_for))evicted = 0for composite_key, idle_for in expired:@@ -1259,18 +1306,92 @@ class SessionHandler(BaseHandler):self.session_last_activity.pop(composite_key, None)self.active_sessions.discard(composite_key)continue- if composite_key in self.active_sessions:- continueif current_last_activity is None:continue- if time.monotonic() - current_last_activity < idle_timeout:- continue- logger.info("Evicting idle Claude session %s after %.1fs idle", composite_key, idle_for)- await self.cleanup_session(composite_key)+ # Re-derive the decision from current state: a session may have been+ # touched or (de)activated between the two passes.+ recheck_idle = time.monotonic() - current_last_activity+ if composite_key in self.active_sessions:+ if stuck_threshold is None or recheck_idle < stuck_threshold:+ continue+ logger.warning(+ "Force-evicting stuck-active Claude session %s after %.1fs idle "+ "(>= stuck-active threshold %.1fs; multiplier=%s idle_timeout=%ss); "+ "receiver never released the active flag",+ composite_key,+ recheck_idle,+ stuck_threshold,+ stuck_active_multiplier,+ idle_timeout,+ )+ else:+ if recheck_idle < idle_timeout:+ continue+ logger.info("Evicting idle Claude session %s after %.1fs idle", composite_key, recheck_idle)+ if composite_key in self.active_sessions:+ agent_service = getattr(self.controller, "agent_service", None)+ claude_agent = getattr(agent_service, "agents", {}).get("claude") if agent_service else None+ force_cleanup = getattr(claude_agent, "force_cleanup_stuck_active_session", None)+ if callable(force_cleanup):+ await force_cleanup(composite_key)+ else:+ await self.cleanup_session(composite_key)+ else:+ await self.cleanup_session(composite_key)evicted += 1return evicted+ async def reap_orphaned_claude_sessions(self) -> int:+ """Reap leaked ``claude`` subprocesses not owned by any tracked session.++ Defense-in-depth backstop for the idle-eviction path: even if a session+ slips out of tracking (or a previous service instance left a child+ reparented to init), the resident ``claude`` subprocess is reconciled+ against the set of currently-tracked sessions and terminated when it has+ no owner. See ``reap_orphaned_claude_processes`` for the safety guards.+ """+ owned_pids: set[int] = set()+ tracked_resume_ids: dict[str, int] = {}+ owner_set_complete = True+ for client in list(self.claude_sessions.values()):+ pid = get_claude_client_pid(client)+ if not pid:+ # A tracked client whose pid we cannot resolve means the owner+ # set is incomplete: its live process would look ownerless to+ # the in-tree sweep. Disable that sweep this round.+ owner_set_complete = False+ continue+ owned_pids.add(pid)+ native_session_id = getattr(client, "_vibe_native_session_id", None)+ if native_session_id:+ tracked_resume_ids[str(native_session_id)] = pid+ # A session create in flight has spawned a subprocess (connect()) that is+ # not yet in claude_sessions; the in-tree sweep must not touch it.+ creates_in_flight = bool(self.claude_session_creates)+ exclude_pids: set[int] = set()+ watch_service = getattr(self.controller, "watch_service", None)+ active_watch_pids = getattr(watch_service, "active_process_pids", None)+ if callable(active_watch_pids):+ exclude_pids.update(active_watch_pids())+ auth_service = getattr(self.controller, "agent_auth_service", None)+ active_auth_pids = getattr(auth_service, "active_claude_auth_client_pids", None)+ if callable(active_auth_pids):+ exclude_pids.update(active_auth_pids())+ auth_pid_unknown = getattr(auth_service, "has_active_claude_auth_client_with_unknown_pid", None)+ auth_client_pid_unknown = bool(auth_pid_unknown()) if callable(auth_pid_unknown) else False+ # Let unexpected errors surface to the caller (``periodic_cleanup``+ # logs them at error level); ``reap_orphaned_claude_processes`` already+ # absorbs the expected ``ps``-read failure internally.+ return await reap_orphaned_claude_processes(+ owned_pids=owned_pids,+ tracked_resume_ids=tracked_resume_ids,+ cli_path=self._get_claude_cli_path_override(),+ logger=logger,+ reap_in_tree=owner_set_complete and not creates_in_flight and not auth_client_pid_unknown,+ exclude_pids=exclude_pids,+ )+async def handle_session_error(self, composite_key: str, context: MessageContext, error: Exception):"""Handle session-related errors"""error_msg = str(error)diff --git a/core/watches.py b/core/watches.pyindex b1215ee78..b583065f2 100644--- a/core/watches.py+++ b/core/watches.py@@ -405,6 +405,10 @@ class ManagedWatchService:self._store_error_fused = Falseself._store_reconcile_failures = 0+ def active_process_pids(self) -> set[int]:+ """Return active waiter process roots owned by managed watches."""+ return {pid for pid in self._active_pids.values() if isinstance(pid, int) and pid > 0}+def start(self) -> None:if self._running:returndiff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 8ccebaf46..91a986e66 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -5,6 +5,10 @@ from typing import Callable, Optionalfrom core.agent_auth_service import classify_auth_errorfrom modules.claude_sdk_compat import TextBlock, ToolUseBlock, is_claude_sdk_buffer_error+from modules.agents.claude_process_reaper import (+ AVIBE_CLAUDE_SESSION_OWNER,+ register_claude_owned_process,+)from modules.agents.base import (AGENT_RUNTIME_TURN_KEY,@@ -374,6 +378,55 @@ class ClaudeAgent(BaseAgent):if not cleanup_from_receiver:await self._stop_receiver_task(receiver_task)+ async def force_cleanup_stuck_active_session(self, composite_key: str) -> None:+ """Settle and drop a Claude session whose active flag is stale.++ SessionHandler owns the idle timer, but ClaudeAgent owns the pending+ request FIFO and Workbench turn tokens. Force cleanup must retire the+ failed turn here before removing the SDK client, otherwise a later+ result can adopt the stale request/token.+ """+ pending_request = self._pop_pending_request(composite_key)+ context = getattr(pending_request, "context", None)+ if context is not None:+ self._adopt_pending_turn_token(context, pending_request)+ await self._remove_result_pending_reaction(composite_key, context, pending_request)+ else:+ self._pending_reactions.pop(composite_key, None)+ self._last_assistant_text.pop(composite_key, None)+ self._pending_assistant_message.pop(composite_key, None)++ self._suppress_receiver_runtime_release.add(composite_key)+ try:+ try:+ await self._cleanup_runtime_session(+ composite_key,+ preserve_pending_request_state=True,+ )+ except Exception:+ if context is not None:+ self._release_service_runtime_turn(context)+ raise+ finally:+ self._suppress_receiver_runtime_release.discard(composite_key)++ if context is not None:+ try:+ await self.controller.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ )+ except Exception:+ logger.debug(+ "Failed to emit terminal result while force-cleaning Claude session %s",+ composite_key,+ exc_info=True,+ )+ self._release_service_runtime_turn(context)+async def handle_stop(self, request: AgentRequest) -> bool:composite_key = request.composite_session_idif composite_key not in self.claude_sessions:@@ -477,6 +530,11 @@ class ClaudeAgent(BaseAgent):runtime_client = self.claude_sessions.get(composite_key)if runtime_client is client:setattr(runtime_client, "_vibe_native_session_id", claude_session_id)+ register_claude_owned_process(+ runtime_client,+ native_session_id=claude_session_id,+ owner=AVIBE_CLAUDE_SESSION_OWNER,+ )logger.info(f"Captured Claude session id {claude_session_id} for {base_session_id}")if self.claude_client._is_skip_message(message):@@ -654,31 +712,61 @@ class ClaudeAgent(BaseAgent):# stale straggler. No-op for fresh sessions / absent tokens.self._adopt_pending_turn_token(context, pending_request)- await self.emit_result_message(- context,- result_text,- subtype=getattr(message, "subtype", "") or "",- duration_ms=getattr(message, "duration_ms", 0),- parse_mode="markdown",- request=pending_request,- )- native_session_id = self._native_session_ids.get(composite_key) or self._reserved_native_session_id(- context,- self.name,- ) or self._reserved_native_session_id(- getattr(pending_request, "context", None),- self.name,- )- if pending_request is not None and native_session_id:- self._maybe_backfill_session_title(pending_request, native_session_id)-- self._discard_pending_reaction(composite_key)-- self._last_assistant_text.pop(composite_key, None)- is_idle = self._mark_session_idle_if_no_pending_requests(composite_key)- session = await self.session_manager.get_or_create_session(context.user_id, context.channel_id)- if session and is_idle:- session.session_active[composite_key] = False+ # A terminal result settles the turn. The pending request+ # was already popped above, so the idle transition must run+ # even if emitting the result or backfilling the title+ # raises — otherwise the inner ``except … continue`` below+ # would swallow the error, skip the mark-idle, and leave the+ # session pinned ``active`` (exempt from idle eviction until+ # the next service restart). Run it in a ``finally``.+ emit_failed = False+ try:+ await self.emit_result_message(+ context,+ result_text,+ subtype=getattr(message, "subtype", "") or "",+ duration_ms=getattr(message, "duration_ms", 0),+ parse_mode="markdown",+ request=pending_request,+ )+ native_session_id = self._native_session_ids.get(composite_key) or self._reserved_native_session_id(+ context,+ self.name,+ ) or self._reserved_native_session_id(+ getattr(pending_request, "context", None),+ self.name,+ )+ if pending_request is not None and native_session_id:+ self._maybe_backfill_session_title(pending_request, native_session_id)+ except Exception:+ emit_failed = True+ raise+ finally:+ # Settle the turn regardless of an emit/backfill+ # failure: clear the loading reaction and the stale+ # assistant-text fallback, then release the active+ # flag so the session can be idle-evicted.+ await self._remove_result_pending_reaction(+ composite_key,+ context,+ pending_request,+ )+ self._last_assistant_text.pop(composite_key, None)+ is_idle = self._mark_session_idle_if_no_pending_requests(composite_key)+ try:+ session = await self.session_manager.get_or_create_session(+ context.user_id, context.channel_id+ )+ if session and is_idle:+ session.session_active[composite_key] = False+ except Exception:+ logger.debug(+ "claude: failed to update session_active after result for %s",+ composite_key,+ exc_info=True,+ )+ if emit_failed:+ self._release_service_runtime_turn(context)continue# Ignore UserMessage/tool results; toolcalls are emitted from ToolUseBlock.@@ -877,6 +965,20 @@ class ClaudeAgent(BaseAgent):if not reactions:self._pending_reactions.pop(composite_key, None)+ async def _remove_result_pending_reaction(+ self,+ composite_key: str,+ context: MessageContext,+ request: Optional[AgentRequest],+ ) -> None:+ reactions_before = len(self._pending_reactions.get(composite_key) or [])+ if request is not None:+ await self._remove_specific_pending_reaction(composite_key, context, request)+ await self._remove_ack_reaction(request)+ reactions_after = len(self._pending_reactions.get(composite_key) or [])+ if reactions_before and reactions_after == reactions_before:+ self._discard_pending_reaction(composite_key)+def _pop_pending_request(self, composite_key: str) -> Optional[AgentRequest]:requests = self._pending_requests.get(composite_key)if not requests:diff --git a/modules/agents/claude_process_reaper.py b/modules/agents/claude_process_reaper.pyindex eb4f903e8..824cbe6c4 100644--- a/modules/agents/claude_process_reaper.py+++ b/modules/agents/claude_process_reaper.py@@ -3,14 +3,20 @@from __future__ import annotationsimport asyncio+import jsonimport loggingimport osimport signalimport subprocessfrom dataclasses import dataclass+from pathlib import PathKILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)NODE_EXECUTABLES = {"node", "nodejs", "node.exe"}+AVIBE_CLAUDE_PROCESS_OWNER_ENV = "AVIBE_CLAUDE_PROCESS_OWNER"+AVIBE_CLAUDE_SESSION_OWNER = "session"+AVIBE_CLAUDE_AUTH_OWNER = "auth"+CLAUDE_PROCESS_REGISTRY_NAME = "claude_processes.json"@dataclass(frozen=True)@@ -20,6 +26,14 @@ class ClaudeProcessRow:command: str+@dataclass(frozen=True)+class ClaudeOwnedProcess:+ pid: int+ native_session_id: str | None = None+ owner: str = AVIBE_CLAUDE_SESSION_OWNER+ started_at: float | None = None++def get_claude_client_pid(client: object | None) -> int | None:"""Return the SDK-managed Claude CLI pid when the current SDK exposes it."""transport = getattr(client, "_transport", None)@@ -28,6 +42,130 @@ def get_claude_client_pid(client: object | None) -> int | None:return pid if isinstance(pid, int) and pid > 0 else None+def _process_start_time(pid: int) -> float | None:+ try:+ result = subprocess.run(+ ["ps", "-o", "lstart=", "-p", str(pid)],+ check=False,+ capture_output=True,+ text=True,+ timeout=1.5,+ )+ except Exception:+ return None+ text = (result.stdout or "").strip()+ if not text:+ return None+ try:+ from email.utils import parsedate_to_datetime++ return parsedate_to_datetime(text).timestamp()+ except Exception:+ return None+++def _process_start_times(pids: set[int]) -> dict[int, float]:+ starts: dict[int, float] = {}+ for pid in pids:+ started_at = _process_start_time(pid)+ if started_at is not None:+ starts[pid] = started_at+ return starts+++def _process_identity_matches(+ record: ClaudeOwnedProcess,+ row: ClaudeProcessRow,+ current_started_at: float | None,+) -> bool:+ if record.pid != row.pid:+ return False+ if record.started_at is None:+ return True+ if current_started_at is None:+ return False+ return abs(current_started_at - record.started_at) < 1.0+++def _registry_path(runtime_dir: Path | None = None) -> Path:+ if runtime_dir is not None:+ return runtime_dir / CLAUDE_PROCESS_REGISTRY_NAME+ from config import paths++ return paths.get_runtime_dir() / CLAUDE_PROCESS_REGISTRY_NAME+++def _load_owned_process_registry(runtime_dir: Path | None = None) -> list[ClaudeOwnedProcess]:+ path = _registry_path(runtime_dir)+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ return []+ rows = payload.get("processes") if isinstance(payload, dict) else payload+ if not isinstance(rows, list):+ return []+ records: list[ClaudeOwnedProcess] = []+ for item in rows:+ if not isinstance(item, dict):+ continue+ pid = item.get("pid")+ if not isinstance(pid, int) or pid <= 0:+ continue+ native_session_id = item.get("native_session_id")+ owner = item.get("owner") or AVIBE_CLAUDE_SESSION_OWNER+ started_at = item.get("started_at")+ records.append(+ ClaudeOwnedProcess(+ pid=pid,+ native_session_id=str(native_session_id) if native_session_id else None,+ owner=str(owner),+ started_at=float(started_at) if isinstance(started_at, (int, float)) else None,+ )+ )+ return records+++def register_claude_owned_process(+ client: object | None,+ *,+ native_session_id: str | None = None,+ owner: str = AVIBE_CLAUDE_SESSION_OWNER,+ runtime_dir: Path | None = None,+) -> None:+ pid = get_claude_client_pid(client)+ if not pid or os.name == "nt":+ return+ path = _registry_path(runtime_dir)+ records = [record for record in _load_owned_process_registry(runtime_dir) if record.pid != pid]+ records.append(+ ClaudeOwnedProcess(+ pid=pid,+ native_session_id=str(native_session_id) if native_session_id else None,+ owner=owner,+ started_at=_process_start_time(pid),+ )+ )+ payload = {+ "processes": [+ {+ "pid": record.pid,+ "native_session_id": record.native_session_id,+ "owner": record.owner,+ "started_at": record.started_at,+ }+ for record in records+ ]+ }+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path = path.with_suffix(path.suffix + ".tmp")+ tmp_path.write_text(json.dumps(payload, separators=(",", ":")) + "\n", encoding="utf-8")+ tmp_path.replace(path)+ except Exception:+ logger = logging.getLogger(__name__)+ logger.debug("Failed to persist Claude process registry", exc_info=True)++def _run_ps() -> str:result = subprocess.run(["ps", "-axo", "pid=,ppid=,command="],@@ -54,16 +192,32 @@ def _parse_ps_rows(output: str) -> list[ClaudeProcessRow]:return rows-def _command_has_resume(command: str, native_session_id: str) -> bool:+def _command_has_flag_value(command: str, flag: str, value: str) -> bool:+ """True if ``command`` passes ``flag value`` or ``flag=value`` (token-exact)."""parts = command.split()for index, part in enumerate(parts):- if part == "--resume" and index + 1 < len(parts) and parts[index + 1] == native_session_id:+ if part == flag and index + 1 < len(parts) and parts[index + 1] == value:return True- if part.startswith("--resume=") and part.removeprefix("--resume=") == native_session_id:+ if part == f"{flag}={value}":return Truereturn False+def _command_has_resume(command: str, native_session_id: str) -> bool:+ return _command_has_flag_value(command, "--resume", native_session_id)+++def _command_has_stream_json_input(command: str) -> bool:+ """True if the command runs the Claude CLI in bidirectional streaming mode.++ The Claude Agent SDK always launches the session CLI with+ ``--input-format stream-json`` (see the SDK's subprocess transport). This+ marker is public CLI surface; it is only a subprocess-shape check, not an+ ownership proof.+ """+ return _command_has_flag_value(command, "--input-format", "stream-json")++def _command_is_claude(command: str, cli_path: str | None = None) -> bool:parts = command.split()if not parts:@@ -98,10 +252,20 @@ def find_claude_resume_processes(native_session_id: str, *, cli_path: str | None]-def _descendant_pids(rows: list[ClaudeProcessRow], root_pid: int) -> set[int]:+def _build_children_map(rows: list[ClaudeProcessRow]) -> dict[int, list[int]]:children: dict[int, list[int]] = {}for row in rows:children.setdefault(row.ppid, []).append(row.pid)+ return children+++def _descendant_pids(+ rows: list[ClaudeProcessRow],+ root_pid: int,+ children: dict[int, list[int]] | None = None,+) -> set[int]:+ if children is None:+ children = _build_children_map(rows)descendants: set[int] = set()stack = list(children.get(root_pid, []))@@ -204,6 +368,22 @@ async def reap_duplicate_claude_resume_processes(native_session_id,keep_pid,)+ return await _reap_pid_set(target_pids, terminate_timeout=terminate_timeout, logger=logger)+++async def _reap_pid_set(+ target_pids: set[int],+ *,+ terminate_timeout: float,+ logger: logging.Logger,+) -> int:+ """SIGTERM a set of pids, wait briefly, then SIGKILL the survivors.++ Returns the number of pids that were targeted.+ """+ if not target_pids:+ return 0+for pid in sorted(target_pids):_signal_pid(pid, signal.SIGTERM, logger)@@ -223,3 +403,168 @@ async def reap_duplicate_claude_resume_processes(_signal_pid(pid, KILL_SIGNAL, logger)return len(target_pids)+++def _process_ages(pids: set[int]) -> dict[int, float]:+ """Best-effort elapsed-seconds-since-start for the given pids via ``ps``.++ Returns a ``{pid: age_seconds}`` map. Pids whose age cannot be determined+ are simply absent (callers treat unknown age conservatively: do not reap).+ ``etimes`` (elapsed seconds) is available on Linux procps-ng and macOS; on+ busybox ``ps`` (Alpine) it is unsupported, so this returns ``{}`` and the+ caller reaps nothing — the safe conservative fallback.+ """+ if not pids:+ return {}+ try:+ result = subprocess.run(+ ["ps", "-o", "pid=,etimes=", "-p", ",".join(str(p) for p in sorted(pids))],+ check=False,+ capture_output=True,+ text=True,+ timeout=1.5,+ )+ except Exception:+ return {}+ ages: dict[int, float] = {}+ for line in (result.stdout or "").splitlines():+ parts = line.split()+ if len(parts) < 2:+ continue+ try:+ ages[int(parts[0])] = float(parts[1])+ except ValueError:+ continue+ return ages+++async def reap_orphaned_claude_processes(+ *,+ owned_pids: set[int],+ tracked_resume_ids: dict[str, int],+ cli_path: str | None = None,+ logger: logging.Logger,+ min_age_seconds: float = 60.0,+ terminate_timeout: float = 2.0,+ reap_in_tree: bool = True,+ exclude_pids: set[int] | None = None,+ owned_processes: list[ClaudeOwnedProcess] | None = None,+) -> int:+ """Reap leaked Claude CLI processes (defense-in-depth orphan reaper).++ Only processes with a persisted Avibe ownership record are eligible. Public+ Claude CLI flags such as ``--resume`` and ``--input-format stream-json`` are+ not sufficient proof: user watches, other backend turns, and external SDK+ clients can legitimately use the same flags. The caller may still disable+ the current-tree sweep via ``reap_in_tree`` whenever the live owner set is+ incomplete.++ Safety guards:+ - ``owned_pids`` and their descendants are never reaped.+ - ``exclude_pids`` and their descendants are never reaped. Callers use this+ for managed watch/automation commands and in-flight auth/session startup+ roots that are service descendants but not Claude runtime sessions.+ - The current service pid is never reaped.+ - A ``min_age_seconds`` grace window protects a freshly spawned process+ that has not yet been registered into the tracked set (TOCTOU). A+ candidate whose age cannot be determined is **not** reaped.++ Returns the number of pids that were signalled, which includes descendant+ helper processes — not the number of orphan roots. The blocking ``ps``+ reads are offloaded to a thread so this never stalls the event loop (this+ runs on every periodic cleanup sweep).+ """+ if os.name == "nt":+ return 0++ loop = asyncio.get_running_loop()+ try:+ all_rows = _parse_ps_rows(await loop.run_in_executor(None, _run_ps))+ except Exception:+ logger.debug("Failed to read process table for Claude orphan cleanup", exc_info=True)+ return 0++ # Build the parent->children index once and reuse it for every descendant+ # walk below (service tree, owned descendants, orphan descendants).+ children = _build_children_map(all_rows)++ service_pid = os.getpid()+ service_tree = {service_pid} | _descendant_pids(all_rows, service_pid, children)++ owned_all: set[int] = {pid for pid in owned_pids if isinstance(pid, int) and pid > 0}+ for pid in list(owned_all):+ owned_all.update(_descendant_pids(all_rows, pid, children))++ excluded_all: set[int] = {+ pid for pid in (exclude_pids or set()) if isinstance(pid, int) and pid > 0+ }+ for pid in list(excluded_all):+ excluded_all.update(_descendant_pids(all_rows, pid, children))++ claude_rows = [+ row+ for row in all_rows+ if row.pid != service_pid and _command_is_claude(row.command, cli_path=cli_path)+ ]+ row_by_pid = {row.pid: row for row in claude_rows}+ registry = owned_processes if owned_processes is not None else _load_owned_process_registry()+ registry_pids = {+ record.pid+ for record in registry+ if record.started_at is not None and record.pid in row_by_pid+ }+ current_start_times = await loop.run_in_executor(None, _process_start_times, registry_pids)++ candidates: set[int] = set()++ for record in registry:+ row = row_by_pid.get(record.pid)+ if row is None or not _process_identity_matches(record, row, current_start_times.get(record.pid)):+ continue+ if record.started_at is None:+ continue+ in_service_tree = row.pid in service_tree+ if record.owner != AVIBE_CLAUDE_SESSION_OWNER:+ continue+ if not _command_has_stream_json_input(row.command):+ continue+ if row.pid in owned_all or row.pid in excluded_all:+ continue+ if in_service_tree:+ if reap_in_tree:+ candidates.add(row.pid)+ continue+ if record.native_session_id and record.native_session_id in tracked_resume_ids:+ candidates.add(row.pid)++ candidates -= owned_all+ candidates -= excluded_all+ candidates.discard(service_pid)+ if not candidates:+ return 0++ # TOCTOU grace window: never reap a process younger than the cutoff, and+ # never reap one whose age we cannot establish. Offload the ``ps`` read.+ ages = await loop.run_in_executor(None, _process_ages, candidates)+ aged_candidates = {pid for pid in candidates if ages.get(pid, 0.0) >= min_age_seconds}+ if not aged_candidates:+ return 0++ # Reap each orphan together with its descendants (e.g. node helpers).+ target_pids: set[int] = set(aged_candidates)+ for pid in aged_candidates:+ target_pids.update(_descendant_pids(all_rows, pid, children))+ target_pids -= owned_all+ target_pids -= excluded_all+ target_pids.discard(service_pid)+ if not target_pids:+ return 0++ logger.warning(+ "Reaping %d orphaned Claude process(es) with no owning session "+ "(%d pids incl. descendants): %s",+ len(aged_candidates),+ len(target_pids),+ sorted(target_pids),+ )+ return await _reap_pid_set(target_pids, terminate_timeout=terminate_timeout, logger=logger)diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex bac44ea7d..38042309d 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -294,6 +294,61 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynself.assertIs(flow.claude_client, mock_client)self.assertTrue(flow.login_prompt_sent)+ async def test_active_claude_auth_client_pids_includes_im_and_web_flows(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task++ def _client(pid):+ return SimpleNamespace(_transport=SimpleNamespace(_process=SimpleNamespace(pid=pid)))++ im_flow = AgentAuthFlow(+ flow_id="flow-im",+ backend="claude",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=None,+ reader_task=done_task,+ waiter_task=done_task,+ claude_client=_client(501),+ )+ service._flows[im_flow.flow_key] = im_flow+ service._web_flows["web-flow"] = SimpleNamespace(+ backend="claude",+ claude_client=_client(502),+ )++ pids = service.active_claude_auth_client_pids()++ self.assertEqual(pids, {501, 502})+ self.assertFalse(service.has_active_claude_auth_client_with_unknown_pid())++ async def test_active_claude_auth_client_unknown_pid_detected(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task++ flow = AgentAuthFlow(+ flow_id="flow-im",+ backend="claude",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=None,+ reader_task=done_task,+ waiter_task=done_task,+ claude_client=SimpleNamespace(),+ )+ service._flows[flow.flow_key] = flow++ self.assertEqual(service.active_claude_auth_client_pids(), set())+ self.assertTrue(service.has_active_claude_auth_client_with_unknown_pid())+async def test_start_setup_reports_claude_start_failure(self):controller = _StubController()service = AgentAuthService(controller)@@ -1680,6 +1735,39 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynself.assertTrue(captured["connected"])self.assertEqual(captured["options"].max_buffer_size, CLAUDE_SDK_MAX_BUFFER_SIZE)+ self.assertEqual(captured["options"].env["AVIBE_CLAUDE_PROCESS_OWNER"], "auth")++ async def test_claude_control_flow_start_in_flight_disables_unknown_pid_guard(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ started = asyncio.Event()+ release = asyncio.Event()++ async def _create_client(_context):+ started.set()+ await release.wait()+ return SimpleNamespace()++ service._create_claude_control_client = AsyncMock(side_effect=_create_client)+ service._send_claude_control_request = AsyncMock(+ return_value={"manualUrl": "https://platform.claude.com/oauth/code"}+ )+ service._begin_claude_oauth_attempt = AsyncMock(return_value=None)++ task = asyncio.create_task(+ service._start_claude_control_flow(+ MessageContext(user_id="U1", channel_id="C1"),+ force_reset=False,+ login_with_claude_ai=True,+ )+ )+ await started.wait()++ self.assertTrue(service.has_active_claude_auth_client_with_unknown_pid())++ release.set()+ await task+ self.assertFalse(service.has_active_claude_auth_client_with_unknown_pid())async def test_verify_login_reports_opencode_segmentation_fault(self):controller = _StubController()diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex 4e18b60af..973a69777 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -1610,6 +1610,51 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(release_seen_state, {"client_present": False, "receiver_present": False})self.assertFalse(service._turn_gates[composite_key].lock.locked())+ async def test_force_cleanup_stuck_active_session_retires_pending_turn(self):+ controller = _StubController()+ controller.emit_agent_message = AsyncMock()+ agent = ClaudeAgent(controller)+ composite_key = "session-1:/tmp/work"+ pending_context = SimpleNamespace(+ platform_specific={+ "turn_token": "current",+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "current-runtime",+ }+ )+ pending_request = SimpleNamespace(+ context=pending_context,+ ack_reaction_message_id="m1",+ ack_reaction_emoji="eyes",+ )+ next_request = SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "next"}))+ agent._pending_requests[composite_key] = [pending_request, next_request]+ agent._pending_reactions[composite_key] = [("m1", "eyes"), ("m2", "eyes")]+ agent._last_assistant_text[composite_key] = "stale"+ agent._pending_assistant_message[composite_key] = "pending"+ agent._remove_ack_reaction = AsyncMock()++ await agent.force_cleanup_stuck_active_session(composite_key)++ controller.session_handler.cleanup_session.assert_awaited_once_with(+ composite_key,+ current_receiver_task=None,+ )+ agent._remove_ack_reaction.assert_awaited_once_with(pending_request)+ controller.emit_agent_message.assert_awaited_once_with(+ pending_context,+ "result",+ "",+ is_error=True,+ level="silent",+ )+ self.assertEqual(pending_context.platform_specific["turn_token"], "current")+ self.assertEqual(pending_context.platform_specific["agent_runtime_turn_token"], "current-runtime")+ self.assertEqual(agent._pending_requests[composite_key], [next_request])+ self.assertEqual(agent._pending_reactions[composite_key], [("m2", "eyes")])+ self.assertNotIn(composite_key, agent._last_assistant_text)+ self.assertNotIn(composite_key, agent._pending_assistant_message)+async def test_receiver_eof_adopts_pending_turn_token_when_context_is_stale(self):controller = _StubController()controller._get_session_key = lambda context: "telegram::user::U1"diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex 73d588598..6e1ac6b70 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -104,6 +104,22 @@ class _StubClaudeAgentOptions:self.continue_conversation = False+def _disconnect_counting_client(captured: dict[str, Any]):+ """Stub ClaudeSDKClient that records how many times it was disconnected."""++ class _StubClaudeSDKClient:+ def __init__(self, options):+ captured["disconnects"] = 0++ async def connect(self) -> None:+ return None++ async def disconnect(self) -> None:+ captured["disconnects"] += 1++ return _StubClaudeSDKClient++def test_to_app_config_preserves_claude_cli_path() -> None:v2 = V2Config(mode="self_host",@@ -465,6 +481,37 @@ def test_session_handler_reuses_cached_claude_client_when_system_prompt_is_unchaassert "slack/U456" not in first_client.options.system_prompt["append"]+def test_session_handler_marks_claude_sdk_session_process_owner(monkeypatch, tmp_path: Path) -> None:+ captured: dict[str, Any] = {}+ registered: list[dict[str, Any]] = []++ class _StubClaudeSDKClient:+ def __init__(self, options):+ captured["options"] = options+ self._transport = type("T", (), {"_process": type("P", (), {"pid": 4321})()})()++ async def connect(self) -> None:+ captured["connected"] = True++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)+ monkeypatch.setattr(+ session_handler_module,+ "register_claude_owned_process",+ lambda client, **kwargs: registered.append({"client": client, **kwargs}),+ )++ controller = _Controller(tmp_path)+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")++ client = _run_session(handler, context)++ assert captured["connected"] is True+ assert captured["options"].env["AVIBE_CLAUDE_PROCESS_OWNER"] == "session"+ assert registered == [{"client": client, "native_session_id": None, "owner": "session"}]++def test_session_handler_coalesces_concurrent_claude_client_creates(monkeypatch, tmp_path: Path) -> None:@@ -1034,6 +1081,358 @@ def test_session_handler_keeps_active_claude_session(monkeypatch, tmp_path: Pathassert composite_key in controller.claude_sessions+def test_evict_idle_sessions_force_evicts_stuck_active_session(monkeypatch, tmp_path: Path) -> None:+ """The active flag is not an absolute veto.++ Regression for the no-EOF / blocked-receiver leak: a receiver coroutine that+ stays alive but blocked never releases the per-turn ``active`` flag, so the+ session is pinned in ``active_sessions`` forever and its ``last_activity`` is+ frozen. Once that frozen activity is older than the absolute cap+ (``idle_timeout * multiplier``), the backstop must force-evict it. This is+ distinct from the stream-exhausted path covered elsewhere, which relies on+ the receiver actually terminating to release the flag.+ """+ captured: dict[str, Any] = {}++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _disconnect_counting_client(captured))+ monkeypatch.setattr(session_handler_module.time, "monotonic", lambda: 1000.0)++ controller = _Controller(tmp_path)+ cleanup_calls: list[str] = []++ class _ClaudeAgent:+ @staticmethod+ async def force_cleanup_stuck_active_session(composite_key: str) -> None:+ cleanup_calls.append(composite_key)+ handler.clear_session_tracking(composite_key)++ controller.agent_service = type("AgentService", (), {"agents": {"claude": _ClaudeAgent()}})()+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")++ _run_session(handler, context)++ composite_key = f"slack_C123:{tmp_path}"+ # Stuck-active: active flag set, but activity frozen 2000s ago. With the+ # default 3x multiplier the cap is 1800s, so 2000s > cap -> force-evict.+ handler.session_last_activity[composite_key] = -1000.0+ handler.active_sessions.add(composite_key)++ evicted = asyncio.run(handler.evict_idle_sessions(600))++ assert evicted == 1+ assert cleanup_calls == [composite_key]+ assert captured["disconnects"] == 0+ assert composite_key in controller.claude_sessions+ assert composite_key not in handler.active_sessions+++def test_evict_idle_sessions_keeps_stuck_active_below_cap(monkeypatch, tmp_path: Path) -> None:+ """An active session below the absolute cap is still protected."""+ captured: dict[str, Any] = {}++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _disconnect_counting_client(captured))+ 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}"+ # Idle for 1700s: past idle_timeout (600) but below the 1800s absolute cap.+ handler.session_last_activity[composite_key] = -700.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+ assert composite_key in handler.active_sessions+++def test_evict_idle_sessions_stuck_cap_floor_dominates_small_timeout(monkeypatch, tmp_path: Path) -> None:+ """A tiny idle timeout must not shrink the active-turn grace below 30min."""+ captured: dict[str, Any] = {}++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _disconnect_counting_client(captured))+ 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}"+ # idle_timeout=60 would make a 180s multiplier window; the 1800s floor+ # dominates, so 1000s of quiet active time stays protected.+ handler.session_last_activity[composite_key] = 0.0+ handler.active_sessions.add(composite_key)++ evicted = asyncio.run(handler.evict_idle_sessions(60))++ assert evicted == 0+ assert captured["disconnects"] == 0+ assert composite_key in controller.claude_sessions+ assert composite_key in handler.active_sessions+++def test_evict_idle_sessions_stuck_active_backstop_can_be_disabled(monkeypatch, tmp_path: Path) -> None:+ """``stuck_active_multiplier <= 0`` restores the absolute active veto."""+ captured: dict[str, Any] = {}++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _disconnect_counting_client(captured))+ 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] = -100000.0+ handler.active_sessions.add(composite_key)++ evicted = asyncio.run(handler.evict_idle_sessions(600, stuck_active_multiplier=0))++ assert evicted == 0+ assert captured["disconnects"] == 0+ assert composite_key in controller.claude_sessions+++def test_evict_idle_sessions_spares_session_refreshed_between_passes(monkeypatch, tmp_path: Path) -> None:+ """The recheck pass re-reads ``last_activity`` from current state.++ A session that looked idle in the collect pass but was touched (a new+ message arrived) before the recheck pass must NOT be evicted.+ """+ captured: dict[str, Any] = {}++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _disconnect_counting_client(captured))+ 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}"++ class _RefreshingActivity(dict):+ # Collect pass iterates .items() and sees the stale 0.0 (idle 1000s);+ # the recheck pass calls .get() and sees a freshly-touched 900.0+ # (idle 100s < idle_timeout), so the session must be spared.+ def get(self, key, default=None):+ return 900.0++ handler.session_last_activity = _RefreshingActivity({composite_key: 0.0})++ evicted = asyncio.run(handler.evict_idle_sessions(600))++ assert evicted == 0+ assert captured["disconnects"] == 0+ assert composite_key in controller.claude_sessions+++def test_evict_idle_sessions_evicts_stuck_active_deactivated_between_passes(monkeypatch, tmp_path: Path) -> None:+ """Stuck-active in the collect pass, deactivated before recheck.++ It must still be evicted — via the normal idle path — since by the recheck+ pass it is no longer active and is well past ``idle_timeout``.+ """+ captured: dict[str, Any] = {}++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _disconnect_counting_client(captured))+ 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}"+ # Idle 2000s (>= 1800 stuck cap and >= 600 idle_timeout).+ handler.session_last_activity[composite_key] = -1000.0++ class _DeactivatingActiveSet(set):+ def __init__(self, target_key: str):+ super().__init__()+ self.target_key = target_key+ self.add(target_key)+ self._checks = 0++ def __contains__(self, item):+ if item == self.target_key:+ self._checks += 1+ # active in the collect pass, deactivated by the recheck pass+ return self._checks < 2+ return super().__contains__(item)++ handler.active_sessions = _DeactivatingActiveSet(composite_key)++ evicted = asyncio.run(handler.evict_idle_sessions(600))++ assert evicted == 1+ assert captured["disconnects"] == 1+ assert composite_key not in controller.claude_sessions+++def test_reap_orphaned_sessions_disables_in_tree_sweep_when_pid_unresolved(monkeypatch, tmp_path: Path) -> None:+ """If a tracked client's pid cannot be resolved, the in-tree sweep is+ disabled so the live process is not misclassified as an orphan."""+ captured: dict[str, Any] = {}++ async def _fake_reap(**kwargs):+ captured.update(kwargs)+ return 0++ monkeypatch.setattr(session_handler_module, "reap_orphaned_claude_processes", _fake_reap)+ monkeypatch.setattr(session_handler_module, "get_claude_client_pid", lambda client: None)++ controller = _Controller(tmp_path)+ handler = SessionHandler(controller)+ composite_key = f"slack_C123:{tmp_path}"+ controller.claude_sessions[composite_key] = object() # tracked but pid unresolved++ asyncio.run(handler.reap_orphaned_claude_sessions())++ assert captured["reap_in_tree"] is False+++def test_reap_orphaned_sessions_disables_in_tree_sweep_when_create_in_flight(monkeypatch, tmp_path: Path) -> None:+ """A session create in flight (subprocess spawned, not yet tracked) disables+ the in-tree sweep."""+ captured: dict[str, Any] = {}++ async def _fake_reap(**kwargs):+ captured.update(kwargs)+ return 0++ monkeypatch.setattr(session_handler_module, "reap_orphaned_claude_processes", _fake_reap)+ monkeypatch.setattr(session_handler_module, "get_claude_client_pid", lambda client: 4321)++ controller = _Controller(tmp_path)+ handler = SessionHandler(controller)+ handler.claude_session_creates["slack_C123:/in/flight"] = object()++ asyncio.run(handler.reap_orphaned_claude_sessions())++ assert captured["reap_in_tree"] is False+++def test_reap_orphaned_sessions_enables_in_tree_sweep_when_owner_set_complete(monkeypatch, tmp_path: Path) -> None:+ captured: dict[str, Any] = {}++ async def _fake_reap(**kwargs):+ captured.update(kwargs)+ return 0++ monkeypatch.setattr(session_handler_module, "reap_orphaned_claude_processes", _fake_reap)+ monkeypatch.setattr(session_handler_module, "get_claude_client_pid", lambda client: 4321)++ controller = _Controller(tmp_path)+ handler = SessionHandler(controller)+ controller.claude_sessions[f"slack_C123:{tmp_path}"] = object()++ asyncio.run(handler.reap_orphaned_claude_sessions())++ assert captured["reap_in_tree"] is True+++def test_reap_orphaned_sessions_excludes_active_watch_process_roots(monkeypatch, tmp_path: Path) -> None:+ captured: dict[str, Any] = {}++ async def _fake_reap(**kwargs):+ captured.update(kwargs)+ return 0++ class _WatchService:+ @staticmethod+ def active_process_pids():+ return {500}++ monkeypatch.setattr(session_handler_module, "reap_orphaned_claude_processes", _fake_reap)+ monkeypatch.setattr(session_handler_module, "get_claude_client_pid", lambda client: 4321)++ controller = _Controller(tmp_path)+ controller.watch_service = _WatchService()+ handler = SessionHandler(controller)+ controller.claude_sessions[f"slack_C123:{tmp_path}"] = object()++ asyncio.run(handler.reap_orphaned_claude_sessions())++ assert captured["exclude_pids"] == {500}+++def test_reap_orphaned_sessions_excludes_active_claude_auth_clients(monkeypatch, tmp_path: Path) -> None:+ captured: dict[str, Any] = {}++ async def _fake_reap(**kwargs):+ captured.update(kwargs)+ return 0++ class _AuthService:+ @staticmethod+ def active_claude_auth_client_pids():+ return {600}++ monkeypatch.setattr(session_handler_module, "reap_orphaned_claude_processes", _fake_reap)+ monkeypatch.setattr(session_handler_module, "get_claude_client_pid", lambda client: 4321)++ controller = _Controller(tmp_path)+ controller.agent_auth_service = _AuthService()+ handler = SessionHandler(controller)+ controller.claude_sessions[f"slack_C123:{tmp_path}"] = object()++ asyncio.run(handler.reap_orphaned_claude_sessions())++ assert captured["exclude_pids"] == {600}+++def test_reap_orphaned_sessions_disables_in_tree_when_auth_client_pid_unknown(+ monkeypatch,+ tmp_path: Path,+) -> None:+ captured: dict[str, Any] = {}++ async def _fake_reap(**kwargs):+ captured.update(kwargs)+ return 0++ class _AuthService:+ @staticmethod+ def active_claude_auth_client_pids():+ return set()++ @staticmethod+ def has_active_claude_auth_client_with_unknown_pid():+ return True++ monkeypatch.setattr(session_handler_module, "reap_orphaned_claude_processes", _fake_reap)+ monkeypatch.setattr(session_handler_module, "get_claude_client_pid", lambda client: 4321)++ controller = _Controller(tmp_path)+ controller.agent_auth_service = _AuthService()+ handler = SessionHandler(controller)+ controller.claude_sessions[f"slack_C123:{tmp_path}"] = object()++ asyncio.run(handler.reap_orphaned_claude_sessions())++ assert captured["reap_in_tree"] is False++def test_cleanup_session_swallows_cancelled_receiver_task(monkeypatch, tmp_path: Path) -> None:events = []diff --git a/tests/test_claude_process_reaper.py b/tests/test_claude_process_reaper.pyindex 50a9c25d5..c0d19c188 100644--- a/tests/test_claude_process_reaper.py+++ b/tests/test_claude_process_reaper.py@@ -169,3 +169,411 @@ def test_reap_duplicate_claude_resume_processes_ignores_unrelated_unique_match(massert reaped == 0assert signals == []+++def _patch_orphan_env(monkeypatch, table: str, ages: dict[int, float], alive: set[int]):+ def fake_kill(pid, sig):+ if sig == 0:+ if pid not in alive:+ raise ProcessLookupError+ return+ alive.discard(pid)++ monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_ages", lambda pids: ages)+ signals: list[tuple[int, int]] = []+ real_kill = fake_kill++ def recording_kill(pid, sig):+ if sig != 0:+ signals.append((pid, sig))+ return real_kill(pid, sig)++ monkeypatch.setattr(claude_process_reaper.os, "kill", recording_kill)+ return signals+++def test_reap_orphaned_reaps_in_tree_no_owner_and_descendants(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ f"101 {service_pid} /usr/local/bin/claude --output-format stream-json --verbose --resume sess-2 --input-format stream-json",+ "102 101 node helper.js",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {101: 999.0, 102: 999.0}, {100, 101, 102})+ monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ owned_processes=[+ claude_process_reaper.ClaudeOwnedProcess(+ pid=101,+ native_session_id="sess-2",+ started_at=123.0,+ )+ ],+ )+ )++ assert reaped == 2+ killed = {pid for pid, _ in signals}+ assert 101 in killed and 102 in killed+ assert 100 not in killed+ assert service_pid not in killed+++def test_reap_orphaned_ignores_managed_watch_descendants(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"500 {service_pid} /bin/sh -c claude -p --input-format stream-json watch-work",+ "501 500 /usr/local/bin/claude -p --input-format stream-json watch-work",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {501: 999.0}, {500, 501})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids=set(),+ tracked_resume_ids={},+ logger=logging.getLogger("test.claude_orphan"),+ exclude_pids={500},+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_keeps_owned_in_tree_process(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {100: 999.0}, {100})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_ignores_cross_restart_init_parented_match(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ "300 1 /usr/local/bin/claude --output-format stream-json --verbose --resume sess-1 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {100, 300})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_respects_min_age_grace_window(monkeypatch):+ """A freshly spawned, not-yet-tracked process must not be reaped (TOCTOU)."""+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"101 {service_pid} /usr/local/bin/claude --output-format stream-json --verbose --resume sess-2 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {101: 5.0}, {101})+ monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids=set(),+ tracked_resume_ids={},+ logger=logging.getLogger("test.claude_orphan"),+ owned_processes=[claude_process_reaper.ClaudeOwnedProcess(pid=101, started_at=123.0)],+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_skips_when_age_unknown(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"101 {service_pid} /usr/local/bin/claude --output-format stream-json --verbose --resume sess-2 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {}, {101})+ monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids=set(),+ tracked_resume_ids={},+ logger=logging.getLogger("test.claude_orphan"),+ owned_processes=[claude_process_reaper.ClaudeOwnedProcess(pid=101, started_at=123.0)],+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_ignores_unrelated_out_of_tree_claude(monkeypatch):+ """Out-of-tree claude not matching any tracked --resume id is left alone."""+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ "300 1 /usr/local/bin/claude --resume someone-elses-session",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {300})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids=set(),+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_ignores_in_tree_non_sdk_claude(monkeypatch):+ """An in-tree `claude` that is NOT an SDK session subprocess (no+ --input-format stream-json) — e.g. launched by another backend or a watch+ command — must not be reaped even though it is unowned and old."""+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"401 {service_pid} /usr/local/bin/claude -p run-a-build",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {401: 999.0}, {401})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids=set(),+ tracked_resume_ids={},+ logger=logging.getLogger("test.claude_orphan"),+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_skips_in_tree_sweep_when_disabled(monkeypatch):+ """reap_in_tree=False (incomplete owner set) must not touch in-tree pids."""+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"101 {service_pid} /usr/local/bin/claude --output-format stream-json --verbose --resume sess-2 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {101: 999.0}, {101})+ monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids=set(),+ tracked_resume_ids={},+ logger=logging.getLogger("test.claude_orphan"),+ reap_in_tree=False,+ owned_processes=[claude_process_reaper.ClaudeOwnedProcess(pid=101, started_at=123.0)],+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_ignores_out_of_tree_resume_match_not_init_parented(monkeypatch):+ """A user's manual `claude --resume <id>` (parented to a shell, not init)+ must not be reaped even though the resume id matches a tracked session."""+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ "300 999 /usr/local/bin/claude --resume sess-1 --model opus",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {100, 300})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_ignores_init_parented_resume_match_without_sdk_marker(monkeypatch):+ """A user's manual `claude --resume <id>` may become init-reparented after+ its shell exits, but it is not an Avibe SDK session subprocess unless it+ carries the stream-json input marker."""+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ "300 1 /usr/local/bin/claude --resume sess-1 --model opus",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {100, 300})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_ignores_external_init_parented_stream_json_resume_client(monkeypatch):+ """External programmatic Claude clients use public stream-json/resume flags too."""+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ "300 1 /usr/local/bin/claude --output-format stream-json --verbose --resume sess-1 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {100, 300})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_reaps_registry_owned_out_of_tree_resume_match(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ "300 1 /usr/local/bin/claude --output-format stream-json --verbose --resume sess-1 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {100, 300})+ monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ owned_processes=[+ claude_process_reaper.ClaudeOwnedProcess(+ pid=300,+ native_session_id="sess-1",+ started_at=123.0,+ )+ ],+ )+ )++ assert reaped == 1+ assert (300, signal.SIGTERM) in signals+++def test_reap_orphaned_ignores_registered_out_of_tree_without_birth_identity(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"100 {service_pid} /usr/local/bin/claude --resume sess-1 --model opus",+ "300 1 /usr/local/bin/claude --output-format stream-json --verbose --resume sess-1 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {100, 300})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids={100},+ tracked_resume_ids={"sess-1": 100},+ logger=logging.getLogger("test.claude_orphan"),+ owned_processes=[+ claude_process_reaper.ClaudeOwnedProcess(+ pid=300,+ native_session_id="sess-1",+ )+ ],+ )+ )++ assert reaped == 0+ assert signals == []+++def test_reap_orphaned_ignores_other_backend_stream_json_descendant_without_registry(monkeypatch):+ service_pid = os.getpid()+ table = "\n".join(+ [+ f"{service_pid} 1 python service_main.py",+ f"700 {service_pid} /usr/local/bin/codex app-server",+ "701 700 /usr/local/bin/claude --output-format stream-json --verbose --resume sess-9 --input-format stream-json",+ ]+ )+ signals = _patch_orphan_env(monkeypatch, table, {701: 999.0}, {700, 701})++ reaped = asyncio.run(+ claude_process_reaper.reap_orphaned_claude_processes(+ owned_pids=set(),+ tracked_resume_ids={},+ logger=logging.getLogger("test.claude_orphan"),+ owned_processes=[],+ )+ )++ assert reaped == 0+ assert signals == []diff --git a/tests/test_claude_receiver_result_settle.py b/tests/test_claude_receiver_result_settle.pynew file mode 100644index 000000000..87542433c--- /dev/null+++ b/tests/test_claude_receiver_result_settle.py@@ -0,0 +1,182 @@+"""Regression: a terminal ResultMessage must settle the turn (release the+per-turn ``active`` flag) even if emitting the result raises.++Before the hardening, the result branch in ``ClaudeAgent._receive_messages``+popped the pending request and then called ``emit_result_message`` /+``_maybe_backfill_session_title`` BEFORE marking the session idle. If either+raised, the inner ``except Exception: … continue`` swallowed it and skipped the+mark-idle, so the long-lived receiver looped back and blocked with ``active``+still set — pinning the session in ``active_sessions`` (exempt from idle+eviction) until the next service restart. The mark-idle now runs in a+``finally`` so the turn always settles.+"""++from __future__ import annotations++import sys+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from modules.agents.claude_agent import ClaudeAgent+from modules.agents.service import AgentService+++class _ResultMessage:+ subtype = "success"+ result = "done"+ duration_ms = 1+++def _one_result_client():+ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield _ResultMessage()++ return _iterate()++ return _Client()+++def _build_agent(mark_idle_calls):+ controller = SimpleNamespace(+ config=SimpleNamespace(platform="slack"),+ im_client=SimpleNamespace(formatter=None),+ settings_manager=SimpleNamespace(sessions=None),+ session_manager=SimpleNamespace(+ get_or_create_session=AsyncMock(return_value=SimpleNamespace(session_active={})),+ ),+ receiver_tasks={},+ claude_sessions={},+ claude_client=SimpleNamespace(_is_skip_message=lambda message: False),+ session_handler=SimpleNamespace(+ mark_session_idle=lambda key: mark_idle_calls.append(key),+ touch_session_activity=lambda key: None,+ ),+ )+ controller._get_session_key = lambda context: "session-key"++ agent = ClaudeAgent(controller)+ # Stub the external bits the result branch touches so the test isolates the+ # settle-on-failure contract.+ agent._detect_message_type = lambda message: "result"+ agent._maybe_capture_session_id = lambda *a, **k: None+ agent._consume_suppressed_synthetic_result = lambda *a, **k: False+ agent._handle_auth_failure_result = AsyncMock(return_value=False)+ agent._reserved_native_session_id = lambda *a, **k: None+ agent._adopt_pending_turn_token = lambda *a, **k: None+ agent._discard_pending_reaction = lambda key: None+ agent._get_formatter = lambda context: None+ agent._handle_receiver_eof = AsyncMock()+ return agent+++class ResultSettlesTurnOnEmitFailureTests(unittest.IsolatedAsyncioTestCase):+ async def test_emit_failure_still_marks_session_idle(self):+ mark_idle_calls: list[str] = []+ agent = _build_agent(mark_idle_calls)+ context = SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={})+ composite_key = "session-1:/tmp/work"++ # A turn is in flight: one pending request for this session.+ agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]+ # Emitting the terminal result fails.+ agent.emit_result_message = AsyncMock(side_effect=RuntimeError("boom"))++ await agent._receive_messages(+ _one_result_client(), "session-1", "/tmp/work", context, composite_key=composite_key+ )++ # Despite the emit failure, the turn settled: the active flag was released+ # and the pending request was popped.+ agent.emit_result_message.assert_awaited_once()+ self.assertEqual(mark_idle_calls, [composite_key])+ self.assertFalse(agent._has_pending_requests(composite_key))++ async def test_emit_failure_releases_runtime_gate(self):+ mark_idle_calls: list[str] = []+ agent = _build_agent(mark_idle_calls)+ service = AgentService(agent.controller)+ service.register(agent)+ agent.controller.agent_service = service+ composite_key = "session-1:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "R1",+ },+ )+ pending_context = SimpleNamespace(+ platform_specific={+ "turn_token": "T1",+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "R1",+ },+ )+ agent._pending_requests[composite_key] = [SimpleNamespace(context=pending_context)]+ gate = service._get_turn_gate(composite_key)+ await gate.lock.acquire()+ gate.token = "R1"+ agent.emit_result_message = AsyncMock(side_effect=RuntimeError("boom"))++ await agent._receive_messages(+ _one_result_client(), "session-1", "/tmp/work", context, composite_key=composite_key+ )++ agent.emit_result_message.assert_awaited_once()+ self.assertFalse(gate.lock.locked())+ self.assertEqual(mark_idle_calls, [composite_key])+ self.assertFalse(agent._has_pending_requests(composite_key))++ async def test_emit_success_marks_session_idle(self):+ mark_idle_calls: list[str] = []+ agent = _build_agent(mark_idle_calls)+ context = SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={})+ composite_key = "session-2:/tmp/work"++ agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]+ agent.emit_result_message = AsyncMock(return_value=None)++ await agent._receive_messages(+ _one_result_client(), "session-2", "/tmp/work", context, composite_key=composite_key+ )++ agent.emit_result_message.assert_awaited_once()+ self.assertEqual(mark_idle_calls, [composite_key])+ self.assertFalse(agent._has_pending_requests(composite_key))++ async def test_force_cleanup_suppresses_receiver_release_until_terminal_emit(self):+ mark_idle_calls: list[str] = []+ agent = _build_agent(mark_idle_calls)+ composite_key = "session-3:/tmp/work"+ context = SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={})+ agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]+ events: list[tuple[str, bool]] = []++ async def _cleanup_runtime_session(key, **_kwargs):+ events.append(("cleanup", key in agent._suppress_receiver_runtime_release))+ agent._release_service_runtime_turn(context)++ agent._cleanup_runtime_session = _cleanup_runtime_session+ agent.controller.emit_agent_message = AsyncMock(+ side_effect=lambda *_args, **_kwargs: events.append(("emit", False))+ )+ agent._remove_result_pending_reaction = AsyncMock()+ agent._release_service_runtime_turn = lambda _context: events.append(+ ("release", composite_key in agent._suppress_receiver_runtime_release)+ )++ await agent.force_cleanup_stuck_active_session(composite_key)++ self.assertEqual(events, [("cleanup", True), ("release", True), ("emit", False)])+ agent.controller.emit_agent_message.assert_awaited_once()+++if __name__ == "__main__": # pragma: no cover+ unittest.main()