The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): preserve rich finals after DM drafts
Gille790c850144ce
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.pyindex 0715a0e8081..ab447fd3721 100644--- a/gateway/stream_consumer.py+++ b/gateway/stream_consumer.py@@ -1212,18 +1212,27 @@ class GatewayStreamConsumer:and (not self._adapter_requires_finalizeor self._last_edit_overflowed+ or self._use_draft_streaming)):- # Mid-stream edit above already delivered the- # final accumulated content. Skip the redundant- # final edit for adapters that don't need an- # explicit finalize signal, and for any adapter- # when that edit split-and-delivered across- # continuations: the split edit carried- # finalize=True itself, and re-finalizing with- # the full text would overflow-split again into- # the adopted continuation, duplicating chunks- # on screen.+ # The update above already delivered the final+ # accumulated content. Native drafts have no+ # message id, so their got_done update is a fresh,+ # persistent send with finalize=True; running the+ # adapter's explicit finalize hook immediately+ # afterward would edit that already-final message+ # a second time. This is especially harmful for+ # Telegram, where a successful sendRichMessage was+ # being followed by editMessageText and could fall+ # back to the legacy table-to-bullets formatter.+ #+ # Also skip the redundant final edit for adapters+ # that don't need an explicit finalize signal, and+ # for any adapter when the update split-and-+ # delivered across continuations: that update+ # carried finalize=True itself, and re-finalizing+ # with the full text would overflow-split again into+ # the adopted continuation, duplicating chunks.## Delivery is recorded via the shared helper so# the recorded payload is the last ACKED edit,diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 1420fcafaf3..7fb1469bbdc 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -5955,22 +5955,16 @@ class TelegramAdapter(BasePlatformAdapter):(added to python-telegram-bot in 22.6); older PTB installs gracefullyfall back to the edit path even on DMs.- When ``rich_messages`` is enabled but ``rich_drafts`` is not, decline- drafts even on DMs. Final delivery then uses ``sendRichMessage`` /- rich ``editMessageText``, while the default draft path still renders- MarkdownV2 (tables → bullet lists). That mismatch makes the streaming- preview look unformatted/"crooked" and the finalized reply a second- beautiful wiki-style bubble. Prefer edit-in-place streaming so the- same message upgrades via rich finalize. Operators who want animated- rich drafts opt in with ``rich_drafts: true``.+ ``rich_drafts`` controls the draft *format*, not whether native draft+ streaming is available. When final rich delivery is enabled but rich+ drafts are not, keep the preview ephemeral and persist the completed+ response through ``sendRichMessage``. A plain message edited in place+ cannot be relied on to upgrade through ``editMessageText``'s+ ``rich_message`` parameter; when that edit is rejected, the fallback+ formatter permanently turns tables into bullet lists."""if not self._bot or not hasattr(self._bot, "send_message_draft"):return False- if (- getattr(self, "_rich_messages_enabled", False)- and not getattr(self, "_rich_drafts_enabled", False)- ):- return Falsereturn (chat_type or "").lower() in {"dm", "private"}async def send_draft(@@ -6023,7 +6017,19 @@ class TelegramAdapter(BasePlatformAdapter):# malformed escape would be rejected — mirroring the (True, False)# retry the streaming send loop uses — so a single bad token never# kills draft streaming for the whole response.- for use_markdown in (True, False):+ # When the persistent response will use a Rich Message but rich draft+ # rendering is intentionally disabled, do not run rich-only constructs+ # through the legacy formatter in the ephemeral preview. In particular,+ # that formatter rewrites pipe tables into bullet groups. A raw draft+ # preserves the table source until ``sendRichMessage`` replaces it with+ # the native persistent rendering at finalization.+ plain_rich_preview = bool(+ getattr(self, "_rich_messages_enabled", False)+ and not getattr(self, "_rich_drafts_enabled", False)+ and self._needs_rich_rendering(text)+ )+ draft_modes = (False,) if plain_rich_preview else (True, False)+ for use_markdown in draft_modes:kwargs: Dict[str, Any] = {"chat_id": normalize_telegram_chat_id(chat_id),"draft_id": int(draft_id),diff --git a/tests/gateway/test_telegram_rich_messages.py b/tests/gateway/test_telegram_rich_messages.pyindex f3dfb90a2a1..55a2c329233 100644--- a/tests/gateway/test_telegram_rich_messages.py+++ b/tests/gateway/test_telegram_rich_messages.py@@ -10,6 +10,7 @@ The ``telegram`` package is mocked by ``tests/gateway/conftest.py````TelegramAdapter`` and wire a mock bot."""+import asyncioimport loggingfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock@@ -387,12 +388,9 @@ def test_prefers_fresh_final_streaming_stays_disabled_when_rich_enabled():@pytest.mark.asyncioasync def test_legacy_draft_stream_finalizes_with_persistent_rich_message():- """A MarkdownV2 draft must not force the persistent final to MarkdownV2."""+ """A plain draft must not force the persistent final to MarkdownV2."""adapter = _make_adapter() # rich messages on, rich drafts off- # With the gate in supports_draft_streaming, draft streaming is declined- # when rich_drafts is off. The test force-enables it to verify that even- # a legacy MDV2 draft still finalizes as a rich message.- assert adapter.supports_draft_streaming(chat_type="dm") is False+ assert adapter.supports_draft_streaming(chat_type="dm") is Trueconsumer = GatewayStreamConsumer(adapter,@@ -412,16 +410,64 @@ async def test_legacy_draft_stream_finalizes_with_persistent_rich_message():# -----------------------------------------------------------------------# supports_draft_streaming: rich_messages without rich_drafts must NOT use-# MDV2 sendMessageDraft previews that later snap to sendRichMessage (wiki)-# finals — that is the "first bubble crooked, second bubble beautiful" bug.+# supports_draft_streaming: rich_drafts controls draft rendering, not whether+# Telegram's ephemeral DM draft transport is available. Keeping that transport+# lets the persistent final use sendRichMessage instead of relying on an+# edit-in-place conversion from a plain message.# -----------------------------------------------------------------------def test_supports_draft_streaming_disabled_when_rich_without_rich_drafts():+def test_supports_plain_draft_streaming_when_rich_without_rich_drafts():adapter = _make_adapter() # rich_messages True, rich_drafts default False- assert adapter.supports_draft_streaming(chat_type="dm") is False- assert adapter.supports_draft_streaming(chat_type="private") is False+ assert adapter.supports_draft_streaming(chat_type="dm") is True+ assert adapter.supports_draft_streaming(chat_type="private") is True+++async def test_rich_table_uses_raw_plain_draft_before_persistent_rich_final():+ adapter = _make_adapter() # rich messages on, rich drafts off++ result = await adapter.send_draft("12345", draft_id=7, content=RICH_CONTENT)++ assert result.success is True+ adapter._bot.do_api_request.assert_not_called()+ adapter._bot.send_message_draft.assert_awaited_once_with(+ chat_id=12345,+ draft_id=7,+ text=RICH_CONTENT,+ )+++async def test_dm_table_stream_persists_through_send_rich_message():+ """Exercise the reporter's transport: ephemeral DM draft, then rich final."""+ adapter = _make_adapter() # rich messages on, rich drafts off+ consumer = GatewayStreamConsumer(+ adapter,+ "12345",+ StreamConsumerConfig(+ transport="auto",+ chat_type="dm",+ edit_interval=0.01,+ buffer_threshold=1,+ cursor="",+ ),+ )++ task = asyncio.create_task(consumer.run())+ consumer.on_delta(RICH_CONTENT)+ await asyncio.sleep(0.05)+ consumer.finish()+ await task++ adapter._bot.send_message_draft.assert_awaited()+ draft_kwargs = adapter._bot.send_message_draft.call_args.kwargs+ assert draft_kwargs["text"] == RICH_CONTENT+ assert "parse_mode" not in draft_kwargs+ rich_endpoints = [call.args[0] for call in adapter._bot.do_api_request.await_args_list]+ assert rich_endpoints == ["sendRichMessage"]+ adapter._bot.edit_message_text.assert_not_called()+ adapter._bot.send_message.assert_not_called()def test_supports_draft_streaming_enabled_when_rich_drafts_opt_in():@@ -604,5 +650,3 @@ async def test_rich_reply_records_and_recovers_text(monkeypatch, tmp_path):)assert event.reply_to_message_id == "678"assert event.reply_to_text == "Your morning briefing: CI is green."--