From c1067e29269317f017b21bc1f07087752e1dc6e9 Mon Sep 17 00:00:00 2001 From: michaelxer Date: Sat, 8 Aug 2026 11:16:58 +0700 Subject: [PATCH] fix(matrix): reply to the room-level user event that started the turn Room-level Matrix responses were sent as bare top-level events even when the agent turn came from a specific user message. Set message_id from the inbound event id (alongside event_id) so the agent loop can round-trip a reply target, and attach a plain m.in_reply_to relation for non-thread outbound sends. Threaded turns keep the existing m.thread relation. Fixes #5274 --- nanobot/channels/matrix/runtime.py | 31 +++++++- .../matrix/tests/test_matrix_channel.py | 79 +++++++++++++++++++ 2 files changed, 107 insertions(+), 3 deletions(-) diff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.py index a2c78a2b8..2bfe42f4e 100644 --- a/nanobot/channels/matrix/runtime.py +++ b/nanobot/channels/matrix/runtime.py @@ -619,7 +619,7 @@ class MatrixChannel(BaseChannel): raise RuntimeError("Matrix client not initialized") text = msg.content or "" candidates = self._collect_outbound_media_candidates(msg.media) - relates_to = self._build_thread_relates_to(msg.metadata) + relates_to = self._build_outbound_relates_to(msg.metadata) is_progress = isinstance(msg.event, ProgressEvent) try: failures: list[str] = [] @@ -657,7 +657,7 @@ class MatrixChannel(BaseChannel): resuming: bool = False, merge_next: bool = False, ) -> None: - relates_to = self._build_thread_relates_to(metadata) + relates_to = self._build_outbound_relates_to(metadata) if stream_end and merge_next: if not delta: @@ -1200,6 +1200,25 @@ class MatrixChannel(BaseChannel): return {"rel_type": "m.thread", "event_id": root_id, "m.in_reply_to": {"event_id": reply_to}, "is_falling_back": True} + @classmethod + def _build_outbound_relates_to( + cls, metadata: dict[str, Any] | None + ) -> dict[str, Any] | None: + """Build Matrix relation metadata for outbound messages. + + Threaded turns keep the existing ``m.thread`` relation. Non-thread + turns attach a plain ``m.in_reply_to`` so room-level responses link + back to the user event that started the agent turn (issue #5274). + """ + if thread := cls._build_thread_relates_to(metadata): + return thread + if not metadata: + return None + reply_to = metadata.get("message_id") or metadata.get("event_id") + if not isinstance(reply_to, str) or not reply_to: + return None + return {"m.in_reply_to": {"event_id": reply_to}} + def _event_attachment_type(self, event: MatrixMediaEvent) -> str: msgtype = self._event_source_content(event).get("msgtype") return _MSGTYPE_MAP.get(cast(str, msgtype), "file") @@ -1370,10 +1389,16 @@ class MatrixChannel(BaseChannel): return attachment, _ATTACH_MARKER.format(path) def _base_metadata(self, room: MatrixRoom, event: RoomMessage) -> dict[str, Any]: - """Build common metadata for text and media handlers.""" + """Build common metadata for text and media handlers. + + ``message_id`` mirrors the Matrix event id so the agent loop and + message tool can round-trip a reply target the same way Telegram and + Discord do. ``event_id`` is kept for Matrix-specific callers. + """ meta: dict[str, Any] = {"room": getattr(room, "display_name", room.room_id)} if isinstance(eid := getattr(event, "event_id", None), str) and eid: meta["event_id"] = eid + meta["message_id"] = eid if thread := self._thread_metadata(event): meta.update(thread) return meta diff --git a/nanobot/channels/matrix/tests/test_matrix_channel.py b/nanobot/channels/matrix/tests/test_matrix_channel.py index 967c99d62..e83f76a51 100644 --- a/nanobot/channels/matrix/tests/test_matrix_channel.py +++ b/nanobot/channels/matrix/tests/test_matrix_channel.py @@ -1220,6 +1220,7 @@ async def test_on_message_sets_thread_metadata_when_threaded_event() -> None: assert metadata["thread_root_event_id"] == "$root1" assert metadata["thread_reply_to_event_id"] == "$reply1" assert metadata["event_id"] == "$reply1" + assert metadata["message_id"] == "$reply1" assert handled[0]["session_key"] == "matrix:!room:matrix.org:thread:$root1" @@ -1688,6 +1689,84 @@ async def test_send_adds_thread_relates_to_for_thread_metadata() -> None: } +@pytest.mark.asyncio +async def test_on_message_sets_message_id_for_room_level_event() -> None: + channel = MatrixChannel(_make_config(), MessageBus()) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + handled: list[dict[str, object]] = [] + + async def _fake_handle_message(**kwargs) -> None: + handled.append(kwargs) + + channel._handle_message = _fake_handle_message # type: ignore[method-assign] + + room = SimpleNamespace(room_id="!room:matrix.org", display_name="Test room", member_count=3) + event = SimpleNamespace( + sender="@alice:matrix.org", + body="Hello", + event_id="$room1", + source={"content": {}}, + ) + + await channel._on_message(room, event) + + assert len(handled) == 1 + metadata = handled[0]["metadata"] + assert metadata["event_id"] == "$room1" + assert metadata["message_id"] == "$room1" + assert "thread_root_event_id" not in metadata + + +@pytest.mark.asyncio +async def test_send_adds_in_reply_to_for_room_level_message_id() -> None: + channel = MatrixChannel(_make_config(), MessageBus()) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + await channel.send( + OutboundMessage( + channel="matrix", + chat_id="!room:matrix.org", + content="Hi", + metadata={"message_id": "$user1", "event_id": "$user1"}, + ) + ) + + content = client.room_send_calls[0]["content"] + assert content["m.relates_to"] == {"m.in_reply_to": {"event_id": "$user1"}} + + +@pytest.mark.asyncio +async def test_send_prefers_thread_relation_over_plain_reply() -> None: + channel = MatrixChannel(_make_config(), MessageBus()) + client = _FakeAsyncClient("", "", "", None) + channel.client = client + + await channel.send( + OutboundMessage( + channel="matrix", + chat_id="!room:matrix.org", + content="Hi", + metadata={ + "message_id": "$user1", + "event_id": "$user1", + "thread_root_event_id": "$root1", + "thread_reply_to_event_id": "$reply1", + }, + ) + ) + + content = client.room_send_calls[0]["content"] + assert content["m.relates_to"] == { + "rel_type": "m.thread", + "event_id": "$root1", + "m.in_reply_to": {"event_id": "$reply1"}, + "is_falling_back": True, + } + + @pytest.mark.asyncio async def test_send_uses_encrypted_media_payload_in_encrypted_room(tmp_path) -> None: channel = MatrixChannel(_make_config(e2ee_enabled=True), MessageBus())