From e5aaec2129913ff7d7a4d67b6208c780ef1f1a79 Mon Sep 17 00:00:00 2001 From: one Date: Sat, 29 Mar 2025 22:31:31 +0800 Subject: [PATCH] fix: race condition in topic auto renaming --- src/renderer/src/hooks/useTopic.ts | 56 ++++++++++++++++++------------ 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/src/renderer/src/hooks/useTopic.ts b/src/renderer/src/hooks/useTopic.ts index 609da18b..cf5c1e73 100644 --- a/src/renderer/src/hooks/useTopic.ts +++ b/src/renderer/src/hooks/useTopic.ts @@ -11,6 +11,8 @@ import { useEffect, useState } from 'react' import { useAssistant } from './useAssistant' import { getStoreSetting } from './useSettings' +const renamingTopics = new Set() + let _activeTopic: Topic let _setActiveTopic: (topic: Topic) => void @@ -54,35 +56,45 @@ export async function getTopicById(topicId: string) { } export const autoRenameTopic = async (assistant: Assistant, topicId: string) => { - const topic = await getTopicById(topicId) - const enableTopicNaming = getStoreSetting('enableTopicNaming') - - if (isEmpty(topic.messages)) { + if (renamingTopics.has(topicId)) { return } - if (topic.isNameManuallyEdited) { - return - } + try { + renamingTopics.add(topicId) - if (!enableTopicNaming) { - const topicName = topic.messages[0]?.content.substring(0, 50) - if (topicName) { - const data = { ...topic, name: topicName } as Topic - _setActiveTopic(data) - store.dispatch(updateTopic({ assistantId: assistant.id, topic: data })) + const topic = await getTopicById(topicId) + const enableTopicNaming = getStoreSetting('enableTopicNaming') + + if (isEmpty(topic.messages)) { + return } - return - } - if (topic && topic.name === i18n.t('chat.default.topic.name') && topic.messages.length >= 2) { - const { fetchMessagesSummary } = await import('@renderer/services/ApiService') - const summaryText = await fetchMessagesSummary({ messages: topic.messages, assistant }) - if (summaryText) { - const data = { ...topic, name: summaryText } - _setActiveTopic(data) - store.dispatch(updateTopic({ assistantId: assistant.id, topic: data })) + if (topic.isNameManuallyEdited) { + return } + + if (!enableTopicNaming) { + const topicName = topic.messages[0]?.content.substring(0, 50) + if (topicName) { + const data = { ...topic, name: topicName } as Topic + _setActiveTopic(data) + store.dispatch(updateTopic({ assistantId: assistant.id, topic: data })) + } + return + } + + if (topic && topic.name === i18n.t('chat.default.topic.name') && topic.messages.length >= 2) { + const { fetchMessagesSummary } = await import('@renderer/services/ApiService') + const summaryText = await fetchMessagesSummary({ messages: topic.messages, assistant }) + if (summaryText) { + const data = { ...topic, name: summaryText } + _setActiveTopic(data) + store.dispatch(updateTopic({ assistantId: assistant.id, topic: data })) + } + } + } finally { + renamingTopics.delete(topicId) } }