fix(pheby): preserve voice run IDs through Hermes admission
Carry run identity in the native message ID. Preserve typed and voice admission on current Hermes and use explicit reply anchors when a durable drain reuses its task.
This commit is contained in:
+19
-13
@@ -125,7 +125,7 @@ class PhebyAdapter(BasePlatformAdapter):
|
|||||||
async def _process_message_background(self, event, session_key: str) -> None:
|
async def _process_message_background(self, event, session_key: str) -> None:
|
||||||
# Final delivery and the stream consumer's asyncio task inherit this
|
# 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.
|
# 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)
|
cid = self._conv_from_chat_id(event.source.chat_id)
|
||||||
token = _processing_run.set((cid, run_id) if run_id else None)
|
token = _processing_run.set((cid, run_id) if run_id else None)
|
||||||
try:
|
try:
|
||||||
@@ -133,26 +133,29 @@ class PhebyAdapter(BasePlatformAdapter):
|
|||||||
finally:
|
finally:
|
||||||
_processing_run.reset(token)
|
_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)
|
active = hermes_bridge.active_run(conversation_id)
|
||||||
scoped = _processing_run.get()
|
scoped = _processing_run.get()
|
||||||
if scoped and scoped[0] == conversation_id:
|
scoped_run = scoped[1] if scoped and scoped[0] == conversation_id else None
|
||||||
return scoped[1], bool(active and active["run_id"] == scoped[1]
|
if active is None:
|
||||||
and not active.get("cancelling"))
|
# A recovered Hermes delivery can outlive the connector's run map.
|
||||||
if active and active.get("cancelling"):
|
# An in-process callback carrying the old run is still stale.
|
||||||
return None, False
|
return scoped_run, scoped_run is None
|
||||||
return active["run_id"] if active else None, True
|
# 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:
|
async def on_processing_complete(self, event, outcome: ProcessingOutcome) -> None:
|
||||||
await super().on_processing_complete(event, outcome)
|
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:
|
if not run_id:
|
||||||
return
|
return
|
||||||
cid = self._conv_from_chat_id(event.source.chat_id)
|
cid = self._conv_from_chat_id(event.source.chat_id)
|
||||||
if hermes_bridge.active_run_id(cid) != run_id:
|
if hermes_bridge.active_run_id(cid) != run_id:
|
||||||
return
|
return
|
||||||
pending = self._pending_messages.get(self._event_session_key(event))
|
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
|
return
|
||||||
# Attachment-only and failed deliveries can finish without send() or a final edit.
|
# Attachment-only and failed deliveries can finish without send() or a final edit.
|
||||||
statuses = {ProcessingOutcome.SUCCESS: "completed", ProcessingOutcome.FAILURE: "failed",
|
statuses = {ProcessingOutcome.SUCCESS: "completed", ProcessingOutcome.FAILURE: "failed",
|
||||||
@@ -191,7 +194,9 @@ class PhebyAdapter(BasePlatformAdapter):
|
|||||||
await self._server.broadcast(event)
|
await self._server.broadcast(event)
|
||||||
return SendResult(success=True, message_id=event["message_id"])
|
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:
|
if not current:
|
||||||
return SendResult(success=True, message_id=f"draft-{run_id}")
|
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)
|
return SendResult(success=True, message_id=message_id)
|
||||||
|
|
||||||
active = hermes_bridge.active_run(conversation_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)):
|
and active.get("message_id") not in (None, reply_to)):
|
||||||
return SendResult(success=True, message_id=f"draft-{run_id}")
|
return SendResult(success=True, message_id=f"draft-{run_id}")
|
||||||
|
|
||||||
@@ -268,7 +273,8 @@ class PhebyAdapter(BasePlatformAdapter):
|
|||||||
if self._server is None:
|
if self._server is None:
|
||||||
return SendResult(success=False, error="server not running")
|
return SendResult(success=False, error="server not running")
|
||||||
conversation_id = self._conv_from_chat_id(chat_id)
|
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)
|
existing = self._drafts.get(conversation_id)
|
||||||
if not current or (run_id and existing and message_id != existing["message_id"]):
|
if not current or (run_id and existing and message_id != existing["message_id"]):
|
||||||
return SendResult(success=True, message_id=message_id)
|
return SendResult(success=True, message_id=message_id)
|
||||||
|
|||||||
@@ -564,7 +564,9 @@ async def send_chat(server: Any, conversation_id: str, text: str,
|
|||||||
|
|
||||||
run_id = uuid.uuid4().hex[:16]
|
run_id = uuid.uuid4().hex[:16]
|
||||||
source = _source_for(conversation_id)
|
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 ────────────────────────────────────────────────
|
# ── inbound attachments ────────────────────────────────────────────────
|
||||||
media_urls: List[str] = []
|
media_urls: List[str] = []
|
||||||
@@ -627,10 +629,6 @@ async def send_chat(server: Any, conversation_id: str, text: str,
|
|||||||
else MessageType.TEXT)),
|
else MessageType.TEXT)),
|
||||||
source=source,
|
source=source,
|
||||||
message_id=message_id,
|
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_urls=media_urls,
|
||||||
media_types=media_types,
|
media_types=media_types,
|
||||||
media_text_inlined=media_text_inlined,
|
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 {}),
|
**({"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({
|
await server.broadcast({
|
||||||
"type": proto.S_MESSAGE_START,
|
"type": proto.S_MESSAGE_START,
|
||||||
"conversation_id": conversation_id,
|
"conversation_id": conversation_id,
|
||||||
|
|||||||
@@ -108,6 +108,9 @@ S_YOLO_CHANGED = "yolo.changed" # after yolo.set accepted
|
|||||||
# Reasoning effort levels supported by Hermes (hermes_constants).
|
# Reasoning effort levels supported by Hermes (hermes_constants).
|
||||||
REASONING_EFFORTS = ("minimal", "low", "medium", "high", "xhigh", "max", "ultra")
|
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}$")
|
_ATTACHMENT_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
||||||
|
|
||||||
|
|
||||||
@@ -121,6 +124,14 @@ def new_id() -> str:
|
|||||||
return uuid.uuid4().hex
|
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:
|
def is_valid_attachment_id(value: str) -> bool:
|
||||||
"""True when *value* looks like one of our opaque attachment IDs."""
|
"""True when *value* looks like one of our opaque attachment IDs."""
|
||||||
return bool(isinstance(value, str) and _ATTACHMENT_ID_RE.match(value))
|
return bool(isinstance(value, str) and _ATTACHMENT_ID_RE.match(value))
|
||||||
|
|||||||
+77
-7
@@ -903,6 +903,55 @@ class TestBridge:
|
|||||||
assert server.adapter.handled[-1].source.chat_id == cid
|
assert server.adapter.handled[-1].source.chat_id == cid
|
||||||
assert client.ws.events()[0]["type"] == proto.S_RUN_ACCEPTED
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_chat_dispatch_failure_closes_run(self, tmp_path,
|
async def test_chat_dispatch_failure_closes_run(self, tmp_path,
|
||||||
monkeypatch):
|
monkeypatch):
|
||||||
@@ -1434,21 +1483,42 @@ class TestAdapterUnits:
|
|||||||
server._clients["listener"] = listener
|
server._clients["listener"] = listener
|
||||||
adapter = PhebyAdapter(PlatformConfig(enabled=True))
|
adapter = PhebyAdapter(PlatformConfig(enabled=True))
|
||||||
adapter._server = server
|
adapter._server = server
|
||||||
|
adapter._loop = asyncio.get_running_loop()
|
||||||
|
hb.set_adapter(adapter)
|
||||||
conv = "voice-replacement"
|
conv = "voice-replacement"
|
||||||
adapter._drafts[conv] = {"run_id": "new", "message_id": "draft-new", "text": ""}
|
old_run, new_run = "a" * 16, "b" * 16
|
||||||
monkeypatch.setitem(hb._ACTIVE_RUNS, conv, {"run_id": "new", "started": 0})
|
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):
|
async def late_delivery(self, event, key):
|
||||||
await self.send(conv, "old final")
|
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)
|
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 adapter._process_message_background(event, "session-key")
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
|
||||||
assert hb.active_run_id(conv) == "new"
|
assert hb.active_run_id(conv) is None
|
||||||
assert adapter._drafts[conv]["message_id"] == "draft-new"
|
events = listener.ws.events()
|
||||||
assert 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):
|
def test_transport_auth_is_gateway_authorization(self):
|
||||||
from pheby.adapter import PhebyAdapter
|
from pheby.adapter import PhebyAdapter
|
||||||
|
|||||||
Reference in New Issue
Block a user