The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): hold back half-streamed MEDIA:/[[…]] directives
santa-sketchb488f145bf14
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.pyindex 1abcdb27b1f..aa2609c2d41 100644--- a/gateway/stream_consumer.py+++ b/gateway/stream_consumer.py@@ -14,6 +14,7 @@ import contextlibimport inspectimport loggingimport queue+import reimport secretsimport threadingimport time@@ -56,6 +57,13 @@ _FUTURE_TYPES = (asyncio.Future, concurrent.futures.Future)# Boundary finalize text when nothing has accumulated yet (overridable per boundary)._DEFAULT_BOUNDARY_PLACEHOLDER = "⏸ 等待审批中..."+# A delivery directive still being streamed on the open (last) line: "MEDIA:" not yet+# stripped by the cleaner, a word-start prefix of "MEDIA", or a prefix of a [[…]] flag.+_PENDING_MEDIA_RE = re.compile(+ r"""MEDIA:|(?:^|\s)[`"'*_]{0,3}M(?:E(?:D(?:I(?:A)?)?)?)?$""", re.IGNORECASE)+_PENDING_DIRECTIVE_RE = re.compile(r"\[\[?[A-Za-z_]*\]?$")+_STREAM_DIRECTIVES = ("[[audio_as_voice]]", "[[as_document]]")+@dataclassclass StreamConsumerConfig:@@ -749,8 +757,12 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThiand not self._flood_strikes))# Defer mid-stream edits while the buffer could still resolve to a silence# marker ("NO"→"NO_REPLY"); got_done always resolves the buffer.- return should_edit and not _is_partial_silence_marker(- self._clean_for_display(self._accumulated))+ # Likewise defer while a MEDIA:/[[…]] directive is still being typed: the cleaner+ # only strips complete deliverable tags, so a half-streamed one would be shown, and+ # a media-only reply cleans to "" at finish, which never edits the bubble away.+ cleaned = self._clean_for_display(self._accumulated)+ return (should_edit and not _is_partial_silence_marker(cleaned)+ and not self._has_pending_media_directive(cleaned))async def _split_first_send(self, tick: _Tick) -> bool:"""No message to edit yet and the buffer overflows: seal only the head chunks; the@@ -965,6 +977,17 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThiif isinstance(item, tuple) and len(item) == 2 and item[0] is _FLUSH:self._signal_flush(item[1])+ @staticmethod+ def _has_pending_media_directive(cleaned: str) -> bool:+ """True while the open line of cleaned streamed text may still become a delivery+ directive. Complete deliverable tags are already gone, so a ``MEDIA:`` left there is+ unfinished or undeliverable; the final (non-interim) flush still shows the latter."""+ line = cleaned.rsplit("\n", 1)[-1]+ if _PENDING_MEDIA_RE.search(line):+ return True+ bracket = _PENDING_DIRECTIVE_RE.search(line)+ return bool(bracket) and any(d.startswith(bracket.group(0)) for d in _STREAM_DIRECTIVES)+@staticmethod# Strip MEDIA:<path> tags before display. Uses the shared anchored MEDIA_TAG_CLEANUP_RE from# gateway/platforms/base.py — only tags whose path ends in a deliverable extension are removed, so andiff --git a/tests/gateway/test_stream_consumer_pending_media.py b/tests/gateway/test_stream_consumer_pending_media.pynew file mode 100644index 00000000000..eaaad29727e--- /dev/null+++ b/tests/gateway/test_stream_consumer_pending_media.py@@ -0,0 +1,73 @@+"""A streamed reply must never show a MEDIA:/[[...]] directive while it is still being typed.++Regression: a voice-only reply ("MEDIA:/…/tts_….ogg") streamed token by token. Interim+edits fired before the path reached its extension, so the cleaner (which only strips+complete deliverable tags) let ``MEDIA:/home/…`` through. At finish the cleaned text was+empty, so nothing edited the bubble again and the partial path stayed above the voice note.+"""++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+from tests.waiting import async_wait_until+++def _adapter():+ adapter = MagicMock()+ adapter.send = AsyncMock(return_value=SimpleNamespace(success=True, message_id="m1"))+ adapter.edit_message = AsyncMock(return_value=SimpleNamespace(success=True))+ adapter.MAX_MESSAGE_LENGTH = 4096+ return adapter+++def _shown(adapter):+ texts = [c.kwargs.get("content", "") for c in adapter.send.call_args_list]+ texts += [c.kwargs.get("content", "") for c in adapter.edit_message.call_args_list]+ return texts+++async def _stream(deltas):+ adapter = _adapter()+ 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+ # Every chunk is eligible for an interim edit (interval 0): wait until the consumer+ # has absorbed it, then yield so any edit it decides on actually goes out.+ 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+ return adapter+++async def test_voice_only_reply_never_shows_partial_media_path():+ adapter = await _stream([+ "MED", "IA:/home/u/.hermes/cache/audio/", "tts_20261014_143816", "_843235.ogg"])+ for text in _shown(adapter):+ assert "MEDIA" not in text and "/home/" not in text, text+++async def test_partial_voice_directive_is_never_shown():+ adapter = await _stream(["Te mando el audio.\n", "[[audio_", "as_voice]]\n",+ "MEDIA:/home/u/.hermes/cache/audio/a", ".ogg"])+ for text in _shown(adapter):+ assert "[[" not in text and "MEDIA" not in text, text+ assert any("Te mando el audio." in t for t in _shown(adapter))+++async def test_prose_mentioning_media_still_streams():+ adapter = await _stream(["La palabra MEDIA aparece ", "en un texto normal ", "y sigue."])+ assert any("La palabra MEDIA aparece" in t for t in _shown(adapter))