test_adapter.py 92 KB

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