Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(channel): preserve wakeups for messages arriving during run finalization (#2521)
CoralGarden52a051947af493
diff --git a/src/agentscope/app/channel/_gateway.py b/src/agentscope/app/channel/_gateway.pyindex 0029d0e19..3d57fbc12 100644--- a/src/agentscope/app/channel/_gateway.py+++ b/src/agentscope/app/channel/_gateway.py@@ -22,7 +22,7 @@ from ..._logging import loggerfrom ...message import DataBlock, HintBlock, TextBlock, UserMsgfrom ...permission import PermissionContext, PermissionModefrom ...state import AgentState-from .._bus_ops import enqueue_run_trigger+from .._bus_ops import deliver_to_inbox, enqueue_run_triggerfrom ..message_bus import MessageBus, MessageBusKeysfrom ..storage import (ChannelRecord,@@ -210,9 +210,12 @@ class ChannelGateway:# A reply already in flight → inject the input as a hint so the# live run folds it in. Otherwise start a fresh user turn.if await self._bus.is_locked(MessageBusKeys.session_lock(session_id)):- await self._bus.queue_push(- MessageBusKeys.inbox(session_id),- HintBlock(+ await deliver_to_inbox(+ self._bus,+ user_id=record.user_id,+ session_id=session_id,+ agent_id=agent_id,+ payload=HintBlock(hint=content,source=json.dumps({diff --git a/tests/channel_gateway_test.py b/tests/channel_gateway_test.pyindex fbb446c44..8b7539e27 100644--- a/tests/channel_gateway_test.py+++ b/tests/channel_gateway_test.py@@ -8,10 +8,17 @@ needs a running agent and is exercised end-to-end against a real bot."""# pylint: disable=protected-access,missing-function-docstring,unused-argument# pylint: disable=attribute-defined-outside-init+import asynciofrom types import SimpleNamespacefrom typing import Any, AsyncIteratorfrom unittest import IsolatedAsyncioTestCase+from utils import AnyString++from agentscope.app._bus_ops import (+ has_pending_inbox_or_release,+ register_inbox_consumer,+)from agentscope.app.channel._base import (ChannelBase,ChannelConfirmationResultEvent,@@ -19,6 +26,7 @@ from agentscope.app.channel._base import (_EVENT_ADAPTER,)from agentscope.app.channel._gateway import ChannelGateway+from agentscope.app.channel._routing import resolvefrom agentscope.message import Msg, ToolCallBlock, ToolCallStatefrom agentscope.state import AgentStatefrom agentscope.app.message_bus import InMemoryMessageBus@@ -351,6 +359,106 @@ def _channel_record(user_id: str) -> ChannelRecord:)+class _ChannelStorage:+ """Return one channel record for the gateway hand-off test."""++ def __init__(self, record: ChannelRecord) -> None:+ self._record = record++ async def get_channel(self, channel_id: str) -> ChannelRecord:+ del channel_id+ return self._record+++class _PausedSessionCheckBus(InMemoryMessageBus):+ """Pause the gateway after it observes the active session lock."""++ def __init__(self, lock_key: str) -> None:+ super().__init__()+ self._lock_key = lock_key+ self.checked = asyncio.Event()+ self.resume = asyncio.Event()++ async def is_locked(self, key: str) -> bool:+ locked = await super().is_locked(key)+ if key == self._lock_key:+ self.checked.set()+ await self.resume.wait()+ return locked+++class ChannelInboxHandoffTest(IsolatedAsyncioTestCase):+ """Channel hints must use the session inbox hand-off protocol."""++ async def test_late_channel_message_enqueues_wakeup(self) -> None:+ """A message after the final consumer check cannot be stranded."""+ record = _channel_record("user-1")+ event = ChannelEvent(+ channel_id="chan-1",+ channel_user_id="member-1",+ chat_id="chat-1",+ content=[TextBlock(text="late message")],+ )+ _agent_id, session_id, _scope = resolve(event, record)+ bus = _PausedSessionCheckBus(+ MessageBusKeys.session_lock(session_id),+ )+ gateway = ChannelGateway(+ storage=_ChannelStorage(record),+ message_bus=bus,+ workspace_manager=_WM(isolation=IsolationPolicy.PER_AGENT),+ )++ await register_inbox_consumer(bus, session_id)+ async with bus.acquire_lock(+ MessageBusKeys.session_lock(session_id),+ ):+ message_task = asyncio.create_task(gateway.process(event))+ await asyncio.wait_for(bus.checked.wait(), timeout=2)++ self.assertFalse(+ await has_pending_inbox_or_release(bus, session_id),+ )+ bus.resume.set()+ await asyncio.wait_for(message_task, timeout=2)++ wakeups = await bus.queue_drain(MessageBusKeys.wakeup_queue())+ self.assertEqual(len(wakeups), 1)+ self.assertDictEqual(+ wakeups[0][1],+ {+ "user_id": "user-1",+ "session_id": session_id,+ "agent_id": "agent-x",+ "kind": MessageBusKeys.WAKEUP_KIND_WAKE,+ "input": None,+ },+ )++ inbox = await bus.queue_drain(MessageBusKeys.inbox(session_id))+ self.assertListEqual(+ [payload for _entry_id, payload in inbox],+ [+ {+ "type": "hint",+ "hint": [+ {+ "type": "text",+ "text": "late message",+ "id": AnyString(),+ "created_at": AnyString(),+ "finished_at": None,+ },+ ],+ "id": AnyString(),+ "source": '{"label": "channel", "sublabel": "member-1"}',+ "created_at": AnyString(),+ "finished_at": AnyString(),+ },+ ],+ )++class WorkspaceIsolationTest(IsolatedAsyncioTestCase):"""Channel-created sessions get isolated workspaces, not a shared one."""