test_adapter.py 39 KB

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