diff --git a/plugin/adapter.py b/plugin/adapter.py index 402fd73..4a46979 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -859,6 +859,25 @@ class RocketChatAdapter(BasePlatformAdapter): lines.append(f" Keywords Kontext: {kwctx}") return "\n".join(lines) + def _on_ddp_connected(self) -> None: + """Callback when DDP connection is established. + + Sets initial online status and binds DDP to PulseController + if PresenceEngine is active (EC-1: on_connected_cb race). + """ + if self.ddp: + self.ddp.set_status("online") + # V8.6: PulseController DDP-Bindung nach Connect (EC-1) + if hasattr(self, '_presence_engine') and self._presence_engine is not None: + try: + from archivar.presence_engine import PulseController + if hasattr(self._presence_engine, '_pulse_controller') and \ + isinstance(self._presence_engine._pulse_controller, PulseController): + self._presence_engine._pulse_controller.bind_ddp(self.ddp) + logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)") + except Exception as e: + logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e) + def _on_ddp_room_event(self, event: dict) -> None: """A1b: Callback für DDP rooms-changed Events. @@ -1217,7 +1236,7 @@ class RocketChatAdapter(BasePlatformAdapter): host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0] self.ddp = DDPClient( host=host, - on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None, + on_connected_cb=self._on_ddp_connected, on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events ) if not self.ddp.connect_and_login(self._auth_token): @@ -1450,7 +1469,7 @@ class RocketChatAdapter(BasePlatformAdapter): host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0] self.ddp = DDPClient( host=host, - on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None, + on_connected_cb=self._on_ddp_connected, on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events (P0-3) ) if not self.ddp.connect_and_login(self._auth_token): diff --git a/plugin/archivar/presence_engine.py b/plugin/archivar/presence_engine.py index 6e2d1c0..d83c457 100644 --- a/plugin/archivar/presence_engine.py +++ b/plugin/archivar/presence_engine.py @@ -12,11 +12,12 @@ 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 +from typing import Optional, Dict, Callable logger = logging.getLogger(__name__) # Ensure presence_engine logs are visible in journalctl by adding a stderr handler @@ -233,6 +234,9 @@ class PresenceEngine: 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 @@ -460,3 +464,345 @@ class PresenceEngine: 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). + """ + if hasattr(self, '_pulse_controller') and self._pulse_controller is not None: + 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 + if hasattr(self, '_pulse_controller') and self._pulse_controller is not None: + 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 + + # ── 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 + 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. + """ + # Mark that the next tick should be skipped + # (the loop checks _running before each tick anyway) + pass # The loop naturally checks _running; cancel is implicit via pause/stop + + # ── 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.""" + # 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.""" + 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.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] = None + + 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. + + Returns: + True if active_agents > 1 (background agent active), + False otherwise. + """ + # Increment detection telemetry + self._increment_telemetry() + + # Try gateway_state.json first + try: + if os.path.exists(self._gateway_state_path): + with open(self._gateway_state_path, 'r') as f: + state = json.load(f) + active = state.get("active_agents", 0) + return active > 1 + except (json.JSONDecodeError, IOError, OSError) as e: + logger.debug("[detection] gateway_state.json read failed: %s", e) + + # Fallback: pgrep + try: + result = subprocess.run( + ["pgrep", "-f", "hermes chat --profile"], + capture_output=True, + text=True, + timeout=5, + ) + # Count lines: each line is a PID + lines = [l for l in result.stdout.strip().split("\n") if l] + return len(lines) > 1 + except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e: + logger.debug("[detection] pgrep fallback failed: %s", e) + return False + + def _detection_loop(self) -> None: + """Background thread: periodically check for background agents.""" + while self._running.is_set(): + try: + result = self.check() + + # Notify on change + if result != self._last_result and self._on_change is not None: + try: + self._on_change(result) + except Exception as e: + logger.debug("[detection] on_change callback failed: %s", e) + + self._last_result = result + 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.""" + try: + from archivar.routing_telemetry import routing_telemetry + routing_telemetry.heartbeat_detection += 1 + except Exception: + pass diff --git a/plugin/archivar/routing_telemetry.py b/plugin/archivar/routing_telemetry.py index b173bcb..13b7603 100644 --- a/plugin/archivar/routing_telemetry.py +++ b/plugin/archivar/routing_telemetry.py @@ -49,6 +49,9 @@ class RoutingTelemetry: self._enabled: bool = self._read_feature_flag() self._records: List[Dict[str, object]] = [] self._start_time: float = 0.0 + # Heartbeat-Pulsierung Telemetrie + self.heartbeat_pulse: int = 0 + self.heartbeat_detection: int = 0 @staticmethod def _read_feature_flag() -> bool: diff --git a/plugin/archivar/tests/test_presence_engine.py b/plugin/archivar/tests/test_presence_engine.py index f143d72..9cb811a 100644 --- a/plugin/archivar/tests/test_presence_engine.py +++ b/plugin/archivar/tests/test_presence_engine.py @@ -584,3 +584,570 @@ class TestOnboardingAskActiveStatusIndikator: assert data["rooms"]["room123"]["active_status_indikator"] is True finally: os.unlink(map_path) + + +# ═══════════════════════════════════════════════════════════════════════════ +# Phase 3: PulseController (DDP-basiert, 1.5s Intervall) — Tests 17-19 +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestPulseControllerStartStop: + """Test 17: PulseController start/stop lifecycle.""" + + def test_pulse_controller_start(self): + """PulseController startet den Puls-Thread und setzt running=True.""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + pc.start() + + assert pc.is_running() + time.sleep(0.15) # ~3 Zyklen bei 0.05s + + pc.stop() + assert not pc.is_running() + + def test_pulse_controller_stop_cleans_up(self): + """PulseController.stop() stoppt den Thread und setzt running=False.""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + pc.start() + time.sleep(0.1) + + pc.stop() + time.sleep(0.1) + + # Nach stop: kein running mehr + assert not pc.is_running() + # Thread sollte beendet sein + assert pc._thread is None or not pc._thread.is_alive() + + +class TestPulseControllerBindDdp: + """Test 18: PulseController.bind_ddp() — DDP-Referenz setzen.""" + + def test_bind_ddp_sets_reference(self): + """bind_ddp() speichert die DDP-Referenz für set_status-Aufrufe.""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + assert pc._ddp is None + + pc.bind_ddp(mock_ddp) + assert pc._ddp is mock_ddp + + def test_bind_ddp_after_start(self): + """bind_ddp() kann auch nach start() aufgerufen werden (EC-1).""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + # Start ohne DDP — sollte nicht crashen + pc.start() + time.sleep(0.05) + + # DDP nachträglich binden + pc.bind_ddp(mock_ddp) + time.sleep(0.15) + + pc.stop() + # Sollte jetzt Calls haben (nach bind_ddp) + assert mock_ddp.set_status.call_count >= 1 + + +class TestPulseControllerDdpOnly: + """Test 19: PulseController sendet NUR via DDP, nicht REST.""" + + def test_pulse_uses_ddp_not_rest(self): + """PulseController verwendet DDP set_status, nicht REST _send_rest.""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + mock_rest = MagicMock() + mock_rest.auth_token = "token" + mock_rest.user_id = "user123" + mock_rest._request = MagicMock(return_value={"success": True}) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + # Kein REST-Client gesetzt + pc.start() + time.sleep(0.2) + pc.stop() + + # DDP wurde aufgerufen + assert mock_ddp.set_status.call_count >= 2 + # REST wurde NICHT aufgerufen + mock_rest._request.assert_not_called() + + +# ═══════════════════════════════════════════════════════════════════════════ +# Phase 3b: PulseController DDP/REST Fallback (Tests 23-25) +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestPulseControllerDdpOnlySend: + """Test 23: DDP-Only-Send — set_status ohne Message.""" + + def test_ddp_only_send_no_message(self): + """DDP set_status wird ohne message-Parameter aufgerufen (K1).""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + pc.start() + time.sleep(0.2) + pc.stop() + + # Alle set_status Calls prüfen + for call_args in mock_ddp.set_status.call_args_list: + args, kwargs = call_args + # Sollte nur "online" oder "away" sein, keine message + assert args[0] in ("online", "away") + # Kein message-Parameter (DDP set_status hat keine Message-Variante) + assert "message" not in kwargs + + +class TestPulseControllerRestFallback: + """Test 24: REST-Only-Fallback — wenn DDP None, REST für Message-Text.""" + + def test_rest_fallback_when_ddp_none(self): + """Wenn kein DDP gebunden, wird REST für Status+Message verwendet.""" + from plugin.archivar.presence_engine import PulseController + + mock_rest = MagicMock() + mock_rest.auth_token = "token" + mock_rest.user_id = "user123" + mock_rest._request = MagicMock(return_value={"success": True}) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + # Kein DDP gebunden + pc.bind_rest(mock_rest) + pc.start() + time.sleep(0.2) + pc.stop() + + # REST wurde aufgerufen + assert mock_rest._request.call_count >= 2 + + +class TestPulseControllerBothDefective: + """Test 25: Beide-defekt — kein DDP, kein REST → kein Crash.""" + + def test_both_defective_no_crash(self): + """Wenn weder DDP noch REST verfügbar, crasht PulseController nicht.""" + from plugin.archivar.presence_engine import PulseController + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + # Kein DDP, kein REST + pc.start() + time.sleep(0.2) + pc.stop() + + # Sollte nicht gecrasht sein + assert not pc.is_running() + + +# ═══════════════════════════════════════════════════════════════════════════ +# Phase 3c: PulseController Coalesce/Phase/Last-Sent (Tests 26-28) +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestPulseControllerCoalesceSkip: + """Test 26: Coalesce-Skip — wenn Status bereits away und Tick will away → skip.""" + + def test_coalesce_skip_duplicate_away(self): + """Wenn letzter gesendeter Status 'away' ist, wird kein doppelter away-Call gemacht.""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + + # Manuell Phase auf 'away' setzen und last_sent auf 'away' + pc._phase = True # away + pc._last_sent_phase = True # last was away + + # Simuliere einen Tick + pc._pulse_tick() + + # Sollte KEINEN Call gemacht haben (coalesce skip) + call_count_after_skip = mock_ddp.set_status.call_count + + # Jetzt Phase wechseln + pc._phase = False # online + pc._pulse_tick() + + # Jetzt sollte ein Call gemacht worden sein + assert mock_ddp.set_status.call_count > call_count_after_skip + + +class TestPulseControllerPhaseToggle: + """Test 27: Phase-Toggle — online↔away zyklisch.""" + + def test_phase_toggles_correctly(self): + """Jeder Tick toggled die Phase zwischen online und away.""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + + # Start: phase=False (online) + assert pc._phase is False + + # Tick 1: online -> away + pc._pulse_tick() + assert pc._phase is True # away + + # Tick 2: away -> online + pc._pulse_tick() + assert pc._phase is False # online + + # Tick 3: online -> away + pc._pulse_tick() + assert pc._phase is True # away + + +class TestPulseControllerLastSentPhase: + """Test 28: last_sent_phase wird nach jedem erfolgreichen Send aktualisiert.""" + + def test_last_sent_phase_updated(self): + """Nach erfolgreichem DDP-Call wird last_sent_phase aktualisiert.""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + + # Initial: last_sent_phase=None + assert pc._last_sent_phase is None + + # Tick 1: online -> away (toggle from False to True) + pc._pulse_tick() + assert pc._last_sent_phase is True # away + + # Tick 2: away -> online + pc._pulse_tick() + assert pc._last_sent_phase is False # online + + +# ═══════════════════════════════════════════════════════════════════════════ +# Phase 4: DetectionTimer (Tests 20-22) +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestDetectionTimerGatewayState: + """Test 20: DetectionTimer liest gateway_state.json.""" + + def test_detection_from_gateway_state(self): + """DetectionTimer erkennt aktive Agents aus gateway_state.json.""" + from plugin.archivar.presence_engine import DetectionTimer + import tempfile + import json + + # Erstelle gateway_state.json mit active_agents > 1 + state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]} + with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: + json.dump(state, f) + state_path = f.name + + try: + dt = DetectionTimer( + gateway_state_path=state_path, + detection_interval=0.1, + ) + result = dt.check() + assert result is True # active_agents > 1 + finally: + os.unlink(state_path) + + def test_detection_single_agent(self): + """DetectionTimer erkennt wenn nur ein Agent aktiv ist.""" + from plugin.archivar.presence_engine import DetectionTimer + import tempfile + import json + + state = {"active_agents": 1, "profiles": ["default"]} + with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: + json.dump(state, f) + state_path = f.name + + try: + dt = DetectionTimer( + gateway_state_path=state_path, + detection_interval=0.1, + ) + result = dt.check() + assert result is False # nur ein Agent + finally: + os.unlink(state_path) + + +class TestDetectionTimerPgrepFallback: + """Test 21: DetectionTimer pgrep-Fallback.""" + + def test_pgrep_fallback_when_no_gateway_state(self): + """Wenn gateway_state.json nicht existiert, wird pgrep verwendet.""" + from plugin.archivar.presence_engine import DetectionTimer + + dt = DetectionTimer( + gateway_state_path="/tmp/nonexistent_gateway_state.json", + detection_interval=0.1, + ) + # Sollte nicht crashen, sondern pgrep-Fallback nutzen + result = dt.check() + # Ergebnis ist bool (True/False) + assert isinstance(result, bool) + + def test_pgrep_fallback_returns_bool(self): + """pgrep-Fallback liefert immer bool zurück.""" + from plugin.archivar.presence_engine import DetectionTimer + + dt = DetectionTimer( + gateway_state_path="/tmp/nonexistent_gateway_state.json", + detection_interval=0.1, + ) + result = dt.check() + assert result is True or result is False + + +class TestDetectionTimerIntegration: + """Test 22: DetectionTimer start/stop + Callback.""" + + def test_detection_timer_start_stop(self): + """DetectionTimer startet und stoppt korrekt.""" + from plugin.archivar.presence_engine import DetectionTimer + + callback_results = [] + + def on_detection_change(is_active): + callback_results.append(is_active) + + dt = DetectionTimer( + gateway_state_path="/tmp/nonexistent_gateway_state.json", + detection_interval=0.1, + on_change=on_detection_change, + ) + dt.start() + time.sleep(0.35) # ~3 Checks bei 0.1s + dt.stop() + + # Mindestens 1 Callback (erster Check: None→False) + assert len(callback_results) >= 1 + # Alle Ergebnisse sind bool + for r in callback_results: + assert isinstance(r, bool) + + +# ═══════════════════════════════════════════════════════════════════════════ +# Phase 5: Edge Cases (Tests 29-32) +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestEdgeCaseOnConnectedRace: + """Test 29: EC-1 — on_connected_cb race: PulseController startet vor DDP verfügbar.""" + + def test_pulse_starts_before_ddp_available(self): + """PulseController startet, DDP wird erst später gebunden (EC-1).""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + # Starte Pulse VOR DDP-Bindung + pc.start() + time.sleep(0.1) + + # DDP wird erst jetzt verfügbar (simuliert on_connected_cb) + pc.bind_ddp(mock_ddp) + time.sleep(0.2) + + pc.stop() + + # Sollte nach bind_ddp Calls gemacht haben + assert mock_ddp.set_status.call_count >= 1 + + +class TestEdgeCaseReconnectRace: + """Test 30: EC-2 — reconnect race: DDP weg → Pulse pausiert, DDP zurück → Pulse fortsetzen.""" + + def test_reconnect_race_pause_resume(self): + """DDP disconnected → Pulse pausiert, DDP reconnected → Pulse fortsetzen (EC-2).""" + from plugin.archivar.presence_engine import PulseController + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + pc.start() + time.sleep(0.15) + + calls_before_pause = mock_ddp.set_status.call_count + + # Simuliere DDP-Verlust + pc.pause() + time.sleep(0.15) + + # Keine neuen Calls während Pause + assert mock_ddp.set_status.call_count == calls_before_pause + + # Simuliere Reconnect + pc.resume() + time.sleep(0.15) + + # Neue Calls nach Resume + assert mock_ddp.set_status.call_count > calls_before_pause + + pc.stop() + + +class TestEdgeCaseOnAgentBusy: + """Test 31: on_agent_busy() — pausiert Pulse, setzt busy (rot).""" + + def test_on_agent_busy_pauses_pulse(self): + """on_agent_busy() pausiert den PulseController und setzt busy.""" + from plugin.archivar.presence_engine import PresenceEngine, PulseController + + mock_rest = MagicMock() + mock_rest.auth_token = "token" + mock_rest.user_id = "user123" + mock_rest._request = MagicMock(return_value={"success": True}) + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + engine = PresenceEngine(rest=mock_rest, enabled=True, pulse_interval=0.05, _clamp_pulse=False) + + # PulseController manuell starten (simuliert background_tasks > 0) + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + pc.start() + engine._pulse_controller = pc + engine._background_tasks = 3 + + time.sleep(0.1) + assert pc.is_running() + + # on_agent_busy: pausiert Pulse + engine.on_agent_busy(room_name="#Test") + + time.sleep(0.1) + # Pulse sollte pausiert sein + assert not pc.is_running() or pc._paused.is_set() + + # Busy-Status via REST gesetzt + engine._flush_presence() + busy_calls = [ + c for c in mock_rest._request.call_args_list + if c[1].get("data", {}).get("status") == "busy" + ] + assert len(busy_calls) >= 1 + + def test_on_agent_busy_resume_after_task(self): + """Nach busy-Ende: Pulse wird fortgesetzt wenn noch background_tasks > 0.""" + from plugin.archivar.presence_engine import PresenceEngine, PulseController + + mock_rest = MagicMock() + mock_rest.auth_token = "token" + mock_rest.user_id = "user123" + mock_rest._request = MagicMock(return_value={"success": True}) + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + engine = PresenceEngine(rest=mock_rest, enabled=True, pulse_interval=0.05, _clamp_pulse=False) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + pc.start() + engine._pulse_controller = pc + engine._background_tasks = 3 + + # on_agent_busy + engine.on_agent_busy(room_name="#Test") + time.sleep(0.1) + + # Task beendet → decrement + update + engine._active_tasks = 0 + engine.decrement_active_tasks() + engine.update_presence() + + time.sleep(0.2) + + # Pulse sollte wieder laufen (background_tasks noch > 0) + assert pc.is_running() or engine._pulse_controller is not None + + +class TestEdgeCaseOnMessageReceived: + """Test 32: on_message_received() — wie on_agent_busy, pausiert Pulse.""" + + def test_on_message_received_pauses_pulse(self): + """on_message_received() verhält sich wie on_agent_busy().""" + from plugin.archivar.presence_engine import PresenceEngine, PulseController + + mock_rest = MagicMock() + mock_rest.auth_token = "token" + mock_rest.user_id = "user123" + mock_rest._request = MagicMock(return_value={"success": True}) + + mock_ddp = MagicMock() + mock_ddp.connected = True + mock_ddp.set_status = MagicMock(return_value=True) + + engine = PresenceEngine(rest=mock_rest, enabled=True, pulse_interval=0.05, _clamp_pulse=False) + + pc = PulseController(pulse_interval=0.05, _clamp_pulse=False) + pc.bind_ddp(mock_ddp) + pc.start() + engine._pulse_controller = pc + engine._background_tasks = 3 + + time.sleep(0.1) + assert pc.is_running() + + # on_message_received → wie on_agent_busy + engine.on_message_received(room_name="#Test") + + time.sleep(0.1) + assert not pc.is_running() or pc._paused.is_set()