feat(tg): collapse context compaction notices into one edited message

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.
This commit is contained in:
Naster17 authored and chengyongru committed 2026-09-11 13:16:19 +08:00
1 parent 73410e0217
commit 3cc3012b3a
2 files changed
+166

No files matched your search

+59
View File
@@ -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,
@@ -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}