fix: Bug 3 (Onboarding-Buttons), Bug 4 (Move-Request-Sticky), Bug 5 (room-map.json), B9 (Auto-Onboarding)
Bug 3 — Onboarding-Buttons als Text statt interactive: - adapter.py: Neue Methode _get_build_custom_buttons() mit lokalem Fallback der korrekte Rocket.Chat Button-Dicts baut, wenn das rocketchat-Modul nicht in sys.modules ist (Race-Condition beim Import) - _start_onboarding() nutzt jetzt _get_build_custom_buttons() statt des Modul-Level-Fallbacks _build_custom_buttons (der [] liefern kann) - _onboarding_next_room() ebenfalls auf _get_build_custom_buttons() umgestellt - Operator-DM-Erkennung nicht mehr hardcoded auf 'andreas' — nimmt ersten DM - Selbsterklärende Onboarding-Nachricht mit Emoji und Kontext Bug 4 — Move-Request-Schleife, Sticky greift nicht: - Option 2 (Generell hier): Persistiert jetzt in ArchivarState (set_room_state(room_id, 'never_route', username)) — überlebt Neustarts - Option 3 (Hier bleiben): Stay-Counter — nach 3x Stay in 10 Min wird der Raum automatisch auf never_route promoted - _sticky_rooms (in-memory) bleibt als schneller Cache erhalten Bug 5 — Falsche room-map.json wird geladen: - install.sh: Alle 3 room-map.json-Deploy-Stellen prüfen jetzt, ob die existierende Datei 0 Räume enthält (leeres Template) → dann neu deployen - Verhindert dass das leere Template nach Erstinstallation für immer bleibt B9 — Auto-Onboarding ohne Vorkenntnisse: - connect(): Trigger prüft jetzt: MULTIROOM_AGENT=true + Räume ohne Map-Eintrag + Ausnahme: Nur DM → kein Onboarding - Zusätzlich: Wenn room-map.json 0 Räume hat → Onboarding für ALLE non-DM-Räume - _finish_onboarding(): FAISS-Index wird nach Onboarding neu gebaut + gespeichert - _is_user_operator(): Nicht mehr hardcoded — erster DM-User wird Operator Syntax-Check: Alle .py (20 Dateien) + install.sh → OK
This commit is contained in:
+79
-9
@@ -459,9 +459,35 @@ perform_update() {
|
||||
if [ "$RC_MULTIROOM" = "true" ]; then
|
||||
local room_map_data_dir="$HOME/.hermes/hermes-agent/data"
|
||||
mkdir -p "$room_map_data_dir"
|
||||
if [ ! -f "$room_map_data_dir/room-map.json" ] && [ -f "$script_dir/templates/room-map.json" ]; then
|
||||
cp "$script_dir/templates/room-map.json" "$room_map_data_dir/room-map.json"
|
||||
msg room_map_deployed "$room_map_data_dir/room-map.json"
|
||||
local room_map_file="$room_map_data_dir/room-map.json"
|
||||
local template_file="$script_dir/templates/room-map.json"
|
||||
local deploy_template=false
|
||||
|
||||
if [ ! -f "$room_map_file" ]; then
|
||||
# Keine room-map.json vorhanden → Template deployen
|
||||
deploy_template=true
|
||||
elif [ -f "$room_map_file" ] && [ -f "$template_file" ]; then
|
||||
# Bug 5 fix: Prüfe ob die existierende room-map.json das leere Template ist
|
||||
# (keine echten Räume, nur PLACEHOLDER_VAULT_PATH)
|
||||
local room_count
|
||||
room_count=$(python3 -c "
|
||||
import json
|
||||
try:
|
||||
with open('$room_map_file') as f:
|
||||
data = json.load(f)
|
||||
rooms = data.get('rooms', {})
|
||||
print(len(rooms))
|
||||
except: print(0)
|
||||
" 2>/dev/null || echo "0")
|
||||
if [ "$room_count" = "0" ]; then
|
||||
echo " ℹ️ room-map.json is empty template — will deploy fresh"
|
||||
deploy_template=true
|
||||
fi
|
||||
fi
|
||||
|
||||
if $deploy_template && [ -f "$template_file" ]; then
|
||||
cp "$template_file" "$room_map_file"
|
||||
msg room_map_deployed "$room_map_file"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -651,9 +677,31 @@ perform_update_only() {
|
||||
if [ "$RC_MULTIROOM" = "true" ]; then
|
||||
local room_map_data_dir="$HOME/.hermes/hermes-agent/data"
|
||||
mkdir -p "$room_map_data_dir"
|
||||
if [ ! -f "$room_map_data_dir/room-map.json" ] && [ -f "$script_dir/templates/room-map.json" ]; then
|
||||
cp "$script_dir/templates/room-map.json" "$room_map_data_dir/room-map.json"
|
||||
msg room_map_deployed "$room_map_data_dir/room-map.json"
|
||||
local room_map_file="$room_map_data_dir/room-map.json"
|
||||
local template_file="$script_dir/templates/room-map.json"
|
||||
local deploy_template=false
|
||||
|
||||
if [ ! -f "$room_map_file" ]; then
|
||||
deploy_template=true
|
||||
elif [ -f "$room_map_file" ] && [ -f "$template_file" ]; then
|
||||
local room_count
|
||||
room_count=$(python3 -c "
|
||||
import json
|
||||
try:
|
||||
with open('$room_map_file') as f:
|
||||
data = json.load(f)
|
||||
rooms = data.get('rooms', {})
|
||||
print(len(rooms))
|
||||
except: print(0)
|
||||
" 2>/dev/null || echo "0")
|
||||
if [ "$room_count" = "0" ]; then
|
||||
deploy_template=true
|
||||
fi
|
||||
fi
|
||||
|
||||
if $deploy_template && [ -f "$template_file" ]; then
|
||||
cp "$template_file" "$room_map_file"
|
||||
msg room_map_deployed "$room_map_file"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -975,9 +1023,31 @@ fi
|
||||
if [ "$RC_MULTIROOM" = "true" ]; then
|
||||
ROOM_MAP_DATA_DIR="$HOME/.hermes/hermes-agent/data"
|
||||
mkdir -p "$ROOM_MAP_DATA_DIR"
|
||||
if [ ! -f "$ROOM_MAP_DATA_DIR/room-map.json" ] && [ -f "$SCRIPT_DIR/templates/room-map.json" ]; then
|
||||
cp "$SCRIPT_DIR/templates/room-map.json" "$ROOM_MAP_DATA_DIR/room-map.json"
|
||||
msg room_map_deployed "$ROOM_MAP_DATA_DIR/room-map.json"
|
||||
ROOM_MAP_FILE="$ROOM_MAP_DATA_DIR/room-map.json"
|
||||
TEMPLATE_FILE="$SCRIPT_DIR/templates/room-map.json"
|
||||
DEPLOY_TEMPLATE=false
|
||||
|
||||
if [ ! -f "$ROOM_MAP_FILE" ]; then
|
||||
DEPLOY_TEMPLATE=true
|
||||
elif [ -f "$ROOM_MAP_FILE" ] && [ -f "$TEMPLATE_FILE" ]; then
|
||||
# Bug 5 fix: Prüfe ob die existierende room-map.json das leere Template ist
|
||||
ROOM_COUNT=$(python3 -c "
|
||||
import json
|
||||
try:
|
||||
with open('$ROOM_MAP_FILE') as f:
|
||||
data = json.load(f)
|
||||
rooms = data.get('rooms', {})
|
||||
print(len(rooms))
|
||||
except: print(0)
|
||||
" 2>/dev/null || echo "0")
|
||||
if [ "$ROOM_COUNT" = "0" ]; then
|
||||
DEPLOY_TEMPLATE=true
|
||||
fi
|
||||
fi
|
||||
|
||||
if $DEPLOY_TEMPLATE && [ -f "$TEMPLATE_FILE" ]; then
|
||||
cp "$TEMPLATE_FILE" "$ROOM_MAP_FILE"
|
||||
msg room_map_deployed "$ROOM_MAP_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
+131
-14
@@ -619,9 +619,26 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||||
for rid, info in self._room_info.items()
|
||||
}
|
||||
# B9: Trigger-Bedingungen für Auto-Onboarding
|
||||
# 1. MULTIROOM_AGENT=true (bereits geprüft durch _MULTIROOM())
|
||||
# 2. Gateway findet Räume die nicht in room-map.json stehen
|
||||
# 3. Ausnahme: Nur DM → kein Onboarding
|
||||
non_dm_rooms = {rid: info for rid, info in subscribed_with_types.items()
|
||||
if info.get("type") in ("c", "p")}
|
||||
if not non_dm_rooms:
|
||||
logger.info("[rocketchat] B9: Nur DM-Räume gefunden — kein Onboarding nötig")
|
||||
else:
|
||||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||||
if missing and _MULTIROOM():
|
||||
if missing:
|
||||
logger.info("[rocketchat] B9: %d Räume fehlen in room-map.json — starte Auto-Onboarding", len(missing))
|
||||
await self._start_onboarding(missing)
|
||||
else:
|
||||
# B9: Prüfe ob room-map.json leer ist (0 Räume) → trotzdem Onboarding
|
||||
room_count = len(self.archivar._room_map.rooms) if self.archivar._room_map else 0
|
||||
if room_count == 0:
|
||||
logger.info("[rocketchat] B9: room-map.json ist leer (0 Räume) — starte Auto-Onboarding für %d Räume", len(non_dm_rooms))
|
||||
all_rooms = [{"room_id": rid, "name": info["name"]} for rid, info in non_dm_rooms.items()]
|
||||
await self._start_onboarding(all_rooms)
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
||||
self._mark_connected()
|
||||
@@ -866,13 +883,41 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
feedback_type = "confirm"
|
||||
elif choice in ("2", "2️⃣", "generell", "generell hier bleiben"):
|
||||
# 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag
|
||||
# Bug 4 fix: Persistiere in ArchivarState (überlebt Gateway-Neustarts)
|
||||
self._sticky_rooms[room_id] = time.time()
|
||||
await self._post_message_with_retry(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
try:
|
||||
self.archivar._state.set_room_state(room_id, "never_route", username)
|
||||
logger.info("[rocketchat] Sticky persisted: room %s → never_route (ArchivarState)", room_id[:8])
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] Failed to persist sticky decision: %s", e)
|
||||
await self._post_message_with_retry(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt dauerhaft)")
|
||||
feedback_type = "never"
|
||||
else:
|
||||
# 3️⃣ Hier bleiben → Antwort im Ursprungsraum (nur diesmal, kein Sticky)
|
||||
# Bug 4 fix: Track stay count — nach 3× stay in 10 Min → auto-promote zu never_route
|
||||
await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
|
||||
feedback_type = "stay"
|
||||
# Stay-Counter: Wenn der User 3× in 10 Min "Hier bleiben" klickt,
|
||||
# wird der Raum automatisch auf "never_route" gesetzt.
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
now = time.time()
|
||||
stay_key = f"stay_{room_id}"
|
||||
stay_data = self._onboarding_state.get("_stay_tracker", {}).get(stay_key, {"count": 0, "first_seen": now})
|
||||
if now - stay_data["first_seen"] > 600: # 10 Minuten Fenster
|
||||
stay_data = {"count": 0, "first_seen": now}
|
||||
stay_data["count"] += 1
|
||||
if "_stay_tracker" not in self._onboarding_state:
|
||||
self._onboarding_state["_stay_tracker"] = {}
|
||||
self._onboarding_state["_stay_tracker"][stay_key] = stay_data
|
||||
if stay_data["count"] >= 3:
|
||||
try:
|
||||
self.archivar._state.set_room_state(room_id, "never_route", username)
|
||||
self._sticky_rooms[room_id] = now
|
||||
logger.info("[rocketchat] Auto-promoted to never_route after %d stays in room %s", stay_data["count"], room_id[:8])
|
||||
await self._post_message_with_retry(room_id, "🔒 Ich habe gemerkt, dass du hier bleiben möchtest — dieser Raum wird ab jetzt nicht mehr automatisch geroutet.")
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] Failed to auto-promote sticky: %s", e)
|
||||
|
||||
# Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen
|
||||
if _MULTIROOM() and self.archivar is not None and move_req.get("message_id"):
|
||||
@@ -1212,6 +1257,39 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
log_tag, len(buttons), room_id[:8])
|
||||
return success
|
||||
|
||||
def _get_build_custom_buttons(self):
|
||||
"""Robust access to _build_custom_buttons, with fallback.
|
||||
|
||||
Returns the real _build_custom_buttons function from the rocketchat
|
||||
__init__ module. If unavailable, returns a local implementation that
|
||||
builds correct Rocket.Chat button dicts directly.
|
||||
"""
|
||||
import sys as _sys
|
||||
# Try the same lookup pattern used in send() and send_clarify()
|
||||
_init = _sys.modules.get('rocketchat')
|
||||
if _init is not None:
|
||||
fn = getattr(_init, '_build_custom_buttons', None)
|
||||
if fn is not None:
|
||||
return fn
|
||||
# Fallback: local implementation (Bug 3 fix — ensures buttons always render)
|
||||
def _local_build(labels, prefix='', style='default'):
|
||||
buttons = []
|
||||
for label in labels:
|
||||
display = label.strip()
|
||||
msg_payload = display
|
||||
if prefix:
|
||||
msg_payload = f"{prefix}::{msg_payload}"
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": display,
|
||||
"msg": msg_payload,
|
||||
"msg_in_chat_window": True,
|
||||
"style": style,
|
||||
})
|
||||
return buttons
|
||||
logger.warning("[rocketchat] _build_custom_buttons not found in rocketchat module — using local fallback")
|
||||
return _local_build
|
||||
|
||||
async def _start_onboarding(self, missing_rooms: list) -> None:
|
||||
"""v2: Sendet Onboarding-DM mit Nummern-Buttons pro fehlendem Raum.
|
||||
|
||||
@@ -1225,15 +1303,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
Args:
|
||||
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
|
||||
"""
|
||||
# Finde den Operator-DM Raum
|
||||
# Finde den Operator-DM Raum (erster DM-Raum, nicht hardcoded auf "andreas")
|
||||
operator_room_id = None
|
||||
for room_id, info in self._room_info.items():
|
||||
if info.get("type") == "d" and "andreas" in info.get("name", "").lower():
|
||||
if info.get("type") == "d":
|
||||
operator_room_id = room_id
|
||||
break
|
||||
|
||||
if not operator_room_id:
|
||||
logger.warning("[rocketchat] Operator-DM-Raum nicht gefunden, kann Onboarding nicht starten")
|
||||
logger.warning("[rocketchat] Kein DM-Raum gefunden, kann Onboarding nicht starten")
|
||||
return
|
||||
|
||||
# Initialisiere Onboarding-State
|
||||
@@ -1248,20 +1326,26 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = True
|
||||
|
||||
# Baue Nachricht mit Emoji-Nummern-Referenzen
|
||||
# _build_custom_buttons available via top-level sys.modules access
|
||||
# Bug 3 fix: Robuster Zugriff auf _build_custom_buttons
|
||||
_build = self._get_build_custom_buttons()
|
||||
|
||||
# Emoji-Zahlen für bis zu 10 Räume
|
||||
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||
|
||||
lines = ["Folgende Räume fehlen in der Raum-Map:"]
|
||||
lines = [
|
||||
"🤖 **Auto-Onboarding** — Ich habe Räume gefunden, die noch nicht in meiner Raum-Map stehen.",
|
||||
"",
|
||||
"Ich brauche deine Hilfe, um sie einzurichten. Keine Sorge — ich führe dich Schritt für Schritt durch 4 kurze Fragen pro Raum.",
|
||||
"",
|
||||
"**Fehlende Räume:**",
|
||||
]
|
||||
for i, room in enumerate(missing_rooms):
|
||||
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
|
||||
clean_name = room["name"].lstrip("#")
|
||||
lines.append(f"{emoji} {clean_name}")
|
||||
|
||||
lines.append("")
|
||||
lines.append("Klicke auf eine Nummer, um den Raum einzurichten:")
|
||||
lines.append("👉 Klicke auf eine Nummer, um den Raum einzurichten:")
|
||||
text = "\n".join(lines)
|
||||
|
||||
# Raum-Buttons: blaue Nummern (style='primary')
|
||||
@@ -1270,18 +1354,29 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
rid = room["room_id"]
|
||||
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
|
||||
prefix = f"ONBOARD:{rid}"
|
||||
buttons.extend(_build_custom_buttons(
|
||||
buttons.extend(_build(
|
||||
[emoji],
|
||||
prefix=prefix,
|
||||
style="primary"
|
||||
))
|
||||
|
||||
# Globale Buttons (style='default' = grau)
|
||||
buttons.extend(_build_custom_buttons(
|
||||
buttons.extend(_build(
|
||||
["⏭️ Alle überspringen", "⏰ Später"],
|
||||
prefix="ONBOARD"
|
||||
))
|
||||
|
||||
# Bug 3 fix: Wenn keine Buttons gebaut werden konnten, sende als Text
|
||||
# mit klarer Anleitung (Fallback, sollte nie eintreten)
|
||||
if not buttons:
|
||||
logger.error("[rocketchat] Onboarding: Konnte keine Buttons bauen — sende Text-Fallback")
|
||||
fallback_lines = lines + [
|
||||
"",
|
||||
"❌ Button-Fehler — bitte antworte mit der Nummer des Raums (1, 2, …) oder 'überspringen'.",
|
||||
]
|
||||
await self._post_message_with_retry(operator_room_id, "\n".join(fallback_lines))
|
||||
return
|
||||
|
||||
attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": "Raum-Map unvollständig — Räume einrichten?",
|
||||
@@ -1290,7 +1385,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
success = await self._post_message_with_retry(operator_room_id, text, attachments=attachments)
|
||||
if success:
|
||||
logger.info("[rocketchat] Onboarding v2 gestartet: %d Räume fehlen", len(missing_rooms))
|
||||
logger.info("[rocketchat] Onboarding v2 gestartet: %d Räume fehlen, %d Buttons", len(missing_rooms), len(buttons))
|
||||
else:
|
||||
logger.error("[rocketchat] Fehler beim Senden der Onboarding-Nachricht")
|
||||
|
||||
@@ -1568,12 +1663,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
lines.append("")
|
||||
lines.append("Klicke auf einen Button:")
|
||||
|
||||
_build = self._get_build_custom_buttons()
|
||||
buttons = []
|
||||
for room in remaining:
|
||||
rid = room["room_id"]
|
||||
clean_name = room["name"].lstrip("#")
|
||||
prefix = f"ONBOARD:{rid}"
|
||||
buttons.extend(_build_custom_buttons(
|
||||
buttons.extend(_build(
|
||||
[f"📋 {clean_name[:8]}", f"⏭️ Überspringen", f"⏰ Später"],
|
||||
prefix=prefix
|
||||
))
|
||||
@@ -1599,6 +1695,16 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"operator_room_id": operator_room_id,
|
||||
}
|
||||
|
||||
# B9: FAISS-Index nach Onboarding neu bauen
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
try:
|
||||
if self.archivar._room_index is not None and self.archivar._room_index.is_built:
|
||||
self.archivar._room_index.build_index()
|
||||
self.archivar._room_index.save()
|
||||
logger.info("[rocketchat] B9: FAISS-Index nach Onboarding neu gebaut (%d Vektoren)", self.archivar._room_index.size)
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] B9: FAISS-Index-Rebuild fehlgeschlagen: %s", e)
|
||||
|
||||
# Baue nummerierte Raumliste
|
||||
all_rooms = []
|
||||
for rid, entry in self.archivar._room_map.rooms.items():
|
||||
@@ -1674,13 +1780,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
def _is_user_operator(self, username: str) -> bool:
|
||||
"""Prüft, ob der Benutzer der Operator ist.
|
||||
|
||||
Der Operator ist der erste Benutzer, der mit dem Bot interagiert.
|
||||
Kein hardcoded Username — community-tauglich.
|
||||
|
||||
Args:
|
||||
username: Der zu prüfende Benutzername
|
||||
|
||||
Returns:
|
||||
True wenn der Benutzer der Operator ist, sonst False
|
||||
"""
|
||||
return username.lower() == "andreas"
|
||||
# Operator ist der erste User, der im DM mit dem Bot spricht.
|
||||
# Wird beim ersten DM-Kontakt gesetzt.
|
||||
if not hasattr(self, '_operator_username'):
|
||||
self._operator_username = None
|
||||
if self._operator_username is None:
|
||||
# Noch kein Operator gesetzt — der erste DM-User wird Operator
|
||||
self._operator_username = username.lower()
|
||||
logger.info("[rocketchat] Operator gesetzt: %s", username)
|
||||
return username.lower() == self._operator_username
|
||||
|
||||
async def _download_and_inline_files(self, text: str) -> str:
|
||||
"""Download files referenced as [FILE] markers and inline their content."""
|
||||
|
||||
Reference in New Issue
Block a user