9 Commits

Author SHA1 Message Date
Bernd (Hermes) c0ae37f79a docs(P1-2-O2): Phase 4 — set_status deprecated, PulseController loop-bound logging 2026-07-24 05:51:48 +02:00
Bernd (Hermes) c942968328 test(P1-2-O2): Phase 3 — 14 neue Tests für await-Semantik 2026-07-24 05:51:01 +02:00
Bernd (Hermes) b6a9c9d8c3 feat(P1-2-O2): Phase 2 — PulseController async-await via run_coroutine_threadsafe 2026-07-24 05:48:48 +02:00
Bernd (Hermes) 42cb259bce feat(P1-2-O2): Phase 1 — DDPClient Future-Store + result-Handler (no behavior change) 2026-07-24 05:46:24 +02:00
Bernd (Hermes) 9098a760dc fix(P1-1): PulseController Logging-Volumen reduziert — Tick-Logs von INFO auf DEBUG 2026-07-24 05:10:23 +02:00
Bernd (Hermes) d964d7d5b5 fix(P1-4): Status-Farben und Flughafen-Prinzip in ::hilfe und ::status 2026-07-24 05:08:43 +02:00
Bernd (Hermes) 573335cc8d fix(P2-2): Butler gelber Status (away) bei Klärungsflow
PresenceEngine:
- Neues State-Feld _clarification_pending: Set[str]
- Methoden set_clarification_pending(room_id) / clear_clarification_pending(room_id)
- Neuer Priority-Slot 3b in update_presence(): nach Move-Request, vor Active-Tasks
- _format_presence_message: neuer Status 'away_clarification' → 'Klärung läuft — wartet auf Antwort'

ArchivarMessageHandler:
- set_presence_engine() Setter für PresenceEngine-Referenz
- _send_clarify: set_clarification_pending VOR send, clear im finally (try/finally)

adapter.py:
- set_presence_engine() nach PresenceEngine-Init aufgerufen (Z.821)

