The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): report media-only turns as SUCCESS when attachments deliver
Halldrix78de23053f7e
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex f6c60920e5e..a6369e6d460 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2567,11 +2567,14 @@ class BasePlatformAdapter(ABC):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 ``(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)."""+ (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."""from urllib.parse import unquote as _unquote+ delivered = Falsefor image_url, alt_text in images:if human_delay > 0:await asyncio.sleep(human_delay)@@ -2588,8 +2591,15 @@ class BasePlatformAdapter(ABC):chat_id=chat_id, **url_kw, caption=alt_text or None, metadata=metadata)if not img_result.success:logger.error("[%s] Failed to send image: %s", self.name, img_result.error)+ else:+ delivered = Trueexcept Exception as img_err:logger.error("[%s] Error sending image: %s", self.name, img_err, exc_info=True)+ if not images:+ return SendResult(success=False, error="no images to send")+ return SendResult(+ success=delivered,+ error=None if delivered else "all images failed to send")async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None,@@ -3703,11 +3713,12 @@ class BasePlatformAdapter(ABC):async def _deliver_media_attachments(self, event: MessageEvent, media_files: list, local_files: list, *,- force_document_attachments: bool, human_delay: float, metadata: Dict[str, Any]) -> None:+ force_document_attachments: bool, human_delay: float, metadata: Dict[str, Any],+ record_delivery: Callable) -> None:"""Deliver MEDIA-tag files and detected local files by type: images batched via``send_multiple_images`` unless ``[[as_document]]``; otherwise audio → send_voice (MEDIAtags only, never bare local files), video → send_video, else send_document. Every failure is- reported."""+ reported. Each send feeds ``record_delivery`` so media-only turns report SUCCESS."""from urllib.parse import quote as _quotedef _as_image(path: str) -> bool:@@ -3716,10 +3727,11 @@ class BasePlatformAdapter(ABC):_image_paths += [p for p in local_files if _as_image(p)]if _image_paths:await self._send_image_batch(- event, [(f"file://{_quote(p)}", "") for p in _image_paths], metadata, human_delay)+ event, [(f"file://{_quote(p)}", "") for p in _image_paths], metadata, human_delay,+ record_delivery)chat_id = event.source.chat_id- async def _send_one(path: str, *, is_voice: bool, media_tag: bool) -> None:+ async def _send_one(path: str, *, is_voice: bool, media_tag: bool) -> SendResult:"""MEDIA-tag files (``media_tag``) may route to send_voice; bare local files neverdo."""ext = Path(path).suffix.lower()@@ -3735,6 +3747,7 @@ class BasePlatformAdapter(ABC):logger.warning("[%s] Failed to send %s (%s): %s", self.name,"media" if media_tag else "local file", ext, result.error)await self._notify_media_delivery_failure(chat_id, path, is_voice=is_voice, metadata=metadata)+ return resultqueue = [(p, v, True) for p, v in media_files if v or not _as_image(p)]if queue:logger.info("[%s] Delivering %d non-image MEDIA attachment(s)", self.name, len(queue))@@ -3743,21 +3756,31 @@ class BasePlatformAdapter(ABC):if human_delay > 0:await asyncio.sleep(human_delay)try:- await _send_one(path, is_voice=is_voice, media_tag=media_tag)+ record_delivery(await _send_one(path, is_voice=is_voice, media_tag=media_tag))except Exception as err:+ record_delivery(SendResult(success=False, error=str(err)))if media_tag:logger.warning("[%s] Error sending media: %s", self.name, err)else:logger.error("[%s] Error sending local file %s: %s", self.name, path, err)async def _send_image_batch(- self, event: MessageEvent, images: list, metadata: Dict[str, Any], human_delay: float) -> None:- """Batch-send images; a failure is logged (never raised) so other attachments still go."""+ self, event: MessageEvent, images: list, metadata: Dict[str, Any], human_delay: float,+ record_delivery: Callable) -> None:+ """Batch-send images; a failure is logged (never raised) so other attachments still go.+ The batch result feeds ``record_delivery`` so media-only turns report their real+ outcome instead of FAILURE."""try:- await self.send_multiple_images(+ result = await self.send_multiple_images(chat_id=event.source.chat_id, images=images, metadata=metadata, human_delay=human_delay)except Exception as batch_err: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(self, event: MessageEvent, session_key: str, text_content: str, metadata: Dict[str, Any], *,@@ -3809,18 +3832,20 @@ class BasePlatformAdapter(ABC):return _thread_metadataasync def _deliver_attachments(self, event: MessageEvent, extracted: "_ExtractedResponse",- metadata: Dict[str, Any], *, anything_sent: bool) -> None:+ metadata: Dict[str, Any], *, anything_sent: bool,+ record_delivery: Callable) -> None:"""Send extracted image URLs, MEDIA files and bare local files (human-paced),- then fail loudly if a non-empty response produced nothing deliverable."""+ then fail loudly if a non-empty response produced nothing deliverable. Attachment+ results feed ``record_delivery`` so the turn outcome reflects them."""human_delay = self._get_human_delay()images, media_files, local_files = extracted.images, extracted.media_files, extracted.local_filesif images:logger.info("[%s] Extracted %d image(s) to send as attachments", self.name, len(images))- await self._send_image_batch(event, images, metadata, human_delay)+ await self._send_image_batch(event, images, metadata, human_delay, record_delivery)await self._deliver_media_attachments(event, media_files, local_files,force_document_attachments=extracted.force_document_attachments,- human_delay=human_delay, metadata=metadata)+ human_delay=human_delay, metadata=metadata, record_delivery=record_delivery)if not (anything_sent or images or local_files or media_files) and extracted.pre_extract.strip():logger.error("[%s] response_delivery_dropped: non-empty response ""(%d chars) produced no delivered message or attachment "@@ -3978,7 +4003,8 @@ class BasePlatformAdapter(ABC):is_ephemeral_response, _ephemeral_ttl, _record_delivery)await self._deliver_attachments(event, extracted, _final_thread_metadata,- anything_sent=delivery_attempted or _tts_caption_delivered)+ anything_sent=delivery_attempted or _tts_caption_delivered,+ record_delivery=_record_delivery)processing_ok = delivery_succeeded if delivery_attempted else not bool(response)# Clean up the per-turn streaming-TTS flag.self._streaming_tts_completed_turns.discard(self._streaming_tts_turn_key(diff --git a/gateway/platforms/signal.py b/gateway/platforms/signal.pyindex 9c2f8c91d1d..4fce8d22cb6 100644--- a/gateway/platforms/signal.py+++ b/gateway/platforms/signal.py@@ -781,11 +781,12 @@ class SignalAdapter(BasePlatformAdapter):return file_path, None, Noneasync 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 via chunked Signal RPC calls. Alt texts are dropped (one shared body- per send); bad images are skipped with a warning; ``human_delay`` is ignored (scheduler paces)."""+ per send); bad images are skipped with a warning; ``human_delay`` is ignored (scheduler paces).+ Returns success when at least one batch was accepted, so media-only turns report SUCCESS."""if not images:- return+ return SendResult(success=False, error="no images to send")scheduler = get_scheduler()logger.info("Signal send_multiple_images: received %d image(s) for %s — scheduler state: %s", len(images),chat_id[:30], scheduler.state())@@ -802,24 +803,30 @@ class SignalAdapter(BasePlatformAdapter):if not attachments:logger.error("Signal: no valid images in batch of %d (download=%d missing=%d oversize=%d)", len(images),skipped["download"], skipped["missing"], skipped["oversize"])- return+ return SendResult(success=False, error="no valid images in batch")logger.info("Signal send_multiple_images: %d/%d images valid, sending in chunks", len(attachments), len(images))base_params = await self._with_target({"account": self.account, "message": ""}, chat_id)per = SIGNAL_MAX_ATTACHMENTS_PER_MSGatt_batches = [attachments[i:i + per] for i in range(0, len(attachments), per)]n_batches = len(att_batches)+ delivered = Falsefor idx, att_batch in enumerate(att_batches, start=1):n = len(att_batch)estimated = scheduler.estimate_wait(n)logger.debug("Signal batch %d/%d: %d attachments, estimated wait=%.1fs", idx, n_batches, n, estimated)if estimated >= SIGNAL_BATCH_PACING_NOTICE_THRESHOLD:await self._notify_batch_pacing(chat_id, idx, n_batches, estimated)- await self._send_attachment_batch(scheduler, dict(base_params, attachments=att_batch), n,- f"{idx}/{n_batches}")-- async def _send_attachment_batch(self, scheduler, params: Dict[str, Any], n: int, label: str) -> None:+ if await self._send_attachment_batch(scheduler, dict(base_params, attachments=att_batch), n,+ f"{idx}/{n_batches}"):+ delivered = True+ return SendResult(+ success=delivered,+ error=None if delivered else "all Signal attachment batches failed")++ async def _send_attachment_batch(self, scheduler, params: Dict[str, Any], n: int, label: str) -> bool:"""Send one attachment batch with rate-limit pacing and a single transient retry. Tokens are- deducted only on validated success (None = server never accepted it); 429s feed the scheduler."""+ deducted only on validated success (None = server never accepted it); 429s feed the scheduler.+ Returns True when the server accepted the batch."""send_timeout, max_attempts = _signal_send_timeout(n), SIGNAL_RATE_LIMIT_MAX_ATTEMPTSfor attempt in range(1, max_attempts + 1):await scheduler.acquire(n)@@ -832,7 +839,7 @@ class SignalAdapter(BasePlatformAdapter):if attempt >= max_attempts:logger.error("Signal: rate-limit retries exhausted on batch %s (%d attachments lost, ""server retry_after=%s)", label, n, retry_after)- return+ return Falselogger.warning("Signal: rate-limited on batch %s (attempt %d/%d, server retry_after=%s); ""scheduler will pace the retry", label, attempt, max_attempts, retry_after)continue@@ -843,13 +850,14 @@ class SignalAdapter(BasePlatformAdapter):await scheduler.report_rpc_duration(duration, n)logger.info("Signal batch %s: %d attachments sent in %.1fs (attempt %d/%d)", label, n, duration,attempt, max_attempts)- return+ return Truelogger.error("Signal: RPC send failed for batch %s (%d attachments, attempt %d/%d, rpc_duration=%.1fs)%s",label, n, attempt, max_attempts, duration, f": {err_msg}" if result is not None else "")if attempt >= max_attempts:- return+ return Falselogger.info("Signal: retrying batch %s after %.1fs backoff", label, 2.0 ** attempt)await asyncio.sleep(2.0 ** attempt)+ return Falseasync def _notify_batch_pacing(self, chat_id: str, next_batch_idx: int, total_batches: int, wait_s: float) -> None:"""Tell the user about an inter-batch pacing wait over the notice threshold (best-effort)."""diff --git a/tests/gateway/test_media_only_outcome.py b/tests/gateway/test_media_only_outcome.pynew file mode 100644index 00000000000..e6a7369fdec--- /dev/null+++ b/tests/gateway/test_media_only_outcome.py@@ -0,0 +1,120 @@+"""Regression tests for #106153 — media-only turns reported FAILURE.++``_process_message_background`` fed its ``on_processing_complete`` outcome from+``delivery_attempted``/``delivery_succeeded``, which only text/TTS sends+populated. A turn replying with just ``MEDIA:<path>`` delivered the attachment+fine but computed ``processing_ok = False`` (no text attempted, non-empty+response), so Signal swapped the 👀 reaction for ❌ instead of ✅.++The attachment path now feeds the same tracker, so a delivered media-only+turn reports SUCCESS and a failed one still reports FAILURE.+"""++import asyncio++import pytest++from gateway.config import Platform, PlatformConfig+from gateway.platforms.base import (+ BasePlatformAdapter,+ SendResult,+)+from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome+from gateway.session import SessionSource, build_session_key+++class _MediaOutcomeAdapter(BasePlatformAdapter):+ """Base-loop adapter (no ``send_multiple_images`` override) that records+ the turn outcome via the production ``on_processing_complete`` hook."""++ def __init__(self, *, image_ok: bool = True):+ super().__init__(PlatformConfig(enabled=True, token="fake-token"), Platform.SIGNAL)+ self._image_ok = image_ok+ self.outcomes: list = []+ self.images_sent: list = []++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ return True++ async def disconnect(self) -> None:+ return None++ async def send(self, chat_id, content, reply_to=None, metadata=None) -> SendResult:+ return SendResult(success=True, message_id="msg-1")++ async def send_typing(self, chat_id: str, metadata=None) -> None:+ return None++ async def get_chat_info(self, chat_id: str):+ return {"id": chat_id}++ async def send_image_file(self, chat_id, image_path, caption=None,+ reply_to=None, metadata=None, **kwargs) -> SendResult:+ self.images_sent.append(str(image_path))+ if self._image_ok:+ return SendResult(success=True, message_id="img-1")+ return SendResult(success=False, error="boom")++ async def on_processing_complete(self, event: MessageEvent, outcome: ProcessingOutcome) -> None:+ self.outcomes.append(outcome)+++async def _hold_typing(_chat_id, interval=2.0, metadata=None, stop_event=None):+ if stop_event is not None:+ await stop_event.wait()+ else:+ await asyncio.Event().wait()+++def _allowed_image(tmp_path, monkeypatch, name: str = "photo.png"):+ root = tmp_path / "media-cache"+ f = root / name+ f.parent.mkdir(parents=True, exist_ok=True)+ f.write_bytes(b"\x89PNG\r\n\x1a\n" + b"x" * 64)+ monkeypatch.setattr("gateway.platforms.base.MEDIA_DELIVERY_SAFE_ROOTS", (root,))+ return f.resolve()+++def _make_event() -> MessageEvent:+ return MessageEvent(+ text="send the photo",+ message_type=MessageType.TEXT,+ source=SessionSource(platform=Platform.SIGNAL, chat_id="111", chat_type="dm"),+ message_id="m1",+ )+++async def test_media_only_success_reports_success(tmp_path, monkeypatch):+ """Delivered media-only turn must report SUCCESS (was FAILURE → ❌)."""+ png = _allowed_image(tmp_path, monkeypatch)+ adapter = _MediaOutcomeAdapter(image_ok=True)+ adapter._keep_typing = _hold_typing++ async def handler(_event):+ return f"MEDIA:{png}"++ adapter.set_message_handler(handler)+ event = _make_event()+ await adapter._process_message_background(event, build_session_key(event.source))++ assert adapter.images_sent == [str(png)]+ assert adapter.outcomes == [ProcessingOutcome.SUCCESS]+++async def test_media_only_failure_still_reports_failure(tmp_path, monkeypatch):+ """A media-only turn whose attachment failed must still report FAILURE."""+ png = _allowed_image(tmp_path, monkeypatch)+ adapter = _MediaOutcomeAdapter(image_ok=False)+ adapter._keep_typing = _hold_typing++ async def handler(_event):+ return f"MEDIA:{png}"++ adapter.set_message_handler(handler)+ event = _make_event()+ await adapter._process_message_background(event, build_session_key(event.source))++ assert adapter.images_sent == [str(png)]+ assert adapter.outcomes == [ProcessingOutcome.FAILURE]