Skip to content

The agent that grows with you

fix(gateway): every send_multiple_images override returns the aggregate SendResult

teknium191adf584a478
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index a6369e6d460..31c6bdf6227 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -2571,8 +2571,8 @@ class BasePlatformAdapter(ABC):
"""Send ``(url, alt)`` images (``http(s)://`` or ``file://``) one by one (GIFs via
``send_animation``, local files via ``send_image_file``); override to bundle natively
(Signal). Returns success when at least one image was delivered — the outcome
- the turn-level delivery tracker records. Overrides that batch natively but
- still return ``None`` are legacy: the caller records nothing for them."""
+ the turn-level delivery tracker records; every override must return the same
+ aggregate, or a media-only turn on that platform reports FAILURE (#106153)."""
from urllib.parse import unquote as _unquote
delivered = False
for image_url, alt_text in images:
@@ -3777,9 +3777,6 @@ class BasePlatformAdapter(ABC):
logger.warning("[%s] Error batching images: %s", self.name, batch_err, exc_info=True)
record_delivery(SendResult(success=False, error=str(batch_err)))
return
- # Legacy native-batch overrides return None instead of a SendResult:
- # ``record_delivery(None)`` records nothing, so their outcome stays as before
- # until they migrate to the SendResult contract.
record_delivery(result)
async def send_final_ledgered(
diff --git a/plugins/platforms/discord/adapter_media.py b/plugins/platforms/discord/adapter_media.py
index dd8a3b1cd83..e6d66a222c5 100644
--- a/plugins/platforms/discord/adapter_media.py
+++ b/plugins/platforms/discord/adapter_media.py
@@ -65,33 +65,32 @@ class DiscordMediaMixin:
async def send_multiple_images(
self, chat_id: str, images: List[Tuple[str, str]],
metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0,
- ) -> None:
+ ) -> SendResult:
"""Send images as one Discord message (<=10 attachments): URLs are downloaded and uploaded
inline (bare links don't render); on chunk failure the remainder uses the per-image loop."""
from plugins.platforms.discord.adapter import _prompt_target_id, _image_ext_from_content_type, _read_url_image_with_redirect_guard, is_safe_url
if not self._client:
- return
+ return SendResult(success=False, error="Not connected")
if not images:
- return
+ return SendResult(success=False, error="no images to send")
try:
import discord as _discord_mod
import io as _io
from urllib.parse import unquote as _unquote
except Exception: # pragma: no cover
- await super().send_multiple_images(chat_id, images, metadata, human_delay)
- return
+ return await super().send_multiple_images(chat_id, images, metadata, human_delay)
try:
channel = await self._resolve_channel(_prompt_target_id(chat_id, metadata))
if not channel:
logger.warning("[%s] Channel %s not found for multi-image send", self.name, chat_id)
- return
+ return SendResult(success=False, error=f"Channel {chat_id} not found")
except Exception as e:
logger.warning("[%s] Failed to resolve channel for multi-image send: %s", self.name, e)
- await super().send_multiple_images(chat_id, images, metadata, human_delay)
- return
+ return await super().send_multiple_images(chat_id, images, metadata, human_delay)
CHUNK = 10
chunks = [images[i:i + CHUNK] for i in range(0, len(images), CHUNK)]
+ delivered = False
for chunk_idx, chunk in enumerate(chunks):
if human_delay > 0 and chunk_idx > 0:
await asyncio.sleep(human_delay)
@@ -149,18 +148,21 @@ class DiscordMediaMixin:
)
else:
await channel.send(content=content, files=files)
+ delivered = True
except Exception as e:
logger.warning(
"[%s] Multi-image Discord send failed (chunk %d/%d), falling back to per-image: %s",
self.name, chunk_idx + 1, len(chunks), e, exc_info=True,
)
- await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ fallback = await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ delivered = delivered or fallback.success
finally:
if aiohttp_session is not None:
try:
await aiohttp_session.close()
except Exception:
pass
+ return SendResult(success=delivered, error=None if delivered else "all images failed to send")
async def send_voice(
diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.py
index 18256ac1922..da05d324534 100644
--- a/plugins/platforms/email/adapter.py
+++ b/plugins/platforms/email/adapter.py
@@ -717,10 +717,10 @@ class EmailAdapter(BasePlatformAdapter):
return await self.send(chat_id, f"{caption or ''}\n\nImage: {image_url}".strip(), reply_to)
async def send_multiple_images(self, chat_id: str, images: List[Tuple[str, str]],
- metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> None:
+ metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> SendResult:
"""One email per batch: local files attached, URL images linked in the body (no remote download); base-class fallback on failure."""
if not images:
- return
+ return SendResult(success=False, error="no images to send")
from urllib.parse import unquote as _unquote
body_parts, local_paths = [], []
for image_url, alt_text in images:
@@ -733,12 +733,13 @@ class EmailAdapter(BasePlatformAdapter):
else:
logger.warning("[Email] Skipping missing image: %s", local_path)
if not local_paths and not body_parts:
- return
+ return SendResult(success=False, error="no valid images in batch")
try:
- await asyncio.get_running_loop().run_in_executor(None, self._send_email_with_attachments, chat_id, "\n\n".join(body_parts), local_paths)
+ message_id = await asyncio.get_running_loop().run_in_executor(None, self._send_email_with_attachments, chat_id, "\n\n".join(body_parts), local_paths)
except Exception as e:
logger.error("[Email] Multi-image send failed, falling back: %s", e, exc_info=True)
- await super().send_multiple_images(chat_id, images, metadata, human_delay)
+ return await super().send_multiple_images(chat_id, images, metadata, human_delay)
+ return SendResult(success=True, message_id=message_id)
def _send_email_with_attachments(self, to_addr: str, body: str, file_paths: List[str]) -> str:
"""Send an email with multiple file attachments via SMTP (unattachable files are skipped)."""
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 4875458cdaa..d8468fd2ebd 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -1478,11 +1478,12 @@ class MatrixAdapter(BasePlatformAdapter):
async def send_multiple_images(
self, chat_id: str, images: list[tuple[str, str]], metadata: Optional[Dict[str, Any]] = None,
- human_delay: float = 0.0) -> None:
+ human_delay: float = 0.0) -> SendResult:
if not images:
- return
+ return SendResult(success=False, error="no images to send")
from urllib.parse import unquote as _unquote
total = len(images)
+ delivered = False
for idx, (image_url, alt_text) in enumerate(images, start=1):
if human_delay > 0 and idx > 1:
await asyncio.sleep(human_delay)
@@ -1494,6 +1495,8 @@ class MatrixAdapter(BasePlatformAdapter):
result = await self.send_image(chat_id=chat_id, image_url=image_url, caption=caption, metadata=metadata)
if not result.success:
logger.warning("Matrix: failed to send image %d/%d: %s", idx, total, result.error)
+ delivered = delivered or result.success
+ return SendResult(success=delivered, error=None if delivered else "all images failed to send")
async def send_document(
self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
diff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.py
index af114ec27d2..c0b6561ebf1 100644
--- a/plugins/platforms/mattermost/adapter.py
+++ b/plugins/platforms/mattermost/adapter.py
@@ -398,12 +398,13 @@ class MattermostAdapter(BasePlatformAdapter):
return file_data, _url_filename(image_url, f"image_{index}.png"), ct
async def send_multiple_images(self, chat_id: str, images: List[Tuple[str, str]],
- metadata: _Metadata = None, human_delay: float = 0.0) -> None:
+ metadata: _Metadata = None, human_delay: float = 0.0) -> SendResult:
"""Send a batch of images as one post; chunked at Mattermost's 5-``file_ids`` cap, each chunk
falling back to the base per-image loop on failure."""
if not images:
- return
+ return SendResult(success=False, error="no images to send")
chunks = [images[i:i + 5] for i in range(0, len(images), 5)] # Mattermost post file_ids cap
+ delivered = False
for chunk_idx, chunk in enumerate(chunks):
if human_delay > 0 and chunk_idx > 0:
await asyncio.sleep(human_delay)
@@ -420,13 +421,18 @@ class MattermostAdapter(BasePlatformAdapter):
logger.info("Mattermost: sending %d image(s) as single post (chunk %d/%d)",
len(file_ids), chunk_idx + 1, len(chunks))
data = await self._post_message(chat_id, "\n".join(caption_parts), None, metadata, file_ids)
- if not data or "id" not in data:
+ if data and "id" in data:
+ delivered = True
+ else:
logger.warning("Mattermost: multi-image post failed, falling back")
- await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ fallback = await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ delivered = delivered or fallback.success
except Exception as e:
logger.warning("Mattermost: multi-image send failed (chunk %d/%d), falling back: %s",
chunk_idx + 1, len(chunks), e, exc_info=True)
- await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ fallback = await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ delivered = delivered or fallback.success
+ return SendResult(success=delivered, error=None if delivered else "all images failed to send")
# --- WebSocket ---
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py
index 03b016f6f86..dc2c983ea2d 100644
--- a/plugins/platforms/slack/adapter.py
+++ b/plugins/platforms/slack/adapter.py
@@ -2657,25 +2657,25 @@ class SlackAdapter(BasePlatformAdapter):
async def send_multiple_images(
self, chat_id: str, images: List[Tuple[str, str]],
- metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> None:
+ metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> SendResult:
"""Send a batch of images as one message via ``files_upload_v2(file_uploads=...)`` (10 per
call, Slack cap) instead of N posts; falls back to the base per-image loop on failure."""
if self._suppressed_ignored(chat_id, "multi-image upload in"):
- return
+ return SendResult(success=False, error="ignored_channel")
if not self._app:
- return
+ return SendResult(success=False, error="Not connected")
if not images:
- return
+ return SendResult(success=False, error="no images to send")
chat_id = await self._dm_target(chat_id, metadata)
try:
from urllib.parse import unquote as _unquote
from tools.url_safety import create_ssrf_safe_async_client, is_safe_url as _is_safe_url
except Exception:
- await super().send_multiple_images(chat_id, images, metadata, human_delay)
- return
+ return await super().send_multiple_images(chat_id, images, metadata, human_delay)
thread_ts = self._resolve_thread_ts(None, metadata)
CHUNK = 10
chunks = [images[i : i + CHUNK] for i in range(0, len(images), CHUNK)]
+ delivered = False
for chunk_idx, chunk in enumerate(chunks):
if human_delay > 0 and chunk_idx > 0:
await asyncio.sleep(human_delay)
@@ -2692,12 +2692,15 @@ class SlackAdapter(BasePlatformAdapter):
channel=chat_id, file_uploads=file_uploads, initial_comment=initial_comment,
thread_ts=thread_ts)
self._record_uploaded_file_thread(chat_id, thread_ts, metadata)
+ delivered = True
except Exception as e:
logger.warning(
"[Slack] Multi-image files_upload_v2 failed (chunk %d/%d), falling back to per-image: %s",
chunk_idx + 1, len(chunks), e, exc_info=True)
- await super().send_multiple_images(
+ fallback = await super().send_multiple_images(
chat_id, chunk, metadata, human_delay=human_delay)
+ delivered = delivered or fallback.success
+ return SendResult(success=delivered, error=None if delivered else "all images failed to send")
@staticmethod
async def _collect_image_uploads(
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index cfd4816cf57..5dcccfb2063 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -4642,24 +4642,27 @@ class TelegramAdapter(BasePlatformAdapter):
os.unlink(_transcoded_voice_path)
async def send_multiple_images(
- self, chat_id: str, images: List[tuple], metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> None:
+ self, chat_id: str, images: List[tuple], metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> SendResult:
"""Send images as Telegram albums (``send_media_group``, 10 per chunk). Animated GIFs can't join a
media group (need ``send_animation``) so they go via the base per-image path, as does a failed chunk."""
- if not self._bot or not images:
- return
+ if not self._bot:
+ return SendResult(success=False, error="Not connected")
+ if not images:
+ return SendResult(success=False, error="no images to send")
try:
from telegram import InputMediaPhoto
except Exception as exc: # pragma: no cover - missing SDK
logger.warning("[%s] InputMediaPhoto unavailable, falling back to per-image send: %s", self.name, exc)
- await super().send_multiple_images(chat_id, images, metadata, human_delay)
- return
+ return await super().send_multiple_images(chat_id, images, metadata, human_delay)
is_anim = lambda url: not url.startswith("file://") and self._is_animation_url(url) # noqa: E731
animations = [img for img in images if is_anim(img[0])]
photos = [img for img in images if not is_anim(img[0])]
+ delivered = False
if animations:
- await super().send_multiple_images(chat_id, animations, metadata, human_delay=human_delay)
+ anim_result = await super().send_multiple_images(chat_id, animations, metadata, human_delay=human_delay)
+ delivered = anim_result.success
if not photos:
- return
+ return SendResult(success=delivered, error=None if delivered else "all images failed to send")
from urllib.parse import unquote as _unquote
CHUNK = 10 # Telegram's album limit
chunks = [photos[i:i + CHUNK] for i in range(0, len(photos), CHUNK)]
@@ -4692,15 +4695,18 @@ class TelegramAdapter(BasePlatformAdapter):
await self._send_with_dm_topic_reply_anchor_retry(
self._bot.send_media_group, {**send_kwargs, "media": media}, metadata, reply_to_id,
"media group", reset_media=_reset_opened_files)
+ delivered = True
except Exception as e:
logger.warning(
"[%s] send_media_group failed (chunk %d/%d), falling back to per-image: %s", self.name,
chunk_idx + 1, len(chunks), _redact_telegram_error_text(e), exc_info=True)
- await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ fallback = await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
+ delivered = delivered or fallback.success
finally:
for fh in opened_files:
with contextlib.suppress(Exception):
fh.close()
+ return SendResult(success=delivered, error=None if delivered else "all images failed to send")
async def send_image_file(
self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,