The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): slash-confirm card budgets the MarkdownV2 rendering; approval budgets count UTF-16 units
teknium1edd9fd66a4be
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 7ae9199cffd..a57ab1fbe35 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2585,18 +2585,20 @@ class BasePlatformAdapter(ABC):"""Escape hook for command preview/reason; HTML-mode platforms (Telegram) override."""return text- def _ea_fit(self, text: str, budget: int, suffix: str = "...") -> str:- """``_truncate_preview`` measured after ``_ea_escape``: the platform cap applies to the- wire payload, and HTML escaping expands (``&`` → ``&``), so a raw-length cut can- still overflow. Returns raw text (the caller escapes); ``suffix`` rides outside ``budget``- like ``_truncate_preview``."""+ def _ea_fit(self, text: str, budget: int, suffix: str = "...", escape: Optional[Callable[[str], str]] = None) -> str:+ """``_truncate_preview`` measured after ``escape`` (default ``_ea_escape``) in+ ``message_len_fn`` units: the platform cap applies to the wire payload, and escaping+ expands (``&`` → ``&``), so a raw-length cut can still overflow. Returns raw text (the+ caller escapes); ``suffix`` rides outside ``budget`` like ``_truncate_preview``."""text = str(text or "")- if len(self._ea_escape(text)) <= budget:+ escape = escape or self._ea_escape+ len_fn = self.message_len_fn+ if len_fn(escape(text)) <= budget:return textlo, hi = 0, len(text)while lo < hi: # escaped length is monotonic in the raw prefix, so bisect itmid = (lo + hi + 1) // 2- if len(self._ea_escape(text[:mid])) <= budget:+ if len_fn(escape(text[:mid])) <= budget:lo = midelse:hi = mid - 1diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 56c28d9b0c3..76f76013944 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -3930,9 +3930,10 @@ class TelegramAdapter(BasePlatformAdapter):def _exec_approval_cmd_budget(self, description: str, smart_denied: bool) -> int:# Telegram rejects the whole card ("Message is too long") and the gateway then falls back to# the text /approve prompt, so budget the preview against what the framing leaves of the cap.- fixed = (len(self._EA_HEADER) + len(self._EA_CODE_OPEN) + len(self._EA_CODE_CLOSE)- + len(self._EA_REASON_LABEL) + len(self._ea_escape(description)) + len("...")- + len(self._ea_deadline_line()) + (len(self._EA_SMART_DENY_LINE) if smart_denied else 0))+ fixed = utf16_len( # UTF-16 units, like the 4096 chunker in send()+ self._EA_HEADER + self._EA_CODE_OPEN + self._EA_CODE_CLOSE + self._EA_REASON_LABEL+ + self._ea_escape(description) + "..." + self._ea_deadline_line()+ + (self._EA_SMART_DENY_LINE if smart_denied else ""))return max(0, self.MAX_MESSAGE_LENGTH - fixed)_EA_ACTION_LABELS = {"once": "✅ Allow Once", "session": "✅ Session", "always": "✅ Always", "deny": "❌ Deny"}@@ -3965,7 +3966,9 @@ class TelegramAdapter(BasePlatformAdapter):InlineKeyboardButton("🔒 Always Approve", callback_data=f"sc:always:{confirm_id}")],[InlineKeyboardButton("❌ Cancel", callback_data=f"sc:cancel:{confirm_id}")],])- preview = self.format_message(self._truncate_preview(message, 3800))+ # Budget the MarkdownV2 rendering (escaping expands text), not the raw message.+ preview = self.format_message(self._ea_fit(+ message, self.MAX_MESSAGE_LENGTH - utf16_len(self.format_message("...")), escape=self.format_message))return preview, keyboard, lambda msg: self._slash_confirm_state.__setitem__(confirm_id, session_key)return await self._send_prompt("send_slash_confirm", chat_id, metadata, build, thread_id=self._metadata_thread_id(metadata), reply_to_mode=self._reply_to_mode)diff --git a/tests/gateway/test_telegram_approval_buttons.py b/tests/gateway/test_telegram_approval_buttons.pyindex 7ae2cff69ec..746f53042c0 100644--- a/tests/gateway/test_telegram_approval_buttons.py+++ b/tests/gateway/test_telegram_approval_buttons.py@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from gateway.platforms.base import unauthorized_action_notice+from gateway.platforms.base import unauthorized_action_notice, utf16_len# ---------------------------------------------------------------------------# Ensure the repo root is importable@@ -98,6 +98,32 @@ class TestTelegramExecApproval:assert "&&" in kwargs["text"] and "<reason>" in kwargs["text"]assert kwargs["reply_markup"] is not None+ @pytest.mark.asyncio+ async def test_emoji_dense_approval_card_fits_in_utf16_units(self):+ """Telegram counts UTF-16 code units (astral emoji = 2), like the adapter's chunker."""+ adapter = _make_adapter()+ adapter._bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=42))++ await adapter.send_exec_approval(chat_id="12345", command="😀" * 3000, session_key="s")++ kwargs = adapter._bot.send_message.call_args.kwargs+ assert utf16_len(kwargs["text"]) <= adapter.MAX_MESSAGE_LENGTH+ assert kwargs["reply_markup"] is not None++ @pytest.mark.asyncio+ async def test_slash_confirm_preview_fits_after_markdown_escaping(self):+ """The slash-confirm card is measured after format_message (MarkdownV2 escaping expands+ text), so a 3800-char raw message must still land under the 4096 cap."""+ adapter = _make_adapter()+ adapter._bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=42))++ await adapter.send_slash_confirm(+ chat_id="12345", title="t", message="." * 3800, session_key="s", confirm_id="c1")++ kwargs = adapter._bot.send_message.call_args.kwargs+ assert utf16_len(kwargs["text"]) <= adapter.MAX_MESSAGE_LENGTH+ assert kwargs["reply_markup"] is not None+@pytest.mark.asyncioasync def test_non_smart_allow_permanent_false_keeps_session(self, monkeypatch):