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(home): keep a refused Home message in the conversation composer (#22280)

YuTengjing54642e8488c5
diff --git a/oxlint.config.mts b/oxlint.config.mts
index 153bad1da08..812ceddb3bc 100644
--- a/oxlint.config.mts
+++ b/oxlint.config.mts
@@ -627,8 +627,10 @@ export default defineConfig(
'Home cold-path modules must not statically import ChatInput. Load an isolated editor entry with import().',
// `hooks/useAgentModelSelection` reaches the store only through the
// editor-free `store/apiContext`; Home model switches share its path.
+ // `draftStorage` is localStorage-only; a refused Home send hands its
+ // message to the conversation composer through it.
regex:
- '^@/features/ChatInput(?:$|/(?!(?:hooks/useAgentModelSelection|store/initialState|utils/contextSelections)$).+)',
+ '^@/features/ChatInput(?:$|/(?!(?:draftStorage|hooks/useAgentModelSelection|store/initialState|utils/contextSelections)$).+)',
},
],
}),
diff --git a/src/features/Home/InputArea/useSend.test.ts b/src/features/Home/InputArea/useSend.test.ts
index 5082bd38e9a..1a0c1d3ffae 100644
--- a/src/features/Home/InputArea/useSend.test.ts
+++ b/src/features/Home/InputArea/useSend.test.ts
@@ -5,7 +5,9 @@ import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import { getDraft, saveDraft } from '@/features/ChatInput/draftStorage';
import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useSend } from './useSend';
@@ -26,13 +28,16 @@ const messageErrorMock = vi.hoisted(() => vi.fn());
const messageSuccessMock = vi.hoisted(() => vi.fn());
const chatState = vi.hoisted(() => ({
+ activeAgentId: '' as string,
+ activeTopicId: undefined as string | undefined,
inputMessage: 'hello',
mainInputEditor: {
clearContent: clearContentMock,
getJSONState: vi.fn(() => ({ type: 'doc' })),
- },
+ } as Record<string, unknown>,
sendMessage: sendMessageMock,
}));
+const homeEditor = chatState.mainInputEditor;
const fileState = vi.hoisted(() => ({
chatContextSelectionsByContext: {} as Record<string, any[]>,
@@ -199,6 +204,10 @@ describe('Home InputArea useSend', () => {
homeDailyBriefState.advance.mockReset();
homeDailyBriefState.currentPair = undefined;
chatState.inputMessage = 'hello';
+ chatState.activeAgentId = '';
+ chatState.activeTopicId = undefined;
+ chatState.mainInputEditor = homeEditor;
+ localStorage.clear();
fileState.chatContextSelectionsByContext = {};
fileState.chatUploadFileList = [];
homeState.inputActiveMode = null;
@@ -495,6 +504,96 @@ describe('Home InputArea useSend', () => {
expect(routerMock.replace).toHaveBeenCalledWith('/agent/agt_inbox/tpc_created');
});
+ describe('when the server refuses the run after Home navigated away', () => {
+ // ROOT CAUSE (LOBE-15420):
+ //
+ // A Home send navigates to the agent's blank conversation and clears the
+ // Home editor without waiting for the run. When the server then refuses the
+ // run (for example, the plan's concurrent-run limit), `sendMessage` restores
+ // the text into the editor captured at send time — the unmounted Home
+ // editor. The conversation composer reads its draft only on mount, so
+ // before the fix the refusal notice showed over an empty composer.
+ const paragraph = (text: string) => ({ children: [{ text, type: 'text' }], type: 'paragraph' });
+ const doc = (...texts: string[]) => ({
+ root: { children: texts.map(paragraph), type: 'root' },
+ });
+ const typedDraft = doc('hello');
+ const blankKey = 'main_agt_inbox_new';
+
+ const sendAndGetRefusal = async () => {
+ const { result } = renderHook(() => useSend());
+ await act(async () => {
+ await result.current.send({
+ clearContent: vi.fn(),
+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],
+ getEditorData: () => typedDraft,
+ getMarkdownContent: () => 'hello',
+ });
+ });
+ return sendMessageMock.mock.calls[0][0].onPreflightFailure as () => void;
+ };
+
+ const mountConversationEditor = (content = '') => {
+ const editor = {
+ getJSONState: vi.fn(() => (content ? doc(content) : doc())),
+ getMarkdownContent: vi.fn(() => content),
+ setJSONState: vi.fn(),
+ };
+ chatState.activeAgentId = 'agt_inbox';
+ chatState.mainInputEditor = editor;
+ return editor;
+ };
+
+ it('writes the message into the mounted conversation composer', async () => {
+ const refuse = await sendAndGetRefusal();
+ const conversationEditor = mountConversationEditor();
+
+ refuse();
+
+ expect(conversationEditor.setJSONState).toHaveBeenCalledWith(typedDraft);
+ });
+
+ it('saves the message as the blank-conversation draft before the composer mounts', async () => {
+ const refuse = await sendAndGetRefusal();
+
+ refuse();
+
+ expect(blankKey).toBe(messageMapKey({ agentId: 'agt_inbox', topicId: null }));
+ expect(getDraft(blankKey)).toEqual(typedDraft);
+ });
+
+ it('appends the message after what the conversation composer already holds', async () => {
+ const refuse = await sendAndGetRefusal();
+ const conversationEditor = mountConversationEditor('an earlier draft');
+
+ refuse();
+
+ expect(conversationEditor.setJSONState).toHaveBeenCalledWith(
+ doc('an earlier draft', 'hello'),
+ );
+ });
+
+ it('appends the message to an existing blank-conversation draft', async () => {
+ saveDraft(blankKey, doc('an earlier draft'));
+ const refuse = await sendAndGetRefusal();
+
+ refuse();
+
+ expect(getDraft(blankKey)).toEqual(doc('an earlier draft', 'hello'));
+ });
+
+ it('saves a draft instead of filling the composer of another topic', async () => {
+ const refuse = await sendAndGetRefusal();
+ const conversationEditor = mountConversationEditor();
+ chatState.activeTopicId = 'tpc_other';
+
+ refuse();
+
+ expect(conversationEditor.setJSONState).not.toHaveBeenCalled();
+ expect(getDraft(blankKey)).toEqual(typedDraft);
+ });
+ });
+
it('sends chat-mode messages to the Agent selected on Home', async () => {
globalState.systemStatus.homeSelectedAgentId = 'agt_custom';
homeState.ungroupedAgents = [{ id: 'agt_custom', type: 'agent' }];
diff --git a/src/features/Home/InputArea/useSend.ts b/src/features/Home/InputArea/useSend.ts
index 0082952e2ab..fbbc679c189 100644
--- a/src/features/Home/InputArea/useSend.ts
+++ b/src/features/Home/InputArea/useSend.ts
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import { getDraft, saveDraft } from '@/features/ChatInput/draftStorage';
import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';
import { buildMessageContextSelections } from '@/features/ChatInput/utils/contextSelections';
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
@@ -16,6 +17,7 @@ import { agentService } from '@/services/agent';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { fileChatSelectors, useFileStore } from '@/store/file';
import { useHomeStore } from '@/store/home';
import { useTaskStore } from '@/store/task';
@@ -47,6 +49,74 @@ const ensureAgentConfigLoaded = async (agentId: string): Promise<void> => {
if (config) agentState.internal_dispatchAgentMap(agentId, config);
};
+type EditorDocument = Record<string, unknown>;
+
+/**
+ * Append `extra`'s top-level blocks after `base`'s. Both are serialized
+ * editor states (`{ root: { children } }`); when either has another shape,
+ * `base` is returned untouched so content the user already has is never lost.
+ */
+const appendEditorDocument = (base: EditorDocument, extra: EditorDocument): EditorDocument => {
+ const baseRoot = base.root as { children?: unknown } | undefined;
+ const extraRoot = extra.root as { children?: unknown } | undefined;
+ if (!Array.isArray(baseRoot?.children) || !Array.isArray(extraRoot?.children)) return base;
+
+ return {
+ ...base,
+ root: { ...baseRoot, children: [...baseRoot.children, ...extraRoot.children] },
+ };
+};
+
+/**
+ * Put a refused Home send back in the composer of the conversation it moved to.
+ *
+ * A Home send does not wait for the run to start: it navigates to the agent's
+ * blank conversation and clears the Home editor immediately. When the server
+ * then refuses the run (for example, the plan's concurrent-run limit),
+ * `sendMessage` restores the text into the editor captured at send time, which
+ * is the unmounted Home editor. The conversation composer reads its draft only
+ * on mount or on a draft-key change, so without this the message is lost.
+ *
+ * - The conversation composer is mounted on that blank conversation: write
+ * into it.
+ * - Otherwise: save it under the blank-conversation draft key, which the
+ * composer reads when it mounts.
+ *
+ * Either target may already hold content the user typed there; the refused
+ * message is appended after it so neither is lost.
+ */
+const restoreRefusedSendToConversation = ({
+ agentId,
+ editorData,
+ homeEditor,
+}: {
+ agentId: string;
+ editorData: EditorDocument | undefined;
+ /** The Home composer that sent the message; only its identity is compared. */
+ homeEditor: unknown;
+}) => {
+ // A hint-only send has no typed content to give back.
+ if (!editorData) return;
+
+ const { activeAgentId, activeTopicId, mainInputEditor } = useChatStore.getState();
+ const conversationEditor =
+ mainInputEditor && mainInputEditor !== homeEditor ? mainInputEditor : undefined;
+
+ if (conversationEditor && activeAgentId === agentId && !activeTopicId) {
+ const current = conversationEditor.getJSONState();
+ conversationEditor.setJSONState(
+ conversationEditor.getMarkdownContent().trim() && current
+ ? appendEditorDocument(current, editorData)
+ : editorData,
+ );
+ return;
+ }
+
+ const draftKey = messageMapKey({ agentId, topicId: null });
+ const existingDraft = getDraft(draftKey);
+ saveDraft(draftKey, existingDraft ? appendEditorDocument(existingDraft, editorData) : editorData);
+};
+
export const useSend = (mode: HomeMode = 'chat') => {
const { t } = useTranslation('home');
const { t: tChat } = useTranslation('chat');
@@ -238,6 +308,11 @@ export const useSend = (mode: HomeMode = 'chat') => {
message,
onPreflightFailure: () => {
restoreChatContextSelections(contextSelectionKey, contextList);
+ restoreRefusedSendToConversation({
+ agentId: selectedAgentId,
+ editorData,
+ homeEditor: mainInputEditor,
+ });
},
onTopicCreated: (topicId) => {
router.replace(AGENT_CHAT_TOPIC_URL(selectedAgentId, topicId, false));