3 Commits

Author SHA1 Message Date
Bernd (Hermes) f21075eddd refactor: onboarding_active_skip -> onboarding_response_routed (Telemetrie-Klarheit)
Der alte Name 'onboarding_active_skip' war irrefuehrend — es ist kein
Bypass/Skip, sondern ein Post-Dispatch-Counter der zaehlt, wie oft eine
Onboarding-Antwort erfolgreich geroutet wurde.
2026-07-24 20:26:03 +02:00
Bernd (Hermes) b637fcc370 test: Integration-Test Onboarding-Button-Klick setzt Raum-Theme korrekt
- test_button_click_with_suffix_starts_interview: :: Suffix -> Interview start
- test_button_click_without_suffix_is_silent_noop: ohne :: -> stiller No-Op
- test_button_click_without_suffix_corrupts_theme_during_interview: Bug-Repro
- test_button_click_with_suffix_does_not_corrupt_theme: Fix-Verifikation
- test_num_button_with_suffix_produces_double_colon: Payload-Check
- test_special_button_without_suffix_uses_prefix_only: Backward-compat
- test_two_tuple_backward_compat: Review-Flow unveraendert
- test_mixed_buttons: Gemischte Buttons
2026-07-24 20:25:31 +02:00
Bernd (Hermes) 68f3845929 fix(P0): button_builder msg-Payload mit :: Suffix — Onboarding-Button-Klick wird wieder erkannt
ROOT CAUSE: button_builder.py setzte msg = prefix (nur 'ONBOARD:<rid>'),
aber _process_onboarding_response erwartet '::' in text als Trigger fuer
Button-Klick-Handler. Ohne '::' -> Fallthrough zu Text-Antwort-Handler
-> Theme wird mit Room-ID als Literal ueberschrieben (stille Korruption).

FIX (Rainer Option B — explizite Signatur):
- build_button_attachments: num_buttons jetzt (label, prefix[, suffix]),
  special_buttons (label, prefix, style[, suffix])
- msg_payload = f'{prefix}::{suffix}' wenn suffix, sonst prefix (backward-compat)
- adapter.py: 3 Aufrufer (_send_onboarding_message, _onboarding_next_room,
  _finish_onboarding) uebergeben jetzt (clean_name, f'ONBOARD:{rid}', f'select_{rid}')
- Review-Flow (onboarding_review.py) unveraendert — 2-Tupel ohne suffix
  bleiben backward-compatibel
