diff --git a/integrations/hermes-t3-gateway/README.md b/integrations/hermes-t3-gateway/README.md index b177f3067b..bab1f7cd43 100644 --- a/integrations/hermes-t3-gateway/README.md +++ b/integrations/hermes-t3-gateway/README.md @@ -84,6 +84,14 @@ registered as the instance's primary connection, so it cannot disturb a running `hermes gateway`. If T3 is unreachable the delivery is queued and the cron job still reports success. +Attachments ride the same queue-then-ack durability as text: one `media.deliver` +frame per file, each carrying the file's bytes rather than its path, so a +delivery that flushes after an outage still works when the original temp file is +long gone. The raw ceiling is 25MiB per file. A file that cannot be read or that +exceeds the ceiling is reported in the result's `detail` and skipped rather than +queued — a frame T3 would reject forever must not sit in the outbox forever. +Every send result also reports `media_count`, `acked_count`, and `delivery_ids`. + ## Initial scope - Text input and live assistant streaming @@ -98,12 +106,57 @@ still reports success. - Proactive delivery into the Home thread: cron, `send_message`, lifecycle notices, `/handoff` — with a durable queue and out-of-process cron support +- Inbound attachments: files sent from T3 ride `turn.start` / `turn.steer` and + reach Hermes as ordinary media on the message event +- Outbound attachments: `MEDIA:` files from cron, `send_message`, and `/handoff` + are delivered as `media.deliver` frames Non-home T3 threads remain session-only: Hermes cannot message them unprompted, and an unsolicited send to one still fails with `no active T3 turn`. -Attachments intentionally advertise `false`. Adding bounded image/file input is -the first post-stability feature and should not reuse arbitrary raw payloads. +Attachments are pinned to `true`. It is part of the v4 contract rather than a +negotiated option — T3's schema fixes the capability at that literal, so a plugin +that cannot handle attachments is by definition a v3 plugin and is rejected at +the version gate. Inbound files arrive on `turn.start` / `turn.steer` and are +materialized to private temp files before the turn starts; outbound files leave +as `media.deliver` frames. + +## Upstream core bugs this plugin works around + +Hermes core decides media support for `send_message` from a hard-coded list of +platform names rather than from a platform capability, so a plugin platform that +delivers media perfectly well is still treated as if it cannot. Two consequences, +both against **v0.19.0**: + +- **A false warning.** `tools/send_message_tool.py:1108` builds `"MEDIA + attachments were omitted for t3; ..."` whenever a send carries files and the + platform is off that list, and line 1154 appends it to *any* successful result + without checking whether anything was actually dropped. Left alone, the tool + output tells the agent the files were lost immediately after T3 acknowledged + them — which is exactly how a live agent came to report a delivery failure for + files the user could already see. +- **A silent drop.** `tools/send_message_tool.py:711`, taken when the gateway is + co-resident with the caller, invokes `adapter.send(chat_id, content, metadata)` + and returns. `media_files` is never passed, and the `MEDIA:` directives were + already stripped out of `content` upstream at line 442, so the attachments are + simply gone — no error, no warning. Out-of-process sends escape this only + because they fall through to the plugin's standalone sender instead. + +`coreshim.py` compensates for both in-process at plugin load: co-resident `t3` +sends carrying media are rerouted through the plugin's own sender, media-only +sends are rescued from the related hard error at line 1101, and the false warning +is stripped by stable prefix. Everything else — every other platform, every +text-only send — reaches the original untouched. + +**Residual caveat.** The shim is deliberately fail-open: it feature-detects each +target function and, on any signature or shape mismatch, logs one warning and +leaves core alone rather than risking a crash on an upstream upgrade. When that +happens the two bugs return as described above. The accounting keys on every +send result (`media_count`, `acked_count`, and a note naming the delivered file +count) are the backstop — they sit in the same JSON as any stale warning and +contradict it directly. Grep the logs for `leaving it unpatched` to detect it. +The whole module is removable once upstream drives media handling from platform +capabilities instead of the hard-coded list. See [COMPATIBILITY.md](./COMPATIBILITY.md) for public Hermes extension-surface limitations. diff --git a/integrations/hermes-t3-gateway/__init__.py b/integrations/hermes-t3-gateway/__init__.py index a7bee8dd63..c8a5dac735 100644 --- a/integrations/hermes-t3-gateway/__init__.py +++ b/integrations/hermes-t3-gateway/__init__.py @@ -10,6 +10,7 @@ from .adapter import ( validate_config, ) from .cli import register_cli, t3_command +from .coreshim import apply as apply_core_shim from .home import HOME_CHANNEL_ENV, standalone_send @@ -89,6 +90,16 @@ def register(ctx) -> None: ) ctx.register_hook("pre_tool_call", _pre_tool_call) ctx.register_hook("post_tool_call", _post_tool_call) + # Compensate two upstream `send_message` media defects in-process (see + # `coreshim.py` for the file:line analysis). Applied after the platform is + # registered because the Bug B wrapper routes through `standalone_send`, + # which resolves the same enrollment the entry above advertises. This runs + # in every process that loads plugins — `hermes gateway`, `hermes cron`, and + # the `hermes send` CLI, which reaches `register()` via + # `tools/send_message_tool.py:399` -> `gateway/config.py:2530` well before + # it routes a send. Never raises: on any mismatch it logs one warning and + # leaves core untouched. + apply_core_shim() __all__ = ["register"] diff --git a/integrations/hermes-t3-gateway/coreshim.py b/integrations/hermes-t3-gateway/coreshim.py new file mode 100644 index 0000000000..328bbeb556 --- /dev/null +++ b/integrations/hermes-t3-gateway/coreshim.py @@ -0,0 +1,348 @@ +"""In-process compensation for two upstream `send_message` media defects. + +Both defects live in Hermes core's `tools/send_message_tool.py` and both are +about plugin platforms that *can* carry media but are not on core's hard-coded +prose list. Line numbers below are against **Hermes v0.19.0**. + +**Bug A — the false warning (cosmetic, but it lies to the agent).** +`tools/send_message_tool.py:1108-1113` precomputes:: + + warning = f"MEDIA attachments were omitted for {platform.value}; ..." + +whenever `media_files` is non-empty and the platform is not one of the nine +names spelled out in that string. Line 1154-1157 then appends it to *any* +successful result without ever consulting whether the send actually dropped +anything. Our standalone sender delivers media as `media.deliver` frames and +waits for the acks — and is then told, in the same JSON blob, that the files +were omitted. A live agent read that warning and reported a delivery failure to +the user for files T3 had already rendered. + +**Bug B — the silent drop (the one that actually loses data).** +`tools/send_message_tool.py:711-732`: when the gateway is co-resident, the +runner weakref resolves and `runner.adapters.get(platform)` returns our live +adapter, so core calls:: + + result = await adapter.send(chat_id=chat_id, content=chunk, metadata=metadata) + +and returns. `media_files` is never passed. It cannot be recovered from +`content` either, because `BasePlatformAdapter.extract_media` +(`tools/send_message_tool.py:442`) already stripped the `MEDIA:` directives out +of the text before chunking. So `send_message` / `hermes send` with attachments, +run in the same process as `hermes gateway`, loses the files with no error and +no warning. This went unnoticed in live testing only because `hermes send` ran +out-of-process, where the runner weakref is empty and core falls through to the +`standalone_sender_fn` path (line 731+), which does pass `media_files`. + +**What this module does.** At plugin load it wraps the two functions in the +already-imported `tools.send_message_tool` module object: + +* `_send_via_adapter` — for platform `t3` with non-empty `media_files`, skip + core's live-adapter shortcut entirely and call our own `standalone_send` + (from `.home`), which handles media correctly. Text-only `t3` sends and every + other platform reach the original function untouched. +* `_send_to_platform` — post-process the result, dropping the Bug A warning from + `result["warnings"]`. Matched by the stable prefix `"MEDIA attachments were + omitted for t3"`, never the full prose: the nine-platform list inside that + sentence changes between releases, and matching it exactly would silently + stop working on the next upgrade. + +**Removable.** Both wrappers become dead weight the moment upstream grows +capability-driven media handling — i.e. once `PlatformEntry` can advertise +"this platform delivers media" and core consults it instead of the hard-coded +list, and once the co-resident branch forwards `media_files` to `adapter.send`. +Delete this module and its `register()` call at that point; nothing else in the +plugin depends on it. + +**Fail-open contract.** This module never raises into the plugin's `register()` +and never makes a working Hermes worse: + +* Every patch feature-detects its target first — the module must be importable, + the attribute must exist, it must be a coroutine function, and its signature + must carry the parameters we rely on. Any mismatch means no patch. +* On any failure we log exactly one warning and leave core untouched. The + fallback is the current upstream behaviour: buggy, but working and known. +* An upstream upgrade that renames, re-signatures, or restructures these + functions therefore degrades to "unpatched", never to a crash. +* Applying twice is a no-op — the wrappers carry a marker attribute. + +Even fully failed open, the residual damage is bounded: `standalone_send` +stamps `media_count` / `acked_count` / a delivered-count `note` onto every +success result (see `home.py`), so the false warning always sits next to +counter-evidence. The un-compensated Bug B remains a real silent drop, which is +why the patch is attempted at all. +""" + +from __future__ import annotations + +import inspect +import logging +from typing import Any, Callable + +logger = logging.getLogger(__name__) + +PLATFORM = "t3" + +# Bug A's warning text, matched by prefix only. The remainder of the sentence +# names the platforms core believes support media, and that list has changed +# across releases — pinning the full prose would silently stop matching. The +# trailing ";" is part of the prefix and load-bearing: without it the match is +# also satisfied by a platform whose name merely *starts with* "t3". +_OMISSION_WARNING_PREFIX = f"MEDIA attachments were omitted for {PLATFORM};" + +# Marker set on every wrapper we install, so a second `register()` (or a +# `discover_plugins(force=True)` rescan) does not stack wrappers on wrappers. +_MARKER = "_t3_gateway_shim" + + +def _platform_name(platform: Any) -> str: + """Core passes a `Platform` enum member; be liberal about what we accept.""" + value = getattr(platform, "value", platform) + return str(value or "").strip().lower() + + +def _target_module() -> Any | None: + """Return the upstream module, or None when it cannot be imported. + + Imported lazily and defensively: this plugin is loaded by Hermes itself, so + the module is normally already in `sys.modules` and this is a dict hit, but + a stripped or restructured install must degrade to "no patch" rather than + breaking plugin registration. + """ + try: + import tools.send_message_tool as module + + return module + except Exception: # noqa: BLE001 - any import failure means "do not patch" + logger.warning( + "T3 gateway: tools.send_message_tool is unavailable; leaving core " + "send_message unpatched (media may be dropped on the co-resident " + "path and a false omission warning may appear)", + exc_info=True, + ) + return None + + +def _usable(module: Any, name: str, required_params: tuple[str, ...]) -> Callable | None: + """Feature-detect one patch target. Returns the function, or None. + + Checks, in order: the attribute exists, it is a coroutine function (we wrap + it with `async def`, so a sync target would break every caller), it is not + already wrapped, and its signature exposes the parameters this shim reads by + name. A `*args, **kwargs`-style signature is accepted only if the named + parameters are genuinely present — we never guess positionally. + """ + original = getattr(module, name, None) + if original is None: + logger.warning( + "T3 gateway: %s.%s is missing; leaving it unpatched", module.__name__, name + ) + return None + if getattr(original, _MARKER, False): + return None # already patched; idempotent no-op, nothing to report + if not inspect.iscoroutinefunction(original): + logger.warning( + "T3 gateway: %s.%s is not a coroutine function; leaving it unpatched", + module.__name__, + name, + ) + return None + try: + parameters = inspect.signature(original).parameters + except (TypeError, ValueError): + logger.warning( + "T3 gateway: %s.%s has an unreadable signature; leaving it unpatched", + module.__name__, + name, + exc_info=True, + ) + return None + missing = [param for param in required_params if param not in parameters] + if missing: + logger.warning( + "T3 gateway: %s.%s no longer takes %s; leaving it unpatched (upstream " + "may have fixed this, or changed shape)", + module.__name__, + name, + ", ".join(missing), + ) + return None + return original + + +def _patch_send_via_adapter(module: Any) -> bool: + """Bug B: route co-resident `t3` media sends through our own sender.""" + original = _usable( + module, + "_send_via_adapter", + ("platform", "pconfig", "chat_id", "chunk", "thread_id", "media_files"), + ) + if original is None: + return False + + from .home import standalone_send + + async def _send_via_adapter( + platform, + pconfig, + chat_id, + chunk, + *, + thread_id=None, + media_files=None, + force_document=False, + ): + if _platform_name(platform) == PLATFORM and media_files: + # Core would hand this to `adapter.send(chat_id, content, metadata)` + # and drop `media_files` on the floor. Our sender takes the whole + # send — text frame plus one media frame per file — over a + # short-lived `role: "delivery"` socket, which by design cannot + # displace the live gateway connection sitting in the same process. + return await standalone_send( + pconfig, + chat_id, + chunk, + thread_id=thread_id, + media_files=media_files, + force_document=force_document, + ) + return await original( + platform, + pconfig, + chat_id, + chunk, + thread_id=thread_id, + media_files=media_files, + force_document=force_document, + ) + + setattr(_send_via_adapter, _MARKER, True) + _send_via_adapter.__wrapped__ = original + module._send_via_adapter = _send_via_adapter + return True + + +def _strip_false_warning(result: Any) -> Any: + """Drop Bug A's warning from a result dict, in place. Anything else passes.""" + if not isinstance(result, dict): + return result + warnings = result.get("warnings") + if not isinstance(warnings, list): + return result + kept = [ + warning + for warning in warnings + if not ( + isinstance(warning, str) + and warning.startswith(_OMISSION_WARNING_PREFIX) + ) + ] + if len(kept) == len(warnings): + return result + if kept: + result["warnings"] = kept + else: + # An empty list would still read as "this send had warnings" to a + # skimming agent; the key is optional upstream, so remove it. + result.pop("warnings", None) + return result + + +def _patch_send_to_platform(module: Any) -> bool: + """Bug A: strip the unconditional omission warning, and rescue media-only sends. + + Two interceptions, both scoped to media-bearing `t3` sends: + + *Before* the original, one narrow bypass. A send with attachments and no + text hard-errors at `tools/send_message_tool.py:1101-1107` (v0.19.0):: + + if media_files and not message.strip(): + return {"error": "... target t3 had only media attachments"} + + That check sits above the chunk loop, so the send never reaches + `_send_via_adapter` and the Bug B patch cannot see it. `MEDIA:/tmp/x.png` + with no prose — a perfectly ordinary agent send — fails outright. We route + it straight to our sender, which already handles an empty message by + emitting media frames only. Chunking is not skipped in any meaningful sense: + there is no text to chunk. + + *After* the original, warning removal. Post-processing is the least invasive + seam available: `_send_to_platform` is a ~380-line router whose warning is + computed at line 1111 and attached at line 1154 with nothing interceptable + in between. The original runs in full and we drop only the one warning we + know to be false; every other warning it may add survives, and non-`t3` + results are returned without even being inspected. + + A success from our sender means the frames were handed over — acked, or + durably queued for the next connect (`media_count` / `acked_count` on the + result say which). Nothing deliverable is reported as a hard `error`. + """ + original = _usable( + module, + "_send_to_platform", + ("platform", "pconfig", "chat_id", "message", "thread_id", "media_files"), + ) + if original is None: + return False + + from .home import standalone_send + + async def _send_to_platform( + platform, + pconfig, + chat_id, + message, + thread_id=None, + media_files=None, + force_document=False, + ): + is_t3_media = _platform_name(platform) == PLATFORM and bool(media_files) + if is_t3_media and not str(message or "").strip(): + return await standalone_send( + pconfig, + chat_id, + message or "", + thread_id=thread_id, + media_files=media_files, + force_document=force_document, + ) + result = await original( + platform, + pconfig, + chat_id, + message, + thread_id=thread_id, + media_files=media_files, + force_document=force_document, + ) + if not is_t3_media: + return result + if isinstance(result, dict) and result.get("success"): + return _strip_false_warning(result) + return result + + setattr(_send_to_platform, _MARKER, True) + _send_to_platform.__wrapped__ = original + module._send_to_platform = _send_to_platform + return True + + +def apply(module: Any | None = None) -> dict[str, bool]: + """Install both wrappers. Never raises. + + Returns a per-patch applied/not-applied map, which is what the tests assert + on. `module` is injectable so tests can drive a faithful fake of the + upstream shape without importing Hermes. + """ + applied = {"_send_via_adapter": False, "_send_to_platform": False} + try: + target = module if module is not None else _target_module() + if target is None: + return applied + applied["_send_via_adapter"] = _patch_send_via_adapter(target) + applied["_send_to_platform"] = _patch_send_to_platform(target) + except Exception: # noqa: BLE001 - a broken shim must not break the plugin + logger.warning( + "T3 gateway: could not patch core send_message; leaving it unpatched", + exc_info=True, + ) + return applied diff --git a/integrations/hermes-t3-gateway/home.py b/integrations/hermes-t3-gateway/home.py index 1464fe30dd..293fafa895 100644 --- a/integrations/hermes-t3-gateway/home.py +++ b/integrations/hermes-t3-gateway/home.py @@ -611,6 +611,14 @@ async def standalone_send( that T3 will always reject would sit in the outbox forever. `force_document` remains signature parity only: T3 derives rendering from `mimeType`, so there is no document/photo distinction to force. + + Every success result carries additive accounting keys alongside the + unchanged `message_id`: `delivery_ids` (every frame this call minted, text + and media), `media_count`, `acked_count`, and — when media was sent — a + `note` naming the delivered file count. Upstream consumers read this dict by + specific key and otherwise `json.dumps` it wholesale, so extra keys are + inert there while giving an agent reading the tool output direct evidence + against core's unconditional "MEDIA attachments were omitted" warning. """ del force_document @@ -643,6 +651,7 @@ async def standalone_send( kind, label, _certain = classify_delivery(message, None) frames: list[dict[str, Any]] = [] + media_ids: list[str] = [] skipped: list[str] = [] # The text frame is skipped only when media makes the send non-empty # anyway; a bare text send keeps today's behaviour (empty text normalizes @@ -654,13 +663,11 @@ async def standalone_send( for entry in media_files or []: media_path = entry[0] if isinstance(entry, (tuple, list)) else entry try: - frames.append( - build_media_delivery( - thread_id=target, - path=str(media_path), - kind=kind, - label=label, - ) + media_frame = build_media_delivery( + thread_id=target, + path=str(media_path), + kind=kind, + label=label, ) except Exception as exc: # noqa: BLE001 - one bad file must not sink the send # Never queued: a frame T3 will always reject (unreadable then, @@ -669,12 +676,45 @@ async def standalone_send( "T3 standalone send skipping media file %s: %s", media_path, exc ) skipped.append(f"{media_path}: {exc}") + else: + frames.append(media_frame) + media_ids.append(str(media_frame["deliveryId"])) if not frames: return { "error": "T3 standalone send: no deliverable content " + "; ".join(skipped) } delivery = str(frames[0]["deliveryId"]) + all_ids = [str(frame["deliveryId"]) for frame in frames] + + def _observed( + result: dict[str, Any], acked_ids: set[str], *, queued_only: bool + ) -> dict[str, Any]: + """Attach the additive delivery-accounting keys to a success result. + + `message_id` is deliberately untouched — upstream reads that key by + name. Everything here is new, and exists as **counter-evidence**: core + appends a hard-coded "MEDIA attachments were omitted for t3" warning to + any successful generic-path send (`tools/send_message_tool.py:1108` @ + v0.19.0) without ever asking whether the sender delivered them. The + `coreshim` module strips that warning when it can, but if it has failed + open the numbers below still sit in the same JSON blob the agent reads, + so "2 media file(s) delivered and acknowledged" contradicts the stale + warning directly rather than leaving the agent to guess. + """ + acked_media = [entry for entry in media_ids if entry in acked_ids] + result["delivery_ids"] = list(all_ids) + result["media_count"] = len(media_ids) + result["acked_count"] = len(acked_ids) + if media_ids: + verb = "queued for delivery" if queued_only else "delivered" + count = len(media_ids) if queued_only else len(acked_media) + note = f"{count} media file(s) {verb}" + if not queued_only: + note += " and acknowledged" + existing = str(result.get("note") or "").strip() + result["note"] = f"{existing}; {note}" if existing else note + return result queue = HomeDeliveryQueue() queued = all(queue.append(frame) for frame in frames) @@ -689,12 +729,16 @@ async def standalone_send( except Exception as exc: # noqa: BLE001 - cron delivery must not raise logger.debug("T3 standalone send raised", exc_info=True) if queued: - return { - "success": True, - "message_id": delivery, - "queued": True, - "detail": f"T3 unreachable ({exc}); queued for the next connect", - } + return _observed( + { + "success": True, + "message_id": delivery, + "queued": True, + "detail": f"T3 unreachable ({exc}); queued for the next connect", + }, + set(), + queued_only=True, + ) return {"error": f"T3 standalone send failed: {exc}"} for acked_id in acked: @@ -704,17 +748,21 @@ async def standalone_send( result: dict[str, Any] = {"success": True, "message_id": delivery} if result_detail: result["detail"] = result_detail - return result + return _observed(result, acked, queued_only=False) if queued: - return { - "success": True, - "message_id": delivery, - "queued": True, - "detail": ( - "T3 did not acknowledge every delivery; queued for retry" - + (f" ({result_detail})" if result_detail else "") - ), - } + return _observed( + { + "success": True, + "message_id": delivery, + "queued": True, + "detail": ( + "T3 did not acknowledge every delivery; queued for retry" + + (f" ({result_detail})" if result_detail else "") + ), + }, + acked, + queued_only=len(acked) == 0, + ) return {"error": "T3 standalone send: the delivery was neither acked nor queued"} diff --git a/integrations/hermes-t3-gateway/tests/test_coreshim.py b/integrations/hermes-t3-gateway/tests/test_coreshim.py new file mode 100644 index 0000000000..ec5bc7ab9e --- /dev/null +++ b/integrations/hermes-t3-gateway/tests/test_coreshim.py @@ -0,0 +1,420 @@ +"""Tests for the in-process compensation of two upstream `send_message` bugs. + +The fake `tools.send_message_tool` below models the shape `coreshim` actually +depends on at Hermes v0.19.0 — the two coroutine signatures, the live-adapter +shortcut that drops `media_files` (Bug B, upstream line 711), the unconditional +omission warning (Bug A, upstream line 1108), and the media-only hard error +(upstream line 1101). It is deliberately a stand-in and not an import of the +real module: these tests must run with no Hermes installed. +""" + +from __future__ import annotations + +import enum +import importlib.util +import pathlib +import sys +import types +import unittest +import unittest.mock + +ROOT = pathlib.Path(__file__).resolve().parents[1] +PACKAGE = "hermes_t3_gateway_coreshim_test" + +package = types.ModuleType(PACKAGE) +package.__path__ = [str(ROOT)] +sys.modules.setdefault(PACKAGE, package) + +for _name in ("protocol", "connection", "home", "coreshim"): + _spec = importlib.util.spec_from_file_location( + f"{PACKAGE}.{_name}", ROOT / f"{_name}.py" + ) + assert _spec and _spec.loader + _module = importlib.util.module_from_spec(_spec) + sys.modules[f"{PACKAGE}.{_name}"] = _module + _spec.loader.exec_module(_module) + +coreshim = sys.modules[f"{PACKAGE}.coreshim"] +home = sys.modules[f"{PACKAGE}.home"] + + +class Platform(str, enum.Enum): + """Core passes an enum whose `.value` is the platform name.""" + + T3 = "t3" + TELEGRAM = "telegram" + + +# The nine platforms core hard-codes into the warning at upstream line 1112. +# The exact list is version-dependent, which is precisely why the shim matches +# on prefix — this fake spells it out so a prefix regression would be caught. +_SUPPORTED = ( + "telegram, discord, matrix, weixin, signal, yuanbao, feishu, whatsapp and slack" +) + + +def _fake_core() -> types.ModuleType: + """Build a module that reproduces the two defects faithfully.""" + module = types.ModuleType("tools.send_message_tool") + module.calls = [] + # Set by the test to simulate a co-resident gateway (Bug B's precondition). + module.live_adapter = None + # Warnings from unrelated causes, which the shim must never touch. + module.extra_warnings = [] + + async def _send_via_adapter( + platform, + pconfig, + chat_id, + chunk, + *, + thread_id=None, + media_files=None, + force_document=False, + ): + module.calls.append( + { + "fn": "_send_via_adapter", + "platform": platform, + "chat_id": chat_id, + "chunk": chunk, + "media_files": media_files, + "thread_id": thread_id, + } + ) + if module.live_adapter is not None: + # Bug B, upstream `tools/send_message_tool.py:711-732`: the live + # adapter is handed content and metadata only. `media_files` is + # dropped here, and the text was already stripped of its `MEDIA:` + # directives upstream at line 442, so nothing downstream can + # recover the attachments. + return await module.live_adapter(chat_id=chat_id, content=chunk) + return {"success": True, "message_id": "standalone-fallback"} + + async def _send_to_platform( + platform, + pconfig, + chat_id, + message, + thread_id=None, + media_files=None, + force_document=False, + ): + module.calls.append( + { + "fn": "_send_to_platform", + "platform": platform, + "message": message, + "media_files": media_files, + } + ) + name = platform.value if hasattr(platform, "value") else str(platform) + # Upstream line 1101-1107. + if media_files and not message.strip(): + return { + "error": ( + "send_message MEDIA delivery is currently only supported for " + f"{_SUPPORTED}; target {name} had only media attachments" + ) + } + # Upstream line 1108-1113: computed with no reference to what the + # sender below actually does. + warning = None + if media_files: + warning = ( + f"MEDIA attachments were omitted for {name}; native send_message " + f"media delivery is currently only supported for {_SUPPORTED}" + ) + # Resolved off the module, exactly as upstream's module-level call does + # — so a patched `_send_via_adapter` is genuinely reached from here, + # which is what makes the co-resident interception testable. + result = await module._send_via_adapter( + platform, + pconfig, + chat_id, + message, + thread_id=thread_id, + media_files=media_files, + force_document=force_document, + ) + # Upstream line 1154-1157. + if warning and isinstance(result, dict) and result.get("success"): + warnings = list(result.get("warnings", [])) + warnings.extend(module.extra_warnings) + warnings.append(warning) + result["warnings"] = warnings + return result + + module._send_via_adapter = _send_via_adapter + module._send_to_platform = _send_to_platform + return module + + +class ShimApplicationTests(unittest.TestCase): + def test_both_wrappers_attach_to_a_faithful_module(self): + module = _fake_core() + self.assertEqual( + coreshim.apply(module), + {"_send_via_adapter": True, "_send_to_platform": True}, + ) + + def test_applying_twice_does_not_stack_wrappers(self): + """`register()` can run more than once (e.g. discover_plugins(force=True)).""" + module = _fake_core() + coreshim.apply(module) + first = module._send_via_adapter + second_pass = coreshim.apply(module) + + self.assertEqual( + second_pass, {"_send_via_adapter": False, "_send_to_platform": False} + ) + self.assertIs(module._send_via_adapter, first) + # One layer deep, still the genuine original. + self.assertFalse( + hasattr(module._send_via_adapter.__wrapped__, "__wrapped__") + ) + + +class FailOpenTests(unittest.TestCase): + """A shape mismatch must leave core exactly as it was, never raise.""" + + def _assert_untouched(self, module, applied, attribute): + self.assertFalse(applied[attribute]) + self.assertFalse(getattr(getattr(module, attribute, None), "_t3_gateway_shim", False)) + + def test_a_renamed_parameter_blocks_the_patch(self): + module = _fake_core() + + async def _renamed(platform, pconfig, chat_id, chunk, *, thread_id=None, attachments=None): + return {"success": True} + + module._send_via_adapter = _renamed + with self.assertLogs(coreshim.logger, level="WARNING") as logs: + applied = coreshim.apply(module) + + self._assert_untouched(module, applied, "_send_via_adapter") + self.assertIs(module._send_via_adapter, _renamed) + self.assertTrue(any("media_files" in line for line in logs.output)) + # The unrelated patch still lands — one mismatch does not disarm both. + self.assertTrue(applied["_send_to_platform"]) + + def test_a_missing_function_blocks_the_patch(self): + module = _fake_core() + del module._send_to_platform + with self.assertLogs(coreshim.logger, level="WARNING") as logs: + applied = coreshim.apply(module) + + self.assertFalse(applied["_send_to_platform"]) + self.assertFalse(hasattr(module, "_send_to_platform")) + self.assertTrue(any("is missing" in line for line in logs.output)) + + def test_a_sync_rewrite_blocks_the_patch(self): + """If upstream ever makes these sync, an async wrapper would break callers.""" + module = _fake_core() + + def _sync(platform, pconfig, chat_id, chunk, *, thread_id=None, media_files=None): + return {"success": True} + + module._send_via_adapter = _sync + with self.assertLogs(coreshim.logger, level="WARNING") as logs: + applied = coreshim.apply(module) + + self._assert_untouched(module, applied, "_send_via_adapter") + self.assertTrue(any("coroutine" in line for line in logs.output)) + + def test_an_unimportable_core_is_survivable(self): + """The real `apply()` with no Hermes on the path must not raise.""" + with unittest.mock.patch.dict(sys.modules, {}, clear=False): + sys.modules.pop("tools.send_message_tool", None) + with self.assertLogs(coreshim.logger, level="WARNING"): + applied = coreshim.apply() + self.assertEqual( + applied, {"_send_via_adapter": False, "_send_to_platform": False} + ) + + +class RoutingTests(unittest.IsolatedAsyncioTestCase): + """Behaviour of the patched functions, with `standalone_send` stubbed.""" + + def setUp(self): + self.module = _fake_core() + self.sends = [] + + async def _standalone_send( + pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False + ): + self.sends.append( + { + "chat_id": chat_id, + "message": message, + "media_files": media_files, + "thread_id": thread_id, + "force_document": force_document, + } + ) + return { + "success": True, + "message_id": "t3-delivery", + "media_count": len(media_files or []), + "acked_count": 1 + len(media_files or []), + "note": f"{len(media_files or [])} media file(s) delivered and acknowledged", + } + + patch = unittest.mock.patch.object(home, "standalone_send", _standalone_send) + patch.start() + self.addCleanup(patch.stop) + coreshim.apply(self.module) + + async def _live_adapter(*, chat_id, content): + # Whatever core hands the live adapter is all it ever sees. + return {"success": True, "message_id": "live-adapter"} + + self.module.live_adapter = _live_adapter + + async def test_co_resident_t3_media_bypasses_the_live_adapter(self): + """Bug B: the files must reach our sender, not the media-blind adapter.""" + result = await self.module._send_via_adapter( + Platform.T3, + None, + "home-thread", + "Here is the chart", + thread_id="thread-1", + media_files=[("/tmp/chart.png", False)], + ) + + self.assertEqual(result["message_id"], "t3-delivery") + self.assertEqual(len(self.sends), 1) + self.assertEqual(self.sends[0]["media_files"], [("/tmp/chart.png", False)]) + self.assertEqual(self.sends[0]["message"], "Here is the chart") + self.assertEqual(self.sends[0]["thread_id"], "thread-1") + # The original never ran, so the adapter never got a chance to drop it. + self.assertEqual(self.module.calls, []) + + async def test_a_text_only_t3_send_keeps_the_original_path(self): + result = await self.module._send_via_adapter( + Platform.T3, None, "home-thread", "No attachments here" + ) + + self.assertEqual(result["message_id"], "live-adapter") + self.assertEqual(self.sends, []) + self.assertEqual(len(self.module.calls), 1) + + async def test_another_platform_with_media_is_untouched(self): + result = await self.module._send_via_adapter( + Platform.TELEGRAM, + None, + "chat-1", + "Telegram body", + media_files=[("/tmp/chart.png", False)], + ) + + self.assertEqual(result["message_id"], "live-adapter") + self.assertEqual(self.sends, []) + self.assertEqual(len(self.module.calls), 1) + self.assertEqual( + self.module.calls[0]["media_files"], [("/tmp/chart.png", False)] + ) + + async def test_the_false_omission_warning_is_stripped_for_t3(self): + """Bug A: the warning is removed, and the rest of the result survives.""" + result = await self.module._send_to_platform( + Platform.T3, + None, + "home-thread", + "Here is the chart", + media_files=[("/tmp/chart.png", False)], + ) + + self.assertTrue(result["success"]) + self.assertNotIn("warnings", result) + self.assertEqual(result["media_count"], 1) + + async def test_an_unrelated_warning_is_preserved(self): + """Only the one known-false warning is removed, not the whole key.""" + self.module.extra_warnings = ["Something else happened"] + result = await self.module._send_to_platform( + Platform.T3, + None, + "home-thread", + "Here is the chart", + media_files=[("/tmp/chart.png", False)], + ) + + self.assertEqual(result["warnings"], ["Something else happened"]) + + async def test_the_warning_survives_for_a_platform_that_really_omits(self): + """Only `t3` is compensated; another platform's warning is truthful.""" + self.module.live_adapter = None + result = await self.module._send_to_platform( + Platform.TELEGRAM, + None, + "chat-1", + "Telegram body", + media_files=[("/tmp/chart.png", False)], + ) + + self.assertEqual(len(result["warnings"]), 1) + self.assertTrue( + result["warnings"][0].startswith("MEDIA attachments were omitted for telegram") + ) + + async def test_a_media_only_t3_send_is_rescued_from_the_hard_error(self): + """Upstream returns an error before routing; the shim sends instead.""" + result = await self.module._send_to_platform( + Platform.T3, None, "home-thread", "", media_files=[("/tmp/chart.png", False)] + ) + + self.assertTrue(result["success"]) + self.assertEqual(self.sends[0]["media_files"], [("/tmp/chart.png", False)]) + # The original router never ran, so its hard error never happened. + self.assertEqual(self.module.calls, []) + + async def test_a_media_only_send_on_another_platform_still_errors(self): + result = await self.module._send_to_platform( + Platform.TELEGRAM, None, "chat-1", "", media_files=[("/tmp/chart.png", False)] + ) + + self.assertIn("had only media attachments", result["error"]) + self.assertEqual(self.sends, []) + + async def test_a_text_only_send_is_byte_identical_through_the_wrapper(self): + """No media means the wrapper is a pure pass-through, both platforms.""" + for platform in (Platform.T3, Platform.TELEGRAM): + with self.subTest(platform=platform): + result = await self.module._send_to_platform( + platform, None, "chat-1", "Plain text" + ) + self.assertEqual( + result, {"success": True, "message_id": "live-adapter"} + ) + self.assertEqual(self.sends, []) + + +class WarningMatchTests(unittest.TestCase): + """The prefix match must be robust to upstream's changing platform list.""" + + def test_a_future_platform_list_still_matches(self): + result = { + "success": True, + "warnings": [ + "MEDIA attachments were omitted for t3; native send_message media " + "delivery is currently only supported for telegram, discord and " + "seventeen other platforms nobody has written yet" + ], + } + self.assertNotIn("warnings", coreshim._strip_false_warning(result)) + + def test_a_similar_warning_for_another_platform_is_not_matched(self): + warning = "MEDIA attachments were omitted for t3000; ..." + result = {"success": True, "warnings": [warning]} + self.assertEqual( + coreshim._strip_false_warning(result)["warnings"], [warning] + ) + + def test_a_non_dict_result_passes_through(self): + self.assertIsNone(coreshim._strip_false_warning(None)) + self.assertEqual(coreshim._strip_false_warning("nope"), "nope") + + +if __name__ == "__main__": + unittest.main() diff --git a/integrations/hermes-t3-gateway/tests/test_home.py b/integrations/hermes-t3-gateway/tests/test_home.py index 87cebaa040..4850014de9 100644 --- a/integrations/hermes-t3-gateway/tests/test_home.py +++ b/integrations/hermes-t3-gateway/tests/test_home.py @@ -565,6 +565,72 @@ class StandaloneSenderTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(media["mimeType"], "image/png") # Both frames were acked, so nothing stays queued. self.assertEqual(home.HomeDeliveryQueue().entries(), []) + # Counter-evidence against core's unconditional "MEDIA attachments were + # omitted" warning: the accounting keys sit in the same result dict. + self.assertEqual(result["media_count"], 1) + self.assertEqual(result["acked_count"], 2) + self.assertEqual( + result["delivery_ids"], + [message["deliveryId"] for message in server.sent[1:]], + ) + self.assertIn("1 media file(s) delivered and acknowledged", result["note"]) + # `message_id` keeps pointing at the first frame — upstream reads it. + self.assertEqual(result["message_id"], server.sent[1]["deliveryId"]) + + async def test_a_text_only_send_reports_no_media(self): + """The accounting keys are always present; only the note is conditional.""" + server = MockDeliveryServer() + with self._serve(server): + result = await home.standalone_send(None, "home-thread", "Just text") + + self.assertEqual(result["media_count"], 0) + self.assertEqual(result["acked_count"], 1) + self.assertEqual(result["delivery_ids"], [result["message_id"]]) + self.assertNotIn("note", result) + + async def test_a_media_only_send_delivers_without_a_text_frame(self): + """`MEDIA:/tmp/x.png` with no prose is a normal send, not an error. + + Core rejects this outright for `t3` + (`tools/send_message_tool.py:1101-1107` @ v0.19.0); `coreshim` routes it + here instead, so the sender has to handle an empty message. + """ + chart = pathlib.Path(self._tmp.name) / "chart.png" + chart.write_bytes(b"\x89PNG fake bytes") + server = MockDeliveryServer() + with self._serve(server): + result = await home.standalone_send( + None, "home-thread", "", media_files=[(str(chart), False)] + ) + + self.assertTrue(result["success"]) + # No empty text frame rides along. + self.assertEqual( + [message["type"] for message in server.sent], + ["connection.hello", "media.deliver"], + ) + self.assertEqual(result["media_count"], 1) + self.assertEqual(result["acked_count"], 1) + self.assertIn("1 media file(s) delivered and acknowledged", result["note"]) + + async def test_media_counts_exclude_a_skipped_file(self): + """A file that could not be read is not counted as delivered.""" + good = pathlib.Path(self._tmp.name) / "good.png" + good.write_bytes(b"\x89PNG fake bytes") + missing = pathlib.Path(self._tmp.name) / "gone.png" + server = MockDeliveryServer() + with self._serve(server), self.assertLogs(home.logger, level="WARNING"): + result = await home.standalone_send( + None, + "home-thread", + "Two charts, one dead", + media_files=[(str(good), False), (str(missing), False)], + ) + + self.assertTrue(result["success"]) + self.assertEqual(result["media_count"], 1) + self.assertIn("1 media file(s) delivered and acknowledged", result["note"]) + self.assertIn("skipped", result["detail"]) async def test_standalone_send_skips_an_unreadable_media_file(self): """One bad file must not sink the brief — and must never be queued.""" @@ -610,6 +676,12 @@ class StandaloneSenderTests(unittest.IsolatedAsyncioTestCase): # The queued media frame is self-contained: bytes, not a path. self.assertEqual(queued[1]["name"], "chart.png") self.assertTrue(queued[1]["data"]) + # Nothing was acked, so the note must not claim delivery — but it must + # still contradict "omitted", because the file is durably on its way. + self.assertEqual(result["media_count"], 1) + self.assertEqual(result["acked_count"], 0) + self.assertIn("1 media file(s) queued for delivery", result["note"]) + self.assertNotIn("acknowledged", result["note"]) class DesignationTests(unittest.TestCase):