refactor(agent): delegate recovery channel eligibility to admission

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-30 18:31:05 +08:00
1 parent 29d0023fca
commit 3e40684112
4 files changed
+43 -23

No files matched your search

+2 -5
View File
@@ -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)
):
+6 -1
View File
@@ -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: ...
+7 -3
View File
@@ -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()
+28 -14
View File
@@ -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