fix: P1 Quick-Reply Dedup — 3x-Bug + UX-Text-Anpassung
- outbound_gate.py: separates _quick_reply_sent Dict fuer Trigger-Raeume (nicht an _in_flight gebunden), mark_quick_reply_sent/quick_reply_already_sent - adapter.py: zentraler _maybe_send_quick_reply Helper mit Dedup + kontext- abhaengigem Text (same-room vs cross-room) - send() und send_clarify() rufen beide den Helper statt duplizierter Logik - Tests: 3 Gate-Tests (6.1-6.3) + 3 Integration-Tests (Dedup, Same-Room-Text, Cross-Room-Text) - Diff: 268 Zeilen (<300 F4-Limit)
This commit is contained in:
+46
-17
@@ -6537,26 +6537,43 @@ 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
|
||||
) -> None:
|
||||
"""Sendet Quick-Reply wenn noch nicht für diesen Raum gesendet (Dedup).
|
||||
) -> Optional[SendResult]:
|
||||
"""Sendet Quick-Reply wenn noch keiner für diesen Raum gesendet wurde.
|
||||
|
||||
P1 Fix: Verhindert dass Quick-Reply mehrfach gesendet wird wenn
|
||||
parallele Tasks aus _dispatch_agent gleichzeitig feuern.
|
||||
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 not hasattr(self, '_outbound_gate') or self._outbound_gate is None:
|
||||
return
|
||||
if self._outbound_gate.quick_reply_already_sent(gate_room_id):
|
||||
return
|
||||
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.'
|
||||
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.'
|
||||
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.'
|
||||
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)
|
||||
@@ -6565,6 +6582,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"[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:
|
||||
@@ -6656,13 +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", "")
|
||||
await self._maybe_send_quick_reply(_gate_room_id, active_room, active_name)
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
qr_result = await self._maybe_send_quick_reply(
|
||||
_gate_room_id, active_room, active_name
|
||||
)
|
||||
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")
|
||||
@@ -7100,12 +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", "")
|
||||
await self._maybe_send_quick_reply(_gate_room_id, active_room, active_name)
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
qr_result = await self._maybe_send_quick_reply(
|
||||
_gate_room_id, active_room, active_name
|
||||
)
|
||||
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")
|
||||
|
||||
@@ -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,8 +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 — verhindert Mehrfachsendung
|
||||
self._quick_reply_sent: set = set()
|
||||
# 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()
|
||||
@@ -230,26 +231,29 @@ class OutboundGate:
|
||||
)
|
||||
|
||||
# ── 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 für diesen Raum gesendet wurde.
|
||||
"""Markiert dass ein Quick-Reply fuer diesen Raum gesendet wurde.
|
||||
|
||||
Idempotent: returns True beim ersten Aufruf (Quick-Reply wurde
|
||||
tatsächlich gesendet), False bei allen weiteren Aufrufen.
|
||||
tatsaechlich gesendet), False bei allen weiteren Aufrufen.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
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.add(room_id)
|
||||
self._quick_reply_sent[room_id] = True
|
||||
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.
|
||||
"""Prueft ob bereits ein Quick-Reply fuer diesen Raum gesendet wurde.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
|
||||
@@ -287,55 +287,41 @@ def test_outbound_gate_stats_defaults():
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@pytest.mark.outbound_gate
|
||||
@pytest.mark.asyncio
|
||||
async def test_mark_quick_reply_sent_first_call_returns_true():
|
||||
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():
|
||||
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():
|
||||
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
|
||||
@@ -344,5 +330,3 @@ async def test_quick_reply_already_sent_before_and_after():
|
||||
|
||||
# After mark: should be True
|
||||
assert gate.quick_reply_already_sent(room) is True
|
||||
|
||||
gate.release(room, token)
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
"""
|
||||
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
|
||||
P1: Quick-Reply Dedup — Integration-Tests fuer _maybe_send_quick_reply.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,118 +7,77 @@ 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
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 1: Parallele Tasks in selbem Raum → Quick-Reply nur 1x
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
def _make_bare_adapter():
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
return RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_quick_reply_dedup_parallel_tasks_same_room():
|
||||
"""Parallele Tasks im selben Raum senden Quick-Reply nur 1x.
|
||||
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")
|
||||
|
||||
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)
|
||||
call_count = 0
|
||||
async def mock_post(room_id, text):
|
||||
nonlocal call_count; call_count += 1; return "ok"
|
||||
adapter._post_message_unlocked = mock_post
|
||||
|
||||
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"
|
||||
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")
|
||||
|
||||
# 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.
|
||||
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")
|
||||
|
||||
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)
|
||||
posted = []
|
||||
async def mock_post(room_id, text):
|
||||
posted.append(text); return "ok"
|
||||
adapter._post_message_unlocked = mock_post
|
||||
|
||||
room_same = "ROOM_SAME"
|
||||
token = "token-same"
|
||||
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")
|
||||
|
||||
# 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"
|
||||
@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")
|
||||
|
||||
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.'
|
||||
posted = []
|
||||
async def mock_post(room_id, text):
|
||||
posted.append(text); return "ok"
|
||||
adapter._post_message_unlocked = mock_post
|
||||
|
||||
# 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)
|
||||
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")
|
||||
|
||||
Reference in New Issue
Block a user