test_adapter.py 34 KB

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