From 3cc3012b3ac2759b2283957d3ac89a0a216dc4a7 Mon Sep 17 00:00:00 2001 From: Naster17 Date: Tue, 8 Sep 2026 13:11:45 +0200 Subject: [PATCH] feat(tg): collapse context compaction notices into one edited message MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Context compaction previously posted two separate chat messages: a 'Compressing context…' notice when compaction started and a follow-up 'Context compacted.' once it finished. The Telegram channel now collapses this into a single message: the started phase posts the notice and remembers its message id, and a terminal phase (succeeded/failed/cancelled) edits that same message in place instead of posting another. If the edit fails, a fresh message keeps the outcome visible. Notices are keyed by compaction id and bounded, so concurrent or abandoned compactions cannot leak state. --- nanobot/channels/telegram/runtime.py | 59 ++++++++++ .../telegram/tests/test_telegram_channel.py | 107 ++++++++++++++++++ 2 files changed, 166 insertions(+) diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.py index 2ce199cfa..f104e35d2 100644 --- a/nanobot/channels/telegram/runtime.py +++ b/nanobot/channels/telegram/runtime.py @@ -36,6 +36,7 @@ from nanobot.channels.base import BaseChannel from nanobot.command.builtin import build_help_text from nanobot.config.paths import get_media_dir from nanobot.config.schema import Base +from nanobot.events import ContextCompactionEvent from nanobot.security.network import validate_url_target from nanobot.utils.helpers import split_message from nanobot.utils.logging_bridge import redirect_lib_logging @@ -52,6 +53,8 @@ TELEGRAM_HTML_MAX_LEN = 4096 TELEGRAM_RICH_MAX_LEN = 32768 TELEGRAM_REPLY_CONTEXT_MAX_LEN = TELEGRAM_MAX_MESSAGE_LEN # Max length for reply context in user message TELEGRAM_RICH_DRAFT_MIN_INTERVAL = 0.75 # 40 draft updates per 30 seconds per chat +# Bound for in-flight compaction notices in case a terminal phase never arrives. +COMPACTION_NOTICES_MAX = 64 # python-telegram-bot exposes a six-parameter Application generic. Nanobot # doesn't customize its context/data/job-queue types, so keep that SDK boundary @@ -555,6 +558,7 @@ class TelegramChannel(BaseChannel): self._bot_user_id: int | None = None self._bot_username: str | None = None self._stream_bufs: dict[str, _StreamBuf] = {} # chat_id -> streaming state + self._compaction_notices: dict[tuple[str, str], int] = {} # (chat_id, compaction_id) -> message_id self._inbound_buffers: dict[str, list[_QueuedTelegramUpdate]] = {} self._inbound_workers: dict[str, asyncio.Task[None]] = {} self._rich_send_disabled: bool = False # Latch off if Bot API < 10.1 @@ -1087,6 +1091,14 @@ class TelegramChannel(BaseChannel): allow_sending_without_reply=True ) + # Compaction notices collapse into one message: the started phase sends + # it, a terminal phase edits it in place instead of posting a new one. + if isinstance(msg.event, ContextCompactionEvent): + await self._send_compaction_notice( + chat_id, msg, msg.event, reply_params, thread_kwargs, + ) + return + # Send media files for media_path in (msg.media or []): try: @@ -1252,6 +1264,53 @@ class TelegramChannel(BaseChannel): def _is_not_modified_error(exc: Exception) -> bool: return isinstance(exc, BadRequest) and "message is not modified" in str(exc).lower() + async def _send_compaction_notice( + self, + chat_id: int, + msg: OutboundMessage, + event: ContextCompactionEvent, + reply_params: ReplyParameters | None, + thread_kwargs: dict[str, int], + ) -> None: + """Deliver compaction status as one message that is edited in place. + + The started phase posts the notice and remembers its message id; a + terminal phase rewrites that same message instead of posting another. + If the notice cannot be edited, a fresh message keeps the outcome + visible either way. + """ + app = self._require_app() + key = (msg.chat_id, event.compaction_id) + if event.phase == "started": + sent = await self._call_with_retry( + app.bot.send_message, + chat_id=chat_id, + text=msg.content, + reply_parameters=reply_params, + **thread_kwargs, + ) + while len(self._compaction_notices) >= COMPACTION_NOTICES_MAX: + self._compaction_notices.pop(next(iter(self._compaction_notices))) + self._compaction_notices[key] = sent.message_id + return + + message_id = self._compaction_notices.pop(key, None) + if message_id is None or not msg.content: + await self._send_text(chat_id, msg.content, thread_kwargs=thread_kwargs) + return + try: + await self._call_with_retry( + app.bot.edit_message_text, + chat_id=chat_id, + message_id=message_id, + text=msg.content, + ) + except Exception as exc: + if self._is_not_modified_error(exc): + return + self.logger.warning("Compaction notice edit failed, sending anew: {}", exc) + await self._send_text(chat_id, msg.content, thread_kwargs=thread_kwargs) + async def send_delta( self, chat_id: str, diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.py index f9f3a17dc..bd3952151 100644 --- a/nanobot/channels/telegram/tests/test_telegram_channel.py +++ b/nanobot/channels/telegram/tests/test_telegram_channel.py @@ -27,6 +27,7 @@ from nanobot.channels.telegram.runtime import ( _StreamBuf, _telegram_command_text, ) +from nanobot.events import ContextCompactionEvent class _FakeHTTPXRequest: @@ -3250,3 +3251,109 @@ async def test_send_delta_stream_end_rich_disabled_uses_legacy_html() -> None: channel._app.bot.do_api_request.assert_not_called() channel._app.bot.edit_message_text.assert_awaited_once() assert "123" not in channel._stream_bufs + + +# --------------------------------------------------------------------------- +# Compaction notices: started sends, terminal phase edits in place +# --------------------------------------------------------------------------- + +def _compaction_message(phase: str, compaction_id: str = "c1") -> OutboundMessage: + return OutboundMessage( + channel="telegram", + chat_id="999", + content={ + "started": "Compressing context…", + "succeeded": "Context compacted.", + "failed": "Unable to compact context.", + "cancelled": "Context compaction cancelled.", + }[phase], + event=ContextCompactionEvent(compaction_id=compaction_id, phase=phase), + ) + + +@pytest.mark.asyncio +async def test_compaction_terminal_phase_edits_started_notice_in_place() -> None: + channel = TelegramChannel( + TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]), + MessageBus(), + ) + _install_ready_app(channel) + channel._app.bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=77)) + channel._app.bot.edit_message_text = AsyncMock() + + await channel.send(_compaction_message("started")) + + channel._app.bot.send_message.assert_awaited_once() + channel._app.bot.edit_message_text.assert_not_awaited() + assert channel._compaction_notices[("999", "c1")] == 77 + + await channel.send(_compaction_message("succeeded")) + + # The outcome rewrites the original notice instead of posting a new message. + channel._app.bot.send_message.assert_awaited_once() + channel._app.bot.edit_message_text.assert_awaited_once_with( + chat_id=999, message_id=77, text="Context compacted.", + ) + assert ("999", "c1") not in channel._compaction_notices + + +@pytest.mark.asyncio +async def test_compaction_edit_failure_falls_back_to_new_message() -> None: + from telegram.error import BadRequest + + channel = TelegramChannel( + TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]), + MessageBus(), + ) + _install_ready_app(channel) + channel._app.bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=77)) + channel._app.bot.edit_message_text = AsyncMock( + side_effect=BadRequest("Message to edit not found") + ) + + await channel.send(_compaction_message("started")) + await channel.send(_compaction_message("failed")) + + assert channel._app.bot.send_message.await_count == 2 + assert channel._compaction_notices == {} + + +@pytest.mark.asyncio +async def test_compaction_terminal_phase_without_notice_sends_message() -> None: + channel = TelegramChannel( + TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]), + MessageBus(), + ) + _install_ready_app(channel) + channel._app.bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=1)) + channel._app.bot.edit_message_text = AsyncMock() + + await channel.send(_compaction_message("cancelled")) + + channel._app.bot.edit_message_text.assert_not_awaited() + channel._app.bot.send_message.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_compaction_notices_are_tracked_per_compaction_id() -> None: + channel = TelegramChannel( + TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]), + MessageBus(), + ) + _install_ready_app(channel) + channel._app.bot.send_message = AsyncMock( + side_effect=[ + SimpleNamespace(message_id=101), + SimpleNamespace(message_id=202), + ] + ) + channel._app.bot.edit_message_text = AsyncMock() + + await channel.send(_compaction_message("started", compaction_id="c1")) + await channel.send(_compaction_message("started", compaction_id="c2")) + await channel.send(_compaction_message("succeeded", compaction_id="c1")) + + channel._app.bot.edit_message_text.assert_awaited_once_with( + chat_id=999, message_id=101, text="Context compacted.", + ) + assert channel._compaction_notices == {("999", "c2"): 202}