From cf9bfce43c867b7fc2281a7fc37416f0e04d3518 Mon Sep 17 00:00:00 2001 From: icarus Date: Thu, 16 Oct 2025 23:18:32 +0800 Subject: [PATCH] refactor(action): simplify assistant and topic initialization Move assistant and topic initialization to useState hooks and sync with refs Remove redundant initialization code from useEffect fix: Error: Cannot access refs during render fix: Error: Calling setState synchronously within an effect can trigger cascading renders --- .../action/components/ActionGeneral.tsx | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/src/renderer/src/windows/selection/action/components/ActionGeneral.tsx b/src/renderer/src/windows/selection/action/components/ActionGeneral.tsx index 6046da9ae1..ebfa70da0e 100644 --- a/src/renderer/src/windows/selection/action/components/ActionGeneral.tsx +++ b/src/renderer/src/windows/selection/action/components/ActionGeneral.tsx @@ -36,32 +36,38 @@ const ActionGeneral: FC = React.memo(({ action, scrollToBottom }) => { const [isContented, setIsContented] = useState(false) const [isLoading, setIsLoading] = useState(true) const [contentToCopy, setContentToCopy] = useState('') + const [assistant] = useState(() => { + const assistant = action.assistantId + ? getAssistantById(action.assistantId) || getDefaultAssistant() + : getDefaultAssistant() + if (!assistant.model) { + return { ...assistant, model: getDefaultModel() } + } else { + return assistant + } + }) + const [topic] = useState(getDefaultTopic(assistant.id)) const initialized = useRef(false) // Use useRef for values that shouldn't trigger re-renders const assistantRef = useRef(null) - const topicRef = useRef(null) + const topicRef = useRef(topic) const promptContentRef = useRef('') const askId = useRef('') + // Sync refs + useEffect(() => { + assistantRef.current = assistant + }, [assistant]) + useEffect(() => { + topicRef.current = topic + }, [assistant, topic]) + // Initialize values only once when action changes useEffect(() => { if (initialized.current) return initialized.current = true - // Initialize assistant - const currentAssistant = action.assistantId - ? getAssistantById(action.assistantId) || getDefaultAssistant() - : getDefaultAssistant() - - assistantRef.current = { - ...currentAssistant, - model: currentAssistant.model || getDefaultModel() - } - - // Initialize topic - topicRef.current = getDefaultTopic(currentAssistant.id) - // Initialize prompt content let userContent = '' switch (action.id) { @@ -128,7 +134,7 @@ const ActionGeneral: FC = React.memo(({ action, scrollToBottom }) => { fetchResult() }, [fetchResult]) - const allMessages = useTopicMessages(topicRef.current?.id || '') + const allMessages = useTopicMessages(topic?.id || '') // Memoize the messages to prevent unnecessary re-renders const messageContent = useMemo(() => {