Skip to content

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

feat(rooms): tell people when a room of theirs changes

raullopez-sandbox3a624208d0d8
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index 48e26df8c..93b6825e6 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -199,6 +199,7 @@ from switch_core.process_identity import new_process_id
from switch_core.process_lease import ProcessLease
from switch_core.provisioning import Provisioning
from switch_core.provisioning.postgres import PostgresProvisioning
+from switch_core.room_changes import RoomChanges
from switch_core.room_service import RoomService
from switch_core.session_activity.listener import AgentSessionActivityListener
from switch_core.session_activity.maintenance import (
@@ -876,13 +877,14 @@ async def run(config: SwitchConfig, process_id: str) -> None:
signal_bus.on_recheck(lambda: _recheck_agent_rooms(session_factory, router))
# ── Provisioning ─────────────────────────────────────────────────────────
- provisioning: Provisioning = PostgresProvisioning(
+ postgres_provisioning = PostgresProvisioning(
session_factory=session_factory,
room_store=room_store,
client_store=client_store,
router=router,
invites=invites,
)
+ provisioning: Provisioning = postgres_provisioning
# One shared read per room for every client in this process.
room_cache = RoomDeliveryCache(
@@ -1014,6 +1016,11 @@ async def run(config: SwitchConfig, process_id: str) -> None:
# sockets this process holds, reached from every process over the bus.
user_changes = LocalUserChanges()
user_change_publisher = SignalUserChanges(local=user_changes, bus=signal_bus)
+ room_changes = RoomChanges(
+ session_factory=session_factory, publisher=user_change_publisher
+ )
+ room_service.on_room_changed(room_changes.room_changed)
+ postgres_provisioning.on_membership_changed(room_changes.room_changed)
management = create_management(
config,
session_factory,
diff --git a/core/switch_core/provisioning/postgres.py b/core/switch_core/provisioning/postgres.py
index 411b62daf..e2b2e9394 100644
--- a/core/switch_core/provisioning/postgres.py
+++ b/core/switch_core/provisioning/postgres.py
@@ -76,6 +76,24 @@ class PostgresProvisioning:
self._client_store = client_store
self._router = router
self._invites = invites
+ self._membership_listeners: tuple[
+ Callable[[str, str, list[str]], None], ...
+ ] = ()
+
+ def on_membership_changed(
+ self, listener: Callable[[str, str, list[str]], None]
+ ) -> None:
+ """Call `listener(tenant_id, room_id, [client_id])` once a membership
+ written here has committed, a join or a removal (`room_changes`). It
+ must not block."""
+ self._membership_listeners = (*self._membership_listeners, listener)
+
+ def _membership_changed(self, tenant_id: str, room_id: str, client_id: str) -> None:
+ for listener in self._membership_listeners:
+ try:
+ listener(tenant_id, room_id, [client_id])
+ except Exception:
+ logger.exception("Membership listener failed for room %s", room_id)
async def create_room(self, name: str, topic: str) -> str:
"""Mint the id the caller will store on its own room row.
@@ -169,7 +187,12 @@ class PostgresProvisioning:
message=arrival,
attachments=[],
)
- return routed.committed
+
+ def committed() -> None:
+ routed.committed()
+ self._membership_changed(tenant_id, switch_room_id, client_id)
+
+ return committed
async def kick_user(self, room_id: str, user_id: str) -> None:
"""Remove a membership, stopping a live client's delivery with it.
@@ -203,6 +226,7 @@ class PostgresProvisioning:
await session.commit()
await removed.committed()
await self._invites.remove(client_id, room_id)
+ self._membership_changed(tenant_id, switch_room_id, client_id)
async def delete_room(self, room_id: str) -> None:
"""Nothing of its own to discard.
diff --git a/core/switch_core/room_changes.py b/core/switch_core/room_changes.py
new file mode 100644
index 000000000..086b7d892
--- /dev/null
+++ b/core/switch_core/room_changes.py
@@ -0,0 +1,113 @@
+"""Telling people a room of theirs changed, so their Console reads its room
+list again (`switch_core.user_changes`, kind `room`).
+
+Whoever a room concerns is told: its owner, the people in it (through their
+Switch Console member client or a platform account they claimed) and the
+owners of its agents. A room is reported when it is created or archived or
+unarchived, when its agents change, and when anyone joins or leaves it; the
+client that left is named so the person who lost the room is told too.
+
+The notice is a "read again", so it is sent from a task of its own after the
+change has committed, and a lost one costs only a delay: Console still reads
+its lists every few minutes.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import TYPE_CHECKING
+
+from sqlalchemy import Result, or_, select, union
+
+from switch_core.chats import MEMBER_CLIENT_TYPE
+from switch_core.db.models import (
+ Agent,
+ Client,
+ ClientRoom,
+ ExternalUser,
+ ExternalUserClaim,
+ Room,
+ room_agents,
+)
+from switch_core.db.session_scope import tenant_session
+from switch_core.user_changes import ROOM
+
+if TYPE_CHECKING:
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+ from switch_core.user_changes import UserChangePublisher
+
+logger = logging.getLogger(__name__)
+
+
+class RoomChanges:
+ def __init__(
+ self,
+ *,
+ session_factory: async_sessionmaker[AsyncSession],
+ publisher: UserChangePublisher,
+ ) -> None:
+ self._session_factory = session_factory
+ self._publisher = publisher
+ self._tasks: set[asyncio.Task[None]] = set()
+
+ def room_changed(self, tenant_id: str, room_id: str, client_ids: list[str]) -> None:
+ """Tell everyone the room concerns, and the people behind `client_ids`
+ (who may just have left it), that it changed. Returns at once."""
+ task = asyncio.create_task(self._publish(tenant_id, room_id, client_ids))
+ self._tasks.add(task)
+ task.add_done_callback(self._finished)
+
+ def _finished(self, task: asyncio.Task[None]) -> None:
+ self._tasks.discard(task)
+ if not task.cancelled() and task.exception() is not None:
+ logger.error(
+ "Could not tell people a room changed; their Console reads it "
+ "again on its next poll",
+ exc_info=task.exception(),
+ )
+
+ async def _publish(
+ self, tenant_id: str, room_id: str, client_ids: list[str]
+ ) -> None:
+ async with tenant_session(self._session_factory, tenant_id) as session:
+ user_ids = await people_concerned(session, room_id, client_ids)
+ for user_id in user_ids:
+ self._publisher.publish(tenant_id, user_id, ROOM, room_id)
+
+
+async def people_concerned(
+ session: AsyncSession, room_id: str, client_ids: list[str]
+) -> list[str]:
+ """The room's owner, the people in it and behind `client_ids`, and the
+ owners of its agents."""
+ present = set(client_ids) | set(
+ (
+ await session.execute(
+ select(ClientRoom.client_id).where(ClientRoom.room_id == room_id)
+ )
+ ).scalars()
+ )
+ found: Result[tuple[str | None]] = await session.execute(
+ union(
+ select(Room.owner_id).where(Room.id == room_id),
+ select(Client.user_id).where(
+ Client.id.in_(present), Client.type == MEMBER_CLIENT_TYPE
+ ),
+ select(ExternalUserClaim.user_id)
+ .join(ExternalUser, ExternalUser.id == ExternalUserClaim.external_user_id)
+ .where(ExternalUser.client_id.in_(present)),
+ select(Agent.owner_id).where(
+ or_(
+ Agent.id.in_(
+ select(room_agents.c.agent_id).where(
+ room_agents.c.room_id == room_id
+ )
+ ),
+ Agent.client_id.in_(present),
+ )
+ ),
+ )
+ )
+ return sorted({user_id for user_id in found.scalars() if user_id is not None})
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index 8725cffde..a6a595371 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -165,6 +165,7 @@ class RoomService:
# None as "report nothing".
_telemetry: TelemetryService | None = None
_room_agents_listeners: tuple[Callable[[str, str], Awaitable[None]], ...] = ()
+ _room_listeners: tuple[Callable[[str, str, list[str]], None], ...] = ()
def __init__(
self,
@@ -194,6 +195,19 @@ class RoomService:
# The shared delivery read; told when a room goes.
self._room_cache = room_cache
+ def on_room_changed(self, listener: Callable[[str, str, list[str]], None]) -> None:
+ """Call `listener(tenant_id, room_id, [])` once a room is created,
+ archived or unarchived, or its agents change (`room_changes`). It must
+ not block."""
+ self._room_listeners = (*self._room_listeners, listener)
+
+ def _room_changed(self, tenant_id: str, room_id: str) -> None:
+ for listener in self._room_listeners:
+ try:
+ listener(tenant_id, room_id, [])
+ except Exception:
+ logger.exception("Room listener failed for room %s", room_id)
+
def on_room_agents_changed(
self, listener: Callable[[str, str], Awaitable[None]]
) -> None:
@@ -794,6 +808,7 @@ class RoomService:
failed_attachments,
)
+ self._room_changed(room.tenant_id, room.id)
return RoomCreateResult(room=room, failed_attachments=failed_attachments)
async def _seed_aliases(
@@ -1031,6 +1046,7 @@ class RoomService:
logger.info("Added %d agents to room %s", len(agent_ids), room_id)
await self.room_agents_changed(room.tenant_id, room.id)
+ self._room_changed(room.tenant_id, room.id)
emit_safely(
self._telemetry,
@@ -1073,6 +1089,7 @@ class RoomService:
logger.info("Removed %d agents from room %s", len(agent_ids), room_id)
await self.room_agents_changed(room.tenant_id, room.id)
+ self._room_changed(room.tenant_id, room.id)
emit_safely(
self._telemetry,
@@ -1183,6 +1200,7 @@ class RoomService:
async with tenant_session(self._session_factory, room.tenant_id) as session:
await self._room_store.set_archived(session, room_id, archived)
await session.commit()
+ self._room_changed(room.tenant_id, room_id)
if not archived or self._telemetry is None:
return
diff --git a/core/switch_core/user_changes.py b/core/switch_core/user_changes.py
index 497bab076..efde56db1 100644
--- a/core/switch_core/user_changes.py
+++ b/core/switch_core/user_changes.py
@@ -1,7 +1,7 @@
"""Telling a signed-in user that something of theirs changed, so their Console
reads it again instead of polling for it.
-A change names a kind and an id (`managed_agent`, `machine`) and carries
+A change names a kind and an id (`managed_agent`, `machine`, `room`) and carries
nothing else: the client already knows how to read the current state, and a
notice that is only "read again" cannot leak what the reader would not be
allowed to read. That also makes a lost notice cheap. A client reads
@@ -46,7 +46,9 @@ logger = logging.getLogger(__name__)
MANAGED_AGENT = "managed_agent"
MACHINE = "machine"
-KINDS = (MANAGED_AGENT, MACHINE)
+# A room the user takes part in (`switch_core.room_changes`).
+ROOM = "room"
+KINDS = (MANAGED_AGENT, MACHINE, ROOM)
USER_CHANGED_SIGNAL = "user.changed"
diff --git a/core/tests/switch_core/db/stores/test_room_store_involves.py b/core/tests/switch_core/db/stores/test_room_store_involves.py
index d778927e4..4252891c8 100644
--- a/core/tests/switch_core/db/stores/test_room_store_involves.py
+++ b/core/tests/switch_core/db/stores/test_room_store_involves.py
@@ -18,6 +18,7 @@ from switch_core.db.models import (
room_agents,
)
from switch_core.db.stores.room_store import RoomStore
+from switch_core.room_changes import people_concerned
from tests.switch_core.gateway.agent_route_harness import add_agent
@@ -102,3 +103,10 @@ async def test_a_person_reads_the_rooms_they_take_part_in_and_no_other(
await store.involved_room_ids(session, alice.id, [*expected, unrelated.id])
== expected
)
+ assert await people_concerned(session, discord.id, []) == [alice.id]
+ assert set(await people_concerned(session, with_agent.id, [])) == {
+ alice.id,
+ bob.id,
+ }
+ # Someone who just left is named by the client they left with.
+ assert alice.id in await people_concerned(session, unrelated.id, [member.id])
diff --git a/core/tests/switch_core/gateway/test_changes_socket.py b/core/tests/switch_core/gateway/test_changes_socket.py
index 015f39647..337d0efba 100644
--- a/core/tests/switch_core/gateway/test_changes_socket.py
+++ b/core/tests/switch_core/gateway/test_changes_socket.py
@@ -21,7 +21,7 @@ from starlette.websockets import WebSocketDisconnect
from switch_core.gateway import changes
from switch_core.gateway import dependencies as gw_deps
from switch_core.gateway.auth import SocketCaller
-from switch_core.user_changes import MACHINE, MANAGED_AGENT, LocalUserChanges
+from switch_core.user_changes import MACHINE, MANAGED_AGENT, ROOM, LocalUserChanges
def _app(feed: LocalUserChanges) -> FastAPI:
@@ -69,7 +69,7 @@ def test_opens_with_hello_naming_the_kinds_it_sends(
with client.websocket_connect("/changes/ws") as ws:
hello = ws.receive_json()
assert hello["event"] == "hello"
- assert set(hello["data"]["kinds"]) == {MANAGED_AGENT, MACHINE}
+ assert set(hello["data"]["kinds"]) == {MANAGED_AGENT, MACHINE, ROOM}
assert hello["data"]["ping_interval_s"] == changes.PING_INTERVAL_SECONDS
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index f0cfb9f34..98aa883d9 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -20,6 +20,8 @@ from switch_core.bridges.agent.registration_bootstrap import (
from switch_core.chats.service import ChatError, ChatService
from switch_core.db.models import Agent, Client, Message, Room, User, room_agents
from switch_core.gateway import chats as chats_module
+from switch_core.room_changes import RoomChanges
+from switch_core.user_changes import ROOM
from tests.switch_core.gateway.conftest import (
_chat_service,
_FakeActivityListener,
@@ -1231,3 +1233,56 @@ async def test_one_request_id_with_two_payloads_on_two_processes_is_one_request(
f"/chats/{rooms[0].id}/members", headers=chats.as_user(chats.alice)
)
assert len({m["userId"] for m in members.json()["members"]}) == 2
+
+
+# ── Room change notices ──────────────────────────────────────────────────────
+
+
+class _Published:
+ def __init__(self) -> None:
+ self.notices: list[tuple[str, str, str]] = []
+
+ def publish(self, tenant_id: str, user_id: str, kind: str, id: str) -> None:
+ self.notices.append((user_id, kind, id))
+
+
+async def test_people_are_told_when_a_room_of_theirs_changes(chats: _Harness) -> None:
+ published = _Published()
+ changes = RoomChanges(session_factory=chats.factory, publisher=published)
+ chats.room_service.on_room_changed(changes.room_changed)
+ chats.service._provisioning.on_membership_changed(changes.room_changed) # type: ignore[attr-defined]
+
+ async def told() -> set[str]:
+ await asyncio.gather(*changes._tasks)
+ users = {user_id for user_id, kind, _ in published.notices if kind == ROOM}
+ published.notices.clear()
+ return users
+
+ mine = await chats.agent("mine", owner=chats.alice)
+ admins = await chats.agent("admins", owner=chats.admin)
+ room_id = await chats.new_chat(chats.alice, mine, "c1")
+ assert await told() == {chats.alice.id}
+
+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
+ assert await told() == {chats.alice.id, chats.bob.id}
+
+ assert (await _add_agent(chats, chats.alice.id, room_id, admins)).status_code == 200
+ assert chats.admin.id in await told()
+
+ removed = await chats.client.delete(
+ f"/chats/{room_id}/agents/{admins.id}", headers=chats.as_user(chats.alice)
+ )
+ assert removed.status_code == 204
+ assert chats.admin.id in await told()
+
+ left = await chats.client.delete(
+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.bob)
+ )
+ assert left.status_code == 204
+ assert chats.bob.id in await told()
+
+ archived = await chats.client.post(
+ f"/chats/{room_id}/archive", headers=chats.as_user(chats.alice)
+ )
+ assert archived.status_code == 204
+ assert await told() == {chats.alice.id}
diff --git a/core/tests/switch_core/management/test_user_changes.py b/core/tests/switch_core/management/test_user_changes.py
index 2b5069d11..907293e7b 100644
--- a/core/tests/switch_core/management/test_user_changes.py
+++ b/core/tests/switch_core/management/test_user_changes.py
@@ -17,6 +17,7 @@ from switch_core.signals import SignalBus
from switch_core.user_changes import (
MACHINE,
MANAGED_AGENT,
+ ROOM,
USER_CHANGED_SIGNAL,
LocalUserChanges,
SignalUserChanges,
@@ -191,6 +192,7 @@ class TestAcrossProcesses:
assert set(subscription.drain()) == {
UserChange(MANAGED_AGENT, None),
UserChange(MACHINE, None),
+ UserChange(ROOM, None),
}