Skip to content

The agent that grows with you

fix(extract_media): dedupe identical MEDIA tags

StartupBrosb129a72e0d40
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index e0437b0381f..3de61299f47 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -3897,17 +3897,23 @@ class BasePlatformAdapter(ABC):
# stay valid; chaining them masks the union of both protected regions.
scan_content = BasePlatformAdapter._mask_protected_spans(content)
scan_content = BasePlatformAdapter._mask_json_string_media(scan_content)
+ # Dedupe on the expanded path (first occurrence wins) so the same file
+ # referenced twice in one response — e.g. a MEDIA tag inline AND in a
+ # summary footer — is uploaded once, not twice (#29131).
+ seen_paths: set = set()
for match in media_pattern.finditer(scan_content):
path = _normalize_media_tag_path(match.group("path"))
if path:
try:
- media.append((os.path.expanduser(path), has_voice_tag))
+ expanded = os.path.expanduser(path)
except (OSError, RuntimeError, ValueError):
# Skip a crafted ~\x00 path rather than aborting extraction
# and dropping every other attachment in the response.
continue
+ if expanded not in seen_paths:
+ seen_paths.add(expanded)
+ media.append((expanded, has_voice_tag))
- seen_paths = {p for p, _ in media}
for match in MEDIA_EXTENSIONLESS_TAG_RE.finditer(scan_content):
path = _normalize_media_tag_path(match.group("path"))
if not path or not _path_lacks_deliverable_extension(path):
diff --git a/tests/gateway/test_platform_base.py b/tests/gateway/test_platform_base.py
index 7b4170f457a..786a8f69c52 100644
--- a/tests/gateway/test_platform_base.py
+++ b/tests/gateway/test_platform_base.py
@@ -401,6 +401,31 @@ class TestExtractMedia:
assert media == [("/tmp/Jane Doe/speech.flac", False)]
assert cleaned == ""
+ def test_duplicate_media_tags_are_deduplicated(self):
+ content = "MEDIA:/tmp/test.png\nMEDIA:/tmp/test.png\nMEDIA:/tmp/other.png"
+ media, cleaned = BasePlatformAdapter.extract_media(content)
+ assert media == [
+ ("/tmp/test.png", False),
+ ("/tmp/other.png", False),
+ ]
+ assert cleaned == ""
+
+ def test_duplicate_media_tags_dedup_preserves_first_occurrence_order(self):
+ content = "MEDIA:/tmp/a.png\nMEDIA:/tmp/b.png\nMEDIA:/tmp/a.png\nMEDIA:/tmp/c.png"
+ media, _ = BasePlatformAdapter.extract_media(content)
+ assert media == [
+ ("/tmp/a.png", False),
+ ("/tmp/b.png", False),
+ ("/tmp/c.png", False),
+ ]
+
+ def test_dedup_uses_expanded_path_so_tilde_and_absolute_collapse(self):
+ import os
+ home = os.path.expanduser("~")
+ content = f"MEDIA:~/foo.png\nMEDIA:{home}/foo.png"
+ media, _ = BasePlatformAdapter.extract_media(content)
+ assert media == [(f"{home}/foo.png", False)]
+
def test_as_document_directive_stripped_from_cleaned_text(self):
"""[[as_document]] is a routing directive — strip it from
user-visible text just like [[audio_as_voice]]. Callers detect the