fix(channels): retain scheduled results across pre-send outages

This commit is contained in:
Xubin Ren committed 2026-10-17 12:49:03 +08:00
1 parent 61db036cee
commit 508cedff31
31 files changed
+768 -61

No files matched your search

+4
View File
@@ -100,6 +100,10 @@ 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
+2 -1
View File
@@ -17,6 +17,7 @@ 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
@@ -742,7 +743,7 @@ class DingTalkChannel(BaseChannel):
return
token = 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:
+2 -1
View File
@@ -13,6 +13,7 @@ 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
@@ -539,7 +540,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 RuntimeError("Discord client is not ready")
raise ChannelNotReadyError("Discord client is not ready")
is_progress = isinstance(msg.event, ProgressEvent)
+5 -8
View File
@@ -23,6 +23,7 @@ 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
@@ -245,12 +246,10 @@ class EmailChannel(BaseChannel):
):
return
if 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 call
if 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 sends
if 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)
@@ -5,6 +5,7 @@ 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
@@ -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["alice@example.com"] = "Previous email"
# Reply should be skipped (auto_reply_enabled=False)
await channel.send(
OutboundMessage(
channel="email",
chat_id="alice@example.com",
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="alice@example.com",
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 = False
channel = EmailChannel(cfg, MessageBus())
await channel.send(
OutboundMessage(
channel="email",
chat_id="alice@example.com",
content="Should not send.",
metadata={"force_send": True},
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},
)
)
)
assert called["smtp"] is False
+2 -4
View File
@@ -25,6 +25,7 @@ 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
@@ -2446,10 +2447,7 @@ class FeishuChannel(BaseChannel):
):
return
if 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"
+3
View File
@@ -13,6 +13,7 @@ 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
@@ -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.content
if msg.media:
attachments = await self._attachment_markdown(msg)
+81 -3
View File
@@ -5,6 +5,7 @@ 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
@@ -13,6 +14,7 @@ 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,
@@ -32,8 +34,11 @@ 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,
@@ -154,6 +159,9 @@ 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()
@@ -750,18 +758,25 @@ 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:
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.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)
@@ -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)
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
@@ -1043,7 +1121,7 @@ class ChannelManager:
except asyncio.CancelledError:
raise # Propagate cancellation for graceful shutdown
except 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,
+2 -1
View File
@@ -58,6 +58,7 @@ 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
@@ -621,7 +622,7 @@ class MatrixChannel(BaseChannel):
):
return
if 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)
+2 -2
View File
@@ -11,6 +11,7 @@ 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
@@ -499,8 +500,7 @@ class MattermostChannel(BaseChannel):
):
return
if not self._http_client:
self.logger.warning("client not initialized")
return
raise ChannelNotReadyError("Mattermost client not initialized")
try:
chat_id = msg.chat_id
+3 -4
View File
@@ -15,6 +15,7 @@ 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
@@ -356,8 +357,7 @@ class MochatChannel(BaseChannel):
):
return
if 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:
+2 -1
View File
@@ -35,6 +35,7 @@ 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
@@ -256,7 +257,7 @@ class MSTeamsChannel(BaseChannel):
):
return
if 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:
+3 -3
View File
@@ -19,6 +19,7 @@ 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
@@ -443,12 +444,11 @@ class NapcatChannel(BaseChannel):
):
return
if 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 []:
+149
View File
@@ -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 "-")
+2 -1
View File
@@ -37,6 +37,7 @@ 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
@@ -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")
+3
View File
@@ -17,6 +17,7 @@ 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
@@ -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)
+2 -2
View File
@@ -14,6 +14,7 @@ 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
@@ -208,8 +209,7 @@ class SlackChannel(BaseChannel):
):
return
if 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)
+4 -5
View File
@@ -29,6 +29,7 @@ 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
@@ -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._app
def _note_poll_ok(self) -> None:
@@ -1074,8 +1075,7 @@ class TelegramChannel(BaseChannel):
return
app = 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 None
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,6 +12,7 @@ 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
@@ -621,14 +622,15 @@ 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(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")
+2 -1
View File
@@ -12,6 +12,7 @@ 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
@@ -416,7 +417,7 @@ class WecomChannel(BaseChannel):
):
return
if not self._client:
raise RuntimeError("WeCom client not initialized")
raise ChannelNotReadyError("WeCom client not initialized")
try:
content = (msg.content or "").strip()
+9 -2
View File
@@ -31,6 +31,7 @@ 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
@@ -1871,7 +1872,7 @@ class WeixinChannel(BaseChannel):
):
return
if 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
raise
if not is_progress:
self._defer_outbound(msg)
self.logger.warning(
@@ -9,6 +9,7 @@ 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
@@ -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
)
@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,
+2 -1
View File
@@ -18,6 +18,7 @@ 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
@@ -466,7 +467,7 @@ class WhatsAppChannel(BaseChannel):
return
client = self._client
if 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: