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): carry the room in session activity announcements
raullopez-sandbox545b40efa4a9
diff --git a/core/switch_core/db/session_activity_notify_ddl.py b/core/switch_core/db/session_activity_notify_ddl.pyindex 841bc332c..6c4596239 100644--- a/core/switch_core/db/session_activity_notify_ddl.py+++ b/core/switch_core/db/session_activity_notify_ddl.py@@ -10,7 +10,8 @@ capped just under 8000 bytes, so a request too large to fit is announced by keyalone and the subscriber reads that one row.A turn step's announcement carries only the turn it belongs to-(`agent_id`, `session_id`, `turn_id`). Its subscriber, a bridge, redraws the+(`agent_id`, `session_id`, `turn_id`) and its room (`room_id`, null for a step+outside any room). Its subscriber, a bridge, redraws thewhole turn from its rows on every change anyway, and a step's text is toolarge to ride along often enough to be worth the branch.@@ -42,6 +43,7 @@ BEGIN'tenant_id', NEW.tenant_id,'agent_id', NEW.agent_id,'session_id', NEW.session_id,+ 'room_id', NEW.room_id,'key', body->>'turn_id');payload := jsonb_build_object('table', TG_TABLE_NAME, 'key', key)::text;@@ -50,6 +52,7 @@ BEGIN'tenant_id', NEW.tenant_id,'agent_id', NEW.agent_id,'session_id', NEW.session_id,+ 'room_id', NEW.room_id,'key', body->>'request_id');payload := jsonb_build_object('table', TG_TABLE_NAME, 'row', body)::text;diff --git a/core/switch_core/migrations/versions/ddd07a1fcdcb_session_activity_room_in_announcements.py b/core/switch_core/migrations/versions/ddd07a1fcdcb_session_activity_room_in_announcements.pynew file mode 100644index 000000000..042fdd224--- /dev/null+++ b/core/switch_core/migrations/versions/ddd07a1fcdcb_session_activity_room_in_announcements.py@@ -0,0 +1,98 @@+"""Session activity announcements carry the room++A turn step's announcement, and an approval request announced by key because+its row is too large, now name the step's or request's room (`room_id`, null+outside any room), so a subscriber can tell whom the change concerns without+reading the row. Replaces the notify function only.++Revision ID: ddd07a1fcdcb+Revises: c7715ebb95c9+Create Date: 2026-10-19 00:00:00.000000+"""++from alembic import op++revision: str = "ddd07a1fcdcb"+down_revision: str | None = "c7715ebb95c9"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.execute(_NOTIFY_FUNCTION)+++def downgrade() -> None:+ op.execute(_PREVIOUS_NOTIFY_FUNCTION)+++# Frozen copy of `switch_core.db.session_activity_notify_ddl` as of this+# revision; the live module may change later, this migration must not.+_NOTIFY_FUNCTION = """+CREATE OR REPLACE FUNCTION switch_notify_session_activity() RETURNS trigger AS $$+DECLARE+ body jsonb := to_jsonb(NEW);+ key jsonb;+ payload text;+BEGIN+ IF TG_TABLE_NAME = 'session_activity_items' THEN+ key := jsonb_build_object(+ 'tenant_id', NEW.tenant_id,+ 'agent_id', NEW.agent_id,+ 'session_id', NEW.session_id,+ 'room_id', NEW.room_id,+ 'key', body->>'turn_id'+ );+ payload := jsonb_build_object('table', TG_TABLE_NAME, 'key', key)::text;+ ELSE+ key := jsonb_build_object(+ 'tenant_id', NEW.tenant_id,+ 'agent_id', NEW.agent_id,+ 'session_id', NEW.session_id,+ 'room_id', NEW.room_id,+ 'key', body->>'request_id'+ );+ payload := jsonb_build_object('table', TG_TABLE_NAME, 'row', body)::text;+ IF octet_length(payload) > 7500 THEN+ payload := jsonb_build_object('table', TG_TABLE_NAME, 'key', key)::text;+ END IF;+ END IF;+ PERFORM pg_notify('switch_session_activity', payload);+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++# As `c4f7e2a90b13` installed it.+_PREVIOUS_NOTIFY_FUNCTION = """+CREATE OR REPLACE FUNCTION switch_notify_session_activity() RETURNS trigger AS $$+DECLARE+ body jsonb := to_jsonb(NEW);+ key jsonb;+ payload text;+BEGIN+ IF TG_TABLE_NAME = 'session_activity_items' THEN+ key := jsonb_build_object(+ 'tenant_id', NEW.tenant_id,+ 'agent_id', NEW.agent_id,+ 'session_id', NEW.session_id,+ 'key', body->>'turn_id'+ );+ payload := jsonb_build_object('table', TG_TABLE_NAME, 'key', key)::text;+ ELSE+ key := jsonb_build_object(+ 'tenant_id', NEW.tenant_id,+ 'agent_id', NEW.agent_id,+ 'session_id', NEW.session_id,+ 'key', body->>'request_id'+ );+ payload := jsonb_build_object('table', TG_TABLE_NAME, 'row', body)::text;+ IF octet_length(payload) > 7500 THEN+ payload := jsonb_build_object('table', TG_TABLE_NAME, 'key', key)::text;+ END IF;+ END IF;+ PERFORM pg_notify('switch_session_activity', payload);+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""diff --git a/core/switch_core/session_activity/listener.py b/core/switch_core/session_activity/listener.pyindex 1b0f6f06c..9531ba745 100644--- a/core/switch_core/session_activity/listener.py+++ b/core/switch_core/session_activity/listener.py@@ -55,6 +55,8 @@ class Change:session_id: str# The step's `turn_id` or the approval `request_id`.key: str+ # None for a step or request outside any room.+ room_id: str | Nonerow: dict[str, Any] | None@staticmethod@@ -77,12 +79,14 @@ class Change:key = str(fields["request_id"] if row is not None else fields["key"])else:raise ValueError(table)+ room_id = fields["room_id"]return Change(kind=kind,tenant_id=str(fields["tenant_id"]),agent_id=str(fields["agent_id"]),session_id=str(fields["session_id"]),key=key,+ room_id=None if room_id is None else str(room_id),row=row,)except (ValueError, TypeError, KeyError):diff --git a/core/tests/switch_core/gateway/test_chats_routes.py b/core/tests/switch_core/gateway/test_chats_routes.pyindex d4225a40a..cb5403f83 100644--- a/core/tests/switch_core/gateway/test_chats_routes.py+++ b/core/tests/switch_core/gateway/test_chats_routes.py@@ -1609,13 +1609,14 @@ async def _request(await session.commit()-def _turn_change(agent: Agent, turn_id: str) -> Change:+def _turn_change(agent: Agent, room_id: str, turn_id: str) -> Change:return Change(kind="activity",tenant_id="00000000-0000-0000-0000-000000000000",agent_id=agent.id,session_id="s1",key=turn_id,+ room_id=room_id,row=None,)@@ -1703,19 +1704,19 @@ async def test_the_activity_stream_sends_only_readable_rooms_and_moved_steps(assert (await events.next())[0] == "ready"await _step(chats, agent, room_id, "t1", "turn", 1)- await chats.activity.change(_turn_change(agent, "t1"))+ await chats.activity.change(_turn_change(agent, room_id, "t1"))name, item = await events.next()assert name == "activity" and item["roomId"] == room_id and item["revision"] == 1# A reread of the turn resends only the step that moved.await _step(chats, agent, room_id, "t1", "tool-1", 1)- await chats.activity.change(_turn_change(agent, "t1"))+ await chats.activity.change(_turn_change(agent, room_id, "t1"))name, item = await events.next()assert (name, item["itemId"]) == ("activity", "tool-1")# A room the reader is not in is never sent: the next frame is the request.await _step(chats, other_agent, hidden, "t2", "turn", 1)- await chats.activity.change(_turn_change(other_agent, "t2"))+ await chats.activity.change(_turn_change(other_agent, hidden, "t2"))await _request(chats, agent, room_id, "r1", "answered")await chats.activity.change(Change(@@ -1724,6 +1725,7 @@ async def test_the_activity_stream_sends_only_readable_rooms_and_moved_steps(agent_id=agent.id,session_id="s1",key="r1",+ room_id=room_id,row=None,))@@ -1739,7 +1741,7 @@ async def test_the_activity_stream_sends_only_readable_rooms_and_moved_steps()assert removed.status_code == 204await _step(chats, agent, room_id, "t1", "turn", 2)- await chats.activity.change(_turn_change(agent, "t1"))+ await chats.activity.change(_turn_change(agent, room_id, "t1"))with pytest.raises(TimeoutError):await events.next(timeout=0.3)await events.stream.aclose() # type: ignore[attr-defined]@@ -1761,7 +1763,7 @@ async def test_the_activity_stream_says_resync_when_changes_may_be_lost(# Falling behind drops what was queued and asks for a reload instead.for _ in range(3):- await chats.activity.change(_turn_change(agent, "t1"))+ await chats.activity.change(_turn_change(agent, room_id, "t1"))assert await events.next() == ("resync", {})with pytest.raises(TimeoutError):await events.next(timeout=0.3)@@ -1790,7 +1792,7 @@ async def test_the_activity_stream_ends_when_the_tenant_role_is_gone(await _drop_tenant_role(chats, chats.bob)await _step(chats, agent, room_id, "t1", "turn", 1)- await chats.activity.change(_turn_change(agent, "t1"))+ await chats.activity.change(_turn_change(agent, room_id, "t1"))with pytest.raises(StopAsyncIteration):await on_change.next()with pytest.raises(StopAsyncIteration):@@ -1809,11 +1811,11 @@ async def test_the_activity_stream_forgets_revisions_past_its_cap(await _step(chats, agent, room_id, "t1", "turn", 1)await _step(chats, agent, room_id, "t1", "tool-1", 1)- await chats.activity.change(_turn_change(agent, "t1"))+ await chats.activity.change(_turn_change(agent, room_id, "t1"))assert [(await events.next())[1]["itemId"] for _ in range(2)] == ["turn", "tool-1"]# Over the cap, the next reread starts from nothing and resends the turn.- await chats.activity.change(_turn_change(agent, "t1"))+ await chats.activity.change(_turn_change(agent, room_id, "t1"))assert [(await events.next())[1]["itemId"] for _ in range(2)] == ["turn", "tool-1"]await events.stream.aclose() # type: ignore[attr-defined]diff --git a/core/tests/switch_core/session_activity/test_service.py b/core/tests/switch_core/session_activity/test_service.pyindex 7085888b7..85a930684 100644--- a/core/tests/switch_core/session_activity/test_service.py+++ b/core/tests/switch_core/session_activity/test_service.py@@ -118,6 +118,17 @@ async def test_a_step_is_upserted_by_revision_and_announced_by_turn(service, chaassert (step.revision, step.status, step.text) == (2, "completed", "done")announced = await changes.expect([("activity", "turn-1"), ("activity", "turn-1")])assert all(change.row is None for change in announced)+ assert all(change.room_id is None for change in announced)+++async def test_a_step_in_a_room_is_announced_with_its_room(+ service, session_factory, changes+):+ async with session_factory() as db, db.begin():+ room = await make_room(db, member=AGENT)+ await service.report_item(AGENT, SESSION, **_step(room_id=room))+ [change] = await changes.expect([("activity", "turn-1")])+ assert change.room_id == roomdef _turn(turn_id: str, revision: int, status: str, usage=()):@@ -588,11 +599,19 @@ async def test_a_refused_answerer_leaves_the_request_open(service, people, changassert await service.undelivered_outcomes(AGENT) == []-async def test_a_row_too_large_to_announce_is_announced_by_key(service, changes):- await _open(service, detail="é" * 3990)+async def test_a_row_too_large_to_announce_is_announced_by_key(+ service, session_factory, changes+):+ async with session_factory() as db, db.begin():+ room = await make_room(db, member=AGENT)+ await _open(service, detail="é" * 3990, room_id=room)[change] = await changes.expect([("approval.changed", "req-1")])assert change.row is None- assert (change.agent_id, change.session_id) == (AGENT, SESSION)+ assert (change.agent_id, change.session_id, change.room_id) == (+ AGENT,+ SESSION,+ room,+ )async def test_a_signed_in_owner_may_answer_outside_a_room(service, session_factory):diff --git a/core/tests/switch_core/test_migration_session_activity_room_in_announcements.py b/core/tests/switch_core/test_migration_session_activity_room_in_announcements.pynew file mode 100644index 000000000..6f97478d4--- /dev/null+++ b/core/tests/switch_core/test_migration_session_activity_room_in_announcements.py@@ -0,0 +1,126 @@+"""`ddd07a1fcdcb` puts the room in the session-activity announcements that+carry a key instead of a row: a turn step's, and an approval request's too+large to ride along."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from typing import Any++import pytest+from alembic.config import Config+from alembic.runtime.environment import EnvironmentContext+from alembic.script import ScriptDirectory+from sqlalchemy import Connection, text+from sqlalchemy.ext.asyncio import create_async_engine++from switch_core.db.session_activity_notify_ddl import SESSION_ACTIVITY_CHANNEL++_CORE = Path(__file__).resolve().parents[2]+_DB = "migration_session_activity_room_in_announcements"++_MIGRATION_UNDER_TEST = "ddd07a1fcdcb"+++def _script_directory(config: Config) -> ScriptDirectory:+ config.set_main_option("script_location", str(_CORE / "switch_core" / "migrations"))+ return ScriptDirectory.from_config(config)+++def _upgrade_to(revision: str) -> Any:+ def upgrade(connection: Connection) -> None:+ config = Config(str(_CORE / "alembic.ini"))+ script = _script_directory(config)++ def do_upgrade(current_revision: str, context: Any) -> Any:+ return script._upgrade_revs(revision, current_revision)++ with EnvironmentContext(config, script, fn=do_upgrade) as environment:+ environment.configure(connection=connection)+ with environment.begin_transaction():+ environment.run_migrations()++ return upgrade+++async def database_url(postgres_url: str) -> Any:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_DB}"'))+ await connection.execute(text(f'CREATE DATABASE "{_DB}"'))+ await admin.dispose()++ base, _, _ = postgres_url.rpartition("/")+ try:+ yield f"{base}/{_DB}"+ finally:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_DB}"'))+ await admin.dispose()+++async def test_key_announcements_carry_the_room(database_url: str) -> None:+ engine = create_async_engine(database_url)+ payloads: asyncio.Queue[str] = asyncio.Queue()+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_MIGRATION_UNDER_TEST))++ async with engine.connect() as listening:+ raw = await listening.get_raw_connection()+ await raw.driver_connection.add_listener(+ SESSION_ACTIVITY_CHANNEL, lambda *args: payloads.put_nowait(args[3])+ )+ async with engine.begin() as connection:+ # Foreign keys are beside the point; the triggers are the point.+ await connection.execute(+ text("SET LOCAL session_replication_role = replica")+ )+ await connection.execute(+ text(+ "ALTER TABLE session_activity_items "+ "ENABLE ALWAYS TRIGGER session_activity_items_notify"+ )+ )+ await connection.execute(+ text(+ "ALTER TABLE approval_requests "+ "ENABLE ALWAYS TRIGGER approval_requests_notify_insert"+ )+ )+ await connection.execute(+ text(+ """+ INSERT INTO session_activity_items+ (tenant_id, agent_id, session_id, turn_id, item_id,+ kind, revision, status, title, text, room_id,+ occurred_at)+ VALUES ('t', 'a', 's', 'turn', 'turn', 'turn', 1,+ 'running', '', '', 'room-1', now())+ """+ )+ )+ await connection.execute(+ text(+ """+ INSERT INTO approval_requests+ (tenant_id, agent_id, session_id, request_id, turn_id,+ kind, title, detail, options, questions, state,+ room_id)+ VALUES ('t', 'a', 's', 'r', 'turn', 'approval', 'Deploy?',+ repeat('x', 8000), '[]', '[]', 'open', 'room-1')+ """+ )+ )+ step = json.loads(await asyncio.wait_for(payloads.get(), 5))+ request = json.loads(await asyncio.wait_for(payloads.get(), 5))+ finally:+ await engine.dispose()++ assert step["key"]["room_id"] == "room-1"+ assert "row" not in request+ assert request["key"]["room_id"] == "room-1"