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: fix not remove message with server mode (#9207)

Arvin Xu790af5ff40e3
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
index c1256870b38..9501ae58e36 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
@@ -19,7 +19,6 @@ import { ChatMessage } from '@/types/message';
import { useChatStore } from '../../../../store';
import { messageMapKey } from '../../../../utils/messageMapKey';
-import { generateAIChatV2 } from '../generateAIChatV2';
vi.stubGlobal(
'fetch',
@@ -113,6 +112,8 @@ const mockState = {
activeId: 'session-id',
activeTopicId: 'topic-id',
messages: [],
+ messagesMap: {},
+ mainSendMessageOperations: {},
refreshMessages: vi.fn(),
refreshTopic: vi.fn(),
internal_execAgentRuntime: vi.fn(),
@@ -486,6 +487,37 @@ describe('generateAIChatV2 actions', () => {
});
});
+ describe('Temporary message cleanup tests', () => {
+ it('should remove temporary message when creating new topic in default state', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const message = 'Test message for new topic';
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValueOnce({
+ isCreatNewTopic: true,
+ topicId: 'topic-id',
+ messages: [{}, {}] as any,
+ topics: [{}] as any,
+ assistantMessageId: 'abc',
+ userMessageId: 'user-',
+ });
+
+ await act(async () => {
+ // Set up default state (no activeTopicId, simulating inbox)
+ useChatStore.setState({
+ ...mockState,
+ activeTopicId: undefined, // This is the default state
+ messagesMap: {},
+ });
+
+ await result.current.sendMessage({ message });
+ });
+
+ // Verify that deleteMessage was called for temporary message cleanup
+ // This should happen because the mock aiChatService returns isCreatNewTopic: true
+ expect(useChatStore.getState().messagesMap['session-id_null']).toEqual([]);
+ });
+ });
+
describe('Topic switching tests', () => {
it('should automatically switch to newly created topic when no active topic exists', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts b/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts
index 2286d0a9bef..580d7b7a2bb 100644
--- a/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts
+++ b/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts
@@ -181,7 +181,13 @@ export const generateAIChatV2: StateCreator<
}
// remove temporally message
- get().internal_dispatchMessage({ type: 'deleteMessage', id: tempId });
+ if (data?.isCreatNewTopic) {
+ get().internal_dispatchMessage(
+ { type: 'deleteMessage', id: tempId },
+ { topicId: activeTopicId, sessionId: activeId },
+ );
+ }
+
get().internal_toggleMessageLoading(false, tempId);
get().internal_updateSendMessageOperation(
operationKey,
@@ -201,6 +207,26 @@ export const generateAIChatV2: StateCreator<
.filter((item) => item.id !== data.assistantMessageId);
if (data.topicId) get().internal_updateTopicLoading(data.topicId, true);
+
+ const summaryTitle = async () => {
+ // check activeTopic and then auto update topic title
+ if (data.isCreatNewTopic) {
+ await get().summaryTopicTitle(data.topicId, data.messages);
+ return;
+ }
+
+ if (!data.topicId) return;
+
+ const topic = topicSelectors.getTopicById(data.topicId)(get());
+
+ if (topic && !topic.title) {
+ const chats = chatSelectors.getBaseChatsByKey(messageMapKey(activeId, topic.id))(get());
+ await get().summaryTopicTitle(topic.id, chats);
+ }
+ };
+
+ summaryTitle().catch(console.error);
+
try {
await internal_execAgentRuntime({
messages: baseMessages,
@@ -211,31 +237,12 @@ export const generateAIChatV2: StateCreator<
threadId: activeThreadId,
});
- const summaryTitle = async () => {
- // check activeTopic and then auto update topic title
- if (data.isCreatNewTopic) {
- await get().summaryTopicTitle(data.topicId, data.messages);
- return;
- }
-
- if (!data.topicId) return;
-
- const topic = topicSelectors.getTopicById(data.topicId)(get());
-
- if (topic && !topic.title) {
- const chats = chatSelectors.getBaseChatsByKey(messageMapKey(activeId, topic.id))(get());
- await get().summaryTopicTitle(topic.id, chats);
- }
- };
//
// // if there is relative files, then add files to agent
// // only available in server mode
const userFiles = chatSelectors.currentUserFiles(get()).map((f) => f.id);
- const addFilesToAgent = async () => {
- await getAgentStoreState().addFilesToAgent(userFiles, false);
- };
- await Promise.all([summaryTitle(), addFilesToAgent()]);
+ await getAgentStoreState().addFilesToAgent(userFiles, false);
} catch (e) {
console.error(e);
} finally {
diff --git a/src/store/chat/slices/message/action.ts b/src/store/chat/slices/message/action.ts
index a0a350913ce..abb1cfaac2a 100644
--- a/src/store/chat/slices/message/action.ts
+++ b/src/store/chat/slices/message/action.ts
@@ -71,7 +71,10 @@ export interface ChatMessageAction {
* update message at the frontend
* this method will not update messages to database
*/
- internal_dispatchMessage: (payload: MessageDispatch) => void;
+ internal_dispatchMessage: (
+ payload: MessageDispatch,
+ context?: { topicId?: string | null; sessionId: string },
+ ) => void;
/**
* update the message content with optimistic update
@@ -305,14 +308,15 @@ export const chatMessage: StateCreator<
},
// the internal process method of the AI message
- internal_dispatchMessage: (payload) => {
- const { activeId } = get();
+ internal_dispatchMessage: (payload, context) => {
+ const activeId = typeof context !== 'undefined' ? context.sessionId : get().activeId;
+ const topicId = typeof context !== 'undefined' ? context.topicId : get().activeTopicId;
- if (!activeId) return;
+ const messagesKey = messageMapKey(activeId, topicId);
- const messages = messagesReducer(chatSelectors.activeBaseChats(get()), payload);
+ const messages = messagesReducer(chatSelectors.getBaseChatsByKey(messagesKey)(get()), payload);
- const nextMap = { ...get().messagesMap, [chatSelectors.currentChatKey(get())]: messages };
+ const nextMap = { ...get().messagesMap, [messagesKey]: messages };
if (isEqual(nextMap, get().messagesMap)) return;
diff --git a/src/store/global/action.test.ts b/src/store/global/action.test.ts
index 3eb8cce92f0..8c8f96c82a6 100644
--- a/src/store/global/action.test.ts
+++ b/src/store/global/action.test.ts
@@ -252,14 +252,13 @@ describe('createPreferenceSlice', () => {
describe('updatePreference', () => {
it('should update status', () => {
const { result } = renderHook(() => useGlobalStore());
- const status = { wideScreen: false };
act(() => {
useGlobalStore.setState({ isStatusInit: true });
- result.current.updateSystemStatus(status);
+ result.current.updateSystemStatus({ noWideScreen: false });
});
- expect(result.current.status.wideScreen).toEqual(false);
+ expect(result.current.status.noWideScreen).toEqual(false);
});
});
@@ -395,7 +394,7 @@ describe('createPreferenceSlice', () => {
it('should update with data', async () => {
const { result } = renderHook(() => useGlobalStore());
vi.spyOn(useGlobalStore.getState().statusStorage, 'getFromLocalStorage').mockReturnValueOnce({
- wideScreen: false,
+ noWideScreen: false,
} as any);
const { result: hooks } = renderHook(() => result.current.useInitSystemStatus(), {
@@ -403,10 +402,10 @@ describe('createPreferenceSlice', () => {
});
await waitFor(() => {
- expect(hooks.current.data).toEqual({ wideScreen: false });
+ expect(hooks.current.data).toEqual({ noWideScreen: false });
});
- expect(result.current.status.wideScreen).toEqual(false);
+ expect(result.current.status.noWideScreen).toEqual(false);
});
});
diff --git a/src/store/global/actions/__tests__/general.test.ts b/src/store/global/actions/__tests__/general.test.ts
index 8ae3059d5fb..3819977b343 100644
--- a/src/store/global/actions/__tests__/general.test.ts
+++ b/src/store/global/actions/__tests__/general.test.ts
@@ -34,7 +34,7 @@ describe('generalActionSlice', () => {
const { result } = renderHook(() => useGlobalStore());
act(() => {
- result.current.updateSystemStatus({ wideScreen: false });
+ result.current.updateSystemStatus({ noWideScreen: false });
});
expect(result.current.status).toEqual(initialState.status);
@@ -45,10 +45,10 @@ describe('generalActionSlice', () => {
act(() => {
useGlobalStore.setState({ isStatusInit: true });
- result.current.updateSystemStatus({ wideScreen: false });
+ result.current.updateSystemStatus({ noWideScreen: false });
});
- expect(result.current.status.wideScreen).toBe(false);
+ expect(result.current.status.noWideScreen).toBe(false);
});
it('should not update if new status equals current status', () => {
@@ -57,7 +57,7 @@ describe('generalActionSlice', () => {
act(() => {
useGlobalStore.setState({ isStatusInit: true });
- result.current.updateSystemStatus({ wideScreen: initialState.status.wideScreen });
+ result.current.updateSystemStatus({ noWideScreen: initialState.status.noWideScreen });
});
expect(saveToLocalStorageSpy).not.toHaveBeenCalled();
@@ -69,11 +69,11 @@ describe('generalActionSlice', () => {
act(() => {
useGlobalStore.setState({ isStatusInit: true });
- result.current.updateSystemStatus({ wideScreen: false });
+ result.current.updateSystemStatus({ noWideScreen: false });
});
expect(saveToLocalStorageSpy).toHaveBeenCalledWith(
- expect.objectContaining({ wideScreen: false }),
+ expect.objectContaining({ noWideScreen: false }),
);
});
diff --git a/src/store/global/actions/workspacePane.ts b/src/store/global/actions/workspacePane.ts
index 8ce72e87254..589c69dbeb3 100644
--- a/src/store/global/actions/workspacePane.ts
+++ b/src/store/global/actions/workspacePane.ts
@@ -89,9 +89,9 @@ export const globalWorkspaceSlice: StateCreator<
get().updateSystemStatus({ showSystemRole }, n('toggleMobileTopic', newValue));
},
toggleWideScreen: (newValue) => {
- const wideScreen = typeof newValue === 'boolean' ? newValue : !get().status.wideScreen;
+ const wideScreen = typeof newValue === 'boolean' ? newValue : !get().status.noWideScreen;
- get().updateSystemStatus({ wideScreen }, n('toggleWideScreen', newValue));
+ get().updateSystemStatus({ noWideScreen: wideScreen }, n('toggleWideScreen', newValue));
},
toggleZenMode: () => {
const { status } = get();
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 610d8ce353e..c47580040ae 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -73,6 +73,7 @@ export interface SystemStatus {
latestChangelogId?: string;
mobileShowPortal?: boolean;
mobileShowTopic?: boolean;
+ noWideScreen?: boolean;
portalWidth: number;
sessionsWidth: number;
showChatSideBar?: boolean;
@@ -87,7 +88,6 @@ export interface SystemStatus {
* theme mode
*/
themeMode?: ThemeMode;
- wideScreen?: boolean;
zenMode?: boolean;
}
@@ -124,6 +124,7 @@ export const INITIAL_STATUS = {
imagePanelWidth: 320,
imageTopicPanelWidth: 80,
mobileShowTopic: false,
+ noWideScreen: true,
portalWidth: 400,
sessionsWidth: 320,
showChatSideBar: true,
@@ -135,7 +136,6 @@ export const INITIAL_STATUS = {
showSystemRole: false,
systemRoleExpandedMap: {},
themeMode: 'auto',
- wideScreen: true,
zenMode: false,
} satisfies SystemStatus;
diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.ts
index be02ea4f8fa..152b51351ec 100644
--- a/src/store/global/selectors/systemStatus.test.ts
+++ b/src/store/global/selectors/systemStatus.test.ts
@@ -69,7 +69,7 @@ describe('systemStatusSelectors', () => {
expect(systemStatusSelectors.sessionWidth(s)).toBe(300);
expect(systemStatusSelectors.portalWidth(s)).toBe(500);
expect(systemStatusSelectors.filePanelWidth(s)).toBe(400);
- expect(systemStatusSelectors.wideScreen(s)).toBe(true);
+ expect(systemStatusSelectors.wideScreen(s)).toBe(false);
});
it('should handle zen mode effects', () => {
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index cac43ee170a..0bcf01d094b 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -28,7 +28,7 @@ const portalWidth = (s: GlobalState) => s.status.portalWidth || 400;
const filePanelWidth = (s: GlobalState) => s.status.filePanelWidth;
const imagePanelWidth = (s: GlobalState) => s.status.imagePanelWidth;
const imageTopicPanelWidth = (s: GlobalState) => s.status.imageTopicPanelWidth;
-const wideScreen = (s: GlobalState) => s.status.wideScreen;
+const wideScreen = (s: GlobalState) => !s.status.noWideScreen;
const expandInputActionbar = (s: GlobalState) => s.status.expandInputActionbar;
const isStatusInit = (s: GlobalState) => !!s.isStatusInit;
const isPgliteNotEnabled = (s: GlobalState) =>