Skip to content

The agent that grows with you

5.3 KB
Raw Blame
"""Tests for the configurable Discord interactive-view timeout.

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 or exceed the shared platform-safe timeout cap.
"""

import sys
from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest

def _ensure_discord_mock():
    if "discord" in sys.modules and hasattr(sys.modules["discord"], "__file__"):
        return

    discord_mod = MagicMock()
    discord_mod.Intents.default.return_value = MagicMock()
    discord_mod.Client = MagicMock
    discord_mod.File = MagicMock
    discord_mod.DMChannel = type("DMChannel", (), {})
    discord_mod.Thread = type("Thread", (), {})
    discord_mod.ForumChannel = type("ForumChannel", (), {})
    discord_mod.ui = SimpleNamespace(View=object, button=lambda *a, **k: (lambda fn: fn), Button=object)
    discord_mod.ButtonStyle = SimpleNamespace(success=1, primary=2, secondary=2, danger=3, green=1, grey=2, blurple=2, red=3)
    discord_mod.Color = SimpleNamespace(orange=lambda: 1, green=lambda: 2, blue=lambda: 3, red=lambda: 4, purple=lambda: 5)
    discord_mod.Interaction = object
    discord_mod.Embed = MagicMock
    discord_mod.app_commands = SimpleNamespace(
        describe=lambda **kwargs: (lambda fn: fn),
        choices=lambda **kwargs: (lambda fn: fn),
        Choice=lambda **kwargs: SimpleNamespace(**kwargs),
    )

    ext_mod = MagicMock()
    commands_mod = MagicMock()
    commands_mod.Bot = MagicMock
    ext_mod.commands = commands_mod

    sys.modules.setdefault("discord", discord_mod)
    sys.modules.setdefault("discord.ext", ext_mod)
    sys.modules.setdefault("discord.ext.commands", commands_mod)

_ensure_discord_mock()

from plugins.platforms.discord.adapter import (
    _DISCORD_PROMPT_TIMEOUT_DEFAULT,
    _DISCORD_PROMPT_TIMEOUT_MIN,
    _read_discord_prompt_timeout,
)

def _patch_config(monkeypatch, cfg):
    """Stub ``hermes_cli.config.read_raw_config`` to return ``cfg``."""
    import hermes_cli.config
    monkeypatch.setattr(hermes_cli.config, "read_raw_config", lambda: cfg)

def test_explicit_int_value(monkeypatch):
    _patch_config(monkeypatch, {"approvals": {"discord_prompt_timeout": 600}})
    assert _read_discord_prompt_timeout() == 600

def test_numeric_string_accepted(monkeypatch):
    """YAML parsers occasionally return numbers as strings; tolerate it."""
    _patch_config(monkeypatch, {"approvals": {"discord_prompt_timeout": "450"}})
    assert _read_discord_prompt_timeout() == 450

def test_malformed_value_falls_back_to_default(monkeypatch):
    _patch_config(
        monkeypatch,
        {"approvals": {"discord_prompt_timeout": "five minutes"}},
    )
    assert _read_discord_prompt_timeout() == _DISCORD_PROMPT_TIMEOUT_DEFAULT

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)


@pytest.mark.asyncio
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)


def test_configured_through_the_profiles_config_yaml(monkeypatch, tmp_path):
    """The key is registered with its default and reaches the views from a real config.yaml."""
    from hermes_cli.config import load_config

    monkeypatch.setenv("HERMES_HOME", str(tmp_path))
    assert load_config()["approvals"]["discord_prompt_timeout"] == _DISCORD_PROMPT_TIMEOUT_DEFAULT
    (tmp_path / "config.yaml").write_text("approvals:\n  discord_prompt_timeout: 1800\n")
    assert _read_discord_prompt_timeout() == 1800
    assert load_config()["approvals"]["discord_prompt_timeout"] == 1800