The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preserve configured Discord timeouts and retire approval views
Gille39b2158afc61
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 21631f835fc..3dd6b576031 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -5744,8 +5744,13 @@ class DiscordAdapter(DiscordAuthorizationMixin, DiscordMediaMixin, DiscordThreadview = view_holder[0]loop = asyncio.get_running_loop()- def retire(_reason):- loop.call_soon_threadsafe(lambda: loop.create_task(view.retire()))+ def retire(reason):+ def schedule():+ task = loop.create_task(view.retire(reason))+ self._background_tasks.add(task)+ task.add_done_callback(self._background_tasks.discard)+ task.add_done_callback(_consume_background_task_result)+ loop.call_soon_threadsafe(schedule)if not observe_gateway_settle(prompt.session_key, view.request_id, retire):await view.retire()@@ -6467,12 +6472,11 @@ def _define_discord_view_classes() -> None:allow_permanent: bool = True, allow_session: bool = True, smart_denied: bool = False,request_id: Optional[str] = None,):- # The backend starts waiting only after delivery. Its settlement retires- # this exact card; a separate view timer could expire it prematurely.- timeout = None if request_id else _read_discord_prompt_timeout()- super().__init__(allowed_user_ids, allowed_role_ids, timeout=timeout)+ super().__init__(allowed_user_ids, allowed_role_ids, timeout=_read_discord_prompt_timeout())self.session_key = session_keyself.request_id = request_id+ self._backend_settled = False+ self._retire_lock = asyncio.Lock()self.require_admin = require_adminself.admin_user_ids = {str(a).strip() for a in (admin_user_ids or set()) if str(a).strip()}self._localize_buttons(@@ -6508,18 +6512,34 @@ def _define_discord_view_classes() -> None:)return False- async def retire(self):+ async def on_timeout(self):+ await self.retire("timeout", backend_settled=False)++ async def retire(self, reason="resolved", *, backend_settled=True):"""Disable a card when its particular backend request is no longer pending."""- if self.resolved:- return- self.resolved = True- self._disable_all()- if self._message:- try:- await self._message.edit(view=self)- except Exception:- logger.debug("[Discord] Could not retire approval card", exc_info=True)self.stop()+ # A UI timeout can precede a text answer. Serialize their edits, and+ # never let a queued UI timeout overwrite a backend settlement.+ async with self._retire_lock:+ if self._backend_settled:+ return+ self._backend_settled = backend_settled+ self.resolved = True+ self._disable_all()+ footer = t({+ "resolved": "platform.discord.approval.already_resolved",+ "timeout": "platform.discord.prompt.expired_footer",+ }.get(reason, "platform.discord.slash_confirm.resolved_cancel"))+ if self._message:+ try:+ embed = self._first_embed(self._message)+ if embed:+ embed.color = discord.Color.greyple()+ embed.set_footer(text=footer)+ # Notices edit content independently; neither restores controls.+ await self._message.edit(embed=embed, view=None)+ except Exception:+ logger.debug("[Discord] Could not retire approval card", exc_info=True)async def _resolve(self, interaction: discord.Interaction, choice: str, color: discord.Color, label_key: str):"""Resolve the approval via the gateway approval queue and update the embed."""@@ -6530,6 +6550,7 @@ def _define_discord_view_classes() -> None:returnlabel = t(label_key)self.resolved = True+ self._backend_settled = True# Unblock the waiting agent thread FIRST. A click after the approval# wait timed out (count == 0) must not claim "Approved".try:@@ -6545,9 +6566,12 @@ def _define_discord_view_classes() -> None:if not count:color = discord.Color.dark_grey()label = t("platform.discord.approval.expired")- await self._finalize_embed(- interaction, color,- t("platform.discord.approval.by_user", label=label, user=interaction.user.display_name) if count else label)+ try:+ await self._finalize_embed(+ interaction, color,+ t("platform.discord.approval.by_user", label=label, user=interaction.user.display_name) if count else label)+ finally:+ self.stop()# Decorator labels are placeholders; ``_localize_buttons`` in __init__ sets the real text.@discord.ui.button(label="Allow Once", style=discord.ButtonStyle.green)diff --git a/plugins/platforms/discord/adapter_config_readers.py b/plugins/platforms/discord/adapter_config_readers.pyindex 0a1fa2ffc78..bbfca1b4a95 100644--- a/plugins/platforms/discord/adapter_config_readers.py+++ b/plugins/platforms/discord/adapter_config_readers.py@@ -4,6 +4,8 @@ Re-exported from ``plugins.platforms.discord.adapter`` (callers and tests import"""from typing import Any, Optional+from agent.deadline import MAX_SAFE_TIMEOUT_S+def _read_dm_role_auth_guild() -> Optional[int]:"""Return the guild ID opted-in for DM role-based auth, or None (secure default). Read from@@ -24,16 +26,15 @@ def _read_dm_role_auth_guild() -> Optional[int]:return guild_id if guild_id > 0 else None-# Default timeout for non-exec Discord button views when ``approvals.discord_prompt_timeout`` is unset;-# Discord interaction tokens expire at ~15 minutes, so 900s is the practical ceiling.+# All Discord prompt views share this setting; command approval waits have their own timeout._DISCORD_PROMPT_TIMEOUT_DEFAULT = 300_DISCORD_PROMPT_TIMEOUT_MIN = 30-_DISCORD_PROMPT_TIMEOUT_MAX = 900+_DISCORD_PROMPT_TIMEOUT_MAX = int(MAX_SAFE_TIMEOUT_S)def _read_discord_prompt_timeout() -> int:- """Timeout (seconds) for non-exec Discord button views from ``approvals.discord_prompt_timeout``- (default 300), clamped to [MIN, MAX] so a typo can't make prompts vanish or outlive tokens."""+ """Timeout (seconds) for Discord button views from ``approvals.discord_prompt_timeout``+ (default 300), clamped to [MIN, MAX] to keep their UI lifetime bounded."""raw: Any = Nonetry:from hermes_cli.config import read_raw_configdiff --git a/tests/gateway/conftest.py b/tests/gateway/conftest.pyindex 0c79e3c2649..99cf489ce23 100644--- a/tests/gateway/conftest.py+++ b/tests/gateway/conftest.py@@ -271,8 +271,11 @@ def _ensure_discord_mock() -> None:def __init__(self, timeout=None):self.timeout = timeoutself.children = []+ self._finished = Falsedef stop(self):- pass+ self._finished = True+ def is_finished(self):+ return self._finisheddef add_item(self, item):self.children.append(item)def clear_items(self):diff --git a/tests/gateway/test_discord_approval_lifecycle.py b/tests/gateway/test_discord_approval_lifecycle.pynew file mode 100644index 00000000000..65d21c7e52a--- /dev/null+++ b/tests/gateway/test_discord_approval_lifecycle.py@@ -0,0 +1,171 @@+"""Approval cards must release their view and preserve terminal state across edits."""++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from agent.i18n import t+from gateway.config import PlatformConfig+from plugins.platforms.discord import adapter as discord_adapter+from tools import approval+from tools.approval_gateway_wait import _ApprovalEntry+++async def _pending_card(monkeypatch):+ adapter = discord_adapter.DiscordAdapter(PlatformConfig(enabled=True, token="***"))+ session = "agent:other:discord:555"+ entry = _ApprovalEntry({"request_id": "request-1", "command": "ls"})+ monkeypatch.setitem(approval._gateway_queues, session, [entry])+ message = SimpleNamespace(id=1234, edit=AsyncMock(), embeds=[])+ sent = {}++ async def send(**kwargs):+ sent.update(kwargs)+ message.embeds = [kwargs["embed"]]+ return message++ channel = SimpleNamespace(send=send, get_partial_message=lambda _id: message)+ adapter._client = SimpleNamespace(get_channel=lambda _id: channel)+ await adapter.send_exec_approval(+ chat_id="555", command="ls", session_key=session,+ metadata={"_approval_request_id": "request-1"},+ )+ return adapter, sent["view"], entry, message++[email protected]("edit_fails", [False, True])+async def test_click_stops_view_even_if_interaction_edit_fails(monkeypatch, edit_fails):+ adapter, view, entry, message = await _pending_card(monkeypatch)+ monkeypatch.setattr(view, "_gate", AsyncMock(return_value=True))+ edit = AsyncMock(side_effect=RuntimeError("Discord unavailable") if edit_fails else None)+ interaction = SimpleNamespace(+ message=message, user=SimpleNamespace(display_name="tester"),+ response=SimpleNamespace(edit_message=edit),+ )+ if edit_fails:+ with pytest.raises(RuntimeError, match="Discord unavailable"):+ await view._resolve(interaction, "once", 2, "platform.discord.approval.resolved_once")+ else:+ await view._resolve(interaction, "once", 2, "platform.discord.approval.resolved_once")+ assert entry.result == "once"+ assert view.is_finished()+ footer = message.embeds[0].footer+ entry.observers[0]("resolved")+ await asyncio.sleep(0)+ await asyncio.gather(*adapter._background_tasks)+ assert view.is_finished()+ assert message.embeds[0].footer == footer+ message.edit.assert_not_awaited()++[email protected]("ui_timeout_first", [True, False])+async def test_ui_timeout_does_not_end_wait_or_overwrite_later_answer(monkeypatch, ui_timeout_first):+ _adapter, view, entry, message = await _pending_card(monkeypatch)+ if ui_timeout_first:+ await view.on_timeout()+ assert not entry.event.is_set()+ assert entry.result is None+ assert approval._gateway_queues[view.session_key] == [entry]+ assert approval.resolve_gateway_approval(view.session_key, "once", request_id=view.request_id) == 1+ await view.retire("resolved")+ if not ui_timeout_first:+ await view.on_timeout()+ footer = message.embeds[0].footer+ assert (footer["text"] if isinstance(footer, dict) else footer.text) == t(+ "platform.discord.approval.already_resolved")+ assert view.is_finished()++[email protected]("reason,footer_key", [+ ("resolved", "platform.discord.approval.already_resolved"),+ ("timeout", "platform.discord.prompt.expired_footer"),+ ("interrupted", "platform.discord.slash_confirm.resolved_cancel"),+ ("session_closed", "platform.discord.slash_confirm.resolved_cancel"),+ ("notify_failed", "platform.discord.slash_confirm.resolved_cancel"),+])+async def test_external_settlement_retires_card_and_tracks_edit(monkeypatch, reason, footer_key):+ adapter, view, entry, message = await _pending_card(monkeypatch)+ pending_color = message.embeds[0].color+ entered, release = asyncio.Event(), asyncio.Event()++ async def edit(**_kwargs):+ entered.set()+ await release.wait()++ message.edit.side_effect = edit+ entry.observers[0](reason)+ await asyncio.wait_for(entered.wait(), 5)+ assert view.is_finished()+ assert len(adapter._background_tasks) == 1+ task = next(iter(adapter._background_tasks))+ kwargs = message.edit.await_args.kwargs+ assert kwargs["view"] is None+ embed = kwargs["embed"]+ footer = embed.footer+ assert (footer["text"] if isinstance(footer, dict) else footer.text) == t(footer_key)+ assert embed.color != pending_color+ release.set()+ await task+ await asyncio.sleep(0)+ assert not adapter._background_tasks+++async def test_inflight_ui_expiry_cannot_overwrite_backend_answer(monkeypatch):+ _adapter, view, _entry, message = await _pending_card(monkeypatch)+ entered, release = asyncio.Event(), asyncio.Event()+ displayed = []++ async def edit(**kwargs):+ footer = kwargs["embed"].footer+ text = footer["text"] if isinstance(footer, dict) else footer.text+ if not entered.is_set():+ entered.set()+ await release.wait()+ displayed.append(text)++ message.edit.side_effect = edit+ ui_task = asyncio.create_task(view.on_timeout())+ await asyncio.wait_for(entered.wait(), 5)+ backend_task = asyncio.create_task(view.retire("resolved"))+ await asyncio.sleep(0)+ release.set()+ await asyncio.gather(ui_task, backend_task)+ assert displayed == [t("platform.discord.prompt.expired_footer"),+ t("platform.discord.approval.already_resolved")]++[email protected]("notice_last", [False, True])+async def test_timeout_edits_cannot_restore_buttons_or_pending_embed(monkeypatch, notice_last):+ adapter, view, _entry, message = await _pending_card(monkeypatch)+ pending_color = message.embeds[0].color+ entered = {name: asyncio.Event() for name in ("notice", "retire")}+ release = {name: asyncio.Event() for name in entered}+ state = {"content": "command", "view": view, "embed": message.embeds[0]}++ async def edit(**kwargs):+ name = "notice" if "content" in kwargs else "retire"+ entered[name].set()+ await release[name].wait()+ state.update(kwargs)++ message.edit.side_effect = edit+ notice_task = asyncio.create_task(adapter.expire_exec_approval("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")+ tasks = {"notice": notice_task, "retire": retire_task}+ release[first].set()+ await tasks[first]+ release[last].set()+ await tasks[last]+ assert state["content"] == "Timed out"+ assert state["view"] is None+ assert state["embed"].color != pending_color+ assert view.is_finished()diff --git a/tests/gateway/test_discord_exec_approval_content.py b/tests/gateway/test_discord_exec_approval_content.pyindex 7f8423760b4..63b3305b0be 100644--- a/tests/gateway/test_discord_exec_approval_content.py+++ b/tests/gateway/test_discord_exec_approval_content.py@@ -67,7 +67,11 @@ async def test_exec_approval_content_stays_within_discord_cap_for_long_reason():@pytest.mark.asyncio-async def test_exec_approval_view_uses_the_waiting_request_timeout():+async def test_exec_approval_view_honors_discord_timeout_with_request_id(monkeypatch):+ import hermes_cli.config+ monkeypatch.setattr(hermes_cli.config, "read_raw_config", lambda: {+ "approvals": {"timeout": 7200, "discord_prompt_timeout": 3600},+ })adapter = DiscordAdapter(PlatformConfig(enabled=True, token="***"))sent = _capture_channel(adapter)@@ -77,7 +81,7 @@ async def test_exec_approval_view_uses_the_waiting_request_timeout():)assert result.success- assert sent["view"].timeout is None+ assert sent["view"].timeout == 3600assert sent["view"].request_id == "request-1"@@ -131,7 +135,7 @@ async def test_card_retires_when_backend_request_ends(monkeypatch, expire_duringsession = "agent:other:discord:555"entry = _ApprovalEntry({"request_id": "request-1", "command": "ls"})monkeypatch.setitem(approval._gateway_queues, session, [entry])- message = SimpleNamespace(id=1234, edit=AsyncMock())+ message = SimpleNamespace(id=1234, edit=AsyncMock(), embeds=[])sent = {}async def send(**kwargs):diff --git a/tests/gateway/test_discord_prompt_timeout_config.py b/tests/gateway/test_discord_prompt_timeout_config.pyindex 66c3b69658f..cb2810cb096 100644--- a/tests/gateway/test_discord_prompt_timeout_config.py+++ b/tests/gateway/test_discord_prompt_timeout_config.py@@ -1,16 +1,17 @@"""Tests for the configurable Discord interactive-view timeout.-SlashConfirmView, UpdatePromptView, and ClarifyChoiceView read+ExecApprovalView, SlashConfirmView, UpdatePromptView, and ClarifyChoiceView read``approvals.discord_prompt_timeout`` with the same 300s default, clamped to``[_DISCORD_PROMPT_TIMEOUT_MIN, _DISCORD_PROMPT_TIMEOUT_MAX]`` so a typo-can't make prompts disappear (too short) or outlive Discord's 15-min-interaction-token expiry (too long).+can't make prompts disappear or exceed the shared platform-safe timeout cap."""import sysfrom types import SimpleNamespacefrom unittest.mock import MagicMock+import pytest+def _ensure_discord_mock():if "discord" in sys.modules and hasattr(sys.modules["discord"], "__file__"):return@@ -75,3 +76,41 @@ def test_value_clamped_to_minimum(monkeypatch):"""A typo of e.g. 5 seconds must not make prompts disappear."""_patch_config(monkeypatch, {"approvals": {"discord_prompt_timeout": 5}})assert _read_discord_prompt_timeout() == _DISCORD_PROMPT_TIMEOUT_MIN+++def test_hour_long_timeout_and_safe_upper_bound(monkeypatch):+ from agent.deadline import MAX_SAFE_TIMEOUT_S++ _patch_config(monkeypatch, {"approvals": {"discord_prompt_timeout": 3600}})+ assert _read_discord_prompt_timeout() == 3600+ _patch_config(monkeypatch, {"approvals": {"discord_prompt_timeout": int(MAX_SAFE_TIMEOUT_S) + 1}})+ assert _read_discord_prompt_timeout() == int(MAX_SAFE_TIMEOUT_S)+++async def test_all_prompt_types_use_owning_profile_discord_timeout(tmp_path):+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override+ from plugins.platforms.discord.adapter import (+ ExecApprovalView, SlashConfirmView, UpdatePromptView, ClarifyChoiceView,+ )++ for name, expected in (("default", 300), ("other", 3600)):+ home = tmp_path / name+ home.mkdir()+ (home / "config.yaml").write_text(+ "approvals:\n timeout: 7200\n" + (+ " discord_prompt_timeout: 3600\n" if name == "other" else ""), encoding="utf-8",+ )+ token = set_hermes_home_override(str(home))+ try:+ views = [+ ExecApprovalView("session", set(), request_id="request"),+ SlashConfirmView("session", "confirm", set()),+ UpdatePromptView("session", set()),+ ClarifyChoiceView(["yes"], "clarify", set()),+ ]+ assert [view.timeout for view in views] == [expected] * 4+ for view in views:+ view.stop()+ finally:+ reset_hermes_home_override(token)diff --git a/website/docs/user-guide/messaging/discord.md b/website/docs/user-guide/messaging/discord.mdindex 8cd322ca9f5..87b45133c76 100644--- a/website/docs/user-guide/messaging/discord.md+++ b/website/docs/user-guide/messaging/discord.md@@ -784,6 +784,26 @@ The buttons disable themselves once a choice is made so duplicate clicks don't dInteractive prompts (command approvals, `clarify` questions, and slash-command confirmations) share one layout: the **plain message** carries the full payload — the command and why it was flagged plus the approval deadline, or the question and reply hint — the **embed card** underneath is a header only, and the buttons sit below the card. Everything you need to decide is in the plain text, so the prompt reads correctly on clients that hide or detach embeds, and nothing is shown twice on clients that render them.+`approvals.discord_prompt_timeout` controls Discord's interactive button views for+command approvals, clarification questions, update prompts, and slash-command+confirmations. It defaults to 300 seconds, with a minimum of 30 seconds and the same+platform-safe upper bound as `approvals.timeout`.++`approvals.timeout` separately controls how long a command waits for approval. To+allow one hour for both the command and its Discord buttons, set both in the owning+profile's `config.yaml`:++```yaml+approvals:+ timeout: 3600+ discord_prompt_timeout: 3600+```++Each command-approval card answers its own request. Its controls retire when that+request is answered, cancelled, or expires, even if the Discord view timeout is+longer. A shorter Discord timeout retires the buttons without extending or ending+the underlying approval wait.+## Home ChannelYou can designate a "home channel" where the bot sends proactive messages (such as cron job output, reminders, and notifications). There are two ways to set it: