test_adapter.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  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. from datetime import UTC, datetime, timedelta
  17. from unittest.mock import AsyncMock, MagicMock, patch
  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. # Importing ``adapter`` puts the vendored dependencies on sys.path as a side
  28. # effect, but import sorting may legally move that import after the chattolib
  29. # and gateway ones — so bootstrap the vendor paths explicitly instead.
  30. from vendor_path import setup_vendor_path
  31. setup_vendor_path()
  32. from chattolib.realtime_types import ReactionPayload
  33. from chattolib.types import (
  34. Asset,
  35. AssetUpload,
  36. AssetUrl,
  37. DirectoryMember,
  38. Message,
  39. MessageAttachment,
  40. PresenceStatus,
  41. Room,
  42. RoomKind,
  43. RoomViewerState,
  44. RoomWithViewerState,
  45. User,
  46. )
  47. from gateway.config import PlatformConfig
  48. from gateway.platforms.base import (
  49. BasePlatformAdapter,
  50. CachedMedia,
  51. MessageType,
  52. ProcessingOutcome,
  53. SendResult,
  54. get_inbound_media_max_bytes,
  55. )
  56. from adapter import (
  57. ChattoAdapter,
  58. HermesChatType,
  59. _capabilities,
  60. chat_type_for_room_kind,
  61. register,
  62. )
  63. from adapter import (
  64. hermes_check_fn as check_requirements,
  65. )
  66. from adapter import (
  67. hermes_validate_config as validate_config,
  68. )
  69. from platform_config import ChattoConstants
  70. _EMOJI_TO_SHORTCODE = ChattoConstants.EMOJI_TO_SHORTCODE
  71. _MAX_MESSAGE_LENGTH = ChattoConstants.MAX_MESSAGE_LENGTH
  72. _SEEN_CAP = ChattoConstants.SEEN_CAP
  73. # -- Helpers --
  74. class _MockPluginContext:
  75. """Minimal mock for the plugin registration context."""
  76. def __init__(self):
  77. self.registered_names = []
  78. self.registered_kwargs = None
  79. def register_platform(self, **kwargs):
  80. from gateway.platform_registry import PlatformEntry, platform_registry
  81. entry = PlatformEntry(
  82. name=kwargs["name"],
  83. label=kwargs.get("label", kwargs["name"]),
  84. adapter_factory=kwargs.get("adapter_factory"),
  85. check_fn=kwargs.get("check_fn"),
  86. validate_config=kwargs.get("validate_config"),
  87. is_connected=kwargs.get("is_connected"),
  88. required_env=kwargs.get("required_env", []),
  89. source="plugin",
  90. )
  91. platform_registry.register(entry)
  92. self.registered_names.append(kwargs["name"])
  93. self.registered_kwargs = kwargs
  94. def _ensure_chatto_registered():
  95. """Register the platform so Platform(PLATFORM_NAME) resolves."""
  96. from gateway.platform_registry import platform_registry
  97. if not platform_registry.is_registered(ChattoConstants.PLATFORM_NAME):
  98. ctx = _MockPluginContext()
  99. register(ctx)
  100. _CHATTO_ENV_KEYS = [
  101. "CHATTO_BASE_URL",
  102. "CHATTO_LOGIN",
  103. "CHATTO_PASSWORD",
  104. "CHATTO_TOKEN",
  105. "CHATTO_HOME_CHANNEL",
  106. "CHATTO_REQUIRE_MENTION",
  107. "CHATTO_ALLOWED_USERS",
  108. "CHATTO_ALLOW_ALL_USERS",
  109. "CHATTO_AUTO_THREAD",
  110. "CHATTO_REACTIONS",
  111. "CHATTO_RESPOND_ROOMS",
  112. ]
  113. def _clear_chatto_env(monkeypatch=None):
  114. """Remove all CHATTO_* env vars so tests start from a clean slate."""
  115. for key in _CHATTO_ENV_KEYS:
  116. if monkeypatch is not None:
  117. monkeypatch.delenv(key, raising=False)
  118. else:
  119. os.environ.pop(key, None)
  120. def _make_config(**extra_overrides):
  121. """Create a minimal PlatformConfig for testing."""
  122. _ensure_chatto_registered()
  123. extra = {"base_url": "https://chat.example.com"}
  124. extra.update(extra_overrides)
  125. return PlatformConfig(enabled=True, extra=extra)
  126. def _make_room(room_id, name, kind):
  127. """Build a real chattolib Room, as the client would return."""
  128. return Room(
  129. id=room_id,
  130. name=name,
  131. kind=kind,
  132. description="",
  133. archived=False,
  134. group_id="",
  135. universal=kind != RoomKind.DM,
  136. )
  137. def _make_user(user_id, login):
  138. """Build a real chattolib User, as the member directory would return."""
  139. return User(id=user_id, login=login, display_name=login.replace("_", " ").title())
  140. def _make_attachment(filename, content_type, url="https://cdn.example.com/a"):
  141. """Build a real MessageAttachment carrying a (pre-signed) asset URL."""
  142. return MessageAttachment(
  143. id="asset-" + filename,
  144. filename=filename,
  145. content_type=content_type,
  146. asset_url=AssetUrl(url=url),
  147. )
  148. def _make_message(
  149. body="hi",
  150. attachments=None,
  151. message_id="msg-1",
  152. room_id="room-1",
  153. created_at=None,
  154. updated_at=None,
  155. ):
  156. """Build a real chattolib Message, as fetch_message() would return."""
  157. return Message(
  158. id=message_id,
  159. room_id=room_id,
  160. created_at=created_at,
  161. actor_id="user-1",
  162. body=body,
  163. attachments=list(attachments or []),
  164. updated_at=updated_at,
  165. )
  166. def _make_posted_payload(room_id="room-1", message_event_id="msg-1"):
  167. """A message_posted payload whose fetch_message() the caller stubs."""
  168. payload = MagicMock()
  169. payload.room_id = room_id
  170. payload.message_event_id = message_event_id
  171. payload.thread_root_event_id = None
  172. return payload
  173. def _cached(path, media_type, kind):
  174. """The CachedMedia that cache_media_bytes() would return for an attachment."""
  175. return CachedMedia(path=path, media_type=media_type, kind=kind, display_name="f")
  176. def _make_adapter(**extra_overrides):
  177. """Create a ChattoAdapter with mocked config."""
  178. _clear_chatto_env()
  179. cfg = _make_config(**extra_overrides)
  180. adapter = ChattoAdapter(cfg)
  181. adapter._chatto_client = MagicMock()
  182. return adapter
  183. # -- Emoji shortcode conversion --
  184. class TestEmojiShortcode:
  185. """Test emoji to shortcode mapping."""
  186. def test_emoji_to_shortcode_exists(self):
  187. assert isinstance(_EMOJI_TO_SHORTCODE, dict)
  188. assert len(_EMOJI_TO_SHORTCODE) > 0
  189. def test_emoji_to_shortcode_common_emojis(self):
  190. assert _EMOJI_TO_SHORTCODE.get("👍") == "thumbsup"
  191. assert _EMOJI_TO_SHORTCODE.get("👎") == "thumbsdown"
  192. assert _EMOJI_TO_SHORTCODE.get("❤️") == "heart"
  193. assert _EMOJI_TO_SHORTCODE.get("❤") == "heart"
  194. assert _EMOJI_TO_SHORTCODE.get("✅") == "white_check_mark"
  195. assert _EMOJI_TO_SHORTCODE.get("❌") == "x"
  196. # Sent when a message addresses someone else — without the mapping the
  197. # raw emoji would go out as a shortcode and the server would reject it.
  198. assert _EMOJI_TO_SHORTCODE.get("🫥") == "dotted_line_face"
  199. # -- Adapter instantiation and properties --
  200. class TestAdapterInstantiation:
  201. """Test ChattoAdapter creation and basic properties."""
  202. def test_adapter_creation(self):
  203. cfg = _make_config()
  204. adapter = ChattoAdapter(cfg)
  205. assert adapter is not None
  206. # Platform members created dynamically from a plugin name carry the
  207. # name upper-cased; the registered identity is the value.
  208. assert adapter.platform.value == ChattoConstants.PLATFORM_NAME
  209. def test_adapter_max_message_length(self):
  210. """The framework chunks via max_message_length_for_chat(), which reads
  211. the adapter-scalar MAX_MESSAGE_LENGTH and silently falls back to 4096
  212. when it is missing."""
  213. cfg = _make_config()
  214. adapter = ChattoAdapter(cfg)
  215. assert adapter.MAX_MESSAGE_LENGTH == _MAX_MESSAGE_LENGTH
  216. assert adapter.max_message_length_for_chat("room-1") == _MAX_MESSAGE_LENGTH
  217. def test_adapter_splits_long_messages(self):
  218. cfg = _make_config()
  219. adapter = ChattoAdapter(cfg)
  220. assert adapter.splits_long_messages is True
  221. def test_adapter_threads_enabled_by_default(self):
  222. """There is no capability flag for threads — Chatto threading is driven
  223. by the auto_thread setting, which defaults to on."""
  224. cfg = _make_config()
  225. adapter = ChattoAdapter(cfg)
  226. assert adapter.chatto_config.auto_thread.value is True
  227. # -- Registration and requirements --
  228. class TestRegistration:
  229. """Test plugin registration."""
  230. def test_register_called(self):
  231. ctx = _MockPluginContext()
  232. register(ctx)
  233. assert ChattoConstants.PLATFORM_NAME in ctx.registered_names
  234. assert ctx.registered_kwargs["name"] == ChattoConstants.PLATFORM_NAME
  235. assert ctx.registered_kwargs["label"] == ChattoConstants.PLATFORM_LABEL
  236. assert ctx.registered_kwargs["max_message_length"] == _MAX_MESSAGE_LENGTH
  237. def test_platform_hint_advertises_media_sending(self):
  238. """This hint is the only thing telling the model the channel can carry
  239. files — without it the agent has no idea it can deliver an image."""
  240. ctx = _MockPluginContext()
  241. register(ctx)
  242. assert "MEDIA:/absolute/path/to/file" in ctx.registered_kwargs["platform_hint"]
  243. def test_platform_hint_rules_out_markdown_for_local_files(self):
  244. """gateway's extract_images only matches https?:// — markdown pointing at
  245. a local file is never extracted and lands in the chat as literal text."""
  246. ctx = _MockPluginContext()
  247. register(ctx)
  248. hint = ctx.registered_kwargs["platform_hint"]
  249. assert "Do NOT use markdown image syntax for local files" in hint
  250. def test_startup_logs_the_capabilities(self, caplog):
  251. with caplog.at_level("INFO"):
  252. register(_MockPluginContext())
  253. logged = "\n".join(caplog.messages)
  254. assert "images" in logged
  255. assert "reactions" in logged
  256. def test_capabilities_skips_methods_we_do_not_override(self):
  257. """An inherited base fallback is not a capability — claiming it would
  258. promise the user something the adapter cannot actually do."""
  259. assert "video" in _capabilities()
  260. with patch.object(ChattoAdapter, "send_video", BasePlatformAdapter.send_video):
  261. assert "video" not in _capabilities()
  262. def test_check_requirements(self):
  263. assert check_requirements() is True
  264. def test_check_requirements_missing(self):
  265. with patch("builtins.__import__", side_effect=ImportError("no chattolib")):
  266. assert check_requirements() is False
  267. def test_validate_config(self):
  268. _clear_chatto_env()
  269. os.environ["CHATTO_BASE_URL"] = "https://chat.test"
  270. os.environ["CHATTO_LOGIN"] = "user"
  271. os.environ["CHATTO_PASSWORD"] = "pass"
  272. cfg = PlatformConfig(enabled=True, extra={"base_url": "https://chat.test"})
  273. assert validate_config(cfg) is True
  274. _clear_chatto_env()
  275. # -- Send functionality --
  276. class TestSend:
  277. """Test message sending functionality."""
  278. @pytest_asyncio.fixture
  279. def adapter(self):
  280. _clear_chatto_env()
  281. cfg = _make_config()
  282. adapter = ChattoAdapter(cfg)
  283. adapter._chatto_client = MagicMock()
  284. adapter._chatto_client.post_message = AsyncMock()
  285. return adapter
  286. async def test_send_calls_post_message(self, adapter):
  287. mock_msg = MagicMock()
  288. mock_msg.id = "msg-123"
  289. adapter._chatto_client.post_message.return_value = mock_msg
  290. result = await adapter.send("room-1", "Hello world")
  291. assert result.success is True
  292. assert result.message_id == "msg-123"
  293. adapter._chatto_client.post_message.assert_called_once()
  294. async def test_send_with_thread(self, adapter):
  295. mock_msg = MagicMock()
  296. mock_msg.id = "msg-456"
  297. adapter._chatto_client.post_message.return_value = mock_msg
  298. result = await adapter.send("room-1", "Hello", reply_to="thread-123")
  299. assert result.success is True
  300. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  301. assert call_kwargs["thread_root_event_id"] == "thread-123"
  302. async def test_send_raw_response_stays_dict_shaped(self, adapter):
  303. # The cron scheduler calls .get() on SendResult.raw_response when a job
  304. # targets a thread; a chattolib Message there crashes delivery
  305. # bookkeeping after the send and duplicates the message standalone.
  306. adapter._chatto_client.post_message.return_value = _make_message(
  307. body="Hello world", message_id="msg-789"
  308. )
  309. result = await adapter.send("room-1", "Hello world")
  310. assert result.success is True
  311. assert not result.raw_response or isinstance(result.raw_response, dict)
  312. # -- Reactions --
  313. class TestReactions:
  314. """Test reaction functionality."""
  315. @pytest_asyncio.fixture
  316. def adapter(self):
  317. _clear_chatto_env()
  318. cfg = _make_config()
  319. adapter = ChattoAdapter(cfg)
  320. adapter._chatto_client = MagicMock()
  321. adapter._chatto_client.add_reaction = AsyncMock()
  322. adapter._chatto_client.remove_reaction = AsyncMock()
  323. return adapter
  324. async def test_send_reaction(self, adapter):
  325. await adapter.add_reaction("room-1", "msg-1", "👍")
  326. adapter._chatto_client.add_reaction.assert_called_once()
  327. async def test_remove_reaction(self, adapter):
  328. await adapter.remove_reaction("room-1", "msg-1", "👍")
  329. adapter._chatto_client.remove_reaction.assert_called_once()
  330. async def test_on_processing_start_adds_eyes_reaction(self, adapter):
  331. """on_processing_start should call add_reaction with 👀."""
  332. event = MagicMock()
  333. event.message_id = "msg-1"
  334. event.source.chat_id = "room-1"
  335. await adapter.on_processing_start(event)
  336. adapter._chatto_client.add_reaction.assert_called_once()
  337. call_kwargs = adapter._chatto_client.add_reaction.call_args.kwargs
  338. assert call_kwargs["message_event_id"] == "msg-1"
  339. assert call_kwargs["room_id"] == "room-1"
  340. assert call_kwargs["emoji"] == "eyes"
  341. async def test_on_processing_start_empty_message_id(self, adapter):
  342. """on_processing_start should skip reaction when message_id is empty."""
  343. event = MagicMock()
  344. event.message_id = None
  345. event.source.chat_id = "room-1"
  346. await adapter.on_processing_start(event)
  347. adapter._chatto_client.add_reaction.assert_not_called()
  348. async def test_on_processing_start_reactions_disabled(self, adapter):
  349. """on_processing_start should skip when reactions config is False."""
  350. adapter.chatto_config.reactions.value = False
  351. event = MagicMock()
  352. event.message_id = "msg-1"
  353. event.source.chat_id = "room-1"
  354. await adapter.on_processing_start(event)
  355. adapter._chatto_client.add_reaction.assert_not_called()
  356. # -- Edit and Delete Messages --
  357. class TestMessageEditing:
  358. """Test message editing and deletion."""
  359. @pytest_asyncio.fixture
  360. def adapter(self):
  361. _clear_chatto_env()
  362. cfg = _make_config()
  363. adapter = ChattoAdapter(cfg)
  364. adapter._chatto_client = MagicMock()
  365. adapter._chatto_client.update_message = AsyncMock()
  366. adapter._chatto_client.delete_message = AsyncMock(return_value=True)
  367. adapter._token = "test-token"
  368. return adapter
  369. async def test_edit_message(self, adapter):
  370. result = await adapter.edit_message("room-1", "msg-1", "New content")
  371. assert result.success is True
  372. adapter._chatto_client.update_message.assert_called_once()
  373. call_kwargs = adapter._chatto_client.update_message.call_args.kwargs
  374. assert call_kwargs["room_id"] == "room-1"
  375. assert call_kwargs["event_id"] == "msg-1"
  376. assert call_kwargs["body"] == "New content"
  377. async def test_edit_message_marks_own_edit_seen(self, adapter):
  378. """The edit echoes back as message_edited — it must not look inbound."""
  379. mock_msg = MagicMock()
  380. mock_msg.id = "msg-1"
  381. adapter._chatto_client.update_message.return_value = mock_msg
  382. await adapter.edit_message("room-1", "msg-1", "New content")
  383. assert adapter._is_seen("msg-1") is True
  384. async def test_edit_message_too_long_refuses(self, adapter):
  385. """Overlong content must fall back to send() (which splits), not be
  386. silently truncated into a lossy edit."""
  387. result = await adapter.edit_message(
  388. "room-1",
  389. "msg-1",
  390. "x" * (_MAX_MESSAGE_LENGTH + 1),
  391. )
  392. assert result.success is False
  393. adapter._chatto_client.update_message.assert_not_called()
  394. async def test_edit_message_empty_content(self, adapter):
  395. result = await adapter.edit_message("room-1", "msg-1", "")
  396. assert result.success is False
  397. adapter._chatto_client.update_message.assert_not_called()
  398. async def test_edit_message_error_is_retryable(self, adapter):
  399. from chattolib.exceptions import ChattoError
  400. adapter._chatto_client.update_message.side_effect = ChattoError("boom")
  401. result = await adapter.edit_message("room-1", "msg-1", "New content")
  402. assert result.success is False
  403. assert result.retryable is True
  404. async def test_delete_message(self, adapter):
  405. result = await adapter.delete_message("room-1", "msg-1")
  406. assert result is True
  407. adapter._chatto_client.delete_message.assert_called_once()
  408. call_kwargs = adapter._chatto_client.delete_message.call_args.kwargs
  409. assert call_kwargs["room_id"] == "room-1"
  410. assert call_kwargs["event_id"] == "msg-1"
  411. async def test_delete_message_missing_ids(self, adapter):
  412. assert await adapter.delete_message("", "msg-1") is False
  413. assert await adapter.delete_message("room-1", "") is False
  414. adapter._chatto_client.delete_message.assert_not_called()
  415. async def test_delete_message_error_returns_false(self, adapter):
  416. from chattolib.exceptions import ChattoError
  417. adapter._chatto_client.delete_message.side_effect = ChattoError("nope")
  418. assert await adapter.delete_message("room-1", "msg-1") is False
  419. # -- Outgoing text formatting --
  420. class TestFormatMessage:
  421. """format_message() only fixes what renders wrong in Chatto."""
  422. def test_normalises_crlf(self):
  423. adapter = _make_adapter()
  424. assert adapter.format_message("a\r\nb\rc") == "a\nb\nc"
  425. def test_collapses_excess_blank_lines(self):
  426. adapter = _make_adapter()
  427. assert adapter.format_message("a\n\n\n\n\n\nb") == "a\n\n\nb"
  428. def test_leaves_markdown_untouched(self):
  429. adapter = _make_adapter()
  430. text = "**bold** `code`\n\n```py\nx = 1\n```\n- item"
  431. assert adapter.format_message(text) == text
  432. def test_empty_content(self):
  433. adapter = _make_adapter()
  434. assert adapter.format_message("") == ""
  435. # -- Handoff threads --
  436. class TestHandoffThread:
  437. """create_handoff_thread() anchors a handoff on a seed message."""
  438. @pytest_asyncio.fixture
  439. def adapter(self):
  440. adapter = _make_adapter()
  441. adapter._chatto_client.post_message = AsyncMock()
  442. adapter._chatto_client.follow_thread = AsyncMock()
  443. return adapter
  444. async def test_returns_seed_message_id(self, adapter):
  445. mock_msg = MagicMock()
  446. mock_msg.id = "seed-1"
  447. adapter._chatto_client.post_message.return_value = mock_msg
  448. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  449. result = await adapter.create_handoff_thread("room-1", "Refactor run")
  450. assert result == "seed-1"
  451. assert (
  452. adapter._chatto_client.post_message.call_args.kwargs["room_id"] == "room-1"
  453. )
  454. adapter._chatto_client.follow_thread.assert_called_once_with("room-1", "seed-1")
  455. # Our own seed must not come back in as inbound traffic.
  456. assert adapter._is_seen("seed-1") is True
  457. async def test_dm_has_no_threads(self, adapter):
  458. adapter._room_kinds["dm-1"] = RoomKind.DM
  459. assert await adapter.create_handoff_thread("dm-1", "x") is None
  460. adapter._chatto_client.post_message.assert_not_called()
  461. async def test_seed_post_failure(self, adapter):
  462. adapter._chatto_client.post_message.side_effect = RuntimeError("down")
  463. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  464. assert await adapter.create_handoff_thread("room-1", "x") is None
  465. # -- Native file / video / audio delivery --
  466. class TestUploadAsset:
  467. """Drives the real _upload_asset against real chattolib result types.
  468. The send_* tests stub _upload_asset out, so a wrong field name on the
  469. chattolib response was invisible to them until it hit a live server.
  470. """
  471. @pytest_asyncio.fixture
  472. def adapter(self, tmp_path):
  473. adapter = _make_adapter()
  474. self.path = tmp_path / "horse.jpg"
  475. self.path.write_bytes(b"\xff\xd8\xff" + b"x" * 100)
  476. upload = AssetUpload(upload_id="up-1", room_id="room-1")
  477. adapter._chatto_client.create_upload = AsyncMock(return_value=upload)
  478. adapter._chatto_client.upload_chunk = AsyncMock(return_value=upload)
  479. adapter._chatto_client.complete_upload = AsyncMock(
  480. return_value=(
  481. upload,
  482. Asset(
  483. id="asset-9",
  484. filename="horse.jpg",
  485. content_type="image/jpeg",
  486. size=103,
  487. ),
  488. )
  489. )
  490. return adapter
  491. async def test_returns_the_asset_id(self, adapter):
  492. assert await adapter._upload_asset("room-1", str(self.path)) == "asset-9"
  493. async def test_chunks_go_to_the_upload_id_from_create_upload(self, adapter):
  494. """AssetUpload calls it upload_id, not id — reading the wrong field made
  495. every upload fail with 'CreateUpload returned no upload ID'."""
  496. await adapter._upload_asset("room-1", str(self.path))
  497. assert (
  498. adapter._chatto_client.upload_chunk.await_args.kwargs["upload_id"] == "up-1"
  499. )
  500. async def test_missing_upload_id_is_reported(self, adapter):
  501. adapter._chatto_client.create_upload = AsyncMock(
  502. return_value=AssetUpload(upload_id="", room_id="room-1")
  503. )
  504. assert await adapter._upload_asset("room-1", str(self.path)) is None
  505. class TestNativeSends:
  506. """send_document/_video/_voice upload instead of apologising in text."""
  507. @pytest_asyncio.fixture
  508. def adapter(self):
  509. adapter = _make_adapter()
  510. adapter._chatto_client.post_message = AsyncMock()
  511. adapter._upload_asset = AsyncMock(return_value="asset-1")
  512. adapter.validate_media_delivery_path = MagicMock(side_effect=lambda p: p)
  513. mock_msg = MagicMock()
  514. mock_msg.id = "msg-1"
  515. adapter._chatto_client.post_message.return_value = mock_msg
  516. return adapter
  517. @pytest.mark.parametrize(
  518. "method,arg_name",
  519. [
  520. ("send_document", "file_path"),
  521. ("send_video", "video_path"),
  522. ("send_voice", "audio_path"),
  523. ("send_image_file", "image_path"),
  524. ],
  525. )
  526. async def test_uploads_and_attaches(self, adapter, method, arg_name):
  527. result = await getattr(adapter, method)(
  528. "room-1",
  529. **{arg_name: "/tmp/thing.bin"},
  530. caption="here you go",
  531. )
  532. assert result.success is True
  533. adapter._upload_asset.assert_called_once_with("room-1", "/tmp/thing.bin")
  534. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  535. assert call_kwargs["attachment_asset_ids"] == ["asset-1"]
  536. assert call_kwargs["body"] == "here you go"
  537. async def test_unsafe_path_falls_back_to_notice(self, adapter):
  538. adapter.validate_media_delivery_path = MagicMock(return_value=None)
  539. adapter.send = AsyncMock(return_value=SendResult(success=True))
  540. await adapter.send_document("room-1", "/etc/shadow")
  541. adapter._upload_asset.assert_not_called()
  542. # Never echo the host path into chat.
  543. sent_text = adapter.send.call_args.args[1]
  544. assert "/etc/shadow" not in sent_text
  545. async def test_upload_failure_falls_back_to_notice(self, adapter):
  546. adapter._upload_asset = AsyncMock(return_value=None)
  547. adapter.send = AsyncMock(return_value=SendResult(success=True))
  548. await adapter.send_video("room-1", "/tmp/clip.mp4", caption="a clip")
  549. sent_text = adapter.send.call_args.args[1]
  550. assert sent_text.startswith("a clip\n")
  551. assert "/tmp/clip.mp4" not in sent_text
  552. # -- Batched image delivery --
  553. class TestSendMultipleImages:
  554. """A batch of images belongs in ONE Chatto message."""
  555. @pytest_asyncio.fixture
  556. def adapter(self):
  557. adapter = _make_adapter()
  558. adapter._chatto_client.post_message = AsyncMock()
  559. mock_msg = MagicMock()
  560. mock_msg.id = "msg-1"
  561. adapter._chatto_client.post_message.return_value = mock_msg
  562. adapter._upload_asset = AsyncMock(side_effect=["asset-1", "asset-2"])
  563. adapter.validate_media_delivery_path = MagicMock(side_effect=lambda p: p)
  564. return adapter
  565. async def test_bundles_into_single_message(self, adapter):
  566. await adapter.send_multiple_images(
  567. "room-1",
  568. [("/tmp/a.png", "first"), ("/tmp/b.png", "second")],
  569. )
  570. adapter._chatto_client.post_message.assert_called_once()
  571. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  572. assert call_kwargs["attachment_asset_ids"] == ["asset-1", "asset-2"]
  573. assert call_kwargs["body"] == "first\nsecond"
  574. async def test_single_image_uses_base_path(self, adapter):
  575. """One image is not a batch — leave it to the base implementation.
  576. Also pins the send_image_file signature: the base class calls it with
  577. ``image_path=`` as a keyword, so a renamed parameter degrades every
  578. native image send to a text notice.
  579. """
  580. adapter.send_image_file = AsyncMock(return_value=SendResult(success=True))
  581. await adapter.send_multiple_images("room-1", [("file:///tmp/a.png", "only")])
  582. adapter._upload_asset.assert_not_called()
  583. adapter.send_image_file.assert_called_once()
  584. assert adapter.send_image_file.call_args.kwargs["image_path"] == "/tmp/a.png"
  585. async def test_partial_upload_failure_still_sends_the_rest(self, adapter):
  586. adapter._upload_asset = AsyncMock(side_effect=["asset-1", None])
  587. await adapter.send_multiple_images(
  588. "room-1",
  589. [("/tmp/a.png", "first"), ("/tmp/b.png", "second")],
  590. )
  591. call_kwargs = adapter._chatto_client.post_message.call_args.kwargs
  592. assert call_kwargs["attachment_asset_ids"] == ["asset-1"]
  593. async def test_file_uri_is_unquoted(self, adapter):
  594. await adapter.send_multiple_images(
  595. "room-1",
  596. [("file:///tmp/a%20b.png", ""), ("/tmp/c.png", "")],
  597. )
  598. first_path = adapter._upload_asset.call_args_list[0].args[1]
  599. assert first_path == "/tmp/a b.png"
  600. # -- Reaction event forwarding --
  601. class TestReactionForwarding:
  602. """Human reactions reach the gateway's reaction hook surface."""
  603. @pytest_asyncio.fixture
  604. def adapter(self):
  605. adapter = _make_adapter()
  606. adapter.me = _make_user("bot-user-id", "hermes_bot")
  607. return adapter
  608. def _event(self, kind, actor_id="human-1"):
  609. event = MagicMock()
  610. event.id = "evt-1"
  611. event.kind = kind
  612. event.actor_id = actor_id
  613. payload = ReactionPayload(
  614. room_id="room-1",
  615. message_event_id="msg-1",
  616. emoji="thumbsup",
  617. )
  618. # RealtimeEvent.get() only yields the payload for its own kind.
  619. event.get = MagicMock(side_effect=lambda k: payload if k == kind else None)
  620. return event
  621. async def test_forwards_added_reaction(self, adapter):
  622. handler = AsyncMock()
  623. adapter.set_reaction_handler(handler)
  624. await adapter._handle_realtime_event(self._event("reaction_added"))
  625. handler.assert_called_once()
  626. payload = handler.call_args.args[0]
  627. assert payload["event_name"] == "reaction:added"
  628. assert payload["reaction"] == "thumbsup"
  629. assert payload["channel_id"] == "room-1"
  630. assert payload["message_ts"] == "msg-1"
  631. assert payload["user_id"] == "human-1"
  632. assert payload["item_type"] == "message"
  633. async def test_forwards_removed_reaction(self, adapter):
  634. handler = AsyncMock()
  635. adapter.set_reaction_handler(handler)
  636. await adapter._handle_realtime_event(self._event("reaction_removed"))
  637. assert handler.call_args.args[0]["event_name"] == "reaction:removed"
  638. async def test_ignores_own_lifecycle_reactions(self, adapter):
  639. """👀/✅/❌ are ours — forwarding them would feed the agent its own markers."""
  640. handler = AsyncMock()
  641. adapter.set_reaction_handler(handler)
  642. await adapter._handle_realtime_event(
  643. self._event("reaction_added", actor_id="bot-user-id"),
  644. )
  645. handler.assert_not_called()
  646. async def test_no_handler_registered_is_harmless(self, adapter):
  647. await adapter._handle_realtime_event(self._event("reaction_added"))
  648. async def test_handler_exception_does_not_propagate(self, adapter):
  649. adapter.set_reaction_handler(AsyncMock(side_effect=RuntimeError("hook boom")))
  650. await adapter._handle_realtime_event(self._event("reaction_added"))
  651. # -- chat_type mapping --
  652. class TestChatTypeMapping:
  653. """RoomKind -> the gateway's chat_type vocabulary."""
  654. def test_maps_known_kinds(self):
  655. assert chat_type_for_room_kind(RoomKind.DM) is HermesChatType.DM
  656. assert chat_type_for_room_kind(RoomKind.CHANNEL) is HermesChatType.CHANNEL
  657. def test_unknown_kind_is_group_never_dm(self):
  658. """'dm' drives session isolation — never guess it for an unknown kind."""
  659. assert chat_type_for_room_kind(RoomKind.UNSPECIFIED) is HermesChatType.GROUP
  660. assert chat_type_for_room_kind(None) is HermesChatType.GROUP
  661. def test_values_match_the_gateway_vocabulary(self):
  662. """session.py:161 declares exactly these strings; SessionSource.description
  663. and the PII-redacted context prompt branch on them."""
  664. assert [t.value for t in HermesChatType] == ["dm", "group", "channel", "thread"]
  665. def test_is_a_plain_str_at_call_sites(self):
  666. assert HermesChatType.CHANNEL == "channel"
  667. assert f"{HermesChatType.DM}" == "dm"
  668. async def test_get_chat_info_reports_channel(self):
  669. adapter = _make_adapter()
  670. adapter._room_names["room-1"] = "Team"
  671. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  672. info = await adapter.get_chat_info("room-1")
  673. assert info == {"name": "Team", "type": "channel"}
  674. async def test_get_chat_info_reports_dm(self):
  675. adapter = _make_adapter()
  676. adapter._room_kinds["dm-1"] = RoomKind.DM
  677. assert (await adapter.get_chat_info("dm-1"))["type"] == "dm"
  678. async def test_dispatch_stamps_the_mapped_chat_type(self):
  679. """The value reaching build_source decides how the agent is told where
  680. it is — a raw RoomKind lands in SessionSource.description's else-branch."""
  681. adapter = _make_adapter()
  682. adapter.chatto_config.allow_all_users.value = True
  683. adapter.me = _make_user("bot-user-id", "hermes_bot")
  684. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  685. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  686. adapter.handle_message = AsyncMock()
  687. payload = _make_posted_payload()
  688. payload.fetch_message = AsyncMock(return_value=_make_message(body="hi"))
  689. await adapter._dispatch_message_posted(payload)
  690. event = adapter.handle_message.call_args.args[0]
  691. assert event.source.chat_type == "channel"
  692. # -- Presence --
  693. class TestPresence:
  694. """Presence is a server-side TTL: stop re-announcing and the bot goes offline."""
  695. def _adapter(self):
  696. adapter = _make_adapter()
  697. adapter._chatto_client.update_presence = AsyncMock()
  698. return adapter
  699. async def test_refresh_loop_keeps_reannouncing_online(self):
  700. """The bug: a single announce at connect lapses and never comes back."""
  701. adapter = self._adapter()
  702. adapter._closing = False
  703. with patch.object(ChattoConstants, "PRESENCE_REFRESH_INTERVAL", 0.01):
  704. task = asyncio.create_task(adapter._presence_refresh_loop())
  705. for _ in range(200):
  706. if adapter._chatto_client.update_presence.await_count >= 3:
  707. break
  708. await asyncio.sleep(0.01)
  709. adapter._closing = True
  710. task.cancel()
  711. try:
  712. await task
  713. except asyncio.CancelledError:
  714. pass
  715. assert adapter._chatto_client.update_presence.await_count >= 3
  716. for call in adapter._chatto_client.update_presence.await_args_list:
  717. assert call.kwargs["status"] == PresenceStatus.ONLINE
  718. async def test_refresh_survives_a_failing_call(self):
  719. """One bad tick must not kill the loop and strand the bot offline."""
  720. adapter = self._adapter()
  721. adapter._closing = False
  722. adapter._chatto_client.update_presence = AsyncMock(
  723. side_effect=[RuntimeError("boom"), None, None]
  724. )
  725. with patch.object(ChattoConstants, "PRESENCE_REFRESH_INTERVAL", 0.01):
  726. task = asyncio.create_task(adapter._presence_refresh_loop())
  727. for _ in range(200):
  728. if adapter._chatto_client.update_presence.await_count >= 3:
  729. break
  730. await asyncio.sleep(0.01)
  731. adapter._closing = True
  732. task.cancel()
  733. try:
  734. await task
  735. except asyncio.CancelledError:
  736. pass
  737. assert adapter._chatto_client.update_presence.await_count >= 3
  738. async def test_announce_online_reports_failure(self):
  739. adapter = self._adapter()
  740. adapter._chatto_client.update_presence = AsyncMock(
  741. side_effect=RuntimeError("nope")
  742. )
  743. assert await adapter._announce_online() is False
  744. async def test_disconnect_does_not_broadcast_offline(self):
  745. """chattolib raises ValueError on OFFLINE — going offline means stopping."""
  746. adapter = self._adapter()
  747. adapter._chatto_client.close = AsyncMock()
  748. client = adapter._chatto_client # disconnect() drops the reference
  749. await adapter.disconnect()
  750. client.update_presence.assert_not_called()
  751. # -- Mentions of other people --
  752. class TestForeignMention:
  753. """With require_mention off the bot reads everything, so a message aimed at
  754. a named colleague would otherwise get an unsolicited answer. Acknowledge it
  755. with 🫥 and stay out of the conversation."""
  756. def _adapter(self, **overrides):
  757. adapter = _make_adapter()
  758. adapter.chatto_config.allow_all_users.value = True
  759. adapter.chatto_config.require_mention.value = False
  760. adapter.chatto_config.reactions.value = True
  761. for key, value in overrides.items():
  762. getattr(adapter.chatto_config, key).value = value
  763. adapter.me = _make_user("bot-user-id", "hermes_bot")
  764. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  765. adapter.handle_message = AsyncMock()
  766. adapter.add_reaction = AsyncMock(return_value=True)
  767. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  768. adapter._room_kinds["dm-1"] = RoomKind.DM
  769. # The directory knows bob and nobody else.
  770. adapter._chatto_client.get_user = AsyncMock(
  771. side_effect=lambda **kw: (
  772. DirectoryMember(user=_make_user("user-2", "bob"))
  773. if kw.get("login") == "bob"
  774. else None
  775. )
  776. )
  777. return adapter
  778. async def _dispatch(self, adapter, body, room_id="room-1"):
  779. payload = _make_posted_payload(room_id=room_id)
  780. payload.fetch_message = AsyncMock(
  781. return_value=_make_message(body=body, room_id=room_id)
  782. )
  783. await adapter._dispatch_message_posted(payload)
  784. async def test_message_for_someone_else_is_only_acknowledged(self):
  785. adapter = self._adapter()
  786. await self._dispatch(adapter, "@bob can you take a look?")
  787. adapter.handle_message.assert_not_called()
  788. adapter.add_reaction.assert_awaited_once()
  789. assert adapter.add_reaction.await_args.args[2] == "🫥"
  790. async def test_being_mentioned_alongside_someone_else_still_answers(self):
  791. adapter = self._adapter()
  792. await self._dispatch(adapter, "@bob and @hermes_bot, thoughts?")
  793. adapter.handle_message.assert_called_once()
  794. adapter.add_reaction.assert_not_awaited()
  795. async def test_several_people_addressed_and_none_of_them_us(self):
  796. adapter = self._adapter()
  797. adapter._chatto_client.get_user = AsyncMock(
  798. side_effect=lambda **kw: (
  799. DirectoryMember(user=_make_user("u", kw["login"]))
  800. if kw.get("login") in {"bob", "carol"}
  801. else None
  802. )
  803. )
  804. await self._dispatch(adapter, "@bob @carol schaut mal drüber")
  805. adapter.handle_message.assert_not_called()
  806. adapter.add_reaction.assert_awaited_once()
  807. async def test_a_real_handle_after_an_unknown_one_still_counts(self):
  808. """The scan must not stop at the first token it cannot resolve."""
  809. adapter = self._adapter()
  810. await self._dispatch(adapter, "@nonexistent @bob schaut mal drüber")
  811. adapter.handle_message.assert_not_called()
  812. adapter.add_reaction.assert_awaited_once()
  813. async def test_being_named_among_several_others_still_answers(self):
  814. adapter = self._adapter()
  815. await self._dispatch(adapter, "@bob @hermes_bot @carol — was meint ihr?")
  816. adapter.handle_message.assert_called_once()
  817. adapter.add_reaction.assert_not_awaited()
  818. async def test_broadcast_alongside_a_named_colleague_still_answers(self):
  819. """@here keeps the bot in the audience; naming bob as well does not
  820. remove it."""
  821. adapter = self._adapter()
  822. await self._dispatch(adapter, "@here @bob schaut mal drüber")
  823. adapter.handle_message.assert_called_once()
  824. adapter.add_reaction.assert_not_awaited()
  825. async def test_broadcast_mentions_address_the_bot_too(self):
  826. adapter = self._adapter()
  827. for body in ("@here standup in 5", "@channel heads up", "@everyone hi"):
  828. adapter.handle_message.reset_mock()
  829. await self._dispatch(adapter, body)
  830. adapter.handle_message.assert_called_once()
  831. async def test_talking_about_mentions_is_not_a_mention(self):
  832. """Verbatim from the field: the instruction to send a mention later must
  833. not read as a mention now. '@-mention' is not a handle anyone holds."""
  834. adapter = self._adapter()
  835. await self._dispatch(
  836. adapter,
  837. "Bitte schreibe um 8 Uhr Europe/Berlin per @-mention den "
  838. 'Chatto-Nutzer "nickk" an und sage: Guten Morgen.',
  839. )
  840. adapter.handle_message.assert_called_once()
  841. adapter.add_reaction.assert_not_awaited()
  842. async def test_handle_nobody_holds_is_not_a_mention(self):
  843. """A plausible-looking @token that resolves to no user is not someone
  844. else — answering a false positive beats falling silent on one."""
  845. adapter = self._adapter()
  846. adapter._chatto_client.get_user = AsyncMock(return_value=None)
  847. await self._dispatch(adapter, "gilt das auch für @nonexistent_person?")
  848. adapter.handle_message.assert_called_once()
  849. adapter.add_reaction.assert_not_awaited()
  850. async def test_a_resolvable_handle_is_looked_up_once(self):
  851. adapter = self._adapter()
  852. await self._dispatch(adapter, "@bob ping")
  853. await self._dispatch(adapter, "@bob again")
  854. assert adapter._chatto_client.get_user.await_count == 1
  855. assert adapter.handle_message.await_count == 0
  856. async def test_an_email_address_is_not_a_mention(self):
  857. adapter = self._adapter()
  858. await self._dispatch(adapter, "schreib an bob@example.com")
  859. adapter.handle_message.assert_called_once()
  860. adapter._chatto_client.get_user.assert_not_awaited()
  861. async def test_plain_message_is_unaffected(self):
  862. adapter = self._adapter()
  863. await self._dispatch(adapter, "how do I reset the cache?")
  864. adapter.handle_message.assert_called_once()
  865. async def test_dms_are_answered_even_when_they_name_someone_else(self):
  866. adapter = self._adapter()
  867. await self._dispatch(adapter, "@bob said the build is red", room_id="dm-1")
  868. adapter.handle_message.assert_called_once()
  869. async def test_require_mention_keeps_discarding_without_a_reaction(self):
  870. """The older gate wins: it drops the message before we get here, and it
  871. deliberately says nothing at all."""
  872. adapter = self._adapter(require_mention=True)
  873. await self._dispatch(adapter, "@bob can you take a look?")
  874. adapter.handle_message.assert_not_called()
  875. adapter.add_reaction.assert_not_awaited()
  876. async def test_silence_holds_when_reactions_are_disabled(self):
  877. adapter = self._adapter(reactions=False)
  878. await self._dispatch(adapter, "@bob can you take a look?")
  879. adapter.handle_message.assert_not_called()
  880. adapter.add_reaction.assert_not_awaited()
  881. # -- require_mention --
  882. class TestRequireMention:
  883. """require_mention gates channels only — a DM is already addressed at the bot."""
  884. def _adapter(self):
  885. adapter = _make_adapter()
  886. adapter.chatto_config.allow_all_users.value = True
  887. adapter.chatto_config.require_mention.value = True
  888. adapter.me = _make_user("bot-user-id", "hermes_bot")
  889. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  890. adapter.handle_message = AsyncMock()
  891. return adapter
  892. async def _dispatch(self, adapter, room_id, body):
  893. payload = _make_posted_payload(room_id=room_id)
  894. payload.fetch_message = AsyncMock(
  895. return_value=_make_message(body=body, room_id=room_id)
  896. )
  897. await adapter._dispatch_message_posted(payload)
  898. async def test_channel_without_mention_is_discarded(self):
  899. adapter = self._adapter()
  900. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  901. await self._dispatch(adapter, "room-1", "hi there")
  902. adapter.handle_message.assert_not_called()
  903. async def test_channel_with_mention_is_answered(self):
  904. adapter = self._adapter()
  905. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  906. await self._dispatch(adapter, "room-1", "@hermes_bot hi there")
  907. adapter.handle_message.assert_called_once()
  908. async def test_dm_is_answered_without_a_mention(self):
  909. """The point of the room_kind check: require_mention must not mute DMs."""
  910. adapter = self._adapter()
  911. adapter._room_kinds["dm-1"] = RoomKind.DM
  912. await self._dispatch(adapter, "dm-1", "hi there")
  913. adapter.handle_message.assert_called_once()
  914. # -- Inbound edits (edit-dispatch) --
  915. def _make_edited_event(room_id="room-1", message_event_id="msg-1", actor_id="human-1"):
  916. """A message_edited envelope whose payload the caller stubs."""
  917. event = MagicMock()
  918. event.id = "evt-edit-1"
  919. event.kind = "message_edited"
  920. event.actor_id = actor_id
  921. payload = MagicMock()
  922. payload.room_id = room_id
  923. payload.message_event_id = message_event_id
  924. # RealtimeEvent.get() only yields the payload for its own kind.
  925. event.get = MagicMock(
  926. side_effect=lambda kind: payload if kind == "message_edited" else None
  927. )
  928. return event, payload
  929. class TestEditDispatch:
  930. """message_edited events become corrections, late mentions or nothing."""
  931. def _adapter(self):
  932. adapter = _make_adapter()
  933. adapter.chatto_config.allow_all_users.value = True
  934. adapter.me = _make_user("bot-user-id", "hermes_bot")
  935. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  936. adapter.handle_message = AsyncMock()
  937. return adapter
  938. async def _edit(
  939. self,
  940. adapter,
  941. body,
  942. *,
  943. message_id="msg-1",
  944. room_id="room-1",
  945. created_at=None,
  946. updated_at=None,
  947. ):
  948. event, payload = _make_edited_event(
  949. room_id=room_id, message_event_id=message_id
  950. )
  951. payload.fetch_message = AsyncMock(
  952. return_value=_make_message(
  953. body=body,
  954. message_id=message_id,
  955. room_id=room_id,
  956. created_at=created_at,
  957. updated_at=updated_at,
  958. )
  959. )
  960. await adapter._handle_realtime_event(event)
  961. return payload
  962. async def _post_original(self, adapter, body, *, message_id, room_id):
  963. """Dispatch the original posted message so its turn exists."""
  964. payload = _make_posted_payload(room_id=room_id, message_event_id=message_id)
  965. payload.fetch_message = AsyncMock(
  966. return_value=_make_message(
  967. body=body, message_id=message_id, room_id=room_id
  968. )
  969. )
  970. await adapter._dispatch_message_posted(payload)
  971. def test_edit_dispatch_defaults_on_with_five_minute_window(self):
  972. adapter = self._adapter()
  973. assert adapter.chatto_config.edit_dispatch.value is True
  974. assert adapter.chatto_config.edit_window.value == 300
  975. async def test_own_edit_echo_is_ignored(self):
  976. """Our streaming edits echo back as message_edited — never inbound traffic."""
  977. adapter = self._adapter()
  978. event, payload = _make_edited_event(actor_id="bot-user-id")
  979. payload.fetch_message = AsyncMock()
  980. await adapter._handle_realtime_event(event)
  981. payload.fetch_message.assert_not_awaited()
  982. adapter.handle_message.assert_not_called()
  983. async def test_disabled_feature_drops_edits(self):
  984. adapter = self._adapter()
  985. adapter.chatto_config.edit_dispatch.value = False
  986. await self._edit(adapter, "corrected")
  987. adapter.handle_message.assert_not_called()
  988. async def test_read_only_room_costs_no_api_call(self):
  989. """Respond-room gating sits before fetch_message, like for posts."""
  990. adapter = self._adapter()
  991. adapter.chatto_config.respond_rooms.value = ["other-room"]
  992. fetch = await self._edit(adapter, "corrected")
  993. fetch.fetch_message.assert_not_awaited() # type: ignore[union-attr]
  994. adapter.handle_message.assert_not_called()
  995. async def test_mention_added_by_edit_starts_a_turn(self):
  996. adapter = self._adapter()
  997. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  998. adapter.chatto_config.require_mention.value = True
  999. await self._edit(adapter, "@hermes_bot corrected text")
  1000. adapter.handle_message.assert_called_once()
  1001. assert (
  1002. adapter.handle_message.call_args.args[0].text
  1003. == "@hermes_bot corrected text"
  1004. )
  1005. assert "msg-1" in adapter._dispatched_ids
  1006. async def test_edit_without_the_mention_stays_silent(self):
  1007. """Gates run against the new body — no mention in, no answer out."""
  1008. adapter = self._adapter()
  1009. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  1010. adapter.chatto_config.require_mention.value = True
  1011. await self._edit(adapter, "still no mention")
  1012. adapter.handle_message.assert_not_called()
  1013. async def test_already_answered_message_stays_answered(self):
  1014. """The retro-lock: editing an old answered message must not re-animate it."""
  1015. adapter = self._adapter()
  1016. adapter._dispatched_ids.append("msg-1")
  1017. await self._edit(adapter, "late fix")
  1018. adapter.handle_message.assert_not_called()
  1019. async def test_deleted_message_is_ignored(self):
  1020. adapter = self._adapter()
  1021. now = datetime.now(UTC)
  1022. event, payload = _make_edited_event()
  1023. payload.fetch_message = AsyncMock(
  1024. return_value=_make_message(body="gone", created_at=now, updated_at=now)
  1025. )
  1026. payload.fetch_message.return_value.deleted_at = now
  1027. await adapter._handle_realtime_event(event)
  1028. adapter.handle_message.assert_not_called()
  1029. async def test_stale_edit_outside_the_window_is_ignored(self):
  1030. adapter = self._adapter()
  1031. now = datetime.now(UTC)
  1032. await self._edit(
  1033. adapter,
  1034. "very late fix",
  1035. created_at=now,
  1036. updated_at=now + timedelta(seconds=400),
  1037. )
  1038. adapter.handle_message.assert_not_called()
  1039. async def test_fresh_edit_within_the_window_passes_gates(self):
  1040. adapter = self._adapter()
  1041. adapter._room_kinds["dm-room"] = RoomKind.DM
  1042. now = datetime.now(UTC)
  1043. await self._edit(
  1044. adapter,
  1045. "typo fixed",
  1046. room_id="dm-room",
  1047. created_at=now,
  1048. updated_at=now + timedelta(seconds=5),
  1049. )
  1050. adapter.handle_message.assert_called_once()
  1051. async def test_midrun_edit_restarts_the_turn(self):
  1052. adapter = self._adapter()
  1053. adapter._room_kinds["dm-room"] = RoomKind.DM
  1054. await self._post_original(
  1055. adapter, "orignal text", message_id="msg-run", room_id="dm-room"
  1056. )
  1057. first_event = adapter.handle_message.call_args.args[0]
  1058. await adapter.on_processing_start(first_event)
  1059. adapter.cancel_session_processing = AsyncMock()
  1060. await self._edit(
  1061. adapter, "original text", message_id="msg-run", room_id="dm-room"
  1062. )
  1063. adapter.cancel_session_processing.assert_awaited_once()
  1064. assert adapter.handle_message.await_count == 2
  1065. assert adapter.handle_message.await_args.args[0].text == "original text"
  1066. async def test_completion_hook_rearms_the_processing_map(self):
  1067. """After any outcome (incl. CANCELLED) the session accepts new turns."""
  1068. adapter = self._adapter()
  1069. adapter._room_kinds["dm-room"] = RoomKind.DM
  1070. await self._post_original(
  1071. adapter, "hello", message_id="msg-run", room_id="dm-room"
  1072. )
  1073. event = adapter.handle_message.call_args.args[0]
  1074. await adapter.on_processing_start(event)
  1075. session_key = adapter._session_key_for(event.source)
  1076. assert adapter._processing.get(session_key) == "msg-run"
  1077. await adapter.on_processing_complete(event, ProcessingOutcome.CANCELLED)
  1078. assert session_key not in adapter._processing
  1079. async def test_queued_followup_gets_corrected_in_place(self):
  1080. """A still-queued message answers later with its edited wording."""
  1081. from types import SimpleNamespace
  1082. adapter = self._adapter()
  1083. adapter._room_kinds["dm-room"] = RoomKind.DM
  1084. await self._post_original(
  1085. adapter, "queue me", message_id="msg-other", room_id="dm-room"
  1086. )
  1087. other_event = adapter.handle_message.call_args.args[0]
  1088. session_key = adapter._session_key_for(other_event.source)
  1089. pending = SimpleNamespace(message_id="msg-run", text="stale wording")
  1090. adapter._pending_messages[session_key] = pending
  1091. adapter._dispatched_ids.extend(["msg-other", "msg-run"])
  1092. adapter.cancel_session_processing = AsyncMock()
  1093. await self._edit(
  1094. adapter, "fixed wording", message_id="msg-run", room_id="dm-room"
  1095. )
  1096. assert pending.text == "fixed wording"
  1097. adapter.cancel_session_processing.assert_not_awaited()
  1098. # No second dispatch: the queued original carries the correction.
  1099. assert adapter.handle_message.await_count == 1
  1100. async def test_dm_command_edit_neither_reruns_nor_dispatches(self):
  1101. """/join ran when posted; its edited copy must not run twice or leak."""
  1102. adapter = self._adapter()
  1103. adapter._room_kinds["dm-room"] = RoomKind.DM
  1104. adapter._handle_dm_command = AsyncMock(return_value=True)
  1105. await self._edit(adapter, "/leave", room_id="dm-room")
  1106. adapter._handle_dm_command.assert_not_called()
  1107. adapter.handle_message.assert_not_called()
  1108. # -- Inbound attachments --
  1109. class TestInboundAttachments:
  1110. """Messages carrying files must reach the agent, body or not."""
  1111. @pytest_asyncio.fixture
  1112. def adapter(self):
  1113. adapter = _make_adapter()
  1114. adapter.chatto_config.allow_all_users.value = True
  1115. adapter.me = _make_user("bot-user-id", "hermes_bot")
  1116. adapter._room_kinds["room-1"] = RoomKind.DM
  1117. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  1118. adapter.handle_message = AsyncMock()
  1119. adapter._download_attachment_bytes = AsyncMock(
  1120. return_value=b"\x89PNG\r\n\x1a\nrest"
  1121. )
  1122. return adapter
  1123. async def test_image_attachment_becomes_media_url(self, adapter):
  1124. payload = _make_posted_payload()
  1125. adapter._chatto_client.get_room = AsyncMock()
  1126. message = _make_message(
  1127. body="look at this",
  1128. attachments=[_make_attachment("shot.png", "image/png")],
  1129. )
  1130. payload.fetch_message = AsyncMock(return_value=message)
  1131. with patch(
  1132. "adapter.cache_media_bytes",
  1133. return_value=_cached("/cache/shot.png", "image/png", "image"),
  1134. ):
  1135. await adapter._dispatch_message_posted(payload)
  1136. event = adapter.handle_message.call_args.args[0]
  1137. assert event.media_urls == ["/cache/shot.png"]
  1138. assert event.media_types == ["image/png"]
  1139. assert event.message_type == MessageType.PHOTO
  1140. async def test_attachment_only_message_is_not_dropped(self, adapter):
  1141. """The empty-body early return is what silently ate file uploads."""
  1142. payload = _make_posted_payload()
  1143. message = _make_message(
  1144. body="",
  1145. attachments=[_make_attachment("report.pdf", "application/pdf")],
  1146. )
  1147. payload.fetch_message = AsyncMock(return_value=message)
  1148. with patch(
  1149. "adapter.cache_media_bytes",
  1150. return_value=_cached("/cache/report.pdf", "application/pdf", "document"),
  1151. ):
  1152. await adapter._dispatch_message_posted(payload)
  1153. adapter.handle_message.assert_called_once()
  1154. event = adapter.handle_message.call_args.args[0]
  1155. assert event.message_type == MessageType.DOCUMENT
  1156. assert event.media_urls == ["/cache/report.pdf"]
  1157. async def test_empty_message_without_attachments_is_dropped(self, adapter):
  1158. payload = _make_posted_payload()
  1159. payload.fetch_message = AsyncMock(return_value=_make_message(body=""))
  1160. await adapter._dispatch_message_posted(payload)
  1161. adapter.handle_message.assert_not_called()
  1162. async def test_download_failure_still_delivers_the_text(self, adapter):
  1163. adapter._download_attachment_bytes = AsyncMock(side_effect=RuntimeError("404"))
  1164. payload = _make_posted_payload()
  1165. payload.fetch_message = AsyncMock(
  1166. return_value=_make_message(
  1167. body="see attached",
  1168. attachments=[_make_attachment("a.png", "image/png")],
  1169. )
  1170. )
  1171. await adapter._dispatch_message_posted(payload)
  1172. event = adapter.handle_message.call_args.args[0]
  1173. assert event.text == "see attached"
  1174. assert event.media_urls == []
  1175. assert event.message_type == MessageType.TEXT
  1176. async def test_attachment_without_asset_url_is_skipped(self, adapter):
  1177. """Videos are announced before transcoding finishes."""
  1178. payload = _make_posted_payload()
  1179. att = _make_attachment("clip.mp4", "video/mp4")
  1180. att.asset_url = None
  1181. payload.fetch_message = AsyncMock(
  1182. return_value=_make_message(
  1183. body="clip",
  1184. attachments=[att],
  1185. )
  1186. )
  1187. await adapter._dispatch_message_posted(payload)
  1188. event = adapter.handle_message.call_args.args[0]
  1189. assert event.media_urls == []
  1190. adapter._download_attachment_bytes.assert_not_called()
  1191. async def test_document_wins_over_image(self, adapter):
  1192. """Mixed batches classify as DOCUMENT — that gates context injection."""
  1193. assert (
  1194. adapter._message_type_for_media_kinds(["image", "document"])
  1195. is MessageType.DOCUMENT
  1196. )
  1197. assert adapter._message_type_for_media_kinds(["image"]) is MessageType.PHOTO
  1198. assert adapter._message_type_for_media_kinds(["video"]) is MessageType.VIDEO
  1199. assert adapter._message_type_for_media_kinds(["audio"]) is MessageType.AUDIO
  1200. assert adapter._message_type_for_media_kinds([]) is MessageType.TEXT
  1201. async def test_oversized_attachment_is_rejected(self, adapter):
  1202. """The gateway media cap must bound what a hostile upload can buffer."""
  1203. import httpx
  1204. big = get_inbound_media_max_bytes() + 1
  1205. transport = httpx.MockTransport(
  1206. lambda request: httpx.Response(
  1207. 200,
  1208. headers={"content-length": str(big)},
  1209. content=b"x",
  1210. )
  1211. )
  1212. real_adapter = _make_adapter()
  1213. real_client_cls = httpx.AsyncClient
  1214. with (
  1215. patch(
  1216. "httpx.AsyncClient", lambda **kw: real_client_cls(transport=transport)
  1217. ),
  1218. pytest.raises(ValueError),
  1219. ):
  1220. await real_adapter._download_attachment_bytes(
  1221. "https://chat.example.com/a.png"
  1222. )
  1223. # NOTE: there are deliberately no tests for get_user(), set_presence() or
  1224. # set_custom_status() on the adapter. Those are not adapter responsibilities —
  1225. # callers use the chattolib client directly, which exposes them (client.get_user,
  1226. # client.update_presence, client.update_custom_status). The adapter only touches
  1227. # presence in connect()/disconnect().
  1228. # -- Room operations --
  1229. class TestRoomOperations:
  1230. """Test room creation and DM initiation."""
  1231. @pytest_asyncio.fixture
  1232. def adapter(self):
  1233. _clear_chatto_env()
  1234. cfg = _make_config()
  1235. adapter = ChattoAdapter(cfg)
  1236. adapter._chatto_client = MagicMock()
  1237. # AsyncMock, not MagicMock: the adapter awaits these, and awaiting a
  1238. # plain MagicMock raises TypeError, which create_room()/start_dm()
  1239. # swallow into a None return.
  1240. adapter._chatto_client.create_room = AsyncMock()
  1241. adapter._chatto_client.start_dm = AsyncMock()
  1242. adapter._token = "test-token"
  1243. adapter._room_names = {}
  1244. adapter._room_kinds = {}
  1245. return adapter
  1246. async def test_create_room(self, adapter):
  1247. adapter._chatto_client.create_room.return_value = _make_room(
  1248. "room-123",
  1249. "Test Room",
  1250. RoomKind.CHANNEL,
  1251. )
  1252. result = await adapter.create_room("Test Room", "A test room")
  1253. assert result == "room-123"
  1254. adapter._chatto_client.create_room.assert_called_once()
  1255. assert adapter._room_names["room-123"] == "Test Room"
  1256. async def test_start_dm(self, adapter):
  1257. adapter._chatto_client.start_dm.return_value = _make_room(
  1258. "dm-123",
  1259. "DM with user",
  1260. RoomKind.DM,
  1261. )
  1262. result = await adapter.start_dm("user-123")
  1263. assert result == "dm-123"
  1264. adapter._chatto_client.start_dm.assert_called_once()
  1265. assert adapter._room_kinds["dm-123"] == RoomKind.DM
  1266. # -- DM room management (/join, /leave) --
  1267. def _make_room_state(room, is_member):
  1268. """Build a RoomWithViewerState the way list_rooms()/get_room() return it."""
  1269. return RoomWithViewerState(
  1270. room=room,
  1271. viewer_state=RoomViewerState(is_member=is_member),
  1272. )
  1273. class TestDmRoomCommands:
  1274. """/join and /leave arrive over DMs, change server-side membership and
  1275. must never reach the agent pipeline."""
  1276. def _adapter(self):
  1277. adapter = _make_adapter()
  1278. adapter.chatto_config.allow_all_users.value = True
  1279. adapter.me = _make_user("bot-user-id", "hermes_bot")
  1280. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  1281. client = adapter._chatto_client
  1282. client.list_rooms = AsyncMock(return_value=[])
  1283. client.get_room_events = AsyncMock(return_value=MagicMock(events=[]))
  1284. client.join_room = AsyncMock()
  1285. client.leave_room = AsyncMock(return_value=True)
  1286. client.get_room = AsyncMock()
  1287. adapter._room_kinds["dm-1"] = RoomKind.DM
  1288. adapter.handle_message = AsyncMock()
  1289. adapter.send = AsyncMock()
  1290. return adapter
  1291. async def _dispatch(self, adapter, body, room_id="dm-1"):
  1292. payload = _make_posted_payload(room_id=room_id)
  1293. payload.fetch_message = AsyncMock(
  1294. return_value=_make_message(body=body, room_id=room_id)
  1295. )
  1296. await adapter._dispatch_message_posted(payload)
  1297. def _reply(self, adapter):
  1298. assert adapter.send.await_count == 1
  1299. return adapter.send.await_args.kwargs["content"]
  1300. async def test_join_by_name_joins_and_seeds(self):
  1301. adapter = self._adapter()
  1302. state = _make_room_state(
  1303. _make_room("room-9", "Deploy", RoomKind.CHANNEL), False
  1304. )
  1305. adapter._chatto_client.list_rooms = AsyncMock(return_value=[state])
  1306. adapter._chatto_client.join_room = AsyncMock(return_value=state.room)
  1307. await self._dispatch(adapter, "/join #deploy")
  1308. adapter._chatto_client.join_room.assert_awaited_once_with("room-9")
  1309. assert adapter._joined_room_ids == ["room-9"]
  1310. assert "Joined 'Deploy' (room-9)" in self._reply(adapter)
  1311. async def test_join_skips_rpc_when_already_a_member(self):
  1312. adapter = self._adapter()
  1313. """Natively invited accounts hold membership already — they only need
  1314. seeding into the joined list."""
  1315. state = _make_room_state(_make_room("room-9", "Deploy", RoomKind.CHANNEL), True)
  1316. adapter._chatto_client.list_rooms = AsyncMock(return_value=[state])
  1317. await self._dispatch(adapter, "/join #deploy")
  1318. adapter._chatto_client.join_room.assert_not_awaited()
  1319. assert adapter._joined_room_ids == ["room-9"]
  1320. assert "Already a member" in self._reply(adapter)
  1321. async def test_join_unknown_name_reports_without_joining(self):
  1322. adapter = self._adapter()
  1323. adapter._chatto_client.list_rooms = AsyncMock(return_value=[])
  1324. await self._dispatch(adapter, "/join #nope")
  1325. adapter._chatto_client.join_room.assert_not_awaited()
  1326. assert "No room named '#nope'" in self._reply(adapter)
  1327. assert adapter._joined_room_ids == []
  1328. async def test_ambiguous_name_offers_the_candidate_ids(self):
  1329. adapter = self._adapter()
  1330. matches = [
  1331. _make_room_state(_make_room(f"r-{i}", "General", RoomKind.CHANNEL), False)
  1332. for i in range(2)
  1333. ]
  1334. adapter._chatto_client.list_rooms = AsyncMock(return_value=matches)
  1335. adapter._chatto_client.join_room = AsyncMock()
  1336. await self._dispatch(adapter, "/join #general")
  1337. adapter._chatto_client.join_room.assert_not_awaited()
  1338. reply = self._reply(adapter)
  1339. assert "r-0" in reply and "r-1" in reply
  1340. async def test_join_by_room_id_verifies_via_get_room(self):
  1341. adapter = self._adapter()
  1342. state = _make_room_state(
  1343. _make_room("room-9", "Deploy", RoomKind.CHANNEL), False
  1344. )
  1345. adapter._chatto_client.get_room = AsyncMock(return_value=state)
  1346. adapter._chatto_client.join_room = AsyncMock(return_value=state.room)
  1347. await self._dispatch(adapter, "/join room-9")
  1348. adapter._chatto_client.get_room.assert_awaited_once_with("room-9")
  1349. adapter._chatto_client.join_room.assert_awaited_once_with("room-9")
  1350. assert adapter._joined_room_ids == ["room-9"]
  1351. async def test_leave_drops_the_room_from_the_joined_list(self):
  1352. adapter = self._adapter()
  1353. adapter._joined_room_ids = ["room-7"]
  1354. state = _make_room_state(_make_room("room-7", "Deploy", RoomKind.CHANNEL), True)
  1355. adapter._chatto_client.get_room = AsyncMock(return_value=state)
  1356. await self._dispatch(adapter, "/leave room-7")
  1357. adapter._chatto_client.leave_room.assert_awaited_once_with("room-7")
  1358. assert adapter._joined_room_ids == []
  1359. assert "Left 'Deploy' (room-7)" in self._reply(adapter)
  1360. async def test_leave_refuses_direct_messages(self):
  1361. adapter = self._adapter()
  1362. state = _make_room_state(_make_room("dm-2", "", RoomKind.DM), True)
  1363. adapter._chatto_client.get_room = AsyncMock(return_value=state)
  1364. await self._dispatch(adapter, "/leave dm-2")
  1365. adapter._chatto_client.leave_room.assert_not_awaited()
  1366. assert "Direct messages cannot be left" in self._reply(adapter)
  1367. async def test_leave_refuses_home_channel(self):
  1368. """Leaving CHATTO_HOME_CHANNEL would break cron/notification delivery."""
  1369. adapter = self._adapter()
  1370. adapter.chatto_config.home_channel.value = "room-7"
  1371. adapter._joined_room_ids = ["room-7"]
  1372. state = _make_room_state(_make_room("room-7", "Home", RoomKind.CHANNEL), True)
  1373. adapter._chatto_client.get_room = AsyncMock(return_value=state)
  1374. await self._dispatch(adapter, "/leave room-7")
  1375. adapter._chatto_client.leave_room.assert_not_awaited()
  1376. assert "home channel" in self._reply(adapter)
  1377. async def test_commands_outside_dms_are_ignored(self):
  1378. adapter = self._adapter()
  1379. """In a channel the text is just a message — mention gating applies,
  1380. no command runs, nothing is sent."""
  1381. adapter.chatto_config.require_mention.value = True
  1382. adapter._room_kinds["chan-1"] = RoomKind.CHANNEL
  1383. await self._dispatch(adapter, "/leave room-7", room_id="chan-1")
  1384. adapter._chatto_client.leave_room.assert_not_awaited()
  1385. adapter.handle_message.assert_not_called()
  1386. adapter.send.assert_not_called()
  1387. async def test_non_command_dm_falls_through_to_pipeline(self):
  1388. adapter = self._adapter()
  1389. await self._dispatch(adapter, "/status all good")
  1390. adapter.handle_message.assert_awaited_once()
  1391. adapter.send.assert_not_called()
  1392. async def test_missing_argument_gets_usage_reply(self):
  1393. adapter = self._adapter()
  1394. for body in ("/join", "/leave"):
  1395. adapter.send.reset_mock()
  1396. await self._dispatch(adapter, body)
  1397. assert self._reply(adapter).startswith("Usage:")
  1398. class TestJoinedRoomsRefresh:
  1399. """_refresh_rooms mirrors the joined list against server-side membership."""
  1400. def _adapter(self):
  1401. adapter = _make_adapter()
  1402. client = adapter._chatto_client
  1403. client.list_rooms = AsyncMock(return_value=[])
  1404. return adapter
  1405. async def test_drops_rooms_no_longer_joined(self):
  1406. adapter = self._adapter()
  1407. adapter._joined_room_ids = ["gone-1", "kept"]
  1408. kept = _make_room_state(_make_room("kept", "Kept", RoomKind.CHANNEL), True)
  1409. adapter._chatto_client.list_rooms = AsyncMock(return_value=[kept])
  1410. await adapter._refresh_rooms()
  1411. assert adapter._joined_room_ids == ["kept"]
  1412. async def test_warns_once_when_home_channel_is_not_joined(self):
  1413. adapter = self._adapter()
  1414. adapter.chatto_config.home_channel.value = "home-x"
  1415. other = _make_room_state(_make_room("other", "Other", RoomKind.CHANNEL), True)
  1416. adapter._chatto_client.list_rooms = AsyncMock(return_value=[other])
  1417. await adapter._refresh_rooms()
  1418. assert adapter._home_warning_logged
  1419. await adapter._refresh_rooms()
  1420. assert adapter._home_warning_logged
  1421. async def test_no_warning_while_home_channel_is_member(self):
  1422. adapter = self._adapter()
  1423. adapter.chatto_config.home_channel.value = "home-x"
  1424. home = _make_room_state(_make_room("home-x", "Home", RoomKind.CHANNEL), True)
  1425. adapter._chatto_client.list_rooms = AsyncMock(return_value=[home])
  1426. await adapter._refresh_rooms()
  1427. assert not adapter._home_warning_logged
  1428. class TestRespondRooms:
  1429. """CHATTO_RESPOND_ROOMS gates inbound messages: positive list, DMs exempt."""
  1430. def _dropping_adapter(self, respond_rooms):
  1431. """An adapter whose every API call explodes — the gate must exit first."""
  1432. adapter = _make_adapter()
  1433. adapter.chatto_config.respond_rooms.value = respond_rooms
  1434. adapter.me = _make_user("bot-user-id", "hermes_bot")
  1435. adapter.handle_message = AsyncMock()
  1436. adapter._require_client = AsyncMock(side_effect=RuntimeError("no client"))
  1437. return adapter
  1438. async def test_unlisted_room_is_dropped_before_any_api_call(self):
  1439. adapter = self._dropping_adapter(["listed-1"])
  1440. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  1441. payload = _make_posted_payload(room_id="room-1")
  1442. payload.fetch_message = AsyncMock()
  1443. await adapter._dispatch_message_posted(payload)
  1444. payload.fetch_message.assert_not_awaited()
  1445. adapter.handle_message.assert_not_called()
  1446. async def test_unknown_room_kind_fails_closed(self):
  1447. """No cached kind: the allowlist assumes the worst and drops."""
  1448. adapter = self._dropping_adapter(["listed-1"])
  1449. payload = _make_posted_payload(room_id="mystery-room")
  1450. payload.fetch_message = AsyncMock()
  1451. await adapter._dispatch_message_posted(payload)
  1452. payload.fetch_message.assert_not_awaited()
  1453. adapter.handle_message.assert_not_called()
  1454. async def test_listed_room_reaches_the_pipeline(self):
  1455. adapter = self._dropping_adapter(["room-1"])
  1456. adapter.chatto_config.allow_all_users.value = True
  1457. adapter._require_client = AsyncMock(return_value=adapter._chatto_client)
  1458. adapter._room_kinds["room-1"] = RoomKind.CHANNEL
  1459. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  1460. payload = _make_posted_payload(room_id="room-1")
  1461. payload.fetch_message = AsyncMock(
  1462. return_value=_make_message(body="hi", room_id="room-1")
  1463. )
  1464. await adapter._dispatch_message_posted(payload)
  1465. adapter.handle_message.assert_called_once()
  1466. async def test_dm_outside_the_list_still_answers(self):
  1467. """DMs stay respond rooms so /join remains reachable."""
  1468. adapter = self._dropping_adapter(["listed-1"])
  1469. adapter.chatto_config.allow_all_users.value = True
  1470. adapter._require_client = AsyncMock(return_value=adapter._chatto_client)
  1471. adapter._room_kinds["dm-1"] = RoomKind.DM
  1472. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  1473. payload = _make_posted_payload(room_id="dm-1")
  1474. payload.fetch_message = AsyncMock(
  1475. return_value=_make_message(body="hi", room_id="dm-1")
  1476. )
  1477. await adapter._dispatch_message_posted(payload)
  1478. adapter.handle_message.assert_called_once()
  1479. async def test_empty_list_answers_everywhere(self):
  1480. """Unset list keeps the pre-existing behaviour: every room responds."""
  1481. adapter = self._dropping_adapter([])
  1482. adapter.chatto_config.allow_all_users.value = True
  1483. adapter._require_client = AsyncMock(return_value=adapter._chatto_client)
  1484. adapter._room_kinds["any-room"] = RoomKind.CHANNEL
  1485. adapter._user_cache["user-1"] = _make_user("user-1", "alice")
  1486. payload = _make_posted_payload(room_id="any-room")
  1487. payload.fetch_message = AsyncMock(
  1488. return_value=_make_message(body="hi", room_id="any-room")
  1489. )
  1490. await adapter._dispatch_message_posted(payload)
  1491. adapter.handle_message.assert_called_once()
  1492. class TestRespondRoomRefresh:
  1493. """_refresh_rooms keeps read-only rooms joined but skips seeding them."""
  1494. def _adapter(self, respond_rooms):
  1495. adapter = _make_adapter()
  1496. adapter.chatto_config.respond_rooms.value = respond_rooms
  1497. client = adapter._chatto_client
  1498. client.list_rooms = AsyncMock(return_value=[])
  1499. client.join_room = AsyncMock()
  1500. adapter._seed_room = AsyncMock()
  1501. return adapter
  1502. async def test_read_only_rooms_are_joined_but_not_seeded(self):
  1503. adapter = self._adapter(["team-1"])
  1504. news = _make_room_state(_make_room("news-1", "News", RoomKind.CHANNEL), True)
  1505. team = _make_room_state(_make_room("team-1", "Team", RoomKind.CHANNEL), True)
  1506. adapter._chatto_client.list_rooms = AsyncMock(return_value=[news, team])
  1507. await adapter._refresh_rooms()
  1508. assert sorted(adapter._joined_room_ids) == ["news-1", "team-1"]
  1509. adapter._seed_room.assert_awaited_once_with("team-1")
  1510. async def test_join_log_tags_read_only_and_universal(self, caplog):
  1511. adapter = self._adapter(["team-1"])
  1512. news = Room(id="news-1", name="News", kind=RoomKind.CHANNEL, universal=True)
  1513. team = Room(id="team-1", name="Team", kind=RoomKind.CHANNEL, universal=False)
  1514. adapter._chatto_client.list_rooms = AsyncMock(
  1515. return_value=[_make_room_state(news, True), _make_room_state(team, True)]
  1516. )
  1517. with caplog.at_level("INFO"):
  1518. await adapter._refresh_rooms()
  1519. joined = [m for m in caplog.messages if "currently joined" in m]
  1520. assert joined, "expected the joined-rooms summary log line"
  1521. assert "[read-only]" in joined[-1]
  1522. assert "[universal]" in joined[-1]
  1523. async def test_warns_when_respond_list_names_unjoined_rooms(self, caplog):
  1524. adapter = self._adapter(["ghost-id"])
  1525. kept = _make_room_state(_make_room("kept", "Kept", RoomKind.CHANNEL), True)
  1526. adapter._chatto_client.list_rooms = AsyncMock(return_value=[kept])
  1527. with caplog.at_level("WARNING"):
  1528. await adapter._refresh_rooms()
  1529. assert any("ghost-id" in message for message in caplog.messages)
  1530. # -- Constants --
  1531. class TestConstants:
  1532. """Test that constants are properly defined."""
  1533. def test_max_message_length(self):
  1534. assert _MAX_MESSAGE_LENGTH == 10000
  1535. def test_seen_cap(self):
  1536. assert _SEEN_CAP == 500