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.

⚑️ perf(project): open the conversation as soon as the project home sends (#21753)

Arvin Xu358dbd2cb89a
diff --git a/src/features/Projects/Workspace/ProjectComposer.tsx b/src/features/Projects/Workspace/ProjectComposer.tsx
index fae84daef45..98e6f75e0d3 100644
--- a/src/features/Projects/Workspace/ProjectComposer.tsx
+++ b/src/features/Projects/Workspace/ProjectComposer.tsx
@@ -22,7 +22,6 @@ import ProjectAgentSelect from './ProjectAgentSelect';
import { projectComposerAgents } from './projectComposerAgents';
import {
AttachmentsNotReadyError,
- MessageNotAcceptedError,
type ProjectComposerMode,
useProjectComposer,
} from './useProjectComposer';
@@ -82,10 +81,6 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail }) => {
toast.error(tHome('dashboard.task.attachmentsNotReady'));
return;
}
- if (error instanceof MessageNotAcceptedError) {
- toast.error(t('overview.messageNotSent'));
- return;
- }
console.error('Failed to send from the project home', error);
toast.error(t(mode === 'task' ? 'overview.createTaskFailed' : 'overview.sendFailed'));
}
diff --git a/src/features/Projects/Workspace/useProjectComposer.test.ts b/src/features/Projects/Workspace/useProjectComposer.test.ts
index 38c766ffcb6..5161a067bda 100644
--- a/src/features/Projects/Workspace/useProjectComposer.test.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.test.ts
@@ -4,11 +4,11 @@
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { getDraft } from '@/features/ChatInput/draftStorage';
import type { ProjectDetail } from '@/store/project';
import {
AttachmentsNotReadyError,
- MessageNotAcceptedError,
toConversationTitle,
useProjectComposer,
} from './useProjectComposer';
@@ -21,10 +21,13 @@ const mocks = vi.hoisted(() => ({
fileList: [] as unknown[],
getAgentConfigById: vi.fn(),
internal_dispatchAgentMap: vi.fn(),
+ activeAgentId: undefined as string | undefined,
+ activeTopicId: undefined as string | undefined,
+ mainInputEditor: null as unknown,
navigate: vi.fn(),
- refreshProjectTopics: vi.fn(),
- removeTopic: vi.fn(),
+ restoreChatUploadFileList: vi.fn(),
sendMessage: vi.fn(),
+ toastError: vi.fn(),
workspaceSlug: null as string | null,
}));
@@ -32,8 +35,12 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
useActiveWorkspaceSlug: () => mocks.workspaceSlug,
}));
-vi.mock('@/services/topic', () => ({
- topicService: { removeTopic: mocks.removeTopic },
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ toast: { error: mocks.toastError },
}));
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
@@ -44,7 +51,6 @@ vi.mock('@/store/projectWorkingDirectory', () => ({
useProjectDirectoryStore: (selector: (state: unknown) => unknown) =>
selector({
createProjectTopic: mocks.createProjectTopic,
- refreshProjectTopics: mocks.refreshProjectTopics,
}),
}));
@@ -53,15 +59,33 @@ vi.mock('@/store/task', () => ({
selector({ createTask: mocks.createTask }),
}));
-vi.mock('@/store/chat', () => ({
- useChatStore: (selector: (state: unknown) => unknown) =>
- selector({ sendMessage: mocks.sendMessage }),
-}));
+vi.mock('@/store/chat', () => {
+ const state = () => ({
+ activeAgentId: mocks.activeAgentId,
+ activeTopicId: mocks.activeTopicId,
+ mainInputEditor: mocks.mainInputEditor,
+ sendMessage: mocks.sendMessage,
+ });
+ const useChatStore = Object.assign((selector: (s: unknown) => unknown) => selector(state()), {
+ getState: state,
+ });
+ return { useChatStore };
+});
+
+/** A conversation page mounts its composer, which registers as the main editor. */
+const mountConversationEditor = (topicId = 'tpc_1', agentId = 'coordinator') => {
+ const editor = { setDocument: vi.fn(), setJSONState: vi.fn() };
+ mocks.activeAgentId = agentId;
+ mocks.activeTopicId = topicId;
+ mocks.mainInputEditor = editor;
+ return editor;
+};
vi.mock('@/store/file', () => {
const state = () => ({
chatUploadFileList: mocks.fileList,
clearChatUploadFileList: mocks.clearChatUploadFileList,
+ restoreChatUploadFileList: mocks.restoreChatUploadFileList,
});
const useFileStore = Object.assign((selector: (s: unknown) => unknown) => selector(state()), {
getState: state,
@@ -114,7 +138,10 @@ describe('useProjectComposer', () => {
mocks.agentMap = { coordinator: {} };
mocks.fileList = [];
mocks.workspaceSlug = null;
- mocks.removeTopic.mockResolvedValue(undefined);
+ mocks.activeAgentId = undefined;
+ mocks.activeTopicId = undefined;
+ mocks.mainInputEditor = null;
+ localStorage.clear();
// The conversation takes the message, then the run goes on in the background.
mocks.sendMessage.mockImplementation(({ onMessageAccepted }) => {
onMessageAccepted?.();
@@ -146,9 +173,10 @@ describe('useProjectComposer', () => {
context: { agentId: 'coordinator', topicId: 'tpc_1' },
editorData,
files: [image],
- inputEditor: null,
+ inputEditor: expect.objectContaining({ setJSONState: expect.any(Function) }),
message: 'Plan the next milestone\nwith details',
onMessageAccepted: expect.any(Function),
+ onPreflightFailure: expect.any(Function),
});
expect(mocks.navigate).toHaveBeenCalledWith('/project/apollo/topic/tpc_1');
expect(input.clearContent).toHaveBeenCalled();
@@ -186,41 +214,139 @@ describe('useProjectComposer', () => {
);
});
+ /**
+ * @example Project home: sending kept the text and a spinner in the home
+ * composer until the server accepted the message β€” no optimistic message.
+ */
+ it('opens the conversation before the server has accepted the message', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ mocks.sendMessage.mockReturnValue(new Promise(() => {}));
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+ const input = composer('Hello');
+
+ await act(async () => {
+ await result.current.send(input);
+ });
+
+ expect(mocks.sendMessage).toHaveBeenCalled();
+ expect(mocks.navigate).toHaveBeenCalledWith('/project/apollo/topic/tpc_1');
+ expect(input.clearContent).toHaveBeenCalled();
+ expect(result.current.sending).toBe(false);
+ });
+
/**
* @example Codex review: a preflight rejection was fire-and-forget while the
* composer cleared itself and navigated, so the draft and attachments were lost.
*/
- it('keeps the draft and drops the empty topic when the send is refused before acceptance', async () => {
+ it('puts a draft the send refused back into the mounted conversation composer', async () => {
mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
mocks.fileList = [image];
+ const editor = mountConversationEditor();
mocks.sendMessage.mockRejectedValue(new Error('device offline'));
const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
- const input = composer('Hello');
await act(async () => {
- await expect(result.current.send(input)).rejects.toBeInstanceOf(MessageNotAcceptedError);
+ await result.current.send(composer('Hello'));
});
- expect(input.clearContent).not.toHaveBeenCalled();
- expect(mocks.clearChatUploadFileList).not.toHaveBeenCalled();
- expect(mocks.navigate).not.toHaveBeenCalled();
- expect(mocks.removeTopic).toHaveBeenCalledWith('tpc_1');
- expect(mocks.refreshProjectTopics).toHaveBeenCalledWith('prj_1');
- expect(result.current.sending).toBe(false);
+ expect(editor.setJSONState).toHaveBeenCalledWith(editorData);
+ expect(mocks.restoreChatUploadFileList).toHaveBeenCalledWith([image]);
+ expect(mocks.toastError).toHaveBeenCalledWith('overview.messageNotSent');
});
- it('treats a send that resolves without accepting the message as refused', async () => {
+ /**
+ * @example Acceptance: a send refused before the conversation page had
+ * rendered its composer brought the attachment back but not the text β€” the
+ * composer settles its document after it registers and wiped what was
+ * written into it.
+ */
+ it('keeps a draft refused before the conversation composer mounts in that conversation', async () => {
mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
- mocks.sendMessage.mockResolvedValue(undefined);
+ mocks.sendMessage.mockRejectedValue(new Error('device offline'));
const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
- const input = composer('Hello');
await act(async () => {
- await expect(result.current.send(input)).rejects.toBeInstanceOf(MessageNotAcceptedError);
+ await result.current.send(composer('Hello'));
});
- expect(input.clearContent).not.toHaveBeenCalled();
- expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(getDraft('main_coordinator_tpc_1')).toEqual(editorData);
+ });
+
+ it('leaves the restore to the send when it recovered the draft itself', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ mocks.fileList = [image];
+ const editor = mountConversationEditor();
+ // The send's own recovery: text into the composer it names, then the files.
+ mocks.sendMessage.mockImplementation(async ({ inputEditor, onPreflightFailure }) => {
+ inputEditor.setJSONState(editorData);
+ onPreflightFailure();
+ throw new Error('refused');
+ });
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+
+ await act(async () => {
+ await result.current.send(composer('Hello'));
+ });
+
+ expect(editor.setJSONState).toHaveBeenCalledTimes(1);
+ expect(mocks.restoreChatUploadFileList).toHaveBeenCalledTimes(1);
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ });
+
+ /**
+ * @example Codex review: a skill or local file that cannot be read makes the
+ * send hand back only the attachments before rejecting, and the text was lost.
+ */
+ it('puts the text back when the refusal only returned the attachments', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ mocks.fileList = [image];
+ const editor = mountConversationEditor();
+ mocks.sendMessage.mockImplementation(async ({ onPreflightFailure }) => {
+ onPreflightFailure();
+ throw new Error('skill unavailable');
+ });
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+
+ await act(async () => {
+ await result.current.send(composer('Hello'));
+ });
+
+ expect(editor.setJSONState).toHaveBeenCalledWith(editorData);
+ expect(mocks.restoreChatUploadFileList).toHaveBeenCalledTimes(1);
+ expect(mocks.toastError).toHaveBeenCalledWith('overview.messageNotSent');
+ });
+
+ /**
+ * @example Codex review: the user opened another conversation while the send
+ * was pending, and the refused draft overwrote that conversation's composer.
+ */
+ it('keeps a refused draft out of another conversation the user has opened', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ const other = mountConversationEditor('tpc_other');
+ mocks.sendMessage.mockRejectedValue(new Error('device offline'));
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+
+ await act(async () => {
+ await result.current.send(composer('Hello'));
+ });
+
+ expect(other.setJSONState).not.toHaveBeenCalled();
+ expect(getDraft('main_coordinator_tpc_1')).toEqual(editorData);
+ });
+
+ it('leaves a stopped send to the stop flow', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ const editor = mountConversationEditor();
+ const abort = Object.assign(new Error('The operation was aborted'), { name: 'AbortError' });
+ mocks.sendMessage.mockRejectedValue(abort);
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+
+ await act(async () => {
+ await result.current.send(composer('Hello'));
+ });
+
+ expect(editor.setJSONState).not.toHaveBeenCalled();
+ expect(mocks.toastError).not.toHaveBeenCalled();
});
/** @example Codex review: desktop notifications from these sends linked outside the workspace. */
diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.ts
index 018317117d0..97ffc100345 100644
--- a/src/features/Projects/Workspace/useProjectComposer.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.ts
@@ -1,16 +1,21 @@
+import { type IEditor } from '@lobehub/editor';
+import { toast } from '@lobehub/ui';
import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import type { ChatInputEditor } from '@/features/ChatInput';
+import { saveDraft } from '@/features/ChatInput/draftStorage';
import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';
import { appendTaskAttachments } from '@/features/Home/InputArea/taskAttachments';
import { taskNameFromMessage } from '@/features/Home/InputArea/taskName';
import { getProjectTopicPath } from '@/features/Projects/Layout/navigation';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { agentService } from '@/services/agent';
-import { topicService } from '@/services/topic';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { fileChatSelectors, useFileStore } from '@/store/file';
import type { ProjectDetail } from '@/store/project';
import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
@@ -39,6 +44,56 @@ const ensureAgentConfigLoaded = async (agentId: string) => {
if (config) agentState.internal_dispatchAgentMap(agentId, config);
};
+/**
+ * The composer that owns a send from the project home: the conversation page's,
+ * which mounts only after the navigation. It is looked up when the send needs
+ * it β€” to put a refused draft back β€” not when the send starts, and only while
+ * that conversation is the open one: every conversation registers as the main
+ * editor, so a user who has moved on keeps their own draft. Otherwise the draft
+ * goes to the drafts that composer restores for this conversation β€” also before
+ * it has mounted, since it settles its document after it first registers and
+ * would wipe a draft written into the editor directly.
+ */
+export const createConversationComposer = (conversation: { agentId: string; topicId: string }) => {
+ const draftKey = messageMapKey(conversation);
+ let textRestored = false;
+ const mounted = () => {
+ const { activeAgentId, activeTopicId, mainInputEditor } = useChatStore.getState();
+ return activeAgentId === conversation.agentId && activeTopicId === conversation.topicId
+ ? mainInputEditor
+ : null;
+ };
+
+ const editor: ChatInputEditor = {
+ clearContent: () => mounted()?.clearContent(),
+ focus: () => mounted()?.focus(),
+ getJSONState: () => mounted()?.getJSONState(),
+ getMarkdownContent: () => mounted()?.getMarkdownContent() ?? '',
+ get instance() {
+ return mounted()?.instance as IEditor;
+ },
+ // Only the plain-text fallback for a send without editor data comes here.
+ setDocument: (type, content, options) => {
+ textRestored = true;
+ mounted()?.setDocument(type, content, options);
+ },
+ setExpand: (expand) => mounted()?.setExpand(expand),
+ setJSONState: (content) => {
+ textRestored = true;
+ const current = mounted();
+ if (current) current.setJSONState(content);
+ else saveDraft(draftKey, content);
+ },
+ };
+
+ /** Whether the send has put the text back; attachments are reported apart. */
+ return { editor, textRestored: () => textRestored };
+};
+
+/** A user's stop restores the draft through the stop flow itself. */
+const isAbort = (error: unknown) =>
+ error instanceof Error && (error.name === 'AbortError' || error.message.includes('aborted'));
+
export class AttachmentsNotReadyError extends Error {
constructor() {
super('Attachments are still uploading');
@@ -46,24 +101,16 @@ export class AttachmentsNotReadyError extends Error {
}
}
-/** The send was refused before the message reached the conversation; the draft stays. */
-export class MessageNotAcceptedError extends Error {
- constructor() {
- super('The message was not accepted');
- this.name = 'MessageNotAcceptedError';
- }
-}
-
export const useProjectComposer = (
project: ProjectDetail['project'],
mode: ProjectComposerMode,
/** The project agent the message goes to; the main agent unless the user picked another. */
agentId: string,
) => {
+ const { t } = useTranslation('project');
const navigate = useWorkspaceAwareNavigate();
const workspaceSlug = useActiveWorkspaceSlug();
const createProjectTopic = useProjectDirectoryStore((s) => s.createProjectTopic);
- const refreshProjectTopics = useProjectDirectoryStore((s) => s.refreshProjectTopics);
const createTask = useTaskStore((s) => s.createTask);
const sendMessage = useChatStore((s) => s.sendMessage);
const clearChatUploadFileList = useFileStore((s) => s.clearChatUploadFileList);
@@ -104,39 +151,43 @@ export const useProjectComposer = (
createProjectTopic({ agentId, projectId: project.id, title }),
ensureAgentConfigLoaded(agentId),
]);
- // Leave the composer only once the conversation owns the message. A send
- // refused before that (access, device or preflight checks) either rejects
- // or resolves without accepting, and with `inputEditor: null` nothing
- // would put the draft back β€” so it stays here until then.
- const accepted = await new Promise<boolean>((resolve) => {
- sendMessage({
- context: { agentId, topicId: topic.id, ...(workspaceSlug ? { workspaceSlug } : {}) },
- editorData,
- files,
- inputEditor: null,
- message,
- onMessageAccepted: () => resolve(true),
- }).then(
- () => resolve(false),
- (error) => {
- console.error('[ProjectComposer] send failed', error);
- resolve(false);
- },
- );
- });
- if (!accepted) {
- // Don't leave an empty conversation behind for every failed attempt.
- await topicService
- .removeTopic(topic.id)
- .then(() => refreshProjectTopics(project.id))
- .catch((error) =>
- console.error('[ProjectComposer] failed to drop the empty topic', error),
- );
- throw new MessageNotAcceptedError();
- }
+ // Open the conversation right away: the send shows its message there
+ // optimistically instead of holding this composer until the server has
+ // accepted it. From here the conversation's composer owns the draft, so a
+ // refused send puts it back there rather than here.
clearContent();
clearChatUploadFileList();
navigate(getProjectTopicPath(project.slug ?? project.id, topic.id));
+
+ const conversation = createConversationComposer({ agentId, topicId: topic.id });
+ let accepted = false;
+ let filesRestored = false;
+ const restoreFiles = () => {
+ filesRestored = true;
+ useFileStore.getState().restoreChatUploadFileList(files);
+ };
+ sendMessage({
+ context: { agentId, topicId: topic.id, ...(workspaceSlug ? { workspaceSlug } : {}) },
+ editorData,
+ files,
+ inputEditor: conversation.editor,
+ message,
+ onMessageAccepted: () => {
+ accepted = true;
+ },
+ onPreflightFailure: restoreFiles,
+ }).catch((error) => {
+ console.error('[ProjectComposer] send failed', error);
+ if (accepted || isAbort(error)) return;
+ // Some refusals hand back only the attachments before rejecting (a
+ // skill or local file that cannot be read): put back whatever the send
+ // did not.
+ if (!filesRestored) restoreFiles();
+ if (conversation.textRestored()) return;
+ if (editorData) conversation.editor.setJSONState(editorData);
+ else conversation.editor.setDocument('markdown', message);
+ toast.error(t('overview.messageNotSent'));
+ });
} finally {
setSending(false);
}