The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): final-send predicate matches only durable deliveries; pin it at the mark-streamed boundary
teknium180ba7f6f7929
diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 26b2dd85a66..77b0f7c7675 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -3320,12 +3320,14 @@ class GatewayTurnMixin:if matcher(final_text) is False:return Falsereturn True- # Exact-text match against what the consumer genuinely delivered (visible prefix, commentary,- # segments) — safe without the ``previewed`` flag. The codex app-server bridge delivers the- # final agentMessage through the commentary path and never sets response_previewed- # (#74248 / #80519); gating on the flag re-sent every such reply. Mismatching commentary- # still returns False, so a distinct final answer is never suppressed (#65919).- has_delivered_text = getattr(consumer, "has_delivered_text", None)+ # Exact-text match against what the consumer DURABLY delivered (commentary, segments, and the+ # visible prefix only once a real send landed) — safe without the ``previewed`` flag. The codex+ # app-server bridge delivers the final agentMessage through the commentary path and never sets+ # response_previewed (#74248 / #80519); gating on the flag re-sent every such reply. Mismatching+ # commentary still returns False, so a distinct final answer is never suppressed (#65919). Draft+ # frames are ephemeral and must not count: after draft streaming + a failed finalize send this+ # predicate must stay False so the fallback final send still fires (#51828 / #33793).+ has_delivered_text = getattr(consumer, "has_durably_delivered_text", None)if callable(has_delivered_text):try:return bool(has_delivered_text(final_text))diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.pyindex 22a44e8ff0d..04f9373fc3c 100644--- a/gateway/stream_consumer.py+++ b/gateway/stream_consumer.py@@ -364,6 +364,17 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi*self._delivered_segment_texts)return bool(target) and any(sent.strip() == target for sent in seen)+ def has_durably_delivered_text(self, text: str) -> bool:+ """``has_delivered_text`` restricted to deliveries that outlive the turn: commentary and+ finalized segments always count; the visible prefix only once ``_already_sent`` (a draft frame+ sets ``_last_sent_text`` but is ephemeral — a failed finalize send after it must still fall+ back to the gateway's real final send, same gate as ``delivered_final_matches``)."""+ target = self._clean_for_display(text or "").strip()+ seen = [*self._delivered_commentary_texts, *self._delivered_segment_texts]+ if self._already_sent:+ seen.append(self._visible_prefix())+ return bool(target) and any(sent.strip() == target for sent in seen)+def on_segment_break(self) -> None:"""Finalize the current stream segment and start a fresh message."""self._queue.put(_NEW_SEGMENT)diff --git a/tests/gateway/test_stream_consumer.py b/tests/gateway/test_stream_consumer.pyindex a99c1bd2788..884b127d24e 100644--- a/tests/gateway/test_stream_consumer.py+++ b/tests/gateway/test_stream_consumer.py@@ -1399,7 +1399,9 @@ class TestStripOrphanCloseTags:class TestConfirmedFinalDeliveryConsultsCommentaryRecord:"""The gateway's final-send predicate must recognise a final reply the consumer alreadydelivered through the commentary path even when the runtime never set ``response_previewed``- (codex app-server final agentMessage, #74248 / #80519) — and must still send a distinct final."""+ (codex app-server final agentMessage, #74248 / #80519) — and must still send a distinct final.+ Only DURABLE deliveries count: a draft frame followed by a failed finalize send must leave the+ fallback final send armed (#51828 / #33793 failed-finalize family)."""@staticmethoddef _consumer_after_commentary(text):@@ -1409,11 +1411,21 @@ class TestConfirmedFinalDeliveryConsultsCommentaryRecord:assert asyncio.run(c._send_commentary(text)) is Truereturn c- def test_same_text_delivered_as_commentary_is_confirmed_without_previewed_flag(self):+ @staticmethod+ def _mark_streamed_delivery(consumer, final_text):+ """Drive the production gateway boundary that decides ``already_sent`` for the normal final send."""from gateway.run_turn import GatewayTurnMixin+ response = {"final_response": final_text}+ turn_ctx = SimpleNamespace(+ stream_consumer_holder=[consumer], source=SimpleNamespace(platform="telegram"), session_key="s1",+ )+ asyncio.run(GatewayTurnMixin()._run_agent_mark_streamed_delivery(response, turn_ctx))+ return response++ def test_same_text_delivered_as_commentary_suppresses_normal_final_send_without_previewed_flag(self):c = self._consumer_after_commentary("Native compaction is active.")- assert GatewayTurnMixin._run_agent_stream_confirmed_final_delivery(- c, "Native compaction is active.", previewed=False) is True+ response = self._mark_streamed_delivery(c, "Native compaction is active.")+ assert response.get("already_sent") is Truedef test_distinct_final_after_commentary_is_still_sent(self):from gateway.run_turn import GatewayTurnMixin@@ -1421,6 +1433,28 @@ class TestConfirmedFinalDeliveryConsultsCommentaryRecord:assert GatewayTurnMixin._run_agent_stream_confirmed_final_delivery(c, "Native compaction is active.", previewed=False) is False+ def test_draft_streamed_text_with_failed_finalize_send_keeps_fallback_final_send(self):+ """Drafts set ``_last_sent_text`` but are ephemeral: when the finalize send then fails+ (429/flood), the reply is NOT on screen — ``already_sent`` must stay unset so the gateway's+ fallback final send fires instead of silently losing the reply."""+ adapter = MagicMock()+ adapter.send_draft = AsyncMock(return_value=SimpleNamespace(success=True))+ adapter.send = AsyncMock(return_value=SimpleNamespace(success=False, message_id=None, error="429"))+ c = GatewayStreamConsumer(adapter=adapter, chat_id="c1")+ c._use_draft_streaming, c._draft_id = True, "d1"+ text = "Native compaction is active."++ async def stream_then_finalize():+ assert await c._send_or_edit(text, finalize=False) is True+ assert await c._send_or_edit(text, finalize=True) is False++ asyncio.run(stream_then_finalize())+ assert adapter.send_draft.await_count == 1 and adapter.send.await_count >= 1+ assert c.already_sent is False and c.final_response_sent is False+ assert c.has_delivered_text(text) is True # draft-only visibility, not durable+ response = self._mark_streamed_delivery(c, text)+ assert not response.get("already_sent")+class TestHasDeliveredTextAfterSegmentBreak:"""has_delivered_text must find a delivered segment after a segment break,