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 unsent chat drafts across reloads and restarts

raullopez-sandbox71624557aaed
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
index c27bbea4f..909d4cdc3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-composer.tsx
@@ -2,6 +2,8 @@ import { ChevronDown, Minimize2, Plus, RotateCcw, RotateCw, X } from 'lucide-rea
import { observer } from 'mobx-react-lite';
import { type KeyboardEvent as ReactKeyboardEvent, useEffect, useRef, useState } from 'react';
import { reportBuddyMessage } from '@renderer/features/switch-buddy/buddy-telemetry';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { isEditableTarget } from '@renderer/lib/hooks/use-arrow-key-navigation';
import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
@@ -31,6 +33,7 @@ import {
} from '../mentions';
import { isInterruptAck } from '../stop-rows';
import type { AgentActivity, ControlRequest } from '../stores/chat-activity-store';
+import { chatDraftKey, readChatDraft, writeChatDraft } from '../stores/chat-drafts';
import type { ChatFile, ChatTimeline } from '../stores/chat-timeline-store';
import { chatTitler } from '../stores/chats';
import {
@@ -58,9 +61,6 @@ type Suggestion =
| { kind: 'agent'; id: string; agent: ChatAgent }
| { kind: 'person'; id: string; person: MentionPerson & { email: string | null } };
-/** Drafts by chat, so a draft outlives navigating away. */
-const drafts = new Map<string, { text: string; mentions: MentionToken[] }>();
-
/** Chats just created here, whose composer takes focus when it first shows. */
const focusOnOpen = new Set<string>();
/** Composers on screen by chat; a chat's stream event can open it before its create returns. */
@@ -180,13 +180,39 @@ export const ChatComposer = observer(function ChatComposer({
onClearReply: () => void;
disabled: string | null;
}) {
- const draftKey = `${serverId}\u0000${timeline.roomId}`;
- const [draft, setDraft] = useState(() => drafts.get(draftKey)?.text ?? '');
+ // Kept across reloads and restarts, per account, workspace and room.
+ const draftKey = chatDraftKey({
+ serverId,
+ userId: switchServersStore.statusFor(serverId)?.user?.id ?? null,
+ workspaceId: workspacesStore.idOnServerInScope(serverId),
+ roomId: timeline.roomId,
+ });
+ const [draft, setDraft] = useState(() => readChatDraft(draftKey)?.text ?? '');
/** The mentions picked from the list, each with who it names, kept with the draft. */
- const [picked, setPicked] = useState<MentionToken[]>(() => drafts.get(draftKey)?.mentions ?? []);
+ const [picked, setPicked] = useState<MentionToken[]>(
+ () => readChatDraft(draftKey)?.mentions ?? []
+ );
+ // The account or workspace became known: what was kept for it wins over what is on screen.
+ const [readFrom, setReadFrom] = useState(draftKey);
+ if (readFrom !== draftKey) {
+ setReadFrom(draftKey);
+ const kept = readChatDraft(draftKey);
+ if (kept) {
+ setDraft(kept.text);
+ setPicked(kept.mentions);
+ }
+ }
+ /** The send that emptied the composer: its text stays kept until the server has taken it. */
+ const [sending, setSending] = useState<string | null>(null);
+ const sendState =
+ sending === null
+ ? null
+ : (timeline.pending.find((send) => send.requestId === sending)?.state ?? 'sent');
useEffect(() => {
- drafts.set(draftKey, { text: draft, mentions: picked });
- }, [draftKey, draft, picked]);
+ if (readFrom !== draftKey) return;
+ if (draft === '' && sendState !== null && sendState !== 'sent') return;
+ writeChatDraft(draftKey, { text: draft, mentions: picked });
+ }, [draftKey, readFrom, draft, picked, sendState]);
/** A pick the next edit inserts, placed once that edit has moved the others. */
const pendingPick = useRef<MentionToken | null>(null);
/** Picked mentions an edit removed, so undo and redo can bring them back with who they named. */
@@ -340,12 +366,13 @@ export const ChatComposer = observer(function ChatComposer({
timeline.pending.length
);
const sent = allowed(composeMentions(body, shiftMentions(draft, body, picked), targets));
- timeline.send({
+ const requestId = timeline.send({
body,
threadRootId: replyTo?.messageId ?? null,
...mentionPayload(sent, groupChats),
files: files.map(({ file }) => chatFile(file)),
});
+ setSending(requestId);
void chatTitler.sent(serverId, timeline.roomId, body);
setDraft('');
setPicked([]);
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.ts
new file mode 100644
index 000000000..22fe1441f
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chat-drafts.ts
@@ -0,0 +1,66 @@
+import type { MentionToken } from '../mentions';
+
+/** An unsent message: its text and the mentions picked in it, with who each names. */
+export type ChatDraft = { text: string; mentions: MentionToken[] };
+
+const PREFIX = 'chat-draft:';
+
+/** Drafts whose account or workspace is not known yet: kept for this session only. */
+const unscoped = new Map<string, ChatDraft>();
+
+/**
+ * Where a room's draft is kept: one per account, workspace and room, so a draft
+ * never shows up in another account's or workspace's chat. Until the account and
+ * workspace are known it is kept in memory only, by server and room.
+ */
+export function chatDraftKey(scope: {
+ serverId: string;
+ userId: string | null;
+ workspaceId: string | null;
+ roomId: string;
+}): string {
+ if (scope.userId === null || scope.workspaceId === null) {
+ return JSON.stringify([scope.serverId, scope.roomId]);
+ }
+ return `${PREFIX}${JSON.stringify([scope.serverId, scope.userId, scope.workspaceId, scope.roomId])}`;
+}
+
+function isMention(value: unknown): value is MentionToken {
+ if (typeof value !== 'object' || value === null) return false;
+ const mention = value as Record<string, unknown>;
+ return (
+ (mention.kind === 'agent' || mention.kind === 'person') &&
+ typeof mention.id === 'string' &&
+ Number.isInteger(mention.start) &&
+ Number.isInteger(mention.end)
+ );
+}
+
+/** The draft kept under `key` (across reloads and restarts once scoped); null when there is none or it is unreadable. */
+export function readChatDraft(key: string): ChatDraft | null {
+ if (!key.startsWith(PREFIX)) return unscoped.get(key) ?? null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(localStorage.getItem(key) ?? 'null');
+ } catch {
+ return null;
+ }
+ if (typeof parsed !== 'object' || parsed === null) return null;
+ const { text, mentions } = parsed as Record<string, unknown>;
+ if (typeof text !== 'string' || !Array.isArray(mentions)) return null;
+ return {
+ text,
+ mentions: mentions.filter(
+ (mention): mention is MentionToken => isMention(mention) && mention.end <= text.length
+ ),
+ };
+}
+
+/** Keep `draft` under `key`; an empty one is forgotten. */
+export function writeChatDraft(key: string, draft: ChatDraft): void {
+ if (!key.startsWith(PREFIX)) {
+ if (draft.text === '') unscoped.delete(key);
+ else unscoped.set(key, draft);
+ } else if (draft.text === '') localStorage.removeItem(key);
+ else localStorage.setItem(key, JSON.stringify(draft));
+}
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.tsx
new file mode 100644
index 000000000..b6dc6cb45
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-drafts.test.tsx
@@ -0,0 +1,177 @@
+/**
+ * An unsent draft, with the mentions picked in it, survives a reload or a
+ * restart (both remount the composer from what was kept), is kept apart per
+ * account, workspace and room, and goes only once the server has taken it.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const scope = vi.hoisted(() => ({ userId: 'user-a', workspaceId: 'ws-1' }));
+vi.mock('@renderer/lib/hooks/useFeatureFlags', () => ({
+ useFeatureFlags: () => ({ group_chats: true }),
+}));
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: { statusFor: () => ({ user: { id: scope.userId } }) },
+}));
+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
+ workspacesStore: { idOnServerInScope: () => scope.workspaceId },
+}));
+
+import { ChatComposer } from '@renderer/features/chats/components/chat-composer';
+import { chatDraftKey, readChatDraft } from '@renderer/features/chats/stores/chat-drafts';
+import {
+ ChatTimeline,
+ type TimelineApi,
+} from '@renderer/features/chats/stores/chat-timeline-store';
+
+const agent = {
+ id: 'a2',
+ name: 'agent-two',
+ displayName: null,
+ iconUrl: null,
+ provider: null,
+ alias: null,
+ ownerName: null,
+ ownedByViewer: false,
+};
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+async function unmount(): Promise<void> {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+}
+
+afterEach(unmount);
+beforeEach(() => {
+ localStorage.clear();
+ scope.userId = 'user-a';
+ scope.workspaceId = 'ws-1';
+});
+
+function api(send: TimelineApi['send']): TimelineApi {
+ let n = 0;
+ return { newId: () => `id-${++n}`, send } as unknown as TimelineApi;
+}
+
+async function mount(timeline: ChatTimeline): Promise<HTMLTextAreaElement> {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <ChatComposer
+ serverId="srv"
+ timeline={timeline}
+ agents={[agent]}
+ people={[]}
+ groupName="Ship review"
+ activity={null}
+ replyTo={null}
+ onClearReply={() => {}}
+ disabled={null}
+ />
+ </QueryClientProvider>
+ )
+ );
+ return container.querySelector('textarea')!;
+}
+
+async function type(textarea: HTMLTextAreaElement, value: string): Promise<void> {
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(
+ textarea,
+ value
+ );
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+async function pressEnter(textarea: HTMLTextAreaElement): Promise<void> {
+ await act(async () => {
+ textarea.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })
+ );
+ });
+}
+
+const key = (userId: string, workspaceId: string, roomId: string) =>
+ chatDraftKey({ serverId: 'srv', userId, workspaceId, roomId });
+
+const keptMention = { kind: 'agent' as const, id: 'a2', start: 0, end: 10 };
+
+describe('chat drafts', () => {
+ it('come back after a reload or restart with the mentions picked in them', async () => {
+ // What an earlier session kept: a picked mention of agent-two.
+ localStorage.setItem(
+ key('user-a', 'ws-1', 'room-1'),
+ JSON.stringify({ text: '@agent-two please review', mentions: [keptMention] })
+ );
+ const timeline = new ChatTimeline('room-1', api(vi.fn()));
+ let textarea = await mount(timeline);
+ expect(textarea.value).toBe('@agent-two please review');
+ expect(container!.querySelector('mark')?.textContent).toBe('@agent-two');
+
+ await type(textarea, '@agent-two please review today');
+ await unmount();
+ textarea = await mount(new ChatTimeline('room-1', api(vi.fn())));
+
+ expect(textarea.value).toBe('@agent-two please review today');
+ expect(readChatDraft(key('user-a', 'ws-1', 'room-1'))?.mentions).toEqual([keptMention]);
+ });
+
+ it('stay with their account, workspace and room', async () => {
+ let textarea = await mount(new ChatTimeline('room-1', api(vi.fn())));
+ await type(textarea, 'only for user-a in ws-1');
+ await unmount();
+
+ for (const [userId, workspaceId, roomId] of [
+ ['user-b', 'ws-1', 'room-1'],
+ ['user-a', 'ws-2', 'room-1'],
+ ['user-a', 'ws-1', 'room-2'],
+ ]) {
+ scope.userId = userId;
+ scope.workspaceId = workspaceId;
+ textarea = await mount(new ChatTimeline(roomId, api(vi.fn())));
+ expect(textarea.value).toBe('');
+ await unmount();
+ }
+ scope.userId = 'user-a';
+ scope.workspaceId = 'ws-1';
+ textarea = await mount(new ChatTimeline('room-1', api(vi.fn())));
+ expect(textarea.value).toBe('only for user-a in ws-1');
+ });
+
+ it('go once the server has taken the message', async () => {
+ const textarea = await mount(new ChatTimeline('room-1', api(vi.fn(async () => []))));
+ await type(textarea, 'ship it');
+ await pressEnter(textarea);
+ await act(async () => {});
+
+ expect(textarea.value).toBe('');
+ expect(localStorage.getItem(key('user-a', 'ws-1', 'room-1'))).toBeNull();
+ });
+
+ it('stay kept when the send fails, so a reload brings the text back', async () => {
+ const failing = api(
+ vi.fn(async () => {
+ throw new Error('network down');
+ })
+ );
+ let textarea = await mount(new ChatTimeline('room-1', failing));
+ await type(textarea, 'do not lose me');
+ await pressEnter(textarea);
+ await act(async () => {});
+ expect(textarea.value).toBe('');
+
+ await unmount();
+ textarea = await mount(new ChatTimeline('room-1', api(vi.fn())));
+ expect(textarea.value).toBe('do not lose me');
+ });
+});