test_adapter.py 57 KB

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