Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(bridge): don't drop a bridged message when the puppet joined in an earlier run (#199)
Louis Amaudruz6da2d7078375
diff --git a/core/switch_core/clients/client_base.py b/core/switch_core/clients/client_base.pyindex e0b37ae1f..a405896f6 100644--- a/core/switch_core/clients/client_base.py+++ b/core/switch_core/clients/client_base.py@@ -10,6 +10,7 @@ import markdownfrom nio import (AsyncClient,InviteMemberEvent,+ JoinedRoomsError,LoginError,MatrixRoom,ReactionEvent,@@ -119,20 +120,40 @@ class ClientBase[ConfigT: ClientConfig]:self._room_joined_events[room_id] = eventreturn event- def _mark_joined(self, room_id: str) -> None:- self.room_join_times[room_id] = int(time.time() * 1000)+ def _mark_joined(self, room_id: str, joined_at_ms: int) -> None:+ self.room_join_times[room_id] = joined_at_msself._joined_event(room_id).set()+ async def _is_joined_on_server(self, room_id: str) -> bool:+ resp = await self.client.joined_rooms()+ if isinstance(resp, JoinedRoomsError):+ logger.error(+ "Failed to list joined rooms for %s: %s",+ self.matrix_user_id,+ resp.message,+ )+ return False+ return room_id in resp.rooms+async def wait_joined(self, room_id: str, timeout: float) -> bool:- """Block until this client's join to `room_id` has been observed (via- sync or an explicit join), up to `timeout` seconds. Returns True if- joined, False on timeout. Callers that need to *send* into a room they- have only just been invited to must await this first — a send issued- before the join lands is rejected by the homeserver, and any event that- does land before a member's join is filtered out by `_should_ignore`."""+ """Block until this client is a member of `room_id`, up to `timeout`+ seconds. Returns True if joined, False on timeout. Callers that need to+ *send* into a room they have only just been invited to must await this+ first — a send issued before the join lands is rejected by the+ homeserver, and any event that does land before a member's join is+ filtered out by `_should_ignore`.++ A join observed through sync sets the event, but a join that predates+ this process never replays: the client resumes from a stored+ `next_batch` token, so an incremental sync carries no member event for a+ room it joined in an earlier run, and re-inviting an existing member is+ a no-op. The homeserver is therefore asked directly before waiting."""event = self._joined_event(room_id)if event.is_set():return True+ if await self._is_joined_on_server(room_id):+ self._mark_joined(room_id, self._startup_ts)+ return Truetry:await asyncio.wait_for(event.wait(), timeout)except TimeoutError:@@ -271,7 +292,7 @@ class ClientBase[ConfigT: ClientConfig]:) -> None:if event.state_key == self.matrix_user_id and event.membership == "join":already_joined = room.room_id in self.room_join_times- self._mark_joined(room.room_id)+ self._mark_joined(room.room_id, event.server_timestamp)if not already_joined and event.server_timestamp >= self._startup_ts:try:await self.on_self_join(room, event)@@ -705,7 +726,7 @@ class ClientBase[ConfigT: ClientConfig]:async def join_room(self, room_id: str) -> None:resp = await self.client.join(room_id)if hasattr(resp, "room_id"):- self._mark_joined(room_id)+ self._mark_joined(room_id, int(time.time() * 1000))logger.info("Client %s joined %s", self.matrix_user_id, room_id)else:logger.error(diff --git a/core/tests/switch_core/clients/test_wait_joined_existing_membership.py b/core/tests/switch_core/clients/test_wait_joined_existing_membership.pynew file mode 100644index 000000000..0f970e225--- /dev/null+++ b/core/tests/switch_core/clients/test_wait_joined_existing_membership.py@@ -0,0 +1,82 @@+from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from nio import JoinedRoomsError++from switch_core.clients.client_base import ClientBase++MATRIX_ROOM_ID = "!matrix:switch.local"+++class _FakeNioClient:+ def __init__(self, rooms: list[str] | None) -> None:+ self._rooms = rooms+ self.calls = 0++ async def joined_rooms(self) -> object:+ self.calls += 1+ if self._rooms is None:+ return JoinedRoomsError(message="boom")+ return SimpleNamespace(rooms=list(self._rooms))+++def _client(nio_client: _FakeNioClient) -> ClientBase:+ client = ClientBase.__new__(ClientBase)+ client.matrix_user_id = "@ext_alice:switch.local"+ client.nio_client = nio_client+ client.room_join_times = {}+ client._room_joined_events = {}+ client._startup_ts = 1000+ return client+++async def test_wait_joined_accepts_membership_that_predates_this_process() -> None:+ """A puppet joined in an earlier run replays no member event: the client+ resumes from a stored next_batch token, and re-inviting an existing member+ is a no-op. Waiting on sync alone times out and the message is dropped."""+ nio_client = _FakeNioClient([MATRIX_ROOM_ID])+ client = _client(nio_client)++ assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is True+ assert nio_client.calls == 1+ # The join predates startup, so it must not shift the ignore cutoff forward+ # and suppress events already in flight.+ assert client.room_join_times[MATRIX_ROOM_ID] == client._startup_ts++ # Membership is cached — no second round trip.+ assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is True+ assert nio_client.calls == 1+++async def test_wait_joined_still_waits_for_a_pending_join() -> None:+ nio_client = _FakeNioClient([])+ client = _client(nio_client)++ async def join_late() -> None:+ await asyncio.sleep(0.01)+ client._mark_joined(MATRIX_ROOM_ID, 2000)++ task = asyncio.create_task(join_late())+ assert await client.wait_joined(MATRIX_ROOM_ID, 1.0) is True+ await task+++async def test_wait_joined_times_out_when_the_join_never_lands() -> None:+ client = _client(_FakeNioClient([]))+ assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is False+++async def test_wait_joined_falls_back_to_waiting_when_the_lookup_fails() -> None:+ nio_client = _FakeNioClient(None)+ client = _client(nio_client)++ assert await client.wait_joined(MATRIX_ROOM_ID, 0.05) is False+ assert nio_client.calls == 1+ assert MATRIX_ROOM_ID not in client.room_join_times+++if __name__ == "__main__":+ pytest.main([__file__])