diff --git a/plugin/adapter.py b/plugin/adapter.py index 0491ad9..dc09b1b 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -1993,6 +1993,14 @@ class RocketChatAdapter(BasePlatformAdapter): room_type = self._room_info.get(room_id, {}).get("type", "unknown") logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80]) + # ── P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) ── + # ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task + # geht _CURRENT_ORIGIN_ROOM verloren. _room_context (global dict) überlebt. + virtual_chat_id = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(virtual_chat_id, {}) + ctx["origin_room"] = room_id + # ── V8.6 P1a: PresenceEngine — mark_busy_started (Honeymoon-Timer) ── # Graceful degradation: wenn _presence_engine nicht existiert # (z.B. in Tests die __new__ statt __init__ verwenden), skip. @@ -2210,6 +2218,11 @@ class RocketChatAdapter(BasePlatformAdapter): if pending: _CURRENT_ORIGIN_ROOM.set(room_id) _THEMATIC_TARGET_ROOM.set("") + # P1: _room_context als persistenter Fallback + vcid = f"user:{pending['username']}" + with _room_context_lock: + ctx = _room_context.setdefault(vcid, {}) + ctx["origin_room"] = room_id routing_counter.increment('archivar_clarify_dispatched') logger.info( "[rocketchat] FIX 2: Clarify dispatch — " @@ -2311,6 +2324,11 @@ class RocketChatAdapter(BasePlatformAdapter): # 1️⃣ Rüber → Antwort im Zielraum (V8.1 P3: echtes Move, kein Copy) _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) _THEMATIC_TARGET_ROOM.set(move_req["target_room"]) + # P1: _room_context als persistenter Fallback + vcid = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(vcid, {}) + ctx["origin_room"] = move_req["target_room"] forwarded = True feedback_type = "confirm" # ── V8.3-5: Topic für Sticky extrahieren ────────────── @@ -2517,6 +2535,11 @@ class RocketChatAdapter(BasePlatformAdapter): return # _CURRENT_ORIGIN_ROOM: User stays HERE (origin room) _CURRENT_ORIGIN_ROOM.set(room_id) + # P1: _room_context als persistenter Fallback + vcid = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(vcid, {}) + ctx["origin_room"] = room_id # _THEMATIC_TARGET_ROOM: NOT set — no topic change await self._dispatch_agent( text=origin_text, @@ -2635,6 +2658,11 @@ class RocketChatAdapter(BasePlatformAdapter): # c. _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum _CURRENT_ORIGIN_ROOM.set(origin_room_id) _THEMATIC_TARGET_ROOM.set("") + # P1: _room_context als persistenter Fallback + vcid = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(vcid, {}) + ctx["origin_room"] = origin_room_id # d. Sticky löschen self._session_room_preferences.pop(origin_room_id, None) # e. Ring: move_gc(target → origin) — Rückholung @@ -2730,6 +2758,11 @@ class RocketChatAdapter(BasePlatformAdapter): # a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen _CURRENT_ORIGIN_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + vcid = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(vcid, {}) + ctx["origin_room"] = target_room_id # b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel' self._session_room_preferences[room_id] = { "target_room": target_room_id, @@ -6313,6 +6346,11 @@ class RocketChatAdapter(BasePlatformAdapter): # Route: Antwort geht in den Zielraum _CURRENT_ORIGIN_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + if chat_id.startswith("user:"): + with _room_context_lock: + ctx = _room_context.setdefault(chat_id, {}) + ctx["origin_room"] = target_room_id # Strip ROOM: prefix from content content = _strip_red_flag_prefix(content) # ── Ring-Feedback: Agent-Entscheidung trainieren ── @@ -6359,28 +6397,39 @@ class RocketChatAdapter(BasePlatformAdapter): real_room_id = origin logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) else: - # Priority 1: Archivar-Kontext — nur für proaktive Nachrichten - # ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt). - thematic_target = _THEMATIC_TARGET_ROOM.get() - if thematic_target: - real_room_id = thematic_target - logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) + # P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) + # ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task + # ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt. + with _room_context_lock: + ctx = _room_context.get(chat_id, {}) + fallback_origin = ctx.get("origin_room", "") + if fallback_origin: + real_room_id = fallback_origin + routing_counter.increment('contextvar_reset_fallback') + logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id) else: - # Priority 2: proaktive Nachricht — use most recent room for this user - rooms = self._user_rooms.get(chat_id, []) - if rooms: - real_room_id = rooms[-1] # last room user was active in - logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id) + # Priority 1: Archivar-Kontext — nur für proaktive Nachrichten + # ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt). + thematic_target = _THEMATIC_TARGET_ROOM.get() + if thematic_target: + real_room_id = thematic_target + logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) else: - # Fallback: try to find any room with recent activity involving this user - logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id) - fallback_room = self._find_fallback_room_for_user(chat_id) - if fallback_room: - real_room_id = fallback_room - logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id) + # Priority 2: proaktive Nachricht — use most recent room for this user + rooms = self._user_rooms.get(chat_id, []) + if rooms: + real_room_id = rooms[-1] # last room user was active in + logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id) else: - logger.error("[rocketchat] No real room for %s, cannot send", chat_id) - return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}") + # Fallback: try to find any room with recent activity involving this user + logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id) + fallback_room = self._find_fallback_room_for_user(chat_id) + if fallback_room: + real_room_id = fallback_room + logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id) + else: + logger.error("[rocketchat] No real room for %s, cannot send", chat_id) + return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}") # ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ── # This allows the agent to request buttons by embedding markup in its @@ -6724,25 +6773,34 @@ class RocketChatAdapter(BasePlatformAdapter): else: # Priority 1: ContextVar from the message that triggered this turn origin = _CURRENT_ORIGIN_ROOM.get() - if origin: - real_room_id = origin - logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) - else: - # Priority 2: proactive message — use most recent room for this user - rooms = self._user_rooms.get(chat_id, []) - if rooms: - real_room_id = rooms[-1] # last room user was active in - logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id) + if origin: + real_room_id = origin + logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) else: - # Fallback: try to find any room with recent activity involving this user - logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id) - fallback_room = self._find_fallback_room_for_user(chat_id) - if fallback_room: - real_room_id = fallback_room - logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id) + # P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) + with _room_context_lock: + ctx = _room_context.get(chat_id, {}) + fallback_origin = ctx.get("origin_room", "") + if fallback_origin: + real_room_id = fallback_origin + routing_counter.increment('contextvar_reset_fallback') + logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id) else: - logger.error("[rocketchat] No real room for %s, cannot send", chat_id) - return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}") + # Priority 2: proactive message — use most recent room for this user + rooms = self._user_rooms.get(chat_id, []) + if rooms: + real_room_id = rooms[-1] # last room user was active in + logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id) + else: + # Fallback: try to find any room with recent activity involving this user + logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id) + fallback_room = self._find_fallback_room_for_user(chat_id) + if fallback_room: + real_room_id = fallback_room + logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id) + else: + logger.error("[rocketchat] No real room for %s, cannot send", chat_id) + return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}") # Render full option text in the message body so users # can read long choices that would be truncated in buttons. diff --git a/plugin/archivar/tests/test_v8_1_p1_contextvar.py b/plugin/archivar/tests/test_v8_1_p1_contextvar.py index bd2d70e..538f52e 100644 --- a/plugin/archivar/tests/test_v8_1_p1_contextvar.py +++ b/plugin/archivar/tests/test_v8_1_p1_contextvar.py @@ -311,5 +311,178 @@ class TestDispatchTaskContextVar(unittest.TestCase): ) +# ═══════════════════════════════════════════════════════════════════════════════ +# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) +# ═══════════════════════════════════════════════════════════════════════════════ + +class TestRoomContextFallback(unittest.TestCase): + """Tests für _room_context als Fallback bei ContextVar-Reset (P1).""" + + def setUp(self): + """Build a minimal mock adapter for send() testing.""" + import threading + from unittest.mock import MagicMock, AsyncMock + + os.environ["MULTIROOM_AGENT"] = "true" + os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com" + os.environ["ROCKETCHAT_USER"] = "testbot" + os.environ["ROCKETCHAT_PASSWORD"] = "testpass" + + from plugin.adapter import RocketChatAdapter, RocketChatREST + + self.adapter = RocketChatAdapter.__new__(RocketChatAdapter) + self.adapter.config = MagicMock() + self.adapter.config.extra = {} + self.adapter.platform = "rocketchat" + self.adapter.base_url = "https://rocket.example.com" + self.adapter.user = "testbot" + self.adapter.password = "testpass" + self.adapter.rest = MagicMock(spec=RocketChatREST) + self.adapter.rest.auth_token = "fake-token" + self.adapter.rest.user_id = "fake-user-id" + self.adapter.rest.post_message = MagicMock(return_value="msg_12345") + self.adapter.ddp = None + self.adapter._auth_token = None + self.adapter._user_id = None + self.adapter._rooms = [] + self.adapter._subscribed_rooms = set() + self.adapter._listen_task = None + self.adapter._status_timer = None + self.adapter._last_activity = 0.0 + self.adapter._shutdown_event = threading.Event() + self.adapter._room_info = {} + self.adapter._pending_clarifies = {} + self.adapter._user_rooms = {} + self.adapter._rooms_with_pending_questions = set() + self.adapter._excluded_room_ids = set() + self.adapter._last_server_activity = 0.0 + self.adapter._health_check_timer = None + self.adapter._last_ddp_ping_ok = False + self.adapter._running = False + self.adapter._pending_move_requests = {} + self.adapter._session_room_preferences = {} + self.adapter._recent_auto_routes = {} + self.adapter._explicit_switch_sticky = {} + self.adapter._clarify_state = {} + self.adapter._pending_clarify_dispatch = {} + self.adapter._onboarding_state = {} + self.adapter._room_map_summary = "" + self.adapter._post_message_with_retry = AsyncMock(return_value=True) + self.adapter._find_fallback_room_for_user = MagicMock(return_value=None) + self.adapter._replace_slash_with_double_colon = MagicMock( + side_effect=lambda x: x + ) + self.adapter._conversation_history = None # not needed for routing tests + self.adapter._multiroom_context = None + self.adapter.archivar = None + + # Import module-level state + from plugin.adapter import ( + _CURRENT_ORIGIN_ROOM, + _THEMATIC_TARGET_ROOM, + _room_context, + _room_context_lock, + _RED_FLAG_PENDING, + ) + self._CURRENT_ORIGIN_ROOM = _CURRENT_ORIGIN_ROOM + self._THEMATIC_TARGET_ROOM = _THEMATIC_TARGET_ROOM + self._room_context = _room_context + self._room_context_lock = _room_context_lock + self._RED_FLAG_PENDING = _RED_FLAG_PENDING + + def tearDown(self): + """Clean up module-level state between tests.""" + self._CURRENT_ORIGIN_ROOM.set("") + self._THEMATIC_TARGET_ROOM.set("") + self._RED_FLAG_PENDING.set({}) + with self._room_context_lock: + self._room_context.clear() + + # ── Test 6: send() mit leerer ContextVar fällt auf _room_context zurück ── + + def test_send_with_empty_contextvar_falls_back_to_room_context(self): + """ContextVar leer, _room_context hat origin_room → send verwendet _room_context. + + Szenario: Stream-Retry erzeugt neuen asyncio-Task. _CURRENT_ORIGIN_ROOM + ist leer (nicht vererbt). _room_context (global dict) hat aber noch + den origin_room aus _process_incoming. send() soll diesen Fallback nutzen. + """ + chat_id = "user:alice" + correct_room = "room_correct_123" + + # ContextVars sind LEER (simuliert Stream-Retry in neuem Task) + self._CURRENT_ORIGIN_ROOM.set("") + self._THEMATIC_TARGET_ROOM.set("") + + # _room_context hat den korrekten Raum (wurde in _process_incoming gesetzt) + with self._room_context_lock: + self._room_context[chat_id] = {"origin_room": correct_room} + + # _user_rooms ist LEER (kein Fallback über user_map) + self.adapter._user_rooms = {} + + # _find_fallback_room_for_user gibt None zurück (kein weiterer Fallback) + self.adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + result = asyncio.run( + self.adapter.send(chat_id=chat_id, content="Test response") + ) + + # Verify: send() hat _post_message_with_retry mit dem korrekten Raum aufgerufen + self.adapter._post_message_with_retry.assert_called_once() + call_args = self.adapter._post_message_with_retry.call_args + real_room_id = call_args[0][0] + self.assertEqual( + real_room_id, correct_room, + f"send() sollte _room_context Fallback nutzen: {correct_room}, " + f"bekam aber: {real_room_id}" + ) + + # ── Test 7: Stream-Retry simuliert ContextVar-Reset ───────────────── + + def test_stream_retry_simulates_fresh_contextvar(self): + """Simuliere ContextVar-Reset (leer), _room_context hat Wert, + _user_rooms falsch → Korrektes Routing über _room_context. + + Szenario: User ist in mehreren Räumen. _user_rooms hat den + FALSCHEN Raum als letzten Eintrag. ContextVar ist leer (Reset). + _room_context hat den KORREKTEN Raum. send() muss _room_context + priorisieren, nicht _user_rooms[-1]. + """ + chat_id = "user:bob" + correct_room = "room_dm_bob" + wrong_room = "room_general" + + # ContextVars sind LEER (simuliert Stream-Retry in neuem Task) + self._CURRENT_ORIGIN_ROOM.set("") + self._THEMATIC_TARGET_ROOM.set("") + + # _room_context hat den korrekten Raum + with self._room_context_lock: + self._room_context[chat_id] = {"origin_room": correct_room} + + # _user_rooms hat den FALSCHEN Raum als letzten Eintrag + self.adapter._user_rooms = { + chat_id: [wrong_room, "room_other"] + } + + # _find_fallback_room_for_user gibt None zurück + self.adapter._find_fallback_room_for_user = MagicMock(return_value=None) + + result = asyncio.run( + self.adapter.send(chat_id=chat_id, content="Test response") + ) + + # Verify: send() hat _post_message_with_retry mit dem KORREKTEN Raum aufgerufen + self.adapter._post_message_with_retry.assert_called_once() + call_args = self.adapter._post_message_with_retry.call_args + real_room_id = call_args[0][0] + self.assertEqual( + real_room_id, correct_room, + f"send() sollte _room_context ({correct_room}) priorisieren, " + f"nicht _user_rooms[-1] ({wrong_room}). Bekam: {real_room_id}" + ) + + if __name__ == "__main__": unittest.main()