The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): post_message review round 2 — no loop block on pending edits, canonical first-message route, failed-edit fallback
Teknium2db665614c87
diff --git a/gateway/plugin_messages.py b/gateway/plugin_messages.pyindex 5085419724f..5e5074795f1 100644--- a/gateway/plugin_messages.py+++ b/gateway/plugin_messages.py@@ -74,16 +74,14 @@ def bound_route() -> dict:return {field: get_session_env(var, "") for field, var in _ROUTE_VARS.items()}-def _bound_source(route: dict):+def _bound_source(runner, route: dict, *, plugin_home, plugin_id: str):"""A source for a messaging chat whose session has no store entry yet (a plugin command that is- the chat's first message): the route the gateway itself bound for this call."""- from gateway.session import SessionSource+ the chat's first message), rebuilt from the route the gateway bound for this call and given the+ receiving bot's provenance by the same canonicalizer a plugin ``origin`` goes through."""if not route.get("platform") or not route.get("chat_id") or route["platform"] == Platform.LOCAL.value:return None- try:- return SessionSource.from_dict({k: v for k, v in route.items() if v})- except (KeyError, TypeError, ValueError):- return None+ return runner._plugin_origin_source({k: v for k, v in route.items() if v}, plugin_home=plugin_home,+ plugin_id=plugin_id)def resolve(runner, *, session_key: str, route: dict, plugin_home, plugin_id: str):@@ -93,7 +91,7 @@ def resolve(runner, *, session_key: str, route: dict, plugin_home, plugin_id: stfrom gateway.session_identity import replace_sourcesource = replace_source(runner._restored_source(entry))else:- source = _bound_source(route)+ source = _bound_source(runner, route, plugin_home=plugin_home, plugin_id=plugin_id)# The bound route must be the chat this key names (both are bound by the gateway together).if source is None or runner._session_key_for_source(source) != session_key:return None, _err("no_conversation", f"session {session_key!r} is not known to this gateway")@@ -157,11 +155,11 @@ async def edit(target: PostTarget, message_id: Optional[str], text: str, *, plugtry:sent = await target.adapter.edit_message(target.chat_id, message_id,_fit(target.adapter, target.chat_id, text))- edit_error = "" if getattr(sent, "success", False) else str(getattr(sent, "error", "") or "")+ edited, edit_error = bool(getattr(sent, "success", False)), str(getattr(sent, "error", "") or "")except Exception as exc: # a raised edit falls back like a refused onelogger.debug("plugin_message plugin=%s edit_message raised", plugin_id, exc_info=True)- sent, edit_error = None, str(exc) or type(exc).__name__- if sent is not None and not edit_error:+ sent, edited, edit_error = None, False, str(exc) or type(exc).__name__+ if edited:result = {"ok": True, "message_id": str(sent.message_id or message_id), "edited": True}else:result = {**await _send(target, text), "edited": False, "fallback": True,diff --git a/hermes_cli/plugin_messages.py b/hermes_cli/plugin_messages.pyindex 02b95f630a3..445fb971f3f 100644--- a/hermes_cli/plugin_messages.py+++ b/hermes_cli/plugin_messages.py@@ -81,6 +81,8 @@ class PluginMessage:def edit(self, text: str) -> dict[str, Any]:"""Replace the message text: ``{"ok", "message_id", "edited", ["fallback"]}``. Thread-safe."""+ if _on_gateway_loop(): # never block the loop the pending operation needs+ return _err("on_event_loop", "called from the gateway event loop: use await handle.aedit(...)")if self.pending:try:self._pending.result(_TIMEOUT_S)@@ -106,6 +108,14 @@ def _gateway_loop():return runner, loop+def _on_gateway_loop() -> bool:+ _runner, loop = _gateway_loop()+ try:+ return loop is not None and asyncio.get_running_loop() is loop+ except RuntimeError:+ return False++def _run_on_gateway_loop(coro, handle: PluginMessage) -> dict[str, Any]:"""Run *coro* on the gateway loop and wait up to ``_TIMEOUT_S``; past that it keeps running asthe handle's pending operation (its result still lands on the handle)."""@@ -113,11 +123,7 @@ def _run_on_gateway_loop(coro, handle: PluginMessage) -> dict[str, Any]:if loop is None:coro.close()return _err("gateway_unavailable", "no live gateway is running in this process")- try:- running = asyncio.get_running_loop()- except RuntimeError:- running = None- if running is loop:+ if _on_gateway_loop():coro.close()return _err("on_event_loop", "called from the gateway event loop: use the async form (await ...)")future = asyncio.run_coroutine_threadsafe(coro, loop)diff --git a/tests/gateway/test_plugin_post_message.py b/tests/gateway/test_plugin_post_message.pyindex ca744deb5d6..429669e2f88 100644--- a/tests/gateway/test_plugin_post_message.py+++ b/tests/gateway/test_plugin_post_message.py@@ -45,6 +45,11 @@ class _RaisingEditAdapter(_Adapter):raise ValueError("malformed edit response")+class _FailedEditAdapter(_Adapter):+ async def edit_message(self, chat_id, message_id, content, *, finalize=False):+ return SendResult(success=False) # no error text, as an empty platform response gives++def _setup(tmp_path, adapter):store = SessionStore(sessions_dir=tmp_path / "sessions", config=GatewayConfig())entry = store.get_or_create_session(SessionSource(@@ -70,7 +75,8 @@ async def _in_session(session_key, fn):@pytest.mark.asyncio@pytest.mark.parametrize("adapter_cls, edited",- [(_EditingAdapter, True), (_Adapter, False), (_RaisingEditAdapter, False)])+ [(_EditingAdapter, True), (_Adapter, False), (_RaisingEditAdapter, False),+ (_FailedEditAdapter, False)])async def test_post_then_edit_targets_the_calling_session(tmp_path, adapter_cls, edited):adapter = adapter_cls()runner, ctx, entry = _setup(tmp_path, adapter)@@ -82,7 +88,7 @@ async def test_post_then_edit_targets_the_calling_session(tmp_path, adapter_cls,assert result["ok"] is True and result["edited"] is editedif edited:assert adapter.calls == [("send", "42", "step 1/2"), ("edit", "42", "m1", "step 2/2")]- else: # no edit support, or the edit raised: a fresh message, and the handle follows it+ else: # no edit support, a raised or a failed edit: a fresh message, and the handle follows itassert adapter.calls == [("send", "42", "step 1/2"), ("send", "42", "step 2/2")]assert result["fallback"] is True and handle.message_id == "m2"