The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): suppress the completion send only when the queued lane's send actually landed
teknium1b4345b4e5745
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 728b4a3ca36..eaf3e00ccee 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -357,13 +357,19 @@ class GatewayNotificationsMixin:metadata: Optional[Dict[str, Any]] = None, event_message_id: Optional[str] = None,text_already_delivered: bool = False, deliver_media: bool = True, stream_consumer=None,session_key: Optional[str] = None, inbound_message_id: Optional[str] = None,- ) -> None:+ ) -> bool:"""Deliver a queued response using the normal text+attachment split.``session_key`` lets the text send record a delivery-ledger obligation like the normal finalsend does, keyed on ``inbound_message_id`` (the raw inbound id, distinct from the``event_message_id`` reply anchor); see ``_send_queued_final_text``. Without a key the send- stays unledgered."""+ stays unledgered.++ Returns whether the caller may treat this turn's final as delivered. True: the stream had+ already delivered it, the reconcile edit landed, the send succeeded, or there was nothing+ textual to send. False: the send was REFUSED (flood control, dead transport) — the caller+ must leave the normal completion send as the fallback, or the user gets nothing. A connector+ DECLINE returns True: that destination is not approved and must not be re-sent."""from gateway.run import _strip_response_attachments_for_direct_sendif not text_already_delivered:text_content = _strip_response_attachments_for_direct_send(response, adapter)@@ -399,21 +405,27 @@ class GatewayNotificationsMixin:"connector's egress guard; not falling back ""to a send (the destination is not approved).")- return+ return Trueexcept Exception as _qe:logger.debug("Queued-lane reconcile edit failed (%s); falling back to send.", _qe)if not _reconciled:- await self._send_queued_final_text(+ _sent = await self._send_queued_final_text(adapter, source, text_content, metadata, event_message_id, session_key,inbound_message_id)+ if not getattr(_sent, "success", False):+ # The text never landed. Report it undelivered and skip the attachments too:+ # the caller's normal completion send replays the whole response (text and+ # its MEDIA: tags), so uploading here would duplicate every file.+ return False# Failed turns deliver their (normalized failure) text but must not upload attachments as if# they succeeded — mirrors the ``not agent_result.get("failed")`` completed-turn guard.if not deliver_media:- return+ return Trueawait self._deliver_media_from_response(response, MessageEvent(text="", source=source, message_id=event_message_id), adapter,thread_metadata=metadata,)+ return Trueasync def _send_queued_final_text(self, adapter, source: SessionSource, text_content: str, metadata: Optional[Dict[str, Any]],diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 8cd49381521..8053b36bc0e 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1928,7 +1928,9 @@ class GatewayTurnMixin:# Streamed responses still need MEDIA: files delivered (chunks carry the tags verbatim). Never# skip when the agent failed: the error text is new content streaming didn't show.if agent_result.get("already_sent") and not agent_result.get("failed"):- if response and adapter:+ # The queued-follow-up lane uploads this response's attachments itself; re-scanning here+ # would upload every file a second time.+ if response and adapter and not agent_result.get("media_already_delivered"):await self._deliver_media_from_response(response, event, adapter)# Streaming delivered the body, but the footer was held back (`not already_sent` gate).if _footer_line and adapter:@@ -3697,6 +3699,8 @@ class GatewayTurnMixin:)first_response = _UNEXPECTED_SILENCE_REPLY_already_streamed = False+ # Failed turns deliver their text but never their attachments (completed-turn parity).+ _deliver_media = not _delivery_result.get("failed")if first_response:logger.info("Queued follow-up for session %s: final text delivery confirmed; delivering explicit media before continuing."@@ -3705,11 +3709,11 @@ class GatewayTurnMixin:session_key or "?",)try:- await self._deliver_queued_first_response(+ _text_delivered = await self._deliver_queued_first_response(first_response, source=turn_ctx.source, adapter=adapter,metadata=turn_ctx._status_thread_metadata, event_message_id=turn_ctx.event_message_id,text_already_delivered=_already_streamed,- deliver_media=not _delivery_result.get("failed"), stream_consumer=_sc,+ deliver_media=_deliver_media, stream_consumer=_sc,# The text send records a delivery-ledger obligation under this key, keyed on# the raw inbound id (the anchor above is only the reply target).session_key=session_key, inbound_message_id=turn_ctx.inbound_message_id,@@ -3718,14 +3722,16 @@ class GatewayTurnMixin:logger.warning("Failed to send first response before queued message: %s", e)else:# One source of truth for "this turn's final already reached the chat": the normal- # completion path (`_hmwa_deliver_turn_response`) consults ``already_sent`` on whatever+ # completion path (`_hmwa_deliver_turn_response`) consults ``already_sent`` on the# result the queued lane hands back. Every early `return result` after this point# (follow-up text refused, stale goal continuation) otherwise re-sends the text the- # fallback just delivered — the #81052 duplicate. Mark both result objects: the- # lane may return either one.- for _r in (response, result):- if isinstance(_r, dict):- _r["already_sent"] = True+ # fallback just delivered — the #81052 duplicate. A REFUSED send reports False, and+ # the completion send stays the fallback so the user is not left with nothing.+ if _text_delivered and isinstance(result, dict):+ result["already_sent"] = True+ # The queued lane already uploaded this response's MEDIA: attachments; without+ # this the completion path's already_sent rescan uploads every file twice.+ result["media_already_delivered"] = _deliver_media# Release deferred bg-review notifications: pop (no double-fire in base.py's finally) and call._bg_cb = self._pop_post_delivery_callback(adapter, session_key, turn_ctx.run_generation)if callable(_bg_cb):diff --git a/tests/gateway/test_queued_followup_final_delivery.py b/tests/gateway/test_queued_followup_final_delivery.pyindex d3bd55a9880..de08bc7386d 100644--- a/tests/gateway/test_queued_followup_final_delivery.py+++ b/tests/gateway/test_queued_followup_final_delivery.py@@ -4,74 +4,122 @@With streaming disabled (the shipped default) there is never a stream consumer, so the queuedlane always sends the first turn's final itself before running the follow-up. When the lane thenhands the FIRST turn's result back (the follow-up's text was refused), the normal completion path-must see ``already_sent`` and not send that text a second time.+must not send that text — or its attachments — a second time, and must still send them when the+queued lane's own send was refused."""import pytestfrom gateway.config import Platform+from gateway.platforms.base import SendResultfrom gateway.platforms.event import MessageEvent, MessageType, SessionSourcefrom gateway.run import GatewayRunnerfrom tests.gateway.test_run_progress_topics import ProgressCaptureAdapter, _make_runner, _run_with_agent+_SESSION_KEY = "agent:main:telegram:group:-1001:17585"-class _FirstTurnAgent:- calls = 0- def __init__(self, **kwargs):- self.tools = []+class _DocCaptureAdapter(ProgressCaptureAdapter):+ """Capture document uploads so a double MEDIA delivery is visible."""- def run_conversation(self, message, conversation_history=None, task_id=None, **kwargs):- type(self).calls += 1- return {"final_response": f"answer {type(self).calls}", "messages": [], "api_calls": 1}+ def __init__(self, platform=Platform.TELEGRAM):+ super().__init__(platform=platform)+ self.documents = []+ async def send_document(self, chat_id, file_path, caption=None, file_name=None,+ reply_to=None, metadata=None, **kwargs) -> SendResult:+ self.documents.append(file_path)+ return SendResult(success=True, message_id="doc-1")-async def test_refused_followup_returns_first_result_marked_delivered(monkeypatch, tmp_path):- """Follow-up text refused after the fallback send: the returned first-turn result carries- ``already_sent`` so the caller's normal send is suppressed, and the text went out exactly once."""- _FirstTurnAgent.calls = 0++class _RefusingDocCaptureAdapter(_DocCaptureAdapter):+ """Every send is refused (flood control, retries exhausted): a SendResult, not an exception."""++ async def send(self, chat_id, content, reply_to=None, metadata=None) -> SendResult:+ await super().send(chat_id, content, reply_to=reply_to, metadata=metadata)+ return SendResult(success=False, error="flood control", retryable=False)+++def _agent_returning(text):+ class _Agent:+ def __init__(self, **kwargs):+ self.tools = []++ def run_conversation(self, message, conversation_history=None, task_id=None, **kwargs):+ return {"final_response": text, "messages": [], "api_calls": 1}++ return _Agent+++async def _none():+ return None+++async def _run_with_refused_followup(monkeypatch, tmp_path, agent_cls, adapter_cls):+ """First turn answers, the queued follow-up's text is refused: the lane hands back the FIRST+ turn's result, which is the object the completion send then acts on."""monkeypatch.setattr(GatewayRunner, "_expand_inbound_context_references",lambda self, source, session_key, message_text: _none(),)- adapter, result = await _run_with_agent(- monkeypatch, tmp_path, _FirstTurnAgent, session_id="sess-refused-followup",- pending_text="@file:/etc/shadow please",+ return await _run_with_agent(+ monkeypatch, tmp_path, agent_cls, session_id="sess-refused-followup",+ pending_text="@file:/etc/shadow please", adapter_cls=adapter_cls,)- assert _FirstTurnAgent.calls == 1- assert [c["content"] for c in adapter.sent] == ["answer 1"]- assert result["final_response"] == "answer 1"- assert result.get("already_sent") is True-async def test_completion_path_skips_body_the_queued_lane_delivered(monkeypatch, tmp_path):- """Control at the completion seam: a result the queued lane marked delivered is not re-sent,- while an unmarked result still is."""- adapter = ProgressCaptureAdapter(platform=Platform.TELEGRAM)+async def _completion_seam(adapter, agent_result, response):+ """Run the result through ``_hmwa_deliver_turn_response`` — the seam that decides whether the+ caller sends the body again. Returns the text the caller would send (None = suppressed)."""runner = _make_runner(adapter)- source = SessionSource(platform=adapter.platform, chat_id="-1001", chat_type="group", user_id="u1")+ source = SessionSource(+ platform=adapter.platform, chat_id="-1001", chat_type="group", thread_id="17585",+ )event = MessageEvent(text="hi", message_type=MessageType.TEXT, source=source, message_id="1")class _Entry:session_id = "s1"- async def _noop_media(*a, **k):- return None+ return await runner._hmwa_deliver_turn_response(+ event, source, _Entry(), _SESSION_KEY, None, agent_result, [], response, None, False,+ )+- monkeypatch.setattr(runner, "_deliver_media_from_response", _noop_media)- delivered = await runner._hmwa_deliver_turn_response(- event, source, _Entry(), "agent:main:telegram:group:-1001", None,- {"final_response": "answer 1", "already_sent": True}, [], "answer 1", None, False,+async def test_queued_lane_delivers_text_and_media_exactly_once(monkeypatch, tmp_path):+ """Single delivery: the queued lane sends the text and uploads the attachment, and the+ completion seam re-sends neither."""+ doc = tmp_path / "report.pdf"+ doc.write_text("x", encoding="utf-8")+ final = f"answer 1\n\nMEDIA: {doc}"+ adapter, result = await _run_with_refused_followup(+ monkeypatch, tmp_path, _agent_returning(final), _DocCaptureAdapter,)- assert delivered is None- not_marked = await runner._hmwa_deliver_turn_response(- event, source, _Entry(), "agent:main:telegram:group:-1001", None,- {"final_response": "answer 1"}, [], "answer 1", None, False,++ assert [c["content"] for c in adapter.sent] == ["answer 1"]+ assert adapter.documents == [str(doc)]+ assert result["final_response"] == final++ assert await _completion_seam(adapter, result, final) is None+ assert len(adapter.sent) == 1+ assert adapter.documents == [str(doc)]+++async def test_refused_queued_send_leaves_the_completion_send_as_the_fallback(monkeypatch, tmp_path):+ """A refused queued send (``SendResult.success`` False) must NOT mark the turn delivered: the+ completion seam is the only remaining send, and suppressing it loses the answer entirely."""+ doc = tmp_path / "report.pdf"+ doc.write_text("x", encoding="utf-8")+ final = f"answer 1\n\nMEDIA: {doc}"+ adapter, result = await _run_with_refused_followup(+ monkeypatch, tmp_path, _agent_returning(final), _RefusingDocCaptureAdapter,)- assert not_marked == "answer 1"+ # Attempted (and retried) but never accepted by the platform.+ assert adapter.sent and {c["content"] for c in adapter.sent} == {"answer 1"}+ # The text never landed, so its attachments wait for the completion send too.+ assert adapter.documents == []+ assert not result.get("already_sent")-async def _none():- return None+ assert await _completion_seam(adapter, result, final) == final