The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): capture native media off the owner loop
Teknium9cdc9d1803e8
diff --git a/gateway/session_envelope.py b/gateway/session_envelope.pyindex bc42116eb5b..3c5aabb56f5 100644--- a/gateway/session_envelope.py+++ b/gateway/session_envelope.py@@ -4,6 +4,7 @@ Ordinary context and local media are retained without serializing delegated trusMultiplex callbacks bind current connector ownership; roles require fresh preflight.Relay snapshots bind the authenticated connector and exact source; replay rechecks both."""+import asynciofrom copy import copy, deepcopyfrom datetime import datetimeimport json@@ -114,11 +115,16 @@ async def prepare_native(runner, event):# not silently discard them while freezing the caller's source identity.frozen = replace(event, source=copy(event.source))fresh_roles = await reauthorize_roles(runner, frozen.source, provenance)- return _snapshot_native(runner, frozen, provenance, fresh_roles)+ encoded_source = _validate_native(runner, frozen, provenance, fresh_roles)+ # Copy + SHA-256 + fsyncs of up to max_inbound_media_bytes stay off the owner loop; the+ # copied context carries the admission's capture lease.+ media = await asyncio.to_thread(capture_native_media, frozen.media_urls) if frozen.media_urls else None+ return _snapshot_native(runner, frozen, provenance, fresh_roles, encoded_source, media)-def _snapshot_native(runner, event, provenance, fresh_roles=False):- encoded_source = _validate_native(runner, event, provenance, fresh_roles)+def _snapshot_native(runner, event, provenance, fresh_roles=False, encoded_source=None, media=None):+ if encoded_source is None:+ encoded_source = _validate_native(runner, event, provenance, fresh_roles)envelope = {'source': encoded_source,'route': runner.session_store._generate_session_key(event.source),'event': deepcopy({name: getattr(event, name) for name in _EVENT_FIELDS}),@@ -144,7 +150,7 @@ def _snapshot_native(runner, event, provenance, fresh_roles=False):if event.message_type != MessageType.TEXT:envelope['message_type'] = event.message_type.valueif event.media_urls:- envelope['media'] = capture_native_media(event.media_urls)+ envelope['media'] = media if media is not None else capture_native_media(event.media_urls)envelope['event'].update(media_types=list(event.media_types),media_text_inlined=list(event.media_text_inlined))# Keep the private dispatch key so previously committed text-only rows recoverdiff --git a/tests/gateway/test_native_media_capture_off_loop.py b/tests/gateway/test_native_media_capture_off_loop.pynew file mode 100644index 00000000000..baf461c2294--- /dev/null+++ b/tests/gateway/test_native_media_capture_off_loop.py@@ -0,0 +1,48 @@+"""Native media capture (copy + SHA-256 + fsyncs) runs off the owner loop, under the admission lease."""+import threading++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 SessionAuthority, initialize_session_authority+from gateway.session_envelope import restore_native+from hermes_state_runtime import get_session_admission++CHAT = '[email protected]'+++async def test_native_media_capture_runs_off_loop_and_commits_owned_bytes(tmp_path, monkeypatch):+ import gateway.session_envelope as envelope+ import gateway.session_ingress_media as media+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter+ monkeypatch.setenv('WHATSAPP_ALLOWED_USERS', '15551234567')+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)+ loop_thread, captured = threading.current_thread(), []+ real_capture = media.capture_native_media++ def capture(paths):+ captured.append((threading.current_thread() is loop_thread, media._lease_scope.get() is not None))+ return real_capture(paths)++ monkeypatch.setattr(envelope, 'capture_native_media', capture)+ 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='media')+ try:+ attachment = tmp_path / 'clip.mp4'+ attachment.write_bytes(b'video-bytes' * 1000)+ event = MessageEvent(text='look', message_type=MessageType.VIDEO, message_id='v1',+ source=adapter.build_source(chat_id=CHAT, user_id=CHAT, chat_type='dm'),+ media_urls=[str(attachment)], media_types=['video/mp4'])+ receipt = await authority.admit_native(event)+ assert captured == [(False, True)], captured # worker thread, lease carried by the context+ attachment.write_bytes(b'changed')+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ restored = restore_native(row['payload'], runner)+ assert open(restored.media_urls[0], 'rb').read() == b'video-bytes' * 1000+ finally:+ authority.db.close()