The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): resolved approval cards keep the request on Telegram, Feishu and Teams
Teknium92c86afb1ff1
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 72f18b83c67..8d105f31e07 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -1808,6 +1808,7 @@ class FeishuAdapter(BasePlatformAdapter):"session_key": session_key,"message_id": result.message_id or "","chat_id": chat_id,+ "body": card["elements"][0]["content"], # the resolved card keeps what was asked}return result@@ -1841,13 +1842,12 @@ class FeishuAdapter(BasePlatformAdapter):return SendResult(success=False, error=str(exc))@staticmethod- def _build_resolved_approval_card(*, choice: str, user_name: str) -> dict[str, Any]:- """Raw card JSON shown in place of the buttons once an approval is resolved."""+ def _build_resolved_approval_card(*, choice: str, user_name: str, body: str | None = None) -> dict[str, Any]:+ """Raw card JSON shown in place of the buttons once an approval is resolved; the request (*body*) stays."""icon = "❌" if choice == "deny" else "✅"- key = _APPROVAL_LABEL_KEYS.get(choice, "platform.feishu.approval.resolved_fallback")- label = t(key)- return _card(f"{icon} {label}", "red" if choice == "deny" else "green",- t("platform.feishu.approval.resolved_by_user", icon=icon, label=label, user=user_name))+ label = t(_APPROVAL_LABEL_KEYS.get(choice, "platform.feishu.approval.resolved_fallback"))+ decided = t("platform.feishu.approval.resolved_by_user", icon=icon, label=label, user=user_name)+ return _card(f"{icon} {label}", "red" if choice == "deny" else "green", f"{body}\n\n{decided}" if body else decided)@staticmethoddef _build_resolved_update_prompt_card(*, answer: str, user_name: str) -> dict[str, Any]:@@ -2317,7 +2317,7 @@ class FeishuAdapter(BasePlatformAdapter):)if not self._submit_on_loop(loop, coro):return self._card_response()- return self._card_response(self._build_resolved_approval_card(choice=choice, user_name=user_name))+ return self._card_response(self._build_resolved_approval_card(choice=choice, user_name=user_name, body=state.get("body")))def _handle_update_prompt_card_action(self, *, event: Any, action_value: dict[str, Any], loop: Any) -> Any:"""Schedule update prompt resolution and build the synchronous callback response."""diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.pyindex bfd47d5ae1e..fb59021272e 100644--- a/plugins/platforms/teams/adapter.py+++ b/plugins/platforms/teams/adapter.py@@ -650,7 +650,8 @@ class TeamsAdapter(BasePlatformAdapter):if not choice:return self._invoke_message(t("platform.teams.approval.unknown_action"))if not has_blocking_approval(session_key):- return self._invoke_card([TextBlock(text=t("platform.shared.approval_expired"), wrap=True)])+ body = _approval_body(data.get("cmd", ""), data.get("desc", ""))+ return self._invoke_card([*body, TextBlock(text=t("platform.shared.approval_expired"), wrap=True)])resolve_gateway_approval(session_key, choice)body = _approval_body(data.get("cmd", ""), data.get("desc", ""))body.append(TextBlock(text=t(_APPROVAL_LABEL_KEYS[choice]), wrap=True, weight="Bolder"))diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 88fb2649016..598458fe934 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -183,6 +183,7 @@ from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcomefrom plugins.platforms.telegram.telegram_entities import expand_link_entitiesfrom plugins.platforms.telegram.telegram_held_inbound import TelegramHeldInboundMixinfrom plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id, parse_send_target, parse_telegram_message_id+from plugins.platforms.telegram.telegram_resolved_prompt import edit_keeping_promptfrom plugins.platforms.telegram.telegram_topic_transfer import TopicTransferFn, apply_root_dm_topic_transferfrom plugins.platforms.telegram.telegram_network import (SEED_FALLBACK_IPS, TelegramFallbackTransport, discover_fallback_ips, parse_fallback_ip_env, tcp_keepalive_socket_options)@@ -4759,8 +4760,6 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePif not session_key:returnuser_display = getattr(query.from_user, "first_name", None) or t("platform.telegram.user_fallback")- # Resolve FIRST (unblocks the agent thread), render after: a tap landing after the wait timed out- # (count == 0) must NOT claim "Approved" — the command was already denied.try:# Rendering happens after so the message reflects what actually occurred: a tap that lands after# the approval wait timed out (count == 0) must NOT claim "Approved" — the command was already@@ -4781,7 +4780,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePlabel = t("platform.telegram.approval.expired")edit_text = t("platform.telegram.approval.expired_detail", label=label)await query.answer(text=label[:_TOAST_LIMIT])- await self._edit_md_quiet(query, edit_text)+ await edit_keeping_prompt(query, edit_text, self._edit_md_quiet)# Typing was paused when the approval was sent; the text /approve and /deny paths resume it too.if count and cb["chat_id"] is not None:self.resume_typing_for_chat(str(cb["chat_id"]))@@ -4803,7 +4802,8 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePuser_display = getattr(query.from_user, "first_name", None) or t("platform.telegram.user_fallback")label = t(f"platform.telegram.{label_key}")await query.answer(text=label[:_TOAST_LIMIT])- await self._edit_md_quiet(query, t("platform.telegram.approval.resolved_by_user", label=label, user=user_display))+ decided = t("platform.telegram.approval.resolved_by_user", label=label, user=user_display)+ await edit_keeping_prompt(query, decided, self._edit_md_quiet)# The runner stored a handler keyed by session_key; run it and send any returned text as a follow-up.try:from tools import slash_confirm as _slash_confirm_moddiff --git a/plugins/platforms/telegram/telegram_resolved_prompt.py b/plugins/platforms/telegram/telegram_resolved_prompt.pynew file mode 100644index 00000000000..04c2386348a--- /dev/null+++ b/plugins/platforms/telegram/telegram_resolved_prompt.py@@ -0,0 +1,25 @@+"""Resolved-prompt edits that keep the request visible, kept out of the adapter facade.++Replacing an approval or slash-confirm prompt with only the decision ("✅ Approved once by Ana")+erases what was approved, so a shared chat loses its record. The edit keeps the prompt's own+rendering (``Message.text_html`` rebuilds it from the entities, code block included) and appends+the decision.+"""++from __future__ import annotations++import contextlib+import html+from collections.abc import Awaitable, Callable+from typing import Any+++async def edit_keeping_prompt(query: Any, decision: str, fallback: Callable[[Any, str], Awaitable[None]]) -> None:+ """Append *decision* to the prompt and drop its buttons; *fallback* (decision only) runs when the+ prompt has no readable body or the appended line pushes it past Telegram's length cap."""+ body = getattr(query.message, "text_html", None) if query.message else None+ if isinstance(body, str) and body:+ with contextlib.suppress(Exception):+ await query.edit_message_text(text=f"{body}\n\n— {html.escape(decision)}", parse_mode="HTML", reply_markup=None)+ return+ await fallback(query, decision)diff --git a/tests/gateway/test_feishu_approval_buttons.py b/tests/gateway/test_feishu_approval_buttons.pyindex f8f99f94b62..b6ac7c305ad 100644--- a/tests/gateway/test_feishu_approval_buttons.py+++ b/tests/gateway/test_feishu_approval_buttons.py@@ -669,3 +669,23 @@ class TestResolveUpdatePrompt:assert 3 in adapter._update_prompt_state+++def test_resolved_card_keeps_the_request(_patch_callback_card_types):+ """Clicking a button replaces the card; the replacement still shows the command and reason."""+ import asyncio+ adapter = _make_adapter()+ response = SimpleNamespace(success=lambda: True, data=SimpleNamespace(message_id="msg_9"))+ with patch.object(adapter, "_feishu_send_with_retry", new_callable=AsyncMock, return_value=response):+ asyncio.run(adapter.send_exec_approval(chat_id="oc_12345", command="rm -rf ./build",+ session_key="sess-9", description="dangerous deletion"))+ approval_id = next(iter(adapter._approval_state))+ adapter._loop = MagicMock()+ adapter._loop.is_closed = MagicMock(return_value=False)+ adapter._allowed_group_users = {"ou_bob"}+ adapter._sender_name_cache["ou_bob"] = ("Bob", 9999999999)+ data = _make_card_action_data({"hermes_action": "approve_once", "approval_id": approval_id}, open_id="ou_bob")+ with patch("asyncio.run_coroutine_threadsafe", side_effect=_close_submitted_coro):+ card = adapter._on_card_action_trigger(data).card.data+ content = card["elements"][0]["content"]+ assert "rm -rf ./build" in content and "dangerous deletion" in content and "Bob" in contentdiff --git a/tests/gateway/test_teams.py b/tests/gateway/test_teams.pyindex 009f5716fba..caca1c81fe2 100644--- a/tests/gateway/test_teams.py+++ b/tests/gateway/test_teams.py@@ -1140,3 +1140,18 @@ class TestTeamsRequireMention:adapter = self._make_adapter(**extra)assert adapter._require_mention is expectedassert adapter._extra.get("require_mention") == yaml_value # extras stay readable on the instance+++async def test_expired_approval_click_keeps_the_request():+ """A click after the approval ended replaces the card; the replacement still shows command and reason."""+ adapter = TeamsAdapter(_make_config(client_id="bot-id", client_secret="secret", tenant_id="tenant"))+ adapter._card_action_denied = lambda _from: None+ adapter._invoke_card = lambda body: body+ ctx = MagicMock()+ ctx.activity.value.action.data = {"hermes_action": "approve_once", "session_key": "s1",+ "cmd": "rm -rf ./build", "desc": "dangerous deletion"}+ with patch("tools.approval.has_blocking_approval", return_value=False):+ body = await adapter._on_card_action(ctx)+ texts = " ".join(str(block.text) for block in body)+ assert "rm -rf ./build" in texts and "dangerous deletion" in textsdiff --git a/tests/gateway/test_telegram_approval_buttons.py b/tests/gateway/test_telegram_approval_buttons.pyindex 197d71c7f11..1fb82715400 100644--- a/tests/gateway/test_telegram_approval_buttons.py+++ b/tests/gateway/test_telegram_approval_buttons.py@@ -356,3 +356,30 @@ class TestTelegramApprovalCallback:assert runner.last_source.platform == Platform.TELEGRAMassert runner.last_source.user_id == "222"+++async def test_resolved_approval_keeps_the_request_and_appends_the_decision():+ """The resolved prompt keeps its own rendering (command + reason) with the decision appended; a prompt+ the appended line pushes past the cap falls back to the decision alone instead of keeping live buttons."""+ for edit_fails in (False, True):+ adapter = _make_adapter()+ adapter._approval_state[7] = "agent:main:telegram:group:12345:99"+ query = AsyncMock()+ query.data = "ea:once:7"+ query.message = MagicMock()+ query.message.chat_id = 12345+ query.message.text_html = "<b>Dangerous command</b>\n<pre>rm -rf ./build && ls</pre>\nReason: delete"+ query.from_user = MagicMock(first_name="Ana & Bo", id="12345")+ query.edit_message_text = AsyncMock(side_effect=[RuntimeError("Message is too long"), None] if edit_fails else None)+ with patch.dict(os.environ, {"TELEGRAM_ALLOWED_USERS": "*"}, clear=False), \+ patch("tools.approval.resolve_gateway_approval", return_value=1):+ await adapter._handle_callback_query(MagicMock(callback_query=query), MagicMock())+ final = query.edit_message_text.call_args.kwargs+ assert final["reply_markup"] is None+ if edit_fails:+ assert "MARKDOWN_V2" in repr(final["parse_mode"]) and "rm -rf" not in final["text"]+ else:+ assert final["parse_mode"] == "HTML"+ assert final["text"].startswith(query.message.text_html + "\n\n— ")+ assert "Ana & Bo" in final["text"]