The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(whatsapp): quoting the bot's own image/voice/document attaches the file
Tekniumc8b56d43da6a
diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex 8daf427cb51..a88762c2b8e 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -550,14 +550,22 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):filename: Optional[str] = None, reply_to: Optional[str] = None,mime_type: Optional[str] = None,) -> SendResult:- """HTTPS URL → ``link`` send (one fewer round trip); local path → upload + ``id`` send."""+ """HTTPS URL → ``link`` send (one fewer round trip); local path → upload + ``id`` send.+ Local sends are indexed in ``rich_sent_store`` so a later quote of the attachment can be+ resolved (Meta's inbound ``context`` carries only the quoted id)."""ref: Dict[str, Optional[str]] = {"media_link": source}if not source.startswith(_HTTP_PREFIXES):media_id, err = await self._upload_media(source, media_kind, mime_type)if err:return SendResult(success=False, error=err)ref = {"media_id": media_id}- return await self._send_media(chat_id, media_kind, caption=caption, filename=filename, reply_to=reply_to, **ref)+ result = await self._send_media(chat_id, media_kind, caption=caption, filename=filename, reply_to=reply_to, **ref)+ if result.success and result.message_id and "media_id" in ref:+ mime = mime_type or mimetypes.guess_type(source)[0] or _DEFAULT_MIME.get(media_kind, "application/octet-stream")+ rich_sent_store.record_media(chat_id, result.message_id, [(source, mime)])+ if caption:+ rich_sent_store.record(chat_id, result.message_id, caption)+ return result# ``**kwargs`` absorbs base-class args (e.g. ``metadata``) the Cloud API has no use for.async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:@@ -986,8 +994,9 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):media_urls, media_types, body = await self._collect_inbound_media(msg_type_str, raw_message, body)if msg_type_str == "document" and media_urls:body = self._inject_document_text(media_urls, body)- # Meta's ``context`` gives only the quoted message's id (+ author), never its text;- # resolve from rich_sent_store so run.py can build "[Replying to: ...]".+ # Meta's ``context`` gives only the quoted message's id (+ author), never its text or+ # bytes; resolve both from rich_sent_store so run.py can build "[Replying to: ...]" and+ # the quoted attachment reaches the vision/audio pipeline like a direct one.context = raw_message.get("context") or {}reply_to_id = str(context.get("id") or "").strip() or Nonereply_to_text = rich_sent_store.lookup(chat_id, reply_to_id) if reply_to_id else None@@ -1001,6 +1010,13 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):self._bounded_put(self._last_inbound_wamid_by_chat, chat_id, wamid)if body:rich_sent_store.record(chat_id, wamid, body)+ if msg_type_str in _INBOUND_MEDIA_KINDS and media_urls:+ rich_sent_store.record_media(chat_id, wamid, list(zip(media_urls, media_types)))+ if reply_to_id:+ for path, mime in rich_sent_store.lookup_media(chat_id, reply_to_id):+ if path not in media_urls:+ media_urls.append(path)+ media_types.append(mime)return MessageEvent(text=body, message_type=_MESSAGE_TYPE_BY_KIND.get(msg_type_str, MessageType.TEXT),source=self.build_source(diff --git a/gateway/rich_sent_store.py b/gateway/rich_sent_store.pyindex 645c542db79..237977edebc 100644--- a/gateway/rich_sent_store.py+++ b/gateway/rich_sent_store.py@@ -1,8 +1,12 @@-"""Local index of text we've sent via ``sendRichMessage`` (Bot API 10.1). Telegram does NOT echo a rich-message's content back in ``reply_to_message`` (``.text``/``.caption`` empty, ``.api_kwargs`` None), so-replies to rich sends arrive with no quotable text; we remember ``message_id -> text`` at send time and-look it up by ``reply_to_id`` on inbound. Best-effort and dependency-free: every operation swallows-errors and degrades to a no-op / ``None`` so it can never break a send or an inbound message.+"""Local index of what we've sent (and, for WhatsApp, received) keyed by ``(chat_id, message_id)``.++Telegram does NOT echo a rich message's content back in ``reply_to_message`` (``.text``/``.caption``+empty, ``.api_kwargs`` None), and WhatsApp quotes carry only the quoted message's id (Cloud API) or a+thumbnail stub (Baileys) — never the original bytes. So a reply to something we sent arrives with no+quotable text and no way to re-fetch a quoted attachment. We remember ``message_id -> text`` and+``message_id -> [(local_path, mime)]`` at send/receive time and look them up by ``reply_to_id`` on+inbound. Best-effort and dependency-free: every operation swallows errors and degrades to a no-op /+``None`` / ``[]`` so it can never break a send or an inbound message."""from __future__ import annotations@@ -30,15 +34,16 @@ def _load(path: str) -> dict:return data if isinstance(data, dict) else {}-def record(chat_id, message_id, text: Optional[str]) -> None:- """Persist ``text`` for ``(chat_id, message_id)``. No-op on any failure."""- if not text or message_id is None or chat_id is None:- return+def _update(chat_id, message_id, fields: dict) -> None:+ """Merge ``fields`` into the ``(chat_id, message_id)`` entry. No-op on any failure."""path = _store_path()try:os.makedirs(os.path.dirname(path), exist_ok=True)data = _load(path)- data[f"{chat_id}:{message_id}"] = {"t": text[:_MAX_TEXT_CHARS], "ts": int(time.time())}+ key = f"{chat_id}:{message_id}"+ entry = data.get(key)+ entry = entry if isinstance(entry, dict) else {}+ data[key] = {**entry, **fields, "ts": int(time.time())}if len(data) > _MAX_ENTRIES: # trim oldest by timestampfor k, _ in sorted(data.items(), key=lambda kv: kv[1].get("ts", 0))[: len(data) - _MAX_ENTRIES]:data.pop(k, None)@@ -50,9 +55,33 @@ def record(chat_id, message_id, text: Optional[str]) -> None:return-def lookup(chat_id, message_id) -> Optional[str]:- """Return stored text for ``(chat_id, message_id)`` or ``None``."""+def record(chat_id, message_id, text: Optional[str]) -> None:+ """Persist ``text`` for ``(chat_id, message_id)``. No-op on any failure."""+ if not text or message_id is None or chat_id is None:+ return+ _update(chat_id, message_id, {"t": text[:_MAX_TEXT_CHARS]})+++def record_media(chat_id, message_id, media: list[tuple[str, str]]) -> None:+ """Persist local attachment ``(path, mime)`` pairs for ``(chat_id, message_id)``."""+ if not media or message_id is None or chat_id is None:+ return+ _update(chat_id, message_id, {"m": [[str(p), str(mt or "")] for p, mt in media if p]})+++def _entry(chat_id, message_id) -> dict:if message_id is None or chat_id is None:- return None+ return {}entry = _load(_store_path()).get(f"{chat_id}:{message_id}")- return (entry.get("t") or None) if isinstance(entry, dict) else None+ return entry if isinstance(entry, dict) else {}+++def lookup(chat_id, message_id) -> Optional[str]:+ """Return stored text for ``(chat_id, message_id)`` or ``None``."""+ return _entry(chat_id, message_id).get("t") or None+++def lookup_media(chat_id, message_id) -> list[tuple[str, str]]:+ """Return stored ``(path, mime)`` pairs whose file still exists (attachments may be temp files)."""+ pairs = _entry(chat_id, message_id).get("m") or []+ return [(p, mt) for p, mt in pairs if isinstance(p, str) and os.path.isfile(p)]diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 91f6cbb22b9..a08c48232d7 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -3,6 +3,7 @@ client; messages are polled over a local HTTP API and responses are posted backimport asyncioimport logging+import mimetypesimport osimport platformimport re@@ -234,6 +235,11 @@ _MEDIA_INFO = {MessageType.PHOTO: ("image", "image/jpeg"), MessageType.VOICE: ("audio", "audio/ogg"), MessageType.AUDIO: ("audio", "audio/mpeg"),MessageType.VIDEO: ("video", "video/mp4"), MessageType.DOCUMENT: ("document", ""),}+_MEDIA_TYPE_BY_BRIDGE_KIND = {"image": MessageType.PHOTO, "video": MessageType.VIDEO, "audio": MessageType.VOICE, "document": MessageType.DOCUMENT}+_QUOTED_MIME_BY_BRIDGE_KIND = {+ "image": "image/jpeg", "video": "video/mp4", "gif": "video/mp4", "audio": "audio/ogg", "ptt": "audio/ogg",+ "document": "application/octet-stream", "sticker": "image/webp",+}def _needs_bridge(method):@@ -599,9 +605,17 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):async def _send_media_to_bridge(self, chat_id: str, file_path: str, media_type: str, caption: Optional[str] = None, file_name: Optional[str] = None) -> SendResult:if not os.path.exists(file_path):return SendResult(success=False, error=f"File not found: {file_path}")- payload: Dict[str, Any] = {"chatId": to_whatsapp_jid(chat_id), "filePath": file_path, "mediaType": media_type}+ jid = to_whatsapp_jid(chat_id)+ payload: Dict[str, Any] = {"chatId": jid, "filePath": file_path, "mediaType": media_type}payload.update({k: v for k, v in (("caption", caption), ("fileName", file_name)) if v})- return await self._post_bridge_message("send-media", payload, timeout=120)+ result = await self._post_bridge_message("send-media", payload, timeout=120)+ if result.success and result.message_id:+ # A later quote of this attachment carries only a thumbnail stub; the bridge's cache+ # knows inbound media only, so index our own sends (the cron-delivered image case).+ from gateway import rich_sent_store+ mime = mimetypes.guess_type(file_path)[0] or _MEDIA_INFO.get(_MEDIA_TYPE_BY_BRIDGE_KIND.get(media_type), ("", ""))[1]+ rich_sent_store.record_media(jid, result.message_id, [(file_path, mime or "application/octet-stream")])+ return result@_needs_bridgeasync def send_poll(self, chat_id: str, question: str, options: list[str], *, selectable_count: int = 1) -> SendResult:@@ -785,6 +799,27 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):print(f"[{self.name}] Failed to read document text: {e}", flush=True)return body+ def _quoted_media(self, data: Dict[str, Any], raw_reply_id: Any) -> list[tuple[str, str]]:+ """``(path, mime)`` for the quoted message's attachment, folded into this event's own media so the+ vision/audio pipeline sees it like a direct send. ``contextInfo.quotedMessage`` carries only a+ thumbnail stub, so the bridge resolves INBOUND quotes from its download cache (``quotedMediaUrls``,+ guarded like direct media: a rogue bridge could hand back /etc/passwd); quotes of OUR media (cron+ chart, generated image — any path we chose) resolve from the outbound index written by+ ``_send_media_to_bridge``."""+ quoted_type = str(data.get("quotedMediaType") or "").strip()+ accepted: list[tuple[str, str]] = []+ for path in data.get("quotedMediaUrls") or []:+ if not (isinstance(path, str) and os.path.isabs(path) and _is_allowed_bridge_path(path)):+ print(f"[{self.name}] Rejected quoted-media path outside cache dir: {path}", flush=True)+ continue+ accepted.append((path, _QUOTED_MIME_BY_BRIDGE_KIND.get(quoted_type, "application/octet-stream")))+ if not accepted and raw_reply_id is not None:+ from gateway import rich_sent_store+ accepted = rich_sent_store.lookup_media(data.get("chatId", ""), str(raw_reply_id))+ for path, _ in accepted:+ print(f"[{self.name}] Attached quoted-reply media: {path}", flush=True)+ return accepted+async def _build_message_event(self, data: Dict[str, Any]) -> Optional[MessageEvent]:"""Build a MessageEvent from bridge message data, downloading images to cache."""try:@@ -803,33 +838,9 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):quoted = bool(data.get("hasQuotedMessage"))raw_reply_id = data.get("quotedMessageId") if quoted else Noneif quoted:- # contextInfo.quotedMessage only ever carries a thumbnail-sized- # stub for media (or nothing for an uncaptioned attachment) —- # never a way to fetch the original file. The bridge resolves- # the quoted message's already-downloaded media via its own- # cache and hands back real local paths in quotedMediaUrls.- # Append them to this event's own media so the existing- # vision/audio pipeline (which reads media_urls/media_types)- # picks up the quoted attachment exactly like a direct one —- # no separate reply-media code path needed.- quoted_media_urls = data.get("quotedMediaUrls") or []- quoted_media_type = str(data.get("quotedMediaType") or "").strip()- _quoted_mime_map = {- "image": "image/jpeg",- "video": "video/mp4",- "gif": "video/mp4",- "audio": "audio/ogg",- "ptt": "audio/ogg",- "document": "application/octet-stream",- "sticker": "image/webp",- }- for _qurl in quoted_media_urls:- if not (isinstance(_qurl, str) and os.path.isabs(_qurl) and _is_allowed_bridge_path(_qurl)):- print(f"[{self.name}] Rejected quoted-media path outside cache dir: {_qurl}", flush=True)- continue- cached_urls.append(_qurl)- media_types.append(_quoted_mime_map.get(quoted_media_type, "application/octet-stream"))- print(f"[{self.name}] Attached quoted-reply media: {_qurl}", flush=True)+ for path, mime in self._quoted_media(data, raw_reply_id):+ cached_urls.append(path)+ media_types.append(mime)if msg_type == MessageType.DOCUMENT and cached_urls:body = self._inject_document_text(cached_urls, body)native_metadata = data.get("nativeMetadata")diff --git a/tests/gateway/test_whatsapp_cloud.py b/tests/gateway/test_whatsapp_cloud.pyindex 5e46c6341c1..2bbbcc4310d 100644--- a/tests/gateway/test_whatsapp_cloud.py+++ b/tests/gateway/test_whatsapp_cloud.py@@ -1400,3 +1400,29 @@ class TestReplyContextResolution:assert event.reply_to_text is Noneassert event.reply_to_is_own_message is False+ @pytest.mark.asyncio+ async def test_reply_to_bot_sent_image_attaches_the_file(self, tmp_path):+ """The bot sends an uncaptioned image (a cron job delivering a chart); the user quotes it+ and asks "what is this?". Meta's ``context`` carries only the wamid, so the bytes must come+ from the outbound index written at send time — otherwise the agent never sees the image."""+ adapter = _make_adapter()+ image = tmp_path / "chart.png"+ image.write_bytes(b"\x89PNG fake")+ adapter._upload_media = AsyncMock(return_value=("MEDIA-ID", None))+ adapter._post_messages = AsyncMock(return_value=([{"id": "wamid.BOT_IMG"}], None))+ adapter._http_client = MagicMock()++ sent = await adapter.send_image_file("15551234567", str(image))+ assert sent.success and sent.message_id == "wamid.BOT_IMG"++ event = await adapter._build_message_event_from_cloud(+ {"from": "15551234567", "id": "wamid.REPLY", "type": "text",+ "text": {"body": "what is this?"},+ "context": {"id": "wamid.BOT_IMG", "from": "15550000000"}},+ {"15551234567": "Alice"}, {"display_phone_number": "15550000000"},+ )+ assert event is not None+ assert event.reply_to_is_own_message is True+ assert event.media_urls == [str(image)]+ assert event.media_types == ["image/png"]+diff --git a/tests/gateway/test_whatsapp_formatting.py b/tests/gateway/test_whatsapp_formatting.pyindex 914e385e1ef..c97a28cc227 100644--- a/tests/gateway/test_whatsapp_formatting.py+++ b/tests/gateway/test_whatsapp_formatting.py@@ -302,6 +302,34 @@ class TestBridgeEventMetadata:assert event is not Noneassert "/etc/passwd" not in event.media_urls+ @pytest.mark.asyncio+ async def test_reply_to_bot_sent_image_resolves_from_outbound_index(self, tmp_path):+ """The bridge's quoted-media cache knows inbound messages only. A quote of an image WE sent+ (cron chart, generated plot) must resolve from the outbound index written at send time —+ otherwise "what is this?" under the bot's own image reaches the agent with no image."""+ adapter = _make_adapter()+ image = tmp_path / "chart.png" # a workspace path, deliberately NOT inside a cache dir+ image.write_bytes(b"\x89PNG fake")+ resp = MagicMock(status=200)+ resp.json = AsyncMock(return_value={"messageId": "BOT_IMG"})+ adapter._http_session.post = MagicMock(return_value=_AsyncCM(resp))++ sent = await adapter.send_image_file("15551234567", str(image))+ assert sent.success and sent.message_id == "BOT_IMG"++ event = await adapter._build_message_event({+ "messageId": "reply-1", "chatId": "[email protected]",+ "senderId": "[email protected]", "senderName": "Alice", "isGroup": False,+ "body": "what is this?", "hasMedia": False, "mediaUrls": [], "mediaType": "",+ "quotedMessageId": "BOT_IMG", "quotedParticipant": "[email protected]",+ "hasQuotedMessage": True, "quotedText": "", "quotedMediaUrls": [], "quotedMediaType": "",+ "botIds": ["[email protected]"],+ })+ assert event is not None+ assert event.reply_to_is_own_message is True+ assert event.media_urls == [str(image)]+ assert event.media_types == ["image/png"]+# ---------------------------------------------------------------------------# display_config tier classification