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(console): keep a group chat's participants in step with the server

raullopez-sandbox2aa6cc0fae1f
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 72dd52745..415d11d8d 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
@@ -185,13 +185,9 @@ export const chatsController = createRPCController({
onServer(params.serverId, (server) => addChatMember(server, params.roomId, params.userId)),
removeMember: (params: { serverId: string; roomId: string; userId: string }): Promise<void> =>
onServer(params.serverId, (server) => removeChatMember(server, params.roomId, params.userId)),
- /** The people of the window's workspace on the server, who a chat can be opened to. */
- workspaceMembers: async (serverId: string): Promise<WorkspaceMember[]> => {
- const workspace = await requireWorkspaceForServer(serverId);
- if (!workspace.tenantId) throw new Error('This workspace has no tenant to list people from.');
- const tenantId = workspace.tenantId;
- return onServer(serverId, (server) => listWorkspaceMembers(server, tenantId));
- },
+ /** 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)),
messages: (params: {
serverId: string;
roomId: string;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts
index 8f5d8b1ae..6ca0ae361 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts
@@ -233,6 +233,25 @@ export class ChatsStore {
void this.connect(serverId);
}
+ /** Drops an agent the server removed from the chat as it stands now, not as it stood when the removal was asked for. */
+ dropAgent(roomId: string, agentId: string): void {
+ const chat = this.chats.get(roomId);
+ if (chat)
+ this.chats.set(roomId, {
+ ...chat,
+ agents: chat.agents.filter((agent) => agent.id !== agentId),
+ });
+ }
+
+ /**
+ * Calls `onChange` whenever the chat's summary changes on the feed or from
+ * here, which is when what is known of its membership may have moved.
+ * Returns the disposer.
+ */
+ onChatChange(roomId: string, onChange: () => void): () => void {
+ return reaction(() => this.chats.get(roomId), onChange);
+ }
+
/** The chats an agent is in, newest activity first. */
chatsOfAgent(agentId: string): ChatSummary[] {
return [...this.chats.values()]
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 c9ab200ed..1dcbb8ba1 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
@@ -1,7 +1,7 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ExternalLink, FileText, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { opensAsConsoleChat } from '@renderer/features/chats/console-chat-redirect';
import { chatFailure } from '@renderer/features/chats/stores/chat-errors';
import { chatsStore } from '@renderer/features/chats/stores/chats';
@@ -111,6 +111,13 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
queryKey: membersKey,
queryFn: () => rpc.chats.members(serverId, roomId),
});
+ useEffect(
+ () =>
+ chatsStore.onChatChange(roomId, () => {
+ void queryClient.invalidateQueries({ queryKey: ['chat-members', serverId, roomId] });
+ }),
+ [queryClient, serverId, roomId]
+ );
const [adding, setAdding] = useState<'agent' | 'person' | null>(null);
const [removing, setRemoving] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -134,10 +141,7 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
removeAgent: (agentId) =>
void remove(agentId, async () => {
await rpc.chats.removeAgent({ serverId, roomId, agentId });
- chatsStore.add(serverId, {
- ...chat,
- agents: chat.agents.filter((agent) => agent.id !== agentId),
- });
+ chatsStore.dropAgent(roomId, agentId);
}),
// The owner stays: there is no one to hand the chat to.
removePerson: (userId) =>
@@ -207,6 +211,7 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
{adding === 'person' && (
<ChatAddPersonPanel
serverId={serverId}
+ tenantId={chatsStore.tenantId}
roomId={roomId}
memberIds={new Set(people.map((person) => person.userId))}
onAdded={(next) => queryClient.setQueryData(membersKey, next)}
@@ -262,26 +267,36 @@ const ChatAddAgentPanel = observer(function ChatAddAgentPanel({
/** The workspace's people not yet in the chat. */
function ChatAddPersonPanel({
serverId,
+ tenantId,
roomId,
memberIds,
onAdded,
}: {
serverId: string;
+ /** The workspace the chats follow; its roster is the one offered. */
+ tenantId: string | null;
roomId: string;
memberIds: Set<string>;
onAdded: (members: Awaited<ReturnType<typeof rpc.chats.addMember>>) => void;
}) {
const roster = useQuery({
- queryKey: ['workspace-members', serverId],
- queryFn: () => rpc.chats.workspaceMembers(serverId),
+ queryKey: ['workspace-members', serverId, tenantId],
+ queryFn: () => rpc.chats.workspaceMembers({ serverId, tenantId: tenantId as string }),
+ enabled: tenantId !== null,
});
return (
<AddParticipantPanel
noun="person"
searchPlaceholder="Search people in this workspace…"
allInText="Everyone in this workspace is already in this chat."
- loading={roster.isPending}
- loadError={roster.isError ? failureText(roster.error, 'Could not list the people.') : null}
+ loading={tenantId !== null && roster.isPending}
+ loadError={
+ tenantId === null
+ ? 'This workspace has no tenant to list people from.'
+ : roster.isError
+ ? failureText(roster.error, 'Could not list the people.')
+ : null
+ }
candidates={(roster.data ?? [])
.filter((person) => !memberIds.has(person.userId))
.map((person) => ({
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
index 3b9f23e76..e477f8747 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts
@@ -250,3 +250,64 @@ describe('ChatsStore', () => {
expect(timeline.loaded).toBe(false);
});
});
+
+/** A viewer's store whose feed the test drives, already connected to `s1`. */
+async function viewer() {
+ let onSummary: Parameters<ChatsEvents['onSummary']>[0] = () => {};
+ const events: ChatsEvents = {
+ onMessage: () => () => {},
+ onSummary: (cb) => {
+ onSummary = cb;
+ return () => {};
+ },
+ onRemoved: () => () => {},
+ onState: () => () => {},
+ onReset: () => () => {},
+ };
+ const group = { ...summary('g', 1), channelType: 'channel_private' as const };
+ const store = new ChatsStore(
+ {
+ connect: async () => ({ state: 'live', detail: null }),
+ disconnect: async () => {},
+ list: async () => [group],
+ identity: async () => ({ userId: 'u', tenantId: 't' }),
+ timeline: () => ({}) as TimelineApi,
+ archive: async () => {},
+ delete: async () => {},
+ },
+ events
+ );
+ await store.connect('s1');
+ return { store, push: (chat: ChatSummary) => onSummary({ serverId: 's1', chat }), group };
+}
+
+describe('ChatsStore membership', () => {
+ it('tells a viewer with the chat open when the feed changes it, without reopening', async () => {
+ const alice = await viewer();
+ const bob = await viewer();
+ const seen = { alice: 0, bob: 0 };
+ const stopAlice = alice.store.onChatChange('g', () => seen.alice++);
+ const stopBob = bob.store.onChatChange('g', () => seen.bob++);
+ // The server re-announces the chat to both members after Alice changes it.
+ const changed = { ...bob.group, agents: [] };
+ alice.push(changed);
+ bob.push(changed);
+ bob.push({ ...changed, roomId: 'other' });
+ expect(seen).toEqual({ alice: 1, bob: 1 });
+ stopBob();
+ bob.push({ ...changed, name: 'renamed' });
+ expect(seen.bob).toBe(1);
+ stopAlice();
+ });
+
+ it('keeps both of two quick agent removals and a feed update in between', async () => {
+ const { store, push, group } = await viewer();
+ const a = (id: string) => ({ ...group.agents[0], id });
+ push({ ...group, agents: [a('a1'), a('a2'), a('a3')] });
+ store.dropAgent('g', 'a1');
+ push({ ...group, name: 'renamed', agents: [a('a2'), a('a3')] });
+ store.dropAgent('g', 'a2');
+ expect(store.chat('g')?.agents.map((agent) => agent.id)).toEqual(['a3']);
+ expect(store.chat('g')?.name).toBe('renamed');
+ });
+});