Skip to content

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

feat(console): add an agent to a new room or an existing one from its page

raullopez-sandbox6afcaec7c07e
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.tsx
index 996f43771..6085e8016 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
@@ -15,6 +15,12 @@ import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { showModal } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@renderer/lib/ui/dropdown-menu';
import { EmptyState } from '@renderer/lib/ui/empty-state';
import type { ChatSummary } from '@shared/core/chats/chats';
import { isCloudMachine, type ManagedAgentView } from '@shared/core/managed-agents/managed-agents';
@@ -54,11 +60,14 @@ function Section({
title,
addLabel,
onAdd,
+ addChoices,
children,
}: {
title: string;
addLabel: string;
onAdd: () => void;
+ /** Ways to add, offered as a menu on the button instead of `onAdd`; null for just `onAdd`. */
+ addChoices: { label: string; onSelect: () => void }[] | null;
children: ReactNode;
}) {
const [open, setOpen] = useState(true);
@@ -75,9 +84,28 @@ function Section({
<Chevron className="size-3.5" />
{title}
</button>
- <SidebarItemMiniButton aria-label={addLabel} title={addLabel} onClick={onAdd}>
- <Plus className="size-3.5" />
- </SidebarItemMiniButton>
+ {addChoices ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <SidebarItemMiniButton aria-label={addLabel} title={addLabel}>
+ <Plus className="size-3.5" />
+ </SidebarItemMiniButton>
+ }
+ />
+ <DropdownMenuContent align="end">
+ {addChoices.map((choice) => (
+ <DropdownMenuItem key={choice.label} onClick={choice.onSelect}>
+ {choice.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <SidebarItemMiniButton aria-label={addLabel} title={addLabel} onClick={onAdd}>
+ <Plus className="size-3.5" />
+ </SidebarItemMiniButton>
+ )}
</div>
{open && children}
</section>
@@ -172,7 +200,12 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
selected={section}
onSelect={(chosen) => setParams({ section: chosen })}
/>
- <Section title="Direct chats" addLabel="New chat" onAdd={() => void newChat()}>
+ <Section
+ title="Direct chats"
+ addLabel="New chat"
+ onAdd={() => void newChat()}
+ addChoices={null}
+ >
{chatsStore.listError && <Note>{chatsStore.listError}</Note>}
{direct.map((chat) => (
<ChatRow
@@ -187,8 +220,23 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
</Section>
<Section
title="Rooms"
- addLabel="Create room"
- onAdd={() => showModal('createRoomModal', { serverId })}
+ addLabel="Add to a room"
+ onAdd={() => showModal('createRoomModal', { serverId, agentId })}
+ addChoices={[
+ {
+ label: 'New room',
+ onSelect: () => showModal('createRoomModal', { serverId, agentId }),
+ },
+ {
+ label: 'Add to existing room',
+ onSelect: () =>
+ showModal('addAgentToRoomModal', {
+ workspaceId,
+ switchAgentId: agentId,
+ agentName: managedAgentLabel(agent),
+ }),
+ },
+ ]}
>
{roomsError && <Note>{roomsError}</Note>}
{rooms.map((room) => (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
index f28c63709..455b27087 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
@@ -1,7 +1,9 @@
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
+import { chatsStore } from '@renderer/features/chats/stores/chats';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { useReadableRoomsInWorkspace } from '@renderer/features/switch-servers/use-listed-rooms';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
import { ChosenRoomTile, RoomPickerRow } from '@renderer/lib/components/room-picker';
import { failureText } from '@renderer/lib/errors/describe-failure';
@@ -16,6 +18,7 @@ import {
DialogTitle,
} from '@renderer/lib/ui/dialog';
import { Field, FieldLabel } from '@renderer/lib/ui/field';
+import { addAgentToRoom, mayAddToRoom } from './add-agent-to-room';
type Props = BaseModalProps<void> & {
workspaceId: string;
@@ -59,8 +62,12 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
// Every room the server let us see, not only the ones this user created: an
// agent's usefulness is mostly in rooms someone else set up, and a picker that
// omitted them made those rooms unreachable from here entirely.
+ // Only rooms the user may add to: a chat they manage, a room they own or administer.
const candidates: Candidate[] = useReadableRoomsInWorkspace(workspaceId)
.filter((room) => !alreadyIn.has(room.id) && !selected.some((s) => s.id === room.id))
+ .filter((room) =>
+ mayAddToRoom(chatsStore.chat(room.id), switchRoomsStore.canDeleteRoom(workspaceId, room))
+ )
.map((room) => ({ id: room.id, name: room.name, bridgeType: room.bridgeType }));
const nothingToAdd = candidates.length === 0 && selected.length === 0;
@@ -70,13 +77,18 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
setCloseGuard(true);
setError(null);
try {
+ const serverId = workspacesStore.serverIdFor(workspaceId);
+ if (!serverId) throw new Error('This workspace’s server is not known yet.');
for (const room of selected) {
- await rpc.workspaces.addRoomAgents({
- workspaceId,
- roomId: room.id,
- agentIds: [switchAgentId],
- direction: 'room_to_agents',
- });
+ await addAgentToRoom(
+ {
+ chat: (roomId) => chatsStore.chat(roomId),
+ addChatAgent: (input) => rpc.chats.addAgent(input),
+ addRoomAgents: (input) => rpc.workspaces.addRoomAgents(input),
+ chatChanged: (id, chat) => chatsStore.add(id, chat),
+ },
+ { serverId, workspaceId, roomId: room.id, agentId: switchAgentId }
+ );
}
await Promise.all([
switchRoomsStore.fetchAgentRooms(workspaceId, switchAgentId, { force: true }),
@@ -140,7 +152,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
)}
{nothingToAdd && !membershipUnknown && (
<p className="mt-1 text-xs text-foreground-muted">
- {agentName} is already in every room you can see in this workspace.
+ {agentName} is already in every room you can add it to in this workspace.
</p>
)}
</Field>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/add-agent-to-room.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/add-agent-to-room.test.ts
new file mode 100644
index 000000000..1ea027bca
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/add-agent-to-room.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { ChatSummary } from '@shared/core/chats/chats';
+import { addAgentToRoom, mayAddToRoom } from './add-agent-to-room';
+
+const group = {
+ roomId: 'g',
+ channelType: 'channel_private',
+ bridgeType: null,
+ agents: [],
+ canManage: true,
+} as unknown as ChatSummary;
+
+function api(chat: ChatSummary | undefined) {
+ return {
+ chat: () => chat,
+ addChatAgent: vi.fn(async () => group),
+ addRoomAgents: vi.fn(async () => undefined),
+ chatChanged: vi.fn(),
+ };
+}
+
+describe('addAgentToRoom', () => {
+ const input = { serverId: 's', workspaceId: 'w', roomId: 'g', agentId: 'a1' };
+
+ it('adds to a group chat through the chats API', async () => {
+ const calls = api(group);
+ await addAgentToRoom(calls, input);
+ expect(calls.addChatAgent).toHaveBeenCalledWith({ serverId: 's', roomId: 'g', agentId: 'a1' });
+ expect(calls.chatChanged).toHaveBeenCalledWith('s', group);
+ expect(calls.addRoomAgents).not.toHaveBeenCalled();
+ });
+
+ it('adds to a bridged room through the rooms API, and passes on a refusal', async () => {
+ const calls = api({ ...group, bridgeType: 'slack' });
+ await addAgentToRoom(calls, input);
+ expect(calls.addRoomAgents).toHaveBeenCalledWith({
+ workspaceId: 'w',
+ roomId: 'g',
+ agentIds: ['a1'],
+ direction: 'room_to_agents',
+ });
+ calls.addRoomAgents.mockRejectedValueOnce(new Error('refused'));
+ await expect(addAgentToRoom(calls, input)).rejects.toThrow('refused');
+ });
+});
+
+describe('mayAddToRoom', () => {
+ it('asks the chat for a chat, and the room rule otherwise', () => {
+ expect(mayAddToRoom({ ...group, canManage: false }, true)).toBe(false);
+ expect(mayAddToRoom(group, false)).toBe(true);
+ expect(mayAddToRoom(undefined, false)).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/add-agent-to-room.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/add-agent-to-room.ts
new file mode 100644
index 000000000..606ef2088
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/add-agent-to-room.ts
@@ -0,0 +1,54 @@
+import { isConsoleGroupChatSummary } from '@renderer/features/switch-servers/room-filters';
+import type { ChatSummary } from '@shared/core/chats/chats';
+
+export type AddAgentToRoomApi = {
+ /** The chat behind a room, when it is one of the user's chats. */
+ chat: (roomId: string) => ChatSummary | undefined;
+ addChatAgent: (input: {
+ serverId: string;
+ roomId: string;
+ agentId: string;
+ }) => Promise<ChatSummary>;
+ addRoomAgents: (input: {
+ workspaceId: string;
+ roomId: string;
+ agentIds: string[];
+ direction: 'room_to_agents';
+ }) => Promise<unknown>;
+ /** Told the chat as the server returned it, once an agent joins a chat. */
+ chatChanged: (serverId: string, chat: ChatSummary) => void;
+};
+
+/**
+ * Puts an agent in a room through the API that owns it: the chats API for a
+ * Switch Console group chat, the rooms API for any other room. Throws the
+ * server's refusal.
+ */
+export async function addAgentToRoom(
+ api: AddAgentToRoomApi,
+ input: { serverId: string; workspaceId: string; roomId: string; agentId: string }
+): Promise<void> {
+ const chat = api.chat(input.roomId);
+ if (chat && isConsoleGroupChatSummary(chat)) {
+ api.chatChanged(
+ input.serverId,
+ await api.addChatAgent({
+ serverId: input.serverId,
+ roomId: input.roomId,
+ agentId: input.agentId,
+ })
+ );
+ return;
+ }
+ await api.addRoomAgents({
+ workspaceId: input.workspaceId,
+ roomId: input.roomId,
+ agentIds: [input.agentId],
+ direction: 'room_to_agents',
+ });
+}
+
+/** Whether the user may add to a room: a chat they manage, or a room they own or administer. */
+export function mayAddToRoom(chat: ChatSummary | undefined, canManageRoom: boolean): boolean {
+ return chat && isConsoleGroupChatSummary(chat) ? chat.canManage : canManageRoom;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
index 5f71bf246..ad5788ff9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
@@ -43,6 +43,8 @@ type CreateRoomModalArgs = {
/** Create on this server instead of the active one — for callers that are not
* driven by the sidebar's server scope, such as onboarding. */
serverId?: string;
+ /** An agent to start the room with, already picked: the room is made from its page. */
+ agentId?: string;
};
type Props = BaseModalProps<{ roomId: string }> & CreateRoomModalArgs;
@@ -54,6 +56,7 @@ type Props = BaseModalProps<{ roomId: string }> & CreateRoomModalArgs;
*/
export const CreateRoomModal = observer(function CreateRoomModal({
serverId: overrideServerId,
+ agentId: startingAgentId,
onSuccess,
onClose,
}: Props) {
@@ -139,6 +142,15 @@ export const CreateRoomModal = observer(function CreateRoomModal({
personParticipant
),
];
+ // The agent the room is made from starts picked, once the agents are read.
+ const [seeded, setSeeded] = useState(startingAgentId === undefined);
+ if (!seeded) {
+ const start = candidates.find((each) => each.kind === 'agent' && each.id === startingAgentId);
+ if (start) {
+ setSeeded(true);
+ setPicked((current) => [start, ...current.filter((each) => each.id !== start.id)]);
+ }
+ }
const agentIds = picked.filter((each) => each.kind === 'agent').map((each) => each.id);
const memberUserIds = picked.filter((each) => each.kind === 'person').map((each) => each.id);
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx
index 0456cb4b4..f60a8cf54 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx
@@ -370,3 +370,25 @@ it('follows the open direct chat into its room when it becomes a group, not an o
});
}
});
+
+it('offers a new room or an existing one from the Rooms section, with the agent picked', async () => {
+ const { showModal } = await import('@renderer/lib/modal/modal-provider');
+ vi.mocked(showModal).mockClear();
+ await act(async () => root.render(<AgentChats agent={AGENT} />));
+ const add = container.querySelector<HTMLButtonElement>('[aria-label="Add to a room"]')!;
+ await act(async () => add.click());
+ const items = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ expect(items().map((item) => item.textContent)).toEqual(['New room', 'Add to existing room']);
+ await act(async () => items()[0]!.click());
+ expect(showModal).toHaveBeenCalledWith('createRoomModal', {
+ serverId: 'server-1',
+ agentId: 'agent-1',
+ });
+ await act(async () => add.click());
+ await act(async () => items()[1]!.click());
+ expect(showModal).toHaveBeenCalledWith('addAgentToRoomModal', {
+ workspaceId: 'workspace-1',
+ switchAgentId: 'agent-1',
+ agentName: 'pm-agent',
+ });
+});