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): an unsaved chat belongs to the account and workspace it was started in

raullopez-sandbox555ef37799e6
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts
index b75285abb..ee95d77c9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/start-direct-chat.ts
@@ -6,9 +6,13 @@ import { appState } from '@renderer/lib/stores/app-state';
import { focusComposerWhenOpened } from './components/chat-composer';
import { chatDraftKey, moveChatDraft, readChatDraft, unsavedChatKey } from './stores/chat-drafts';
import { chatsStore, chatTitler } from './stores/chats';
-import { DirectChatStarter, UNSAVED_CHAT_PREFIX } from './stores/direct-chat-starter';
+import {
+ type ChatScope,
+ DirectChatStarter,
+ UNSAVED_CHAT_PREFIX,
+} from './stores/direct-chat-starter';
-function scope(serverId: string) {
+function scope(serverId: string): ChatScope {
return {
serverId,
userId: switchServersStore.statusFor(serverId)?.user?.id ?? null,
@@ -24,8 +28,9 @@ export const directChats = new DirectChatStarter({
chatsStore.timelines.unsaved(chat.serverId, chat.roomId, create);
focusComposerWhenOpened(chat.roomId);
},
- created: ({ serverId, roomId: from }, chat) => {
- const draftKey = (roomId: string) => chatDraftKey({ ...scope(serverId), roomId });
+ created: (unsaved, chat) => {
+ const { serverId, roomId: from } = unsaved;
+ const draftKey = (roomId: string) => chatDraftKey({ ...unsaved, roomId });
moveChatDraft(draftKey(from), draftKey(chat.roomId));
if (document.activeElement?.closest('[data-chat-panel]')) focusComposerWhenOpened(chat.roomId);
runInAction(() => {
@@ -42,18 +47,19 @@ export const directChats = new DirectChatStarter({
const first = chatsStore.timelines.peek(serverId, chat.roomId)?.pending[0];
if (first) void chatTitler.sent(serverId, chat.roomId, first.body);
},
- kept: (serverId, agentId) => {
- const key = unsavedChatKey({ ...scope(serverId), agentId });
+ scope,
+ kept: (chatScope, agentId) => {
+ const key = unsavedChatKey({ ...chatScope, agentId });
const requestId = key && localStorage.getItem(key);
if (!key || !requestId) return null;
const roomId = `${UNSAVED_CHAT_PREFIX}${requestId}`;
- if (readChatDraft(chatDraftKey({ ...scope(serverId), roomId }))) return requestId;
+ if (readChatDraft(chatDraftKey({ ...chatScope, roomId }))) return requestId;
// Emptied before it was sent: nothing to come back to.
localStorage.removeItem(key);
return null;
},
- keep: (serverId, agentId, requestId) => {
- const key = unsavedChatKey({ ...scope(serverId), agentId });
+ keep: (chatScope, agentId, requestId) => {
+ const key = unsavedChatKey({ ...chatScope, agentId });
if (!key) return;
if (requestId) localStorage.setItem(key, requestId);
else localStorage.removeItem(key);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts
index 22d054204..1f9d2e948 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/direct-chat-starter.ts
@@ -6,8 +6,18 @@ export const UNSAVED_CHAT_PREFIX = 'unsaved-chat:';
/** What an unsaved chat is called: the name the server gives a chat made without one. */
export const UNSAVED_CHAT_NAME = 'New Chat';
-export type UnsavedChat = {
+/** Whose chats these are on a server: an unsaved chat belongs to one account and workspace. */
+export type ChatScope = {
serverId: string;
+ userId: string | null;
+ workspaceId: string | null;
+};
+
+/** The error an unsaved chat's send gets when the account or workspace changed under it. */
+export const SCOPE_CHANGED =
+ 'You switched account or workspace before this chat was made, so its message was not sent.';
+
+export type UnsavedChat = ChatScope & {
agentId: string;
/** The id it goes by on screen until its room exists. */
roomId: string;
@@ -27,10 +37,12 @@ export type DirectChatStarterDeps = {
opened: (chat: UnsavedChat, create: () => Promise<string>) => void;
/** Its room exists: the chat moves from its unsaved id to the room's. */
created: (unsaved: UnsavedChat, chat: ChatSummary) => void;
+ /** The account and workspace the server's chats belong to now. */
+ scope: (serverId: string) => ChatScope;
/** The create request id of the agent's unsaved chat kept from an earlier session, if it still has a draft. */
- kept: (serverId: string, agentId: string) => string | null;
+ kept: (scope: ChatScope, agentId: string) => string | null;
/** Keep the agent's unsaved chat's create request id across restarts; null forgets it. */
- keep: (serverId: string, agentId: string, requestId: string | null) => void;
+ keep: (scope: ChatScope, agentId: string, requestId: string | null) => void;
newId: () => string;
};
@@ -50,12 +62,13 @@ export class DirectChatStarter {
/** The id of the chat to open: the agent's unsaved one, made now if it has none. */
start(serverId: string, agentId: string): string {
- const key = `${serverId}:${agentId}`;
+ const scope = this.deps.scope(serverId);
+ const key = keyOf(scope, agentId);
let chat = this.unsaved.get(key);
if (!chat) {
- const requestId = this.deps.kept(serverId, agentId) ?? this.deps.newId();
- this.deps.keep(serverId, agentId, requestId);
- chat = { serverId, agentId, roomId: `${UNSAVED_CHAT_PREFIX}${requestId}`, requestId };
+ const requestId = this.deps.kept(scope, agentId) ?? this.deps.newId();
+ this.deps.keep(scope, agentId, requestId);
+ chat = { ...scope, agentId, roomId: `${UNSAVED_CHAT_PREFIX}${requestId}`, requestId };
this.unsaved.set(key, chat);
this.byRoomId.set(chat.roomId, chat);
}
@@ -66,9 +79,10 @@ export class DirectChatStarter {
/** The id of the agent's unsaved chat, open in this session or kept from an earlier one with a draft; null if none. */
waiting(serverId: string, agentId: string): string | null {
- const open = this.unsaved.get(`${serverId}:${agentId}`);
+ const scope = this.deps.scope(serverId);
+ const open = this.unsaved.get(keyOf(scope, agentId));
if (open) return open.roomId;
- const kept = this.deps.kept(serverId, agentId);
+ const kept = this.deps.kept(scope, agentId);
return kept ? `${UNSAVED_CHAT_PREFIX}${kept}` : null;
}
@@ -77,10 +91,15 @@ export class DirectChatStarter {
return this.byRoomId.get(roomId);
}
+ private inScope(chat: UnsavedChat): boolean {
+ return keyOf(this.deps.scope(chat.serverId), chat.agentId) === keyOf(chat, chat.agentId);
+ }
+
/** Make the chat's room, once however often asked; a failure lets the next ask try again under the same request id. */
private create(chat: UnsavedChat): Promise<string> {
let creating = this.creating.get(chat.roomId);
if (!creating) {
+ if (!this.inScope(chat)) return Promise.reject(new Error(SCOPE_CHANGED));
creating = this.deps
.create({
serverId: chat.serverId,
@@ -91,9 +110,12 @@ export class DirectChatStarter {
})
.then(
(created) => {
- this.unsaved.delete(`${chat.serverId}:${chat.agentId}`);
+ this.creating.delete(chat.roomId);
+ // Made for the account it was started in; another's view must not take it.
+ if (!this.inScope(chat)) throw new Error(SCOPE_CHANGED);
+ this.unsaved.delete(keyOf(chat, chat.agentId));
this.byRoomId.delete(chat.roomId);
- this.deps.keep(chat.serverId, chat.agentId, null);
+ this.deps.keep(chat, chat.agentId, null);
this.deps.created(chat, created);
return created.roomId;
},
@@ -107,3 +129,7 @@ export class DirectChatStarter {
return creating;
}
}
+
+function keyOf(scope: ChatScope, agentId: string): string {
+ return JSON.stringify([scope.serverId, scope.userId, scope.workspaceId, agentId]);
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts
index c7d1cc130..8e5135277 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/direct-chat-starter.test.ts
@@ -3,7 +3,11 @@ import {
ChatTimelines,
type TimelineApi,
} from '@renderer/features/chats/stores/chat-timeline-store';
-import { DirectChatStarter } from '@renderer/features/chats/stores/direct-chat-starter';
+import {
+ type ChatScope,
+ DirectChatStarter,
+ SCOPE_CHANGED,
+} from '@renderer/features/chats/stores/direct-chat-starter';
import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';
const chat = { roomId: 'r1', channelType: 'direct' } as ChatSummary;
@@ -11,6 +15,7 @@ const chat = { roomId: 'r1', channelType: 'direct' } as ChatSummary;
/** The starter wired to real timelines, as the app wires it, over fake RPCs. */
function setup(stored = new Map<string, string>()) {
let id = 0;
+ const account = { userId: 'alice' };
const api = {
messages: vi.fn(async () => ({ messages: [], headSeq: 0, hasMore: false })),
threadMessages: vi.fn(),
@@ -41,14 +46,17 @@ function setup(stored = new Map<string, string>()) {
timelines.unsaved(unsaved.serverId, unsaved.roomId, make);
},
created,
- kept: (serverId: string, agentId: string) => stored.get(`${serverId}:${agentId}`) ?? null,
- keep: (serverId: string, agentId: string, requestId: string | null) => {
- if (requestId) stored.set(`${serverId}:${agentId}`, requestId);
- else stored.delete(`${serverId}:${agentId}`);
+ scope: (serverId: string) => ({ serverId, userId: account.userId, workspaceId: 'w1' }),
+ kept: (scope: ChatScope, agentId: string) =>
+ stored.get(`${scope.userId}:${scope.serverId}:${agentId}`) ?? null,
+ keep: (scope: ChatScope, agentId: string, requestId: string | null) => {
+ const key = `${scope.userId}:${scope.serverId}:${agentId}`;
+ if (requestId) stored.set(key, requestId);
+ else stored.delete(key);
},
newId: () => `req-${++id}`,
});
- return { api, timelines, create, created, starter, stored };
+ return { api, timelines, create, created, starter, stored, account };
}
const message = (body: string) => ({
@@ -165,7 +173,7 @@ describe('DirectChatStarter', () => {
it('comes back after a reload or restart under the same create request id, and is forgotten once its room is made', async () => {
const before = setup();
const roomId = before.starter.start('s1', 'a1');
- const requestId = before.stored.get('s1:a1');
+ const requestId = before.stored.get('alice:s1:a1');
expect(requestId).toMatch(/^req-/);
// A restart: a new starter over what was kept.
@@ -178,4 +186,38 @@ describe('DirectChatStarter', () => {
expect(after.stored.size).toBe(0);
expect(after.starter.waiting('s1', 'a1')).toBeNull();
});
+
+ it('keeps each account its own unsaved chat with the same agent, and its own record', () => {
+ const { account, create, starter, stored } = setup();
+ const alices = starter.start('s1', 'a1');
+ account.userId = 'bob';
+ const bobs = starter.start('s1', 'a1');
+ expect(bobs).not.toBe(alices);
+ expect(starter.waiting('s1', 'a1')).toBe(bobs);
+ expect(stored.get('alice:s1:a1')).not.toBe(stored.get('bob:s1:a1'));
+ expect(stored.get('bob:s1:a1')).toBeDefined();
+ account.userId = 'alice';
+ expect(starter.start('s1', 'a1')).toBe(alices);
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it('never hands a room made after an account switch to the other account', async () => {
+ const { account, api, create, created, starter, timelines } = setup();
+ let finish: (chat: ChatSummary) => void = () => {};
+ create.mockImplementationOnce(() => new Promise((resolve) => (finish = resolve)));
+ const timeline = timelines.get('s1', starter.start('s1', 'a1'));
+ timeline.send(message('for alice'));
+ await vi.waitFor(() => expect(create).toHaveBeenCalledOnce());
+ account.userId = 'bob';
+ finish(chat);
+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('failed'));
+ expect(timeline.pending[0]?.error).toContain(SCOPE_CHANGED);
+ expect(created).not.toHaveBeenCalled();
+ expect(api.send).not.toHaveBeenCalled();
+
+ // Retrying as Bob asks the server for nothing.
+ timeline.retry(timeline.pending[0]!.requestId);
+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('failed'));
+ expect(create).toHaveBeenCalledOnce();
+ });
});