From 9f3cc0214831a7b0cd97c2c89bf143e3d7a01c52 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sat, 1 Aug 2026 06:40:40 +0200 Subject: [PATCH] =?UTF-8?q?P1:=20Quick-Reply=20Dedup=20=E2=80=94=20zentral?= =?UTF-8?q?er=20Helper,=20kontextabh=C3=A4ngiger=20Text,=20Same-Room-Erken?= =?UTF-8?q?nung?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _maybe_send_quick_reply() in adapter.py: Dedup via OutboundGate-Flag - outbound_gate.py: quick_reply_sent-Flag in _TurnHandle, mark/check-Methoden - Same-Room: 'Ich bin gerade beschäftigt' (kein Raum-Name) - Cross-Room: 'Ich antworte gerade in #RaumX' - Tests: test_outbound_gate.py +50 Zeilen, test_quick_reply_dedup.py +83 Zeilen Re-Implementierung nach .45 Clean-Install (31.07.2026). --- plugin/adapter.py | 84 ++++++++++++++----- plugin/archivar/outbound_gate.py | 36 ++++++++ plugin/archivar/tests/test_outbound_gate.py | 50 +++++++++++ .../archivar/tests/test_quick_reply_dedup.py | 83 ++++++++++++++++++ 4 files changed, 230 insertions(+), 23 deletions(-) create mode 100644 plugin/archivar/tests/test_quick_reply_dedup.py diff --git a/plugin/adapter.py b/plugin/adapter.py index da73d03..53457c1 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -6537,6 +6537,53 @@ class RocketChatAdapter(BasePlatformAdapter): self.ddp = None logger.info("[rocketchat] Disconnected") + # ── P1: Quick-Reply Dedup Helper ────────────────────────────────── + # Zentraler Helper für Quick-Reply — verhindert 3x-Senden durch + # Dedup-Flag im _TurnHandle und kontextabhängigen Text (same-room + # vs cross-room). + + async def _maybe_send_quick_reply( + self, gate_room_id: str, active_room_id: Optional[str], active_room_name: str + ) -> Optional[SendResult]: + """Sendet Quick-Reply wenn noch keiner für diesen Raum gesendet wurde. + + Dedup: quick_reply_already_sent prüft das Flag im _TurnHandle. + Kontextabhängiger Text: + - Same-Raum (active_room_id == gate_room_id): kein Raum-Name + - Cross-Raum mit Name: „Ich antworte gerade in #RaumX — …" + - Cross-Raum ohne Name: generischer Fallback + + Returns: + SendResult wenn Quick-Reply gesendet wurde, None wenn bereits + gesendet (Dedup). + """ + if self._outbound_gate.quick_reply_already_sent(gate_room_id): + return None + + # Kontextabhängiger Text + 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} — " + f"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", + ) + return SendResult(success=True, message_id="quick_reply") + 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: @@ -6627,25 +6674,18 @@ class RocketChatAdapter(BasePlatformAdapter): decision = GateDecision(allow=False, reason="timeout") if not decision.allow: - # Quick-Reply: anderer Raum blockiert immer noch + # Quick-Reply via zentralem Helper (Dedup + kontextabhängiger Text) 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." + qr_result = await self._maybe_send_quick_reply( + _gate_room_id, active_room, active_name ) - 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, - ) - return SendResult(success=True, message_id="quick_reply") + if qr_result is not None: + return qr_result + # Dedup: Quick-Reply bereits gesendet → trotzdem return + return SendResult(success=True, message_id="quick_reply_dedup") # 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) _gate_acquired = (decision.reason == "gate_clear") @@ -7083,20 +7123,18 @@ class RocketChatAdapter(BasePlatformAdapter): except asyncio.TimeoutError: decision = GateDecision(allow=False, reason="timeout") if not decision.allow: + # Quick-Reply via zentralem Helper (Dedup + kontextabhängiger Text) 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." + qr_result = await self._maybe_send_quick_reply( + _gate_room_id, active_room, active_name ) - await self._post_message_unlocked(_gate_room_id, quick_reply_text) - self._outbound_gate.stats.quick_reply += 1 - return SendResult(success=True, message_id="quick_reply") + if qr_result is not None: + return qr_result + # Dedup: Quick-Reply bereits gesendet → trotzdem return + return SendResult(success=True, message_id="quick_reply_dedup") # 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) _gate_acquired = (decision.reason == "gate_clear") diff --git a/plugin/archivar/outbound_gate.py b/plugin/archivar/outbound_gate.py index 90a3c1e..c516db1 100644 --- a/plugin/archivar/outbound_gate.py +++ b/plugin/archivar/outbound_gate.py @@ -58,6 +58,7 @@ class _TurnHandle: real_room_id: str task: Optional[asyncio.Task] = None chat_id: str = "" + quick_reply_sent: bool = False # ── GateStats: 9 Counter für Monitoring ─────────────────────────────────── @@ -134,6 +135,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 — separates Tracking fuer Trigger-Raeume + self._quick_reply_sent: Dict[str, bool] = {} self.default_timeout_s = default_timeout_s self.max_entry_age_s = max_entry_age_s self.stats = GateStats() @@ -227,6 +230,39 @@ class OutboundGate: reason="gate_clear", ) + # ── Quick-Reply Dedup (P1) ────────────────────────────────────────── + # Separates Tracking-Dict unabhaengig von _in_flight: + # Quick-Reply wird fuer den TRIGGER-Raum gesendet, der NICHT in + # _in_flight ist (dort ist nur der aktive/beschaeftigte Raum). + + def mark_quick_reply_sent(self, room_id: str) -> bool: + """Markiert dass ein Quick-Reply fuer diesen Raum gesendet wurde. + + Idempotent: returns True beim ersten Aufruf (Quick-Reply wurde + tatsaechlich gesendet), False bei allen weiteren Aufrufen. + + Args: + room_id: Rocket.Chat Raum-ID (der Trigger-Raum, nicht der aktive). + + 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[room_id] = True + return True + return False + + def quick_reply_already_sent(self, room_id: str) -> bool: + """Prueft ob bereits ein Quick-Reply fuer 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..03378ca 100644 --- a/plugin/archivar/tests/test_outbound_gate.py +++ b/plugin/archivar/tests/test_outbound_gate.py @@ -280,3 +280,53 @@ 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 +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" + + result = gate.mark_quick_reply_sent(room) + assert result is True, "First mark_quick_reply_sent should return True" + + +# ═══════════════════════════════════════════════════════════════════════════ +# 6.2: mark_quick_reply_sent returns False on second call (idempotent) +# ═══════════════════════════════════════════════════════════════════════════ + +@pytest.mark.outbound_gate +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" + + 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)" + + +# ═══════════════════════════════════════════════════════════════════════════ +# 6.3: quick_reply_already_sent returns correct before/after mark +# ═══════════════════════════════════════════════════════════════════════════ + +@pytest.mark.outbound_gate +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" + + # 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 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..08d7f3c --- /dev/null +++ b/plugin/archivar/tests/test_quick_reply_dedup.py @@ -0,0 +1,83 @@ +""" +P1: Quick-Reply Dedup — Integration-Tests fuer _maybe_send_quick_reply. +""" + +from __future__ import annotations + +import asyncio +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[3])) +from plugin.archivar.outbound_gate import OutboundGate + + +def _make_bare_adapter(): + from plugin.adapter import RocketChatAdapter + return RocketChatAdapter.__new__(RocketChatAdapter) + + +@pytest.mark.asyncio +async def test_parallel_tasks_quick_reply_only_once(): + """Parallele Tasks → Quick-Reply nur 1x (Dedup).""" + adapter = _make_bare_adapter() + gate = OutboundGate() + adapter._outbound_gate = gate + await gate.try_acquire("ROOM_A", "token-a") + + call_count = 0 + async def mock_post(room_id, text): + nonlocal call_count; call_count += 1; return "ok" + adapter._post_message_unlocked = mock_post + + results = await asyncio.gather( + adapter._maybe_send_quick_reply("ROOM_B", "ROOM_A", "Alpha"), + adapter._maybe_send_quick_reply("ROOM_B", "ROOM_A", "Alpha"), + ) + assert call_count == 1 + assert sum(1 for r in results if r is not None) == 1 + assert sum(1 for r in results if r is None) == 1 + gate.release("ROOM_A", "token-a") + + +@pytest.mark.asyncio +async def test_same_room_quick_reply_text_no_room_name(): + """Same-Raum → Text OHNE Raum-Namen.""" + adapter = _make_bare_adapter() + gate = OutboundGate() + adapter._outbound_gate = gate + await gate.try_acquire("ROOM_S", "token-s") + + posted = [] + async def mock_post(room_id, text): + posted.append(text); return "ok" + adapter._post_message_unlocked = mock_post + + result = await adapter._maybe_send_quick_reply("ROOM_S", "ROOM_S", "Testraum") + assert result is not None + assert "Testraum" not in posted[0] + assert "#" not in posted[0] + assert "beschäftigt" in posted[0] + gate.release("ROOM_S", "token-s") + + +@pytest.mark.asyncio +async def test_cross_room_quick_reply_text_has_room_name(): + """Cross-Raum → Text MIT Raum-Namen.""" + adapter = _make_bare_adapter() + gate = OutboundGate() + adapter._outbound_gate = gate + await gate.try_acquire("ROOM_A", "token-c") + + posted = [] + async def mock_post(room_id, text): + posted.append(text); return "ok" + adapter._post_message_unlocked = mock_post + + result = await adapter._maybe_send_quick_reply("ROOM_T", "ROOM_A", "Gamma") + assert result is not None + assert "Gamma" in posted[0] + assert "#" in posted[0] + gate.release("ROOM_A", "token-c")