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.

♻️ refactor: refactor chat message model to speed up (#10053)

Arvin Xu035994f1a81c
diff --git a/packages/database/package.json b/packages/database/package.json
index 60e51720530..b84d767aabf 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -24,7 +24,7 @@
"peerDependencies": {
"@electric-sql/pglite": "^0.2.17",
"dayjs": ">=1.11.18",
- "drizzle-orm": ">=0.44.6",
+ "drizzle-orm": ">=0.44.7",
"nanoid": ">=5.1.5",
"pg": ">=8.16.3"
}
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 780f581c691..7377c3ff8d0 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -603,6 +603,7 @@ export class MessageModel {
id: string,
{ imageList, ...message }: Partial<UpdateMessageParams>,
options?: {
+ groupAssistantMessages?: boolean;
postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
sessionId?: string | null;
topicId?: string | null;
@@ -633,6 +634,7 @@ export class MessageModel {
topicId: options.topicId,
},
{
+ groupAssistantMessages: options.groupAssistantMessages ?? false,
postProcessUrl: options.postProcessUrl,
},
);
@@ -660,16 +662,41 @@ export class MessageModel {
.where(and(eq(messages.userId, this.userId), eq(messages.id, id)));
};
- updatePluginState = async (id: string, state: Record<string, any>) => {
+ updatePluginState = async (
+ id: string,
+ state: Record<string, any>,
+ options?: {
+ groupAssistantMessages?: boolean;
+ postProcessUrl?: (path: string | null, file: { fileType: string }) => Promise<string>;
+ sessionId?: string | null;
+ topicId?: string | null;
+ },
+ ): Promise<UpdateMessageResult> => {
const item = await this.db.query.messagePlugins.findFirst({
where: eq(messagePlugins.id, id),
});
if (!item) throw new Error('Plugin not found');
- return this.db
+ await this.db
.update(messagePlugins)
.set({ state: merge(item.state || {}, state) })
.where(eq(messagePlugins.id, id));
+
+ // Return updated messages if sessionId or topicId is provided
+ if (options?.sessionId !== undefined || options?.topicId !== undefined) {
+ const messageList = await this.query(
+ {
+ sessionId: options.sessionId,
+ topicId: options.topicId,
+ },
+ {
+ groupAssistantMessages: options.groupAssistantMessages ?? false,
+ postProcessUrl: options.postProcessUrl,
+ },
+ );
+ return { messages: messageList, success: true };
+ }
+ return { success: true };
};
updateMessagePlugin = async (id: string, value: Partial<MessagePluginItem>) => {
diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.ts
index 315c092ba1f..e62efe78245 100644
--- a/packages/types/src/message/ui/params.ts
+++ b/packages/types/src/message/ui/params.ts
@@ -120,55 +120,6 @@ const ChatPluginPayloadSchema = z.object({
type: z.string(),
});
-export const CreateMessageParamsSchema = z
- .object({
- content: z.string(),
- role: UIMessageRoleTypeSchema,
- sessionId: z.string().nullable().optional(),
- error: ChatMessageErrorSchema.nullable().optional(),
- fileChunks: z.array(SemanticSearchChunkSchema).optional(),
- files: z.array(z.string()).optional(),
- fromModel: z.string().optional(),
- fromProvider: z.string().optional(),
- groupId: z.string().nullable().optional(),
- targetId: z.string().nullable().optional(),
- threadId: z.string().nullable().optional(),
- topicId: z.string().nullable().optional(),
- traceId: z.string().optional(),
- // Allow additional fields from UIChatMessage (many can be null)
- agentId: z.string().optional(),
- children: z.any().optional(),
- chunksList: z.any().optional(),
- createdAt: z.number().optional(),
- extra: z.any().optional(),
- favorite: z.boolean().optional(),
- fileList: z.any().optional(),
- id: z.string().optional(),
- imageList: z.any().optional(),
- meta: z.any().optional(),
- metadata: z.any().nullable().optional(),
- model: z.string().nullable().optional(),
- observationId: z.string().optional(),
- parentId: z.string().optional(),
- performance: z.any().optional(),
- plugin: z.any().optional(),
- pluginError: z.any().optional(),
- pluginState: z.any().optional(),
- provider: z.string().nullable().optional(),
- quotaId: z.string().optional(),
- ragQuery: z.string().nullable().optional(),
- ragQueryId: z.string().nullable().optional(),
- reasoning: z.any().optional(),
- search: z.any().optional(),
- tool_call_id: z.string().optional(),
- toolCalls: z.any().optional(),
- tools: z.any().optional(),
- translate: z.any().optional(),
- tts: z.any().optional(),
- updatedAt: z.number().optional(),
- })
- .passthrough();
-
export const CreateNewMessageParamsSchema = z
.object({
// Required fields
diff --git a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts b/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
index 946b8091ba3..0cd99b20ba6 100644
--- a/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/message.integration.test.ts
@@ -72,7 +72,7 @@ describe('Message Router Integration Tests', () => {
it('should create message with correct sessionId and topicId', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
- const messageId = await caller.createMessage({
+ const result = await caller.createNewMessage({
content: 'Test message',
role: 'user',
sessionId: testSessionId,
@@ -83,11 +83,11 @@ describe('Message Router Integration Tests', () => {
const [createdMessage] = await serverDB
.select()
.from(messages)
- .where(eq(messages.id, messageId));
+ .where(eq(messages.id, result.id));
expect(createdMessage).toBeDefined();
expect(createdMessage).toMatchObject({
- id: messageId,
+ id: result.id,
sessionId: testSessionId,
topicId: testTopicId,
userId: userId,
@@ -111,7 +111,7 @@ describe('Message Router Integration Tests', () => {
})
.returning();
- const messageId = await caller.createMessage({
+ const result = await caller.createNewMessage({
content: 'Test message in thread',
role: 'user',
sessionId: testSessionId,
@@ -123,12 +123,12 @@ describe('Message Router Integration Tests', () => {
const [createdMessage] = await serverDB
.select()
.from(messages)
- .where(eq(messages.id, messageId));
+ .where(eq(messages.id, result.id));
expect(createdMessage).toBeDefined();
expect(createdMessage.threadId).toBe(thread.id);
expect(createdMessage).toMatchObject({
- id: messageId,
+ id: result.id,
sessionId: testSessionId,
topicId: testTopicId,
threadId: thread.id,
@@ -140,7 +140,7 @@ describe('Message Router Integration Tests', () => {
it('should create message without topicId', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
- const messageId = await caller.createMessage({
+ const result = await caller.createNewMessage({
content: 'Test message without topic',
role: 'user',
sessionId: testSessionId,
@@ -150,7 +150,7 @@ describe('Message Router Integration Tests', () => {
const [createdMessage] = await serverDB
.select()
.from(messages)
- .where(eq(messages.id, messageId));
+ .where(eq(messages.id, result.id));
expect(createdMessage.topicId).toBeNull();
expect(createdMessage.sessionId).toBe(testSessionId);
@@ -160,7 +160,7 @@ describe('Message Router Integration Tests', () => {
const caller = messageRouter.createCaller(createTestContext(userId));
await expect(
- caller.createMessage({
+ caller.createNewMessage({
content: 'Test message',
role: 'user',
sessionId: 'non-existent-session',
@@ -192,7 +192,7 @@ describe('Message Router Integration Tests', () => {
// 尝试在 testSessionId 下创建消息,但使用 anotherTopic 的 ID
await expect(
- caller.createMessage({
+ caller.createNewMessage({
content: 'Test message',
role: 'user',
sessionId: testSessionId,
@@ -207,13 +207,13 @@ describe('Message Router Integration Tests', () => {
const caller = messageRouter.createCaller(createTestContext(userId));
// 创建多个消息
- const msg1Id = await caller.createMessage({
+ const msg1Result = await caller.createNewMessage({
content: 'Message 1',
role: 'user',
sessionId: testSessionId,
});
- const msg2Id = await caller.createMessage({
+ const msg2Result = await caller.createNewMessage({
content: 'Message 2',
role: 'assistant',
sessionId: testSessionId,
@@ -228,7 +228,7 @@ describe('Message Router Integration Tests', () => {
})
.returning();
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Message in another session',
role: 'user',
sessionId: anotherSession.id,
@@ -240,15 +240,15 @@ describe('Message Router Integration Tests', () => {
});
expect(result).toHaveLength(2);
- expect(result.map((m) => m.id)).toContain(msg1Id);
- expect(result.map((m) => m.id)).toContain(msg2Id);
+ expect(result.map((m) => m.id)).toContain(msg1Result.id);
+ expect(result.map((m) => m.id)).toContain(msg2Result.id);
});
it('should return messages filtered by topicId', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
// 在 topic 中创建消息
- const msgInTopicId = await caller.createMessage({
+ const msgInTopicResult = await caller.createNewMessage({
content: 'Message in topic',
role: 'user',
sessionId: testSessionId,
@@ -256,7 +256,7 @@ describe('Message Router Integration Tests', () => {
});
// 在 session 中创建消息(不在 topic 中)
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Message without topic',
role: 'user',
sessionId: testSessionId,
@@ -269,7 +269,7 @@ describe('Message Router Integration Tests', () => {
});
expect(result).toHaveLength(1);
- expect(result[0].id).toBe(msgInTopicId);
+ expect(result[0].id).toBe(msgInTopicResult.id);
expect(result[0].topicId).toBe(testTopicId);
});
@@ -278,7 +278,7 @@ describe('Message Router Integration Tests', () => {
// 创建多个消息
for (let i = 0; i < 5; i++) {
- await caller.createMessage({
+ await caller.createNewMessage({
content: `Pagination test message ${i}`,
role: 'user',
sessionId: testSessionId,
@@ -323,20 +323,20 @@ describe('Message Router Integration Tests', () => {
const caller = messageRouter.createCaller(createTestContext(userId));
// 创建消息
- const msg1Id = await caller.createMessage({
+ const msg1Result = await caller.createNewMessage({
content: 'Message 1',
role: 'user',
sessionId: testSessionId,
});
- const msg2Id = await caller.createMessage({
+ const msg2Result = await caller.createNewMessage({
content: 'Message 2',
role: 'user',
sessionId: testSessionId,
});
// 删除消息
- await caller.removeMessages({ ids: [msg1Id, msg2Id] });
+ await caller.removeMessages({ ids: [msg1Result.id, msg2Result.id] });
// 验证消息已删除
const remainingMessages = await serverDB
@@ -353,13 +353,13 @@ describe('Message Router Integration Tests', () => {
const caller = messageRouter.createCaller(createTestContext(userId));
// 创建多个消息
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Message 1',
role: 'user',
sessionId: testSessionId,
});
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Message 2',
role: 'assistant',
sessionId: testSessionId,
@@ -383,7 +383,7 @@ describe('Message Router Integration Tests', () => {
const caller = messageRouter.createCaller(createTestContext(userId));
// 在 topic 中创建消息
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Message in topic',
role: 'user',
sessionId: testSessionId,
@@ -391,7 +391,7 @@ describe('Message Router Integration Tests', () => {
});
// 在 session 中创建消息(不在 topic 中)
- const msgOutsideTopicId = await caller.createMessage({
+ const msgOutsideTopicResult = await caller.createNewMessage({
content: 'Message outside topic',
role: 'user',
sessionId: testSessionId,
@@ -410,7 +410,7 @@ describe('Message Router Integration Tests', () => {
.where(eq(messages.sessionId, testSessionId));
expect(remainingMessages).toHaveLength(1);
- expect(remainingMessages[0].id).toBe(msgOutsideTopicId);
+ expect(remainingMessages[0].id).toBe(msgOutsideTopicResult.id);
});
});
@@ -418,14 +418,14 @@ describe('Message Router Integration Tests', () => {
it('should update message content', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
- const messageId = await caller.createMessage({
+ const result = await caller.createNewMessage({
content: 'Original content',
role: 'user',
sessionId: testSessionId,
});
await caller.update({
- id: messageId,
+ id: result.id,
value: {
content: 'Updated content',
},
@@ -434,7 +434,7 @@ describe('Message Router Integration Tests', () => {
const [updatedMessage] = await serverDB
.select()
.from(messages)
- .where(eq(messages.id, messageId));
+ .where(eq(messages.id, result.id));
expect(updatedMessage.content).toBe('Updated content');
});
@@ -444,13 +444,13 @@ describe('Message Router Integration Tests', () => {
it('should search messages by keyword', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'This is a test message about TypeScript',
role: 'user',
sessionId: testSessionId,
});
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Another message about JavaScript',
role: 'user',
sessionId: testSessionId,
@@ -470,13 +470,13 @@ describe('Message Router Integration Tests', () => {
const caller = messageRouter.createCaller(createTestContext(userId));
// 创建消息
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Message 1',
role: 'user',
sessionId: testSessionId,
});
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Message 2',
role: 'assistant',
sessionId: testSessionId,
@@ -490,7 +490,7 @@ describe('Message Router Integration Tests', () => {
it('should count words', async () => {
const caller = messageRouter.createCaller(createTestContext(userId));
- await caller.createMessage({
+ await caller.createNewMessage({
content: 'Hello world',
role: 'user',
sessionId: testSessionId,
diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.ts
index e8bfd221775..c0d5f723252 100644
--- a/src/server/routers/lambda/message.ts
+++ b/src/server/routers/lambda/message.ts
@@ -1,5 +1,4 @@
import {
- CreateMessageParamsSchema,
CreateNewMessageParamsSchema,
UpdateMessageParamsSchema,
UpdateMessageRAGParamsSchema,
@@ -53,14 +52,6 @@ export const messageRouter = router({
return ctx.messageModel.countWords(input);
}),
- createMessage: messageProcedure
- .input(CreateMessageParamsSchema)
- .mutation(async ({ input, ctx }) => {
- const data = await ctx.messageModel.create(input as any);
-
- return data.id;
- }),
-
createNewMessage: messageProcedure
.input(CreateNewMessageParamsSchema)
.mutation(async ({ input, ctx }) => {
@@ -109,9 +100,32 @@ export const messageRouter = router({
}),
removeMessage: messageProcedure
- .input(z.object({ id: z.string() }))
+ .input(
+ z.object({
+ id: z.string(),
+ sessionId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+ useGroup: z.boolean().optional(),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.deleteMessage(input.id);
+ await ctx.messageModel.deleteMessage(input.id);
+
+ // If sessionId or topicId is provided, return the full message list
+ if (input.sessionId !== undefined || input.topicId !== undefined) {
+ const messageList = await ctx.messageModel.query(
+ {
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ },
+ {
+ groupAssistantMessages: input.useGroup ?? false,
+ postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
+ },
+ );
+ return { messages: messageList, success: true };
+ }
+ return { success: true };
}),
removeMessageQuery: messageProcedure
@@ -121,9 +135,32 @@ export const messageRouter = router({
}),
removeMessages: messageProcedure
- .input(z.object({ ids: z.array(z.string()) }))
+ .input(
+ z.object({
+ ids: z.array(z.string()),
+ sessionId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+ useGroup: z.boolean().optional(),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.deleteMessages(input.ids);
+ await ctx.messageModel.deleteMessages(input.ids);
+
+ // If sessionId or topicId is provided, return the full message list
+ if (input.sessionId !== undefined || input.topicId !== undefined) {
+ const messageList = await ctx.messageModel.query(
+ {
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ },
+ {
+ groupAssistantMessages: input.useGroup ?? false,
+ postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
+ },
+ );
+ return { messages: messageList, success: true };
+ }
+ return { success: true };
}),
removeMessagesByAssistant: messageProcedure
@@ -165,11 +202,13 @@ export const messageRouter = router({
id: z.string(),
sessionId: z.string().nullable().optional(),
topicId: z.string().nullable().optional(),
+ useGroup: z.boolean().optional(),
value: UpdateMessageParamsSchema,
}),
)
.mutation(async ({ input, ctx }) => {
return ctx.messageModel.update(input.id, input.value as any, {
+ groupAssistantMessages: input.useGroup ?? false,
postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
sessionId: input.sessionId,
topicId: input.topicId,
@@ -188,9 +227,31 @@ export const messageRouter = router({
}),
updateMessageRAG: messageProcedure
- .input(UpdateMessageRAGParamsSchema)
+ .input(
+ UpdateMessageRAGParamsSchema.extend({
+ sessionId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+ useGroup: z.boolean().optional(),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
await ctx.messageModel.updateMessageRAG(input.id, input.value);
+
+ // If sessionId or topicId is provided, return the full message list
+ if (input.sessionId !== undefined || input.topicId !== undefined) {
+ const messageList = await ctx.messageModel.query(
+ {
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ },
+ {
+ groupAssistantMessages: input.useGroup ?? false,
+ postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
+ },
+ );
+ return { messages: messageList, success: true };
+ }
+ return { success: true };
}),
updateMetadata: messageProcedure
@@ -208,22 +269,49 @@ export const messageRouter = router({
.input(
z.object({
id: z.string(),
+ sessionId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+ useGroup: z.boolean().optional(),
value: z.object({}).passthrough().nullable(),
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.updateMessagePlugin(input.id, { error: input.value });
+ // If sessionId or topicId is provided, we need to return the full message list
+ if (input.sessionId !== undefined || input.topicId !== undefined) {
+ await ctx.messageModel.updateMessagePlugin(input.id, { error: input.value });
+ const messageList = await ctx.messageModel.query(
+ {
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ },
+ {
+ groupAssistantMessages: input.useGroup ?? false,
+ postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
+ },
+ );
+ return { messages: messageList, success: true };
+ }
+ await ctx.messageModel.updateMessagePlugin(input.id, { error: input.value });
+ return { success: true };
}),
updatePluginState: messageProcedure
.input(
z.object({
id: z.string(),
+ sessionId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
+ useGroup: z.boolean().optional(),
value: z.object({}).passthrough(),
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.updatePluginState(input.id, input.value);
+ return ctx.messageModel.updatePluginState(input.id, input.value, {
+ groupAssistantMessages: input.useGroup ?? false,
+ postProcessUrl: (path) => ctx.fileService.getFullFileUrl(path),
+ sessionId: input.sessionId,
+ topicId: input.topicId,
+ });
}),
updateTTS: messageProcedure
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 99d7746878a..0d00012d0f5 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -2,8 +2,8 @@
import {
ChatMessageError,
ChatMessagePluginError,
- ChatTranslate,
ChatTTS,
+ ChatTranslate,
CreateMessageParams,
CreateMessageResult,
ModelRankItem,
@@ -20,12 +20,9 @@ import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
export class MessageService {
- createMessage = async ({ sessionId, ...params }: CreateMessageParams): Promise<string> => {
- return lambdaClient.message.createMessage.mutate({
- ...params,
- sessionId: sessionId ? this.toDbSessionId(sessionId) : undefined,
- });
- };
+ private get useGroup() {
+ return labPreferSelectors.enableAssistantMessageGroup(useUserStore.getState());
+ }
createNewMessage = async ({
sessionId,
@@ -42,27 +39,21 @@ export class MessageService {
topicId?: string,
groupId?: string,
): Promise<UIChatMessage[]> => {
- // Get user lab preference for message grouping
- const useGroup = labPreferSelectors.enableAssistantMessageGroup(useUserStore.getState());
-
const data = await lambdaClient.message.getMessages.query({
groupId,
sessionId: this.toDbSessionId(sessionId),
topicId,
- useGroup,
+ useGroup: this.useGroup,
});
return data as unknown as UIChatMessage[];
};
getGroupMessages = async (groupId: string, topicId?: string): Promise<UIChatMessage[]> => {
- // Get user lab preference for message grouping
- const useGroup = labPreferSelectors.enableAssistantMessageGroup(useUserStore.getState());
-
const data = await lambdaClient.message.getMessages.query({
groupId,
topicId,
- useGroup,
+ useGroup: this.useGroup,
});
return data as unknown as UIChatMessage[];
};
@@ -109,6 +100,7 @@ export class MessageService {
id,
sessionId: options?.sessionId,
topicId: options?.topicId,
+ useGroup: this.useGroup,
value,
});
};
@@ -121,24 +113,70 @@ export class MessageService {
return lambdaClient.message.updateTTS.mutate({ id, value: tts });
};
- updateMessagePluginState = async (id: string, value: Record<string, any>) => {
- return lambdaClient.message.updatePluginState.mutate({ id, value });
+ updateMessagePluginState = async (
+ id: string,
+ value: Record<string, any>,
+ options?: { sessionId?: string | null; topicId?: string | null },
+ ): Promise<UpdateMessageResult> => {
+ return lambdaClient.message.updatePluginState.mutate({
+ id,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ useGroup: this.useGroup,
+ value,
+ });
};
- updateMessagePluginError = async (id: string, error: ChatMessagePluginError | null) => {
- return lambdaClient.message.updatePluginError.mutate({ id, value: error as any });
+ updateMessagePluginError = async (
+ id: string,
+ error: ChatMessagePluginError | null,
+ options?: { sessionId?: string | null; topicId?: string | null },
+ ): Promise<UpdateMessageResult> => {
+ return lambdaClient.message.updatePluginError.mutate({
+ id,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ useGroup: this.useGroup,
+ value: error as any,
+ });
};
- updateMessageRAG = async (id: string, data: UpdateMessageRAGParams): Promise<void> => {
- return lambdaClient.message.updateMessageRAG.mutate({ id, value: data });
+ updateMessageRAG = async (
+ id: string,
+ data: UpdateMessageRAGParams,
+ options?: { sessionId?: string | null; topicId?: string | null },
+ ): Promise<UpdateMessageResult> => {
+ return lambdaClient.message.updateMessageRAG.mutate({
+ id,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ useGroup: this.useGroup,
+ value: data,
+ });
};
- removeMessage = async (id: string) => {
- return lambdaClient.message.removeMessage.mutate({ id });
+ removeMessage = async (
+ id: string,
+ options?: { sessionId?: string | null; topicId?: string | null },
+ ): Promise<UpdateMessageResult> => {
+ return lambdaClient.message.removeMessage.mutate({
+ id,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ useGroup: this.useGroup,
+ });
};
- removeMessages = async (ids: string[]) => {
- return lambdaClient.message.removeMessages.mutate({ ids });
+ removeMessages = async (
+ ids: string[],
+ options?: { sessionId?: string | null; topicId?: string | null },
+ ): Promise<UpdateMessageResult> => {
+ return lambdaClient.message.removeMessages.mutate({
+ ids,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ useGroup: this.useGroup,
+ });
};
removeMessagesByAssistant = async (sessionId: string, topicId?: string) => {
@@ -162,16 +200,6 @@ export class MessageService {
private toDbSessionId = (sessionId: string | undefined) => {
return sessionId === INBOX_SESSION_ID ? null : sessionId;
};
-
- hasMessages = async (): Promise<boolean> => {
- const number = await this.countMessages();
- return number > 0;
- };
-
- messageCountToCheckTrace = async (): Promise<boolean> => {
- const number = await this.countMessages();
- return number >= 4;
- };
}
export const messageService = new MessageService();
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts
index 386e36acff7..47f0560c863 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChat.test.ts
@@ -61,7 +61,7 @@ describe('chatMessage actions', () => {
await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();
});
@@ -72,7 +72,7 @@ describe('chatMessage actions', () => {
await result.current.sendMessage({ message: TEST_CONTENT.EMPTY });
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
});
it('should not send when message is empty with empty files array', async () => {
@@ -82,7 +82,7 @@ describe('chatMessage actions', () => {
await result.current.sendMessage({ message: TEST_CONTENT.EMPTY, files: [] });
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
});
});
@@ -97,13 +97,13 @@ describe('chatMessage actions', () => {
});
});
- expect(messageService.createMessage).toHaveBeenCalled();
+ expect(messageService.createNewMessage).toHaveBeenCalled();
expect(result.current.internal_coreProcessMessage).not.toHaveBeenCalled();
});
it('should handle message creation errors gracefully', async () => {
const { result } = renderHook(() => useChatStore());
- vi.spyOn(messageService, 'createMessage').mockRejectedValue(
+ vi.spyOn(messageService, 'createNewMessage').mockRejectedValue(
new Error('create message error'),
);
@@ -210,6 +210,8 @@ describe('chatMessage actions', () => {
describe('internal_coreProcessMessage', () => {
it('should process user message and generate AI response', async () => {
+ const mockMessages = [{ id: 'msg-1', content: 'test' }] as any;
+
act(() => {
useChatStore.setState({ internal_coreProcessMessage: realCoreProcessMessage });
});
@@ -227,8 +229,10 @@ describe('chatMessage actions', () => {
.mockResolvedValue({ isFunctionCall: false, content: 'AI response' });
const createMessageSpy = vi
- .spyOn(messageService, 'createMessage')
- .mockResolvedValue(TEST_IDS.ASSISTANT_MESSAGE_ID);
+ .spyOn(messageService, 'createNewMessage')
+ .mockResolvedValue({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, messages: mockMessages });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
await act(async () => {
await result.current.internal_coreProcessMessage([userMessage], userMessage.id);
@@ -245,7 +249,7 @@ describe('chatMessage actions', () => {
);
expect(fetchAIChatSpy).toHaveBeenCalled();
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
});
it('should handle RAG flow when ragQuery is provided', async () => {
@@ -268,7 +272,10 @@ describe('chatMessage actions', () => {
rewriteQuery: 'rewritten query',
});
- vi.spyOn(messageService, 'createMessage').mockResolvedValue(TEST_IDS.ASSISTANT_MESSAGE_ID);
+ vi.spyOn(messageService, 'createNewMessage').mockResolvedValue({
+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [],
+ });
await act(async () => {
await result.current.internal_coreProcessMessage([userMessage], userMessage.id, {
@@ -299,7 +306,7 @@ describe('chatMessage actions', () => {
.spyOn(result.current, 'internal_fetchAIChatMessage')
.mockResolvedValue({ isFunctionCall: false, content: '' });
- vi.spyOn(messageService, 'createMessage').mockResolvedValue(undefined as any);
+ vi.spyOn(messageService, 'createNewMessage').mockResolvedValue(undefined as any);
await act(async () => {
await result.current.internal_coreProcessMessage([userMessage], userMessage.id);
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 4c8015ff5f4..e6bffc47425 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/generateAIChatV2.test.ts
@@ -131,7 +131,7 @@ describe('generateAIChatV2 actions', () => {
await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
});
@@ -142,7 +142,7 @@ describe('generateAIChatV2 actions', () => {
await result.current.sendMessage({ message: TEST_CONTENT.EMPTY });
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
});
it('should not send when message is empty with empty files array', async () => {
@@ -152,7 +152,7 @@ describe('generateAIChatV2 actions', () => {
await result.current.sendMessage({ message: TEST_CONTENT.EMPTY, files: [] });
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
});
});
@@ -312,7 +312,7 @@ describe('generateAIChatV2 actions', () => {
});
});
- expect(messageService.createMessage).toHaveBeenCalled();
+ expect(messageService.createNewMessage).toHaveBeenCalled();
expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
});
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
index 586bc07a20f..180b7a72d21 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts
@@ -58,8 +58,8 @@ export const createMockAbortController = () => {
*/
export const spyOnMessageService = () => {
const createMessageSpy = vi
- .spyOn(messageService, 'createMessage')
- .mockResolvedValue(TEST_IDS.NEW_MESSAGE_ID);
+ .spyOn(messageService, 'createNewMessage')
+ .mockResolvedValue({ id: TEST_IDS.NEW_MESSAGE_ID, messages: [] });
const updateMessageSpy = vi
.spyOn(messageService, 'updateMessage')
.mockResolvedValue({ messages: [], success: true });
diff --git a/src/store/chat/slices/aiChat/actions/generateAIChat.ts b/src/store/chat/slices/aiChat/actions/generateAIChat.ts
index 6c55ea28720..d0e567530b5 100644
--- a/src/store/chat/slices/aiChat/actions/generateAIChat.ts
+++ b/src/store/chat/slices/aiChat/actions/generateAIChat.ts
@@ -220,9 +220,10 @@ export const generateAIChat: StateCreator<
ragQueryId,
};
- const assistantId = await get().internal_createMessage(assistantMessage);
+ const result = await get().internal_createMessage(assistantMessage);
- if (!assistantId) return;
+ if (!result) return;
+ const assistantId = result.id;
// 3. place a search with the search working model if this model is not support tool use
const aiInfraStoreState = getAiInfraStoreState();
diff --git a/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts b/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts
index 644c8ba6978..1942b87bfd0 100644
--- a/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts
+++ b/src/store/chat/slices/aiChat/actions/generateAIChatV2.ts
@@ -659,7 +659,7 @@ export const generateAIChatV2: StateCreator<
groupId: groupMessage.groupId, // Propagate groupId from parent message for group chat
};
- const result = await get().internal_createNewMessage(toolMessage);
+ const result = await get().internal_createMessage(toolMessage);
if (!result) {
log('[triggerToolsCalling] Failed to create tool message for %s', payload.identifier);
@@ -768,7 +768,7 @@ export const generateAIChatV2: StateCreator<
topicId: get().activeTopicId,
});
- const result = await get().internal_createNewMessage(assistantMessage, { groupMessageId });
+ const result = await get().internal_createMessage(assistantMessage, { groupMessageId });
if (!result) {
log('[callToolFollowAssistantMessage] Failed to create assistant message');
diff --git a/src/store/chat/slices/aiChat/actions/generateAIGroupChat.ts b/src/store/chat/slices/aiChat/actions/generateAIGroupChat.ts
index d70b3b4b77c..0fc1ea43eb0 100644
--- a/src/store/chat/slices/aiChat/actions/generateAIGroupChat.ts
+++ b/src/store/chat/slices/aiChat/actions/generateAIGroupChat.ts
@@ -294,7 +294,7 @@ export const chatAiGroupChat: StateCreator<
targetId: targetMemberId,
};
- const messageId = await internal_createMessage(userMessage);
+ const result = await internal_createMessage(userMessage);
// if only add user message, then stop
if (onlyAddUserMessage) {
@@ -302,6 +302,9 @@ export const chatAiGroupChat: StateCreator<
return;
}
+ if (!result) return;
+ const messageId = result.id;
+
if (messageId) {
// Use the specific group's config rather than relying on active session
const groupConfig = selectGroupConfig(groupId);
@@ -668,7 +671,9 @@ export const chatAiGroupChat: StateCreator<
console.log('DEBUG: Creating agent message with:', agentMessage);
- const assistantId = await internal_createMessage(agentMessage);
+ const result = await internal_createMessage(agentMessage);
+ if (!result) return;
+ const assistantId = result.id;
const systemMessage: UIChatMessage = {
id: 'group-system',
diff --git a/src/store/chat/slices/builtinTool/actions/search.ts b/src/store/chat/slices/builtinTool/actions/search.ts
index 94b41a85023..0aeffe457e3 100644
--- a/src/store/chat/slices/builtinTool/actions/search.ts
+++ b/src/store/chat/slices/builtinTool/actions/search.ts
@@ -106,16 +106,16 @@ export const searchSlice: StateCreator<
});
};
- const [newMessageId] = await Promise.all([
+ const [result] = await Promise.all([
// 1. 添加 tool message
internal_createMessage(toolMessage),
// 2. 将这条 tool call message 插入到 ai 消息的 tools 中
addToolItem(),
]);
- if (!newMessageId) return;
+ if (!result) return;
// 将新创建的 tool message 激活
- openToolUI(newMessageId, message.plugin.identifier);
+ openToolUI(result.id, message.plugin.identifier);
},
search: async (id, params, aiSummary = true) => {
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index 387ea66aa7d..a8935f1a83c 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -25,7 +25,7 @@ vi.mock('@/services/message', () => ({
removeMessage: vi.fn(),
removeMessagesByAssistant: vi.fn(),
removeMessages: vi.fn(() => Promise.resolve()),
- createMessage: vi.fn(() => Promise.resolve('new-message-id')),
+ createNewMessage: vi.fn(() => Promise.resolve({ id: 'new-message-id', messages: [] })),
updateMessage: vi.fn(),
removeAllMessages: vi.fn(() => Promise.resolve()),
},
@@ -71,7 +71,7 @@ describe('chatMessage actions', () => {
await result.current.addAIMessage();
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
expect(updateInputMessageSpy).not.toHaveBeenCalled();
});
@@ -84,7 +84,7 @@ describe('chatMessage actions', () => {
await result.current.addAIMessage();
});
- expect(messageService.createMessage).toHaveBeenCalledWith({
+ expect(messageService.createNewMessage).toHaveBeenCalledWith({
content: inputMessage,
role: 'assistant',
sessionId: mockState.activeId,
@@ -113,7 +113,7 @@ describe('chatMessage actions', () => {
await result.current.addUserMessage({ message: 'test message' });
});
- expect(messageService.createMessage).not.toHaveBeenCalled();
+ expect(messageService.createNewMessage).not.toHaveBeenCalled();
expect(updateInputMessageSpy).not.toHaveBeenCalled();
});
@@ -130,7 +130,7 @@ describe('chatMessage actions', () => {
await result.current.addUserMessage({ message, fileList });
});
- expect(messageService.createMessage).toHaveBeenCalledWith({
+ expect(messageService.createNewMessage).toHaveBeenCalledWith({
content: message,
files: fileList,
role: 'user',
@@ -154,7 +154,7 @@ describe('chatMessage actions', () => {
await result.current.addUserMessage({ message });
});
- expect(messageService.createMessage).toHaveBeenCalledWith({
+ expect(messageService.createNewMessage).toHaveBeenCalledWith({
content: message,
files: undefined,
role: 'user',
@@ -184,7 +184,7 @@ describe('chatMessage actions', () => {
await result.current.addUserMessage({ message });
});
- expect(messageService.createMessage).toHaveBeenCalledWith({
+ expect(messageService.createNewMessage).toHaveBeenCalledWith({
content: message,
files: undefined,
role: 'user',
@@ -200,6 +200,15 @@ describe('chatMessage actions', () => {
const { result } = renderHook(() => useChatStore());
const messageId = 'message-id';
const deleteSpy = vi.spyOn(result.current, 'deleteMessage');
+ const mockMessages = [{ id: 'other-message' }] as any;
+
+ // Mock the service to return messages
+ (messageService.removeMessages as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
act(() => {
useChatStore.setState({
@@ -215,13 +224,22 @@ describe('chatMessage actions', () => {
});
expect(deleteSpy).toHaveBeenCalledWith(messageId);
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
});
it('deleteMessage should remove messages with tools', async () => {
const { result } = renderHook(() => useChatStore());
const messageId = 'message-id';
const removeMessagesSpy = vi.spyOn(messageService, 'removeMessages');
+ const mockMessages = [{ id: 'remaining-message' }] as any;
+
+ // Mock the service to return messages
+ (messageService.removeMessages as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
act(() => {
useChatStore.setState({
@@ -240,8 +258,120 @@ describe('chatMessage actions', () => {
await result.current.deleteMessage(messageId);
});
- expect(removeMessagesSpy).toHaveBeenCalledWith([messageId, '2', '3']);
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(removeMessagesSpy).toHaveBeenCalledWith([messageId, '2', '3'], {
+ sessionId: 'session-id',
+ topicId: undefined,
+ });
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
+ });
+
+ it('deleteMessage should remove group message with all children', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const groupMessageId = 'group-message-id';
+ const removeMessagesSpy = vi.spyOn(messageService, 'removeMessages');
+ const mockMessages = [{ id: 'remaining-message' }] as any;
+
+ // Mock the service to return messages
+ (messageService.removeMessages as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
+
+ act(() => {
+ useChatStore.setState({
+ activeId: 'session-id',
+ activeTopicId: undefined,
+ messagesMap: {
+ [messageMapKey('session-id')]: [
+ { id: groupMessageId, role: 'group', content: 'Group message' } as UIChatMessage,
+ {
+ id: 'child-1',
+ parentId: groupMessageId,
+ role: 'assistant',
+ content: 'Child 1',
+ } as UIChatMessage,
+ {
+ id: 'child-2',
+ parentId: groupMessageId,
+ role: 'assistant',
+ content: 'Child 2',
+ } as UIChatMessage,
+ { id: 'other-message', role: 'user', content: 'Other' } as UIChatMessage,
+ ],
+ },
+ });
+ });
+ await act(async () => {
+ await result.current.deleteMessage(groupMessageId);
+ });
+
+ expect(removeMessagesSpy).toHaveBeenCalledWith([groupMessageId, 'child-1', 'child-2'], {
+ sessionId: 'session-id',
+ topicId: undefined,
+ });
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
+ });
+
+ it('deleteMessage should remove group message with children that have tool calls', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const groupMessageId = 'group-message-id';
+ const removeMessagesSpy = vi.spyOn(messageService, 'removeMessages');
+ const mockMessages = [{ id: 'remaining-message' }] as any;
+
+ // Mock the service to return messages
+ (messageService.removeMessages as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
+
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
+
+ act(() => {
+ useChatStore.setState({
+ activeId: 'session-id',
+ activeTopicId: undefined,
+ messagesMap: {
+ [messageMapKey('session-id')]: [
+ { id: groupMessageId, role: 'group', content: 'Group message' } as UIChatMessage,
+ {
+ id: 'child-1',
+ parentId: groupMessageId,
+ role: 'assistant',
+ content: 'Child with tools',
+ tools: [{ id: 'tool1' }],
+ } as UIChatMessage,
+ {
+ id: 'tool-result-1',
+ tool_call_id: 'tool1',
+ role: 'tool',
+ content: 'Tool result',
+ } as UIChatMessage,
+ {
+ id: 'child-2',
+ parentId: groupMessageId,
+ role: 'assistant',
+ content: 'Child 2',
+ } as UIChatMessage,
+ { id: 'other-message', role: 'user', content: 'Other' } as UIChatMessage,
+ ],
+ },
+ });
+ });
+ await act(async () => {
+ await result.current.deleteMessage(groupMessageId);
+ });
+
+ // Should delete group message + all children + tool results of children
+ expect(removeMessagesSpy).toHaveBeenCalledWith(
+ [groupMessageId, 'child-1', 'child-2', 'tool-result-1'],
+ {
+ sessionId: 'session-id',
+ topicId: undefined,
+ },
+ );
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
});
});
@@ -309,10 +439,16 @@ describe('chatMessage actions', () => {
});
expect(removeMessageSpy).toHaveBeenCalled();
- expect(updateMessageSpy).toHaveBeenCalledWith('message-id', {
- tools: [{ id: 'tool2' }],
- });
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(updateMessageSpy).toHaveBeenCalledWith(
+ 'message-id',
+ {
+ tools: [{ id: 'tool2' }],
+ },
+ {
+ sessionId: 'session-id',
+ topicId: undefined,
+ },
+ );
});
});
@@ -320,13 +456,14 @@ describe('chatMessage actions', () => {
it('clearAllMessages should remove all messages', async () => {
const { result } = renderHook(() => useChatStore());
const clearAllSpy = vi.spyOn(result.current, 'clearAllMessages');
+ const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
await act(async () => {
await result.current.clearAllMessages();
});
expect(clearAllSpy).toHaveBeenCalled();
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(replaceMessagesSpy).toHaveBeenCalledWith([]);
});
});
diff --git a/src/store/chat/slices/message/action.ts b/src/store/chat/slices/message/action.ts
index 6bc86037f63..30f94c37ae9 100644
--- a/src/store/chat/slices/message/action.ts
+++ b/src/store/chat/slices/message/action.ts
@@ -6,7 +6,6 @@ import {
ChatMessageError,
ChatMessagePluginError,
CreateMessageParams,
- CreateNewMessageParams,
GroundingSearch,
MessageMetadata,
MessageToolCall,
@@ -108,24 +107,17 @@ export interface ChatMessageAction {
) => Promise<void>;
/**
* create a message with optimistic update
+ * returns the created message ID and updated message list
*/
internal_createMessage: (
params: CreateMessageParams,
- context?: { tempMessageId?: string; skipRefresh?: boolean },
- ) => Promise<string | undefined>;
+ context?: { tempMessageId?: string; skipRefresh?: boolean; groupMessageId?: string },
+ ) => Promise<{ id: string; messages: UIChatMessage[] } | undefined>;
/**
* create a temp message for optimistic update
* otherwise the message will be too slow to show
*/
internal_createTmpMessage: (params: CreateMessageParams) => string;
- /**
- * create a new message using createNewMessage API and return full message list
- * used for group message scenarios to reduce network requests
- */
- internal_createNewMessage: (
- params: CreateNewMessageParams,
- context?: { tempMessageId?: string; groupMessageId?: string },
- ) => Promise<{ id: string; messages: UIChatMessage[] } | undefined>;
/**
* delete the message content with optimistic update
*/
@@ -172,22 +164,42 @@ export const chatMessage: StateCreator<
if (!message) return;
let ids = [message.id];
+ const allMessages = chatSelectors.activeBaseChats(get());
- // if the message is a tool calls, then delete all the related messages
+ // if the message is a tool calls, then delete all the related tool messages
if (message.tools) {
const toolMessageIds = message.tools.flatMap((tool) => {
- const messages = chatSelectors
- .activeBaseChats(get())
- .filter((m) => m.tool_call_id === tool.id);
-
+ const messages = allMessages.filter((m) => m.tool_call_id === tool.id);
return messages.map((m) => m.id);
});
ids = ids.concat(toolMessageIds);
}
+ // if the message is a group message, find all children messages (via parentId)
+ if (message.role === 'group') {
+ const childMessages = allMessages.filter((m) => m.parentId === message.id);
+ const childMessageIds = childMessages.map((m) => m.id);
+ ids = ids.concat(childMessageIds);
+
+ // Also delete tool results of children messages
+ const childToolMessageIds = childMessages.flatMap((child) => {
+ if (!child.tools) return [];
+ return child.tools.flatMap((tool) => {
+ const toolMessages = allMessages.filter((m) => m.tool_call_id === tool.id);
+ return toolMessages.map((m) => m.id);
+ });
+ });
+ ids = ids.concat(childToolMessageIds);
+ }
+
get().internal_dispatchMessage({ type: 'deleteMessages', ids });
- await messageService.removeMessages(ids);
- await get().refreshMessages();
+ const result = await messageService.removeMessages(ids, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
},
deleteToolMessage: async (id) => {
@@ -208,14 +220,7 @@ export const chatMessage: StateCreator<
},
clearMessage: async () => {
- const {
- activeId,
- activeTopicId,
- refreshMessages,
- refreshTopic,
- switchTopic,
- activeSessionType,
- } = get();
+ const { activeId, activeTopicId, refreshTopic, switchTopic, activeSessionType } = get();
// Check if this is a group session - use activeSessionType if available, otherwise check session store
let isGroupSession = activeSessionType === 'group';
@@ -239,22 +244,24 @@ export const chatMessage: StateCreator<
await topicService.removeTopic(activeTopicId);
}
await refreshTopic();
- await refreshMessages();
+
+ // Clear messages directly since all messages are deleted
+ get().replaceMessages([]);
// after remove topic , go back to default topic
switchTopic();
},
clearAllMessages: async () => {
- const { refreshMessages } = get();
await messageService.removeAllMessages();
- await refreshMessages();
+ // Clear messages directly since all messages are deleted
+ get().replaceMessages([]);
},
addAIMessage: async () => {
const { internal_createMessage, updateInputMessage, activeTopicId, activeId, inputMessage } =
get();
if (!activeId) return;
- await internal_createMessage({
+ const result = await internal_createMessage({
content: inputMessage,
role: 'assistant',
sessionId: activeId,
@@ -262,14 +269,16 @@ export const chatMessage: StateCreator<
topicId: activeTopicId,
});
- updateInputMessage('');
+ if (result) {
+ updateInputMessage('');
+ }
},
addUserMessage: async ({ message, fileList }) => {
const { internal_createMessage, updateInputMessage, activeTopicId, activeId, activeThreadId } =
get();
if (!activeId) return;
- await internal_createMessage({
+ const result = await internal_createMessage({
content: message,
files: fileList,
role: 'user',
@@ -279,7 +288,9 @@ export const chatMessage: StateCreator<
threadId: activeThreadId,
});
- updateInputMessage('');
+ if (result) {
+ updateInputMessage('');
+ }
},
copyMessage: async (id, content) => {
await copyToClipboard(content);
@@ -359,10 +370,13 @@ export const chatMessage: StateCreator<
},
internal_updateMessageRAG: async (id, data) => {
- const { refreshMessages } = get();
-
- await messageService.updateMessageRAG(id, data);
- await refreshMessages();
+ const result = await messageService.updateMessageRAG(id, data, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
},
// the internal process method of the AI message
@@ -396,8 +410,13 @@ export const chatMessage: StateCreator<
},
internal_updateMessagePluginError: async (id, error) => {
- await messageService.updateMessagePluginError(id, error);
- await get().refreshMessages();
+ const result = await messageService.updateMessagePluginError(id, error, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
},
internal_updateMessageContent: async (id, content, extra) => {
@@ -447,42 +466,6 @@ export const chatMessage: StateCreator<
}
},
- internal_createMessage: async (message, context) => {
- const {
- internal_createTmpMessage,
- refreshMessages,
- internal_toggleMessageLoading,
- internal_dispatchMessage,
- } = get();
- let tempId = context?.tempMessageId;
- if (!tempId) {
- // use optimistic update to avoid the slow waiting
- tempId = internal_createTmpMessage(message);
-
- internal_toggleMessageLoading(true, tempId);
- }
-
- try {
- const id = await messageService.createMessage(message);
- if (!context?.skipRefresh) {
- internal_toggleMessageLoading(true, tempId);
- await refreshMessages();
- }
-
- internal_toggleMessageLoading(false, tempId);
- return id;
- } catch (e) {
- internal_toggleMessageLoading(false, tempId);
- internal_dispatchMessage({
- id: tempId,
- type: 'updateMessage',
- value: {
- error: { type: ChatErrorType.CreateMessageError, message: (e as Error).message, body: e },
- },
- });
- }
- },
-
internal_fetchMessages: async () => {
const messages = await messageService.getMessages(get().activeId, get().activeTopicId);
const nextMap = { ...get().messagesMap, [chatSelectors.currentChatKey(get())]: messages };
@@ -504,8 +487,7 @@ export const chatMessage: StateCreator<
return tempId;
},
-
- internal_createNewMessage: async (message, context) => {
+ internal_createMessage: async (message, context) => {
const {
internal_createTmpMessage,
internal_toggleMessageLoading,
@@ -537,11 +519,12 @@ export const chatMessage: StateCreator<
}
try {
- // 使用 createNewMessage API
const result = await messageService.createNewMessage(message);
- // 直接用返回的 messages 更新 store(已包含 group 结构)
- replaceMessages(result.messages);
+ if (!context?.skipRefresh) {
+ // Use the messages returned from createNewMessage (already grouped)
+ replaceMessages(result.messages);
+ }
internal_toggleMessageLoading(false, tempId);
return result;
@@ -563,8 +546,13 @@ export const chatMessage: StateCreator<
internal_deleteMessage: async (id: string) => {
get().internal_dispatchMessage({ type: 'deleteMessage', id });
- await messageService.removeMessage(id);
- await get().refreshMessages();
+ const result = await messageService.removeMessage(id, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
},
internal_traceMessage: async (id, payload) => {
// tracing the diff of update
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index 221086e01c8..e95c476f2f2 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -26,7 +26,7 @@ vi.mock('@/services/message', () => ({
updateMessageError: vi.fn(),
updateMessagePluginState: vi.fn(),
updateMessagePluginArguments: vi.fn(),
- createMessage: vi.fn(),
+ createNewMessage: vi.fn(),
},
}));
@@ -271,9 +271,16 @@ describe('ChatPluginAction', () => {
const pluginPayload = { apiName: 'testApi', arguments: { key: 'value' } };
const messageId = 'message-id';
const error = new Error('API call failed');
+ const mockMessages = [{ id: 'msg-1', content: 'test' }] as any;
+
+ // Mock the service to return messages
+ (messageService.updateMessageError as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
const storeState = useChatStore.getState();
- vi.spyOn(storeState, 'refreshMessages');
+ const replaceMessagesSpy = vi.spyOn(storeState, 'replaceMessages');
vi.spyOn(storeState, 'triggerAIMessage').mockResolvedValue(undefined);
vi.spyOn(storeState, 'internal_togglePluginApiCalling').mockReturnValue(undefined);
@@ -291,7 +298,7 @@ describe('ChatPluginAction', () => {
);
expect(chatService.runPluginApi).toHaveBeenCalledWith(pluginPayload, { trace: {} });
expect(messageService.updateMessageError).toHaveBeenCalledWith(messageId, error);
- expect(storeState.refreshMessages).toHaveBeenCalled();
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
expect(storeState.internal_togglePluginApiCalling).toHaveBeenCalledWith(
false,
'message-id',
@@ -345,7 +352,9 @@ describe('ChatPluginAction', () => {
const invokeBuiltinToolMock = vi.fn();
const invokeDefaultTypePluginMock = vi.fn().mockResolvedValue('Default tool response');
const triggerAIMessageMock = vi.fn();
- const internal_createMessageMock = vi.fn().mockResolvedValue('tool-message-id');
+ const internal_createMessageMock = vi
+ .fn()
+ .mockResolvedValue({ id: 'tool-message-id', messages: [] });
const getTraceIdByMessageIdMock = vi.fn().mockReturnValue('trace-id');
act(() => {
@@ -472,7 +481,9 @@ describe('ChatPluginAction', () => {
const invokeMarkdownTypePluginMock = vi.fn();
const invokeBuiltinToolMock = vi.fn();
const triggerAIMessageMock = vi.fn();
- const internal_createMessageMock = vi.fn().mockResolvedValue('tool-message-id');
+ const internal_createMessageMock = vi
+ .fn()
+ .mockResolvedValue({ id: 'tool-message-id', messages: [] });
act(() => {
useChatStore.setState({
@@ -518,9 +529,17 @@ describe('ChatPluginAction', () => {
it('should update the plugin state for a message', async () => {
const messageId = 'message-id';
const pluginStateValue = { key: 'value' };
+ const mockMessages = [{ id: 'msg-1', content: 'test' }] as any;
+ // Mock the service to return messages
+ (messageService.updateMessagePluginState as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
+
+ const replaceMessagesSpy = vi.fn();
const initialState = {
- refreshMessages: vi.fn(),
+ replaceMessages: replaceMessagesSpy,
};
useChatStore.setState(initialState);
@@ -533,19 +552,28 @@ describe('ChatPluginAction', () => {
expect(messageService.updateMessagePluginState).toHaveBeenCalledWith(
messageId,
pluginStateValue,
+ {
+ sessionId: 'inbox',
+ topicId: null,
+ },
);
- expect(initialState.refreshMessages).toHaveBeenCalled();
+
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
});
});
describe('createAssistantMessageByPlugin', () => {
- it('should create an assistant message and refresh messages', async () => {
- // 模拟 messageService.create 方法的实现
- (messageService.createMessage as Mock).mockResolvedValue({});
+ it('should create an assistant message and replace messages', async () => {
+ const mockMessages = [{ id: 'msg-1', content: 'test' }] as any;
+ // 模拟 messageService.createNewMessage 方法的实现
+ (messageService.createNewMessage as Mock).mockResolvedValue({
+ id: 'new-message-id',
+ messages: mockMessages,
+ });
- // 设置初始状态并模拟 refreshMessages 方法
+ // 设置初始状态并模拟 replaceMessages 方法
const initialState = {
- refreshMessages: vi.fn(),
+ replaceMessages: vi.fn(),
activeId: 'session-id',
activeTopicId: 'topic-id',
};
@@ -560,8 +588,8 @@ describe('ChatPluginAction', () => {
await result.current.createAssistantMessageByPlugin(content, parentId);
});
- // 验证 messageService.create 是否被带有正确参数调用
- expect(messageService.createMessage).toHaveBeenCalledWith({
+ // 验证 messageService.createNewMessage 是否被带有正确参数调用
+ expect(messageService.createNewMessage).toHaveBeenCalledWith({
content,
parentId,
role: 'assistant',
@@ -569,14 +597,14 @@ describe('ChatPluginAction', () => {
topicId: initialState.activeTopicId,
});
- // 验证 refreshMessages 是否被调用
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ // 验证 replaceMessages 是否被调用
+ expect(result.current.replaceMessages).toHaveBeenCalledWith(mockMessages);
});
it('should handle errors when message creation fails', async () => {
// 模拟 messageService.create 方法,使其抛出错误
const errorMessage = 'Failed to create message';
- (messageService.createMessage as Mock).mockRejectedValue(new Error(errorMessage));
+ (messageService.createNewMessage as Mock).mockRejectedValue(new Error(errorMessage));
// 设置初始状态并模拟 refreshMessages 方法
const initialState = {
@@ -598,7 +626,7 @@ describe('ChatPluginAction', () => {
});
// 验证 messageService.create 是否被带有正确参数调用
- expect(messageService.createMessage).toHaveBeenCalledWith({
+ expect(messageService.createNewMessage).toHaveBeenCalledWith({
content,
parentId,
role: 'assistant',
@@ -706,11 +734,20 @@ describe('ChatPluginAction', () => {
describe('invokeStandaloneTypePlugin', () => {
it('should update message with error and refresh messages if plugin settings are invalid', async () => {
const messageId = 'message-id';
+ const mockMessages = [{ id: 'msg-1', content: 'test' }] as any;
const payload = {
identifier: 'pluginName',
} as ChatToolPayload;
+ // Mock the service to return messages
+ (messageService.updateMessageError as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
+
+ const replaceMessagesSpy = vi.fn();
+
act(() => {
useToolStore.setState({
validatePluginSettings: vi
@@ -718,7 +755,7 @@ describe('ChatPluginAction', () => {
.mockResolvedValue({ valid: false, errors: ['Invalid setting'] }),
});
- useChatStore.setState({ refreshMessages: vi.fn(), invokeStandaloneTypePlugin });
+ useChatStore.setState({ replaceMessages: replaceMessagesSpy, invokeStandaloneTypePlugin });
});
const { result } = renderHook(() => useChatStore());
@@ -738,7 +775,7 @@ describe('ChatPluginAction', () => {
type: 'PluginSettingsInvalid',
});
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
});
});
@@ -917,13 +954,22 @@ describe('ChatPluginAction', () => {
arguments: '{}',
};
const error = new Error('API call failed');
+ const mockMessages = [{ id: 'msg-1', content: 'test' }] as any;
+
+ // Mock the service to return messages
+ (messageService.updateMessageError as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
vi.spyOn(chatService, 'runPluginApi').mockRejectedValue(error);
+ const replaceMessagesSpy = vi.fn();
+
act(() => {
useChatStore.setState({
internal_togglePluginApiCalling: vi.fn(),
- refreshMessages: vi.fn(),
+ replaceMessages: replaceMessagesSpy,
});
});
@@ -934,7 +980,7 @@ describe('ChatPluginAction', () => {
});
expect(messageService.updateMessageError).toHaveBeenCalledWith(messageId, error);
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
});
});
@@ -1040,10 +1086,19 @@ describe('ChatPluginAction', () => {
it('should update plugin error and refresh messages', async () => {
const messageId = 'message-id';
const error = { message: 'Plugin error' } as any;
+ const mockMessages = [{ id: 'msg-1', content: 'test' }] as any;
+
+ // Mock the service to return messages
+ (messageService.updateMessage as Mock).mockResolvedValue({
+ success: true,
+ messages: mockMessages,
+ });
+
+ const replaceMessagesSpy = vi.fn();
act(() => {
useChatStore.setState({
- refreshMessages: vi.fn(),
+ replaceMessages: replaceMessagesSpy,
});
});
@@ -1053,8 +1108,12 @@ describe('ChatPluginAction', () => {
await result.current.internal_updatePluginError(messageId, error);
});
- expect(messageService.updateMessage).toHaveBeenCalledWith(messageId, { error });
- expect(result.current.refreshMessages).toHaveBeenCalled();
+ expect(messageService.updateMessage).toHaveBeenCalledWith(
+ messageId,
+ { error },
+ { sessionId: 'inbox', topicId: null },
+ );
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages);
});
});
diff --git a/src/store/chat/slices/plugin/action.ts b/src/store/chat/slices/plugin/action.ts
index b744fcc5a89..aa9b04b82bb 100644
--- a/src/store/chat/slices/plugin/action.ts
+++ b/src/store/chat/slices/plugin/action.ts
@@ -98,8 +98,8 @@ export const chatPlugin: StateCreator<
topicId: get().activeTopicId, // if there is activeTopicId,then add it to topicId
};
- await messageService.createMessage(newMessage);
- await get().refreshMessages();
+ const result = await messageService.createNewMessage(newMessage);
+ get().replaceMessages(result.messages);
},
fillPluginMessageContent: async (id, content, triggerAiMessage) => {
@@ -144,7 +144,7 @@ export const chatPlugin: StateCreator<
// if the plugin settings is not valid, then set the message with error type
if (!result.valid) {
- await messageService.updateMessageError(id, {
+ const updateResult = await messageService.updateMessageError(id, {
body: {
error: result.errors,
message: '[plugin] your settings is invalid with plugin manifest setting schema',
@@ -153,7 +153,9 @@ export const chatPlugin: StateCreator<
type: PluginErrorType.PluginSettingsInvalid as any,
});
- await get().refreshMessages();
+ if (updateResult?.success && updateResult.messages) {
+ get().replaceMessages(updateResult.messages);
+ }
return;
}
},
@@ -228,15 +230,15 @@ export const chatPlugin: StateCreator<
groupId: message.groupId, // Propagate groupId from parent message for group chat
};
- const id = await get().internal_createMessage(toolMessage);
- if (!id) return;
+ const result = await get().internal_createMessage(toolMessage);
+ if (!result) return;
// trigger the plugin call
- const data = await get().internal_invokeDifferentTypePlugin(id, payload);
+ const data = await get().internal_invokeDifferentTypePlugin(result.id, payload);
if (data && !['markdown', 'standalone'].includes(payload.type)) {
shouldCreateMessage = true;
- latestToolId = id;
+ latestToolId = result.id;
}
});
@@ -252,13 +254,19 @@ export const chatPlugin: StateCreator<
await get().triggerAIMessage({ traceId, threadId, inPortalThread, inSearchWorkflow });
},
updatePluginState: async (id, value) => {
- const { refreshMessages } = get();
+ const { replaceMessages } = get();
// optimistic update
get().internal_dispatchMessage({ id, type: 'updateMessage', value: { pluginState: value } });
- await messageService.updateMessagePluginState(id, value);
- await refreshMessages();
+ const result = await messageService.updateMessagePluginState(id, value, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
},
updatePluginArguments: async (id, value, replace = false) => {
@@ -336,18 +344,26 @@ export const chatPlugin: StateCreator<
const message = chatSelectors.getMessageById(id)(get());
if (!message || !message.tools) return;
- const { internal_toggleMessageLoading, refreshMessages } = get();
+ const { internal_toggleMessageLoading, replaceMessages } = get();
internal_toggleMessageLoading(true, id);
- await messageService.updateMessage(id, { tools: message.tools });
+ const result = await messageService.updateMessage(
+ id,
+ { tools: message.tools },
+ {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ },
+ );
internal_toggleMessageLoading(false, id);
- await refreshMessages();
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
},
internal_callPluginApi: async (id, payload) => {
- const { internal_updateMessageContent, refreshMessages, internal_togglePluginApiCalling } =
- get();
+ const { internal_updateMessageContent, internal_togglePluginApiCalling } = get();
let data: string;
try {
@@ -375,8 +391,10 @@ export const chatPlugin: StateCreator<
// ignore the aborted request error
if (!err.message.includes('The user aborted a request.')) {
- await messageService.updateMessageError(id, error as any);
- await refreshMessages();
+ const result = await messageService.updateMessageError(id, error as any);
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
}
data = '';
@@ -418,7 +436,6 @@ export const chatPlugin: StateCreator<
invokeMCPTypePlugin: async (id, payload) => {
const {
internal_updateMessageContent,
- refreshMessages,
internal_togglePluginApiCalling,
internal_constructToolsCallingContext,
} = get();
@@ -444,8 +461,10 @@ export const chatPlugin: StateCreator<
// ignore the aborted request error
if (!err.message.includes('The user aborted a request.')) {
- await messageService.updateMessageError(id, error as any);
- await refreshMessages();
+ const result = await messageService.updateMessageError(id, error as any);
+ if (result?.success && result.messages) {
+ get().replaceMessages(result.messages);
+ }
}
}
@@ -487,11 +506,20 @@ export const chatPlugin: StateCreator<
return toolNameResolver.resolve(toolCalls, manifests);
},
internal_updatePluginError: async (id, error) => {
- const { refreshMessages } = get();
+ const { replaceMessages } = get();
get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } });
- await messageService.updateMessage(id, { error });
- await refreshMessages();
+ const result = await messageService.updateMessage(
+ id,
+ { error },
+ {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ },
+ );
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
},
internal_constructToolsCallingContext: (id: string) => {
diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.ts
index 5e100d487c0..7b85299cdf4 100644
--- a/src/store/chat/slices/thread/action.test.ts
+++ b/src/store/chat/slices/thread/action.test.ts
@@ -764,7 +764,7 @@ describe('thread action', () => {
const createMessageSpy = vi
.spyOn(result.current, 'internal_createMessage')
- .mockResolvedValue('new-msg-id');
+ .mockResolvedValue({ id: 'new-msg-id', messages: [] });
const coreProcessSpy = vi
.spyOn(result.current, 'internal_coreProcessMessage')
.mockResolvedValue();
@@ -803,7 +803,10 @@ describe('thread action', () => {
});
});
- vi.spyOn(result.current, 'internal_createMessage').mockResolvedValue('new-msg-id');
+ vi.spyOn(result.current, 'internal_createMessage').mockResolvedValue({
+ id: 'new-msg-id',
+ messages: [],
+ });
vi.spyOn(result.current, 'internal_coreProcessMessage').mockResolvedValue();
vi.spyOn(result.current, 'internal_createTmpMessage').mockReturnValue('temp-msg-id');
vi.spyOn(result.current, 'internal_toggleMessageLoading');
@@ -833,7 +836,10 @@ describe('thread action', () => {
});
});
- vi.spyOn(result.current, 'internal_createMessage').mockResolvedValue('new-msg-id');
+ vi.spyOn(result.current, 'internal_createMessage').mockResolvedValue({
+ id: 'new-msg-id',
+ messages: [],
+ });
vi.spyOn(result.current, 'internal_coreProcessMessage').mockResolvedValue();
vi.spyOn(result.current, 'internal_createTmpMessage').mockReturnValue('temp-msg-id');
vi.spyOn(result.current, 'internal_toggleMessageLoading');
@@ -855,7 +861,10 @@ describe('thread action', () => {
});
vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);
- vi.spyOn(result.current, 'internal_createMessage').mockResolvedValue('new-msg-id');
+ vi.spyOn(result.current, 'internal_createMessage').mockResolvedValue({
+ id: 'new-msg-id',
+ messages: [],
+ });
vi.spyOn(result.current, 'internal_createTmpMessage').mockReturnValue('temp-msg-id');
vi.spyOn(result.current, 'internal_toggleMessageLoading');
diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.ts
index 6d17ef0ff81..3b47d39c8b4 100644
--- a/src/store/chat/slices/thread/action.ts
+++ b/src/store/chat/slices/thread/action.ts
@@ -158,7 +158,9 @@ export const chatThreadMessage: StateCreator<
tempMessageId = get().internal_createTmpMessage(newMessage);
get().internal_toggleMessageLoading(true, tempMessageId);
- parentMessageId = await get().internal_createMessage(newMessage, { tempMessageId });
+ const result = await get().internal_createMessage(newMessage, { tempMessageId });
+ if (!result) return;
+ parentMessageId = result.id;
}
get().internal_toggleMessageLoading(false, tempMessageId);