Skip to content

The agent that grows with you

refactor: the Discord approval card's timeout notice goes through edit_message

kshitijk4poor62c89c1894c2
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 423b332bd22..f94913cbbc6 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -246,6 +246,12 @@ def _custom_unit_to_cp(s: str, budget: int, len_fn) -> int:
return lo
+def fit_prefix(text: str, budget: int, measure, suffix: str = "...") -> str:
+ """``text``, or its longest prefix within ``budget`` ``measure`` units plus ``suffix`` (outside it)."""
+ n = _custom_unit_to_cp(text, budget, measure)
+ return text if n == len(text) else text[:n] + suffix
+
+
def _prefix_within_utf16_limit(s: str, limit: int) -> str:
"""Longest prefix of *s* with UTF-16 length ≤ *limit*; never splits a surrogate pair."""
return s[:_custom_unit_to_cp(s, limit, utf16_len)]
@@ -2720,19 +2726,8 @@ class BasePlatformAdapter(ABC):
``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 "")
escape = escape or self._ea_escape
- len_fn = self.message_len_fn
- if len_fn(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_fn(escape(text[:mid])) <= budget:
- lo = mid
- else:
- hi = mid - 1
- return text[:lo] + suffix
+ return fit_prefix(str(text or ""), budget, lambda s: self.message_len_fn(escape(s)), 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."""
diff --git a/gateway/run_turn_runner_approval_settle.py b/gateway/run_turn_runner_approval_settle.py
index e02c7ca22d6..5525e29d6b8 100644
--- a/gateway/run_turn_runner_approval_settle.py
+++ b/gateway/run_turn_runner_approval_settle.py
@@ -12,9 +12,11 @@ Best-effort by design: a failed notice is logged at debug — the approval alrea
from __future__ import annotations
import logging
+import re
from typing import Any, Callable, Optional
from agent.i18n import t
+from gateway.platforms.base import fit_prefix
from gateway.platforms.base_exec_approval import approval_timeout_seconds, format_approval_timed_out_notice
logger = logging.getLogger(__name__)
@@ -64,25 +66,36 @@ 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,
- t("gateway.exec_approval.timed_out_card_body", notice=notice, command=command)):
+ if card_message_id and await _edit_card(adapter, ctx._status_chat_id, card_message_id, notice, command):
return
await adapter.send(ctx._status_chat_id, notice, metadata=metadata)
except Exception:
logger.debug("Approval timeout notice failed", exc_info=True)
-async def _edit_card(adapter, chat_id: str, message_id: str, content: str) -> bool:
- """Edit the card in place (drops the buttons on platforms whose edit replaces the markup)."""
- expire = getattr(type(adapter), "expire_exec_approval", None)
- edit: Optional[Callable[..., Any]] = (
- adapter.expire_exec_approval if callable(expire) else getattr(adapter, "edit_message", None)
- )
+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
+ message in the platform's own units (Telegram counts UTF-16), or the edit is truncated in
+ place behind a dangling "(1/N)" and keeps streaming-preview state. A run of backticks in the
+ command 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)
+ measure, suffix = adapter.message_len_fn_for_chat(chat_id), "..."
+ 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:
+ """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."""
+ edit: Optional[Callable[..., Any]] = getattr(adapter, "edit_message", None)
if edit is None:
return False
try:
- result = await edit(chat_id, message_id, content)
+ result = await edit(chat_id, message_id, _timed_out_card_body(adapter, chat_id, notice, command))
except Exception:
logger.debug("Approval card edit failed; sending the notice as a new message", exc_info=True)
return False
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index fa6694f8bd4..61a9e6255f6 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -5695,20 +5695,6 @@ class DiscordAdapter(DiscordAuthorizationMixin, DiscordMediaMixin, DiscordThread
+ len(self._approval_mention_content() or "") + 1)
return max(0, self.MAX_MESSAGE_LENGTH - fixed)
- async def expire_exec_approval(self, chat_id: str, message_id: str, content: str) -> SendResult:
- """Remove Discord's components when the backend approval expires."""
- if not self._client:
- return SendResult(success=False, error="Not connected")
- try:
- channel = await self._resolve_channel(chat_id)
- msg = channel.get_partial_message(int(message_id))
- content = self.truncate_message(self.format_message(content), self.MAX_MESSAGE_LENGTH)[0]
- await msg.edit(content=content, view=None)
- return SendResult(success=True, message_id=message_id)
- except Exception as exc:
- logger.warning("[Discord] Failed to expire approval card: %s", exc, exc_info=True)
- return SendResult(success=False, error=str(exc))
-
async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult:
"""Send an approval with content as its canonical payload and an embed for state."""
require_admin, admin_user_ids = _resolve_exec_approval_admin_gate(getattr(self.config, "extra", None))
diff --git a/tests/gateway/test_approval_timeout_notice.py b/tests/gateway/test_approval_timeout_notice.py
index 57d2c3852dd..a556cbd0edc 100644
--- a/tests/gateway/test_approval_timeout_notice.py
+++ b/tests/gateway/test_approval_timeout_notice.py
@@ -47,6 +47,12 @@ async def test_text_prompt_is_never_edited_in_place():
calls = []
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):
calls.append(("edit", message_id))
return SimpleNamespace(success=True)
@@ -63,15 +69,49 @@ async def test_text_prompt_is_never_edited_in_place():
@pytest.mark.asyncio
-async def test_timeout_notice_uses_platform_approval_expiry():
[email protected]("command", ["echo " + "x" * 5000, "echo " + "\U0001F600" * 3000], ids=["ascii", "astral"])
+async def test_card_body_fills_the_message_in_the_platforms_own_units(command):
+ """Telegram counts UTF-16 units: the command is cut to what fits in those units, so the edit
+ lands whole (no in-place truncation behind a dangling "(1/N)")."""
+ from gateway.platforms.base import utf16_len
+ edits = []
+
+ class _Utf16Adapter:
+ def max_message_length_for_chat(self, chat_id):
+ return 4096
+
+ def message_len_fn_for_chat(self, chat_id):
+ return utf16_len
+
+ async def edit_message(self, chat_id, message_id, content):
+ edits.append(content)
+ return SimpleNamespace(success=True)
+
+ ctx = SimpleNamespace(_status_adapter=_Utf16Adapter(), _status_chat_id="c", _status_thread_metadata=None)
+ await settle_mod._post_timeout_notice(ctx, command, "card-9", 300)
+ (content,) = edits
+ # An emoji is two units and is never split, so that cut may stop one unit short.
+ assert utf16_len(content) in ((4095, 4096) if "\U0001F600" in command else (4096,))
+ assert content.endswith("...\n```")
+
+
+async def test_card_body_failure_still_sends_the_notice():
calls = []
class _Adapter:
- async def expire_exec_approval(self, chat_id, message_id, content):
- calls.append((chat_id, message_id, content))
- return SimpleNamespace(success=True)
+ def max_message_length_for_chat(self, chat_id):
+ raise RuntimeError("limit lookup broke")
+
+ def message_len_fn_for_chat(self, chat_id):
+ return len
+
+ async def edit_message(self, chat_id, message_id, content):
+ calls.append("edit")
+
+ async def send(self, chat_id, content, metadata=None):
+ calls.append(("send", content))
ctx = SimpleNamespace(_status_adapter=_Adapter(), _status_chat_id="c", _status_thread_metadata=None)
- await settle_mod._post_timeout_notice(ctx, "ls", "card-9", 3600)
- assert len(calls) == 1
- assert calls[0][:2] == ("c", "card-9")
+ await settle_mod._post_timeout_notice(ctx, "ls", "card-9", 300)
+ assert calls == [("send", settle_mod.format_approval_timed_out_notice(300))]
diff --git a/tests/gateway/test_discord_approval_lifecycle.py b/tests/gateway/test_discord_approval_lifecycle.py
index 65931cc5b02..75a18681822 100644
--- a/tests/gateway/test_discord_approval_lifecycle.py
+++ b/tests/gateway/test_discord_approval_lifecycle.py
@@ -192,7 +192,8 @@ async def test_timeout_edits_cannot_restore_buttons_or_pending_embed(monkeypatch
state.update(kwargs)
message.edit.side_effect = edit
- notice_task = asyncio.create_task(adapter.expire_exec_approval("555", "1234", "Timed out"))
+ # The gateway's timeout notice edits the card through the generic edit_message.
+ notice_task = asyncio.create_task(adapter.edit_message("555", "1234", "Timed out"))
retire_task = asyncio.create_task(view.retire("timeout"))
await asyncio.wait_for(asyncio.gather(*(event.wait() for event in entered.values())), 5)
first, last = ("retire", "notice") if notice_last else ("notice", "retire")
@@ -292,3 +293,29 @@ async def test_failed_click_keeps_a_pending_card_live(monkeypatch):
assert (footer["text"] if isinstance(footer, dict) else footer.text) == t(
"platform.discord.approval.already_resolved")
assert view.is_finished()
+
+
+_FENCED_TABLE = "cat <<'EOF'\n```\n| item | " + "description " * 10 + "|\n|---|---|\n" + "| a | b |\n" * 30 + "```\nEOF"
+
+
[email protected]("command", ["echo " + "x" * 5000, _FENCED_TABLE * 10, ("echo '" + "`" * 7 + "' ") * 300],
+ ids=["long", "fenced-table", "backtick-runs"])
+async def test_timeout_notice_fits_the_command_into_one_in_place_edit(monkeypatch, command):
+ """The gateway's notice reaches the real Discord edit as one message: the command is cut to
+ the room left and cannot close the card's fence (Discord would rewrite a table after it into
+ a longer bullet list), so no "(1/N)" marker and no streaming-preview state are left."""
+ from gateway import run_turn_runner_approval_settle as settle_mod
+
+ adapter, _view, _entry, message = await _pending_card(monkeypatch)
+ adapter.send = AsyncMock()
+ ctx = SimpleNamespace(_status_adapter=adapter, _status_chat_id="555", _status_thread_metadata=None)
+
+ await settle_mod._post_timeout_notice(ctx, command, "1234", 300)
+
+ message.edit.assert_awaited_once()
+ content = message.edit.await_args.kwargs["content"]
+ assert content.endswith("...\n```") and len(content) == adapter.MAX_MESSAGE_LENGTH
+ assert content.count("```") == 2 # only the card's own fence
+ assert "(1/" not in content and adapter._last_overflow_preview == {}
+ adapter.send.assert_not_awaited()
diff --git a/tests/gateway/test_discord_exec_approval_content.py b/tests/gateway/test_discord_exec_approval_content.py
index d5a891a1ab8..ccc9db9a39a 100644
--- a/tests/gateway/test_discord_exec_approval_content.py
+++ b/tests/gateway/test_discord_exec_approval_content.py
@@ -137,19 +137,6 @@ async def test_unsettled_click_without_an_observer_marks_the_card_expired(monkey
interaction.response.send_message.assert_not_awaited()
-async def test_expired_approval_removes_discord_components():
- adapter = DiscordAdapter(PlatformConfig(enabled=True, token="***"))
- message = SimpleNamespace(edit=AsyncMock())
- channel = SimpleNamespace(get_partial_message=lambda _id: message)
- adapter._client = SimpleNamespace(get_channel=lambda _id: channel)
-
- result = await adapter.expire_exec_approval("555", "1234", "Approval timed out")
-
- assert result.success
- assert message.edit.await_args.kwargs["view"] is None
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize("ends,footer_key", [
("after_send", "platform.discord.prompt.expired_footer"),
diff --git a/tests/gateway/test_exec_approval_timeout_notice.py b/tests/gateway/test_exec_approval_timeout_notice.py
index 0bd81467eb5..2c24c191593 100644
--- a/tests/gateway/test_exec_approval_timeout_notice.py
+++ b/tests/gateway/test_exec_approval_timeout_notice.py
@@ -35,6 +35,12 @@ class _ButtonAdapter:
self.send_metadata: list[Any] = []
self._editable = editable
+ def max_message_length_for_chat(self, chat_id: str) -> int:
+ return 4096
+
+ def message_len_fn_for_chat(self, chat_id: str):
+ return len
+
def pause_typing_for_chat(self, chat_id: str) -> None:
return None