Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(bridge): don't drop first message from an unknown channel member

switch-worker-louis-remote8be349d6b41f
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 397f35b3b..d7e7c0d83 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -44,6 +44,10 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+# How long to wait for a freshly-invited external-user puppet to actually join a
+# room before giving up on relaying its message.
+PUPPET_JOIN_TIMEOUT = 30.0
+
_LOBBY_DEPRECATION_NOTICE = (
"πŸ‘‹ This isn't where you talk to agents β€” direct messages to the Switch "
"app aren't routed to anyone. Head to a channel and @-mention an agent "
@@ -353,6 +357,7 @@ class BridgeCore:
external_user_id=msg.sender_id,
external_username=msg.sender_name,
room_id=room_id,
+ matrix_room_id=matrix_room_id,
)
if puppet is None:
return
@@ -389,13 +394,20 @@ class BridgeCore:
format="markdown",
thread_root_id=thread_root_id,
)
- # Record the correlation so a later reply (either direction) threads.
- if event_id is not None:
- await self._record_message_map(
- external_channel_id=msg.channel_id,
- matrix_event_id=event_id,
- external_post_id=msg.message_ref,
+ if event_id is None:
+ logger.error(
+ "[BRIDGE-IN] failed to relay message from %s into room %s β€” "
+ "it will not reach the room",
+ msg.sender_name,
+ matrix_room_id,
)
+ return
+ # Record the correlation so a later reply (either direction) threads.
+ await self._record_message_map(
+ external_channel_id=msg.channel_id,
+ matrix_event_id=event_id,
+ external_post_id=msg.message_ref,
+ )
return
# Caption convention: the text rides as the caption on the first
@@ -421,6 +433,13 @@ class BridgeCore:
caption=caption if index == 0 else None,
thread_root_id=thread_root_id,
)
+ if event_id is None:
+ logger.error(
+ "[BRIDGE-IN] failed to relay attachment %s from %s into room %s",
+ attachment.filename,
+ msg.sender_name,
+ matrix_room_id,
+ )
if index == 0:
first_event_id = event_id
@@ -442,6 +461,7 @@ class BridgeCore:
external_user_id=cmd.sender_id,
external_username=cmd.sender_name,
room_id=room_id,
+ matrix_room_id=matrix_room_id,
)
if puppet is None:
return
@@ -730,6 +750,7 @@ class BridgeCore:
external_user_id=ext_user.external_user_id,
external_username=ext_user.external_username,
room_id=room_id,
+ matrix_room_id=matrix_room_id,
)
async def _ensure_user_in_matrix_room(
@@ -738,10 +759,11 @@ class BridgeCore:
external_user_id: str,
external_username: str,
room_id: str,
+ matrix_room_id: str,
) -> ClientBase[ClientConfig] | None:
- """Get-or-create the puppet for this external user and ensure it is a
- member of the room (invited; it auto-joins). Returns the running
- puppet, or None if it couldn't be brought up. Idempotent."""
+ """Get-or-create the puppet for this external user and ensure it has
+ actually joined the room. Returns the running puppet, or None if it
+ couldn't be brought up or didn't join in time. Idempotent."""
client_id = self._user_puppets.get(external_user_id)
if client_id is None:
client_id = await self._create_puppet(external_user_id, external_username)
@@ -754,14 +776,28 @@ class BridgeCore:
)
return None
await puppet.wait_ready()
- # Tolerant of failure so one puppet that can't join does not break
- # bridged delivery for the rest of the room.
try:
await self._room_service.ensure_client_in_room(room_id, client_id)
except Exception:
logger.exception(
"Failed to add puppet client %s to room %s", client_id, room_id
)
+ return None
+
+ # ensure_client_in_room only *invites*; the puppet joins asynchronously
+ # from its own sync loop. Sending before that join lands gets rejected by
+ # the homeserver, so the message that triggered the provisioning would be
+ # lost. Block until the join is observed.
+ if not await puppet.wait_joined(matrix_room_id, PUPPET_JOIN_TIMEOUT):
+ logger.error(
+ "Puppet %s (external user %s) did not join room %s within %ss β€” "
+ "cannot relay its message",
+ puppet.matrix_user_id,
+ external_user_id,
+ matrix_room_id,
+ PUPPET_JOIN_TIMEOUT,
+ )
+ return None
return puppet
async def _handle_user_joined_channel(self, join: InboundUserJoin) -> None:
@@ -803,6 +839,7 @@ class BridgeCore:
external_user_id=join.external_user_id,
external_username=join.external_username,
room_id=room_id,
+ matrix_room_id=matrix_room_id,
)
# ── Puppet lifecycle ─────────────────────────────────────────────────────
diff --git a/core/switch_core/clients/client_base.py b/core/switch_core/clients/client_base.py
index 67bc54ac9..eb065107e 100644
--- a/core/switch_core/clients/client_base.py
+++ b/core/switch_core/clients/client_base.py
@@ -101,6 +101,7 @@ class ClientBase[ConfigT: ClientConfig]:
self.nio_client: AsyncClient | None = None
self.room_join_times: dict[str, int] = {}
+ self._room_joined_events: dict[str, asyncio.Event] = {}
self._ready = asyncio.Event()
self._startup_ts: int = 0
self._last_sync_persist: float = 0.0
@@ -110,6 +111,33 @@ class ClientBase[ConfigT: ClientConfig]:
async def wait_ready(self) -> None:
await self._ready.wait()
+ def _joined_event(self, room_id: str) -> asyncio.Event:
+ event = self._room_joined_events.get(room_id)
+ if event is None:
+ event = asyncio.Event()
+ self._room_joined_events[room_id] = event
+ return event
+
+ def _mark_joined(self, room_id: str) -> None:
+ self.room_join_times[room_id] = int(time.time() * 1000)
+ self._joined_event(room_id).set()
+
+ 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`."""
+ event = self._joined_event(room_id)
+ if event.is_set():
+ return True
+ try:
+ await asyncio.wait_for(event.wait(), timeout)
+ except TimeoutError:
+ return False
+ return True
+
@property
def client(self) -> AsyncClient:
if self.nio_client is None:
@@ -242,7 +270,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.room_join_times[room.room_id] = int(time.time() * 1000)
+ self._mark_joined(room.room_id)
if not already_joined and event.server_timestamp >= self._startup_ts:
try:
await self.on_self_join(room, event)
@@ -437,7 +465,7 @@ class ClientBase[ConfigT: ClientConfig]:
logger.info(
"Client %s auto-accepting invite to %s", self.matrix_user_id, room.room_id
)
- await self.client.join(room.room_id)
+ await self.join_room(room.room_id)
async def on_command(self, room: MatrixRoom, event: CommandEvent) -> None:
pass
@@ -666,7 +694,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.room_join_times[room_id] = int(time.time() * 1000)
+ self._mark_joined(room_id)
logger.info("Client %s joined %s", self.matrix_user_id, room_id)
else:
logger.error(
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py
new file mode 100644
index 000000000..7cf01da09
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_unknown_member_first_message.py
@@ -0,0 +1,145 @@
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from switch_core.bridges.collaboration import bridge_core as bridge_core_module
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+from switch_core.bridges.collaboration.models import InboundMessage
+
+# CHOO-1781: the first message from a channel member not yet known to the room
+# must not be dropped. Provisioning only *invites* the external user's puppet β€”
+# the join lands asynchronously from the puppet's own sync loop. Relaying before
+# that join is rejected by the homeserver, so the triggering message vanishes.
+# _ensure_user_in_matrix_room must therefore block until the join is observed,
+# and must refuse to hand back a puppet that never joined.
+
+MATRIX_ROOM_ID = "!matrix:switch.local"
+
+
+class _FakePuppet:
+ """Stands in for a ClientBase puppet whose join lands after the invite."""
+
+ def __init__(self) -> None:
+ self.matrix_user_id = "@ext_alice:switch.local"
+ self._joined = asyncio.Event()
+ self.sent: list[tuple[str, str]] = []
+ self.wait_joined_calls: list[tuple[str, float]] = []
+
+ async def wait_ready(self) -> None:
+ return None
+
+ def complete_join(self) -> None:
+ self._joined.set()
+
+ async def wait_joined(self, room_id: str, timeout: float) -> bool:
+ self.wait_joined_calls.append((room_id, timeout))
+ try:
+ await asyncio.wait_for(self._joined.wait(), timeout)
+ except TimeoutError:
+ return False
+ return True
+
+ async def send_message(self, room_id: str, content: str, **_kw: object) -> str:
+ if not self._joined.is_set():
+ # Mirrors the homeserver rejecting a send from a non-member.
+ raise AssertionError("puppet sent into a room it has not joined")
+ self.sent.append((room_id, content))
+ return "$event-1"
+
+
+def _bridge(puppet: _FakePuppet) -> SimpleNamespace:
+ async def _ensure_client_in_room(room_id: str, client_id: str) -> None:
+ return None # invite only β€” the join is asynchronous, as in production
+
+ return SimpleNamespace(
+ _user_puppets={"ext-alice": "client-1"},
+ _client_lifecycle=SimpleNamespace(get=lambda _id: puppet),
+ _room_service=SimpleNamespace(ensure_client_in_room=_ensure_client_in_room),
+ )
+
+
+async def test_waits_for_puppet_join_before_returning() -> None:
+ puppet = _FakePuppet()
+ bridge = _bridge(puppet)
+
+ task = asyncio.create_task(
+ BridgeCore._ensure_user_in_matrix_room(
+ bridge,
+ external_user_id="ext-alice",
+ external_username="alice",
+ room_id="room-uuid",
+ matrix_room_id=MATRIX_ROOM_ID,
+ )
+ )
+ await asyncio.sleep(0)
+
+ # Still blocked: the puppet has been invited but has not joined yet.
+ assert not task.done()
+
+ puppet.complete_join()
+ assert await task is puppet
+ assert puppet.wait_joined_calls == [
+ (MATRIX_ROOM_ID, bridge_core_module.PUPPET_JOIN_TIMEOUT)
+ ]
+
+
+async def test_returns_none_when_join_never_lands(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(bridge_core_module, "PUPPET_JOIN_TIMEOUT", 0.01)
+ puppet = _FakePuppet() # never joins
+
+ result = await BridgeCore._ensure_user_in_matrix_room(
+ _bridge(puppet),
+ external_user_id="ext-alice",
+ external_username="alice",
+ room_id="room-uuid",
+ matrix_room_id=MATRIX_ROOM_ID,
+ )
+
+ # Fail loud, never fake: no puppet handed back, so nothing is relayed into a
+ # room the sender is not a member of.
+ assert result is None
+
+
+async def test_first_message_from_unknown_member_is_relayed() -> None:
+ puppet = _FakePuppet()
+ relayed: list[tuple[str, str]] = []
+
+ async def _is_registered_agent(_name: str) -> bool:
+ return False
+
+ async def _ensure_user_in_matrix_room(**_kw: object) -> _FakePuppet:
+ # Provisioning completes the join, as the real path now guarantees.
+ puppet.complete_join()
+ return puppet
+
+ async def _record_message_map(**kwargs: str) -> None:
+ relayed.append((kwargs["matrix_event_id"], kwargs["external_post_id"]))
+
+ bridge = SimpleNamespace(
+ _is_registered_agent=_is_registered_agent,
+ _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,
+ _record_message_map=_record_message_map,
+ _adapter=SimpleNamespace(translate_inbound=lambda text: text),
+ _channel_to_room={"chan-1": ("room-uuid", MATRIX_ROOM_ID)},
+ _channel_locks={},
+ )
+
+ await BridgeCore._handle_inbound_message(
+ bridge,
+ InboundMessage(
+ channel_id="chan-1",
+ channel_type="channel_public",
+ sender_id="ext-alice",
+ sender_name="alice",
+ content="hello from a brand new member",
+ message_ref="mm-post-1",
+ ),
+ )
+
+ assert puppet.sent == [(MATRIX_ROOM_ID, "hello from a brand new member")]
+ assert relayed == [("$event-1", "mm-post-1")]