""" V8.6: PresenceEngine — Rocket.Chat User-Status automatisch setzen. Phase 1: Basis-PresenceEngine mit Status-Modell, Coalesce-Timer, Caching. Phase 2: Heartbeat-Pulsieren (Flughafen-Prinzip) für Background-Tasks. Zero external dependencies — stdlib only. """ from __future__ import annotations import json import logging import os import subprocess import threading import time import urllib.request import urllib.error from typing import Optional, Dict, Callable logger = logging.getLogger(__name__) # Ensure presence_engine logs are visible in journalctl by adding a stderr handler if not logger.handlers: _pe_handler = logging.StreamHandler() _pe_handler.setLevel(logging.INFO) _pe_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")) logger.addHandler(_pe_handler) logger.propagate = False # Don't double-log to root # ═══════════════════════════════════════════════════════════════════════════ # Pure Function: _format_presence_message # ═══════════════════════════════════════════════════════════════════════════ def _format_presence_message( status: str, room_name: str = "", error: str = "", background_count: int = 0, ) -> str: """Format a presence status message as a pure function. Args: status: One of 'online', 'busy', 'away_onboarding', 'away_move_request', 'away_error', 'heartbeat'. room_name: Room name for busy/move_request messages. error: Error description for away_error. background_count: Number of background tasks for heartbeat. Returns: Formatted message string (empty string for online/idle). """ if status == "online": return "" elif status == "busy": return f"Verarbeitet in {room_name}" if room_name else "Verarbeitet" elif status == "away_onboarding": return "Onboarding läuft" elif status == "away_move_request": return f"Wartet auf Bestätigung in {room_name}" if room_name else "Wartet auf Bestätigung" elif status == "away_error": return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler" elif status == "heartbeat": return f"wartet — {background_count} Aufträge im Hintergrund" else: return "" # ═══════════════════════════════════════════════════════════════════════════ # PresenceEngine # ═══════════════════════════════════════════════════════════════════════════ class PresenceEngine: """Manages Rocket.Chat user presence status with coalescing and heartbeat. Thread-safe: uses threading.Lock for all counter operations. Coalesce-Timer: prevents flickering by delaying status updates by 2s. Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle. """ def __init__( self, rest=None, enabled: bool = True, coalesce_ms: int = 2000, pulse_interval: float = 1.5, gateway_state_path: str = "", _clamp_pulse: bool = True, ): """Initialize the PresenceEngine. Args: rest: RocketChatREST instance for API calls. enabled: Whether presence updates are enabled. coalesce_ms: Coalesce delay in milliseconds (default 2000). pulse_interval: PulseController interval in seconds (0.5-30, default 1.5). gateway_state_path: Path to gateway_state.json. Defaults to ROCKETCHAT_GATEWAY_STATE_PATH env var or ~/.hermes/gateway_state.json. _clamp_pulse: If True, clamp pulse_interval to 0.5-30. Set False for testing. """ self._rest = rest self._enabled = enabled # Coalesce self._coalesce_ms = coalesce_ms self._coalesce_timer: Optional[threading.Timer] = None self._coalesce_lock = threading.Lock() # Pending state self._pending_status: Optional[str] = None self._pending_message: str = "" # Caching self._last_sent_status: Optional[str] = None self._last_sent_message: str = "" # Active tasks counter (threading.Lock, NOT asyncio.Lock) self._active_tasks: int = 0 self._active_tasks_lock = threading.Lock() # Sentinels for special states self._onboarding_active: bool = False self._move_request_pending: Dict[str, str] = {} # room_id → room_name self._error_state: Optional[str] = None # Current room name for busy messages self._current_room_name: str = "" # Background tasks counter (for display + PulseController coordination) self._background_tasks: int = 0 self._background_tasks_lock = threading.Lock() # P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s) self._pulse_controller = PulseController( pulse_interval=pulse_interval, _clamp_pulse=_clamp_pulse, ) # P0-1: DetectionTimer — erkennt Hintergrund-Agenten, steuert PulseController self._detection_timer = DetectionTimer( gateway_state_path=gateway_state_path, detection_interval=10.0, on_change=self._on_detection_change, ) # Start detection if enabled if self._enabled: self._detection_timer.start() # ── Public API ─────────────────────────────────────────────────────── def is_enabled(self) -> bool: """Check if presence updates are enabled.""" return self._enabled def enable(self) -> None: """Enable presence updates. Starts DetectionTimer.""" self._enabled = True self._detection_timer.start() logger.info("[presence] PresenceEngine enabled") def disable(self) -> None: """Disable presence updates. Stops PulseController and DetectionTimer.""" self._enabled = False self._pulse_controller.stop() self._detection_timer.stop() logger.info("[presence] PresenceEngine disabled") def increment_active_tasks(self) -> int: """Increment the active tasks counter. Thread-safe. Returns: New counter value. """ with self._active_tasks_lock: self._active_tasks += 1 return self._active_tasks def decrement_active_tasks(self) -> int: """Decrement the active tasks counter. Thread-safe. Returns: New counter value. """ with self._active_tasks_lock: if self._active_tasks > 0: self._active_tasks -= 1 return self._active_tasks def set_onboarding_active(self, active: bool) -> None: """Set the onboarding sentinel.""" self._onboarding_active = active def set_move_request_pending(self, room_id: str, room_name: str) -> None: """Set a move request as pending.""" self._move_request_pending[room_id] = room_name def clear_move_request(self, room_id: str) -> None: """Clear a move request.""" self._move_request_pending.pop(room_id, None) def set_error_state(self, error: Optional[str]) -> None: """Set or clear the error state.""" self._error_state = error def set_current_room(self, room_name: str) -> None: """Set the current room name for busy messages.""" self._current_room_name = room_name def increment_background_tasks(self) -> int: """Increment background tasks counter. Thread-safe. Returns: New counter value. """ with self._background_tasks_lock: self._background_tasks += 1 count = self._background_tasks self._pulse_controller.set_background_count(count) return count def decrement_background_tasks(self) -> int: """Decrement background tasks counter. Thread-safe. Returns: New counter value. """ with self._background_tasks_lock: if self._background_tasks > 0: self._background_tasks -= 1 count = self._background_tasks self._pulse_controller.set_background_count(count) if count == 0: self._pulse_controller.stop() return count # ── Internal: Presence Setting ─────────────────────────────────────── def _set_presence(self, status: str, message: str) -> None: """Schedule a presence update with coalescing. The update is delayed by coalesce_ms to prevent flickering. If called again before the timer fires, the timer is reset. Args: status: Rocket.Chat status ('online', 'away', 'busy'). message: Custom status message. """ if not self._enabled: return # EC-5: Cancel pending pulse when higher-priority status fires self.cancel_pending() with self._coalesce_lock: self._pending_status = status self._pending_message = message # Cancel existing timer if self._coalesce_timer is not None: self._coalesce_timer.cancel() self._coalesce_timer = None # Start new timer delay = self._coalesce_ms / 1000.0 self._coalesce_timer = threading.Timer(delay, self._flush_presence) self._coalesce_timer.daemon = True self._coalesce_timer.start() def _flush_presence(self) -> None: """Flush the pending presence update immediately. Skips the REST call if the (status, message) pair is identical to the last sent one (caching). """ with self._coalesce_lock: status = self._pending_status message = self._pending_message self._pending_status = None self._pending_message = "" self._coalesce_timer = None if status is None: return # Caching: skip if identical to last sent if status == self._last_sent_status and message == self._last_sent_message: return if not self._enabled: return # Send via REST API self._send_rest(status, message) # Update cache self._last_sent_status = status self._last_sent_message = message def _send_rest(self, status: str, message: str) -> None: """Send the presence update via REST API. POST /api/v1/users.setStatus with {"status": "...", "message": "..."} Called in a background thread (via Timer), non-blocking. Args: status: Rocket.Chat status ('online', 'away', 'busy'). message: Custom status message. """ if self._rest is None: return if not self._rest.auth_token: return try: data = {"status": status} if message: data["message"] = message self._rest._request("POST", "/api/v1/users.setStatus", headers={ "X-Auth-Token": self._rest.auth_token, "X-User-Id": self._rest.user_id, }, data=data) logger.info( "[presence] Status set: status=%s, message=%s", status, message[:50] if message else "", ) except Exception as e: logger.warning("[presence] Failed to set status: %s", e) # ── DetectionTimer Callback ────────────────────────────────────────── def _on_detection_change(self, is_active: bool) -> None: """Callback from DetectionTimer: start/stop PulseController. When background agents are detected (is_active=True), start pulsing. When no background agents (is_active=False), stop pulsing. """ if not self._enabled: return if is_active: if not self._pulse_controller.is_running(): self._pulse_controller.start() logger.info("[presence] PulseController gestartet (Hintergrund-Agenten erkannt)") else: if self._pulse_controller.is_running(): self._pulse_controller.stop() logger.info("[presence] PulseController gestoppt (keine Hintergrund-Agenten)") # ── Convenience: Determine and set appropriate presence ────────────── def update_presence(self) -> None: """Determine the appropriate presence state and schedule an update. Priority (highest first): 1. Error state → away + error message 2. Onboarding active → away + onboarding message 3. Move request pending → away + move request message 4. Active tasks > 0 → busy + room message 5. Active tasks == 0 → online """ if not self._enabled: return # 1. Error state if self._error_state: msg = _format_presence_message("away_error", error=self._error_state) self._set_presence("away", msg) return # 2. Onboarding active if self._onboarding_active: msg = _format_presence_message("away_onboarding") self._set_presence("away", msg) return # 3. Move request pending if self._move_request_pending: # Use the first pending room name room_name = next(iter(self._move_request_pending.values()), "") msg = _format_presence_message("away_move_request", room_name=room_name) self._set_presence("away", msg) return # 4. Active tasks with self._active_tasks_lock: active = self._active_tasks if active > 0: msg = _format_presence_message("busy", room_name=self._current_room_name) self._set_presence("busy", msg) else: self._set_presence("online", "") def shutdown(self) -> None: """Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer.""" self._pulse_controller.stop() self._detection_timer.stop() with self._coalesce_lock: if self._coalesce_timer is not None: self._coalesce_timer.cancel() self._coalesce_timer = None # ── PulseController Integration ────────────────────────────────────── def cancel_pending(self) -> None: """Cancel any pending pulse tick (K2: API auf PresenceEngine). Called by _set_presence when a higher-priority status fires while the PulseController is running (EC-5). """ self._pulse_controller.cancel_pending() def on_agent_busy(self, room_name: str = "") -> None: """Hook: Agent is processing a message — pause pulse, set busy. Priority 1 (highest): busy (rot) — Nachricht wird verarbeitet. """ self.set_current_room(room_name) self.increment_active_tasks() self.update_presence() # Pause pulse if running self._pulse_controller.pause() def on_message_received(self, room_name: str = "") -> None: """Hook: Message received — same as on_agent_busy. Alias for on_agent_busy for semantic clarity. """ self.on_agent_busy(room_name=room_name) # ═══════════════════════════════════════════════════════════════════════════ # PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall) # ═══════════════════════════════════════════════════════════════════════════ class PulseController: """DDP-based pulse timer: toggles online↔away at configurable interval. Uses DDP set_status (NOT REST) for the status toggle. REST fallback only for message text (K1: DDP set_status has no message variant). Thread-safe: uses threading.Event for start/stop signalling. Coalesce: skips duplicate status calls (if already away and tick wants away). """ def __init__( self, pulse_interval: float = 1.5, _clamp_pulse: bool = True, ): """Initialize PulseController. Args: pulse_interval: Pulse interval in seconds (default 1.5). _clamp_pulse: If True, clamp to 0.5-30s. Set False for testing. """ if _clamp_pulse: self._pulse_interval: float = max(0.5, min(30.0, float(pulse_interval))) else: self._pulse_interval: float = float(pulse_interval) self._ddp: Optional[object] = None self._rest: Optional[object] = None self._thread: Optional[threading.Thread] = None self._running = threading.Event() self._paused = threading.Event() self._phase: bool = False # False=online, True=away self._last_sent_phase: Optional[bool] = None self._background_count: int = 0 self._cancel_pending: bool = False # P0-2: skip next tick flag # ── Public API ─────────────────────────────────────────────────────── def bind_ddp(self, ddp: object) -> None: """Bind a DDP client reference for set_status calls. Args: ddp: DDPClient instance with set_status(status) method. """ self._ddp = ddp def bind_rest(self, rest: object) -> None: """Bind a REST client reference for fallback status+message calls. Args: rest: RocketChatREST instance with _request method. """ self._rest = rest def set_background_count(self, count: int) -> None: """Set the background task count for heartbeat messages.""" self._background_count = count def start(self) -> None: """Start the pulse thread.""" if self._running.is_set(): return # P1-1: Check DDP availability before starting if self._ddp is None: logger.warning( "[pulse] PulseController.start() called without DDP bound — " "pulses will have no effect until bind_ddp() is called" ) self._running.set() self._paused.clear() self._phase = False # Start with online self._last_sent_phase = None self._thread = threading.Thread( target=self._pulse_loop, daemon=True, name="pulse-controller", ) self._thread.start() logger.info("[pulse] PulseController started (interval=%.1fs)", self._pulse_interval) def stop(self) -> None: """Stop the pulse thread and wait for it to finish.""" if not self._running.is_set(): return self._running.clear() self._paused.clear() if self._thread is not None and self._thread.is_alive(): self._thread.join(timeout=self._pulse_interval + 1) self._thread = None logger.info("[pulse] PulseController stopped") def pause(self) -> None: """Pause pulsing without stopping the thread (EC-2: reconnect race).""" self._paused.set() logger.debug("[pulse] PulseController paused") def resume(self) -> None: """Resume pulsing after pause (EC-2: reconnect race).""" self._paused.clear() logger.debug("[pulse] PulseController resumed") def is_running(self) -> bool: """Check if the pulse thread is running.""" return self._running.is_set() def cancel_pending(self) -> None: """Cancel any pending pulse tick (K2: EC-5). Called by PresenceEngine._set_presence when a higher-priority status fires while the PulseController is running. Sets a flag that the next tick will skip. """ self._cancel_pending = True logger.debug("[pulse] cancel_pending: next tick will be skipped") # ── Internal: Pulse Loop ───────────────────────────────────────────── def _pulse_loop(self) -> None: """Background thread: pulse between online and away.""" while self._running.is_set(): # Check if paused if self._paused.is_set(): time.sleep(0.1) continue self._pulse_tick() # Sleep for pulse interval, checking running flag periodically for _ in range(int(self._pulse_interval * 10)): if not self._running.is_set(): break if self._paused.is_set(): break time.sleep(0.1) def _pulse_tick(self) -> None: """Execute one pulse tick: toggle phase and send status.""" # P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence) if self._cancel_pending: self._cancel_pending = False logger.debug("[pulse] tick skipped (cancel_pending)") return # Toggle phase self._phase = not self._phase # Coalesce: skip if same phase as last sent if self._phase == self._last_sent_phase: return status = "away" if self._phase else "online" # Try DDP first (K1: DDP set_status has no message variant) if self._ddp is not None and getattr(self._ddp, 'connected', False): try: self._ddp.set_status(status) self._last_sent_phase = self._phase self._increment_telemetry() return except Exception as e: logger.debug("[pulse] DDP set_status failed: %s", e) # REST fallback for message text if self._rest is not None and getattr(self._rest, 'auth_token', None): try: msg = "" if self._phase: msg = _format_presence_message("heartbeat", background_count=self._background_count) self._rest._request( "POST", "/api/v1/users.setStatus", headers={ "X-Auth-Token": self._rest.auth_token, "X-User-Id": self._rest.user_id, }, data={"status": status, "message": msg} if msg else {"status": status}, ) self._last_sent_phase = self._phase self._increment_telemetry() except Exception as e: logger.debug("[pulse] REST setStatus failed: %s", e) def _increment_telemetry(self) -> None: """Increment the heartbeat_pulse telemetry counter. NOTE: Coupled to archivar.routing_telemetry.routing_telemetry. This is a cross-module dependency that should be refactored to use a shared telemetry interface or event bus. """ try: from archivar.routing_telemetry import routing_telemetry routing_telemetry.heartbeat_pulse += 1 except Exception: pass # ═══════════════════════════════════════════════════════════════════════════ # DetectionTimer — erkennt Hintergrund-Agenten (10s Intervall) # ═══════════════════════════════════════════════════════════════════════════ class DetectionTimer: """Detects whether background agents are active. Checks gateway_state.json for active_agents > 1. Falls back to pgrep for 'hermes chat --profile' processes. Calls on_change callback when detection state changes. """ def __init__( self, gateway_state_path: str = "", detection_interval: float = 10.0, on_change: Optional[Callable[[bool], None]] = None, ): """Initialize DetectionTimer. Args: gateway_state_path: Path to gateway_state.json. detection_interval: Check interval in seconds (default 10). on_change: Callback(is_active) when detection state changes. """ if not gateway_state_path: gateway_state_path = os.environ.get( "ROCKETCHAT_GATEWAY_STATE_PATH", os.path.expanduser("~/.hermes/gateway_state.json"), ) self._gateway_state_path = gateway_state_path self._detection_interval = detection_interval self._on_change = on_change self._thread: Optional[threading.Thread] = None self._running = threading.Event() self._last_result: Optional[bool] = False # Start with False to avoid spurious first callback self._check_count: int = 0 # P0-1: tick counter for diagnostic logging def start(self) -> None: """Start the detection timer thread.""" if self._running.is_set(): return self._running.set() self._thread = threading.Thread( target=self._detection_loop, daemon=True, name="detection-timer", ) self._thread.start() logger.info("[detection] DetectionTimer started (interval=%.1fs)", self._detection_interval) def stop(self) -> None: """Stop the detection timer thread.""" if not self._running.is_set(): return self._running.clear() if self._thread is not None and self._thread.is_alive(): self._thread.join(timeout=self._detection_interval + 1) self._thread = None logger.info("[detection] DetectionTimer stopped") def check(self) -> bool: """Check if background agents are active. pgrep is the PRIMARY signal — always executed, regardless of gateway_state. gateway_state is SECONDARY — read only for diagnostic logging, never for decisions. Returns: True if pgrep finds other hermes chat processes (self-excluded), False otherwise. """ self._check_count += 1 self._increment_telemetry() result = False pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error # ── PRIMARY: pgrep — ALWAYS run ────────────────────────────────── try: own_pid = os.getpid() proc = subprocess.run( ["pgrep", "-f", "hermes chat --profile"], capture_output=True, text=True, timeout=5, ) # Parse PIDs and self-exclude raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()] all_pids = [int(l) for l in raw_lines if l.isdigit()] pids = [p for p in all_pids if p != own_pid] pgrep_pids = len(pids) result = pgrep_pids > 0 except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: logger.debug("[detection] pgrep failed: %s", e) # pgrep_pids stays -1 (error sentinel) # ── SECONDARY: gateway_state — diagnostic only ──────────────────── gateway_active = 0 try: if os.path.exists(self._gateway_state_path): with open(self._gateway_state_path, 'r') as f: state = json.load(f) gateway_active = state.get("active_agents", 0) except (json.JSONDecodeError, IOError, OSError) as e: logger.debug("[detection] gateway_state.json read failed: %s", e) # ── Log: both signals, result ───────────────────────────────────── pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error" logger.info( "[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s", self._check_count, pgrep_str, gateway_active, "active" if result else "inactive", ) # Notify on change (P1-2: callback fires from check() itself) if result != self._last_result and self._on_change is not None: try: logger.info( "[detection] state changed: %s→%s", "active" if self._last_result else "inactive", "active" if result else "inactive", ) self._on_change(result) except Exception as e: logger.debug("[detection] on_change callback failed: %s", e) self._last_result = result return result def _detection_loop(self) -> None: """Background thread: periodically check for background agents.""" tick = 0 while self._running.is_set(): tick += 1 try: logger.info( "[detection] tick #%d (interval=%.1fs)", tick, self._detection_interval, ) self.check() # check() now handles logging + callback except Exception as e: logger.debug("[detection] check failed: %s", e) # Sleep for detection interval for _ in range(int(self._detection_interval * 10)): if not self._running.is_set(): break time.sleep(0.1) def _increment_telemetry(self) -> None: """Increment the heartbeat_detection telemetry counter. NOTE: Coupled to archivar.routing_telemetry.routing_telemetry. This is a cross-module dependency that should be refactored to use a shared telemetry interface or event bus. """ try: from archivar.routing_telemetry import routing_telemetry routing_telemetry.heartbeat_detection += 1 except Exception: pass