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
feat(console): add group chat support to chats data layer
raullopez-sandbox1766d8dc3324
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 a2e5882c6..479e6bf6d 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@@ -33,13 +33,16 @@ import {} from './chat-streams';import { generateChatTitle } from './chat-title';import {+ addChatAgent,answerChatApproval,archiveChat,createChat,fetchChatMedia,fetchChatMessages,fetchRoomActivity,+ fetchThreadMessages,listChats,+ removeChatAgent,renameChat,sendChatControl,sendChatMessage,@@ -147,19 +150,33 @@ export const chatsController = createRPCController({/** `greeting`: what the chat's one agent, the caller's own, says as it joins, in place of its usual line. */create: async (params: {serverId: string;- agentIds: string[];+ agentIds?: string[];+ memberUserIds?: string[];name: string | null;requestId: string;greeting: string | null;}): Promise<ChatSummary> => {const chat = await onServer(params.serverId, (server) => createChat(server, params));- if (params.agentIds.length === 1)+ const agentIds = params.agentIds ?? [];+ if (agentIds.length === 1)void warmChat(- { serverId: params.serverId, agentId: params.agentIds[0], roomId: chat.roomId },+ { serverId: params.serverId, agentId: agentIds[0], roomId: chat.roomId },false);return chat;},+ addAgent: (params: {+ serverId: string;+ roomId: string;+ agentId: string;+ }): Promise<ChatSummary> =>+ onServer(params.serverId, (server) => addChatAgent(server, params.roomId, params.agentId)),+ removeAgent: (params: {+ serverId: string;+ roomId: string;+ agentId: string;+ }): Promise<void> =>+ onServer(params.serverId, (server) => removeChatAgent(server, params.roomId, params.agentId)),messages: (params: {serverId: string;roomId: string;@@ -179,8 +196,23 @@ export const chatsController = createRPCController({body: input.body,threadRootId: input.threadRootId,uploadIds: input.uploadIds,+ mentionAgentIds: input.mentionAgentIds,})),+ threadMessages: (params: {+ serverId: string;+ roomId: string;+ rootId: string;+ beforeSeq: number | null;+ limit: number;+ }): Promise<ChatMessage[]> =>+ onServer(params.serverId, async (server) => {+ const page = await fetchThreadMessages(server, params.roomId, params.rootId, {+ beforeSeq: params.beforeSeq,+ limit: Math.min(200, Math.max(1, params.limit)),+ });+ return page.messages;+ }),upload: (input: ChatUploadInput): Promise<ChatUpload> =>onServer(input.serverId, (server) =>uploadChatAttachment(server, input.roomId, {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 5936de62b..ca91150de 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@@ -1,7 +1,15 @@import { describe, expect, it, vi } from 'vitest';import { gatewayFetch } from '@main/core/switch-servers/gateway-client';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { parseChatRows, warmChatAgent } from './gateway';+import {+ addChatAgent,+ createChat,+ fetchThreadMessages,+ parseChatRows,+ removeChatAgent,+ sendChatMessage,+ warmChatAgent,+} from './gateway';const warn = vi.hoisted(() => vi.fn());vi.mock('@main/lib/logger', () => ({ log: { warn } }));@@ -52,3 +60,115 @@ describe('warmChatAgent', () => {});});});++describe('createChat', () => {+ it('creates chat with zero agents and memberUserIds', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ vi.mocked(gatewayFetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ chat: row('room-new', 'group') }), { status: 200 })+ );+ await createChat(server, {+ agentIds: [],+ memberUserIds: ['user-1', 'user-2'],+ name: 'Test Group',+ requestId: 'req-1',+ greeting: null,+ });+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats', {+ authenticated: true,+ method: 'POST',+ body: {+ requestId: 'req-1',+ memberUserIds: ['user-1', 'user-2'],+ name: 'Test Group',+ },+ });+ });++ it('creates chat with one agent using agentId field', 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: null,+ });+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats', {+ authenticated: true,+ method: 'POST',+ body: { requestId: 'req-1', agentId: 'agent-1' },+ });+ });+});++describe('addChatAgent', () => {+ it('posts agent to the chat agents route', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ vi.mocked(gatewayFetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ chat: row('room-1', 'group') }), { status: 200 })+ );+ await addChatAgent(server, 'room-1', 'agent-2');+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room-1/agents', {+ authenticated: true,+ method: 'POST',+ body: { agentId: 'agent-2' },+ });+ });+});++describe('removeChatAgent', () => {+ it('deletes agent from the chat', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ vi.mocked(gatewayFetch).mockResolvedValueOnce(new Response(null, { status: 204 }));+ await removeChatAgent(server, 'room-1', 'agent-2');+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room-1/agents/agent-2', {+ authenticated: true,+ method: 'DELETE',+ });+ });+});++describe('sendChatMessage', () => {+ it('sends message with mentionAgentIds', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ vi.mocked(gatewayFetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ messages: [] }), { status: 200 })+ );+ await sendChatMessage(server, 'room-1', {+ requestId: 'req-1',+ body: 'Test message',+ threadRootId: null,+ uploadIds: [],+ mentionAgentIds: ['agent-1', 'agent-2'],+ });+ expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room-1/messages', {+ authenticated: true,+ method: 'POST',+ body: {+ requestId: 'req-1',+ body: 'Test message',+ threadRootId: null,+ uploadIds: [],+ mentionAgentIds: ['agent-1', 'agent-2'],+ },+ });+ });+});++describe('fetchThreadMessages', () => {+ it('fetches thread messages with pagination', async () => {+ const server = { id: 'server-1' } as SwitchServer;+ vi.mocked(gatewayFetch).mockResolvedValueOnce(+ new Response(JSON.stringify({ messages: [], headSeq: 100, hasMore: false }), { status: 200 })+ );+ await fetchThreadMessages(server, 'room-1', 'msg-root', { beforeSeq: 50, limit: 20 });+ expect(gatewayFetch).toHaveBeenCalledWith(+ server,+ '/chats/room-1/threads/msg-root/messages?limit=20&beforeSeq=50',+ { 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.tsindex 31284dc40..3789792ed 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@@ -14,6 +14,8 @@ import {type ChatMessage,type ChatMessagesPage,chatMessagesPageSchema,+ type ChatThreadMessagesPage,+ chatThreadMessagesPageSchema,chatCreatedSchema,chatErrorBodySchema,chatListSchema,@@ -22,6 +24,7 @@ import {chatSummarySchema,type ChatUpload,chatUploadSchema,+ chatAgentAddedSchema,} from '@shared/core/chats/chats';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';@@ -104,20 +107,26 @@ export async function listChats(server: SwitchServer): Promise<ChatSummary[]> {/*** One agent goes as `agentId`, which every server with chats accepts; only a- * chat with several needs `agentIds`.+ * chat with several needs `agentIds`. Zero agents allowed; memberUserIds optional.*/export async function createChat(server: SwitchServer,- input: { agentIds: string[]; name: string | null; requestId: string; greeting: string | null }+ input: {+ agentIds?: string[];+ memberUserIds?: string[];+ name: string | null;+ requestId: string;+ greeting: string | null;+ }): Promise<ChatSummary> {+ const agentIds = input.agentIds ?? [];const body: Record<string, string | string[]> = {- ...(input.agentIds.length === 1- ? { agentId: input.agentIds[0] }- : { agentIds: input.agentIds }),requestId: input.requestId,};+ if (agentIds.length === 1) body.agentId = agentIds[0];+ else if (agentIds.length > 1) body.agentIds = agentIds;+ if (input.memberUserIds) body.memberUserIds = input.memberUserIds;if (input.name) body.name = input.name;- // What its one agent says as it joins, in place of its usual line.if (input.greeting !== null) body.greeting = input.greeting;return (await json(server, '/chats', chatCreatedSchema, { method: 'POST', body })).chat;}@@ -132,6 +141,27 @@ export async function fetchChatMessages(return json(server, `${room(roomId)}/messages?${query}`, chatMessagesPageSchema);}+export async function addChatAgent(+ server: SwitchServer,+ roomId: string,+ agentId: string+): Promise<ChatSummary> {+ return (+ await json(server, `${room(roomId)}/agents`, chatAgentAddedSchema, {+ method: 'POST',+ body: { agentId },+ })+ ).chat;+}++export async function removeChatAgent(+ server: SwitchServer,+ roomId: string,+ agentId: string+): Promise<void> {+ await call(server, `${room(roomId)}/agents/${encodeURIComponent(agentId)}`, { method: 'DELETE' });+}+export async function sendChatMessage(server: SwitchServer,roomId: string,@@ -140,6 +170,7 @@ export async function sendChatMessage(body: string;threadRootId: string | null;uploadIds: string[];+ mentionAgentIds?: string[];}): Promise<ChatMessage[]> {return (@@ -150,6 +181,21 @@ export async function sendChatMessage().messages;}+export async function fetchThreadMessages(+ server: SwitchServer,+ roomId: string,+ rootId: string,+ page: { beforeSeq: number | null; limit: number }+): Promise<ChatThreadMessagesPage> {+ const query = new URLSearchParams({ limit: String(page.limit) });+ if (page.beforeSeq !== null) query.set('beforeSeq', String(page.beforeSeq));+ return json(+ server,+ `${room(roomId)}/threads/${encodeURIComponent(rootId)}/messages?${query}`,+ chatThreadMessagesPageSchema+ );+}+/** The room's turn steps and approval requests, as Switch stores them. */export async function fetchRoomActivity(server: SwitchServer,diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.tsindex 8e751c8e2..97e3df3f0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-store.ts@@ -58,6 +58,12 @@ export type SendInput = {export type TimelineApi = {messages: (roomId: string, beforeSeq: number | null, limit: number) => Promise<ChatMessagesPage>;+ threadMessages: (+ roomId: string,+ rootId: string,+ beforeSeq: number | null,+ limit: number+ ) => Promise<ChatMessage[]>;upload: (roomId: string,file: { uploadId: string; name: string; mimeType: string; data: string }@@ -69,6 +75,7 @@ export type TimelineApi = {body: string;threadRootId: string | null;uploadIds: string[];+ mentionAgentIds?: string[];}) => Promise<ChatMessage[]>;newId: () => string;@@ -85,6 +92,8 @@ export class ChatTimeline {notMember = false;/** The person was a member and lost access while the chat was known. */accessLost = false;+ /** Thread reply counts by root message id, tracked from live events even if root not loaded. */+ threadReplyCounts = new Map<string, number>();constructor(readonly roomId: string,@@ -101,6 +110,22 @@ export class ChatTimeline {return this.messages.find((message) => message.messageId === messageId);}+ /** Get the live reply count for a thread root, or the server's count if the root is loaded. */+ threadReplyCount(rootId: string): number {+ const root = this.byId(rootId);+ if (root?.threadReplyCount !== undefined) return root.threadReplyCount;+ return this.threadReplyCounts.get(rootId) ?? 0;+ }++ /** Load thread messages for a root. */+ async loadThread(rootId: string, beforeSeq: number | null = null): Promise<ChatMessage[]> {+ try {+ return await this.api.threadMessages(this.roomId, rootId, beforeSeq, PAGE_SIZE);+ } catch (error) {+ throw chatFailure(error);+ }+ }+/** Merge a message from the room: by sequence, once, retiring the send it echoes. */apply(message: ChatMessage): void {if (message.roomId !== this.roomId) return;@@ -110,6 +135,10 @@ export class ChatTimeline {const at = this.messages.findIndex((each) => each.seq > message.seq);if (at === -1) this.messages.push(message);else this.messages.splice(at, 0, message);+ if (message.threadRootId) {+ const current = this.threadReplyCounts.get(message.threadRootId) ?? 0;+ this.threadReplyCounts.set(message.threadRootId, current + 1);+ }}async load(): Promise<void> {diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-threads.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-threads.test.tsnew file mode 100644index 000000000..fe601d1df--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-timeline-threads.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it, vi } from 'vitest';+import type { ChatMessage } from '@shared/core/chats/chats';+import { ChatTimeline, type TimelineApi } from './chat-timeline-store';++const makeMessage = (overrides: Partial<ChatMessage> = {}): ChatMessage => ({+ messageId: 'msg-1',+ seq: 1,+ roomId: 'room-1',+ sentAt: '2024-01-01T00:00:00Z',+ sender: {+ clientId: 'client-1',+ name: 'User',+ kind: 'human',+ agentId: null,+ userId: 'user-1',+ },+ source: 'text',+ body: 'Test message',+ format: null,+ threadRootId: null,+ attachments: [],+ clientTxn: null,+ namedAgentIds: [],+ ...overrides,+});++const makeApi = (): TimelineApi => ({+ messages: vi.fn().mockResolvedValue({ messages: [], headSeq: 0, hasMore: false }),+ threadMessages: vi.fn().mockResolvedValue([]),+ upload: vi.fn().mockResolvedValue({ uploadId: '', uri: '', filename: '', mimetype: '', size: 0 }),+ send: vi.fn().mockResolvedValue([]),+ newId: () => crypto.randomUUID(),+});++describe('ChatTimeline thread reply counts', () => {+ it('increments thread reply count when a reply arrives', () => {+ const timeline = new ChatTimeline('room-1', makeApi());+ const root = makeMessage({ messageId: 'root-1', seq: 1 });+ const reply = makeMessage({ messageId: 'reply-1', seq: 2, threadRootId: 'root-1' });++ timeline.apply(root);+ timeline.apply(reply);++ expect(timeline.threadReplyCount('root-1')).toBe(1);+ });++ it('tracks multiple replies to the same root', () => {+ const timeline = new ChatTimeline('room-1', makeApi());+ const root = makeMessage({ messageId: 'root-1', seq: 1 });+ const reply1 = makeMessage({ messageId: 'reply-1', seq: 2, threadRootId: 'root-1' });+ const reply2 = makeMessage({ messageId: 'reply-2', seq: 3, threadRootId: 'root-1' });++ timeline.apply(root);+ timeline.apply(reply1);+ timeline.apply(reply2);++ expect(timeline.threadReplyCount('root-1')).toBe(2);+ });++ it('tracks counts even if root is not loaded', () => {+ const timeline = new ChatTimeline('room-1', makeApi());+ const reply = makeMessage({ messageId: 'reply-1', seq: 2, threadRootId: 'unloaded-root' });++ timeline.apply(reply);++ expect(timeline.threadReplyCount('unloaded-root')).toBe(1);+ });++ it('prefers server threadReplyCount if root message has it', () => {+ const timeline = new ChatTimeline('room-1', makeApi());+ const root = makeMessage({ messageId: 'root-1', seq: 1, threadReplyCount: 5 });++ timeline.apply(root);++ expect(timeline.threadReplyCount('root-1')).toBe(5);+ });++ it('returns 0 for a root with no replies', () => {+ const timeline = new ChatTimeline('room-1', makeApi());+ expect(timeline.threadReplyCount('nonexistent-root')).toBe(0);+ });++ it('calls threadMessages API when loading a thread', async () => {+ const api = makeApi();+ const timeline = new ChatTimeline('room-1', api);++ await timeline.loadThread('root-1');++ expect(api.threadMessages).toHaveBeenCalledWith('room-1', 'root-1', null, 50);+ });++ it('calls threadMessages with beforeSeq for pagination', async () => {+ const api = makeApi();+ const timeline = new ChatTimeline('room-1', api);++ await timeline.loadThread('root-1', 100);++ expect(api.threadMessages).toHaveBeenCalledWith('room-1', 'root-1', 100, 50);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.tsindex 862decd19..8e035c183 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts@@ -23,6 +23,8 @@ export const chatsStore = new ChatsStore(timeline: (serverId) => ({messages: (roomId, beforeSeq, limit) =>rpc.chats.messages({ serverId, roomId, beforeSeq, limit }),+ threadMessages: (roomId, rootId, beforeSeq, limit) =>+ rpc.chats.threadMessages({ serverId, roomId, rootId, beforeSeq, limit }),upload: (roomId, file) => rpc.chats.upload({ serverId, roomId, ...file }),send: (roomId, input) => rpc.chats.send({ serverId, roomId, ...input }),newId: () => crypto.randomUUID(),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.tsindex 772a10322..d3768b12f 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@@ -13,6 +13,9 @@ export const chatAgentSchema = z.object({displayName: z.string().nullable(),iconUrl: z.string().nullable(),provider: z.string().nullable(),+ alias: z.string().optional(),+ ownerName: z.string().optional(),+ ownedByViewer: z.boolean().optional(),});export type ChatAgent = z.infer<typeof chatAgentSchema>;@@ -67,6 +70,9 @@ export const chatMessageSchema = z.object({threadRootId: z.string().nullable(),attachments: z.array(chatAttachmentSchema),clientTxn: z.string().nullable(),+ namedAgentIds: z.array(z.string()).optional(),+ threadReplyCount: z.number().int().optional(),+ threadLastReplySeq: z.number().int().nullable().optional(),});export type ChatMessage = z.infer<typeof chatMessageSchema>;@@ -78,7 +84,14 @@ export const chatMessagesPageSchema = z.object({hasMore: z.boolean(),});export type ChatMessagesPage = z.infer<typeof chatMessagesPageSchema>;+export const chatThreadMessagesPageSchema = z.object({+ messages: z.array(chatMessageSchema),+ headSeq: z.number().int(),+ hasMore: z.boolean(),+});+export type ChatThreadMessagesPage = z.infer<typeof chatThreadMessagesPageSchema>;export const chatSentSchema = z.object({ messages: z.array(chatMessageSchema) });+export const chatAgentAddedSchema = z.object({ chat: chatSummarySchema });export const chatUploadSchema = z.object({uploadId: z.string(),uri: z.string(),@@ -116,6 +129,7 @@ export type ChatSendInput = {body: string;threadRootId: string | null;uploadIds: string[];+ mentionAgentIds?: string[];};export type ChatUploadInput = {