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): an unsent New chat survives a reload or restart
raullopez-sandbox039507657c98
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsxindex 81e39b618..e0b97b653 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx@@ -11,6 +11,7 @@ import { RelativeTime } from '@renderer/lib/ui/relative-time';import type { ChatSummary } from '@shared/core/chats/chats';import { agentActivities } from '../stores/activities';import { chatsStore } from '../stores/chats';+import { UNSAVED_CHAT_NAME } from '../stores/direct-chat-starter';import { ChatActionItems, chatActions } from './chat-actions';import { UnreadBadge } from './unread-badge';@@ -80,3 +81,23 @@ export const ChatRow = observer(function ChatRow({</SidebarMenuRow>);});++/** A chat not sent yet, so with no room: only its draft, kept across restarts. */+export function UnsavedChatRow({ isActive, onOpen }: { isActive: boolean; onOpen: () => void }) {+ return (+ <SidebarMenuRow className="justify-between" isActive={isActive} onClick={onOpen}>+ <div className="flex h-6 min-w-0 flex-1 items-center gap-1">+ <span className="flex size-6 shrink-0 items-center justify-center">+ <MessageSquare className="size-4 text-foreground-muted" />+ </span>+ <SidebarMenuAction+ aria-label={`Open chat ${UNSAVED_CHAT_NAME}`}+ className="overflow-hidden"+ >+ <span className="min-w-0 truncate italic">{UNSAVED_CHAT_NAME}</span>+ </SidebarMenuAction>+ </div>+ <span className="ml-2 shrink-0 text-xs text-foreground-passive">Draft</span>+ </SidebarMenuRow>+ );+}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.tsindex 94322a7d2..b75285abb 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@@ -4,9 +4,17 @@ import { workspacesStore } from '@renderer/features/workspaces/workspaces-store'import { rpc } from '@renderer/lib/ipc';import { appState } from '@renderer/lib/stores/app-state';import { focusComposerWhenOpened } from './components/chat-composer';-import { chatDraftKey, moveChatDraft } from './stores/chat-drafts';+import { chatDraftKey, moveChatDraft, readChatDraft, unsavedChatKey } from './stores/chat-drafts';import { chatsStore, chatTitler } from './stores/chats';-import { DirectChatStarter } from './stores/direct-chat-starter';+import { DirectChatStarter, UNSAVED_CHAT_PREFIX } from './stores/direct-chat-starter';++function scope(serverId: string) {+ return {+ serverId,+ userId: switchServersStore.statusFor(serverId)?.user?.id ?? null,+ workspaceId: workspacesStore.idOnServerInScope(serverId),+ };+}/** Starts a direct chat with one agent, made on its first message and named from it. */export const directChats = new DirectChatStarter({@@ -17,13 +25,7 @@ export const directChats = new DirectChatStarter({focusComposerWhenOpened(chat.roomId);},created: ({ serverId, roomId: from }, chat) => {- const draftKey = (roomId: string) =>- chatDraftKey({- serverId,- userId: switchServersStore.statusFor(serverId)?.user?.id ?? null,- workspaceId: workspacesStore.idOnServerInScope(serverId),- roomId,- });+ const draftKey = (roomId: string) => chatDraftKey({ ...scope(serverId), roomId });moveChatDraft(draftKey(from), draftKey(chat.roomId));if (document.activeElement?.closest('[data-chat-panel]')) focusComposerWhenOpened(chat.roomId);runInAction(() => {@@ -40,5 +42,21 @@ 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 });+ 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;+ // 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 });+ if (!key) return;+ if (requestId) localStorage.setItem(key, requestId);+ else localStorage.removeItem(key);+ },newId: () => crypto.randomUUID(),});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.tsindex 7de9470a5..6244682b2 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts@@ -89,3 +89,18 @@ export function moveChatDraft(from: string, to: string): void {writeChatDraft(to, draft);writeChatDraft(from, { ...draft, text: '' });}++/**+ * Where an agent's unsaved chat's create request id is kept across restarts:+ * one per account, workspace and agent, like drafts; null until the account and+ * workspace are known, when it is kept for this session only.+ */+export function unsavedChatKey(scope: {+ serverId: string;+ userId: string | null;+ workspaceId: string | null;+ agentId: string;+}): string | null {+ if (scope.userId === null || scope.workspaceId === null) return null;+ return `unsaved-chat:${JSON.stringify([scope.serverId, scope.userId, scope.workspaceId, scope.agentId])}`;+}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.tsindex 7a3d35f31..22d054204 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@@ -27,6 +27,10 @@ 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 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;+ /** Keep the agent's unsaved chat's create request id across restarts; null forgets it. */+ keep: (serverId: string, agentId: string, requestId: string | null) => void;newId: () => string;};@@ -34,7 +38,8 @@ export type DirectChatStarterDeps = {* Starts an unnamed direct chat with one agent. Nothing is asked of the server* until the first message: the chat opens at once under an unsaved id, and its* room is made as that message is sent. Starting again for the same agent- * before then opens the same unsaved chat, with whatever was typed in it.+ * before then opens the same unsaved chat, with whatever was typed in it, and+ * so does starting after a restart, under the same create request id.*/export class DirectChatStarter {private readonly unsaved = new Map<string, UnsavedChat>();@@ -48,7 +53,8 @@ export class DirectChatStarter {const key = `${serverId}:${agentId}`;let chat = this.unsaved.get(key);if (!chat) {- const requestId = this.deps.newId();+ 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 };this.unsaved.set(key, chat);this.byRoomId.set(chat.roomId, chat);@@ -58,6 +64,14 @@ export class DirectChatStarter {return chat.roomId;}+ /** 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}`);+ if (open) return open.roomId;+ const kept = this.deps.kept(serverId, agentId);+ return kept ? `${UNSAVED_CHAT_PREFIX}${kept}` : null;+ }+/** The unsaved chat shown under `roomId`, while its room does not exist yet. */unsavedChat(roomId: string): UnsavedChat | undefined {return this.byRoomId.get(roomId);@@ -79,6 +93,7 @@ export class DirectChatStarter {(created) => {this.unsaved.delete(`${chat.serverId}:${chat.agentId}`);this.byRoomId.delete(chat.roomId);+ this.deps.keep(chat.serverId, chat.agentId, null);this.deps.created(chat, created);return created.roomId;},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.tsxindex 7d8a10250..9632ffaef 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@@ -4,7 +4,7 @@ import { type ReactNode, useEffect, useRef, useState } from 'react';import { agentConversations } from '@renderer/features/chats/agent-conversations';import { ArchivedFold } from '@renderer/features/chats/components/archived-fold';import { ChatPanel } from '@renderer/features/chats/components/chat-panel';-import { ChatRow } from '@renderer/features/chats/components/chat-row';+import { ChatRow, UnsavedChatRow } from '@renderer/features/chats/components/chat-row';import { useOpenGroupAsRoom } from '@renderer/features/chats/console-chat-redirect';import { directChats } from '@renderer/features/chats/start-direct-chat';import { chatsStore } from '@renderer/features/chats/stores/chats';@@ -184,6 +184,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag// The chat open here that becomes a group follows into its room, rather than another chat taking its place.useOpenGroupAsRoom(shownRoom || section ? null : (params.roomId ?? null), 'managedAgent');const newChat = () => open(directChats.start(serverId, agentId));+ const unsavedId = directChats.waiting(serverId, agentId);const ownServer = chatsStore.serverId === serverId;const listing = ownServer && chatsStore.userId === null && !chatsStore.listError;@@ -226,6 +227,9 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag</Button></div>)}+ {unsavedId && (+ <UnsavedChatRow isActive={!section && unsavedId === roomId} onOpen={newChat} />+ )}{direct.map((chat) => (<ChatRowkey={chat.roomId}@@ -235,7 +239,9 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: ManagonOpen={() => open(chat.roomId)}/>))}- {direct.length === 0 && !chatsStore.listError && <Note>No direct chats yet.</Note>}+ {direct.length === 0 && !unsavedId && !chatsStore.listError && (+ <Note>No direct chats yet.</Note>+ )}<ArchivedFold count={archived.length} error={ownServer ? chatsStore.archivedError : null}>{archived.map((chat) => (<ChatRowdiff --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.tsxindex 44c14461c..19153c695 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@@ -100,9 +100,12 @@ vi.mock('@renderer/features/chats/components/chat-panel', async (importOriginal)import '@renderer/index.css';import { runInAction } from 'mobx';import { directChats } from '@renderer/features/chats/start-direct-chat';+import { chatDraftKey, unsavedChatKey } from '@renderer/features/chats/stores/chat-drafts';import { chatsStore } from '@renderer/features/chats/stores/chats';import { AgentChats, openAgentChat } from '@renderer/features/managed-agents/agent-chats';import { roomEmbedSlotStore } from '@renderer/features/switch-rooms/room-embed-slot';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';import { appState } from '@renderer/lib/stores/app-state';import type { ChatSummary } from '@shared/core/chats/chats';@@ -414,6 +417,43 @@ it('opens no other chat in place of an unsaved one, so its header is not that ch}});+it('lists an unsent New chat kept from before a restart, with its draft, and reopens it', async () => {+ const status = vi+ .spyOn(switchServersStore, 'statusFor')+ .mockReturnValue({ user: { id: 'user-a' } } as ReturnType<typeof switchServersStore.statusFor>);+ const workspace = vi.spyOn(workspacesStore, 'idOnServerInScope').mockReturnValue('ws-1');+ const scope = { serverId: 'server-1', userId: 'user-a', workspaceId: 'ws-1' };+ // An agent no other test opened a chat with: the starter is the app's own, shared by every test.+ const record = unsavedChatKey({ ...scope, agentId: 'agent-3' })!;+ try {+ localStorage.setItem(record, 'kept-request');+ localStorage.setItem(+ chatDraftKey({ ...scope, roomId: 'unsaved-chat:kept-request' }),+ JSON.stringify({ text: 'half a thought', mentions: [] })+ );+ navigation.reset({ serverId: 'server-1', agentId: 'agent-3', name: 'pm-agent' });+ await act(async () => root.render(<AgentChats agent={{ ...AGENT, agentId: 'agent-3' }} />));+ const row = container.querySelector<HTMLElement>('[aria-label="Open chat New Chat"]');+ expect(row).not.toBeNull();+ await act(async () => row!.click());+ expect(navigation.params().roomId).toBe('unsaved-chat:kept-request');++ // Emptied before the restart: there is nothing to come back to.+ act(() => root.unmount());+ root = createRoot(container);+ localStorage.removeItem(chatDraftKey({ ...scope, roomId: 'unsaved-chat:kept-request' }));+ navigation.reset({ serverId: 'server-1', agentId: 'agent-2', name: 'pm-agent' });+ localStorage.setItem(unsavedChatKey({ ...scope, agentId: 'agent-2' })!, 'emptied');+ await act(async () => root.render(<AgentChats agent={{ ...AGENT, agentId: 'agent-2' }} />));+ expect(container.querySelector('[aria-label="Open chat New Chat"]')).toBeNull();+ expect(localStorage.getItem(unsavedChatKey({ ...scope, agentId: 'agent-2' })!)).toBeNull();+ } finally {+ status.mockRestore();+ workspace.mockRestore();+ localStorage.clear();+ }+});+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();diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsxindex b41f00edf..b0a87ea1a 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx@@ -27,6 +27,7 @@ import {} from '@renderer/features/chats/stores/chat-drafts';import {ChatTimeline,+ ChatTimelines,type TimelineApi,} from '@renderer/features/chats/stores/chat-timeline-store';@@ -205,6 +206,58 @@ describe('chat drafts', () => {expect(readChatDraft(key('user-a', 'ws-1', 'r1'))).toBeNull();});+ describe('of a New chat whose room was made but whose first send failed, across a reload', () => {+ /** Sends the first message of an unsaved chat whose room is made as `r1` and whose send then fails. */+ async function failFirstSend(): Promise<string> {+ const timelines = new ChatTimelines(() =>+ api(+ vi.fn(async () => {+ throw new Error('network down');+ })+ )+ );+ const timeline = timelines.unsaved('srv', 'unsaved-chat:1', async () => {+ moveChatDraft(key('user-a', 'ws-1', 'unsaved-chat:1'), key('user-a', 'ws-1', 'r1'));+ timelines.rekey('srv', 'unsaved-chat:1', 'r1');+ return 'r1';+ });+ const textarea = await mount(timeline);+ await type(textarea, 'first message');+ await pressEnter(textarea);+ await vi.waitFor(() => expect(timeline.pending[0]?.state).toBe('failed'));+ expect(timeline.roomId).toBe('r1');+ await unmount();+ return timeline.pending[0]!.requestId;+ }++ it('reopens as the room, and sends the message again once, under the same request id', async () => {+ const requestId = await failFirstSend();+ expect(readChatDraft(key('user-a', 'ws-1', 'unsaved-chat:1'))).toBeNull();++ const send = vi.fn(async () => []);+ const textarea = await mount(new ChatTimeline('r1', api(send)));+ expect(textarea.value).toBe('first message');+ await pressEnter(textarea);+ await act(async () => {});+ expect(send).toHaveBeenCalledOnce();+ expect(send).toHaveBeenCalledWith('r1', expect.objectContaining({ requestId }));+ });++ it('sends it under a new request id once edited', async () => {+ const requestId = await failFirstSend();+ const send = vi.fn(async () => []);+ // A fresh window's ids: they must not collide with the failed send's.+ const textarea = await mount(+ new ChatTimeline('r1', { ...api(send), newId: () => crypto.randomUUID() })+ );+ await type(textarea, 'first message, edited');+ await pressEnter(textarea);+ await act(async () => {});+ expect(send).toHaveBeenCalledOnce();+ expect(send).not.toHaveBeenCalledWith('r1', expect.objectContaining({ requestId }));+ });+ });+it('shows the other room’s draft, or none, in the same composer, and never carries one over', async () => {localStorage.setItem(key('user-a', 'ws-1', 'room-a'),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.tsindex 78878eb09..c7d1cc130 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@@ -9,7 +9,7 @@ import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';const chat = { roomId: 'r1', channelType: 'direct' } as ChatSummary;/** The starter wired to real timelines, as the app wires it, over fake RPCs. */-function setup() {+function setup(stored = new Map<string, string>()) {let id = 0;const api = {messages: vi.fn(async () => ({ messages: [], headSeq: 0, hasMore: false })),@@ -41,9 +41,14 @@ function setup() {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}`);+ },newId: () => `req-${++id}`,});- return { api, timelines, create, created, starter };+ return { api, timelines, create, created, starter, stored };}const message = (body: string) => ({@@ -156,4 +161,21 @@ describe('DirectChatStarter', () => {]);expect(requestId).not.toBe(create.mock.calls[0]![0].requestId);});++ 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');+ expect(requestId).toMatch(/^req-/);++ // A restart: a new starter over what was kept.+ const after = setup(before.stored);+ expect(after.starter.waiting('s1', 'a1')).toBe(roomId);+ expect(after.starter.start('s1', 'a1')).toBe(roomId);+ after.timelines.get('s1', roomId).send(message('hello'));+ await vi.waitFor(() => expect(after.api.send).toHaveBeenCalledOnce());+ expect(after.create.mock.calls[0]![0].requestId).toBe(requestId);+ expect(after.stored.size).toBe(0);+ expect(after.starter.waiting('s1', 'a1')).toBeNull();+ });});