Files
hermes-agent/tests/gateway/test_clarify_active_session_bypass.py
T
ygd58 525ca9ca1c fix(gateway): match the profile-namespaced session key in the clarify bypass lookup
Fixes #82975.

The adapter-level clarify reply bypass in gateway/platforms/base.py's
handle_message() built its session_key via build_session_key(...)
without a profile= argument, defaulting to the legacy agent:main
namespace. The runner registers pending clarifies under
SessionStore._generate_session_key()'s key, which DOES include
profile=self._resolve_profile_for_key(source). Under a named-profile
multiplex these diverge, so the bypass lookup at
clarify_gateway.get_pending_for_session(session_key, ...) misses --
the user's answer to a pending clarify() gets routed to the adapter's
busy-session queue instead of resolving it. The turn then hangs until
the clarify's 3600s timeout, with no inbound message: log line and no
"Gateway intercepted clarify text response" log line, matching the
reported Telegram symptom exactly.

Verified the divergence directly: _resolve_profile_for_key() returns
None when multiplex_profiles is off (default) -- byte-identical to
the prior implicit profile=None, so this only changes behavior for
multiplexed deployments, matching the issue's exact reported scope.

Fixed by using the same self._session_store._resolve_profile_for_key()
the runner's key generator calls, guarded with getattr() + a None
fallback since _session_store is set via a setter and can be unset
for adapters that never call set_session_store() -- preserving prior
behavior for any such adapter rather than introducing a new crash.

Added a regression test alongside the existing bypass coverage: with a
mocked session_store configured for profile multiplexing, a clarify
registered under the profile-namespaced key must still be found and
resolved (not routed to the busy queue). Verified as a genuine
regression by reverting the fix and confirming the new test fails
with the exact reported symptom (the message handler never gets
awaited -- the clarify lookup misses).

21/21 pass across the five directly related clarify test files;
16/16 across the broader multiplex/clarify-progress test files (no
regression).
2026-08-14 20:57:37 -07:00

143 lines
5.2 KiB
Python

"""Regression tests for clarify replies while a gateway session is busy."""
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import (
BasePlatformAdapter,
MessageEvent,
MessageType,
SendResult,
)
from gateway.session import SessionSource, build_session_key
class _ClarifyBypassAdapter(BasePlatformAdapter):
def __init__(self):
super().__init__(PlatformConfig(enabled=True, token="test"), Platform.TELEGRAM)
async def connect(self):
return True
async def disconnect(self):
pass
async def send(self, chat_id, content, reply_to=None, metadata=None):
return SendResult(success=True, message_id="text")
async def get_chat_info(self, chat_id):
return {"id": chat_id, "type": "private"}
def _event(text="custom answer"):
return MessageEvent(
text=text,
message_type=MessageType.TEXT,
source=SessionSource(
platform=Platform.TELEGRAM,
chat_id="12345",
chat_type="private",
user_id="user1",
),
message_id="msg1",
)
def _clear_clarify_state():
from tools import clarify_gateway as cm
with cm._lock:
cm._entries.clear()
cm._session_index.clear()
cm._notify_cbs.clear()
@pytest.mark.asyncio
async def test_active_session_routes_typed_choice_clarify_reply_to_runner_not_busy_queue():
"""Typed text must resolve a pending choice clarify even while the agent is busy.
Telegram button clarifies keep the adapter session active while the agent
thread blocks on ``wait_for_response``. If the adapter only bypasses for
entries already marked ``awaiting_text``, typed replies to the visible
multi-choice prompt are handled as busy follow-ups and the clarify wait is
never resolved.
"""
_clear_clarify_state()
from tools import clarify_gateway as cm
adapter = _ClarifyBypassAdapter()
adapter._message_handler = AsyncMock(return_value="")
adapter._busy_session_handler = AsyncMock(return_value=True)
event = _event("None of those are valid options")
session_key = build_session_key(
event.source,
group_sessions_per_user=adapter.config.extra.get("group_sessions_per_user", True),
thread_sessions_per_user=adapter.config.extra.get("thread_sessions_per_user", False),
)
adapter._active_sessions[session_key] = asyncio.Event()
cm.register("clarify-1", session_key, "Pick one", ["A", "B"])
await adapter.handle_message(event)
adapter._message_handler.assert_awaited_once_with(event)
adapter._busy_session_handler.assert_not_awaited()
assert adapter._pending_messages == {}
@pytest.mark.asyncio
async def test_active_session_bypass_uses_profile_namespaced_key_under_multiplex():
"""Regression for issue #82975: under a named-profile multiplex, the
adapter's clarify bypass lookup must use the SAME profile-namespaced
session key that the runner registers pending clarifies under
(SessionStore._generate_session_key() includes
profile=self._resolve_profile_for_key(source)), not the legacy
unnamespaced key. Otherwise the lookup misses, and a user's answer to
a pending clarify is routed to the busy-session queue instead of
resolving it -- the turn then hangs until the clarify's 3600s timeout."""
_clear_clarify_state()
from tools import clarify_gateway as cm
adapter = _ClarifyBypassAdapter()
adapter._message_handler = AsyncMock(return_value="")
adapter._busy_session_handler = AsyncMock(return_value=True)
event = _event("None of those are valid options")
# A session_store configured for profile multiplexing, matching what
# the runner's SessionStore._generate_session_key() actually produces.
session_store = MagicMock()
session_store._resolve_profile_for_key.return_value = "ops"
adapter._session_store = session_store
profile_namespaced_key = build_session_key(
event.source,
group_sessions_per_user=adapter.config.extra.get("group_sessions_per_user", True),
thread_sessions_per_user=adapter.config.extra.get("thread_sessions_per_user", False),
profile="ops",
)
# Sanity: the profile-namespaced key really is different from the
# legacy unnamespaced one -- otherwise this test wouldn't distinguish
# the fixed behavior from the bug.
legacy_key = build_session_key(
event.source,
group_sessions_per_user=adapter.config.extra.get("group_sessions_per_user", True),
thread_sessions_per_user=adapter.config.extra.get("thread_sessions_per_user", False),
)
assert profile_namespaced_key != legacy_key
adapter._active_sessions[profile_namespaced_key] = asyncio.Event()
# The runner registers the pending clarify under its own
# profile-namespaced key, exactly as it would in a real multiplexed
# deployment.
cm.register("clarify-1", profile_namespaced_key, "Pick one", ["A", "B"])
await adapter.handle_message(event)
adapter._message_handler.assert_awaited_once_with(event)
adapter._busy_session_handler.assert_not_awaited()
assert adapter._pending_messages == {}