From cade8c61de390138a34272bce8328bab3ad8859e Mon Sep 17 00:00:00 2001 From: mintaka Date: Mon, 23 Nov 2026 00:06:24 -0500 Subject: [PATCH] fix(hermes): send Discord approval cards through the live adapter (RIG-12360) Approval cards failed with Not connected while replies to the same thread worked: after a reconnect the turn kept the adapter it started with, and that adapter's client was gone. Resolve the live delivery adapter for the card, its timeout notice and resume typing, as the reply path does. When the card send fails, post the text prompt in the thread and mention only the requester. If both fail, mark the approval undelivered and log an error instead of withdrawing silently. A card whose send timed out may be on screen, so it does not trigger a second text prompt. Refs: RIG-12360, RIG-12369 Co-authored-by: Matt Wilkinson --- forks/hermes-agent/gateway/run_turn_runner.py | 13 +- .../run_turn_runner_approval_settle.py | 8 +- .../plugins/platforms/discord/adapter.py | 52 +++++-- .../test_decline_fallback_suppression.py | 2 +- .../gateway/test_discord_allowed_mentions.py | 4 + .../gateway/test_discord_approval_index.py | 2 +- .../test_discord_approval_reconnect.py | 139 ++++++++++++++++-- .../tests/gateway/test_discord_connect.py | 4 + .../test_exec_approval_timeout_notice.py | 11 ++ 9 files changed, 197 insertions(+), 38 deletions(-) diff --git a/forks/hermes-agent/gateway/run_turn_runner.py b/forks/hermes-agent/gateway/run_turn_runner.py index 4ac0ccee6..5d8f980c5 100644 --- a/forks/hermes-agent/gateway/run_turn_runner.py +++ b/forks/hermes-agent/gateway/run_turn_runner.py @@ -713,7 +713,8 @@ def _text_fallback(): except Exception: logger.debug("request_reopen_seed after clarify answer failed", exc_info=True) try: - ctx._status_adapter.resume_typing_for_chat(ctx._status_chat_id) + (self._runner._delivery_adapter_for(ctx.source) if getattr(ctx, "source", None) is not None + else ctx._status_adapter).resume_typing_for_chat(ctx._status_chat_id) except Exception: logger.debug("resume_typing_for_chat after clarify answer failed", exc_info=True) return response, answered @@ -736,7 +737,9 @@ def _render_approval_sync(self, approval_data: dict) -> None: from gateway.run_turn_runner_approval_settle import register_timeout_notice from gateway.run_turn_runner_approval_text import approval_text_prompt ctx = self._ctx - adapter = ctx._status_adapter + adapter = self._runner._delivery_adapter_for(ctx.source) if getattr(ctx, "source", None) is not None else ctx._status_adapter + if adapter is None: + raise RuntimeError("exec approval undeliverable: no live delivery adapter") # Slack's assistant_threads_setStatus disables the compose box, so the user can't type # /approve while "is thinking..." shows. Pausing stops _keep_typing re-setting it; resumed # in approve/deny. @@ -773,7 +776,7 @@ def _render_approval_sync(self, approval_data: dict) -> None: # learns the command did NOT run (only the TUI registered a settle hook). register_timeout_notice( self, approval_data, command=cmd, - card_message_id=getattr(fut.result(timeout=0), "message_id", None)) + card_message_id=getattr(fut.result(timeout=0), "message_id", None), adapter=adapter) return if outcome == "ambiguous": # Timeout ≠ failure: the card may have posted with a late ack. The prompt @@ -790,7 +793,7 @@ def _render_approval_sync(self, approval_data: dict) -> None: raw = getattr(fut.result(timeout=0), "raw_response", None) if fut.exception(timeout=0) is None else None if outcome == "failed" and isinstance(raw, dict) and raw.get("approval_text_fallback_posted"): # The adapter already posted the text prompt in the approval's thread and owns its deadline. - register_timeout_notice(self, approval_data, command=cmd, card_message_id=None) + register_timeout_notice(self, approval_data, command=cmd, card_message_id=None, adapter=adapter) return if outcome == "declined": # P5(b): the connector AUTHORIZED this destination and @@ -845,7 +848,7 @@ def _render_approval_sync(self, approval_data: dict) -> None: approval_data.get("request_id"), ctx.session_key) # No card to edit on the text path: the prompt has no buttons to drop and carries # the /approve instructions, so the timeout notice is posted as a new message. - register_timeout_notice(self, approval_data, command=cmd, card_message_id=None) + register_timeout_notice(self, approval_data, command=cmd, card_message_id=None, adapter=adapter) except Exception as e: logger.error("Failed to send approval request: %s", e) diff --git a/forks/hermes-agent/gateway/run_turn_runner_approval_settle.py b/forks/hermes-agent/gateway/run_turn_runner_approval_settle.py index 1b0ae6fda..0ca3dd754 100644 --- a/forks/hermes-agent/gateway/run_turn_runner_approval_settle.py +++ b/forks/hermes-agent/gateway/run_turn_runner_approval_settle.py @@ -24,7 +24,7 @@ def register_timeout_notice( - runner, approval_data: dict, *, command: str, card_message_id: Optional[str]) -> None: + runner, approval_data: dict, *, command: str, card_message_id: Optional[str], adapter=None) -> None: """Arm a settle hook that posts the timed-out notice for ``approval_data['request_id']``. ``runner`` is the ``TurnRunner`` (for ``_ctx`` and ``_schedule``); ``card_message_id`` is the @@ -54,7 +54,7 @@ def settle(reason: str) -> None: if callable(still_current) and not still_current(): return runner._schedule( - _post_timeout_notice(runner._ctx, command, card_message_id, timeout_s, flagged), + _post_timeout_notice(runner._ctx, command, card_message_id, timeout_s, flagged, adapter=adapter), "Approval timeout notice scheduling error") register_gateway_settle(session_key, request_id, settle) @@ -78,12 +78,12 @@ def settle(choice: str) -> None: async def _post_timeout_notice( - ctx, command: str, card_message_id: Optional[str], timeout_s: int, reason: str = "") -> None: + ctx, command: str, card_message_id: Optional[str], timeout_s: int, reason: str = "", *, adapter=None) -> None: from gateway.run import _interim_metadata from gateway.bot_peer_notices import automatic_notices_allowed - adapter = ctx._status_adapter + adapter = adapter if adapter is not None else ctx._status_adapter if not automatic_notices_allowed(getattr(ctx, "source", None)): return notice = format_approval_timed_out_notice(timeout_s) diff --git a/forks/hermes-agent/plugins/platforms/discord/adapter.py b/forks/hermes-agent/plugins/platforms/discord/adapter.py index 952d9bb30..47cbbc389 100644 --- a/forks/hermes-agent/plugins/platforms/discord/adapter.py +++ b/forks/hermes-agent/plugins/platforms/discord/adapter.py @@ -3361,8 +3361,16 @@ async def send( chunk_reference = reference else: # "first" (default) or "off" chunk_reference = reference if i == 0 else None + send_kwargs = {"content": chunk, "reference": chunk_reference} + if metadata and metadata.get("_approval_mentions"): + allowed_mentions_cls = getattr(discord, "AllowedMentions", None) + if allowed_mentions_cls is not None: + send_kwargs["allowed_mentions"] = allowed_mentions_cls( + users=[discord.Object(id=int(metadata["_approval_mentions"]))], + roles=False, everyone=False, replied_user=False, + ) try: - msg = await channel.send(content=chunk, reference=chunk_reference) + msg = await channel.send(**send_kwargs) except Exception as e: if chunk_reference is not None and self._is_reply_reference_rejected(e): logger.warning( @@ -3370,7 +3378,8 @@ async def send( self.name, reply_to, ) reference = None - msg = await channel.send(content=chunk, reference=None) + retry_kwargs = {**send_kwargs, "reference": None} + msg = await channel.send(**retry_kwargs) else: raise message_ids.append(str(msg.id)) @@ -5733,7 +5742,7 @@ async def _send_prompt( """Shared tail for interactive prompts: resolve target channel, call ``build(channel) -> (send_kwargs, view)``, send, remember the message on the view. ``fail_log`` labels failures.""" if not self._client or not DISCORD_AVAILABLE: - return SendResult(success=False, error="Not connected") + return SendResult(success=False, error="Not connected", retryable=DISCORD_AVAILABLE) try: client = self._client channel = await self._resolve_channel(_prompt_target_id(chat_id, metadata)) @@ -5747,9 +5756,10 @@ async def _send_prompt( view.bound_client = client return SendResult(success=True, message_id=str(msg.id)) except Exception as e: + retryable = _is_discord_transport_error(e) if fail_log: logger.warning("[%s] %s failed: %s", self.name, fail_log, e) - return SendResult(success=False, error=str(e)) + return SendResult(success=False, error=str(e), retryable=retryable) # Payload lives in plain content: embeds can be invisible/detached on web/mobile. Properties, not # class constants: the wording comes from the catalog for the language active at send time. @@ -5965,22 +5975,21 @@ async def _reply_unanswered_approval_press(self, interaction, custom_id: str, te custom_id, exc_info=True) async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult: - """Send an approval card. A card that fails or does not confirm within ``approval_card_confirm_timeout`` - keeps its request pending: the plain-text prompt goes to the approval's thread, and the request is - withdrawn if nobody answers it within the same window.""" + """Send the card, then fall back to text before withdrawing.""" view = self._new_exec_approval_view(prompt) window = _read_approval_card_confirm_timeout(getattr(self.config, "extra", None)) try: result = await asyncio.wait_for(self._send_exec_approval_card(prompt, view), window) except TimeoutError: result = SendResult(success=False, error=_CARD_CONFIRM_TIMEOUT_ERROR) + except Exception as exc: + result = SendResult(success=False, error=str(exc), retryable=_is_discord_transport_error(exc)) from gateway.relay.egress import declined_send if result.success or not view.request_id or declined_send(result): return result logger.warning("[%s] approval card not delivered (request_id=%s): %s; posting the text prompt", self.name, view.request_id, result.error) view.undelivered = True - # The withdrawal starts before the fallback send, so a hung send cannot hold the request past the window. view.undelivered_withdrawal = task = asyncio.get_running_loop().create_task( self._withdraw_undelivered_approval(prompt.session_key, view.request_id, window)) self._background_tasks.add(task) @@ -5988,16 +5997,16 @@ async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendRe task.add_done_callback(_consume_background_task_result) text_failure = await self._send_exec_approval_text_fallback(prompt) if text_failure is not None and result.error != _CARD_CONFIRM_TIMEOUT_ERROR: - # Card and text fallback both failed: no surface shows the prompt, so a /stop must say so. A reconnect - # repost that already showed the card wins: its request is not marked, even if this fallback fails later. from tools.approval import mark_gateway_approval_undelivered - mark_gateway_approval_undelivered(prompt.session_key, view.request_id, f"{result.error}, then {text_failure}") - return SendResult(success=False, error=result.error, raw_response={"approval_text_fallback_posted": True}) + reason = f"{result.error}, then {text_failure}" + if mark_gateway_approval_undelivered(prompt.session_key, view.request_id, reason): + logger.error("[%s] approval prompt was never delivered (request_id=%s): %s", + self.name, view.request_id, reason) + return SendResult(success=False, error=result.error, + raw_response={"approval_text_fallback_posted": True}) async def _send_exec_approval_text_fallback(self, prompt: ExecApprovalPrompt) -> str | None: - """Post the plain-text approval prompt in the approval's own thread. Never raises. Returns ``None`` when the - text prompt was delivered, else the failure reason. The request is withdrawn after approval_card_confirm_timeout, - so the prompt states that window, not approvals.timeout.""" + """Post the text fallback in the approval thread with the card's opt-in owner mention.""" from gateway.run_turn_runner_approval_text import approval_text_prompt actions = set(prompt.choices) window = _read_approval_card_confirm_timeout(getattr(self.config, "extra", None)) @@ -6005,8 +6014,19 @@ async def _send_exec_approval_text_fallback(self, prompt: ExecApprovalPrompt) -> prompt.description, getattr(self, "typed_command_prefix", "/"), allow_permanent="always" in actions, allow_session="session" in actions, smart_denied=prompt.smart_denied, deadline_s=math.ceil(window)) + from tools.approval import list_gateway_approval_authority + authority = next((a for a in list_gateway_approval_authority(prompt.session_key) + if a.get("request_id") == prompt.request_id), {}) + requester = str(authority.get("requester_id") or "") + mention = (requester.isdigit() and self._approval_mention_content() + and self._approval_mentions_target() == "session") + if mention: + text = f"<@{requester}>\n{text}" try: - metadata = {**(prompt.metadata or {}), "is_approval_prompt": True} + thread_id = _prompt_target_id(prompt.chat_id, prompt.metadata) + metadata = {**(prompt.metadata or {}), "thread_id": thread_id, "is_approval_prompt": True} + if mention: + metadata["_approval_mentions"] = requester result = await self.send(prompt.chat_id, text, metadata=metadata) if not getattr(result, "success", False): return getattr(result, "error", None) or "text prompt send failed" diff --git a/forks/hermes-agent/tests/gateway/test_decline_fallback_suppression.py b/forks/hermes-agent/tests/gateway/test_decline_fallback_suppression.py index 50b000f63..4292e0b28 100644 --- a/forks/hermes-agent/tests/gateway/test_decline_fallback_suppression.py +++ b/forks/hermes-agent/tests/gateway/test_decline_fallback_suppression.py @@ -63,7 +63,7 @@ def _runner(adapter: _Adapter): session_key="sk1", source=SimpleNamespace(chat_id="C1", platform="discord", session_key="sk1"), ) - runner = TurnRunner(SimpleNamespace(), ctx) + runner = TurnRunner(SimpleNamespace(_delivery_adapter_for=lambda _source: adapter), ctx) class _Fut: def __init__(self, result): self._r = result diff --git a/forks/hermes-agent/tests/gateway/test_discord_allowed_mentions.py b/forks/hermes-agent/tests/gateway/test_discord_allowed_mentions.py index 50632475e..963ee4937 100644 --- a/forks/hermes-agent/tests/gateway/test_discord_allowed_mentions.py +++ b/forks/hermes-agent/tests/gateway/test_discord_allowed_mentions.py @@ -24,6 +24,10 @@ def __init__(self, *, everyone=True, roles=True, users=True, replied_user=True): self.users = users self.replied_user = replied_user + @classmethod + def none(cls): + return cls(everyone=False, roles=False, users=False, replied_user=False) + def __repr__(self) -> str: # pragma: no cover - debug helper return ( f"AllowedMentions(everyone={self.everyone}, roles={self.roles}, " diff --git a/forks/hermes-agent/tests/gateway/test_discord_approval_index.py b/forks/hermes-agent/tests/gateway/test_discord_approval_index.py index 5645667b7..a38d5c9f2 100644 --- a/forks/hermes-agent/tests/gateway/test_discord_approval_index.py +++ b/forks/hermes-agent/tests/gateway/test_discord_approval_index.py @@ -877,7 +877,7 @@ async def test_runner_to_discord_redacts_credential_from_prompt_and_index(tmp_pa session_key="discord:555", source=SimpleNamespace(platform=SimpleNamespace(value="discord")), _loop_for_step=asyncio.get_running_loop(), stream_consumer_holder=[None], ) - runner = TurnRunner(SimpleNamespace(), ctx) + runner = TurnRunner(SimpleNamespace(_delivery_adapter_for=lambda _source: adapter), ctx) loop = asyncio.get_running_loop() runner._schedule = lambda coro, _label: _LoopFuture(asyncio.run_coroutine_threadsafe(coro, loop)) runner._close_native_stream_boundary = lambda _why: None diff --git a/forks/hermes-agent/tests/gateway/test_discord_approval_reconnect.py b/forks/hermes-agent/tests/gateway/test_discord_approval_reconnect.py index 6daf26bab..9c11dfce3 100644 --- a/forks/hermes-agent/tests/gateway/test_discord_approval_reconnect.py +++ b/forks/hermes-agent/tests/gateway/test_discord_approval_reconnect.py @@ -642,6 +642,98 @@ def register(rid): assert "n39" in adapter._exec_approval_views +@pytest.mark.asyncio +async def test_approval_uses_same_replacement_adapter_as_reply(monkeypatch): + from gateway.turn_context import TurnContext + from gateway.run_turn_runner import TurnRunner + + old = DiscordAdapter(PlatformConfig(enabled=True, token="test-token")) + live = DiscordAdapter(PlatformConfig(enabled=True, token="test-token")) + created = [] + thread = _channel_for(777, 1234) + monkeypatch.setattr(_FakeBot, "get_channel", lambda self, cid: thread) + await _connect(live, monkeypatch, created) + session = "agent:other:discord:555" + request_id = uuid.uuid4().hex + _queue_entry(monkeypatch, session, request_id) + source = SimpleNamespace(chat_id="555") + runner = SimpleNamespace(_delivery_adapter_for=lambda actual: live if actual is source else None) + ctx = TurnContext(source=source, session_key=session, _status_adapter=old, + _status_chat_id="555", _status_thread_metadata={"thread_id": "777"}) + turn = TurnRunner(runner, ctx) + turn._close_native_stream_boundary = lambda *args: None + loop = asyncio.get_running_loop() + turn._schedule = lambda coro, message: asyncio.run_coroutine_threadsafe(coro, loop) + monkeypatch.setattr("gateway.run_turn_runner_approval_settle.register_approval_index_settle", lambda *args: None) + monkeypatch.setattr("gateway.run_turn_runner_approval_settle.register_timeout_notice", lambda *args, **kwargs: None) + assert (await live.send("555", "reply", metadata={"thread_id": "777"})).success + await asyncio.to_thread(turn._render_approval_sync, {"command": "rm x", "request_id": request_id}) + assert thread.send.await_count == 2 + assert "view" in thread.send.await_args.kwargs + await live.disconnect() + + + +@pytest.mark.asyncio +async def test_failed_card_posts_mentioned_text_in_thread(monkeypatch): + monkeypatch.setenv("DISCORD_ALLOWED_USERS", "11111") + monkeypatch.setenv("DISCORD_APPROVAL_MENTIONS", "true") + monkeypatch.setattr(discord_platform.discord, "AllowedMentions", lambda **kwargs: SimpleNamespace(**kwargs)) + monkeypatch.setattr(discord_platform.discord, "Object", lambda **kwargs: SimpleNamespace(**kwargs)) + adapter = DiscordAdapter(PlatformConfig(enabled=True, token="test-token", + extra={"approval_mentions": True, "approval_card_confirm_timeout": 0.05})) + created = [] + thread = _channel_for(777, 1234) + monkeypatch.setattr(_FakeBot, "get_channel", lambda self, cid: thread) + await _connect(adapter, monkeypatch, created) + session = "agent:other:discord:555" + request_id = uuid.uuid4().hex + _queue_entry(monkeypatch, session, request_id) + client = adapter._client + adapter._client = None + adapter._ready_event.clear() + original_fallback = adapter._send_exec_approval_text_fallback + async def fallback(prompt): + adapter._client = client + return await original_fallback(prompt) + monkeypatch.setattr(adapter, "_send_exec_approval_text_fallback", fallback) + result = await adapter.send_exec_approval( + chat_id="555", command="rm x", session_key=session, request_id=request_id, metadata={"thread_id": "777"}) + assert result.raw_response == {"approval_text_fallback_posted": True} + assert thread.send.await_count == 1 + sent = thread.send.await_args.kwargs + assert sent["content"].startswith("<@11111>\n") + assert [user.id for user in sent["allowed_mentions"].users] == [11111] + assert sent["allowed_mentions"].roles is False + assert sent["allowed_mentions"].everyone is False + await adapter.disconnect() + + +@pytest.mark.asyncio +async def test_approval_stays_down_fails_loudly_instead_of_silent_withdraw(monkeypatch, caplog): + from gateway.platforms.base import ExecApprovalPrompt, SendResult + + adapter = DiscordAdapter(PlatformConfig(enabled=True, token="test-token", + extra={"approval_card_confirm_timeout": 0.01})) + session = "agent:other:discord:555" + request_id = uuid.uuid4().hex + entry = _queue_entry(monkeypatch, session, request_id) + monkeypatch.setattr(adapter, "_send_exec_approval_card", + AsyncMock(return_value=SendResult(success=False, error="Not connected", retryable=True))) + monkeypatch.setattr(adapter, "_send_exec_approval_text_fallback", AsyncMock(return_value="send_path_degraded")) + prompt = ExecApprovalPrompt( + chat_id="555", session_key=session, text="rm x", command="rm x", smart_denied=False, + actions=[("Allow once", "once", "primary"), ("Deny", "deny", "danger")], + request_id=request_id, metadata={"thread_id": "777"}) + + result = await adapter._send_exec_approval_prompt(prompt) + + assert result.success is False + assert result.raw_response == {"approval_text_fallback_posted": True} + assert entry.undelivered == "Not connected, then send_path_degraded" + assert "approval prompt was never delivered" in caplog.text + + @pytest.mark.asyncio async def test_failed_card_send_is_kept_as_undelivered(monkeypatch): adapter = DiscordAdapter(PlatformConfig(enabled=True, token="test-token")) @@ -666,9 +758,8 @@ async def test_failed_card_send_is_kept_as_undelivered(monkeypatch): @pytest.mark.asyncio -async def test_unconfirmed_card_is_not_marked_never_shown_when_the_text_fallback_also_fails(monkeypatch): - """A card that is not confirmed in time may already be on screen, so the prompt is not 'never shown': - a failed text fallback must not mark the request undelivered. The timed-out request is still withdrawn.""" +async def test_unconfirmed_card_does_not_claim_never_shown(monkeypatch): + """A timed-out send may have posted the card, so do not mark it never shown.""" from gateway.platforms.base import ExecApprovalPrompt adapter = DiscordAdapter(PlatformConfig(enabled=True, token="test-token", @@ -688,16 +779,15 @@ async def card_never_confirmed(_prompt, _view): result = await adapter._send_exec_approval_prompt(prompt) - assert result.error == discord_platform._CARD_CONFIRM_TIMEOUT_ERROR + assert result.success is False + assert result.raw_response == {"approval_text_fallback_posted": True} assert entry.undelivered is None - assert await _until(lambda: entry not in approval._gateway_queues.get(session, []), timeout=3) - assert entry.cancelled == "the approval card was not delivered" + assert entry.cancelled is None @pytest.mark.asyncio async def test_failed_card_with_failed_text_fallback_is_marked_never_shown(monkeypatch): - """Counterpart: a card that failed outright (not a confirm timeout) and a failed text fallback leave no - surface showing the prompt, so the request is marked undelivered with both failure reasons.""" + """Counterpart: a card and text send failure cancel the approval as undelivered.""" from gateway.platforms.base import ExecApprovalPrompt, SendResult adapter = DiscordAdapter(PlatformConfig(enabled=True, token="test-token", @@ -706,19 +796,21 @@ async def test_failed_card_with_failed_text_fallback_is_marked_never_shown(monke request_id = uuid.uuid4().hex entry = _queue_entry(monkeypatch, session, request_id) monkeypatch.setattr(adapter, "_send_exec_approval_card", - AsyncMock(return_value=SendResult(success=False, error="Not connected"))) + AsyncMock(return_value=SendResult(success=False, error="Not connected", retryable=True))) monkeypatch.setattr(adapter, "_send_exec_approval_text_fallback", AsyncMock(return_value="send_path_degraded")) prompt = ExecApprovalPrompt( chat_id="555", session_key=session, text="rm x", command="rm x", smart_denied=False, actions=[("Allow once", "once", "primary"), ("Deny", "deny", "danger")], request_id=request_id, metadata={"thread_id": "777"}) - await adapter._send_exec_approval_prompt(prompt) + result = await adapter._send_exec_approval_prompt(prompt) + assert result.raw_response == {"approval_text_fallback_posted": True} assert entry.undelivered == "Not connected, then send_path_degraded" - assert await _until(lambda: entry not in approval._gateway_queues.get(session, []), timeout=3) + assert entry.cancelled is None @pytest.mark.asyncio + async def test_ui_timeout_then_reconnect_press_ends_wait_as_cancelled(monkeypatch): # Live sequence: the card's UI timeout finishes the view; a reconnect swaps the client; an # Approve then arrives. The timeout withdraws the request at once, so the wait ends cancelled and the @@ -1714,6 +1806,31 @@ async def send(**kwargs): fallback = [call.kwargs for call in thread.send.await_args_list if "view" not in call.kwargs] assert len(fallback) == 1 assert "within 30 seconds it will NOT run" in fallback[0]["content"] + assert fallback[0].get("reference") is None + await adapter.disconnect() + +@pytest.mark.asyncio +async def test_text_fallback_is_posted_in_thread_and_mentions_allowed_users(monkeypatch): + monkeypatch.setenv("DISCORD_ALLOWED_USERS", "11111") + monkeypatch.setattr(discord_platform.discord, "AllowedMentions", lambda **kwargs: SimpleNamespace(**kwargs)) + monkeypatch.setattr(discord_platform.discord, "Object", lambda **kwargs: SimpleNamespace(**kwargs)) + monkeypatch.setenv("DISCORD_APPROVAL_MENTIONS", "true") + adapter = DiscordAdapter(PlatformConfig(enabled=True, token="test-token", + extra={"approval_mentions": True, "approval_card_confirm_timeout": 1})) + created: list[_FakeBot] = [] + thread = _channel_for(777, 1) + monkeypatch.setattr(_FakeBot, "get_channel", lambda self, _cid: thread) + await _connect(adapter, monkeypatch, created) + _queue_entry(monkeypatch, "session", "r1") + prompt = SimpleNamespace( + chat_id="555", session_key="session", request_id="r1", command="rm x", description="test", + choices=("once", "deny"), smart_denied=False, metadata={"thread_id": "777"}) + + assert await adapter._send_exec_approval_text_fallback(prompt) is None + assert thread.send.await_count == 1 + fallback = thread.send.await_args + assert fallback.kwargs["content"].startswith("<@11111>\n") + assert [user.id for user in fallback.kwargs["allowed_mentions"].users] == [11111] await adapter.disconnect() diff --git a/forks/hermes-agent/tests/gateway/test_discord_connect.py b/forks/hermes-agent/tests/gateway/test_discord_connect.py index d6cddb043..3520695e2 100644 --- a/forks/hermes-agent/tests/gateway/test_discord_connect.py +++ b/forks/hermes-agent/tests/gateway/test_discord_connect.py @@ -21,6 +21,10 @@ def __init__(self, *, everyone=True, roles=True, users=True, replied_user=True): self.users = users self.replied_user = replied_user + @classmethod + def none(cls): + return cls(everyone=False, roles=False, users=False, replied_user=False) + def _ensure_discord_mock(): """Install (or augment) a mock ``discord`` module. diff --git a/forks/hermes-agent/tests/gateway/test_exec_approval_timeout_notice.py b/forks/hermes-agent/tests/gateway/test_exec_approval_timeout_notice.py index 2c24c1915..0b9d02d81 100644 --- a/forks/hermes-agent/tests/gateway/test_exec_approval_timeout_notice.py +++ b/forks/hermes-agent/tests/gateway/test_exec_approval_timeout_notice.py @@ -73,6 +73,7 @@ def _runner(adapter): _status_adapter=adapter, _status_chat_id="C1", _status_thread_metadata={"thread_id": "t1"}, session_key=SESSION, source=SimpleNamespace(chat_id="C1", platform="telegram", session_key=SESSION), ) + runner._runner = SimpleNamespace(_delivery_adapter_for=lambda _source: adapter) class _Fut: def __init__(self, result): self._r = result @@ -95,6 +96,16 @@ def pending_entry(monkeypatch): _approval._gateway_queues.pop(SESSION, None) +def test_timeout_notice_uses_the_adapter_that_sent_the_card(pending_entry): + old, live = _ButtonAdapter(), _ButtonAdapter() + runner = _runner(old) + runner._runner._delivery_adapter_for = lambda _source: live + runner._approval_notify_sync(dict(pending_entry.data)) + pending_entry.settle("timeout") + assert live.card_request_ids and live.edits + assert old.card_request_ids == [] and old.edits == [] + + @pytest.mark.parametrize("warning_notifications", [True, False]) def test_timeout_edits_the_card_to_say_the_command_did_not_run(pending_entry, tmp_path, monkeypatch, warning_notifications): import gateway.run as gateway_run