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(send-message): forward topic-list filter to server response (#14160)

Arvin Xubbf239705c5b
diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.ts
index 2d385de4744..3e525783c0e 100644
--- a/packages/types/src/aiChat.ts
+++ b/packages/types/src/aiChat.ts
@@ -82,6 +82,17 @@ export interface SendMessageServerParams {
preloadMessages?: SendPreloadMessage[];
sessionId?: string;
threadId?: string;
+ /**
+ * Filters applied to the topic list returned alongside the message.
+ * Callers pass whatever filter the active sidebar is using so the server
+ * doesn't echo back topics the UI was already excluding (e.g. completed
+ * status), which would overwrite the filtered list in `topicDataMap`.
+ */
+ topicFilter?: {
+ excludeStatuses?: string[];
+ excludeTriggers?: string[];
+ includeTriggers?: string[];
+ };
// if there is activeTopicId, then add topicId to message
topicId?: string;
}
@@ -136,6 +147,13 @@ export const AiSendMessageServerSchema = z.object({
}),
sessionId: z.string().optional(),
threadId: z.string().optional(),
+ topicFilter: z
+ .object({
+ excludeStatuses: z.array(z.string()).optional(),
+ excludeTriggers: z.array(z.string()).optional(),
+ includeTriggers: z.array(z.string()).optional(),
+ })
+ .optional(),
topicId: z.string().optional(),
});
diff --git a/src/server/routers/lambda/aiChat.ts b/src/server/routers/lambda/aiChat.ts
index a527a9f1535..0302b716032 100644
--- a/src/server/routers/lambda/aiChat.ts
+++ b/src/server/routers/lambda/aiChat.ts
@@ -202,6 +202,7 @@ export const aiChatRouter = router({
includeTopic: isCreateNewTopic,
sessionId,
threadId,
+ topicFilter: input.topicFilter,
topicId,
});
diff --git a/src/server/services/aiChat/index.test.ts b/src/server/services/aiChat/index.test.ts
index 83ca7226654..e2a05a1dce8 100644
--- a/src/server/services/aiChat/index.test.ts
+++ b/src/server/services/aiChat/index.test.ts
@@ -42,6 +42,42 @@ describe('AiChatService', () => {
expect(res.topics).toEqual([{ id: 't1' }]);
});
+ it('getMessagesAndTopics should forward topicFilter to topicModel.query', async () => {
+ const serverDB = {} as unknown as LobeChatDatabase;
+
+ const mockQueryMessages = vi.fn().mockResolvedValue([]);
+ const mockQueryTopics = vi.fn().mockResolvedValue([]);
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ query: mockQueryMessages }) as any);
+ vi.mocked(TopicModel).mockImplementation(() => ({ query: mockQueryTopics }) as any);
+ vi.mocked(FileService).mockImplementation(
+ () => ({ getFullFileUrl: vi.fn().mockResolvedValue('url') }) as any,
+ );
+
+ const service = new AiChatService(serverDB, 'u1');
+
+ await service.getMessagesAndTopics({
+ agentId: 'agent-1',
+ includeTopic: true,
+ topicFilter: {
+ excludeStatuses: ['completed'],
+ excludeTriggers: ['cron', 'eval'],
+ },
+ });
+
+ expect(mockQueryTopics).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ excludeStatuses: ['completed'],
+ excludeTriggers: ['cron', 'eval'],
+ groupId: undefined,
+ });
+ // topicFilter must not leak into messageModel.query
+ expect(mockQueryMessages).toHaveBeenCalledWith(
+ expect.not.objectContaining({ topicFilter: expect.anything() }),
+ expect.objectContaining({ postProcessUrl: expect.any(Function) }),
+ );
+ });
+
it('getMessagesAndTopics should not query topics when includeTopic is false', async () => {
const serverDB = {} as unknown as LobeChatDatabase;
diff --git a/src/server/services/aiChat/index.ts b/src/server/services/aiChat/index.ts
index b3c30486ef9..a7980112679 100644
--- a/src/server/services/aiChat/index.ts
+++ b/src/server/services/aiChat/index.ts
@@ -26,14 +26,24 @@ export class AiChatService {
pageSize?: number;
sessionId?: string;
threadId?: string;
+ topicFilter?: {
+ excludeStatuses?: string[];
+ excludeTriggers?: string[];
+ includeTriggers?: string[];
+ };
topicId?: string;
}) {
+ const { topicFilter, ...messageParams } = params;
const [messages, topics] = await Promise.all([
- this.messageModel.query(params, {
+ this.messageModel.query(messageParams, {
postProcessUrl: (path) => this.fileService.getFullFileUrl(path),
}),
params.includeTopic
- ? this.topicModel.query({ agentId: params.agentId, groupId: params.groupId })
+ ? this.topicModel.query({
+ agentId: params.agentId,
+ groupId: params.groupId,
+ ...topicFilter,
+ })
: undefined,
]);
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index d01aade6b38..bfcf5a86b28 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -46,6 +46,7 @@ import { useUserMemoryStore } from '@/store/userMemory';
import { dbMessageSelectors, displayMessageSelectors, topicSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
+import { topicMapKey } from '../../../utils/topicMapKey';
import { AI_RUNTIME_OPERATION_TYPES } from '../../operation/types';
import {
type CommandSendOverrides,
@@ -118,6 +119,30 @@ export class ConversationLifecycleActionImpl {
this.#get = get;
}
+ /**
+ * Read the active topic-list filter from `topicDataMap` so it can be
+ * forwarded to `sendMessageInServer`. Without this, the server returns
+ * an unfiltered list which `internal_updateTopics` then writes back over
+ * the filtered sidebar — completed/cron topics reappear until the next
+ * SWR revalidation.
+ */
+ #getTopicFilter = (
+ agentId?: string,
+ groupId?: string,
+ ):
+ | { excludeStatuses?: string[]; excludeTriggers?: string[]; includeTriggers?: string[] }
+ | undefined => {
+ if (!agentId && !groupId) return undefined;
+ const data = this.#get().topicDataMap[topicMapKey({ agentId, groupId })];
+ if (!data) return undefined;
+ const { excludeStatuses, excludeTriggers } = data;
+ if (!excludeStatuses?.length && !excludeTriggers?.length) return undefined;
+ return {
+ ...(excludeStatuses?.length ? { excludeStatuses } : {}),
+ ...(excludeTriggers?.length ? { excludeTriggers } : {}),
+ };
+ };
+
sendMessage = async ({
message,
editorData: inputEditorData,
@@ -411,6 +436,10 @@ export class ConversationLifecycleActionImpl {
parentId,
},
threadId: operationContext.threadId ?? undefined,
+ topicFilter: this.#getTopicFilter(
+ operationContext.agentId,
+ operationContext.groupId ?? undefined,
+ ),
topicId: operationContext.topicId ?? undefined,
},
abortController,
@@ -602,6 +631,10 @@ export class ConversationLifecycleActionImpl {
preloadMessages: undefined,
// if there is topicId, then add topicId to message
topicId: topicId ?? undefined,
+ topicFilter: this.#getTopicFilter(
+ operationContext.agentId,
+ operationContext.groupId ?? undefined,
+ ),
threadId: operationContext.threadId ?? undefined,
// Support creating new thread along with message
newThread: newThread
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index b03d8c1601c..e68306e2463 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -1109,4 +1109,44 @@ describe('topic action', () => {
expect(summaryTopicTitleSpy).toHaveBeenCalledWith(topicId, messages);
});
});
+
+ describe('internal_updateTopics', () => {
+ it('should preserve excludeStatuses/excludeTriggers from existing topicDataMap entry', () => {
+ const agentId = 'agent-1';
+ const key = topicMapKey({ agentId });
+ const { result } = renderHook(() => useChatStore());
+
+ // Seed the entry as the SWR onData handler would, with filter fields.
+ act(() => {
+ useChatStore.setState({
+ topicDataMap: {
+ [key]: {
+ currentPage: 0,
+ excludeStatuses: ['completed'],
+ excludeTriggers: ['cron', 'eval'],
+ hasMore: false,
+ isExpandingPageSize: false,
+ items: [{ id: 'topic-1', title: 'old' } as ChatTopic],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+ });
+
+ // Simulate the post-sendMessage write-back which previously dropped filters.
+ act(() => {
+ result.current.internal_updateTopics(agentId, {
+ items: [{ id: 'topic-2', title: 'new' } as ChatTopic],
+ pageSize: 20,
+ total: 2,
+ });
+ });
+
+ const next = useChatStore.getState().topicDataMap[key];
+ expect(next.excludeStatuses).toEqual(['completed']);
+ expect(next.excludeTriggers).toEqual(['cron', 'eval']);
+ expect(next.items.map((i) => i.id)).toEqual(['topic-2']);
+ });
+ });
});
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 0bb71be87b4..1a80bf50d84 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -762,6 +762,13 @@ export class ChatTopicActionImpl {
...this.#get().topicDataMap,
[key]: {
currentPage,
+ // Carry filter fields forward so subsequent reads (e.g. the
+ // sendMessageInServer `topicFilter` helper) keep seeing the
+ // filter the SWR fetch was using; otherwise the next request
+ // forgets to exclude completed/cron topics until SWR
+ // revalidates.
+ excludeStatuses: currentData?.excludeStatuses,
+ excludeTriggers: currentData?.excludeTriggers,
hasMore: items.length >= pageSize,
isExpandingPageSize: false,
isLoadingMore: false,