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
Make the Slack hand-off safe to retry and resume
raullopez-sandbox619dc0b77e58
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsxindex e70ba951f..e04b5705e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx@@ -14,7 +14,7 @@ import { Button } from '@renderer/lib/ui/button';import { Spinner } from '@renderer/lib/ui/spinner';import type { RemoteBridge } from '@shared/core/switch-servers/switch-servers';import { buddySetupStep } from './buddy-setup-step';-import { BUDDY_CHAT_NAME, continueBuddyInSlack } from './open-buddy';+import { BUDDY_CHAT_NAME, buddyHandoffRequestId, continueBuddyInSlack } from './open-buddy';/*** The setup cards under the greeting in the buddy's Welcome chat: pick Slack,@@ -74,7 +74,15 @@ const Cards = observer(function Cards({ids.refresh();};- const doneRoomId = step.kind === 'done' ? step.roomId : null;+ const confirmBridgeId = step.kind === 'confirm' ? step.bridge.id : null;+ const confirmQuery = useQuery({+ queryKey: ['buddy-handoff', buddyHandoffRequestId(agentId, confirmBridgeId ?? '')],+ queryFn: () => continueBuddyInSlack(serverId, { agentId }, confirmBridgeId as string),+ enabled: confirmBridgeId !== null,+ retry: false,+ staleTime: Infinity,+ });+ const doneRoomId = confirmBridgeId ? (confirmQuery.data?.roomId ?? null) : null;const roomQuery = useQuery({queryKey: ['buddy-handoff-room', workspaceId, doneRoomId],queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId, roomId: doneRoomId as string }),@@ -92,7 +100,8 @@ const Cards = observer(function Cards({setCreating(true);setCreateError(null);try {- await continueBuddyInSlack(serverId, { agentId }, bridge.id);+ const chat = await continueBuddyInSlack(serverId, { agentId }, bridge.id);+ queryClient.setQueryData(['buddy-handoff', buddyHandoffRequestId(agentId, bridge.id)], chat);await queryClient.invalidateQueries({ queryKey: ['buddy-handoff-chats', serverId] });} catch (cause) {setCreateError(failureText(cause, 'Switch did not answer.'));@@ -103,7 +112,7 @@ const Cards = observer(function Cards({const slackIcon = <BridgeIcon bridgeType="slack" className="size-4" />;const pastChoice =- picked || step.kind === 'link' || step.kind === 'create' || step.kind === 'done';+ picked || step.kind === 'link' || step.kind === 'create' || step.kind === 'confirm';return (<div className="mt-4 flex flex-col gap-2" data-testid="buddy-setup-cards">@@ -190,7 +199,34 @@ const Cards = observer(function Cards({</Alert>)}- {step.kind === 'done' && (+ {step.kind === 'confirm' && confirmQuery.isPending && (+ <Alert>+ <Spinner size="sm" />+ <AlertTitle>Finishing setup…</AlertTitle>+ </Alert>+ )}++ {step.kind === 'confirm' && confirmQuery.isError && (+ <Alert variant="destructive">+ <AlertTitle>Couldn’t finish moving to Slack</AlertTitle>+ <AlertDescription>+ {failureText(confirmQuery.error, 'Switch did not answer.')}+ </AlertDescription>+ <AlertAction>+ <Button+ size="sm"+ variant="outline"+ disabled={confirmQuery.isFetching}+ onClick={() => void confirmQuery.refetch()}+ >+ {confirmQuery.isFetching && <Spinner size="sm" />}+ Try again+ </Button>+ </AlertAction>+ </Alert>+ )}++ {doneRoomId && (<Alert>{slackIcon}<AlertTitle>Continued in Slack</AlertTitle>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.tsindex 04efb5d31..9b81e1017 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts@@ -35,13 +35,21 @@ describe('buddySetupStep', () => {});});- it('is done once a Slack direct chat with the buddy exists', () => {- expect(buddySetupStep({ ...base, chats: [slackChat], failed: true })).toEqual({- kind: 'done',- roomId: 'r-1',+ it('confirms, not assumes, a Slack direct chat with the buddy', () => {+ expect(buddySetupStep({ ...base, bridges: [slack], chats: [slackChat] })).toEqual({+ kind: 'confirm',+ bridge: slack,});+ expect(buddySetupStep({ ...base, bridges: [slack], chats: [slackChat], failed: true })).toEqual(+ { kind: 'unknown' }+ );expect(- buddySetupStep({ ...base, chats: [{ ...slackChat, agents: [] }] as ChatSummary[] }).kind- ).toBe('connect');+ buddySetupStep({+ ...base,+ bridges: [slack],+ identities: [linked],+ chats: [{ ...slackChat, agents: [] }] as ChatSummary[],+ }).kind+ ).toBe('create');});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.tsindex 799d82f30..9d9bd0e80 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts@@ -7,11 +7,13 @@ export type BuddySetupStep =| { kind: 'connect' }| { kind: 'link'; bridge: RemoteBridge }| { kind: 'create'; bridge: RemoteBridge }- | { kind: 'done'; roomId: string };+ | { kind: 'confirm'; bridge: RemoteBridge };/*** Where the person is in moving their buddy to Slack, from live reads. A read* not in yet is `loading`; one that failed is `unknown`, never "not connected".+ * A Slack chat with the buddy is `confirm`, not done: the server lists it+ * before its hand-off has finished, so the hand-off is resumed to know.*/export function buddySetupStep({agentId,@@ -32,11 +34,11 @@ export function buddySetupStep({chat.bridgeType === 'slack' &&chat.agents.some((agent) => agent.id === agentId));- if (handedOff) return { kind: 'done', roomId: handedOff.roomId };if (failed) return { kind: 'unknown' };if (!bridges || !chats) return { kind: 'loading' };const slack = bridges.find((bridge) => bridge.type === 'slack' && bridge.status === 'active');if (!slack) return { kind: 'connect' };+ if (handedOff) return { kind: 'confirm', bridge: slack };if (!identities) return { kind: 'loading' };if (!identities.some((identity) => identity.bridgeId === slack.id))return { kind: 'link', bridge: slack };diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex c7ea9b07a..5a214b952 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -24,7 +24,8 @@ import loggingimport reimport uuidimport weakref-from collections.abc import Callable+from collections.abc import AsyncIterator, Callable+from contextlib import asynccontextmanagerfrom dataclasses import dataclassfrom datetime import UTC, datetimefrom typing import TYPE_CHECKING, Literal@@ -42,7 +43,6 @@ from sqlalchemy import (update,)from sqlalchemy.dialects.postgresql import insert as pg_insert-from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.addressing import allows_on_behalf_of, parse_policy@@ -1483,59 +1483,50 @@ class ChatService:session, tenant_id, user, operation.room_id)return room- operation_id = self._operation_id(tenant_id, user.id, request_id)- found = await self._room_of_operation(session, operation_id)- if found is None:- names = ", ".join(- [agent.name for agent in agents]- + [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",- description=(- f"Switch Console chat with {names}"- if names- else "Switch Console chat"- ),- agent_ids=[agent.id for agent in agents],- channel_type="direct" if direct else "channel_private",- 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",- write_visibility="private",- acting_user_id=user.id,- created_by_kind="user",- chat_operation_id=operation_id,- agent_greeting=(- {"agent_id": agents[0].id, "body": greeting}- if greeting is not None- else None- ),- )+ operation_id = self._operation_id(tenant_id, user.id, request_id)+ async with self._provisioning_one_at_a_time(operation_id):+ async with tenant_session(self.session_factory, tenant_id) as session:+ found = await self._room_of_operation(session, operation_id)+ if found is None:+ names = ", ".join(+ [agent.name for agent in agents]+ + [member.name for member in members])- except ValueError as exc:- raise ChatError(422, "CHAT_NOT_CREATED", str(exc)) from exc- except IntegrityError:- # The same request made the room first, on another process.- async with tenant_session(- self.session_factory, tenant_id- ) as session:- found = await self._room_of_operation(session, operation_id)- if found is None:- raise- room = found- await self._room_service.reconcile_room(room)- else:+ 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",+ description=(+ f"Switch Console chat with {names}"+ if names+ else "Switch Console chat"+ ),+ agent_ids=[agent.id for agent in agents],+ channel_type="direct" if direct else "channel_private",+ 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",+ write_visibility="private",+ acting_user_id=user.id,+ created_by_kind="user",+ chat_operation_id=operation_id,+ agent_greeting=(+ {"agent_id": agents[0].id, "body": greeting}+ if greeting is not None+ else None+ ),+ )+ )+ except ValueError as exc:+ raise ChatError(422, "CHAT_NOT_CREATED", str(exc)) from excroom = created.room- else:- room = found- await self._room_service.reconcile_room(room)+ else:+ room = found+ await self._room_service.reconcile_room(room, user_names)for joiner in [user, *members]:client = await self.member_actor(tenant_id, joiner)await self._join(tenant_id, room, client)@@ -1559,6 +1550,21 @@ class ChatService:self._start_session(agents[0].id, room.id)return room+ @asynccontextmanager+ async def _provisioning_one_at_a_time(+ self, operation_id: str+ ) -> AsyncIterator[None]:+ """At most one attempt at an operation's room at once, across every+ server process: a session-level advisory lock, released with the+ connection if the process dies."""+ key = func.hashtext(f"chat-create:{operation_id}")+ async with self.session_factory() as session:+ await session.execute(select(func.pg_advisory_lock(key)))+ try:+ yield+ finally:+ await session.execute(select(func.pg_advisory_unlock(key)))+@staticmethodasync def _linked_username(session: AsyncSession, user_id: str, bridge_id: strdiff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 7c70a4dc5..6acb6de87 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -1697,12 +1697,26 @@ class RoomService:", ".join(failures),)- async def reconcile_room(self, room: Room) -> None:+ async def reconcile_room(self, room: Room, user_names: list[str] | None) -> None:"""Put the room's agent and system clients in it where they are missing.For a caller repairing one room whose creation may have stopped after- the room row committed and before its clients joined.+ the room row committed and before its clients joined. A room on a+ bridge also gets the bridge client and the actors of `user_names`,+ ahead of the agents as in `create_room`."""+ if room.bridge_id is not None and room.external_channel_id is not None:+ collaboration_core = self._collab_lifecycle.get(room.bridge_id)+ if collaboration_core is None:+ raise ValueError(f"Bridge not running: {room.bridge_id}")+ await self._provisioning.invite_to_room(+ room.transport_room_id,+ collaboration_core._workspace_consumer_transport_user_id,+ )+ if user_names:+ await collaboration_core.ensure_users_in_room(+ room.id, room.transport_room_id, user_names+ )await self._reconcile_one_room(room)async def _reconcile_one_room(self, room: Room) -> None:diff --git a/core/tests/switch_core/gateway/test_chats_bridged_direct.py b/core/tests/switch_core/gateway/test_chats_bridged_direct.pyindex 46dc6df5c..19f4a9441 100644--- a/core/tests/switch_core/gateway/test_chats_bridged_direct.py+++ b/core/tests/switch_core/gateway/test_chats_bridged_direct.py@@ -3,10 +3,14 @@ on that bridge, between the caller's own linked account and the agent."""from __future__ import annotations+import asyncio+import copy+import weakreffrom types import SimpleNamespacefrom typing import Anyimport httpx+import pytestfrom switch_core.db.models import (Agent,@@ -17,6 +21,7 @@ from switch_core.db.models import (Room,User,)+from switch_core.tenant_context import tenant_scopefrom tests.switch_core.gateway.conftest import _Harnessfrom tests.switch_core.gateway.test_chats_routes import _code@@ -28,6 +33,7 @@ class _FakeCore:self._workspace_consumer_transport_user_id = transport_user_idself._known = knownself.dm_calls: list[dict[str, str]] = []+ self.users_added: list[list[str]] = []async def create_dm_channel(*, agent_name: str, user_name: str, user_external_id: str@@ -39,6 +45,8 @@ class _FakeCore:"user_external_id": user_external_id,})+ # Yields, so a concurrent attempt can run while the channel is made.+ await asyncio.sleep(0.05)return f"C-DM-{len(self.dm_calls)}"async def ensure_channel_subscriptions(channels: Any) -> None:@@ -63,8 +71,10 @@ class _FakeCore:def add_room_mapping(self, *args: Any) -> None:return None- async def ensure_users_in_room(self, *args: Any) -> None:- return None+ async def ensure_users_in_room(+ self, room_id: str, transport_room_id: str, user_names: list[str]+ ) -> None:+ self.users_added.append(user_names)class _FakeCollabLifecycle:@@ -225,3 +235,91 @@ async def test_a_bridged_chat_has_one_agent(chats: _Harness) -> None:assert response.status_code == 422assert _code(response) == "BRIDGED_CHAT_NEEDS_ONE_AGENT"assert core.dm_calls == []+++async def _create_on(+ chats: _Harness, service: Any, agent: Agent, bridge_id: str+) -> Room:+ with tenant_scope(TENANT):+ return await service.create_chat(+ TENANT,+ chats.alice,+ agent_ids=[agent.id],+ member_user_ids=[],+ name=None,+ request_id="c1",+ greeting=None,+ kind=None,+ bridge_id=bridge_id,+ )+++async def test_two_processes_racing_one_request_open_one_channel(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)+ other = copy.copy(chats.service)+ other._locks = weakref.WeakValueDictionary()++ first, second = await asyncio.gather(+ _create_on(chats, chats.service, agent, bridge_id),+ _create_on(chats, other, agent, bridge_id),+ )++ assert first.id == second.id+ assert len(core.dm_calls) == 1+++async def test_a_retry_after_a_failed_join_finishes_the_same_chat(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)+ make_lasting = chats.service._make_lasting+ failures = [RuntimeError("join failed")]++ async def failing_make_lasting(*args: Any) -> None:+ if failures:+ raise failures.pop()+ await make_lasting(*args)++ monkeypatch.setattr(chats.service, "_make_lasting", failing_make_lasting)++ with pytest.raises(RuntimeError, match="join failed"):+ await _create_on(chats, chats.service, agent, bridge_id)+ room = await _create_on(chats, chats.service, agent, bridge_id)+ again = await _create(chats, [agent], bridge_id)++ assert again.status_code == 200, again.text+ assert again.json()["chat"]["roomId"] == room.id+ assert len(core.dm_calls) == 1+++async def test_a_retry_after_a_failed_bridge_invite_puts_the_bridge_in(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)+ provisioning = chats.room_service._provisioning+ invite = provisioning.invite_to_room+ bridge_invites: list[str] = []+ failures = [RuntimeError("invite failed")]++ async def failing_invite(room_id: str, user_id: str) -> None:+ if user_id == "@slack-bot:switch.test":+ if failures:+ raise failures.pop()+ bridge_invites.append(room_id)+ await invite(room_id, user_id)++ monkeypatch.setattr(provisioning, "invite_to_room", failing_invite)++ with pytest.raises(RuntimeError, match="invite failed"):+ await _create_on(chats, chats.service, agent, bridge_id)+ assert core.users_added == []+ room = await _create_on(chats, chats.service, agent, bridge_id)++ assert bridge_invites == [room.transport_room_id]+ assert core.users_added == [["alice.s"]]+ assert len(core.dm_calls) == 1diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.pyindex 269e096ae..c597c323a 100644--- a/core/tests/switch_core/gateway/test_chats_groups.py+++ b/core/tests/switch_core/gateway/test_chats_groups.py@@ -919,23 +919,10 @@ def _second_process(chats: _Harness) -> ChatService:async def test_one_create_on_two_processes_makes_one_room(- chats: _Harness, monkeypatch: pytest.MonkeyPatch+ chats: _Harness,) -> None:agent = await chats.agent("helper", owner=chats.alice)other = _second_process(chats)- both_looked = asyncio.Barrier(2)- for service in (chats.service, other):- look = service._room_of_operation-- async def look_then_wait(- session: AsyncSession, operation_id: str, look=look- ) -> Room | None:- found = await look(session, operation_id)- if found is None:- await both_looked.wait()- return found-- monkeypatch.setattr(service, "_room_of_operation", look_then_wait)def create(service: ChatService) -> Any:return service.create_chat(