2026-07-24 20:23:38 +02:00
3 changed files with 340 additions and 14 deletions
+5 -5
View File
@@ -2236,8 +2236,8 @@ class RocketChatAdapter(BasePlatformAdapter):
if is_onboarding: if is_onboarding:
await self._process_onboarding_response(text, room_id) await self._process_onboarding_response(text, room_id)
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Onboarding active — skipping") logger.debug("[rocketchat] ARCHIVAR-DEBUG: Onboarding active — skipping")
routing_counter.increment('onboarding_active_skip') routing_counter.increment('onboarding_response_routed')
logger.info("ROUTING BYPASS: reason=onboarding_active_skip, origin_room=%s", room_id) logger.info("ROUTING BYPASS: reason=onboarding_response_routed, origin_room=%s", room_id)
return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig
# ── Move-Request-Antwort? (VOR Archivar-Klassifikation!) ──────── # ── Move-Request-Antwort? (VOR Archivar-Klassifikation!) ────────
@@ -4699,7 +4699,7 @@ class RocketChatAdapter(BasePlatformAdapter):
for room in missing_rooms: for room in missing_rooms:
rid = room["room_id"] rid = room["room_id"]
clean_name = room["name"].lstrip("#") clean_name = room["name"].lstrip("#")
num_buttons.append((clean_name, f"ONBOARD:{rid}")) num_buttons.append((clean_name, f"ONBOARD:{rid}", f"select_{rid}"))
special_buttons = [ special_buttons = [
("⏭️ Alle überspringen", "ONBOARD", "default"), ("⏭️ Alle überspringen", "ONBOARD", "default"),
@@ -5830,7 +5830,7 @@ class RocketChatAdapter(BasePlatformAdapter):
for room in remaining: for room in remaining:
rid = room["room_id"] rid = room["room_id"]
clean_name = room["name"].lstrip("#") clean_name = room["name"].lstrip("#")
num_buttons.append((clean_name, f"ONBOARD:{rid}")) num_buttons.append((clean_name, f"ONBOARD:{rid}", f"select_{rid}"))
special_buttons = [ special_buttons = [
("⏭️ Überspringen", "ONBOARD", "default"), ("⏭️ Überspringen", "ONBOARD", "default"),
@@ -5923,7 +5923,7 @@ class RocketChatAdapter(BasePlatformAdapter):
from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS
num_buttons = [] num_buttons = []
for rid, name, is_catch in all_rooms: for rid, name, is_catch in all_rooms:
num_buttons.append((name, f"ONBOARD:{rid}")) num_buttons.append((name, f"ONBOARD:{rid}", f"select_{rid}"))
special_buttons = [ special_buttons = [
("⏭️ Überspringen", "ONBOARD", "default"), ("⏭️ Überspringen", "ONBOARD", "default"),
+24 -9
View File
@@ -11,15 +11,15 @@ Regeln:
- Jedes Attachment hat max 3 actions - Jedes Attachment hat max 3 actions
""" """
from typing import List, Tuple from typing import Any, List, Tuple
# Emoji-Nummern für bis zu 10 Buttons # Emoji-Nummern für bis zu 10 Buttons
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
def build_button_attachments( def build_button_attachments(
num_buttons: List[Tuple[str, str]], num_buttons: List[Tuple[Any, ...]],
special_buttons: List[Tuple[str, str, str]], special_buttons: List[Tuple[Any, ...]],
color: str = "#1d74f5", color: str = "#1d74f5",
title: str = "", title: str = "",
number_buttons: bool = True, number_buttons: bool = True,
@@ -34,9 +34,15 @@ def build_button_attachments(
IMMER in separatem (letztem) Attachment IMMER in separatem (letztem) Attachment
- Jedes Attachment hat max 3 actions - Jedes Attachment hat max 3 actions
P0-Fix: msg-Payload mit '::' Suffix für Button-Klick-Erkennung.
num_buttons: (label, prefix) oder (label, prefix, suffix)
special_buttons: (label, prefix, style) oder (label, prefix, suffix, style)
Wenn suffix vorhanden: msg = f'{prefix}::{suffix}'
Sonst (backward-compat): msg = prefix
Args: Args:
num_buttons: Liste von (label, prefix) Tuples für nummerierte Buttons num_buttons: Liste von (label, prefix[, suffix]) Tuples
special_buttons: Liste von (label, prefix, style) Tuples für Sonderschaltflächen special_buttons: Liste von (label, prefix, style[, suffix]) Tuples
color: Attachment-Farbe (default: "#1d74f5") color: Attachment-Farbe (default: "#1d74f5")
title: Attachment-Titel (nur für erstes Attachment) title: Attachment-Titel (nur für erstes Attachment)
number_buttons: Wenn False, werden Buttons NICHT nummeriert number_buttons: Wenn False, werden Buttons NICHT nummeriert
@@ -52,7 +58,11 @@ def build_button_attachments(
for i in range(0, len(num_buttons), 3): for i in range(0, len(num_buttons), 3):
chunk = num_buttons[i:i + 3] chunk = num_buttons[i:i + 3]
actions = [] actions = []
for j, (label, prefix) in enumerate(chunk): for j, tup in enumerate(chunk):
label = tup[0]
prefix = tup[1]
suffix = tup[2] if len(tup) >= 3 else None
msg_payload = f"{prefix}::{suffix}" if suffix else prefix
if number_buttons: if number_buttons:
num_idx = i + j num_idx = i + j
emoji = EMOJI_NUMBERS[num_idx] if num_idx < len(EMOJI_NUMBERS) else str(num_idx + 1) emoji = EMOJI_NUMBERS[num_idx] if num_idx < len(EMOJI_NUMBERS) else str(num_idx + 1)
@@ -62,7 +72,7 @@ def build_button_attachments(
actions.append({ actions.append({
"type": "button", "type": "button",
"text": text, "text": text,
"msg": prefix, "msg": msg_payload,
"msg_in_chat_window": True, "msg_in_chat_window": True,
"style": button_style, "style": button_style,
}) })
@@ -77,11 +87,16 @@ def build_button_attachments(
# Sonderschaltflächen in separatem Attachment # Sonderschaltflächen in separatem Attachment
if special_buttons: if special_buttons:
special_actions = [] special_actions = []
for label, prefix, style in special_buttons: for tup in special_buttons:
label = tup[0]
prefix = tup[1]
style = tup[2]
suffix = tup[3] if len(tup) >= 4 else None
msg_payload = f"{prefix}::{suffix}" if suffix else prefix
special_actions.append({ special_actions.append({
"type": "button", "type": "button",
"text": label, "text": label,
"msg": prefix, "msg": msg_payload,
"msg_in_chat_window": True, "msg_in_chat_window": True,
"style": style, "style": style,
}) })
+311
View File
@@ -0,0 +1,311 @@
"""
P0 Integration-Test: Onboarding-Button-Klick setzt Raum-Theme korrekt.
ROOT CAUSE: button_builder.py setzte msg = prefix (nur 'ONBOARD:<rid>'),
ohne '::' Suffix. _process_onboarding_response erwartet '::' als Trigger
fuer Button-Klick-Handler. Ohne '::' -> Fallthrough zu Text-Antwort-Handler
-> Theme wird mit Room-ID als Literal ueberschrieben (stille Korruption).
Dieser Test verifiziert:
1. ONBOARD:<rid>::select_<rid> wird als Button-Klick erkannt
2. _handle_onboarding_button_click wird aufgerufen (nicht interview answer)
3. build_button_attachments produziert korrekte msg-Payloads
4. Backward-compat: 2-Tupel ohne suffix -> msg = prefix
"""
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[1]))
# ═══════════════════════════════════════════════════════════════════════════
# Helpers
# ═══════════════════════════════════════════════════════════════════════════
def _make_mock_adapter():
"""Erzeugt einen minimalen Mock-Adapter mit Onboarding-State."""
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
# Grundlegende Attribute
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = MagicMock()
adapter._room_info = {}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {}
adapter._clarify_state = {}
adapter._room_map_summary = ""
# Mock REST
mock_rest = MagicMock()
mock_rest.auth_token = "fake-token"
mock_rest.user_id = "fake-user-id"
mock_rest.post_message = MagicMock(return_value="msg_12345")
adapter.rest = mock_rest
# Mock Archivar
mock_archivar = MagicMock()
mock_archivar._room_map = MagicMock()
mock_archivar._stats = {"onboarding_active": True}
mock_archivar._state = MagicMock()
adapter.archivar = mock_archivar
# Mock Post-Message
adapter._post_message_with_retry = AsyncMock(return_value=True)
# Mock _ask_onboarding_question (damit kein echter Rocket.Chat-Call)
adapter._ask_onboarding_question = AsyncMock()
# Mock _onboarding_next_room
adapter._onboarding_next_room = AsyncMock()
return adapter
# ═══════════════════════════════════════════════════════════════════════════
# Tests: Dispatch-Pfad
# ═══════════════════════════════════════════════════════════════════════════
class TestOnboardingButtonClickDispatch:
"""P0: ONBOARD:<rid>::select_<rid> wird als Button-Klick erkannt."""
def test_button_click_with_suffix_starts_interview(self):
"""ONBOARD:<rid>::select_<rid> -> _handle_onboarding_button_click
-> Interview wird gestartet (current_room_index=0, current_question=1)."""
adapter = _make_mock_adapter()
test_rid = "room_test_123"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#Testraum"},
],
"current_room_index": -1,
"current_question": 0,
"collected_data": {},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick mit :: Suffix (der Fix)
button_text = f"ONBOARD:{test_rid}::select_{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
state = adapter._onboarding_state
assert state["current_room_index"] == 0, (
f"current_room_index sollte 0 sein (Interview gestartet), "
f"ist aber {state['current_room_index']}"
)
assert state["current_question"] == 1, (
f"current_question sollte 1 sein (Frage 1: Theme), "
f"ist aber {state['current_question']}"
)
assert test_rid in state["collected_data"], (
f"collected_data sollte Eintrag fuer {test_rid} enthalten"
)
adapter._ask_onboarding_question.assert_called_once()
def test_button_click_without_suffix_is_silent_noop(self):
"""ONBOARD:<rid> ohne :: -> Fallthrough zu interview answer
-> current_q=0 -> early return (stiller No-Op, kein Interview)."""
adapter = _make_mock_adapter()
test_rid = "room_test_456"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#Bugraum"},
],
"current_room_index": -1,
"current_question": 0,
"collected_data": {},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick OHNE :: Suffix (alter Bug)
button_text = f"ONBOARD:{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
state = adapter._onboarding_state
# Kein Interview gestartet — stiller No-Op
assert state["current_room_index"] == -1, (
f"Ohne :: sollte kein Interview gestartet werden, "
f"current_room_index ist {state['current_room_index']}"
)
assert state["current_question"] == 0
# _ask_onboarding_question wurde NICHT aufgerufen
adapter._ask_onboarding_question.assert_not_called()
def test_button_click_without_suffix_corrupts_theme_during_interview(self):
"""Der eigentliche Bug: Wenn Interview laeuft (current_q=1),
wird ONBOARD:<rid> ohne :: als Theme-Text interpretiert
-> Theme = 'ONBOARD:<rid>' (stille Korruption)."""
adapter = _make_mock_adapter()
test_rid = "room_test_789"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#Korrumpiert"},
],
"current_room_index": 0,
"current_question": 1, # Frage 1: Theme
"collected_data": {
test_rid: {"theme": "", "keywords_100": [], "keywords_context": [], "catch_all": False},
},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick OHNE :: Suffix (alter Bug)
button_text = f"ONBOARD:{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
# BUG REPRODUZIERT: Theme wurde mit Room-ID als Literal ueberschrieben
state = adapter._onboarding_state
theme = state["collected_data"][test_rid]["theme"]
assert theme == f"ONBOARD:{test_rid}", (
f"BUG REPRODUZIERT: Theme wurde mit '{theme}' ueberschrieben "
f"(sollte NICHT die Room-ID als Literal enthalten)"
)
def test_button_click_with_suffix_does_not_corrupt_theme(self):
"""Mit :: Suffix: Button-Klick wird korrekt erkannt,
Theme bleibt unberuehrt (wird nicht mit Room-ID ueberschrieben)."""
adapter = _make_mock_adapter()
test_rid = "room_test_fixed"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#FixTest"},
],
"current_room_index": -1,
"current_question": 0,
"collected_data": {},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick MIT :: Suffix (der Fix)
button_text = f"ONBOARD:{test_rid}::select_{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
state = adapter._onboarding_state
data = state["collected_data"].get(test_rid, {})
theme = data.get("theme", "")
assert theme == "", (
f"Theme sollte leer sein (''), ist aber '{theme}' — "
f"Room-ID wurde faelschlich als Theme gesetzt"
)
# ═══════════════════════════════════════════════════════════════════════════
# Tests: button_builder Payload
# ═══════════════════════════════════════════════════════════════════════════
class TestButtonBuilderPayload:
"""P0: build_button_attachments produziert korrekte msg-Payloads."""
def test_num_button_with_suffix_produces_double_colon(self):
"""3-Tupel (label, prefix, suffix) -> msg = 'prefix::suffix'."""
from plugin.archivar.button_builder import build_button_attachments
test_rid = "room_bb_test"
num_buttons = [
("Testraum", f"ONBOARD:{test_rid}", f"select_{test_rid}"),
]
attachments = build_button_attachments(
num_buttons, [], color="#1d74f5",
)
num_action = attachments[0]["actions"][0]
assert num_action["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}", (
f"num_button msg sollte 'ONBOARD:{test_rid}::select_{test_rid}' sein, "
f"ist aber '{num_action['msg']}'"
)
def test_special_button_without_suffix_uses_prefix_only(self):
"""3-Tupel (label, prefix, style) ohne suffix -> msg = prefix (backward-compat)."""
from plugin.archivar.button_builder import build_button_attachments
special_buttons = [
("⏭️ Überspringen", "ONBOARD", "default"),
]
attachments = build_button_attachments(
[], special_buttons, color="#1d74f5",
)
special_action = attachments[0]["actions"][0]
assert special_action["msg"] == "ONBOARD", (
f"special_button msg sollte 'ONBOARD' sein (backward-compat), "
f"ist aber '{special_action['msg']}'"
)
def test_two_tuple_backward_compat(self):
"""2-Tupel (label, prefix) ohne suffix -> msg = prefix (backward-compat)."""
from plugin.archivar.button_builder import build_button_attachments
num_buttons = [
("ReviewRaum", "REVIEW_ROOM_EDIT::rid123::edit"),
]
attachments = build_button_attachments(
num_buttons, [], color="#1d74f5",
)
num_action = attachments[0]["actions"][0]
assert num_action["msg"] == "REVIEW_ROOM_EDIT::rid123::edit", (
f"2-Tupel msg sollte unveraendert 'REVIEW_ROOM_EDIT::rid123::edit' sein, "
f"ist aber '{num_action['msg']}'"
)
def test_mixed_buttons(self):
"""Gemischt: num_buttons mit suffix, special_buttons ohne suffix."""
from plugin.archivar.button_builder import build_button_attachments
test_rid = "room_mixed"
num_buttons = [
("Raum A", f"ONBOARD:{test_rid}", f"select_{test_rid}"),
("Raum B", f"ONBOARD:other_rid", f"select_other_rid"),
]
special_buttons = [
("⏭️ Skip", "ONBOARD", "default"),
("⏰ Später", "ONBOARD", "default"),
]
attachments = build_button_attachments(
num_buttons, special_buttons, color="#1d74f5",
)
# Erstes Attachment: num_buttons
assert attachments[0]["actions"][0]["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}"
assert attachments[0]["actions"][1]["msg"] == "ONBOARD:other_rid::select_other_rid"
# Zweites Attachment: special_buttons
assert attachments[1]["actions"][0]["msg"] == "ONBOARD"
assert attachments[1]["actions"][1]["msg"] == "ONBOARD"