Skip to content

The agent that grows with you

fix(gateway): stream image tags prefix-stably and drop them from queued text

Teknium01185213a354
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index b1ffb8dd522..f746f5bdaf5 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -1264,6 +1264,11 @@ _MEDIA_EXT_ALTERNATION = "|".join(sorted((e.lstrip(".") for e in MEDIA_DELIVERY_
# attachment is silently dropped (#88038).
_MEDIA_CJK_TERMINATORS = "()〈〉《》:,。;!?、\u201c\u201d\u2018\u2019【】"
+# Image tags ``extract_images`` turns into attachments (the streamed display hides the same tags).
+MD_IMAGE_TAG_PATTERN = r'!\[([^\]]*)\]\((https?://[^\s\)]+)\)'
+HTML_IMAGE_TAG_PATTERN = r'<img\s+src=["\']?(https?://[^\s"\'<>]+)["\']?\s*/?>\s*(?:</img>)?'
+_IMAGE_URL_MARKERS = ('.png', '.jpg', '.jpeg', '.gif', '.webp', 'fal.media', 'fal-cdn', 'replicate.delivery')
+
MEDIA_TAG_CLEANUP_RE = re.compile(
r'''[`"'*_]{0,3}MEDIA:\s*'''
r'''(?P<path>`[^`\n]+?`|"[^"\n]+?"|'[^'\n]+?'|'''
@@ -3009,15 +3014,10 @@ class BasePlatformAdapter(ABC):
def extract_images(content: str) -> tuple[list[tuple[str, str]], str]:
"""Extract ``![alt](url)`` and ``<img src=...>`` image URLs from a response;
returns ``([(url, alt_text), ...], content with those tags removed)``."""
- md_pattern = r'!\[([^\]]*)\]\((https?://[^\s\)]+)\)'
- # <img src="url"> / <img src="url"></img> / <img src="url"/>
- html_pattern = r'<img\s+src=["\']?(https?://[^\s"\'<>]+)["\']?\s*/?>\s*(?:</img>)?'
- # Only extract URLs that look like actual images.
- markers = ('.png', '.jpg', '.jpeg', '.gif', '.webp', 'fal.media', 'fal-cdn',
- 'replicate.delivery')
+ md_pattern, html_pattern = MD_IMAGE_TAG_PATTERN, HTML_IMAGE_TAG_PATTERN
images = [(m.group(2), m.group(1)) for m in re.finditer(md_pattern, content)
if any(m.group(2).lower().endswith(ext) or ext in m.group(2).lower()
- for ext in markers)]
+ for ext in _IMAGE_URL_MARKERS)] # only URLs that look like actual images
images.extend((match.group(1), "") for match in re.finditer(html_pattern, content))
if not images:
return images, content
diff --git a/gateway/run.py b/gateway/run.py
index 69a3d8d0b6d..3b79fcb8d75 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -2779,13 +2779,11 @@ def _is_control_interrupt_message(message: Optional[str]) -> bool:
def _strip_response_attachments_for_direct_send(response: str, adapter) -> str:
"""Return the visible text portion of a response before direct send().
- Only explicit ``MEDIA:`` attachments are stripped; bare paths/URLs stay visible. No broad regex after
- ``extract_media()``: it deliberately preserves protected code spans and unvalidated tags.
-
- Queued follow-up resends only replay explicit ``MEDIA:`` attachments in this path. Keep bare local paths
- and ordinary image URLs visible because the post-stream uploader intentionally ignores them (#20834).
+ Explicit ``MEDIA:`` attachments and the image tags ``extract_images`` attaches are stripped, because
+ the post-stream uploader delivers both; bare local paths stay visible (it ignores them, #20834). No
+ broad regex after ``extract_media()``: it deliberately preserves protected code spans and unvalidated tags.
"""
- _, cleaned = adapter.extract_media(response)
+ _, cleaned = BasePlatformAdapter.extract_images(adapter.extract_media(response)[1])
return cleaned.replace("[[audio_as_voice]]", "").replace("[[as_document]]", "").strip()
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py
index d0d40b23507..af5dfcd2e40 100644
--- a/gateway/stream_consumer.py
+++ b/gateway/stream_consumer.py
@@ -30,7 +30,7 @@ from gateway.config import (
from gateway.response_filters import (
is_intentional_silence_response as _is_intentional_silence_response,
is_partial_silence_marker as _is_partial_silence_marker)
-from gateway.stream_consumer_directives import has_pending_media_directive
+from gateway.stream_consumer_directives import has_pending_media_directive, strip_image_tags_for_display
from gateway.stream_consumer_fences import ensure_closed_code_fences
from gateway.stream_consumer_transport import StreamTransportMixin
from gateway.stream_consumer_fallback import StreamFallbackMixin
@@ -980,13 +980,9 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
"""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.
+ Image tags are the ones the non-streaming path's ``extract_images`` split attaches: once a
+ tag becomes an attachment it must not also render as text — on Discord ``![alt](url)``
+ shows as ``!alt`` plus an unfurl (#141806). The tag is removed without trimming the text
+ around it, so interim frames stay prefix-stable.
"""
- _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]
+ return strip_image_tags_for_display(_BasePlatformAdapter.strip_media_directives_for_display(text))
diff --git a/gateway/stream_consumer_directives.py b/gateway/stream_consumer_directives.py
index 23817622270..822e0ccd2e4 100644
--- a/gateway/stream_consumer_directives.py
+++ b/gateway/stream_consumer_directives.py
@@ -1,9 +1,12 @@
-"""Hold-back check for delivery directives still being streamed (``MEDIA:<path>``, ``[[…]]`` flags)."""
+"""Hold-back check for attachments still being streamed: ``MEDIA:<path>``, ``[[…]]`` flags and
+markdown/HTML image tags (the display cleaner hides each one only once it is complete)."""
from __future__ import annotations
import re
+from gateway.platforms.base import HTML_IMAGE_TAG_PATTERN, MD_IMAGE_TAG_PATTERN, BasePlatformAdapter
+
# A delivery directive still being typed on the open (last) line: "MEDIA:" the cleaner has not
# stripped yet whose remainder can still become a path (MEDIA_TAG_CLEANUP_RE's openers: a quote,
# ~/, /, a drive letter), or a prefix of "MEDIA" not glued to a preceding letter or digit. A
@@ -15,16 +18,44 @@ _PENDING_MEDIA_RE = re.compile(
re.IGNORECASE)
_PENDING_FLAG_RE = re.compile(r"\[\[?[A-Za-z_]*\]?$")
_STREAM_FLAGS = ("[[audio_as_voice]]", "[[as_document]]")
+# An image tag still being typed (``extract_images`` hides the complete one): ``![alt``,
+# ``![alt](https://ho`` or ``<img src="…``. A bare "!" or "<" counts only at the start of a word,
+# so prose exclamations ("Great!") keep streaming. Whitespace in the URL ends the hold: that tag is
+# never extracted, so it stays visible either way.
+_PENDING_IMAGE_RE = re.compile(
+ r"""!\[[^\]\n]*(?:\](?:\([^)\s]*)?)?$|(?<!\S)!$"""
+ r"""|<img\s[^>\n]*$|(?<!\S)<(?:i(?:m(?:g)?)?)?$""",
+ re.IGNORECASE)
+
+
+def strip_image_tags_for_display(text: str) -> str:
+ """Hide the image tags ``extract_images`` delivers as attachments post-stream.
+
+ Each tag goes with the spaces and up to two line breaks after it, and nothing else is trimmed
+ or collapsed: an interim frame must stay a prefix of the next one, so text in front of the tag
+ (already shown) is never rewritten.
+ """
+ if "![" not in text and "<img" not in text:
+ return text
+ images, _ = BasePlatformAdapter.extract_images(text)
+ if not images:
+ return text
+ urls = {url for url, _ in images}
+ for pattern, url_group in ((MD_IMAGE_TAG_PATTERN, 2), (HTML_IMAGE_TAG_PATTERN, 1)):
+ text = re.sub(f"(?:{pattern})[ \\t]*(?:\\r?\\n){{0,2}}",
+ lambda m, g=url_group: "" if m.group(g) in urls else m.group(0), text)
+ return text
def has_pending_media_directive(cleaned: str) -> bool:
- """True while the open line of cleaned streamed text may still become a delivery directive.
+ """True while the open line of cleaned streamed text may still become a hidden attachment.
- Complete deliverable tags are already gone from *cleaned*, so a ``MEDIA:`` left there is
- unfinished or undeliverable; the final (non-interim) flush still shows the latter.
+ Complete deliverable tags are already gone from *cleaned*, so a ``MEDIA:`` or image tag left
+ there is unfinished or undeliverable; the final (non-interim) flush still shows the latter.
+ Showing the unfinished part and hiding it later would break prefix-stable draft frames.
"""
line = cleaned.rsplit("\n", 1)[-1]
- if _PENDING_MEDIA_RE.search(line):
+ if _PENDING_MEDIA_RE.search(line) or _PENDING_IMAGE_RE.search(line):
return True
flag = _PENDING_FLAG_RE.search(line)
return bool(flag) and any(f.startswith(flag.group(0)) for f in _STREAM_FLAGS)
diff --git a/tests/gateway/test_streamed_markdown_images.py b/tests/gateway/test_streamed_markdown_images.py
index 4b3730c9f45..8bcf24ee084 100644
--- a/tests/gateway/test_streamed_markdown_images.py
+++ b/tests/gateway/test_streamed_markdown_images.py
@@ -7,6 +7,7 @@ tag as text and never sent the picture. The post-stream rescan has to deliver th
and the streamed display must not keep the literal tag on screen.
"""
+import itertools
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -148,3 +149,75 @@ def test_display_hides_the_image_tag_and_keeps_the_prose():
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
+
+
+async def _stream_frames(deltas):
+ """Run a real consumer over *deltas* (every chunk edit-eligible); return the shown frames."""
+ import asyncio
+ from unittest.mock import MagicMock
+
+ from gateway.stream_consumer import StreamConsumerConfig
+ from tests.waiting import async_wait_until
+
+ adapter = MagicMock()
+ frames = []
+
+ async def _send(**kw):
+ frames.append(kw["content"])
+ return SimpleNamespace(success=True, message_id="m1")
+
+ async def _edit(**kw):
+ frames.append(kw["content"])
+ return SimpleNamespace(success=True)
+
+ adapter.send, adapter.edit_message = _send, _edit
+ adapter.MAX_MESSAGE_LENGTH = 4096
+ consumer = GatewayStreamConsumer(adapter, "chat_1", StreamConsumerConfig(edit_interval=0.0, buffer_threshold=1))
+ task = asyncio.create_task(consumer.run())
+ seen = ""
+ for delta in deltas:
+ consumer.on_delta(delta)
+ seen += delta
+ await async_wait_until(lambda: consumer._accumulated.endswith(seen[-8:]) and consumer._queue.empty())
+ for _ in range(5):
+ await asyncio.sleep(0)
+ consumer.finish()
+ await task
+ cursor = (consumer.cfg.cursor or "").strip()
+ return [f.replace(cursor, "") if cursor else f for f in frames]
+
+
+async def test_streamed_image_tag_never_shows_and_frames_stay_prefix_stable():
+ """No frame shows any part of the tag, and each frame extends the previous one: showing
+ ``![barrel](https://ex`` and removing it later would break prefix-stable draft frames."""
+ frames = await _stream_frames([
+ "Here is the render.\n\n!", "[barrel ren", "der](https://exa", "mple.com/r/b",
+ "arrel.png)", "\n\nWant another ", "angle?"])
+
+ assert frames, "nothing was streamed"
+ for frame in frames:
+ assert "![" not in frame and "example.com" not in frame and "](" not in frame, frame
+ interim = [f.rstrip() for f in frames[:-1]]
+ for prev, nxt in itertools.pairwise(interim):
+ assert nxt.startswith(prev), (prev, nxt)
+ assert frames[-1].strip() == "Here is the render.\n\nWant another angle?"
+
+
+async def test_queued_lane_sends_the_text_without_the_tag_and_the_image_once():
+ """The queued follow-up lane sends the text itself, then runs the post-stream uploader: the
+ tag it now attaches must not also stay in the text (one picture, no literal tag)."""
+ adapter = _adapter()
+ adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="t1"))
+ source = _event().source
+
+ await GatewayRunner._deliver_queued_first_response(
+ object.__new__(GatewayRunner), "Done.\n\n![chart](https://example.com/chart.png)",
+ source=source, adapter=adapter, metadata={}, event_message_id=None,
+ text_already_delivered=False, deliver_media=True)
+
+ adapter.send.assert_awaited_once()
+ assert adapter.send.await_args.args[1] == "Done."
+ adapter.send_multiple_images.assert_awaited_once()
+ assert adapter.send_multiple_images.await_args.kwargs["images"] == [("https://example.com/chart.png", "chart")]