From a41f5e18ed0d2a489591d434c80038b0e561d541 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 26 Jul 2026 09:36:06 +0200 Subject: [PATCH] =?UTF-8?q?fix(P0):=20stay=5Fhere/stay=5Fonce=20dispatched?= =?UTF-8?q?=20Originalnachricht=20an=20Agent=20=E2=80=94=20Datenverlust=20?= =?UTF-8?q?behoben?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root Cause: Der else-Zweig (Button 2/3: stay_here/stay_once) in _process_incoming loggte nur "skipping" und returnte, ohne die Originalnachricht aus move_req["text"] an den Agenten weiterzuleiten. Da der move_request_pending_guard den initialen Dispatch blockiert, war die Nachricht NUR in move_req["text"] verfügbar — nach dem pop() war sie komplett verloren. Fix: - else-Zweig holt origin_text aus move_req.get("text", "") - Bei leerem Text: logger.warning + return (kein Dispatch) - Setzt _CURRENT_ORIGIN_ROOM auf room_id (User bleibt im Ursprungsraum) - _THEMATIC_TARGET_ROOM wird NICHT gesetzt (kein Themenwechsel) - Dispatch via _dispatch_agent mit room_id=Ursprungsraum, category="work_order" - Telemetrie-Counter "stay_here_dispatched" wird incrementiert Tests: 3 neue Tests in test_p0_stay_here_dispatch.py - test_stay_here_dispatches_original_message - test_stay_once_dispatches_original_message - test_stay_here_empty_text_skips_dispatch Ergebnis: 1330 passed, 3 pre-existing failures, 2 skipped --- plugin/adapter.py | 30 +- .../tests/test_p0_stay_here_dispatch.py | 332 ++++++++++++++++++ 2 files changed, 360 insertions(+), 2 deletions(-) create mode 100644 plugin/archivar/tests/test_p0_stay_here_dispatch.py diff --git a/plugin/adapter.py b/plugin/adapter.py index 19c9976..0491ad9 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -2506,8 +2506,34 @@ class RocketChatAdapter(BasePlatformAdapter): ) return else: - # Button 2/3: stay in origin — no agent dispatch needed - logger.debug("[rocketchat] ARCHIVAR-DEBUG: Move-Request processed — skipping") + # Button 2/3: stay_here / stay_once — dispatch original message + # to agent in the origin room (P0 fix: data loss prevention) + origin_text = move_req.get("text", "") + if not origin_text: + logger.warning( + "[rocketchat] P0: stay_here/stay_once without origin text — " + "skipping dispatch (room=%s)", room_id[:8] + ) + return + # _CURRENT_ORIGIN_ROOM: User stays HERE (origin room) + _CURRENT_ORIGIN_ROOM.set(room_id) + # _THEMATIC_TARGET_ROOM: NOT set — no topic change + await self._dispatch_agent( + text=origin_text, + room_id=room_id, + room_name=room_name, + room_type=room_type, + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, + category="work_order", + ) + routing_counter.increment("stay_here_dispatched") + logger.info( + "[rocketchat] P0: stay_here dispatch — origin_room=%s, " + "text=[:80]%s", room_id[:8], origin_text[:80] + ) return # Move-Request verarbeitet — keine weitere Verarbeitung forwarded = False diff --git a/plugin/archivar/tests/test_p0_stay_here_dispatch.py b/plugin/archivar/tests/test_p0_stay_here_dispatch.py new file mode 100644 index 0000000..9b65837 --- /dev/null +++ b/plugin/archivar/tests/test_p0_stay_here_dispatch.py @@ -0,0 +1,332 @@ +""" +P0 Fix: stay_here/stay_once dispatches original message to agent. + +Root Cause (Rainer): +- Button 1 (confirm_move): dispatches original message correctly +- Button 2/3 (stay_here/stay_once): else-branch only logged + returned, + the original message from move_req['text'] was NEVER forwarded to the agent. +- Since the move_request_pending_guard blocks the dispatch on first arrival, + the message is ONLY available in move_req['text']. +- After self._pending_move_requests.pop(room_id), it's gone forever. + +These tests are RED before the fix and GREEN after. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import sys +import tempfile +import threading +import unittest +from pathlib import Path +from unittest.mock import MagicMock, AsyncMock + +sys.path.insert(0, str(Path(__file__).resolve().parents[3])) + + +# ── Helpers ──────────────────────────────────────────────────────────────── + + +def _make_room_map_json(tmpdir: str) -> str: + """Create a room-map.json with 2 rooms + catch-all.""" + rooms = { + "room_a": { + "name": "#Raum-A", + "theme": "Raum A", + "keywords_100": ["thema-a"], + "keywords_context": [], + "catch_all": False, + }, + "room_b": { + "name": "#Raum-B", + "theme": "Raum B", + "keywords_100": ["thema-b"], + "keywords_context": [], + "catch_all": False, + }, + "room_catchall": { + "name": "#CatchAll", + "theme": "Catch-all room", + "keywords_100": [], + "keywords_context": [], + "catch_all": True, + }, + } + data = { + "version": 5, + "rooms": rooms, + "excluded_rooms": [], + "butler_mode": "cognitive", + "fact_store_path": str(Path(tmpdir) / "docs"), + } + map_path = Path(tmpdir) / "room-map.json" + with open(map_path, "w") as f: + json.dump(data, f) + return str(map_path) + + +def _build_mock_adapter(room_map_path: str): + """Build a RocketChatAdapter with mocked external dependencies.""" + os.environ["MULTIROOM_AGENT"] = "true" + os.environ["ARCHIVAR_ROOM_MAP_PATH"] = room_map_path + os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/archivar_test_p0_stay_state.json" + os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com" + os.environ["ROCKETCHAT_USER"] = "testbot" + os.environ["ROCKETCHAT_PASSWORD"] = "testpass" + + # Clean leftover state + try: + os.remove("/tmp/archivar_test_p0_stay_state.json") + except FileNotFoundError: + pass + + from plugin.adapter import RocketChatAdapter, RocketChatREST + from archivar.conversation_history import ConversationHistory + from archivar.multiroom_context import MultiRoomContextRing + from archivar.adapter_integration import ArchivarMessageHandler + from archivar.room_map import RoomMap + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + + adapter.config = MagicMock() + adapter.config.extra = {} + adapter.platform = "rocketchat" + adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "") + adapter.user = os.getenv("ROCKETCHAT_USER", "") + adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "") + adapter.rest = RocketChatREST(adapter.base_url) + adapter.ddp = None + adapter._auth_token = None + adapter._user_id = None + adapter._rooms = [] + adapter._subscribed_rooms = set() + adapter._listen_task = None + adapter._status_timer = None + adapter._last_activity = 0.0 + adapter._shutdown_event = threading.Event() + 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._conversation_history = ConversationHistory(max_size=10) + adapter._multiroom_context = MultiRoomContextRing(max_entries=10) + adapter.archivar = ArchivarMessageHandler( + send_callback=lambda *a, **kw: None, + button_send_callback=lambda *a, **kw: None, + conversation_history=adapter._conversation_history, + ) + adapter.archivar._room_map = RoomMap.load(Path(room_map_path)) + + adapter._pending_move_requests = {} + adapter._session_room_preferences = {} + adapter._recent_auto_routes = {} + adapter._explicit_switch_sticky = {} + adapter._clarify_state = {} + adapter._pending_clarify_dispatch = {} + adapter._onboarding_state = {} + adapter._room_map_summary = "" + + # Mock the REST client + mock_rest = MagicMock(spec=RocketChatREST) + mock_rest.auth_token = "fake-token" + mock_rest.user_id = "fake-user-id" + mock_rest.post_message = MagicMock(return_value="msg_12345") + mock_rest.get_rooms = MagicMock(return_value=[ + {"id": "room_a", "name": "Raum-A", "type": "c"}, + {"id": "room_b", "name": "Raum-B", "type": "c"}, + {"id": "room_catchall", "name": "CatchAll", "type": "c"}, + ]) + adapter.rest = mock_rest + + adapter._room_info = { + "room_a": {"name": "Raum-A", "type": "c"}, + "room_b": {"name": "Raum-B", "type": "c"}, + "room_catchall": {"name": "CatchAll", "type": "c"}, + } + + adapter._dispatch_agent = AsyncMock() + adapter.handle_message = AsyncMock() + + asyncio.run(adapter.archivar.initialize()) + + # Mock gateway types + import plugin.adapter as _adapter_mod + _adapter_mod.MessageType = type('MessageType', (), { + 'TEXT': 'text', 'BUTTON_CLICK': 'button_click', + 'COMMAND': 'command', + }) + _adapter_mod.RoutingCounter = type('RoutingCounter', (), { + 'increment': lambda self, key: None, + }) + _adapter_mod.routing_counter = _adapter_mod.RoutingCounter() + + return adapter + + +# ── Test: stay_here dispatches original message ───────────────────────────── + + +class TestP0StayHereDispatchesOriginalMessage(unittest.TestCase): + """P0: stay_here/stay_once must dispatch the original message to the agent. + + Before the fix, Button 2/3 (stay_here/stay_once) only logged and returned + without dispatching the original message. The message was lost forever + because the move_request_pending_guard blocked the initial dispatch. + """ + + @classmethod + def setUpClass(cls): + cls._tmpdir = tempfile.TemporaryDirectory() + room_map_path = _make_room_map_json(cls._tmpdir.name) + cls.adapter = _build_mock_adapter(room_map_path) + + @classmethod + def tearDownClass(cls): + cls._tmpdir.cleanup() + + def setUp(self): + # Clean state before each test + self.adapter._rooms_with_pending_questions.clear() + self.adapter._pending_move_requests.clear() + self.adapter._session_room_preferences.clear() + self.adapter._dispatch_agent.reset_mock() + self.adapter.handle_message.reset_mock() + + def test_stay_here_dispatches_original_message(self): + """Button 2 (stay_here) dispatches original message to agent in origin room.""" + original_text = "Wie funktioniert der neue Trading-Algorithmus?" + + # ── Setup: Move-Request in Raum A (came from Raum A itself) ───── + self.adapter._pending_move_requests["room_a"] = { + "text": original_text, + "origin_room": "room_a", + "target_room": "room_b", + "target_name": "Raum-B", + "username": "andreas", + "message_id": "msg_001", + } + + # ── Act: Andreas klickt "2️⃣ Thema hier lassen" (stay_here) ────── + msg_obj = { + "_id": "msg_btn_001", + "rid": "room_a", + "msg": "MOVE_REQ:room_a::stay_here", + "u": {"username": "andreas", "_id": "user_andreas"}, + } + + asyncio.run(self.adapter._process_incoming(msg_obj)) + + # ── Assert: _dispatch_agent was called with original text ──────── + self.adapter._dispatch_agent.assert_called_once() + call_kwargs = self.adapter._dispatch_agent.call_args[1] + + self.assertEqual( + call_kwargs["text"], + original_text, + "P0 BUG: _dispatch_agent should receive the original message text, " + f"got: {call_kwargs['text'][:80]!r}", + ) + self.assertEqual( + call_kwargs["room_id"], + "room_a", + "P0 BUG: Agent should be dispatched in the ORIGIN room (room_a), " + f"got: {call_kwargs['room_id']}", + ) + self.assertEqual( + call_kwargs["room_name"], + "Raum-A", + f"Expected room_name='Raum-A', got: {call_kwargs['room_name']}", + ) + self.assertEqual( + call_kwargs["room_type"], + "c", + f"Expected room_type='c', got: {call_kwargs['room_type']}", + ) + self.assertEqual( + call_kwargs["username"], + "andreas", + f"Expected username='andreas', got: {call_kwargs['username']}", + ) + self.assertFalse( + call_kwargs["is_button_response"], + "is_button_response should be False for MOVE_REQ text messages " + "(they are excluded from button detection at line 1894)", + ) + self.assertEqual( + call_kwargs["category"], + "work_order", + f"Expected category='work_order', got: {call_kwargs['category']}", + ) + + def test_stay_once_dispatches_original_message(self): + """Button 3 (stay_once) dispatches original message to agent in origin room.""" + original_text = "Kannst du mir die Doku zum API-Endpoint zeigen?" + + # ── Setup: Move-Request in Raum A ─────────────────────────────── + self.adapter._pending_move_requests["room_a"] = { + "text": original_text, + "origin_room": "room_a", + "target_room": "room_b", + "target_name": "Raum-B", + "username": "andreas", + "message_id": "msg_002", + } + + # ── Act: Andreas klickt "3️⃣ Nur diesmal" (stay_once) ──────────── + msg_obj = { + "_id": "msg_btn_002", + "rid": "room_a", + "msg": "MOVE_REQ:room_a::stay_once", + "u": {"username": "andreas", "_id": "user_andreas"}, + } + + asyncio.run(self.adapter._process_incoming(msg_obj)) + + # ── Assert: _dispatch_agent was called with original text ──────── + self.adapter._dispatch_agent.assert_called_once() + call_kwargs = self.adapter._dispatch_agent.call_args[1] + + self.assertEqual( + call_kwargs["text"], + original_text, + "P0 BUG: stay_once should dispatch the original message text", + ) + self.assertEqual( + call_kwargs["room_id"], + "room_a", + "P0 BUG: stay_once should dispatch in the ORIGIN room", + ) + + def test_stay_here_empty_text_skips_dispatch(self): + """Empty move_req['text'] → no dispatch, only warning.""" + # ── Setup: Move-Request with empty text ────────────────────────── + self.adapter._pending_move_requests["room_a"] = { + "text": "", + "origin_room": "room_a", + "target_room": "room_b", + "target_name": "Raum-B", + "username": "andreas", + "message_id": "msg_003", + } + + # ── Act: Andreas klickt "2️⃣ Thema hier lassen" ────────────────── + msg_obj = { + "_id": "msg_btn_003", + "rid": "room_a", + "msg": "MOVE_REQ:room_a::stay_here", + "u": {"username": "andreas", "_id": "user_andreas"}, + } + + asyncio.run(self.adapter._process_incoming(msg_obj)) + + # ── Assert: _dispatch_agent was NOT called ─────────────────────── + self.adapter._dispatch_agent.assert_not_called()