test(cron): narrow delivery review to saved-chat routing
This commit is contained in:
1 parent
8691bdedd5
commit
61db036cee
32 files changed
+140
-774
No files matched your search
+10
-45
@@ -46,52 +46,17 @@ 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.
|
||||
|
||||
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.
|
||||
Writing "send to WhatsApp" in the instructions does not change the task's saved chat. Its normal
|
||||
reply still returns to that chat. A separate send requires the agent to call `message` with the
|
||||
other destination.
|
||||
For a fixed destination, create the task in that chat or use
|
||||
[Change the Chat for a Scheduled Task](#change-the-chat-for-a-scheduled-task). Keep explicit
|
||||
`message` instructions when you want separate sends or several recipients.
|
||||
|
||||
### Scheduled Result Delivery
|
||||
|
||||
Task completion and message delivery are separate. `Turn completed` and a successful task run
|
||||
mean that execution finished. They do not confirm that a chat service received the result.
|
||||
|
||||
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.
|
||||
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
|
||||
streaming is unchanged.
|
||||
|
||||
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 a task's chat affects
|
||||
future runs; it does not redirect 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; pending delivery resumes only when a version with queue support runs again.
|
||||
If a result does not arrive, check the saved chat and the run's `message` calls first. Then check
|
||||
the gateway's channel send errors. `Turn completed` confirms execution finished, not that the
|
||||
destination received a message. A successful `message` tool return confirms queue acceptance,
|
||||
not receipt by the chat service. Do not resend until you check whether the first send arrived.
|
||||
|
||||
For background checks that should stay quiet unless there is something useful to report, use heartbeat instead of a user-created scheduled automation.
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import ToolContext, current_request_context
|
||||
from nanobot.agent.tools.path_utils import resolve_workspace_path
|
||||
from nanobot.agent.tools.schema import ArraySchema, StringSchema, tool_parameters_schema
|
||||
from nanobot.bus.delivery import DeliveryRequest
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.config.paths import get_workspace_path
|
||||
from nanobot.security.workspace_access import current_tool_workspace
|
||||
@@ -237,9 +236,6 @@ 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():
|
||||
@@ -257,7 +253,6 @@ class MessageTool(Tool):
|
||||
if button_rows
|
||||
else ""
|
||||
)
|
||||
action = "queued" if msg.delivery is not None else "sent"
|
||||
return f"Message {action} to {channel}:{chat_id}{media_info}{button_info}"
|
||||
return f"Message sent to {channel}:{chat_id}{media_info}{button_info}"
|
||||
except Exception as e:
|
||||
return ToolResult.error(f"Error sending message: {str(e)}")
|
||||
@@ -9,7 +9,6 @@ from copy import deepcopy
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from nanobot.bus.delivery import DeliveryRequest
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.notification_delivery import notification_is_deliverable
|
||||
from nanobot.bus.outbound_events import (
|
||||
@@ -342,12 +341,6 @@ 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(
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
"""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)
|
||||
@@ -4,8 +4,6 @@ from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
from nanobot.bus.delivery import DeliveryRequest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.events import AgentEvent
|
||||
|
||||
@@ -70,5 +68,3 @@ 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 = None
|
||||
@@ -33,7 +33,6 @@ 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 = None
|
||||
|
||||
async def publish_inbound(self, msg: InboundMessage) -> None:
|
||||
"""Publish a message from a channel to the agent."""
|
||||
@@ -45,8 +44,6 @@ 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(
|
||||
|
||||
@@ -100,10 +100,6 @@ class BaseChannel(ABC):
|
||||
|
||||
Implementations should raise on delivery failure so the channel manager
|
||||
can 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.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ from urllib.parse import unquote, urljoin, urlparse
|
||||
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
|
||||
@@ -743,7 +742,7 @@ class DingTalkChannel(BaseChannel):
|
||||
return
|
||||
token = await self._get_access_token()
|
||||
if not token:
|
||||
raise ChannelNotReadyError("DingTalk access token unavailable")
|
||||
raise RuntimeError("DingTalk access token unavailable")
|
||||
|
||||
content = msg.content.strip() if msg.content else ""
|
||||
if content:
|
||||
|
||||
@@ -13,7 +13,6 @@ from typing import TYPE_CHECKING, Any, Literal, cast
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -540,7 +539,7 @@ class DiscordChannel(BaseChannel):
|
||||
"""Send a message through Discord using discord.py."""
|
||||
client = self._client
|
||||
if client is None or not client.is_ready():
|
||||
raise ChannelNotReadyError("Discord client is not ready")
|
||||
raise RuntimeError("Discord client is not ready")
|
||||
|
||||
is_progress = isinstance(msg.event, ProgressEvent)
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ from typing import Any, Literal, cast
|
||||
from loguru import logger
|
||||
from pydantic import Field, field_validator
|
||||
|
||||
from nanobot.bus.delivery import DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -246,10 +245,12 @@ class EmailChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self.config.consent_granted:
|
||||
raise DeliveryRejectedError("Email consent_granted is false")
|
||||
self.logger.warning("Skip email send: consent_granted is false")
|
||||
return
|
||||
|
||||
if not self.config.smtp_host:
|
||||
raise DeliveryRejectedError("SMTP host not configured")
|
||||
self.logger.warning("SMTP host not configured")
|
||||
return
|
||||
|
||||
# Skip progress messages to prevent sending an empty email after each tool call
|
||||
if isinstance(msg.event, ProgressEvent):
|
||||
@@ -258,7 +259,8 @@ class EmailChannel(BaseChannel):
|
||||
|
||||
to_addr = msg.chat_id.strip()
|
||||
if not to_addr:
|
||||
raise DeliveryRejectedError("Missing email recipient address")
|
||||
self.logger.warning("Missing recipient address")
|
||||
return
|
||||
|
||||
# Determine if this is a reply (recipient has sent us an email before)
|
||||
is_reply = to_addr in self._last_subject_by_chat
|
||||
@@ -266,7 +268,8 @@ class EmailChannel(BaseChannel):
|
||||
|
||||
# autoReplyEnabled only controls automatic replies, not proactive sends
|
||||
if is_reply and not self.config.auto_reply_enabled and not force_send:
|
||||
raise DeliveryRejectedError("Email auto_reply_enabled is false")
|
||||
self.logger.info("Skip automatic reply to {}: auto_reply_enabled is false", to_addr)
|
||||
return
|
||||
|
||||
base_subject = self._last_subject_by_chat.get(to_addr, "nanobot reply")
|
||||
subject = self._reply_subject(base_subject)
|
||||
|
||||
@@ -5,7 +5,6 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.delivery import DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -875,15 +874,14 @@ 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["alice@example.com"] = "Previous email"
|
||||
|
||||
# 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="alice@example.com",
|
||||
content="Should not send.",
|
||||
)
|
||||
# Reply should be skipped (auto_reply_enabled=False)
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="email",
|
||||
chat_id="alice@example.com",
|
||||
content="Should not send.",
|
||||
)
|
||||
)
|
||||
assert fake_instances == []
|
||||
|
||||
# Reply with force_send=True should be sent
|
||||
@@ -981,15 +979,14 @@ async def test_send_skips_when_consent_not_granted(monkeypatch) -> None:
|
||||
cfg = _make_config()
|
||||
cfg.consent_granted = False
|
||||
channel = EmailChannel(cfg, MessageBus())
|
||||
with pytest.raises(DeliveryRejectedError, match="consent_granted"):
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="email",
|
||||
chat_id="alice@example.com",
|
||||
content="Should not send.",
|
||||
metadata={"force_send": True},
|
||||
)
|
||||
await channel.send(
|
||||
OutboundMessage(
|
||||
channel="email",
|
||||
chat_id="alice@example.com",
|
||||
content="Should not send.",
|
||||
metadata={"force_send": True},
|
||||
)
|
||||
)
|
||||
assert called["smtp"] is False
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ from rich.markup import escape
|
||||
from rich.panel import Panel
|
||||
from rich.text import Text
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -2447,7 +2446,10 @@ class FeishuChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self._client:
|
||||
raise ChannelNotReadyError("Feishu client is not ready to send the reply")
|
||||
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
|
||||
|
||||
try:
|
||||
receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"
|
||||
|
||||
@@ -13,7 +13,6 @@ from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -168,8 +167,6 @@ class LinearChannel(BaseChannel):
|
||||
ephemeral=True,
|
||||
)
|
||||
return
|
||||
if self._client is None:
|
||||
raise ChannelNotReadyError("Linear HTTP client is not initialized")
|
||||
body = msg.content
|
||||
if msg.media:
|
||||
attachments = await self._attachment_markdown(msg)
|
||||
|
||||
@@ -5,7 +5,6 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import hashlib
|
||||
import inspect
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
||||
from contextlib import suppress
|
||||
@@ -14,7 +13,6 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ProgressEvent,
|
||||
@@ -34,11 +32,8 @@ from nanobot.channels.contracts import (
|
||||
channel_runtime_name,
|
||||
resolve_channel_action_target,
|
||||
)
|
||||
from nanobot.channels.outbox import RETRY_SECONDS, DeliveryOutbox
|
||||
from nanobot.channels.registry import channel_default_enabled
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.security.workspace_access import WorkspaceScopeResolver
|
||||
from nanobot.security.workspace_policy import resolve_allowed_path
|
||||
from nanobot.utils.restart import (
|
||||
RestartNotice,
|
||||
consume_restart_notice_from_env,
|
||||
@@ -159,9 +154,6 @@ class ChannelManager:
|
||||
self._stopping_channels: set[str] = set()
|
||||
self._started = False
|
||||
self._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.record
|
||||
|
||||
self._init_channels()
|
||||
|
||||
@@ -758,25 +750,18 @@ class ChannelManager:
|
||||
Retry waits occupy only their destination and one send slot. Saturation
|
||||
pauses dispatch rather than creating unbounded tasks or dropping messages.
|
||||
"""
|
||||
if msg.delivery_id in self._scheduled_deliveries:
|
||||
return
|
||||
await self._outbound_slots.acquire()
|
||||
if msg.channel in self._stopping_channels or self.channels.get(msg.channel) is not channel:
|
||||
self._outbound_slots.release()
|
||||
return
|
||||
key = (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:
|
||||
if msg.delivery_id is not None:
|
||||
await self._send_scheduled(channel, msg)
|
||||
else:
|
||||
await self._send_with_retry(channel, msg)
|
||||
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
|
||||
@@ -784,8 +769,6 @@ 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()
|
||||
@@ -794,58 +777,6 @@ 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()
|
||||
@@ -859,16 +790,9 @@ 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.0
|
||||
|
||||
while 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 queue
|
||||
if pending:
|
||||
msg = pending.pop(0)
|
||||
@@ -932,14 +856,12 @@ class ChannelManager:
|
||||
StreamDeltaEvent | StreamEndEvent | StreamedResponseEvent,
|
||||
)
|
||||
):
|
||||
if msg.delivery_id is None and self._should_suppress_outbound(msg):
|
||||
if self._should_suppress_outbound(msg):
|
||||
logger.info("Suppressing duplicate outbound message to {}:{}", msg.channel, msg.chat_id)
|
||||
continue
|
||||
await 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
|
||||
@@ -1121,7 +1043,7 @@ class ChannelManager:
|
||||
except asyncio.CancelledError:
|
||||
raise # Propagate cancellation for graceful shutdown
|
||||
except Exception as e:
|
||||
if isinstance(e, DeliveryRejectedError) or not channel.should_retry_send_error(e):
|
||||
if not channel.should_retry_send_error(e):
|
||||
logger.error(
|
||||
"Send to {} failed with a non-retryable {}: {}",
|
||||
msg.channel,
|
||||
|
||||
@@ -58,7 +58,6 @@ except ImportError as e:
|
||||
"Matrix dependencies not installed. Run: nanobot plugins enable matrix"
|
||||
) from e
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -622,7 +621,7 @@ class MatrixChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self.client:
|
||||
raise ChannelNotReadyError("Matrix client not initialized")
|
||||
raise RuntimeError("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)
|
||||
|
||||
@@ -11,7 +11,6 @@ from typing import Any, cast
|
||||
import httpx
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -500,7 +499,8 @@ class MattermostChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self._http_client:
|
||||
raise ChannelNotReadyError("Mattermost client not initialized")
|
||||
self.logger.warning("client not initialized")
|
||||
return
|
||||
|
||||
try:
|
||||
chat_id = msg.chat_id
|
||||
|
||||
@@ -15,7 +15,6 @@ from typing import Any, cast
|
||||
import httpx
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.bus.delivery import DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
@@ -357,7 +356,8 @@ class MochatChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self.config.claw_token:
|
||||
raise DeliveryRejectedError("MoChat claw_token missing")
|
||||
self.logger.warning("claw_token missing, skip send")
|
||||
return
|
||||
|
||||
parts = ([msg.content.strip()] if msg.content and msg.content.strip() else [])
|
||||
if msg.media:
|
||||
@@ -372,7 +372,8 @@ class MochatChannel(BaseChannel):
|
||||
|
||||
target = resolve_mochat_target(msg.chat_id)
|
||||
if not target.id:
|
||||
raise DeliveryRejectedError("MoChat outbound target is empty")
|
||||
self.logger.warning("outbound target is empty")
|
||||
return
|
||||
|
||||
is_panel = (target.is_panel or target.id in self._panel_set) and not target.id.startswith("session_")
|
||||
try:
|
||||
|
||||
@@ -35,7 +35,6 @@ except ImportError: # pragma: no cover
|
||||
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
|
||||
@@ -257,7 +256,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self._http:
|
||||
raise ChannelNotReadyError("MSTeams HTTP client not initialized")
|
||||
raise RuntimeError("MSTeams HTTP client not initialized")
|
||||
|
||||
ref = self._conversation_refs.get(str(msg.chat_id))
|
||||
if not ref:
|
||||
|
||||
@@ -19,7 +19,6 @@ from pydantic import Field
|
||||
from websockets.asyncio.client import ClientConnection
|
||||
from websockets.asyncio.client import connect as ws_connect
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
@@ -444,11 +443,12 @@ class NapcatChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if self._ws is None:
|
||||
raise ChannelNotReadyError("napcat: not connected")
|
||||
raise RuntimeError("napcat: not connected")
|
||||
|
||||
kind, _, target = msg.chat_id.partition(":")
|
||||
if kind not in ("private", "group") or not target:
|
||||
raise DeliveryRejectedError("napcat: invalid chat_id")
|
||||
logger.error("napcat: invalid chat_id '{}'", msg.chat_id)
|
||||
return
|
||||
|
||||
segments: list[dict[str, Any]] = []
|
||||
for ref in msg.media or []:
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
"""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 "-")
|
||||
@@ -37,7 +37,6 @@ import aiohttp
|
||||
from loguru import logger
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -438,7 +437,7 @@ class QQChannel(BaseChannel):
|
||||
|
||||
try:
|
||||
if not self._client:
|
||||
raise ChannelNotReadyError("QQ client not initialized")
|
||||
raise RuntimeError("QQ client not initialized")
|
||||
|
||||
msg_id = msg.metadata.get("message_id")
|
||||
chat_type = self._chat_type_cache.get(msg.chat_id, "c2c")
|
||||
|
||||
@@ -17,7 +17,6 @@ from typing import Any, TypedDict, cast
|
||||
import httpx
|
||||
from pydantic import Field, computed_field, field_validator
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -572,8 +571,6 @@ 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)
|
||||
|
||||
@@ -14,7 +14,6 @@ from slack_sdk.socket_mode.response import SocketModeResponse
|
||||
from slack_sdk.web.async_client import AsyncWebClient
|
||||
from slackify_markdown import slackify_markdown # pyright: ignore[reportMissingTypeStubs]
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -209,7 +208,8 @@ class SlackChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self._web_client:
|
||||
raise ChannelNotReadyError("Slack client not running")
|
||||
self.logger.warning("client not running")
|
||||
return
|
||||
try:
|
||||
web_api = self._require_web_api()
|
||||
target_chat_id = await self._resolve_target_chat_id(msg.chat_id)
|
||||
|
||||
@@ -29,7 +29,6 @@ from telegram.error import BadRequest, InvalidToken, NetworkError, RetryAfter, T
|
||||
from telegram.ext import Application, CallbackQueryHandler, ContextTypes, MessageHandler, filters
|
||||
from telegram.request import BaseRequest, HTTPXRequest
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError, DeliveryRejectedError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -802,7 +801,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 ChannelNotReadyError("Telegram application is restarting; message not delivered")
|
||||
raise RuntimeError("Telegram application is restarting; message not delivered")
|
||||
return self._app
|
||||
|
||||
def _note_poll_ok(self) -> None:
|
||||
@@ -1075,7 +1074,8 @@ class TelegramChannel(BaseChannel):
|
||||
return
|
||||
app = await self._wait_for_app()
|
||||
if app is None:
|
||||
raise ChannelNotReadyError("Telegram bot not running")
|
||||
self.logger.warning("bot not running")
|
||||
return
|
||||
|
||||
progress_event = msg.event if isinstance(msg.event, ProgressEvent) else None
|
||||
|
||||
@@ -1089,7 +1089,8 @@ class TelegramChannel(BaseChannel):
|
||||
try:
|
||||
chat_id = int(msg.chat_id)
|
||||
except ValueError:
|
||||
raise DeliveryRejectedError("Invalid Telegram chat_id") from None
|
||||
self.logger.exception("Invalid chat_id: {}", msg.chat_id)
|
||||
return
|
||||
reply_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:
|
||||
|
||||
@@ -12,7 +12,6 @@ try:
|
||||
except ImportError:
|
||||
pytest.skip("Telegram dependencies not installed (python-telegram-bot)", allow_module_level=True)
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -622,15 +621,14 @@ async def test_send_during_rebuild_fails_instead_of_dropping(monkeypatch) -> Non
|
||||
channel._app = None
|
||||
|
||||
msg = OutboundMessage(channel="telegram", chat_id="123", content="hello")
|
||||
with pytest.raises(ChannelNotReadyError, match="restarting"):
|
||||
with pytest.raises(RuntimeError, match="restarting"):
|
||||
await channel.send(msg)
|
||||
with pytest.raises(RuntimeError, match="restarting"):
|
||||
await channel.send_delta("123", "hello", stream_id="s1")
|
||||
|
||||
# A stopped channel must not report a final message as delivered.
|
||||
# Stopped: nothing to deliver, so stay quiet.
|
||||
channel._running = False
|
||||
with pytest.raises(ChannelNotReadyError, match="not running"):
|
||||
await channel.send(msg)
|
||||
await channel.send(msg)
|
||||
await channel.send_delta("123", "hello", stream_id="s1")
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from typing import Any, cast
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -417,7 +416,7 @@ class WecomChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self._client:
|
||||
raise ChannelNotReadyError("WeCom client not initialized")
|
||||
raise RuntimeError("WeCom client not initialized")
|
||||
|
||||
try:
|
||||
content = (msg.content or "").strip()
|
||||
|
||||
@@ -31,7 +31,6 @@ from loguru import logger
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from nanobot import __version__
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -1872,7 +1871,7 @@ class WeixinChannel(BaseChannel):
|
||||
):
|
||||
return
|
||||
if not self._client or not self._token:
|
||||
raise ChannelNotReadyError("WeChat client not initialized or not authenticated")
|
||||
raise RuntimeError("WeChat client not initialized or not authenticated")
|
||||
self._assert_session_active()
|
||||
|
||||
delivery_id = self._delivery_id(msg)
|
||||
@@ -2082,13 +2081,7 @@ class WeixinChannel(BaseChannel):
|
||||
)
|
||||
delivery_state.completed_parts.add(text_part)
|
||||
completed = True
|
||||
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
|
||||
raise
|
||||
except WeixinQuotaError:
|
||||
if not is_progress:
|
||||
self._defer_outbound(msg)
|
||||
self.logger.warning(
|
||||
|
||||
@@ -9,7 +9,6 @@ from unittest.mock import AsyncMock
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.weixin import runtime as weixin_mod
|
||||
@@ -547,7 +546,9 @@ async def test_send_without_context_token_raises() -> None:
|
||||
channel._send_text = AsyncMock()
|
||||
|
||||
with pytest.raises(RuntimeError, match="context_token missing"):
|
||||
await channel.send(_make_outbound_msg(chat_id="unknown-user", content="pong"))
|
||||
await channel.send(
|
||||
type("Msg", (), {"chat_id": "unknown-user", "content": "pong", "media": [], "metadata": {}})()
|
||||
)
|
||||
|
||||
channel._send_text.assert_not_awaited()
|
||||
|
||||
@@ -1481,26 +1482,6 @@ def _make_outbound_msg(chat_id: str = "wx-user", content: str = "", media: list
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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.asyncio
|
||||
async def test_send_media_timeout_error_propagates_without_text_fallback() -> None:
|
||||
"""httpx.TimeoutException during media send must re-raise immediately,
|
||||
|
||||
@@ -18,7 +18,6 @@ from urllib.parse import urlparse
|
||||
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
|
||||
@@ -467,7 +466,7 @@ class WhatsAppChannel(BaseChannel):
|
||||
return
|
||||
client = self._client
|
||||
if client is None or not self._connected:
|
||||
raise ChannelNotReadyError("WhatsApp channel is not connected")
|
||||
raise RuntimeError("WhatsApp channel is not connected")
|
||||
|
||||
to = self._build_jid(msg.chat_id)
|
||||
if msg.content:
|
||||
|
||||
@@ -8,7 +8,6 @@ import time
|
||||
import uuid
|
||||
from typing import Any, Protocol
|
||||
|
||||
from nanobot.bus.delivery import DELIVERY_RUN_META
|
||||
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
|
||||
@@ -53,10 +52,6 @@ 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
|
||||
|
||||
@@ -94,7 +89,6 @@ async def run_bound_cron_job(
|
||||
),
|
||||
}
|
||||
metadata[CRON_DEFER_UNTIL_IDLE_META] = True
|
||||
metadata[DELIVERY_RUN_META] = run_id
|
||||
run_record_base: dict[str, Any] = {
|
||||
"job_id": job.id,
|
||||
"job_name": job.name,
|
||||
|
||||
@@ -1,338 +0,0 @@
|
||||
"""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)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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"))
|
||||
@@ -6,7 +6,8 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
from nanobot.agent.tools.context import RequestContext, current_request_context, request_context
|
||||
from nanobot.agent.tools.cron import CronTool
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.cron.binding import CronBinding, binding_revision
|
||||
@@ -131,3 +132,70 @@ async def test_moved_cron_keeps_reply_send_and_prompt_prefix_contract(tmp_path,
|
||||
finally:
|
||||
cron.stop()
|
||||
await agent.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("origin", ["websocket", "whatsapp"])
|
||||
@pytest.mark.parametrize("explicit_send", [False, True])
|
||||
async def test_saved_cron_separates_source_chat_from_explicit_recipient(tmp_path, origin, explicit_send):
|
||||
"""Instructions alone do not change routing; a real tool call adds its recipient."""
|
||||
workspace = tmp_path / "workspace"
|
||||
sessions = SessionManager(workspace)
|
||||
bus = MessageBus()
|
||||
cron = CronService(tmp_path / "cron" / "jobs.json")
|
||||
chat_id = "source" if origin == "websocket" else "target"
|
||||
session_key = f"{origin}:{chat_id}"
|
||||
instructions = "Prepare a report and use message to send it to whatsapp:target."
|
||||
with request_context(RequestContext(origin, chat_id, session_key=session_key)):
|
||||
created = await CronTool(cron).execute(action="add", message=instructions, every_seconds=86400)
|
||||
assert "Created job" in created
|
||||
# The saved binding, not the recipient named in free text, survives a reload.
|
||||
cron = CronService(cron.store_path)
|
||||
job = cron.list_jobs()[0]
|
||||
assert job.payload.session_key == session_key
|
||||
assert (job.payload.origin_channel, job.payload.origin_chat_id) == (origin, chat_id)
|
||||
assert job.payload.message == instructions
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings(max_tokens=100)
|
||||
provider.can_resume_conversation_state.return_value = False
|
||||
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
requests = []
|
||||
|
||||
async def reply(**kwargs):
|
||||
requests.append(json.loads(json.dumps({"messages": kwargs["messages"], "tools": kwargs["tools"]})))
|
||||
if explicit_send and len(requests) == 1:
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
id="send", name="message", arguments={
|
||||
"content": "Report", "channel": "whatsapp", "chat_id": "target",
|
||||
},
|
||||
)], finish_reason="tool_calls")
|
||||
return LLMResponse(content="Report")
|
||||
|
||||
provider.chat_stream_with_retry = reply
|
||||
agent = AgentLoop(bus=bus, provider=provider, workspace=workspace, model="test-model",
|
||||
session_manager=sessions, tools_config=Config().tools, cron_service=cron)
|
||||
try:
|
||||
await run_bound_cron_job(job, agent=agent, cron=cron)
|
||||
messages = []
|
||||
while bus.outbound_size:
|
||||
message = await bus.consume_outbound()
|
||||
if message.event is None and message.content:
|
||||
messages.append(message)
|
||||
expected = [(origin, chat_id)]
|
||||
if explicit_send and origin == "websocket":
|
||||
expected.insert(0, ("whatsapp", "target"))
|
||||
assert [(message.channel, message.chat_id) for message in messages] == expected
|
||||
assert all(message.content == "Report" for message in messages)
|
||||
assert len(requests) == (2 if explicit_send else 1)
|
||||
if explicit_send:
|
||||
assert requests[1]["tools"] == requests[0]["tools"]
|
||||
prefix = requests[0]["messages"]
|
||||
assert requests[1]["messages"][:len(prefix)] == prefix
|
||||
assert "Report" in json.dumps(sessions.read_session_file(session_key))
|
||||
if origin == "websocket":
|
||||
assert sessions.read_session_file("whatsapp:target") is None
|
||||
finally:
|
||||
cron.stop()
|
||||
await agent.aclose()
|
||||
Reference in new issue
Block a user