Commit e25e6f38 by liimin

refactor(chat): 优化聊天组件初始化逻辑和性能

- 修改了 ChatWrapper 组件中的 useEffect,增加了对 config.initial_message 的判断
- 移除了 ChatConfigProvider 中的 opening_statement 属性
- 调整了 useChat hook 中的逻辑,使用 initial_message 替代 opening_statement
- 优化了 Chat 组件的结构,移除了不必要的类名和属性
- 改进了 InitQuestions 组件的性能,使用 useMemo 避免不必要的渲染
1 parent 9de4be95
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @Author: limin * @Author: limin
* @Date: 2025-04-16 18:17:38 * @Date: 2025-04-16 18:17:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-17 16:34:07 * @LastEditTime: 2025-07-21 20:46:08
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx
*/ */
...@@ -55,10 +55,10 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => { ...@@ -55,10 +55,10 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
} = useChat(undefined, inputs) } = useChat(undefined, inputs)
useEffect(() => { useEffect(() => {
if (presuppositionQuestion) { if (presuppositionQuestion && config.initial_message !== undefined) {
sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO) setTimeout(() => sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO), 0)
} }
}, [presuppositionQuestion]) }, [presuppositionQuestion, config.initial_message])
useEffect(() => { useEffect(() => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, { Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
...@@ -85,7 +85,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => { ...@@ -85,7 +85,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs }) => {
} }
} }
}, []) }, [])
if (config.initial_message === undefined) return null
return ( return (
<div className="h-full overflow-hidden"> <div className="h-full overflow-hidden">
<ChatConfigProvider config={config}> <ChatConfigProvider config={config}>
......
...@@ -21,7 +21,6 @@ export const ChatConfigProvider = ({ children, config }: Props) => { ...@@ -21,7 +21,6 @@ export const ChatConfigProvider = ({ children, config }: Props) => {
suggested_questions: config.suggested_questions, suggested_questions: config.suggested_questions,
file_upload: config.file_upload, file_upload: config.file_upload,
supportFeedback: config.supportFeedback, supportFeedback: config.supportFeedback,
opening_statement: config.opening_statement,
supportAnnotation: config.supportAnnotation, supportAnnotation: config.supportAnnotation,
supportCitationHitInfo: config.supportCitationHitInfo, supportCitationHitInfo: config.supportCitationHitInfo,
speech_to_text: config.speech_to_text, speech_to_text: config.speech_to_text,
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @Author: limin * @Author: limin
* @Date: 2025-07-10 15:04:55 * @Date: 2025-07-10 15:04:55
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-17 18:14:48 * @LastEditTime: 2025-07-21 23:56:43
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\hooks\useChat.ts * @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\hooks\useChat.ts
*/ */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
...@@ -61,7 +61,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -61,7 +61,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([]) const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
const conversationMessagesAbortControllerRef = useRef<AbortController | null>(null) const conversationMessagesAbortControllerRef = useRef<AbortController | null>(null)
const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null) const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null)
const chatListRef = useRef<ChatItemInTree[]>([])
const [chatTree, setChatTree] = useState<ChatItemInTree[]>([]) const [chatTree, setChatTree] = useState<ChatItemInTree[]>([])
const chatTreeRef = useRef<ChatItemInTree[]>(chatTree) const chatTreeRef = useRef<ChatItemInTree[]>(chatTree)
const [targetMessageId, setTargetMessageId] = useState<string>() const [targetMessageId, setTargetMessageId] = useState<string>()
...@@ -73,7 +73,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -73,7 +73,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
isLoading: appInfoLoading, isLoading: appInfoLoading,
error: appInfoError, error: appInfoError,
} = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo, { revalidateOnFocus: false }) } = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo, { revalidateOnFocus: false })
const appId = useMemo(() => appInfo?.app_id, [appInfo]) const appId = appInfo?.app_id
const swrKey = useMemo(() => { const swrKey = useMemo(() => {
if (!appId) { if (!appId) {
return null return null
...@@ -95,7 +95,6 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -95,7 +95,6 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
fileUploadConfig: (cfg as any).system_parameters, fileUploadConfig: (cfg as any).system_parameters,
}, },
supportFeedback: true, supportFeedback: true,
opening_statement: (cfg as any).opening_statement,
initial_message: (cfg as any).opening_statement, initial_message: (cfg as any).opening_statement,
} as ChatConfig } as ChatConfig
}, [appParams]) }, [appParams])
...@@ -133,10 +132,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -133,10 +132,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
}, []) }, [])
/** Final chat list that will be rendered */ /** Final chat list that will be rendered */
const chatList = useMemo(() => { const chatList = useMemo(() => [...threadMessages], [threadMessages])
return [...threadMessages]
}, [threadMessages])
const chatListRef = useRef<ChatItemInTree[]>(chatList)
useEffect(() => { useEffect(() => {
chatListRef.current = chatList chatListRef.current = chatList
}, [chatList]) }, [chatList])
...@@ -197,7 +193,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -197,7 +193,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
const handleRestart = useCallback( const handleRestart = useCallback(
(cb?: any) => { (cb?: any) => {
conversationId.current = '' // conversationId.current = ''
taskIdRef.current = '' taskIdRef.current = ''
chatListRef.current = [] chatListRef.current = []
handleStop() handleStop()
......
...@@ -4,11 +4,11 @@ ...@@ -4,11 +4,11 @@
* @Author: limin * @Author: limin
* @Date: 2025-04-16 18:17:38 * @Date: 2025-04-16 18:17:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-17 19:45:58 * @LastEditTime: 2025-07-21 16:25:39
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\index.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\index.tsx
*/ */
import type { FC } from 'react' import type { FC } from 'react'
import { useEffect, useState } from 'react' import { memo, useEffect, useState } from 'react'
import ChatWrapper from './chat-wrapper' import ChatWrapper from './chat-wrapper'
import Loading from '@/app/components/base/loading' import Loading from '@/app/components/base/loading'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
...@@ -66,4 +66,4 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta ...@@ -66,4 +66,4 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
) )
} }
export default ChatWithHistoryWrapWithCheckToken export default memo(ChatWithHistoryWrapWithCheckToken)
import { FC, memo } from 'react' import { FC, memo } from 'react'
import { FileListInChatInput } from '@/app/components/base/file-uploader' import { FileListInChatInput } from '@/app/components/base/file-uploader'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context' import { useChatConfigContext } from '@/app/components/base/chat/chat-with-history/context/chat-config-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const FileList: FC = () => { const FileList: FC = () => {
const { file_upload } = useChatConfigContext () const { file_upload } = useChatConfigContext ()
return <FileListInChatInput fileConfig={file_upload} /> return <FileListInChatInput fileConfig={file_upload} />
......
...@@ -3,7 +3,7 @@ import { useToastContext } from '@/app/components/base/toast' ...@@ -3,7 +3,7 @@ import { useToastContext } from '@/app/components/base/toast'
import { FC, memo, useCallback, useState } from 'react' import { FC, memo, useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { CLEAR_BUTTON } from '@/app/components/base/chat/constants' import { CLEAR_BUTTON } from '@/app/components/base/chat/constants'
import { useChatRespondingContext,useChatContext } from '@/app/components/base/chat/chat-with-history/context' import { useChatRespondingContext, useChatContext } from '@/app/components/base/chat/chat-with-history/context'
const ReStart: FC = () => { const ReStart: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { notify } = useToastContext() const { notify } = useToastContext()
......
...@@ -5,8 +5,8 @@ import { useTranslation } from 'react-i18next' ...@@ -5,8 +5,8 @@ import { useTranslation } from 'react-i18next'
import { useChatRespondingContext,useChatContext } from '@/app/components/base/chat/chat-with-history/context' import { useChatRespondingContext,useChatContext } from '@/app/components/base/chat/chat-with-history/context'
const StopRespondingButton: FC = () => { const StopRespondingButton: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { onStopResponding: stopResponding } = useChatContext()
const { isResponding } = useChatRespondingContext() const { isResponding } = useChatRespondingContext()
const { onStopResponding: stopResponding } = useChatContext()
if (!isResponding) return null if (!isResponding) return null
return ( return (
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2"> <div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
......
import React, { FC, memo, useMemo} from 'react' import React, { FC, memo, useMemo } from 'react'
import TryToAsk from './components/try-to-ask' import TryToAsk from './components/try-to-ask'
import ChatInput from './components/input' import ChatInput from './components/input'
import StopResponding from './components/stopResponding' import StopResponding from './components/stopResponding'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
type FooterProps = { type FooterProps = {
chatFooterClassName?: string
chatFooterInnerClassName?: string
// isShowPracticeButton: boolean
suggestedQuestions?: string[]
isMobile?: boolean isMobile?: boolean
chatFooterRef: React.RefObject<HTMLDivElement> chatFooterRef: React.RefObject<HTMLDivElement>
chatFooterInnerRef: React.RefObject<HTMLDivElement> chatFooterInnerRef: React.RefObject<HTMLDivElement>
} }
const Footer: FC<FooterProps> = ({ const Footer: FC<FooterProps> = ({ isMobile, chatFooterRef, chatFooterInnerRef }) => {
chatFooterClassName,
chatFooterInnerClassName,
// isMobile,
// suggestedQuestions,
// isShowPracticeButton,
chatFooterRef,
chatFooterInnerRef,
}) => {
return ( return (
<div className={`absolute bottom-0 flex justify-center bg-chat-input-mask pb-4 w-full`} ref={chatFooterRef}>
<div <div
className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${chatFooterClassName}`} ref={chatFooterInnerRef}
ref={chatFooterRef}> className={cn('relative', `mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`)}>
<div ref={chatFooterInnerRef} className={cn('relative', chatFooterInnerClassName)}>
<div className="mb-2 flex items-center justify-between relative h-8"> <div className="mb-2 flex items-center justify-between relative h-8">
{/* {isShowPracticeButton && <Practice />} */} {/* {isShowPracticeButton && <Practice />} */}
{ <StopResponding />} {<StopResponding />}
</div> </div>
{/* {!!suggestedQuestions?.length && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />} */} {/* {!!suggestedQuestions?.length && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />} */}
{<ChatInput />} {<ChatInput />}
......
...@@ -2,17 +2,15 @@ ...@@ -2,17 +2,15 @@
* @Author: liimin 17653212@qq.com * @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38 * @Date: 2025-04-16 18:17:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-16 18:48:45 * @LastEditTime: 2025-07-21 21:07:03
* @FilePath: \ai-assistant\app\components\base\chat\chat\index.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\index.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import React, { FC, memo, useEffect, useRef } from 'react' import React, { FC, memo, useEffect, useRef } from 'react'
import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import InitQuestions from '@/app/components/base/chat/chat/question/init-questions' import InitQuestions from '@/app/components/base/chat/chat/question/init-questions'
import ChatFooter from './footer' import ChatFooter from './footer'
import chatStyles from './chat.module.css' import chatStyles from './chat.module.css'
import { AVATAR_USER_URL, AVATAR_AI_URL } from '@/app/components/base/chat/constants'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints' import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import ChatBody from './body' import ChatBody from './body'
...@@ -48,9 +46,7 @@ const Chat: FC<ChatProps> = () => { ...@@ -48,9 +46,7 @@ const Chat: FC<ChatProps> = () => {
} }
} }
const chatContainerInnerClassName = `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}` // const chatContainerInnerClassName = `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`
const chatFooterClassName = 'pb-4 w-full'
const chatFooterInnerClassName = `mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`
// 使用 MutationObserver 监听 DOM 变化 // 使用 MutationObserver 监听 DOM 变化
useEffect(() => { useEffect(() => {
const container = chatContainerRef.current const container = chatContainerRef.current
...@@ -75,20 +71,14 @@ const Chat: FC<ChatProps> = () => { ...@@ -75,20 +71,14 @@ const Chat: FC<ChatProps> = () => {
<div <div
ref={chatContainerRef} ref={chatContainerRef}
className={cn('relative h-full overflow-y-auto overflow-x-hidden', chatStyles.chatContainer)}> className={cn('relative h-full overflow-y-auto overflow-x-hidden', chatStyles.chatContainer)}>
<div ref={chatContainerInnerRef} className={cn('w-full', 'px-8', chatContainerInnerClassName)}> <div
ref={chatContainerInnerRef}
className={cn('w-full', 'px-8', `mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`)}>
<InitQuestions /> <InitQuestions />
<ChatBody /> <ChatBody />
</div> </div>
</div> </div>
<ChatFooter <ChatFooter chatFooterRef={chatFooterRef} chatFooterInnerRef={chatFooterInnerRef} isMobile={isMobile} />
chatFooterRef={chatFooterRef}
chatFooterInnerRef={chatFooterInnerRef}
chatFooterClassName={chatFooterClassName}
chatFooterInnerClassName={chatFooterInnerClassName}
// suggestedQuestions={[]}
isMobile={isMobile}
// isShowPracticeButton={isShowPracticeButton}
/>
</div> </div>
) )
} }
......
...@@ -4,11 +4,11 @@ ...@@ -4,11 +4,11 @@
* @Author: limin * @Author: limin
* @Date: 2025-06-23 15:19:04 * @Date: 2025-06-23 15:19:04
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-17 16:32:28 * @LastEditTime: 2025-07-21 22:56:46
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-questions.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-questions.tsx
*/ */
import type { FC } from 'react' import type { FC } from 'react'
import { memo } from 'react' import { memo, useMemo } from 'react'
import InitSuggest from './init-suggest' import InitSuggest from './init-suggest'
import AnswerIcon from '@/app/components/base/answer-icon' import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
...@@ -18,8 +18,9 @@ type InitQuestionsProps = { ...@@ -18,8 +18,9 @@ type InitQuestionsProps = {
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
} }
const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => { const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => {
const { suggested_questions, initial_message } = useChatConfigContext() const { suggested_questions = [], initial_message } = useChatConfigContext()
if (!suggested_questions?.length || !initial_message?.trim()) return null if (!suggested_questions.length && !initial_message) return null
return useMemo(() => {
const suggestedQuestions = suggested_questions const suggestedQuestions = suggested_questions
.filter(q => !!q && q.trim()) .filter(q => !!q && q.trim())
.sort(() => Math.random() - 0.5) .sort(() => Math.random() - 0.5)
...@@ -33,12 +34,13 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => ...@@ -33,12 +34,13 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) =>
className={cn( className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary', 'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
)}> )}>
<Markdown content={initial_message} /> {initial_message && <Markdown content={initial_message} />}
<InitSuggest suggestedQuestions={suggestedQuestions} /> {suggestedQuestions.length > 0 && <InitSuggest suggestedQuestions={suggestedQuestions} />}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
) )
}, [initial_message])
} }
export default memo(InitQuestions) export default InitQuestions
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @Author: limin * @Author: limin
* @Date: 2025-07-15 09:16:38 * @Date: 2025-07-15 09:16:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-17 16:31:54 * @LastEditTime: 2025-07-21 16:39:18
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-suggest.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-suggest.tsx
*/ */
import type { FC } from 'react' import type { FC } from 'react'
......
...@@ -4,11 +4,11 @@ ...@@ -4,11 +4,11 @@
* @Author: limin * @Author: limin
* @Date: 2025-04-16 18:17:38 * @Date: 2025-04-16 18:17:38
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-17 16:32:50 * @LastEditTime: 2025-07-21 16:36:40
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\question.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\question\question.tsx
*/ */
import type { FC } from 'react' import type { FC } from 'react'
import { memo } from 'react' import { memo, useMemo } from 'react'
import { CssTransform } from '@/app/components/base/chat/embedded-chatbot/theme/utils' import { CssTransform } from '@/app/components/base/chat/embedded-chatbot/theme/utils'
import { Markdown } from '@/app/components/base/markdown' import { Markdown } from '@/app/components/base/markdown'
import { useChatBodyContext } from '@/app/components/base/chat/chat/body/context' import { useChatBodyContext } from '@/app/components/base/chat/chat/body/context'
......
...@@ -12,7 +12,7 @@ const ImageLink: FC<LinkProps> = ({ node }) => { ...@@ -12,7 +12,7 @@ const ImageLink: FC<LinkProps> = ({ node }) => {
className="max-w-full h-auto rounded-lg cursor-pointer hover:opacity-90" className="max-w-full h-auto rounded-lg cursor-pointer hover:opacity-90"
onClick={() => setImagePreviewUrl(node.properties.href)} onClick={() => setImagePreviewUrl(node.properties.href)}
/> />
<ImagePreview url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} title={''} /> {imagePreviewUrl && <ImagePreview url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} title={''} />}
</> </>
) )
} }
......
...@@ -24,6 +24,6 @@ const Paragraph = (paragraph: any) => { ...@@ -24,6 +24,6 @@ const Paragraph = (paragraph: any) => {
// if(node.properties.dataDisable==='disable'){ // if(node.properties.dataDisable==='disable'){
// return <div className="practice-tags">{children}</div> // return <div className="practice-tags">{children}</div>
// } // }
return <p>{children}</p> return <div>{children}</div>
} }
export default Paragraph export default Paragraph
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!