test_adapter.py 78 KB

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