From c49d84b4e514008d314cad92584b0b2dcfeb83b9 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:59:40 +0800 Subject: [PATCH] fix(whatsapp_agent): retain unsent scheduled results across reconnects --- docs/guides/whatsapp-agent-platform.md | 1 + nanobot/channels/whatsapp_agent/runtime.py | 17 ++--- .../whatsapp_agent/tests/test_runtime.py | 73 ++++++++++++++++++- 3 files changed, 81 insertions(+), 10 deletions(-) diff --git a/docs/guides/whatsapp-agent-platform.md b/docs/guides/whatsapp-agent-platform.md index 8d104825b..634905fa9 100644 --- a/docs/guides/whatsapp-agent-platform.md +++ b/docs/guides/whatsapp-agent-platform.md @@ -156,6 +156,7 @@ At most one poller may run per agent token. If you start a second gateway agains - **Durable cursor.** nanobot records message ids before handling them and saves the server cursor after each batch. A restart deduplicates recorded ids. A crash between recording and dispatch can lose that message; this is not exactly-once delivery. If state cannot be saved, the channel stops instead of acknowledging more traffic. - **Retention.** WhatsApp keeps updates for 30 days. On first run, nanobot saves the current time and reads from `offset=0`, discarding messages older than that time or without a timestamp. This avoids gaps after empty polls. Keep the gateway clock synchronized. Timestamps have one-second precision, so messages from the startup second are included. Reading a large backlog can delay the first reply. Restarts retain the original boundary and cursor; changing the token starts a new boundary. - **Invalid token.** If WhatsApp rejects the token, the channel stops and logs an actionable message instead of retrying forever. +- **Scheduled results.** A result that reaches the channel before it connects or learns the creator identifier remains in the gateway's pending-delivery queue. After connection, the gateway can send the saved result without running the task again. A connection loss after any part is sent is recorded as an unknown outcome and is not automatically replayed. - **Privacy.** Agent conversations are not end-to-end encrypted. nanobot processes these messages and sends them to your configured model provider. Downloaded attachments and session history may remain on the nanobot host. Your other WhatsApp chats are unaffected. Do not use this channel for data that requires end-to-end encryption. ## Troubleshooting diff --git a/nanobot/channels/whatsapp_agent/runtime.py b/nanobot/channels/whatsapp_agent/runtime.py index f13f8a2f4..02651b02b 100644 --- a/nanobot/channels/whatsapp_agent/runtime.py +++ b/nanobot/channels/whatsapp_agent/runtime.py @@ -32,6 +32,7 @@ from weakref import ReferenceType, ref import httpx from pydantic import Field +from nanobot.bus.delivery import ChannelNotReadyError from nanobot.bus.events import OutboundMessage from nanobot.bus.queue import MessageBus from nanobot.channels.base import BaseChannel @@ -247,7 +248,7 @@ class WhatsAppAgentChannel(BaseChannel): """Perform one paced API request and decode a JSON body when present.""" client = self._client if client is None: - raise RuntimeError("WhatsApp Agent Platform channel is not connected") + raise ChannelNotReadyError("WhatsApp Agent Platform channel is not connected") await self._limiter.acquire(method_key) response = await client.request( @@ -740,14 +741,8 @@ class WhatsAppAgentChannel(BaseChannel): to = self._recipient() if not to: - raise WhatsAppAgentAPIError( - APIError( - status_code=0, - code=0, - message="No creator identifier is known yet; wait for an inbound message.", - details="", - fbtrace_id="", - ) + raise ChannelNotReadyError( + "No creator identifier is known yet; wait for an inbound message." ) # The reply implicitly clears the typing indicator. @@ -780,6 +775,10 @@ class WhatsAppAgentChannel(BaseChannel): self._pending_sends.pop(key, None) raise except Exception as exc: + if isinstance(exc, ChannelNotReadyError) and pending.next_part: + # The scheduled outbox can only replay a wholly unsent result. + # A reconnect after partial delivery must not resend earlier parts. + raise RuntimeError("WhatsApp Agent connection closed after partial delivery") from exc if not self.should_retry_send_error(exc): self._pending_sends.pop(key, None) raise diff --git a/nanobot/channels/whatsapp_agent/tests/test_runtime.py b/nanobot/channels/whatsapp_agent/tests/test_runtime.py index de9f82675..c58c77ba5 100644 --- a/nanobot/channels/whatsapp_agent/tests/test_runtime.py +++ b/nanobot/channels/whatsapp_agent/tests/test_runtime.py @@ -11,6 +11,7 @@ import base64 import gc import hashlib import json +import sqlite3 from pathlib import Path from typing import Any @@ -18,6 +19,7 @@ import httpx import pytest from loguru import logger +from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRequest from nanobot.bus.events import OutboundMessage from nanobot.bus.outbound_events import ProgressEvent from nanobot.bus.queue import MessageBus @@ -471,12 +473,58 @@ def test_reply_quotes_the_originating_message_once(tmp_path: Path, monkeypatch: def test_send_without_a_known_creator_fails_loudly(tmp_path: Path): channel = _channel(tmp_path) - with pytest.raises(WhatsAppAgentAPIError): + with pytest.raises(ChannelNotReadyError): asyncio.run( channel.send(OutboundMessage(channel="whatsapp_agent", chat_id=CREATOR_CHAT_ID, content="hi")) ) +@pytest.mark.parametrize("outage", ["offline", "creator_unknown", "after_first_chunk"]) +async def test_scheduled_delivery_recovers_only_before_any_part_was_sent( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, outage: str, +): + from nanobot.channels import outbox as outbox_module + from nanobot.config.schema import Config + + monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0) + config = Config.model_validate({"channels": {"websocket": {"enabled": False}}}) + manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json") + channel = _channel(tmp_path) + if outage != "creator_unknown": + channel._state.note_creator("user:55") + sent: list[str] = [] + + def accept(request: httpx.Request) -> httpx.Response: + sent.append(json.loads(request.content)["text"]["body"]) + if outage == "after_first_chunk": + channel._client = None + return httpx.Response(200, json={"messages": [{"id": "wamid.sent"}]}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(accept)) as client: + if outage != "offline": + channel._client = client + msg = OutboundMessage(channel.name, CREATOR_CHAT_ID, "x" * 5000, + delivery=DeliveryRequest("scheduled-run", "whatsapp_agent:creator", None)) + manager._outbox.record(msg) + await manager._send_scheduled(channel, msg) + with sqlite3.connect(manager._outbox.path) as db: + status, error = db.execute("SELECT status, error FROM deliveries").fetchone() + if outage == "after_first_chunk": + assert status == "unknown" + assert error != "channel_not_ready" + assert sent == ["x" * 4096] + assert manager._outbox.ready() == [] + else: + assert (status, error) == ("pending", "channel_not_ready") + assert sent == [] + channel._client = client + channel._state.note_creator("user:55") + [saved] = manager._outbox.ready() + await manager._send_scheduled(channel, saved) + assert sent == ["x" * 4096, "x" * 904] + assert manager._outbox.ready() == [] + + def test_outbound_wamid_is_remembered_for_receipts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): channel = _channel(tmp_path) channel._state.note_creator("user:55") @@ -492,6 +540,29 @@ def test_outbound_wamid_is_remembered_for_receipts(tmp_path: Path, monkeypatch: assert channel._state.last_status["wamid.sent"] == "sent" +async def test_normal_retry_keeps_partial_progress_after_disconnect(tmp_path: Path): + channel = _channel(tmp_path) + channel._state.note_creator("user:55") + sent: list[str] = [] + + def accept(request: httpx.Request) -> httpx.Response: + sent.append(json.loads(request.content)["text"]["body"]) + channel._client = None + return httpx.Response(200, json={"messages": [{"id": "wamid.sent"}]}) + + msg = OutboundMessage(channel.name, CREATOR_CHAT_ID, "x" * 5000) + async with httpx.AsyncClient(transport=httpx.MockTransport(accept)) as client: + channel._client = client + with pytest.raises(RuntimeError, match="after partial delivery") as caught: + await channel.send(msg) + assert not isinstance(caught.value, ChannelNotReadyError) + assert channel.should_retry_send_error(caught.value) + channel._client = client + await channel.send(msg) + assert sent == ["x" * 4096, "x" * 904] + assert not channel._pending_sends + + def test_media_uses_the_matching_payload_object_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): channel = _channel(tmp_path) channel._state.note_creator("user:55")