# 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
486 lines
17 KiB
Python
486 lines
17 KiB
Python
"""Tests for the SimpleX Chat platform-plugin adapter.
|
|
|
|
Loaded via the ``_plugin_adapter_loader`` helper so this lives under
|
|
``plugin_adapter_simplex`` in ``sys.modules`` and cannot collide with
|
|
sibling platform-plugin tests in the same process.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import base64
|
|
import io
|
|
import json
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
|
|
from tests.gateway._plugin_adapter_loader import load_plugin_adapter
|
|
|
|
_simplex = load_plugin_adapter("simplex")
|
|
|
|
SimplexAdapter = _simplex.SimplexAdapter
|
|
check_requirements = _simplex.check_requirements
|
|
validate_config = _simplex.validate_config
|
|
is_connected = _simplex.is_connected
|
|
register = _simplex.register
|
|
_env_enablement = _simplex._env_enablement
|
|
_standalone_send = _simplex._standalone_send
|
|
_is_image_ext = _simplex._is_image_ext
|
|
_is_audio_ext = _simplex._is_audio_ext
|
|
_CORR_PREFIX = _simplex._CORR_PREFIX
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 1. Platform enum (plugin-discovered, not bundled)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def test_platform_enum_resolves_via_plugin_scan():
|
|
"""The plugin filesystem scan should expose Platform("simplex")."""
|
|
from gateway.config import Platform
|
|
p = Platform("simplex")
|
|
assert p.value == "simplex"
|
|
# Identity stability — repeated lookups return the same pseudo-member
|
|
assert Platform("simplex") is p
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 2. check_requirements / validate_config / is_connected
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_check_requirements_true_when_configured(monkeypatch):
|
|
monkeypatch.setenv("SIMPLEX_WS_URL", "ws://127.0.0.1:5225")
|
|
# websockets is a dev dep in this repo via the test plugins; the
|
|
# check_requirements() gate also asserts the package imports.
|
|
websockets_present = True
|
|
try:
|
|
import websockets # noqa: F401
|
|
except ImportError:
|
|
websockets_present = False
|
|
assert check_requirements() is websockets_present
|
|
|
|
|
|
def test_validate_config_uses_env_or_extra():
|
|
from gateway.config import PlatformConfig
|
|
# Empty extra + no env → invalid
|
|
cfg = PlatformConfig(enabled=True)
|
|
assert validate_config(cfg) is False
|
|
# extra-only path → valid
|
|
cfg2 = PlatformConfig(enabled=True, extra={"ws_url": "ws://localhost:5225"})
|
|
assert validate_config(cfg2) is True
|
|
|
|
|
|
def test_is_connected_mirrors_validate(monkeypatch):
|
|
from gateway.config import PlatformConfig
|
|
monkeypatch.delenv("SIMPLEX_WS_URL", raising=False)
|
|
cfg = PlatformConfig(enabled=True, extra={"ws_url": "ws://x"})
|
|
assert is_connected(cfg) is True
|
|
assert is_connected(PlatformConfig(enabled=True)) is False
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 3. _env_enablement seeds PlatformConfig.extra
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_env_enablement_seeds_home_channel(monkeypatch):
|
|
monkeypatch.setenv("SIMPLEX_WS_URL", "ws://127.0.0.1:5225")
|
|
monkeypatch.setenv("SIMPLEX_HOME_CHANNEL", "42")
|
|
monkeypatch.setenv("SIMPLEX_HOME_CHANNEL_NAME", "Personal")
|
|
seed = _env_enablement()
|
|
assert seed["home_channel"] == {"chat_id": "42", "name": "Personal"}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 4. Adapter init
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 6. Correlation IDs
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_corr_id_pending_set_self_trims():
|
|
from gateway.config import PlatformConfig
|
|
cfg = PlatformConfig(enabled=True, extra={"ws_url": "ws://localhost:5225"})
|
|
adapter = SimplexAdapter(cfg)
|
|
adapter._max_pending_corr = 4
|
|
for _ in range(10):
|
|
adapter._make_corr_id()
|
|
# After many additions, the pending set should be bounded by the trim
|
|
# logic — at most one trim window above the cap.
|
|
assert len(adapter._pending_corr_ids) <= adapter._max_pending_corr + 1
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 7. Outbound send (mocked WS)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_dm():
|
|
"""DMs use the structured ``/_send @<id> json [...]`` form.
|
|
|
|
The bare ``@<id> text`` chat-command form is unreliable — the
|
|
daemon silently drops messages when it cannot resolve the display
|
|
name. The structured ``/_send`` form addresses by ID and
|
|
survives newlines/quoting through ``json.dumps``, matching what
|
|
``send_image`` and ``send_document`` already do.
|
|
"""
|
|
from gateway.config import PlatformConfig
|
|
cfg = PlatformConfig(enabled=True, extra={"ws_url": "ws://localhost:5225"})
|
|
adapter = SimplexAdapter(cfg)
|
|
|
|
mock_ws = AsyncMock()
|
|
adapter._ws = mock_ws
|
|
|
|
result = await adapter.send("contact-42", "Hello, SimpleX!")
|
|
mock_ws.send.assert_called_once()
|
|
payload = json.loads(mock_ws.send.call_args[0][0])
|
|
assert payload["cmd"].startswith("/_send @contact-42 json ")
|
|
msg_content = json.loads(payload["cmd"].split(" json ", 1)[1])[0][
|
|
"msgContent"
|
|
]
|
|
assert msg_content == {"type": "text", "text": "Hello, SimpleX!"}
|
|
assert payload["corrId"].startswith(_CORR_PREFIX)
|
|
assert result.success is True
|
|
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_group():
|
|
"""Groups use the structured ``/_send #<id> json [...]`` form.
|
|
|
|
The bracket chat-command form ``#[<id>] text`` *looks* like an exact
|
|
ID match in the daemon docs but is parsed as a display-name lookup
|
|
— so messages to groups whose display name isn't literally the ID
|
|
silently drop. The structured ``/_send`` form addresses by numeric
|
|
ID and survives newlines/quoting through ``json.dumps``.
|
|
"""
|
|
from gateway.config import PlatformConfig
|
|
cfg = PlatformConfig(enabled=True, extra={"ws_url": "ws://localhost:5225"})
|
|
adapter = SimplexAdapter(cfg)
|
|
|
|
mock_ws = AsyncMock()
|
|
adapter._ws = mock_ws
|
|
|
|
result = await adapter.send("group:grp-99", "Hello, group!")
|
|
payload = json.loads(mock_ws.send.call_args[0][0])
|
|
assert payload["cmd"].startswith("/_send #grp-99 json ")
|
|
msg_content = json.loads(payload["cmd"].split(" json ", 1)[1])[0][
|
|
"msgContent"
|
|
]
|
|
assert msg_content == {"type": "text", "text": "Hello, group!"}
|
|
assert result.success is True
|
|
|
|
|
|
@pytest.mark.parametrize(("mode", "color"), [
|
|
("RGBA", (255, 0, 0, 128)),
|
|
("LA", (128, 128)),
|
|
("P", 0),
|
|
])
|
|
def test_prepare_image_flattens_jpeg_incompatible_modes(tmp_path, mode, color):
|
|
from PIL import Image
|
|
|
|
image_path = tmp_path / f"{mode}.png"
|
|
image = Image.new(mode, (256, 128), color)
|
|
if mode == "P":
|
|
image.putpalette([255, 0, 0] + [0, 0, 0] * 255)
|
|
image.info["transparency"] = 0
|
|
image.save(image_path)
|
|
|
|
prepared_path, thumb_uri = SimplexAdapter._prepare_image(str(image_path))
|
|
|
|
assert prepared_path == str(image_path)
|
|
encoded = thumb_uri.removeprefix(_simplex._THUMB_URI_PREFIX)
|
|
with Image.open(io.BytesIO(base64.b64decode(encoded))) as thumbnail:
|
|
assert thumbnail.mode == "RGB"
|
|
assert thumbnail.size == (128, 64)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_image_reports_thumbnail_preparation_failure(tmp_path, monkeypatch):
|
|
adapter = _adapter_with_ws()
|
|
image_path = tmp_path / "broken.png"
|
|
image_path.write_bytes(b"not an image")
|
|
monkeypatch.setattr(adapter, "_prepare_image", MagicMock(side_effect=OSError("bad image")))
|
|
adapter._send_items = AsyncMock()
|
|
|
|
result = await adapter.send_image_file("contact-42", str(image_path))
|
|
|
|
assert result.success is False
|
|
assert result.error == "Failed to prepare image: bad image"
|
|
adapter._send_items.assert_not_awaited()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 7b. Channel directory enumeration (list_channels)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _adapter_with_ws():
|
|
from gateway.config import PlatformConfig
|
|
cfg = PlatformConfig(enabled=True, extra={"ws_url": "ws://localhost:5225"})
|
|
adapter = SimplexAdapter(cfg)
|
|
adapter._ws = AsyncMock()
|
|
return adapter
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_channels_contacts_and_groups():
|
|
adapter = _adapter_with_ws()
|
|
|
|
async def fake_send_command(command, timeout=30.0):
|
|
if command == "/contacts":
|
|
return {
|
|
"contacts": [
|
|
{"contactId": 1, "localDisplayName": "alice"},
|
|
{"contactId": 2, "profile": {"displayName": "bob"}},
|
|
"garbage",
|
|
]
|
|
}
|
|
if command == "/groups":
|
|
return {
|
|
"groups": [
|
|
{"groupId": 7, "localDisplayName": "friends"},
|
|
# [groupInfo, groupSummary] pair form
|
|
[{"groupId": 9, "groupProfile": {"displayName": "work"}}, {}],
|
|
]
|
|
}
|
|
return None
|
|
|
|
adapter._send_command = fake_send_command
|
|
channels = await adapter.list_channels()
|
|
|
|
assert {"id": "alice", "name": "alice", "type": "dm"} in channels
|
|
assert {"id": "bob", "name": "bob", "type": "dm"} in channels
|
|
assert {"id": "group:7", "name": "friends", "type": "group"} in channels
|
|
assert {"id": "group:9", "name": "work", "type": "group"} in channels
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_channels_returns_none_when_disconnected():
|
|
"""None (not []) so the directory falls back to session discovery."""
|
|
from gateway.config import PlatformConfig
|
|
cfg = PlatformConfig(enabled=True, extra={"ws_url": "ws://localhost:5225"})
|
|
adapter = SimplexAdapter(cfg)
|
|
assert adapter._ws is None
|
|
assert await adapter.list_channels() is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_channels_returns_none_on_contacts_timeout():
|
|
adapter = _adapter_with_ws()
|
|
|
|
async def fake_send_command(command, timeout=30.0):
|
|
return None # daemon unresponsive
|
|
|
|
adapter._send_command = fake_send_command
|
|
assert await adapter.list_channels() is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 8. Inbound: filter own-echo by corrId prefix
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 9. Standalone (out-of-process) send for cron
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_standalone_send_missing_websockets(monkeypatch):
|
|
"""When websockets is unimportable, return a clean error dict.
|
|
|
|
Implementation detail: the standalone path does ``import websockets``
|
|
inside the function body. We simulate the package being absent by
|
|
pulling it out of ``sys.modules`` and pointing the finder at None.
|
|
"""
|
|
import sys
|
|
saved_websockets = sys.modules.pop("websockets", None)
|
|
saved_meta = list(sys.meta_path)
|
|
|
|
class _Blocker:
|
|
@staticmethod
|
|
def find_spec(name, path=None, target=None):
|
|
if name == "websockets" or name.startswith("websockets."):
|
|
raise ImportError("websockets blocked for test")
|
|
return None
|
|
|
|
sys.meta_path.insert(0, _Blocker())
|
|
try:
|
|
pconfig = MagicMock()
|
|
pconfig.extra = {"ws_url": "ws://localhost:5225"}
|
|
result = await _standalone_send(pconfig, "contact-42", "hi")
|
|
assert isinstance(result, dict)
|
|
assert "error" in result
|
|
assert "websockets" in result["error"]
|
|
finally:
|
|
sys.meta_path[:] = saved_meta
|
|
if saved_websockets is not None:
|
|
sys.modules["websockets"] = saved_websockets
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_standalone_send_defaults_to_local_daemon(monkeypatch):
|
|
monkeypatch.delenv("SIMPLEX_WS_URL", raising=False)
|
|
pconfig = MagicMock()
|
|
pconfig.extra = {}
|
|
|
|
sent_payloads = []
|
|
|
|
class DummyWs:
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, exc_type, exc, tb):
|
|
return None
|
|
|
|
async def send(self, payload):
|
|
sent_payloads.append(json.loads(payload))
|
|
|
|
def fake_connect(url, **kwargs):
|
|
assert url == "ws://127.0.0.1:5225"
|
|
assert kwargs["open_timeout"] == 10
|
|
assert kwargs["close_timeout"] == 5
|
|
return DummyWs()
|
|
|
|
import websockets
|
|
monkeypatch.setattr(websockets, "connect", fake_connect)
|
|
|
|
result = await _standalone_send(pconfig, "contact-42", "hi")
|
|
assert result == {"success": True, "platform": "simplex", "chat_id": "contact-42"}
|
|
assert sent_payloads[0]["cmd"].startswith("/_send @contact-42 json ")
|
|
msg_content = json.loads(
|
|
sent_payloads[0]["cmd"].split(" json ", 1)[1]
|
|
)[0]["msgContent"]
|
|
assert msg_content == {"type": "text", "text": "hi"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_health_monitor_does_not_reconnect_quiet_healthy_ws(monkeypatch):
|
|
from gateway.config import PlatformConfig
|
|
cfg = PlatformConfig(enabled=True, extra={"ws_url": "ws://localhost:5225"})
|
|
adapter = SimplexAdapter(cfg)
|
|
adapter._running = True
|
|
adapter._last_ws_activity = 0
|
|
adapter._ws = AsyncMock()
|
|
|
|
monkeypatch.setattr(_simplex, "HEALTH_CHECK_INTERVAL", 0.01)
|
|
monkeypatch.setattr(_simplex, "HEALTH_CHECK_STALE_THRESHOLD", 0.01)
|
|
|
|
task = asyncio.create_task(adapter._health_monitor())
|
|
await asyncio.sleep(0.03)
|
|
adapter._running = False
|
|
await asyncio.wait_for(task, timeout=1)
|
|
|
|
adapter._ws.close.assert_not_called()
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 10. register() — plugin-side metadata
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Inbound attachment message type classification
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _make_file_chat_item(file_path: str, file_name: str) -> dict:
|
|
"""Minimal direct-chat rcvMsgContent item carrying a completed file."""
|
|
return {
|
|
"chatInfo": {
|
|
"type": "direct",
|
|
"contact": {"contactId": 42, "localDisplayName": "tester"},
|
|
},
|
|
"chatItem": {
|
|
"chatDir": {"type": "directRcv"},
|
|
"meta": {"itemTs": "2026-01-01T00:00:00Z"},
|
|
"content": {
|
|
"type": "rcvMsgContent",
|
|
"msgContent": {"type": "file", "text": "here you go"},
|
|
},
|
|
"file": {
|
|
"fileId": 7,
|
|
"fileName": file_name,
|
|
"fileSource": {"filePath": file_path},
|
|
},
|
|
},
|
|
}
|
|
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Multiplex secondary-profile scope
|
|
# ---------------------------------------------------------------------------
|
|
#
|
|
# Every SIMPLEX_* read (auto_accept / group_allowed in __init__, ws_url in the
|
|
# registry gates, everything in _env_enablement) went through raw os.getenv,
|
|
# which under multiplexing holds the DEFAULT profile's YAML-to-env bridge
|
|
# output -- a secondary profile silently borrowed the default's daemon URL,
|
|
# group allowlist and auto-accept setting. Reads now go through the module's
|
|
# ``_get_scoped_secret`` (profile .env AND extra both honored; scoped miss
|
|
# fails closed; unscoped default profile keeps env precedence).
|
|
|
|
|
|
@pytest.fixture
|
|
def multiplex_scope():
|
|
"""Install multiplex + a secondary-profile secret scope; restore after."""
|
|
from agent.secret_scope import (
|
|
reset_secret_scope,
|
|
set_multiplex_active,
|
|
set_secret_scope,
|
|
)
|
|
|
|
tokens = []
|
|
|
|
def install(scope=None):
|
|
set_multiplex_active(True)
|
|
tokens.append(set_secret_scope(scope or {}))
|
|
|
|
yield install
|
|
for token in reversed(tokens):
|
|
reset_secret_scope(token)
|
|
set_multiplex_active(False)
|
|
|
|
|
|
@pytest.fixture
|
|
def default_profile_env(monkeypatch):
|
|
"""The default profile's YAML-to-env bridge output in os.environ."""
|
|
monkeypatch.setenv("SIMPLEX_WS_URL", "ws://default:5225")
|
|
monkeypatch.setenv("SIMPLEX_GROUP_ALLOWED", "*")
|
|
monkeypatch.setenv("SIMPLEX_AUTO_ACCEPT", "true")
|
|
|
|
|
|
def test_multiplex_scoped_miss_does_not_borrow_default_profile_env(
|
|
multiplex_scope, default_profile_env
|
|
):
|
|
"""A secondary profile with no SimpleX config of its own must not be
|
|
auto-enabled off the default's daemon URL, nor inherit its wide-open
|
|
group allowlist."""
|
|
from gateway.config import PlatformConfig
|
|
|
|
multiplex_scope({"SOMETHING_ELSE": "x"})
|
|
assert _env_enablement() is None
|
|
assert check_requirements() is False
|
|
assert is_connected(PlatformConfig(enabled=True, extra={})) is False
|
|
adapter = SimplexAdapter(PlatformConfig(enabled=True, extra={"auto_accept": False}))
|
|
assert adapter.group_allow_from == set()
|
|
assert adapter.auto_accept is False
|
|
|
|
|
|
def test_multiplex_scope_reads_profile_own_env_not_default(
|
|
multiplex_scope, default_profile_env
|
|
):
|
|
"""A secondary profile's own .env (installed as the scope) is honored --
|
|
the extra-only shape would have ignored it."""
|
|
multiplex_scope({"SIMPLEX_WS_URL": "ws://profile:5225", "SIMPLEX_GROUP_ALLOWED": "g1"})
|
|
seeded = _env_enablement()
|
|
assert seeded == {"ws_url": "ws://profile:5225", "group_allowed": "g1"}
|
|
assert check_requirements() is True
|