test_adapter.py 113 KB

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