# Conflicts: # apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts # apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts # apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts # apps/desktop/e2e/bot-mode-roster-localized.spec.ts # apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts # apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts # apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts # apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts # apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts # apps/desktop/e2e/bot-roster-user-sections.spec.ts # apps/desktop/e2e/bot-routines-pane-narrow.spec.ts # apps/desktop/e2e/bot-row-open-recent-session.spec.ts # apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts # apps/desktop/e2e/group-composer-auto-grow.spec.ts # apps/desktop/e2e/group-create-gate-remote-roster.spec.ts # apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts # apps/desktop/e2e/hosted-room-backend-continuity.spec.ts # apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts # apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts # apps/desktop/e2e/worktree-branch-status.spec.ts # apps/desktop/electron/backend-probes.test.ts # apps/desktop/electron/connection-apply.test.ts # apps/desktop/electron/desktop-electron-pin.test.ts # apps/desktop/electron/desktop-uninstall.test.ts # apps/desktop/electron/gateway-file-download-transport.test.ts # apps/desktop/electron/gateway-stop-before-update.test.ts # apps/desktop/electron/github-api-auth.test.ts # apps/desktop/electron/registry-primary-profile-scope.test.ts # apps/desktop/electron/update-api-check.test.ts # apps/desktop/electron/update-handoff-marker.test.ts # apps/desktop/electron/venv-blocker-scan.test.ts # apps/desktop/scripts/after-extract.test.mjs # apps/desktop/scripts/local-pack-publish.test.mjs # apps/desktop/scripts/tasks-scroll.test.mjs # apps/desktop/src/app/settings/model-settings.test.tsx # apps/desktop/src/app/updates-overlay.blockers.test.tsx # apps/desktop/src/components/desktop-install-overlay.test.tsx # apps/desktop/src/lib/update-copy.test.ts # scripts/ci/check_os_marker_fakes.py # tests-js/desktop-mac-usage-descriptions.test.ts # tests-js/node-engine-alignment.test.ts # tests/agent/lsp/test_install_and_lint_fixes.py # tests/agent/test_command_token_source.py # tests/agent/test_compression_boundary_hook.py # tests/agent/test_create_openai_client_ssl_verify.py # tests/agent/test_custom_provider_ca_probes.py # tests/agent/test_endpoint_blackhole.py # tests/agent/test_estimator_parity.py # tests/agent/test_in_place_compaction.py # tests/agent/test_moa_loop_mode.py # tests/agent/test_model_metadata.py # tests/agent/test_skill_session_platform_gate.py # tests/agent/test_skill_utils.py # tests/agent/test_ssl_ca_guard.py # tests/computer_use/test_doctor.py # tests/cron/test_codex_execution_paths.py # tests/cron/test_cron_bot_chat_delivery.py # tests/cron/test_cron_script.py # tests/cron/test_media_delivery_parity.py # tests/cron/test_misfire_catchup.py # tests/cron/test_parallel_pool.py # tests/cron/test_recurring_eagain_redispatch.py # tests/gateway/test_choice_picker.py # tests/gateway/test_control_socket_windows_live.py # tests/gateway/test_dingtalk.py # tests/gateway/test_feishu.py # tests/gateway/test_feishu_onboard.py # tests/gateway/test_gateway_shutdown.py # tests/gateway/test_matrix.py # tests/gateway/test_model_command_custom_providers.py # tests/gateway/test_reasoning_command.py # tests/gateway/test_runtime_footer.py # tests/gateway/test_session.py # tests/gateway/test_session_hygiene.py # tests/gateway/test_status.py # tests/gateway/test_teams.py # tests/gateway/test_turn_lease.py # tests/gateway/test_whatsapp_connect.py # tests/hermes_cli/test_approvals_command.py # tests/hermes_cli/test_auth_store_lock_concurrent.py # tests/hermes_cli/test_backup.py # tests/hermes_cli/test_banner_git_state.py # tests/hermes_cli/test_certifi_repair.py # tests/hermes_cli/test_cmd_update.py # tests/hermes_cli/test_compat_manifest_targets.py # tests/hermes_cli/test_computer_use_cli.py # tests/hermes_cli/test_cpr_local_leak.py # tests/hermes_cli/test_dashboard_auth_gate.py # tests/hermes_cli/test_dashboard_procs_kill_grace.py # tests/hermes_cli/test_desktop_lifecycle_windows_live.py # tests/hermes_cli/test_doctor.py # tests/hermes_cli/test_doctor_command_install.py # tests/hermes_cli/test_fleet_config_migration_windows_live.py # tests/hermes_cli/test_gateway.py # tests/hermes_cli/test_gateway_platform_gating.py # tests/hermes_cli/test_gateway_restart_loop.py # tests/hermes_cli/test_gateway_task_probe.py # tests/hermes_cli/test_gateway_wsl.py # tests/hermes_cli/test_gui_command.py # tests/hermes_cli/test_install_cua_driver.py # tests/hermes_cli/test_kanban_db.py # tests/hermes_cli/test_lazy_command_exports.py # tests/hermes_cli/test_lazy_refresh_venv_repair.py # tests/hermes_cli/test_linux_desktop_entry.py # tests/hermes_cli/test_local_runtime.py # tests/hermes_cli/test_local_runtime_updates.py # tests/hermes_cli/test_managed_uv.py # tests/hermes_cli/test_mcp_reload_confirm_gate.py # tests/hermes_cli/test_nous_subscription.py # tests/hermes_cli/test_npm_engine.py # tests/hermes_cli/test_personality_none.py # tests/hermes_cli/test_pet_toggle.py # tests/hermes_cli/test_plan_reconciliation_windows_live.py # tests/hermes_cli/test_plugin_event_bus.py # tests/hermes_cli/test_plugin_manifest_v2.py # tests/hermes_cli/test_plugin_packs.py # tests/hermes_cli/test_plugins_cmd.py # tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py # tests/hermes_cli/test_process_identity.py # tests/hermes_cli/test_profiles.py # tests/hermes_cli/test_profiles_sidebar_cache.py # tests/hermes_cli/test_pty_bridge.py # tests/hermes_cli/test_resolve_turn_limit.py # tests/hermes_cli/test_serve_runtime_inventory.py # tests/hermes_cli/test_session_vacuum_config.py # tests/hermes_cli/test_set_config_value.py # tests/hermes_cli/test_signal_handler_kanban_worker.py # tests/hermes_cli/test_slash_confirm_windows.py # tests/hermes_cli/test_stale_pid_guard.py # tests/hermes_cli/test_startup_fast_guards.py # tests/hermes_cli/test_status.py # tests/hermes_cli/test_telegram_managed_bot.py # tests/hermes_cli/test_tools_config.py # tests/hermes_cli/test_update_apply_shallow_count.py # tests/hermes_cli/test_update_autostash.py # tests/hermes_cli/test_update_concurrent_quarantine.py # tests/hermes_cli/test_update_fetch_failure_classifier.py # tests/hermes_cli/test_update_fleet_probe_resume_token.py # tests/hermes_cli/test_update_handoff_backend_reap.py # tests/hermes_cli/test_update_handoff_desktop_rebuild.py # tests/hermes_cli/test_update_head_moved_gate.py # tests/hermes_cli/test_update_host_obligation.py # tests/hermes_cli/test_update_import_guard.py # tests/hermes_cli/test_update_interrupted_recovery.py # tests/hermes_cli/test_update_inventory.py # tests/hermes_cli/test_update_launchd_unloaded_gateway.py # tests/hermes_cli/test_update_missing_configured_deps.py # tests/hermes_cli/test_update_modified_notice.py # tests/hermes_cli/test_update_multiplex_migration_hook.py # tests/hermes_cli/test_update_no_gateway_restart.py # tests/hermes_cli/test_update_orphan_backend_reap.py # tests/hermes_cli/test_update_parked_branch_guard.py # tests/hermes_cli/test_update_post_pull_syntax_guard.py # tests/hermes_cli/test_update_receipt.py # tests/hermes_cli/test_update_self_lock.py # tests/hermes_cli/test_update_shim_fail_closed.py # tests/hermes_cli/test_update_shim_self_lock.py # tests/hermes_cli/test_update_sqlite_remediation.py # tests/hermes_cli/test_update_stale_dashboard.py # tests/hermes_cli/test_update_stale_virtualenv.py # tests/hermes_cli/test_update_venv_health.py # tests/hermes_cli/test_update_venv_ownership_preflight.py # tests/hermes_cli/test_update_wedged_gateway.py # tests/hermes_cli/test_update_yes_flag.py # tests/hermes_cli/test_update_zip_two_phase.py # tests/hermes_cli/test_urllib_security.py # tests/hermes_cli/test_ux_messages_auth_config.py # tests/hermes_cli/test_ux_messages_startup.py # tests/hermes_cli/test_venv_holder_classifier.py # tests/hermes_cli/test_verify_console_scripts.py # tests/hermes_cli/test_verify_core_dependencies.py # tests/hermes_cli/test_web_server.py # tests/hermes_cli/test_web_server_console_ws.py # tests/hermes_cli/test_web_server_ws_ping.py # tests/hermes_cli/test_web_ui_build.py # tests/hermes_state/test_fts_rebuild_admission.py # tests/hermes_state/test_hermes_state.py # tests/plugins/memory/test_memory_lazy_install.py # tests/plugins/test_google_meet_plugin.py # tests/plugins/test_langfuse_plugin.py # tests/plugins/test_security_guidance_plugin.py # tests/plugins/test_transform_llm_output_hook.py # tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py # tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py # tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py # tests/scripts/install/test_install_clone_throttle_fallback.py # tests/scripts/install/test_install_lockfile_churn.py # tests/scripts/install/test_install_no_initial_commit.py # tests/scripts/install/test_install_sh_browser_install.py # tests/scripts/install/test_install_sh_node_prerelease.py # tests/scripts/install/test_install_sh_symlink_stomp.py # tests/scripts/install/test_install_sh_uv_lock_config.py # tests/scripts/install/test_install_unmerged_index.py # tests/scripts/test_contributor_map.py # tests/scripts/test_run_tests_parallel.py # tests/skills/test_competitor_news_monitor_skill.py # tests/skills/test_document_to_action_items_skill.py # tests/skills/test_google_workspace_setup.py # tests/skills/test_google_workspace_setup_deps.py # tests/skills/test_grounded_citations_skill.py # tests/skills/test_ip_as_logo_skill.py # tests/skills/test_live_dashboard_skill.py # tests/skills/test_mcp_oauth_remote_gateway_skill.py # tests/skills/test_office_document_skills.py # tests/skills/test_openclaw_migration.py # tests/skills/test_product_price_monitor_skill.py # tests/skills/test_scrollcraft_skill.py # tests/skills/test_setup_wizard_generator_skill.py # tests/skills/test_weekly_review_planning_skill.py # tests/test_engines_satisfiable.py # tests/test_fast_safe_load.py # tests/test_hermes_bootstrap.py # tests/test_hermes_constants.py # tests/test_hermes_logging.py # tests/test_managed_runtime_resolution.py # tests/test_model_tools_async_bridge.py # tests/test_packaging_build_guard.py # tests/test_packaging_metadata.py # tests/test_yaml_indent_consistency.py # tests/tools/test_approval_timeout_overflow.py # tests/tools/test_base_environment.py # tests/tools/test_bot_mode_dm.py # tests/tools/test_browser_chromium_check.py # tests/tools/test_browser_hardening.py # tests/tools/test_browser_homebrew_paths.py # tests/tools/test_browser_npx_warmup.py # tests/tools/test_browser_orphan_reaper.py # tests/tools/test_browser_real_profile.py # tests/tools/test_browser_use_cli.py # tests/tools/test_clipboard.py # tests/tools/test_code_execution.py # tests/tools/test_code_execution_modes.py # tests/tools/test_code_execution_windows_env.py # tests/tools/test_computer_use.py # tests/tools/test_delegate_liveness_timeout.py # tests/tools/test_execute_code_approval_cluster.py # tests/tools/test_execution_flag_detection.py # tests/tools/test_fal_common.py # tests/tools/test_file_operations.py # tests/tools/test_file_tools.py # tests/tools/test_file_tools_cwd_resolution.py # tests/tools/test_file_tools_live.py # tests/tools/test_lazy_deps.py # tests/tools/test_lazy_deps_durable_target.py # tests/tools/test_lazy_deps_managed.py # tests/tools/test_local_env_blocklist.py # tests/tools/test_local_tempdir.py # tests/tools/test_macos_protected_search.py # tests/tools/test_mcp_npx_cached_bin.py # tests/tools/test_oneshot_completion_linger.py # tests/tools/test_process_registry.py # tests/tools/test_read_file_schema_gating.py # tests/tools/test_skill_improvements.py # tests/tools/test_skills_sync.py # tests/tools/test_termux_api_detection.py # tests/tools/test_tirith_security.py # tests/tools/test_transcription_tools.py # tests/tools/test_tts_streaming.py # tests/tools/test_wake_word.py # tests/tui_gateway/test_compute_host_borrowed_lease.py # tests/tui_gateway/test_compute_host_turn_protocol.py # tests/tui_gateway/test_isolated_orphan_activity.py # tests/tui_gateway/test_protocol.py # tests/tui_gateway/test_slash_worker_profile_home.py # tests/tui_gateway/test_subprocess_encoding.py # tests/tui_gateway/test_tui_gateway_server.py # ui-tui/src/__tests__/terminalParity.test.ts # ui-tui/src/__tests__/termuxComposerLayout.test.ts # ui-tui/src/__tests__/textInputFastEcho.test.ts
719 lines
31 KiB
Python
719 lines
31 KiB
Python
"""Tests for the Discord server introspection and management tool."""
|
|
|
|
import json
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
from tools.discord_tool import (
|
|
DiscordAPIError,
|
|
_ACTIONS,
|
|
_ADMIN_ACTIONS,
|
|
_CORE_ACTIONS,
|
|
_available_actions,
|
|
_detect_capabilities,
|
|
_discord_request,
|
|
_get_bot_token,
|
|
_load_allowed_actions_config,
|
|
_reset_capability_cache,
|
|
check_discord_tool_requirements,
|
|
discord_admin_handler,
|
|
discord_core,
|
|
get_dynamic_schema_admin,
|
|
get_dynamic_schema_core,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _mock_urlopen(response_data, status=200):
|
|
"""Create a mock for urllib.request.urlopen."""
|
|
mock_resp = MagicMock()
|
|
mock_resp.status = status
|
|
mock_resp.read.return_value = json.dumps(response_data).encode("utf-8")
|
|
mock_resp.__enter__ = MagicMock(return_value=mock_resp)
|
|
mock_resp.__exit__ = MagicMock(return_value=False)
|
|
return mock_resp
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Token / check_fn
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestCheckRequirements:
|
|
@pytest.mark.parametrize("token, expected", [(None, False), ("test-token-123", True)])
|
|
def test_requirements_follow_token(self, monkeypatch, token, expected):
|
|
if token is None:
|
|
monkeypatch.delenv("DISCORD_BOT_TOKEN", raising=False)
|
|
else:
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", token)
|
|
assert check_discord_tool_requirements() is expected
|
|
|
|
def test_get_bot_token(self, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", " my-token ")
|
|
assert _get_bot_token() == "my-token"
|
|
|
|
def test_multiplex_scope_token_wins_over_process_environment(self, monkeypatch):
|
|
from agent import secret_scope
|
|
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "another-profile-token")
|
|
secret_scope.set_multiplex_active(True)
|
|
scope_token = secret_scope.set_secret_scope(
|
|
{"DISCORD_BOT_TOKEN": " active-profile-token "}
|
|
)
|
|
try:
|
|
assert _get_bot_token() == "active-profile-token"
|
|
assert check_discord_tool_requirements() is True
|
|
finally:
|
|
secret_scope.reset_secret_scope(scope_token)
|
|
secret_scope.set_multiplex_active(False)
|
|
|
|
def test_multiplex_scope_missing_token_fails_closed(self, monkeypatch):
|
|
from agent import secret_scope
|
|
from tools.registry import invalidate_check_fn_cache, registry
|
|
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "another-profile-token")
|
|
secret_scope.set_multiplex_active(True)
|
|
scope_token = secret_scope.set_secret_scope({"UNRELATED_SECRET": "value"})
|
|
invalidate_check_fn_cache()
|
|
try:
|
|
assert _get_bot_token() is None
|
|
assert check_discord_tool_requirements() is False
|
|
assert registry.get_definitions({"discord", "discord_admin"}) == []
|
|
finally:
|
|
invalidate_check_fn_cache()
|
|
secret_scope.reset_secret_scope(scope_token)
|
|
secret_scope.set_multiplex_active(False)
|
|
|
|
def test_non_multiplex_scope_miss_keeps_environment_compatibility(self, monkeypatch):
|
|
from agent import secret_scope
|
|
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "process-token")
|
|
secret_scope.set_multiplex_active(False)
|
|
scope_token = secret_scope.set_secret_scope({"UNRELATED_SECRET": "value"})
|
|
try:
|
|
assert _get_bot_token() == "process-token"
|
|
assert check_discord_tool_requirements() is True
|
|
finally:
|
|
secret_scope.reset_secret_scope(scope_token)
|
|
|
|
def test_gateway_tool_prompt_gate_uses_active_profile_token(self, monkeypatch):
|
|
from agent import secret_scope
|
|
from gateway.session import _discord_tools_loaded
|
|
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "another-profile-token")
|
|
secret_scope.set_multiplex_active(True)
|
|
scope_token = secret_scope.set_secret_scope({"UNRELATED_SECRET": "value"})
|
|
try:
|
|
with patch("hermes_cli.config.load_config") as load_config:
|
|
assert _discord_tools_loaded() is False
|
|
load_config.assert_not_called()
|
|
finally:
|
|
secret_scope.reset_secret_scope(scope_token)
|
|
secret_scope.set_multiplex_active(False)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Channel type names
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Discord API request helper
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestDiscordRequest:
|
|
@patch("tools.discord_tool.urllib.request.urlopen")
|
|
def test_get_request(self, mock_urlopen_fn):
|
|
mock_urlopen_fn.return_value = _mock_urlopen({"ok": True})
|
|
result = _discord_request("GET", "/test", "token123")
|
|
assert result == {"ok": True}
|
|
|
|
# Verify the request was constructed correctly
|
|
call_args = mock_urlopen_fn.call_args
|
|
req = call_args[0][0]
|
|
assert "https://discord.com/api/v10/test" in req.full_url
|
|
assert req.get_header("Authorization") == "Bot token123"
|
|
assert req.get_method() == "GET"
|
|
|
|
|
|
@patch("tools.discord_tool.urllib.request.urlopen")
|
|
def test_response_body_size_limit(self, mock_urlopen_fn, monkeypatch):
|
|
monkeypatch.setattr("tools.discord_tool._DISCORD_RESPONSE_BODY_MAX_BYTES", 8)
|
|
mock_resp = MagicMock()
|
|
mock_resp.status = 200
|
|
mock_resp.read.return_value = b"x" * 9
|
|
mock_resp.__enter__ = MagicMock(return_value=mock_resp)
|
|
mock_resp.__exit__ = MagicMock(return_value=False)
|
|
mock_urlopen_fn.return_value = mock_resp
|
|
|
|
with pytest.raises(DiscordAPIError) as exc_info:
|
|
_discord_request("GET", "/test", "tok")
|
|
|
|
assert exc_info.value.status == 502
|
|
assert "response body exceeded 8 bytes" in exc_info.value.body
|
|
mock_resp.read.assert_called_once_with(9)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Main handler: validation
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestDiscordServerValidation:
|
|
def test_no_token(self, monkeypatch):
|
|
monkeypatch.delenv("DISCORD_BOT_TOKEN", raising=False)
|
|
result = json.loads(discord_admin_handler(action="list_guilds"))
|
|
assert "error" in result
|
|
assert "DISCORD_BOT_TOKEN" in result["error"]
|
|
|
|
|
|
def test_missing_multiple_params(self, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
result = json.loads(discord_admin_handler(action="add_role"))
|
|
assert "error" in result
|
|
assert "guild_id" in result["error"]
|
|
assert "user_id" in result["error"]
|
|
assert "role_id" in result["error"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Action: list_channels
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestListChannels:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_list_channels_organized(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.return_value = [
|
|
{"id": "10", "name": "General", "type": 4, "position": 0, "parent_id": None},
|
|
{"id": "11", "name": "chat", "type": 0, "position": 0, "parent_id": "10", "topic": "Main chat", "nsfw": False},
|
|
{"id": "12", "name": "voice", "type": 2, "position": 1, "parent_id": "10", "topic": None, "nsfw": False},
|
|
{"id": "13", "name": "no-category", "type": 0, "position": 0, "parent_id": None, "topic": None, "nsfw": False},
|
|
]
|
|
result = json.loads(discord_admin_handler(action="list_channels", guild_id="111"))
|
|
assert result["total_channels"] == 3 # excludes the category itself
|
|
groups = result["channel_groups"]
|
|
# Uncategorized first
|
|
assert groups[0]["category"] is None
|
|
assert len(groups[0]["channels"]) == 1
|
|
assert groups[0]["channels"][0]["name"] == "no-category"
|
|
# Then the category
|
|
assert groups[1]["category"]["name"] == "General"
|
|
assert len(groups[1]["channels"]) == 2
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Action: list_roles
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestListRoles:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_list_roles_sorted(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.return_value = [
|
|
{"id": "1", "name": "@everyone", "position": 0, "color": 0, "mentionable": False, "managed": False, "hoist": False},
|
|
{"id": "2", "name": "Admin", "position": 2, "color": 16711680, "mentionable": True, "managed": False, "hoist": True},
|
|
{"id": "3", "name": "Mod", "position": 1, "color": 255, "mentionable": True, "managed": False, "hoist": True},
|
|
]
|
|
result = json.loads(discord_admin_handler(action="list_roles", guild_id="111"))
|
|
assert result["count"] == 3
|
|
# Should be sorted by position descending
|
|
assert result["roles"][0]["name"] == "Admin"
|
|
assert result["roles"][0]["color"] == "#ff0000"
|
|
assert result["roles"][1]["name"] == "Mod"
|
|
assert result["roles"][2]["name"] == "@everyone"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Action: search_members
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestSearchMembers:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_search_members_limit_capped(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.return_value = []
|
|
discord_core(action="search_members", guild_id="111", query="x", limit=200)
|
|
call_params = mock_req.call_args[1]["params"]
|
|
assert call_params["limit"] == "100" # Capped at 100
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Action: fetch_messages
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestFetchMessages:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_fetch_messages(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.return_value = [
|
|
{
|
|
"id": "1001",
|
|
"content": "Hello world",
|
|
"author": {"id": "42", "username": "user1", "global_name": "User One", "bot": False},
|
|
"timestamp": "2024-01-01T12:00:00Z",
|
|
"edited_timestamp": None,
|
|
"attachments": [],
|
|
"pinned": False,
|
|
},
|
|
]
|
|
result = json.loads(discord_core(action="fetch_messages", channel_id="11"))
|
|
assert result["count"] == 1
|
|
assert result["messages"][0]["content"] == "Hello world"
|
|
assert result["messages"][0]["author"]["username"] == "user1"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Action: create_thread
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestCreateThread:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_create_standalone_thread(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.return_value = {"id": "800", "name": "New Thread"}
|
|
result = json.loads(discord_core(action="create_thread", channel_id="11", name="New Thread"))
|
|
assert result["success"] is True
|
|
assert result["thread_id"] == "800"
|
|
# Verify the API call
|
|
mock_req.assert_called_once_with(
|
|
"POST", "/channels/11/threads", "test-token",
|
|
body={"name": "New Thread", "auto_archive_duration": 1440, "type": 11},
|
|
)
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_create_thread_from_message(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.return_value = {"id": "801", "name": "Discussion"}
|
|
result = json.loads(discord_core(
|
|
action="create_thread", channel_id="11", name="Discussion", message_id="1001",
|
|
))
|
|
assert result["success"] is True
|
|
mock_req.assert_called_once_with(
|
|
"POST", "/channels/11/messages/1001/threads", "test-token",
|
|
body={"name": "Discussion", "auto_archive_duration": 1440},
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Error handling
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestErrorHandling:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_api_error_handled(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.side_effect = DiscordAPIError(403, '{"message": "Missing Access"}')
|
|
result = json.loads(discord_admin_handler(action="list_guilds"))
|
|
assert "error" in result
|
|
assert "403" in result["error"]
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_unexpected_error_handled_core(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "test-token")
|
|
mock_req.side_effect = RuntimeError("something broke")
|
|
result = json.loads(discord_core(action="fetch_messages", channel_id="11"))
|
|
assert "error" in result
|
|
assert "something broke" in result["error"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Registration
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestRegistration:
|
|
|
|
def test_all_actions_covered(self):
|
|
"""Core + admin actions should cover all known actions."""
|
|
assert set(_CORE_ACTIONS.keys()) | set(_ADMIN_ACTIONS.keys()) == set(_ACTIONS.keys())
|
|
assert set(_CORE_ACTIONS.keys()) & set(_ADMIN_ACTIONS.keys()) == set()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Toolset: discord / discord_admin only in hermes-discord
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Capability detection (privileged intents)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestCapabilityDetection:
|
|
def setup_method(self):
|
|
_reset_capability_cache()
|
|
|
|
def teardown_method(self):
|
|
_reset_capability_cache()
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_both_intents_enabled(self, mock_req):
|
|
# flags: GUILD_MEMBERS (1<<14) + MESSAGE_CONTENT (1<<18) = 278528
|
|
mock_req.return_value = {"flags": (1 << 14) | (1 << 18)}
|
|
caps = _detect_capabilities("tok")
|
|
assert caps["has_members_intent"] is True
|
|
assert caps["has_message_content"] is True
|
|
assert caps["detected"] is True
|
|
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_detection_failure_is_permissive(self, mock_req):
|
|
"""If detection fails (network/401/revoked token), expose everything
|
|
and let runtime errors surface. Silent failure should never hide
|
|
actions the bot actually has."""
|
|
mock_req.side_effect = DiscordAPIError(401, "unauthorized")
|
|
caps = _detect_capabilities("tok")
|
|
assert caps["detected"] is False
|
|
assert caps["has_members_intent"] is True
|
|
assert caps["has_message_content"] is True
|
|
|
|
|
|
class TestNonBlockingCapabilityDetection:
|
|
"""The schema-build path must never block on a discord.com HTTP call.
|
|
|
|
``_detect_capabilities_nonblocking`` resolves memory cache → disk cache →
|
|
permissive default (+ background detect), keeping the ~2s blocking
|
|
detection off the first-token critical path (TTFT fix, July 2026).
|
|
"""
|
|
|
|
def setup_method(self):
|
|
_reset_capability_cache()
|
|
|
|
def teardown_method(self):
|
|
_reset_capability_cache()
|
|
|
|
def test_memory_cache_hit_no_network(self):
|
|
from tools.discord_tool import _capability_cache, _detect_capabilities_nonblocking
|
|
caps_in = {"has_members_intent": False, "has_message_content": True, "detected": True}
|
|
_capability_cache["tok"] = caps_in
|
|
with patch("tools.discord_tool._discord_request") as mock_req:
|
|
caps = _detect_capabilities_nonblocking("tok")
|
|
assert caps == caps_in
|
|
mock_req.assert_not_called()
|
|
|
|
|
|
def test_disk_cache_expires(self, tmp_path, monkeypatch):
|
|
import time as _time
|
|
|
|
import tools.discord_tool as dt
|
|
monkeypatch.setattr(
|
|
dt, "_capability_disk_cache_path",
|
|
lambda: tmp_path / "discord_capabilities.json",
|
|
)
|
|
caps_in = {"has_members_intent": True, "has_message_content": True, "detected": True}
|
|
dt._save_caps_to_disk("tok", caps_in)
|
|
# Rewrite timestamp to be stale
|
|
import json as _json
|
|
p = tmp_path / "discord_capabilities.json"
|
|
data = _json.loads(p.read_text())
|
|
for entry in data.values():
|
|
entry["ts"] = _time.time() - dt._CAPABILITY_DISK_TTL_SECONDS - 10
|
|
p.write_text(_json.dumps(data))
|
|
assert dt._load_caps_from_disk("tok") is None
|
|
|
|
def test_schema_build_uses_nonblocking_path(self, monkeypatch):
|
|
"""get_dynamic_schema_core must not call the blocking detection."""
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": ""}},
|
|
)
|
|
with patch("tools.discord_tool._load_caps_from_disk", return_value=None), \
|
|
patch("tools.discord_tool.threading.Thread") as mock_thread, \
|
|
patch("tools.discord_tool._discord_request") as mock_req:
|
|
schema = get_dynamic_schema_core()
|
|
# No blocking HTTP call happened on the schema-build path
|
|
mock_req.assert_not_called()
|
|
# Background detection was scheduled exactly once
|
|
assert mock_thread.call_count == 1
|
|
assert schema is not None
|
|
actions = set(schema["parameters"]["properties"]["action"]["enum"])
|
|
assert actions == set(_CORE_ACTIONS.keys()) # permissive default
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_cache_is_keyed_by_token(self, mock_req):
|
|
"""Regression: token A's capabilities must not leak to token B.
|
|
|
|
Before the fix, the cache was a single module-global dict. The first
|
|
call populated it and every subsequent call — regardless of token —
|
|
returned the same cached value, producing wrong schema gating for
|
|
rotated or multi-token deployments.
|
|
"""
|
|
def _per_token_flags(method, path, token, **_kwargs):
|
|
# token A: both intents; token B: neither.
|
|
if token == "tok_a":
|
|
return {"flags": (1 << 14) | (1 << 18)}
|
|
return {"flags": 0}
|
|
|
|
mock_req.side_effect = _per_token_flags
|
|
|
|
caps_a = _detect_capabilities("tok_a")
|
|
caps_b = _detect_capabilities("tok_b")
|
|
|
|
assert caps_a["has_members_intent"] is True
|
|
assert caps_a["has_message_content"] is True
|
|
assert caps_b["has_members_intent"] is False
|
|
assert caps_b["has_message_content"] is False
|
|
# Each token should hit the endpoint exactly once.
|
|
assert mock_req.call_count == 2
|
|
|
|
# Re-requesting either token serves from its own cache entry.
|
|
_detect_capabilities("tok_a")
|
|
_detect_capabilities("tok_b")
|
|
assert mock_req.call_count == 2
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Config allowlist
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestConfigAllowlist:
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_tools_logger(self):
|
|
"""Restore the ``tools`` logger level after cross-test pollution.
|
|
|
|
``AIAgent(quiet_mode=True)`` globally sets ``tools`` and
|
|
``tools.*`` children to ``ERROR`` (see run_agent.py quiet_mode
|
|
block). A persistent test process keeps that setting, so a
|
|
streaming test will silence WARNING-level logs from
|
|
``tools.discord_tool`` for every test that follows. Reset here so
|
|
``caplog`` can capture warnings regardless of earlier tests.
|
|
"""
|
|
import logging as _logging
|
|
_prev_tools = _logging.getLogger("tools").level
|
|
_prev_dt = _logging.getLogger("tools.discord_tool").level
|
|
_logging.getLogger("tools").setLevel(_logging.NOTSET)
|
|
_logging.getLogger("tools.discord_tool").setLevel(_logging.NOTSET)
|
|
try:
|
|
yield
|
|
finally:
|
|
_logging.getLogger("tools").setLevel(_prev_tools)
|
|
_logging.getLogger("tools.discord_tool").setLevel(_prev_dt)
|
|
|
|
def test_empty_string_returns_none(self, monkeypatch):
|
|
"""Empty config means no allowlist — all actions visible."""
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": ""}},
|
|
)
|
|
assert _load_allowed_actions_config() is None
|
|
|
|
def test_comma_separated_string(self, monkeypatch):
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": "list_guilds,list_channels,fetch_messages"}},
|
|
)
|
|
result = _load_allowed_actions_config()
|
|
assert result == ["list_guilds", "list_channels", "fetch_messages"]
|
|
|
|
|
|
def test_config_load_failure_is_permissive(self, monkeypatch):
|
|
"""If config can't be loaded at all, fall back to None (all allowed)."""
|
|
def bad_load():
|
|
raise RuntimeError("disk gone")
|
|
monkeypatch.setattr("hermes_cli.config.load_config", bad_load)
|
|
assert _load_allowed_actions_config() is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Action filtering combines intents + allowlist
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestAvailableActions:
|
|
def test_all_available_when_unrestricted(self):
|
|
caps = {"detected": True, "has_members_intent": True, "has_message_content": True}
|
|
assert _available_actions(caps, None) == list(_ACTIONS.keys())
|
|
|
|
def test_no_members_intent_hides_member_actions(self):
|
|
caps = {"detected": True, "has_members_intent": False, "has_message_content": True}
|
|
actions = _available_actions(caps, None)
|
|
assert "search_members" not in actions
|
|
assert "member_info" not in actions
|
|
# fetch_messages stays — MESSAGE_CONTENT affects content field but action works
|
|
assert "fetch_messages" in actions
|
|
|
|
def test_allowlist_intersects_with_intents(self):
|
|
"""Allowlist can only narrow — not re-enable intent-gated actions."""
|
|
caps = {"detected": True, "has_members_intent": False, "has_message_content": True}
|
|
allowlist = ["list_guilds", "search_members", "fetch_messages"]
|
|
actions = _available_actions(caps, allowlist)
|
|
# search_members gated by intent → stripped even though allowlisted;
|
|
# result stays in canonical order regardless of allowlist order
|
|
assert actions == ["list_guilds", "fetch_messages"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Dynamic schema build (integration of intents + config)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestDynamicSchema:
|
|
def setup_method(self):
|
|
_reset_capability_cache()
|
|
|
|
def teardown_method(self):
|
|
_reset_capability_cache()
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_no_token_returns_none(self, mock_req, monkeypatch):
|
|
monkeypatch.delenv("DISCORD_BOT_TOKEN", raising=False)
|
|
assert get_dynamic_schema_core() is None
|
|
assert get_dynamic_schema_admin() is None
|
|
mock_req.assert_not_called()
|
|
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_no_members_intent_hides_search_members_from_core(
|
|
self, mock_req, monkeypatch,
|
|
):
|
|
"""search_members is a core action gated by GUILD_MEMBERS intent."""
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": ""}},
|
|
)
|
|
mock_req.return_value = {"flags": 1 << 18} # only MESSAGE_CONTENT
|
|
# Warm the capability cache — schema builds are non-blocking and use
|
|
# the permissive default until detection has completed (background
|
|
# thread + disk cache); filtering applies once caps are known.
|
|
_detect_capabilities("tok")
|
|
schema = get_dynamic_schema_core()
|
|
actions = schema["parameters"]["properties"]["action"]["enum"]
|
|
assert "search_members" not in actions
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_config_allowlist_narrows_admin_schema(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": "list_guilds,list_channels"}},
|
|
)
|
|
mock_req.return_value = {"flags": (1 << 14) | (1 << 18)}
|
|
schema = get_dynamic_schema_admin()
|
|
actions = schema["parameters"]["properties"]["action"]["enum"]
|
|
assert actions == ["list_guilds", "list_channels"]
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_empty_allowlist_with_valid_values_hides_tools(self, mock_req, monkeypatch):
|
|
"""If the allowlist resolves to zero valid actions (e.g. all names
|
|
were typos), get_dynamic_schema returns None so the tool is dropped."""
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": "typo_one,typo_two"}},
|
|
)
|
|
mock_req.return_value = {"flags": (1 << 14) | (1 << 18)}
|
|
assert get_dynamic_schema_core() is None
|
|
assert get_dynamic_schema_admin() is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Runtime allowlist enforcement (defense in depth — schema already filtered)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestRuntimeAllowlistEnforcement:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_denied_action_blocked_at_runtime(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": "list_guilds"}},
|
|
)
|
|
result = json.loads(discord_admin_handler(action="add_role", guild_id="1", user_id="2", role_id="3"))
|
|
assert "error" in result
|
|
assert "disabled by config" in result["error"]
|
|
mock_req.assert_not_called()
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_allowed_action_proceeds(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": "list_guilds"}},
|
|
)
|
|
mock_req.return_value = []
|
|
result = json.loads(discord_admin_handler(action="list_guilds"))
|
|
assert "guilds" in result
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 403 enrichment
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class Test403Enrichment:
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_403_in_runtime_is_enriched(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": ""}},
|
|
)
|
|
mock_req.side_effect = DiscordAPIError(403, '{"message":"Missing Permissions"}')
|
|
result = json.loads(discord_admin_handler(
|
|
action="add_role", guild_id="1", user_id="2", role_id="3",
|
|
))
|
|
assert "error" in result
|
|
assert "MANAGE_ROLES" in result["error"]
|
|
assert "Missing Permissions" in result["error"] # Raw body preserved
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_non_403_errors_are_not_enriched(self, mock_req, monkeypatch):
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": ""}},
|
|
)
|
|
mock_req.side_effect = DiscordAPIError(500, "server error")
|
|
result = json.loads(discord_admin_handler(action="list_guilds"))
|
|
assert "500" in result["error"]
|
|
assert "MANAGE_ROLES" not in result["error"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# model_tools integration — dynamic schema replaces static
|
|
# ---------------------------------------------------------------------------
|
|
|
|
class TestModelToolsIntegration:
|
|
def setup_method(self):
|
|
_reset_capability_cache()
|
|
from model_tools import _clear_tool_defs_cache
|
|
from tools.registry import invalidate_check_fn_cache
|
|
_clear_tool_defs_cache()
|
|
invalidate_check_fn_cache()
|
|
|
|
def teardown_method(self):
|
|
_reset_capability_cache()
|
|
from model_tools import _clear_tool_defs_cache
|
|
from tools.registry import invalidate_check_fn_cache
|
|
_clear_tool_defs_cache()
|
|
invalidate_check_fn_cache()
|
|
|
|
@patch("tools.discord_tool._discord_request")
|
|
def test_discord_admin_schema_rebuilt_by_get_tool_definitions(
|
|
self, mock_req, monkeypatch,
|
|
):
|
|
"""When model_tools.get_tool_definitions runs with discord_admin
|
|
available, it should replace the static schema with the dynamic one."""
|
|
monkeypatch.setenv("DISCORD_BOT_TOKEN", "tok")
|
|
monkeypatch.setattr(
|
|
"hermes_cli.config.load_config",
|
|
lambda: {"discord": {"server_actions": "list_guilds,server_info"}},
|
|
)
|
|
# Bot without GUILD_MEMBERS intent
|
|
mock_req.return_value = {"flags": 0}
|
|
|
|
from model_tools import get_tool_definitions
|
|
# skip_tool_search_assembly: this test exercises the dynamic schema
|
|
# rebuild; under tiered disclosure the discord tools defer behind the
|
|
# bridge, but the rebuilt schema is what tool_describe serves.
|
|
tools = get_tool_definitions(enabled_toolsets=["hermes-discord"], quiet_mode=True,
|
|
skip_tool_search_assembly=True)
|
|
discord_admin_tool = next(
|
|
(t for t in tools if t.get("function", {}).get("name") == "discord_admin"),
|
|
None,
|
|
)
|
|
assert discord_admin_tool is not None, "discord_admin should be in the schema"
|
|
actions = discord_admin_tool["function"]["parameters"]["properties"]["action"]["enum"]
|
|
assert actions == ["list_guilds", "server_info"]
|