Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(chat-input): queue send while uploading, one fixed Send/Stop button (#23095)

YuTengjing24f4e3702ab9
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 0db0963c659..9b1590299ca 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1732,6 +1732,7 @@
"input.more": "More",
"input.notice.summary_one": "{{count}} input notice",
"input.notice.summary_other": "{{count}} input notices",
+ "input.running": "Agent is running",
"input.schedule.cancel": "Cancel",
"input.schedule.clear": "Cancel scheduled send",
"input.schedule.failed": "Could not schedule this message. Try again.",
@@ -1744,6 +1745,8 @@
"input.sendWithCmdEnter": "Press <key/> to send",
"input.sendWithEnter": "Press <key/> to send",
"input.stop": "Stop",
+ "input.uploadFailedNotSent_one": "{{count}} attachment failed to upload and was not sent. It stays in the input to retry or remove.",
+ "input.uploadFailedNotSent_other": "{{count}} attachments failed to upload and were not sent. They stay in the input to retry or remove.",
"input.viewOnlyAgent": "You can only view this agent",
"input.viewOnlyGroup": "You can only view this group",
"input.warp": "New Line",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 707fd4f7a45..f5d7ba3921f 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1170,6 +1170,8 @@
"hotkey.invalidCombination": "The hotkey must include at least one modifier key (Ctrl, Alt, Shift) and one regular key",
"hotkey.record": "Press a key to record the hotkey",
"hotkey.reset": "Reset to default hotkeys",
+ "hotkey.sendKey.desc": "The other combination inserts a new line",
+ "hotkey.sendKey.title": "Send message",
"hotkey.title": "Hotkeys",
"hotkey.updateError": "Failed to update hotkey: Network or system error",
"hotkey.updateSuccess": "Hotkey updated successfully",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 05102dc1d37..ed13023e3a4 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1732,6 +1732,7 @@
"input.more": "更多",
"input.notice.summary_one": "{{count}} 个输入提醒",
"input.notice.summary_other": "{{count}} 个输入提醒",
+ "input.running": "助理运行中",
"input.schedule.cancel": "取消排期",
"input.schedule.clear": "取消定时",
"input.schedule.failed": "定时发送失败,请重试",
@@ -1744,6 +1745,8 @@
"input.sendWithCmdEnter": "按 <key/> 发送",
"input.sendWithEnter": "按 <key/> 发送",
"input.stop": "停止",
+ "input.uploadFailedNotSent_one": "{{count}} 个附件上传失败,未随消息发送,已保留在输入框中,可重试或移除",
+ "input.uploadFailedNotSent_other": "{{count}} 个附件上传失败,未随消息发送,已保留在输入框中,可重试或移除",
"input.viewOnlyAgent": "您仅可查看该助理",
"input.viewOnlyGroup": "您仅可查看该群组",
"input.warp": "换行",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index e888da6a44d..4964b016dee 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1170,6 +1170,8 @@
"hotkey.invalidCombination": "快捷键需要至少包含一个修饰键 (Ctrl, Alt, Shift) 和一个常规键",
"hotkey.record": "按下按键以录制快捷键",
"hotkey.reset": "重置为默认快捷键",
+ "hotkey.sendKey.desc": "另一种组合用于换行",
+ "hotkey.sendKey.title": "发送消息",
"hotkey.title": "快捷键",
"hotkey.updateError": "快捷键更新失败:网络或系统错误",
"hotkey.updateSuccess": "快捷键更新成功",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d9a5449c797..c0370e0a21a 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1072,7 +1072,12 @@ export default {
'input.send': 'Send',
'input.sendWithCmdEnter': 'Press <key/> to send',
'input.sendWithEnter': 'Press <key/> to send',
+ 'input.running': 'Agent is running',
'input.stop': 'Stop',
+ 'input.uploadFailedNotSent_one':
+ '{{count}} attachment failed to upload and was not sent. It stays in the input to retry or remove.',
+ 'input.uploadFailedNotSent_other':
+ '{{count}} attachments failed to upload and were not sent. They stay in the input to retry or remove.',
'input.warp': 'New Line',
'input.warpWithKey': 'Press <key/> to insert a line break',
'inputQueue.delete': 'Delete',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 50ca45b26cd..6ded6b8b25f 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1070,6 +1070,8 @@ export default {
'The hotkey must include at least one modifier key (Ctrl, Alt, Shift) and one regular key',
'hotkey.record': 'Press a key to record the hotkey',
'hotkey.reset': 'Reset to default hotkeys',
+ 'hotkey.sendKey.desc': 'The other combination inserts a new line',
+ 'hotkey.sendKey.title': 'Send message',
'hotkey.title': 'Hotkeys',
'hotkey.updateError': 'Failed to update hotkey: Network or system error',
'hotkey.updateSuccess': 'Hotkey updated successfully',
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index 6c22883205c..7da63ae54df 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -27,13 +27,13 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
sendButtonProps,
onSend,
onVoiceMessageSend,
- sendMenu,
chatInputEditorRef,
onMarkdownContentChange,
mentionItems,
allowExpand = true,
slashPlacement,
getMessages,
+ queueSendWhileUploading,
resolveSendBlocked,
topicId,
uploadContextKey,
@@ -58,7 +58,6 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
rightActions,
onVoiceMessageSend,
sendButtonProps,
- sendMenu,
slashMenuRef,
slashPlacement,
topicId,
@@ -79,10 +78,10 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
leftActions={leftActions}
mentionItems={mentionItems}
mobile={mobile}
+ queueSendWhileUploading={queueSendWhileUploading}
resolveSendBlocked={resolveSendBlocked}
rightActions={rightActions}
sendButtonProps={sendButtonProps}
- sendMenu={sendMenu}
slashPlacement={slashPlacement}
topicId={topicId}
uploadContextKey={uploadContextKey}
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index 47c579dd50e..871bc2db7bd 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -243,15 +243,9 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
style={actionBarStyle ?? { paddingRight: 8 }}
right={
loadingRightSlot ??
- rightContent ??
- (sendAreaPrefix ? (
- <Flexbox horizontal align={'center'} gap={6}>
- {sendAreaPrefix}
- <SendArea hideContextWindow={hasControlBar} />
- </Flexbox>
- ) : (
- <SendArea hideContextWindow={hasControlBar} />
- ))
+ rightContent ?? (
+ <SendArea hideContextWindow={hasControlBar} prefix={sendAreaPrefix} />
+ )
}
/>
)
diff --git a/src/features/ChatInput/SendArea/RunningIndicator.tsx b/src/features/ChatInput/SendArea/RunningIndicator.tsx
new file mode 100644
index 00000000000..8e3df5d0746
--- /dev/null
+++ b/src/features/ChatInput/SendArea/RunningIndicator.tsx
@@ -0,0 +1,35 @@
+import { cssVar, Icon, Tooltip } from '@lobehub/ui';
+import { LoaderCircleIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatInputStore } from '../store';
+
+/**
+ * A small spinner at the head of the send area while the agent runs, so it sits
+ * beside the model selector that qualifies the run. Stop itself stays static.
+ */
+const RunningIndicator = memo(() => {
+ const { t } = useTranslation('chat');
+ const generating = useChatInputStore((s) => !!s.sendButtonProps?.generating);
+
+ if (!generating) return null;
+
+ return (
+ <Tooltip title={t('input.running')}>
+ <Icon
+ spin
+ aria-label={t('input.running')}
+ color={cssVar.colorTextTertiary}
+ data-testid="chat-input-running-indicator"
+ icon={LoaderCircleIcon}
+ role={'status'}
+ size={14}
+ />
+ </Tooltip>
+ );
+});
+
+RunningIndicator.displayName = 'RunningIndicator';
+
+export default RunningIndicator;
diff --git a/src/features/ChatInput/SendArea/SendButton.tsx b/src/features/ChatInput/SendArea/SendButton.tsx
index e2b19c85ac7..316477a86de 100644
--- a/src/features/ChatInput/SendArea/SendButton.tsx
+++ b/src/features/ChatInput/SendArea/SendButton.tsx
@@ -8,19 +8,24 @@ import { usePermission } from '@/hooks/usePermission';
import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { selectors, useChatInputStore } from '../store';
+import { PendingSendButton, StopButton } from './StateButton';
const SendButton = memo(() => {
const { t } = useTranslation('setting');
- const sendMenu = useChatInputStore((s) => s.sendMenu);
const shape = useChatInputStore((s) => s.sendButtonProps?.shape);
const size = useChatInputStore((s) => s.sendButtonProps?.size);
- const { generating, disabled, showSendWhileGenerating } = useChatInputStore(
- selectors.sendButtonProps,
- isEqual,
- );
+ const {
+ generating,
+ disabled,
+ loading: dispatching,
+ showSendWhileGenerating,
+ } = useChatInputStore(selectors.sendButtonProps, isEqual);
const [send, handleStop] = useChatInputStore((s) => [s.handleSendButton, s.handleStop]);
- // Market agents/skills picked from the @ menu install before the send commits.
+ // A send that is committed but not yet sent shows as a loading Send: Market
+ // agents/skills picked from the @ menu are installing, or uploads are settling.
const installing = useChatInputStore((s) => s.installingMarketMentions);
+ const queuedForUploads = useChatInputStore(selectors.isSendQueuedForUploads);
+ const queued = installing || queuedForUploads;
// Workspace viewer doesn't have `message:create` → backend would 403.
// OR the permission gate into the existing disabled prop so the button
@@ -33,34 +38,32 @@ const SendButton = memo(() => {
const viewOnly = !canUseResource;
const canSend = canCreate && !viewOnly;
- // Stop keeps its spinner so the running state stays visible; Send sits beside
- // it for the follow-up the user typed (Enter sends too).
- const button =
- generating && showSendWhileGenerating ? (
- <Flexbox horizontal align={'center'} gap={8}>
- <Send generating shape={shape} size={size} onStop={() => handleStop()} />
- <Send
- disabled={disabled || !canSend}
- loading={installing}
- shape={shape}
- size={size}
- onClick={canSend ? () => send() : undefined}
- />
- </Flexbox>
+ // Only a pending send spins, inside Send itself. A running turn shows a static
+ // Stop; the run is indicated once, by RunningIndicator beside the model selector.
+ // Send sits beside Stop for the follow-up the user typed (Enter sends too).
+ const renderSend = (pending: boolean) =>
+ pending ? (
+ <PendingSendButton shape={shape} size={size} />
) : (
<Send
disabled={disabled || !canSend}
- generating={generating}
- loading={installing}
- menu={canSend ? (sendMenu as any) : undefined}
- placement={'topRight'}
shape={shape}
size={size}
- trigger={['hover']}
- onClick={generating || !canSend ? undefined : () => send()}
- onStop={() => handleStop()}
+ onClick={canSend ? () => send() : undefined}
/>
);
+ const stop = <StopButton shape={shape} size={size} onStop={() => handleStop()} />;
+ const button =
+ generating && showSendWhileGenerating ? (
+ <Flexbox horizontal align={'center'} gap={8}>
+ {stop}
+ {renderSend(queued)}
+ </Flexbox>
+ ) : generating ? (
+ stop
+ ) : (
+ renderSend(queued || !!dispatching)
+ );
if (!canCreate) return <Tooltip title={reason}>{button}</Tooltip>;
if (viewOnly) return <Tooltip title={t('permission.viewOnlySendTip')}>{button}</Tooltip>;
diff --git a/src/features/ChatInput/SendArea/StateButton.tsx b/src/features/ChatInput/SendArea/StateButton.tsx
new file mode 100644
index 00000000000..57a009eb02d
--- /dev/null
+++ b/src/features/ChatInput/SendArea/StateButton.tsx
@@ -0,0 +1,78 @@
+import { Button } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface StateButtonProps {
+ shape?: 'round' | 'default';
+ size?: number;
+}
+
+/**
+ * Send and its other states share one solid button of a fixed size; only the glyph
+ * changes, as in Codex's composer. `@lobehub/editor`'s `SendButton` cannot do this:
+ * its `loading` also disables the button, which grays it out, and its `generating`
+ * Stop spins for the whole run.
+ */
+const buttonStyle = (size: number) => ({
+ flex: 'none',
+ height: size,
+ paddingInline: 0,
+ width: size,
+});
+
+/**
+ * Stops the running turn. A plain square, still: the run itself is indicated once,
+ * by `RunningIndicator` beside the model selector.
+ */
+export const StopButton = memo<StateButtonProps & { onStop: () => void }>(
+ ({ onStop, shape, size = 32 }) => {
+ const { t } = useTranslation('chat');
+ const glyph = Math.round(size * 0.34);
+
+ return (
+ <Button
+ aria-label={t('input.stop')}
+ data-testid="chat-input-stop"
+ shape={shape}
+ style={buttonStyle(size)}
+ title={t('input.stop')}
+ type={'primary'}
+ icon={
+ <svg aria-hidden height={glyph} viewBox="0 0 10 10" width={glyph}>
+ <rect fill="currentColor" height="10" rx="2" width="10" />
+ </svg>
+ }
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ onStop();
+ }}
+ />
+ );
+ },
+);
+
+StopButton.displayName = 'StopButton';
+
+/**
+ * A send that is committed but not out yet (uploads settling, the message being
+ * created): the Send button keeps its color and shows a spinner in place of the arrow.
+ * `loading` already blocks clicks; it also marks the button `aria-disabled`, which the
+ * Button styles dim to half opacity, so opacity is pinned back to full.
+ */
+export const PendingSendButton = memo<StateButtonProps>(({ shape, size = 32 }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <Button
+ loading
+ aria-label={t('input.send')}
+ data-testid="chat-input-send-pending"
+ shape={shape}
+ style={{ ...buttonStyle(size), cursor: 'default', opacity: 1 }}
+ type={'primary'}
+ />
+ );
+});
+
+PendingSendButton.displayName = 'PendingSendButton';
diff --git a/src/features/ChatInput/SendArea/index.tsx b/src/features/ChatInput/SendArea/index.tsx
index 979be309acc..38146124054 100644
--- a/src/features/ChatInput/SendArea/index.tsx
+++ b/src/features/ChatInput/SendArea/index.tsx
@@ -1,12 +1,13 @@
import { Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
-import { memo, useMemo } from 'react';
+import { memo, type ReactNode, useMemo } from 'react';
import { type ActionKey } from '../ActionBar/config';
import { actionMap } from '../ActionBar/config';
import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
import { useChatInputStore } from '../store';
import { resolveSendAreaActionKeys } from './resolveActionKeys';
+import RunningIndicator from './RunningIndicator';
import SendButton from './SendButton';
const mapActionsToItems = (keys: ActionKey[]) =>
@@ -22,9 +23,11 @@ interface SendAreaProps {
* `false` or the token indicator has nowhere to render.
*/
hideContextWindow?: boolean;
+ /** Host content placed right before the actions, e.g. a heterogeneous agent's model selector. */
+ prefix?: ReactNode;
}
-const SendArea = memo<SendAreaProps>(({ hideContextWindow = true }) => {
+const SendArea = memo<SendAreaProps>(({ hideContextWindow = true, prefix }) => {
const { canShowControls } = useChatInputResourceAccess();
const rightActions = useChatInputStore((s) => s.rightActions, isEqual);
const activeAudioInputMode = useChatInputStore((s) => s.activeAudioInputMode);
@@ -46,9 +49,15 @@ const SendArea = memo<SendAreaProps>(({ hideContextWindow = true }) => {
return (
/** The model label must yield space before the footer clips Send on narrow panels. */
- <Flexbox horizontal align={'center'} flex={'0 1 auto'} gap={12} style={{ minWidth: 0 }}>
- {items}
- {!audioInputActive && <SendButton />}
+ <Flexbox horizontal align={'center'} flex={'0 1 auto'} gap={6} style={{ minWidth: 0 }}>
+ {/* Heads the group, so it sits beside the model selector — the host's prefix or the
+ first action item — whichever one this composer shows. */}
+ {!audioInputActive && <RunningIndicator />}
+ {prefix}
+ <Flexbox horizontal align={'center'} flex={'0 1 auto'} gap={12} style={{ minWidth: 0 }}>
+ {items}
+ {!audioInputActive && <SendButton />}
+ </Flexbox>
</Flexbox>
);
});
diff --git a/src/features/ChatInput/StoreUpdater.test.tsx b/src/features/ChatInput/StoreUpdater.test.tsx
index d27fb389d7b..8c680c3413d 100644
--- a/src/features/ChatInput/StoreUpdater.test.tsx
+++ b/src/features/ChatInput/StoreUpdater.test.tsx
@@ -1,4 +1,3 @@
-import { type DropdownItem } from '@lobehub/ui';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { type PropsWithChildren, useEffect } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -45,25 +44,6 @@ vi.mock('./VoiceMessage/useVoiceMessageRecorder', () => ({
useVoiceMessageRecorder: () => voiceRecorder,
}));
-interface TestHarnessProps {
- onSendMenuChange: (menu: { items: DropdownItem[] } | undefined) => void;
- sendMenu?: { items: DropdownItem[] };
-}
-
-const Probe = ({
- onSendMenuChange,
-}: {
- onSendMenuChange: TestHarnessProps['onSendMenuChange'];
-}) => {
- const sendMenu = useChatInputStore((s) => s.sendMenu);
-
- useEffect(() => {
- onSendMenuChange(sendMenu);
- }, [onSendMenuChange, sendMenu]);
-
- return null;
-};
-
const VoiceCapabilityProbe = ({ onChange }: { onChange: (value?: boolean) => void }) => {
const canRecordVoiceMessage = useChatInputStore((s) => s.canRecordVoiceMessage);
@@ -88,71 +68,81 @@ beforeEach(() => {
});
describe('ChatInput StoreUpdater', () => {
- it('keeps follow-up Send disabled during uploads and restores it without disabling Stop', () => {
+ it('shows a queued follow-up as a loading Send beside a static Stop', () => {
const onStop = vi.fn();
const send = vi.fn();
const store = createStore();
store.setState({ handleSendButton: send, handleStop: onStop });
- const composer = (isUploading: boolean) => (
+ render(
<Provider createStore={() => store}>
<StoreUpdater
leftActions={[]}
rightActions={[]}
sendButtonProps={getConversationSendButtonProps(
- { disabled: isUploading, generating: true, onStop, showSendWhileGenerating: true },
- { disabled: false, shape: 'round' },
- isUploading,
+ { disabled: false, generating: true, onStop, showSendWhileGenerating: true },
+ { shape: 'round' },
)}
/>
<SendButton />
- </Provider>
+ </Provider>,
);
- const { rerender } = render(composer(true));
- const [stopButton, sendButton] = screen.getAllByRole('button');
+ act(() => store.setState({ uploadQueuedSend: { draftKey: undefined, unsubscribe: vi.fn() } }));
+ const stopButton = screen.getByTestId('chat-input-stop');
+ const sendButton = screen.getByTestId('chat-input-send-pending');
+
+ // Stop draws its square only — no spinning arc around it.
+ expect(stopButton.querySelectorAll('svg')).toHaveLength(1);
+ expect(stopButton.querySelector('circle')).toBeNull();
expect(stopButton).not.toBeDisabled();
- expect(sendButton).toBeDisabled();
+ expect(sendButton).toHaveAttribute('aria-busy', 'true');
fireEvent.click(sendButton);
expect(send).not.toHaveBeenCalled();
fireEvent.click(stopButton);
expect(onStop).toHaveBeenCalledOnce();
- rerender(composer(false));
- const [restoredStop, restoredSend] = screen.getAllByRole('button');
- expect(restoredStop).not.toBeDisabled();
+ act(() => store.setState({ uploadQueuedSend: undefined }));
+ expect(screen.queryByTestId('chat-input-send-pending')).toBeNull();
+ const [, restoredSend] = screen.getAllByRole('button');
expect(restoredSend).not.toBeDisabled();
fireEvent.click(restoredSend);
expect(send).toHaveBeenCalledOnce();
});
- it('clears sendMenu when the prop becomes undefined', () => {
- const initialSendMenu = { items: [{ key: 'test', label: 'Test' }] } satisfies {
- items: DropdownItem[];
- };
- const onSendMenuChange = vi.fn();
+ it('drops a send queued for uploads as soon as the conversation switches', () => {
+ const store = createStore();
+ const renderAt = (draftKey: string) => (
+ <Provider createStore={() => store}>
+ <StoreUpdater draftKey={draftKey} leftActions={[]} rightActions={[]} />
+ </Provider>
+ );
+ const { rerender } = render(renderAt('tpc_a'));
+ const unsubscribe = vi.fn();
+ act(() => store.setState({ uploadQueuedSend: { draftKey: 'tpc_a', unsubscribe } }));
- const { rerender } = render(
- <TestHarness>
+ rerender(renderAt('tpc_b'));
+ // Coming back before the uploads settle must not revive it.
+ rerender(renderAt('tpc_a'));
+
+ expect(unsubscribe).toHaveBeenCalledOnce();
+ expect(store.getState().uploadQueuedSend).toBeUndefined();
+ });
+
+ it('shows Send as loading instead of Stop while the sent message is being created', () => {
+ const store = createStore();
+ render(
+ <Provider createStore={() => store}>
<StoreUpdater
leftActions={[]}
rightActions={[]}
- sendMenu={initialSendMenu}
- onSend={() => {}}
+ sendButtonProps={{ generating: false, loading: true, onStop: vi.fn() }}
/>
- <Probe onSendMenuChange={onSendMenuChange} />
- </TestHarness>,
- );
-
- expect(onSendMenuChange).toHaveBeenLastCalledWith(initialSendMenu);
-
- rerender(
- <TestHarness>
- <StoreUpdater leftActions={[]} rightActions={[]} sendMenu={undefined} onSend={() => {}} />
- <Probe onSendMenuChange={onSendMenuChange} />
- </TestHarness>,
+ <SendButton />
+ </Provider>,
);
- expect(onSendMenuChange).toHaveBeenLastCalledWith(undefined);
+ expect(screen.queryByTestId('chat-input-stop')).toBeNull();
+ expect(screen.getByTestId('chat-input-send-pending')).toHaveAttribute('aria-busy', 'true');
});
it('keeps canRecordVoiceMessage in sync when the prop changes', () => {
diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsx
index 6e71f231f91..eac7f38d72c 100644
--- a/src/features/ChatInput/StoreUpdater.tsx
+++ b/src/features/ChatInput/StoreUpdater.tsx
@@ -30,11 +30,11 @@ const StoreUpdater = memo<StoreUpdaterProps>(
onSend,
onVoiceMessageSend,
onMarkdownContentChange,
- sendMenu,
mentionItems,
allowExpand,
slashPlacement,
getMessages,
+ queueSendWhileUploading,
resolveSendBlocked,
topicId,
uploadContextKey,
@@ -55,6 +55,9 @@ const StoreUpdater = memo<StoreUpdaterProps>(
// it post-paint would flash the previous topic's draft for one frame.
useLayoutEffect(() => {
if (draftKey !== undefined && storeApi.getState().draftKey !== draftKey) {
+ // A send queued in the conversation being left must not fire if the user
+ // comes back before its uploads settle: drop it on the first switch.
+ storeApi.getState().cancelUploadQueuedSend();
storeApi.setState({ draftKey });
}
}, [draftKey, storeApi]);
@@ -69,16 +72,14 @@ const StoreUpdater = memo<StoreUpdaterProps>(
useStoreUpdater('sendButtonProps', sendButtonProps);
useStoreUpdater('resolveSendBlocked', resolveSendBlocked);
+ useStoreUpdater('queueSendWhileUploading', queueSendWhileUploading);
+ // A send queued for uploads watches the global file store; an unmounted
+ // composer has nothing left to send it from.
+ useEffect(() => () => storeApi.getState().cancelUploadQueuedSend(), [storeApi]);
useStoreUpdater('onSend', onSend);
useStoreUpdater('onVoiceMessageSend', onVoiceMessageSend);
useStoreUpdater('onMarkdownContentChange', onMarkdownContentChange);
- useEffect(() => {
- // `createStoreUpdater` skips undefined values, but follow-up mode needs to
- // actively clear any previously injected send menu from the store.
- storeApi.setState({ sendMenu });
- }, [sendMenu, storeApi]);
-
useImperativeHandle(chatInputEditorRef, () => editor);
return null;
diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.ts
index 791be9c5b02..3fb7a183ec0 100644
--- a/src/features/ChatInput/store/action.test.ts
+++ b/src/features/ChatInput/store/action.test.ts
@@ -6,9 +6,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { installMarketMentions, MarketMentionInstallError } from '@/services/mentionMarketInstall';
import { useAgentStore } from '@/store/agent';
+import { useFileStore } from '@/store/file';
import { systemAgentSelectors } from '@/store/user/selectors';
+import type { UploadFileItem } from '@/types/files/upload';
import { getDraft, saveDraft } from '../draftStorage';
+import { SYNC_IMAGE_REF_TAGS_COMMAND } from '../InputEditor/ImageRefTag/ImageRefTagPlugin';
import { getInputHistory } from '../inputHistoryStorage';
import { createStore, selectors } from '.';
@@ -468,3 +471,107 @@ describe('ChatInput store actions', () => {
});
});
});
+
+describe('sending while uploads are in flight', () => {
+ const KEY = 'main_agt_a_tpc_1';
+ const upload = (id: string, status: UploadFileItem['status']) =>
+ ({
+ file: { name: `${id}.png`, type: 'image/png' },
+ id,
+ previewUrl: `blob:${id}`,
+ status,
+ }) as unknown as UploadFileItem;
+ const setUploads = (files: UploadFileItem[]) =>
+ useFileStore.setState({ chatUploadFileListByContext: { [KEY]: files } });
+
+ beforeEach(() => {
+ localStorage.clear();
+ setUploads([]);
+ });
+
+ it('queues the send until every upload settles, then sends with the settled numbering', () => {
+ const editor = createHelloEditor();
+ const onSend = vi.fn();
+ const store = createStore({
+ contextSelectionKey: KEY,
+ draftKey: KEY,
+ editor: editor as unknown as IEditor,
+ onSend,
+ queueSendWhileUploading: true,
+ });
+ setUploads([upload('a', 'uploading'), upload('b', 'uploading')]);
+
+ store.getState().handleSendButton();
+ expect(onSend).not.toHaveBeenCalled();
+ expect(selectors.isSendQueuedForUploads(store.getState())).toBe(true);
+
+ // A second press while queued neither sends nor queues twice.
+ store.getState().handleSendButton();
+ setUploads([upload('a', 'error'), upload('b', 'uploading')]);
+ expect(onSend).not.toHaveBeenCalled();
+
+ setUploads([upload('a', 'error'), upload('b', 'success')]);
+ expect(onSend).toHaveBeenCalledOnce();
+ expect(selectors.isSendQueuedForUploads(store.getState())).toBe(false);
+ // The failed image takes no number, so the one that uploaded is [Image #1].
+ const syncPayload = editor.dispatchCommand.mock.calls.find(
+ ([command]) => command === SYNC_IMAGE_REF_TAGS_COMMAND,
+ )?.[1];
+ expect([...syncPayload.refs.values()]).toEqual([{ fileId: 'b', number: 1, src: 'blob:b' }]);
+ });
+
+ it('drops a queued send once the composer shows another conversation', () => {
+ const onSend = vi.fn();
+ const store = createStore({
+ contextSelectionKey: KEY,
+ draftKey: KEY,
+ editor: createHelloEditor() as unknown as IEditor,
+ onSend,
+ queueSendWhileUploading: true,
+ });
+ setUploads([upload('a', 'uploading')]);
+
+ store.getState().handleSendButton();
+ store.setState({ draftKey: 'main_agt_a_tpc_2' });
+ // The conversation now on screen has nothing queued.
+ expect(selectors.isSendQueuedForUploads(store.getState())).toBe(false);
+
+ setUploads([upload('a', 'success')]);
+ expect(onSend).not.toHaveBeenCalled();
+ expect(store.getState().uploadQueuedSend).toBeUndefined();
+ });
+
+ it('stops watching the uploads once the queued send is cancelled', () => {
+ const onSend = vi.fn();
+ const store = createStore({
+ contextSelectionKey: KEY,
+ draftKey: KEY,
+ editor: createHelloEditor() as unknown as IEditor,
+ onSend,
+ queueSendWhileUploading: true,
+ });
+ setUploads([upload('a', 'uploading')]);
+
+ store.getState().handleSendButton();
+ store.getState().cancelUploadQueuedSend();
+ expect(store.getState().uploadQueuedSend).toBeUndefined();
+
+ setUploads([upload('a', 'success')]);
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it('leaves the upload gate to hosts that do not opt in', () => {
+ const onSend = vi.fn();
+ const store = createStore({
+ contextSelectionKey: KEY,
+ editor: createHelloEditor() as unknown as IEditor,
+ onSend,
+ });
+ setUploads([upload('a', 'uploading')]);
+
+ store.getState().handleSendButton();
+
+ expect(onSend).toHaveBeenCalledOnce();
+ expect(store.getState().uploadQueuedSend).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.ts
index 9ac590d8fca..ed5d65009d8 100644
--- a/src/features/ChatInput/store/action.ts
+++ b/src/features/ChatInput/store/action.ts
@@ -5,23 +5,31 @@ import { type StateCreator } from 'zustand/vanilla';
import { installMarketMentions, MarketMentionInstallError } from '@/services/mentionMarketInstall';
import { useAgentStore } from '@/store/agent';
+import { fileChatSelectors, useFileStore } from '@/store/file';
import { useUserStore } from '@/store/user';
import { systemAgentSelectors, userProfileSelectors } from '@/store/user/selectors';
import { removeDraft } from '../draftStorage';
import { readDocument, writeDocument } from '../editorDocument';
import { getInstalledSkillIdentifiers } from '../InputEditor/ActionTag/useInstalledSkillsAndTools';
-import { PRUNE_UNATTACHED_IMAGE_REFS_COMMAND } from '../InputEditor/ImageRefTag/ImageRefTagPlugin';
+import {
+ PRUNE_UNATTACHED_IMAGE_REFS_COMMAND,
+ SYNC_IMAGE_REF_TAGS_COMMAND,
+} from '../InputEditor/ImageRefTag/ImageRefTagPlugin';
import {
applyInstalledMarketAgents,
collectPendingMarketAgents,
collectPendingMarketSkills,
} from '../InputEditor/marketMention';
import { addInputHistory } from '../inputHistoryStorage';
+import { getImageUploadRefs } from '../utils/imageUploads';
import { type PublicState, type State } from './initialState';
import { initialState } from './initialState';
+import { selectors } from './selectors';
export interface Action {
+ /** Drop a send queued for uploads and stop watching them (e.g. the composer unmounts). */
+ cancelUploadQueuedSend: () => void;
clearInputCompletionError: () => void;
dismissInputCompletionError: () => void;
getJSONState: () => Record<string, any> | undefined;
@@ -55,6 +63,13 @@ export const store: CreateStore = (publicState) => (set, get) => ({
leftActions: publicState?.leftActions ?? initialState.leftActions,
rightActions: publicState?.rightActions ?? initialState.rightActions,
+ cancelUploadQueuedSend: () => {
+ const queued = get().uploadQueuedSend;
+ if (!queued) return;
+ queued.unsubscribe();
+ set({ uploadQueuedSend: undefined });
+ },
+
clearInputCompletionError: () => {
set({ inputCompletionError: undefined, inputCompletionErrorDismissed: false });
},
@@ -75,8 +90,43 @@ export const store: CreateStore = (publicState) => (set, get) => ({
const { installingMarketMentions, resolveSendBlocked, sendButtonProps } = get();
if (installingMarketMentions) return;
+ if (selectors.isSendQueuedForUploads(get())) return;
if (resolveSendBlocked ? resolveSendBlocked() : sendButtonProps?.disabled) return;
+ // Uploads still in flight: queue the send instead of refusing it. The composer keeps
+ // its content (and stays editable) until every upload settles, then the send goes
+ // through this same path with whatever the composer holds by then, so an edit made
+ // while waiting is sent too and a failed upload is left for the host to drop.
+ const uploadKey = get().uploadContextKey ?? get().contextSelectionKey;
+ if (
+ get().queueSendWhileUploading &&
+ uploadKey &&
+ fileChatSelectors.isUploadingFiles(uploadKey)(useFileStore.getState())
+ ) {
+ const queued = { draftKey: get().draftKey, unsubscribe: () => {} };
+ set({ uploadQueuedSend: queued });
+ const unsubscribe = useFileStore.subscribe((fileState) => {
+ if (fileChatSelectors.isUploadingFiles(uploadKey)(fileState)) return;
+ unsubscribe();
+ // A newer queued send (made after a conversation switch) owns the state now.
+ if (get().uploadQueuedSend !== queued) return;
+ set({ uploadQueuedSend: undefined });
+ // The composer outlives a conversation switch; the conversation it now
+ // shows never asked to send, so the send is dropped.
+ if (get().draftKey !== queued.draftKey) return;
+
+ // The inline references re-sync from a React effect that has not run yet at
+ // this point; bring them in line with the settled uploads first, so a failed
+ // image loses its [Image #N] and the rest keep the numbers they are sent with.
+ get().editor?.dispatchCommand(SYNC_IMAGE_REF_TAGS_COMMAND, {
+ refs: getImageUploadRefs(fileChatSelectors.chatUploadFileList(uploadKey)(fileState)),
+ });
+ get().handleSendButton();
+ });
+ queued.unsubscribe = unsubscribe;
+ return;
+ }
+
// Drop any pending AI input-completion ghost before serializing the message.
// The suggestion is materialized as real placeholder nodes inside the
// document, so sending without clearing would emit the ghost text too —
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index 519f49d0b95..b4f0c41f5d6 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -6,7 +6,6 @@ import {
} from '@lobechat/types';
import { type IEditor, type SlashOptions } from '@lobehub/editor';
import { type ChatInputProps } from '@lobehub/editor/react';
-import { type DropdownItem } from '@lobehub/ui';
import { type ActionKeys } from '@/features/ChatInput';
@@ -22,6 +21,12 @@ export type VoiceMessageSendHandler = (recording: VoiceMessageRecording) => bool
export interface SendButtonProps {
disabled?: boolean;
generating: boolean;
+ /**
+ * A send was committed but has not reached the agent yet (the message and its
+ * topic are still being created). Send shows as loading instead of Stop: there
+ * is no run to stop until the message is accepted.
+ */
+ loading?: boolean;
onStop: (params: { editor: IEditor }) => void;
shape?: 'round' | 'default';
/**
@@ -103,6 +108,13 @@ export interface PublicState {
onMarkdownContentChange?: (content: string) => void;
onSend?: SendButtonHandler;
onVoiceMessageSend?: VoiceMessageSendHandler;
+ /**
+ * Accept a send while this composer's attachments are still uploading: the
+ * send is queued (Send shows loading) and commits once every upload settles,
+ * with whatever the composer holds by then. Only hosts whose `onSend` leaves
+ * failed uploads out of the message should enable this.
+ */
+ queueSendWhileUploading?: boolean;
/**
* Live send gate consulted by `handleSendButton` instead of
* `sendButtonProps.disabled`. The disabled flag mirrors editor content
@@ -114,7 +126,6 @@ export interface PublicState {
resolveSendBlocked?: () => boolean;
rightActions: ActionKeys[];
sendButtonProps?: SendButtonProps;
- sendMenu?: { items: DropdownItem[] };
showTypoBar?: boolean;
/**
* Slash menu placement: 'bottom' for home page (input in center), 'top' for page input (at bottom)
@@ -149,6 +160,13 @@ export interface State extends PublicState {
isContentEmpty: boolean;
markdownContent: string;
slashMenuRef: ChatInputProps['slashMenuRef'];
+ /**
+ * The send queued until the composer's uploads settle (see
+ * `queueSendWhileUploading`), tagged with the draft it was made from: the
+ * composer outlives a conversation switch, and the conversation it shows next
+ * has nothing queued.
+ */
+ uploadQueuedSend?: { draftKey?: string; unsubscribe: () => void };
}
export const initialState: State = {
diff --git a/src/features/ChatInput/store/selectors.ts b/src/features/ChatInput/store/selectors.ts
index 5482790fe7e..13e2c6197b4 100644
--- a/src/features/ChatInput/store/selectors.ts
+++ b/src/features/ChatInput/store/selectors.ts
@@ -6,5 +6,8 @@ export const selectors = {
inputCompletionErrorVisible: (s: State): InputCompletionError | undefined =>
s.inputCompletionErrorDismissed ? undefined : s.inputCompletionError,
inputCompletionPaused: (s: State): boolean => Boolean(s.inputCompletionError),
+ /** A send from the draft on screen is waiting for its uploads to settle. */
+ isSendQueuedForUploads: (s: State): boolean =>
+ !!s.uploadQueuedSend && s.uploadQueuedSend.draftKey === s.draftKey,
sendButtonProps: (s: State): SendButtonProps => s.sendButtonProps || initialSendButtonState,
};
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 059bde26ba0..523e61738c1 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -6,10 +6,11 @@ import {
type ChatInputActionsProps,
type ChatInputProps as EditorChatInputProps,
} from '@lobehub/editor/react';
-import { type DropdownItem, Flexbox, toast } from '@lobehub/ui';
+import { Flexbox, toast } from '@lobehub/ui';
import i18next from 'i18next';
import { type ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import {
getBusinessChatInputSendAreaPrefix,
@@ -56,7 +57,12 @@ import { sendVoiceMessage } from './sendVoiceMessage';
import { transcribeVoiceMessage } from './transcribeVoiceMessage';
import { useConversationChatInputUiState } from './useConversationChatInputUiState';
import { useRestoreServerQueue } from './useRestoreServerQueue';
-import { getContextWindow, getConversationSendButtonProps, toChatInputMessages } from './utils';
+import {
+ getContextWindow,
+ getConversationSendButtonProps,
+ partitionSendableUploads,
+ toChatInputMessages,
+} from './utils';
import {
canSendVoiceMessage,
isVoiceMessageTranscribed,
@@ -163,10 +169,6 @@ export interface ChatInputProps {
* Custom send button props override
*/
sendButtonProps?: Partial<SendButtonProps>;
- /**
- * Send menu configuration (for send options like Enter/Cmd+Enter, Add AI/User message)
- */
- sendMenu?: { items: DropdownItem[] };
/**
* Whether to show the control bar (Local/Cloud/Auto Approve)
*/
@@ -202,13 +204,13 @@ const ChatInput = memo<ChatInputProps>(
mentionItems,
notices,
controlBarSlot,
- sendMenu,
sendAreaPrefix,
sendButtonProps: customSendButtonProps,
showControlBar = true,
onEditorReady,
skipScrollMarginWithList,
}) => {
+ const { t } = useTranslation('chat');
// ConversationStore state
const storeApi = useConversationStoreApi();
const dbMessages = useConversationStore(dataSelectors.dbMessages);
@@ -272,6 +274,9 @@ const ChatInput = memo<ChatInputProps>(
const isInputQueueBlocked = useChatStore((s) =>
operationSelectors.isInputLoadingByContext(context)(s),
);
+ const isSendDispatchPending = useChatStore((s) =>
+ operationSelectors.isSendDispatchPendingByContext(context)(s),
+ );
const pendingInterventions = usePendingInterventions();
const hasPendingInterventions = pendingInterventions.length > 0;
@@ -283,7 +288,6 @@ const ChatInput = memo<ChatInputProps>(
// File store - for UI state only (disabled button, etc.)
const fileList = useFileStore(fileChatSelectors.chatUploadFileList(contextKey));
const contextList = useFileStore(fileChatSelectors.chatContextSelections(contextKey));
- const isUploadingFiles = useFileStore(fileChatSelectors.isUploadingFiles(contextKey));
// Queue state
const hasQueuedMessages = useChatStore(
@@ -303,13 +307,14 @@ const ChatInput = memo<ChatInputProps>(
// Computed state
const isInputEmpty = !inputMessage.trim() && fileList.length === 0 && contextList.length === 0;
- const { placeholderVariant, showSendMenu, showSendWhileGenerating, showStopButton } =
+ const { placeholderVariant, showSendWhileGenerating, showStopButton } =
useConversationChatInputUiState({ disableFollowUpVariant, disableQueue, isInputEmpty });
// Input stays enabled during agent execution — messages are queued.
// When disableQueue is set (e.g. onboarding), block sending while loading.
// disableSend hard-blocks regardless of content (host surface is read-only).
- const disabled =
- isInputEmpty || isUploadingFiles || (!!disableQueue && isInputQueueBlocked) || !!disableSend;
+ // Uploads in flight do not block: the send is queued until they settle (see
+ // `queueSendWhileUploading`).
+ const disabled = isInputEmpty || (!!disableQueue && isInputQueueBlocked) || !!disableSend;
// `disabled` above lags the editor: `inputMessage` mirrors content through
// the editor's debounced onChange, so a fast type→Enter arrives while the
@@ -323,7 +328,6 @@ const ChatInput = memo<ChatInputProps>(
const { context: liveContext, editor } = storeApi.getState();
const liveContextKey = messageMapKey(liveContext);
const fileStore = useFileStore.getState();
- if (fileChatSelectors.isUploadingFiles(liveContextKey)(fileStore)) return true;
if (customDisabled !== undefined) return customDisabled;
if (
@@ -338,7 +342,6 @@ const ChatInput = memo<ChatInputProps>(
fileChatSelectors.chatContextSelections(liveContextKey)(fileStore).length > 0;
return !hasText && !hasFiles && !hasContextSelections;
}, [customDisabled, disableQueue, disableSend, storeApi]);
- const shouldUsePlainSendButton = !showSendMenu && !!sendMenu;
const businessAlerts = useBusinessChatInputAlerts();
const businessSendAreaPrefix = getBusinessChatInputSendAreaPrefix(sendAreaPrefix);
@@ -351,20 +354,37 @@ const ChatInput = memo<ChatInputProps>(
// Get instant values from stores at trigger time
const fileStore = useFileStore.getState();
- const currentFileList = fileChatSelectors.chatUploadFileList(contextKey)(fileStore);
+ const uploadList = fileChatSelectors.chatUploadFileList(contextKey)(fileStore);
const currentIsUploading = fileChatSelectors.isUploadingFiles(contextKey)(fileStore);
const currentContextList = fileChatSelectors.chatContextSelections(contextKey)(fileStore);
+ // The composer queues a send until its uploads settle; reaching here with one
+ // still in flight means the send came from elsewhere, which cannot wait.
if (currentIsUploading) return;
+ // A failed or cancelled upload has no file to attach. It is left out of the
+ // message (its [Image #N] is pruned with it, so the numbers still match the
+ // images sent) and stays in the composer to retry or remove.
+ const { failed: failedUploads, sendable: currentFileList } =
+ partitionSendableUploads(uploadList);
+ // Said only once the send is settled (sent without them, or nothing left to
+ // send), never ahead of a return that sends nothing for another reason.
+ const notifyFailedUploads = () => {
+ if (failedUploads.length === 0) return;
+ toast.warning(t('input.uploadFailedNotSent', { count: failedUploads.length }));
+ };
+
// Onboarding-style surfaces opt out of message queuing — pressing Enter
// while the agent is streaming should be a no-op rather than enqueue.
if (disableQueue && isInputQueueBlocked) return;
// Get content before clearing
const message = getMarkdownContent();
- if (!message.trim() && currentFileList.length === 0 && currentContextList.length === 0)
+ if (!message.trim() && currentFileList.length === 0 && currentContextList.length === 0) {
+ // Only failed uploads were attached: the queued send ends with nothing sent.
+ notifyFailedUploads();
return;
+ }
// A rejected preflight has no persisted message to recover from. Keep
// the composer and attachments intact until the target is usable.
@@ -381,12 +401,17 @@ const ChatInput = memo<ChatInputProps>(
return;
}
+ notifyFailedUploads();
+
// Capture editor JSON state before clearing for rich text rendering
const editorData = getEditorData();
const clearComposer = () => {
clearContent();
- fileStore.clearChatUploadFileList(contextKey);
+ fileStore.clearChatUploadFileList(
+ contextKey,
+ currentFileList.map((file) => file.id),
+ );
fileStore.clearChatContextSelections(contextKey);
};
@@ -452,19 +477,21 @@ const ChatInput = memo<ChatInputProps>(
pageSelections,
});
},
- [contextKey, sendMessage, storeApi, disableQueue, disableSend, isInputQueueBlocked],
+ [contextKey, sendMessage, storeApi, disableQueue, disableSend, isInputQueueBlocked, t],
);
- const sendButtonProps: SendButtonProps = {
- ...getConversationSendButtonProps(
- { disabled, generating: showStopButton, onStop: stopGenerating, showSendWhileGenerating },
- customSendButtonProps,
- isUploadingFiles,
- ),
- ...(shouldUsePlainSendButton
- ? { shape: customSendButtonProps?.shape ?? 'round' }
- : undefined),
- };
+ const sendButtonProps: SendButtonProps = getConversationSendButtonProps(
+ {
+ disabled,
+ // While the message is still being created there is no run to stop yet:
+ // Send shows as loading, and Stop takes over once the run starts.
+ generating: showStopButton && !isSendDispatchPending,
+ loading: isSendDispatchPending,
+ onStop: stopGenerating,
+ showSendWhileGenerating: showSendWhileGenerating && !isSendDispatchPending,
+ },
+ customSendButtonProps,
+ );
const handleVoiceMessageSend = useCallback(
(recording: VoiceMessageRecording) => {
@@ -559,6 +586,7 @@ const ChatInput = memo<ChatInputProps>(
return (
<ChatInputProvider
+ queueSendWhileUploading
agentId={agentId}
allowExpand={allowExpand}
canRecordVoiceMessage={canRecordVoiceMessage}
@@ -572,7 +600,6 @@ const ChatInput = memo<ChatInputProps>(
resolveSendBlocked={resolveSendBlocked}
rightActions={rightActions}
sendButtonProps={sendButtonProps}
- sendMenu={showSendMenu ? sendMenu : undefined}
slashPlacement="top"
topicId={topicId}
chatInputEditorRef={(instance) => {
diff --git a/src/features/Conversation/ChatInput/useConversationChatInputUiState.test.ts b/src/features/Conversation/ChatInput/useConversationChatInputUiState.test.ts
index 771ea5e4565..4f7bcc91be5 100644
--- a/src/features/Conversation/ChatInput/useConversationChatInputUiState.test.ts
+++ b/src/features/Conversation/ChatInput/useConversationChatInputUiState.test.ts
@@ -53,7 +53,6 @@ describe('useConversationChatInputUiState', () => {
expect(result.current).toEqual({
placeholderVariant: 'followUp',
- showSendMenu: false,
showSendWhileGenerating: false,
showStopButton: true,
});
@@ -84,7 +83,6 @@ describe('useConversationChatInputUiState', () => {
expect(result.current).toEqual({
placeholderVariant: 'default',
- showSendMenu: true,
showSendWhileGenerating: false,
showStopButton: false,
});
diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.ts
index a6cb3196cc3..0a896ed3e37 100644
--- a/src/features/Conversation/ChatInput/utils.test.ts
+++ b/src/features/Conversation/ChatInput/utils.test.ts
@@ -9,6 +9,7 @@ import {
getConversationChatInputUiState,
getConversationSendButtonProps,
getQueuedHintKey,
+ partitionSendableUploads,
putQueuedMessageInEditor,
sendQueuedMessageNow,
toChatInputMessages,
@@ -254,45 +255,40 @@ describe('getContextWindow', () => {
});
describe('getConversationSendButtonProps', () => {
- it.each([false, true])(
- 'keeps uploads disabled with generating=%s despite a host override',
- (generating) => {
- const defaults = {
- disabled: true,
- generating,
- onStop: vi.fn(),
- showSendWhileGenerating: generating,
- };
- const overrides = { disabled: false, shape: 'round' as const };
-
- expect(getConversationSendButtonProps(defaults, overrides, true)).toEqual({
- ...defaults,
- disabled: true,
- shape: 'round',
- });
- expect(getConversationSendButtonProps(defaults, overrides, false).disabled).toBe(false);
- },
- );
-
it.each([
{ customDisabled: undefined, disabled: true, expected: true },
{ customDisabled: undefined, disabled: false, expected: false },
{ customDisabled: true, disabled: false, expected: true },
{ customDisabled: false, disabled: true, expected: false },
])(
- 'preserves non-upload disabled overrides: $customDisabled / $disabled',
+ 'lets a host override disabled: $customDisabled / $disabled',
({ customDisabled, disabled, expected }) => {
expect(
getConversationSendButtonProps(
{ disabled, generating: false, onStop: vi.fn() },
customDisabled === undefined ? undefined : { disabled: customDisabled },
- false,
).disabled,
).toBe(expected);
},
);
});
+describe('partitionSendableUploads', () => {
+ it('leaves failed and cancelled uploads out, keeping the rest in composer order', () => {
+ const files = [
+ { id: 'a', status: 'success' as const },
+ { id: 'b', status: 'error' as const },
+ { id: 'c', status: 'success' as const },
+ { id: 'd', status: 'cancelled' as const },
+ ];
+
+ expect(partitionSendableUploads(files)).toEqual({
+ failed: [files[1], files[3]],
+ sendable: [files[0], files[2]],
+ });
+ });
+});
+
describe('getConversationChatInputUiState', () => {
it('shows follow-up placeholder and only the stop button while loading with an empty composer', () => {
expect(
@@ -302,7 +298,6 @@ describe('getConversationChatInputUiState', () => {
}),
).toEqual({
placeholderVariant: 'followUp',
- showSendMenu: false,
showSendWhileGenerating: false,
showStopButton: true,
});
@@ -320,7 +315,6 @@ describe('getConversationChatInputUiState', () => {
}),
).toEqual({
placeholderVariant: 'default',
- showSendMenu: false,
showSendWhileGenerating: true,
showStopButton: true,
});
@@ -347,7 +341,6 @@ describe('getConversationChatInputUiState', () => {
}),
).toEqual({
placeholderVariant: 'default',
- showSendMenu: true,
showSendWhileGenerating: false,
showStopButton: false,
});
@@ -362,7 +355,6 @@ describe('getConversationChatInputUiState', () => {
}),
).toEqual({
placeholderVariant: 'default',
- showSendMenu: false,
showSendWhileGenerating: false,
showStopButton: true,
});
diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.ts
index 03ac01aabdf..89e3f73ea9f 100644
--- a/src/features/Conversation/ChatInput/utils.ts
+++ b/src/features/Conversation/ChatInput/utils.ts
@@ -15,6 +15,7 @@ import {
SEND_NOW_CANCEL_REASON,
} from '@/store/chat/slices/operation/types';
import type { ChatStore } from '@/store/chat/store';
+import type { UploadFileItem } from '@/types/files/upload';
import { isMachineErrorMessage } from '@/utils/machineErrorMessage';
type SupportedChatInputRole = Extract<OpenAIChatMessage['role'], 'assistant' | 'tool' | 'user'>;
@@ -179,17 +180,37 @@ export const getContextWindow = (
export const getConversationSendButtonProps = (
defaults: SendButtonProps,
overrides: Partial<SendButtonProps> | undefined,
- isUploadingFiles: boolean,
): SendButtonProps => ({
...defaults,
...overrides,
- // Uploads are a hard gate even when a host explicitly enables sending.
- disabled: isUploadingFiles || (overrides?.disabled ?? defaults.disabled),
+ disabled: overrides?.disabled ?? defaults.disabled,
});
+/**
+ * Split a composer's uploads into those the message can carry and those it cannot.
+ *
+ * Use when:
+ * - Sending from the composer: a failed or cancelled upload has no stored file, so
+ * it is left out of the message instead of being sent as a dangling id.
+ *
+ * Returns:
+ * - `sendable` in composer order, which is the order image numbers
+ * (`[Image #N]`) are counted in, and `failed`, which stays in the composer.
+ */
+export const partitionSendableUploads = <T extends Pick<UploadFileItem, 'status'>>(
+ files: T[],
+): { failed: T[]; sendable: T[] } => {
+ const failed: T[] = [];
+ const sendable: T[] = [];
+ for (const file of files) {
+ if (file.status === 'error' || file.status === 'cancelled') failed.push(file);
+ else sendable.push(file);
+ }
+ return { failed, sendable };
+};
+
export interface ConversationChatInputUiState {
placeholderVariant: PlaceholderVariant;
- showSendMenu: boolean;
/** Show Send beside Stop so a typed follow-up can be queued by click. */
showSendWhileGenerating: boolean;
showStopButton: boolean;
@@ -220,7 +241,6 @@ export const getConversationChatInputUiState = ({
const followUp = !disableFollowUpVariant && isInputLoading && isInputEmpty;
return {
placeholderVariant: followUp ? 'followUp' : 'default',
- showSendMenu: !isInputLoading,
showSendWhileGenerating: isInputLoading && !isInputEmpty && !disableQueue,
showStopButton: isInputLoading,
};
diff --git a/src/features/Settings/hotkey/features/Conversation.tsx b/src/features/Settings/hotkey/features/Conversation.tsx
index a4bff134558..130b5a737ed 100644
--- a/src/features/Settings/hotkey/features/Conversation.tsx
+++ b/src/features/Settings/hotkey/features/Conversation.tsx
@@ -1,7 +1,7 @@
'use client';
-import { HotkeyGroupEnum } from '@lobechat/const/hotkeys';
-import { HotkeyInput } from '@lobehub/ui';
+import { HotkeyGroupEnum, KeyEnum } from '@lobechat/const/hotkeys';
+import { combineKeys, Hotkey, HotkeyInput, Select } from '@lobehub/ui';
import { Form, type FormGroupItem, useForm } from '@lobehub/ui/form';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
@@ -14,7 +14,7 @@ import { FORM_STYLE } from '@/const/layoutTokens';
import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
import { useSaveState } from '@/hooks/useSaveState';
import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
+import { preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
import { type HotkeyItem } from '@/types/hotkey';
import { type UserHotkeyConfig } from '@/types/user/settings';
@@ -22,6 +22,10 @@ const HotkeySetting = memo(() => {
const { t } = useTranslation(['setting', 'hotkey']);
const { hotkey } = useUserStore(settingsSelectors.currentSettings, isEqual);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
+ const [useCmdEnterToSend, updatePreference] = useUserStore((s) => [
+ preferenceSelectors.useCmdEnterToSend(s),
+ s.updatePreference,
+ ]);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
const form = useForm({
initialValues: hotkey,
@@ -63,10 +67,44 @@ const HotkeySetting = memo(() => {
};
};
+ /**
+ * The send key is a user preference (`useCmdEnterToSend`), not a hotkey binding, so
+ * this row has no form `name` and saves through `updatePreference` on its own.
+ */
+ const sendKeyItem = {
+ children: (
+ <Select
+ style={{ minWidth: 160 }}
+ value={useCmdEnterToSend ? 'cmdEnter' : 'enter'}
+ options={[
+ { label: <Hotkey keys={KeyEnum.Enter} variant={'borderless'} />, value: 'enter' },
+ {
+ label: (
+ <Hotkey keys={combineKeys([KeyEnum.Mod, KeyEnum.Enter])} variant={'borderless'} />
+ ),
+ value: 'cmdEnter',
+ },
+ ]}
+ onChange={(value) =>
+ save(() => updatePreference({ useCmdEnterToSend: value === 'cmdEnter' }))
+ }
+ />
+ ),
+ desc: t('hotkey.sendKey.desc'),
+ label: (
+ <SettingsSearchAnchor id={'hotkey-send-key'}>
+ {t('hotkey.sendKey.title')}
+ </SettingsSearchAnchor>
+ ),
+ };
+
const conversation: FormGroupItem<UserHotkeyConfig> = {
- children: HOTKEYS_REGISTRATION.filter(
- (item) => item.group === HotkeyGroupEnum.Conversation,
- ).map((item) => mapHotkeyItem(item)),
+ children: [
+ sendKeyItem,
+ ...HOTKEYS_REGISTRATION.filter((item) => item.group === HotkeyGroupEnum.Conversation).map(
+ (item) => mapHotkeyItem(item),
+ ),
+ ],
extra:
saveStatus === 'idle' ? undefined : (
<AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />
diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.ts
index ea336b5e224..7d26e784fa0 100644
--- a/src/features/SettingsSearch/items.ts
+++ b/src/features/SettingsSearch/items.ts
@@ -642,6 +642,13 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [
labelKey: 'hotkey.group.conversation',
tab: SettingsTabs.Hotkey,
},
+ {
+ anchor: 'hotkey-send-key',
+ descKey: 'hotkey.sendKey.desc',
+ keywords: ['send', 'enter', 'cmd', 'ctrl', 'newline'],
+ labelKey: 'hotkey.sendKey.title',
+ tab: SettingsTabs.Hotkey,
+ },
{
anchor: 'hotkey-desktop',
keywords: ['shortcut', 'keyboard', 'global'],
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
index 1a7f5fedfcc..d14b57a1f37 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
@@ -9,11 +9,9 @@ import { useModelSupportImageOutput } from '@/hooks/useModelSupportImageOutput';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { useUserStore } from '@/store/user';
-import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import AgentConfigError from './AgentConfigError';
-import { useSendMenuItems } from './useSendMenuItems';
+import { useAddUserMessageShortcut } from './useAddUserMessageShortcut';
const contextWindowRightActions: ActionKeys[] = ['model', 'voiceMessage', 'contextWindow'];
const promptTransformRightActions: ActionKeys[] = [
@@ -32,8 +30,7 @@ const promptTransformRightActions: ActionKeys[] = [
* Only adds MessageFromUrl for desktop mode.
*/
const MainChatInput = memo(() => {
- const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
- const sendMenuItems = useSendMenuItems();
+ useAddUserMessageShortcut();
const agentId = useConversationStore(contextSelectors.agentId);
const model = useAgentStore(agentByIdSelectors.getAgentModelById(agentId));
@@ -56,11 +53,7 @@ const MainChatInput = memo(() => {
isConfigLoading={isAgentConfigLoading}
leftActions={leftActions}
rightActions={rightActions}
- {...(isDevMode
- ? { sendMenu: { items: sendMenuItems } }
- : {
- sendButtonProps: { shape: 'round' },
- })}
+ sendButtonProps={{ shape: 'round' }}
onEditorReady={(instance) => {
// Sync to global ChatStore for compatibility with other features
useChatStore.setState({ mainInputEditor: instance });
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/useAddUserMessageShortcut.ts b/src/routes/(main)/agent/features/Conversation/MainChatInput/useAddUserMessageShortcut.ts
new file mode 100644
index 00000000000..05534a35169
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/useAddUserMessageShortcut.ts
@@ -0,0 +1,27 @@
+'use client';
+
+import { useCallback } from 'react';
+
+import { useConversationStore, useConversationStoreApi } from '@/features/Conversation';
+import { useAddUserMessageHotkey } from '@/hooks/useHotkeys';
+
+/**
+ * Binds the "add user message" hotkey: appends the composer text as a user
+ * message without asking the agent to reply.
+ */
+export const useAddUserMessageShortcut = () => {
+ const storeApi = useConversationStoreApi();
+ const editor = useConversationStore((s) => s.editor);
+
+ const handleAddUserMessage = useCallback(() => {
+ const store = storeApi.getState();
+ const message = store.inputMessage;
+ if (!message.trim()) return;
+
+ store.addUserMessage({ message });
+ editor?.clearContent();
+ editor?.focus();
+ }, [storeApi, editor]);
+
+ useAddUserMessageHotkey(handleAddUserMessage);
+};
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx
deleted file mode 100644
index c9c0770def5..00000000000
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * @vitest-environment happy-dom
- */
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useSendMenuItems as useGroupSendMenuItems } from '@/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems';
-
-import { useSendMenuItems as useAgentSendMenuItems } from './useSendMenuItems';
-
-const mocks = vi.hoisted(() => ({
- addAIMessage: vi.fn(),
- addUserMessage: vi.fn(),
- clearContent: vi.fn(),
- editorContent: '',
- focus: vi.fn(),
- inputMessage: '',
- updatePreference: vi.fn(),
-}));
-
-vi.mock('react-i18next', () => ({
- Trans: () => null,
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@/features/Conversation', () => ({
- useConversationStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({
- editor: {
- clearContent: mocks.clearContent,
- focus: mocks.focus,
- getMarkdownContent: () => mocks.editorContent,
- },
- }),
- useConversationStoreApi: () => ({
- getState: () => ({
- addAIMessage: mocks.addAIMessage,
- addUserMessage: mocks.addUserMessage,
- inputMessage: mocks.inputMessage,
- }),
- }),
-}));
-
-vi.mock('@/hooks/useHotkeys', () => ({
- useAddUserMessageHotkey: vi.fn(),
-}));
-
-vi.mock('@/store/user', () => ({
- useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({ updatePreference: mocks.updatePreference }),
-}));
-
-vi.mock('@/store/user/selectors', () => ({
- preferenceSelectors: { useCmdEnterToSend: () => false },
- settingsSelectors: { getHotkeyById: () => () => [] },
-}));
-
-type MenuAction = { key?: string; onClick?: () => void };
-
-const getAddAIAction = (items: unknown) =>
- (items as MenuAction[]).find((item) => item?.key === 'addAi');
-
-describe.each([
- ['agent', useAgentSendMenuItems],
- ['group', useGroupSendMenuItems],
-])('%s conversation send menu', (_name, useSendMenuItems) => {
- beforeEach(() => {
- mocks.editorContent = '';
- mocks.inputMessage = '';
- vi.clearAllMocks();
- });
-
- it('adds the current editor text as an assistant message', () => {
- mocks.editorContent = 'assistant content';
- mocks.inputMessage = 'stale cached content';
- const { result } = renderHook(() => useSendMenuItems());
-
- act(() => getAddAIAction(result.current)?.onClick?.());
-
- expect(mocks.addAIMessage).toHaveBeenCalledWith('assistant content');
- expect(mocks.clearContent).toHaveBeenCalledOnce();
- expect(mocks.focus).toHaveBeenCalledOnce();
- });
-
- it('preserves support for empty assistant placeholders', () => {
- const { result } = renderHook(() => useSendMenuItems());
-
- act(() => getAddAIAction(result.current)?.onClick?.());
-
- expect(mocks.addAIMessage).toHaveBeenCalledWith('');
- });
-});
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.tsx
deleted file mode 100644
index 1f3ae7cdd9a..00000000000
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-'use client';
-
-import { HotkeyEnum, KeyEnum } from '@lobechat/const/hotkeys';
-import { type DropdownItem } from '@lobehub/ui';
-import { Flexbox, Hotkey, Icon } from '@lobehub/ui';
-import { BotMessageSquare, LucideCheck, MessageSquarePlus } from 'lucide-react';
-import { useCallback, useMemo } from 'react';
-import { Trans, useTranslation } from 'react-i18next';
-
-import { useConversationStore, useConversationStoreApi } from '@/features/Conversation';
-import { useAddUserMessageHotkey } from '@/hooks/useHotkeys';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
-
-/**
- * useSendMenuItems hook for ConversationStore
- *
- * Provides send menu items for:
- * - Send with Enter / Cmd+Enter toggle
- * - Add AI Message
- * - Add User Message
- */
-export const useSendMenuItems = (): DropdownItem[] => {
- const { t } = useTranslation('chat');
-
- const storeApi = useConversationStoreApi();
- const editor = useConversationStore((s) => s.editor);
-
- const [useCmdEnterToSend, updatePreference] = useUserStore((s) => [
- preferenceSelectors.useCmdEnterToSend(s),
- s.updatePreference,
- ]);
-
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
-
- const handleAddAIMessage = useCallback(() => {
- const store = storeApi.getState();
- const message = editor?.getMarkdownContent() ?? store.inputMessage;
- store.addAIMessage(message);
- // Clear and focus editor
- editor?.clearContent();
- editor?.focus();
- }, [storeApi, editor]);
-
- const handleAddUserMessage = useCallback(() => {
- const store = storeApi.getState();
- const message = store.inputMessage;
- if (!message.trim()) return;
-
- store.addUserMessage({ message });
- // Clear and focus editor
- editor?.clearContent();
- editor?.focus();
- }, [storeApi, editor]);
-
- useAddUserMessageHotkey(handleAddUserMessage);
-
- return useMemo(
- () => [
- {
- icon: !useCmdEnterToSend ? <Icon icon={LucideCheck} /> : <div />,
- key: 'sendWithEnter',
- label: (
- <Flexbox horizontal align={'center'} gap={4}>
- <Trans
- i18nKey={'input.sendWithEnter'}
- ns={'chat'}
- components={{
- key: <Hotkey keys={KeyEnum.Enter} variant={'borderless'} />,
- }}
- />
- </Flexbox>
- ),
- onClick: () => {
- updatePreference({ useCmdEnterToSend: false });
- },
- },
- {
- icon: useCmdEnterToSend ? <Icon icon={LucideCheck} /> : <div />,
- key: 'sendWithCmdEnter',
- label: (
- <Flexbox horizontal align={'center'} gap={4}>
- <Trans
- i18nKey={'input.sendWithCmdEnter'}
- ns={'chat'}
- components={{
- key: (
- <Hotkey keys={[KeyEnum.Mod, KeyEnum.Enter].join('+')} variant={'borderless'} />
- ),
- }}
- />
- </Flexbox>
- ),
- onClick: () => {
- updatePreference({ useCmdEnterToSend: true });
- },
- },
- { type: 'divider' },
- {
- icon: <Icon icon={BotMessageSquare} />,
- key: 'addAi',
- label: t('input.addAi'),
- onClick: handleAddAIMessage,
- },
- {
- icon: <Icon icon={MessageSquarePlus} />,
- key: 'addUser',
- label: (
- <Flexbox horizontal align={'center'} gap={24}>
- {t('input.addUser')}
- <Hotkey keys={hotkey} />
- </Flexbox>
- ),
- onClick: handleAddUserMessage,
- },
- ],
- [useCmdEnterToSend, updatePreference, hotkey, handleAddAIMessage, handleAddUserMessage],
- );
-};
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
index 22d0a824659..75b15029a70 100644
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
@@ -6,8 +6,6 @@ import { type ActionKeys } from '@/features/ChatInput';
import { ChatInput } from '@/features/Conversation';
import { useChatStore } from '@/store/chat';
-import { useSendMenuItems } from './useSendMenuItems';
-
const leftActions: ActionKeys[] = [
'search',
'memory',
@@ -29,14 +27,12 @@ const rightActions: ActionKeys[] = ['model', 'voiceMessage', 'contextWindow'];
* Only adds MessageFromUrl for desktop mode.
*/
const MainChatInput = memo(() => {
- const sendMenuItems = useSendMenuItems();
-
return (
<ChatInput
skipScrollMarginWithList
leftActions={leftActions}
rightActions={rightActions}
- sendMenu={{ items: sendMenuItems }}
+ sendButtonProps={{ shape: 'round' }}
onEditorReady={(instance) => {
// Sync to global ChatStore for compatibility with other features
useChatStore.setState({ mainInputEditor: instance });
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
deleted file mode 100644
index 5abf3ae1f64..00000000000
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-'use client';
-
-import { HotkeyEnum, KeyEnum } from '@lobechat/const/hotkeys';
-import { type DropdownItem } from '@lobehub/ui';
-import { Flexbox, Hotkey, Icon } from '@lobehub/ui';
-import { BotMessageSquare, LucideCheck, MessageSquarePlus } from 'lucide-react';
-import { useCallback, useMemo } from 'react';
-import { Trans, useTranslation } from 'react-i18next';
-
-import { useConversationStore, useConversationStoreApi } from '@/features/Conversation';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
-
-/**
- * useSendMenuItems hook for ConversationStore
- *
- * Provides send menu items for:
- * - Send with Enter / Cmd+Enter toggle
- * - Add AI Message
- * - Add User Message
- */
-export const useSendMenuItems = (): DropdownItem[] => {
- const { t } = useTranslation('chat');
-
- const storeApi = useConversationStoreApi();
- const editor = useConversationStore((s) => s.editor);
-
- const [useCmdEnterToSend, updatePreference] = useUserStore((s) => [
- preferenceSelectors.useCmdEnterToSend(s),
- s.updatePreference,
- ]);
-
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
-
- const handleAddAIMessage = useCallback(() => {
- const store = storeApi.getState();
- const message = editor?.getMarkdownContent() ?? store.inputMessage;
- store.addAIMessage(message);
- // Clear and focus editor
- editor?.clearContent();
- editor?.focus();
- }, [storeApi, editor]);
-
- const handleAddUserMessage = useCallback(() => {
- const store = storeApi.getState();
- const message = store.inputMessage;
- if (!message.trim()) return;
-
- store.addUserMessage({ message });
- // Clear and focus editor
- editor?.clearContent();
- editor?.focus();
- }, [storeApi, editor]);
-
- return useMemo(
- () => [
- {
- icon: !useCmdEnterToSend ? <Icon icon={LucideCheck} /> : <div />,
- key: 'sendWithEnter',
- label: (
- <Flexbox horizontal align={'center'} gap={4}>
- <Trans
- i18nKey={'input.sendWithEnter'}
- ns={'chat'}
- components={{
- key: <Hotkey keys={KeyEnum.Enter} variant={'borderless'} />,
- }}
- />
- </Flexbox>
- ),
- onClick: () => {
- updatePreference({ useCmdEnterToSend: false });
- },
- },
- {
- icon: useCmdEnterToSend ? <Icon icon={LucideCheck} /> : <div />,
- key: 'sendWithCmdEnter',
- label: (
- <Flexbox horizontal align={'center'} gap={4}>
- <Trans
- i18nKey={'input.sendWithCmdEnter'}
- ns={'chat'}
- components={{
- key: (
- <Hotkey keys={[KeyEnum.Mod, KeyEnum.Enter].join('+')} variant={'borderless'} />
- ),
- }}
- />
- </Flexbox>
- ),
- onClick: () => {
- updatePreference({ useCmdEnterToSend: true });
- },
- },
- { type: 'divider' },
- {
- icon: <Icon icon={BotMessageSquare} />,
- key: 'addAi',
- label: t('input.addAi'),
- onClick: handleAddAIMessage,
- },
- {
- icon: <Icon icon={MessageSquarePlus} />,
- key: 'addUser',
- label: (
- <Flexbox horizontal align={'center'} gap={24}>
- {t('input.addUser')}
- <Hotkey keys={hotkey} />
- </Flexbox>
- ),
- onClick: handleAddUserMessage,
- },
- ],
- [useCmdEnterToSend, updatePreference, hotkey, handleAddAIMessage, handleAddUserMessage],
- );
-};
diff --git a/src/store/chat/slices/operation/selectors.sendDispatch.test.ts b/src/store/chat/slices/operation/selectors.sendDispatch.test.ts
new file mode 100644
index 00000000000..8fdc61dbb4c
--- /dev/null
+++ b/src/store/chat/slices/operation/selectors.sendDispatch.test.ts
@@ -0,0 +1,54 @@
+import { act } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { useChatStore } from '@/store/chat/store';
+
+import { operationSelectors } from './selectors';
+
+const context = { agentId: 'agent1', topicId: 'topic1' };
+const isPending = () =>
+ operationSelectors.isSendDispatchPendingByContext(context)(useChatStore.getState());
+
+describe('isSendDispatchPendingByContext', () => {
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ });
+
+ it('is pending from the send until the run it hands off to starts', () => {
+ let sendOpId = '';
+ act(() => {
+ sendOpId = useChatStore
+ .getState()
+ .startOperation({ context, type: 'sendMessage' }).operationId;
+ });
+ expect(isPending()).toBe(true);
+
+ act(() => {
+ useChatStore.getState().startOperation({
+ context,
+ parentOperationId: sendOpId,
+ type: 'execServerAgentRuntime',
+ });
+ useChatStore.getState().completeOperation(sendOpId);
+ });
+ expect(isPending()).toBe(false);
+ });
+
+ it('is not pending while only a run is going', () => {
+ act(() => {
+ useChatStore.getState().startOperation({ context, type: 'execHeterogeneousAgent' });
+ });
+
+ expect(isPending()).toBe(false);
+ });
+
+ it('ignores a send in another conversation', () => {
+ act(() => {
+ useChatStore
+ .getState()
+ .startOperation({ context: { ...context, topicId: 'topic2' }, type: 'sendMessage' });
+ });
+
+ expect(isPending()).toBe(false);
+ });
+});
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index 452a243ed5f..5b2b7c30643 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -497,6 +497,32 @@ const isInputVisiblyLoadingByContext =
return isSteerHandoffPending(context)(s);
};
+/**
+ * Whether a sent message is still on its way to the agent in a specific context.
+ *
+ * Use when:
+ * - The composer decides between a loading Send and Stop. While `sendMessage`
+ * creates the message (and, for a new conversation, its topic) no run exists
+ * yet, so the send is shown as pending rather than as a run to stop.
+ *
+ * Returns:
+ * - `true` while a `sendMessage` op runs with no AI runtime op running beside it.
+ * `sendMessage` completes right as it hands off to its runtime op, so the two
+ * only overlap for that hand-off.
+ */
+const isSendDispatchPendingByContext =
+ (context: MessageMapKeyInput) =>
+ (s: ChatStoreState): boolean => {
+ if (!context.agentId) return false;
+
+ const running = getOperationsByContext(context)(s).filter(isRunningOperation);
+
+ return (
+ running.some((op) => op.type === 'sendMessage') &&
+ !running.some((op) => AI_RUNTIME_OPERATION_TYPES.includes(op.type))
+ );
+ };
+
// === Backward Compatibility ===
/**
@@ -1087,6 +1113,7 @@ export const operationSelectors = {
isAgentRuntimeVisiblyRunningByContext,
isInputLoadingByContext,
isInputVisiblyLoadingByContext,
+ isSendDispatchPendingByContext,
isAnyMessageLoading,
isContinuing,
isInSearchWorkflow,