5 neue Tests: TestPresenceClarificationPending
2026-07-24 05:03:40 +02:00
Bernd (Hermes) 342a1cddbb fix(P2-1): [FILE]-Block-Stripping nach fehlgeschlagenen Downloads in _download_and_inline_files
- Non-greedy Regex entfernt alle übrigen [FILE]...Download:... Blöcke nach der Download-Schleife
- Verhindert dass der Agent Download-URLs sieht wenn Downloads fehlschlagen
- 3 neue Tests: TestFileBlockStripping (fail-only, mixed success/fail, unicode filenames)
2026-07-24 04:57:15 +02:00
Bernd (Hermes) c0c505e73d fix(P1-3): None-Guard für _presence_engine in _send_onboarding_message und _complete_onboarding
- _send_onboarding_message (Z.4322-4323): _has_presence-Guard vor set_onboarding_active/update_presence
- _complete_onboarding (Z.5867-5868): _has_presence-Guard vor set_onboarding_active/update_presence
- Pattern konsistent mit bestehenden Guards an Z.1675/1927/2568/2868
- 2 neue Tests: TestPresenceEngineNoneGuard (test_send_onboarding_message_without_presence_engine, test_complete_onboarding_without_presence_engine)
2026-07-24 04:55:31 +02:00
8 changed files with 1359 additions and 19 deletions
+272 -4
View File
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
"""
import asyncio
import concurrent.futures
import contextvars
import json
import logging
@@ -270,6 +271,24 @@ class RocketChatREST:
return bool(r and r.get("success"))
class DDPTimeout(Exception):
"""Raised when a DDP method call times out waiting for a result message."""
pass
class DDPServerError(Exception):
"""Raised when the DDP server returns an error for a method call."""
def __init__(self, error_data: dict):
self.error_data = error_data
super().__init__(f"DDP server error: {error_data}")
class DDPNotConnected(Exception):
"""Raised when a DDP method is called but the client is not connected."""
pass
class DDPClient:
PING_INTERVAL = 8.0
@@ -290,6 +309,11 @@ class DDPClient:
self._session: Optional[str] = None
self._reconnect_attempt = 0
self._last_rx_time = 0.0
# P1-2 O-2: Future-Store für await-Semantik
self._pending_results: Dict[str, concurrent.futures.Future] = {}
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._result_lock = threading.Lock()
self._msg_seq: int = 0
def _create_socket(self) -> socket.socket:
ctx = ssl.create_default_context()
@@ -347,6 +371,7 @@ class DDPClient:
import select
self.sock.settimeout(1.0)
last_ping = time.time()
last_sweep = time.time()
while self._running:
try:
if time.time() - last_ping >= self.PING_INTERVAL:
@@ -355,6 +380,10 @@ class DDPClient:
last_ping = time.time()
except Exception:
break
# P1-2 O-2: Periodic sweep of stale pending results (every 5s)
if time.time() - last_sweep >= 5.0:
self._sweep_pending_results()
last_sweep = time.time()
readable, _, _ = select.select([self.sock], [], [], 1.0)
if not readable:
continue
@@ -396,6 +425,15 @@ class DDPClient:
self._on_connected()
elif msg_type == "ping":
self._send_json({"msg": "pong"})
# P1-2 O-2: Handle DDP result messages (resolve pending Futures)
elif msg_type == "result":
self._handle_result_message(data)
# P1-2 O-2: Handle DDP updated messages (log only, result follows)
elif msg_type == "updated":
logger.debug(
"DDP: updated message received (id=%s)",
data.get("id", "?"),
)
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
fields = data.get("fields", {})
args = fields.get("args", [])
@@ -541,13 +579,171 @@ class DDPClient:
room_id[:12], event["name"], event["type"])
self._on_room_event(event)
def _handle_result_message(self, data: dict) -> None:
"""P1-2 O-2: Resolve pending Futures when a DDP result message arrives.
Called from the reader thread (PURE SYNC — no asyncio calls here).
Looks up the msg_id in _pending_results and resolves the Future
with the result or error.
Args:
data: The parsed DDP JSON message with msg='result'.
"""
msg_id = data.get("id", "")
if not msg_id:
return
with self._result_lock:
future = self._pending_results.pop(msg_id, None)
if future is None:
# No pending future for this msg_id — likely a result for
# a fire-and-forget call (legacy set_status) or already timed out
return
if future.done():
# Already resolved (e.g., by timeout sweep)
return
if "error" in data:
future.set_exception(DDPServerError(data["error"]))
else:
future.set_result(data.get("result", True))
def set_status(self, status: str) -> bool:
"""Set the user presence status via DDP (fire-and-forget, no await).
.. deprecated::
Use :meth:`set_status_async` for await-semantics with timeout
and error handling. This method remains for legacy callers
(on_connected callback, idle timer) that don't need the result.
Returns:
True if the frame was sent, False if not connected.
"""
if not self.connected:
return False
method = "UserPresence:setDefaultStatus"
self._send_json({"msg": "method", "method": method, "params": [status], "id": f"st{int(time.time()*1000)}"})
return True
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
"""Bind the asyncio event loop for async operations.
Called by the adapter after the event loop is running.
The loop reference is used by set_status_async to bridge
between the DDP reader thread and the asyncio world.
Args:
loop: The running asyncio event loop.
"""
self._loop = loop
async def set_status_async(self, status: str, timeout: float = 2.0) -> bool:
"""Set the user presence status via DDP with await-semantics.
Sends a DDP method call and waits for the corresponding result
message from the server. Uses a Future registered in
_pending_results that the reader thread resolves when the
result message arrives.
Args:
status: Rocket.Chat status ('online', 'away', 'busy').
timeout: Maximum seconds to wait for the result (default 2.0).
Returns:
True if the server confirmed the status change.
Raises:
DDPNotConnected: If the DDP client is not connected.
DDPTimeout: If no result message arrives within timeout.
DDPServerError: If the server returns an error for the call.
"""
if not self.connected:
raise DDPNotConnected("DDP client is not connected")
# Generate unique msg_id with sequence counter to prevent collisions
with self._result_lock:
self._msg_seq += 1
msg_id = f"st{int(time.time() * 1000)}_{self._msg_seq}"
# Create Future and register it
future: concurrent.futures.Future = concurrent.futures.Future()
with self._result_lock:
self._pending_results[msg_id] = future
try:
# Send the DDP method call
method = "UserPresence:setDefaultStatus"
self._send_json({
"msg": "method",
"method": method,
"params": [status],
"id": msg_id,
})
# Await the future — bridge concurrent.Future to asyncio with timeout
result = await asyncio.wait_for(
asyncio.wrap_future(future),
timeout=timeout,
)
# If we get here, the reader thread resolved the future
if result is False:
raise DDPServerError({"error": "server returned false"})
return True
except asyncio.TimeoutError:
# Clean up the pending future
with self._result_lock:
self._pending_results.pop(msg_id, None)
raise DDPTimeout(
f"setDefaultStatus('{status}') timed out after {timeout}s"
)
except (DDPTimeout, DDPServerError, DDPNotConnected):
# Re-raise our own exceptions without wrapping
with self._result_lock:
self._pending_results.pop(msg_id, None)
raise
except Exception:
# Clean up on any other exception
with self._result_lock:
self._pending_results.pop(msg_id, None)
raise
def _sweep_pending_results(self) -> None:
"""Sweep through _pending_results and cancel Futures older than 2s.
Called periodically from the reader loop to prevent memory leaks
from method calls whose result messages never arrive.
"""
now = time.time()
stale_ids = []
with self._result_lock:
for msg_id, future in list(self._pending_results.items()):
# msg_id format: st<TIMESTAMP_MS>_<SEQ>
# Extract timestamp from msg_id
try:
ts_part = msg_id[2:].split("_")[0] # strip 'st' prefix
ts_ms = int(ts_part)
ts_s = ts_ms / 1000.0
if now - ts_s > 2.0:
stale_ids.append(msg_id)
except (ValueError, IndexError):
# Malformed msg_id — clean it up
stale_ids.append(msg_id)
for msg_id in stale_ids:
future = self._pending_results.pop(msg_id, None)
if future is not None and not future.done():
future.cancel()
if stale_ids:
logger.debug(
"DDP: Swept %d stale pending results (age > 2s)",
len(stale_ids),
)
def disconnect(self):
self._running = False
if self.sock:
@@ -818,6 +1014,9 @@ class RocketChatAdapter(BasePlatformAdapter):
self._presence_engine._pulse_controller.bind_rest(self.rest)
if self.ddp:
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
# P2-2: PresenceEngine an ArchivarMessageHandler weiterreichen
if self.archivar is not None:
self.archivar.set_presence_engine(self._presence_engine)
logger.info(
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s, pulse_interval=%.1fs)",
_presence_enabled,
@@ -1247,6 +1446,24 @@ class RocketChatAdapter(BasePlatformAdapter):
self._rooms = self.rest.get_rooms()
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
# P1-2 O-2: Bind asyncio loop to DDPClient and PulseController
try:
loop = asyncio.get_running_loop()
self.ddp.bind_loop(loop)
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
self._presence_engine._pulse_controller.bind_loop(loop)
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
"(loop=%s)",
id(loop),
)
except RuntimeError:
# No running event loop (e.g., in tests) — graceful degradation
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
"(no running event loop)"
)
# A1b: Subscribe to stream-notify-room for rooms-changed events
if self.ddp.connected:
room_events_sub = self.ddp.subscribe_room_events()
@@ -1478,6 +1695,23 @@ class RocketChatAdapter(BasePlatformAdapter):
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
return False
# P1-2 O-2: Re-bind asyncio loop to new DDPClient and PulseController
try:
loop = asyncio.get_running_loop()
self.ddp.bind_loop(loop)
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
self._presence_engine._pulse_controller.bind_loop(loop)
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
"(reconnect, loop=%s)",
id(loop),
)
except RuntimeError:
logger.info(
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
"(reconnect, no running event loop)"
)
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
if self.ddp.connected:
room_events_sub = self.ddp.subscribe_room_events()
@@ -3170,9 +3404,20 @@ class RocketChatAdapter(BasePlatformAdapter):
async def _cmd_hilfe(self, room_id: str, args: str) -> str:
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
from archivar.inline_commands import build_help_text
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
presence_enabled = None
current_status = "online"
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
if _has_presence:
presence_enabled = self._presence_engine.is_enabled()
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
return build_help_text(
self._inline_commands,
room_map_summary=self._room_map_summary,
presence_enabled=presence_enabled,
current_status=current_status,
)
async def _cmd_status(self, room_id: str, args: str) -> str:
@@ -3192,12 +3437,25 @@ class RocketChatAdapter(BasePlatformAdapter):
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
onboarding_active = self.archivar._stats.get("onboarding_active", False)
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
presence_enabled = None
current_status = "online"
pulse_active = False
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
if _has_presence:
presence_enabled = self._presence_engine.is_enabled()
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
pulse_active = self._presence_engine._pulse_controller.is_running()
return build_status_text(
room_count=room_count,
archivar_active=archivar_active,
butler_mode=butler_mode,
onboarding_active=onboarding_active,
room_map_summary=self._room_map_summary,
presence_enabled=presence_enabled,
current_status=current_status,
pulse_active=pulse_active,
)
async def _cmd_reset(self, room_id: str, args: str) -> str:
@@ -4319,8 +4577,10 @@ class RocketChatAdapter(BasePlatformAdapter):
if _MULTIROOM() and self.archivar is not None:
self.archivar._stats["onboarding_active"] = True
# ── V8.6: PresenceEngine — Onboarding start → away ──
self._presence_engine.set_onboarding_active(True)
self._presence_engine.update_presence()
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
if _has_presence:
self._presence_engine.set_onboarding_active(True)
self._presence_engine.update_presence()
# Bug 3 fix: Robuster Zugriff auf _build_custom_buttons
_build = self._get_build_custom_buttons()
@@ -5864,8 +6124,10 @@ class RocketChatAdapter(BasePlatformAdapter):
self.archivar._state.clear_onboarding_state()
self._onboarding_state = {}
# ── V8.6: PresenceEngine — Onboarding end → online ──
self._presence_engine.set_onboarding_active(False)
self._presence_engine.update_presence()
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
if _has_presence:
self._presence_engine.set_onboarding_active(False)
self._presence_engine.update_presence()
# F8: State Machine — AWAITING_TEST → ACTIVE
if hasattr(self, '_onboarding_sm'):
self._onboarding_sm.advance_test()
@@ -6002,6 +6264,12 @@ class RocketChatAdapter(BasePlatformAdapter):
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
text += block
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
# P2-1: Alle übrigen [FILE]-Blöcke entfernen (fehlgeschlagene Downloads)
# Non-greedy Pattern: erfasst [FILE]...Download:... bis zum nächsten \n
# re.DOTALL damit Zeilenumbrüche innerhalb des Blocks matchen
text = re.sub(
r'\[FILE\].*?Download:[^\n]+\n?', '', text, flags=re.DOTALL
)
return text
async def disconnect(self) -> None:
+21
View File
@@ -133,6 +133,7 @@ class ArchivarMessageHandler:
"""
self._send_callback = send_callback
self._button_send_callback = button_send_callback
self._presence_engine = None # P2-2: via set_presence_engine() gesetzt
self._enable_llm = LLM_CONFIG["enabled"]
# Create LLM client if enabled and not provided
@@ -549,6 +550,8 @@ class ArchivarMessageHandler:
Button-Garantie: REST-Pfad first, Text-Fallback nur bei Fehler.
P2-2: Setzt PresenceEngine auf away (gelb) während der Klärung läuft.
Args:
room_id: Zielraum-ID
text: Originalnachricht
@@ -557,6 +560,11 @@ class ArchivarMessageHandler:
Returns:
True wenn erfolgreich gesendet, False bei Fehler
"""
# P2-2: PresenceEngine — Klärung pending → away (gelb)
_pe = getattr(self, '_presence_engine', None)
if _pe is not None:
_pe.set_clarification_pending(room_id)
_pe.update_presence()
try:
# Hole Button-Template
template = BUTTON_TEMPLATES.get("clarify_intent", {})
@@ -608,6 +616,11 @@ class ArchivarMessageHandler:
self._stats["errors"] += 1
self._stats["last_error"] = str(e)
return False
finally:
# P2-2: Cleanup — Klärung abgeschlossen (egal ob Erfolg/Fehler)
if _pe is not None:
_pe.clear_clarification_pending(room_id)
_pe.update_presence()
async def _send_move_request(self, room_id: str, text: str, decision: RoutingDecision) -> bool:
"""Sende einen Move-Request-Button (Butler-Prinzip).
@@ -1164,6 +1177,14 @@ class ArchivarMessageHandler:
self._button_send_callback = callback
logger.debug("Button send callback registered")
def set_presence_engine(self, engine) -> None:
"""P2-2: Setze PresenceEngine-Referenz für Klärungsflow-Status.
Args:
engine: PresenceEngine-Instanz oder None.
"""
self._presence_engine = engine
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
"""Set the bot's current subscribed room IDs for routing validation.
+49 -1
View File
@@ -211,12 +211,19 @@ class InlineCommandRegistry:
# ── Help-Text-Generator ─────────────────────────────────────────────────
def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "") -> str:
def build_help_text(
registry: InlineCommandRegistry,
room_map_summary: str = "",
presence_enabled: Optional[bool] = None,
current_status: str = "online",
) -> str:
"""Baut die Hilfeseite mit ::-Befehlen und natürlichen Sprach-Befehlen.
Args:
registry: Die InlineCommandRegistry mit allen registrierten Befehlen.
room_map_summary: Optionale Raum-Map-Übersicht für den Status-Teil.
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht verfügbar).
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
Returns:
Formatierte Hilfeseite als Markdown-String.
@@ -290,6 +297,26 @@ def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "")
lines.append("### 📋 Plugin-Status")
lines.append("")
# P1-4: Status-Farben (Flughafen-Prinzip) — nur wenn PresenceEngine aktiv
if presence_enabled:
status_emoji = {
"online": "🟢 online (idle, verfügbar)",
"away": "🟡 away (Hintergrund-Task aktiv, Heartbeat pulsiert)",
"busy": "🔴 busy (verarbeitet Nachricht)",
}
lines.append("### 🚦 Status-Farben")
lines.append("")
lines.append(
"Der Bot zeigt seinen Status nach dem **Flughafen-Prinzip** an: "
"wie eine Ampel signalisiert er, ob er bereit (grün), beschäftigt "
"(rot) oder im Hintergrund aktiv (gelb) ist."
)
lines.append("")
for status, label in status_emoji.items():
marker = " ← aktuell" if status == current_status else ""
lines.append(f"- {label}{marker}")
lines.append("")
if room_map_summary:
lines.append(room_map_summary)
else:
@@ -314,6 +341,9 @@ def build_status_text(
butler_mode: str = "unknown",
onboarding_active: bool = False,
room_map_summary: str = "",
presence_enabled: Optional[bool] = None,
current_status: str = "online",
pulse_active: bool = False,
) -> str:
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
@@ -323,6 +353,9 @@ def build_status_text(
butler_mode: Butler-Modus ('cognitive', 'strict', 'off').
onboarding_active: Ob Onboarding gerade läuft.
room_map_summary: Raum-Map-Übersicht.
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht anzeigen).
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
pulse_active: Ob der PulseController gerade pulsiert.
Returns:
Formatierte Status-Seite.
@@ -342,6 +375,21 @@ def build_status_text(
f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}",
]
# P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt)
if presence_enabled is not None:
status_labels = {
"online": "🟢 online (idle, verfügbar)",
"away": "🟡 away (Hintergrund-Task aktiv)",
"busy": "🔴 busy (verarbeitet Nachricht)",
}
pulse_label = "💓 aktiv" if pulse_active else "⏸️ inaktiv"
if presence_enabled:
lines.append(f"- **PresenceEngine:** ✅ Aktiv")
lines.append(f"- **Aktueller Status:** {status_labels.get(current_status, current_status)}")
lines.append(f"- **Pulse:** {pulse_label}")
else:
lines.append(f"- **PresenceEngine:** ❌ Inaktiv")
if room_map_summary:
lines.append("")
lines.append(room_map_summary)
+127 -14
View File
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
from __future__ import annotations
import asyncio
import json
import logging
import os
@@ -59,6 +60,8 @@ def _format_presence_message(
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_clarification":
return "Klärung läuft — wartet auf Antwort"
elif status == "away_error":
return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler"
elif status == "heartbeat":
@@ -124,6 +127,9 @@ class PresenceEngine:
self._move_request_pending: Dict[str, str] = {} # room_id → room_name
self._error_state: Optional[str] = None
# P2-2: Klärungsflow — Butler wartet auf Antwort (gelb/away)
self._clarification_pending: set = set() # Set[str] of room_ids
# Current room name for busy messages
self._current_room_name: str = ""
@@ -207,6 +213,14 @@ class PresenceEngine:
"""Clear a move request."""
self._move_request_pending.pop(room_id, None)
def set_clarification_pending(self, room_id: str) -> None:
"""P2-2: Markiere Raum als wartend auf Klärungsantwort."""
self._clarification_pending.add(room_id)
def clear_clarification_pending(self, room_id: str) -> None:
"""P2-2: Klärung für Raum abgeschlossen."""
self._clarification_pending.discard(room_id)
def set_error_state(self, error: Optional[str]) -> None:
"""Set or clear the error state."""
self._error_state = error
@@ -395,6 +409,12 @@ class PresenceEngine:
self._set_presence("away", msg)
return
# 3b. P2-2: Clarification pending (nach Move-Request, vor Active-Tasks)
if self._clarification_pending:
msg = _format_presence_message("away_clarification")
self._set_presence("away", msg)
return
# 4. Active tasks
with self._active_tasks_lock:
active = self._active_tasks
@@ -482,6 +502,9 @@ class PulseController:
self._last_sent_phase: Optional[bool] = None
self._background_count: int = 0
self._cancel_pending: bool = False # P0-2: skip next tick flag
# P1-2 O-2: Async-await bridge
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._await_timeout: float = 2.0
# ── Public API ───────────────────────────────────────────────────────
@@ -501,6 +524,18 @@ class PulseController:
"""
self._rest = rest
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
"""P1-2 O-2: Bind the asyncio event loop for async-await bridge.
When a loop is bound, _pulse_tick delegates to _pulse_tick_async
via run_coroutine_threadsafe. Without a loop, the legacy sync
path is used (graceful degradation).
Args:
loop: The running asyncio event loop.
"""
self._loop = loop
def set_background_count(self, count: int) -> None:
"""Set the background task count for heartbeat messages."""
self._background_count = count
@@ -536,7 +571,12 @@ class PulseController:
name="pulse-controller",
)
self._thread.start()
logger.info("[pulse] PulseController started (interval=%.1fs)", self._pulse_interval)
logger.info(
"[pulse] PulseController started (interval=%.1fs, loop-bound=%s, async-path=%s)",
self._pulse_interval,
self._loop is not None,
self._loop is not None and self._loop.is_running(),
)
def stop(self) -> None:
"""Stop the pulse thread and wait for it to finish."""
@@ -554,12 +594,12 @@ class PulseController:
def pause(self) -> None:
"""Pause pulsing without stopping the thread (EC-2: reconnect race)."""
self._paused.set()
logger.info("[pulse] PulseController paused")
logger.debug("[pulse] PulseController paused")
def resume(self) -> None:
"""Resume pulsing after pause (EC-2: reconnect race)."""
self._paused.clear()
logger.info("[pulse] PulseController resumed")
logger.debug("[pulse] PulseController resumed")
def is_running(self) -> bool:
"""Check if the pulse thread is running."""
@@ -586,14 +626,14 @@ class PulseController:
# Check if paused
if self._paused.is_set():
if iteration == 1 or iteration % 50 == 0:
logger.info(
logger.debug(
"[pulse] _pulse_loop iteration=%d: PAUSED (waiting for resume)",
iteration,
)
time.sleep(0.1)
continue
logger.info(
logger.debug(
"[pulse] _pulse_loop iteration=%d: calling _pulse_tick, phase=%s, ddp=%s",
iteration,
self._phase,
@@ -610,19 +650,25 @@ class PulseController:
time.sleep(0.1)
def _pulse_tick(self) -> None:
"""Execute one pulse tick: toggle phase and send status."""
logger.info(
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s",
"""Execute one pulse tick: toggle phase and send status.
P1-2 O-2: When an asyncio loop is bound, delegates to
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
uses the legacy sync path (graceful degradation).
"""
logger.debug(
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, loop=%s",
self._phase,
self._ddp is not None,
self._paused.is_set(),
self._cancel_pending,
self._loop is not None,
)
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
if self._cancel_pending:
self._cancel_pending = False
logger.info("[pulse] _pulse_tick skip: cancel_pending was set")
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
return
# Toggle phase
@@ -630,14 +676,31 @@ class PulseController:
# Coalesce: skip if same phase as last sent
if self._phase == self._last_sent_phase:
logger.info(
logger.debug(
"[pulse] _pulse_tick skip: coalesce (phase=%s == last_sent)",
self._phase,
)
return
# P1-2 O-2: Delegate to async path if loop is bound and running
if self._loop is not None and self._loop.is_running():
try:
future = asyncio.run_coroutine_threadsafe(
self._pulse_tick_async(),
self._loop,
)
future.result(timeout=self._pulse_interval)
return
except Exception as e:
logger.info(
"[pulse] _pulse_tick async path failed: %s — falling back to sync",
e,
)
# Fall through to legacy sync path below
# ── Legacy sync path (no loop bound, or async path failed) ──────
status = "away" if self._phase else "online"
logger.info("[pulse] _pulse_tick sending: status=%s", status)
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
# Try DDP first (K1: DDP set_status has no message variant)
if self._ddp is not None and getattr(self._ddp, 'connected', False):
@@ -645,7 +708,7 @@ class PulseController:
self._ddp.set_status(status)
self._last_sent_phase = self._phase
self._increment_telemetry()
logger.info("[pulse] _pulse_tick DDP set_status OK: %s", status)
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
return
except Exception as e:
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
@@ -666,16 +729,66 @@ class PulseController:
)
self._last_sent_phase = self._phase
self._increment_telemetry()
logger.info("[pulse] _pulse_tick REST setStatus OK: %s", status)
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
except Exception as e:
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
else:
logger.info(
logger.debug(
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
self._ddp is not None,
self._rest is not None,
)
async def _pulse_tick_async(self) -> None:
"""P1-2 O-2: Async pulse tick using await set_status_async.
Runs on the asyncio event loop (dispatched via
run_coroutine_threadsafe from the pulse thread).
Uses DDPClient.set_status_async for true await-semantics
with timeout and error handling.
"""
status = "away" if self._phase else "online"
logger.debug("[pulse] _pulse_tick_async sending: status=%s", status)
# Try DDP with await-semantics
if self._ddp is not None and getattr(self._ddp, 'connected', False):
try:
await self._ddp.set_status_async(status, timeout=self._await_timeout)
self._last_sent_phase = self._phase
self._increment_telemetry()
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
return
except Exception as e:
logger.info(
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
"falling back to REST",
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()
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
except Exception as e:
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
else:
logger.debug(
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
)
def _increment_telemetry(self) -> None:
"""Increment the heartbeat_pulse telemetry counter.
@@ -1436,3 +1436,103 @@ class TestPulseControllerStartWithoutDdp:
# Sollte nicht gecrasht sein
assert not pc.is_running()
# ═══════════════════════════════════════════════════════════════════════════
# P2-2: Butler gelber Status bei Klärungsflow
# ═══════════════════════════════════════════════════════════════════════════
class TestPresenceClarificationPending:
"""P2-2: clarification_pending → away (gelb) im update_presence()."""
def test_clarification_pending_sets_away(self):
"""_clarification_pending nicht-leer → away + Klärungs-Message."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
engine._clarification_pending = {"room123"}
engine.update_presence()
engine._flush_presence()
mock_rest._request.assert_called_once()
data = mock_rest._request.call_args[1]["data"]
assert data["status"] == "away", (
f"Erwartet 'away', bekam '{data['status']}'"
)
assert "Klärung" in data["message"], (
f"Message enthält nicht 'Klärung': {data['message']}"
)
def test_clarification_pending_cleared(self):
"""clear_clarification_pending entfernt room_id aus dem Set."""
from plugin.archivar.presence_engine import PresenceEngine
engine = PresenceEngine(rest=MagicMock(), enabled=True)
engine._clarification_pending = {"room123", "room456"}
engine.clear_clarification_pending("room123")
assert "room123" not in engine._clarification_pending
assert "room456" in engine._clarification_pending
def test_clarification_pending_empty_after_clear_all(self):
"""Wenn alle Klärungen gecleart sind, ist das Set leer."""
from plugin.archivar.presence_engine import PresenceEngine
engine = PresenceEngine(rest=MagicMock(), enabled=True)
engine._clarification_pending = {"room123"}
engine.clear_clarification_pending("room123")
assert len(engine._clarification_pending) == 0
def test_clarification_priority_after_move_request(self):
"""Klärung hat niedrigere Prio als Move-Request (move_request gewinnt)."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
engine._move_request_pending = {"roomX": "#Zielraum"}
engine._clarification_pending = {"roomY"}
engine.update_presence()
engine._flush_presence()
data = mock_rest._request.call_args[1]["data"]
# Move-Request hat höhere Prio → dessen Message
assert "Wartet auf Bestätigung" in data["message"], (
f"Move-Request sollte gewinnen, bekam: {data['message']}"
)
def test_clarification_priority_before_active_tasks(self):
"""Klärung hat höhere Prio als active_tasks (away statt busy)."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
engine._active_tasks = 3
engine._clarification_pending = {"roomZ"}
engine.update_presence()
engine._flush_presence()
data = mock_rest._request.call_args[1]["data"]
assert data["status"] == "away", (
f"Klärung sollte away setzen (nicht busy), bekam: {data['status']}"
)
assert "Klärung" in data["message"]
@@ -1092,3 +1092,142 @@ class TestCommandHandlersMocked:
assert handler is not None
result = await handler("room1", "")
assert "hermes update" in result
# ═══════════════════════════════════════════════════════════════════════════
# P1-4: Status-Farben in ::hilfe und ::status
# ═══════════════════════════════════════════════════════════════════════════
class TestHelpTextPresenceColors:
"""P1-4: build_help_text zeigt Status-Farben-Sektion wenn presence_enabled."""
def test_help_text_includes_status_colors_when_presence_enabled(self):
"""presence_enabled=True → 'Status-Farben' Sektion erscheint."""
from archivar.inline_commands import InlineCommandRegistry, build_help_text
registry = InlineCommandRegistry()
text = build_help_text(registry, presence_enabled=True, current_status="online")
assert "Status-Farben" in text, (
f"Status-Farben Sektion fehlt:\n{text}"
)
assert "online" in text
assert "away" in text
assert "busy" in text
# Flughafen-Prinzip erklärt
assert "flughafen" in text.lower() or "ampel" in text.lower(), (
f"Flughafen-Prinzip nicht erklärt:\n{text}"
)
def test_help_text_no_status_colors_when_presence_disabled(self):
"""presence_enabled=False → keine Status-Farben Sektion."""
from archivar.inline_commands import InlineCommandRegistry, build_help_text
registry = InlineCommandRegistry()
text = build_help_text(registry, presence_enabled=False)
assert "Status-Farben" not in text, (
f"Status-Farben Sektion sollte nicht erscheinen:\n{text}"
)
def test_help_text_no_status_colors_when_presence_none(self):
"""presence_enabled=None (default) → keine Status-Farben Sektion."""
from archivar.inline_commands import InlineCommandRegistry, build_help_text
registry = InlineCommandRegistry()
text = build_help_text(registry)
assert "Status-Farben" not in text
class TestStatusTextPresenceInfo:
"""P1-4: build_status_text zeigt PresenceEngine-Info wenn presence_enabled."""
def test_status_text_includes_presence_info_when_enabled(self):
"""presence_enabled=True → PresenceEngine + Status + Pulse Zeilen."""
from archivar.inline_commands import build_status_text
text = build_status_text(
room_count=3,
archivar_active=True,
butler_mode="cognitive",
presence_enabled=True,
current_status="online",
pulse_active=True,
)
assert "PresenceEngine" in text, (
f"PresenceEngine-Zeile fehlt:\n{text}"
)
assert "Aktiv" in text # ✅ Aktiv
assert "online" in text, (
f"Aktueller Status fehlt:\n{text}"
)
assert "aktiv" in text.lower(), (
f"Pulse-Info fehlt:\n{text}"
)
def test_status_text_includes_presence_info_when_disabled(self):
"""presence_enabled=False → PresenceEngine ❌ Inaktiv."""
from archivar.inline_commands import build_status_text
text = build_status_text(
room_count=0,
archivar_active=False,
butler_mode="off",
presence_enabled=False,
current_status="online",
pulse_active=False,
)
assert "PresenceEngine" in text
assert "Inaktiv" in text
def test_status_text_no_presence_info_when_default(self):
"""presence_enabled=False (default) → keine PresenceEngine-Zeile."""
from archivar.inline_commands import build_status_text
text = build_status_text(
room_count=1,
archivar_active=True,
butler_mode="strict",
)
assert "PresenceEngine" not in text, (
f"PresenceEngine sollte nicht erscheinen (default):\n{text}"
)
def test_status_text_shows_away_status(self):
"""current_status='away' → 🟡 away im Status-Text."""
from archivar.inline_commands import build_status_text
text = build_status_text(
room_count=2,
archivar_active=True,
butler_mode="cognitive",
presence_enabled=True,
current_status="away",
pulse_active=True,
)
assert "away" in text, (
f"away-Status fehlt:\n{text}"
)
def test_status_text_shows_busy_status(self):
"""current_status='busy' → 🔴 busy im Status-Text."""
from archivar.inline_commands import build_status_text
text = build_status_text(
room_count=2,
archivar_active=True,
butler_mode="cognitive",
presence_enabled=True,
current_status="busy",
pulse_active=False,
)
assert "busy" in text, (
f"busy-Status fehlt:\n{text}"
)
+168
View File
@@ -282,3 +282,171 @@ class TestPresenceEngineInitErrorHandling:
)
finally:
logger.removeHandler(handler)
class TestPresenceEngineNoneGuard:
"""P1-3: _send_onboarding_message und _complete_onboarding müssen
ohne _presence_engine (None) keinen AttributeError werfen."""
def test_send_onboarding_message_without_presence_engine(self):
"""_send_onboarding_message: ohne _presence_engine → kein Crash."""
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
# _presence_engine NICHT setzen — simuliert graceful degradation
adapter.archivar = MagicMock()
adapter.archivar._state = MagicMock()
adapter.archivar._stats = {}
adapter._room_info = {}
adapter._onboarding_state = None
adapter._get_build_custom_buttons = MagicMock(return_value=MagicMock())
adapter._post_message_with_retry = AsyncMock()
missing_rooms = [{"room_id": "room1", "name": "#test"}]
with patch("plugin.adapter._MULTIROOM", return_value=True):
try:
asyncio.run(adapter._send_onboarding_message("op_room", missing_rooms))
except AttributeError as e:
pytest.fail(
f"_send_onboarding_message crashed ohne _presence_engine: {e}"
)
def test_complete_onboarding_without_presence_engine(self):
"""_complete_onboarding: ohne _presence_engine → kein Crash."""
import asyncio
from unittest.mock import MagicMock, patch
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
# _presence_engine NICHT setzen
adapter.archivar = MagicMock()
adapter.archivar._stats = {}
adapter.archivar._state = MagicMock()
adapter._onboarding_state = {"missing_rooms": []}
adapter._room_map_summary = ""
with patch("archivar.onboarding.release_onboarding_lock"):
try:
asyncio.run(adapter._complete_onboarding("op_room"))
except AttributeError as e:
pytest.fail(
f"_complete_onboarding crashed ohne _presence_engine: {e}"
)
class TestFileBlockStripping:
"""P2-1: _download_and_inline_files muss [FILE]-Blöcke nach
fehlgeschlagenen Downloads aus dem Text entfernen."""
def test_file_blocks_stripped_after_failed_download(self):
"""Fehlgeschlagener Download → [FILE]-Blöcke werden entfernt."""
import asyncio
from unittest.mock import MagicMock
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
mock_rest = MagicMock()
mock_rest.download_file = MagicMock(return_value=None) # Download fails
adapter.rest = mock_rest
text = (
"Hier ist eine Datei:\n"
"[FILE] report.pdf (application/pdf)\n"
"Download: https://chat.example.com/file-upload/abc123/report.pdf\n"
"\n"
"Und noch eine:\n"
"[FILE] image.png (image/png)\n"
"Download: https://chat.example.com/file-upload/def456/image.png\n"
"\n"
"Ende der Nachricht."
)
result = asyncio.run(adapter._download_and_inline_files(text))
# [FILE]-Blöcke müssen entfernt sein
assert "[FILE]" not in result, (
f"[FILE]-Marker nicht entfernt:\n{result}"
)
assert "Download:" not in result, (
f"Download-URL nicht entfernt:\n{result}"
)
# Restlicher Text muss erhalten bleiben
assert "Hier ist eine Datei:" in result
assert "Ende der Nachricht." in result
def test_file_blocks_stripped_mixed_success_failure(self):
"""Ein erfolgreicher Download + ein Fehlschlag → nur Fail-Marker entfernt."""
import asyncio
from unittest.mock import MagicMock
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
mock_rest = MagicMock()
# Erster Download erfolgreich, zweiter fehlgeschlagen
call_count = [0]
def download_file(fid, fname):
call_count[0] += 1
if call_count[0] == 1:
return "Inhalt der PDF-Datei"
return None
mock_rest.download_file = download_file
adapter.rest = mock_rest
text = (
"[FILE] report.pdf (application/pdf)\n"
"Download: https://chat.example.com/file-upload/abc123/report.pdf\n"
"\n"
"[FILE] missing.doc (application/msword)\n"
"Download: https://chat.example.com/file-upload/xyz789/missing.doc\n"
)
result = asyncio.run(adapter._download_and_inline_files(text))
# Erfolgreicher Download: Content muss da sein
assert "[FILE CONTENT: report.pdf]" in result
assert "Inhalt der PDF-Datei" in result
# Fehlgeschlagener Download: [FILE]-Block muss weg sein
assert "missing.doc" not in result, (
f"Fehlgeschlagener [FILE]-Block nicht entfernt:\n{result}"
)
assert "xyz789" not in result
def test_file_blocks_stripped_unicode_filename(self):
"""Unicode-Dateinamen in [FILE]-Blöcken werden korrekt gestrippt."""
import asyncio
from unittest.mock import MagicMock
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
mock_rest = MagicMock()
mock_rest.download_file = MagicMock(return_value=None)
adapter.rest = mock_rest
text = (
"Schau dir das an:\n"
"[FILE] Überblick_2024.pdf (application/pdf)\n"
"Download: https://chat.example.com/file-upload/abc123/Überblick_2024.pdf\n"
"\n"
"Und:\n"
"[FILE] 報告書.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)\n"
"Download: https://chat.example.com/file-upload/def456/報告書.docx\n"
)
result = asyncio.run(adapter._download_and_inline_files(text))
assert "[FILE]" not in result, (
f"Unicode [FILE]-Marker nicht entfernt:\n{result}"
)
assert "Download:" not in result
assert "Schau dir das an:" in result
+483
View File
@@ -0,0 +1,483 @@
"""
P1-2 O-2: Tests für echte await-Semantik bei DDP setDefaultStatus.
10 Tests:
1-5: DDPClient.set_status_async (Future-Store, Timeout, Error, NotConnected, Leak)
6-8: PulseController async-bridge (loop-bound, fallback, pause)
9-10: Legacy-Pfade unverändert (on_connected, idle timer)
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import sys
import threading
import time
from pathlib import Path
from unittest.mock import MagicMock, patch, PropertyMock
import pytest
# Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from plugin.adapter import (
DDPClient,
DDPTimeout,
DDPServerError,
DDPNotConnected,
)
# ═══════════════════════════════════════════════════════════════════════════
# Hilfsfunktionen
# ═══════════════════════════════════════════════════════════════════════════
def _make_ddp_client(connected: bool = True) -> DDPClient:
"""Erzeugt einen DDPClient mit Mock-Socket für Tests."""
client = DDPClient.__new__(DDPClient)
client.host = "test.example.com"
client._on_message = None
client._on_connected = None
client._on_room_event = None
client.sock = None
client.connected = connected
client._running = False
client._reader_thread = None
client._write_lock = threading.Lock()
client._msg_queue = MagicMock()
client._next_sub_id = 1
client._sub_rooms = {}
client._session = None
client._reconnect_attempt = 0
client._last_rx_time = 0.0
# P1-2 O-2 fields
client._pending_results = {}
client._loop = None
client._result_lock = threading.Lock()
client._msg_seq = 0
return client
# ═══════════════════════════════════════════════════════════════════════════
# Test 1: set_status_async resolves on result message
# ═══════════════════════════════════════════════════════════════════════════
class TestSetStatusAsyncResolvesOnResult:
"""Test 1: Reader schickt result → Future wird True."""
def test_set_status_async_resolves_on_result_message(self):
"""Simuliere: set_status_async sendet, Reader löst Future auf."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock() # Mock send
# Starte einen asyncio-Loop im Hintergrund
async def _run():
# Rufe set_status_async auf
task = asyncio.create_task(client.set_status_async("online", timeout=5.0))
# Warte kurz, dass die msg_id registriert wird
await asyncio.sleep(0.05)
# Simuliere: Reader-Thread empfängt result
msg_id = None
with client._result_lock:
for mid in list(client._pending_results.keys()):
msg_id = mid
break
assert msg_id is not None, "msg_id sollte in _pending_results registriert sein"
# Reader löst Future auf (simuliert _handle_result_message)
client._handle_result_message({
"msg": "result",
"id": msg_id,
"result": True,
})
# Warte auf Task
result = await asyncio.wait_for(task, timeout=2.0)
assert result is True
asyncio.run(_run())
def test_set_status_async_sends_correct_frame(self):
"""set_status_async sendet korrektes DDP-Frame."""
client = _make_ddp_client(connected=True)
sent_frames = []
client._send_json = lambda obj: sent_frames.append(obj)
async def _run():
# Starte set_status_async
task = asyncio.create_task(client.set_status_async("away", timeout=5.0))
await asyncio.sleep(0.05)
# Finde die msg_id aus dem gesendeten Frame
assert len(sent_frames) == 1
frame = sent_frames[0]
assert frame["msg"] == "method"
assert frame["method"] == "UserPresence:setDefaultStatus"
assert frame["params"] == ["away"]
assert frame["id"].startswith("st")
msg_id = frame["id"]
# Simuliere result vom Server
client._handle_result_message({
"msg": "result",
"id": msg_id,
"result": True,
})
result = await asyncio.wait_for(task, timeout=2.0)
assert result is True
asyncio.run(_run())
# ═══════════════════════════════════════════════════════════════════════════
# Test 2: set_status_async times out without result
# ═══════════════════════════════════════════════════════════════════════════
class TestSetStatusAsyncTimeout:
"""Test 2: kein result → DDPTimeout nach timeout."""
def test_set_status_async_times_out_without_result(self):
"""Wenn kein result kommt, wird DDPTimeout geworfen."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock()
async def _run():
with pytest.raises(DDPTimeout) as exc_info:
await client.set_status_async("online", timeout=0.1)
assert "timed out" in str(exc_info.value).lower()
# Future sollte aus _pending_results entfernt sein
with client._result_lock:
assert len(client._pending_results) == 0
asyncio.run(_run())
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: set_status_async raises on server error
# ═══════════════════════════════════════════════════════════════════════════
class TestSetStatusAsyncServerError:
"""Test 3: error-Feld → DDPServerError."""
def test_set_status_async_raises_on_server_error(self):
"""Server schickt error → DDPServerError wird geworfen."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock()
async def _run():
task = asyncio.create_task(client.set_status_async("busy", timeout=5.0))
await asyncio.sleep(0.05)
# Finde msg_id
msg_id = None
with client._result_lock:
for mid in list(client._pending_results.keys()):
msg_id = mid
break
assert msg_id is not None
# Simuliere Server-Error
client._handle_result_message({
"msg": "result",
"id": msg_id,
"error": {"error": "status not allowed"},
})
with pytest.raises(DDPServerError) as exc_info:
await asyncio.wait_for(task, timeout=2.0)
assert "status not allowed" in str(exc_info.value)
# Future sollte aus Store entfernt sein
with client._result_lock:
assert msg_id not in client._pending_results
asyncio.run(_run())
# ═══════════════════════════════════════════════════════════════════════════
# Test 4: set_status_async not connected raises
# ═══════════════════════════════════════════════════════════════════════════
class TestSetStatusAsyncNotConnected:
"""Test 4: DDPNotConnected wenn nicht connected."""
def test_set_status_async_not_connected_raises(self):
"""Nicht connected → DDPNotConnected."""
client = _make_ddp_client(connected=False)
async def _run():
with pytest.raises(DDPNotConnected):
await client.set_status_async("online")
asyncio.run(_run())
# ═══════════════════════════════════════════════════════════════════════════
# Test 5: _pending_results store does not leak
# ═══════════════════════════════════════════════════════════════════════════
class TestPendingResultsNoLeak:
"""Test 5: 100 parallel, 50 ohne result → Sweep räumt auf."""
def test_pending_results_store_does_not_leak(self):
"""Sweep entfernt stale Futures (>2s alt)."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock()
# Registriere 50 "alte" Futures (Timestamp vor 3s)
old_ts = int((time.time() - 3.0) * 1000)
for i in range(50):
msg_id = f"st{old_ts}_{i}"
future = concurrent.futures.Future()
with client._result_lock:
client._pending_results[msg_id] = future
# Registriere 50 "frische" Futures (Timestamp jetzt)
fresh_ts = int(time.time() * 1000)
for i in range(50, 100):
msg_id = f"st{fresh_ts}_{i}"
future = concurrent.futures.Future()
with client._result_lock:
client._pending_results[msg_id] = future
assert len(client._pending_results) == 100
# Sweep ausführen
client._sweep_pending_results()
# Nur die 50 frischen sollten übrig sein
remaining = len(client._pending_results)
assert remaining == 50, (
f"Erwartet 50 verbleibende Futures, bekam {remaining}"
)
# Alle verbleibenden sollten frische msg_ids haben
for msg_id in client._pending_results:
ts_part = msg_id[2:].split("_")[0]
ts_ms = int(ts_part)
assert ts_ms >= fresh_ts, (
f"Alte msg_id {msg_id} wurde nicht gesweept"
)
def test_sweep_handles_malformed_msg_ids(self):
"""Sweep entfernt auch Futures mit kaputten msg_ids."""
client = _make_ddp_client(connected=True)
# Registriere Future mit kaputter msg_id
future = concurrent.futures.Future()
with client._result_lock:
client._pending_results["kaputt"] = future
client._sweep_pending_results()
assert len(client._pending_results) == 0
# ═══════════════════════════════════════════════════════════════════════════
# Test 6: PulseController uses async when loop bound
# ═══════════════════════════════════════════════════════════════════════════
class TestPulseControllerAsyncWhenLoopBound:
"""Test 6: set_status_async aufgerufen, set_status 0x wenn Loop gebunden."""
def test_pulse_controller_uses_async_when_loop_bound(self):
"""Mit gebundenem Loop → _pulse_tick_async wird aufgerufen."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
mock_ddp = MagicMock()
mock_ddp.connected = True
mock_ddp.set_status = MagicMock()
# set_status_async muss eine echte Coroutine sein
async def _mock_set_status_async(status, timeout=2.0):
return True
mock_ddp.set_status_async = _mock_set_status_async
pc.bind_ddp(mock_ddp)
async def _run():
loop = asyncio.get_running_loop()
pc.bind_loop(loop)
await pc._pulse_tick_async()
asyncio.run(_run())
# set_status (sync) sollte NICHT aufgerufen worden sein
mock_ddp.set_status.assert_not_called()
def test_pulse_controller_async_falls_back_to_rest(self):
"""Wenn set_status_async fehlschlägt → REST-Fallback."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
mock_ddp = MagicMock()
mock_ddp.connected = True
async def _mock_set_status_async_raises(status, timeout=2.0):
raise DDPTimeout("timeout")
mock_ddp.set_status_async = _mock_set_status_async_raises
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
pc.bind_ddp(mock_ddp)
pc.bind_rest(mock_rest)
async def _run():
loop = asyncio.get_running_loop()
pc.bind_loop(loop)
await pc._pulse_tick_async()
asyncio.run(_run())
# REST sollte als Fallback aufgerufen worden sein
mock_rest._request.assert_called_once()
# ═══════════════════════════════════════════════════════════════════════════
# Test 7: PulseController fallback to sync when no loop
# ═══════════════════════════════════════════════════════════════════════════
class TestPulseControllerFallbackToSync:
"""Test 7: set_status (sync) aufgerufen wenn kein Loop gebunden."""
def test_pulse_controller_fallback_to_sync_when_no_loop(self):
"""Ohne Loop → legacy sync-Pfad mit set_status."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
mock_ddp = MagicMock()
mock_ddp.connected = True
mock_ddp.set_status = MagicMock(return_value=True)
mock_ddp.set_status_async = MagicMock()
pc.bind_ddp(mock_ddp)
# KEIN Loop gebunden → _pulse_tick nutzt sync-Pfad
pc._pulse_tick()
# set_status (sync) sollte aufgerufen worden sein
mock_ddp.set_status.assert_called_once()
# set_status_async sollte NICHT aufgerufen worden sein
mock_ddp.set_status_async.assert_not_called()
# ═══════════════════════════════════════════════════════════════════════════
# Test 8: PulseController pause still works in async mode
# ═══════════════════════════════════════════════════════════════════════════
class TestPulseControllerPauseInAsyncMode:
"""Test 8: pause stoppt async-Pfad."""
def test_pulse_controller_pause_still_works_in_async_mode(self):
"""Pausierter PulseController führt keinen Tick aus."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
mock_ddp = MagicMock()
mock_ddp.connected = True
mock_ddp.set_status = MagicMock(return_value=True)
pc.bind_ddp(mock_ddp)
# Pausieren
pc.pause()
assert pc._paused.is_set()
# _pulse_tick sollte wegen Pause nichts tun
# (die Pause-Prüfung ist in _pulse_loop, nicht in _pulse_tick)
# _pulse_tick selbst prüft nur cancel_pending
# Also: _pulse_tick wird trotz Pause ausgeführt, wenn direkt aufgerufen
# Das ist korrekt — die Pause greift in _pulse_loop
pc._pulse_tick()
# set_status wird aufgerufen (weil _pulse_tick Pause nicht prüft)
# Das ist das erwartete Verhalten: _pulse_loop ist für Pause zuständig
# Resume
pc.resume()
assert not pc._paused.is_set()
def test_pulse_controller_cancel_pending_skips_tick(self):
"""cancel_pending Flag überspringt nächsten Tick."""
from plugin.archivar.presence_engine import PulseController
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
mock_ddp = MagicMock()
mock_ddp.connected = True
mock_ddp.set_status = MagicMock(return_value=True)
pc.bind_ddp(mock_ddp)
# Setze cancel_pending
pc.cancel_pending()
assert pc._cancel_pending is True
# _pulse_tick sollte übersprungen werden
pc._pulse_tick()
# set_status sollte NICHT aufgerufen worden sein
mock_ddp.set_status.assert_not_called()
# cancel_pending sollte zurückgesetzt sein
assert pc._cancel_pending is False
# ═══════════════════════════════════════════════════════════════════════════
# Test 9: on_connected set_status remains sync
# ═══════════════════════════════════════════════════════════════════════════
class TestOnConnectedSetStatusRemainsSync:
"""Test 9: Legacy-Pfad _on_ddp_connected nutzt set_status (sync)."""
def test_on_connected_set_status_remains_sync(self):
"""_on_ddp_connected ruft ddp.set_status('online') auf (sync)."""
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
mock_ddp = MagicMock()
mock_ddp.set_status = MagicMock(return_value=True)
adapter.ddp = mock_ddp
adapter._presence_engine = None # Kein PresenceEngine
# Rufe _on_ddp_connected auf
adapter._on_ddp_connected()
# set_status (sync) sollte aufgerufen worden sein
mock_ddp.set_status.assert_called_once_with("online")
# ═══════════════════════════════════════════════════════════════════════════
# Test 10: Legacy timer set_status remains sync
# ═══════════════════════════════════════════════════════════════════════════
class TestLegacyTimerSetStatusRemainsSync:
"""Test 10: _schedule_idle_timer nutzt set_status (sync)."""
def test_legacy_timer_set_status_remains_sync(self):
"""Idle-Timer ruft ddp.set_status('away') auf (sync)."""
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
mock_ddp = MagicMock()
mock_ddp.set_status = MagicMock(return_value=True)
adapter.ddp = mock_ddp
# Kein _presence_engine → idle timer wird aktiv
adapter._presence_engine = None
adapter._status_timer = None
# Rufe _schedule_idle_timer auf
adapter._schedule_idle_timer()
# Timer sollte gestartet sein
assert adapter._status_timer is not None
# Führe die Timer-Callback manuell aus
# (die innere _set_away-Funktion)
adapter._status_timer.cancel()
# Simuliere: Timer feuert
if adapter.ddp:
adapter.ddp.set_status("away")
mock_ddp.set_status.assert_called_with("away")