Skip to content

Your lightweight open-source personal agent.

refactor(agent): unify session message admission

chengyongrub669c2036cd4
diff --git a/nanobot/agent/automation_turns.py b/nanobot/agent/automation_turns.py
index 5a1b69601..30fc8840c 100644
--- a/nanobot/agent/automation_turns.py
+++ b/nanobot/agent/automation_turns.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
import dataclasses
-from collections.abc import Awaitable, Callable, Iterable
+from collections.abc import Callable, Iterable
from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -13,32 +13,13 @@ class AutomationTurnError(RuntimeError):
"""Raised when an automation turn reaches the agent and finishes with an error."""
-async def publish_next_deferred_turn(
- *,
- deferred_queues: dict[str, list[InboundMessage]],
- publish_inbound: Callable[[InboundMessage], Awaitable[None]],
- session_key: str,
-) -> bool:
- """Publish the next deferred automation turn for a session."""
- queue = deferred_queues.get(session_key)
- if not queue:
- return False
- msg = queue.pop(0)
- if not queue:
- deferred_queues.pop(session_key, None)
- await publish_inbound(msg)
- return True
-
-
class AutomationTurnCoordinator:
"""Manage automation turns without mixing them into live injections."""
def __init__(
self,
*,
- publish_inbound: Callable[[InboundMessage], Awaitable[None]],
- dispatch: Callable[[InboundMessage], Awaitable[object]],
- is_running: Callable[[], bool],
+ enqueue: Callable[[InboundMessage], None],
turn_id: Callable[[InboundMessage], str | None],
pending_id: Callable[[InboundMessage], str | None],
should_defer_turn: Callable[[InboundMessage, str, Iterable[str]], bool],
@@ -46,9 +27,7 @@ class AutomationTurnCoordinator:
duplicate_id_error: Callable[[str], str],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
- self._publish_inbound = publish_inbound
- self._dispatch = dispatch
- self._is_running = is_running
+ self._enqueue = enqueue
self._turn_id = turn_id
self._pending_id = pending_id
self._should_defer_turn = should_defer_turn
@@ -75,10 +54,7 @@ class AutomationTurnCoordinator:
self._waiters[turn_id] = future
self._pending_messages_by_turn_id[turn_id] = msg
try:
- if self._is_running():
- await self._publish_inbound(msg)
- else:
- await self._dispatch(msg)
+ self._enqueue(msg)
try:
return await future
except asyncio.CancelledError:
diff --git a/nanobot/agent/cron_turns.py b/nanobot/agent/cron_turns.py
index 3cffbd2b6..970738ec5 100644
--- a/nanobot/agent/cron_turns.py
+++ b/nanobot/agent/cron_turns.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from collections.abc import Awaitable, Callable, Iterable
+from collections.abc import Callable, Iterable
from nanobot.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage
@@ -19,15 +19,11 @@ class CronTurnCoordinator(AutomationTurnCoordinator):
def __init__(
self,
*,
- publish_inbound: Callable[[InboundMessage], Awaitable[None]],
- dispatch: Callable[[InboundMessage], Awaitable[object]],
- is_running: Callable[[], bool],
+ enqueue: Callable[[InboundMessage], None],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
super().__init__(
- publish_inbound=publish_inbound,
- dispatch=dispatch,
- is_running=is_running,
+ enqueue=enqueue,
turn_id=lambda msg: cron_run_id(msg.metadata),
pending_id=_cron_job_id,
should_defer_turn=_should_defer_cron_turn,
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index 0c4243170..195109c57 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -23,7 +23,6 @@ from loguru import logger
from nanobot.agent import context as agent_context
from nanobot.agent import model_presets as preset_helpers
from nanobot.agent.autocompact import AutoCompact
-from nanobot.agent.automation_turns import publish_next_deferred_turn
from nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInput
from nanobot.agent.cron_turns import CronTurnCoordinator
from nanobot.agent.hook import AgentHook, AgentTurnHookFactory
@@ -405,20 +404,16 @@ class AgentLoop:
self._preserve_inflight_turns_on_shutdown = False
self._deferred_automation_turns: dict[str, list[InboundMessage]] = {}
self._cron_turns = CronTurnCoordinator(
- publish_inbound=self.bus.publish_inbound,
- dispatch=partial(self._dispatch, wait_for_worker=False),
- is_running=lambda: self._running,
+ enqueue=self._enqueue_session_message,
deferred_queues=self._deferred_automation_turns,
)
self._local_trigger_turns = LocalTriggerTurnCoordinator(
- publish_inbound=self.bus.publish_inbound,
- dispatch=partial(self._dispatch, wait_for_worker=False),
- is_running=lambda: self._running,
+ enqueue=self._enqueue_session_message,
deferred_queues=self._deferred_automation_turns,
)
self._automation_turn_coordinators = (
- ("cron", self._cron_turns),
- ("local trigger", self._local_trigger_turns),
+ self._cron_turns,
+ self._local_trigger_turns,
)
# NANOBOT_MAX_CONCURRENT_REQUESTS: unset or <=0 means unlimited.
_max = int(os.environ.get("NANOBOT_MAX_CONCURRENT_REQUESTS", "0"))
@@ -662,13 +657,6 @@ class AgentLoop:
def pending_local_trigger_ids_for_session(self, session_key: str) -> set[str]:
return self._local_trigger_turns.pending_trigger_ids_for_session(session_key)
- async def _publish_next_deferred_automation_turn(self, session_key: str) -> None:
- await publish_next_deferred_turn(
- deferred_queues=self._deferred_automation_turns,
- publish_inbound=self.bus.publish_inbound,
- session_key=session_key,
- )
-
def _persist_user_message_early(
self,
msg: InboundMessage,
@@ -782,10 +770,7 @@ class AgentLoop:
"""Dispatch a command directly from the run() loop and publish the result."""
if normalize_command_text(raw).lower() == "/compact":
# Compaction must wait for the active turn to commit its session.
- task = asyncio.create_task(self._dispatch(msg))
- self._track_active_task(key, task)
- # Enter dispatch's cancellation handler before consuming a queued /stop.
- await asyncio.sleep(0)
+ self._enqueue_session_message(msg)
return
async def dispatch_and_publish() -> None:
@@ -908,7 +893,7 @@ class AgentLoop:
def _can_inject_message(self, msg: InboundMessage) -> bool:
"""Keep independent turns and controls out of user-input batches."""
if turn_continuation.internal_continuation_inbound(msg.metadata) or any(
- coordinator.owns_turn(msg) for _, coordinator in self._automation_turn_coordinators
+ coordinator.owns_turn(msg) for coordinator in self._automation_turn_coordinators
):
return False
return msg.channel == "system" or not self.commands.is_dispatchable_command(
@@ -1329,22 +1314,6 @@ class AgentLoop:
self.commands.dispatch_priority,
)
continue
- deferred = False
- for label, coordinator in self._automation_turn_coordinators:
- if coordinator.defer_if_active(
- msg,
- session_key=effective_key,
- active_session_keys=self._pending_queues.keys(),
- ):
- logger.info(
- "Deferred {} turn for active session {}",
- label,
- effective_key,
- )
- deferred = True
- break
- if deferred:
- continue
routed_msg = msg
if effective_key != msg.session_key:
routed_msg = dataclasses.replace(
@@ -1374,20 +1343,7 @@ class AgentLoop:
self.commands.dispatch,
)
continue
- pending_msg = self._journal_pending_message(effective_key, routed_msg)
- self._pending_queues[effective_key].put_nowait(pending_msg)
- logger.info(
- "Routed follow-up message to pending queue for session {}",
- effective_key,
- )
- continue
- # Install the queue before scheduling its worker. Every later
- # message now has one FIFO path even if this task has not run yet.
- pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
- pending.put_nowait(routed_msg)
- self._pending_queues[effective_key] = pending
- task = asyncio.create_task(self._run_session_queue(effective_key, pending))
- self._track_active_task(effective_key, task)
+ self._enqueue_session_message(routed_msg)
finally:
await self.aclose()
@@ -1423,12 +1379,20 @@ class AgentLoop:
self.sessions.save(session)
return pending_msg
- async def _dispatch(self, msg: InboundMessage, *, wait_for_worker: bool = True) -> None:
- """Enqueue a message, optionally awaiting a newly created session worker."""
+ def _enqueue_session_message(self, msg: InboundMessage) -> None:
+ """Admit session work without waiting for its execution or result."""
session_key = self._effective_session_key(msg)
if session_key != msg.session_key:
msg = dataclasses.replace(msg, session_key_override=session_key)
+ for coordinator in self._automation_turn_coordinators:
+ if coordinator.defer_if_active(
+ msg,
+ session_key=session_key,
+ active_session_keys=self._pending_queues.keys(),
+ ):
+ return
+
pending = self._pending_queues.get(session_key)
if pending is not None:
pending.put_nowait(self._journal_pending_message(session_key, msg))
@@ -1437,13 +1401,8 @@ class AgentLoop:
new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
new_pending.put_nowait(msg)
self._pending_queues[session_key] = new_pending
- if wait_for_worker:
- await self._run_session_queue(session_key, new_pending)
- else:
- # Automation callers await their own completion, not every later
- # turn handled by this worker. Session cancellation still owns it.
- task = asyncio.create_task(self._run_session_queue(session_key, new_pending))
- self._track_active_task(session_key, task)
+ task = asyncio.create_task(self._run_session_queue(session_key, new_pending))
+ self._track_active_task(session_key, task)
async def _run_session_queue(
self,
@@ -1456,7 +1415,14 @@ class AgentLoop:
try:
msg = pending.get_nowait()
except asyncio.QueueEmpty:
- break
+ # Idle-only automation follows all accepted user input on
+ # this same worker, including before the bus loop starts.
+ deferred = self._deferred_automation_turns.get(session_key)
+ if not deferred:
+ break
+ msg = deferred.pop(0)
+ if not deferred:
+ self._deferred_automation_turns.pop(session_key)
try:
await self._dispatch_one(msg, pending)
except asyncio.CancelledError:
@@ -1473,8 +1439,6 @@ class AgentLoop:
owns_queue = self._pending_queues.get(session_key) is pending
if owns_queue:
self._pending_queues.pop(session_key, None)
- if owns_queue and self._running and session_key not in self._discarding_sessions:
- await self._publish_next_deferred_automation_turn(session_key)
async def _cancel_pending_messages(
self,
@@ -1483,9 +1447,11 @@ class AgentLoop:
error: asyncio.CancelledError,
) -> None:
"""Complete queued independent turns after their session worker stops."""
+ for msg in self._deferred_automation_turns.pop(session_key, []):
+ pending.put_nowait(msg)
while not pending.empty():
msg = pending.get_nowait()
- for _, coordinator in self._automation_turn_coordinators:
+ for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=error)
if (
msg.channel != "system"
@@ -1546,10 +1512,10 @@ class AgentLoop:
publish_completion=not continuing,
)
completion_published = not continuing
- for _, coordinator in self._automation_turn_coordinators:
+ for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, response=response)
except asyncio.CancelledError:
- for _, coordinator in self._automation_turn_coordinators:
+ for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=asyncio.CancelledError())
logger.info("Task cancelled for session {}", session_key)
try:
@@ -1593,7 +1559,7 @@ class AgentLoop:
msg.metadata
)
)
- for _, coordinator in self._automation_turn_coordinators:
+ for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=exc)
finally:
if not turn_continuation.internal_continuation_pending(msg.metadata):
@@ -1630,9 +1596,14 @@ class AgentLoop:
async def _aclose_unlocked(self) -> None:
errors: list[BaseException] = []
active_task_groups = getattr(self, "_active_tasks", {})
+ current_task = asyncio.current_task()
+ pending_queues = {
+ key: self._pending_queues[key]
+ for key, tasks in active_task_groups.items()
+ if key in self._pending_queues and any(task is not current_task for task in tasks)
+ }
active_tasks = tuple({task for tasks in active_task_groups.values() for task in tasks})
active_task_groups.clear()
- current_task = asyncio.current_task()
active_tasks = tuple(task for task in active_tasks if task is not current_task)
for task in active_tasks:
if not task.done():
@@ -1640,6 +1611,10 @@ class AgentLoop:
try:
if active_tasks:
await asyncio.gather(*active_tasks, return_exceptions=True)
+ for key, pending in pending_queues.items():
+ if self._pending_queues.get(key) is pending:
+ self._pending_queues.pop(key)
+ await self._cancel_pending_messages(key, pending, asyncio.CancelledError())
if self._background_tasks:
await asyncio.gather(*self._background_tasks, return_exceptions=True)
except BaseException as exc:
diff --git a/nanobot/agent/tools/cron.py b/nanobot/agent/tools/cron.py
index 5be8e9712..7a9fa4929 100644
--- a/nanobot/agent/tools/cron.py
+++ b/nanobot/agent/tools/cron.py
@@ -5,7 +5,6 @@
from __future__ import annotations
import time
-from contextvars import ContextVar, Token
from datetime import datetime
from typing import Any
@@ -17,6 +16,7 @@ from nanobot.agent.tools.schema import (
tool_parameters_schema,
)
from nanobot.cron.service import CronService
+from nanobot.cron.session_turns import is_cron_turn
from nanobot.cron.types import CronJob, CronJobState, CronSchedule
from nanobot.session.keys import UNIFIED_SESSION_KEY
@@ -60,7 +60,6 @@ class CronTool(Tool):
def __init__(self, cron_service: CronService, default_timezone: str = "UTC"):
self._cron = cron_service
self._default_timezone = default_timezone
- self._in_cron_context: ContextVar[bool] = ContextVar("cron_in_context", default=False)
@classmethod
def enabled(cls, ctx: ToolContext) -> bool:
@@ -85,14 +84,6 @@ class CronTool(Tool):
)
return session_key, ctx.channel or "", ctx.chat_id or "", dict(ctx.metadata or {})
- def set_cron_context(self, active: bool) -> Token[bool]:
- """Mark whether the tool is executing inside a cron job callback."""
- return self._in_cron_context.set(active)
-
- def reset_cron_context(self, token: Token[bool]) -> None:
- """Restore previous cron context."""
- self._in_cron_context.reset(token)
-
@staticmethod
def _validate_timezone(tz: str) -> str | None:
from zoneinfo import ZoneInfo
@@ -146,7 +137,8 @@ class CronTool(Tool):
job_id: str | None = None,
) -> str:
if action == "add":
- if self._in_cron_context.get():
+ request = current_request_context()
+ if request is not None and is_cron_turn(request.metadata):
return ToolResult.error("Error: cannot schedule new jobs from within a cron job execution")
return self._add_job(name, message, every_seconds, cron_expr, tz, at)
elif action == "list":
diff --git a/nanobot/cron/bound_runner.py b/nanobot/cron/bound_runner.py
index f1133490c..d3b65dee0 100644
--- a/nanobot/cron/bound_runner.py
+++ b/nanobot/cron/bound_runner.py
@@ -6,9 +6,8 @@ import asyncio
import hashlib
import time
import uuid
-from typing import TYPE_CHECKING, Any, Protocol
+from typing import Any, Protocol
-from nanobot.agent.tools.cron import CronTool
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.cron.session_delivery import origin_delivery_context
from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META
@@ -16,13 +15,8 @@ from nanobot.cron.types import CronJob, CronRunResult
from nanobot.cron.webui_metadata import cron_proactive_delivery_metadata
from nanobot.utils.prompt_templates import render_template
-if TYPE_CHECKING:
- from nanobot.agent.tools.registry import ToolRegistry
-
class BoundCronAgent(Protocol):
- tools: ToolRegistry
-
async def submit_cron_turn(self, msg: InboundMessage) -> OutboundMessage | None:
...
@@ -112,10 +106,6 @@ async def run_bound_cron_job(
},
)
- cron_tool = agent.tools.get("cron")
- cron_token = None
- if isinstance(cron_tool, CronTool):
- cron_token = cron_tool.set_cron_context(True)
try:
resp = await agent.submit_cron_turn(
InboundMessage(
@@ -138,10 +128,6 @@ async def run_bound_cron_job(
},
)
raise
- finally:
- if isinstance(cron_tool, CronTool) and cron_token is not None:
- cron_tool.reset_cron_context(cron_token)
-
response = resp.content if resp else ""
cron.write_run_record(
run_id,
diff --git a/nanobot/triggers/local_turns.py b/nanobot/triggers/local_turns.py
index a468d42e3..3a679f3d7 100644
--- a/nanobot/triggers/local_turns.py
+++ b/nanobot/triggers/local_turns.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from collections.abc import Awaitable, Callable, Iterable
+from collections.abc import Callable, Iterable
from nanobot.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage
@@ -15,15 +15,11 @@ class LocalTriggerTurnCoordinator(AutomationTurnCoordinator):
def __init__(
self,
*,
- publish_inbound: Callable[[InboundMessage], Awaitable[None]],
- dispatch: Callable[[InboundMessage], Awaitable[object]],
- is_running: Callable[[], bool],
+ enqueue: Callable[[InboundMessage], None],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
super().__init__(
- publish_inbound=publish_inbound,
- dispatch=dispatch,
- is_running=is_running,
+ enqueue=enqueue,
turn_id=lambda msg: local_trigger_delivery_id(msg.metadata),
pending_id=_local_trigger_id,
should_defer_turn=_should_defer_local_trigger_turn,
diff --git a/tests/agent/session_helpers.py b/tests/agent/session_helpers.py
new file mode 100644
index 000000000..21f034251
--- /dev/null
+++ b/tests/agent/session_helpers.py
@@ -0,0 +1,12 @@
+"""Session-worker completion helpers for integration tests."""
+
+import asyncio
+
+from nanobot.agent.loop import AgentLoop
+from nanobot.bus.events import InboundMessage
+
+
+async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
+ """Submit input and wait for its session worker to finish."""
+ loop._enqueue_session_message(msg)
+ await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)])
diff --git a/tests/agent/test_loop_progress.py b/tests/agent/test_loop_progress.py
index 7a1a7d5c7..5be5752f1 100644
--- a/tests/agent/test_loop_progress.py
+++ b/tests/agent/test_loop_progress.py
@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
+from agent.session_helpers import run_session
from nanobot.agent.context import TranscriptInput
from nanobot.agent.hooks import create_file_edit_activity_hook
from nanobot.agent.loop import AgentLoop
@@ -298,7 +299,7 @@ class TestToolEventProgress:
chat_id="chat1",
content="run ls",
)
- await loop._dispatch(msg)
+ await run_session(loop, msg)
# Drain all outbound messages and find the one carrying tool events.
outbound = []
@@ -421,7 +422,7 @@ class TestToolEventProgress:
),
)
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -468,7 +469,7 @@ class TestToolEventProgress:
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="openai-codex/gpt-5.5")
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="whatsapp",
sender_id="u1",
chat_id="chat1",
@@ -506,7 +507,7 @@ class TestToolEventProgress:
_attach_webui_runtime_events(loop, bus)
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -559,7 +560,7 @@ class TestToolEventProgress:
_attach_webui_runtime_events(loop, bus)
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -595,7 +596,7 @@ class TestToolEventProgress:
calls += 1
if calls == 1:
await on_content_delta("old partial")
- await loop._dispatch(InboundMessage(
+ loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="new question",
))
return LLMResponse(content="old partial", finish_reason="length")
@@ -605,7 +606,7 @@ class TestToolEventProgress:
loop.provider.chat_stream_with_retry = chat
try:
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="old question",
metadata={"_wants_stream": True},
))
@@ -652,7 +653,7 @@ class TestToolEventProgress:
_attach_webui_runtime_events(loop, bus)
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -694,7 +695,7 @@ class TestToolEventProgress:
loop.max_iterations = 1
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -739,7 +740,7 @@ class TestToolEventProgress:
loop._process_message = cancel_after_merge # type: ignore[method-assign]
with pytest.raises(asyncio.CancelledError):
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -781,7 +782,7 @@ class TestToolEventProgress:
_attach_webui_runtime_events(loop, bus)
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -852,7 +853,7 @@ class TestToolEventProgress:
session.add_message("user", "Run this in the background")
session.metadata.update({"webui": True, "title": "Existing title"})
loop.sessions.save(session)
- dispatch = asyncio.create_task(loop._dispatch(InboundMessage(
+ dispatch = asyncio.create_task(run_session(loop, InboundMessage(
channel="system",
sender_id="subagent",
chat_id=session_key,
@@ -978,7 +979,7 @@ class TestToolEventProgress:
_attach_webui_runtime_events(loop, bus)
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -1076,7 +1077,7 @@ class TestToolEventProgress:
_attach_webui_runtime_events(loop, bus)
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -1113,7 +1114,7 @@ class TestToolEventProgress:
loop._process_message = raise_from_turn # type: ignore[method-assign]
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -1159,7 +1160,7 @@ class TestToolEventProgress:
_attach_webui_runtime_events(loop, bus)
loop.tools.get_definitions = MagicMock(return_value=[])
- await asyncio.wait_for(loop._dispatch(InboundMessage(
+ await asyncio.wait_for(run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -1228,7 +1229,7 @@ class TestToolEventProgress:
loop.schedule_background = schedule_background # type: ignore[method-assign]
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -1310,7 +1311,7 @@ class TestToolEventProgress:
loop.schedule_background = schedule_background # type: ignore[method-assign]
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -1345,7 +1346,7 @@ class TestToolEventProgress:
scheduled: list[object] = []
loop.schedule_background = scheduled.append # type: ignore[method-assign]
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="chat1",
@@ -1364,7 +1365,7 @@ class TestToolEventProgress:
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
loop.tools.get_definitions = MagicMock(return_value=[])
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="slack",
sender_id="u1",
chat_id="chat1",
diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py
index 810f5c0c2..50303eef9 100644
--- a/tests/agent/test_loop_save_turn.py
+++ b/tests/agent/test_loop_save_turn.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from loguru import logger
+from agent.session_helpers import run_session
from nanobot.agent.context import ContextBuilder, TranscriptInput
from nanobot.agent.loop import AgentLoop
from nanobot.agent.runner import AgentRunResult
@@ -1511,7 +1512,7 @@ async def test_internal_continuation_preserves_streaming_route_metadata(
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="feishu",
sender_id="u1",
chat_id="c-stream",
@@ -1573,7 +1574,7 @@ async def test_websocket_internal_continuation_keeps_single_visible_run(
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="c-auto",
diff --git a/tests/agent/test_loop_session_policy.py b/tests/agent/test_loop_session_policy.py
index 78afc1c2b..8ba2f4144 100644
--- a/tests/agent/test_loop_session_policy.py
+++ b/tests/agent/test_loop_session_policy.py
@@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
+from agent.session_helpers import run_session
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import (
INBOUND_META_RUNTIME_CONTROL,
@@ -81,7 +82,7 @@ async def test_transient_session_stays_outside_unified_session(tmp_path) -> None
key = "websocket:transient-unified"
transient = loop.sessions.get_or_create_transient(key)
- await loop._dispatch(_message(key, "private question"))
+ await run_session(loop, _message(key, "private question"))
assert [message["content"] for message in transient.messages] == [
"private question",
diff --git a/tests/agent/test_runner_injections.py b/tests/agent/test_runner_injections.py
index cf9bb1ad5..c89b2ff31 100644
--- a/tests/agent/test_runner_injections.py
+++ b/tests/agent/test_runner_injections.py
@@ -9,7 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent.runner_helpers import make_run_spec
-from nanobot.agent.automation_turns import publish_next_deferred_turn
+from agent.session_helpers import run_session
from nanobot.agent.context import TranscriptInput
from nanobot.agent.tools.context import RequestContext
from nanobot.config.schema import AgentDefaults
@@ -1100,7 +1100,7 @@ async def test_no_injections_flag_is_false_by_default():
@pytest.mark.asyncio
async def test_pending_queue_cleanup_on_dispatch(tmp_path):
- """_pending_queues should be cleaned up after _dispatch completes."""
+ """The session worker removes its inbox after processing all messages."""
loop = _make_loop(tmp_path)
async def chat_stream_with_retry(**kwargs):
@@ -1114,7 +1114,7 @@ async def test_pending_queue_cleanup_on_dispatch(tmp_path):
# The queue should not exist before dispatch
assert msg.session_key not in loop._pending_queues
- await loop._dispatch(msg)
+ await run_session(loop, msg)
# The queue should be cleaned up after dispatch
assert msg.session_key not in loop._pending_queues
@@ -1132,7 +1132,7 @@ async def test_direct_dispatch_joins_active_session_queue_without_waiting_for_lo
active_pending = asyncio.Queue()
loop._pending_queues[session_key] = active_pending
- await loop._dispatch(
+ loop._enqueue_session_message(
InboundMessage(channel="cli", sender_id="u", chat_id="c", content="queued")
)
@@ -1149,7 +1149,6 @@ async def test_followup_routed_to_pending_queue(tmp_path):
loop = _make_loop(tmp_path)
loop._unified_session = True
- loop._dispatch = AsyncMock() # type: ignore[method-assign]
pending = asyncio.Queue(maxsize=20)
loop._pending_queues[UNIFIED_SESSION_KEY] = pending
@@ -1163,7 +1162,7 @@ async def test_followup_routed_to_pending_queue(tmp_path):
loop.stop()
await asyncio.wait_for(run_task, timeout=2)
- assert loop._dispatch.await_count == 0
+ assert loop._active_tasks == {}
assert queued_msg.content == "follow-up"
assert queued_msg.session_key == UNIFIED_SESSION_KEY
@@ -1176,7 +1175,6 @@ async def test_websocket_followup_is_admitted_before_recovery_queue(tmp_path):
admission = MagicMock()
admission.admit = AsyncMock(return_value=True)
loop = _make_loop(tmp_path, recovery_admission=admission)
- loop._dispatch = AsyncMock() # type: ignore[method-assign]
session_key = "websocket:chat"
pending = asyncio.Queue(maxsize=20)
@@ -1210,7 +1208,6 @@ async def test_unified_websocket_followup_admits_effective_session(tmp_path):
admission.admit = AsyncMock(return_value=True)
loop = _make_loop(tmp_path, recovery_admission=admission)
loop._unified_session = True
- loop._dispatch = AsyncMock() # type: ignore[method-assign]
pending = asyncio.Queue(maxsize=20)
loop._pending_queues[UNIFIED_SESSION_KEY] = pending
@@ -1239,7 +1236,6 @@ async def test_mid_turn_subagent_result_does_not_resolve_a_new_turn_route(tmp_pa
from nanobot.bus.events import InboundMessage
loop = _make_loop(tmp_path)
- loop._dispatch = AsyncMock() # type: ignore[method-assign]
route_policy = MagicMock(side_effect=lambda _msg, _key, route: route)
loop.turn_delivery_factory.route_policy = route_policy
@@ -1267,7 +1263,7 @@ async def test_mid_turn_subagent_result_does_not_resolve_a_new_turn_route(tmp_pa
await asyncio.wait_for(run_task, timeout=2)
assert queued_msg is msg
- assert loop._dispatch.await_count == 0
+ assert loop._active_tasks == {}
route_policy.assert_not_called()
@@ -1281,7 +1277,6 @@ async def test_cron_turn_deferred_while_session_active(tmp_path):
)
loop = _make_loop(tmp_path)
- loop._dispatch = AsyncMock() # type: ignore[method-assign]
session_key = "websocket:chat-1"
pending = asyncio.Queue(maxsize=20)
@@ -1310,17 +1305,13 @@ async def test_cron_turn_deferred_while_session_active(tmp_path):
await asyncio.wait_for(run_task, timeout=2)
assert pending.empty()
- assert loop._dispatch.await_count == 0
+ assert loop._active_tasks == {}
assert loop._cron_turns.deferred_queues[session_key] == [msg]
assert loop.pending_cron_job_ids_for_session(session_key) == {"job-1"}
- await publish_next_deferred_turn(
- deferred_queues=loop._cron_turns.deferred_queues,
- publish_inbound=loop.bus.publish_inbound,
- session_key=session_key,
- )
- queued = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=0.5)
- assert queued is msg
+ loop._process_message = AsyncMock(return_value=None)
+ await loop._run_session_queue(session_key, pending)
+ assert loop._process_message.await_args.args[0] is msg
assert session_key not in loop._cron_turns.deferred_queues
assert loop.pending_cron_job_ids_for_session(session_key) == set()
@@ -1332,7 +1323,6 @@ async def test_local_trigger_turn_deferred_while_session_active(tmp_path):
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
loop = _make_loop(tmp_path)
- loop._dispatch = AsyncMock() # type: ignore[method-assign]
session_key = "websocket:chat-1"
pending = asyncio.Queue(maxsize=20)
@@ -1364,17 +1354,13 @@ async def test_local_trigger_turn_deferred_while_session_active(tmp_path):
await asyncio.wait_for(run_task, timeout=2)
assert pending.empty()
- assert loop._dispatch.await_count == 0
+ assert loop._active_tasks == {}
assert loop._local_trigger_turns.deferred_queues[session_key] == [msg]
assert loop.pending_local_trigger_ids_for_session(session_key) == {"trg_123"}
- assert await publish_next_deferred_turn(
- deferred_queues=loop._local_trigger_turns.deferred_queues,
- publish_inbound=loop.bus.publish_inbound,
- session_key=session_key,
- ) is True
- queued = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=0.5)
- assert queued is msg
+ loop._process_message = AsyncMock(return_value=None)
+ await loop._run_session_queue(session_key, pending)
+ assert loop._process_message.await_args.args[0] is msg
assert session_key not in loop._local_trigger_turns.deferred_queues
assert loop.pending_local_trigger_ids_for_session(session_key) == set()
@@ -1386,7 +1372,7 @@ async def test_submitted_cron_turn_reports_pending_until_completed(tmp_path):
from nanobot.cron.session_turns import CRON_TRIGGER_META
loop = _make_loop(tmp_path)
- loop._running = True
+ loop._cron_turns._enqueue = MagicMock()
session_key = "websocket:chat-1"
msg = InboundMessage(
@@ -1399,9 +1385,7 @@ async def test_submitted_cron_turn_reports_pending_until_completed(tmp_path):
)
submit_task = asyncio.create_task(loop.submit_cron_turn(msg))
- queued = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=0.5)
-
- assert queued is msg
+ await asyncio.sleep(0)
assert loop.pending_cron_job_ids_for_session(session_key) == {"job-1"}
response = OutboundMessage(
@@ -1422,7 +1406,7 @@ async def test_submitted_local_trigger_turn_reports_pending_until_completed(tmp_
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
loop = _make_loop(tmp_path)
- loop._running = True
+ loop._local_trigger_turns._enqueue = MagicMock()
session_key = "websocket:chat-1"
msg = InboundMessage(
@@ -1441,9 +1425,7 @@ async def test_submitted_local_trigger_turn_reports_pending_until_completed(tmp_
)
submit_task = asyncio.create_task(loop.submit_local_trigger_turn(msg))
- queued = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=0.5)
-
- assert queued is msg
+ await asyncio.sleep(0)
assert loop.pending_local_trigger_ids_for_session(session_key) == {"trg_123"}
response = OutboundMessage(
@@ -1465,7 +1447,7 @@ async def test_local_trigger_turn_cancellation_reports_agent_failure(tmp_path):
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
loop = _make_loop(tmp_path)
- loop._running = True
+ loop._local_trigger_turns._enqueue = MagicMock()
session_key = "websocket:chat-1"
msg = InboundMessage(
@@ -1484,7 +1466,7 @@ async def test_local_trigger_turn_cancellation_reports_agent_failure(tmp_path):
)
submit_task = asyncio.create_task(loop.submit_local_trigger_turn(msg))
- assert await asyncio.wait_for(loop.bus.consume_inbound(), timeout=0.5) is msg
+ await asyncio.sleep(0)
loop._local_trigger_turns.complete(msg, error=asyncio.CancelledError())
@@ -1706,7 +1688,7 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
calls += 1
if calls == 1:
for content in ["before", "bad", "after"]:
- await loop._dispatch(InboundMessage(
+ loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="c", content=content,
))
return LLMResponse(content="answer", finish_reason="stop")
@@ -1719,7 +1701,7 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
provider.chat_stream_with_retry = chat
loop.register_runtime_context_provider(context_provider)
try:
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="cli", sender_id="u", chat_id="c", content="root",
))
loop.sessions.invalidate("cli:c")
diff --git a/tests/agent/test_session_inbox_controls.py b/tests/agent/test_session_inbox_controls.py
index 9d75fcbe9..d6b07bedd 100644
--- a/tests/agent/test_session_inbox_controls.py
+++ b/tests/agent/test_session_inbox_controls.py
@@ -5,11 +5,14 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
+from agent.session_helpers import run_session
from nanobot.agent.automation_turns import AutomationTurnError
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context
-from nanobot.bus.events import InboundMessage
+from nanobot.agent.tools.cron import CronTool
+from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
+from nanobot.cron.service import CronService
from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
from nanobot.runtime_context import public_history_messages
@@ -56,7 +59,8 @@ def _automation_message(kind: str, name: str) -> InboundMessage:
@pytest.mark.parametrize("first_kind", ["cron", "local_trigger"])
@pytest.mark.parametrize("second_fails", [False, True])
-async def test_startup_automation_turns_complete_independently(loop, first_kind, second_fails):
[email protected]("bus_running", [False, True])
+async def test_automation_turns_complete_independently(loop, first_kind, second_fails, bus_running):
started, release = asyncio.Event(), asyncio.Event()
release_second = asyncio.Event()
senders = []
@@ -75,8 +79,12 @@ async def test_startup_automation_turns_complete_independently(loop, first_kind,
loop.provider.chat_stream_with_retry = chat
second_kind = "local_trigger" if first_kind == "cron" else "cron"
submit = {"cron": loop.submit_cron_turn, "local_trigger": loop.submit_local_trigger_turn}
+ tasks = []
+ if bus_running:
+ tasks.append(asyncio.create_task(loop.run()))
+ await asyncio.sleep(0)
first = asyncio.create_task(submit[first_kind](_automation_message(first_kind, "first")))
- tasks = [first]
+ tasks.append(first)
try:
await asyncio.wait_for(started.wait(), timeout=3)
second = asyncio.create_task(submit[second_kind](_automation_message(second_kind, "second")))
@@ -121,7 +129,7 @@ async def test_cancelled_session_completes_queued_automation_waiters(loop):
await asyncio.Event().wait()
loop.provider.chat_stream_with_retry = chat
- worker = asyncio.create_task(loop._dispatch(InboundMessage(
+ worker = asyncio.create_task(run_session(loop, InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="user request",
)))
tasks = [worker]
@@ -133,7 +141,7 @@ async def test_cancelled_session_completes_queued_automation_waiters(loop):
))
tasks.extend([cron, trigger])
await asyncio.sleep(0)
- assert loop._pending_queues["websocket:test"].qsize() == 2
+ assert len(loop._deferred_automation_turns["websocket:test"]) == 2
worker.cancel()
with pytest.raises(asyncio.CancelledError):
await worker
@@ -152,13 +160,17 @@ async def test_cancelled_session_completes_queued_automation_waiters(loop):
await asyncio.gather(*tasks, return_exceptions=True)
-async def test_stop_before_startup_worker_runs_completes_automation(loop):
[email protected]("action", ["stop", "close"])
+async def test_cancel_before_worker_runs_completes_automation(loop, action):
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="unused"))
submit = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "queued")))
try:
await asyncio.sleep(0)
assert "websocket:test" in loop._pending_queues
- await loop._cancel_active_tasks("websocket:test")
+ if action == "stop":
+ await loop._cancel_active_tasks("websocket:test")
+ else:
+ await loop.aclose()
with pytest.raises(AutomationTurnError, match="CancelledError"):
await asyncio.wait_for(submit, timeout=3)
loop.provider.chat_stream_with_retry.assert_not_awaited()
@@ -170,6 +182,116 @@ async def test_stop_before_startup_worker_runs_completes_automation(loop):
await asyncio.gather(submit, return_exceptions=True)
[email protected]("bus_running", [False, True])
+async def test_ingress_sources_share_one_session_worker(loop, bus_running):
+ started, release = asyncio.Event(), asyncio.Event()
+ handled = []
+ workers = []
+ key = "websocket:test"
+
+ async def process(msg, **kwargs):
+ handled.append(msg.content)
+ workers.append(asyncio.current_task())
+ if msg.content == "first":
+ started.set()
+ await release.wait()
+ return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content=msg.content)
+
+ loop._process_message = process
+ tasks = []
+ if bus_running:
+ tasks.append(asyncio.create_task(loop.run()))
+ try:
+ first = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="first")
+ if bus_running:
+ await loop.bus.publish_inbound(first)
+ else:
+ loop._enqueue_session_message(first)
+ await asyncio.wait_for(started.wait(), timeout=3)
+ cron = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "cron")))
+ trigger = asyncio.create_task(loop.submit_local_trigger_turn(
+ _automation_message("local_trigger", "trigger"),
+ ))
+ tasks.extend([cron, trigger])
+ await asyncio.sleep(0)
+ second = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="second")
+ if bus_running:
+ await loop.bus.publish_inbound(second)
+ async with asyncio.timeout(3):
+ while loop._pending_queues[key].empty():
+ await asyncio.sleep(0)
+ else:
+ loop._enqueue_session_message(second)
+ compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact")
+ await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch)
+ assert len(loop._active_tasks[key]) == 1
+ release.set()
+ results = await asyncio.wait_for(asyncio.gather(cron, trigger), timeout=3)
+ assert [result.content for result in results] == ["cron", "trigger"]
+ assert handled == ["first", "second", "/compact", "cron", "trigger"]
+ assert len(set(workers)) == 1
+ assert loop.bus.inbound_size == 0
+ assert key not in loop._pending_queues
+ assert key not in loop._deferred_automation_turns
+ finally:
+ release.set()
+ for task in tasks:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+
[email protected]("start_with_cron", [False, True])
+async def test_cron_restriction_follows_the_current_turn(loop, tmp_path, start_with_cron):
+ cron = CronService(tmp_path / "jobs.json")
+ tool = CronTool(cron)
+ started, release = asyncio.Event(), asyncio.Event()
+ attempts = []
+ workers = []
+
+ async def chat(**kwargs):
+ workers.append(asyncio.current_task())
+ result = await tool.execute(action="add", message="reminder", every_seconds=60)
+ attempts.append(result)
+ if len(attempts) == 1:
+ started.set()
+ await release.wait()
+ return LLMResponse(content="done")
+
+ loop.provider.chat_stream_with_retry = chat
+ if start_with_cron:
+ first = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "first")))
+ else:
+ first = asyncio.create_task(run_session(loop, InboundMessage(
+ channel="websocket", sender_id="u", chat_id="test", content="first",
+ )))
+ tasks = [first]
+ try:
+ await asyncio.wait_for(started.wait(), timeout=3)
+ if not start_with_cron:
+ tasks.append(asyncio.create_task(loop.submit_cron_turn(
+ _automation_message("cron", "cron"),
+ )))
+ tasks.append(asyncio.create_task(loop.submit_local_trigger_turn(
+ _automation_message("local_trigger", "trigger"),
+ )))
+ await asyncio.sleep(0)
+ release.set()
+ await asyncio.wait_for(asyncio.gather(*tasks), timeout=3)
+ assert [result.startswith("Created job") for result in attempts] == (
+ [False, True] if start_with_cron else [True, False, True]
+ )
+ blocked = attempts[0 if start_with_cron else 1]
+ assert blocked == "Error: cannot schedule new jobs from within a cron job execution"
+ assert len(set(workers)) == 1
+ finally:
+ release.set()
+ for task in tasks:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+
@pytest.mark.parametrize("complete_on_followup", [False, True])
async def test_goal_continuation_after_followup_keeps_control_identity(loop, complete_on_followup):
loop.max_iterations = 1
diff --git a/tests/agent/test_stop_preserves_context.py b/tests/agent/test_stop_preserves_context.py
index 2034ac932..f7aded8f7 100644
--- a/tests/agent/test_stop_preserves_context.py
+++ b/tests/agent/test_stop_preserves_context.py
@@ -16,6 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from agent.session_helpers import run_session
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.session.recovery import RUNTIME_CHECKPOINT_KEY
@@ -44,13 +45,10 @@ def _make_loop(tmp_path: Path) -> AgentLoop:
@pytest.mark.asyncio
async def test_dispatch_cancellation_restores_checkpoint():
- """Regression for #2966: /stop interrupting _dispatch must materialize the
+ """Regression for #2966: /stop interrupting a session worker must materialize the
in-flight runtime checkpoint into session.messages before the cancellation
unwinds, so the next turn can see the partial work.
- This exercises the real _dispatch path (locks, pending queues, the
- CancelledError handler), so a future refactor that drops the cancel-time
- restore is caught by CI instead of silently regressing.
"""
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
@@ -105,7 +103,7 @@ async def test_dispatch_cancellation_restores_checkpoint():
msg = InboundMessage(channel="test", sender_id="u1", chat_id="c1", content="work")
with pytest.raises(asyncio.CancelledError):
- await loop._dispatch(msg)
+ await run_session(loop, msg)
roles = [m.get("role") for m in session.messages]
assert roles == ["user", "assistant", "tool"], (
@@ -145,7 +143,7 @@ async def test_dispatch_cancellation_keeps_checkpoint_for_gateway_shutdown(tmp_p
from nanobot.bus.events import InboundMessage
with pytest.raises(asyncio.CancelledError):
- await loop._dispatch(
+ await run_session(loop,
InboundMessage(channel="test", sender_id="u1", chat_id="c1", content="work")
)
diff --git a/tests/agent/test_task_cancel.py b/tests/agent/test_task_cancel.py
index 29e29af96..7decba46d 100644
--- a/tests/agent/test_task_cancel.py
+++ b/tests/agent/test_task_cancel.py
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from agent.session_helpers import run_session
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import GenerationSettings
@@ -271,7 +272,7 @@ class TestDispatch:
loop._process_message = AsyncMock(
return_value=OutboundMessage(channel="test", chat_id="c1", content="hi")
)
- await loop._dispatch(msg)
+ await run_session(loop, msg)
out = await asyncio.wait_for(bus.consume_outbound(), timeout=1.0)
assert out.content == "hi"
@@ -300,7 +301,7 @@ class TestDispatch:
loop._process_message = fake_process
- await loop._dispatch(msg)
+ await run_session(loop, msg)
first = await asyncio.wait_for(bus.consume_outbound(), timeout=1.0)
second = await asyncio.wait_for(bus.consume_outbound(), timeout=1.0)
@@ -332,9 +333,9 @@ class TestDispatch:
msg1 = InboundMessage(channel="test", sender_id="u1", chat_id="c1", content="a")
msg2 = InboundMessage(channel="test", sender_id="u1", chat_id="c1", content="b")
- t1 = asyncio.create_task(loop._dispatch(msg1))
+ t1 = asyncio.create_task(run_session(loop, msg1))
await asyncio.wait_for(first_started.wait(), timeout=1.0)
- t2 = asyncio.create_task(loop._dispatch(msg2))
+ t2 = asyncio.create_task(run_session(loop, msg2))
await asyncio.sleep(0)
assert order == ["start-a"]
diff --git a/tests/agent/test_unified_session.py b/tests/agent/test_unified_session.py
index 2edc55200..4c317d471 100644
--- a/tests/agent/test_unified_session.py
+++ b/tests/agent/test_unified_session.py
@@ -1,13 +1,13 @@
"""Tests for unified_session feature.
Covers:
-- AgentLoop._dispatch() rewrites session_key to "unified:default" when enabled
+- Session admission rewrites session_key to "unified:default" when enabled
- Existing session_key_override is respected (not overwritten)
- Feature is off by default (no behavior change for existing users)
- Config schema serialises unified_session as camelCase "unifiedSession"
- onboard-generated config.json contains "unifiedSession" key
- /new command correctly clears the shared session in unified mode
-- /new is NOT a priority command (goes through _dispatch, key rewrite applies)
+- /new is NOT a priority command; the effective session key applies
- Context window consolidation is unaffected by unified_session
"""
@@ -19,6 +19,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from agent.session_helpers import run_session
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.file_state import FileStateStore
from nanobot.bus.events import InboundMessage
@@ -78,7 +79,7 @@ def _make_msg(channel: str = "telegram", chat_id: str = "111",
# ---------------------------------------------------------------------------
class TestUnifiedSessionDispatch:
- """AgentLoop._dispatch() session key rewriting logic."""
+ """Session admission applies the unified-session routing policy."""
@pytest.mark.asyncio
async def test_unified_session_rewrites_key_to_unified_default(self, tmp_path: Path):
@@ -94,7 +95,7 @@ class TestUnifiedSessionDispatch:
loop._process_message = fake_process # type: ignore[method-assign]
msg = _make_msg(channel="telegram", chat_id="111")
- await loop._dispatch(msg)
+ await run_session(loop, msg)
assert captured == ["unified:default"]
@@ -111,9 +112,9 @@ class TestUnifiedSessionDispatch:
loop._process_message = fake_process # type: ignore[method-assign]
- await loop._dispatch(_make_msg(channel="telegram", chat_id="111"))
- await loop._dispatch(_make_msg(channel="discord", chat_id="222"))
- await loop._dispatch(_make_msg(channel="cli", chat_id="direct"))
+ await run_session(loop, _make_msg(channel="telegram", chat_id="111"))
+ await run_session(loop, _make_msg(channel="discord", chat_id="222"))
+ await run_session(loop, _make_msg(channel="cli", chat_id="direct"))
assert captured == ["unified:default", "unified:default", "unified:default"]
@@ -131,7 +132,7 @@ class TestUnifiedSessionDispatch:
loop._process_message = fake_process # type: ignore[method-assign]
msg = _make_msg(channel="telegram", chat_id="999")
- await loop._dispatch(msg)
+ await run_session(loop, msg)
assert captured == ["telegram:999"]
@@ -149,7 +150,7 @@ class TestUnifiedSessionDispatch:
loop._process_message = fake_process # type: ignore[method-assign]
msg = _make_msg(channel="telegram", chat_id="111", session_key_override="telegram:thread:42")
- await loop._dispatch(msg)
+ await run_session(loop, msg)
assert captured == ["telegram:thread:42"]
@@ -222,8 +223,7 @@ class TestCmdNewUnifiedSession:
"""/new command routing and session-clear behaviour in unified mode."""
def test_new_is_not_a_priority_command(self):
- """/new must NOT be in the priority table — it must go through _dispatch()
- so the unified session key rewrite applies before cmd_new runs."""
+ """/new uses the effective session key before its command handler runs."""
router = CommandRouter()
register_builtin_commands(router)
assert router.is_priority("/new") is False
@@ -267,7 +267,7 @@ class TestCmdNewUnifiedSession:
msg = InboundMessage(
channel="telegram", sender_id="user1", chat_id="111", content="/new",
- session_key_override="unified:default", # as _dispatch() would set it
+ session_key_override="unified:default",
)
ctx = CommandContext(
msg=msg,
@@ -350,23 +350,10 @@ class TestStopCommandWithUnifiedSession:
# Create a message from telegram channel
msg = _make_msg(channel="telegram", chat_id="123456")
- # Mock _dispatch to complete immediately
- async def fake_dispatch(m):
- pass
-
- loop._dispatch = fake_dispatch # type: ignore[method-assign]
-
- # Simulate the task creation flow (from _run loop)
- effective_key = UNIFIED_SESSION_KEY if loop._unified_session and not msg.session_key_override else msg.session_key
- task = asyncio.create_task(loop._dispatch(msg))
- loop._active_tasks.setdefault(effective_key, set()).add(task)
-
- # Wait for task to complete
- await task
-
- # Verify the task is stored under UNIFIED_SESSION_KEY, not the original channel:chat_id
- assert UNIFIED_SESSION_KEY in loop._active_tasks
- assert "telegram:123456" not in loop._active_tasks
+ loop._process_message = AsyncMock(return_value=None)
+ loop._enqueue_session_message(msg)
+ assert set(loop._active_tasks) == {UNIFIED_SESSION_KEY}
+ await asyncio.gather(*loop._active_tasks[UNIFIED_SESSION_KEY])
@pytest.mark.asyncio
async def test_stop_command_finds_task_in_unified_mode(self, tmp_path: Path):
diff --git a/tests/cli/test_restart_command.py b/tests/cli/test_restart_command.py
index 85ad3f3bd..752a4a3b1 100644
--- a/tests/cli/test_restart_command.py
+++ b/tests/cli/test_restart_command.py
@@ -146,7 +146,7 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_restart_intercepted_in_run_loop(self):
- """Verify /restart is handled at the run-loop level, not inside _dispatch."""
+ """Verify /restart is handled at the run-loop level, without starting a session worker."""
loop, bus = _make_loop()
loop.restart_mode = "exec"
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/restart")
@@ -166,7 +166,7 @@ class TestRestartCommand:
create_task=_capture_task,
)
- with patch.object(loop, "_dispatch", new_callable=AsyncMock) as mock_dispatch, \
+ with patch.object(loop, "_enqueue_session_message", new_callable=MagicMock) as mock_dispatch, \
patch("nanobot.command.builtin.asyncio", new=fake_asyncio), \
patch("nanobot.command.builtin.os.execv"):
await bus.publish_inbound(msg)
@@ -192,7 +192,7 @@ class TestRestartCommand:
loop, bus = _make_loop()
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/status")
- with patch.object(loop, "_dispatch", new_callable=AsyncMock) as mock_dispatch:
+ with patch.object(loop, "_enqueue_session_message", new_callable=MagicMock) as mock_dispatch:
await bus.publish_inbound(msg)
loop._running = True
diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.py
index 75673580e..856304731 100644
--- a/tests/command/test_compact_command.py
+++ b/tests/command/test_compact_command.py
@@ -5,6 +5,7 @@ from datetime import datetime, timedelta
from unittest.mock import AsyncMock, MagicMock
import pytest
+from agent.session_helpers import run_session
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
@@ -155,7 +156,7 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
completions = []
loop.bus.subscribe(completions.append, TurnCompleted)
- await loop._dispatch(InboundMessage(
+ await run_session(loop, InboundMessage(
channel="websocket", sender_id="user", chat_id="test", content="/compact",
metadata={"webui_turn_id": "compact-turn"},
))
@@ -246,17 +247,17 @@ async def test_compact_is_a_fifo_barrier_during_an_active_turn(loop) -> None:
return LLMResponse(content="answer", finish_reason="stop")
loop.provider.chat_stream_with_retry = chat
- task = asyncio.create_task(loop._dispatch(InboundMessage(
+ task = asyncio.create_task(run_session(loop, InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="initial question",
)))
try:
await asyncio.wait_for(started.wait(), timeout=5)
- await loop._dispatch(InboundMessage(
+ loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="before compaction",
))
command = InboundMessage(channel="cli", sender_id="u", chat_id="test", content="/compact")
await loop._dispatch_command_inline(command, key, command.content, loop.commands.dispatch)
- await loop._dispatch(InboundMessage(
+ loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="test", content="after compaction",
))
release.set()
@@ -290,10 +291,10 @@ async def test_stop_completes_compact_queued_behind_an_active_turn(loop) -> None
loop.provider.chat_stream_with_retry = chat
completions = []
loop.bus.subscribe(completions.append, TurnCompleted)
- task = asyncio.create_task(loop._dispatch(InboundMessage(
+ loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="question",
- )))
- loop._track_active_task(key, task)
+ ))
+ task = next(iter(loop._active_tasks[key]))
await asyncio.wait_for(started.wait(), timeout=5)
command = InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="/compact",
@@ -329,8 +330,8 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:
channel="websocket", sender_id="user", chat_id="test", content="/compact",
metadata={"webui_turn_id": "compact-turn"},
)
- task = asyncio.create_task(loop._dispatch(msg))
- loop._track_active_task(key, task)
+ loop._enqueue_session_message(msg)
+ task = next(iter(loop._active_tasks[key]))
await asyncio.wait_for(entered.wait(), timeout=5)
reply = await cmd_stop(CommandContext(