Skip to content

The agent that grows with you

fix(matrix): answer a voice message whose @mention was typed while recording

kshitijk4poorcb7bdd217721
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 29a0fca7f08..391f2fe5318 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -398,6 +398,7 @@ def _resolve_max_message_length(config) -> int:
# identity in one crypto.db.
# Store directory for E2EE keys and sync state. Mirrors the pairing-store fix (a6397c379). See #89168.
from hermes_constants import get_hermes_dir as _get_hermes_dir
+from plugins.platforms.matrix.voice_mention import ParkedVoices, is_voice_event
_STARTUP_GRACE_SECONDS = 5 # ignore messages older than this many seconds before startup
@@ -871,6 +872,7 @@ class MatrixAdapter(BasePlatformAdapter):
self._processed_events: deque = deque(maxlen=1000) # event dedup, newest kept
self._processed_events_set: set = set()
self._threads = ThreadParticipationTracker("matrix") # require_mention bypass
+ self._parked_voices = ParkedVoices() # unmentioned voice awaiting a bare @mention
self._require_mention: bool = self._parse_require_mention(config)
self._thread_require_mention: bool = self._parse_thread_require_mention(config)
self._free_rooms: Set[str] = _extra_csv_set(config, "free_response_rooms", "MATRIX_FREE_RESPONSE_ROOMS")
@@ -2046,7 +2048,10 @@ class MatrixAdapter(BasePlatformAdapter):
is_free_room = room_id in self._free_rooms
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 (not is_mentioned and not body.startswith("/")
+ and not self._parked_voices.consume_claim(event_id)):
+ 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)
logger.debug(
"Matrix: ignoring message %s in %s — no @mention "
"(set MATRIX_REQUIRE_MENTION=false to disable)", event_id, room_id)
@@ -2139,6 +2144,16 @@ class MatrixAdapter(BasePlatformAdapter):
body = source_content.get("body", "") or ""
if not body:
return
+ mentions = source_content.get("m.mentions") or {}
+ if (self._require_mention and not self._strip_mention(body).strip() and self._is_bot_mentioned(
+ body, source_content.get("formatted_body"),
+ mentions.get("user_ids") if isinstance(mentions, dict) else None)):
+ parked = self._parked_voices.claim(room_id, sender)
+ if parked: # answer the voice this bare mention was typed for, not an empty text
+ voice_id, voice_content, voice_relates = parked
+ await self._handle_media_message(
+ room_id, sender, voice_id, event_ts, voice_content, voice_relates, "m.audio")
+ return
msg_event = await self._build_inbound_event(
room_id, sender, event_id, _normalize_matrix_bang_command(body), source_content, relates_to)
if msg_event is None:
diff --git a/plugins/platforms/matrix/voice_mention.py b/plugins/platforms/matrix/voice_mention.py
new file mode 100644
index 00000000000..f364ad2c1b3
--- /dev/null
+++ b/plugins/platforms/matrix/voice_mention.py
@@ -0,0 +1,51 @@
+"""Park unmentioned MSC3245 voice messages until the sender's bare @mention claims them.
+
+Element X sends a mention typed while recording as a SEPARATE ``m.text`` event after the
+voice event (which carries an empty ``m.mentions``). Under ``require_mention`` the voice is
+parked instead of forgotten; a bare mention from the same sender in the same room within
+the window claims it. Unmentioned voices are never downloaded or transcribed while parked.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Dict, Optional, Set, Tuple
+
+CLAIM_WINDOW_SECONDS = 120.0
+
+
+def is_voice_event(content: dict) -> bool:
+ return content.get("msgtype") == "m.audio" and "org.matrix.msc3245.voice" in content
+
+
+class ParkedVoices:
+ def __init__(self, window: float = CLAIM_WINDOW_SECONDS) -> None:
+ self._window = window
+ # (room_id, sender) -> (parked_at, event_id, content, relates_to)
+ self._parked: Dict[Tuple[str, str], Tuple[float, str, dict, dict]] = {}
+ self._claimed: Set[str] = set()
+
+ def _prune(self) -> None:
+ cutoff = time.monotonic() - self._window
+ self._parked = {k: v for k, v in self._parked.items() if v[0] >= cutoff}
+
+ def park(self, room_id: str, sender: str, event_id: str, content: dict, relates_to: dict) -> None:
+ self._prune()
+ self._parked[(room_id, sender)] = (time.monotonic(), event_id, content, relates_to)
+
+ def claim(self, room_id: str, sender: str) -> Optional[Tuple[str, dict, dict]]:
+ """Pop the sender's parked voice for this room; the claimed event id then passes the
+ mention gate exactly once (see ``consume_claim``) instead of being re-parked."""
+ self._prune()
+ entry = self._parked.pop((room_id, sender), None)
+ if entry is None:
+ return None
+ _ts, event_id, content, relates_to = entry
+ self._claimed.add(event_id)
+ return event_id, content, relates_to
+
+ def consume_claim(self, event_id: str) -> bool:
+ if event_id in self._claimed:
+ self._claimed.discard(event_id)
+ return True
+ return False
diff --git a/tests/gateway/test_matrix_mention.py b/tests/gateway/test_matrix_mention.py
index 64dce30b3bc..ed2adfeb951 100644
--- a/tests/gateway/test_matrix_mention.py
+++ b/tests/gateway/test_matrix_mention.py
@@ -242,6 +242,30 @@ async def test_bare_mention_passes_empty_string(monkeypatch):
assert msg.text == ""
[email protected]("mention_room, claims", [("!room1:example.org", True), ("!room2:example.org", False)])
+async def test_bare_mention_claims_parked_voice_only_in_same_room(monkeypatch, mention_room, claims):
+ """An unmentioned MSC3245 voice (empty m.mentions) is answered by the sender's bare @mention
+ typed right after it in the SAME room; a bare mention in another room never pulls it across."""
+ monkeypatch.delenv("MATRIX_REQUIRE_MENTION", raising=False)
+ monkeypatch.delenv("MATRIX_FREE_RESPONSE_ROOMS", raising=False)
+ monkeypatch.setenv("MATRIX_AUTO_THREAD", "false")
+
+ adapter = _make_adapter()
+ adapter._download_and_cache_media = AsyncMock(return_value="/tmp/voice.ogg")
+ voice = _make_event("voice message", event_id="$voice")
+ voice.content.update({"msgtype": "m.audio", "url": "mxc://example.org/v", "info": {"mimetype": "audio/ogg"},
+ "org.matrix.msc3245.voice": {}, "m.mentions": {}})
+
+ await adapter._on_room_message(voice)
+ adapter.handle_message.assert_not_awaited()
+ await adapter._on_room_message(_make_event(
+ "@hermes:example.org", event_id="$text", room_id=mention_room, mention_user_ids=["@hermes:example.org"]))
+
+ dispatched = [(m.args[0].source.chat_id, m.args[0].message_id) for m in adapter.handle_message.await_args_list]
+ assert dispatched == ([("!room1:example.org", "$voice")] if claims else [(mention_room, "$text")])
+
+
# ---------------------------------------------------------------------------
# Auto-thread in _on_room_message
# ---------------------------------------------------------------------------