The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: stand-in Telegram/Discord/Slack platform servers + drivers for the adapter contract suite
teknium1f0c96c3ba1b0
diff --git a/tests/e2e/core/platforms/__init__.py b/tests/e2e/core/platforms/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/platforms/_drv_discord.py b/tests/e2e/core/platforms/_drv_discord.pynew file mode 100644index 00000000000..29821c36025--- /dev/null+++ b/tests/e2e/core/platforms/_drv_discord.py@@ -0,0 +1,137 @@+"""Discord driver for the adapter contract: binds the shared contract to ``DiscordStandin``.++Same surface as ``_drv_telegram.TelegramDriver``. Discord specifics:++* a DM lives in its own DM channel (id != user id). ``dm()`` returns ``Inbound.chat_id`` = that DM+ channel id; ``visible()/sends()/edits()/buttons()`` also accept the user id and map it to the DM.+* the child gateway reaches the stand-in through ``tests/fakes/platforms/discord_shim`` (a+ ``sitecustomize`` on ``PYTHONPATH`` that repoints discord.py's ``Route.BASE``/``DEFAULT_GATEWAY``).+* ``connected()`` is true once the adapter finished ``on_ready`` post-connect work: the bulk slash+ command sync (``PUT /applications/{id}/commands``) only runs after ``_ready_event`` is set.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional++from tests.fakes.platforms._standin import Call, Visible+from tests.fakes.platforms.discord_standin import BOT_ID, MAX_TEXT, DiscordStandin++SHIM_DIR = Path(__file__).resolve().parents[3] / "fakes" / "platforms" / "discord_shim"+++@dataclass+class Inbound:+ chat_id: str+ message_id: str+ raw: Any+++class DiscordDriver:+ name = "discord"+ limit = MAX_TEXT+ bot_id = BOT_ID+ user_id = "200000000000000111"+ other_user_id = "200000000000000222"+ group_chat_id = "1300000000000000001" # #general in the stand-in guild+ home_channel = "1300000000000000002" # #home in the stand-in guild++ def __init__(self) -> None:+ self.standin = DiscordStandin()+ self.standin.add_text_channel(self.group_chat_id, "general")+ self.standin.add_text_channel(self.home_channel, "home")+ for uid in (self.user_id, self.other_user_id):+ self.standin.user(uid)["_in_guild"] = True++ def start(self) -> None:+ self.standin.start()++ def stop(self) -> None:+ self.standin.stop()++ def gateway_config(self) -> Dict[str, Any]:+ return {"platforms": {"discord": {"enabled": True, "extra": {+ "require_mention": True,+ # replies land inline in the group channel (contract parity); threads are implemented too+ "auto_thread": False,+ }}}}++ def gateway_env(self) -> Dict[str, str]:+ return {+ "DISCORD_BOT_TOKEN": self.standin.token, "DISCORD_ALLOWED_USERS": self.user_id,+ "DISCORD_HOME_CHANNEL": self.home_channel,+ # one PUT instead of ~100 paced POSTs (safe policy sleeps 4.5 s per mutation)+ "DISCORD_COMMAND_SYNC_POLICY": "bulk",+ # no text-batch debounce: one inbound is one turn, immediately+ "DISCORD_TEXT_BATCH_DELAY_SECONDS": "0", "DISCORD_TEXT_BATCH_SPLIT_DELAY_SECONDS": "0",+ "HERMES_STANDIN_DISCORD_API": self.standin.api_base,+ "HERMES_STANDIN_DISCORD_GATEWAY": self.standin.gateway_url,+ "PYTHONPATH_PREPEND": str(SHIM_DIR),+ }++ def connected(self) -> bool:+ return bool(self.standin.sessions() and self.standin.calls_of("bulk_commands"))++ # inbound -----------------------------------------------------------------------------------+ def _chat(self, chat_id: Any) -> str:+ return self.standin.dm_of_user.get(str(chat_id), str(chat_id))++ @staticmethod+ def _wrap(payload: Dict[str, Any]) -> Inbound:+ return Inbound(str(payload["channel_id"]), str(payload["id"]), payload)++ def dm(self, text: str, user_id: Optional[str] = None) -> Inbound:+ uid = str(user_id or self.user_id)+ channel = self.standin.dm_channel(uid)+ return self._wrap(self.standin.inbound_message(channel["id"], uid, text))++ def group(self, text: str, *, mention: bool) -> Inbound:+ content, mentions = (f"<@{BOT_ID}> {text}", [BOT_ID]) if mention else (text, [])+ return self._wrap(self.standin.inbound_message(self.group_chat_id, self.user_id, content, mentions=mentions))++ def redeliver(self, inbound: Inbound) -> None:+ self.standin.redeliver(inbound.raw)++ def document(self, filename: str, data: bytes, mime: str, caption: str = "") -> Inbound:+ channel = self.standin.dm_channel(self.user_id)+ att = self.standin.attachment(filename, data, mime)+ return self._wrap(self.standin.inbound_message(channel["id"], self.user_id, caption, attachments=[att]))++ def buttons(self, chat_id: str) -> List[Dict[str, Any]]:+ return self.standin.buttons(self._chat(chat_id))++ def click(self, chat_id: str, button: Dict[str, Any], user_id: Optional[str] = None) -> None:+ self.standin.click(str(user_id or self.user_id), self._chat(chat_id), str(button["message_id"]),+ button["custom_id"], component_type=int(button.get("type") or 2))++ def callback_answers(self) -> List[Call]:+ return self.standin.calls_of("interaction_callback")++ # ground truth ------------------------------------------------------------------------------+ def visible(self, chat_id: str) -> List[Visible]:+ return self.standin.visible(self._chat(chat_id))++ def _ok(self, methods: tuple, chat_id: str) -> List[Call]:+ chat = self._chat(chat_id)+ return [c for c in self.standin.calls_of(*methods)+ if not c.faulted and str(c.params.get("channel_id")) == chat]++ def sends(self, chat_id: str) -> List[Call]:+ return self._ok(("create_message",), chat_id)++ def edits(self, chat_id: str) -> List[Call]:+ return self._ok(("edit_message",), chat_id)++ def describe(self) -> str:+ return self.standin.describe()++ # faults ------------------------------------------------------------------------------------+ def fail_send(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("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)diff --git a/tests/e2e/core/platforms/_drv_slack.py b/tests/e2e/core/platforms/_drv_slack.pynew file mode 100644index 00000000000..952435c4f75--- /dev/null+++ b/tests/e2e/core/platforms/_drv_slack.py@@ -0,0 +1,125 @@+"""Slack driver for the adapter contract: binds the shared contract to ``SlackStandin``.++Same surface as ``_drv_telegram.TelegramDriver`` (see its docstring). The child gateway runs the real+``plugins/platforms/slack`` adapter (slack_bolt Socket Mode + slack_sdk Web API); the+``slack_shim/sitecustomize.py`` module on the child's ``PYTHONPATH`` points slack_sdk at the stand-in+(``HERMES_STANDIN_SLACK_API``). Chat ids are Slack channel ids: DMs are ``D<user>``, the group is a+public channel ``C…``. Message ids are Slack ``ts`` strings.++Known limits: ``document()`` delivers a real ``file_share`` event, but the adapter (by design) only+downloads ``https://*.slack.com`` URLs that pass the SSRF guard, so the stand-in's 127.0.0.1 file URL+is refused (logged "Blocked unsafe Slack file URL") and the turn runs on the caption alone. Replies are+threaded under the inbound ts (``reply_in_thread`` default), including DMs. ``sends()`` counts+``chat.startStream`` too: with ``streaming.enabled`` the adapter streams natively+(startStream/appendStream/stopStream) instead of postMessage + chat.update.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional++from tests.fakes.platforms._standin import Call, Visible+from tests.fakes.platforms.slack_standin import SlackStandin++_SHIM = Path(__file__).resolve().parents[3] / "fakes" / "platforms" / "slack_shim"+++@dataclass+class Inbound:+ chat_id: str+ message_id: str+ raw: Any+++class SlackDriver:+ name = "slack"+ limit = 39_000 # SlackAdapter.MAX_MESSAGE_LENGTH (Slack rejects > 40,000 with msg_too_long)+ user_id = "U0000111"+ other_user_id = "U0000222"+ group_chat_id = "C0000123"+ home_channel = "C0000999"++ def __init__(self) -> None:+ self.standin = SlackStandin()++ def start(self) -> None:+ self.standin.start()++ def stop(self) -> None:+ self.standin.stop()++ def gateway_config(self) -> Dict[str, Any]:+ return {"platforms": {"slack": {"enabled": True, "extra": {"require_mention": True}}}}++ def gateway_env(self) -> Dict[str, str]:+ return {"SLACK_BOT_TOKEN": self.standin.bot_token, "SLACK_APP_TOKEN": self.standin.app_token,+ "SLACK_ALLOWED_USERS": self.user_id, "SLACK_HOME_CHANNEL": self.home_channel,+ "HERMES_STANDIN_SLACK_API": self.standin.api_base, "PYTHONPATH_PREPEND": str(_SHIM)}++ def connected(self) -> bool:+ # auth.test proves the shim redirected the SDK; an open socket proves Socket Mode is live.+ return bool(self.standin.calls_of("auth.test")) and self.standin.socket_count() > 0++ # inbound -----------------------------------------------------------------------------------+ @staticmethod+ def _wrap(envelope: Dict[str, Any]) -> Inbound:+ event = envelope["payload"]["event"]+ return Inbound(event["channel"], event["ts"], envelope)++ def dm(self, text: str, user_id: Optional[str] = None) -> Inbound:+ return self._wrap(self.standin.dm(user_id or self.user_id, text))++ def group(self, text: str, *, mention: bool) -> Inbound:+ envelopes = self.standin.channel_post(self.group_chat_id, self.user_id, text, mention=mention)+ return self._wrap(envelopes[0])++ def redeliver(self, inbound: Inbound) -> None:+ self.standin.redeliver(inbound.raw)++ def document(self, filename: str, data: bytes, mime: str, caption: str = "") -> Inbound:+ return self._wrap(self.standin.dm_file(self.user_id, filename, data, mime, caption))++ def buttons(self, chat_id: str) -> List[Dict[str, Any]]:+ return self.standin.buttons(chat_id)++ def click(self, chat_id: str, button: Dict[str, Any], user_id: Optional[str] = None) -> None:+ self.standin.block_action(user_id or self.user_id, chat_id, str(button["message_id"]), button)++ def slash(self, command: str, text: str = "", chat_id: Optional[str] = None) -> Dict[str, Any]:+ return self.standin.slash(self.user_id, chat_id or self.standin.dm_channel(self.user_id), command, text)++ def callback_answers(self) -> List[Call]:+ """Socket Mode acks for interactive envelopes (Slack's analogue of answerCallbackQuery)."""+ ids = {e["envelope_id"] for e in self.standin.envelopes if e["type"] == "interactive"}+ return [c for c in self.standin.calls_of("socket_ack") if c.params.get("envelope_id") in ids]++ # ground truth ------------------------------------------------------------------------------+ def visible(self, chat_id: str) -> List[Visible]:+ return self.standin.visible(chat_id)++ def ephemerals(self, chat_id: str) -> List[Dict[str, Any]]:+ """Replies only the invoking user sees (slash ``response_url`` POSTs, chat.postEphemeral)."""+ return self.standin.ephemerals(chat_id)++ def _ok(self, methods: tuple, chat_id: str) -> List[Call]:+ return [c for c in self.standin.calls_of(*methods)+ if not c.faulted and str(c.params.get("channel")) == str(chat_id)]++ def sends(self, chat_id: str) -> List[Call]:+ return self._ok(("chat.postMessage", "chat.startStream"), chat_id)++ def edits(self, chat_id: str) -> List[Call]:+ return self._ok(("chat.update", "chat.appendStream"), chat_id)++ def describe(self) -> str:+ return self.standin.describe()++ # faults ------------------------------------------------------------------------------------+ def fail_send(self, *, times: int = 1, match: Optional[Callable[[str], bool]] = None) -> None:+ pred = (lambda p: match(str(p.get("text", "")))) if match else None+ self.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)diff --git a/tests/e2e/core/platforms/_drv_telegram.py b/tests/e2e/core/platforms/_drv_telegram.pynew file mode 100644index 00000000000..4608d125ab6--- /dev/null+++ b/tests/e2e/core/platforms/_drv_telegram.py@@ -0,0 +1,117 @@+"""Telegram driver for the adapter contract: binds the shared contract to ``TelegramStandin``.++Every adapter driver exposes the same surface (see ``_contract.py``):++* ``name``, ``limit`` (the platform text cap the adapter must split at), ``user_id`` (allowlisted)+* ``start()/stop()`` the stand-in, ``gateway_config()``/``gateway_env()`` for the child, ``connected()``+* inbound: ``dm(text)``, ``group(text, mention=)``, ``redeliver(inbound)``, ``document(...)``,+ ``click(inbound_chat, button)``+* ground truth: ``visible(chat_id)`` (bot messages a human sees now), ``sends(chat_id)`` /+ ``edits(chat_id)`` (successful outbound create/edit calls), ``describe()``+* faults: ``fail_send(match=, times=)`` / ``fail_edit(times=)`` make the platform reject the call+ with its documented error body.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Callable, Dict, List, Optional++from tests.fakes.platforms._standin import Call, Visible+from tests.fakes.platforms.telegram_standin import MAX_TEXT, TelegramStandin+++@dataclass+class Inbound:+ chat_id: str+ message_id: str+ raw: Any+++class TelegramDriver:+ name = "telegram"+ limit = MAX_TEXT+ user_id = "111"+ other_user_id = "222"+ group_chat_id = "-1001234567890"+ home_channel = "999"++ def __init__(self) -> None:+ self.standin = TelegramStandin()++ def start(self) -> None:+ self.standin.start()++ def stop(self) -> None:+ self.standin.stop()++ def gateway_config(self) -> Dict[str, Any]:+ return {"platforms": {"telegram": {"enabled": True, "extra": {+ "base_url": self.standin.api_base, "base_file_url": self.standin.file_base,+ "require_mention": True,+ }}}}++ def gateway_env(self) -> Dict[str, str]:+ return {"TELEGRAM_BOT_TOKEN": self.standin.token, "TELEGRAM_ALLOWED_USERS": self.user_id,+ "TELEGRAM_HOME_CHANNEL": self.home_channel, "HERMES_TELEGRAM_DISABLE_FALLBACK_IPS": "1",+ # no text-batch debounce: one inbound is one turn, immediately+ "HERMES_TELEGRAM_TEXT_BATCH_DELAY_SECONDS": "0", "HERMES_TELEGRAM_TEXT_BATCH_SPLIT_DELAY_SECONDS": "0"}++ def connected(self) -> bool:+ return bool(self.standin.calls_of("getUpdates"))++ # inbound -----------------------------------------------------------------------------------+ def _wrap(self, update: Dict[str, Any]) -> Inbound:+ msg = update["message"]+ return Inbound(str(msg["chat"]["id"]), str(msg["message_id"]), update)++ def dm(self, text: str, user_id: Optional[str] = None) -> Inbound:+ return self._wrap(self.standin.dm(int(user_id or self.user_id), text))++ def group(self, text: str, *, mention: bool) -> Inbound:+ return self._wrap(self.standin.group(int(self.group_chat_id), int(self.user_id), text, mention=mention))++ def redeliver(self, inbound: Inbound) -> None:+ self.standin.redeliver(inbound.raw)++ def document(self, filename: str, data: bytes, mime: str, caption: str = "") -> Inbound:+ return self._wrap(self.standin.dm_document(int(self.user_id), filename, data, mime, caption))++ def buttons(self, chat_id: str) -> List[Dict[str, Any]]:+ return self.standin.buttons(chat_id)++ def click(self, chat_id: str, button: Dict[str, Any], user_id: Optional[str] = None) -> None:+ self.standin.callback(int(user_id or self.user_id), int(chat_id), int(button["message_id"]),+ button["callback_data"])++ def callback_answers(self) -> List[Call]:+ return self.standin.calls_of("answerCallbackQuery")++ # ground truth ------------------------------------------------------------------------------+ def visible(self, chat_id: str) -> List[Visible]:+ return self.standin.visible(chat_id)++ def _ok(self, methods: tuple, chat_id: str) -> List[Call]:+ return [c for c in self.standin.calls_of(*methods)+ if not c.faulted and str(c.params.get("chat_id")) == str(chat_id)]++ def sends(self, chat_id: str) -> List[Call]:+ return self._ok(("sendMessage",), chat_id)++ def edits(self, chat_id: str) -> List[Call]:+ return self._ok(("editMessageText",), chat_id)++ def describe(self) -> str:+ return self.standin.describe()++ # faults ------------------------------------------------------------------------------------+ def fail_send(self, *, times: int = 1, match: Optional[Callable[[str], bool]] = None) -> None:+ pred = (lambda p: match(str(p.get("text", "")))) if match else None+ self.standin.fail("sendMessage", {"ok": False, "error_code": 400,+ "description": "Bad Request: chat not found"},+ status=400, times=times, match=pred)++ def fail_edit(self, *, times: int = 1) -> None:+ self.standin.fail("editMessageText", {"ok": False, "error_code": 400,+ "description": "Bad Request: message can't be edited"},+ status=400, times=times)diff --git a/tests/e2e/core/platforms/_helpers.py b/tests/e2e/core/platforms/_helpers.pynew file mode 100644index 00000000000..55f36e7444e--- /dev/null+++ b/tests/e2e/core/platforms/_helpers.py@@ -0,0 +1,182 @@+"""Harness for the messaging-adapter contract suite.++``GatewayUnderTest`` runs the REAL ``hermes gateway run`` (``python -m hermes_cli.main gateway run``)+in a child process on a throwaway HOME/HERMES_HOME, with the real platform adapter plugin loaded and+its SDK pointed at a local stand-in platform server (``tests/fakes/platforms``). The model is+``tests/fakes/fake_llm_provider.FakeLLMServer`` driven by a ``Director`` that answers per inbound+token. Nothing on our side of the platform boundary is mocked.+"""++from __future__ import annotations++import os+import re+import signal+import sqlite3+import subprocess+import sys+import threading+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional++import yaml++from tests.fakes.fake_llm_provider import Text, write_hermes_home+from tests.fakes.platforms._standin import wait_until++REPO_ROOT = Path(__file__).resolve().parents[4]++_STRIP_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_PASSWORD", "_KEY")+_STRIP_PREFIXES = ("HERMES_", "TELEGRAM_", "DISCORD_", "SLACK_", "OPENAI_", "ANTHROPIC_", "OPENROUTER_",+ "GATEWAY_", "NOUS_")+_TOKEN_RE = re.compile(r"\[in:([A-Za-z0-9_.-]+)\]")+++def real_user_home() -> Path:+ import pwd++ return Path(pwd.getpwuid(os.getuid()).pw_dir).resolve()+++def hermetic_env(home: Path, extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:+ home = home.resolve()+ assert home != real_user_home(), home+ env = {k: v for k, v in os.environ.items()+ if 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"):+ env.pop(var, None)+ 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),+ 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",+ )+ env.update(extra or {})+ return env+++class Director:+ """Scripts the fake model per inbound ``[in:<token>]`` and counts model turns per token."""++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self.scripts: Dict[str, List[Any]] = {}+ self.turns: Dict[str, int] = {}+ self.requests: Dict[str, List[dict]] = {}++ def script(self, token: str, *responses: Any) -> None:+ with self._lock:+ self.scripts[token] = list(responses)++ @staticmethod+ def _text(m: dict) -> str:+ c = m.get("content")+ if isinstance(c, list):+ return " ".join(p.get("text", "") for p in c if isinstance(p, dict))+ return c or ""++ def __call__(self, record: dict) -> Any:+ body = record["body"]+ users = [m for m in body.get("messages", []) if m.get("role") == "user"]+ last = self._text(users[-1]) if users else ""+ tokens = _TOKEN_RE.findall(last)+ continuation = body["messages"][-1].get("role") == "tool"+ token = tokens[-1] if tokens else "none"+ with self._lock:+ self.requests.setdefault(token, []).append(body)+ if not continuation:+ self.turns[token] = self.turns.get(token, 0) + 1+ queue = self.scripts.get(token)+ if queue:+ return queue.pop(0)+ return Text(f"reply to {token}")+++class GatewayUnderTest:+ """A real ``hermes gateway run`` child on its own fake HOME; SIGTERM stop + restart on the same state."""++ def __init__(self, root: Path, *, llm_base_url: str, config: Dict[str, Any], env: Dict[str, str],+ ready: Callable[[], bool]) -> None:+ self.root = root+ self.home = root / "home"+ self.hermes_home = self.home / ".hermes"+ 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))+ self.proc: Optional[subprocess.Popen] = None+ self.pids: List[int] = []++ @property+ def db_path(self) -> Path:+ return self.hermes_home / "state.db"++ def start(self, timeout: float = 120.0) -> "GatewayUnderTest":+ assert self.proc is None or self.proc.poll() is not None+ log = open(self.log_path, "a", encoding="utf-8") # noqa: SIM115 - handed to the child+ self.proc = subprocess.Popen(+ [sys.executable, "-m", "hermes_cli.main", "gateway", "run"], cwd=str(self.home),+ env=hermetic_env(self.home, dict(self._env)), stdin=subprocess.DEVNULL, stdout=log,+ stderr=subprocess.STDOUT, start_new_session=True)+ log.close()+ self.pids.append(self.proc.pid)+ wait_until(lambda: self._ready() or self.proc.poll() is not None, "adapter connected to the stand-in",+ timeout=timeout, on_timeout=self.tail)+ assert self.proc.poll() is None, f"gateway exited rc={self.proc.returncode}\n{self.tail()}"+ return self++ def stop(self, timeout: float = 60.0) -> Optional[int]:+ if self.proc is None:+ return None+ proc = self.proc+ if proc.poll() is None:+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ os.killpg(proc.pid, signal.SIGKILL)+ proc.wait(timeout=15)+ except ProcessLookupError:+ pass+ try:+ os.killpg(proc.pid, signal.SIGKILL) # stragglers in the session+ except (ProcessLookupError, PermissionError):+ pass+ return proc.returncode++ def run_cli(self, *argv: str, timeout: float = 120.0) -> subprocess.CompletedProcess:+ return subprocess.run([sys.executable, "-m", "hermes_cli.main", *argv], cwd=str(self.home),+ env=hermetic_env(self.home, dict(self._env)), stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=timeout)++ def alive(self) -> bool:+ return self.proc is not None and self.proc.poll() is None++ def tail(self, n: int = 6000) -> str:+ try:+ return "--- gateway log tail\n" + self.log_path.read_text(errors="replace")[-n:]+ except OSError:+ return "--- (no gateway log)"++ def user_rows(self, needle: str) -> List[str]:+ if not self.db_path.exists():+ return []+ conn = sqlite3.connect(f"file:{self.db_path}?mode=ro", uri=True, timeout=30)+ try:+ return [r[0] for r in conn.execute(+ "SELECT content FROM messages WHERE role='user' AND content LIKE ?", (f"%{needle}%",))]+ finally:+ conn.close()+++def _deep_merge(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:+ out = dict(a)+ for k, v in b.items():+ out[k] = _deep_merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v+ return outdiff --git a/tests/fakes/platforms/__init__.py b/tests/fakes/platforms/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/fakes/platforms/_standin.py b/tests/fakes/platforms/_standin.pynew file mode 100644index 00000000000..85e64f11e74--- /dev/null+++ b/tests/fakes/platforms/_standin.py@@ -0,0 +1,198 @@+"""Shared plumbing for local stand-in messaging platform servers.++A stand-in is a real HTTP (and, where the platform needs it, WebSocket) server on 127.0.0.1 that+implements only the endpoints a Hermes adapter actually calls, shaped per the platform's published+API reference. It runs on a private asyncio loop in a daemon thread so a synchronous pytest body can+drive it, records every call it serves (method + decoded params + the response it returned), and+lets a test queue faults per method (an API error body, an HTTP status) that are consumed in order.++Nothing here knows about Hermes: the adapter under test talks to it through its own SDK+(python-telegram-bot, discord.py, slack_sdk) exactly as it would talk to the real platform.+"""++from __future__ import annotations++import asyncio+import json+import threading+import time+from dataclasses import dataclass, field+from typing import Any, Callable, Dict, List, Optional++from aiohttp import web+++@dataclass+class Call:+ """One request the stand-in served."""++ method: str+ params: Dict[str, Any]+ at: float+ response: Any = None+ faulted: bool = False+++@dataclass+class Fault:+ """A queued failure for one API method; ``match`` narrows which call consumes it."""++ method: str+ body: Any+ status: int = 200+ times: int = 1+ match: Optional[Callable[[Dict[str, Any]], bool]] = None+ fired: int = 0+++@dataclass+class Visible:+ """What a human would currently see for one bot message in a chat (after edits/deletes)."""++ message_id: str+ text: str+ edits: int = 0+ deleted: bool = False+ extra: Dict[str, Any] = field(default_factory=dict)+++def wait_until(pred: Callable[[], Any], what: str, timeout: float = 60.0, interval: float = 0.05,+ on_timeout: Optional[Callable[[], str]] = None) -> Any:+ deadline = time.monotonic() + timeout+ while True:+ got = pred()+ if got:+ return got+ if time.monotonic() > deadline:+ ctx = on_timeout() if on_timeout else ""+ raise AssertionError(f"timed out after {timeout}s waiting for {what}\n{ctx}")+ time.sleep(interval)+++def decode_value(raw: str) -> Any:+ """Bot-API style form fields carry JSON for structured values; plain strings stay strings."""+ text = raw.strip()+ if text[:1] in "[{" or text in ("true", "false", "null"):+ try:+ return json.loads(text)+ except ValueError:+ return raw+ return raw+++class StandinServer:+ """Base class: an aiohttp application on a private loop thread with call recording + faults."""++ def __init__(self) -> None:+ self._lock = threading.RLock()+ self.calls: List[Call] = []+ self._faults: List[Fault] = []+ self._loop: Optional[asyncio.AbstractEventLoop] = None+ self._thread: Optional[threading.Thread] = None+ self._runner: Optional[web.AppRunner] = None+ self._ready = threading.Event()+ self.port = 0++ # lifecycle ---------------------------------------------------------------------------------+ def build_app(self) -> web.Application: # pragma: no cover - abstract+ raise NotImplementedError++ def start(self) -> "StandinServer":+ self._thread = threading.Thread(target=self._serve, name=type(self).__name__, daemon=True)+ self._thread.start()+ if not self._ready.wait(30):+ raise RuntimeError(f"{type(self).__name__} did not start")+ return self++ def _serve(self) -> None:+ self._loop = asyncio.new_event_loop()+ asyncio.set_event_loop(self._loop)+ self._loop.run_until_complete(self._astart())+ self._ready.set()+ self._loop.run_forever()++ async def _astart(self) -> None:+ self._runner = web.AppRunner(self.build_app(), access_log=None)+ await self._runner.setup()+ site = web.TCPSite(self._runner, "127.0.0.1", 0)+ await site.start()+ self.port = site._server.sockets[0].getsockname()[1] # type: ignore[union-attr]++ def stop(self) -> None:+ if self._loop is None:+ return++ async def _shutdown() -> None:+ await self.on_shutdown()+ if self._runner is not None:+ await self._runner.cleanup()++ try:+ asyncio.run_coroutine_threadsafe(_shutdown(), self._loop).result(15)+ except Exception:+ pass+ self._loop.call_soon_threadsafe(self._loop.stop)+ if self._thread is not None:+ self._thread.join(10)+ self._loop = None++ async def on_shutdown(self) -> None:+ """Subclasses close long-lived sockets here."""++ def __enter__(self) -> "StandinServer":+ return self.start()++ def __exit__(self, *_exc: object) -> None:+ self.stop()++ @property+ def base_url(self) -> str:+ return f"http://127.0.0.1:{self.port}"++ def run_in_loop(self, coro: Any, timeout: float = 15.0) -> Any:+ assert self._loop is not None, "stand-in not running"+ return asyncio.run_coroutine_threadsafe(coro, self._loop).result(timeout)++ # recording + faults ------------------------------------------------------------------------+ def record(self, method: str, params: Dict[str, Any], response: Any, faulted: bool = False) -> Call:+ call = Call(method=method, params=params, at=time.monotonic(), response=response, faulted=faulted)+ with self._lock:+ self.calls.append(call)+ return call++ def calls_of(self, *methods: str) -> List[Call]:+ with self._lock:+ return [c for c in self.calls if c.method in methods]++ def fail(self, method: str, body: Any, *, status: int = 200, times: int = 1,+ match: Optional[Callable[[Dict[str, Any]], bool]] = None) -> Fault:+ fault = Fault(method=method, body=body, status=status, times=times, match=match)+ with self._lock:+ self._faults.append(fault)+ return fault++ def clear_faults(self) -> None:+ with self._lock:+ self._faults.clear()++ def take_fault(self, method: str, params: Dict[str, Any]) -> Optional[Fault]:+ with self._lock:+ for fault in self._faults:+ if fault.method != method or fault.fired >= fault.times:+ continue+ if fault.match is not None and not fault.match(params):+ continue+ fault.fired += 1+ return fault+ return None++ def describe(self, last: int = 40) -> str:+ """Human-readable tail of the call log for assertion messages."""+ with self._lock:+ rows = self.calls[-last:]+ out = []+ for c in rows:+ p = {k: (v[:80] + "…" if isinstance(v, str) and len(v) > 80 else v) for k, v in c.params.items()+ if k not in ("reply_markup", "blocks", "embeds", "components")}+ out.append(f" {'!' if c.faulted else ' '}{c.method} {json.dumps(p, default=str)[:240]}")+ return "--- stand-in calls (last %d)\n%s" % (len(rows), "\n".join(out))diff --git a/tests/fakes/platforms/discord_shim/sitecustomize.py b/tests/fakes/platforms/discord_shim/sitecustomize.pynew file mode 100644index 00000000000..abbffdeb49e--- /dev/null+++ b/tests/fakes/platforms/discord_shim/sitecustomize.py@@ -0,0 +1,27 @@+"""Point discord.py at a local Discord stand-in (tests only).++discord.py has no base-URL knob: REST URLs are built from the class attribute+``discord.http.Route.BASE`` and the gateway socket from+``discord.gateway.DiscordWebSocket.DEFAULT_GATEWAY`` (non-sharded ``Client.connect`` never calls+``GET /gateway/bot``; the resume URL comes from READY's ``resume_gateway_url``, which the stand-in+also points at itself). This module is put on a child process's ``PYTHONPATH`` by the Discord driver+and does nothing unless ``HERMES_STANDIN_DISCORD_API`` is set. It patches the SDK only; no Hermes+code is touched.+"""++import os++_api = os.environ.get("HERMES_STANDIN_DISCORD_API")+_gw = os.environ.get("HERMES_STANDIN_DISCORD_GATEWAY")+if _api:+ try:+ import yarl+ import discord.gateway+ import discord.http++ discord.http.Route.BASE = _api.rstrip("/")+ if _gw:+ discord.gateway.DiscordWebSocket.DEFAULT_GATEWAY = yarl.URL(_gw)+ os.environ["HERMES_STANDIN_DISCORD_SHIM_LOADED"] = "1"+ except ImportError: # discord.py absent in this interpreter: nothing to redirect+ passdiff --git a/tests/fakes/platforms/discord_standin.py b/tests/fakes/platforms/discord_standin.pynew file mode 100644index 00000000000..0e72effc67b--- /dev/null+++ b/tests/fakes/platforms/discord_standin.py@@ -0,0 +1,699 @@+"""Discord stand-in: REST API v10 + Gateway websocket (https://discord.com/developers/docs).++The real ``plugins/platforms/discord`` adapter reaches it through discord.py itself: the child+gateway gets ``tests/fakes/platforms/discord_shim`` on ``PYTHONPATH`` whose ``sitecustomize``+repoints ``Route.BASE`` at ``{base}/api/v10`` and ``DiscordWebSocket.DEFAULT_GATEWAY`` at+``ws://{host}/gw``. Every request then crosses discord.py's real HTTP client, rate-limit handling,+gateway handshake (HELLO -> IDENTIFY -> READY -> GUILD_CREATE, heartbeat/ACK) and model parsing.++Only the routes the adapter actually calls are implemented, shaped per the API reference. Anything+else is recorded as ``unknown`` and answered ``404 {"message": "404: Not Found", "code": 0}`` (what+Discord returns for an unknown route) so a test can see it in ``describe()``.++Recorded call names: ``get_me``, ``get_app``, ``list_commands``, ``bulk_commands``,+``create_command``, ``edit_command``, ``delete_command``, ``create_message``, ``edit_message``,+``delete_message``, ``get_message``, ``history``, ``typing``, ``add_reaction``, ``remove_reaction``,+``get_channel``, ``edit_channel``, ``start_thread_from_message``, ``start_thread``,+``join_thread``, ``create_dm``, ``get_user``, ``get_member``, ``interaction_callback``, ``followup``,+``edit_followup``, ``attachment_download``, ``gw_connect``, ``gw_identify``, ``gw_resume``,+``gw_dispatch``, ``unknown``.+"""++from __future__ import annotations++import asyncio+import datetime as _dt+import itertools+import json+import re+import time+from typing import Any, Dict, List, Optional, Tuple++from aiohttp import WSMsgType, web++from tests.fakes.platforms._standin import StandinServer, Visible++DISCORD_EPOCH_MS = 1420070400000+MAX_TEXT = 2000+BOT_ID = "1100000000000000001"+APP_ID = BOT_ID # a bot's application id equals its user id for modern apps+BOT_USERNAME = "hermes-standin"+GUILD_ID = "1200000000000000001"+TOKEN = "MTEwMDAwMDAwMDAwMDAwMDAwMQ.standin.token"+ALL_PERMISSIONS = str((1 << 50) - 1)+HEARTBEAT_MS = 41250++_ROUTES: List[Tuple[str, str, str]] = [+ ("GET", r"/users/@me", "get_me"),+ ("GET", r"/oauth2/applications/@me", "get_app"),+ ("GET", r"/applications/@me", "get_app"),+ ("GET", r"/applications/(?P<app>\d+)/commands", "list_commands"),+ ("PUT", r"/applications/(?P<app>\d+)/commands", "bulk_commands"),+ ("POST", r"/applications/(?P<app>\d+)/commands", "create_command"),+ ("PATCH", r"/applications/(?P<app>\d+)/commands/(?P<cmd>\d+)", "edit_command"),+ ("DELETE", r"/applications/(?P<app>\d+)/commands/(?P<cmd>\d+)", "delete_command"),+ ("POST", r"/channels/(?P<channel_id>\d+)/messages", "create_message"),+ ("GET", r"/channels/(?P<channel_id>\d+)/messages", "history"),+ ("GET", r"/channels/(?P<channel_id>\d+)/messages/(?P<message_id>\d+)", "get_message"),+ ("PATCH", r"/channels/(?P<channel_id>\d+)/messages/(?P<message_id>\d+)", "edit_message"),+ ("DELETE", r"/channels/(?P<channel_id>\d+)/messages/(?P<message_id>\d+)", "delete_message"),+ ("POST", r"/channels/(?P<channel_id>\d+)/typing", "typing"),+ ("PUT", r"/channels/(?P<channel_id>\d+)/messages/(?P<message_id>\d+)/reactions/(?P<emoji>[^/]+)/@me",+ "add_reaction"),+ ("DELETE", r"/channels/(?P<channel_id>\d+)/messages/(?P<message_id>\d+)/reactions/(?P<emoji>[^/]+)/@me",+ "remove_reaction"),+ ("POST", r"/channels/(?P<channel_id>\d+)/messages/(?P<message_id>\d+)/threads", "start_thread_from_message"),+ ("POST", r"/channels/(?P<channel_id>\d+)/threads", "start_thread"),+ ("PUT", r"/channels/(?P<channel_id>\d+)/thread-members/@me", "join_thread"),+ ("GET", r"/channels/(?P<channel_id>\d+)", "get_channel"),+ ("PATCH", r"/channels/(?P<channel_id>\d+)", "edit_channel"),+ ("POST", r"/users/@me/channels", "create_dm"),+ ("GET", r"/users/(?P<user_id>\d+)", "get_user"),+ ("GET", r"/guilds/(?P<guild_id>\d+)/members/(?P<user_id>\d+)", "get_member"),+ ("POST", r"/interactions/(?P<interaction_id>\d+)/(?P<token>[^/]+)/callback", "interaction_callback"),+ ("POST", r"/webhooks/(?P<app>\d+)/(?P<token>[^/]+)", "followup"),+ ("PATCH", r"/webhooks/(?P<app>\d+)/(?P<token>[^/]+)/messages/(?P<message_id>@original|\d+)", "edit_followup"),+ ("GET", r"/webhooks/(?P<app>\d+)/(?P<token>[^/]+)/messages/(?P<message_id>@original|\d+)", "get_followup"),+ ("DELETE", r"/webhooks/(?P<app>\d+)/(?P<token>[^/]+)/messages/(?P<message_id>@original|\d+)",+ "delete_followup"),+]+_COMPILED = [(m, re.compile(f"^{p}$"), n) for m, p, n in _ROUTES]+++def _json(obj: Any, status: int = 200, headers: Optional[Dict[str, str]] = None) -> web.Response:+ """Discord answers ``Content-Type: application/json`` exactly; discord.py's ``json_or_text`` compares+ the header verbatim, so aiohttp's ``json_response`` (``; charset=utf-8``) would arrive as a str."""+ return web.Response(body=json.dumps(obj).encode(), status=status,+ headers={"Content-Type": "application/json", **(headers or {})})+++def _iso(ts: Optional[float] = None) -> str:+ return _dt.datetime.fromtimestamp(ts or time.time(), _dt.timezone.utc).isoformat()+++class DiscordStandin(StandinServer):+ def __init__(self, token: str = TOKEN) -> None:+ super().__init__()+ self.token = token+ self._seq = itertools.count(1)+ self._sockets: List[Dict[str, Any]] = []+ self.users: Dict[str, Dict[str, Any]] = {BOT_ID: self._bot_user()}+ self.channels: Dict[str, Dict[str, Any]] = {}+ self.dm_of_user: Dict[str, str] = {}+ self.messages: Dict[str, Dict[str, Any]] = {} # every message object by id (bot + inbound)+ self.commands: List[Dict[str, Any]] = []+ self.interactions: Dict[str, Dict[str, Any]] = {} # token -> interaction payload+ self.files: Dict[str, bytes] = {}+ self._visible: Dict[Tuple[str, str], Visible] = {}+ self.guild = {"id": GUILD_ID, "name": "Standin Guild", "owner_id": "1", "channels": []}++ # ids / shapes ----------------------------------------------------------------------------+ def snowflake(self) -> str:+ ms = int(time.time() * 1000) - DISCORD_EPOCH_MS+ return str((ms << 22) | (next(self._seq) & 0x3FFFFF))++ @staticmethod+ def _bot_user() -> Dict[str, Any]:+ return {"id": BOT_ID, "username": BOT_USERNAME, "discriminator": "0", "global_name": "Hermes",+ "avatar": None, "bot": True, "flags": 0, "public_flags": 0, "verified": True,+ "mfa_enabled": False}++ def user(self, user_id: str, name: Optional[str] = None) -> Dict[str, Any]:+ uid = str(user_id)+ if uid not in self.users:+ uname = name or f"user{uid[-4:]}"+ self.users[uid] = {"id": uid, "username": uname, "discriminator": "0", "global_name": uname.title(),+ "avatar": None, "bot": False, "public_flags": 0}+ return self.users[uid]++ def member(self, user_id: str, *, with_user: bool = True) -> Dict[str, Any]:+ m = {"roles": [], "nick": None, "avatar": None, "joined_at": _iso(1700000000), "premium_since": None,+ "deaf": False, "mute": False, "flags": 0, "pending": False}+ if with_user:+ m["user"] = self.user(user_id)+ return m++ def add_text_channel(self, channel_id: str, name: str) -> Dict[str, Any]:+ ch = {"id": str(channel_id), "type": 0, "guild_id": GUILD_ID, "name": name, "position": len(self.channels),+ "permission_overwrites": [], "nsfw": False, "parent_id": None, "topic": None,+ "last_message_id": None, "rate_limit_per_user": 0, "flags": 0}+ self.channels[str(channel_id)] = ch+ return ch++ def dm_channel(self, user_id: str) -> Dict[str, Any]:+ uid = str(user_id)+ if uid not in self.dm_of_user:+ cid = self.snowflake()+ self.dm_of_user[uid] = cid+ self.channels[cid] = {"id": cid, "type": 1, "last_message_id": None, "flags": 0,+ "recipients": [self.user(uid)]}+ return self.channels[self.dm_of_user[uid]]++ def _guild_payload(self) -> Dict[str, Any]:+ everyone = {"id": GUILD_ID, "name": "@everyone", "color": 0, "hoist": False, "icon": None,+ "unicode_emoji": None, "position": 0, "permissions": ALL_PERMISSIONS, "managed": False,+ "mentionable": False, "flags": 0}+ members = [self.member(uid) for uid, u in self.users.items() if u.get("_in_guild") or uid == BOT_ID]+ return {**self.guild, "icon": None, "splash": None, "discovery_splash": None, "afk_channel_id": None,+ "afk_timeout": 300, "verification_level": 0, "default_message_notifications": 0,+ "explicit_content_filter": 0, "roles": [everyone], "emojis": [], "stickers": [], "features": [],+ "mfa_level": 0, "application_id": None, "system_channel_id": None, "system_channel_flags": 0,+ "rules_channel_id": None, "max_members": 500000, "vanity_url_code": None, "description": None,+ "banner": None, "premium_tier": 0, "premium_subscription_count": 0, "preferred_locale": "en-US",+ "public_updates_channel_id": None, "nsfw_level": 0, "premium_progress_bar_enabled": False,+ "joined_at": _iso(1700000000), "large": False, "unavailable": False,+ "member_count": len(members), "voice_states": [], "members": members,+ "channels": [dict(c) for c in self.channels.values() if c.get("guild_id") == GUILD_ID],+ "threads": [], "presences": [], "stage_instances": [], "guild_scheduled_events": [],+ "soundboard_sounds": []}++ # server ----------------------------------------------------------------------------------+ @property+ def api_base(self) -> str:+ return f"{self.base_url}/api/v10"++ @property+ def gateway_url(self) -> str:+ return f"ws://127.0.0.1:{self.port}/gw"++ def build_app(self) -> web.Application:+ app = web.Application(client_max_size=64 * 1024 * 1024)+ app.router.add_get("/gw", self._gateway)+ app.router.add_get("/gw/", self._gateway)+ app.router.add_get("/attachments/{att_id}/{filename}", self._attachment)+ app.router.add_route("*", "/api/v10/{path:.*}", self._api)+ return app++ async def on_shutdown(self) -> None:+ for sock in list(self._sockets):+ try:+ await sock["ws"].close(code=1001)+ except Exception:+ pass++ async def _attachment(self, request: web.Request) -> web.Response:+ att_id = request.match_info["att_id"]+ self.record("attachment_download", {"id": att_id, "filename": request.match_info["filename"]}, None)+ data = self.files.get(att_id)+ return web.Response(body=data) if data is not None else web.Response(status=404)++ async def _params(self, request: web.Request) -> Dict[str, Any]:+ params: Dict[str, Any] = dict(request.query)+ ctype = request.content_type or ""+ if ctype == "application/json":+ raw = await request.read()+ if raw:+ body = json.loads(raw)+ params.update(body if isinstance(body, dict) else {"_body": body})+ elif ctype.startswith("multipart/"):+ files: List[Dict[str, Any]] = []+ reader = await request.multipart()+ async for part in reader:+ if part.filename:+ data = await part.read()+ files.append({"name": part.name, "filename": part.filename, "size": len(data)})+ elif part.name == "payload_json":+ params.update(json.loads(await part.text()))+ else:+ params[part.name] = await part.text()+ params["_files"] = files+ return params++ def _route(self, method: str, path: str) -> Tuple[str, Dict[str, str]]:+ for m, rx, name in _COMPILED:+ if m == method:+ hit = rx.match(path)+ if hit:+ return name, hit.groupdict()+ return "unknown", {}++ async def _api(self, request: web.Request) -> web.Response:+ path = "/" + request.match_info["path"].rstrip("/")+ name, args = self._route(request.method, path)+ params = {**await self._params(request), **args}+ if not path.startswith(("/interactions/", "/webhooks/")) and \+ request.headers.get("Authorization") != f"Bot {self.token}":+ body = {"message": "401: Unauthorized", "code": 0}+ self.record(name, params, body, faulted=True)+ return _json(body, status=401)+ if name == "unknown":+ body = {"message": "404: Not Found", "code": 0}+ self.record(name, {**params, "_method": request.method, "_path": path}, body)+ return _json(body, status=404)+ fault = self.take_fault(name, params)+ if fault is not None:+ self.record(name, params, fault.body, faulted=True)+ headers = {"Retry-After": str(fault.body.get("retry_after", 1)), "X-RateLimit-Scope": "user"} \+ if fault.status == 429 and isinstance(fault.body, dict) else None+ return _json(fault.body, status=fault.status, headers=headers)+ try:+ status, result = getattr(self, f"_r_{name}")(params)+ except Exception as exc: # a stand-in bug must be loud in describe(), not a silent 5xx retry loop+ body = {"message": f"stand-in handler error: {exc!r}", "code": 0}+ self.record(name, {**params, "_error": repr(exc)}, body, faulted=True)+ return _json(body, status=500)+ self.record(name, params, result)+ if status == 204:+ return web.Response(status=204)+ return _json(result, status=status)++ # REST handlers: each returns (status, json) -------------------------------------------------+ def _r_get_me(self, _p: Dict[str, Any]) -> Tuple[int, Any]:+ return 200, self._bot_user()++ def _r_get_app(self, _p: Dict[str, Any]) -> Tuple[int, Any]:+ owner = {"id": "1", "username": "owner", "discriminator": "0", "global_name": None, "avatar": None}+ return 200, {"id": APP_ID, "name": "Hermes Standin", "icon": None, "description": "", "summary": "",+ "type": None, "bot_public": True, "bot_require_code_grant": False, "verify_key": "0" * 64,+ "flags": (1 << 19) | (1 << 15), "owner": owner, "team": None, "bot": self._bot_user(),+ "interactions_endpoint_url": None, "redirect_uris": [], "tags": [],+ "approximate_guild_count": 1, "integration_types_config": {"0": {}, "1": {}}}++ def _command(self, body: Dict[str, Any]) -> Dict[str, Any]:+ cmd = {k: v for k, v in body.items() if not k.startswith("_") and k not in ("app",)}+ cmd.setdefault("id", self.snowflake())+ cmd.update(application_id=APP_ID, version=self.snowflake(), type=cmd.get("type", 1))+ cmd.setdefault("default_member_permissions", None)+ cmd.setdefault("dm_permission", True)+ cmd.setdefault("nsfw", False)+ cmd.setdefault("description", "")+ return cmd++ def _r_list_commands(self, _p: Dict[str, Any]) -> Tuple[int, Any]:+ return 200, list(self.commands)++ def _r_bulk_commands(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ self.commands = [self._command(c) for c in (p.get("_body") or [])]+ return 200, list(self.commands)++ def _r_create_command(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ cmd = self._command(p)+ self.commands = [c for c in self.commands if c.get("name") != cmd.get("name")] + [cmd]+ return 201, cmd++ def _r_edit_command(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ for c in self.commands:+ if c["id"] == p["cmd"]:+ c.update({k: v for k, v in p.items() if not k.startswith("_") and k not in ("app", "cmd")})+ return 200, c+ return 404, {"message": "Unknown application command", "code": 10063}++ def _r_delete_command(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ self.commands = [c for c in self.commands if c["id"] != p["cmd"]]+ return 204, None++ def _bot_message(self, channel_id: str, p: Dict[str, Any], *, interaction: Optional[Dict[str, Any]] = None,+ ephemeral: bool = False) -> Dict[str, Any]:+ mid = self.snowflake()+ ch = self.channels.get(channel_id) or {}+ attachments = [{"id": self.snowflake(), "filename": f["filename"], "size": f["size"],+ "url": f"{self.base_url}/attachments/out/{f['filename']}",+ "proxy_url": f"{self.base_url}/attachments/out/{f['filename']}"}+ for f in p.get("_files") or []]+ msg = {"id": mid, "channel_id": channel_id, "author": self._bot_user(), "content": p.get("content") or "",+ "timestamp": _iso(), "edited_timestamp": None, "tts": False, "mention_everyone": False,+ "mentions": [], "mention_roles": [], "attachments": attachments, "embeds": p.get("embeds") or [],+ "components": p.get("components") or [], "pinned": False, "type": 0 if not p.get(+ "message_reference") else 19, "flags": (64 if ephemeral else 0)}+ if p.get("message_reference"):+ msg["message_reference"] = p["message_reference"]+ if p.get("nonce") is not None:+ msg["nonce"] = p["nonce"]+ if ch.get("guild_id"):+ msg["guild_id"] = ch["guild_id"]+ if interaction is not None:+ msg["interaction_metadata"] = {"id": interaction["id"], "type": interaction["type"],+ "user": interaction["_user"]}+ msg["webhook_id"] = APP_ID+ self.messages[mid] = msg+ with self._lock:+ self._visible[(channel_id, mid)] = Visible(mid, msg["content"], extra={+ "components": msg["components"], "embeds": msg["embeds"], "attachments": attachments,+ "reply_to": (p.get("message_reference") or {}).get("message_id"), "ephemeral": ephemeral})+ if ch:+ ch["last_message_id"] = mid+ return msg++ def _unknown_channel(self) -> Tuple[int, Any]:+ return 404, {"message": "Unknown Channel", "code": 10003}++ def _r_create_message(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ cid = p["channel_id"]+ if cid not in self.channels:+ return self._unknown_channel()+ if len(p.get("content") or "") > MAX_TEXT:+ return 400, {"message": "Invalid Form Body", "code": 50035, "errors": {"content": {"_errors": [+ {"code": "BASE_TYPE_MAX_LENGTH", "message": "Must be 2000 or fewer in length."}]}}}+ return 200, self._bot_message(cid, p)++ def _edit(self, cid: str, mid: str, p: Dict[str, Any]) -> Tuple[int, Any]:+ msg = self.messages.get(mid)+ if msg is None or msg["channel_id"] != cid:+ return 404, {"message": "Unknown Message", "code": 10008}+ if msg["author"]["id"] != BOT_ID:+ return 403, {"message": "Cannot edit a message authored by another user", "code": 50005}+ if len(p.get("content") or "") > MAX_TEXT:+ return 400, {"message": "Invalid Form Body", "code": 50035}+ for key in ("content", "embeds", "components"):+ if key in p:+ msg[key] = p[key] if p[key] is not None else ([] if key != "content" else "")+ msg["edited_timestamp"] = _iso()+ with self._lock:+ vis = self._visible.get((cid, mid))+ if vis is not None:+ vis.text = msg["content"]+ vis.edits += 1+ vis.extra["components"] = msg["components"]+ vis.extra["embeds"] = msg["embeds"]+ return 200, msg++ def _r_edit_message(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ return self._edit(p["channel_id"], p["message_id"], p)++ def _r_delete_message(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ msg = self.messages.get(p["message_id"])+ if msg is None:+ return 404, {"message": "Unknown Message", "code": 10008}+ with self._lock:+ vis = self._visible.get((p["channel_id"], p["message_id"]))+ if vis is not None:+ vis.deleted = True+ return 204, None++ def _r_get_message(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ msg = self.messages.get(p["message_id"])+ if msg is None or msg["channel_id"] != p["channel_id"]:+ return 404, {"message": "Unknown Message", "code": 10008}+ return 200, msg++ def _r_history(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ rows = [m for m in self.messages.values() if m["channel_id"] == p["channel_id"]]+ rows.sort(key=lambda m: int(m["id"]), reverse=True)+ if p.get("after"):+ rows = [m for m in rows if int(m["id"]) > int(p["after"])]+ if p.get("before"):+ rows = [m for m in rows if int(m["id"]) < int(p["before"])]+ return 200, rows[: int(p.get("limit") or 50)]++ def _r_typing(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ return (204, None) if p["channel_id"] in self.channels else self._unknown_channel()++ def _r_add_reaction(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ return 204, None++ _r_remove_reaction = _r_add_reaction++ def _r_get_channel(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ ch = self.channels.get(p["channel_id"])+ return (200, ch) if ch else self._unknown_channel()++ def _make_thread(self, parent_id: str, thread_id: str, p: Dict[str, Any]) -> Dict[str, Any]:+ parent = self.channels[parent_id]+ now = _iso()+ th = {"id": thread_id, "type": int(p.get("type") or 11), "guild_id": parent.get("guild_id"),+ "parent_id": parent_id, "name": p.get("name") or "thread", "owner_id": BOT_ID, "message_count": 0,+ "member_count": 1, "total_message_sent": 0, "rate_limit_per_user": int(p.get("rate_limit_per_user") or 0),+ "last_message_id": None, "flags": 0, "applied_tags": [],+ "thread_metadata": {"archived": False, "auto_archive_duration": int(p.get("auto_archive_duration") or 1440),+ "archive_timestamp": now, "locked": False, "create_timestamp": now},+ "member": {"id": thread_id, "user_id": BOT_ID, "join_timestamp": now, "flags": 0}}+ self.channels[thread_id] = th+ if self._loop is not None: # Discord announces the new thread on the gateway too+ asyncio.ensure_future(self._broadcast("THREAD_CREATE", {**th, "newly_created": True}), loop=self._loop)+ return th++ def _r_start_thread_from_message(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ msg = self.messages.get(p["message_id"])+ if p["channel_id"] not in self.channels or msg is None:+ return 404, {"message": "Unknown Message", "code": 10008}+ if p["message_id"] in self.channels:+ return 400, {"message": "A thread has already been created for this message", "code": 160004}+ return 201, self._make_thread(p["channel_id"], p["message_id"], p)++ def _r_start_thread(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ if p["channel_id"] not in self.channels:+ return self._unknown_channel()+ th = self._make_thread(p["channel_id"], self.snowflake(), p)+ if isinstance(p.get("message"), dict): # forum/media post: starter message id == thread id+ starter = self._bot_message(th["id"], {**p["message"], "_files": p.get("_files")})+ return 201, {**th, "message": starter}+ return 201, th++ def _r_join_thread(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ return (204, None) if p["channel_id"] in self.channels else self._unknown_channel()++ def threads_of(self, channel_id: Any) -> List[Dict[str, Any]]:+ return [c for c in self.channels.values() if c.get("parent_id") == str(channel_id)]++ def _r_edit_channel(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ ch = self.channels.get(p["channel_id"])+ if ch is None:+ return self._unknown_channel()+ for key in ("name", "topic", "rate_limit_per_user", "nsfw", "applied_tags"):+ if key in p:+ ch[key] = p[key]+ meta = ch.get("thread_metadata")+ if meta is not None:+ for key in ("archived", "locked", "auto_archive_duration"):+ if key in p:+ meta[key] = p[key]+ if self._loop is not None:+ event = "THREAD_UPDATE" if meta is not None else "CHANNEL_UPDATE"+ asyncio.ensure_future(self._broadcast(event, dict(ch)), loop=self._loop)+ return 200, ch++ def _r_create_dm(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ return 200, self.dm_channel(str(p["recipient_id"]))++ def _r_get_user(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ u = self.users.get(p["user_id"])+ return (200, u) if u else (404, {"message": "Unknown User", "code": 10013})++ def _r_get_member(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ u = self.users.get(p["user_id"])+ return (200, self.member(p["user_id"])) if u else (404, {"message": "Unknown Member", "code": 10007})++ def _r_interaction_callback(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ inter = self.interactions.get(p["token"])+ if inter is None or inter["id"] != p["interaction_id"]:+ return 404, {"message": "Unknown interaction", "code": 10062}+ if inter.get("_answered"):+ return 400, {"message": "Interaction has already been acknowledged.", "code": 40060}+ inter["_answered"] = True+ rtype, data = int(p.get("type") or 0), (p.get("data") or {})+ ephemeral = bool(int(data.get("flags") or 0) & 64)+ cb: Dict[str, Any] = {"interaction": {"id": inter["id"], "type": inter["type"],+ "response_message_loading": rtype == 5,+ "response_message_ephemeral": ephemeral}}+ msg = None+ if rtype == 4: # CHANNEL_MESSAGE_WITH_SOURCE+ msg = self._bot_message(inter["channel_id"], {**data, "_files": p.get("_files")}, interaction=inter,+ ephemeral=ephemeral)+ inter["_original"] = msg["id"]+ elif rtype == 7 and inter.get("message"): # UPDATE_MESSAGE on the component's message+ _, msg = self._edit(inter["channel_id"], inter["message"]["id"], data)+ elif rtype == 5: # deferred: a loading placeholder becomes @original+ msg = self._bot_message(inter["channel_id"], {"content": ""}, interaction=inter, ephemeral=ephemeral)+ inter["_original"] = msg["id"]+ if msg is not None:+ cb["interaction"]["response_message_id"] = msg["id"]+ cb["resource"] = {"type": rtype, "message": msg}+ elif rtype:+ cb["resource"] = {"type": rtype}+ return 200, cb++ def _r_followup(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ inter = self.interactions.get(p["token"])+ if inter is None:+ return 404, {"message": "Unknown Webhook", "code": 10015}+ ephemeral = bool(int(p.get("flags") or 0) & 64)+ return 200, self._bot_message(inter["channel_id"], p, interaction=inter, ephemeral=ephemeral)++ def _followup_target(self, p: Dict[str, Any]) -> Optional[Tuple[str, str]]:+ inter = self.interactions.get(p["token"])+ if inter is None:+ return None+ mid = inter.get("_original") if p["message_id"] == "@original" else p["message_id"]+ if mid is None and inter.get("message"):+ mid = inter["message"]["id"]+ return (inter["channel_id"], mid) if mid else None++ def _r_edit_followup(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ target = self._followup_target(p)+ if target is None:+ return 404, {"message": "Unknown Message", "code": 10008}+ return self._edit(target[0], target[1], p)++ def _r_get_followup(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ target = self._followup_target(p)+ msg = self.messages.get(target[1]) if target else None+ return (200, msg) if msg else (404, {"message": "Unknown Message", "code": 10008})++ def _r_delete_followup(self, p: Dict[str, Any]) -> Tuple[int, Any]:+ target = self._followup_target(p)+ if target is None:+ return 404, {"message": "Unknown Message", "code": 10008}+ return self._r_delete_message({"channel_id": target[0], "message_id": target[1]})++ # gateway ---------------------------------------------------------------------------------+ async def _gateway(self, request: web.Request) -> web.WebSocketResponse:+ ws = web.WebSocketResponse(autoping=True, max_msg_size=0)+ await ws.prepare(request)+ sock: Dict[str, Any] = {"ws": ws, "seq": 0, "ready": False, "session_id": None,+ "query": dict(request.query)}+ self.record("gw_connect", dict(request.query), None)+ await ws.send_str(json.dumps({"op": 10, "d": {"heartbeat_interval": HEARTBEAT_MS}, "s": None, "t": None}))+ try:+ async for frame in ws:+ if frame.type != WSMsgType.TEXT:+ if frame.type in (WSMsgType.ERROR, WSMsgType.CLOSE):+ break+ continue+ await self._on_gateway_frame(sock, json.loads(frame.data))+ finally:+ if sock in self._sockets:+ self._sockets.remove(sock)+ return ws++ async def _on_gateway_frame(self, sock: Dict[str, Any], msg: Dict[str, Any]) -> None:+ op, d = msg.get("op"), msg.get("d")+ ws = sock["ws"]+ if op == 1: # HEARTBEAT+ await ws.send_str(json.dumps({"op": 11, "d": None, "s": None, "t": None}))+ elif op == 2: # IDENTIFY+ self.record("gw_identify", {"intents": d.get("intents"), "shard": d.get("shard"),+ "token_ok": d.get("token") == self.token}, None)+ if d.get("token") != self.token:+ await ws.close(code=4004, message=b"Authentication failed.")+ return+ sock["session_id"] = f"standin-{self.snowflake()}"+ sock["intents"] = d.get("intents")+ await self._send_dispatch(sock, "READY", {+ "v": 10, "user": self._bot_user(), "guilds": [{"id": GUILD_ID, "unavailable": True}],+ "session_id": sock["session_id"], "session_type": "normal",+ "resume_gateway_url": self.gateway_url, "shard": d.get("shard") or [0, 1],+ "application": {"id": APP_ID, "flags": (1 << 19) | (1 << 15)}, "private_channels": [],+ "relationships": [], "presences": [], "user_settings": {}, "guild_join_requests": [],+ "geo_ordered_rtc_regions": [], "auth": {}, "_trace": ["standin"]})+ await self._send_dispatch(sock, "GUILD_CREATE", self._guild_payload())+ sock["ready"] = True+ self._sockets.append(sock)+ elif op == 6: # RESUME: no event buffer is kept, so ask for a fresh IDENTIFY (resumable=false)+ self.record("gw_resume", {"session_id": (d or {}).get("session_id"), "seq": (d or {}).get("seq")}, None)+ await ws.send_str(json.dumps({"op": 9, "d": False, "s": None, "t": None}))+ # op 3 presence / op 4 voice state / op 8 request members: accepted silently++ async def _send_dispatch(self, sock: Dict[str, Any], event: str, data: Dict[str, Any]) -> None:+ sock["seq"] += 1+ await sock["ws"].send_str(json.dumps({"op": 0, "t": event, "s": sock["seq"], "d": data}))++ async def _broadcast(self, event: str, data: Dict[str, Any]) -> int:+ sent = 0+ for sock in list(self._sockets):+ if sock["ready"] and not sock["ws"].closed:+ await self._send_dispatch(sock, event, data)+ sent += 1+ return sent++ def dispatch(self, event: str, data: Dict[str, Any]) -> int:+ """Send one DISPATCH (op 0) to every identified gateway session; returns sessions reached."""+ sent = self.run_in_loop(self._broadcast(event, data))+ self.record("gw_dispatch", {"t": event, "id": data.get("id"), "channel_id": data.get("channel_id"),+ "sessions": sent}, None)+ return sent++ def sessions(self) -> int:+ return sum(1 for s in self._sockets if s["ready"] and not s["ws"].closed)++ def drop_sessions(self, code: int = 4000) -> None:+ """Close every gateway socket (a Discord-side disconnect; the client reconnects/resumes)."""++ async def _drop() -> None:+ for sock in list(self._sockets):+ await sock["ws"].close(code=code)++ self.run_in_loop(_drop())++ # test-facing inbound ---------------------------------------------------------------------+ def inbound_message(self, channel_id: str, user_id: str, content: str, *, mentions: Optional[List[str]] = None,+ attachments: Optional[List[Dict[str, Any]]] = None, dispatch: bool = True) -> Dict[str, Any]:+ ch = self.channels[str(channel_id)]+ author = self.user(user_id)+ mid = self.snowflake()+ msg: Dict[str, Any] = {"id": mid, "channel_id": ch["id"], "author": author, "content": content,+ "timestamp": _iso(), "edited_timestamp": None, "tts": False,+ "mention_everyone": False, "mention_roles": [], "attachments": attachments or [],+ "embeds": [], "components": [], "pinned": False, "type": 0, "flags": 0,+ "nonce": mid, "mentions": []}+ for uid in mentions or []:+ mu = dict(self.users.get(uid) or self.user(uid))+ if ch.get("guild_id"):+ mu["member"] = self.member(uid, with_user=False)+ msg["mentions"].append(mu)+ if ch.get("guild_id"):+ author["_in_guild"] = True+ msg["guild_id"] = ch["guild_id"]+ msg["member"] = self.member(user_id, with_user=False)+ payload = {k: v for k, v in msg.items()}+ payload["author"] = {k: v for k, v in author.items() if not k.startswith("_")}+ payload["mentions"] = [{k: v for k, v in m.items() if not k.startswith("_")} for m in msg["mentions"]]+ self.messages[mid] = payload+ ch["last_message_id"] = mid+ if dispatch:+ self.dispatch("MESSAGE_CREATE", payload)+ return payload++ def attachment(self, filename: str, data: bytes, mime: str) -> Dict[str, Any]:+ att_id = self.snowflake()+ self.files[att_id] = data+ url = f"{self.base_url}/attachments/{att_id}/{filename}"+ return {"id": att_id, "filename": filename, "size": len(data), "url": url, "proxy_url": url,+ "content_type": mime}++ def click(self, user_id: str, channel_id: str, message_id: str, custom_id: str,+ component_type: int = 2, values: Optional[List[str]] = None) -> Dict[str, Any]:+ """A user presses a component (button/select) on bot message ``message_id``: INTERACTION_CREATE."""+ ch = self.channels[str(channel_id)]+ iid, token = self.snowflake(), f"itoken-{self.snowflake()}"+ data: Dict[str, Any] = {"custom_id": custom_id, "component_type": component_type}+ if values is not None:+ data["values"] = values+ inter: Dict[str, Any] = {+ "id": iid, "application_id": APP_ID, "type": 3, "data": data, "channel_id": ch["id"],+ "channel": {k: v for k, v in ch.items() if k != "recipients"} | {"type": ch["type"]},+ "token": token, "version": 1, "message": self.messages.get(str(message_id)),+ "app_permissions": ALL_PERMISSIONS, "locale": "en-US", "entitlements": [],+ "authorizing_integration_owners": {"0": GUILD_ID} if ch.get("guild_id") else {"1": str(user_id)},+ "context": 0 if ch.get("guild_id") else 1, "attachment_size_limit": 26214400,+ }+ user = {k: v for k, v in self.user(user_id).items() if not k.startswith("_")}+ if ch.get("guild_id"):+ inter["guild_id"] = ch["guild_id"]+ inter["member"] = {**self.member(user_id, with_user=False), "user": user,+ "permissions": ALL_PERMISSIONS}+ inter["guild_locale"] = "en-US"+ else:+ inter["user"] = user+ self.interactions[token] = {**inter, "_user": user}+ self.dispatch("INTERACTION_CREATE", inter)+ return inter++ def redeliver(self, payload: Dict[str, Any]) -> None:+ """Deliver the very same MESSAGE_CREATE again (a gateway replay of an already-seen event)."""+ self.dispatch("MESSAGE_CREATE", payload)++ # ground truth ----------------------------------------------------------------------------+ def visible(self, channel_id: Any) -> List[Visible]:+ with self._lock:+ rows = [v for (c, _), v in self._visible.items() if c == str(channel_id) and not v.deleted]+ return sorted(rows, key=lambda v: int(v.message_id))++ def buttons(self, channel_id: Any) -> List[Dict[str, Any]]:+ """Every component (button/select) currently attached to a visible bot message in the channel."""+ out: List[Dict[str, Any]] = []+ for vis in self.visible(channel_id):+ for row in vis.extra.get("components") or []:+ for comp in row.get("components") or []:+ out.append({**comp, "message_id": vis.message_id})+ return out+diff --git a/tests/fakes/platforms/slack_shim/sitecustomize.py b/tests/fakes/platforms/slack_shim/sitecustomize.pynew file mode 100644index 00000000000..dec19a056c1--- /dev/null+++ b/tests/fakes/platforms/slack_shim/sitecustomize.py@@ -0,0 +1,68 @@+"""Point slack_sdk (and raw ``https://slack.com/api/`` aiohttp posts) at a local Slack stand-in.++slack_sdk has no base-URL environment variable, so this module is put on ``PYTHONPATH`` of the child+``hermes gateway run`` process by the contract harness. Python imports ``sitecustomize`` at startup;+when ``HERMES_STANDIN_SLACK_API`` is set (e.g. ``http://127.0.0.1:PORT/api/``) every Web API client+the Slack adapter builds defaults its ``base_url`` to the stand-in, which also moves+``apps.connections.open`` and therefore the Socket Mode websocket. Nothing in Hermes is touched: the+redirect lives at the SDK/HTTP boundary, exactly where DNS would send the real traffic.+"""++import os++_API = os.environ.get("HERMES_STANDIN_SLACK_API", "")+_REAL_API = "https://slack.com/api/"+++def _wrap_init(cls):+ original = cls.__init__+ if getattr(original, "_standin_wrapped", False):+ return++ def __init__(self, *args, **kwargs):+ # base_url is the 2nd positional parameter of both base clients (after token).+ if len(args) < 2:+ kwargs.setdefault("base_url", _API)+ original(self, *args, **kwargs)+ if getattr(self, "base_url", "") == _REAL_API:+ self.base_url = _API++ __init__._standin_wrapped = True # type: ignore[attr-defined]+ cls.__init__ = __init__+++def _install_sdk() -> None:+ try:+ from slack_sdk.web.async_base_client import AsyncBaseClient+ from slack_sdk.web.base_client import BaseClient+ except Exception: # slack_sdk not installed: nothing to redirect+ return+ _wrap_init(AsyncBaseClient)+ _wrap_init(BaseClient)+++def _install_aiohttp() -> None:+ """The adapter's standalone (out-of-gateway) sender POSTs to ``https://slack.com/api/<m>``."""+ try:+ import aiohttp+ except Exception:+ return+ original = aiohttp.ClientSession._request+ if getattr(original, "_standin_wrapped", False):+ return++ async def _request(self, method, str_or_url, *args, **kwargs):+ url = str(str_or_url)+ if url.startswith(_REAL_API):+ str_or_url = _API + url[len(_REAL_API):]+ return await original(self, method, str_or_url, *args, **kwargs)++ _request._standin_wrapped = True # type: ignore[attr-defined]+ aiohttp.ClientSession._request = _request+++if _API:+ if not _API.endswith("/"):+ _API += "/"+ _install_sdk()+ _install_aiohttp()diff --git a/tests/fakes/platforms/slack_standin.py b/tests/fakes/platforms/slack_standin.pynew file mode 100644index 00000000000..a8dd123021b--- /dev/null+++ b/tests/fakes/platforms/slack_standin.py@@ -0,0 +1,534 @@+"""Slack Web API + Socket Mode stand-in (https://api.slack.com/methods, /apis/socket-mode).++The real ``plugins/platforms/slack`` adapter reaches it through slack_bolt/slack_sdk: the+``slack_shim/sitecustomize.py`` module (on the child's ``PYTHONPATH``) defaults every slack_sdk Web+API client's ``base_url`` to ``{base}/api/``, so ``auth.test``, ``chat.*``, ``conversations.*`` and+``apps.connections.open`` all land here. ``apps.connections.open`` hands out ``ws://…/ws``; the SDK's+Socket Mode client connects, receives ``hello``, and from then on the test pushes envelopes+(``events_api`` / ``interactive`` / ``slash_commands``) that the client acks by ``envelope_id``.++Web API semantics kept faithful to Slack: every response is HTTP 200 JSON with ``ok``; failures are+``{"ok": false, "error": "<code>"}`` (the SDK raises ``SlackApiError`` on them); bodies arrive+form-encoded or JSON (structured fields like ``blocks`` may be JSON strings); ``chat.postMessage``+above 40,000 chars answers ``msg_too_long``. Unknown methods answer ``{"ok": true}`` and are still+recorded so a test can see them.+"""++from __future__ import annotations++import itertools+import json+import time+import uuid+from typing import Any, Dict, List, Optional++from aiohttp import WSMsgType, web++from tests.fakes.platforms._standin import StandinServer, Visible++TEAM_ID = "T0STANDIN"+APP_ID = "A0STANDIN"+BOT_USER_ID = "UBOT0001"+BOT_ID = "B0STANDIN"+BOT_NAME = "hermes"+MAX_TEXT = 40_000 # chat.postMessage hard limit (msg_too_long above it)+_STRUCTURED = ("blocks", "attachments", "metadata", "files", "chunks", "file_uploads")+_SCOPES = ",".join((+ "app_mentions:read", "assistant:write", "channels:history", "channels:read", "chat:write",+ "commands", "files:read", "files:write", "groups:history", "groups:read", "im:history", "im:read",+ "im:write", "mpim:history", "mpim:read", "mpim:write", "reactions:read", "reactions:write",+ "users:read"))+++def _decode(key: str, value: Any) -> Any:+ if key in _STRUCTURED and isinstance(value, str) and value.strip()[:1] in "[{":+ try:+ return json.loads(value)+ except ValueError:+ return value+ return value+++class SlackStandin(StandinServer):+ def __init__(self, bot_token: str = "xoxb-standin", app_token: str = "xapp-standin") -> None:+ super().__init__()+ self.bot_token = bot_token+ self.app_token = app_token+ self._ts_base = int(time.time())+ self._ts_seq = itertools.count(100)+ self._ids = itertools.count(1)+ self._sockets: List[web.WebSocketResponse] = []+ self.acks: Dict[str, Dict[str, Any]] = {}+ self.envelopes: List[Dict[str, Any]] = []+ # (channel, ts) -> Visible for BOT messages; every message (bot + inbound) per channel for+ # conversations.history/replies.+ self._visible: Dict[tuple, Visible] = {}+ self._history: Dict[str, List[Dict[str, Any]]] = {}+ self.files: Dict[str, Dict[str, Any]] = {}+ self.uploads: Dict[str, bytes] = {}+ self.users: Dict[str, Dict[str, Any]] = {}+ # Ephemeral replies (response_url POSTs + chat.postEphemeral): seen only by one user, so kept+ # out of ``visible()``. response id -> (channel, user) for response_url routing.+ self._responses: Dict[str, tuple] = {}+ self._ephemerals: List[Dict[str, Any]] = []++ @property+ def api_base(self) -> str:+ return f"{self.base_url}/api/"++ @property+ def ws_url(self) -> str:+ return f"ws://127.0.0.1:{self.port}/ws"++ def next_ts(self) -> str:+ return f"{self._ts_base}.{next(self._ts_seq):06d}"++ # server ------------------------------------------------------------------------------------+ def build_app(self) -> web.Application:+ app = web.Application(client_max_size=64 * 1024 * 1024)+ app.router.add_route("*", "/api/{method}", self._api)+ app.router.add_get("/ws", self._ws)+ app.router.add_post("/upload/{file_id}", self._upload)+ app.router.add_get("/files-pri/{path:.*}", self._download)+ app.router.add_post("/response/{rid}", self._response_url)+ return app++ async def _params(self, request: web.Request) -> Dict[str, Any]:+ params: Dict[str, Any] = dict(request.query)+ ctype = request.content_type or ""+ if ctype == "application/json":+ params.update(await request.json() or {})+ elif ctype.startswith("multipart/"):+ reader = await request.multipart()+ async for part in reader:+ if part.filename:+ params[part.name] = {"filename": part.filename, "size": len(await part.read())}+ else:+ params[part.name] = await part.text()+ elif request.can_read_body:+ params.update({k: v for k, v in (await request.post()).items()})+ return {k: _decode(k, v) for k, v in params.items()}++ @staticmethod+ def _token(request: web.Request, params: Dict[str, Any]) -> str:+ auth = request.headers.get("Authorization", "")+ return auth[7:] if auth.startswith("Bearer ") else str(params.pop("token", ""))++ def _reply(self, body: Dict[str, Any]) -> web.Response:+ return web.json_response(body, headers={"x-oauth-scopes": _SCOPES, "x-accepted-oauth-scopes": ""})++ async def _api(self, request: web.Request) -> web.Response:+ method = request.match_info["method"]+ params = await self._params(request)+ token = self._token(request, params)+ want = self.app_token if method == "apps.connections.open" else self.bot_token+ if token != want:+ body = {"ok": False, "error": "invalid_auth"}+ self.record(method, params, body, faulted=True)+ return self._reply(body)+ fault = self.take_fault(method, params)+ if fault is not None:+ self.record(method, params, fault.body, faulted=True)+ return web.json_response(fault.body, status=fault.status)+ handler = getattr(self, "_m_" + method.replace(".", "_"), None)+ try:+ result = handler(params) if handler else {}+ except _ApiError as exc:+ body = {"ok": False, "error": exc.code}+ self.record(method, params, body, faulted=True)+ return self._reply(body)+ body = {"ok": True, **(result or {})}+ self.record(method, params, body)+ return self._reply(body)++ async def _upload(self, request: web.Request) -> web.Response:+ fid = request.match_info["file_id"]+ data = await request.read()+ self.uploads[fid] = data+ self.record("file_upload", {"file_id": fid, "size": len(data)}, None)+ return web.Response(text=f"OK - {len(data)}")++ async def _download(self, request: web.Request) -> web.Response:+ path = request.match_info["path"]+ self.record("file_download", {"path": path}, None)+ for f in self.files.values():+ if f.get("_path") == path:+ return web.Response(body=f["_data"], content_type=f.get("mimetype", "application/octet-stream"))+ return web.Response(status=404)++ async def _response_url(self, request: web.Request) -> web.Response:+ rid = request.match_info["rid"]+ params = await self._params(request)+ target = self._responses.get(rid)+ if target is None:+ self.record("response_url", {"rid": rid, **params}, None, faulted=True)+ return web.Response(status=404, text="no_such_response_url")+ self.record("response_url", {"rid": rid, "channel": target[0], **params}, None)+ with self._lock:+ self._ephemerals.append({"channel": target[0], "user": target[1], "text": params.get("text", ""),+ "replace_original": params.get("replace_original"), "via": "response_url"})+ return web.Response(text="ok")++ def _new_response_url(self, channel: str, user_id: str) -> str:+ rid = uuid.uuid4().hex[:12]+ self._responses[rid] = (channel, user_id)+ return f"{self.base_url}/response/{rid}"++ def ephemerals(self, channel: str) -> List[Dict[str, Any]]:+ with self._lock:+ return [e for e in self._ephemerals if e["channel"] == str(channel)]++ # Socket Mode -------------------------------------------------------------------------------+ async def _ws(self, request: web.Request) -> web.StreamResponse:+ ws = web.WebSocketResponse(autoping=True)+ await ws.prepare(request)+ self._sockets.append(ws)+ self.record("socket_connect", {"sockets": len(self._sockets)}, None)+ await ws.send_str(json.dumps({"type": "hello", "num_connections": len(self._sockets),+ "debug_info": {"host": "standin", "approximate_connection_time": 3600},+ "connection_info": {"app_id": APP_ID}}))+ try:+ async for msg in ws:+ if msg.type != WSMsgType.TEXT:+ continue+ try:+ ack = json.loads(msg.data)+ except ValueError:+ continue+ if isinstance(ack, dict) and ack.get("envelope_id"):+ with self._lock:+ self.acks[ack["envelope_id"]] = ack+ self.record("socket_ack", ack, None)+ finally:+ if ws in self._sockets:+ self._sockets.remove(ws)+ self.record("socket_close", {"sockets": len(self._sockets)}, None)+ return ws++ async def on_shutdown(self) -> None:+ for ws in list(self._sockets):+ await ws.close()++ def socket_count(self) -> int:+ return len([ws for ws in self._sockets if not ws.closed])++ async def _asend(self, envelope: Dict[str, Any]) -> None:+ live = [ws for ws in self._sockets if not ws.closed]+ if not live:+ raise RuntimeError("no Socket Mode client connected to the Slack stand-in")+ # Slack delivers one envelope to ONE of the app's connections.+ await live[-1].send_str(json.dumps(envelope))++ def push(self, envelope_type: str, payload: Dict[str, Any], *, retry_attempt: int = 0,+ retry_reason: str = "", accepts_response_payload: bool = False) -> Dict[str, Any]:+ envelope = {"envelope_id": str(uuid.uuid4()), "type": envelope_type, "payload": payload,+ "accepts_response_payload": accepts_response_payload,+ "retry_attempt": retry_attempt, "retry_reason": retry_reason}+ with self._lock:+ self.envelopes.append(envelope)+ self.run_in_loop(self._asend(envelope))+ return envelope++ def acked(self, envelope: Dict[str, Any]) -> bool:+ with self._lock:+ return envelope["envelope_id"] in self.acks++ # Web API methods ---------------------------------------------------------------------------+ def _user(self, user_id: str) -> Dict[str, Any]:+ if user_id in self.users:+ return self.users[user_id]+ is_bot = user_id == BOT_USER_ID+ name = BOT_NAME if is_bot else f"user{user_id.lower()}"+ return {"id": user_id, "team_id": TEAM_ID, "name": name, "real_name": name.title(), "deleted": False,+ "is_bot": is_bot, "is_app_user": False, "tz": "UTC",+ "profile": {"display_name": name, "real_name": name.title(), "bot_id": BOT_ID if is_bot else None}}++ def _channel(self, channel: str) -> Dict[str, Any]:+ is_im = channel.startswith("D")+ info: Dict[str, Any] = {"id": channel, "is_im": is_im, "is_channel": channel.startswith("C"),+ "is_group": channel.startswith("G"), "is_mpim": False, "is_private": not channel.startswith("C"),+ "is_member": True, "is_archived": False, "context_team_id": TEAM_ID}+ if is_im:+ info["user"] = "U" + channel[1:]+ else:+ info["name"] = f"standin-{channel.lower()}"+ return info++ def _m_auth_test(self, _p: Dict[str, Any]) -> Dict[str, Any]:+ return {"url": "https://standin.slack.com/", "team": "Standin", "user": BOT_NAME, "team_id": TEAM_ID,+ "user_id": BOT_USER_ID, "bot_id": BOT_ID, "is_enterprise_install": False}++ def _m_apps_connections_open(self, _p: Dict[str, Any]) -> Dict[str, Any]:+ return {"url": self.ws_url}++ def _m_users_info(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return {"user": self._user(str(p.get("user", "")))}++ def _m_bots_info(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return {"bot": {"id": p.get("bot", BOT_ID), "name": BOT_NAME, "user_id": BOT_USER_ID, "app_id": APP_ID}}++ def _m_conversations_info(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return {"channel": self._channel(str(p.get("channel", "")))}++ def _m_conversations_open(self, p: Dict[str, Any]) -> Dict[str, Any]:+ users = str(p.get("users", "")).split(",")[0]+ return {"channel": self._channel("D" + users[1:])}++ def _thread_messages(self, channel: str, ts: str) -> List[Dict[str, Any]]:+ with self._lock:+ msgs = list(self._history.get(channel, []))+ return [m for m in msgs if m["ts"] == ts or m.get("thread_ts") == ts]++ def _m_conversations_replies(self, p: Dict[str, Any]) -> Dict[str, Any]:+ msgs = self._thread_messages(str(p.get("channel", "")), str(p.get("ts", "")))+ limit = int(p.get("limit") or 1000)+ return {"messages": msgs[:limit], "has_more": False, "response_metadata": {"next_cursor": ""}}++ def _m_conversations_history(self, p: Dict[str, Any]) -> Dict[str, Any]:+ with self._lock:+ msgs = [m for m in self._history.get(str(p.get("channel", "")), []) if not m.get("thread_ts")+ or m.get("thread_ts") == m["ts"]]+ limit = int(p.get("limit") or 100)+ return {"messages": list(reversed(msgs))[:limit], "has_more": False,+ "response_metadata": {"next_cursor": ""}}++ def _remember(self, channel: str, msg: Dict[str, Any]) -> None:+ with self._lock:+ self._history.setdefault(channel, []).append(msg)++ def _bot_post(self, channel: str, text: str, p: Dict[str, Any], kind: str) -> Dict[str, Any]:+ ts = self.next_ts()+ msg = {"type": "message", "user": BOT_USER_ID, "bot_id": BOT_ID, "app_id": APP_ID, "text": text,+ "ts": ts, "team": TEAM_ID}+ if p.get("blocks"):+ msg["blocks"] = p["blocks"]+ thread_ts = p.get("thread_ts")+ if thread_ts:+ msg["thread_ts"] = str(thread_ts)+ self._remember(channel, msg)+ with self._lock:+ self._visible[(channel, ts)] = Visible(ts, text, extra={+ "kind": kind, "thread_ts": msg.get("thread_ts"), "blocks": p.get("blocks")})+ return msg++ def _m_chat_postMessage(self, p: Dict[str, Any]) -> Dict[str, Any]:+ channel = str(p.get("channel", ""))+ text = str(p.get("text") or "")+ if not channel:+ raise _ApiError("channel_not_found")+ if len(text) > MAX_TEXT:+ raise _ApiError("msg_too_long")+ if not text and not p.get("blocks") and not p.get("attachments"):+ raise _ApiError("no_text")+ msg = self._bot_post(channel, text, p, "text")+ return {"channel": channel, "ts": msg["ts"], "message": msg}++ def _m_chat_postEphemeral(self, p: Dict[str, Any]) -> Dict[str, Any]:+ with self._lock:+ self._ephemerals.append({"channel": str(p.get("channel", "")), "user": p.get("user"),+ "text": p.get("text", ""), "via": "chat.postEphemeral"})+ return {"message_ts": self.next_ts()}++ def _vis(self, p: Dict[str, Any]) -> Visible:+ with self._lock:+ vis = self._visible.get((str(p.get("channel", "")), str(p.get("ts", ""))))+ if vis is None or vis.deleted:+ raise _ApiError("message_not_found")+ return vis++ def _m_chat_update(self, p: Dict[str, Any]) -> Dict[str, Any]:+ vis = self._vis(p)+ text = str(p.get("text") or "")+ if len(text) > MAX_TEXT:+ raise _ApiError("msg_too_long")+ with self._lock:+ vis.text = text+ vis.edits += 1+ if "blocks" in p:+ vis.extra["blocks"] = p.get("blocks")+ return {"channel": p["channel"], "ts": p["ts"], "text": text,+ "message": {"type": "message", "user": BOT_USER_ID, "bot_id": BOT_ID, "text": text}}++ def _m_chat_delete(self, p: Dict[str, Any]) -> Dict[str, Any]:+ vis = self._vis(p)+ with self._lock:+ vis.deleted = True+ return {"channel": p["channel"], "ts": p["ts"]}++ def _m_chat_startStream(self, p: Dict[str, Any]) -> Dict[str, Any]:+ channel = str(p.get("channel", ""))+ if not p.get("thread_ts"):+ raise _ApiError("invalid_arguments")+ msg = self._bot_post(channel, str(p.get("markdown_text") or ""), p, "stream")+ return {"channel": channel, "ts": msg["ts"]}++ def _append(self, p: Dict[str, Any], stop: bool) -> Dict[str, Any]:+ vis = self._vis(p)+ if vis.extra.get("stopped"):+ raise _ApiError("message_not_in_streaming_state")+ with self._lock:+ vis.text += str(p.get("markdown_text") or "")+ vis.edits += 1+ if stop:+ vis.extra["stopped"] = True+ if p.get("blocks"):+ vis.extra["blocks"] = p["blocks"]+ return {"channel": p["channel"], "ts": p["ts"]}++ def _m_chat_appendStream(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return self._append(p, stop=False)++ def _m_chat_stopStream(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return self._append(p, stop=True)++ def _m_files_getUploadURLExternal(self, p: Dict[str, Any]) -> Dict[str, Any]:+ fid = f"F{next(self._ids):08d}"+ self.files[fid] = {"id": fid, "name": p.get("filename"), "title": p.get("filename"),+ "size": int(p.get("length") or 0)}+ return {"upload_url": f"{self.base_url}/upload/{fid}", "file_id": fid}++ def _m_files_completeUploadExternal(self, p: Dict[str, Any]) -> Dict[str, Any]:+ entries = p.get("files") or []+ channel = str(p.get("channel_id") or p.get("channels") or "")+ out = []+ for e in entries if isinstance(entries, list) else []:+ f = self.files.setdefault(e["id"], {"id": e["id"]})+ f["title"] = e.get("title") or f.get("title")+ out.append({k: v for k, v in f.items() if not k.startswith("_")})+ if channel:+ comment = str(p.get("initial_comment") or "")+ msg = self._bot_post(channel, comment, {"thread_ts": p.get("thread_ts")}, "file")+ with self._lock:+ self._visible[(channel, msg["ts"])].extra.update(file_id=e["id"], title=f.get("title"))+ return {"files": out}++ def _m_files_info(self, p: Dict[str, Any]) -> Dict[str, Any]:+ f = self.files.get(str(p.get("file", "")))+ if f is None:+ raise _ApiError("file_not_found")+ return {"file": {k: v for k, v in f.items() if not k.startswith("_")}}++ # test-facing inbound -----------------------------------------------------------------------+ def dm_channel(self, user_id: str) -> str:+ return "D" + user_id[1:]++ def message_event(self, channel: str, user_id: str, text: str, *, channel_type: str,+ thread_ts: Optional[str] = None, event_type: str = "message", ts: Optional[str] = None,+ **extra: Any) -> Dict[str, Any]:+ ts = ts or self.next_ts()+ event: Dict[str, Any] = {"type": event_type, "user": user_id, "text": text, "ts": ts, "event_ts": ts,+ "channel": channel, "team": TEAM_ID, "client_msg_id": str(uuid.uuid4()),+ "blocks": [{"type": "rich_text", "block_id": "b1", "elements": [+ {"type": "rich_text_section", "elements": [{"type": "text", "text": text}]}]}]}+ if event_type == "message":+ event["channel_type"] = channel_type+ if thread_ts:+ event["thread_ts"] = thread_ts+ event.update(extra)+ return event++ def deliver(self, event: Dict[str, Any], *, event_id: Optional[str] = None, retry_attempt: int = 0,+ retry_reason: str = "") -> Dict[str, Any]:+ """Wrap ``event`` in an ``event_callback`` and push it over Socket Mode."""+ if retry_attempt == 0 and event.get("type") in ("message", "app_mention") and "subtype" not in event:+ self._remember(event["channel"], {k: v for k, v in event.items() if k != "blocks"})+ payload = {"token": "verification-token", "team_id": TEAM_ID, "api_app_id": APP_ID, "event": event,+ "type": "event_callback", "event_id": event_id or f"Ev{next(self._ids):010d}",+ "event_time": int(float(event.get("event_ts") or time.time())),+ "authorizations": [{"enterprise_id": None, "team_id": TEAM_ID, "user_id": BOT_USER_ID,+ "is_bot": True, "is_enterprise_install": False}],+ "is_ext_shared_channel": False, "event_context": f"4-standin-{uuid.uuid4().hex[:12]}"}+ return self.push("events_api", payload, retry_attempt=retry_attempt, retry_reason=retry_reason)++ def redeliver(self, envelope: Dict[str, Any]) -> Dict[str, Any]:+ """Slack's at-least-once retry: same event_id/event, new envelope, ``retry_attempt`` + 1."""+ payload = envelope["payload"]+ return self.deliver(payload["event"], event_id=payload["event_id"],+ retry_attempt=int(envelope.get("retry_attempt") or 0) + 1, retry_reason="timeout")++ def dm(self, user_id: str, text: str, **extra: Any) -> Dict[str, Any]:+ event = self.message_event(self.dm_channel(user_id), user_id, text, channel_type="im", **extra)+ return self.deliver(event)++ def channel_post(self, channel: str, user_id: str, text: str, *, mention: bool,+ thread_ts: Optional[str] = None) -> List[Dict[str, Any]]:+ """A human posts in a channel. With ``mention`` Slack emits BOTH ``app_mention`` and the+ ``message`` (channel_type=channel) event for the same ts, as separate envelopes."""+ if mention:+ text = f"<@{BOT_USER_ID}> {text}"+ msg = self.message_event(channel, user_id, text, channel_type="channel", thread_ts=thread_ts)+ out = [self.deliver(msg)]+ if mention:+ app_mention = dict(msg, type="app_mention")+ app_mention.pop("channel_type", None)+ out.insert(0, self.deliver(app_mention))+ return out++ def dm_file(self, user_id: str, filename: str, data: bytes, mime: str, caption: str = "") -> Dict[str, Any]:+ fid = f"F{next(self._ids):08d}"+ path = f"{TEAM_ID}-{fid}/{filename}"+ url = f"{self.base_url}/files-pri/{path}"+ self.files[fid] = {"id": fid, "name": filename, "title": filename, "mimetype": mime,+ "filetype": filename.rsplit(".", 1)[-1], "size": len(data), "url_private": url,+ "url_private_download": url, "mode": "hosted", "_path": path, "_data": data}+ public = {k: v for k, v in self.files[fid].items() if not k.startswith("_")}+ event = self.message_event(self.dm_channel(user_id), user_id, caption, channel_type="im",+ subtype="file_share", files=[public])+ return self.deliver(event)++ def block_action(self, user_id: str, channel: str, message_ts: str, action: Dict[str, Any]) -> Dict[str, Any]:+ with self._lock:+ vis = self._visible.get((channel, message_ts))+ message = {"type": "message", "user": BOT_USER_ID, "bot_id": BOT_ID, "ts": message_ts,+ "text": vis.text if vis else "", "blocks": (vis.extra.get("blocks") if vis else None) or []}+ if vis and vis.extra.get("thread_ts"):+ message["thread_ts"] = vis.extra["thread_ts"]+ act = {"action_id": action["action_id"], "block_id": action.get("block_id") or "blk",+ "type": action.get("type", "button"), "value": action.get("value", ""),+ "text": action.get("text") or {"type": "plain_text", "text": action.get("value", "")},+ "action_ts": f"{time.time():.6f}"}+ payload = {"type": "block_actions", "team": {"id": TEAM_ID, "domain": "standin"},+ "user": {"id": user_id, "username": f"user{user_id.lower()}", "name": f"user{user_id.lower()}",+ "team_id": TEAM_ID},+ "api_app_id": APP_ID, "token": "verification-token", "trigger_id": f"trig-{uuid.uuid4().hex[:10]}",+ "container": {"type": "message", "message_ts": message_ts, "channel_id": channel,+ "is_ephemeral": False},+ "channel": {"id": channel, "name": self._channel(channel).get("name", "directmessage")},+ "message": message, "state": {"values": {}},+ "response_url": self._new_response_url(channel, user_id), "actions": [act]}+ return self.push("interactive", payload, accepts_response_payload=False)++ def slash(self, user_id: str, channel: str, command: str, text: str = "") -> Dict[str, Any]:+ payload = {"token": "verification-token", "team_id": TEAM_ID, "team_domain": "standin",+ "channel_id": channel, "channel_name": self._channel(channel).get("name", "directmessage"),+ "user_id": user_id, "user_name": f"user{user_id.lower()}", "command": command, "text": text,+ "api_app_id": APP_ID, "is_enterprise_install": "false",+ "response_url": self._new_response_url(channel, user_id),+ "trigger_id": f"trig-{uuid.uuid4().hex[:10]}"}+ return self.push("slash_commands", payload, accepts_response_payload=True)++ # ground truth ------------------------------------------------------------------------------+ def visible(self, channel: str) -> List[Visible]:+ with self._lock:+ return [v for (c, _), v in self._visible.items() if c == str(channel) and not v.deleted]++ def buttons(self, channel: str) -> List[Dict[str, Any]]:+ """Every button element in blocks the bot currently shows in ``channel`` (with ``message_id``)."""+ out = []+ with self._lock:+ items = [(ts, v) for (c, ts), v in self._visible.items() if c == str(channel) and not v.deleted]+ for ts, vis in items:+ for block in vis.extra.get("blocks") or []:+ if not isinstance(block, dict):+ continue+ elements = block.get("elements") or ([block["accessory"]] if block.get("accessory") else [])+ for el in elements:+ if isinstance(el, dict) and el.get("type") == "button":+ out.append({**el, "block_id": block.get("block_id"), "message_id": ts})+ return out+++class _ApiError(Exception):+ def __init__(self, code: str) -> None:+ super().__init__(code)+ self.code = codediff --git a/tests/fakes/platforms/telegram_standin.py b/tests/fakes/platforms/telegram_standin.pynew file mode 100644index 00000000000..277636e54a0--- /dev/null+++ b/tests/fakes/platforms/telegram_standin.py@@ -0,0 +1,270 @@+"""Telegram Bot API stand-in (https://core.telegram.org/bots/api).++The real ``plugins/platforms/telegram`` adapter reaches it through python-telegram-bot's own+``base_url``/``base_file_url`` (``platforms.telegram.extra.base_url``), so every request crosses the+real PTB HTTP stack: ``POST {base}/bot<token>/<method>`` with form/JSON/multipart parameters, and+long-poll ``getUpdates`` that returns queued ``Update`` objects. Only the methods the adapter calls+are implemented; any other method answers ``ok: true, result: true`` and is still recorded, so a test+can see it.+"""++from __future__ import annotations++import asyncio+import itertools+import time+from typing import Any, Dict, List, Optional++from aiohttp import web++from tests.fakes.platforms._standin import StandinServer, Visible, decode_value++BOT_ID = 7000000001+BOT_USERNAME = "hermes_standin_bot"+MAX_TEXT = 4096+++class TelegramStandin(StandinServer):+ def __init__(self, token: str = "123456:standin-token") -> None:+ super().__init__()+ self.token = token+ self._update_ids = itertools.count(1000)+ self._message_ids = itertools.count(1)+ self._inbound_ids = itertools.count(50_000)+ self._updates: List[Dict[str, Any]] = []+ self._update_event: Optional[asyncio.Event] = None+ self.files: Dict[str, bytes] = {}+ self.file_paths: Dict[str, str] = {}+ # (chat_id, message_id) -> Visible for BOT messages only+ self._visible: Dict[tuple, Visible] = {}+ self.chats: Dict[str, Dict[str, Any]] = {}++ @property+ def api_base(self) -> str:+ return f"{self.base_url}/bot"++ @property+ def file_base(self) -> str:+ return f"{self.base_url}/file/bot"++ # server ------------------------------------------------------------------------------------+ def build_app(self) -> web.Application:+ app = web.Application(client_max_size=64 * 1024 * 1024)+ app.router.add_route("*", "/bot{token}/{method}", self._api)+ app.router.add_get("/file/bot{token}/{path:.*}", self._file)+ return app++ async def _params(self, request: web.Request) -> Dict[str, Any]:+ params: Dict[str, Any] = dict(request.query)+ ctype = request.content_type or ""+ if ctype == "application/json":+ body = await request.json()+ params.update(body or {})+ elif ctype.startswith("multipart/"):+ reader = await request.multipart()+ async for part in reader:+ if part.filename:+ params[part.name] = {"filename": part.filename, "size": len(await part.read())}+ else:+ params[part.name] = decode_value(await part.text())+ elif request.can_read_body:+ for k, v in (await request.post()).items():+ params[k] = decode_value(v) if isinstance(v, str) else v+ return params++ async def _api(self, request: web.Request) -> web.Response:+ method = request.match_info["method"]+ if request.match_info["token"] != self.token:+ return web.json_response({"ok": False, "error_code": 401, "description": "Unauthorized"}, status=401)+ params = await self._params(request)+ if method == "getUpdates":+ result = await self._get_updates(params)+ self.record(method, params, result)+ return web.json_response({"ok": True, "result": result})+ fault = self.take_fault(method, params)+ if fault is not None:+ self.record(method, params, fault.body, faulted=True)+ return web.json_response(fault.body, status=fault.status)+ handler = getattr(self, f"_m_{method}", None)+ result = handler(params) if handler else True+ self.record(method, params, result)+ return web.json_response({"ok": True, "result": result})++ async def _file(self, request: web.Request) -> web.Response:+ path = request.match_info["path"]+ self.record("file_download", {"path": path}, None)+ for file_id, fpath in self.file_paths.items():+ if fpath == path:+ return web.Response(body=self.files[file_id])+ return web.Response(status=404)++ async def _get_updates(self, params: Dict[str, Any]) -> List[Dict[str, Any]]:+ if self._update_event is None:+ self._update_event = asyncio.Event()+ offset = int(params.get("offset") or 0)+ timeout = min(float(params.get("timeout") or 0), 2.0)+ deadline = time.monotonic() + timeout+ while True:+ with self._lock:+ # An update id below the confirmed offset is gone (Bot API semantics); a replay+ # (``redeliver``) re-queues the very same update object with a fresh position.+ self._updates = [u for u in self._updates if u["_replay"] or u["update_id"] >= offset]+ ready = self._updates[:]+ for u in ready:+ u["_replay"] = False+ if ready:+ return [{k: v for k, v in u.items() if k != "_replay"} for u in ready]+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return []+ self._update_event.clear()+ try:+ await asyncio.wait_for(self._update_event.wait(), remaining)+ except asyncio.TimeoutError:+ return []++ def _push(self, update: Dict[str, Any], replay: bool = False) -> None:+ with self._lock:+ self._updates.append({**update, "_replay": replay})+ loop = self._loop+ if loop is not None and self._update_event is not None:+ loop.call_soon_threadsafe(self._update_event.set)++ # Bot API methods ---------------------------------------------------------------------------+ def _bot_user(self) -> Dict[str, Any]:+ return {"id": BOT_ID, "is_bot": True, "first_name": "Hermes", "username": BOT_USERNAME,+ "can_join_groups": True, "can_read_all_group_messages": True, "supports_inline_queries": False}++ def _chat(self, chat_id: Any) -> Dict[str, Any]:+ return self.chats.get(str(chat_id)) or {"id": int(chat_id), "type": "private", "first_name": "User"}++ def _bot_message(self, params: Dict[str, Any], **fields: Any) -> Dict[str, Any]:+ chat_id = str(params["chat_id"])+ mid = next(self._message_ids)+ msg = {"message_id": mid, "date": int(time.time()), "chat": self._chat(chat_id), "from": self._bot_user(),+ **fields}+ if params.get("message_thread_id"):+ msg["message_thread_id"] = int(params["message_thread_id"])+ with self._lock:+ self._visible[(chat_id, str(mid))] = Visible(str(mid), fields.get("text") or fields.get("caption") or "",+ extra={"kind": fields.get("_kind", "text")})+ return msg++ def _m_getMe(self, _p: Dict[str, Any]) -> Dict[str, Any]:+ return self._bot_user()++ def _m_getMyCommands(self, _p: Dict[str, Any]) -> List[Any]:+ return []++ def _m_getChat(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return {**self._chat(p["chat_id"]), "accent_color_id": 0, "max_reaction_count": 11}++ def _m_sendMessage(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return self._bot_message(p, text=p.get("text", ""))++ def _m_sendPhoto(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return self._bot_message(p, caption=p.get("caption", ""), _kind="photo",+ photo=[{"file_id": "out-photo", "file_unique_id": "op", "width": 1, "height": 1}])++ def _m_sendDocument(self, p: Dict[str, Any]) -> Dict[str, Any]:+ return self._bot_message(p, caption=p.get("caption", ""), _kind="document",+ document={"file_id": "out-doc", "file_unique_id": "od"})++ def _m_editMessageText(self, p: Dict[str, Any]) -> Dict[str, Any]:+ chat_id, mid = str(p["chat_id"]), str(p["message_id"])+ with self._lock:+ vis = self._visible.get((chat_id, mid))+ if vis is not None:+ vis.text = p.get("text", "")+ vis.edits += 1+ return {"message_id": int(mid), "date": int(time.time()), "chat": self._chat(chat_id),+ "from": self._bot_user(), "text": p.get("text", ""), "edit_date": int(time.time())}++ def _m_editMessageReplyMarkup(self, p: Dict[str, Any]) -> Any:+ return {"message_id": int(p["message_id"]), "date": int(time.time()), "chat": self._chat(p["chat_id"]),+ "from": self._bot_user(), "text": ""}++ def _m_deleteMessage(self, p: Dict[str, Any]) -> bool:+ with self._lock:+ vis = self._visible.get((str(p["chat_id"]), str(p["message_id"])))+ if vis is not None:+ vis.deleted = True+ return True++ def _m_getFile(self, p: Dict[str, Any]) -> Dict[str, Any]:+ fid = p["file_id"]+ return {"file_id": fid, "file_unique_id": f"u-{fid}", "file_size": len(self.files.get(fid, b"")),+ "file_path": self.file_paths.get(fid, f"documents/{fid}")}++ # test-facing driver ------------------------------------------------------------------------+ def _user(self, user_id: int, name: str = "Tester") -> Dict[str, Any]:+ return {"id": int(user_id), "is_bot": False, "first_name": name, "username": f"user{user_id}",+ "language_code": "en"}++ def _inbound(self, chat: Dict[str, Any], user_id: int, **fields: Any) -> Dict[str, Any]:+ self.chats[str(chat["id"])] = chat+ mid = next(self._inbound_ids)+ update = {"update_id": next(self._update_ids),+ "message": {"message_id": mid, "date": int(time.time()), "chat": chat,+ "from": self._user(user_id), **fields}}+ self._push(update)+ return update++ def dm(self, user_id: int, text: str) -> Dict[str, Any]:+ chat = {"id": int(user_id), "type": "private", "first_name": "Tester", "username": f"user{user_id}"}+ return self._inbound(chat, user_id, text=text)++ def group(self, chat_id: int, user_id: int, text: str, *, mention: bool) -> Dict[str, Any]:+ chat = {"id": int(chat_id), "type": "supergroup", "title": "Standin Group"}+ fields: Dict[str, Any] = {"text": text}+ if mention:+ handle = f"@{BOT_USERNAME}"+ fields["text"] = f"{handle} {text}"+ fields["entities"] = [{"type": "mention", "offset": 0, "length": len(handle)}]+ return self._inbound(chat, user_id, **fields)++ def dm_document(self, user_id: int, filename: str, data: bytes, mime: str, caption: str = "") -> Dict[str, Any]:+ fid = f"doc-{len(self.files) + 1}"+ self.files[fid] = data+ self.file_paths[fid] = f"documents/{filename}"+ chat = {"id": int(user_id), "type": "private", "first_name": "Tester"}+ fields: Dict[str, Any] = {"document": {"file_id": fid, "file_unique_id": f"u-{fid}", "file_name": filename,+ "mime_type": mime, "file_size": len(data)}}+ if caption:+ fields["caption"] = caption+ return self._inbound(chat, user_id, **fields)++ def callback(self, user_id: int, chat_id: int, message_id: int, data: str) -> Dict[str, Any]:+ """A user clicks an inline button under bot message ``message_id``."""+ chat = self._chat(chat_id)+ with self._lock:+ vis = self._visible.get((str(chat_id), str(message_id)))+ update = {"update_id": next(self._update_ids),+ "callback_query": {"id": f"cb-{next(self._inbound_ids)}", "from": self._user(user_id),+ "chat_instance": f"ci-{chat_id}", "data": data,+ "message": {"message_id": int(message_id), "date": int(time.time()),+ "chat": chat, "from": self._bot_user(),+ "text": vis.text if vis else ""}}}+ self._push(update)+ return update++ def redeliver(self, update: Dict[str, Any]) -> None:+ """Serve an already-delivered update again (a Bot API replay after a lost offset ack)."""+ self._push(dict(update), replay=True)++ def visible(self, chat_id: Any) -> List[Visible]:+ with self._lock:+ return [v for (c, _), v in self._visible.items() if c == str(chat_id) and not v.deleted]++ def buttons(self, chat_id: Any) -> List[Dict[str, Any]]:+ """Every inline button the bot attached to a message in ``chat_id`` (with its message id)."""+ out = []+ for call in self.calls_of("sendMessage", "editMessageText", "editMessageReplyMarkup"):+ if str(call.params.get("chat_id")) != str(chat_id) or call.faulted:+ continue+ markup = call.params.get("reply_markup") or {}+ mid = call.params.get("message_id") or (call.response or {}).get("message_id")+ for row in (markup.get("inline_keyboard") or []) if isinstance(markup, dict) else []:+ for btn in row:+ out.append({**btn, "message_id": mid})+ return out