Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(web): clear the composer before a sent message paints (#7246)

Wolf Mermelstein8bf364555dbe
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 4e7b5ce021..6d43cdc82a 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -102,7 +102,7 @@ checks project ranking and insertion on desktop and phone.
Channel composer draft persistence has a backend-free browser regression:
`bunx playwright test --config src/features/channel/Input/browser-test/playwright.config.ts`.
-It types a draft, remounts the composer over it, and checks the blank lines survive.
+It checks draft blank lines across remounts and pending sends on desktop and phone: clear immediately, restore failed sends, and preserve a new draft typed during delivery.
Block formatting passes a forward copy of the selection to Lexical's
`$setBlocksType` so backward selections include their first paragraph and keep
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.test.tsx b/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
index 2cd4b38b0f..afb3437067 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
@@ -52,6 +52,7 @@ const editor = vi.hoisted(() => ({
| ((files: File[], directories: FileSystemDirectoryEntry[]) => void)
| undefined,
text: '',
+ readMarkdown: (): string => '',
}));
vi.mock(
@@ -90,7 +91,7 @@ vi.mock(
clear: editor.clear,
setMarkdown: editor.setMarkdown,
focus: vi.fn(),
- getMarkdown: () => editor.text,
+ getMarkdown: () => editor.readMarkdown(),
},
lexical: editor.lexical,
};
@@ -156,7 +157,10 @@ beforeEach(() => {
);
vi.clearAllMocks();
vi.mocked(isTouchDevice).mockReturnValue(false);
+ editor.clear.mockReset();
+ editor.setMarkdown.mockReset();
editor.text = '';
+ editor.readMarkdown = () => editor.text;
editor.enter = undefined;
editor.change = undefined;
});
@@ -196,6 +200,33 @@ describe('Chat session input', () => {
}
);
+ it('does not write a sent prompt back into the editor', () => {
+ const [draft, setDraft] = createSignal('');
+ const [markdown, setMarkdown] = createSignal('');
+ editor.readMarkdown = markdown;
+ editor.clear.mockImplementation(() => setMarkdown(''));
+ editor.setMarkdown.mockImplementation((value: string) =>
+ setMarkdown(value)
+ );
+ const send = vi.fn();
+ render(() => (
+ <ChatComposer
+ draft={draft()}
+ onDraftChange={setDraft}
+ onSend={send}
+ selector={<span />}
+ />
+ ));
+ setDraft('Hello agent');
+ setMarkdown('Hello agent');
+ editor.setMarkdown.mockClear();
+ editor.enter?.(undefined, 'Hello agent');
+ expect(send).toHaveBeenCalledWith('Hello agent', []);
+ expect(draft()).toBe('');
+ expect(markdown()).toBe('');
+ expect(editor.setMarkdown).not.toHaveBeenCalledWith('Hello agent');
+ });
+
it('preloads the fold only when focused without sending or changing the draft', () => {
const send = vi.fn();
const change = vi.fn();
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.tsx b/apps/web/src/features/agents-view/components/ChatComposer.tsx
index 83b5c8e333..1b98687b7b 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.tsx
@@ -40,6 +40,7 @@ import {
createEffect,
createSignal,
type JSX,
+ on,
onCleanup,
onMount,
Show,
@@ -176,11 +177,16 @@ export function ChatComposer(props: {
: 'auto',
});
- // Apply host-supplied drafts (Home suggestions) to the existing editor.
- createEffect(() => {
- if (props.draft !== editor.controls.getMarkdown())
- editor.controls.setMarkdown(props.draft);
- });
+ // Only host draft changes should replace the editor contents.
+ createEffect(
+ on(
+ () => props.draft,
+ (draft) => {
+ if (draft !== editor.controls.getMarkdown())
+ editor.controls.setMarkdown(draft);
+ }
+ )
+ );
onMount(() => {
if (props.collapseOnBlur) {
@@ -214,8 +220,8 @@ export function ChatComposer(props: {
)
return;
const attached = attachments();
- editor.controls.clear();
props.onDraftChange('');
+ editor.controls.clear();
hapticImpact('light');
props.onSend(prompt, attached);
};
diff --git a/apps/web/src/features/block-chat/component/Chat.tsx b/apps/web/src/features/block-chat/component/Chat.tsx
index 67b1810607..90a5f71648 100644
--- a/apps/web/src/features/block-chat/component/Chat.tsx
+++ b/apps/web/src/features/block-chat/component/Chat.tsx
@@ -41,6 +41,7 @@ import {
getChatInputStoredState,
type StoredStuff,
storeChatState,
+ storeChatStateImmediate,
} from '@core/component/AI/util/storage';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
import { usePaywallState } from '@core/constant/PaywallState';
@@ -262,7 +263,15 @@ function ChatInner(props: {
const inputText = markdownText();
const attached = input.attachments.attached();
const model_ = input.model();
- saveChatState({ attachments: attached, input: inputText, model: model_ });
+ const state = { attachments: attached, input: inputText, model: model_ };
+ // An empty composer is the sent state. Write it now and drop any
+ // debounced copy of the prompt, so a remount cannot put that prompt
+ // back in the box beside the message already in the transcript.
+ if (inputText.length === 0 && attached.length === 0) {
+ storeChatStateImmediate(props.data.chat.id, state);
+ return;
+ }
+ saveChatState(state);
});
const setPendingLocation = pendingLocationParamsSignal.set;
diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsx
index 8dd2889b84..4ce4bdd879 100644
--- a/apps/web/src/features/channel/Channel/Channel.tsx
+++ b/apps/web/src/features/channel/Channel/Channel.tsx
@@ -672,29 +672,54 @@ export function Channel(props: ChannelProps) {
},
});
+ let sendSurfaceDisposed = false;
+ onCleanup(() => {
+ sendSurfaceDisposed = true;
+ });
+
const onSend: ChannelInputProps['onSend'] = (snapshot) => {
+ const channelId = props.channelId;
const senderId = userId();
if (!senderId) return;
const payload = buildPostMessageSendPayload({
snapshot,
});
- sendMessageMutation.mutate(
- {
- parent: { type: 'channel', id: props.channelId },
- senderId,
- optimisticId: newMessageId(),
- ...payload,
- },
- {
- onError: () => {
+ const optimisticId = newMessageId();
+ fireAndForget(
+ Telemetry.span('channel.send', async (span) => {
+ span.setAttr('message.id', optimisticId);
+ span.setAttr('channel.id', channelId);
+ try {
+ await sendMessageMutation.mutateAsync({
+ parent: { type: 'channel', id: channelId },
+ senderId,
+ optimisticId,
+ ...payload,
+ });
+ span.setAttr('composer.outcome', 'succeeded');
+ } catch {
+ span.error('Channel send failed');
const handle = channelInputHandle();
- if (!handle) return;
+ if (
+ !handle ||
+ sendSurfaceDisposed ||
+ props.channelId !== channelId ||
+ userId() !== senderId
+ ) {
+ span.setAttr('composer.outcome', 'unmounted');
+ return;
+ }
const current = channelInputSnapshot();
- if (current && hasSendableInputContent(current)) return;
+ if (current && hasSendableInputContent(current)) {
+ span.setAttr('composer.outcome', 'preserved_newer_draft');
+ return;
+ }
handle.restoreSnapshot(snapshot);
- },
- }
+ span.setAttr('composer.outcome', 'restored');
+ }
+ }),
+ 'channel-input'
);
};
diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsx
index d2e932358b..aee300d872 100644
--- a/apps/web/src/features/channel/Input/ChannelInput.tsx
+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx
@@ -253,6 +253,9 @@ export function ChannelInput(props: ChannelInputProps) {
// Suppresses focus-out handling during clearComposer's iOS blur/refocus
// cycle, which is not a user-intended blur.
let isInternalRefocus = false;
+ // Assigned once applySnapshot exists. Send clears before the request, so a
+ // failure has to put the same draft back into the editor.
+ let restoreFailedSend = (_snapshot: InputSnapshot) => {};
const {
inputState,
@@ -267,6 +270,7 @@ export function ChannelInput(props: ChannelInputProps) {
callbacks: props,
onSendError: props.onSendError,
clearEditor: () => clearComposer(),
+ restoreEditor: (snapshot) => restoreFailedSend(snapshot),
trackTyping: () => acceptTyping,
attachFiles: async (files) => {
await uploadInputAttachments({
@@ -314,6 +318,9 @@ export function ChannelInput(props: ChannelInputProps) {
acceptTyping = true;
});
};
+ restoreFailedSend = (snapshot) => {
+ applySnapshot(snapshot, { focus: false });
+ };
const flushPendingRestore = () => {
const restore = pendingRestore;
diff --git a/apps/web/src/features/channel/Input/browser-test/README.md b/apps/web/src/features/channel/Input/browser-test/README.md
index 582a1cc81b..f61b433791 100644
--- a/apps/web/src/features/channel/Input/browser-test/README.md
+++ b/apps/web/src/features/channel/Input/browser-test/README.md
@@ -15,3 +15,7 @@ and blocks hosted API traffic, so it needs no backend. It types a draft with a
blank line, unmounts the composer and mounts it again over the persisted draft,
which is the round trip through internal markdown that used to drop every blank
line.
+
+The send regression checks desktop and phone: a pending send clears the editor,
+a rejected send restores its draft, and a rejection preserves a newer draft
+typed while delivery was pending. The fixture controls completion locally.
diff --git a/apps/web/src/features/channel/Input/browser-test/draft.tsx b/apps/web/src/features/channel/Input/browser-test/draft.tsx
index 0423edcbfb..efd745264e 100644
--- a/apps/web/src/features/channel/Input/browser-test/draft.tsx
+++ b/apps/web/src/features/channel/Input/browser-test/draft.tsx
@@ -26,6 +26,10 @@ function Fixture() {
});
onCleanup(() => client.clear());
const [open, setOpen] = createSignal(true);
+ const [sent, setSent] = createSignal('');
+ const [pending, setPending] = createSignal(false);
+ let completeSend: (() => void) | undefined;
+ let failSend: (() => void) | undefined;
return (
<QueryClientProvider client={client}>
<AnalyticsContextProvider>
@@ -39,6 +43,21 @@ function Fixture() {
<button type="button" onClick={() => setOpen(!open())}>
{open() ? 'Leave channel' : 'Open channel'}
</button>
+ <output aria-label="Sent message">{sent()}</output>
+ <button
+ type="button"
+ disabled={!pending()}
+ onClick={() => completeSend?.()}
+ >
+ Complete send
+ </button>
+ <button
+ type="button"
+ disabled={!pending()}
+ onClick={() => failSend?.()}
+ >
+ Fail send
+ </button>
<Show when={open()}>
<ChannelInput
input={{
@@ -46,6 +65,21 @@ function Fixture() {
id: `channel-input-${channelId}`,
placeholder: 'Message #draft-fixture',
}}
+ onSend={(snapshot) => {
+ setSent(snapshot.value);
+ setPending(true);
+ return new Promise<void>((resolve, reject) => {
+ completeSend = () => {
+ setPending(false);
+ resolve();
+ };
+ failSend = () => {
+ setPending(false);
+ reject(new Error('offline'));
+ };
+ });
+ }}
+ onSendError={() => {}}
participants={() => []}
bots={() => []}
persistenceKey={makeInputValuePersistenceKey({
diff --git a/apps/web/src/features/channel/Input/browser-test/send.browser.e2e.ts b/apps/web/src/features/channel/Input/browser-test/send.browser.e2e.ts
new file mode 100644
index 0000000000..038bb8898e
--- /dev/null
+++ b/apps/web/src/features/channel/Input/browser-test/send.browser.e2e.ts
@@ -0,0 +1,50 @@
+import { expect, test } from '@playwright/test';
+
+for (const mobile of [false, true]) {
+ test(`clears a pending send and restores a failed draft on ${mobile ? 'phone' : 'desktop'}`, async ({
+ browser,
+ }) => {
+ const context = await browser.newContext({
+ viewport: mobile
+ ? { width: 390, height: 844 }
+ : { width: 1280, height: 900 },
+ isMobile: mobile,
+ hasTouch: mobile,
+ });
+ const page = await context.newPage();
+ await page.route('**/*', async (route) => {
+ const url = new URL(route.request().url());
+ if (
+ url.hostname === 'localhost' &&
+ !url.pathname.startsWith('/__macro_dev/')
+ )
+ await route.continue();
+ else
+ await route.fulfill({
+ status: 401,
+ contentType: 'application/json',
+ body: '{"responses":[]}',
+ });
+ });
+ await page.routeWebSocket('**/*', (socket) => socket.close());
+ await page.goto('/src/features/channel/Input/browser-test/draft.html');
+ const editor = page.locator('[data-markdown-editable]');
+ await expect(editor).toBeVisible({ timeout: 60_000 });
+ await editor.fill('pending message');
+ await page
+ .getByRole('button', { name: 'Send message', exact: true })
+ .click();
+ await expect(page.getByLabel('Sent message')).toHaveText('pending message');
+ await expect(editor).toHaveText('');
+ await page.getByRole('button', { name: 'Fail send' }).click();
+ await expect(editor).toHaveText('pending message');
+ await page
+ .getByRole('button', { name: 'Send message', exact: true })
+ .click();
+ await expect(editor).toHaveText('');
+ await editor.fill('next draft');
+ await page.getByRole('button', { name: 'Fail send' }).click();
+ await expect(editor).toHaveText('next draft');
+ await context.close();
+ });
+}
diff --git a/apps/web/src/features/channel/Input/create-input-commands.ts b/apps/web/src/features/channel/Input/create-input-commands.ts
index b0e459c438..0046fd1fca 100644
--- a/apps/web/src/features/channel/Input/create-input-commands.ts
+++ b/apps/web/src/features/channel/Input/create-input-commands.ts
@@ -17,6 +17,8 @@ type CreateInputCommandsDeps = {
setIsSending: (value: boolean) => void;
setShowFormatRibbon: (updater: (prev: boolean) => boolean) => void;
reset: () => void;
+ /** Puts a failed send's draft back after the optimistic clear. */
+ restoreSnapshot?: (snapshot: InputSnapshot) => void;
clearComposer?: () => void;
removeTrackedAttachment: (id: string) => void;
attachFiles?: (files: File[]) => Promise<void> | void;
@@ -41,20 +43,42 @@ export function createInputCommands(
return {
send: async () => {
if (deps.view().hasPendingAttachments) return false;
- if (!deps.callbacks?.onSend) return false;
+ const onSend = deps.callbacks?.onSend;
+ if (!onSend) return false;
const current = deps.snapshot();
if (!hasSendableInputContent(current)) return false;
- hapticImpact('light');
- deps.setIsSending(true);
- try {
- await deps.callbacks.onSend(current);
+ return Telemetry.span('message.composer_send', async (span) => {
+ span.setAttr('composer.mode', deps.view().mode);
+ hapticImpact('light');
+ deps.setIsSending(true);
+ // Clear before delivery. The optimistic message paints as soon as
+ // onSend mutates, and waiting for that promise lets the sent text
+ // stay in the box — a second copy — until the request settles.
deps.reset();
deps.clearComposer?.();
- return true;
- } finally {
- deps.setIsSending(false);
- }
+ try {
+ await onSend(current);
+ span.setAttr('composer.outcome', 'dispatched');
+ return true;
+ } catch (error) {
+ const draft = deps.snapshot();
+ if (
+ draft.value.trim().length === 0 &&
+ draft.attachments.length === 0 &&
+ draft.mentions.length === 0
+ ) {
+ deps.restoreSnapshot?.(current);
+ span.setAttr('composer.outcome', 'restored');
+ } else {
+ span.setAttr('composer.outcome', 'preserved_newer_draft');
+ }
+ span.error('Message send failed');
+ throw error;
+ } finally {
+ deps.setIsSending(false);
+ }
+ });
},
attachFiles: async (files: File[]) => {
if (files.length === 0) return;
diff --git a/apps/web/src/features/channel/Input/create-input-state.ts b/apps/web/src/features/channel/Input/create-input-state.ts
index fc55cd08cc..77cee5e274 100644
--- a/apps/web/src/features/channel/Input/create-input-state.ts
+++ b/apps/web/src/features/channel/Input/create-input-state.ts
@@ -16,6 +16,7 @@ type CreateInputStateOptions = {
mentions: Accessor<ItemMention[]>;
attachmentTracker: InputAttachmentTracker;
clearComposer?: () => void;
+ restoreEditor?: (snapshot: InputSnapshot) => void;
attachFiles?: (files: File[]) => Promise<void> | void;
clearInput?: () => void;
callbacks?: InputCallbacks;
@@ -48,6 +49,11 @@ export function createInputState(options: CreateInputStateOptions): InputState {
// Sending/closing clears the editor once, through the focus-preserving path.
clearComposer: options.clearComposer ?? options.clearInput,
reset: view.reset,
+ restoreSnapshot: (snapshot) => {
+ view.setValue(snapshot.value);
+ options.attachmentTracker.setAttachments(snapshot.attachments);
+ options.restoreEditor?.(snapshot);
+ },
removeTrackedAttachment: (id) =>
options.attachmentTracker.removeAttachment(id),
attachFiles: options.attachFiles,
diff --git a/apps/web/src/features/channel/Input/tests/create-input-commands.test.ts b/apps/web/src/features/channel/Input/tests/create-input-commands.test.ts
index 688e17e374..77d3845b13 100644
--- a/apps/web/src/features/channel/Input/tests/create-input-commands.test.ts
+++ b/apps/web/src/features/channel/Input/tests/create-input-commands.test.ts
@@ -73,6 +73,43 @@ describe('createInputCommands', () => {
expect(clearComposer).toHaveBeenCalledOnce();
});
+ it('clears the draft before the message is delivered and restores it when send fails', async () => {
+ let value = 'Hello agent';
+ let duringSend = 'unset';
+ const snapshot = (): InputSnapshot => ({
+ value,
+ mentions: [],
+ attachments: [],
+ });
+ const commands = createInputCommands({
+ view: () => ({
+ mode: 'channel',
+ hasPendingAttachments: false,
+ }),
+ snapshot,
+ setIsSending: vi.fn(),
+ setShowFormatRibbon: vi.fn(),
+ reset: () => {
+ value = '';
+ },
+ restoreSnapshot: (next) => {
+ value = next.value;
+ },
+ clearComposer: vi.fn(),
+ removeTrackedAttachment: vi.fn(),
+ callbacks: {
+ onSend: async () => {
+ duringSend = value;
+ throw new Error('offline');
+ },
+ },
+ });
+
+ await expect(commands.send()).rejects.toThrow('offline');
+ expect(duringSend).toBe('');
+ expect(value).toBe('Hello agent');
+ });
+
it('resets before invoking onClose', () => {
const events: string[] = [];
const snapshot: InputSnapshot = {
diff --git a/apps/web/src/lib/core/component/AI/util/storage.test.ts b/apps/web/src/lib/core/component/AI/util/storage.test.ts
index 23f39346c3..6e037cf013 100644
--- a/apps/web/src/lib/core/component/AI/util/storage.test.ts
+++ b/apps/web/src/lib/core/component/AI/util/storage.test.ts
@@ -1,12 +1,13 @@
/**
* @vitest-environment jsdom
*/
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_MODEL, Model } from '../constant';
import { resolveChatInputModel } from './parse';
import {
getChatInputStoredState,
getChatStoredModel,
+ storeChatState,
storeChatStateImmediate,
} from './storage';
@@ -50,6 +51,26 @@ describe('chat input storage: model defaults', () => {
expect(getChatStoredModel('input-only')).toBeUndefined();
});
+ it('drops a pending draft save when the composer is cleared', () => {
+ vi.useFakeTimers();
+ try {
+ storeChatState('chat-a', {
+ input: 'sent prompt',
+ model: Model.gpt56,
+ attachments: [],
+ });
+ storeChatStateImmediate('chat-a', {
+ input: '',
+ model: Model.gpt56,
+ attachments: [],
+ });
+ vi.advanceTimersByTime(300);
+ expect(getChatInputStoredState('chat-a').input).toBe('');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('preserves a historical provider for icons without selecting an unavailable model', () => {
storeChatStateImmediate('chat-c', {
model: 'openai/gpt-5.5' as Model,
diff --git a/apps/web/src/lib/core/component/AI/util/storage.ts b/apps/web/src/lib/core/component/AI/util/storage.ts
index 1e4ffa63fd..6f4a69179e 100644
--- a/apps/web/src/lib/core/component/AI/util/storage.ts
+++ b/apps/web/src/lib/core/component/AI/util/storage.ts
@@ -46,14 +46,24 @@ function purgeLRU() {
}
purgeLRU();
+// Debounced saves of a draft the user just sent must not land after the
+// composer has already been cleared, or a remount shows the sent message again.
+const chatStateSaveTimeouts: Record<string, ReturnType<typeof setTimeout>> = {};
+
+function cancelChatStateSave(id: string) {
+ const pending = chatStateSaveTimeouts[id];
+ if (!pending) return;
+ clearTimeout(pending);
+ delete chatStateSaveTimeouts[id];
+}
+
// debounced save chat state
function useStoreChatState() {
- const timeouts: Record<string, ReturnType<typeof setTimeout>> = {};
return (id: string, state: Partial<StoredStuff>) => {
- if (timeouts[id]) clearTimeout(timeouts[id]);
- timeouts[id] = setTimeout(() => {
- const updated_at = Date.now();
- setPersistentChatState(id, { ...state, used_at: updated_at });
+ cancelChatStateSave(id);
+ chatStateSaveTimeouts[id] = setTimeout(() => {
+ delete chatStateSaveTimeouts[id];
+ setPersistentChatState(id, { ...state, used_at: Date.now() });
}, 300);
};
}
@@ -64,6 +74,7 @@ export function storeChatStateImmediate(
id: string,
state: Partial<StoredStuff>
) {
+ cancelChatStateSave(id);
setPersistentChatState(id, { ...state, used_at: Date.now() });
}
diff --git a/apps/web/src/lib/core/messages/create-message-composer.test.ts b/apps/web/src/lib/core/messages/create-message-composer.test.ts
index 85ce36e0b8..69cec0a3b2 100644
--- a/apps/web/src/lib/core/messages/create-message-composer.test.ts
+++ b/apps/web/src/lib/core/messages/create-message-composer.test.ts
@@ -24,6 +24,7 @@ it('retains the complete draft after a failed send and clears it after a success
onSendError,
});
});
+ clearEditor.mockImplementation(() => composer.onChange('\n \n'));
try {
composer.mentionsTracker.onMentionCreate({
itemType: 'user',
@@ -32,16 +33,17 @@ it('retains the complete draft after a failed send and clears it after a success
const draft = composer.inputState.snapshot();
expect(await composer.inputState.commands.send()).toBe(false);
expect(composer.inputState.snapshot()).toEqual(draft);
- expect(clearEditor).not.toHaveBeenCalled();
+ // The box clears before delivery so a successful send cannot leave a
+ // second copy behind; a failure puts that same draft back.
+ expect(clearEditor).toHaveBeenCalledOnce();
expect(onSendError).toHaveBeenCalledOnce();
expect(await composer.inputState.commands.send()).toBe(true);
expect(send).toHaveBeenLastCalledWith(draft);
- expect(composer.inputState.snapshot()).toEqual({
- value: '',
- attachments: [],
- mentions: [],
- });
- expect(clearEditor).toHaveBeenCalledOnce();
+ const cleared = composer.inputState.snapshot();
+ expect(cleared.value.trim()).toBe('');
+ expect(cleared.attachments).toEqual([]);
+ expect(cleared.mentions).toEqual([]);
+ expect(clearEditor).toHaveBeenCalledTimes(2);
} finally {
dispose();
}
@@ -75,3 +77,42 @@ it('does not dispatch a second send while the first one is pending', async () =>
dispose();
}
});
+
+it('preserves a new draft typed while a failed send is pending', async () => {
+ let rejectSend!: (error: Error) => void;
+ let dispose!: () => void;
+ const restoreEditor = vi.fn();
+ const composer = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createMessageComposer({
+ input: { mode: 'channel', value: 'first message' },
+ callbacks: {
+ onSend: () =>
+ new Promise<void>((_resolve, reject) => {
+ rejectSend = reject;
+ }),
+ },
+ clearEditor: () => {},
+ restoreEditor,
+ attachFiles: async () => {},
+ onSendError: vi.fn(),
+ });
+ });
+ try {
+ const sending = composer.inputState.commands.send();
+ composer.onChange('next message');
+ composer.attachmentTracker.setAttachments([
+ { id: 'next-doc', kind: 'document', name: 'Document' },
+ ]);
+ rejectSend(new Error('offline'));
+ expect(await sending).toBe(false);
+ expect(composer.inputState.snapshot()).toEqual({
+ value: 'next message',
+ attachments: [{ id: 'next-doc', kind: 'document', name: 'Document' }],
+ mentions: [],
+ });
+ expect(restoreEditor).not.toHaveBeenCalled();
+ } finally {
+ dispose();
+ }
+});
diff --git a/apps/web/src/lib/core/messages/create-message-composer.ts b/apps/web/src/lib/core/messages/create-message-composer.ts
index 85c4d45e1d..13d567e631 100644
--- a/apps/web/src/lib/core/messages/create-message-composer.ts
+++ b/apps/web/src/lib/core/messages/create-message-composer.ts
@@ -7,6 +7,7 @@ import type {
InputCallbacks,
InputData,
InputPersistenceKey,
+ InputSnapshot,
} from '@channel/Input/types';
type ComposerOptions = {
@@ -15,6 +16,8 @@ type ComposerOptions = {
attachmentTracker?: InputAttachmentTracker;
persistenceKey?: InputPersistenceKey;
clearEditor: () => void;
+ /** Puts the editor draft back when send fails after the optimistic clear. */
+ restoreEditor?: (snapshot: InputSnapshot) => void;
attachFiles: (files: File[]) => Promise<void>;
trackTyping?: () => boolean;
onSendError?: (error: unknown) => void;
@@ -42,6 +45,10 @@ export function createMessageComposer(options: ComposerOptions) {
mentionsTracker.setMentions([]);
options.clearEditor();
},
+ restoreEditor: (snapshot) => {
+ mentionsTracker.setMentions(snapshot.mentions);
+ options.restoreEditor?.(snapshot);
+ },
callbacks: {
onChange: options.callbacks.onChange,
onToggleFormatRibbon: options.callbacks.onToggleFormatRibbon,
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 50a9726ff0..28a9dfbaf1 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -1421,3 +1421,10 @@ If the metadata is unavailable, the fallback extension comes from the response
MIME type. Linked video preview cards also offer Download, using the document's
current version, name, and file type. See [Downloading files](files.md#downloading-files)
for progress, cancellation, retries, and mobile save/share verification.
+
+## Pending message drafts
+
+Sending clears the composer immediately while delivery is pending. If delivery
+fails and the composer is still empty, its text, mentions, and attachments return.
+A new draft typed during delivery stays intact if the earlier send fails. Verify
+this with both the Send button on a phone and the desktop composer.