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
feat(core): route session activity to room subscribers
raullopez-sandbox46895c077045
diff --git a/core/switch_core/session_activity/listener.py b/core/switch_core/session_activity/listener.pyindex 9531ba745..b93c88b17 100644--- a/core/switch_core/session_activity/listener.py+++ b/core/switch_core/session_activity/listener.py@@ -20,7 +20,7 @@ import asyncioimport contextlibimport jsonimport logging-from collections.abc import Awaitable, Callable+from collections.abc import Awaitable, Callable, Iterablefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any@@ -108,6 +108,45 @@ class _Subscriber:on_resync: OnResync+class RoomSubscription:+ """A subscriber to the changes in a set of a tenant's rooms.++ Only routing: a change for a room in the set wakes the subscriber, and+ nothing else does. Whether its reader may still see the room is for the+ subscriber to check.+ """++ def __init__(+ self,+ index: dict[tuple[str, str], set[_Subscriber]],+ subscribers: dict[_Subscriber, str],+ tenant_id: str,+ subscriber: _Subscriber,+ ) -> None:+ self._index = index+ self._subscribers = subscribers+ self._tenant_id = tenant_id+ self._subscriber = subscriber+ self._rooms: set[str] = set()++ def set_rooms(self, rooms: Iterable[str]) -> None:+ wanted = set(rooms)+ for room_id in self._rooms - wanted:+ key = (self._tenant_id, room_id)+ self._index[key].discard(self._subscriber)+ if not self._index[key]:+ del self._index[key]+ for room_id in wanted - self._rooms:+ self._index.setdefault((self._tenant_id, room_id), set()).add(+ self._subscriber+ )+ self._rooms = wanted++ def close(self) -> None:+ self.set_rooms(())+ self._subscribers.pop(self._subscriber, None)++_RESYNC = object()@@ -115,6 +154,9 @@ class AgentSessionActivityListener:def __init__(self, engine_factory: EngineFactory) -> None:self._engine_factory = engine_factoryself._subscribers: dict[str, set[_Subscriber]] = {}+ self._room_index: dict[tuple[str, str], set[_Subscriber]] = {}+ # Every room subscriber, open, to its tenant.+ self._room_subscribers: dict[_Subscriber, str] = {}self._queue: asyncio.Queue[Change | object] = asyncio.Queue()self._tasks: list[asyncio.Task[None]] = []self._running = False@@ -140,6 +182,23 @@ class AgentSessionActivityListener:return unsubscribe+ def subscribe_rooms(+ self,+ tenant_id: str,+ rooms: Iterable[str],+ on_change: OnChange,+ on_resync: OnResync,+ ) -> RoomSubscription:+ """Receive the changes in these rooms only; a change outside any room+ reaches none. `on_resync` runs as for `subscribe`."""+ subscriber = _Subscriber(on_change, on_resync)+ self._room_subscribers[subscriber] = tenant_id+ subscription = RoomSubscription(+ self._room_index, self._room_subscribers, tenant_id, subscriber+ )+ subscription.set_rooms(rooms)+ return subscription+# ── Lifecycle ─────────────────────────────────────────────────────────────async def start(self) -> None:@@ -234,8 +293,13 @@ class AgentSessionActivityListener:for tenant_id, subscribers in list(self._subscribers.items()):for subscriber in list(subscribers):await self._call(tenant_id, subscriber.on_resync())+ for subscriber, tenant_id in list(self._room_subscribers.items()):+ await self._call(tenant_id, subscriber.on_resync())elif isinstance(item, Change):- for subscriber in list(self._subscribers.get(item.tenant_id, ())):+ targets = list(self._subscribers.get(item.tenant_id, ()))+ if item.room_id is not None:+ targets += self._room_index.get((item.tenant_id, item.room_id), ())+ for subscriber in targets:await self._call(item.tenant_id, subscriber.on_change(item))async def _call(self, tenant_id: str, handler: Awaitable[None]) -> None:diff --git a/core/tests/switch_core/session_activity/test_listener_rooms.py b/core/tests/switch_core/session_activity/test_listener_rooms.pynew file mode 100644index 000000000..ba4b6171e--- /dev/null+++ b/core/tests/switch_core/session_activity/test_listener_rooms.py@@ -0,0 +1,148 @@+from __future__ import annotations++import asyncio+import json+from collections.abc import AsyncIterator++import pytest+from sqlalchemy import text+from sqlalchemy.ext.asyncio import create_async_engine+from sqlalchemy.pool import NullPool++from switch_core.db.session_activity_notify_ddl import SESSION_ACTIVITY_CHANNEL+from switch_core.session_activity.listener import AgentSessionActivityListener+from switch_core.tenant_context import current_tenant_id++from .conftest import AGENT, Recorder, make_room+from .test_service import SESSION, _step+++def _tenant() -> str:+ tenant = current_tenant_id()+ assert tenant is not None+ return tenant+++async def _start(listener: AgentSessionActivityListener) -> None:+ await listener.start()+ await asyncio.wait_for(listener.connected.wait(), 5)+++def listener(postgres_url) -> AgentSessionActivityListener:+ return AgentSessionActivityListener(+ lambda: create_async_engine(postgres_url, poolclass=NullPool)+ )+++async def started(listener) -> AsyncIterator[AgentSessionActivityListener]:+ await _start(listener)+ try:+ yield listener+ finally:+ await listener.stop()+++async def rooms(session_factory, people) -> tuple[str, str]:+ async with session_factory() as db, db.begin():+ return (+ await make_room(db, member=AGENT),+ await make_room(db, member=AGENT),+ )+++async def _report(service, turn_id: str, room_id: str | None) -> None:+ await service.report_item(AGENT, SESSION, **_step(turn_id=turn_id, room_id=room_id))+++async def test_a_room_subscriber_hears_only_its_rooms(started, service, rooms):+ x, y = rooms+ everything, in_x = Recorder(), Recorder()+ started.subscribe(_tenant(), everything.on_change, everything.on_resync)+ started.subscribe_rooms(_tenant(), [x], in_x.on_change, in_x.on_resync)++ await _report(service, "in-y", y)+ await _report(service, "nowhere", None)+ await _report(service, "in-x", x)++ await in_x.expect([("activity", "in-x")])+ await everything.expect(+ [("activity", "in-y"), ("activity", "nowhere"), ("activity", "in-x")]+ )+++async def test_set_rooms_moves_what_is_heard(started, service, rooms):+ x, y = rooms+ recorder = Recorder()+ subscription = started.subscribe_rooms(+ _tenant(), [x], recorder.on_change, recorder.on_resync+ )+ subscription.set_rooms([y])++ await _report(service, "in-x", x)+ await _report(service, "in-y", y)++ await recorder.expect([("activity", "in-y")])+++async def test_the_same_room_in_another_tenant_never_crosses(+ started, service, session_factory, rooms+):+ x, _ = rooms+ recorder = Recorder()+ started.subscribe_rooms(_tenant(), [x], recorder.on_change, recorder.on_resync)+ elsewhere = {+ "tenant_id": "another-tenant",+ "agent_id": AGENT,+ "session_id": SESSION,+ "room_id": x,+ "key": "elsewhere",+ }+ async with session_factory() as db, db.begin():+ await db.execute(+ text("SELECT pg_notify(:channel, :payload)"),+ {+ "channel": SESSION_ACTIVITY_CHANNEL,+ "payload": json.dumps(+ {"table": "session_activity_items", "key": elsewhere}+ ),+ },+ )++ await _report(service, "in-x", x)++ await recorder.expect([("activity", "in-x")])+++async def test_resync_reaches_tenant_and_room_subscribers(listener, rooms):+ x, _ = rooms+ everything, in_x = Recorder(), Recorder()+ listener.subscribe(_tenant(), everything.on_change, everything.on_resync)+ listener.subscribe_rooms(_tenant(), [x], in_x.on_change, in_x.on_resync)+ await _start(listener)+ try:+ await everything.expect([])+ await in_x.expect([])+ finally:+ await listener.stop()+ assert (everything.resyncs, in_x.resyncs) == (1, 1)+++async def test_closing_leaves_nothing_behind(started, service, rooms):+ x, y = rooms+ closed, open_ = Recorder(), Recorder()+ subscription = started.subscribe_rooms(+ _tenant(), [x, y], closed.on_change, closed.on_resync+ )+ other = started.subscribe_rooms(_tenant(), [x], open_.on_change, open_.on_resync)++ subscription.close()+ await _report(service, "in-x", x)+ await open_.expect([("activity", "in-x")])+ await closed.expect([])++ other.close()+ assert started._room_index == {}+ assert started._room_subscribers == {}