fix: race condition in topic auto renaming

This commit is contained in:
one 2025-03-29 22:31:31 +08:00 committed by 亢奋猫
parent 464634d051
commit e5aaec2129

View File

@ -11,6 +11,8 @@ import { useEffect, useState } from 'react'
import { useAssistant } from './useAssistant' import { useAssistant } from './useAssistant'
import { getStoreSetting } from './useSettings' import { getStoreSetting } from './useSettings'
const renamingTopics = new Set<string>()
let _activeTopic: Topic let _activeTopic: Topic
let _setActiveTopic: (topic: Topic) => void let _setActiveTopic: (topic: Topic) => void
@ -54,35 +56,45 @@ export async function getTopicById(topicId: string) {
} }
export const autoRenameTopic = async (assistant: Assistant, topicId: string) => { export const autoRenameTopic = async (assistant: Assistant, topicId: string) => {
const topic = await getTopicById(topicId) if (renamingTopics.has(topicId)) {
const enableTopicNaming = getStoreSetting('enableTopicNaming')
if (isEmpty(topic.messages)) {
return return
} }
if (topic.isNameManuallyEdited) { try {
return renamingTopics.add(topicId)
}
if (!enableTopicNaming) { const topic = await getTopicById(topicId)
const topicName = topic.messages[0]?.content.substring(0, 50) const enableTopicNaming = getStoreSetting('enableTopicNaming')
if (topicName) {
const data = { ...topic, name: topicName } as Topic if (isEmpty(topic.messages)) {
_setActiveTopic(data) return
store.dispatch(updateTopic({ assistantId: assistant.id, topic: data }))
} }
return
}
if (topic && topic.name === i18n.t('chat.default.topic.name') && topic.messages.length >= 2) { if (topic.isNameManuallyEdited) {
const { fetchMessagesSummary } = await import('@renderer/services/ApiService') return
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 (!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)
} }
} }