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(chats): group chats in Switch Console
raullopez-sandboxbc47536aeae5
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex 8d54716d6..b44e022a0 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -37,6 +37,7 @@ from sqlalchemy import (exists,false,func,+ or_,select,update,)@@ -579,7 +580,8 @@ class ChatService:return list(result.scalars().all())async def stream_rooms(self, session: AsyncSession, user_id: str) -> list[Room]:- """The caller's member rooms that are chats: unarchived, with an agent."""+ """The caller's member rooms that are chats: unarchived, and either+ holding an agent or started in Switch Console (which may have none)."""client = await self.member_client(session, user_id)if client is None:return []@@ -589,7 +591,10 @@ class ChatService:.where(ClientRoom.client_id == client.id,Room.archived_at.is_(None),- exists().where(room_agents.c.room_id == Room.id),+ or_(+ exists().where(room_agents.c.room_id == Room.id),+ Room.metadata_.has_key("chat_operation_id"),+ ),).order_by(Room.created_at))@@ -668,9 +673,19 @@ class ChatService:) -> tuple[list[Message], int, bool]:"""Messages before `before_seq` (newest first, returned oldest first),the room's head position, and whether older messages remain."""- query = select(Message).where(- Message.room_id == room_id, Message.event_type.in_(SHOWN_EVENT_TYPES)+ return await self._paged(+ session, room_id, Message.room_id == room_id, before_seq, limit)++ async def _paged(+ self,+ session: AsyncSession,+ room_id: str,+ where: ColumnElement[bool],+ before_seq: int | None,+ limit: int,+ ) -> tuple[list[Message], int, bool]:+ query = select(Message).where(where, Message.event_type.in_(SHOWN_EVENT_TYPES))if before_seq is not None:query = query.where(Message.seq < before_seq)rows = list(@@ -683,6 +698,32 @@ class ChatService:rows.reverse()return rows, await self._message_store.head_seq(session, room_id), has_more+ async def thread_page(+ self,+ session: AsyncSession,+ room: Room,+ root_id: str,+ before_seq: int | None,+ limit: int,+ ) -> tuple[list[Message], int, bool]:+ """`page` for the replies in one thread of this room, the root not+ among them. A reply's id names its thread's root."""+ found = await self._message_store.list_by_transport_event_ids(+ session, room.id, [root_id]+ )+ if not found:+ raise ChatError(+ 404, "THREAD_NOT_FOUND", "That message is not in this chat."+ )+ root = found[0].thread_root_event_id or found[0].transport_event_id+ return await self._paged(+ session,+ room.id,+ and_(Message.room_id == room.id, Message.thread_root_event_id == root),+ before_seq,+ limit,+ )+async def head_seq(self, session: AsyncSession, room_id: str) -> int:return await self._message_store.head_seq(session, room_id)@@ -735,25 +776,55 @@ class ChatService:room.transport_room_id, client.transport_user_id)+ async def _require_tenant_member(+ self, session: AsyncSession, tenant_id: str, user_id: str+ ) -> User:+ user = await self._user_store.get(session, user_id)+ if user is None or not await self.has_tenant_role(session, tenant_id, user_id):+ raise ChatError(+ 422,+ "NOT_A_TENANT_MEMBER",+ "That person is not a member of this workspace.",+ )+ return user++ async def _make_group(self, session: AsyncSession, room: Room) -> None:+ """Turn a Switch Console direct chat into a group, for good.++ Committed before the person or agent is added, so no message routes+ as direct once the room has them. A bridged room's type is its+ platform's and is never touched.+ """+ if room.channel_type != "direct" or "chat_operation_id" not in (+ room.metadata_ or {}+ ):+ return+ await session.execute(+ update(Room)+ .where(Room.id == room.id, Room.channel_type == "direct")+ .values(channel_type="channel_private")+ )+ room.channel_type = "channel_private"+async def add_member(self, tenant_id: str, actor: User, room_id: str, target_user_id: str) -> Room:async with tenant_session(self.session_factory, tenant_id) as session:room = await self._room(session, tenant_id, room_id)await self._require_manager(session, tenant_id, actor, room)- target = await self._user_store.get(session, target_user_id)- if target is None or not await self.has_tenant_role(+ target = await self._require_tenant_member(session, tenant_id, target_user_id- ):- raise ChatError(- 422,- "NOT_A_TENANT_MEMBER",- "That person is not a member of this workspace.",- )+ )+ # The creator is the direct chat's own person; anyone else makes a group.+ if target_user_id not in (room.created_by, room.owner_id):+ await self._make_group(session, room)+ await session.commit()client = await self.member_actor(tenant_id, target)await self._join(tenant_id, room, client)await self._make_lasting(tenant_id, target_user_id, room.id)- self._memberships_changed(tenant_id, [target_user_id])+ async with tenant_session(self.session_factory, tenant_id) as session:+ member_ids = [member.id for member, _ in await self.members(session, room)]+ self._memberships_changed(tenant_id, member_ids)return roomasync def remove_member(@@ -794,6 +865,47 @@ class ChatService:await self._make_lasting(tenant_id, target_user_id, room.id)self._memberships_changed(tenant_id, [target_user_id])+ async def add_agent(+ self, tenant_id: str, actor: User, room_id: str, agent_id: str+ ) -> Room:+ """Manager only, and only an agent the manager may use in this room.+ Already in is success. A second agent makes a direct chat a group."""+ async with self._lock("agents", tenant_id, room_id):+ async with tenant_session(self.session_factory, tenant_id) as session:+ room = await self._room(session, tenant_id, room_id)+ await self._require_manager(session, tenant_id, actor, room)+ await self._require_may_use_agent(+ session,+ tenant_id,+ actor,+ agent_id,+ room_id=room.id,+ group_id=room.group_id,+ )+ present = await self._room_store.get_agent_ids(session, room.id)+ if agent_id in present:+ return room+ if present:+ await self._make_group(session, room)+ await session.commit()+ await self._room_service.add_agents_to_room(room.id, agent_ids=[agent_id])+ return room++ async def remove_agent(+ self, tenant_id: str, actor: User, room_id: str, agent_id: str+ ) -> None:+ """Manager only, with no check on using the agent, so an unwanted+ agent can always be taken out. Already gone is success."""+ async with self._lock("agents", tenant_id, room_id):+ async with tenant_session(self.session_factory, tenant_id) as session:+ room = await self._room(session, tenant_id, room_id)+ await self._require_manager(session, tenant_id, actor, room)+ if agent_id not in await self._room_store.get_agent_ids(+ session, room.id+ ):+ return+ await self._room_service.remove_agents_from_room(room.id, [agent_id])+async def archive(self, tenant_id: str, user: User, room_id: str) -> None:async with tenant_session(self.session_factory, tenant_id) as session:room, _ = await self.require_member(session, tenant_id, user, room_id)@@ -884,27 +996,35 @@ class ChatService:return claimed is not Noneasync def _require_may_use_agent(- self, session: AsyncSession, tenant_id: str, user: User, agent_id: str+ self,+ session: AsyncSession,+ tenant_id: str,+ user: User,+ agent_id: str,+ *,+ room_id: str,+ group_id: str | None,) -> Agent:- """The agent, if the user may address it themselves.+ """The agent, if the user may address it themselves in `room_id`.- The rule the platform applies when it speaks for a person, asked- before the room exists: a rule naming particular rooms admits nobody- into a new one, and no claimed platform account is consulted.+ The rule the platform applies when it speaks for a person. Asked+ before a new room exists, `room_id` is "": a rule naming particular+ rooms admits nobody into a new one. No claimed platform account is+ consulted."""agent = await self._agent_store.get(session, agent_id)if agent is None or agent.tenant_id != tenant_id:raise ChatError(404, "AGENT_NOT_FOUND", "Agent not found.")if not allows_on_behalf_of(parse_policy(agent.addressing_policy),- room_id="",- group_id=None,+ room_id=room_id,+ group_id=group_id,user_id=user.id,external_user_ids=[],owner_user_id=agent.owner_id,):raise ChatError(- 403, "AGENT_NOT_ALLOWED", "You may not start a chat with this agent."+ 403, "AGENT_NOT_ALLOWED", "You may not chat with this agent here.")return agent@@ -917,15 +1037,18 @@ class ChatService:user: User,*,agent_ids: list[str],+ member_user_ids: list[str],name: str | None,request_id: str,greeting: str | None,) -> Room:- """A private room with the agents, owned by and joined by the user.+ """A private room with the agents and members, owned by and joined by+ the user.- One agent makes a direct room, which addresses it without a mention.- Several make a private channel, where a message names the agent it is- for. Every agent must be one the user may address.+ One agent and no other member makes a direct room, which addresses+ the agent without a mention. Anything else is a group (a private+ channel), where a message names the agents it is for. Every agent must+ be one the user may address; every member a member of the workspace.Retrying with the same request id finishes whatever an earlier attemptleft undone: the room is found by the operation id stamped on it, and@@ -935,8 +1058,8 @@ class ChatService:one-liner: its first words, written for it (switch-buddy's welcome).Only for a direct chat with one of the user's own agents."""- if not agent_ids:- raise ChatError(422, "AGENTS_REQUIRED", "A chat needs at least one agent.")+ member_user_ids = sorted(set(member_user_ids) - {user.id})+ direct = len(agent_ids) == 1 and not member_user_idsif greeting is not None:if len(agent_ids) != 1:raise ChatError(@@ -952,13 +1075,16 @@ class ChatService:"GREETING_TOO_LONG",f"A greeting is at most {GREETING_MAX_CHARS} characters.",)- payload_hash = _hash(+ request: dict[str, object] = ({"agentId": agent_ids[0], "name": name}if len(agent_ids) == 1 and greeting is Noneelse {"agentId": agent_ids[0], "name": name, "greeting": greeting}if len(agent_ids) == 1else {"agentIds": agent_ids, "name": name})+ if member_user_ids:+ request["memberUserIds"] = member_user_ids+ payload_hash = _hash(request)async with self._lock("create", tenant_id, user.id):async with tenant_session(self.session_factory, tenant_id) as session:operation = await self._operation(session, user.id, request_id)@@ -971,10 +1097,14 @@ class ChatService:return roomagents = [await self._require_may_use_agent(- session, tenant_id, user, agent_id+ session, tenant_id, user, agent_id, room_id="", group_id=None)for agent_id in agent_ids]+ members = [+ await self._require_tenant_member(session, tenant_id, member_id)+ for member_id in member_user_ids+ ]if greeting is not None and agents[0].owner_id != user.id:raise ChatError(403,@@ -1007,11 +1137,12 @@ class ChatService:RoomCreateConfig(name=name or "New Chat",description="Switch Console chat with "- + ", ".join(agent.name for agent in agents),- agent_ids=[agent.id for agent in agents],- channel_type=(- "direct" if len(agents) == 1 else "channel_private"+ + ", ".join(+ [agent.name for agent in agents]+ + [member.name for member in members]),+ agent_ids=[agent.id for agent in agents],+ channel_type="direct" if direct else "channel_private",internal_only=True,created_by=user.id,owner_id=user.id,@@ -1033,9 +1164,10 @@ class ChatService:else:room = foundawait self._room_service.reconcile_room(room)- client = await self.member_actor(tenant_id, user)- await self._join(tenant_id, room, client)- await self._make_lasting(tenant_id, user.id, room.id)+ for joiner in [user, *members]:+ client = await self.member_actor(tenant_id, joiner)+ await self._join(tenant_id, room, client)+ await self._make_lasting(tenant_id, joiner.id, room.id)async with tenant_session(self.session_factory, tenant_id) as session:await session.execute(update(ChatOperation)@@ -1047,7 +1179,7 @@ class ChatService:.values(state="done", room_id=room.id, result={"roomId": room.id}))await session.commit()- self._memberships_changed(tenant_id, [user.id])+ self._memberships_changed(tenant_id, [user.id, *member_user_ids])if len(agents) == 1:self._start_session(agents[0].id, room.id)return room@@ -1134,6 +1266,7 @@ class ChatService:thread_root_id: str | None,upload_ids: list[str],mention_agent_id: str | None,+ mention_agent_ids: list[str],) -> tuple[Room, list[Message]]:"""Post the user's message, every part of it in one transaction.@@ -1141,16 +1274,23 @@ class ChatService:writing rows: each part, and the operation marked done, committogether or not at all. A retry after a failure before the commitposts it once; one after the commit answers the parts already posted.++ The agents the message is for are `mention_agent_ids` together with+ `mention_agent_id`, the one earlier clients send, as a set."""- payload_hash = _hash(- {- "roomId": room_id,- "body": body,- "threadRootId": thread_root_id,- "uploadIds": upload_ids,- "mentionAgentId": mention_agent_id,- }- )+ mentions = sorted(set(mention_agent_ids))+ request: dict[str, object] = {+ "roomId": room_id,+ "body": body,+ "threadRootId": thread_root_id,+ "uploadIds": upload_ids,+ "mentionAgentId": mention_agent_id,+ }+ if mentions:+ request["mentionAgentIds"] = mentions+ payload_hash = _hash(request)+ if mention_agent_id is not None:+ mentions = sorted({*mentions, mention_agent_id})async with tenant_session(self.session_factory, tenant_id) as session:room, client = await self.require_member(session, tenant_id, user, room_id)operation = await self._operation(session, user.id, request_id)@@ -1165,8 +1305,8 @@ class ChatService:for upload_id in upload_ids]root = await self._thread_root(session, room, thread_root_id)- if mention_agent_id is not None:- body = await self._with_mention(session, room, mention_agent_id, body)+ if mentions:+ body = await self._with_mentions(session, room, mentions, body)if not await self._claim(session,@@ -1420,16 +1560,28 @@ class ChatService:)return found[0].thread_root_event_id or found[0].transport_event_id- async def _with_mention(- self, session: AsyncSession, room: Room, agent_id: str, body: str+ async def _with_mentions(+ self, session: AsyncSession, room: Room, agent_ids: list[str], body: str) -> str:- if agent_id not in await self._room_store.get_agent_ids(session, room.id):+ """`body` led by an `@name` for each agent it does not already name by+ name or room alias, so every agent decides it was addressed by the+ same rule a typed mention meets."""+ in_room = set(await self._room_store.get_agent_ids(session, room.id))+ if any(agent_id not in in_room for agent_id in agent_ids):raise ChatError(422, "AGENT_NOT_IN_CHAT", "That agent is not in this chat.")- agent = await self._agent_store.get(session, agent_id)- assert agent is not None- if mention_regex(agent.name).search(strip_emphasis(body)) is not None:+ aliases = await self._room_store.list_aliases(session, room.id)+ text = strip_emphasis(body)+ missing: list[str] = []+ for agent_id in agent_ids:+ agent = await self._agent_store.get(session, agent_id)+ assert agent is not None+ spoken = [agent.name, *([aliases[agent_id]] if agent_id in aliases else [])]+ if all(mention_regex(name).search(text) is None for name in spoken):+ missing.append(agent.name)+ prefix = " ".join(f"@{name}" for name in sorted(missing))+ if not prefix:return body- return f"@{agent.name} {body}" if body else f"@{agent.name}"+ return f"{prefix} {body}" if body else prefixdef _owns_agent_in_room(user_id: str) -> ColumnElement[bool]:diff --git a/core/switch_core/chats/views.py b/core/switch_core/chats/views.pyindex afd6e83f3..01862ed48 100644--- a/core/switch_core/chats/views.py+++ b/core/switch_core/chats/views.py@@ -11,7 +11,7 @@ from datetime import datetimefrom pydantic import BaseModel, ConfigDictfrom pydantic.alias_generators import to_camel-from sqlalchemy import select+from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.chats import MEMBER_CLIENT_TYPE@@ -22,9 +22,11 @@ from switch_core.db.models import (CollaborationBridge,Message,Room,+ User,room_agents,)from switch_core.db.stores.message_store import MessageStore+from switch_core.delivery.addressing import named_agentsMESSAGE_EVENT_TYPE = "m.room.message"COMMAND_EVENT_TYPE = "com.switch.command"@@ -62,6 +64,10 @@ class ChatAgent(CamelModel):display_name: str | Noneicon_url: str | Noneprovider: str | None+ # The name the agent also answers to in this room, if any.+ alias: str | None+ owner_name: str | None+ owned_by_viewer: boolclass ChatLastMessage(CamelModel):@@ -112,6 +118,12 @@ class ChatMessage(CamelModel):thread_root_id: str | Noneattachments: list[ChatAttachment]client_txn: str | None+ # The room's agents the body names by @name or @alias. Display only: who+ # a message addresses is each agent's own decision.+ named_agent_ids: list[str]+ # Of a thread's root; 0 and None on a reply and on a message with none.+ thread_reply_count: int+ thread_last_reply_seq: int | Noneclass ChatMember(CamelModel):@@ -133,15 +145,16 @@ async def _bridge(session: AsyncSession, room: Room) -> CollaborationBridge | Noasync def chat_summary(session: AsyncSession, room: Room, *, viewer_id: str, can_manage: bool) -> ChatSummary:- agent_rows = (+ rows = (await session.execute(- select(Agent)+ select(Agent, room_agents.c.alias, User.name).join(room_agents, room_agents.c.agent_id == Agent.id)+ .outerjoin(User, User.id == Agent.owner_id).where(room_agents.c.room_id == room.id).order_by(Agent.name))- ).scalars()- agents = list(agent_rows)+ ).all()+ agents = [agent for agent, _alias, _owner in rows]providers = {definition.agent_id: definition.definition.get("provider")for definition in (@@ -182,8 +195,11 @@ async def chat_summary(display_name=agent.display_name,icon_url=agent.icon_url,provider=_provider(agent, providers.get(agent.id)),+ alias=alias,+ owner_name=owner_name,+ owned_by_viewer=agent.owner_id == viewer_id,)- for agent in agents+ for agent, alias, owner_name in rows],can_manage=can_manage,owns_agent=any(agent.owner_id == viewer_id for agent in agents),@@ -231,6 +247,29 @@ async def chat_messages(}bridge = await _bridge(session, room)attachments = await _MESSAGE_STORE.attachments_for(session, [m.id for m in shown])+ names: dict[str, str] = {}+ aliases: dict[str, str] = {}+ for agent_id, name, alias in await session.execute(+ select(Agent.id, Agent.name, room_agents.c.alias)+ .join(room_agents, room_agents.c.agent_id == Agent.id)+ .where(room_agents.c.room_id == room.id)+ ):+ names[agent_id] = name+ if alias:+ aliases[agent_id] = alias+ roots = [m.transport_event_id for m in shown if m.thread_root_event_id is None]+ threads: dict[str, tuple[int, int]] = {}+ if roots:+ for root, count, last in await session.execute(+ select(Message.thread_root_event_id, func.count(), func.max(Message.seq))+ .where(+ Message.room_id == room.id,+ Message.thread_root_event_id.in_(roots),+ Message.event_type.in_(SHOWN_EVENT_TYPES),+ )+ .group_by(Message.thread_root_event_id)+ ):+ threads[root] = (count, last)out: list[ChatMessage] = []for message in shown:client = clients.get(message.sender_client_id or "")@@ -244,6 +283,7 @@ async def chat_messages(else:kind, source = "system", "switch"format_ = message.content.get("format")+ thread = threads.get(message.transport_event_id)out.append(ChatMessage(message_id=message.transport_event_id,@@ -273,6 +313,9 @@ async def chat_messages(for attachment in attachments.get(message.id, [])],client_txn=message.client_txn_id,+ named_agent_ids=named_agents(names, aliases, message.body or ""),+ thread_reply_count=thread[0] if thread is not None else 0,+ thread_last_reply_seq=thread[1] if thread is not None else None,))return outdiff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.pyindex 83dca8980..46d722247 100644--- a/core/switch_core/gateway/chats.py+++ b/core/switch_core/gateway/chats.py@@ -1,7 +1,8 @@"""`/chats`: Switch Console's view of the rooms a person is a member of.Every route except creating a chat requires the caller's membership of the-room (`ChatService.require_member`); adding a member requires managing it.+room (`ChatService.require_member`); adding a member or adding or removing+an agent requires managing it.With `agent_chats` on, owning an agent in a chat one started keeps one amember of it (`sync_owned_rooms`), so the list, the event stream and the roomroutes bring that up to date first.@@ -91,11 +92,13 @@ class ChatEnvelope(CamelModel):class CreateChatRequest(CamelModel):- """`agentIds` names the chat's agents; `agentId` is the one-agent form- earlier clients send. Exactly one of the two is given."""+ """`agentIds` names the chat's agents, none or more; `agentId` is the+ one-agent form earlier clients send. Exactly one of the two is given.+ `memberUserIds` are the other people to add."""agent_id: str | None = Noneagent_ids: list[str] | None = None+ member_user_ids: list[str] = []name: str | None = Nonerequest_id: str# What the agent says as it joins, instead of its usual line; older@@ -125,6 +128,7 @@ class SendRequest(CamelModel):thread_root_id: str | None = Noneupload_ids: list[str] = []mention_agent_id: str | None = None+ mention_agent_ids: list[str] = []class ControlRequest(CamelModel):@@ -160,6 +164,10 @@ class AddMemberRequest(CamelModel):user_id: str+class AddAgentRequest(CamelModel):+ agent_id: str++class ActivityItemView(CamelModel):"""One step of a turn; `revision` only grows, so a lower one is stale."""@@ -258,6 +266,7 @@ async def create_chat(tenant_id,user,agent_ids=req.chosen_agents(),+ member_user_ids=req.member_user_ids,name=req.name,request_id=req.request_id,greeting=req.greeting,@@ -342,6 +351,29 @@ async def list_messages()[email protected]("/{room_id}/threads/{root_id}/messages", response_model=MessagePage)+async def list_thread_messages(+ room_id: str,+ root_id: str,+ user: CurrentUser,+ service: Service,+ before_seq: Annotated[int | None, Query(alias="beforeSeq")] = None,+ limit: Annotated[int, Query(ge=1, le=MAX_PAGE)] = 50,+) -> MessagePage:+ """The thread's replies, paged like `/messages`; the root is not one."""+ tenant_id = require_tenant_id()+ async with tenant_session(service.session_factory, tenant_id) as session:+ room, _ = await service.require_member(session, tenant_id, user, room_id)+ rows, head_seq, has_more = await service.thread_page(+ session, room, root_id, before_seq, limit+ )+ return MessagePage(+ messages=await chat_messages(session, room, rows),+ head_seq=head_seq,+ has_more=has_more,+ )++@router.post("/{room_id}/attachments", response_model=StagedUploadResponse)async def upload_attachment(room_id: str,@@ -383,6 +415,7 @@ async def send_message(thread_root_id=req.thread_root_id,upload_ids=req.upload_ids,mention_agent_id=req.mention_agent_id,+ mention_agent_ids=req.mention_agent_ids,)async with tenant_session(service.session_factory, tenant_id) as session:return SentMessages(messages=await chat_messages(session, room, posted))@@ -461,6 +494,27 @@ async def remove_member(return Response(status_code=204)[email protected]("/{room_id}/agents", response_model=ChatEnvelope)+async def add_agent(+ room_id: str, req: AddAgentRequest, user: CurrentUser, service: Service+) -> ChatEnvelope:+ """Manager only, and only an agent the manager may use in this room."""+ tenant_id = require_tenant_id()+ room = await service.add_agent(tenant_id, user, room_id, req.agent_id)+ async with tenant_session(service.session_factory, tenant_id) as session:+ return ChatEnvelope(+ chat=await _summary(service, session, tenant_id, user, room)+ )++[email protected]("/{room_id}/agents/{agent_id}", status_code=204)+async def remove_agent(+ room_id: str, agent_id: str, user: CurrentUser, service: Service+) -> Response:+ await service.remove_agent(require_tenant_id(), user, room_id, agent_id)+ return Response(status_code=204)++@router.put("/{room_id}/hidden", status_code=204)async def hide_chat(room_id: str, user: CurrentUser, service: Service) -> Response:await service.set_hidden(require_tenant_id(), user, room_id, True)diff --git a/core/switch_core/migrations/versions/d4e8a1c5b7f3_console_direct_chats_with_people_are_groups.py b/core/switch_core/migrations/versions/d4e8a1c5b7f3_console_direct_chats_with_people_are_groups.pynew file mode 100644index 000000000..0d3e14b3e--- /dev/null+++ b/core/switch_core/migrations/versions/d4e8a1c5b7f3_console_direct_chats_with_people_are_groups.py@@ -0,0 +1,50 @@+"""console direct chats that already have another person are groups++A Switch Console chat becomes a group (`channel_private`) once a person other+than its creator is added to it, and a group never addresses its agent without+a mention. Chats that gained such a person before that rule existed are still+`direct`; this converts them. A member held only by an owner grant (the+agent's owner, kept in while the agent is) does not count. Data only, and+one way: the downgrade cannot tell these rooms from groups made since.++Revision ID: d4e8a1c5b7f3+Revises: c7715ebb95c9+Create Date: 2026-10-21 00:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "d4e8a1c5b7f3"+down_revision: str | Sequence[str] | None = "c7715ebb95c9"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.execute(+ """+ UPDATE rooms SET channel_type = 'channel_private'+ WHERE channel_type = 'direct'+ AND metadata ? 'chat_operation_id'+ AND EXISTS (+ SELECT 1 FROM client_rooms cr+ JOIN clients c ON c.id = cr.client_id+ WHERE cr.room_id = rooms.id+ AND c.type = 'member'+ AND c.user_id IS NOT NULL+ AND c.user_id IS DISTINCT FROM rooms.created_by+ AND c.user_id IS DISTINCT FROM rooms.owner_id+ AND NOT EXISTS (+ SELECT 1 FROM chat_owner_grants g+ WHERE g.room_id = rooms.id AND g.user_id = c.user_id+ )+ )+ """+ )+++def downgrade() -> None:+ passdiff --git a/core/tests/switch_core/delivery/test_system_message_never_addresses.py b/core/tests/switch_core/delivery/test_system_message_never_addresses.pyindex 3ab391bbe..17f61cd35 100644--- a/core/tests/switch_core/delivery/test_system_message_never_addresses.py+++ b/core/tests/switch_core/delivery/test_system_message_never_addresses.py@@ -66,6 +66,7 @@ def _client(name: str = "flintai-sdk.ts") -> SimpleNamespace:resolver.addressed_without_lookup = lambda **kw: (AddressingResolver.addressed_without_lookup(resolver, **kw))+async def _one_agent_direct_room(_session: object, *, room_id: str, channel_type: str | None) -> bool:diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.pynew file mode 100644index 000000000..c5d6e9138--- /dev/null+++ b/core/tests/switch_core/gateway/test_chats_groups.py@@ -0,0 +1,456 @@+"""`/chats` group chats: a direct chat turning into a group, creating a chat+with people, adding and removing agents, naming several agents, and reading+a thread — against real Postgres, through the shared harness."""++from __future__ import annotations++import asyncio++import httpx+from sqlalchemy import select++from switch_core.db.models import Agent, Room, room_agents+from tests.switch_core.gateway.conftest import _Harness+from tests.switch_core.gateway.test_chats_routes import (+ _code,+ _events_of,+ _left_chat,+ _listed,+ _reads,+)+++async def _channel_type(chats: _Harness, room_id: str) -> str | None:+ async with chats.factory() as session:+ room = await session.get(Room, room_id)+ assert room is not None+ return room.channel_type+++async def _agent_ids(chats: _Harness, room_id: str) -> set[str]:+ async with chats.factory() as session:+ return set(+ (+ await session.execute(+ select(room_agents.c.agent_id).where(+ room_agents.c.room_id == room_id+ )+ )+ ).scalars()+ )+++async def _set_policy(chats: _Harness, agent: Agent, policy: dict) -> None:+ async with chats.factory() as session:+ row = await session.get(Agent, agent.id)+ assert row is not None+ row.addressing_policy = policy+ await session.commit()+++async def _add_agent(+ chats: _Harness, manager_id: str, room_id: str, agent: Agent+) -> httpx.Response:+ return await chats.client.post(+ f"/chats/{room_id}/agents",+ json={"agentId": agent.id},+ headers={"x-user": manager_id},+ )+++async def _addressed(chats: _Harness, room_id: str, agent: Agent, body: str) -> bool:+ sent = await chats.send(chats.alice, room_id, body, body)+ assert sent.status_code == 200, sent.text+ seq = sent.json()["messages"][0]["seq"]+ return (room_id, seq) in await _events_of(chats, agent)+++# ── Direct becomes group ─────────────────────────────────────────────────────+++async def test_adding_a_person_makes_a_direct_chat_a_group_for_good(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert await _addressed(chats, room_id, agent, "before") is True++ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200+ assert await _channel_type(chats, room_id) == "channel_private"+ assert await _addressed(chats, room_id, agent, "unnamed") is False+ assert await _addressed(chats, room_id, agent, "@helper named") is True++ removed = await chats.client.delete(+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ assert await _channel_type(chats, room_id) == "channel_private"+ assert await _addressed(chats, room_id, agent, "still a group") is False+++async def test_the_creator_rejoining_keeps_a_chat_direct(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert (await chats.invite(chats.alice, room_id, chats.alice)).status_code == 200+ assert await _channel_type(chats, room_id) == "direct"+++async def test_a_second_agent_makes_a_direct_chat_a_group(chats: _Harness) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, helper, "c1")++ added = await _add_agent(chats, chats.alice.id, room_id, other)+ assert added.status_code == 200, added.text+ chat = added.json()["chat"]+ assert chat["channelType"] == "channel_private"+ assert {a["id"] for a in chat["agents"]} == {helper.id, other.id}+ assert await _addressed(chats, room_id, helper, "unnamed") is False++ removed = await chats.client.delete(+ f"/chats/{room_id}/agents/{other.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ assert await _channel_type(chats, room_id) == "channel_private"+ assert await _addressed(chats, room_id, helper, "one agent, still a group") is False+++async def test_an_owner_grant_does_not_make_a_group(chats: _Harness) -> None:+ agent = await chats.agent("mine", owner=chats.alice)+ room_id = await _left_chat(chats, chats.alice)+ [guest] = await _agent_ids(chats, room_id)+ await chats.room_service.remove_agents_from_room(room_id, [guest])+ await chats.room_service.add_agents_to_room(room_id, agent_ids=[agent.id])++ assert await _reads(chats, chats.alice, room_id) == 200+ assert await _channel_type(chats, room_id) == "direct"+ assert await _addressed(chats, room_id, agent, "hello") is True+++async def test_concurrent_adds_leave_one_consistent_group(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")++ responses = await asyncio.gather(+ chats.invite(chats.alice, room_id, chats.bob),+ chats.invite(chats.alice, room_id, chats.admin),+ chats.invite(chats.alice, room_id, chats.bob),+ )+ assert [r.status_code for r in responses] == [200, 200, 200]+ assert await _channel_type(chats, room_id) == "channel_private"+ members = await chats.client.get(+ f"/chats/{room_id}/members", headers=chats.as_user(chats.alice)+ )+ assert {m["userId"] for m in members.json()["members"]} == {+ chats.alice.id,+ chats.bob.id,+ chats.admin.id,+ }+++async def test_a_bridged_direct_room_is_never_converted(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.alice)+ async with chats.factory() as session:+ room = Room(+ transport_room_id="!dm:test",+ name="dm",+ description="",+ owner_id=chats.alice.id,+ channel_type="direct",+ )+ session.add(room)+ await session.flush()+ await session.execute(+ room_agents.insert().values(room_id=room.id, agent_id=agent.id)+ )+ await session.commit()+ room_id = room.id++ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200+ added = await _add_agent(chats, chats.alice.id, room_id, other)+ assert added.status_code == 200+ assert await _channel_type(chats, room_id) == "direct"+++# ── Creating with people ─────────────────────────────────────────────────────+++async def test_a_chat_with_people_and_no_agent_is_a_listed_group(+ chats: _Harness,+) -> None:+ created = await chats.client.post(+ "/chats",+ json={"agentIds": [], "memberUserIds": [chats.bob.id], "requestId": "c1"},+ headers=chats.as_user(chats.alice),+ )+ assert created.status_code == 200, created.text+ chat = created.json()["chat"]+ assert chat["channelType"] == "channel_private"+ assert chat["agents"] == []+ assert chat["roomId"] in await _listed(chats, chats.bob)+ assert chat["roomId"] in await _listed(chats, chats.alice)+ assert (await chats.send(chats.bob, chat["roomId"], "s1", "hi")).status_code == 200+++async def test_one_agent_and_a_person_make_a_group(chats: _Harness) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ created = await chats.client.post(+ "/chats",+ json={"agentId": agent.id, "memberUserIds": [chats.bob.id], "requestId": "c1"},+ headers=chats.as_user(chats.alice),+ )+ assert created.status_code == 200, created.text+ room_id = created.json()["chat"]["roomId"]+ assert created.json()["chat"]["channelType"] == "channel_private"+ assert await _addressed(chats, room_id, agent, "unnamed") is False+ assert await _addressed(chats, room_id, agent, "@helper named") is True+++async def test_a_create_with_people_is_retried_as_one_request(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)++ async def create(member_ids: list[str]) -> httpx.Response:+ return await chats.client.post(+ "/chats",+ json={"agentId": agent.id, "memberUserIds": member_ids, "requestId": "c1"},+ headers=chats.as_user(chats.alice),+ )++ first = await create([chats.bob.id])+ second = await create([chats.bob.id, chats.alice.id])+ assert first.status_code == second.status_code == 200+ assert first.json()["chat"]["roomId"] == second.json()["chat"]["roomId"]++ other = await create([chats.admin.id])+ assert other.status_code == 409+ assert _code(other) == "REQUEST_REUSED"+++async def test_a_create_refuses_someone_outside_the_workspace(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ refused = await chats.client.post(+ "/chats",+ json={+ "agentId": agent.id,+ "memberUserIds": [chats.carol.id],+ "requestId": "c1",+ },+ headers=chats.as_user(chats.alice),+ )+ assert refused.status_code == 422+ assert _code(refused) == "NOT_A_TENANT_MEMBER"+++# ── Adding and removing agents ───────────────────────────────────────────────+++async def test_adding_an_agent_needs_its_permission_in_this_room(+ chats: _Harness,+) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ scoped = await chats.agent("scoped", owner=chats.admin)+ denied_room = await chats.new_chat(chats.alice, helper, "c1")+ allowed_room = await chats.new_chat(chats.alice, helper, "c2")+ await _set_policy(chats, scoped, {"rules": [{"rooms": [allowed_room]}]})++ refused = await _add_agent(chats, chats.alice.id, denied_room, scoped)+ assert refused.status_code == 403+ assert _code(refused) == "AGENT_NOT_ALLOWED"+ assert await _agent_ids(chats, denied_room) == {helper.id}+ assert await _channel_type(chats, denied_room) == "direct"++ added = await _add_agent(chats, chats.alice.id, allowed_room, scoped)+ assert added.status_code == 200, added.text+ assert await _agent_ids(chats, allowed_room) == {helper.id, scoped.id}+++async def test_only_a_manager_adds_or_removes_an_agent(chats: _Harness) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ other = await chats.agent("other", owner=chats.bob)+ room_id = await chats.new_chat(chats.alice, helper, "c1")+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200++ added = await _add_agent(chats, chats.bob.id, room_id, other)+ assert added.status_code == 403+ assert _code(added) == "NOT_A_MANAGER"+ removed = await chats.client.delete(+ f"/chats/{room_id}/agents/{helper.id}", headers=chats.as_user(chats.bob)+ )+ assert removed.status_code == 403+ assert await _agent_ids(chats, room_id) == {helper.id}+++async def test_adding_and_removing_an_agent_are_idempotent(chats: _Harness) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, helper, "c1")++ again = await _add_agent(chats, chats.alice.id, room_id, helper)+ assert again.status_code == 200+ assert await _channel_type(chats, room_id) == "direct"++ for _ in range(2):+ removed = await chats.client.delete(+ f"/chats/{room_id}/agents/{helper.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ assert await _agent_ids(chats, room_id) == set()+ # A Switch Console chat stays listed, and readable, with no agent left.+ assert room_id in await _listed(chats, chats.alice)+ assert await _reads(chats, chats.alice, room_id) == 200+++async def test_a_manager_removes_an_agent_they_may_no_longer_use(+ chats: _Harness,+) -> None:+ helper = await chats.agent("helper", owner=chats.alice)+ guest = await chats.agent("guest", owner=chats.admin)+ room_id = await chats.new_chat(chats.alice, helper, "c1")+ added = await _add_agent(chats, chats.alice.id, room_id, guest)+ assert added.status_code == 200+ await _set_policy(chats, guest, {"rules": [{"owner": True, "users": []}]})++ removed = await chats.client.delete(+ f"/chats/{room_id}/agents/{guest.id}", headers=chats.as_user(chats.alice)+ )+ assert removed.status_code == 204+ assert await _agent_ids(chats, room_id) == {helper.id}+++# ── Mentions ─────────────────────────────────────────────────────────────────+++async def test_mention_agent_ids_address_only_those_agents(chats: _Harness) -> None:+ a = await chats.agent("ann", owner=chats.alice)+ b = await chats.agent("ben", owner=chats.alice)+ c = await chats.agent("cat", owner=chats.alice)+ created = await chats.client.post(+ "/chats",+ json={"agentIds": [a.id, b.id, c.id], "requestId": "c1"},+ headers=chats.as_user(chats.alice),+ )+ room_id = created.json()["chat"]["roomId"]++ sent = await chats.send(+ chats.alice,+ room_id,+ "s1",+ "please look",+ mentionAgentIds=[b.id],+ mentionAgentId=a.id,+ )+ assert sent.status_code == 200, sent.text+ [message] = sent.json()["messages"]+ assert message["body"] == "@ann @ben please look"+ assert sorted(message["namedAgentIds"]) == sorted([a.id, b.id])+ place = (room_id, message["seq"])+ assert place in await _events_of(chats, a)+ assert place in await _events_of(chats, b)+ assert place not in await _events_of(chats, c)++ retried = await chats.send(+ chats.alice,+ room_id,+ "s1",+ "please look",+ mentionAgentIds=[b.id],+ mentionAgentId=a.id,+ )+ assert retried.json()["messages"][0]["seq"] == message["seq"]+ reused = await chats.send(+ chats.alice, room_id, "s1", "please look", mentionAgentIds=[c.id]+ )+ assert reused.status_code == 409+++# ── Threads ──────────────────────────────────────────────────────────────────+++async def test_a_thread_pages_its_replies_and_roots_count_them(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ root = (await chats.send(chats.alice, room_id, "r", "root")).json()["messages"][0]+ other = (await chats.send(chats.alice, room_id, "o", "other")).json()["messages"][0]+ replies = [+ (+ await chats.send(+ chats.alice,+ room_id,+ f"t{i}",+ f"reply {i}",+ threadRootId=root["messageId"],+ )+ ).json()["messages"][0]+ for i in range(3)+ ]++ url = f"/chats/{room_id}/threads/{root['messageId']}/messages"+ first = await chats.client.get(+ url, params={"limit": 2}, headers=chats.as_user(chats.alice)+ )+ assert first.status_code == 200, first.text+ page = first.json()+ assert [m["body"] for m in page["messages"]] == ["reply 1", "reply 2"]+ assert page["hasMore"] is True+ older = await chats.client.get(+ url,+ params={"limit": 2, "beforeSeq": page["messages"][0]["seq"]},+ headers=chats.as_user(chats.alice),+ )+ assert [m["body"] for m in older.json()["messages"]] == ["reply 0"]+ assert older.json()["hasMore"] is False++ history = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.alice)+ )+ by_id = {m["messageId"]: m for m in history.json()["messages"]}+ assert by_id[root["messageId"]]["threadReplyCount"] == 3+ assert by_id[root["messageId"]]["threadLastReplySeq"] == replies[-1]["seq"]+ assert by_id[other["messageId"]]["threadReplyCount"] == 0+ assert by_id[other["messageId"]]["threadLastReplySeq"] is None+ assert by_id[replies[0]["messageId"]]["threadRootId"] == root["messageId"]+++async def test_a_thread_is_read_only_by_members_and_only_in_its_room(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ elsewhere = await chats.new_chat(chats.alice, agent, "c2")+ foreign = (await chats.send(chats.alice, elsewhere, "f", "there")).json()[+ "messages"+ ][0]+ root = (await chats.send(chats.alice, room_id, "r", "root")).json()["messages"][0]++ missing = await chats.client.get(+ f"/chats/{room_id}/threads/{foreign['messageId']}/messages",+ headers=chats.as_user(chats.alice),+ )+ assert missing.status_code == 404+ assert _code(missing) == "THREAD_NOT_FOUND"+ outsider = await chats.client.get(+ f"/chats/{room_id}/threads/{root['messageId']}/messages",+ headers=chats.as_user(chats.bob),+ )+ assert outsider.status_code == 403+++async def test_history_stays_readable_once_the_agents_are_gone(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.bob)+ room_id = await chats.new_chat(chats.alice, agent, "c1")+ assert (await chats.send(chats.alice, room_id, "s1", "kept")).status_code == 200+ await chats.room_service.remove_agents_from_room(room_id, [agent.id])++ history = await chats.client.get(+ f"/chats/{room_id}/messages", headers=chats.as_user(chats.alice)+ )+ assert history.status_code == 200+ assert "kept" in [m["body"] for m in history.json()["messages"]]diff --git a/core/tests/switch_core/gateway/test_chats_routes.py b/core/tests/switch_core/gateway/test_chats_routes.pyindex d401db3c0..e8ad909d1 100644--- a/core/tests/switch_core/gateway/test_chats_routes.py+++ b/core/tests/switch_core/gateway/test_chats_routes.py@@ -346,7 +346,6 @@ async def test_a_create_names_its_agents_one_way(chats: _Harness) -> None:helper = await chats.agent("helper", owner=chats.alice)for body in ({"requestId": "c1"},- {"requestId": "c2", "agentIds": []},{"requestId": "c3", "agentId": helper.id, "agentIds": [helper.id]},):response = await chats.client.post(@@ -885,7 +884,8 @@ async def test_unlisted_room_still_delivers_messages_to_invited_member(chats: _Harness,) -> None:agent = await chats.agent("helper", owner=chats.alice)- room_id = await chats.new_chat(chats.alice, agent, "c1")+ room_id = await _room(chats, [agent], owner=chats.alice)+ assert (await chats.invite(chats.alice, room_id, chats.alice)).status_code == 200assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200events = _stream(chats, chats.bob, {}, recheck=60.0)@@ -911,7 +911,8 @@ async def test_unlisted_then_revoked_room_emits_access_removal(chats: _Harness,) -> None:agent = await chats.agent("helper", owner=chats.alice)- room_id = await chats.new_chat(chats.alice, agent, "c1")+ room_id = await _room(chats, [agent], owner=chats.alice)+ assert (await chats.invite(chats.alice, room_id, chats.alice)).status_code == 200assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200events = _stream(chats, chats.bob, {}, recheck=60.0)@@ -944,7 +945,7 @@ async def test_an_unlisted_chat_is_announced_again_when_an_agent_returns(chats: _Harness,) -> None:agent = await chats.agent("helper", owner=chats.alice)- room_id = await chats.new_chat(chats.alice, agent, "c1")+ room_id = await _room(chats, [agent], owner=chats.alice)assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200events = _stream(chats, chats.bob, {}, recheck=60.0)@@ -968,7 +969,7 @@ async def test_the_periodic_recheck_announces_a_chat_that_regains_an_agent(chats: _Harness,) -> None:agent = await chats.agent("helper", owner=chats.alice)- room_id = await chats.new_chat(chats.alice, agent, "c1")+ room_id = await _room(chats, [agent], owner=chats.alice)assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200async with chats.factory() as session:await session.execute(diff --git a/core/tests/switch_core/test_migration_console_direct_chats_to_groups.py b/core/tests/switch_core/test_migration_console_direct_chats_to_groups.pynew file mode 100644index 000000000..2df13881d--- /dev/null+++ b/core/tests/switch_core/test_migration_console_direct_chats_to_groups.py@@ -0,0 +1,126 @@+"""`d4e8a1c5b7f3` turns a Switch Console direct chat that already has another+person into a group. Seeds one chat of each kind that must stay direct (only+its creator, an owner-grant holder, a bridged direct room) beside one that+gained a person, and checks only that one changes."""++from __future__ import annotations++from typing import Any++import pytest+from sqlalchemy import text+from sqlalchemy.ext.asyncio import create_async_engine++from tests.switch_core.test_migration_oidc_identities_backfill import _upgrade_to++_DB = "migration_console_direct_chats_to_groups"+_BEFORE = "c7715ebb95c9"+_UNDER_TEST = "d4e8a1c5b7f3"+_TENANT = "00000000-0000-0000-0000-000000000000"+++async def migration_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_only_a_console_direct_chat_with_another_person_becomes_a_group(+ migration_url: str,+) -> None:+ engine = create_async_engine(migration_url)+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_BEFORE))++ async with engine.begin() as connection:+ await connection.execute(+ text("SET LOCAL session_replication_role = replica")+ )+ for room_id, metadata in (+ ("alone", '{"chat_operation_id": "op-1"}'),+ ("granted", '{"chat_operation_id": "op-2"}'),+ ("joined", '{"chat_operation_id": "op-3"}'),+ ("bridged", None),+ ):+ await connection.execute(+ text(+ "INSERT INTO rooms (id, tenant_id, matrix_room_id, name, "+ "description, channel_type, created_by, owner_id, metadata) "+ "VALUES (:id, :tenant, :transport, :id, '', 'direct', "+ "'alice', 'alice', CAST(:metadata AS jsonb))"+ ),+ {+ "id": room_id,+ "tenant": _TENANT,+ "transport": f"!{room_id}:test",+ "metadata": metadata,+ },+ )+ for client_id, user_id in (("c-alice", "alice"), ("c-bob", "bob")):+ await connection.execute(+ text(+ "INSERT INTO clients (id, tenant_id, matrix_user_id, "+ "display_name, type, user_id) VALUES (:id, :tenant, "+ ":transport, :user, 'member', :user)"+ ),+ {+ "id": client_id,+ "tenant": _TENANT,+ "transport": f"@{client_id}:test",+ "user": user_id,+ },+ )+ for client_id, room_id in (+ ("c-alice", "alone"),+ ("c-alice", "granted"),+ ("c-bob", "granted"),+ ("c-alice", "joined"),+ ("c-bob", "joined"),+ ("c-bob", "bridged"),+ ):+ await connection.execute(+ text(+ "INSERT INTO client_rooms (client_id, room_id, tenant_id) "+ "VALUES (:client, :room, :tenant)"+ ),+ {"client": client_id, "room": room_id, "tenant": _TENANT},+ )+ await connection.execute(+ text(+ "INSERT INTO chat_owner_grants (tenant_id, user_id, room_id) "+ "VALUES (:tenant, 'bob', 'granted')"+ ),+ {"tenant": _TENANT},+ )++ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_UNDER_TEST))++ async with engine.connect() as connection:+ types = dict(+ (+ await connection.execute(text("SELECT id, channel_type FROM rooms"))+ ).all()+ )+ finally:+ await engine.dispose()++ assert types == {+ "alone": "direct",+ "granted": "direct",+ "joined": "channel_private",+ "bridged": "direct",+ }