test_adapter.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. """Unit tests for the Chatto platform adapter.
  2. Covers:
  3. - Emoji shortcode conversion
  4. - Adapter instantiation and properties
  5. - Registration and requirements
  6. - Basic functionality with chattolib
  7. - Message sending and reactions
  8. - User lookup (with caching)
  9. - Presence and custom status
  10. All network calls are mocked — no real HTTP or WebSocket connections.
  11. """
  12. import asyncio
  13. import os
  14. import sys
  15. import tempfile
  16. from unittest.mock import AsyncMock, MagicMock, patch, call
  17. from collections import OrderedDict
  18. import pytest
  19. import pytest_asyncio
  20. # Import chattolib types for tests - using vendored chattolib from adapter
  21. # -- Path setup --
  22. # The Hermes agent itself is not a dependency of this plugin; point HERMES_ROOT
  23. # at a checkout to run these tests outside a deployed agent.
  24. PLUGIN_ROOT = os.path.abspath(os.path.dirname(__file__))
  25. sys.path.insert(0, PLUGIN_ROOT)
  26. sys.path.insert(0, os.environ.get("HERMES_ROOT", "/opt/hermes"))
  27. sys.path.insert(0, "/root/.hermes/plugins/platforms/chatto")
  28. from adapter import (
  29. ChattoAdapter,
  30. _capabilities,
  31. HermesChatType,
  32. chat_type_for_room_kind,
  33. hermes_check_fn as check_requirements,
  34. hermes_validate_config as validate_config,
  35. register,
  36. )
  37. from chattolib.realtime_types import ReactionPayload
  38. from chattolib.types import (
  39. AssetUrl,
  40. Message,
  41. MessageAttachment,
  42. PresenceStatus,
  43. Room,
  44. RoomKind,
  45. User,
  46. )
  47. from platform_config import ChattoConstants
  48. from gateway.config import PlatformConfig
  49. from gateway.platforms.base import (
  50. BasePlatformAdapter,
  51. CachedMedia,
  52. MessageEvent,
  53. MessageType,
  54. SendResult,
  55. get_inbound_media_max_bytes,
  56. )
  57. _EMOJI_TO_SHORTCODE = ChattoConstants.EMOJI_TO_SHORTCODE
  58. _MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  59. _SEEN_CAP = ChattoConstants.SEEN_CAP
  60. # -- Helpers --
  61. class _MockPluginContext:
  62. """Minimal mock for the plugin registration context."""
  63. def __init__(self):
  64. self.registered_names = []
  65. self.registered_kwargs = None
  66. def register_platform(self, **kwargs):
  67. from gateway.platform_registry import platform_registry, PlatformEntry
  68. entry = PlatformEntry(
  69. name=kwargs["name"],
  70. label=kwargs.get("label", kwargs["name"]),
  71. adapter_factory=kwargs.get("adapter_factory"),
  72. check_fn=kwargs.get("check_fn"),
  73. validate_config=kwargs.get("validate_config"),
  74. is_connected=kwargs.get("is_connected"),
  75. required_env=kwargs.get("required_env", []),
  76. source="plugin",
  77. )
  78. platform_registry.register(entry)
  79. self.registered_names.append(kwargs["name"])
  80. self.registered_kwargs = kwargs
  81. def _ensure_chatto_registered():
  82. """Register the platform so Platform(PLATFORM_NAME) resolves."""
  83. from gateway.platform_registry import platform_registry
  84. if not platform_registry.is_registered(ChattoConstants.PLATFORM_NAME):
  85. ctx = _MockPluginContext()
  86. register(ctx)
  87. _CHATTO_ENV_KEYS = [
  88. "CHATTO_BASE_URL", "CHATTO_LOGIN", "CHATTO_PASSWORD",
  89. "CHATTO_CHANNELS", "CHATTO_HOME_CHANNEL",
  90. "CHATTO_REQUIRE_MENTION", "CHATTO_ALLOWED_USERS",
  91. "CHATTO_ALLOW_ALL_USERS", "CHATTO_AUTO_THREAD",
  92. "CHATTO_REACTIONS",
  93. ]
  94. def _clear_chatto_env(monkeypatch=None):
  95. """Remove all CHATTO_* env vars so tests start from a clean slate."""
  96. for key in _CHATTO_ENV_KEYS:
  97. if monkeypatch is not None:
  98. monkeypatch.delenv(key, raising=False)
  99. else:
  100. os.environ.pop(key, None)
  101. def _make_config(**extra_overrides):
  102. """Create a minimal PlatformConfig for testing."""
  103. _ensure_chatto_registered()
  104. extra = {"base_url": "https://chat.example.com", "channels": ["room1"]}
  105. extra.update(extra_overrides)
  106. return PlatformConfig(enabled=True, extra=extra)
  107. def _make_room(room_id, name, kind):
  108. """Build a real chattolib Room, as the client would return."""
  109. return Room(id=room_id, name=name, kind=kind, description="",
  110. archived=False, group_id="", universal=kind != RoomKind.DM)
  111. def _make_user(user_id, login):
  112. """Build a real chattolib User, as the member directory would return."""
  113. return User(id=user_id, login=login, display_name=login.replace("_", " ").title())
  114. def _make_attachment(filename, content_type, url="https://cdn.example.com/a"):
  115. """Build a real MessageAttachment carrying a (pre-signed) asset URL."""
  116. return MessageAttachment(
  117. id="asset-" + filename,
  118. filename=filename,
  119. content_type=content_type,
  120. asset_url=AssetUrl(url=url),
  121. )
  122. def _make_message(body="hi", attachments=None, message_id="msg-1", room_id="room-1"):
  123. """Build a real chattolib Message, as fetch_message() would return."""
  124. return Message(
  125. id=message_id,
  126. room_id=room_id,
  127. created_at=None,
  128. actor_id="user-1",
  129. body=body,
  130. attachments=list(attachments or []),
  131. )
  132. def _make_posted_payload(room_id="room-1", message_event_id="msg-1"):
  133. """A message_posted payload whose fetch_message() the caller stubs."""
  134. payload = MagicMock()
  135. payload.room_id = room_id
  136. payload.message_event_id = message_event_id
  137. payload.thread_root_event_id = None
  138. return payload
  139. def _cached(path, media_type, kind):
  140. """The CachedMedia that cache_media_bytes() would return for an attachment."""
  141. return CachedMedia(path=path, media_type=media_type, kind=kind, display_name="f")
  142. def _make_adapter(**extra_overrides):
  143. """Create a ChattoAdapter with mocked config."""
  144. _clear_chatto_env()
  145. cfg = _make_config(**extra_overrides)
  146. adapter = ChattoAdapter(cfg)
  147. adapter._chatto_client = MagicMock()
  148. adapter._token = "test-token"
  149. adapter._user_id = "bot-user-id"
  150. adapter._user_login = "hermes_bot"
  151. adapter._user_display = "Hermes Bot"
  152. return adapter
  153. # -- Emoji shortcode conversion --
  154. class TestEmojiShortcode:
  155. """Test emoji to shortcode mapping."""
  156. def test_emoji_to_shortcode_exists(self):
  157. assert isinstance(_EMOJI_TO_SHORTCODE, dict)
  158. assert len(_EMOJI_TO_SHORTCODE) > 0
  159. def test_emoji_to_shortcode_common_emojis(self):
  160. assert _EMOJI_TO_SHORTCODE.get("👍") == "thumbsup"
  161. assert _EMOJI_TO_SHORTCODE.get("👎") == "thumbsdown"
  162. assert _EMOJI_TO_SHORTCODE.get("❤️") == "heart"
  163. assert _EMOJI_TO_SHORTCODE.get("❤") == "heart"
  164. assert _EMOJI_TO_SHORTCODE.get("✅") == "white_check_mark"
  165. assert _EMOJI_TO_SHORTCODE.get("❌") == "x"
  166. # -- Adapter instantiation and properties --
  167. class TestAdapterInstantiation:
  168. """Test ChattoAdapter creation and basic properties."""
  169. def test_adapter_creation(self):
  170. cfg = _make_config()
  171. adapter = ChattoAdapter(cfg)
  172. assert adapter is not None
  173. # Platform members created dynamically from a plugin name carry the
  174. # name upper-cased; the registered identity is the value.
  175. assert adapter.platform.value == ChattoConstants.PLATFORM_NAME
  176. def test_adapter_max_message_length(self):
  177. """The framework chunks via max_message_length_for_chat(), which reads
  178. the adapter-scalar MAX_MESSAGE_LENGTH and silently falls back to 4096
  179. when it is missing."""
  180. cfg = _make_config()
  181. adapter = ChattoAdapter(cfg)
  182. assert adapter.MAX_MESSAGE_LENGTH == _MAX_MESSAGE_LENGTH
  183. assert adapter.max_message_length_for_chat("room-1") == _MAX_MESSAGE_LENGTH
  184. def test_adapter_splits_long_messages(self):
  185. cfg = _make_config()
  186. adapter = ChattoAdapter(cfg)
  187. assert adapter.splits_long_messages is True
  188. def test_adapter_threads_enabled_by_default(self):
  189. """There is no capability flag for threads — Chatto threading is driven
  190. by the auto_thread setting, which defaults to on."""
  191. cfg = _make_config()
  192. adapter = ChattoAdapter(cfg)
  193. assert adapter.chatto_config.auto_thread.value is True
  194. # -- Registration and requirements --
  195. class TestRegistration:
  196. """Test plugin registration."""
  197. def test_register_called(self):
  198. ctx = _MockPluginContext()
  199. register(ctx)
  200. assert ChattoConstants.PLATFORM_NAME in ctx.registered_names
  201. assert ctx.registered_kwargs["name"] == ChattoConstants.PLATFORM_NAME
  202. assert ctx.registered_kwargs["label"] == ChattoConstants.PLATFORM_LABEL
  203. assert ctx.registered_kwargs["max_message_length"] == _MAX_MESSAGE_LENGTH
  204. def test_platform_hint_advertises_media_sending(self):
  205. """This hint is the only thing telling the model the channel can carry
  206. files — without it the agent shells out to a CLI to deliver an image."""
  207. ctx = _MockPluginContext()
  208. register(ctx)
  209. hint = ctx.registered_kwargs["platform_hint"]
  210. assert "MEDIA:/absolute/path/to/file" in hint
  211. assert "![alt](url)" in hint
  212. def test_startup_logs_the_capabilities(self, caplog):
  213. with caplog.at_level("INFO"):
  214. register(_MockPluginContext())
  215. logged = "\n".join(caplog.messages)
  216. assert "images" in logged
  217. assert "reactions" in logged
  218. def test_capabilities_skips_methods_we_do_not_override(self):
  219. """An inherited base fallback is not a capability — claiming it would
  220. promise the user something the adapter cannot actually do."""
  221. assert "video" in _capabilities()
  222. with patch.object(ChattoAdapter, "send_video", BasePlatformAdapter.send_video):
  223. assert "video" not in _capabilities()
  224. def test_check_requirements(self):
  225. assert check_requirements() is True
  226. def test_check_requirements_missing(self):
  227. with patch("builtins.__import__", side_effect=ImportError("no chattolib")):
  228. assert check_requirements() is False
  229. def test_validate_config(self):
  230. _clear_chatto_env()
  231. os.environ["CHATTO_BASE_URL"] = "https://chat.test"
  232. os.environ["CHATTO_LOGIN"] = "user"
  233. os.environ["CHATTO_PASSWORD"] = "pass"
  234. cfg = PlatformConfig(enabled=True, extra={"base_url": "https://chat.test"})
  235. assert validate_config(cfg) is True
  236. _clear_chatto_env()
  237. # -- Send functionality --
  238. class TestSend:
  239. """Test message sending functionality."""
  240. @pytest_asyncio.fixture
  241. def adapter(self):
  242. _clear_chatto_env()
  243. cfg = _make_config()
  244. adapter = ChattoAdapter(cfg)
  245. adapter._chatto_client = MagicMock()
  246. adapter._chatto_client.post_message = AsyncMock()
  247. adapter._token = "test-token"
  248. adapter._user_id = "bot-user-id"
  249. return adapter
  250. async def test_send_calls_post_message(self, adapter):
  251. mock_msg = MagicMock()
  252. mock_msg.id = "msg-123"
  253. adapter._chatto_client.post_message.return_value = mock_msg
  254. result = await adapter.send("room-1", "Hello world")
  255. assert result.success is True
  256. assert result.message_id == "msg-123"
  257. adapter._chatto_client.post_message.assert_called_once()
  258. async def test_send_with_thread(self, adapter):
  259. mock_msg = MagicMock()
  260. mock_msg.id = "msg-456"
  261. adapter._chatto_client.post_message.return_value = mock_msg
  262. result = await adapter.send("room-1", "Hello", reply_to="thread-123")
  263. assert result.success is True
  264. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  265. assert call_kwargs["thread_root_event_id"] == "thread-123"
  266. # -- Reactions --
  267. class TestReactions:
  268. """Test reaction functionality."""
  269. @pytest_asyncio.fixture
  270. def adapter(self):
  271. _clear_chatto_env()
  272. cfg = _make_config()
  273. adapter = ChattoAdapter(cfg)
  274. adapter._chatto_client = MagicMock()
  275. adapter._chatto_client.add_reaction = AsyncMock()
  276. adapter._chatto_client.remove_reaction = AsyncMock()
  277. adapter._token = "test-token"
  278. return adapter
  279. async def test_send_reaction(self, adapter):
  280. await adapter.add_reaction("room-1", "msg-1", "👍")
  281. adapter._chatto_client.add_reaction.assert_called_once()
  282. async def test_remove_reaction(self, adapter):
  283. await adapter.remove_reaction("room-1", "msg-1", "👍")
  284. adapter._chatto_client.remove_reaction.assert_called_once()
  285. async def test_on_processing_start_adds_eyes_reaction(self, adapter):
  286. """on_processing_start should call add_reaction with 👀."""
  287. event = MagicMock()
  288. event.message_id = "msg-1"
  289. event.source.chat_id = "room-1"
  290. await adapter.on_processing_start(event)
  291. adapter._chatto_client.add_reaction.assert_called_once()
  292. call_kwargs = adapter._chatto_client.add_reaction.call_args.kwargs
  293. assert call_kwargs["message_event_id"] == "msg-1"
  294. assert call_kwargs["room_id"] == "room-1"
  295. assert call_kwargs["emoji"] == "eyes"
  296. async def test_on_processing_start_empty_message_id(self, adapter):
  297. """on_processing_start should skip reaction when message_id is empty."""
  298. event = MagicMock()
  299. event.message_id = None
  300. event.source.chat_id = "room-1"
  301. await adapter.on_processing_start(event)
  302. adapter._chatto_client.add_reaction.assert_not_called()
  303. async def test_on_processing_start_reactions_disabled(self, adapter):
  304. """on_processing_start should skip when reactions config is False."""
  305. adapter.chatto_config.reactions.value = False
  306. event = MagicMock()
  307. event.message_id = "msg-1"
  308. event.source.chat_id = "room-1"
  309. await adapter.on_processing_start(event)
  310. adapter._chatto_client.add_reaction.assert_not_called()
  311. # -- Edit and Delete Messages --
  312. class TestMessageEditing:
  313. """Test message editing and deletion."""
  314. @pytest_asyncio.fixture
  315. def adapter(self):
  316. _clear_chatto_env()
  317. cfg = _make_config()
  318. adapter = ChattoAdapter(cfg)
  319. adapter._chatto_client = MagicMock()
  320. adapter._chatto_client.update_message = AsyncMock()
  321. adapter._chatto_client.delete_message = AsyncMock(return_value=True)
  322. adapter._token = "test-token"
  323. return adapter
  324. async def test_edit_message(self, adapter):
  325. result = await adapter.edit_message("room-1", "msg-1", "New content")
  326. assert result.success is True
  327. adapter._chatto_client.update_message.assert_called_once()
  328. call_kwargs = adapter._chatto_client.update_message.call_args.kwargs
  329. assert call_kwargs["room_id"] == "room-1"
  330. assert call_kwargs["event_id"] == "msg-1"
  331. assert call_kwargs["body"] == "New content"
  332. async def test_edit_message_marks_own_edit_seen(self, adapter):
  333. """The edit echoes back as message_edited — it must not look inbound."""
  334. mock_msg = MagicMock()
  335. mock_msg.id = "msg-1"
  336. adapter._chatto_client.update_message.return_value = mock_msg
  337. await adapter.edit_message("room-1", "msg-1", "New content")
  338. assert adapter._is_seen("msg-1") is True
  339. async def test_edit_message_too_long_refuses(self, adapter):
  340. """Overlong content must fall back to send() (which splits), not be
  341. silently truncated into a lossy edit."""
  342. result = await adapter.edit_message(
  343. "room-1", "msg-1", "x" * (_MAX_MESSAGE_LENGTH + 1),
  344. )
  345. assert result.success is False
  346. adapter._chatto_client.update_message.assert_not_called()
  347. async def test_edit_message_empty_content(self, adapter):
  348. result = await adapter.edit_message("room-1", "msg-1", "")
  349. assert result.success is False
  350. adapter._chatto_client.update_message.assert_not_called()
  351. async def test_edit_message_error_is_retryable(self, adapter):
  352. from chattolib.exceptions import ChattoError
  353. adapter._chatto_client.update_message.side_effect = ChattoError("boom")
  354. result = await adapter.edit_message("room-1", "msg-1", "New content")
  355. assert result.success is False
  356. assert result.retryable is True
  357. async def test_delete_message(self, adapter):
  358. result = await adapter.delete_message("room-1", "msg-1")
  359. assert result is True
  360. adapter._chatto_client.delete_message.assert_called_once()
  361. call_kwargs = adapter._chatto_client.delete_message.call_args.kwargs
  362. assert call_kwargs["room_id"] == "room-1"
  363. assert call_kwargs["event_id"] == "msg-1"
  364. async def test_delete_message_missing_ids(self, adapter):
  365. assert await adapter.delete_message("", "msg-1") is False
  366. assert await adapter.delete_message("room-1", "") is False
  367. adapter._chatto_client.delete_message.assert_not_called()
  368. async def test_delete_message_error_returns_false(self, adapter):
  369. from chattolib.exceptions import ChattoError
  370. adapter._chatto_client.delete_message.side_effect = ChattoError("nope")
  371. assert await adapter.delete_message("room-1", "msg-1") is False
  372. # -- Outgoing text formatting --
  373. class TestFormatMessage:
  374. """format_message() only fixes what renders wrong in Chatto."""
  375. def test_normalises_crlf(self):
  376. adapter = _make_adapter()
  377. assert adapter.format_message("a\r\nb\rc") == "a\nb\nc"
  378. def test_collapses_excess_blank_lines(self):
  379. adapter = _make_adapter()
  380. assert adapter.format_message("a\n\n\n\n\n\nb") == "a\n\n\nb"
  381. def test_leaves_markdown_untouched(self):
  382. adapter = _make_adapter()
  383. text = "**bold** `code`\n\n```py\nx = 1\n```\n- item"
  384. assert adapter.format_message(text) == text
  385. def test_empty_content(self):
  386. adapter = _make_adapter()
  387. assert adapter.format_message("") == ""
  388. # -- Handoff threads --
  389. class TestHandoffThread:
  390. """create_handoff_thread() anchors a handoff on a seed message."""
  391. @pytest_asyncio.fixture
  392. def adapter(self):
  393. adapter = _make_adapter()
  394. adapter._chatto_client.post_message = AsyncMock()
  395. adapter._chatto_client.follow_thread = AsyncMock()
  396. return adapter
  397. async def test_returns_seed_message_id(self, adapter):
  398. mock_msg = MagicMock()
  399. mock_msg.id = "seed-1"
  400. adapter._chatto_client.post_message.return_value = mock_msg
  401. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  402. result = await adapter.create_handoff_thread("room-1", "Refactor run")
  403. assert result == "seed-1"
  404. assert adapter._chatto_client.post_message.call_args.kwargs["room_id"] == "room-1"
  405. adapter._chatto_client.follow_thread.assert_called_once_with("room-1", "seed-1")
  406. # Our own seed must not come back in as inbound traffic.
  407. assert adapter._is_seen("seed-1") is True
  408. async def test_dm_has_no_threads(self, adapter):
  409. adapter._room_kinds["dm-1"] = RoomKind.DM
  410. assert await adapter.create_handoff_thread("dm-1", "x") is None
  411. adapter._chatto_client.post_message.assert_not_called()
  412. async def test_seed_post_failure(self, adapter):
  413. adapter._chatto_client.post_message.side_effect = RuntimeError("down")
  414. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  415. assert await adapter.create_handoff_thread("room-1", "x") is None
  416. # -- Native file / video / audio delivery --
  417. class TestNativeSends:
  418. """send_document/_video/_voice upload instead of apologising in text."""
  419. @pytest_asyncio.fixture
  420. def adapter(self):
  421. adapter = _make_adapter()
  422. adapter._chatto_client.post_message = AsyncMock()
  423. adapter._upload_asset = AsyncMock(return_value="asset-1")
  424. adapter.validate_media_delivery_path = MagicMock(side_effect=lambda p: p)
  425. mock_msg = MagicMock()
  426. mock_msg.id = "msg-1"
  427. adapter._chatto_client.post_message.return_value = mock_msg
  428. return adapter
  429. @pytest.mark.parametrize(
  430. "method,arg_name",
  431. [
  432. ("send_document", "file_path"),
  433. ("send_video", "video_path"),
  434. ("send_voice", "audio_path"),
  435. ("send_image_file", "image_path"),
  436. ],
  437. )
  438. async def test_uploads_and_attaches(self, adapter, method, arg_name):
  439. result = await getattr(adapter, method)(
  440. "room-1", **{arg_name: "/tmp/thing.bin"}, caption="here you go",
  441. )
  442. assert result.success is True
  443. adapter._upload_asset.assert_called_once_with("room-1", "/tmp/thing.bin")
  444. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  445. assert call_kwargs["attachment_asset_ids"] == ["asset-1"]
  446. assert call_kwargs["body"] == "here you go"
  447. async def test_unsafe_path_falls_back_to_notice(self, adapter):
  448. adapter.validate_media_delivery_path = MagicMock(return_value=None)
  449. adapter.send = AsyncMock(return_value=SendResult(success=True))
  450. await adapter.send_document("room-1", "/etc/shadow")
  451. adapter._upload_asset.assert_not_called()
  452. # Never echo the host path into chat.
  453. sent_text = adapter.send.call_args.args[1]
  454. assert "/etc/shadow" not in sent_text
  455. async def test_upload_failure_falls_back_to_notice(self, adapter):
  456. adapter._upload_asset = AsyncMock(return_value=None)
  457. adapter.send = AsyncMock(return_value=SendResult(success=True))
  458. await adapter.send_video("room-1", "/tmp/clip.mp4", caption="a clip")
  459. sent_text = adapter.send.call_args.args[1]
  460. assert sent_text.startswith("a clip\n")
  461. assert "/tmp/clip.mp4" not in sent_text
  462. # -- Batched image delivery --
  463. class TestSendMultipleImages:
  464. """A batch of images belongs in ONE Chatto message."""
  465. @pytest_asyncio.fixture
  466. def adapter(self):
  467. adapter = _make_adapter()
  468. adapter._chatto_client.post_message = AsyncMock()
  469. mock_msg = MagicMock()
  470. mock_msg.id = "msg-1"
  471. adapter._chatto_client.post_message.return_value = mock_msg
  472. adapter._upload_asset = AsyncMock(side_effect=["asset-1", "asset-2"])
  473. adapter.validate_media_delivery_path = MagicMock(side_effect=lambda p: p)
  474. return adapter
  475. async def test_bundles_into_single_message(self, adapter):
  476. await adapter.send_multiple_images(
  477. "room-1", [("/tmp/a.png", "first"), ("/tmp/b.png", "second")],
  478. )
  479. adapter._chatto_client.post_message.assert_called_once()
  480. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  481. assert call_kwargs["attachment_asset_ids"] == ["asset-1", "asset-2"]
  482. assert call_kwargs["body"] == "first\nsecond"
  483. async def test_single_image_uses_base_path(self, adapter):
  484. """One image is not a batch — leave it to the base implementation.
  485. Also pins the send_image_file signature: the base class calls it with
  486. ``image_path=`` as a keyword, so a renamed parameter degrades every
  487. native image send to a text notice.
  488. """
  489. adapter.send_image_file = AsyncMock(return_value=SendResult(success=True))
  490. await adapter.send_multiple_images("room-1", [("file:///tmp/a.png", "only")])
  491. adapter._upload_asset.assert_not_called()
  492. adapter.send_image_file.assert_called_once()
  493. assert adapter.send_image_file.call_args.kwargs["image_path"] == "/tmp/a.png"
  494. async def test_partial_upload_failure_still_sends_the_rest(self, adapter):
  495. adapter._upload_asset = AsyncMock(side_effect=["asset-1", None])
  496. await adapter.send_multiple_images(
  497. "room-1", [("/tmp/a.png", "first"), ("/tmp/b.png", "second")],
  498. )
  499. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  500. assert call_kwargs["attachment_asset_ids"] == ["asset-1"]
  501. async def test_file_uri_is_unquoted(self, adapter):
  502. await adapter.send_multiple_images(
  503. "room-1",
  504. [("file:///tmp/a%20b.png", ""), ("/tmp/c.png", "")],
  505. )
  506. first_path = adapter._upload_asset.call_args_list[0].args[1]
  507. assert first_path == "/tmp/a b.png"
  508. # -- Reaction event forwarding --
  509. class TestReactionForwarding:
  510. """Human reactions reach the gateway's reaction hook surface."""
  511. @pytest_asyncio.fixture
  512. def adapter(self):
  513. adapter = _make_adapter()
  514. adapter.me = _make_user("bot-user-id", "hermes_bot")
  515. return adapter
  516. def _event(self, kind, actor_id="human-1"):
  517. event = MagicMock()
  518. event.id = "evt-1"
  519. event.kind = kind
  520. event.actor_id = actor_id
  521. payload = ReactionPayload(
  522. room_id="room-1", message_event_id="msg-1", emoji="thumbsup",
  523. )
  524. # RealtimeEvent.get() only yields the payload for its own kind.
  525. event.get = MagicMock(side_effect=lambda k: payload if k == kind else None)
  526. return event
  527. async def test_forwards_added_reaction(self, adapter):
  528. handler = AsyncMock()
  529. adapter.set_reaction_handler(handler)
  530. await adapter._handle_realtime_event(self._event("reaction_added"))
  531. handler.assert_called_once()
  532. payload = handler.call_args.args[0]
  533. assert payload["event_name"] == "reaction:added"
  534. assert payload["reaction"] == "thumbsup"
  535. assert payload["channel_id"] == "room-1"
  536. assert payload["message_ts"] == "msg-1"
  537. assert payload["user_id"] == "human-1"
  538. assert payload["item_type"] == "message"
  539. async def test_forwards_removed_reaction(self, adapter):
  540. handler = AsyncMock()
  541. adapter.set_reaction_handler(handler)
  542. await adapter._handle_realtime_event(self._event("reaction_removed"))
  543. assert handler.call_args.args[0]["event_name"] == "reaction:removed"
  544. async def test_ignores_own_lifecycle_reactions(self, adapter):
  545. """👀/✅/❌ are ours — forwarding them would feed the agent its own markers."""
  546. handler = AsyncMock()
  547. adapter.set_reaction_handler(handler)
  548. await adapter._handle_realtime_event(
  549. self._event("reaction_added", actor_id="bot-user-id"),
  550. )
  551. handler.assert_not_called()
  552. async def test_no_handler_registered_is_harmless(self, adapter):
  553. await adapter._handle_realtime_event(self._event("reaction_added"))
  554. async def test_handler_exception_does_not_propagate(self, adapter):
  555. adapter.set_reaction_handler(AsyncMock(side_effect=RuntimeError("hook boom")))
  556. await adapter._handle_realtime_event(self._event("reaction_added"))
  557. # -- chat_type mapping --
  558. class TestChatTypeMapping:
  559. """RoomKind -> the gateway's chat_type vocabulary."""
  560. def test_maps_known_kinds(self):
  561. assert chat_type_for_room_kind(RoomKind.DM) is HermesChatType.DM
  562. assert chat_type_for_room_kind(RoomKind.CHANNEL) is HermesChatType.CHANNEL
  563. def test_unknown_kind_is_group_never_dm(self):
  564. """'dm' drives session isolation — never guess it for an unknown kind."""
  565. assert chat_type_for_room_kind(RoomKind.UNSPECIFIED) is HermesChatType.GROUP
  566. assert chat_type_for_room_kind(None) is HermesChatType.GROUP
  567. def test_values_match_the_gateway_vocabulary(self):
  568. """session.py:161 declares exactly these strings; SessionSource.description
  569. and the PII-redacted context prompt branch on them."""
  570. assert [t.value for t in HermesChatType] == ["dm", "group", "channel", "thread"]
  571. def test_is_a_plain_str_at_call_sites(self):
  572. assert HermesChatType.CHANNEL == "channel"
  573. assert f"{HermesChatType.DM}" == "dm"
  574. async def test_get_chat_info_reports_channel(self):
  575. adapter = _make_adapter()
  576. adapter._room_names["room-1"] = "Team"
  577. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  578. info = await adapter.get_chat_info("room-1")
  579. assert info == {"name": "Team", "type": "channel"}
  580. async def test_get_chat_info_reports_dm(self):
  581. adapter = _make_adapter()
  582. adapter._room_kinds["dm-1"] = RoomKind.DM
  583. assert (await adapter.get_chat_info("dm-1"))["type"] == "dm"
  584. async def test_dispatch_stamps_the_mapped_chat_type(self):
  585. """The value reaching build_source decides how the agent is told where
  586. it is — a raw RoomKind lands in SessionSource.description's else-branch."""
  587. adapter = _make_adapter()
  588. adapter.chatto_config.allow_all_users.value = True
  589. adapter.me = _make_user("bot-user-id", "hermes_bot")
  590. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  591. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  592. adapter.handle_message = AsyncMock()
  593. payload = _make_posted_payload()
  594. payload.fetch_message = AsyncMock(return_value=_make_message(body="hi"))
  595. await adapter._dispatch_message_posted(payload)
  596. event = adapter.handle_message.call_args.args[0]
  597. assert event.source.chat_type == "channel"
  598. # -- Presence --
  599. class TestPresence:
  600. """Presence is a server-side TTL: stop re-announcing and the bot goes offline."""
  601. def _adapter(self):
  602. adapter = _make_adapter()
  603. adapter._chatto_client.update_presence = AsyncMock()
  604. return adapter
  605. async def test_refresh_loop_keeps_reannouncing_online(self):
  606. """The bug: a single announce at connect lapses and never comes back."""
  607. adapter = self._adapter()
  608. adapter._closing = False
  609. with patch.object(ChattoConstants, "PRESENCE_REFRESH_INTERVAL", 0.01):
  610. task = asyncio.create_task(adapter._presence_refresh_loop())
  611. for _ in range(200):
  612. if adapter._chatto_client.update_presence.await_count >= 3:
  613. break
  614. await asyncio.sleep(0.01)
  615. adapter._closing = True
  616. task.cancel()
  617. try:
  618. await task
  619. except asyncio.CancelledError:
  620. pass
  621. assert adapter._chatto_client.update_presence.await_count >= 3
  622. for call in adapter._chatto_client.update_presence.await_args_list:
  623. assert call.kwargs["status"] == PresenceStatus.ONLINE
  624. async def test_refresh_survives_a_failing_call(self):
  625. """One bad tick must not kill the loop and strand the bot offline."""
  626. adapter = self._adapter()
  627. adapter._closing = False
  628. adapter._chatto_client.update_presence = AsyncMock(
  629. side_effect=[RuntimeError("boom"), None, None])
  630. with patch.object(ChattoConstants, "PRESENCE_REFRESH_INTERVAL", 0.01):
  631. task = asyncio.create_task(adapter._presence_refresh_loop())
  632. for _ in range(200):
  633. if adapter._chatto_client.update_presence.await_count >= 3:
  634. break
  635. await asyncio.sleep(0.01)
  636. adapter._closing = True
  637. task.cancel()
  638. try:
  639. await task
  640. except asyncio.CancelledError:
  641. pass
  642. assert adapter._chatto_client.update_presence.await_count >= 3
  643. async def test_announce_online_reports_failure(self):
  644. adapter = self._adapter()
  645. adapter._chatto_client.update_presence = AsyncMock(side_effect=RuntimeError("nope"))
  646. assert await adapter._announce_online() is False
  647. async def test_disconnect_does_not_broadcast_offline(self):
  648. """chattolib raises ValueError on OFFLINE — going offline means stopping."""
  649. adapter = self._adapter()
  650. adapter._chatto_client.close = AsyncMock()
  651. client = adapter._chatto_client # disconnect() drops the reference
  652. await adapter.disconnect()
  653. client.update_presence.assert_not_called()
  654. # -- require_mention --
  655. class TestRequireMention:
  656. """require_mention gates channels only — a DM is already addressed at the bot."""
  657. def _adapter(self):
  658. adapter = _make_adapter()
  659. adapter.chatto_config.allow_all_users.value = True
  660. adapter.chatto_config.require_mention.value = True
  661. adapter.me = _make_user("bot-user-id", "hermes_bot")
  662. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  663. adapter.handle_message = AsyncMock()
  664. return adapter
  665. async def _dispatch(self, adapter, room_id, body):
  666. payload = _make_posted_payload(room_id=room_id)
  667. payload.fetch_message = AsyncMock(
  668. return_value=_make_message(body=body, room_id=room_id))
  669. await adapter._dispatch_message_posted(payload)
  670. async def test_channel_without_mention_is_discarded(self):
  671. adapter = self._adapter()
  672. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  673. await self._dispatch(adapter, "room-1", "hi there")
  674. adapter.handle_message.assert_not_called()
  675. async def test_channel_with_mention_is_answered(self):
  676. adapter = self._adapter()
  677. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  678. await self._dispatch(adapter, "room-1", "@hermes_bot hi there")
  679. adapter.handle_message.assert_called_once()
  680. async def test_dm_is_answered_without_a_mention(self):
  681. """The point of the room_kind check: require_mention must not mute DMs."""
  682. adapter = self._adapter()
  683. adapter._room_kinds["dm-1"] = RoomKind.DM
  684. await self._dispatch(adapter, "dm-1", "hi there")
  685. adapter.handle_message.assert_called_once()
  686. # -- Inbound attachments --
  687. class TestInboundAttachments:
  688. """Messages carrying files must reach the agent, body or not."""
  689. @pytest_asyncio.fixture
  690. def adapter(self):
  691. adapter = _make_adapter()
  692. adapter.chatto_config.allow_all_users.value = True
  693. adapter.me = _make_user("bot-user-id", "hermes_bot")
  694. adapter._room_kinds["room-1"] = RoomKind.DM
  695. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  696. adapter.handle_message = AsyncMock()
  697. adapter._download_attachment_bytes = AsyncMock(return_value=b"\x89PNG\r\n\x1a\nrest")
  698. return adapter
  699. async def test_image_attachment_becomes_media_url(self, adapter):
  700. payload = _make_posted_payload()
  701. adapter._chatto_client.get_room = AsyncMock()
  702. message = _make_message(
  703. body="look at this",
  704. attachments=[_make_attachment("shot.png", "image/png")],
  705. )
  706. payload.fetch_message = AsyncMock(return_value=message)
  707. with patch("adapter.cache_media_bytes", return_value=_cached("/cache/shot.png", "image/png", "image")):
  708. await adapter._dispatch_message_posted(payload)
  709. event = adapter.handle_message.call_args.args[0]
  710. assert event.media_urls == ["/cache/shot.png"]
  711. assert event.media_types == ["image/png"]
  712. assert event.message_type == MessageType.PHOTO
  713. async def test_attachment_only_message_is_not_dropped(self, adapter):
  714. """The empty-body early return is what silently ate file uploads."""
  715. payload = _make_posted_payload()
  716. message = _make_message(
  717. body="", attachments=[_make_attachment("report.pdf", "application/pdf")],
  718. )
  719. payload.fetch_message = AsyncMock(return_value=message)
  720. with patch("adapter.cache_media_bytes", return_value=_cached("/cache/report.pdf", "application/pdf", "document")):
  721. await adapter._dispatch_message_posted(payload)
  722. adapter.handle_message.assert_called_once()
  723. event = adapter.handle_message.call_args.args[0]
  724. assert event.message_type == MessageType.DOCUMENT
  725. assert event.media_urls == ["/cache/report.pdf"]
  726. async def test_empty_message_without_attachments_is_dropped(self, adapter):
  727. payload = _make_posted_payload()
  728. payload.fetch_message = AsyncMock(return_value=_make_message(body=""))
  729. await adapter._dispatch_message_posted(payload)
  730. adapter.handle_message.assert_not_called()
  731. async def test_download_failure_still_delivers_the_text(self, adapter):
  732. adapter._download_attachment_bytes = AsyncMock(side_effect=RuntimeError("404"))
  733. payload = _make_posted_payload()
  734. payload.fetch_message = AsyncMock(return_value=_make_message(
  735. body="see attached", attachments=[_make_attachment("a.png", "image/png")],
  736. ))
  737. await adapter._dispatch_message_posted(payload)
  738. event = adapter.handle_message.call_args.args[0]
  739. assert event.text == "see attached"
  740. assert event.media_urls == []
  741. assert event.message_type == MessageType.TEXT
  742. async def test_attachment_without_asset_url_is_skipped(self, adapter):
  743. """Videos are announced before transcoding finishes."""
  744. payload = _make_posted_payload()
  745. att = _make_attachment("clip.mp4", "video/mp4")
  746. att.asset_url = None
  747. payload.fetch_message = AsyncMock(return_value=_make_message(
  748. body="clip", attachments=[att],
  749. ))
  750. await adapter._dispatch_message_posted(payload)
  751. event = adapter.handle_message.call_args.args[0]
  752. assert event.media_urls == []
  753. adapter._download_attachment_bytes.assert_not_called()
  754. async def test_document_wins_over_image(self, adapter):
  755. """Mixed batches classify as DOCUMENT — that gates context injection."""
  756. assert adapter._message_type_for_media_kinds(["image", "document"]) is MessageType.DOCUMENT
  757. assert adapter._message_type_for_media_kinds(["image"]) is MessageType.PHOTO
  758. assert adapter._message_type_for_media_kinds(["video"]) is MessageType.VIDEO
  759. assert adapter._message_type_for_media_kinds(["audio"]) is MessageType.AUDIO
  760. assert adapter._message_type_for_media_kinds([]) is MessageType.TEXT
  761. async def test_oversized_attachment_is_rejected(self, adapter):
  762. """The gateway media cap must bound what a hostile upload can buffer."""
  763. import httpx
  764. big = get_inbound_media_max_bytes() + 1
  765. transport = httpx.MockTransport(lambda request: httpx.Response(
  766. 200, headers={"content-length": str(big)}, content=b"x",
  767. ))
  768. real_adapter = _make_adapter()
  769. real_client_cls = httpx.AsyncClient
  770. with patch("httpx.AsyncClient", lambda **kw: real_client_cls(transport=transport)):
  771. with pytest.raises(ValueError):
  772. await real_adapter._download_attachment_bytes("https://chat.example.com/a.png")
  773. # NOTE: there are deliberately no tests for get_user(), set_presence() or
  774. # set_custom_status() on the adapter. Those are not adapter responsibilities —
  775. # callers use the chattolib client directly, which exposes them (client.get_user,
  776. # client.update_presence, client.update_custom_status). The adapter only touches
  777. # presence in connect()/disconnect().
  778. # -- Room operations --
  779. class TestRoomOperations:
  780. """Test room creation and DM initiation."""
  781. @pytest_asyncio.fixture
  782. def adapter(self):
  783. _clear_chatto_env()
  784. cfg = _make_config()
  785. adapter = ChattoAdapter(cfg)
  786. adapter._chatto_client = MagicMock()
  787. # AsyncMock, not MagicMock: the adapter awaits these, and awaiting a
  788. # plain MagicMock raises TypeError, which create_room()/start_dm()
  789. # swallow into a None return.
  790. adapter._chatto_client.create_room = AsyncMock()
  791. adapter._chatto_client.start_dm = AsyncMock()
  792. adapter._token = "test-token"
  793. adapter._room_names = {}
  794. adapter._room_kinds = {}
  795. return adapter
  796. async def test_create_room(self, adapter):
  797. adapter._chatto_client.create_room.return_value = _make_room(
  798. "room-123", "Test Room", RoomKind.CHANNEL,
  799. )
  800. result = await adapter.create_room("Test Room", "A test room")
  801. assert result == "room-123"
  802. adapter._chatto_client.create_room.assert_called_once()
  803. assert adapter._room_names["room-123"] == "Test Room"
  804. async def test_start_dm(self, adapter):
  805. adapter._chatto_client.start_dm.return_value = _make_room(
  806. "dm-123", "DM with user", RoomKind.DM,
  807. )
  808. result = await adapter.start_dm("user-123")
  809. assert result == "dm-123"
  810. adapter._chatto_client.start_dm.assert_called_once()
  811. assert adapter._room_kinds["dm-123"] == RoomKind.DM
  812. # -- Constants --
  813. class TestConstants:
  814. """Test that constants are properly defined."""
  815. def test_max_message_length(self):
  816. assert _MAX_MESSAGE_LENGTH == 10000
  817. def test_seen_cap(self):
  818. assert _SEEN_CAP == 500