The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e): messaging-adapter contract suite across Telegram/Discord/Slack
teknium179872aaf3fd9
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 6472aa8fe0e..30440960bc5 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -143,7 +143,9 @@ jobs:uses: ./.github/actions/setup-pmwith:toolchain: all- extras: '["all", "anthropic", "bedrock", "mistral", "fal", "modal", "daytona", "parallel-web"]'+ # `messaging`: tests/e2e/core/platforms runs the real Telegram/Discord/Slack+ # adapters (their SDKs) against local stand-ins.+ extras: '["all", "anthropic", "bedrock", "mistral", "fal", "modal", "daytona", "parallel-web", "messaging"]'test-environment: 'true'prune-python-cache: truediff --git a/tests/e2e/core/platforms/_contract.py b/tests/e2e/core/platforms/_contract.pynew file mode 100644index 00000000000..f898bce320a--- /dev/null+++ b/tests/e2e/core/platforms/_contract.py@@ -0,0 +1,339 @@+"""The messaging-adapter contract: scenarios every real adapter must pass through a real gateway.++Each scenario takes a running ``Rig`` (gateway child + stand-in driver + fake LLM director) and+asserts user-visible outcomes at the stand-in (what a human in the chat now sees), the next wire+request Hermes sent the model, or persisted state (state.db). Tokens ``[in:<id>]`` tie every inbound+to the model turns it started, so duplicate or dropped turns are counted, never guessed.++Negative claims ("no second reply", "no turn for the unmentioned message") are settled by a BARRIER:+a later inbound in the same chat whose reply proves the gateway already processed everything+queued before it — never by sleeping.+"""++from __future__ import annotations++import html+import io+import re+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Dict, List++from tests.e2e.core.platforms._helpers import Director, GatewayUnderTest+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall+from tests.fakes.platforms._standin import Visible, wait_until++TURN_TIMEOUT = 90.0+++@dataclass+class Rig:+ gw: GatewayUnderTest+ drv: Any+ director: Director+ llm: FakeLLMServer++ def ctx(self) -> str:+ return f"{self.drv.describe()}\n{self.gw.tail(4000)}"+++def head(aid: str) -> str:+ return f"<<{aid}>>"+++def foot(aid: str) -> str:+ return f"<<end-{aid}>>"+++def answer(aid: str, body: str, **kw: Any) -> Text:+ return Text(f"{head(aid)} {body} {foot(aid)}", **kw)+++def norm(text: str) -> str:+ # Renderers escape markdown punctuation (``\\.``) or HTML (``<``) and may re-wrap whitespace.+ return re.sub(r"\s+", " ", html.unescape(text).replace("\\", "")).strip()+++def copies(visible: List[Visible], aid: str) -> List[Visible]:+ return [v for v in visible if head(aid) in norm(v.text) or foot(aid) in norm(v.text)]+++def complete(visible: List[Visible], aid: str) -> List[Visible]:+ return [v for v in visible if head(aid) in norm(v.text) and foot(aid) in norm(v.text)]+++def wait_reply(rig: Rig, chat_id: str, aid: str, what: str = "", timeout: float = TURN_TIMEOUT) -> None:+ """Until the reply's LAST piece (footer) is visible in ``chat_id``."""+ wait_until(lambda: any(foot(aid) in norm(v.text) for v in rig.drv.visible(chat_id)),+ what or f"reply {aid} visible in {chat_id}", timeout=timeout, on_timeout=rig.ctx)+++def barrier(rig: Rig, token: str, *, group: bool = False) -> None:+ """One more inbound in the same chat, answered: everything queued before it has been handled."""+ aid = f"B-{token}"+ rig.director.script(token, answer(aid, "barrier"))+ inbound = rig.drv.group(f"barrier [in:{token}]", mention=True) if group else rig.drv.dm(f"barrier [in:{token}]")+ wait_reply(rig, inbound.chat_id, aid, f"barrier {token} answered")+++def turns(rig: Rig, token: str) -> int:+ return rig.director.turns.get(token, 0)+++# 1. inbound DM -> exactly one reply --------------------------------------------------------------+def dm_gets_exactly_one_reply(rig: Rig, tag: str) -> None:+ token, aid = f"dm-{tag}", f"A-dm-{tag}"+ rig.director.script(token, answer(aid, "hello back"))+ inbound = rig.drv.dm(f"hello [in:{token}]")+ wait_reply(rig, inbound.chat_id, aid)+ barrier(rig, f"dmb-{tag}")+ vis = copies(rig.drv.visible(inbound.chat_id), aid)+ assert len(vis) == 1 and complete(vis, aid), f"expected one complete reply, got {vis}\n{rig.ctx()}"+ assert turns(rig, token) == 1, f"inbound started {turns(rig, token)} model turns\n{rig.ctx()}"+ assert len(rig.gw.user_rows(f"[in:{token}]")) == 1, "inbound persisted != once"+++# 2. group without mention obeys require_mention --------------------------------------------------+def group_obeys_require_mention(rig: Rig, tag: str) -> None:+ quiet, loud = f"gq-{tag}", f"gl-{tag}"+ rig.director.script(quiet, answer(f"A-{quiet}", "should never be said"))+ rig.director.script(loud, answer(f"A-{loud}", "mentioned, so answered"))+ rig.drv.group(f"just chatting [in:{quiet}]", mention=False)+ inbound = rig.drv.group(f"please answer [in:{loud}]", mention=True)+ wait_reply(rig, inbound.chat_id, f"A-{loud}")+ barrier(rig, f"gb-{tag}", group=True)+ assert turns(rig, quiet) == 0, f"unmentioned group message started a model turn\n{rig.ctx()}"+ assert not copies(rig.drv.visible(inbound.chat_id), f"A-{quiet}"), "unmentioned message was answered"+ assert len(complete(rig.drv.visible(inbound.chat_id), f"A-{loud}")) == 1, rig.ctx()+++# 3. reply longer than the platform limit -> split, in order, nothing lost ------------------------+def long_body(limit: int, factor: float = 2.4) -> str:+ n = int(limit * factor / 7) + 1+ return " ".join(f"w{i:05d}" for i in range(n))+++def _words(text: str) -> List[str]:+ return re.findall(r"w\d{5}", text)+++def long_reply_is_split_in_order(rig: Rig, tag: str) -> None:+ token, aid = f"long-{tag}", f"A-long-{tag}"+ body = long_body(rig.drv.limit)+ rig.director.script(token, answer(aid, body, chunk_chars=4000))+ inbound = rig.drv.dm(f"write a lot [in:{token}]")+ wait_reply(rig, inbound.chat_id, aid)+ barrier(rig, f"longb-{tag}")+ parts = [v for v in rig.drv.visible(inbound.chat_id) if _words(v.text) or head(aid) in norm(v.text)]+ assert len(parts) >= 2, f"a {len(body)}-char reply was not split\n{rig.ctx()}"+ too_long = [len(v.text) for v in parts if len(v.text) > rig.drv.limit]+ assert not too_long, f"chunks over the {rig.drv.limit} cap: {too_long}"+ seen = [w for v in parts for w in _words(v.text)]+ assert seen == _words(body), (f"split reply lost/reordered/duplicated words: got {len(seen)} of "+ f"{len(_words(body))}\n{rig.ctx()}")+++# 4. failed continuation chunk is not silently dropped (#120073) ----------------------------------+def failed_continuation_is_retried_or_reported(rig: Rig, tag: str) -> None:+ token, aid = f"gap-{tag}", f"A-gap-{tag}"+ body = long_body(rig.drv.limit)+ words = _words(body)+ marker = words[int(len(words) * 0.75)] # lands in a continuation chunk, never the first+ rig.director.script(token, answer(aid, body, chunk_chars=4000))+ # every attempt at that chunk is rejected (a plain-text/markdown fallback or a short retry ladder+ # must not paper over it): only a later retry or an honest notice satisfies the contract+ rig.drv.fail_send(times=3, match=lambda text: marker in text)+ inbound = rig.drv.dm(f"write a lot again [in:{token}]")+ wait_until(lambda: turns(rig, token) >= 1, "model turn started", timeout=TURN_TIMEOUT, on_timeout=rig.ctx)+ barrier(rig, f"gapb-{tag}")+ visible = rig.drv.visible(inbound.chat_id)+ seen = [w for v in visible for w in _words(v.text)]+ missing = [w for w in words if w not in seen]+ if not missing:+ return # the rejected continuation was re-sent: nothing lost+ tail_idx = max(i for i, v in enumerate(visible) if _words(v.text))+ notices = [v.text for v in visible[tail_idx + 1:]+ if not _words(v.text) and "barrier" not in v.text and head(aid) not in norm(v.text)]+ assert notices, (f"{len(missing)} words of the reply (from {missing[0]}) were never delivered and the "+ f"user was not told\n{rig.ctx()}")+++# 5. stream finalize rejected -> exactly one complete copy (#121108 pattern) -----------------------+def rejected_finalize_leaves_one_copy(rig: Rig, tag: str) -> None:+ token, aid = f"fin-{tag}", f"A-fin-{tag}"+ body = " ".join(f"q{i:03d}" for i in range(120))+ rig.director.script(token, answer(aid, body, chunk_chars=12, delay_per_chunk=0.03))+ rig.drv.fail_edit(times=50, match=lambda text: foot(aid) in norm(text))+ inbound = rig.drv.dm(f"stream it [in:{token}]")+ wait_reply(rig, inbound.chat_id, aid)+ barrier(rig, f"finb-{tag}")+ rig.drv.standin.clear_faults()+ shown = _shown(rig, inbound.chat_id, aid, "q")+ ctx = f"visible: {shown[:600]!r}\n{rig.ctx()}"+ assert shown.count(head(aid)) == 1 and shown.count(foot(aid)) == 1, f"answer shown != once after a rejected finalize\n{ctx}"+ assert _pwords(shown, "q") == _pwords(body, "q"), f"answer words lost/duplicated after a rejected finalize\n{ctx}"+ assert turns(rig, token) == 1, rig.ctx()+++def _pwords(text: str, prefix: str) -> List[str]:+ return re.findall(rf"\b{prefix}\d{{3}}\b", text)+++def _shown(rig: Rig, chat_id: str, aid: str, prefix: str) -> str:+ """Everything visible that carries a piece of THIS answer (the chat is shared across scenarios)."""+ return " ".join(norm(v.text) for v in rig.drv.visible(chat_id)+ if copies([v], aid) or _pwords(norm(v.text), prefix))+++def streamed_reply_ending_in_whitespace_shown_once(rig: Rig, tag: str) -> None:+ """Models routinely end on a newline; the streamed transport must still finalize ONE message."""+ token, aid = f"ws-{tag}", f"A-ws-{tag}"+ body = " ".join(f"w{i:03d}" for i in range(80))+ rig.director.script(token, Text(f"{head(aid)} {body} {foot(aid)}\n\n", chunk_chars=12, delay_per_chunk=0.03))+ inbound = rig.drv.dm(f"stream with a trailing newline [in:{token}]")+ wait_reply(rig, inbound.chat_id, aid)+ barrier(rig, f"wsb-{tag}")+ shown = _shown(rig, inbound.chat_id, aid, "w")+ assert shown.count(head(aid)) == 1 and shown.count(foot(aid)) == 1, (+ f"a streamed reply ending in whitespace is shown != once: {shown[:400]!r}\n{rig.ctx()}")+++# 6. the platform redelivers the same inbound -> one reply (#119848 pattern) -----------------------+def redelivered_inbound_gets_one_reply(rig: Rig, tag: str) -> None:+ token, aid = f"re-{tag}", f"A-re-{tag}"+ rig.director.script(token, answer(aid, "first and only"), answer(f"{aid}-dup", "DUPLICATE"))+ inbound = rig.drv.dm(f"once please [in:{token}]")+ wait_reply(rig, inbound.chat_id, aid)+ rig.drv.redeliver(inbound)+ barrier(rig, f"reb-{tag}")+ assert turns(rig, token) == 1, f"redelivered inbound started {turns(rig, token)} turns\n{rig.ctx()}"+ assert not copies(rig.drv.visible(inbound.chat_id), f"{aid}-dup"), "a duplicate reply was sent"+ assert len(copies(rig.drv.visible(inbound.chat_id), aid)) == 1, rig.ctx()+++# 7. approval button click: allowlisted user accepted, stranger refused ----------------------------+def _approve_button(rig: Rig, chat_id: str) -> Dict[str, Any]:+ def pick() -> Any:+ for b in rig.drv.buttons(chat_id):+ label = str(b.get("text") or b.get("label") or "")+ if re.search(r"once", label, re.I):+ return b+ return None+ return wait_until(pick, "an approve-once button under the approval prompt", timeout=TURN_TIMEOUT,+ on_timeout=rig.ctx)+++def approval_click_by_allowlisted_user_runs_command(rig: Rig, tag: str, victim: Path) -> None:+ token, aid = f"ap-{tag}", f"A-ap-{tag}"+ victim.mkdir(parents=True, exist_ok=True)+ (victim / "f.txt").write_text("x")+ rig.director.script(token, ToolCall("terminal", {"command": f"rm -rf {victim}"}), answer(aid, "cleaned"))+ inbound = rig.drv.dm(f"clean up [in:{token}]")+ button = _approve_button(rig, inbound.chat_id)+ assert victim.exists(), "dangerous command ran before approval"+ rig.drv.click(inbound.chat_id, button, user_id=rig.drv.other_user_id) # a stranger first+ rig.drv.click(inbound.chat_id, button)+ wait_reply(rig, inbound.chat_id, aid, "turn completed after the approval click")+ assert not victim.exists(), f"approved command did not run (click refused?)\n{rig.ctx()}"+++# 8. platform_toolsets / disabled_toolsets honored (#121089) --------------------------------------+def _offered_tools(rig: Rig, tag: str) -> set:+ token, aid = f"ts-{tag}", f"A-ts-{tag}"+ rig.director.script(token, answer(aid, "tools checked"))+ inbound = rig.drv.dm(f"what tools [in:{token}]")+ wait_reply(rig, inbound.chat_id, aid)+ req = rig.director.requests[token][0]+ names = {t.get("function", {}).get("name") for t in req.get("tools") or []}+ assert names, "the model request carried no tools at all"+ return names+++def platform_toolsets_are_honored(rig: Rig, tag: str) -> None:+ """``platform_toolsets.<platform>: [file]``: the file tools, and never the terminal."""+ names = _offered_tools(rig, tag)+ assert "read_file" in names, f"the configured toolset (file) is missing: {sorted(names)}"+ assert "terminal" not in names, f"terminal offered although platform_toolsets omits it: {sorted(names)}"+++def disabled_toolsets_are_honored(rig: Rig, tag: str) -> None:+ """``agent.disabled_toolsets: [web]``: web tools gone, the rest of the platform preset kept."""+ names = _offered_tools(rig, tag)+ assert "terminal" in names, f"control: the platform preset lost terminal: {sorted(names)}"+ web = sorted(n for n in names if n.startswith("web_"))+ assert not web, f"disabled toolset 'web' still offered: {web}"+++def merge(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:+ out = dict(a)+ for k, v in b.items():+ out[k] = merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v+ return out+++# 9. inbound photo sent as a file (HEIC) reaches the agent as an image (#119593) -------------------+def _image(fmt: str) -> bytes:+ from PIL import Image++ img = Image.new("RGB", (32, 32), (200, 30, 30))+ buf = io.BytesIO()+ if fmt == "HEIF":+ import pillow_heif++ pillow_heif.register_heif_opener()+ img.save(buf, format=fmt)+ return buf.getvalue()+++def _model_saw_image(req: dict) -> bool:+ for m in req.get("messages", []):+ content = m.get("content")+ if isinstance(content, list) and any(p.get("type") in ("image_url", "input_image") for p in content+ if isinstance(p, dict)):+ return True+ return False+++def heic_document_reaches_agent_as_image(rig: Rig, tag: str) -> None:+ got: Dict[str, bool] = {}+ for fmt, name, mime in (("PNG", "control.png", "image/png"), ("HEIF", "IMG_0001.HEIC", "image/heic")):+ token, aid = f"img-{fmt}-{tag}", f"A-img-{fmt}-{tag}"+ rig.director.script(token, answer(aid, "saw it"))+ inbound = rig.drv.document(name, _image(fmt), mime, caption=f"look [in:{token}]")+ try:+ wait_reply(rig, inbound.chat_id, aid, timeout=30)+ except AssertionError:+ got[fmt] = False # the photo never started a turn at all+ continue+ got[fmt] = _model_saw_image(rig.director.requests[token][0])+ log = rig.gw.grep(r"image|attach|heic|png|cache")+ assert got["PNG"], f"control: a PNG sent as a file did not reach the model as an image\n{log}\n{rig.ctx()}"+ assert got["HEIF"], f"a HEIC photo sent as a file did not reach the model as an image\n{log}"+++# 10. planned restart: notice delivered once; a redelivered /restart does not loop ----------------+def planned_restart_notice_once(rig: Rig, tag: str, restart: Callable[[], None]) -> None:+ inbound = rig.drv.dm("/restart")+ wait_until(lambda: not rig.gw.alive(), "gateway exits for the planned restart", timeout=TURN_TIMEOUT,+ on_timeout=rig.ctx)+ rc = rig.gw.proc.returncode if rig.gw.proc else None+ assert rc == 75, f"planned restart under a supervisor must exit 75 (got {rc})\n{rig.gw.tail()}"+ reborn = time.monotonic()+ restart() # what the supervisor does on exit 75++ def notices() -> List[str]:+ texts = [str(c.params.get("text") or c.params.get("content") or c.params) for c in rig.drv.sends(inbound.chat_id)+ if c.at > reborn]+ return [t for t in texts if "restart" in t.lower() and "<<" not in norm(t)] # not a scripted reply++ wait_until(notices, "restart notice after the gateway came back", timeout=TURN_TIMEOUT, on_timeout=rig.ctx)+ rig.drv.redeliver(inbound) # the pre-restart /restart replayed (lost ack on the way out)+ bid = f"B-rsb-{tag}"+ rig.director.script(f"rsb-{tag}", answer(bid, "barrier"))+ probe = rig.drv.dm(f"barrier [in:rsb-{tag}]")+ wait_until(lambda: complete(rig.drv.visible(probe.chat_id), bid) or not rig.gw.alive(),+ "barrier answered (or the gateway went down again)", timeout=TURN_TIMEOUT, on_timeout=rig.ctx)+ assert rig.gw.alive(), f"a redelivered /restart restarted the gateway again\n{rig.ctx()}"+ assert len(notices()) == 1, (f"expected exactly one restart notice from the new process, got "+ f"{notices()} (a second restart ack means the replayed /restart was obeyed)\n{rig.ctx()}")diff --git a/tests/e2e/core/platforms/_drv_discord.py b/tests/e2e/core/platforms/_drv_discord.pyindex 29821c36025..65e186c33ba 100644--- a/tests/e2e/core/platforms/_drv_discord.py+++ b/tests/e2e/core/platforms/_drv_discord.py@@ -133,5 +133,7 @@ class DiscordDriver:self.standin.fail("create_message", {"message": "Missing Access", "code": 50001},status=403, times=times, match=pred)- def fail_edit(self, *, times: int = 1) -> None:- self.standin.fail("edit_message", {"message": "Unknown Message", "code": 10008}, status=404, times=times)+ def fail_edit(self, *, times: int = 1, match: Optional[Callable[[str], bool]] = None) -> None:+ pred = (lambda p: match(str(p.get("content", "")))) if match else None+ self.standin.fail("edit_message", {"message": "Unknown Message", "code": 10008}, status=404, times=times,+ match=pred)diff --git a/tests/e2e/core/platforms/_drv_slack.py b/tests/e2e/core/platforms/_drv_slack.pyindex 952435c4f75..b953b9fa075 100644--- a/tests/e2e/core/platforms/_drv_slack.py+++ b/tests/e2e/core/platforms/_drv_slack.py@@ -121,5 +121,7 @@ class SlackDriver:pred = (lambda p: match(str(p.get("text", "")))) if match else Noneself.standin.fail("chat.postMessage", {"ok": False, "error": "channel_not_found"}, times=times, match=pred)- def fail_edit(self, *, times: int = 1) -> None:- self.standin.fail("chat.update", {"ok": False, "error": "cant_update_message"}, times=times)+ def fail_edit(self, *, times: int = 1, match: Optional[Callable[[str], bool]] = None) -> None:+ pred = (lambda p: match(str(p.get("text", "")) + str(p.get("markdown_text", "")))) if match else None+ for method in ("chat.update", "chat.appendStream", "chat.stopStream"):+ self.standin.fail(method, {"ok": False, "error": "cant_update_message"}, times=times, match=pred)diff --git a/tests/e2e/core/platforms/_drv_telegram.py b/tests/e2e/core/platforms/_drv_telegram.pyindex 4608d125ab6..3703c7b00e7 100644--- a/tests/e2e/core/platforms/_drv_telegram.py+++ b/tests/e2e/core/platforms/_drv_telegram.py@@ -111,7 +111,8 @@ class TelegramDriver:"description": "Bad Request: chat not found"},status=400, times=times, match=pred)- def fail_edit(self, *, times: int = 1) -> None:+ def fail_edit(self, *, times: int = 1, match: Optional[Callable[[str], bool]] = None) -> None:+ pred = (lambda p: match(str(p.get("text", "")))) if match else Noneself.standin.fail("editMessageText", {"ok": False, "error_code": 400,"description": "Bad Request: message can't be edited"},- status=400, times=times)+ status=400, times=times, match=pred)diff --git a/tests/e2e/core/platforms/_helpers.py b/tests/e2e/core/platforms/_helpers.pyindex 55f36e7444e..a3a3d0c8759 100644--- a/tests/e2e/core/platforms/_helpers.py+++ b/tests/e2e/core/platforms/_helpers.py@@ -45,11 +45,15 @@ def hermetic_env(home: Path, extra: Optional[Dict[str, str]] = None) -> Dict[strif not (k.endswith(_STRIP_SUFFIXES) or k.startswith(_STRIP_PREFIXES))}for var in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy","XDG_STATE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME",- "DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR", "NOTIFY_SOCKET", "INVOCATION_ID"):+ "DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR", "NOTIFY_SOCKET", "INVOCATION_ID",+ "PYTEST_CURRENT_TEST"):env.pop(var, None)+ extra = dict(extra or {})+ shim = extra.pop("PYTHONPATH_PREPEND", "")env.update(HOME=str(home), HERMES_HOME=str(home / ".hermes"), XDG_STATE_HOME=str(home / ".local" / "state"),- PYTHONPATH=os.pathsep.join(p for p in (str(REPO_ROOT), (extra or {}).pop("PYTHONPATH_PREPEND", "")) if p),+ # a stand-in's sitecustomize shim (if any) first, then the checkout under test+ PYTHONPATH=os.pathsep.join(p for p in (shim, str(REPO_ROOT)) if p),NO_COLOR="1", TERM="dumb", NO_PROXY="127.0.0.1,localhost", no_proxy="127.0.0.1,localhost",HERMES_STATE_DB_GUARD_BYPASS="1", HERMES_DISABLE_LAZY_INSTALLS="1", TZ="UTC", PYTHONUNBUFFERED="1",TIRITH_ENABLED="false", AWS_EC2_METADATA_DISABLED="true",@@ -106,10 +110,13 @@ class GatewayUnderTest:self.log_path = root / "gateway.log"self._env = dict(env)self._ready = ready- base = {"updates": {"check": False}, "approvals": {"destructive_slash_confirm": False}}- merged = _deep_merge(base, config)- write_hermes_home(self.hermes_home, llm_base_url,- extra_config=yaml.safe_dump(merged, sort_keys=False))+ # approvals.mode manual: a dangerous command waits for a human click (``smart`` would ask the+ # fake model to judge it).+ base = {"updates": {"check": False},+ "approvals": {"mode": "manual", "destructive_slash_confirm": False}}+ cfg_path = write_hermes_home(self.hermes_home, llm_base_url) / "config.yaml"+ merged = _deep_merge(_deep_merge(yaml.safe_load(cfg_path.read_text()), base), config)+ cfg_path.write_text(yaml.safe_dump(merged, sort_keys=False), encoding="utf-8")self.proc: Optional[subprocess.Popen] = Noneself.pids: List[int] = []@@ -164,6 +171,15 @@ class GatewayUnderTest:except OSError:return "--- (no gateway log)"+ def grep(self, pattern: str, limit: int = 30) -> str:+ """Gateway log lines matching ``pattern`` (case-insensitive), for assertion context."""+ try:+ lines = self.log_path.read_text(errors="replace").splitlines()+ except OSError:+ return ""+ rx = re.compile(pattern, re.I)+ return "\n".join([ln for ln in lines if rx.search(ln)][-limit:])+def user_rows(self, needle: str) -> List[str]:if not self.db_path.exists():return []diff --git a/tests/e2e/core/platforms/_suite.py b/tests/e2e/core/platforms/_suite.pynew file mode 100644index 00000000000..8ecd78ddd14--- /dev/null+++ b/tests/e2e/core/platforms/_suite.py@@ -0,0 +1,124 @@+"""Binds the shared contract (``_contract.py``) to one adapter driver for a test module.++A test module declares ``KNOWN`` (scenario -> "#<issue> <symptom>") and gets:++* two module-scoped rigs: ``rig`` (the adapter's default delivery config, ``agent.disabled_toolsets:+ [web]``, supervisor-owned so ``/restart`` exits 75) and ``rig_stream`` (edit-streaming on,+ ``platform_toolsets.<platform>: [file]``);+* one parametrized ``test_contract`` over every scenario, KNOWN ones as ``xfail(strict=True)`` so+ a fix turns them red until the entry is removed.+"""++from __future__ import annotations++import os+from pathlib import Path+from typing import Any, Callable, Dict, List, Tuple++import pytest++from tests.e2e.core.platforms import _contract as C+from tests.e2e.core.platforms._helpers import Director, GatewayUnderTest+from tests.fakes.fake_llm_provider import FakeLLMServer++# scenario -> (rig fixture, runner(rig, tag, tmp_dir))+SCENARIOS: Dict[str, Tuple[str, Callable[..., None]]] = {+ "dm_one_reply": ("rig", lambda r, t, d: C.dm_gets_exactly_one_reply(r, t)),+ "group_require_mention": ("rig", lambda r, t, d: C.group_obeys_require_mention(r, t)),+ "long_reply_split": ("rig", lambda r, t, d: C.long_reply_is_split_in_order(r, t)),+ "failed_continuation": ("rig", lambda r, t, d: C.failed_continuation_is_retried_or_reported(r, t)),+ "redelivery_one_reply": ("rig", lambda r, t, d: C.redelivered_inbound_gets_one_reply(r, t)),+ "approval_click": ("rig", lambda r, t, d: C.approval_click_by_allowlisted_user_runs_command(+ r, t, d / "victim")),+ "disabled_toolsets": ("rig", lambda r, t, d: C.disabled_toolsets_are_honored(r, t)),+ "heic_as_image": ("rig", lambda r, t, d: C.heic_document_reaches_agent_as_image(r, t)),+ "stream_finalize_rejected": ("rig_stream", lambda r, t, d: C.rejected_finalize_leaves_one_copy(r, t)),+ "stream_trailing_whitespace": ("rig_stream",+ lambda r, t, d: C.streamed_reply_ending_in_whitespace_shown_once(r, t)),+ "platform_toolsets": ("rig_stream", lambda r, t, d: C.platform_toolsets_are_honored(r, t)),+ # last: it restarts the default rig's gateway+ "planned_restart_notice": ("rig", lambda r, t, d: C.planned_restart_notice_once(r, t, r.restart)),+}+++def scenario_params(known: Dict[str, str], skip: Dict[str, str] | None = None) -> List[Any]:+ out = []+ for name in SCENARIOS:+ marks = []+ if name in known:+ marks.append(pytest.mark.xfail(strict=True, reason=known[name]))+ if skip and name in skip:+ marks.append(pytest.mark.skip(reason=skip[name]))+ out.append(pytest.param(name, id=name, marks=marks))+ return out+++def run_scenario(name: str, request: pytest.FixtureRequest, tmp_path: Path) -> None:+ fixture, runner = SCENARIOS[name]+ rig = request.getfixturevalue(fixture)+ assert rig.gw.alive(), f"gateway died before {name}\n{rig.gw.tail()}"+ runner(rig, name.replace("_", ""), tmp_path)+++class _RestartableRig(C.Rig):+ def restart(self) -> None:+ self.gw.stop()+ self.gw.start()+++def _short_root(factory: pytest.TempPathFactory, name: str) -> Path:+ # The gateway binds an AF_UNIX tick socket under its home: keep the path well under 108 bytes.+ return factory.mktemp(name)+++def rig_fixtures(driver_cls: type) -> Tuple[Any, Any]:+ """``(rig, rig_stream)`` module-scoped fixtures for ``driver_cls``."""++ def _make(factory: pytest.TempPathFactory, label: str, extra_cfg: Dict[str, Any], extra_env: Dict[str, str]):+ drv = driver_cls()+ drv.start()+ director = Director()+ llm = FakeLLMServer(director)+ llm.start()+ cfg = C.merge(drv.gateway_config(), extra_cfg)+ gw = GatewayUnderTest(_short_root(factory, f"{drv.name[:2]}{label}"), llm_base_url=llm.base_url,+ config=cfg, env={**drv.gateway_env(), **extra_env}, ready=drv.connected)+ rig = _RestartableRig(gw=gw, drv=drv, director=director, llm=llm)+ try:+ gw.start()+ except BaseException:+ gw.stop()+ llm.stop()+ drv.stop()+ raise+ return rig++ def _teardown(rig: C.Rig) -> None:+ rig.gw.stop()+ for pid in rig.gw.pids:+ try:+ os.kill(pid, 9)+ except (ProcessLookupError, PermissionError):+ pass+ rig.llm.stop()+ rig.drv.stop()++ @pytest.fixture(scope="module")+ def rig(tmp_path_factory: pytest.TempPathFactory):+ r = _make(tmp_path_factory, "a", {"agent": {"disabled_toolsets": ["web"]}},+ {"HERMES_GATEWAY_EXTERNAL_SUPERVISOR": "1"})+ yield r+ _teardown(r)++ @pytest.fixture(scope="module")+ def rig_stream(tmp_path_factory: pytest.TempPathFactory):+ name = driver_cls.name+ r = _make(tmp_path_factory, "b", {+ "streaming": {"enabled": True, "edit_interval": 0.3},+ "display": {"platforms": {name: {"streaming": True}}},+ "platform_toolsets": {name: ["file"]},+ }, {})+ yield r+ _teardown(r)++ return rig, rig_streamdiff --git a/tests/e2e/core/platforms/test_discord_contract.py b/tests/e2e/core/platforms/test_discord_contract.pynew file mode 100644index 00000000000..980470d789a--- /dev/null+++ b/tests/e2e/core/platforms/test_discord_contract.py@@ -0,0 +1,37 @@+"""Messaging-adapter contract, Discord leg: the REAL gateway + REAL ``plugins/platforms/discord`` adapter.++The child is ``hermes gateway run`` on a throwaway HOME; the adapter's own SDK (discord.py via the ``discord_shim`` sitecustomize) talks to+``tests/fakes/platforms/discord_standin.py``, a local stand-in shaped per the platform's published+API. Scenarios live in ``_contract.py`` and are identical for every adapter; this file only binds the+Discord driver and lists the scenarios that are red on main (``KNOWN``, strict xfail: a fix turns+the entry red until it is removed).+"""++from __future__ import annotations++import sys++import pytest++from tests.e2e.core.platforms._drv_discord import DiscordDriver+from tests.e2e.core.platforms._suite import rig_fixtures, run_scenario, scenario_params++pytestmark = [+ pytest.mark.spawns_gateway_lookalike,+ pytest.mark.skipif(sys.platform == "win32", reason="POSIX process-group gateway harness"),+]++KNOWN: dict[str, str] = {+ "planned_restart_notice": "#121325 a replayed /restart restarts the gateway again (guard needs Telegram update ids)",+}+SKIP: dict[str, str] = {+ "heic_as_image": "image attachments are fetched by URL behind the SSRF guard, which refuses the loopback "+ "stand-in's CDN URL (a real cdn.discordapp.com URL passes)",+}++rig, rig_stream = rig_fixtures(DiscordDriver)++[email protected]("scenario", scenario_params(KNOWN, SKIP))+def test_contract(scenario: str, request: pytest.FixtureRequest, tmp_path) -> None:+ run_scenario(scenario, request, tmp_path)diff --git a/tests/e2e/core/platforms/test_slack_contract.py b/tests/e2e/core/platforms/test_slack_contract.pynew file mode 100644index 00000000000..df3d6389a29--- /dev/null+++ b/tests/e2e/core/platforms/test_slack_contract.py@@ -0,0 +1,38 @@+"""Messaging-adapter contract, Slack leg: the REAL gateway + REAL ``plugins/platforms/slack`` adapter.++The child is ``hermes gateway run`` on a throwaway HOME; the adapter's own SDK (slack_bolt Socket Mode + slack_sdk via the ``slack_shim`` sitecustomize) talks to+``tests/fakes/platforms/slack_standin.py``, a local stand-in shaped per the platform's published+API. Scenarios live in ``_contract.py`` and are identical for every adapter; this file only binds the+Slack driver and lists the scenarios that are red on main (``KNOWN``, strict xfail: a fix turns+the entry red until it is removed).+"""++from __future__ import annotations++import sys++import pytest++from tests.e2e.core.platforms._drv_slack import SlackDriver+from tests.e2e.core.platforms._suite import rig_fixtures, run_scenario, scenario_params++pytestmark = [+ pytest.mark.spawns_gateway_lookalike,+ pytest.mark.skipif(sys.platform == "win32", reason="POSIX process-group gateway harness"),+]++KNOWN: dict[str, str] = {+ "stream_trailing_whitespace": "#121326 native streaming re-posts the whole reply when it ends in whitespace",+ "planned_restart_notice": "#121325 a replayed /restart restarts the gateway again (guard needs Telegram update ids)",+}+SKIP: dict[str, str] = {+ "heic_as_image": "the adapter only downloads https://*.slack.com file URLs (SSRF guard); a loopback "+ "stand-in cannot serve one",+}++rig, rig_stream = rig_fixtures(SlackDriver)++[email protected]("scenario", scenario_params(KNOWN, SKIP))+def test_contract(scenario: str, request: pytest.FixtureRequest, tmp_path) -> None:+ run_scenario(scenario, request, tmp_path)diff --git a/tests/e2e/core/platforms/test_telegram_contract.py b/tests/e2e/core/platforms/test_telegram_contract.pynew file mode 100644index 00000000000..62214238995--- /dev/null+++ b/tests/e2e/core/platforms/test_telegram_contract.py@@ -0,0 +1,34 @@+"""Messaging-adapter contract, Telegram leg: the REAL gateway + REAL ``plugins/platforms/telegram`` adapter.++The child is ``hermes gateway run`` on a throwaway HOME; the adapter's own SDK (python-telegram-bot via ``extra.base_url``) talks to+``tests/fakes/platforms/telegram_standin.py``, a local stand-in shaped per the platform's published+API. Scenarios live in ``_contract.py`` and are identical for every adapter; this file only binds the+Telegram driver and lists the scenarios that are red on main (``KNOWN``, strict xfail: a fix turns+the entry red until it is removed).+"""++from __future__ import annotations++import sys++import pytest++from tests.e2e.core.platforms._drv_telegram import TelegramDriver+from tests.e2e.core.platforms._suite import rig_fixtures, run_scenario, scenario_params++pytestmark = [+ pytest.mark.spawns_gateway_lookalike,+ pytest.mark.skipif(sys.platform == "win32", reason="POSIX process-group gateway harness"),+]++KNOWN: dict[str, str] = {+ "heic_as_image": "#119593 HEIC photo sent as a file is refused by the image cache (never reaches the model)",+}+SKIP: dict[str, str] = {}++rig, rig_stream = rig_fixtures(TelegramDriver)++[email protected]("scenario", scenario_params(KNOWN, SKIP))+def test_contract(scenario: str, request: pytest.FixtureRequest, tmp_path) -> None:+ run_scenario(scenario, request, tmp_path)