test(cron): cover WebUI-origin cross-channel delivery

This commit is contained in:
Xubin Ren committed 2026-10-17 12:49:03 +08:00
1 parent 182ada6825
commit 8691bdedd5
2 files changed
+46 -11

No files matched your search

+7
View File
@@ -46,6 +46,11 @@ Write what the task should do, such as "Remind me to drink water". nanobot sends
For separate sends, specify the recipients in the instructions. The agent can still use `message` to send to other chats, send to several recipients, or attach files. Existing tasks that explicitly request this tool remain supported. For separate sends, specify the recipients in the instructions. The agent can still use `message` to send to other chats, send to several recipients, or attach files. Existing tasks that explicitly request this tool remain supported.
Writing "send to WhatsApp" in a task's instructions does not change its saved chat. If you create
the task in a WebUI chat, its normal reply still returns there. A separate WhatsApp send requires
the agent to call `message` with that destination. To make WhatsApp the normal reply destination,
create the task in that WhatsApp chat, or change its saved chat in Automations.
### Scheduled Result Delivery ### Scheduled Result Delivery
Task completion and message delivery are separate. `Turn completed` and a successful task run Task completion and message delivery are separate. `Turn completed` and a successful task run
@@ -55,6 +60,8 @@ The gateway saves final scheduled messages before it accepts them into the outgo
This includes explicit `message` calls in existing tasks. Each recipient has a separate delivery This includes explicit `message` calls in existing tasks. Each recipient has a separate delivery
record. Progress, reasoning, and streaming events do not enter this queue. WebUI streaming and record. Progress, reasoning, and streaming events do not enter this queue. WebUI streaming and
saved chat history keep their existing behavior. saved chat history keep their existing behavior.
The queue cannot recover a send that the agent never requested. If an expected recipient has no
delivery record, check the task's saved chat and the run's `message` tool calls first.
External channels receive one final scheduled reply instead of a streamed reply. Ordinary chat External channels receive one final scheduled reply instead of a streamed reply. Ordinary chat
streaming is unchanged. streaming is unchanged.
+39 -11
View File
@@ -11,6 +11,7 @@ import pytest
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import RequestContext, request_context from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.tools.cron import CronTool
from nanobot.agent.tools.message import MessageTool from nanobot.agent.tools.message import MessageTool
from nanobot.bus.delivery import ( from nanobot.bus.delivery import (
DELIVERY_RUN_META, DELIVERY_RUN_META,
@@ -61,8 +62,11 @@ async def drain(manager):
await asyncio.sleep(0.01) await asyncio.sleep(0.01)
@pytest.mark.parametrize("legacy_message,one_shot", [(False, False), (True, False), (True, True)]) @pytest.mark.parametrize("legacy_message,one_shot,origin", [
async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, monkeypatch, legacy_message, one_shot): (False, False, "whatsapp"), (True, False, "whatsapp"), (True, True, "whatsapp"),
(True, False, "websocket"),
])
async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, monkeypatch, legacy_message, one_shot, origin):
monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0) monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)
workspace = tmp_path / "workspace" workspace = tmp_path / "workspace"
workspace.mkdir() workspace.mkdir()
@@ -80,8 +84,11 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
async def reply(**kwargs): async def reply(**kwargs):
calls.append(kwargs) calls.append(kwargs)
if legacy_message and len(calls) == 1: if legacy_message and len(calls) == 1:
arguments = {"content": "Diagnostic result"}
if origin == "websocket":
arguments.update(channel="whatsapp", chat_id="synthetic")
return LLMResponse(content=None, tool_calls=[ToolCallRequest( return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="send", name="message", arguments={"content": "Diagnostic result"}, id="send", name="message", arguments=arguments,
)], finish_reason="tool_calls") )], finish_reason="tool_calls")
return LLMResponse(content="Diagnostic result") return LLMResponse(content="Diagnostic result")
@@ -98,13 +105,30 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
monkeypatch.setattr(channel, "_build_jid", lambda value: value) monkeypatch.setattr(channel, "_build_jid", lambda value: value)
monkeypatch.setattr(channel, "stop", AsyncMock()) monkeypatch.setattr(channel, "stop", AsyncMock())
manager.channels["whatsapp"] = channel manager.channels["whatsapp"] = channel
if origin == "websocket":
manager.channels["websocket"] = MagicMock(spec=BaseChannel, send=AsyncMock(), stop=AsyncMock())
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound()) manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
# Legacy channel/to fields still normalize through the existing binding migration. # Legacy channel/to fields still normalize through the existing binding migration.
schedule = CronSchedule(kind="at", at_ms=4102444800000) if one_shot else CronSchedule(kind="every", every_ms=86400000) schedule = CronSchedule(kind="at", at_ms=4102444800000) if one_shot else CronSchedule(kind="every", every_ms=86400000)
job = cron.add_job("Reminder", schedule, if origin == "websocket":
"Use message to send Diagnostic result" if legacy_message else "Return Diagnostic result", # A WebUI-created task remains in its source chat even when its instructions
deliver=True, channel="whatsapp", to="synthetic", delete_after_run=one_shot, # explicitly request a separate send. Recovery must keep that send's target.
channel_meta={"_wants_stream": True}) with request_context(RequestContext("websocket", "source", session_key="websocket:source",
metadata={"webui": True, "_wants_stream": True})):
await CronTool(cron).execute(action="add", name="Reminder", every_seconds=86400,
message="Use message to send Diagnostic result to whatsapp:synthetic")
job = cron.list_jobs()[0]
assert job.payload.session_key == "websocket:source"
assert job.payload.origin_channel == "websocket"
else:
job = cron.add_job("Reminder", schedule,
"Use message to send Diagnostic result" if legacy_message else "Return Diagnostic result",
deliver=True, channel="whatsapp", to="synthetic", delete_after_run=one_shot,
channel_meta={"_wants_stream": True})
def whatsapp_rows():
return [row for row in rows(manager._outbox) if row["channel"] == "whatsapp"]
try: try:
assert await asyncio.wait_for(cron.run_job(job.id), 15) assert await asyncio.wait_for(cron.run_job(job.id), 15)
await drain(manager) await drain(manager)
@@ -112,8 +136,12 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
assert cron.list_jobs() == [] assert cron.list_jobs() == []
else: else:
assert cron.list_jobs()[0].state.last_status == "ok" assert cron.list_jobs()[0].state.last_status == "ok"
assert len(rows(manager._outbox)) == 1 assert len(whatsapp_rows()) == 1
assert rows(manager._outbox)[0]["status"] == "pending" assert whatsapp_rows()[0]["status"] == "pending"
if origin == "websocket":
saved = json.loads(whatsapp_rows()[0]["payload"])
assert saved["delivery"]["session_key"] == "websocket:source"
assert saved["metadata"] == {}
channel._client.send_message.assert_not_called() channel._client.send_message.assert_not_called()
count = len(calls) count = len(calls)
assert count == (2 if legacy_message else 1) assert count == (2 if legacy_message else 1)
@@ -127,8 +155,8 @@ async def test_cron_offline_restart_and_reconnect_do_not_rerun_model(tmp_path, m
await manager._recover_scheduled() await manager._recover_scheduled()
await drain(manager) await drain(manager)
channel._client.send_message.assert_awaited_once_with("synthetic", "Diagnostic result") channel._client.send_message.assert_awaited_once_with("synthetic", "Diagnostic result")
assert rows(manager._outbox)[0]["status"] == "sent" assert whatsapp_rows()[0]["status"] == "sent"
assert rows(manager._outbox)[0]["payload"] is None assert whatsapp_rows()[0]["payload"] is None
again = make_manager(tmp_path, sessions) again = make_manager(tmp_path, sessions)
again.channels["whatsapp"] = channel again.channels["whatsapp"] = channel
await again._recover_scheduled() await again._recover_scheduled()