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(agent-bridge): write the room binding row only for connectionless callers
Louis Amaudruz1a1f79e808c4
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 5d95e3c4a..be13f3aba 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -97,6 +97,48 @@ def claim_room_on_caller_connection(return evicted.id+async def bind_room_for_connectionless_caller(+ protocol: ProtocolService,+ *,+ agent_id: str,+ connection_id: str,+ room_id: str,+ connection_model: str,+) -> bool:+ """Record the room binding row, for callers that have no connection.++ The row is how an MCP transport session resolves its room, and the only+ way it can. A connection carries its own rooms, so writing the row for one+ records a binding nothing reads — and the row has no liveness check and no+ expiry, so it outlives the connection it was written for and keeps+ answering room-scoped calls afterwards. A connection that reopens without+ re-claiming its room then reads as connected on the send path while+ delivery, which consults the connection, has nothing: the agent posts into+ a room it is no longer receiving from, invisibly from either side.++ Returns whether a row was written.+ """+ if protocol.connections.get(connection_id) is not None:+ return False++ # session_passive agents have no poll loop, so the row exists only to bind+ # the MCP transport to a room — lifecycle="explicit". always_on and+ # session_addressable agents also receive heartbeat upserts; we mark the row+ # "heartbeat" so the poll path's on-conflict update doesn't need to+ # special-case it.+ lifecycle = "explicit" if connection_model == "session_passive" else "heartbeat"+ async with protocol.session_factory() as db:+ await protocol.agent_session_store.set_connected_room(+ db,+ agent_id=agent_id,+ room_id=room_id,+ transport_session_id=connection_id,+ lifecycle=lifecycle,+ )+ await db.commit()+ return True++@operationasync def list_rooms(include_archived: bool = False) -> list[dict[str, Any]]:"""List rooms this agent is assigned to.@@ -117,10 +159,17 @@ async def list_rooms(include_archived: bool = False) -> list[dict[str, Any]]:connected_room_id: str | None = Nonekey = session_key()if key:- async with protocol.session_factory() as db:- row = await protocol.agent_session_store.get_connected_room(db, key)- if row is not None:- _, connected_room_id = row+ # Ask the live connection first and the binding row only for callers+ # that have none, matching how require_connected_room resolves it — a+ # connection carries its own rooms and no row is written for it.+ connection = protocol.connections.get(key)+ if connection is not None and len(connection.rooms) == 1:+ connected_room_id = next(iter(connection.rooms))+ elif connection is None:+ async with protocol.session_factory() as db:+ row = await protocol.agent_session_store.get_connected_room(db, key)+ if row is not None:+ _, connected_room_id = rowrooms = await protocol.list_rooms(agent_id, include_archived=include_archived)return [@@ -218,27 +267,17 @@ async def connect_to_room(key = session_key()if not key:raise ValueError("MCP session has no session id; cannot connect to room")- # session_passive agents have no poll loop, so the row exists only to- # bind the MCP transport to a room — lifecycle="explicit". always_on and- # session_addressable agents also receive heartbeat upserts; we mark the- # row "heartbeat" so the poll path's on-conflict update doesn't need to- # special-case it.- lifecycle = (- "explicit" if profile.connection_model == "session_passive" else "heartbeat"- )evicted_connection_id = claim_room_on_caller_connection(protocol, agent_id, key, room.id)- async with protocol.session_factory() as db:- await protocol.agent_session_store.set_connected_room(- db,- agent_id=agent_id,- room_id=room.id,- transport_session_id=key,- lifecycle=lifecycle,- )- await db.commit()+ await bind_room_for_connectionless_caller(+ protocol,+ agent_id=agent_id,+ connection_id=key,+ room_id=room.id,+ connection_model=profile.connection_model,+ )return {"agent_id": agent_id,diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex ddf89a063..4f9239390 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -2039,12 +2039,20 @@ class ProtocolService:"""Return (present_here, session_room_name) for a lease."""if lease.transport_session_id is None:return False, None- conn = await self.agent_session_store.get_connected_room(- session, lease.transport_session_id- )- if conn is None:- return False, None- conn_room_id = conn[1]+ # A live connection knows its own rooms and has no binding row; the+ # row is only there for callers that predate connections.+ connection = self.connections.get(lease.transport_session_id)+ if connection is not None:+ if len(connection.rooms) != 1:+ return False, None+ conn_room_id = next(iter(connection.rooms))+ else:+ conn = await self.agent_session_store.get_connected_room(+ session, lease.transport_session_id+ )+ if conn is None:+ return False, None+ conn_room_id = conn[1]if conn_room_id == room_id:return True, Noneif conn_room_id not in room_name_cache:diff --git a/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py b/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.pynew file mode 100644index 000000000..bd488c93a--- /dev/null+++ b/core/tests/switch_core/bridges/agent/operations/test_binding_row_is_legacy_only.py@@ -0,0 +1,117 @@+"""The room binding row is written only for callers with no connection.++A connection carries its own rooms, so a row written for one records a binding+nothing reads. It matters because that row has no liveness check and no expiry:+it outlives the connection it was written for and keeps answering room-scoped+calls. A connection that reopens without re-claiming its room then looks+connected to the send path while delivery, which reads the connection, has+nothing — the agent posts into a room it is no longer receiving from, and+neither side can see the discrepancy.++MCP transport sessions have no connection and the row is the only thing holding+them to a room, so it is still written for them.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from switch_core.bridges.agent.operations.definitions import (+ bind_room_for_connectionless_caller,+)+from switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_VERSION,+ ConnectionRegistry,+)++AGENT = "agent-1"+ROOM = "room-1"+CONN = "conn-1"+++class _RecordingSessionStore:+ """Captures binding-row writes without a database."""++ def __init__(self) -> None:+ self.writes: list[dict[str, Any]] = []++ async def set_connected_room(self, _db: Any, **kwargs: Any) -> None:+ self.writes.append(kwargs)+++def _open(registry: ConnectionRegistry, connection_id: str) -> Any:+ return registry.open(+ agent_id=AGENT,+ connection_id=connection_id,+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ protocol_version=PROTOCOL_VERSION,+ )+++async def _write_binding_row_if_needed(protocol: Any, key: str) -> bool:+ return await bind_room_for_connectionless_caller(+ protocol,+ agent_id=AGENT,+ connection_id=key,+ room_id=ROOM,+ connection_model="session_addressable",+ )+++def _protocol(registry: ConnectionRegistry, store: _RecordingSessionStore) -> Any:+ class _Db:+ async def __aenter__(self) -> Any:+ return self++ async def __aexit__(self, *_exc: Any) -> None:+ return None++ async def commit(self) -> None:+ return None++ return SimpleNamespace(+ connections=registry,+ agent_session_store=store,+ session_factory=lambda: _Db(),+ )+++async def test_no_row_is_written_for_a_connection_backed_caller() -> None:+ registry = ConnectionRegistry()+ _open(registry, CONN)+ store = _RecordingSessionStore()++ await _write_binding_row_if_needed(_protocol(registry, store), CONN)++ assert store.writes == []+++async def test_the_row_is_still_written_for_an_mcp_transport_session() -> None:+ # No connection was ever opened for this key, so the row is the only thing+ # that can resolve the caller's room.+ registry = ConnectionRegistry()+ store = _RecordingSessionStore()++ await _write_binding_row_if_needed(_protocol(registry, store), "mcp-session-1")++ assert len(store.writes) == 1+ assert store.writes[0]["transport_session_id"] == "mcp-session-1"+ assert store.writes[0]["room_id"] == ROOM+++async def test_a_closed_connection_falls_back_to_writing_the_row() -> None:+ # A runtime reusing a key whose connection has expired is indistinguishable+ # from an MCP transport session, and resolves the same way.+ registry = ConnectionRegistry()+ _open(registry, CONN)+ registry.close(CONN, "gone")+ store = _RecordingSessionStore()++ await _write_binding_row_if_needed(_protocol(registry, store), CONN)++ assert len(store.writes) == 1+ assert store.writes[0]["transport_session_id"] == CONN