Skip to content

The agent that grows with you

feat(matrix): implement create_handoff_thread

ea-s213063d0f2bb8d
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 418882f9089..b533c15c5e8 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -1413,6 +1413,40 @@ class MatrixAdapter(BasePlatformAdapter):
self._client.send_message_event(RoomID(chat_id), EventType.ROOM_MESSAGE, msg_content), timeout=45)
return str(event_id)
+ async def create_handoff_thread(
+ self,
+ parent_chat_id: str,
+ name: str,
+ ) -> Optional[str]:
+ """Create a Matrix thread anchor for a session handoff.
+
+ Matrix has no channel-level "create thread" API — a thread is just
+ events whose ``m.relates_to``/``rel_type: m.thread`` reference a root
+ event's ``event_id`` (the same model Slack uses with ``thread_ts``).
+ So post a seed/root message into ``parent_chat_id`` and return its
+ ``event_id``: the handoff watcher / cron scheduler uses that as the
+ ``thread_id`` for subsequent sends, and ``_apply_relation_metadata``
+ already threads them off it.
+
+ Returns the seed event id as a string, or ``None`` if the client is
+ unavailable or the seed send failed (callers fall back to
+ ``parent_chat_id`` directly).
+ """
+ if self._client is None:
+ return None
+ seed_text = (name or "").strip() or "Hermes session"
+ result = await self.send(parent_chat_id, seed_text)
+ root = result.message_id if (result and result.success) else None
+ if not root:
+ return None
+ try:
+ # Register the root so inbound replies in this thread are
+ # recognised as participated (mirrors inbound thread handling).
+ self._threads.mark(str(root))
+ except Exception: # pragma: no cover - defensive
+ pass
+ return str(root)
+
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
identity = await self._resolve_room_identity(chat_id)
return {"name": identity.display_name, "type": "dm" if identity.chat_type == "dm" else "group"}
diff --git a/tests/gateway/test_matrix_handoff_thread.py b/tests/gateway/test_matrix_handoff_thread.py
new file mode 100644
index 00000000000..6004209debb
--- /dev/null
+++ b/tests/gateway/test_matrix_handoff_thread.py
@@ -0,0 +1,81 @@
+"""Tests for MatrixAdapter.create_handoff_thread.
+
+Matrix has no channel-level "create thread" API, so the adapter seeds a root
+message and returns its event_id as the thread handle (Slack-style — mirrors
+``tests/gateway/test_slack_sdk_response.py::TestHandoffThread``). These tests
+cover: the seed event id becomes the thread id (and the root is registered as a
+participated thread), a blank name falls back to a default seed, and ``None`` is
+returned when the client is absent or the seed send fails.
+"""
+
+import asyncio
+import time
+from unittest.mock import AsyncMock, MagicMock
+
+from gateway.config import PlatformConfig
+from gateway.platforms.base import SendResult
+
+
+def _make_adapter():
+ """Create a MatrixAdapter with mocked config (no live client)."""
+ from plugins.platforms.matrix.adapter import MatrixAdapter
+
+ config = PlatformConfig(
+ enabled=True,
+ token="syt_test_token",
+ extra={
+ "homeserver": "https://matrix.example.org",
+ "user_id": "@hermes:example.org",
+ },
+ )
+ adapter = MatrixAdapter(config)
+ adapter._startup_ts = time.time() - 10
+ return adapter
+
+
+class TestHandoffThread:
+ """``create_handoff_thread`` anchors a session on the seed event's id."""
+
+ def test_seed_event_becomes_the_thread_id(self):
+ adapter = _make_adapter()
+ adapter._client = MagicMock() # truthy: a client is connected
+ adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="$root_evt"))
+
+ thread_id = asyncio.run(adapter.create_handoff_thread("!room1:example.org", "Hermes — daily brief"))
+
+ assert thread_id == "$root_evt"
+ adapter.send.assert_awaited_once_with("!room1:example.org", "Hermes — daily brief")
+ # Root registered so inbound replies in this thread are recognised.
+ assert "$root_evt" in adapter._threads
+
+ def test_blank_name_falls_back_to_default_seed(self):
+ adapter = _make_adapter()
+ adapter._client = MagicMock()
+ adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="$root2"))
+
+ thread_id = asyncio.run(adapter.create_handoff_thread("!room1:example.org", " "))
+
+ assert thread_id == "$root2"
+ adapter.send.assert_awaited_once_with("!room1:example.org", "Hermes session")
+
+ def test_no_client_yields_no_thread(self):
+ adapter = _make_adapter()
+ adapter._client = None
+ adapter.send = AsyncMock()
+
+ assert asyncio.run(adapter.create_handoff_thread("!room1:example.org", "x")) is None
+ adapter.send.assert_not_awaited()
+
+ def test_failed_seed_send_yields_no_thread(self):
+ adapter = _make_adapter()
+ adapter._client = MagicMock()
+ adapter.send = AsyncMock(return_value=SendResult(success=False, error="boom"))
+
+ assert asyncio.run(adapter.create_handoff_thread("!room1:example.org", "x")) is None
+
+ def test_seed_send_without_event_id_yields_no_thread(self):
+ adapter = _make_adapter()
+ adapter._client = MagicMock()
+ adapter.send = AsyncMock(return_value=SendResult(success=True, message_id=None))
+
+ assert asyncio.run(adapter.create_handoff_thread("!room1:example.org", "x")) is None