The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): approval button card fits the 4096-char cap after HTML escaping
teknium1b502504b744d
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex d29f5d01cb7..7ae9199cffd 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2585,6 +2585,23 @@ 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``."""+ text = str(text or "")+ if len(self._ea_escape(text)) <= budget:+ return text+ lo, hi = 0, len(text)+ while lo < hi: # escaped length is monotonic in the raw prefix, so bisect it+ mid = (lo + hi + 1) // 2+ if len(self._ea_escape(text[:mid])) <= budget:+ lo = mid+ else:+ hi = mid - 1+ return text[:lo] + suffix+def _exec_approval_cmd_budget(self, description: str, smart_denied: bool) -> int:"""Chars of command preview that fit; platforms with a hard message cap compute it."""return self._EA_CMD_BUDGET@@ -2599,8 +2616,8 @@ class BasePlatformAdapter(ABC):flagged + the deadline line, plus the smart-deny line. Buttons/trailing instructions stayplatform-local."""if self._EA_REASON_BUDGET:- description = self._truncate_preview(str(description or ""), self._EA_REASON_BUDGET)- cmd_preview = self._truncate_preview(+ description = self._ea_fit(str(description or ""), self._EA_REASON_BUDGET)+ cmd_preview = self._ea_fit(str(command or ""), self._exec_approval_cmd_budget(description, smart_denied))text = (f"{self._EA_HEADER}"f"{self._EA_CODE_OPEN}{self._ea_escape(cmd_preview)}{self._EA_CODE_CLOSE}"diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex ad9dca59ad2..56c28d9b0c3 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -3922,11 +3922,19 @@ class TelegramAdapter(BasePlatformAdapter):_EA_CODE_OPEN = "<pre>"_EA_CODE_CLOSE = "</pre>\n\n"_EA_SMART_DENY_LINE = "\n\n<b>Smart DENY:</b> owner override applies to this one operation only."- _EA_CMD_BUDGET = 3800+ _EA_REASON_BUDGET = 500 # escaped chars; the reason shares the 4096 cap with the commanddef _ea_escape(self, text: str) -> str:return _html.escape(text)+ 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))+ return max(0, self.MAX_MESSAGE_LENGTH - fixed)+_EA_ACTION_LABELS = {"once": "✅ Allow Once", "session": "✅ Session", "always": "✅ Always", "deny": "❌ Deny"}async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult:diff --git a/tests/gateway/test_interactive_prompt_base.py b/tests/gateway/test_interactive_prompt_base.pyindex 4bb3549a91c..e4beec2319b 100644--- a/tests/gateway/test_interactive_prompt_base.py+++ b/tests/gateway/test_interactive_prompt_base.py@@ -39,6 +39,16 @@ class TestTruncatePreview:def test_exact_budget_unchanged(self):assert BasePlatformAdapter._truncate_preview("x" * 10, 10) == "x" * 10+ def test_ea_fit_measures_the_escaped_rendering(self):+ """An escaping platform's budget applies to the wire payload, never to raw chars."""+ class _Html(_DefaultAdapter):+ def _ea_escape(self, text):+ return _html.escape(text)++ adapter = _bare(_Html)+ assert adapter._ea_fit("&" * 100, 20) == "&&&&..." # 4 x "&" == 20 escaped chars+ assert adapter._ea_fit("&" * 4, 20) == "&" * 4 # fits once escaped → untouched+class TestFormatExecApproval:def test_default_template(self, monkeypatch):diff --git a/tests/gateway/test_telegram_approval_buttons.py b/tests/gateway/test_telegram_approval_buttons.pyindex 980675cd6a8..7ae2cff69ec 100644--- a/tests/gateway/test_telegram_approval_buttons.py+++ b/tests/gateway/test_telegram_approval_buttons.py@@ -77,6 +77,27 @@ class TestTelegramExecApproval:assert "dangerous deletion" in kwargs["text"]assert kwargs["reply_markup"] is not None # InlineKeyboardMarkup+ @pytest.mark.asyncio+ @pytest.mark.parametrize("smart_denied", [False, True])+ async def test_oversized_escaped_approval_text_keeps_inline_keyboard(self, smart_denied):+ """The rendered HTML card (escaped command + reason + framing) must fit Telegram's+ 4096-char cap, otherwise the API rejects it and the gateway falls back to /approve."""+ adapter = _make_adapter()+ adapter._bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=42))++ await adapter.send_exec_approval(+ chat_id="12345",+ command="&" * 3700, # inside the old raw budget; 5x larger once escaped+ session_key="s",+ description="<reason>" * 1000,+ smart_denied=smart_denied,+ )++ kwargs = adapter._bot.send_message.call_args.kwargs+ assert len(kwargs["text"]) <= adapter.MAX_MESSAGE_LENGTH+ assert "&&" in kwargs["text"] and "<reason>" in kwargs["text"]+ assert kwargs["reply_markup"] is not None+@pytest.mark.asyncioasync def test_non_smart_allow_permanent_false_keeps_session(self, monkeypatch):