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.

🐛 fix(chat): pass editor text when adding assistant message (#17121)

H-TTTTT6464eaecb443
diff --git a/src/features/Conversation/store/slices/message/action/index.test.ts b/src/features/Conversation/store/slices/message/action/index.test.ts
new file mode 100644
index 00000000000..cb37603aec9
--- /dev/null
+++ b/src/features/Conversation/store/slices/message/action/index.test.ts
@@ -0,0 +1,212 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { act } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ConversationContext } from '../../../../types';
+import { createStore } from '../../../index';
+
+// Mock conversation-flow parse so createStore initialization never reaches a real parser.
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => {
+ const messageMap: Record<string, UIChatMessage> = {};
+ for (const msg of messages) messageMap[msg.id] = msg;
+ return { flatList: [...messages].sort((a, b) => a.createdAt - b.createdAt), messageMap };
+ },
+}));
+
+const createTestStore = (context?: Partial<ConversationContext>) =>
+ createStore({
+ context: {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ threadId: null,
+ ...context,
+ },
+ });
+
+describe('message convenience actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('addAIMessage', () => {
+ it('creates an assistant message with its conversation context and the submitted text', async () => {
+ const store = createTestStore();
+ const createMessage = vi.fn().mockResolvedValue('message-1');
+ store.setState({ createMessage });
+
+ await act(async () => {
+ await store.getState().addAIMessage('assistant content');
+ });
+
+ expect(createMessage).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ content: 'assistant content',
+ parentId: undefined,
+ role: 'assistant',
+ threadId: undefined,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('does not forward groupId to createMessage (canary-aligned context)', async () => {
+ const store = createTestStore({ groupId: 'group-1', scope: 'group' });
+ const createMessage = vi.fn().mockResolvedValue('message-1');
+ store.setState({ createMessage });
+
+ await act(async () => {
+ await store.getState().addAIMessage('assistant content');
+ });
+
+ expect(createMessage).toHaveBeenCalledWith(
+ expect.not.objectContaining({ groupId: expect.anything() }),
+ );
+ });
+
+ it('still allows an empty assistant placeholder', async () => {
+ const store = createTestStore();
+ const createMessage = vi.fn().mockResolvedValue('message-1');
+ store.setState({ createMessage });
+
+ await act(async () => {
+ await store.getState().addAIMessage('');
+ });
+
+ expect(createMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ content: '', role: 'assistant' }),
+ );
+ });
+
+ it('uses the last display message as the parent id', async () => {
+ const store = createTestStore();
+ const createMessage = vi.fn().mockResolvedValue('message-1');
+ store.setState({
+ createMessage,
+ displayMessages: [
+ { id: 'prev-1', content: 'previous', role: 'user', createdAt: 1, updatedAt: 1 },
+ ],
+ });
+
+ await act(async () => {
+ await store.getState().addAIMessage('assistant content');
+ });
+
+ expect(createMessage).toHaveBeenCalledWith(expect.objectContaining({ parentId: 'prev-1' }));
+ });
+
+ it('fires the onMessageCreated hook for the created assistant message', async () => {
+ const onMessageCreated = vi.fn();
+ const store = createTestStore();
+ const created: UIChatMessage = {
+ id: 'message-1',
+ content: 'assistant content',
+ role: 'assistant',
+ createdAt: 1,
+ updatedAt: 1,
+ };
+ store.setState({
+ createMessage: vi.fn().mockResolvedValue('message-1'),
+ displayMessages: [created],
+ hooks: { onMessageCreated },
+ });
+
+ await act(async () => {
+ await store.getState().addAIMessage('assistant content');
+ });
+
+ expect(onMessageCreated).toHaveBeenCalledWith(created);
+ });
+
+ it('clears the input after successful creation', async () => {
+ const store = createTestStore();
+ store.setState({
+ createMessage: vi.fn().mockResolvedValue('message-1'),
+ inputMessage: 'submitted draft',
+ });
+
+ await act(async () => {
+ await store.getState().addAIMessage('submitted draft');
+ });
+
+ expect(store.getState().inputMessage).toBe('');
+ });
+
+ it('does not clear the input when creation fails', async () => {
+ const store = createTestStore();
+ store.setState({
+ createMessage: vi.fn().mockResolvedValue(undefined),
+ inputMessage: 'submitted draft',
+ });
+
+ await act(async () => {
+ await store.getState().addAIMessage('submitted draft');
+ });
+
+ expect(store.getState().inputMessage).toBe('submitted draft');
+ });
+ });
+
+ describe('addUserMessage', () => {
+ it('creates a user message with its conversation context, files and the submitted text', async () => {
+ const store = createTestStore();
+ const createMessage = vi.fn().mockResolvedValue('message-1');
+ store.setState({ createMessage });
+
+ await act(async () => {
+ await store.getState().addUserMessage({ message: 'user content', fileList: ['file-1'] });
+ });
+
+ expect(createMessage).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ content: 'user content',
+ files: ['file-1'],
+ parentId: undefined,
+ role: 'user',
+ threadId: undefined,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('does not forward groupId to createMessage (canary-aligned context)', async () => {
+ const store = createTestStore({ groupId: 'group-1', scope: 'group' });
+ const createMessage = vi.fn().mockResolvedValue('message-1');
+ store.setState({ createMessage });
+
+ await act(async () => {
+ await store.getState().addUserMessage({ message: 'user content' });
+ });
+
+ expect(createMessage).toHaveBeenCalledWith(
+ expect.not.objectContaining({ groupId: expect.anything() }),
+ );
+ });
+
+ it('clears the input after successful creation', async () => {
+ const store = createTestStore();
+ store.setState({
+ createMessage: vi.fn().mockResolvedValue('message-1'),
+ inputMessage: 'submitted draft',
+ });
+
+ await act(async () => {
+ await store.getState().addUserMessage({ message: 'submitted draft' });
+ });
+
+ expect(store.getState().inputMessage).toBe('');
+ });
+
+ it('does not clear the input when creation fails', async () => {
+ const store = createTestStore();
+ store.setState({
+ createMessage: vi.fn().mockResolvedValue(undefined),
+ inputMessage: 'submitted draft',
+ });
+
+ await act(async () => {
+ await store.getState().addUserMessage({ message: 'submitted draft' });
+ });
+
+ expect(store.getState().inputMessage).toBe('submitted draft');
+ });
+ });
+});
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx
new file mode 100644
index 00000000000..70ba2f657a3
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx
@@ -0,0 +1,99 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import type { ReactNode } from '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('@lobehub/ui', () => ({
+ Flexbox: ({ children }: { children?: ReactNode }) => children,
+ Hotkey: () => null,
+ Icon: () => null,
+}));
+
+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
index 26262bea237..1cff5324281 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.tsx
@@ -35,8 +35,8 @@ export const useSendMenuItems = (): MenuProps['items'] => {
const handleAddAIMessage = useCallback(() => {
const store = storeApi.getState();
- // Add empty AI message placeholder
- store.addAIMessage('');
+ const message = editor?.getMarkdownContent() ?? store.inputMessage;
+ store.addAIMessage(message);
// Clear and focus editor
editor?.clearContent();
editor?.focus();
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
index 0c54fa27fcb..00dd98a4822 100644
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems.tsx
@@ -34,8 +34,8 @@ export const useSendMenuItems = (): MenuProps['items'] => {
const handleAddAIMessage = useCallback(() => {
const store = storeApi.getState();
- // Add empty AI message placeholder
- store.addAIMessage('');
+ const message = editor?.getMarkdownContent() ?? store.inputMessage;
+ store.addAIMessage(message);
// Clear and focus editor
editor?.clearContent();
editor?.focus();