The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(platforms): set media_text_inlined in the sibling document paths
teknium17f2b64f7a25d
diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex 3e82233d358..a409f009bf9 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -933,9 +933,11 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return [local_path], [dl_mime or inbound_mime or "application/octet-stream"], body@staticmethod- def _inject_document_text(media_urls: list[str], body: str) -> str:- """Prepend text-readable document contents (≤100KB) to the body."""- for doc in map(Path, media_urls):+ def _inject_document_text(media_urls: list[str], body: str) -> tuple[str, list[bool]]:+ """Prepend text-readable document contents (≤100KB) to the body; returns+ ``(body, media_text_inlined)`` with one flag per ``media_urls`` entry (True = injected)."""+ inlined = [False] * len(media_urls)+ for i, doc in enumerate(map(Path, media_urls)):if doc.suffix.lower() not in _TEXT_INJECT_EXTS:continuetry:@@ -945,9 +947,10 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):continueinjection = f"[Content of {doc.name}]:\n{doc.read_text(encoding='utf-8', errors='replace')}"body = f"{injection}\n\n{body}" if body else injection+ inlined[i] = Trueexcept OSError:logger.exception("[whatsapp_cloud] failed to read document text: %s", doc)- return body+ return body, inlinedasync def _build_message_event_from_cloud(self, raw_message: Dict[str, Any], contacts_by_waid: Dict[str, str], metadata: Dict[str, Any],@@ -978,11 +981,11 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return Noneif not self._should_process_message({"chatId": chat_id, "senderId": sender_id, "isGroup": False, "body": body}):return None- media_urls, media_types = [], []+ media_urls, media_types, media_text_inlined = [], [], []if msg_type_str in _INBOUND_MEDIA_KINDS: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)+ body, media_text_inlined = self._inject_document_text(media_urls, body)# 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.@@ -1014,5 +1017,5 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):),raw_message=raw_message, message_id=wamid, reply_to_message_id=reply_to_id,reply_to_text=reply_to_text, reply_to_is_own_message=reply_to_is_own,- media_urls=media_urls, media_types=media_types,+ media_urls=media_urls, media_types=media_types, media_text_inlined=media_text_inlined,)diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 676432eaaed..52bfff7188d 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -5772,9 +5772,12 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):return att.urlasync def _collect_attachment_media(self, all_attachments: list) -> tuple:- """Cache every attachment and return ``(media_urls, media_types, pending_text_injection)``."""+ """Cache every attachment and return ``(media_urls, media_types, media_text_inlined,+ pending_text_injection)``; ``media_text_inlined[i]`` is True only when attachment ``i``'s+ text was injected."""media_urls = []media_types = []+ media_text_inlined: list = []pending_text_injection: Optional[str] = Nonefor att in all_attachments:content_type = att.content_type or "unknown"@@ -5782,10 +5785,12 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):media_urls.append(await self._cache_simple_media(att, content_type, "image", {".jpg", ".jpeg", ".png", ".gif", ".webp"}, ".jpg"))media_types.append(content_type)+ media_text_inlined.append(False)elif content_type.startswith("audio/"):media_urls.append(await self._cache_simple_media(att, content_type, "audio", {".ogg", ".mp3", ".wav", ".webm", ".m4a"}, ".ogg"))media_types.append(content_type)+ media_text_inlined.append(False)else:ext = ""if att.filename:@@ -5815,6 +5820,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):)media_urls.append(cached_path)media_types.append(doc_mime)+ media_text_inlined.append(False)logger.info("[Discord] Cached user %s: %s", "document" if in_allowlist else "attachment", cached_path,)@@ -5833,11 +5839,12 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):pending_text_injection = f"{pending_text_injection}\n\n{injection}"else:pending_text_injection = injection+ media_text_inlined[-1] = Trueexcept UnicodeDecodeError:passexcept Exception as e:logger.warning("[Discord] Failed to cache document %s: %s", att.filename, e, exc_info=True)- return media_urls, media_types, pending_text_injection+ return media_urls, media_types, media_text_inlined, pending_text_injectiondef _attachment_message_type(self, att: Any) -> MessageType:"""MessageType from the first attachment's MIME. Any non-media (or untyped) attachment@@ -6020,7 +6027,8 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):or self._derive_auto_thread_name(message.content or "")) if auto_threaded_channel is not None else None,)- media_urls, media_types, pending_text_injection = await self._collect_attachment_media(all_attachments)+ media_urls, media_types, media_text_inlined, pending_text_injection = await self._collect_attachment_media(+ all_attachments)event_text = normalized_contentif pending_text_injection:event_text = f"{pending_text_injection}\n\n{event_text}" if event_text else pending_text_injection@@ -6067,6 +6075,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):event = MessageEvent(text=event_text, message_type=msg_type, source=source, raw_message=message,message_id=str(message.id), media_urls=media_urls, media_types=media_types,+ media_text_inlined=media_text_inlined,reply_to_message_id=reply_to_id, reply_to_text=reply_to_text,timestamp=message.created_at, auto_skill=_skills, channel_prompt=_channel_prompt,channel_context=_channel_context,diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex 330099917ee..ea8374041f5 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -4506,13 +4506,13 @@ class SlackAdapter(BasePlatformAdapter):team_id=team_id, is_thread_reply=is_thread_reply, is_mentioned=is_mentioned,is_dm=is_dm)# Thread-root media is delivered ahead of the trigger message's own files.- media_urls, media_types, text = await self._collect_inbound_media(+ media_urls, media_types, media_text_inlined, text = await self._collect_inbound_media(event, channel_id, team_id, text, thread_root_media_urls, thread_root_media_types)msg_event = await self._build_message_event(event, text=text, original_text=original_text, command_probe_text=command_probe_text,is_command_text=is_command_text, channel_id=channel_id, team_id=team_id, ts=ts,user_id=user_id, thread_ts=thread_ts, is_dm=is_dm, media_urls=media_urls,- media_types=media_types, channel_context=channel_context)+ media_types=media_types, media_text_inlined=media_text_inlined, channel_context=channel_context)# React only when directly addressed; MPIMs are shared, so they need a# mention like any channel.if (is_one_to_one_dm or is_mentioned) and self._reactions_enabled():@@ -4532,7 +4532,7 @@ class SlackAdapter(BasePlatformAdapter):self, event: dict, *, text: str, original_text: str, command_probe_text: str,is_command_text: bool, channel_id: str, team_id: str, ts: str, user_id: str,thread_ts: Optional[str], is_dm: bool, media_urls: List[str], media_types: List[str],- channel_context: Optional[str]) -> MessageEvent:+ media_text_inlined: List[bool], channel_context: Optional[str]) -> MessageEvent:"""Resolve names, title the DM thread, and build the ``MessageEvent``. Commands are restoredfrom canonical input: the parser needs the token at char zero and enrichment (blocks,unfurls, file text, history) must never mutate arguments."""@@ -4569,6 +4569,7 @@ class SlackAdapter(BasePlatformAdapter):message_id=ts,media_urls=media_urls,media_types=media_types,+ media_text_inlined=media_text_inlined,reply_to_message_id=thread_ts if thread_ts != ts else None,channel_prompt=self._channel_prompt_with_identity(channel_id, team_id),channel_context=channel_context,@@ -4690,12 +4691,14 @@ class SlackAdapter(BasePlatformAdapter):async def _collect_inbound_media(self, event: dict, channel_id: str, team_id: str, text: str,thread_root_media_urls: List[str], thread_root_media_types: List[str],- ) -> Tuple[List[str], List[str], str]:- """Download/cache ``event["files"]`` → ``(media_urls, media_types, text)``; root images- lead. Small text-like docs are injected into ``text`` (gated on ext/MIME, not blind UTF-8- decode — PDF/zip headers decode). Failures are prepended as an attachment notice."""+ ) -> Tuple[List[str], List[str], List[bool], str]:+ """Download/cache ``event["files"]`` → ``(media_urls, media_types, media_text_inlined, text)``;+ root images lead. Small text-like docs are injected into ``text`` (gated on ext/MIME, not blind+ UTF-8 decode — PDF/zip headers decode) and flagged True in ``media_text_inlined``. Failures are+ prepended as an attachment notice."""media_urls = list(thread_root_media_urls)media_types = list(thread_root_media_types)+ media_text_inlined: List[bool] = [False] * len(media_urls)notices: List[str] = []for f in event.get("files", []):if f.get("file_access") == "check_file_info":@@ -4714,6 +4717,7 @@ class SlackAdapter(BasePlatformAdapter):cached_path, media_type, injection = cachedmedia_urls.append(cached_path)media_types.append(media_type)+ media_text_inlined.append(bool(injection))if injection:text = f"{injection}\n\n{text}" if text else injectionexcept Exception as e: # pragma: no cover - defensive logging@@ -4723,7 +4727,7 @@ class SlackAdapter(BasePlatformAdapter):if notices:notice_block = "[Slack attachment notice]\n" + "\n".join(f"- {n}" for n in notices)text = f"{notice_block}\n\n{text}" if text else notice_block- return media_urls, media_types, text+ return media_urls, media_types, media_text_inlined, text# ----- Approval button support (Block Kit) -----diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 76f76013944..f55bb5a9ae7 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -6298,6 +6298,7 @@ class TelegramAdapter(BasePlatformAdapter):return await self._dispatch_with_text(event, f"Document '{display}' could not be cached.")event.media_urls = [cached.path]event.media_types = [cached.media_type]+ event.media_text_inlined = [False] # flipped below once the text is actually injectedif cached.kind == "audio":event.message_type = MessageType.AUDIOlogger.info("[Telegram] Cached user %s at %s (%s)", cached.kind, cached.path, cached.media_type)@@ -6311,6 +6312,7 @@ class TelegramAdapter(BasePlatformAdapter):display_name = re.sub(r'[^\w.\- ]', '_', original_filename or f"document{ext or '.txt'}")injection = f"[Content of {display_name}]:\n{text_content}"event.text = f"{injection}\n\n{event.text}" if event.text else injection+ event.media_text_inlined = [True]except UnicodeDecodeError:pass # binary — agent has the cached pathexcept Exception as e:diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 21d97ed9612..bab4525237b 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -777,9 +777,11 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):accepted.append((url, "unknown"))return [u for u, _ in accepted], [m for _, m in accepted]- def _inject_document_text(self, cached_urls: list, body: str) -> str:- """Prepend text-readable document contents (≤100KB) so the agent reads them inline."""- for doc_path in cached_urls:+ def _inject_document_text(self, cached_urls: list, body: str) -> tuple[str, list[bool]]:+ """Prepend text-readable document contents (≤100KB) so the agent reads them inline; returns+ ``(body, media_text_inlined)`` with one flag per ``cached_urls`` entry (True = injected)."""+ inlined = [False] * len(cached_urls)+ for i, doc_path in enumerate(cached_urls):p = Path(doc_path)if p.suffix.lower() not in _TEXT_INJECT_EXTS:continue@@ -792,10 +794,11 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):parts = p.name.split("_", 2) # strip the doc_<hex>_ prefix for displayinjection = f"[Content of {parts[2] if len(parts) >= 3 else p.name}]:\n{content}"body = f"{injection}\n\n{body}" if body else injection+ inlined[i] = Trueprint(f"[{self.name}] Injected text content from: {doc_path}", flush=True)except Exception as e:print(f"[{self.name}] Failed to read document text: {e}", flush=True)- return body+ return body, inlineddef _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@@ -840,8 +843,9 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):for path, mime in self._quoted_media(data, raw_reply_id):cached_urls.append(path)media_types.append(mime)+ media_text_inlined: list[bool] = []if msg_type == MessageType.DOCUMENT and cached_urls:- body = self._inject_document_text(cached_urls, body)+ body, media_text_inlined = self._inject_document_text(cached_urls, body)native_metadata = data.get("nativeMetadata")metadata: Dict[str, Any] = {k: v for k, v in (("whatsapp_native_type", str(data.get("nativeType") or "").strip()),@@ -855,7 +859,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):body = f"{_OWNER_REPLY_PREFIX}{body}"return MessageEvent(text=body, message_type=msg_type, source=source, raw_message=data, message_id=data.get("messageId"),- media_urls=cached_urls, media_types=media_types, metadata=metadata,+ media_urls=cached_urls, media_types=media_types, media_text_inlined=media_text_inlined, metadata=metadata,reply_to_message_id=str(raw_reply_id) if raw_reply_id is not None else None,reply_to_text=str(data.get("quotedText") or "").strip() or None,reply_to_author_id=(self._normalize_whatsapp_id(data.get("quotedParticipant")) or None) if quoted else None,diff --git a/tests/gateway/test_discord_document_handling.py b/tests/gateway/test_discord_document_handling.pyindex 8abc0f8e230..56f1642eaae 100644--- a/tests/gateway/test_discord_document_handling.py+++ b/tests/gateway/test_discord_document_handling.py@@ -233,6 +233,22 @@ class TestIncomingDocumentHandling:assert os.path.exists(event.media_urls[0])assert "[Content of" not in (event.text or "")+ @pytest.mark.asyncio+ @pytest.mark.parametrize("content, inlined", [(b"small text", True), (b"x" * (200 * 1024), False)], ids=["small", "large"])+ async def test_document_marks_media_text_inlined(self, adapter, content, inlined):+ """The per-attachment flag must track whether the text was injected, so the document+ note never claims the content is inlined when the >100 KB gate skipped it."""+ with _mock_aiohttp_download(content):+ msg = make_message(+ attachments=[make_attachment(filename="notes.txt", content_type="text/plain", size=len(content))],+ content="",+ )+ await adapter._handle_message(msg)++ event = adapter.handle_message.call_args[0][0]+ assert ("[Content of" in (event.text or "")) is inlined+ assert event.media_text_inlined == [inlined]+@pytest.mark.asyncioasync def test_multiple_text_files_both_injected(self, adapter):"""Two text file attachments should both be injected into event.text in order."""diff --git a/tests/gateway/test_slack.py b/tests/gateway/test_slack.pyindex c2b22dbab6a..851acf50052 100644--- a/tests/gateway/test_slack.py+++ b/tests/gateway/test_slack.py@@ -1779,6 +1779,32 @@ class TestIncomingDocumentHandling:assert len(msg_event.media_urls) == 1assert "[Content of" not in (msg_event.text or "")+ @pytest.mark.asyncio+ @pytest.mark.parametrize("content, inlined", [(b"small text", True), (b"x" * (200 * 1024), False)], ids=["small", "large"])+ async def test_document_marks_media_text_inlined(self, adapter, content, inlined):+ """The per-attachment flag must track whether the text was injected, so the document+ note never claims the content is inlined when the >100 KB gate skipped it."""+ with patch.object(+ adapter, "_download_slack_file_bytes", new_callable=AsyncMock+ ) as dl:+ dl.return_value = content+ event = self._make_event(+ files=[+ {+ "mimetype": "text/plain",+ "name": "notes.txt",+ "url_private_download": "https://files.slack.com/notes.txt",+ "size": len(content),+ }+ ],+ text="",+ )+ await adapter._handle_slack_message(event)++ msg_event = adapter.handle_message.call_args[0][0]+ assert ("[Content of" in (msg_event.text or "")) is inlined+ assert msg_event.media_text_inlined == [inlined]+@pytest.mark.asyncioasync def test_unauthorized_message_does_not_fetch_file_info(diff --git a/tests/gateway/test_telegram_documents.py b/tests/gateway/test_telegram_documents.pyindex ef29f113037..1eba4bbeb3d 100644--- a/tests/gateway/test_telegram_documents.py+++ b/tests/gateway/test_telegram_documents.py@@ -226,6 +226,20 @@ class TestDocumentDownloadBlock:# Content should NOT be injectedassert "[Content of" not in (event.text or "")+ @pytest.mark.asyncio+ @pytest.mark.parametrize("content, inlined", [(b"small text", True), (b"x" * (200 * 1024), False)], ids=["small", "large"])+ async def test_document_marks_media_text_inlined(self, adapter, content, inlined):+ """The per-attachment flag must track whether the text was injected, so the document+ note never claims the content is inlined when the >100 KB gate skipped it."""+ doc = _make_document(+ file_name="notes.txt", mime_type="text/plain",+ file_size=len(content), file_obj=_make_file_obj(content),+ )+ await adapter._handle_media_message(_make_update(_make_message(document=doc)), MagicMock())+ event = adapter.handle_message.call_args[0][0]+ assert ("[Content of" in event.text) is inlined+ assert event.media_text_inlined == [inlined]+@pytest.mark.asyncioasync def test_document_cache_failure_replies_and_signals_agent(self, adapter):diff --git a/tests/gateway/test_whatsapp_cloud.py b/tests/gateway/test_whatsapp_cloud.pyindex cd9056fd228..e2ef201f932 100644--- a/tests/gateway/test_whatsapp_cloud.py+++ b/tests/gateway/test_whatsapp_cloud.py@@ -873,6 +873,30 @@ class TestInboundMediaDispatch:# File still available in media_urls for the agent's other toolsassert len(event.media_urls) == 1+ @pytest.mark.asyncio+ @pytest.mark.parametrize("content, inlined", [(b"small text", True), (b"x" * (200 * 1024), False)], ids=["small", "large"])+ async def test_document_marks_media_text_inlined(self, tmp_path, content, inlined):+ """The per-attachment flag must track whether the text was injected, so the document+ note never claims the content is inlined when the >100 KB gate skipped it."""+ adapter = _make_adapter(app_secret="key")+ adapter._http_client = MagicMock()+ adapter._http_client.get = AsyncMock(side_effect=[+ MagicMock(status_code=200, json=MagicMock(return_value={+ "url": "https://lookaside.fbsbx.com/whatsapp/m/doc", "mime_type": "text/plain"})),+ MagicMock(status_code=200, content=content),+ ])+ raw_message = {+ "from": "1555", "id": "wamid.doc2", "timestamp": "0", "type": "document",+ "document": {"id": "media_doc_abc", "mime_type": "text/plain", "filename": "notes.txt"},+ }+ from gateway.platforms import whatsapp_cloud as wac+ with _patch.object(wac, "_INBOUND_MEDIA_CACHE", tmp_path):+ event = await adapter._build_message_event_from_cloud(+ raw_message, {"1555": "U"}, {"phone_number_id": "1"})++ assert ("[Content of" in (event.text or "")) is inlined+ assert event.media_text_inlined == [inlined]+# ---------------------------------------------------------------------------# Group-shaped message guarddiff --git a/tests/gateway/test_whatsapp_formatting.py b/tests/gateway/test_whatsapp_formatting.pyindex c97a28cc227..fbbbc34bec0 100644--- a/tests/gateway/test_whatsapp_formatting.py+++ b/tests/gateway/test_whatsapp_formatting.py@@ -265,6 +265,27 @@ class TestBridgeEventMetadata:idx = event.media_urls.index(str(quoted_image_path))assert event.media_types[idx] == "image/jpeg"+ @pytest.mark.asyncio+ @pytest.mark.parametrize("content, inlined", [("small text", True), ("x" * (200 * 1024), False)], ids=["small", "large"])+ async def test_document_marks_media_text_inlined(self, tmp_path, monkeypatch, content, inlined):+ """The per-attachment flag must track whether the text was injected, so the document+ note never claims the content is inlined when the >100 KB gate skipped it."""+ adapter = _make_adapter()+ doc_path = tmp_path / "doc_abc_notes.txt"+ doc_path.write_text(content, encoding="utf-8")+ from plugins.platforms.whatsapp import adapter as adapter_module+ monkeypatch.setattr(adapter_module, "_is_allowed_bridge_path", lambda url: True)++ event = await adapter._build_message_event({+ "messageId": "doc-msg", "chatId": "[email protected]",+ "senderId": "[email protected]", "senderName": "Ananya", "isGroup": False,+ "body": "", "hasMedia": True, "mediaUrls": [str(doc_path)], "mediaType": "document",+ })++ assert event is not None+ assert ("[Content of" in (event.text or "")) is inlined+ assert event.media_text_inlined == [inlined]+@pytest.mark.asyncioasync def test_quoted_media_path_outside_cache_dir_is_rejected(self, monkeypatch):# _is_allowed_bridge_path guards against a compromised/buggy bridge