Skip to content

The agent that grows with you

refactor(gateway): directive hold-back in a sibling; hold a MEDIA prefix after punctuation

Teknium3403b92c4b6d
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py
index 6ddf69b31be..28b96d48bac 100644
--- a/gateway/stream_consumer.py
+++ b/gateway/stream_consumer.py
@@ -14,7 +14,6 @@ import contextlib
import inspect
import logging
import queue
-import re
import secrets
import threading
import time
@@ -31,6 +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_fences import ensure_closed_code_fences
from gateway.stream_consumer_transport import StreamTransportMixin
from gateway.stream_consumer_fallback import StreamFallbackMixin
@@ -57,16 +57,6 @@ _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 and opening a path the way MEDIA_TAG_CLEANUP_RE's does (quote,
-# ~/, /, a drive letter), a word-start prefix of "MEDIA", or a prefix of a [[…]] flag.
-# Prose such as "social media: X" is not a path, so it never holds the line back.
-_PENDING_MEDIA_RE = re.compile(
- r"""MEDIA:\s*(?:$|[`"'~/\\]|[A-Za-z](?::|$))|(?:^|\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]]")
-
@dataclass
class StreamConsumerConfig:
@@ -765,7 +755,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
# 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))
+ and not 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
@@ -980,17 +970,6 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
if 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 an
diff --git a/gateway/stream_consumer_directives.py b/gateway/stream_consumer_directives.py
new file mode 100644
index 00000000000..23817622270
--- /dev/null
+++ b/gateway/stream_consumer_directives.py
@@ -0,0 +1,30 @@
+"""Hold-back check for delivery directives still being streamed (``MEDIA:<path>``, ``[[…]]`` flags)."""
+
+from __future__ import annotations
+
+import re
+
+# 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
+# complete tag has no left boundary, so a prefix after punctuation ("图片:MED") is held too.
+# Prose such as "social media: Twitter" is not a path, so it never holds the line back.
+_PENDING_MEDIA_RE = re.compile(
+ r"""MEDIA:\s*(?:$|[`"'~/\\]|[A-Za-z](?::|$))"""
+ r"""|(?<![A-Za-z0-9])[`"'*_]{0,3}M(?:E(?:D(?:I(?:A)?)?)?)?$""",
+ re.IGNORECASE)
+_PENDING_FLAG_RE = re.compile(r"\[\[?[A-Za-z_]*\]?$")
+_STREAM_FLAGS = ("[[audio_as_voice]]", "[[as_document]]")
+
+
+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 from *cleaned*, 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
+ 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_stream_consumer_pending_media.py b/tests/gateway/test_stream_consumer_pending_media.py
index ad4083b59ff..5dcc644241c 100644
--- a/tests/gateway/test_stream_consumer_pending_media.py
+++ b/tests/gateway/test_stream_consumer_pending_media.py
@@ -80,3 +80,13 @@ async def test_prose_with_media_colon_streams_before_the_line_ends():
" plus a few forums", " in one long line"])
interim = [t for t in _shown(adapter) if "in one long line" not in t]
assert any("Twitter, Mastodon" in t for t in interim), _shown(adapter)
+
+
+async def test_partial_tag_after_punctuation_is_never_shown():
+ # A complete tag has no left boundary ("图片:MEDIA:/…" is stripped), so its prefix after
+ # punctuation must be held too; showing "MED" and then removing it breaks prefix-stable frames.
+ adapter = await _stream(["Report attached.\n", "图片:MED", "IA:/home/u/report.pdf"])
+ for text in _shown(adapter):
+ assert "MED" not in text, text
+ assert any("Report attached." in t for t in _shown(adapter))