Skip to content

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

Let a Console chat be a private Slack channel with the user's agent

raullopez-sandboxcd8a34341401
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 40ee8e045..c7ea9b07a 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -67,6 +67,7 @@ from switch_core.db.models import (
ChatRead,
Client,
ClientRoom,
+ CollaborationBridge,
MediaBlob,
Message,
MessageAttachment,
@@ -1363,6 +1364,7 @@ class ChatService:
request_id: str,
greeting: str | None,
kind: Literal["group"] | None,
+ bridge_id: str | None,
) -> Room:
"""A private room with the agents and members, owned by and joined by
the user.
@@ -1380,9 +1382,18 @@ class ChatService:
`greeting` is what the agent says as it joins, in place of its usual
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.
+
+ `bridge_id` makes the direct chat a private channel on that bridge
+ between the user's own linked account there and the agent.
"""
member_user_ids = sorted(set(member_user_ids) - {user.id})
direct = kind != "group" and len(agent_ids) == 1 and not member_user_ids
+ if bridge_id is not None and not direct:
+ raise ChatError(
+ 422,
+ "BRIDGED_CHAT_NEEDS_ONE_AGENT",
+ "A chat on a bridge is a direct chat with one agent and nobody else.",
+ )
if member_user_ids or kind == "group" or not agent_ids:
self._require_group_chats()
if greeting is not None:
@@ -1412,6 +1423,11 @@ class ChatService:
# Only when given, so a request without it hashes as it always has.
if kind is not None:
request["kind"] = kind
+ if bridge_id is not None:
+ # The greeting's text changes between app versions; a retry must
+ # still match the request it repeats.
+ request.pop("greeting", None)
+ request["bridgeId"] = bridge_id
payload_hash = _hash(request)
async with self._lock("create", tenant_id, user.id):
async with tenant_session(self.session_factory, tenant_id) as session:
@@ -1439,6 +1455,11 @@ class ChatService:
"NOT_AGENT_OWNER",
"Only the agent's owner can give it a greeting.",
)
+ user_names = (
+ [await self._linked_username(session, user.id, bridge_id)]
+ if bridge_id is not None
+ else None
+ )
if operation is None:
claimed = await self._claim(
session,
@@ -1470,6 +1491,7 @@ class ChatService:
+ [member.name for member in members]
)
try:
+ # shortcut: a crash or lost Slack response after the channel exists but before the room is saved leaves an orphan channel and a retry makes a second one; add adoption if this shows up.
created = await self._room_service.create_room(
RoomCreateConfig(
name=name or "New Chat",
@@ -1480,7 +1502,9 @@ class ChatService:
),
agent_ids=[agent.id for agent in agents],
channel_type="direct" if direct else "channel_private",
- internal_only=True,
+ internal_only=bridge_id is None,
+ bridge_id=bridge_id,
+ user_names=user_names,
created_by=user.id,
owner_id=user.id,
read_visibility="private",
@@ -1535,6 +1559,30 @@ class ChatService:
self._start_session(agents[0].id, room.id)
return room
+ @staticmethod
+ async def _linked_username(
+ session: AsyncSession, user_id: str, bridge_id: str
+ ) -> str:
+ """The user's own account name on the bridge, from the identity they
+ linked there; never one the client names."""
+ bridge = await session.get(CollaborationBridge, bridge_id)
+ if bridge is None or bridge.tenant_id != require_tenant_id():
+ raise ChatError(404, "BRIDGE_NOT_FOUND", "No such bridge.")
+ linked = [
+ external
+ for external in await ExternalUserStore().get_by_user(session, user_id)
+ if external.bridge_id == bridge_id
+ ]
+ if not linked:
+ raise ChatError(
+ 422,
+ "ACCOUNT_NOT_LINKED",
+ f"Your Switch account is not linked to an account on "
+ f"{bridge.display_name}. Link it in your Switch settings, then "
+ "try again.",
+ )
+ return linked[0].external_username
+
async def _room_of_operation(
self, session: AsyncSession, operation_id: str
) -> Room | None:
diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.py
index 8928eba9e..57751fb51 100644
--- a/core/switch_core/gateway/chats.py
+++ b/core/switch_core/gateway/chats.py
@@ -114,6 +114,9 @@ class CreateChatRequest(CamelModel):
# "group" makes a group even of one agent and nobody else, which would
# otherwise be a direct chat; older clients send none.
kind: Literal["group"] | None = None
+ # Makes the direct chat a private channel on this collaboration bridge
+ # (Slack), with the caller's own linked account; older clients send none.
+ bridge_id: str | None = None
def chosen_agents(self) -> list[str]:
if (self.agent_id is None) == (self.agent_ids is None):
@@ -326,6 +329,7 @@ async def create_chat(
request_id=req.request_id,
greeting=req.greeting,
kind=req.kind,
+ bridge_id=req.bridge_id,
)
async with tenant_session(service.session_factory, tenant_id) as session:
return ChatEnvelope(
diff --git a/core/tests/switch_core/gateway/test_chats_bridged_direct.py b/core/tests/switch_core/gateway/test_chats_bridged_direct.py
new file mode 100644
index 000000000..46dc6df5c
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_chats_bridged_direct.py
@@ -0,0 +1,227 @@
+"""A chat created with a `bridgeId`: a direct chat that is a private channel
+on that bridge, between the caller's own linked account and the agent."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+
+from switch_core.db.models import (
+ Agent,
+ Client,
+ CollaborationBridge,
+ ExternalUser,
+ ExternalUserClaim,
+ Room,
+ User,
+)
+from tests.switch_core.gateway.conftest import _Harness
+from tests.switch_core.gateway.test_chats_routes import _code
+
+TENANT = "00000000-0000-0000-0000-000000000000"
+
+
+class _FakeCore:
+ def __init__(self, transport_user_id: str, known: dict[str, str]) -> None:
+ self._workspace_consumer_transport_user_id = transport_user_id
+ self._known = known
+ self.dm_calls: list[dict[str, str]] = []
+
+ async def create_dm_channel(
+ *, agent_name: str, user_name: str, user_external_id: str
+ ) -> str:
+ self.dm_calls.append(
+ {
+ "agent_name": agent_name,
+ "user_name": user_name,
+ "user_external_id": user_external_id,
+ }
+ )
+ return f"C-DM-{len(self.dm_calls)}"
+
+ async def ensure_channel_subscriptions(channels: Any) -> None:
+ return None
+
+ self.adapter = SimpleNamespace(
+ create_dm_channel=create_dm_channel,
+ ensure_channel_subscriptions=ensure_channel_subscriptions,
+ )
+
+ async def resolve_external_user_id_map(
+ self, user_names: list[str]
+ ) -> dict[str, str]:
+ return {n: self._known[n] for n in user_names if n in self._known}
+
+ def begin_provisioning(self, channel_id: str) -> None:
+ return None
+
+ def end_provisioning(self, channel_id: str) -> None:
+ return None
+
+ def add_room_mapping(self, *args: Any) -> None:
+ return None
+
+ async def ensure_users_in_room(self, *args: Any) -> None:
+ return None
+
+
+class _FakeCollabLifecycle:
+ def __init__(self, bridges: dict[str, _FakeCore]) -> None:
+ self._bridges = bridges
+
+ def get(self, bridge_id: str) -> _FakeCore | None:
+ return self._bridges.get(bridge_id)
+
+ def rooms_changed(self, bridge_id: str) -> None:
+ return None
+
+
+async def _slack(chats: _Harness, *, link: User | None) -> tuple[str, _FakeCore]:
+ """A running Slack bridge on which `link`, if given, has claimed `U-ALICE`."""
+ async with chats.factory() as session:
+ bot = Client(
+ transport_user_id="@slack-bot:switch.test",
+ display_name="Slack Bot",
+ type="bridge",
+ )
+ session.add(bot)
+ await session.flush()
+ bridge = CollaborationBridge(
+ tenant_id=TENANT,
+ type="slack",
+ display_name="Acme Slack",
+ connection_config={},
+ client_id=bot.id,
+ status="active",
+ channel_creation_enabled=True,
+ )
+ session.add(bridge)
+ await session.flush()
+ if link is not None:
+ person = Client(
+ transport_user_id="@slack-alice:switch.test",
+ display_name="alice.s",
+ type="human",
+ )
+ session.add(person)
+ await session.flush()
+ external = ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id="U-ALICE",
+ external_username="alice.s",
+ client_id=person.id,
+ )
+ session.add(external)
+ await session.flush()
+ session.add(
+ ExternalUserClaim(external_user_id=external.id, user_id=link.id)
+ )
+ await session.commit()
+ bridge_id = bridge.id
+ core = _FakeCore("@slack-bot:switch.test", {"alice.s": "U-ALICE"})
+ chats.room_service._collab_lifecycle = _FakeCollabLifecycle({bridge_id: core}) # type: ignore[assignment]
+ return bridge_id, core
+
+
+async def _create(
+ chats: _Harness, agents: list[Agent], bridge_id: str, request_id: str = "c1"
+) -> httpx.Response:
+ return await chats.client.post(
+ "/chats",
+ json={
+ "agentIds": [agent.id for agent in agents],
+ "requestId": request_id,
+ "bridgeId": bridge_id,
+ },
+ headers=chats.as_user(chats.alice),
+ )
+
+
+async def test_a_bridged_chat_opens_a_dm_with_the_callers_linked_account(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ bridge_id, core = await _slack(chats, link=chats.alice)
+
+ response = await _create(chats, [agent], bridge_id)
+
+ assert response.status_code == 200, response.text
+ chat = response.json()["chat"]
+ assert chat["bridgeType"] == "slack"
+ assert chat["channelType"] == "direct"
+ assert core.dm_calls == [
+ {"agent_name": "helper", "user_name": "alice.s", "user_external_id": "U-ALICE"}
+ ]
+ async with chats.factory() as session:
+ room = await session.get(Room, chat["roomId"])
+ assert room is not None
+ assert room.bridge_id == bridge_id
+ assert room.external_channel_id == "C-DM-1"
+
+
+async def test_a_retry_returns_the_same_chat_and_opens_one_channel(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ bridge_id, core = await _slack(chats, link=chats.alice)
+
+ first = await _create(chats, [agent], bridge_id)
+ again = await _create(chats, [agent], bridge_id)
+
+ assert first.status_code == 200, first.text
+ assert again.status_code == 200, again.text
+ assert again.json()["chat"]["roomId"] == first.json()["chat"]["roomId"]
+ assert len(core.dm_calls) == 1
+
+
+async def test_a_retry_with_a_changed_greeting_is_the_same_request(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ bridge_id, core = await _slack(chats, link=chats.alice)
+
+ async def create(greeting: str) -> httpx.Response:
+ return await chats.client.post(
+ "/chats",
+ json={
+ "agentId": agent.id,
+ "requestId": "c1",
+ "bridgeId": bridge_id,
+ "greeting": greeting,
+ },
+ headers=chats.as_user(chats.alice),
+ )
+
+ first = await create("Hi.")
+ again = await create("Hello there.")
+
+ assert again.status_code == 200, again.text
+ assert again.json()["chat"]["roomId"] == first.json()["chat"]["roomId"]
+ assert len(core.dm_calls) == 1
+
+
+async def test_an_unlinked_caller_is_told_to_link_their_account(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ bridge_id, core = await _slack(chats, link=None)
+
+ response = await _create(chats, [agent], bridge_id)
+
+ assert response.status_code == 422
+ assert _code(response) == "ACCOUNT_NOT_LINKED"
+ assert core.dm_calls == []
+
+
+async def test_a_bridged_chat_has_one_agent(chats: _Harness) -> None:
+ one = await chats.agent("one", owner=chats.alice)
+ two = await chats.agent("two", owner=chats.alice)
+ bridge_id, core = await _slack(chats, link=chats.alice)
+
+ response = await _create(chats, [one, two], bridge_id)
+
+ assert response.status_code == 422
+ assert _code(response) == "BRIDGED_CHAT_NEEDS_ONE_AGENT"
+ assert core.dm_calls == []
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index 335eb117e..269e096ae 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -947,6 +947,7 @@ async def test_one_create_on_two_processes_makes_one_room(
name=None,
request_id="c1",
greeting=None,
+ bridge_id=None,
)
first, second = await asyncio.gather(create(chats.service), create(other))
@@ -1223,6 +1224,7 @@ async def test_one_request_id_with_two_payloads_on_two_processes_is_one_request(
name=None,
request_id="c1",
greeting=None,
+ bridge_id=None,
)
except ChatError as refused:
return refused