fix(gateway): drop an uncached remote attachment instead of refusing the whole message

An adapter that cannot cache a download leaves its remote URL in
media_urls (DingTalk always does). Native capture takes only local
regular files, so that one entry raised invalid_params and the whole
message, text included, was refused before the agent saw it.

At the envelope boundary, drop each non-local media entry (and its
parallel media_types / media_text_inlined entries) and append a short
note naming the dropped attachment to the text. Malformed media lists
still reach validation and refuse as before.

Refs #143547
This commit is contained in:
unsupportedpastels
2026-10-25 17:13:46 +00:00
committed by Mark S.
parent 765c646300
commit 538755f980
2 changed files with 54 additions and 1 deletions

View File

@@ -10,6 +10,7 @@ from dataclasses import replace
from datetime import datetime
import json
import logging
import os
from gateway.platforms.event import MessageEvent, MessageType
from gateway.session import SessionSource
@@ -65,7 +66,24 @@ def _adapter_event(event, **changes):
"""An adapter's event at the envelope boundary: an absent media list (``None``) is no media.
Any other non-list still reaches ``_validate_native`` and refuses."""
changes.update({name: [] for name in _MEDIA_FIELDS if getattr(event, name) is None})
return replace(event, **changes) if changes else event
return _drop_remote_media(replace(event, **changes) if changes else event)
def _drop_remote_media(event):
"""An adapter that could not cache a download leaves its remote URL in ``media_urls`` (DingTalk
always does). Capture takes only local files, so that one entry refused the whole message, text
included: drop it and tell the agent instead. Malformed media lists still reach validation."""
urls, types = event.media_urls, event.media_types
if not isinstance(event.text, str) or _media_clause(event) is not None or all(map(os.path.isabs, urls)):
return event
kept = [index for index, url in enumerate(urls) if os.path.isabs(url)]
notes = ''.join(f"\n[The user sent an attachment ({types[index] if types else 'file'}) that could not be retrieved.]"
for index in range(len(urls)) if index not in kept)
def keep(values):
return [values[index] for index in kept] if values else values
return replace(event, text=event.text + notes, media_urls=keep(urls), media_types=keep(types),
media_text_inlined=keep(event.media_text_inlined))
def _refuse(event, reason, clause):

View File

@@ -0,0 +1,35 @@
"""An attachment an adapter could not cache locally (a remote URL left in ``media_urls``, as DingTalk
always does) is dropped with a note; the message and its other media are still admitted."""
import pytest
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.platforms.event import MessageEvent, MessageType
from gateway.run import GatewayRunner
from gateway.session_authority import initialize_session_authority
from gateway.session_envelope import prepare_native
CHAT = '15551234567@s.whatsapp.net'
@pytest.mark.asyncio
async def test_remote_media_url_is_dropped_with_a_note_instead_of_refusing_the_message(tmp_path, monkeypatch):
from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
monkeypatch.setenv('WHATSAPP_ALLOWED_USERS', '15551234567')
runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))
adapter = WhatsAppAdapter(PlatformConfig(enabled=True, extra={'session_path': str(tmp_path / 'wa')}))
runner.adapters = {Platform.WHATSAPP: adapter}
authority = await initialize_session_authority(runner, profile_id='default', instance_id='remote-media')
local = tmp_path / 'clip.mp4'
local.write_bytes(b'video-bytes')
event = MessageEvent(text='see these', message_type=MessageType.PHOTO, message_id='m1',
source=adapter.build_source(chat_id=CHAT, user_id=CHAT, chat_type='dm'),
media_urls=['https://static.dingtalk.com/media/abc.png', str(local)],
media_types=['image/png', 'video/mp4'])
try:
payload = await prepare_native(runner, event)
envelope = payload['native_text_v1']
assert payload['text'].startswith('see these\n') and 'image/png' in payload['text']
assert [media['size'] for media in envelope['media']] == [len(b'video-bytes')]
assert envelope['event']['media_types'] == ['video/mp4']
finally:
authority.db.close()