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
Add buddy setup cards that continue the chat in Slack
raullopez-sandbox77cb100700a2
diff --git a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts b/console/apps/switch-console-desktop/src/main/core/chats/controller.tsindex 1e9757f9e..959c08360 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/controller.ts@@ -168,6 +168,8 @@ export const chatsController = createRPCController({name: string | null;requestId: string;greeting: string | null;+ /** Open the chat in this messaging app connection instead of in Switch. */+ bridgeId?: string | null;kind?: 'group';}): Promise<ChatSummary> => {const chat = await onServer(params.serverId, (server) => createChat(server, params));diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.tsindex c7cac190d..b6ce6fdce 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts@@ -110,6 +110,25 @@ describe('createChat', () => {});});+ it('sends bridgeId only when one is given', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ vi.mocked(gatewayFetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ chat: row('room-new', 'direct') }), { status: 200 })+ );+ await createChat(server, {+ agentIds: ['agent-1'],+ name: null,+ requestId: 'req-1',+ greeting: 'Hi',+ bridgeId: 'bridge-1',+ });+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats', {+ authenticated: true,+ method: 'POST',+ body: { requestId: 'req-1', agentId: 'agent-1', greeting: 'Hi', bridgeId: 'bridge-1' },+ });+ });+it('asks for a group of one agent when kind is group', async () => {const server = { id: 'server-1' } as SwitchServer;vi.mocked(gatewayFetch).mockResolvedValueOnce(diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.tsindex 97922a01c..2c76fa287 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts@@ -129,6 +129,7 @@ export async function createChat(name: string | null;requestId: string;greeting: string | null;+ bridgeId?: string | null;/** `group` makes a group even of one agent and nobody else. */kind?: 'group';}@@ -142,6 +143,7 @@ export async function createChat(if (input.memberUserIds) body.memberUserIds = input.memberUserIds;if (input.name) body.name = input.name;if (input.greeting !== null) body.greeting = input.greeting;+ if (input.bridgeId) body.bridgeId = input.bridgeId;if (input.kind) body.kind = input.kind;return (await json(server, '/chats', chatCreatedSchema, { method: 'POST', body })).chat;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsxindex 53a8db95e..d6766d578 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx@@ -1,6 +1,6 @@import { Lock, UserPlus } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect, useRef, useState } from 'react';+import { type ReactNode, useEffect, useRef, useState } from 'react';import { Button } from '@renderer/lib/ui/button';import { SERVER_TOO_OLD_FOR_ACTIVITY } from '@shared/core/chats/activity';import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';@@ -72,9 +72,12 @@ const Notice = ({ icon, title, body }: { icon: React.ReactNode; title: string; bexport const ChatPanel = observer(function ChatPanel({serverId,roomId,+ afterMessages,}: {serverId: string;roomId: string;+ /** Drawn under the conversation, as switch-buddy's setup cards. */+ afterMessages?: ReactNode;}) {const timeline = chatsStore.timelines.get(serverId, roomId);const chat = chatsStore.chat(roomId);@@ -180,6 +183,7 @@ export const ChatPanel = observer(function ChatPanel({onReply={setReplyTo}/>)}+ {timeline.loaded && afterMessages}{timeline.loaded && timeline.messages.length === 0 && timeline.pending.length === 0 && (<p className="mt-10 text-center text-sm text-foreground-muted">No messages yet. Say what you need below.diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsxindex 4ec456a07..0b1ed8dfa 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx@@ -10,6 +10,8 @@ import { directChats } from '@renderer/features/chats/start-direct-chat';import { chatsStore } from '@renderer/features/chats/stores/chats';import { RoomListRow } from '@renderer/features/sidebar/main-section';import { SidebarItemMiniButton } from '@renderer/features/sidebar/sidebar-primitives';+import { isBuddy } from '@renderer/features/switch-buddy/buddy-identity';+import { BuddySetupCards } from '@renderer/features/switch-buddy/buddy-setup-cards';import { EmbeddedRoom } from '@renderer/features/switch-rooms/view';import { isConsoleDirectChatSummary } from '@renderer/features/switch-servers/room-filters';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';@@ -325,7 +327,21 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag<EmbeddedRoom roomId={shownRoom} />) : roomId ? (<>- <ChatPanel key={`${serverId}:${roomId}`} serverId={serverId} roomId={roomId} />+ <ChatPanel+ key={`${serverId}:${roomId}`}+ serverId={serverId}+ roomId={roomId}+ afterMessages={+ isBuddy(agent) ? (+ <BuddySetupCards+ serverId={serverId}+ workspaceId={workspaceId}+ agentId={agentId}+ roomId={roomId}+ />+ ) : null+ }+ /><divaria-hiddenclassName="pointer-events-none absolute inset-x-0 top-0 z-10 h-6 bg-linear-to-b from-background to-transparent"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.tsxnew file mode 100644index 000000000..e70ba951f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx@@ -0,0 +1,215 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { observer } from 'mobx-react-lite';+import { useState } from 'react';+import { chatsStore } from '@renderer/features/chats/stores/chats';+import { offerAccountLinkAfterConnect } from '@renderer/features/switch-servers/offer-account-link';+import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';+import { BridgeIcon } from '@renderer/lib/components/bridge-icon';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { reportOpenAttempt } from '@renderer/lib/open-external';+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';+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';++/**+ * The setup cards under the greeting in the buddy's Welcome chat: pick Slack,+ * connect it, link your account, then continue with the buddy in a private+ * Slack channel. Drawn only in the Welcome chat.+ */+export const BuddySetupCards = observer(function BuddySetupCards({+ serverId,+ workspaceId,+ agentId,+ roomId,+}: {+ serverId: string;+ workspaceId: string;+ agentId: string;+ roomId: string;+}) {+ const chat = chatsStore.chat(roomId);+ if (!chat || chat.name !== BUDDY_CHAT_NAME || chat.bridgeType !== null) return null;+ return <Cards serverId={serverId} workspaceId={workspaceId} agentId={agentId} />;+});++const Cards = observer(function Cards({+ serverId,+ workspaceId,+ agentId,+}: {+ serverId: string;+ workspaceId: string;+ agentId: string;+}) {+ const queryClient = useQueryClient();+ const showConnect = useShowModal('connectMessagingAppModal');+ const [picked, setPicked] = useState(false);+ const [creating, setCreating] = useState(false);+ const [createError, setCreateError] = useState<string | null>(null);++ const bridgesQuery = useQuery({+ queryKey: ['remote-bridges', workspaceId],+ queryFn: () => rpc.workspaces.listBridges(workspaceId),+ });+ const chatsQuery = useQuery({+ queryKey: ['buddy-handoff-chats', serverId],+ queryFn: () => rpc.chats.list(serverId),+ });+ const ids = useMyIdentities(workspaceId);+ const step = buddySetupStep({+ agentId,+ bridges: bridgesQuery.data ?? null,+ identities: ids.identities,+ chats: chatsQuery.data ?? null,+ failed: bridgesQuery.isError || chatsQuery.isError || ids.error != null,+ });+ const retry = () => {+ void bridgesQuery.refetch();+ void chatsQuery.refetch();+ ids.refresh();+ };++ const doneRoomId = step.kind === 'done' ? step.roomId : null;+ const roomQuery = useQuery({+ queryKey: ['buddy-handoff-room', workspaceId, doneRoomId],+ queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId, roomId: doneRoomId as string }),+ enabled: doneRoomId !== null,+ });+ const channelUrl = roomQuery.data?.externalChannelUrl ?? null;+ const openSlack = (url: string) =>+ void reportOpenAttempt(+ rpc.switchRooms.openRoomChannel({ serverId, channelUrl: url }),+ 'Could not open Slack',+ url+ );++ const create = async (bridge: RemoteBridge) => {+ setCreating(true);+ setCreateError(null);+ try {+ await continueBuddyInSlack(serverId, { agentId }, bridge.id);+ await queryClient.invalidateQueries({ queryKey: ['buddy-handoff-chats', serverId] });+ } catch (cause) {+ setCreateError(failureText(cause, 'Switch did not answer.'));+ } finally {+ setCreating(false);+ }+ };++ const slackIcon = <BridgeIcon bridgeType="slack" className="size-4" />;+ const pastChoice =+ picked || step.kind === 'link' || step.kind === 'create' || step.kind === 'done';++ return (+ <div className="mt-4 flex flex-col gap-2" data-testid="buddy-setup-cards">+ <Alert>+ <AlertTitle>Where does your team chat?</AlertTitle>+ <AlertDescription>Using something else? Just tell me below.</AlertDescription>+ <AlertAction>+ <Button+ size="sm"+ variant={pastChoice ? 'default' : 'outline'}+ onClick={() => setPicked(true)}+ >+ {slackIcon}+ Slack+ </Button>+ </AlertAction>+ </Alert>++ {pastChoice && step.kind === 'loading' && (+ <Alert>+ <Spinner size="sm" />+ <AlertTitle>Checking Slack…</AlertTitle>+ </Alert>+ )}++ {pastChoice && step.kind === 'unknown' && (+ <Alert variant="destructive">+ <AlertTitle>Couldn’t check Slack</AlertTitle>+ <AlertDescription>Switch did not answer.</AlertDescription>+ <AlertAction>+ <Button size="sm" variant="outline" onClick={retry}>+ Retry+ </Button>+ </AlertAction>+ </Alert>+ )}++ {pastChoice && step.kind === 'connect' && (+ <Alert>+ <AlertTitle>Connect Slack</AlertTitle>+ <AlertDescription>Add Slack to your Switch workspace.</AlertDescription>+ <AlertAction>+ <Button size="sm" onClick={() => showConnect({ serverId, onClosed: retry })}>+ Connect Slack+ </Button>+ </AlertAction>+ </Alert>+ )}++ {step.kind === 'link' && (+ <Alert>+ <AlertTitle>Link your Slack account</AlertTitle>+ <AlertDescription>So I recognise you in {step.bridge.displayName}.</AlertDescription>+ <AlertAction>+ <Button+ size="sm"+ onClick={() =>+ offerAccountLinkAfterConnect(workspaceId, {+ bridgeId: step.bridge.id,+ displayName: step.bridge.displayName,+ directorySearchSupported: step.bridge.directorySearchSupported,+ })+ }+ >+ Link account+ </Button>+ </AlertAction>+ </Alert>+ )}++ {step.kind === 'create' && (+ <Alert variant={createError ? 'destructive' : 'default'}>+ <AlertTitle>Continue in Slack</AlertTitle>+ <AlertDescription>+ {createError ??+ `This creates a private Slack channel with you and switch-buddy in ${step.bridge.displayName}.`}+ </AlertDescription>+ <AlertAction>+ <Button size="sm" disabled={creating} onClick={() => void create(step.bridge)}>+ {creating && <Spinner size="sm" />}+ {createError ? 'Try again' : 'Create channel and continue'}+ </Button>+ </AlertAction>+ </Alert>+ )}++ {step.kind === 'done' && (+ <Alert>+ {slackIcon}+ <AlertTitle>Continued in Slack</AlertTitle>+ <AlertDescription>+ {channelUrl+ ? 'Our chat goes on there.'+ : roomQuery.isPending+ ? 'Looking up the Slack channel…'+ : 'Couldn’t get a link to the Slack channel. Find it in Slack.'}+ </AlertDescription>+ {channelUrl && (+ <AlertAction>+ <Button size="sm" onClick={() => openSlack(channelUrl)}>+ Open Slack+ </Button>+ </AlertAction>+ )}+ </Alert>+ )}+ </div>+ );+});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.tsnew file mode 100644index 000000000..04efb5d31--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';+import type { ChatSummary } from '@shared/core/chats/chats';+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';+import { buddySetupStep } from './buddy-setup-step';++const slack = { id: 'b-1', type: 'slack', status: 'active' } as RemoteBridge;+const linked = { bridgeId: 'b-1' } as LinkedIdentity;+const slackChat = {+ roomId: 'r-1',+ channelType: 'direct',+ bridgeType: 'slack',+ agents: [{ id: 'a-1' }],+} as ChatSummary;++const base = { agentId: 'a-1', bridges: [], identities: [], chats: [], failed: false };++describe('buddySetupStep', () => {+ it('waits for the reads, and says unknown when one failed, never not connected', () => {+ expect(buddySetupStep({ ...base, bridges: null })).toEqual({ kind: 'loading' });+ expect(buddySetupStep({ ...base, bridges: null, failed: true })).toEqual({ kind: 'unknown' });+ });++ it('walks connect, link, create', () => {+ expect(buddySetupStep(base)).toEqual({ kind: 'connect' });+ expect(buddySetupStep({ ...base, bridges: [{ ...slack, status: 'error' }] }).kind).toBe(+ 'connect'+ );+ expect(buddySetupStep({ ...base, bridges: [slack], identities: null })).toEqual({+ kind: 'loading',+ });+ expect(buddySetupStep({ ...base, bridges: [slack] })).toEqual({ kind: 'link', bridge: slack });+ expect(buddySetupStep({ ...base, bridges: [slack], identities: [linked] })).toEqual({+ kind: 'create',+ bridge: slack,+ });+ });++ 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',+ });+ expect(+ buddySetupStep({ ...base, chats: [{ ...slackChat, agents: [] }] as ChatSummary[] }).kind+ ).toBe('connect');+ });+});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.tsnew file mode 100644index 000000000..799d82f30--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts@@ -0,0 +1,44 @@+import type { ChatSummary } from '@shared/core/chats/chats';+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';++export type BuddySetupStep =+ | { kind: 'loading' }+ | { kind: 'unknown' }+ | { kind: 'connect' }+ | { kind: 'link'; bridge: RemoteBridge }+ | { kind: 'create'; bridge: RemoteBridge }+ | { kind: 'done'; roomId: string };++/**+ * 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".+ */+export function buddySetupStep({+ agentId,+ bridges,+ identities,+ chats,+ failed,+}: {+ agentId: string;+ bridges: RemoteBridge[] | null;+ identities: LinkedIdentity[] | null;+ chats: ChatSummary[] | null;+ failed: boolean;+}): BuddySetupStep {+ const handedOff = chats?.find(+ (chat) =>+ chat.channelType === 'direct' &&+ 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 (!identities) return { kind: 'loading' };+ if (!identities.some((identity) => identity.bridgeId === slack.id))+ return { kind: 'link', bridge: slack };+ return { kind: 'create', bridge: slack };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.tsindex 603d82e7f..6bc9fc5d6 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.ts@@ -4,7 +4,7 @@ import { platformLogoMarkdown } from '@renderer/features/chats/ui/platform-logo'const PLATFORMS: { type: string; name: string }[] = [{ type: 'slack', name: 'Slack' },{ type: 'teams', name: 'Microsoft Teams' },- { type: 'mattermost', name: 'Mattermost' },+ { type: 'discord', name: 'Discord' },{ type: 'telegram', name: 'Telegram' },];@@ -39,6 +39,15 @@ export function buddyWelcomeMessage({'- 🏠 Set up rooms where your team and agents work together','- 💬 Answer anything about Switch','',- 'Tell me which app your team uses, and I’ll walk you through connecting it.',+ 'Pick where your team chats below to get started.',].join('\n');}++/** What the buddy says first in the Slack channel it continues in, once setup is done. */+export function buddySlackOpener(firstName: string | null): string {+ return [+ `Hi${firstName ? ` ${firstName}` : ''}, setup is done: Slack is connected and this is our private channel. 🎉`,+ 'From here I can help you create agents and bring them into your team’s channels.',+ 'What do you mostly work on?',+ ].join('\n\n');+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.tsindex 2a2447355..202eb1324 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts@@ -26,16 +26,24 @@ vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({}));vi.mock('./buddy-intro-store', () => ({ buddyIntroStore: { skipped } }));vi.mock('./buddy-welcome-message', () => ({+ buddySlackOpener: () => 'opener',buddyWelcomeMessage: ({ firstName, agentName }: { firstName: string; agentName: string }) =>`welcome ${firstName} from ${agentName}`,}));-const { BUDDY_CHAT_NAME, openBuddyAfterOnboarding, openBuddyChat } = await import('./open-buddy');+const { BUDDY_CHAT_NAME, continueBuddyInSlack, openBuddyAfterOnboarding, openBuddyChat } =+ await import('./open-buddy');const buddy = { agentId: 'a-1', name: 'switch-buddy-max' };-function chat(roomId: string, name: string, agentId = 'a-1', channelType = 'direct') {- return { roomId, name, channelType, agents: [{ id: agentId }] };+function chat(+ roomId: string,+ name: string,+ agentId = 'a-1',+ channelType = 'direct',+ bridgeType: string | null = null+) {+ return { roomId, name, channelType, bridgeType, agents: [{ id: agentId }] };}beforeEach(() => {@@ -62,6 +70,7 @@ describe('openBuddyChat', () => {listChats.mockResolvedValue([chat('r-room', BUDDY_CHAT_NAME, 'a-1', 'channel_public'),chat('r-someone', BUDDY_CHAT_NAME, 'a-2'),+ chat('r-slack', BUDDY_CHAT_NAME, 'a-1', 'direct', 'slack'),chat('r-newest', 'Ideas'),chat('r-older', 'Notes'),]);@@ -160,3 +169,25 @@ describe('openBuddyAfterOnboarding', () => {expect(listChats).not.toHaveBeenCalled();});});++describe('continueBuddyInSlack', () => {+ it('asks once, under a request id fixed by the agent and the connection', async () => {+ createChat.mockResolvedValue(chat('r-slack', '', 'a-1', 'direct', 'slack'));++ await Promise.all([+ continueBuddyInSlack('srv-1', buddy, 'b-1'),+ continueBuddyInSlack('srv-1', buddy, 'b-1'),+ ]);+ await continueBuddyInSlack('srv-1', buddy, 'b-1');++ expect(createChat).toHaveBeenCalledTimes(2);+ expect(createChat).toHaveBeenCalledWith({+ serverId: 'srv-1',+ agentIds: ['a-1'],+ name: null,+ bridgeId: 'b-1',+ requestId: 'buddy-handoff:a-1:b-1',+ greeting: 'opener',+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.tsindex aec46e272..7ec21fa70 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts@@ -8,7 +8,7 @@ import type { ChatSummary } from '@shared/core/chats/chats';import { firstNameOf } from './buddy-identity';import { buddyIntroStore } from './buddy-intro-store';import { buddyPerson } from './buddy-person';-import { buddyWelcomeMessage } from './buddy-welcome-message';+import { buddySlackOpener, buddyWelcomeMessage } from './buddy-welcome-message';/** What the buddy's first chat is called, as on the board; it keeps it. */export const BUDDY_CHAT_NAME = 'Welcome';@@ -44,7 +44,11 @@ async function findOrMakeBuddyChat(): Promise<ChatSummary> {const agentId = agent.agentId;const direct = (await rpc.chats.list(serverId)).filter(- (chat) => chat.channelType === 'direct' && chat.agents.some((member) => member.id === agentId)+ (chat) =>+ chat.channelType === 'direct' &&+ // A chat continued in a messaging app is not the Welcome chat.+ chat.bridgeType === null &&+ chat.agents.some((member) => member.id === agentId));const existing = direct.find((chat) => chat.name === BUDDY_CHAT_NAME) ?? direct[0];if (existing) return existing;@@ -108,3 +112,42 @@ export async function openBuddyAfterOnboarding(buddyIntroStore.skipped();appState.navigation.navigate('switchBuddy', { serverId });}++/**+ * The same for every attempt to continue with the buddy on one Slack+ * connection, so a double click, a second window or a reopened Console all+ * land on the one chat the server made for the first.+ */+export function buddyHandoffRequestId(agentId: string, bridgeId: string): string {+ return `buddy-handoff:${agentId}:${bridgeId}`;+}++/** The handoffs under way, by request id: one at a time each. */+const handingOff = new Map<string, Promise<ChatSummary>>();++/** Makes the person's private Slack channel with their buddy, the buddy opening it. */+export function continueBuddyInSlack(+ serverId: string,+ agent: { agentId: string },+ bridgeId: string+): Promise<ChatSummary> {+ const requestId = buddyHandoffRequestId(agent.agentId, bridgeId);+ const running = handingOff.get(requestId);+ if (running) return running;+ const made = rpc.chats+ .create({+ serverId,+ agentIds: [agent.agentId],+ name: null,+ bridgeId,+ requestId,+ greeting: buddySlackOpener(firstNameOf(buddyPerson(serverId).name)),+ })+ .then((chat) => {+ chatsStore.add(serverId, chat);+ return chat;+ })+ .finally(() => handingOff.delete(requestId));+ handingOff.set(requestId, made);+ return made;+}