diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index cdf991b16..f7e30917b 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -1451,13 +1451,10 @@ class AgentLoop: msg, session_key_override=effective_key, ) - # A newer WebUI message must supersede an explicit recovery - # before it is injected into that recovery's pending queue. - # Without this admission point, a recovered turn could finish - # first and only then observe the user's newer request. + # Mid-turn injection bypasses _dispatch_one, so admit before joining + # an active queue. Admission may cancel its worker and release the queue. if ( effective_key in self._pending_queues - and msg.channel == "websocket" and self._recovery_admission is not None and not await self._recovery_admission.admit(routed_msg) ): diff --git a/nanobot/session/recovery.py b/nanobot/session/recovery.py index 40eb4c168..e2a81d6d0 100644 --- a/nanobot/session/recovery.py +++ b/nanobot/session/recovery.py @@ -50,7 +50,12 @@ def request_origin_from_metadata(metadata: Mapping[str, Any]) -> RequestOrigin | class RecoveryAdmission(Protocol): - """Narrow AgentLoop boundary for explicit recovery validation.""" + """Own recovery eligibility before queue injection and worker dispatch. + + Messages carry their effective session key and may come from any channel. + Implementations must tolerate repeated admission. Admission may cancel an + active worker, so callers must re-read queue ownership afterwards. + """ async def admit(self, message: InboundMessage) -> bool: ... diff --git a/tests/agent/test_runner_injections.py b/tests/agent/test_runner_injections.py index 1706cd820..bf7cecd60 100644 --- a/tests/agent/test_runner_injections.py +++ b/tests/agent/test_runner_injections.py @@ -1138,7 +1138,8 @@ async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path): @pytest.mark.asyncio -async def test_unified_websocket_followup_admits_effective_session(tmp_path): +@pytest.mark.parametrize("channel", ["websocket", "discord"]) +async def test_unified_followup_admits_effective_session(tmp_path, channel): from nanobot.bus.events import InboundMessage from nanobot.session.keys import UNIFIED_SESSION_KEY @@ -1151,7 +1152,7 @@ async def test_unified_websocket_followup_admits_effective_session(tmp_path): loop._pending_queues[UNIFIED_SESSION_KEY] = pending msg = InboundMessage( - channel="websocket", + channel=channel, sender_id="u", chat_id="chat", content="new request", @@ -1166,7 +1167,10 @@ async def test_unified_websocket_followup_admits_effective_session(tmp_path): assert admitted_msg.session_key == UNIFIED_SESSION_KEY assert queued_msg.session_key == UNIFIED_SESSION_KEY assert queued_msg.content == msg.content - assert queued_msg.metadata["_recovery_followup_id"] + if channel == "websocket": + assert queued_msg.metadata["_recovery_followup_id"] + else: + assert queued_msg.metadata == msg.metadata finally: await loop.aclose() diff --git a/tests/session/test_recovery.py b/tests/session/test_recovery.py index 037ee707c..4439b6bf9 100644 --- a/tests/session/test_recovery.py +++ b/tests/session/test_recovery.py @@ -9,6 +9,7 @@ from nanobot.bus.events import InboundMessage from nanobot.bus.outbound_events import RecoveryStateEvent, SessionUpdatedEvent from nanobot.bus.queue import MessageBus from nanobot.providers.base import ProviderConversationState +from nanobot.session.keys import UNIFIED_SESSION_KEY from nanobot.session.manager import Session, SessionManager from nanobot.session.recovery import ( PENDING_FOLLOWUPS_KEY, @@ -602,9 +603,11 @@ async def test_new_user_message_supersedes_waiting_recovery(tmp_path: Path) -> N @pytest.mark.asyncio -async def test_new_user_message_cancels_active_recovery_task(tmp_path: Path) -> None: +@pytest.mark.parametrize("channel", ["websocket", "discord"]) +async def test_new_input_only_supersedes_recovery_for_websocket(tmp_path: Path, channel: str) -> None: coordinator, bus, sessions = _coordinator(tmp_path) - session = sessions.get_or_create("websocket:chat") + coordinator.unified_session = True + session = sessions.get_or_create(UNIFIED_SESSION_KEY) session.metadata[RECOVERY_METADATA_KEY] = { "status": "resuming", "recovery_id": "active", @@ -620,24 +623,35 @@ async def test_new_user_message_cancels_active_recovery_task(tmp_path: Path) -> task = asyncio.create_task(_active_recovery()) await started.wait() - coordinator.register_recovery_task("websocket:chat", task) + coordinator.register_recovery_task(session.key, task) newer = InboundMessage( - channel="websocket", + channel=channel, sender_id="user", chat_id="chat", content="new request", + session_key_override=session.key, ) - assert await coordinator.admit(newer) is True - assert task.cancelled() - restored = sessions.get_or_create("websocket:chat") - assert restored.metadata[RECOVERY_METADATA_KEY]["reason"] == "superseded" - assert restored.messages[-1]["_recovery_interrupted"] is True - first = bus.outbound.get_nowait().event - second = bus.outbound.get_nowait().event - assert isinstance(first, RecoveryStateEvent) - assert isinstance(second, SessionUpdatedEvent) - assert bus.outbound.empty() + try: + assert await coordinator.admit(newer) is True + restored = sessions.get_or_create(session.key) + if channel == "websocket": + assert task.cancelled() + assert restored.metadata[RECOVERY_METADATA_KEY]["reason"] == "superseded" + assert restored.messages[-1]["_recovery_interrupted"] is True + first = bus.outbound.get_nowait().event + second = bus.outbound.get_nowait().event + assert isinstance(first, RecoveryStateEvent) + assert isinstance(second, SessionUpdatedEvent) + else: + assert not task.done() + assert restored.metadata[RECOVERY_METADATA_KEY] == { + "status": "resuming", "recovery_id": "active", "attempts": 1, + } + assert bus.outbound.empty() + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) @pytest.mark.asyncio