test_adapter.py 48 KB

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