Skip to content

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

fix(chats): a second agent and the group it makes commit together

raullopez-sandbox9af98f109f2d
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index b44e022a0..a202dd40a 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -870,41 +870,49 @@ class ChatService:
) -> 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 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,
+ )
+ if agent_id in await self._room_store.get_agent_ids(session, room.id):
+ return room
+ await self._room_service.add_agents_to_room(
+ room.id,
+ agent_ids=[agent_id],
+ with_agents=lambda session: self._group_if_several_agents(session, room),
+ )
+ async with tenant_session(self.session_factory, tenant_id) as session:
+ return await self._room(session, tenant_id, room_id)
+
+ async def _group_if_several_agents(self, session: AsyncSession, room: Room) -> None:
+ """`_make_group` once the room holds more than one agent, in the
+ transaction that added the agent. The room row is locked before counting, so a
+ concurrent add counts this one's agent once this one commits."""
+ locked = await session.scalar(
+ select(Room).where(Room.id == room.id).with_for_update(key_share=True)
+ )
+ assert locked is not None
+ if len(await self._room_store.get_agent_ids(session, room.id)) > 1:
+ await self._make_group(session, locked)
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 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:
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index 8cc79c00a..8725cffde 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -957,7 +957,10 @@ class RoomService:
include_subagents_for: list[str] | None = None,
join_event_listeners: list[str] | None = None,
added_by_kind: Literal["user", "agent", "system"] = "user",
+ with_agents: Callable[[AsyncSession], Awaitable[None]] | None = None,
) -> None:
+ """`with_agents` runs in the transaction that records the agents, so
+ what it writes commits with them or not at all."""
by_name = agent_ids is None and agent_names is not None
if by_name:
assert agent_names is not None
@@ -1007,6 +1010,8 @@ class RoomService:
aid for aid in new_agent_ids if aid in listeners
},
)
+ if with_agents is not None:
+ await with_agents(session)
await session.commit()
await self._invite_clients(room.transport_room_id, agent_clients)
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index c5d6e9138..665401c42 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -7,7 +7,9 @@ from __future__ import annotations
import asyncio
import httpx
+import pytest
from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import Agent, Room, room_agents
from tests.switch_core.gateway.conftest import _Harness
@@ -115,6 +117,54 @@ async def test_a_second_agent_makes_a_direct_chat_a_group(chats: _Harness) -> No
assert await _addressed(chats, room_id, helper, "one agent, still a group") is False
+async def test_a_second_agent_that_fails_to_commit_leaves_the_chat_direct(
+ chats: _Harness, monkeypatch: pytest.MonkeyPatch
+) -> 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")
+ convert = chats.service._group_if_several_agents
+
+ async def convert_then_fail(session: AsyncSession, room: Room) -> None:
+ await convert(session, room)
+ raise RuntimeError("lost before commit")
+
+ monkeypatch.setattr(chats.service, "_group_if_several_agents", convert_then_fail)
+ with pytest.raises(RuntimeError, match="lost before commit"):
+ await _add_agent(chats, chats.alice.id, room_id, other)
+ assert await _agent_ids(chats, room_id) == {helper.id}
+ assert await _channel_type(chats, room_id) == "direct"
+
+
+async def test_concurrent_agent_adds_make_one_group(
+ chats: _Harness, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ convert = chats.service._group_if_several_agents
+ both_written = asyncio.Barrier(2)
+
+ async def after_both_agents_are_written(session: AsyncSession, room: Room) -> None:
+ await both_written.wait()
+ await convert(session, room)
+
+ monkeypatch.setattr(
+ chats.service, "_group_if_several_agents", after_both_agents_are_written
+ )
+ helper = await chats.agent("helper", owner=chats.alice)
+ ann = await chats.agent("ann", owner=chats.alice)
+ ben = await chats.agent("ben", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, helper, "c1")
+ await chats.room_service.remove_agents_from_room(room_id, [helper.id])
+ assert await _channel_type(chats, room_id) == "direct"
+
+ responses = await asyncio.gather(
+ _add_agent(chats, chats.alice.id, room_id, ann),
+ _add_agent(chats, chats.alice.id, room_id, ben),
+ )
+ assert [r.status_code for r in responses] == [200, 200]
+ assert await _agent_ids(chats, room_id) == {ann.id, ben.id}
+ assert await _channel_type(chats, room_id) == "channel_private"
+
+
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)
@@ -193,6 +243,19 @@ async def test_a_chat_with_people_and_no_agent_is_a_listed_group(
assert (await chats.send(chats.bob, chat["roomId"], "s1", "hi")).status_code == 200
+async def test_a_chat_with_no_agents_and_no_one_else(chats: _Harness) -> None:
+ created = await chats.client.post(
+ "/chats",
+ json={"agentIds": [], "requestId": "c1"},
+ headers=chats.as_user(chats.alice),
+ )
+ assert created.status_code == 200, created.text
+ chat = created.json()["chat"]
+ assert chat["agents"] == []
+ assert chat["channelType"] == "channel_private"
+ assert chat["roomId"] in await _listed(chats, chats.alice)
+
+
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(