fix(archivar): User-Flow C — Antwort bleibt im Ursprungsraum, Nachricht wird kopiert
DM-Aufträge werden nie geroutet. Bei thematischen Fragen: Silent Copy. Bei Aufträgen: Buttons [Ja, rüberkopieren] [Hier bleiben] [Generell hier bleiben]. Architektur-Skizze: docs/archivar-user-flow-c.md
This commit is contained in:
+124
-33
@@ -380,6 +380,28 @@ class DDPClient:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
# ── Auftrag-Erkennung (User-Flow C) ────────────────────────────────────
|
||||
_AUFTRAG_KEYWORDS: list = [
|
||||
"bitte", "erstell", "mach", "änder", "konfigurier",
|
||||
"schreib", "bau", "implementier", "test", "deploy",
|
||||
"start", "stopp", "analysier", "prüf", "untersuch",
|
||||
"beheb", "fix", "korrigier", "optimier", "erweiter",
|
||||
"füg hinzu", "entfern", "lösch", "verschieb",
|
||||
"generier", "kompilier", "installier",
|
||||
]
|
||||
|
||||
|
||||
def _is_auftrag(text: str) -> bool:
|
||||
"""Heuristik: Enthält die Nachricht Imperative oder direkte Ansprache?"""
|
||||
t = text.lower()
|
||||
for kw in _AUFTRAG_KEYWORDS:
|
||||
if kw in t:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class RocketChatAdapter(BasePlatformAdapter):
|
||||
HEALTH_CHECK_INTERVAL = 60.0 # seconds
|
||||
HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect
|
||||
@@ -407,6 +429,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Key: "user:<username>", Value: list of real room_ids for that user.
|
||||
# Built during connect() from REST get_rooms.
|
||||
self._user_rooms: Dict[str, List[str]] = {}
|
||||
# Rooms where the agent has posted a question with buttons.
|
||||
# Used to keep the response in the same room — no Archivar routing,
|
||||
# no catch-all forwarding. Removed after the next user message from
|
||||
# that room (on the assumption that the response IS the button answer).
|
||||
# No timers, no cleanup — just a simple set.
|
||||
self._rooms_with_pending_questions: set = set()
|
||||
# Health-check state
|
||||
self._last_server_activity = 0.0 # ts of last DDP ping/pong or message
|
||||
self._health_check_timer: Optional[threading.Timer] = None
|
||||
@@ -414,6 +442,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._running = False
|
||||
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
||||
self.archivar = ArchivarMessageHandler(send_callback=self._send_via_archivar)
|
||||
# User-Flow C: Move-Requests + Sticky Rooms
|
||||
self._pending_move_requests: Dict[str, dict] = {}
|
||||
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
|
||||
|
||||
async def connect(self) -> bool:
|
||||
if not self.base_url or not self.user or not self.password:
|
||||
@@ -510,16 +541,21 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if not isinstance(msg_obj, dict):
|
||||
return
|
||||
|
||||
# Check if this is a button click response by looking for specific fields
|
||||
# Check if this is a button click response by looking for specific fields.
|
||||
# TWO detection paths:
|
||||
# 1. Native Rocket.Chat button events (triggerId + actions + triggerSender + payload)
|
||||
# 2. In-chat button responses via msg_in_chat_window, which arrive as regular
|
||||
# text messages containing a question_id::choice payload (e.g. "bypass_001::Ja").
|
||||
text = msg_obj.get("msg", "")
|
||||
is_button_response = (
|
||||
msg_obj.get("triggerId") and
|
||||
msg_obj.get("actions") and
|
||||
msg_obj.get("params", {}).get("triggerSender") and
|
||||
msg_obj.get("params", {}).get("payload")
|
||||
(msg_obj.get("triggerId") and
|
||||
msg_obj.get("actions") and
|
||||
msg_obj.get("params", {}).get("triggerSender") and
|
||||
msg_obj.get("params", {}).get("payload"))
|
||||
or "::" in text
|
||||
)
|
||||
|
||||
msg_id = msg_obj.get("_id", "")
|
||||
text = msg_obj.get("msg", "")
|
||||
room_id = msg_obj.get("rid", "")
|
||||
user_info = msg_obj.get("u", {})
|
||||
username = (user_info.get("username", "") or "").lower() # normalize case
|
||||
@@ -592,38 +628,90 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self._process_onboarding_response(text, room_id)
|
||||
return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig
|
||||
|
||||
# ── Archivar-Klassifikation ──────────────────────────────────
|
||||
# Klassifiziere die Nachricht und reichere den Context an
|
||||
# ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
|
||||
# Klassifiziere die Nachricht und entscheide über Copy/Routing.
|
||||
# Die Antwort des Agenten bleibt IMMER im Ursprungsraum.
|
||||
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
||||
category = ""
|
||||
decision = None
|
||||
is_auftrag = _is_auftrag(text)
|
||||
|
||||
try:
|
||||
# Button clicks and button responses are ALWAYS direct replies
|
||||
# to an agent question — they carry a question_id::choice payload
|
||||
# and must never be routed through the Archivar. Routing them
|
||||
# risks landing a one-character "A" in the catch-all room where
|
||||
# the agent sees it without the question context.
|
||||
if not is_button_response:
|
||||
decision = await self.archivar.handle_and_forward(text, origin_room_id=room_id, message_id=msg_id)
|
||||
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||||
if not is_button_response:
|
||||
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
||||
self._rooms_with_pending_questions.discard(room_id)
|
||||
elif room_id in self._sticky_rooms:
|
||||
logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8])
|
||||
elif room_type == "d" and is_auftrag:
|
||||
logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username)
|
||||
else:
|
||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||||
if decision and decision.category:
|
||||
category = decision.category
|
||||
else:
|
||||
logger.debug("[rocketchat] Button response — Archivar bypassed for %s", text[:40])
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||||
|
||||
# Forward-Antwort-Umleitung
|
||||
# Nur umleiten, wenn der Zielraum subscribed ist (nicht unrouteable).
|
||||
# is_unrouteable=True bedeutet: target_room ist nicht in den Bot-Subscriptions;
|
||||
# dann im Ursprungsraum bleiben und dort antworten.
|
||||
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
|
||||
# _CURRENT_ORIGIN_ROOM wird NIE auf den Zielraum gesetzt.
|
||||
# Die Agent-Antwort bleibt im Ursprungsraum. Nur die Nachricht
|
||||
# wird kopiert — mit User-Entscheidung bei Aufträgen.
|
||||
forwarded = False
|
||||
if (decision and hasattr(decision, 'target_room') and decision.target_room
|
||||
and decision.target_room != room_id
|
||||
and not getattr(decision, 'is_unrouteable', False)):
|
||||
_CURRENT_ORIGIN_ROOM.set(decision.target_room)
|
||||
try:
|
||||
note_text = f"Ich antworte im {getattr(decision, 'matched_room_name', None) or 'Zielraum'}."
|
||||
self.rest.post_message(room_id, note_text)
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Failed to send forward note: %s", e)
|
||||
|
||||
target_name = getattr(decision, 'matched_room_name', None) or 'Zielraum'
|
||||
|
||||
if is_auftrag:
|
||||
# Typ 2: Buttons — User entscheidet
|
||||
note = (
|
||||
f"Dein Auftrag passt thematisch besser in **{target_name}**.\n"
|
||||
f"Soll ich den Auftrag dorthin kopieren und dort abarbeiten?"
|
||||
)
|
||||
self._pending_move_requests[msg_id] = {
|
||||
"text": text,
|
||||
"origin_room": room_id,
|
||||
"target_room": decision.target_room,
|
||||
"target_name": target_name,
|
||||
"username": username,
|
||||
}
|
||||
self.rest.post_message(room_id, note)
|
||||
# Kein Forwarding — auf Button-Antwort warten
|
||||
forwarded = True
|
||||
else:
|
||||
# Typ 1: Silent Copy — Nachricht in Zielraum kopieren
|
||||
self.rest.post_message(decision.target_room,
|
||||
f"*(Thema passt zu {target_name} — von @{username})*\n{text}")
|
||||
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
|
||||
self.rest.post_message(room_id, note)
|
||||
|
||||
# Button-Antwort auf move-request?
|
||||
if msg_id in self._pending_move_requests:
|
||||
move_req = self._pending_move_requests.pop(msg_id)
|
||||
choice = text.strip().lower()
|
||||
|
||||
if "rüberkopieren" in choice:
|
||||
# Auftrag in Zielraum kopieren + Antwort dorthin
|
||||
self.rest.post_message(move_req["target_room"],
|
||||
f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}")
|
||||
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
|
||||
forwarded = True
|
||||
|
||||
elif "generell" in choice:
|
||||
self._sticky_rooms[room_id] = time.time()
|
||||
self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
|
||||
|
||||
else:
|
||||
# "Hier bleiben" — Default
|
||||
self.rest.post_message(room_id, "👍 Bleiben hier.")
|
||||
|
||||
# Nach Button-Antwort: nicht als normale Nachricht verarbeiten
|
||||
return
|
||||
|
||||
# ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
|
||||
if not forwarded:
|
||||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||
|
||||
# ── Virtual Room Translation ─────────────────────────────────
|
||||
# Replace room-based chat_id with user-based virtual chat_id.
|
||||
@@ -632,12 +720,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# #Project-Chat: room_id=XYZ789 → chat_id="user:alice"
|
||||
# Both get the same session key.
|
||||
virtual_chat_id = f"user:{username}"
|
||||
# Track the REAL room for send() to route the response back
|
||||
# Only set if no forwarding occurred (or forwarding was unrouteable)
|
||||
if not (decision and hasattr(decision, 'target_room') and decision.target_room
|
||||
and decision.target_room != room_id
|
||||
and not getattr(decision, 'is_unrouteable', False)):
|
||||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||
# _CURRENT_ORIGIN_ROOM wurde bereits oben im User-Flow-C gesetzt
|
||||
|
||||
# Ensure this user→room mapping is recorded for proaktive sends
|
||||
if virtual_chat_id not in self._user_rooms:
|
||||
@@ -1053,6 +1136,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
success = self.rest.post_message(real_room_id, content, attachments=attachments)
|
||||
if success:
|
||||
# If this message has buttons, mark the room so the next user
|
||||
# message from here stays put (no Archivar routing). Button
|
||||
# responses must be answered in the same room the question was
|
||||
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
||||
# and the agent loses context.
|
||||
if attachments:
|
||||
self._rooms_with_pending_questions.add(real_room_id)
|
||||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
return SendResult(success=False, error="chat.postMessage failed")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user