The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): timed-out and resolved approval cards keep the full request
Teknium02a790293dc0
diff --git a/gateway/run_turn_runner_approval_settle.py b/gateway/run_turn_runner_approval_settle.pyindex 5525e29d6b8..742dff352ba 100644--- a/gateway/run_turn_runner_approval_settle.py+++ b/gateway/run_turn_runner_approval_settle.py@@ -17,7 +17,8 @@ from typing import Any, Callable, Optionalfrom agent.i18n import tfrom gateway.platforms.base import fit_prefix-from gateway.platforms.base_exec_approval import approval_timeout_seconds, format_approval_timed_out_notice+from gateway.platforms.base_exec_approval import (+ approval_timeout_seconds, ea_default_reason_text, ea_reason_label_text, format_approval_timed_out_notice)logger = logging.getLogger(__name__)@@ -42,6 +43,7 @@ def register_timeout_notice(timeout_s = approval_data.get("timeout_s")if timeout_s is None:timeout_s = approval_timeout_seconds()+ flagged = approval_data.get("description") or ea_default_reason_text()def settle(reason: str) -> None:if reason != "timeout":@@ -52,13 +54,14 @@ def register_timeout_notice(if callable(still_current) and not still_current():returnrunner._schedule(- _post_timeout_notice(runner._ctx, command, card_message_id, timeout_s),+ _post_timeout_notice(runner._ctx, command, card_message_id, timeout_s, flagged),"Approval timeout notice scheduling error")register_gateway_settle(session_key, request_id, settle)-async def _post_timeout_notice(ctx, command: str, card_message_id: Optional[str], timeout_s: int) -> None:+async def _post_timeout_notice(+ ctx, command: str, card_message_id: Optional[str], timeout_s: int, reason: str = "") -> None:from gateway.run import _interim_metadataadapter = ctx._status_adapter@@ -66,28 +69,30 @@ async def _post_timeout_notice(ctx, command: str, card_message_id: Optional[str]metadata = _interim_metadata(ctx._status_thread_metadata)try:# Plain markdown, not the card's platform markup: ``edit_message`` re-formats it itself.- if card_message_id and await _edit_card(adapter, ctx._status_chat_id, card_message_id, notice, command):+ if card_message_id and await _edit_card(adapter, ctx._status_chat_id, card_message_id, notice, command, reason):returnawait adapter.send(ctx._status_chat_id, notice, metadata=metadata)except Exception:logger.debug("Approval timeout notice failed", exc_info=True)-def _timed_out_card_body(adapter, chat_id: str, notice: str, command: str) -> str:- """The notice plus the command, which is now the card's only record of it. It must fit one+def _timed_out_card_body(adapter, chat_id: str, notice: str, command: str, reason: str = "") -> str:+ """The notice plus the reason and command, which are now the card's only record of the request. It must fit onemessage in the platform's own units (Telegram counts UTF-16), or the edit is truncated inplace behind a dangling "(1/N)" and keeps streaming-preview state. A run of backticks in thecommand would close the card's fence and let the platform's formatter rewrite, and grow,the rest, so it is split with zero-width spaces (which also ride along in a copy)."""- command = re.sub(r"`{3,}", lambda run: "\u200b".join(run.group()), command)+ command, reason = (re.sub(r"`{3,}", lambda run: "\u200b".join(run.group()), s) for s in (command, reason))measure, suffix = adapter.message_len_fn_for_chat(chat_id), "..."+ if reason: # capped like the card's own reason, so the command keeps most of the budget+ notice = f"{notice}\n{ea_reason_label_text()}: {fit_prefix(reason, 500, measure, suffix)}"frame = measure(t("gateway.exec_approval.timed_out_card_body", notice=notice, command=""))budget = adapter.max_message_length_for_chat(chat_id) - frame - measure(suffix)return t("gateway.exec_approval.timed_out_card_body", notice=notice,command=fit_prefix(command, max(0, budget), measure, suffix))-async def _edit_card(adapter, chat_id: str, message_id: str, notice: str, command: str) -> bool:+async def _edit_card(adapter, chat_id: str, message_id: str, notice: str, command: str, reason: str = "") -> bool:"""Edit the card in place to the timed-out body; False sends the notice as a new message.Platforms whose edit replaces the markup drop the buttons here; Discord's edit keeps them,and its card's settle observer removes them."""@@ -95,7 +100,7 @@ async def _edit_card(adapter, chat_id: str, message_id: str, notice: str, commanif edit is None:return Falsetry:- result = await edit(chat_id, message_id, _timed_out_card_body(adapter, chat_id, notice, command))+ result = await edit(chat_id, message_id, _timed_out_card_body(adapter, chat_id, notice, command, reason))except Exception:logger.debug("Approval card edit failed; sending the notice as a new message", exc_info=True)return Falsediff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 8d105f31e07..b6547069175 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -1808,7 +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+ "body": card["elements"][0]["content"].replace(self._ea_deadline_line(), ""), # kept; deadline is moot}return resultdiff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex 1aa25e88f9f..b2edc353b11 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -5654,7 +5654,7 @@ class SlackAdapter(BasePlatformAdapter):if not count:decision_text = t("platform.shared.approval_expired")await self._finalize_interactive_message(- channel_id, msg_ts, self._section_text(message), decision_text,+ channel_id, msg_ts, self._section_text(message).replace(self._ea_deadline_line(), ""), decision_text,"Command approval request", "approval", team_id or None)async def _update_clarify_message(diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.pyindex fb59021272e..baaf9345a64 100644--- a/plugins/platforms/teams/adapter.py+++ b/plugins/platforms/teams/adapter.py@@ -332,10 +332,6 @@ _APPROVAL_LABEL_KEYS = {}-def _truncate(text: str, limit: int) -> str:- return text[:limit] + "..." if len(text) > limit else text--def _approval_body(cmd: str, desc: str, *, always: bool = False) -> list:"""Adaptive Card body blocks for an approval prompt; unless ``always``, empty ``cmd``/``desc`` omit their blocks."""body = []@@ -686,15 +682,16 @@ class TeamsAdapter(BasePlatformAdapter):"""Adaptive Card: the shared text is split into its header / fenced command / reason blocks."""if not self._app:return SendResult(success=False, error="Teams app not initialized")- # Button data carries a truncated cmd — just enough to reconstruct the card body.- btn_data_base = {"session_key": prompt.session_key, "cmd": _truncate(prompt.command, 200), "desc": prompt.description}+ # Button data carries the card's own command preview, so the resolved card shows what was asked.+ cmd = self._truncate_preview(prompt.command, self._EA_CMD_BUDGET)+ btn_data_base = {"session_key": prompt.session_key, "cmd": cmd, "desc": prompt.description}actions = []for label, choice, style in prompt.actions:kw = {"style": self._EA_CARD_STYLES[style]} if style else {}actions.append(ExecuteAction(title=label, verb="hermes_approve",data={**btn_data_base, "hermes_action": self._EA_CARD_ACTIONS[choice]}, **kw))- body = _approval_body(self._truncate_preview(prompt.command, self._EA_CMD_BUDGET), prompt.description, always=True)+ body = _approval_body(cmd, prompt.description, always=True)body.append(TextBlock(text=format_approval_deadline_line(approval_timeout_seconds()), wrap=True))if prompt.smart_denied:body.append(TextBlock(text=self._EA_SMART_DENY_LINE.strip(), wrap=True))diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 598458fe934..7a94db71fed 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -4780,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 edit_keeping_prompt(query, edit_text, self._edit_md_quiet)+ await edit_keeping_prompt(self, query, edit_text)# 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 +4803,7 @@ class TelegramAdapter(TelegramHeldInboundMixin, TelegramTopicRoutingMixin, BasePlabel = t(f"platform.telegram.{label_key}")await query.answer(text=label[:_TOAST_LIMIT])decided = t("platform.telegram.approval.resolved_by_user", label=label, user=user_display)- await edit_keeping_prompt(query, decided, self._edit_md_quiet)+ await edit_keeping_prompt(self, query, decided)# 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.pyindex 04c2386348a..3a243abd26d 100644--- a/plugins/platforms/telegram/telegram_resolved_prompt.py+++ b/plugins/platforms/telegram/telegram_resolved_prompt.py@@ -2,24 +2,24 @@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.+rendering (``Message.text_html`` rebuilds it from the entities, code block included), drops the+"if you don't answer within N minutes" line that no longer applies, and appends the decision."""from __future__ import annotationsimport contextlibimport html-from collections.abc import Awaitable, Callablefrom 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."""+async def edit_keeping_prompt(adapter: Any, query: Any, decision: str) -> None:+ """Append *decision* to the prompt and drop its buttons; the adapter's decision-only edit 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 Noneif isinstance(body, str) and body:+ body = body.replace(adapter._ea_deadline_line(), "") # same escaping as text_htmlwith 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)+ await adapter._edit_md_quiet(query, decision)diff --git a/tests/gateway/test_approval_timeout_notice.py b/tests/gateway/test_approval_timeout_notice.pyindex a556cbd0edc..ec775b573c4 100644--- a/tests/gateway/test_approval_timeout_notice.py+++ b/tests/gateway/test_approval_timeout_notice.py@@ -115,3 +115,32 @@ async def test_card_body_failure_still_sends_the_notice():ctx = SimpleNamespace(_status_adapter=_Adapter(), _status_chat_id="c", _status_thread_metadata=None)await settle_mod._post_timeout_notice(ctx, "ls", "card-9", 300)assert calls == [("send", settle_mod.format_approval_timed_out_notice(300))]+++async def test_timed_out_card_keeps_the_command_and_reason(monkeypatch):+ """The timeout edit replaces the card, so it must carry the request: command AND why it was flagged."""+ hooks, edits = _capture_settle(monkeypatch), []++ class _Adapter:+ def max_message_length_for_chat(self, chat_id):+ return 4096++ def message_len_fn_for_chat(self, chat_id):+ return len++ async def edit_message(self, chat_id, message_id, content):+ edits.append(content)+ return SimpleNamespace(success=True)++ runner = _Runner(current=True)+ runner._ctx = SimpleNamespace(session_key="telegram:1", _run_still_current=lambda: True, _status_adapter=_Adapter(),+ _status_chat_id="c", _status_thread_metadata=None)+ pending = []+ runner._schedule = lambda coro, label: pending.append(coro)+ settle_mod.register_timeout_notice(+ runner, {"request_id": "r4", "description": "delete in root path"}, command="rm -rf /x", card_message_id="9")+ hooks["r4"]("timeout")+ await pending[0]+ (content,) = edits+ assert "rm -rf /x" in content and "delete in root path" in contentdiff --git a/tests/gateway/test_teams.py b/tests/gateway/test_teams.pyindex caca1c81fe2..46d591abc1f 100644--- a/tests/gateway/test_teams.py+++ b/tests/gateway/test_teams.py@@ -1155,3 +1155,22 @@ async def test_expired_approval_click_keeps_the_request():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 texts+++async def test_resolved_card_shows_the_prompts_full_command_preview():+ """The button data carries the same command preview as the prompt card, so a command longer than a+ short stub is not cut short on the resolved card."""+ adapter = TeamsAdapter(_make_config(client_id="bot-id", client_secret="secret", tenant_id="tenant"))+ adapter._app, adapter._card_action_denied, adapter._invoke_card = object(), (lambda _from: None), (lambda body: body)+ adapter._send_card = AsyncMock()+ command = "echo " + "x" * 600 + " END"+ buttons = []+ with patch.object(sys.modules[TeamsAdapter.__module__], "ExecuteAction", lambda **kw: buttons.append(kw)):+ await adapter.send_exec_approval(chat_id="c1", command=command, session_key="s1", description="flagged")+ ctx = MagicMock()+ ctx.activity.value.action.data = buttons[0]["data"]+ with patch("tools.approval.has_blocking_approval", return_value=True), \+ patch("tools.approval.resolve_gateway_approval", return_value=1):+ body = await adapter._on_card_action(ctx)+ assert command in " ".join(str(block.text) for block in body)diff --git a/tests/gateway/test_telegram_approval_buttons.py b/tests/gateway/test_telegram_approval_buttons.pyindex 1fb82715400..b8654472b24 100644--- a/tests/gateway/test_telegram_approval_buttons.py+++ b/tests/gateway/test_telegram_approval_buttons.py@@ -360,8 +360,9 @@ class TestTelegramApprovalCallback:@pytest.mark.asyncioasync 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."""+ """The resolved prompt keeps its own rendering (command + reason, minus the moot deadline line) 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"@@ -369,7 +370,8 @@ async def test_resolved_approval_keeps_the_request_and_appends_the_decision():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"+ prompt_html = "<b>Dangerous command</b>\n<pre>rm -rf ./build && ls</pre>\nReason: delete"+ query.message.text_html = prompt_html + adapter._ea_deadline_line() # moot once decided: droppedquery.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), \@@ -381,5 +383,5 @@ async def test_resolved_approval_keeps_the_request_and_appends_the_decision():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 final["text"].startswith(prompt_html + "\n\n— ")assert "Ana & Bo" in final["text"]