Skip to content

The agent that grows with you

fix(gateway): deliver a streamed reply's markdown images post-stream

686f6c612959e3d93a93
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index f0ca76d2162..b74239b3f6f 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -225,14 +225,14 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica
async def _deliver_media_from_response(
self, response: str, event: MessageEvent, adapter, thread_metadata: Optional[dict[str, Any]] = None
) -> None:
- """Deliver explicit MEDIA: tags from an already-streamed response (text already delivered).
+ """Deliver explicit attachments from an already-streamed response (text already delivered).
EXPLICIT-ONLY, unlike the non-streaming path in ``gateway/platforms/base.py``: a bare local
path in a streamed reply is shown text or stale inspected content, and promoting it sent
files the model never asked for. MEDIA tags are NOT deduped against prior turns (a final-reply
directive is a deliberate attach); stale auto-appended tags are deduped upstream.
- Only ``MEDIA:`` directives — the explicit attachment contract — trigger post-stream uploads. See
- #20834.
+ Explicit means ``MEDIA:`` directives and markdown/HTML image tags — the two contracts the
+ non-streaming chain turns into attachments. See #20834 and #141806.
"""
from urllib.parse import quote as _quote
with _log_suppressed(logging.WARNING, "Post-stream media extraction failed: %s"):
@@ -249,7 +249,11 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica
# the same filter removal on the non-streaming path in gateway/platforms/base.py. Bare local
# paths in an already-streamed reply are text the user has seen (or stale inspected content),
# not an attachment request.
- adapter.extract_images(cleaned)
+ # A markdown/HTML image tag IS an attachment request, though — the non-streaming chain turns it
+ # into a native attachment, so post-stream it has to be delivered here too. Discarding the
+ # extraction left a streamed reply that showed the tag as text and never sent the image
+ # (#141806).
+ url_images, _ = adapter.extract_images(cleaned)
_thread_meta = (
dict(thread_metadata)
if thread_metadata is not None
@@ -263,9 +267,13 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica
image_paths = [p for p, v in media_files if _is_photo(p, v)]
non_image_media = [(p, v) for p, v in media_files if not _is_photo(p, v)]
- if image_paths:
+ # Local images and URL images go out in one batch so a platform that bundles native
+ # multi-attachment sends (Signal) still gets a single call. ``[[as_document]]`` only
+ # applies to local files: a URL has no file to hand to send_document.
+ if image_paths or url_images:
try:
images = [(f"file://{_quote(p)}", "") for p in image_paths]
+ images.extend(url_images)
await adapter.send_multiple_images(chat_id=chat_id, images=images, metadata=_thread_meta)
except Exception as e:
logger.warning("[%s] Post-stream image batch delivery failed: %s", adapter.name, e)
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py
index 28b96d48bac..d0d40b23507 100644
--- a/gateway/stream_consumer.py
+++ b/gateway/stream_consumer.py
@@ -977,5 +977,16 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
# non-streaming paths share the same regex, so a tag is treated identically whichever path delivered the
# text.
def _clean_for_display(text: str) -> str:
- """Hide MEDIA:<path> / [[audio_as_voice]] directives; media is delivered post-stream."""
- return _BasePlatformAdapter.strip_media_directives_for_display(text)
+ """Hide MEDIA:<path> / [[audio_as_voice]] directives and markdown/HTML image tags; both are
+ delivered post-stream as native attachments.
+
+ Image tags go through the same ``extract_images`` split the non-streaming path uses
+ (``_extract_response_content``): once a tag becomes an attachment, the tag itself must not
+ also render as text — on Discord ``![alt](url)`` shows as ``!alt`` plus an unfurl (#141806).
+ Sharing the extractor keeps display and delivery in agreement, including its own fence
+ handling (#93724) once that lands.
+ """
+ _clean = _BasePlatformAdapter.strip_media_directives_for_display(text)
+ if '![' not in _clean and '<img' not in _clean:
+ return _clean
+ return _BasePlatformAdapter.extract_images(_clean)[1]
diff --git a/tests/gateway/test_streamed_markdown_images.py b/tests/gateway/test_streamed_markdown_images.py
new file mode 100644
index 00000000000..4b3730c9f45
--- /dev/null
+++ b/tests/gateway/test_streamed_markdown_images.py
@@ -0,0 +1,150 @@
+"""A streamed reply's markdown/HTML images must arrive as attachments (#141806).
+
+When streaming already delivered the answer, the gateway suppresses its normal final
+send, and with it the ``extract_images`` step that turns ``![alt](url)`` / ``<img src>``
+into a native attachment. A streamed reply that carried an image therefore showed the
+tag as text and never sent the picture. The post-stream rescan has to deliver the URLs,
+and the streamed display must not keep the literal tag on screen.
+"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import Platform
+from gateway.platforms.base import BasePlatformAdapter, SendResult
+from gateway.platforms.event import MessageEvent, MessageType
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource
+from gateway.stream_consumer import GatewayStreamConsumer
+
+
+def _event():
+ source = SessionSource(
+ platform=Platform.DISCORD,
+ chat_id="D123CHAN",
+ chat_type="group",
+ thread_id=None,
+ )
+ return MessageEvent(
+ text="hi",
+ message_type=MessageType.TEXT,
+ source=source,
+ message_id="171.000001",
+ )
+
+
+def _fake_runner(thread_meta):
+ return SimpleNamespace(
+ _thread_metadata_for_source=lambda source, anchor=None: thread_meta,
+ _reply_anchor_for_event=lambda event: None,
+ )
+
+
+def _adapter():
+ return SimpleNamespace(
+ name="test",
+ extract_media=BasePlatformAdapter.extract_media,
+ extract_images=BasePlatformAdapter.extract_images,
+ extract_local_files=BasePlatformAdapter.extract_local_files,
+ send_voice=AsyncMock(return_value=SendResult(success=True, message_id="voice")),
+ send_document=AsyncMock(return_value=SendResult(success=True, message_id="doc")),
+ send_image_file=AsyncMock(return_value=SendResult(success=True, message_id="image")),
+ send_video=AsyncMock(return_value=SendResult(success=True, message_id="video")),
+ send_multiple_images=AsyncMock(return_value=SendResult(success=True, message_id="imgs")),
+ )
+
+
+async def test_markdown_image_is_delivered_post_stream():
+ """The report's shape: the reply is only a markdown image."""
+ adapter = _adapter()
+
+ await GatewayRunner._deliver_media_from_response(
+ _fake_runner({}),
+ "![meme](https://api.memegen.link/images/drake/a/b.png)",
+ _event(),
+ adapter,
+ )
+
+ adapter.send_multiple_images.assert_awaited_once()
+ kwargs = adapter.send_multiple_images.await_args.kwargs
+ assert kwargs["chat_id"] == "D123CHAN"
+ assert kwargs["images"] == [("https://api.memegen.link/images/drake/a/b.png", "meme")]
+
+
+async def test_html_image_is_delivered_post_stream():
+ adapter = _adapter()
+
+ await GatewayRunner._deliver_media_from_response(
+ _fake_runner({}),
+ 'Chart follows.\n<img src="https://example.com/chart.png" />',
+ _event(),
+ adapter,
+ )
+
+ adapter.send_multiple_images.assert_awaited_once()
+ assert adapter.send_multiple_images.await_args.kwargs["images"] == [
+ ("https://example.com/chart.png", "")
+ ]
+
+
+async def test_url_image_and_media_file_share_one_batch(tmp_path, monkeypatch):
+ """A reply with both contracts still produces a single attachment call."""
+ root = tmp_path / "media-cache"
+ media_file = root / "chart.png"
+ media_file.parent.mkdir(parents=True, exist_ok=True)
+ media_file.write_bytes(b"media")
+ monkeypatch.setattr(
+ "gateway.platforms.base.MEDIA_DELIVERY_SAFE_ROOTS",
+ (root,),
+ )
+ resolved = media_file.resolve()
+ adapter = _adapter()
+
+ await GatewayRunner._deliver_media_from_response(
+ _fake_runner({}),
+ f"Two pictures.\nMEDIA:{resolved}\n![remote](https://example.com/remote.png)",
+ _event(),
+ adapter,
+ )
+
+ adapter.send_multiple_images.assert_awaited_once()
+ images = adapter.send_multiple_images.await_args.kwargs["images"]
+ assert len(images) == 2
+ assert any(url.endswith("remote.png") for url, _ in images)
+ assert any(url.startswith("file://") for url, _ in images)
+
+
+async def test_plain_link_is_not_delivered():
+ """Only the image form is an attachment; a plain markdown link stays text."""
+ adapter = _adapter()
+
+ await GatewayRunner._deliver_media_from_response(
+ _fake_runner({}),
+ "See [the chart](https://example.com/chart.png) for details.",
+ _event(),
+ adapter,
+ )
+
+ adapter.send_multiple_images.assert_not_awaited()
+ adapter.send_document.assert_not_awaited()
+
+
+def test_display_hides_the_image_tag_and_keeps_the_prose():
+ shown = GatewayStreamConsumer._clean_for_display(
+ "Here it is:\n\n![meme](https://api.memegen.link/images/drake/a/b.png)\n\nEnjoy."
+ )
+
+ assert "![meme]" not in shown
+ assert "Here it is:" in shown
+ assert "Enjoy." in shown
+
+
+def test_display_leaves_plain_text_untouched():
+ text = "No pictures here, just [a link](https://example.com/page)."
+ assert GatewayStreamConsumer._clean_for_display(text) == text