diff --git a/plugin/pheby/adapter.py b/plugin/pheby/adapter.py index 81df6a4..6c202b8 100644 --- a/plugin/pheby/adapter.py +++ b/plugin/pheby/adapter.py @@ -125,7 +125,7 @@ class PhebyAdapter(BasePlatformAdapter): async def _process_message_background(self, event, session_key: str) -> None: # Final delivery and the stream consumer's asyncio task inherit this # turn's ID, even if another run takes over the chat while they unwind. - run_id = (event.metadata or {}).get("pheby_run_id") + run_id = proto.run_id_from_message_id(event.message_id) cid = self._conv_from_chat_id(event.source.chat_id) token = _processing_run.set((cid, run_id) if run_id else None) try: @@ -133,26 +133,29 @@ class PhebyAdapter(BasePlatformAdapter): finally: _processing_run.reset(token) - def _delivery_run(self, conversation_id: str) -> tuple[Optional[str], bool]: + def _delivery_run(self, conversation_id: str, anchored_run: Optional[str] = None) -> tuple[Optional[str], bool]: active = hermes_bridge.active_run(conversation_id) scoped = _processing_run.get() - if scoped and scoped[0] == conversation_id: - return scoped[1], bool(active and active["run_id"] == scoped[1] - and not active.get("cancelling")) - if active and active.get("cancelling"): - return None, False - return active["run_id"] if active else None, True + scoped_run = scoped[1] if scoped and scoped[0] == conversation_id else None + if active is None: + # A recovered Hermes delivery can outlive the connector's run map. + # An in-process callback carrying the old run is still stale. + return scoped_run, scoped_run is None + # A durable Hermes drain may handle a successor in the same task. + # Its explicit reply or draft anchor identifies the actual turn. + run_id = anchored_run or scoped_run or active["run_id"] + return run_id, run_id == active["run_id"] and not active.get("cancelling") async def on_processing_complete(self, event, outcome: ProcessingOutcome) -> None: await super().on_processing_complete(event, outcome) - run_id = (event.metadata or {}).get("pheby_run_id") + run_id = proto.run_id_from_message_id(event.message_id) if not run_id: return cid = self._conv_from_chat_id(event.source.chat_id) if hermes_bridge.active_run_id(cid) != run_id: return pending = self._pending_messages.get(self._event_session_key(event)) - if pending is not None and (pending.metadata or {}).get("pheby_run_id") == run_id: + if pending is not None and pending.message_id == event.message_id: return # Attachment-only and failed deliveries can finish without send() or a final edit. statuses = {ProcessingOutcome.SUCCESS: "completed", ProcessingOutcome.FAILURE: "failed", @@ -191,7 +194,9 @@ class PhebyAdapter(BasePlatformAdapter): await self._server.broadcast(event) return SendResult(success=True, message_id=event["message_id"]) - run_id, current = self._delivery_run(conversation_id) + anchored_run = (proto.run_id_from_message_id(reply_to) + or proto.run_id_from_message_id(metadata.get("reply_to_message_id"))) + run_id, current = self._delivery_run(conversation_id, anchored_run) if not current: return SendResult(success=True, message_id=f"draft-{run_id}") @@ -212,7 +217,7 @@ class PhebyAdapter(BasePlatformAdapter): return SendResult(success=True, message_id=message_id) active = hermes_bridge.active_run(conversation_id) - if (_processing_run.get() != (conversation_id, run_id) and reply_to and active + if (anchored_run is None and _processing_run.get() != (conversation_id, run_id) and reply_to and active and active.get("message_id") not in (None, reply_to)): return SendResult(success=True, message_id=f"draft-{run_id}") @@ -268,7 +273,8 @@ class PhebyAdapter(BasePlatformAdapter): if self._server is None: return SendResult(success=False, error="server not running") conversation_id = self._conv_from_chat_id(chat_id) - run_id, current = self._delivery_run(conversation_id) + anchored_run = proto.run_id_from_message_id(message_id, proto.DRAFT_MESSAGE_PREFIX) + run_id, current = self._delivery_run(conversation_id, anchored_run) existing = self._drafts.get(conversation_id) if not current or (run_id and existing and message_id != existing["message_id"]): return SendResult(success=True, message_id=message_id) diff --git a/plugin/pheby/hermes_bridge.py b/plugin/pheby/hermes_bridge.py index 6807b28..5ca9b5e 100644 --- a/plugin/pheby/hermes_bridge.py +++ b/plugin/pheby/hermes_bridge.py @@ -564,7 +564,9 @@ async def send_chat(server: Any, conversation_id: str, text: str, run_id = uuid.uuid4().hex[:16] source = _source_for(conversation_id) - message_id = uuid.uuid4().hex[:12] + # Hermes preserves message_id through native admission and replay. Its + # native envelope rejects custom metadata from messaging plugins. + message_id = f"{proto.INBOUND_MESSAGE_PREFIX}{run_id}" # ── inbound attachments ──────────────────────────────────────────────── media_urls: List[str] = [] @@ -627,10 +629,6 @@ async def send_chat(server: Any, conversation_id: str, text: str, else MessageType.TEXT)), source=source, message_id=message_id, - # No metadata: the gateway's native-admission validation only accepts - # empty metadata on the native path (anything non-empty is refused as - # invalid_params unless it is WhatsApp's own native payload), and - # nothing in the plugin reads event metadata back. media_urls=media_urls, media_types=media_types, media_text_inlined=media_text_inlined, @@ -658,7 +656,7 @@ async def send_chat(server: Any, conversation_id: str, text: str, **({"request_id": request_id} if request_id else {}), }) - draft_message_id = f"draft-{run_id}" + draft_message_id = f"{proto.DRAFT_MESSAGE_PREFIX}{run_id}" await server.broadcast({ "type": proto.S_MESSAGE_START, "conversation_id": conversation_id, diff --git a/plugin/pheby/protocol.py b/plugin/pheby/protocol.py index a4ae99f..39ba1e1 100644 --- a/plugin/pheby/protocol.py +++ b/plugin/pheby/protocol.py @@ -108,6 +108,9 @@ S_YOLO_CHANGED = "yolo.changed" # after yolo.set accepted # Reasoning effort levels supported by Hermes (hermes_constants). REASONING_EFFORTS = ("minimal", "low", "medium", "high", "xhigh", "max", "ultra") +INBOUND_MESSAGE_PREFIX = "pheby-" +DRAFT_MESSAGE_PREFIX = "draft-" +_RUN_ID_RE = re.compile(r"[0-9a-f]{16}") _ATTACHMENT_ID_RE = re.compile(r"^[0-9a-f]{32}$") @@ -121,6 +124,14 @@ def new_id() -> str: return uuid.uuid4().hex +def run_id_from_message_id(value: Any, prefix: str = INBOUND_MESSAGE_PREFIX) -> Optional[str]: + """Return the run ID encoded in a Pheby message ID, when present.""" + if not isinstance(value, str) or not value.startswith(prefix): + return None + run_id = value[len(prefix):] + return run_id if _RUN_ID_RE.fullmatch(run_id) else None + + def is_valid_attachment_id(value: str) -> bool: """True when *value* looks like one of our opaque attachment IDs.""" return bool(isinstance(value, str) and _ATTACHMENT_ID_RE.match(value)) diff --git a/tests/test_pheby.py b/tests/test_pheby.py index 3d4f715..c6b081e 100644 --- a/tests/test_pheby.py +++ b/tests/test_pheby.py @@ -903,6 +903,55 @@ class TestBridge: assert server.adapter.handled[-1].source.chat_id == cid assert client.ws.events()[0]["type"] == proto.S_RUN_ACCEPTED + @pytest.mark.asyncio + @pytest.mark.parametrize("voice_context", [None, "Find a train for Friday."]) + async def test_chat_send_passes_hermes_native_admission_in_an_existing_chat( + self, tmp_path, monkeypatch, voice_context): + from gateway.config import Platform, PlatformConfig + from gateway.session_envelope import prepare_native, restore_native + from pheby import hermes_bridge as hb + + if "pheby" not in Platform._value2member_map_: + platform = object.__new__(Platform) + platform._name_, platform._value_ = "PHEBY", "pheby" + monkeypatch.setitem(Platform._value2member_map_, "pheby", platform) + adapter = PhebyAdapter(PlatformConfig(enabled=True)) + server = make_server(tmp_path) + server.adapter = adapter + hb.set_adapter(adapter) + monkeypatch.setattr(hb, "_ACTIVE_RUNS", {}) + client = FakeClientConnection() + cid = "existing-chat" + await server.router.ensure_conversation(cid) + route = f"agent:main:pheby:dm:{cid}" + runner = SimpleNamespace( + config=SimpleNamespace(multiplex_profiles=False), + session_store=SimpleNamespace(_generate_session_key=lambda source: route), + _adapter_for_source=lambda source: adapter, + _adapter_flag=lambda *_: True, + _adapter_profile_for_source=lambda source: None, + _is_user_authorized_for_source=lambda source, allow_adapter_delegation: allow_adapter_delegation, + ) + adapter.gateway_runner = runner + admitted = [] + + async def handle_message(event): + payload = await prepare_native(runner, event) + assert payload["native_text_v1"]["route"] == route + admitted.append(restore_native(payload, runner)) + + monkeypatch.setattr(adapter, "handle_message", handle_message) + frame = {"conversation_id": cid, "text": "Thursday instead."} + if voice_context is not None: + frame["voice_context"] = voice_context + await server._handle_chat_send(client, frame, "r1") + + restored, = admitted + assert restored.source.chat_id == cid + assert hb._display_user_text(restored.text) == frame["text"] + assert restored.metadata == {} + assert restored.message_id == "pheby-" + client.ws.events()[0]["run_id"] + @pytest.mark.asyncio async def test_chat_dispatch_failure_closes_run(self, tmp_path, monkeypatch): @@ -1434,21 +1483,42 @@ class TestAdapterUnits: server._clients["listener"] = listener adapter = PhebyAdapter(PlatformConfig(enabled=True)) adapter._server = server + adapter._loop = asyncio.get_running_loop() + hb.set_adapter(adapter) conv = "voice-replacement" - adapter._drafts[conv] = {"run_id": "new", "message_id": "draft-new", "text": ""} - monkeypatch.setitem(hb._ACTIVE_RUNS, conv, {"run_id": "new", "started": 0}) + old_run, new_run = "a" * 16, "b" * 16 + old_message, new_message = f"pheby-{old_run}", f"pheby-{new_run}" + old_draft, new_draft = f"draft-{old_run}", f"draft-{new_run}" + adapter._drafts[conv] = {"run_id": new_run, "message_id": new_draft, "text": ""} + monkeypatch.setitem(hb._ACTIVE_RUNS, conv, {"run_id": new_run, "message_id": new_message, "started": 0}) async def late_delivery(self, event, key): await self.send(conv, "old final") - await self.edit_message(conv, "draft-old", "old edit", finalize=True) + await self.send(conv, "old anchored reply", reply_to=old_message) + await self.edit_message(conv, old_draft, "old edit", finalize=True) + + assert hb.active_run_id(conv) == new_run + assert adapter._drafts[conv]["message_id"] == new_draft + assert listener.ws.events() == [] + + # Hermes can drain the replacement in the same task. The explicit + # anchor takes precedence over the stale task's context. + await self.send(conv, "new preview", metadata={ + "reply_to_message_id": new_message, "expect_edits": True, + }) + await self.edit_message(conv, new_draft, "new final", finalize=True) monkeypatch.setattr(BasePlatformAdapter, "_process_message_background", late_delivery) - event = SimpleNamespace(metadata={"pheby_run_id": "old"}, source=SimpleNamespace(chat_id=conv)) + event = SimpleNamespace(message_id=old_message, source=SimpleNamespace(chat_id=conv)) await adapter._process_message_background(event, "session-key") + await asyncio.sleep(0) - assert hb.active_run_id(conv) == "new" - assert adapter._drafts[conv]["message_id"] == "draft-new" - assert listener.ws.events() == [] + assert hb.active_run_id(conv) is None + events = listener.ws.events() + assert [event["type"] for event in events] == [ + proto.S_MESSAGE_DELTA, proto.S_MESSAGE_COMPLETE, proto.S_RUN_FINISHED, + ] + assert all(event["run_id"] == new_run for event in events) def test_transport_auth_is_gateway_authorization(self): from pheby.adapter import PhebyAdapter