The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(matrix): track every in-flight voice per sender and release the mark at the park decision
kshitijk4poordf2f8b8afc1f
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 4e3a6655409..3eb83abb28c 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -2028,10 +2028,11 @@ class MatrixAdapter(BasePlatformAdapter):async def _resolve_message_context(self, room_id: str, sender: str, event_id: str, body: str, source_content: dict,- relates_to: dict, mention_claimed: bool = False) -> Optional[tuple]:+ relates_to: dict, mention_claimed: bool = False, voice_gate=None) -> Optional[tuple]:"""Shared mention/thread/DM gating. Returns (body, is_dm, chat_type, thread_id,display_name, source) or None when the message should be dropped. ``mention_claimed``- marks a parked voice claimed by the sender's follow-up bare @mention."""+ marks a parked voice claimed by the sender's follow-up bare @mention; ``voice_gate`` is+ the in-flight mark of a parkable voice, released once the park decision is made."""identity = await self._resolve_room_identity(room_id)is_dm = await self._is_dm_room(room_id)chat_type = "dm" if is_dm else "group"@@ -2047,8 +2048,8 @@ class MatrixAdapter(BasePlatformAdapter):in_bot_thread = bool(thread_id and thread_id in self._threads)if self._require_mention and not is_free_room and not in_bot_thread:if not is_mentioned and not body.startswith("/"):- if is_voice_event(source_content): # a bare @mention may follow (Element X)- self._parked_voices.park(room_id, sender, event_id, source_content, relates_to)+ if voice_gate is not None: # parkable voice: a bare @mention may follow (Element X)+ self._parked_voices.park(room_id, sender, voice_gate, event_id, source_content, relates_to)logger.debug("Matrix: ignoring message %s in %s — no @mention ""(set MATRIX_REQUIRE_MENTION=false to disable)", event_id, room_id)@@ -2081,6 +2082,8 @@ class MatrixAdapter(BasePlatformAdapter):self._matrix_session_scope != "room" and self._auto_thread)if synthetic:thread_id = event_id+ if voice_gate is not None: # decided (parked or passing): don't hold bare mentions any longer+ self._parked_voices.release(room_id, sender, voice_gate)display_name = await self._get_display_name(room_id, sender)source = self.build_source(chat_id=room_id, chat_name=identity.display_name, chat_type=chat_type, user_id=sender,@@ -2194,12 +2197,13 @@ class MatrixAdapter(BasePlatformAdapter):msg_type, media_type, is_voice_message = self._classify_inbound_media(msgtype, event_mimetype, source_content)# Gate (require_mention / allowed rooms) BEFORE the download: an unmentioned or# non-allowlisted room must not pull media onto the host only to drop it.- # First await: mark a parkable voice in-flight so a concurrent bare mention waits for it.- gate = (self._parked_voices.begin(room_id, sender)- if self._require_mention and not mention_claimed and is_voice_event(source_content) else None)+ # First await: mark a voice that may park in-flight so a concurrent bare mention waits for it.+ gate = self._parked_voices.begin(room_id, sender) if self._voice_may_park(+ room_id, body, source_content, relates_to, mention_claimed) else Nonetry:ctx = await self._resolve_message_context(- room_id, sender, event_id, body, source_content, relates_to, mention_claimed=mention_claimed)+ room_id, sender, event_id, body, source_content, relates_to, mention_claimed=mention_claimed,+ voice_gate=gate)finally:if gate is not None:self._parked_voices.release(room_id, sender, gate)@@ -2904,6 +2908,19 @@ class MatrixAdapter(BasePlatformAdapter):return Truereturn bool(formatted_body and self._user_id and f"matrix.to/#/{self._user_id}" in formatted_body)+ def _voice_may_park(self, room_id: str, body: str, content: dict, relates_to: dict,+ mention_claimed: bool) -> bool:+ """Synchronous pre-check of the ``_resolve_message_context`` park branch (only DM-ness+ needs an await; a DM voice's mark is released as soon as that is known)."""+ if mention_claimed or not self._require_mention or not is_voice_event(content):+ return False+ if room_id in self._free_rooms or (self._allowed_rooms and room_id not in self._allowed_rooms):+ return False+ thread_id = relates_to.get("event_id") if relates_to.get("rel_type") == "m.thread" else None+ if thread_id and thread_id in self._threads:+ return False+ return not body.startswith("/") and not self._content_mentions_bot(body, content)+def _content_mentions_bot(self, body: str, content: dict) -> bool:"""``_is_bot_mentioned`` fed from an event's content (MSC3952 ``m.mentions`` is authoritative)."""mentions = content.get("m.mentions") or {}diff --git a/plugins/platforms/matrix/voice_mention.py b/plugins/platforms/matrix/voice_mention.pyindex f17f313b8ca..52f63a76c78 100644--- a/plugins/platforms/matrix/voice_mention.py+++ b/plugins/platforms/matrix/voice_mention.py@@ -9,8 +9,9 @@ the window claims it. Unmentioned voices are never downloaded or transcribed whifrom __future__ import annotationsimport asyncio+import itertoolsimport time-from typing import Dict, Optional, Tuple+from typing import Dict, List, Optional, TupleCLAIM_WINDOW_SECONDS = 120.0# How long a bare mention waits for a voice from the same /sync batch that is still being gated.@@ -29,14 +30,28 @@ def is_voice_event(content: dict) -> bool:return content.get("msgtype") == "m.audio" and has_voice_marker(content)+class VoiceGate:+ """One voice being gated; ``seq`` orders voices from the same sender by arrival."""++ __slots__ = ("seq", "done")++ def __init__(self, seq: int) -> None:+ self.seq = seq+ self.done = asyncio.Event()++class ParkedVoices:def __init__(self) -> None:- # (room_id, sender) -> (parked_at, parked voice)- self._parked: Dict[Tuple[str, str], Tuple[float, ParkedVoice]] = {}- # (room_id, sender) -> set once that sender's voice has been gated (parked or not).- # mautrix runs one /sync batch's events as concurrent tasks, so the voice may still be- # awaiting room identity when its bare mention is handled.- self._inflight: Dict[Tuple[str, str], asyncio.Event] = {}+ # (room_id, sender) -> (parked_at, seq, parked voice)+ self._parked: Dict[Tuple[str, str], Tuple[float, int, ParkedVoice]] = {}+ # (room_id, sender) -> every voice of that sender still being gated. mautrix runs one+ # /sync batch's events as concurrent tasks, so a voice may still be awaiting room+ # identity when its bare mention is handled -- and a sender can have several in flight.+ self._inflight: Dict[Tuple[str, str], List[VoiceGate]] = {}+ # (room_id, sender) -> seq of the newest voice parked while gates were in flight, so an+ # older voice finishing late never lands over (or after the claim of) a newer one.+ self._newest: Dict[Tuple[str, str], int] = {}+ self._seq = itertools.count()def _prune(self) -> None:cutoff = time.monotonic() - CLAIM_WINDOW_SECONDS@@ -47,32 +62,46 @@ class ParkedVoices:key = (room_id, sender)return key in self._parked or key in self._inflight- def begin(self, room_id: str, sender: str) -> asyncio.Event:- """Mark a voice as being gated. Call before the first await; always pair with ``release``."""- gate = self._inflight[(room_id, sender)] = asyncio.Event()+ def begin(self, room_id: str, sender: str) -> VoiceGate:+ """Mark a parkable voice as being gated. Call before the first await; always pair with+ ``release`` (idempotent, so it may run early and again in a ``finally``)."""+ gate = VoiceGate(next(self._seq))+ self._inflight.setdefault((room_id, sender), []).append(gate)return gate- def release(self, room_id: str, sender: str, gate: asyncio.Event) -> None:- gate.set()- if self._inflight.get((room_id, sender)) is gate:- del self._inflight[(room_id, sender)]+ def release(self, room_id: str, sender: str, gate: VoiceGate) -> None:+ gate.done.set()+ key = (room_id, sender)+ gates = self._inflight.get(key)+ if gates and gate in gates:+ gates.remove(gate)+ if not gates: # no older voice can park any more+ del self._inflight[key]+ self._newest.pop(key, None)async def settle(self, room_id: str, sender: str) -> None:- """Wait (bounded) for a concurrently gated voice from this sender to be parked or dropped."""- gate = self._inflight.get((room_id, sender))- if gate is not None:+ """Wait (bounded) for every concurrently gated voice from this sender to park or drop."""+ gates = self._inflight.get((room_id, sender))+ if gates:+ waits = [asyncio.ensure_future(g.done.wait()) for g in gates]try:- await asyncio.wait_for(gate.wait(), SETTLE_TIMEOUT_SECONDS)- except asyncio.TimeoutError:- pass+ await asyncio.wait(waits, timeout=SETTLE_TIMEOUT_SECONDS)+ finally:+ for w in waits:+ w.cancel()- def park(self, room_id: str, sender: str, event_id: str, content: dict, relates_to: dict) -> None:+ def park(self, room_id: str, sender: str, gate: VoiceGate, event_id: str, content: dict,+ relates_to: dict) -> None:+ key = (room_id, sender)+ if gate.seq < self._newest.get(key, -1):+ return # a newer voice from this sender already parked (and maybe was claimed)self._prune()- self._parked[(room_id, sender)] = (time.monotonic(), (event_id, content, relates_to))+ self._parked[key] = (time.monotonic(), gate.seq, (event_id, content, relates_to))+ self._newest[key] = gate.seqdef claim(self, room_id: str, sender: str) -> Optional[ParkedVoice]:"""Pop the sender's parked voice for this room (the caller re-dispatches it with``mention_claimed=True`` so it passes the mention gate without re-parking)."""self._prune()entry = self._parked.pop((room_id, sender), None)- return entry[1] if entry else None+ return entry[2] if entry else None