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): offer only the agents the viewer may add

raullopez-sandbox9147e6002296
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.ts
index b521ac86b..b0a24c232 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
@@ -47,6 +47,7 @@ import {
listChatMembers,
listChats,
listWorkspaceMembers,
+ listAgentCandidates,
removeChatAgent,
removeChatMember,
renameChat,
@@ -190,6 +191,9 @@ export const chatsController = createRPCController({
/** The people of a workspace on the server, who a chat can be opened to. */
workspaceMembers: (params: { serverId: string; tenantId: string }): Promise<WorkspaceMember[]> =>
onServer(params.serverId, (server) => listWorkspaceMembers(server, params.tenantId)),
+ /** The agents the viewer may add to a new chat (`roomId` null) or to that chat. */
+ agentCandidates: (params: { serverId: string; roomId: string | null }): Promise<string[]> =>
+ onServer(params.serverId, (server) => listAgentCandidates(server, params.roomId)),
messages: (params: {
serverId: string;
roomId: string;
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.ts
index cd20be15f..f46c78b75 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
@@ -7,6 +7,7 @@ import {
createChat,
fetchThreadMessages,
listWorkspaceMembers,
+ listAgentCandidates,
parseChatRows,
removeChatAgent,
sendChatMessage,
@@ -242,3 +243,20 @@ describe('fetchThreadMessages', () => {
);
});
});
+
+describe('listAgentCandidates', () => {
+ it('asks for a new chat without a room and for a chat with its id', async () => {
+ const server = { id: 'server-1' } as SwitchServer;
+ vi.mocked(gatewayFetch)
+ .mockResolvedValueOnce(new Response(JSON.stringify({ agentIds: ['a1'] }), { status: 200 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({ agentIds: [] }), { status: 200 }));
+ expect(await listAgentCandidates(server, null)).toEqual(['a1']);
+ expect(await listAgentCandidates(server, 'room 1')).toEqual([]);
+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/agent-candidates', {
+ authenticated: true,
+ });
+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/agent-candidates?roomId=room%201', {
+ authenticated: true,
+ });
+ });
+});
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.ts
index 1eb039da2..381766abb 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
@@ -29,6 +29,7 @@ import {
chatMemberListSchema,
type WorkspaceMember,
workspaceMemberSchema,
+ agentCandidatesSchema,
} from '@shared/core/chats/chats';
import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
@@ -208,6 +209,15 @@ export async function listWorkspaceMembers(
);
}
+/** The ids of the agents the viewer may add to a new chat (`roomId` null) or to that chat. */
+export async function listAgentCandidates(
+ server: SwitchServer,
+ roomId: string | null
+): Promise<string[]> {
+ const query = roomId === null ? '' : `?roomId=${encodeURIComponent(roomId)}`;
+ return (await json(server, `/chats/agent-candidates${query}`, agentCandidatesSchema)).agentIds;
+}
+
export async function sendChatMessage(
server: SwitchServer,
roomId: string,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index cf7950287..363aa9e71 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -269,10 +269,21 @@ const ChatAddParticipantPanel = observer(function ChatAddParticipantPanel({
queryFn: () => rpc.chats.workspaceMembers({ serverId, tenantId: tenantId as string }),
enabled: tenantId !== null,
});
+ const allowed = useQuery({
+ // Keyed by the chat's agents, so adding or removing one asks again.
+ queryKey: [
+ 'chat-agent-candidates',
+ serverId,
+ workspaceId,
+ chat.roomId,
+ chat.agents.map((agent) => agent.id).join(','),
+ ],
+ queryFn: () => rpc.chats.agentCandidates({ serverId, roomId: chat.roomId }),
+ });
const [adding, setAdding] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const candidates = [
- ...addableAgents(agents.data ?? [], chat.agents).map((agent) =>
+ ...addableAgents(agents.data ?? [], allowed.data ?? []).map((agent) =>
agentParticipant(agent, knownAgentTypeDisplayName(agent.knownAgentType) ?? 'Agent')
),
...addablePeople(roster.data ?? [], memberIds).map(personParticipant),
@@ -306,12 +317,12 @@ const ChatAddParticipantPanel = observer(function ChatAddParticipantPanel({
if (picked) void add(picked);
}}
serverId={serverId}
- loading={agents.isPending || (tenantId !== null && roster.isPending)}
+ loading={agents.isPending || allowed.isPending || (tenantId !== null && roster.isPending)}
/>
{error !== null && <p className="text-xs text-destructive">{error}</p>}
- {agents.isError && (
+ {(agents.isError || allowed.isError) && (
<p className="text-xs text-destructive">
- {failureText(agents.error, 'Could not list the agents.')}
+ {failureText(agents.error ?? allowed.error, 'Could not list the agents.')}
</p>
)}
{tenantId === null ? (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts
index fbde1b86e..38982572b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts
@@ -42,7 +42,9 @@ describe('addablePeople', () => {
});
describe('addableAgents', () => {
- it('offers only the agents not in the chat yet', () => {
- expect(addableAgents([{ id: 'a1' }, { id: 'a2' }], [{ id: 'a1' }])).toEqual([{ id: 'a2' }]);
+ it('offers only the agents the server names as candidates', () => {
+ expect(addableAgents([{ id: 'a1' }, { id: 'a2' }, { id: 'a3' }], ['a2', 'gone'])).toEqual([
+ { id: 'a2' },
+ ]);
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts
index 3f63ab6bc..115ad46ab 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts
@@ -36,11 +36,11 @@ export function addablePeople<T extends { userId: string; serviceAccount: boolea
return roster.filter((person) => !person.serviceAccount && !memberIds.has(person.userId));
}
-/** The agents not in the chat yet: one already in is not offered again. */
-export function addableAgents<T extends { id: string }>(
- agents: T[],
- inChat: { id: string }[]
-): T[] {
- const ids = new Set(inChat.map((agent) => agent.id));
- return agents.filter((agent) => !ids.has(agent.id));
+/**
+ * The agents the server says the viewer may add (`GET /chats/agent-candidates`):
+ * one the viewer may not use, or already in the chat, is not offered.
+ */
+export function addableAgents<T extends { id: string }>(agents: T[], candidateIds: string[]): T[] {
+ const ids = new Set(candidateIds);
+ return agents.filter((agent) => ids.has(agent.id));
}
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 118392fd9..f893c8e5c 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
@@ -7,7 +7,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';
import { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
-import { addablePeople } from '@renderer/features/switch-rooms/room-labels';
+import { addableAgents, addablePeople } from '@renderer/features/switch-rooms/room-labels';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
import { agentProviderLabelFor } from '@renderer/lib/components/agent-picker';
@@ -92,6 +92,11 @@ export const CreateRoomModal = observer(function CreateRoomModal({
queryFn: () => rpc.chats.workspaceMembers({ serverId, tenantId: tenantId as string }),
enabled: tenantId !== null,
});
+ const allowedQuery = useQuery({
+ queryKey: ['chat-agent-candidates', serverId, workspaceId, null],
+ queryFn: () => rpc.chats.agentCandidates({ serverId, roomId: null }),
+ enabled: serverId !== '',
+ });
const managedQuery = useManagedAgents(serverId || null);
// Only a running bridge allowed to create channels can back a new room.
@@ -109,17 +114,18 @@ export const CreateRoomModal = observer(function CreateRoomModal({
: (knownAgentTypeDisplayName(knownType) ?? agentProviderLabelFor(agentId, workspaceId));
// A bridged room is driven from this install, so it takes only the agents
// this install registered or manages, and no people at creation. A Switch
- // Console room is driven through the server: any agent the workspace shows,
- // the server refusing one the person may not use, and its people.
- const agentCandidates = (agentsQuery.data ?? []).filter(
- (remote) =>
- !selectedBridge ||
- (workspaceId !== null &&
- (managedProviders.has(remote.id) ||
- agentsStore
- .agentsInWorkspace(workspaceId)
- .some((local) => local.switchAgentId === remote.id)))
- );
+ // Console room is driven through the server: the agents the server says the
+ // person may use, and its people.
+ const agentCandidates = selectedBridge
+ ? (agentsQuery.data ?? []).filter(
+ (remote) =>
+ workspaceId !== null &&
+ (managedProviders.has(remote.id) ||
+ agentsStore
+ .agentsInWorkspace(workspaceId)
+ .some((local) => local.switchAgentId === remote.id))
+ )
+ : addableAgents(agentsQuery.data ?? [], allowedQuery.data ?? []);
const candidates: Participant[] = [
...agentCandidates.map((agent) =>
agentParticipant(agent, providerLabel(agent.id, agent.knownAgentType))
@@ -248,14 +254,18 @@ export const CreateRoomModal = observer(function CreateRoomModal({
picked={picked}
onChange={setPicked}
serverId={serverId || null}
- loading={agentsQuery.isLoading || rosterQuery.isLoading}
+ loading={
+ agentsQuery.isLoading ||
+ rosterQuery.isLoading ||
+ (!selectedBridge && allowedQuery.isLoading)
+ }
/>
<span className="text-xs text-foreground-muted">
Agents answer only when someone @-mentions them.
</span>
- {agentsQuery.isError && (
+ {(agentsQuery.isError || (!selectedBridge && allowedQuery.isError)) && (
<p className="text-xs text-destructive">
- {failureText(agentsQuery.error, 'Could not load the agents.')}
+ {failureText(agentsQuery.error ?? allowedQuery.error, 'Could not load the agents.')}
</p>
)}
{rosterQuery.isError && (
diff --git a/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts b/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts
index b9149c0cf..3e88468a4 100644
--- a/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts
@@ -118,6 +118,8 @@ export const workspaceMemberSchema = z
serviceAccount: service_account ?? false,
}));
export type WorkspaceMember = z.infer<typeof workspaceMemberSchema>;
+/** The agents the viewer may add to a new chat, or to one they manage. */
+export const agentCandidatesSchema = z.object({ agentIds: z.array(z.string()) });
export const chatUploadSchema = z.object({
uploadId: z.string(),
uri: z.string(),
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 92f0a4a4b..6949d7405 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -1045,19 +1045,36 @@ class ChatService:
agent = await self._agent_store.get(session, agent_id)
if agent is None or agent.tenant_id != tenant_id:
raise ChatError(404, "AGENT_NOT_FOUND", "Agent not found.")
- if not allows_on_behalf_of(
- parse_policy(agent.addressing_policy),
- room_id=room_id,
- group_id=group_id,
- user_id=user.id,
- external_user_ids=[],
- owner_user_id=agent.owner_id,
- ):
+ if not _may_use(agent, user, room_id=room_id, group_id=group_id):
raise ChatError(
403, "AGENT_NOT_ALLOWED", "You may not chat with this agent here."
)
return agent
+ async def agent_candidates(
+ self, session: AsyncSession, tenant_id: str, user: User, room_id: str | None
+ ) -> list[str]:
+ """The ids of the agents the user could add: to a new chat when
+ `room_id` is None, else to that room, which they must manage, less
+ the agents already in it. The rule `_require_may_use_agent` applies."""
+ target_room_id, group_id, present = "", None, set[str]()
+ if room_id is not None:
+ room = await self._room(session, tenant_id, room_id)
+ await self._require_manager(session, tenant_id, user, room)
+ target_room_id, group_id = room.id, room.group_id
+ present = set(await self._room_store.get_agent_ids(session, room.id))
+ agents = (
+ await session.execute(
+ select(Agent).where(Agent.tenant_id == tenant_id).order_by(Agent.name)
+ )
+ ).scalars()
+ return [
+ agent.id
+ for agent in agents
+ if agent.id not in present
+ and _may_use(agent, user, room_id=target_room_id, group_id=group_id)
+ ]
+
def _operation_id(self, tenant_id: str, user_id: str, request_id: str) -> str:
return str(uuid.uuid5(_CHATS_NAMESPACE, f"{tenant_id}:{user_id}:{request_id}"))
@@ -1623,6 +1640,19 @@ class ChatService:
return f"{prefix} {body}" if body else prefix
+def _may_use(agent: Agent, user: User, *, room_id: str, group_id: str | None) -> bool:
+ """Whether `user` may address `agent` themselves in `room_id` ("" for a
+ room not made yet), with no claimed platform account consulted."""
+ return allows_on_behalf_of(
+ parse_policy(agent.addressing_policy),
+ room_id=room_id,
+ group_id=group_id,
+ user_id=user.id,
+ external_user_ids=[],
+ owner_user_id=agent.owner_id,
+ )
+
+
def _owns_agent_in_room(user_id: str) -> ColumnElement[bool]:
"""True for a `Room` row holding an agent `user_id` owns."""
return exists().where(
diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.py
index 5929812d4..d1d8bb0a8 100644
--- a/core/switch_core/gateway/chats.py
+++ b/core/switch_core/gateway/chats.py
@@ -302,6 +302,25 @@ async def chat_events_stream(
)
+class AgentCandidates(CamelModel):
+ agent_ids: list[str]
+
+
[email protected]("/agent-candidates", response_model=AgentCandidates)
+async def agent_candidates(
+ user: CurrentUser,
+ service: Service,
+ room_id: Annotated[str | None, Query(alias="roomId")] = None,
+) -> AgentCandidates:
+ """The agents the caller could add to a new chat, or with `roomId` to
+ that chat, which they must manage."""
+ tenant_id = require_tenant_id()
+ async with tenant_session(service.session_factory, tenant_id) as session:
+ return AgentCandidates(
+ agent_ids=await service.agent_candidates(session, tenant_id, user, room_id)
+ )
+
+
@router.get("/activity/events")
async def chat_activity_stream(
user: CurrentUser, service: Service
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index 3ea255a13..905973cda 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import asyncio
from collections.abc import Callable
+from typing import Any
import httpx
import pytest
@@ -599,6 +600,37 @@ async def test_a_manager_removes_an_agent_they_may_no_longer_use(
assert await _agent_ids(chats, room_id) == {helper.id}
+async def _candidates(chats: _Harness, user: User, room_id: str | None) -> Any:
+ return await chats.client.get(
+ "/chats/agent-candidates",
+ params={"roomId": room_id} if room_id is not None else {},
+ headers=chats.as_user(user),
+ )
+
+
+async def test_agent_candidates_are_the_agents_the_caller_may_add(
+ chats: _Harness,
+) -> None:
+ mine = await chats.agent("mine", owner=chats.alice)
+ spare = await chats.agent("spare", owner=chats.alice)
+ private = await chats.agent("private", owner=chats.bob)
+ await _set_policy(chats, private, {"rules": [{"owner": True, "users": []}]})
+ scoped = await chats.agent("scoped", owner=chats.bob)
+ room_id = await chats.new_chat(chats.alice, mine, "c1")
+ await _set_policy(chats, scoped, {"rules": [{"rooms": [room_id]}]})
+
+ new_chat = await _candidates(chats, chats.alice, None)
+ assert new_chat.status_code == 200, new_chat.text
+ assert set(new_chat.json()["agentIds"]) == {mine.id, spare.id}
+
+ in_room = await _candidates(chats, chats.alice, room_id)
+ assert set(in_room.json()["agentIds"]) == {spare.id, scoped.id}
+
+ outsider = await _candidates(chats, chats.bob, room_id)
+ assert outsider.status_code == 403
+ assert _code(outsider) == "NOT_A_MANAGER"
+
+
# ── Mentions ─────────────────────────────────────────────────────────────────