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): a draft sent just before a reload is not offered to be sent twice

raullopez-sandbox5c2d29b4599a
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 a06c423ad..0ca927074 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
@@ -12,7 +12,12 @@ import { Button } from '@renderer/lib/ui/button';
import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@renderer/lib/ui/popover';
import { cn } from '@renderer/utils/utils';
import { agentInitials } from '@shared/core/agents/agent-avatar';
-import { type ChatAgent, type ChatMessage, chatAgentLabel } from '@shared/core/chats/chats';
+import {
+ type ChatAgent,
+ type ChatMessage,
+ chatAgentLabel,
+ requestIdOfClientTxn,
+} from '@shared/core/chats/chats';
import { snippetOf } from '../chat-threads';
import {
agentTargets,
@@ -33,7 +38,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 ChatDraft, chatDraftKey, readChatDraft, writeChatDraft } from '../stores/chat-drafts';
import type { ChatFile, ChatTimeline } from '../stores/chat-timeline-store';
import { chatTitler } from '../stores/chats';
import {
@@ -63,6 +68,30 @@ type Suggestion =
/** Chats just created here, whose composer takes focus when it first shows. */
const focusOnOpen = new Set<string>();
+/** A send of a draft made before a reload, which may have landed: its id, and the draft as sent. */
+type PendingResend = { requestId: string; text: string; mentions: MentionToken[] };
+
+function pendingOf(draft: ChatDraft | null): PendingResend | null {
+ return draft?.pendingRequestId
+ ? { requestId: draft.pendingRequestId, text: draft.text, mentions: draft.mentions }
+ : null;
+}
+
+/** Whether the draft is still exactly what was sent before, so it may go again under the same id. */
+function unchangedSince(
+ resend: PendingResend | null,
+ text: string,
+ mentions: MentionToken[],
+ files: number
+): resend is PendingResend {
+ return (
+ resend !== null &&
+ files === 0 &&
+ resend.text === text &&
+ JSON.stringify(resend.mentions) === JSON.stringify(mentions)
+ );
+}
+
/** Composers on screen by chat; a chat's stream event can open it before its create returns. */
const mountedFocus = new Map<string, () => void>();
@@ -194,6 +223,10 @@ export const ChatComposer = observer(function ChatComposer({
);
/** The send that emptied the composer: its text stays kept until the server has taken it. */
const [sending, setSending] = useState<string | null>(null);
+ /** A send of the draft on screen made before a reload, which may have landed: its id and text. */
+ const [resend, setResend] = useState<PendingResend | null>(() =>
+ pendingOf(readChatDraft(draftKey))
+ );
const sendState =
sending === null
? null
@@ -212,13 +245,29 @@ export const ChatComposer = observer(function ChatComposer({
setDraft(kept?.text ?? '');
setPicked(kept?.mentions ?? []);
setSending(null);
+ setResend(pendingOf(kept));
}
}
+ // The send before the reload did land: its draft is done with.
+ const landed =
+ unchangedSince(resend, draft, picked, 0) &&
+ timeline.messages.some(
+ (message) => requestIdOfClientTxn(message.clientTxn) === resend.requestId
+ );
+ if (landed) {
+ setDraft('');
+ setPicked([]);
+ setResend(null);
+ }
useEffect(() => {
if (readFrom !== draftKey) return;
if (draft === '' && sendState !== null && sendState !== 'sent') return;
- writeChatDraft(draftKey, { text: draft, mentions: picked });
- }, [draftKey, readFrom, draft, picked, sendState]);
+ writeChatDraft(draftKey, {
+ text: draft,
+ mentions: picked,
+ pendingRequestId: unchangedSince(resend, draft, picked, 0) ? resend.requestId : null,
+ });
+ }, [draftKey, readFrom, draft, picked, sendState, resend]);
/** 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. */
@@ -377,7 +426,13 @@ export const ChatComposer = observer(function ChatComposer({
threadRootId: replyTo?.messageId ?? null,
...mentionPayload(sent, groupChats),
files: files.map(({ file }) => chatFile(file)),
+ // The same message sent before a reload goes under the same id, so it lands once.
+ requestId: unchangedSince(resend, draft, picked, files.length) ? resend.requestId : null,
});
+ // Kept under its request id until the server takes it: a reload meanwhile
+ // finds out whether it landed rather than offering it to be sent twice.
+ writeChatDraft(draftKey, { text: draft, mentions: picked, pendingRequestId: requestId });
+ setResend({ requestId, text: draft, mentions: picked });
setSending(requestId);
void chatTitler.sent(serverId, timeline.roomId, body);
setDraft('');
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
index 22fe1441f..d65a4e083 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
@@ -1,7 +1,13 @@
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[] };
+/**
+ * An unsent message: its text and the mentions picked in it, with who each names.
+ * `pendingRequestId` is the request id it was sent under when the window went
+ * before the server answered: the message may have landed, so the draft is
+ * dropped if it did, and sent again under that id if not, which the server
+ * takes once.
+ */
+export type ChatDraft = { text: string; mentions: MentionToken[]; pendingRequestId: string | null };
const PREFIX = 'chat-draft:';
@@ -46,10 +52,11 @@ export function readChatDraft(key: string): ChatDraft | null {
return null;
}
if (typeof parsed !== 'object' || parsed === null) return null;
- const { text, mentions } = parsed as Record<string, unknown>;
+ const { text, mentions, pendingRequestId } = parsed as Record<string, unknown>;
if (typeof text !== 'string' || !Array.isArray(mentions)) return null;
return {
text,
+ pendingRequestId: typeof pendingRequestId === 'string' ? pendingRequestId : null,
mentions: mentions.filter(
(mention): mention is MentionToken => isMention(mention) && mention.end <= text.length
),
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.ts
index eb09925cb..8cbc1cabc 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
@@ -64,6 +64,8 @@ export type SendInput = {
/** Each picked or matched mention's stretch of the body and whom it names. */
mentionSpans: ChatMentionSpan[];
files: ChatFile[];
+ /** The request id an earlier send of this same message used, when it may have landed; null for a new one. */
+ requestId: string | null;
};
export type TimelineApi = {
@@ -208,7 +210,7 @@ export class ChatTimeline {
/** Send a message; returns its request id. */
send(input: SendInput): string {
const send: PendingSend = {
- requestId: this.api.newId(),
+ requestId: input.requestId ?? this.api.newId(),
body: input.body,
threadRootId: input.threadRootId,
mentionAgentIds: input.mentionAgentIds,
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
index 51b0dd801..5aec42987 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
@@ -209,4 +209,71 @@ describe('chat drafts', () => {
expect(textarea.value).toBe('typed while starting');
expect(readChatDraft(key('user-a', 'ws-1', 'room-1'))?.text).toBe('typed while starting');
});
+ it('keeps a send the window lost before the answer under its request id', async () => {
+ const textarea = await mount(
+ new ChatTimeline('room-1', api(vi.fn(() => new Promise<never>(() => {}))))
+ );
+ await type(textarea, 'in flight');
+ await pressEnter(textarea);
+ expect(textarea.value).toBe('');
+ expect(readChatDraft(key('user-a', 'ws-1', 'room-1'))).toEqual({
+ text: 'in flight',
+ mentions: [],
+ pendingRequestId: 'id-1',
+ });
+ });
+
+ it('drops the draft after a reload when that send did land', async () => {
+ localStorage.setItem(
+ key('user-a', 'ws-1', 'room-1'),
+ JSON.stringify({ text: 'in flight', mentions: [], pendingRequestId: 'req-1' })
+ );
+ const timeline = new ChatTimeline('room-1', api(vi.fn()));
+ timeline.apply({
+ messageId: 'm1',
+ seq: 1,
+ roomId: 'room-1',
+ sentAt: '2026-01-01T00:00:00Z',
+ sender: { clientId: 'c', name: 'Ada', kind: 'human', agentId: null, userId: 'user-a' },
+ source: 'console',
+ body: 'in flight',
+ format: null,
+ threadRootId: null,
+ attachments: [],
+ clientTxn: 'req-1:0',
+ namedAgentIds: [],
+ namedUserIds: [],
+ mentions: [],
+ threadReplyCount: 0,
+ threadLastReplySeq: null,
+ } as never);
+ const textarea = await mount(timeline);
+ expect(textarea.value).toBe('');
+ expect(localStorage.getItem(key('user-a', 'ws-1', 'room-1'))).toBeNull();
+ });
+
+ it('restores it when that send did not land, and sends it again under the same request id', async () => {
+ localStorage.setItem(
+ key('user-a', 'ws-1', 'room-1'),
+ JSON.stringify({ text: 'in flight', mentions: [], pendingRequestId: 'req-1' })
+ );
+ const send = vi.fn(async () => []);
+ const textarea = await mount(new ChatTimeline('room-1', api(send)));
+ expect(textarea.value).toBe('in flight');
+ await pressEnter(textarea);
+ await act(async () => {});
+ expect(send).toHaveBeenCalledWith('room-1', expect.objectContaining({ requestId: 'req-1' }));
+ });
+ it('sends an edited restored draft under a new request id', async () => {
+ localStorage.setItem(
+ key('user-a', 'ws-1', 'room-1'),
+ JSON.stringify({ text: 'in flight', mentions: [], pendingRequestId: 'req-1' })
+ );
+ const send = vi.fn(async () => []);
+ const textarea = await mount(new ChatTimeline('room-1', api(send)));
+ await type(textarea, 'in flight, edited');
+ await pressEnter(textarea);
+ await act(async () => {});
+ expect(send).toHaveBeenCalledWith('room-1', expect.objectContaining({ requestId: 'id-1' }));
+ });
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts
index 2619c4462..02bfaab29 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-timeline-store.test.ts
@@ -84,6 +84,7 @@ const input = (files: ChatFile[] = []) => ({
mentionUserIds: [],
mentionSpans: [],
files,
+ requestId: null,
});
describe('ChatTimeline', () => {