Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(channels): retain scheduled results across pre-send outages
Xubin Ren508cedff3118
diff --git a/docs/automations.md b/docs/automations.mdindex 5b3c13ac3..0746a1f4e 100644--- a/docs/automations.md+++ b/docs/automations.md@@ -64,6 +64,46 @@ Repetition alone does not select heartbeat. "Every day at 8am, remind me to drinAn upgrade does not overwrite your workspace's `AGENTS.md` or convert existing heartbeat entries into cron jobs. The current scheduling rules are included in the system prompt. If an old workspace rule directs all recurring tasks to heartbeat, update that rule too. To correct an existing reminder, remove its old heartbeat entry and create the cron task once. Check the task list to avoid duplicates.+### Scheduled Result Delivery++The gateway saves final scheduled messages before it accepts them into the outgoing queue.+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+saved chat history keep their existing behavior. External channels receive a complete scheduled+reply instead of a streamed reply. Ordinary chat streaming is unchanged.++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` calls first.++If a channel reports that it has not sent any part of a message, the gateway retries every+30 seconds, for up to one hour after queue acceptance. It sends the saved message to the saved+destination. It does not run the task or call the model again. A gateway restart resumes pending+messages. Deleting or resetting the source chat cancels pending messages from that chat generation.+Disabling a channel prevents its pending messages from being sent. Changing, pausing, or deleting+a task affects future runs; it does not redirect or recall an already queued result.++If a request times out after sending starts, or the gateway stops during a send, delivery is+unknown. The gateway does not retry that message automatically: the service might already have+accepted it. Check the destination before sending the result again. This is not an exactly-once+delivery guarantee. Adapter or service-specific retries still follow their own protocol.++Look for `Channel delivery` in the gateway log. The run ID links execution to each delivery ID:++| Status | Meaning |+|---|---|+| `pending` | Saved locally; waiting for an attempt or a channel connection |+| `sent` | The channel adapter completed its send; not a recipient read receipt |+| `failed` | Not sent: expired, disabled channel, replaced source chat, or rejected destination/policy |+| `unknown` | An interrupted or failed attempt might have reached the service; no automatic retry |++The queue is stored in `delivery/outbox.sqlite3`, beside the active config file. Include this+directory in instance backups; stop the gateway before copying it. It holds at most 256 pending+messages, with a 1 MiB serialized limit per message. A full queue or storage error rejects the+enqueue operation instead of reporting it as accepted. Terminal records discard message text+and keep status for up to seven days, capped at 1,000 records. Existing job and session files+are not converted. Older versions ignore this queue. After an upgrade, pending messages can+resume only within the original one-hour limit.+## Local TriggersLocal triggers let a local script or external service send a message into a specific nanobot session later.diff --git a/nanobot/agent/tools/message.py b/nanobot/agent/tools/message.pyindex 0c04637c6..49f793058 100644--- a/nanobot/agent/tools/message.py+++ b/nanobot/agent/tools/message.py@@ -14,6 +14,7 @@ from nanobot.agent.tools.base import Tool, ToolResult, tool_parametersfrom nanobot.agent.tools.context import ToolContext, current_request_contextfrom nanobot.agent.tools.path_utils import resolve_workspace_pathfrom nanobot.agent.tools.schema import ArraySchema, StringSchema, tool_parameters_schema+from nanobot.bus.delivery import DeliveryRequestfrom nanobot.bus.events import OutboundMessagefrom nanobot.config.paths import get_workspace_pathfrom nanobot.security.workspace_access import current_tool_workspace@@ -236,6 +237,9 @@ class MessageTool(Tool):media=media or [],buttons=button_rows or [],metadata=metadata,+ delivery=(DeliveryRequest.from_context(+ default_metadata, request_ctx.session_key, request_ctx.session_generation,+ ) if request_ctx is not None else None),)if self._suppress_delivery_var.get():@@ -253,6 +257,7 @@ class MessageTool(Tool):if button_rowselse "")- return f"Message sent to {channel}:{chat_id}{media_info}{button_info}"+ action = "queued" if msg.delivery is not None else "sent"+ return f"Message {action} to {channel}:{chat_id}{media_info}{button_info}"except Exception as e:return ToolResult.error(f"Error sending message: {str(e)}")diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.pyindex e8ce9ae7b..988e44398 100644--- a/nanobot/agent/turn_delivery.py+++ b/nanobot/agent/turn_delivery.py@@ -9,6 +9,7 @@ from copy import deepcopyfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, cast+from nanobot.bus.delivery import DeliveryRequestfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.notification_delivery import notification_is_deliverablefrom nanobot.bus.outbound_events import (@@ -341,6 +342,12 @@ class TurnDelivery:"response_sources": [dataclasses.asdict(self._response_source)],})if response.channel != "websocket" or stop_reason != "error":+ delivery = DeliveryRequest.from_context(+ self.input_message.metadata, self.session_key,+ self.delivery_message.session_generation,+ )+ if delivery is not None:+ response = dataclasses.replace(response, delivery=delivery)await self.bus.publish_outbound(response)elif self.lifecycle_message.channel == "cli":await self.bus.publish_outbound(diff --git a/nanobot/bus/delivery.py b/nanobot/bus/delivery.pynew file mode 100644index 000000000..bfde9db5b--- /dev/null+++ b/nanobot/bus/delivery.py@@ -0,0 +1,36 @@+"""Delivery correlation and pre-send failure contracts, independent of transports."""++from __future__ import annotations++from collections.abc import Mapping+from dataclasses import dataclass++DELIVERY_RUN_META = "_delivery_run_id"+++class ChannelNotReadyError(RuntimeError):+ """No part of the message was sent; retry after the channel reconnects."""+++class DeliveryRejectedError(RuntimeError):+ """No part of the message was sent; configuration or destination needs repair."""+++@dataclass(frozen=True)+class DeliveryRequest:+ """A scheduled result belongs to one run and one admitted source session."""++ run_id: str+ session_key: str+ session_generation: str | None++ @classmethod+ def from_context(+ cls, metadata: Mapping[str, object], session_key: str | None, generation: str | None,+ ) -> DeliveryRequest | None:+ run_id = metadata.get(DELIVERY_RUN_META)+ if not isinstance(run_id, str) or not run_id:+ return None+ if not session_key:+ raise ValueError("Scheduled delivery requires a source session")+ return cls(run_id, session_key, generation)diff --git a/nanobot/bus/events.py b/nanobot/bus/events.pyindex 5b031c0e1..a2b2325a8 100644--- a/nanobot/bus/events.py+++ b/nanobot/bus/events.py@@ -4,6 +4,8 @@ from dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import TYPE_CHECKING, Any, Literal+from nanobot.bus.delivery import DeliveryRequest+if TYPE_CHECKING:from nanobot.events import AgentEvent@@ -68,3 +70,5 @@ class OutboundMessage:metadata: dict[str, Any] = field(default_factory=dict)buttons: list[list[str]] = field(default_factory=list)event: "AgentEvent | None" = None+ delivery: DeliveryRequest | None = None+ delivery_id: str | None = Nonediff --git a/nanobot/bus/queue.py b/nanobot/bus/queue.pyindex eee2a1923..8a344a82a 100644--- a/nanobot/bus/queue.py+++ b/nanobot/bus/queue.py@@ -33,6 +33,7 @@ class MessageBus:self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()self._handlers: list[EventHandler] = []self._pending: set[asyncio.Task[None]] = set()+ self.outbound_recorder: Callable[[OutboundMessage], None] | None = Noneasync def publish_inbound(self, msg: InboundMessage) -> None:"""Publish a message from a channel to the agent."""@@ -44,6 +45,8 @@ class MessageBus:async def publish_outbound(self, msg: OutboundMessage) -> None:"""Queue a routed message or event for its channel."""+ if self.outbound_recorder is not None:+ self.outbound_recorder(msg)await self.outbound.put(msg)async def publish_event(diff --git a/nanobot/channels/base.py b/nanobot/channels/base.pyindex f59045a35..a9466c46e 100644--- a/nanobot/channels/base.py+++ b/nanobot/channels/base.py@@ -100,6 +100,10 @@ class BaseChannel(ABC):Implementations should raise on delivery failure so the channel managercan apply any retry policy in one place.+ Raise ChannelNotReadyError only before submitting any part of a message.+ Raise DeliveryRejectedError for a rejected destination or policy.+ Other exceptions have an unknown delivery outcome for scheduled results.+ A normal return confirms this adapter completed, not a recipient read receipt."""passdiff --git a/nanobot/channels/dingtalk/runtime.py b/nanobot/channels/dingtalk/runtime.pyindex 86d0a1cbd..de297d2bc 100644--- a/nanobot/channels/dingtalk/runtime.py+++ b/nanobot/channels/dingtalk/runtime.py@@ -17,6 +17,7 @@ from urllib.parse import unquote, urljoin, urlparseimport httpxfrom pydantic import Field+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel@@ -742,7 +743,7 @@ class DingTalkChannel(BaseChannel):returntoken = await self._get_access_token()if not token:- raise RuntimeError("DingTalk access token unavailable")+ raise ChannelNotReadyError("DingTalk access token unavailable")content = msg.content.strip() if msg.content else ""if content:diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex 7257b515a..c4ef223cc 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Any, Literal, castfrom pydantic import Field+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEventfrom nanobot.bus.queue import MessageBus@@ -539,7 +540,7 @@ class DiscordChannel(BaseChannel):"""Send a message through Discord using discord.py."""client = self._clientif client is None or not client.is_ready():- raise RuntimeError("Discord client is not ready")+ raise ChannelNotReadyError("Discord client is not ready")is_progress = isinstance(msg.event, ProgressEvent)diff --git a/nanobot/channels/email/runtime.py b/nanobot/channels/email/runtime.pyindex 6ee202f1e..92f9beaaf 100644--- a/nanobot/channels/email/runtime.py+++ b/nanobot/channels/email/runtime.py@@ -23,6 +23,7 @@ from typing import Any, Literal, castfrom loguru import loggerfrom pydantic import Field, field_validator+from nanobot.bus.delivery import DeliveryRejectedErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -245,12 +246,10 @@ class EmailChannel(BaseChannel):):returnif not self.config.consent_granted:- self.logger.warning("Skip email send: consent_granted is false")- return+ raise DeliveryRejectedError("Email consent_granted is false")if not self.config.smtp_host:- self.logger.warning("SMTP host not configured")- return+ raise DeliveryRejectedError("SMTP host not configured")# Skip progress messages to prevent sending an empty email after each tool callif isinstance(msg.event, ProgressEvent):@@ -259,8 +258,7 @@ class EmailChannel(BaseChannel):to_addr = msg.chat_id.strip()if not to_addr:- self.logger.warning("Missing recipient address")- return+ raise DeliveryRejectedError("Missing email recipient address")# Determine if this is a reply (recipient has sent us an email before)is_reply = to_addr in self._last_subject_by_chat@@ -268,8 +266,7 @@ class EmailChannel(BaseChannel):# autoReplyEnabled only controls automatic replies, not proactive sendsif is_reply and not self.config.auto_reply_enabled and not force_send:- self.logger.info("Skip automatic reply to {}: auto_reply_enabled is false", to_addr)- return+ raise DeliveryRejectedError("Email auto_reply_enabled is false")base_subject = self._last_subject_by_chat.get(to_addr, "nanobot reply")subject = self._reply_subject(base_subject)diff --git a/nanobot/channels/email/tests/test_email_channel.py b/nanobot/channels/email/tests/test_email_channel.pyindex 917cfac42..668ebce05 100644--- a/nanobot/channels/email/tests/test_email_channel.py+++ b/nanobot/channels/email/tests/test_email_channel.py@@ -5,6 +5,7 @@ from pathlib import Pathimport pytest+from nanobot.bus.delivery import DeliveryRejectedErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -874,14 +875,15 @@ async def test_send_skips_reply_when_auto_reply_disabled(monkeypatch) -> None:# Mark alice as someone who sent us an email (making this a "reply")channel._last_subject_by_chat["[email protected]"] = "Previous email"- # Reply should be skipped (auto_reply_enabled=False)- await channel.send(- OutboundMessage(- channel="email",- chat_id="[email protected]",- content="Should not send.",+ # A policy rejection must not look like successful delivery to the manager.+ with pytest.raises(DeliveryRejectedError, match="auto_reply_enabled"):+ await channel.send(+ OutboundMessage(+ channel="email",+ chat_id="[email protected]",+ content="Should not send.",+ ))- )assert fake_instances == []# Reply with force_send=True should be sent@@ -979,14 +981,15 @@ async def test_send_skips_when_consent_not_granted(monkeypatch) -> None:cfg = _make_config()cfg.consent_granted = Falsechannel = EmailChannel(cfg, MessageBus())- await channel.send(- OutboundMessage(- channel="email",- chat_id="[email protected]",- content="Should not send.",- metadata={"force_send": True},+ with pytest.raises(DeliveryRejectedError, match="consent_granted"):+ await channel.send(+ OutboundMessage(+ channel="email",+ chat_id="[email protected]",+ content="Should not send.",+ metadata={"force_send": True},+ ))- )assert called["smtp"] is Falsediff --git a/nanobot/channels/feishu/runtime.py b/nanobot/channels/feishu/runtime.pyindex ec8a184a5..ed54d2130 100644--- a/nanobot/channels/feishu/runtime.py+++ b/nanobot/channels/feishu/runtime.py@@ -25,6 +25,7 @@ from rich.markup import escapefrom rich.panel import Panelfrom rich.text import Text+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -2446,10 +2447,7 @@ class FeishuChannel(BaseChannel):):returnif not self._client:- if msg.metadata.get(PAIRING_CODE_META_KEY):- raise RuntimeError("Feishu client is not ready to send the pairing reply")- self.logger.warning("client not initialized")- return+ raise ChannelNotReadyError("Feishu client is not ready to send the reply")try:receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.pyindex 3929d2904..e3ab0b6f5 100644--- a/nanobot/channels/linear/runtime.py+++ b/nanobot/channels/linear/runtime.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom typing import Any, castfrom urllib.parse import urlparse+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEventfrom nanobot.bus.queue import MessageBus@@ -167,6 +168,8 @@ class LinearChannel(BaseChannel):ephemeral=True,)return+ if self._client is None:+ raise ChannelNotReadyError("Linear HTTP client is not initialized")body = msg.contentif msg.media:attachments = await self._attachment_markdown(msg)diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.pyindex 74919ceee..1f21b7d5b 100644--- a/nanobot/channels/manager.py+++ b/nanobot/channels/manager.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asyncioimport hashlibimport inspect+import timefrom collections import OrderedDictfrom collections.abc import Awaitable, Callable, Iterable, Mappingfrom contextlib import suppress@@ -13,6 +14,7 @@ from typing import TYPE_CHECKING, Any, castfrom loguru import logger+from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import (ProgressEvent,@@ -32,8 +34,11 @@ from nanobot.channels.contracts import (channel_runtime_name,resolve_channel_action_target,)+from nanobot.channels.outbox import RETRY_SECONDS, DeliveryOutboxfrom nanobot.channels.registry import channel_default_enabledfrom nanobot.config.schema import Config+from nanobot.security.workspace_access import WorkspaceScopeResolver+from nanobot.security.workspace_policy import resolve_allowed_pathfrom nanobot.utils.restart import (RestartNotice,consume_restart_notice_from_env,@@ -154,6 +159,9 @@ class ChannelManager:self._stopping_channels: set[str] = set()self._started = Falseself._origin_reply_fingerprints: OrderedDict[tuple[str, str, str], str] = OrderedDict()+ self._outbox = DeliveryOutbox(self._config_path.parent / "delivery" / "outbox.sqlite3")+ self._scheduled_deliveries: set[str] = set()+ self.bus.outbound_recorder = self._outbox.recordself._init_channels()@@ -750,18 +758,25 @@ class ChannelManager:Retry waits occupy only their destination and one send slot. Saturationpauses dispatch rather than creating unbounded tasks or dropping messages."""+ if msg.delivery_id in self._scheduled_deliveries:+ returnawait self._outbound_slots.acquire()if msg.channel in self._stopping_channels or self.channels.get(msg.channel) is not channel:self._outbound_slots.release()returnkey = (msg.channel, msg.chat_id)previous = self._outbound_tails.get(key)+ if msg.delivery_id is not None:+ self._scheduled_deliveries.add(msg.delivery_id)async def send() -> None:if previous is not None:await asyncio.shield(asyncio.gather(previous, return_exceptions=True))async with self._outbound_sends:- await self._send_with_retry(channel, msg)+ if msg.delivery_id is not None:+ await self._send_scheduled(channel, msg)+ else:+ await self._send_with_retry(channel, msg)task = asyncio.create_task(send(), name=f"outbound-{msg.channel}-{msg.chat_id}")self._outbound_tasks[task] = key@@ -769,6 +784,8 @@ class ChannelManager:def finished(done: asyncio.Task[None]) -> None:self._outbound_tasks.pop(done, None)+ if msg.delivery_id is not None:+ self._scheduled_deliveries.discard(msg.delivery_id)if self._outbound_tails.get(key) is done:self._outbound_tails.pop(key, None)self._outbound_slots.release()@@ -777,6 +794,58 @@ class ChannelManager:task.add_done_callback(finished)+ async def _send_scheduled(self, channel: BaseChannel, msg: OutboundMessage) -> None:+ request = msg.delivery+ if request is not None and request.session_generation is not None and self._session_manager:+ session = await self._session_manager.state.read(request.session_key)+ if session is None or session.generation != request.session_generation:+ self._outbox.finish(msg, "failed", "session_replaced")+ return+ if msg.media:+ # An accepted local path can become a symlink during an outage.+ # Recheck the current source policy before the adapter opens it.+ scope = WorkspaceScopeResolver(+ self.config.workspace_path, self.config.tools.restrict_to_workspace,+ ).for_turn(channel=request.session_key.split(":", 1)[0],+ message_metadata={}, session_metadata=session.metadata)+ try:+ for path in msg.media:+ if not path.startswith(("http://", "https://")):+ resolve_allowed_path(+ path, workspace=scope.project_path,+ allowed_root=scope.project_path if scope.restrict_to_workspace else None,+ extra_allowed_roots=[self._config_path.parent / "media"],+ )+ except (OSError, ValueError):+ self._outbox.finish(msg, "failed", "attachment_access_denied")+ return+ if not self._outbox.claim(msg):+ return+ try:+ await self._send_once(channel, msg)+ except ChannelNotReadyError:+ # The adapter guarantees that no part of the message was submitted.+ self._outbox.finish(msg, "pending", "channel_not_ready")+ except DeliveryRejectedError:+ self._outbox.finish(msg, "failed", "delivery_rejected")+ except asyncio.CancelledError:+ self._outbox.finish(msg, "unknown", "interrupted_send")+ raise+ except Exception as error:+ # A timeout can follow an accepted send, including a partial multi-part send.+ # Retrying the whole result here could deliver it twice.+ self._outbox.finish(msg, "unknown", type(error).__name__)+ else:+ self._outbox.finish(msg, "sent")++ async def _recover_scheduled(self) -> None:+ for msg in self._outbox.ready():+ channel = self.channels.get(msg.channel)+ if channel is None:+ self._outbox.finish(msg, "failed", "channel_disabled")+ else:+ await self._queue_outbound(channel, msg)+async def _dispatch_outbound(self) -> None:try:await self._dispatch_outbound_loop()@@ -790,9 +859,16 @@ class ChannelManager:# Buffer for messages that couldn't be processed during delta coalescing# (since asyncio.Queue doesn't support push_front)pending: list[OutboundMessage] = []+ next_recovery = 0.0while True:try:+ if time.monotonic() >= next_recovery:+ next_recovery = time.monotonic() + RETRY_SECONDS+ try:+ await self._recover_scheduled()+ except Exception:+ logger.exception("Scheduled delivery recovery failed; check the instance delivery store")# First check pending buffer before waiting on queueif pending:msg = pending.pop(0)@@ -856,12 +932,14 @@ class ChannelManager:StreamDeltaEvent | StreamEndEvent | StreamedResponseEvent,)):- if self._should_suppress_outbound(msg):+ if msg.delivery_id is None and self._should_suppress_outbound(msg):logger.info("Suppressing duplicate outbound message to {}:{}", msg.channel, msg.chat_id)continueawait self._queue_outbound(channel, msg)else:logger.warning("Unknown channel: {}", msg.channel)+ if msg.delivery_id is not None:+ self._outbox.finish(msg, "failed", "channel_disabled")except asyncio.TimeoutError:continue@@ -1043,7 +1121,7 @@ class ChannelManager:except asyncio.CancelledError:raise # Propagate cancellation for graceful shutdownexcept Exception as e:- if not channel.should_retry_send_error(e):+ if isinstance(e, DeliveryRejectedError) or not channel.should_retry_send_error(e):logger.error("Send to {} failed with a non-retryable {}: {}",msg.channel,diff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.pyindex 8eb9b94dd..94997d9b1 100644--- a/nanobot/channels/matrix/runtime.py+++ b/nanobot/channels/matrix/runtime.py@@ -58,6 +58,7 @@ except ImportError as e:"Matrix dependencies not installed. Run: nanobot plugins enable matrix") from e+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -621,7 +622,7 @@ class MatrixChannel(BaseChannel):):returnif not self.client:- raise RuntimeError("Matrix client not initialized")+ raise ChannelNotReadyError("Matrix client not initialized")text = msg.content or ""candidates = self._collect_outbound_media_candidates(msg.media)relates_to = self._build_outbound_relates_to(msg.metadata)diff --git a/nanobot/channels/mattermost/runtime.py b/nanobot/channels/mattermost/runtime.pyindex 039aac9cc..580f1e630 100644--- a/nanobot/channels/mattermost/runtime.py+++ b/nanobot/channels/mattermost/runtime.py@@ -11,6 +11,7 @@ from typing import Any, castimport httpxfrom pydantic import Field, model_validator+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -499,8 +500,7 @@ class MattermostChannel(BaseChannel):):returnif not self._http_client:- self.logger.warning("client not initialized")- return+ raise ChannelNotReadyError("Mattermost client not initialized")try:chat_id = msg.chat_iddiff --git a/nanobot/channels/mochat/runtime.py b/nanobot/channels/mochat/runtime.pyindex 4c60321d8..12ba004c0 100644--- a/nanobot/channels/mochat/runtime.py+++ b/nanobot/channels/mochat/runtime.py@@ -15,6 +15,7 @@ from typing import Any, castimport httpxfrom pydantic import Field+from nanobot.bus.delivery import DeliveryRejectedErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel@@ -356,8 +357,7 @@ class MochatChannel(BaseChannel):):returnif not self.config.claw_token:- self.logger.warning("claw_token missing, skip send")- return+ raise DeliveryRejectedError("MoChat claw_token missing")parts = ([msg.content.strip()] if msg.content and msg.content.strip() else [])if msg.media:@@ -372,8 +372,7 @@ class MochatChannel(BaseChannel):target = resolve_mochat_target(msg.chat_id)if not target.id:- self.logger.warning("outbound target is empty")- return+ raise DeliveryRejectedError("MoChat outbound target is empty")is_panel = (target.is_panel or target.id in self._panel_set) and not target.id.startswith("session_")try:diff --git a/nanobot/channels/msteams/runtime.py b/nanobot/channels/msteams/runtime.pyindex ae8a06828..c6be29696 100644--- a/nanobot/channels/msteams/runtime.py+++ b/nanobot/channels/msteams/runtime.py@@ -35,6 +35,7 @@ except ImportError: # pragma: no coverimport httpxfrom pydantic import Field+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel@@ -256,7 +257,7 @@ class MSTeamsChannel(BaseChannel):):returnif not self._http:- raise RuntimeError("MSTeams HTTP client not initialized")+ raise ChannelNotReadyError("MSTeams HTTP client not initialized")ref = self._conversation_refs.get(str(msg.chat_id))if not ref:diff --git a/nanobot/channels/napcat/runtime.py b/nanobot/channels/napcat/runtime.pyindex 3a57f190b..515d9d870 100644--- a/nanobot/channels/napcat/runtime.py+++ b/nanobot/channels/napcat/runtime.py@@ -19,6 +19,7 @@ from pydantic import Fieldfrom websockets.asyncio.client import ClientConnectionfrom websockets.asyncio.client import connect as ws_connect+from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel@@ -443,12 +444,11 @@ class NapcatChannel(BaseChannel):):returnif self._ws is None:- raise RuntimeError("napcat: not connected")+ raise ChannelNotReadyError("napcat: not connected")kind, _, target = msg.chat_id.partition(":")if kind not in ("private", "group") or not target:- logger.error("napcat: invalid chat_id '{}'", msg.chat_id)- return+ raise DeliveryRejectedError("napcat: invalid chat_id")segments: list[dict[str, Any]] = []for ref in msg.media or []:diff --git a/nanobot/channels/outbox.py b/nanobot/channels/outbox.pynew file mode 100644index 000000000..2a6b0aef5--- /dev/null+++ b/nanobot/channels/outbox.py@@ -0,0 +1,149 @@+"""Bounded storage for scheduled results; never reruns an agent turn."""++from __future__ import annotations++import json+import os+import sqlite3+import time+import uuid+from collections.abc import Generator+from contextlib import contextmanager+from dataclasses import asdict+from pathlib import Path+from typing import Literal++from loguru import logger++from nanobot.bus.delivery import DeliveryRequest+from nanobot.bus.events import OutboundMessage++DeliveryStatus = Literal["pending", "sending", "sent", "failed", "unknown"]+RETRY_SECONDS = 30+MAX_AGE_SECONDS = 3600+MAX_PENDING = 256+MAX_PAYLOAD_BYTES = 1024 * 1024+RETENTION_SECONDS = 7 * 86400+++class DeliveryOutbox:+ """One gateway lease owns this instance store. Terminal rows contain no message text."""++ def __init__(self, path: Path) -> None:+ self.path = path+ self._initialized = False++ @contextmanager+ def _connect(self) -> Generator[sqlite3.Connection, None, None]:+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o600)+ os.close(fd)+ db = sqlite3.connect(self.path)+ db.execute("PRAGMA secure_delete=ON")+ db.row_factory = sqlite3.Row+ try:+ with db:+ if not self._initialized:+ db.execute("""CREATE TABLE IF NOT EXISTS deliveries (+ id TEXT PRIMARY KEY, run_id TEXT NOT NULL, channel TEXT NOT NULL,+ chat_id TEXT NOT NULL,+ payload TEXT, status TEXT NOT NULL, created REAL NOT NULL,+ updated REAL NOT NULL, next_attempt REAL NOT NULL, error TEXT+ )""")+ # A crash during send cannot tell us whether the service accepted it.+ interrupted = db.execute("SELECT id, run_id, channel FROM deliveries WHERE status='sending'").fetchall()+ db.execute("""UPDATE deliveries SET status='unknown', payload=NULL,+ error='interrupted_send', updated=? WHERE status='sending'""", (time.time(),))+ for row in interrupted:+ logger.warning("Channel delivery: run={} delivery={} channel={} status=unknown error=interrupted_send",+ row["run_id"], row["id"], row["channel"])+ yield db+ self._initialized = True+ finally:+ db.close()++ def record(self, msg: OutboundMessage) -> None:+ """Commit before queue acceptance. Do not store runtime events or empty replies."""+ if msg.delivery is None or msg.event is not None or not (msg.content.strip() or msg.media):+ return+ if msg.delivery_id is not None:+ return+ delivery_id = uuid.uuid4().hex+ data = asdict(msg)+ data["delivery_id"] = delivery_id+ # Cron prompt audit data is already in the run record, not routing context.+ data["metadata"] = {key: value for key, value in msg.metadata.items()+ if not key.startswith("_cron_")}+ payload = json.dumps(data, ensure_ascii=False)+ if len(payload.encode("utf-8")) > MAX_PAYLOAD_BYTES:+ raise ValueError("Scheduled delivery exceeds the 1 MiB queue limit")+ now = time.time()+ with self._connect() as db:+ self._prune(db, now)+ count = db.execute(+ "SELECT count(*) FROM deliveries WHERE status IN ('pending','sending')",+ ).fetchone()[0]+ if count >= MAX_PENDING:+ raise RuntimeError("Scheduled delivery queue is full; check channel connectivity")+ db.execute("INSERT INTO deliveries VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?, NULL)",+ (delivery_id, msg.delivery.run_id, msg.channel, msg.chat_id, payload, now, now, now))+ msg.delivery_id = delivery_id+ self._log(msg, "pending")++ @staticmethod+ def _prune(db: sqlite3.Connection, now: float) -> None:+ expired = db.execute("""UPDATE deliveries SET status='failed', payload=NULL,+ error='expired', updated=? WHERE status='pending' AND created<=?""",+ (now, now - MAX_AGE_SECONDS)).rowcount+ if expired:+ logger.warning("{} scheduled deliveries expired; check the instance delivery store", expired)+ db.execute("DELETE FROM deliveries WHERE status NOT IN ('pending','sending') AND updated<?",+ (now - RETENTION_SECONDS,))+ db.execute("""DELETE FROM deliveries WHERE id IN (+ SELECT id FROM deliveries WHERE status NOT IN ('pending','sending')+ ORDER BY updated DESC LIMIT -1 OFFSET 1000)""")++ def ready(self) -> list[OutboundMessage]:+ if not self.path.exists():+ return []+ now = time.time()+ with self._connect() as db:+ self._prune(db, now)+ rows = db.execute("""SELECT payload FROM deliveries WHERE status='pending'+ AND next_attempt<=? ORDER BY created LIMIT ?""", (now, MAX_PENDING)).fetchall()+ messages: list[OutboundMessage] = []+ for row in rows:+ data = json.loads(row["payload"])+ data["delivery"] = DeliveryRequest(**data["delivery"])+ messages.append(OutboundMessage(**data))+ return messages++ def claim(self, msg: OutboundMessage) -> bool:+ """Only one queued copy may start an attempt; expired messages never start."""+ now = time.time()+ with self._connect() as db:+ self._prune(db, now)+ changed = db.execute("""UPDATE deliveries SET status='sending', updated=?+ WHERE id=? AND status='pending' AND next_attempt<=?+ AND NOT EXISTS (SELECT 1 FROM deliveries AS older+ WHERE older.channel=deliveries.channel AND older.chat_id=deliveries.chat_id+ AND older.rowid<deliveries.rowid AND older.status IN ('pending','sending'))""",+ (now, msg.delivery_id, now)).rowcount+ return changed == 1++ def finish(self, msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:+ now = time.time()+ with self._connect() as db:+ changed = db.execute("""UPDATE deliveries SET status=?, error=?, updated=?, next_attempt=?,+ payload=CASE WHEN ?='pending' THEN payload ELSE NULL END+ WHERE id=? AND status IN ('pending','sending')""",+ (status, error, now, now + RETRY_SECONDS, status, msg.delivery_id)).rowcount+ self._prune(db, now)+ if changed:+ self._log(msg, status, error)++ @staticmethod+ def _log(msg: OutboundMessage, status: DeliveryStatus, error: str | None = None) -> None:+ logger.info("Channel delivery: run={} delivery={} channel={} status={} error={}",+ msg.delivery.run_id if msg.delivery else "-", msg.delivery_id,+ msg.channel, status, error or "-")diff --git a/nanobot/channels/qq/runtime.py b/nanobot/channels/qq/runtime.pyindex a144ef0b2..8b809c385 100644--- a/nanobot/channels/qq/runtime.py+++ b/nanobot/channels/qq/runtime.py@@ -37,6 +37,7 @@ import aiohttpfrom loguru import loggerfrom pydantic import Field+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEventfrom nanobot.bus.queue import MessageBus@@ -437,7 +438,7 @@ class QQChannel(BaseChannel):try:if not self._client:- raise RuntimeError("QQ client not initialized")+ raise ChannelNotReadyError("QQ client not initialized")msg_id = msg.metadata.get("message_id")chat_type = self._chat_type_cache.get(msg.chat_id, "c2c")diff --git a/nanobot/channels/signal/runtime.py b/nanobot/channels/signal/runtime.pyindex c05d51ee9..fd9243e05 100644--- a/nanobot/channels/signal/runtime.py+++ b/nanobot/channels/signal/runtime.py@@ -17,6 +17,7 @@ from typing import Any, TypedDict, castimport httpxfrom pydantic import Field, computed_field, field_validator+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -571,6 +572,8 @@ class SignalChannel(BaseChannel):msg.event.notify or self.show_compaction_notices):return+ if not self._http:+ raise ChannelNotReadyError("Signal client not connected")is_progress_message = isinstance(msg.event, ProgressEvent)try:plain_text, text_styles = _markdown_to_signal(msg.content)diff --git a/nanobot/channels/slack/runtime.py b/nanobot/channels/slack/runtime.pyindex e14e5d7a5..13f393005 100644--- a/nanobot/channels/slack/runtime.py+++ b/nanobot/channels/slack/runtime.py@@ -14,6 +14,7 @@ from slack_sdk.socket_mode.response import SocketModeResponsefrom slack_sdk.web.async_client import AsyncWebClientfrom slackify_markdown import slackify_markdown # pyright: ignore[reportMissingTypeStubs]+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -208,8 +209,7 @@ class SlackChannel(BaseChannel):):returnif not self._web_client:- self.logger.warning("client not running")- return+ raise ChannelNotReadyError("Slack client not running")try:web_api = self._require_web_api()target_chat_id = await self._resolve_target_chat_id(msg.chat_id)diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.pyindex 22dd9462b..de82cfb13 100644--- a/nanobot/channels/telegram/runtime.py+++ b/nanobot/channels/telegram/runtime.py@@ -29,6 +29,7 @@ from telegram.error import BadRequest, InvalidToken, NetworkError, RetryAfter, Tfrom telegram.ext import Application, CallbackQueryHandler, ContextTypes, MessageHandler, filtersfrom telegram.request import BaseRequest, HTTPXRequest+from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -801,7 +802,7 @@ class TelegramChannel(BaseChannel):with suppress(asyncio.TimeoutError):await asyncio.wait_for(self._app_ready.wait(), APP_RESTART_SEND_WAIT_SECONDS)if not self._app_ready.is_set() or self._app is None:- raise RuntimeError("Telegram application is restarting; message not delivered")+ raise ChannelNotReadyError("Telegram application is restarting; message not delivered")return self._appdef _note_poll_ok(self) -> None:@@ -1074,8 +1075,7 @@ class TelegramChannel(BaseChannel):returnapp = await self._wait_for_app()if app is None:- self.logger.warning("bot not running")- return+ raise ChannelNotReadyError("Telegram bot not running")progress_event = msg.event if isinstance(msg.event, ProgressEvent) else None@@ -1089,8 +1089,7 @@ class TelegramChannel(BaseChannel):try:chat_id = int(msg.chat_id)except ValueError:- self.logger.exception("Invalid chat_id: {}", msg.chat_id)- return+ raise DeliveryRejectedError("Invalid Telegram chat_id") from Nonereply_to_message_id = msg.metadata.get("message_id")message_thread_id = msg.metadata.get("message_thread_id")if message_thread_id is None and reply_to_message_id is not None:diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.pyindex 6d99cba27..13b17d8c2 100644--- a/nanobot/channels/telegram/tests/test_telegram_channel.py+++ b/nanobot/channels/telegram/tests/test_telegram_channel.py@@ -12,6 +12,7 @@ try:except ImportError:pytest.skip("Telegram dependencies not installed (python-telegram-bot)", allow_module_level=True)+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -621,14 +622,15 @@ async def test_send_during_rebuild_fails_instead_of_dropping(monkeypatch) -> Nonchannel._app = Nonemsg = OutboundMessage(channel="telegram", chat_id="123", content="hello")- with pytest.raises(RuntimeError, match="restarting"):+ with pytest.raises(ChannelNotReadyError, match="restarting"):await channel.send(msg)with pytest.raises(RuntimeError, match="restarting"):await channel.send_delta("123", "hello", stream_id="s1")- # Stopped: nothing to deliver, so stay quiet.+ # A stopped channel must not report a final message as delivered.channel._running = False- await channel.send(msg)+ with pytest.raises(ChannelNotReadyError, match="not running"):+ await channel.send(msg)await channel.send_delta("123", "hello", stream_id="s1")diff --git a/nanobot/channels/wecom/runtime.py b/nanobot/channels/wecom/runtime.pyindex db5982af7..3fe3a8293 100644--- a/nanobot/channels/wecom/runtime.py+++ b/nanobot/channels/wecom/runtime.py@@ -12,6 +12,7 @@ from typing import Any, castfrom pydantic import Field+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -416,7 +417,7 @@ class WecomChannel(BaseChannel):):returnif not self._client:- raise RuntimeError("WeCom client not initialized")+ raise ChannelNotReadyError("WeCom client not initialized")try:content = (msg.content or "").strip()diff --git a/nanobot/channels/weixin/runtime.py b/nanobot/channels/weixin/runtime.pyindex e03939f1a..35d09f593 100644--- a/nanobot/channels/weixin/runtime.py+++ b/nanobot/channels/weixin/runtime.py@@ -31,6 +31,7 @@ from loguru import loggerfrom pydantic import Field, model_validatorfrom nanobot import __version__+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBus@@ -1871,7 +1872,7 @@ class WeixinChannel(BaseChannel):):returnif not self._client or not self._token:- raise RuntimeError("WeChat client not initialized or not authenticated")+ raise ChannelNotReadyError("WeChat client not initialized or not authenticated")self._assert_session_active()delivery_id = self._delivery_id(msg)@@ -2081,7 +2082,13 @@ class WeixinChannel(BaseChannel):)delivery_state.completed_parts.add(text_part)completed = True- except WeixinQuotaError:+ except WeixinQuotaError as error:+ if msg.delivery_id is not None:+ # The durable outbox owns scheduled results. Do not also retain+ # one in the channel's independently replayed, volatile queue.+ if not delivery_state.completed_parts:+ raise ChannelNotReadyError("WeChat needs a fresh inbound context") from error+ raiseif not is_progress:self._defer_outbound(msg)self.logger.warning(diff --git a/nanobot/channels/weixin/tests/test_weixin_channel.py b/nanobot/channels/weixin/tests/test_weixin_channel.pyindex 2acd14b91..85f26a815 100644--- a/nanobot/channels/weixin/tests/test_weixin_channel.py+++ b/nanobot/channels/weixin/tests/test_weixin_channel.py@@ -9,6 +9,7 @@ from unittest.mock import AsyncMockimport httpximport pytest+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.weixin import runtime as weixin_mod@@ -546,9 +547,7 @@ async def test_send_without_context_token_raises() -> None:channel._send_text = AsyncMock()with pytest.raises(RuntimeError, match="context_token missing"):- await channel.send(- type("Msg", (), {"chat_id": "unknown-user", "content": "pong", "media": [], "metadata": {}})()- )+ await channel.send(_make_outbound_msg(chat_id="unknown-user", content="pong"))channel._send_text.assert_not_awaited()@@ -1482,6 +1481,26 @@ def _make_outbound_msg(chat_id: str = "wx-user", content: str = "", media: list)[email protected]("partial", [False, True])+async def test_scheduled_quota_failure_has_only_one_recovery_owner(partial):+ channel, _bus = _make_channel()+ channel._client = object()+ channel._token = "token"+ channel._refresh_context_token_if_stale = AsyncMock(return_value="context")+ channel._get_typing_ticket = AsyncMock(return_value="")+ channel._send_media_part = AsyncMock()+ channel._send_text = AsyncMock(side_effect=weixin_mod.WeixinQuotaError("sendmessage"))+ msg = _make_outbound_msg(content="result", media=["image.png"] if partial else [])+ msg.delivery_id = "scheduled-result"++ expected = weixin_mod.WeixinQuotaError if partial else ChannelNotReadyError+ with pytest.raises(expected):+ await channel.send(msg)++ assert channel._deferred_outbound == {}+ assert channel._send_media_part.await_count == int(partial)++@pytest.mark.asyncioasync def test_send_media_timeout_error_propagates_without_text_fallback() -> None:"""httpx.TimeoutException during media send must re-raise immediately,diff --git a/nanobot/channels/whatsapp/runtime.py b/nanobot/channels/whatsapp/runtime.pyindex b8f2bc46c..71df1e5b5 100644--- a/nanobot/channels/whatsapp/runtime.py+++ b/nanobot/channels/whatsapp/runtime.py@@ -18,6 +18,7 @@ from urllib.parse import urlparseimport httpxfrom pydantic import Field+from nanobot.bus.delivery import ChannelNotReadyErrorfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel@@ -466,7 +467,7 @@ class WhatsAppChannel(BaseChannel):returnclient = self._clientif client is None or not self._connected:- raise RuntimeError("WhatsApp channel is not connected")+ raise ChannelNotReadyError("WhatsApp channel is not connected")to = self._build_jid(msg.chat_id)if msg.content:diff --git a/nanobot/cron/bound_runner.py b/nanobot/cron/bound_runner.pyindex d3b65dee0..3f10053cf 100644--- a/nanobot/cron/bound_runner.py+++ b/nanobot/cron/bound_runner.py@@ -8,6 +8,7 @@ import timeimport uuidfrom typing import Any, Protocol+from nanobot.bus.delivery import DELIVERY_RUN_METAfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.cron.session_delivery import origin_delivery_contextfrom nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META@@ -52,6 +53,10 @@ def _bound_session_delivery_context(source_label=source_label,))+ else:+ # External scheduled results need one recoverable final message, not a+ # transient stream whose completion marker cannot be replayed safely.+ metadata.pop("_wants_stream", None)return channel, chat_id, metadata@@ -89,6 +94,7 @@ async def run_bound_cron_job(),}metadata[CRON_DEFER_UNTIL_IDLE_META] = True+ metadata[DELIVERY_RUN_META] = run_idrun_record_base: dict[str, Any] = {"job_id": job.id,"job_name": job.name,diff --git a/tests/channels/test_scheduled_delivery.py b/tests/channels/test_scheduled_delivery.pynew file mode 100644index 000000000..083d07740--- /dev/null+++ b/tests/channels/test_scheduled_delivery.py@@ -0,0 +1,338 @@+"""Exercise scheduled delivery through the real gateway pipeline, without external sends."""++import asyncio+import json+import os+import sqlite3+from functools import partial+from unittest.mock import AsyncMock, MagicMock++import pytest++from nanobot.agent.loop import AgentLoop+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.bus.delivery import (+ DELIVERY_RUN_META,+ ChannelNotReadyError,+ DeliveryRejectedError,+ DeliveryRequest,+)+from nanobot.bus.events import OutboundMessage+from nanobot.bus.outbound_events import ProgressEvent+from nanobot.bus.queue import MessageBus+from nanobot.channels import outbox as outbox_module+from nanobot.channels.base import BaseChannel+from nanobot.channels.manager import ChannelManager+from nanobot.channels.outbox import DeliveryOutbox+from nanobot.channels.registry import load_channel_plugin+from nanobot.channels.whatsapp.runtime import WhatsAppChannel+from nanobot.config.schema import Config+from nanobot.cron.bound_runner import run_bound_cron_job+from nanobot.cron.service import CronService+from nanobot.cron.types import CronSchedule+from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest+from nanobot.session.manager import SessionManager+++def rows(outbox):+ with sqlite3.connect(outbox.path) as db:+ db.row_factory = sqlite3.Row+ return [dict(row) for row in db.execute("SELECT * FROM deliveries ORDER BY created")]+++def make_manager(tmp_path, sessions=None):+ config = Config.model_validate({"channels": {+ "websocket": {"enabled": False}, "sendProgress": False, "sendToolHints": False,+ }})+ bus = MessageBus()+ manager = ChannelManager(config, bus, config_path=tmp_path / "config.json", session_manager=sessions)+ return manager+++def message(channel="whatsapp", content="result", generation=None):+ return OutboundMessage(channel, "synthetic", content,+ delivery=DeliveryRequest("run-1", "whatsapp:synthetic", generation))+++async def drain(manager):+ async with asyncio.timeout(5):+ while manager.bus.outbound_size or manager._outbound_tasks:+ await asyncio.sleep(0.01)++[email protected]("legacy_message,one_shot,origin", [+ (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)+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")+ manager = make_manager(tmp_path, sessions)+ bus = manager.bus+ cron = CronService(tmp_path / "cron" / "jobs.json")+ provider = MagicMock(aclose=AsyncMock())+ provider.get_default_model.return_value = "offline-test-model"+ provider.generation = GenerationSettings(max_tokens=100)+ provider.can_resume_conversation_state.return_value = False+ provider.estimate_prompt_tokens.return_value = (100, "test")+ calls = []++ async def reply(**kwargs):+ calls.append(kwargs)+ 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(+ id="send", name="message", arguments=arguments,+ )], finish_reason="tool_calls")+ return LLMResponse(content="Diagnostic result")++ provider.chat_stream_with_retry = reply+ agent = AgentLoop(bus=bus, provider=provider, workspace=workspace,+ model="offline-test-model", session_manager=sessions,+ tools_config=manager.config.tools, cron_service=cron)+ cron.on_job = partial(run_bound_cron_job, agent=agent, cron=cron)+ channel = WhatsAppChannel({}, bus)+ channel.send_progress = False+ channel.send_tool_hints = False+ channel._client = MagicMock(send_message=AsyncMock())+ channel._connected = False+ monkeypatch.setattr(channel, "_build_jid", lambda value: value)+ monkeypatch.setattr(channel, "stop", AsyncMock())+ 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())+ # 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)+ if origin == "websocket":+ # A WebUI-created task remains in its source chat even when its instructions+ # explicitly request a separate send. Recovery must keep that send's target.+ 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:+ assert await asyncio.wait_for(cron.run_job(job.id), 15)+ await drain(manager)+ if one_shot:+ assert cron.list_jobs() == []+ else:+ assert cron.list_jobs()[0].state.last_status == "ok"+ assert len(whatsapp_rows()) == 1+ 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()+ count = len(calls)+ assert count == (2 if legacy_message else 1)+ assert DELIVERY_RUN_META not in json.dumps(calls[0]["messages"])+ assert "Diagnostic result" not in calls[0]["messages"][0]["content"]+ await manager.stop_all()+ # A second gateway uses the saved result; no timer, agent, or model is restarted.+ manager = make_manager(tmp_path, sessions)+ manager.channels["whatsapp"] = channel+ channel._connected = True+ await manager._recover_scheduled()+ await drain(manager)+ channel._client.send_message.assert_awaited_once_with("synthetic", "Diagnostic result")+ assert whatsapp_rows()[0]["status"] == "sent"+ assert whatsapp_rows()[0]["payload"] is None+ again = make_manager(tmp_path, sessions)+ again.channels["whatsapp"] = channel+ await again._recover_scheduled()+ assert channel._client.send_message.await_count == 1+ assert len(calls) == count+ # Existing jobs still load after delivery state is added beside them.+ old_jobs = CronService(cron.store_path).list_jobs()+ assert old_jobs == [] if one_shot else old_jobs[0].payload.message == job.payload.message+ finally:+ await manager.stop_all()+ cron.stop()+ await agent.aclose()++[email protected]("failure", [TimeoutError("response lost"), asyncio.CancelledError()])+async def test_uncertain_attempt_is_not_replayed(tmp_path, failure):+ manager = make_manager(tmp_path)+ channel = MagicMock(spec=BaseChannel)+ channel.send = AsyncMock(side_effect=failure)+ msg = message()+ await manager.bus.publish_outbound(msg)+ if isinstance(failure, asyncio.CancelledError):+ with pytest.raises(asyncio.CancelledError):+ await manager._send_scheduled(channel, msg)+ else:+ await manager._send_scheduled(channel, msg)+ assert rows(manager._outbox)[0]["status"] == "unknown"+ assert DeliveryOutbox(manager._outbox.path).ready() == []+ channel.send.assert_awaited_once()+++async def test_legacy_broadcast_has_independent_targets_and_no_foreign_thread_metadata(tmp_path, monkeypatch):+ monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)+ manager = make_manager(tmp_path)+ tool = MessageTool(send_callback=manager.bus.publish_outbound, workspace=tmp_path)+ with request_context(RequestContext(+ "telegram", "source", session_key="telegram:source", metadata={+ DELIVERY_RUN_META: "run-1", "message_thread_id": 42, "message_id": "parent",+ },+ )):+ for channel in ("slack", "whatsapp"):+ assert str(await tool.execute(content="result", channel=channel, chat_id="target")).startswith("Message queued")+ messages = [manager.bus.outbound.get_nowait() for _ in range(2)]+ assert all(msg.metadata == {} for msg in messages)+ assert len({msg.delivery_id for msg in messages}) == 2+ healthy = MagicMock(spec=BaseChannel, send=AsyncMock())+ offline = MagicMock(spec=BaseChannel, send=AsyncMock(side_effect=ChannelNotReadyError()))+ await manager._send_scheduled(healthy, messages[0])+ await manager._send_scheduled(offline, messages[1])+ assert [row["status"] for row in rows(manager._outbox)] == ["sent", "pending"]+ assert [msg.channel for msg in manager._outbox.ready()] == ["whatsapp"]+++async def test_queue_acceptance_survives_restart_but_inflight_is_unknown(tmp_path):+ manager = make_manager(tmp_path)+ pending, inflight = message(), message(content="second")+ inflight.chat_id = "other-destination"+ await manager.bus.publish_outbound(pending)+ await manager.bus.publish_outbound(inflight)+ assert manager._outbox.claim(inflight)+ restarted = DeliveryOutbox(manager._outbox.path)+ assert [msg.delivery_id for msg in restarted.ready()] == [pending.delivery_id]+ assert [row["status"] for row in rows(restarted)] == ["pending", "unknown"]+++async def test_queue_bounds_expiry_and_untracked_events(tmp_path, monkeypatch):+ manager = make_manager(tmp_path)+ monkeypatch.setattr(outbox_module, "MAX_PENDING", 1)+ event = message()+ event.event = ProgressEvent(tool_hint=True)+ await manager.bus.publish_outbound(event)+ await manager.bus.publish_outbound(OutboundMessage("slack", "synthetic", "ordinary reply"))+ assert not manager._outbox.path.exists()+ first = message()+ await manager.bus.publish_outbound(first)+ with pytest.raises(RuntimeError, match="queue is full"):+ await manager.bus.publish_outbound(message(content="second"))+ with pytest.raises(ValueError, match="1 MiB"):+ await manager.bus.publish_outbound(message(content="a" * (1024 * 1024)))+ monkeypatch.setattr(outbox_module, "MAX_AGE_SECONDS", 0)+ assert manager._outbox.ready() == []+ assert rows(manager._outbox)[0]["error"] == "expired"+ assert not manager._outbox.claim(first)+ if os.name != "nt":+ assert manager._outbox.path.stat().st_mode & 0o777 == 0o600++[email protected]("operation", ["delete", "reset"])+async def test_pending_result_cannot_send_after_source_session_is_replaced(tmp_path, operation):+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")+ session = await sessions.state.get("whatsapp:synthetic")+ manager = make_manager(tmp_path, sessions)+ channel = MagicMock(spec=BaseChannel, send=AsyncMock())+ msg = message(generation=session.generation)+ try:+ await manager.bus.publish_outbound(msg)+ await getattr(sessions.state, operation)(session.key)+ await manager._send_scheduled(channel, msg)+ channel.send.assert_not_called()+ assert rows(manager._outbox)[0]["error"] == "session_replaced"+ finally:+ await sessions.state.aclose()+++async def test_recovery_keeps_destination_order_and_does_not_block_other_chats(tmp_path, monkeypatch):+ monkeypatch.setattr(outbox_module, "RETRY_SECONDS", 0)+ manager = make_manager(tmp_path)+ first, second, other = message(content="first"), message(content="second"), message(content="other")+ other.chat_id = "another-chat"+ for msg in (first, second, other):+ await manager.bus.publish_outbound(msg)+ await manager.bus.consume_outbound()+ channel = MagicMock(spec=BaseChannel, send=AsyncMock(side_effect=ChannelNotReadyError()))+ await manager._send_scheduled(channel, first)+ channel.send.side_effect = None+ await manager._send_scheduled(channel, second)+ await manager._send_scheduled(channel, other)+ assert [call.args[0].content for call in channel.send.await_args_list] == ["first", "other"]+ manager.channels["whatsapp"] = channel+ await manager._recover_scheduled()+ await drain(manager)+ assert [call.args[0].content for call in channel.send.await_args_list] == ["first", "other", "first", "second"]+ # A stale queued copy must not downgrade the durable successful result.+ manager._outbox.finish(first, "failed", "channel_disabled")+ assert all(row["status"] == "sent" for row in rows(manager._outbox))+++async def test_relocated_instance_finds_queue_and_disabled_channel_does_not_send(tmp_path):+ original = tmp_path / "original"+ manager = make_manager(original)+ await manager.bus.publish_outbound(message())+ moved = tmp_path / "moved"+ original.rename(moved)+ restarted = make_manager(moved)+ await restarted._recover_scheduled()+ assert rows(restarted._outbox)[0]["error"] == "channel_disabled"+ assert not original.exists()+++async def test_recovery_rechecks_attachment_workspace_boundary(tmp_path):+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions")+ session = await sessions.state.get("whatsapp:synthetic")+ manager = make_manager(tmp_path, sessions)+ manager.config.agents.defaults.workspace = str(workspace)+ manager.config.tools.restrict_to_workspace = True+ attachment = workspace / "report.txt"+ attachment.write_text("report")+ msg = message(generation=session.generation)+ msg.media = [str(attachment)]+ channel = MagicMock(spec=BaseChannel, send=AsyncMock())+ try:+ await manager.bus.publish_outbound(msg)+ attachment.unlink()+ private = tmp_path / "private.txt"+ private.write_text("not authorized")+ attachment.symlink_to(private)+ await manager._send_scheduled(channel, msg)+ channel.send.assert_not_called()+ assert rows(manager._outbox)[0]["error"] == "attachment_access_denied"+ finally:+ await sessions.state.aclose()++[email protected]("name", [+ "whatsapp", "telegram", "discord", "slack", "matrix", "mattermost", "feishu",+ "qq", "wecom", "weixin", "napcat", "msteams", "linear", "signal", "dingtalk",+ "mochat", "email",+])+async def test_unavailable_adapter_does_not_report_success(name, monkeypatch):+ cls = load_channel_plugin(name).load_channel_class()+ channel = cls(cls.default_config(), MessageBus())+ if name == "dingtalk":+ monkeypatch.setattr(channel, "_get_access_token", AsyncMock(return_value=None))+ with pytest.raises((ChannelNotReadyError, DeliveryRejectedError)):+ await channel.send(OutboundMessage(name, "synthetic", "result"))