Skip to content

The agent that grows with you

fix(gateway): suspend typing refresh before final delivery (#117300)

chenzeyan54-commitsbcdb1decaf3c
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 115c29a0eaa..092decb7474 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -4423,6 +4423,18 @@ class BasePlatformAdapter(ABC):
if not _tts_paths and _tts_requested_path is not None:
with contextlib.suppress(OSError):
os.remove(_tts_requested_path)
+ # Suspend the typing refresh before the first delivery attempt, not just in
+ # the turn's finally (#117300): if the final send stalls (platform accepted it
+ # but the HTTP ack never returns), control never reaches the finally, and
+ # _keep_typing keeps refreshing sendChatAction forever while the agent is
+ # already idle and the user can read the answer. Reuse the existing
+ # _typing_paused mechanism: _keep_typing skips paused chats each tick and
+ # _stop_typing_refresh's finally discards it, so it cannot leak into the next
+ # turn. No new await on the delivery path (a fire-and-forget stop task was
+ # measured to have no effect).
+ if text_content or extracted.images or extracted.media_files or extracted.local_files \
+ or _tts_paths or _tts_caption_delivered:
+ self.pause_typing_for_chat(event.source.chat_id)
if text_content and not _tts_caption_delivered:
await self._send_final_text(
event, session_key, text_content, _final_thread_metadata,
diff --git a/tests/gateway/test_keep_typing_timeout.py b/tests/gateway/test_keep_typing_timeout.py
index e303f103495..79d9bb28adf 100644
--- a/tests/gateway/test_keep_typing_timeout.py
+++ b/tests/gateway/test_keep_typing_timeout.py
@@ -234,3 +234,117 @@ class TestKeepTypingTimeoutPerTick:
("discord-chat", True),
]
assert "discord-chat" not in adapter._typing_paused
+
+
+class TestPreDeliveryTypingSuspend:
+ """Regression guard for #117300: once delivery begins, the refresh loop
+ must be suspended so a stalled final send (platform accepted it, HTTP ack
+ lost) cannot keep ``send_typing`` firing while the agent is idle.
+
+ The fix reuses the existing ``_typing_paused`` mechanism: the delivery path
+ pauses the chat before the first send attempt, and ``_stop_typing_refresh``'s
+ finally discards it so it never leaks into the next turn.
+ """
+
+ @pytest.mark.asyncio
+ async def test_paused_before_delivery_stall_suppresses_refresh(self, monkeypatch):
+ """Pause the chat the way the delivery path does; a refresh loop running
+ during the stall must never call send_typing (0 ticks)."""
+ adapter = _StubAdapter()
+ ticks = []
+
+ async def recording_send_typing(chat_id, metadata=None):
+ ticks.append(chat_id)
+
+ monkeypatch.setattr(adapter, "send_typing", recording_send_typing)
+ adapter.stop_typing = MagicMock(return_value=asyncio.sleep(0))
+
+ # The delivery path pauses typing before the first send attempt.
+ adapter.pause_typing_for_chat("123")
+
+ stop_event = asyncio.Event()
+ task = asyncio.create_task(
+ adapter._keep_typing(
+ chat_id="123",
+ interval=0.2,
+ stop_event=stop_event,
+ )
+ )
+ # Simulate the 9s stall from the issue's repro: the refresh loop is
+ # still live but the chat is paused, so no tick should reach send_typing.
+ await asyncio.sleep(0.8)
+ stop_event.set()
+ await asyncio.wait_for(task, timeout=1.0)
+
+ assert ticks == [], (
+ f"typing kept refreshing across a pre-delivery pause: {ticks}"
+ )
+ # Pausing the delivery path must not leave the chat permanently paused.
+ await adapter._stop_typing_refresh("123", None, stop_attempts=1)
+ assert "123" not in adapter._typing_paused
+
+ @pytest.mark.asyncio
+ async def test_unpaused_stall_still_ticks(self, monkeypatch):
+ """Control case: without the pre-delivery pause, the refresh loop keeps
+ ticking (the buggy pre-fix behavior), proving the test discriminates."""
+ adapter = _StubAdapter()
+ ticks = []
+
+ async def recording_send_typing(chat_id, metadata=None):
+ ticks.append(chat_id)
+
+ monkeypatch.setattr(adapter, "send_typing", recording_send_typing)
+ adapter.stop_typing = MagicMock(return_value=asyncio.sleep(0))
+
+ stop_event = asyncio.Event()
+ task = asyncio.create_task(
+ adapter._keep_typing(
+ chat_id="456",
+ interval=0.2,
+ stop_event=stop_event,
+ )
+ )
+ await asyncio.sleep(0.8)
+ stop_event.set()
+ await asyncio.wait_for(task, timeout=1.0)
+
+ assert len(ticks) >= 2, (
+ f"expected the unpaused refresh loop to keep ticking, "
+ f"got {len(ticks)}"
+ )
+
+
+async def test_process_message_pauses_typing_before_a_stalled_final_send():
+ """Production entry point (#117300): ``_process_message_background`` must pause the chat
+ BEFORE awaiting the final send. With the send parked forever the turn's ``finally`` never
+ runs, so only a pre-delivery pause keeps ``_keep_typing`` from refreshing an idle agent."""
+ from gateway.platforms.event import MessageEvent, MessageType
+ from gateway.session import SessionSource
+
+ adapter = _StubAdapter()
+ send_started = asyncio.Event()
+ never = asyncio.Event()
+
+ async def _stalled_final_send(*args, **kwargs):
+ send_started.set()
+ await never.wait() # platform accepted the message; the HTTP ack never comes back
+
+ async def _handler(evt):
+ return "a long final answer the user can already read"
+
+ adapter.set_message_handler(_handler)
+ adapter._send_final_text = _stalled_final_send
+ adapter._start_typing_refresh = MagicMock(return_value=None) # loop shape irrelevant here
+ event = MessageEvent(
+ text="hi", message_id="msg-1", message_type=MessageType.TEXT,
+ source=SessionSource(platform=Platform.TELEGRAM, chat_id="77", user_id="u-1"),
+ )
+ turn = asyncio.create_task(adapter._process_message_background(event, "agent:main:telegram:private:77"))
+ try:
+ await asyncio.wait_for(send_started.wait(), timeout=5)
+ assert "77" in adapter._typing_paused, "typing not paused while the final send is stalled"
+ finally:
+ turn.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await turn