diff --git a/plugin/adapter.py b/plugin/adapter.py index da73d03..f8a9a04 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -6537,6 +6537,35 @@ class RocketChatAdapter(BasePlatformAdapter): self.ddp = None logger.info("[rocketchat] Disconnected") + async def _maybe_send_quick_reply( + self, gate_room_id: str, active_room_id: Optional[str], active_room_name: str + ) -> None: + """Sendet Quick-Reply wenn noch nicht für diesen Raum gesendet (Dedup). + + P1 Fix: Verhindert dass Quick-Reply mehrfach gesendet wird wenn + parallele Tasks aus _dispatch_agent gleichzeitig feuern. + """ + if not hasattr(self, '_outbound_gate') or self._outbound_gate is None: + return + if self._outbound_gate.quick_reply_already_sent(gate_room_id): + return + + same_room = (active_room_id is not None and active_room_id == gate_room_id) + if same_room: + text = 'Ich bin gerade beschäftigt — einen Moment bitte, ich bin gleich bei dir.' + elif active_room_name: + text = f'Ich antworte gerade in #{active_room_name} — einen Moment bitte, ich bin gleich bei dir.' + else: + text = 'Ich antworte gerade in einem anderen Raum — einen Moment bitte, ich bin gleich bei dir.' + + await self._post_message_unlocked(gate_room_id, text) + self._outbound_gate.mark_quick_reply_sent(gate_room_id) + self._outbound_gate.stats.quick_reply += 1 + logger.info( + "[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)", + gate_room_id[:8], active_room_name or "unknown", + ) + async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult: if not self.rest.auth_token: @@ -6631,20 +6660,8 @@ class RocketChatAdapter(BasePlatformAdapter): active_room = self._outbound_gate.active_room_id active_name = "" if active_room and active_room in self._room_info: - active_name = self._room_info[active_room].get("name", active_room[:12] + "…") - quick_reply_text = ( - f"Ich antworte gerade in #{active_name} — " - f"einen Moment bitte, ich bin gleich bei dir." - ) if active_name else ( - "Ich antworte gerade in einem anderen Raum — " - "einen Moment bitte, ich bin gleich bei dir." - ) - await self._post_message_unlocked(_gate_room_id, quick_reply_text) - self._outbound_gate.stats.quick_reply += 1 - logger.info( - "[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)", - _gate_room_id[:8], active_name, - ) + active_name = self._room_info[active_room].get("name", "") + await self._maybe_send_quick_reply(_gate_room_id, active_room, active_name) return SendResult(success=True, message_id="quick_reply") # Fell through: decision.allow is True — track if WE created the entry # (gate_clear = we own it; same_room_same_token = someone else owns it) @@ -7086,16 +7103,8 @@ class RocketChatAdapter(BasePlatformAdapter): active_room = self._outbound_gate.active_room_id active_name = "" if active_room and active_room in self._room_info: - active_name = self._room_info[active_room].get("name", active_room[:12] + "…") - quick_reply_text = ( - f"Ich antworte gerade in #{active_name} — " - f"einen Moment bitte, ich bin gleich bei dir." - ) if active_name else ( - "Ich antworte gerade in einem anderen Raum — " - "einen Moment bitte, ich bin gleich bei dir." - ) - await self._post_message_unlocked(_gate_room_id, quick_reply_text) - self._outbound_gate.stats.quick_reply += 1 + active_name = self._room_info[active_room].get("name", "") + await self._maybe_send_quick_reply(_gate_room_id, active_room, active_name) return SendResult(success=True, message_id="quick_reply") # Fell through: decision.allow is True — track if WE created the entry # (gate_clear = we own it; same_room_same_token = someone else owns it) diff --git a/plugin/archivar/outbound_gate.py b/plugin/archivar/outbound_gate.py index 90a3c1e..b5687e5 100644 --- a/plugin/archivar/outbound_gate.py +++ b/plugin/archivar/outbound_gate.py @@ -134,6 +134,8 @@ class OutboundGate: self._lock = asyncio.Lock() # A4: Per-Raum Dict statt flat List — kein False-Wake-Bug self._waiters: Dict[str, List[asyncio.Event]] = {} + # P1: Quick-Reply Dedup — verhindert Mehrfachsendung + self._quick_reply_sent: set = set() self.default_timeout_s = default_timeout_s self.max_entry_age_s = max_entry_age_s self.stats = GateStats() @@ -227,6 +229,36 @@ class OutboundGate: reason="gate_clear", ) + # ── Quick-Reply Dedup (P1) ────────────────────────────────────────── + + def mark_quick_reply_sent(self, room_id: str) -> bool: + """Markiert dass ein Quick-Reply für diesen Raum gesendet wurde. + + Idempotent: returns True beim ersten Aufruf (Quick-Reply wurde + tatsächlich gesendet), False bei allen weiteren Aufrufen. + + Args: + room_id: Rocket.Chat Raum-ID. + + Returns: + True wenn dies das erste Markieren war, False wenn bereits markiert. + """ + if room_id not in self._quick_reply_sent: + self._quick_reply_sent.add(room_id) + return True + return False + + def quick_reply_already_sent(self, room_id: str) -> bool: + """Prüft ob bereits ein Quick-Reply für diesen Raum gesendet wurde. + + Args: + room_id: Rocket.Chat Raum-ID. + + Returns: + True wenn bereits ein Quick-Reply gesendet wurde. + """ + return room_id in self._quick_reply_sent + # ── release (idempotent) ────────────────────────────────────────────── def release(self, room_id: str, task_token: str) -> None: diff --git a/plugin/archivar/tests/test_outbound_gate.py b/plugin/archivar/tests/test_outbound_gate.py index b78bd79..9bc1be4 100644 --- a/plugin/archivar/tests/test_outbound_gate.py +++ b/plugin/archivar/tests/test_outbound_gate.py @@ -280,3 +280,69 @@ def test_outbound_gate_stats_defaults(): assert stats.quick_reply == 0 assert stats.stale_swept == 0 assert stats.released_total == 0 + + +# ═══════════════════════════════════════════════════════════════════════════ +# 6.1: mark_quick_reply_sent returns True on first call +# ═══════════════════════════════════════════════════════════════════════════ + +@pytest.mark.outbound_gate +@pytest.mark.asyncio +async def test_mark_quick_reply_sent_first_call_returns_true(): + """6.1: mark_quick_reply_sent returns True beim ersten Aufruf.""" + gate = OutboundGate() + room = "ROOM_QR_TEST_1" + token = "token-qr-1" + + await gate.try_acquire(room, token) + result = gate.mark_quick_reply_sent(room) + assert result is True, "First mark_quick_reply_sent should return True" + + gate.release(room, token) + + +# ═══════════════════════════════════════════════════════════════════════════ +# 6.2: mark_quick_reply_sent returns False on second call (idempotent) +# ═══════════════════════════════════════════════════════════════════════════ + +@pytest.mark.outbound_gate +@pytest.mark.asyncio +async def test_mark_quick_reply_sent_second_call_returns_false(): + """6.2: mark_quick_reply_sent returns False beim zweiten Aufruf (idempotent).""" + gate = OutboundGate() + room = "ROOM_QR_TEST_2" + token = "token-qr-2" + + await gate.try_acquire(room, token) + first = gate.mark_quick_reply_sent(room) + assert first is True + + second = gate.mark_quick_reply_sent(room) + assert second is False, "Second mark_quick_reply_sent should return False (idempotent)" + + gate.release(room, token) + + +# ═══════════════════════════════════════════════════════════════════════════ +# 6.3: quick_reply_already_sent returns correct before/after mark +# ═══════════════════════════════════════════════════════════════════════════ + +@pytest.mark.outbound_gate +@pytest.mark.asyncio +async def test_quick_reply_already_sent_before_and_after(): + """6.3: quick_reply_already_sent returns korrekt vor/nach mark.""" + gate = OutboundGate() + room = "ROOM_QR_TEST_3" + token = "token-qr-3" + + await gate.try_acquire(room, token) + + # Before mark: should be False + assert gate.quick_reply_already_sent(room) is False + + gate.mark_quick_reply_sent(room) + + # After mark: should be True + assert gate.quick_reply_already_sent(room) is True + + gate.release(room, token) diff --git a/plugin/archivar/tests/test_quick_reply_dedup.py b/plugin/archivar/tests/test_quick_reply_dedup.py new file mode 100644 index 0000000..1c2b958 --- /dev/null +++ b/plugin/archivar/tests/test_quick_reply_dedup.py @@ -0,0 +1,128 @@ +""" +P1 Integration-Test: Quick-Reply Dedup + UX-Text. + +Testet dass: +1. Parallele Tasks im selben Raum Quick-Reply nur 1x senden (Dedup) +2. Same-Raum-Trigger Text OHNE Raum-Namen produziert +""" + +from __future__ import annotations + +import asyncio +import sys +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[3])) + +from plugin.archivar.outbound_gate import OutboundGate, GateDecision + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 1: Parallele Tasks in selbem Raum → Quick-Reply nur 1x +# ═══════════════════════════════════════════════════════════════════════════ + +@pytest.mark.asyncio +async def test_quick_reply_dedup_parallel_tasks_same_room(): + """Parallele Tasks im selben Raum senden Quick-Reply nur 1x. + + Simuliert: Zwei parallele _dispatch_agent Tasks feuern gleichzeitig + und beide landen im Quick-Reply-Pfad. Der Dedup-Mechanismus + (quick_reply_sent Flag) verhindert die 2. und 3. Sendung. + """ + gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0) + + room_a = "ROOM_A_BUSY" + room_b = "ROOM_B_QR" + token_a = "token-busy-a" + token_b1 = "token-qr-b1" + token_b2 = "token-qr-b2" + + # Raum A hält das Gate (simuliert beschäftigten Agent) + await gate.try_acquire(room_a, token_a) + + # Beide Tasks für Raum B werden blockiert + decision_b1 = await gate.try_acquire(room_b, token_b1) + assert decision_b1.allow is False + assert decision_b1.reason == "different_room_busy" + + decision_b2 = await gate.try_acquire(room_b, token_b2) + assert decision_b2.allow is False + assert decision_b2.reason == "different_room_busy" + + # Simuliere: Task 1 sendet Quick-Reply + call_count = [0] + + async def fake_post_message(room_id, text): + call_count[0] += 1 + return "msg_1" + + # Task 1: mark_quick_reply_sent → True (erster) + if not gate.quick_reply_already_sent(room_b): + await fake_post_message(room_b, "quick reply") + gate.mark_quick_reply_sent(room_b) + gate.stats.quick_reply += 1 + + assert call_count[0] == 1 + assert gate.quick_reply_already_sent(room_b) is True + + # Task 2: quick_reply_already_sent → True → skip + if not gate.quick_reply_already_sent(room_b): + await fake_post_message(room_b, "quick reply") + gate.mark_quick_reply_sent(room_b) + gate.stats.quick_reply += 1 + + # Task 2 sollte NICHT gesendet haben + assert call_count[0] == 1, ( + f"Expected 1 Quick-Reply, got {call_count[0]} — Dedup failed" + ) + + # Cleanup + gate.release(room_a, token_a) + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 2: Same-Raum-Trigger → Text enthält NICHT den Raum-Namen +# ═══════════════════════════════════════════════════════════════════════════ + +@pytest.mark.asyncio +async def test_quick_reply_same_room_text_no_room_name(): + """Same-Raum-Trigger produziert Text OHNE Raum-Referenz. + + Wenn der Agent im selben Raum beschäftigt ist wo die neue Nachricht + reinkommt, soll der Quick-Reply-Text keine Raum-Referenz enthalten + (zirkulärer Text vermeiden). + """ + gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0) + + room_same = "ROOM_SAME" + token = "token-same" + + # Agent ist in room_same beschäftigt + await gate.try_acquire(room_same, token) + + # Simuliere _maybe_send_quick_reply mit same-room Logik + active_room_id = room_same + gate_room_id = room_same + active_room_name = "Testraum" + + same_room = (active_room_id is not None and active_room_id == gate_room_id) + if same_room: + text = 'Ich bin gerade beschäftigt — einen Moment bitte, ich bin gleich bei dir.' + elif active_room_name: + text = f'Ich antworte gerade in #{active_room_name} — einen Moment bitte, ich bin gleich bei dir.' + else: + text = 'Ich antworte gerade in einem anderen Raum — einen Moment bitte, ich bin gleich bei dir.' + + # Same-Raum: Text darf KEINEN Raum-Namen enthalten + assert "Testraum" not in text, ( + f"Same-room text should NOT contain room name, got: {text}" + ) + assert "#" not in text, ( + f"Same-room text should NOT contain #, got: {text}" + ) + assert "Ich bin gerade beschäftigt" in text + + gate.release(room_same, token)