Commit 26e9e006 by liimin

refactor(base): 重构聊天组件并优化状态管理

- 新增 useChatStore 用于全局状态管理
- 重构 ChatWrapper 组件,使用新的聊天上下文
- 更新 Answer、Operation、ChatInputArea 等组件以使用新状态
- 优化 Footer 组件,移除不必要的 useMemo
- 调整 Practice、StopResponding、TryToAsk 组件以适应新逻辑
1 parent 63bf4926
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn * @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17 * @Date: 2025-04-22 09:29:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-07-03 18:48:32 * @LastEditTime: 2025-07-08 18:29:59
* @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
* @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 { useCallback, useEffect, useMemo, useState, FC, useRef, use } from 'react' import { useCallback, useEffect, useMemo, useState, FC, useRef, use } from 'react'
import Chat from '../chat' import Chat from '../chat'
import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types' import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types'
import { useChat, useChatMethods } from '../chat/hooks' import { useChat } from '../chat/hooks'
import { getLastAnswer, isValidGeneratedAnswer } from '../utils' import { getLastAnswer, isValidGeneratedAnswer } from '../utils'
import { useChatWithHistoryContext } from './context' import { useChatWithHistoryContext } from './context'
import { InputVarType } from '@/app/components/workflow/types' import { InputVarType } from '@/app/components/workflow/types'
...@@ -24,6 +24,8 @@ import cn from '@/utils/classnames' ...@@ -24,6 +24,8 @@ import cn from '@/utils/classnames'
// import { SELF_INPUT } from "@/app/components/base/chat/constants"; // import { SELF_INPUT } from "@/app/components/base/chat/constants";
import { InputMessageType } from '../types' import { InputMessageType } from '../types'
import { useChatWithHistory } from './hooks' import { useChatWithHistory } from './hooks'
import { useChatStore } from './store'
import { ChatContextProvider } from '@/app/components/base/chat/chat/context'
enum MessageListenerType { enum MessageListenerType {
RESET_CHAT = 'reset_chat', RESET_CHAT = 'reset_chat',
} }
...@@ -45,7 +47,6 @@ type Props = { ...@@ -45,7 +47,6 @@ type Props = {
isShowPracticeButton: boolean isShowPracticeButton: boolean
} }
const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPracticeButton }) => { const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPracticeButton }) => {
const chatRef = useRef<{ handleSend: Function }>()
const { const {
appParams, appParams,
currentConversationId, currentConversationId,
...@@ -61,39 +62,109 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -61,39 +62,109 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
clearChatList, clearChatList,
setClearChatList, setClearChatList,
} = useChatWithHistory(undefined, inputs) } = useChatWithHistory(undefined, inputs)
const config = useMemo(() => {
useEffect(() => { const config = appParams || {}
if (presuppositionQuestion) { return {
chatRef.current?.handleSend( ...config,
file_upload: {
...(config as any).file_upload,
fileUploadConfig: (config as any).system_parameters,
},
supportFeedback: true,
opening_statement: (config as any).opening_statement,
initial_message: (config as any).opening_statement,
} as ChatConfig
}, [appParams])
const {
chatList,
isResponding,
handleRestart,
handleStop,
sendMessage,
doRegenerate,
} = useChat(
config,
{ {
message: presuppositionQuestion, inputs: inputs as any,
type: InputMessageType.SYSTEM, inputsForm: [], //InputsForm,
}, },
undefined, appPrevChatTree,
taskId => stopChatMessageResponding('', taskId, isInstalledApp, appId),
clearChatList,
setClearChatList,
currentConversationId,
handleNewConversationCompleted,
isInstalledApp,
newConversationInputs,
appId,
handleFeedback,
) )
useEffect(() => {
if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
if (presuppositionQuestion) {
sendMessage(presuppositionQuestion)
} }
}, [presuppositionQuestion]) }, [presuppositionQuestion])
useEffect(() => {
Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
value: (data: MessageListenerProps) => {
try {
switch (data.type) {
case MessageListenerType.RESET_CHAT:
handleNewConversation()
data.payload.message && sendMessage(data.payload.message)
break
}
} catch (error) {
console.error('send failed:', error)
}
},
writable: false,
configurable: true,
enumerable: false,
})
return () => {
if (SEND_MESSAGE_KEY in globalThis) {
delete (globalThis as IGlobalThis)[SEND_MESSAGE_KEY] // 使用 Symbol 作为 key
}
}
}, [])
return ( return (
<div className="h-full overflow-hidden"> <div className="h-full overflow-hidden">
<ChatContextProvider
config={config}
chatList={chatList}
isResponding={isResponding}
onSend={sendMessage}
onRegenerate={doRegenerate}
onRestart={handleRestart}
onStopResponding={handleStop}
onFeedback={handleFeedback}>
<Chat <Chat
ref={chatRef} // ref={chatRef}
inputs={inputs} // inputs={inputs}
isShowPracticeButton={isShowPracticeButton} isShowPracticeButton={isShowPracticeButton}
appParams={appParams} // appParams={appParams}
clearChatList={clearChatList} // clearChatList={clearChatList}
setClearChatList={setClearChatList} // setClearChatList={setClearChatList}
currentChatInstanceRef={currentChatInstanceRef} // currentChatInstanceRef={currentChatInstanceRef}
handleFeedback={handleFeedback} // handleFeedback={handleFeedback}
appId={appId || ''} // appId={appId || ''}
isInstalledApp={isInstalledApp} // isInstalledApp={isInstalledApp}
currentConversationId={currentConversationId} // currentConversationId={currentConversationId}
appPrevChatTree={appPrevChatTree} // appPrevChatTree={appPrevChatTree}
newConversationInputs={newConversationInputs} // newConversationInputs={newConversationInputs}
newConversationInputsRef={newConversationInputsRef} // newConversationInputsRef={newConversationInputsRef}
handleNewConversation={handleNewConversation} // handleNewConversation={handleNewConversation}
handleNewConversationCompleted={handleNewConversationCompleted} // handleNewConversationCompleted={handleNewConversationCompleted}
/> />
</ChatContextProvider>
</div> </div>
) )
} }
......
...@@ -55,7 +55,6 @@ const avatarUrl: string = avatar ?? AVATAR_USER_URL ...@@ -55,7 +55,6 @@ const avatarUrl: string = avatar ?? AVATAR_USER_URL
const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => { const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
const { appInfoError, appInfoLoading, isMobile } = useChatWithHistoryContext() const { appInfoError, appInfoLoading, isMobile } = useChatWithHistoryContext()
if (appInfoLoading) { if (appInfoLoading) {
return <Loading type="app" /> return <Loading type="app" />
} else if (appInfoError) { } else if (appInfoError) {
......
import { create } from 'zustand' import { create } from 'zustand'
import { InputMessageProp } from '../types' import { ChatConfig, ChatItemInTree, Feedback } from '@/app/components/base/chat/types'
import { FileEntity } from '../../file-uploader/types' import { OnSendMessage } from '@/app/components/base/chat/chat/context'
import { noop } from 'lodash-es'
type OnRegenerate = (chatItem: ChatItemInTree) => void
type State = { type State = {
handleNewConversation: () => void chatList: ChatItemInTree[],
handleSend: (query: InputMessageProp, files: FileEntity[] | undefined) => void isResponding: boolean
sendMessage:OnSendMessage
config: ChatConfig,
doRegenerate:(chatItem: ChatItemInTree)=>void
stopResponding: ()=>void
restartChat: () => void
handleFeedback: (messageId: string, feedback: Feedback) => Promise<void>,
} }
type Action = { type Action = {
setHandleNewConversation: (fn: () => void) => void setChatList: (chatList: ChatItemInTree[]) => void
setHandleSend: (fn: (query: InputMessageProp, files: FileEntity[] | undefined) => void) => void setIsResponding: (isRespongding: boolean) => void
setSendMessage: (sendMessage:OnSendMessage) => void
setConfig: (config: ChatConfig) => void
setDoRegenerate: (doRegenerate:OnRegenerate) => void
setStopResponding: (stopResponding: ()=>void) => void
setRestartChat: (restartChat: () => void) => void
setHandleFeedback: (handleFeedback: (messageId: string, feedback: Feedback) => Promise<void>) => void
} }
export const useChatStore = create<State & Action>(set => ({ export const useChatStore = create<State & Action>(set => ({
handleNewConversation: noop, chatList: [],
setHandleNewConversation: handleNewConversation => set({ handleNewConversation }), setChatList: chatList => set({ chatList }),
handleSend: noop, isResponding: false,
setHandleSend: handleSend => set({ handleSend }), setIsResponding: (isResponding: boolean) => set({ isResponding }),
sendMessage: () => {},
setSendMessage: (sendMessage: OnSendMessage) => set({ sendMessage }),
config: {} as ChatConfig,
setConfig: (config: ChatConfig) => set({ config }),
doRegenerate: () => {},
setDoRegenerate: (doRegenerate: OnRegenerate) => set({ doRegenerate }),
stopResponding: () => {},
setStopResponding: (stopResponding: () => void) => set({ stopResponding }),
restartChat: () => {},
setRestartChat: (restartChat:() => void) => set({ restartChat }),
handleFeedback: () => Promise.resolve(),
setHandleFeedback: (handleFeedback:(messageId: string, feedback: Feedback) => Promise<void>) => set({ handleFeedback }),
})) }))
...@@ -17,6 +17,7 @@ import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows ...@@ -17,6 +17,7 @@ import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { FileList } from '@/app/components/base/file-uploader' import { FileList } from '@/app/components/base/file-uploader'
import { useChatContext } from '../context' import { useChatContext } from '../context'
import { useChatStore } from '../../chat-with-history/store'
type AnswerProps = { type AnswerProps = {
item: ChatItem item: ChatItem
...@@ -48,6 +49,7 @@ const Answer: FC<AnswerProps> = ({ ...@@ -48,6 +49,7 @@ const Answer: FC<AnswerProps> = ({
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null) const contentRef = useRef<HTMLDivElement>(null)
const { config, isResponding } = useChatContext() const { config, isResponding } = useChatContext()
// const [config,isResponding] = useChatStore(state =>[state.config,state.isResponding])
const responding = isLast && isResponding const responding = isLast && isResponding
const getContainerWidth = () => { const getContainerWidth = () => {
if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16) if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16)
......
...@@ -7,12 +7,14 @@ import SuggestedQuestions from './suggested-questions' ...@@ -7,12 +7,14 @@ import SuggestedQuestions from './suggested-questions'
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'
import { useChatContext } from '../context' import { useChatContext } from '../context'
import { useChatStore } from '../../chat-with-history/store'
type InitQuestionsProps = { type InitQuestionsProps = {
// config: ChatConfig // config: ChatConfig
answerIcon: ReactNode answerIcon: ReactNode
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
} }
const InitQuestions: FC<InitQuestionsProps> = ({ answerIcon, chatAnswerContainerInner }) => { const InitQuestions: FC<InitQuestionsProps> = ({ answerIcon, chatAnswerContainerInner }) => {
// const config = useChatStore(state => state.config)
const {config} = useChatContext() const {config} = useChatContext()
const questions = useMemo(() => { const questions = useMemo(() => {
const { suggested_questions, initial_message } = config const { suggested_questions, initial_message } = config
......
...@@ -10,6 +10,7 @@ import Log from '@/app/components/base/chat/chat/log' ...@@ -10,6 +10,7 @@ import Log from '@/app/components/base/chat/chat/log'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button' import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
import NewAudioButton from '@/app/components/base/new-audio-button' import NewAudioButton from '@/app/components/base/new-audio-button'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { useChatStore } from '../../chat-with-history/store'
type OperationProps = { type OperationProps = {
item: ChatItem item: ChatItem
...@@ -25,7 +26,8 @@ type OperationProps = { ...@@ -25,7 +26,8 @@ type OperationProps = {
const Operation: FC<OperationProps> = ({ item, isLast, question, index, showPromptLog, maxSize, contentWidth, hasWorkflowProcess, noChatInput }) => { const Operation: FC<OperationProps> = ({ item, isLast, question, index, showPromptLog, maxSize, contentWidth, hasWorkflowProcess, noChatInput }) => {
const { t } = useTranslation() const { t } = useTranslation()
const { config, onFeedback, onRegenerate } = useChatContext() const { config, onFeedback, onSend:sendMessage,onRegenerate } = useChatContext()
// const [config,onFeedback,sendMessage,onRegenerate] = useChatStore(state => [state.config,state.handleFeedback,state.sendMessage,state.doRegenerate])
const [isShowReplyModal, setIsShowReplyModal] = useState(false) const [isShowReplyModal, setIsShowReplyModal] = useState(false)
const [showLike, setShowLike] = useState(false) const [showLike, setShowLike] = useState(false)
...@@ -39,10 +41,10 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm ...@@ -39,10 +41,10 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm
}, [agent_thoughts, messageContent]) }, [agent_thoughts, messageContent])
// 判断反馈按钮是否启用 // 判断反馈按钮是否启用
const feedbackEnabled = useMemo(() => config?.supportFeedback && !localFeedback?.rating && onFeedback && !isOpeningStatement, [config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement]) const feedbackEnabled = useMemo(() => config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement, [config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement])
// 判断是否已点赞 // 判断是否已点赞
const feedbackActive = useMemo(() => config?.supportFeedback && localFeedback?.rating && onFeedback && !isOpeningStatement, [config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement]) const feedbackActive = useMemo(() => config?.supportFeedback && localFeedback?.rating && !isOpeningStatement, [config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement])
// 处理反馈 // 处理反馈
const handleFeedback = async (rating: 'like' | 'dislike' | null) => { const handleFeedback = async (rating: 'like' | 'dislike' | null) => {
...@@ -96,8 +98,8 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm ...@@ -96,8 +98,8 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm
if (!isOpeningStatement && showPromptLog) width += 28 + 8 if (!isOpeningStatement && showPromptLog) width += 28 + 8
if (!isOpeningStatement && config?.text_to_speech?.enabled) width += 26 if (!isOpeningStatement && config?.text_to_speech?.enabled) width += 26
if (!isOpeningStatement && config?.supportAnnotation && config?.annotation_reply?.enabled) width += 26 if (!isOpeningStatement && config?.supportAnnotation && config?.annotation_reply?.enabled) width += 26
if (config?.supportFeedback && !localFeedback?.rating && onFeedback && !isOpeningStatement) width += 60 + 8 if (config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement) width += 60 + 8
if (config?.supportFeedback && localFeedback?.rating && onFeedback && !isOpeningStatement) width += 28 + 8 if (config?.supportFeedback && localFeedback?.rating && !isOpeningStatement) width += 28 + 8
return width return width
}, [isOpeningStatement, showPromptLog, config?.text_to_speech?.enabled, config?.supportAnnotation, config?.annotation_reply?.enabled, config?.supportFeedback, localFeedback?.rating, onFeedback]) }, [isOpeningStatement, showPromptLog, config?.text_to_speech?.enabled, config?.supportAnnotation, config?.annotation_reply?.enabled, config?.supportFeedback, localFeedback?.rating, onFeedback])
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn * @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17 * @Date: 2025-04-22 09:29:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-06-26 10:32:55 * @LastEditTime: 2025-07-08 18:09:11
* @FilePath: \ai-assistant\app\components\base\chat\chat\answer\suggested-questions.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\answer\suggested-questions.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
*/ */
...@@ -13,11 +13,13 @@ import { useChatContext } from '../context' ...@@ -13,11 +13,13 @@ import { useChatContext } from '../context'
import Button from '@/app/components/base/button/next-button' import Button from '@/app/components/base/button/next-button'
// import { AUTO_INPUT } from '@/app/components/base/chat/constants' // import { AUTO_INPUT } from '@/app/components/base/chat/constants'
import { InputMessageType } from '../../types' import { InputMessageType } from '../../types'
import { useChatStore } from '../../chat-with-history/store'
type SuggestedQuestionsProps = { type SuggestedQuestionsProps = {
item: ChatItem item: ChatItem
} }
const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => { const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => {
const { onSend } = useChatContext() // const sendMessage = useChatStore(state=>state.sendMessage)
const { onSend:sendMessage } = useChatContext()
const { suggestedQuestions } = item const { suggestedQuestions } = item
if (!suggestedQuestions?.length) return null if (!suggestedQuestions?.length) return null
// const questionList = useMemo(() => { // const questionList = useMemo(() => {
...@@ -30,7 +32,7 @@ const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => { ...@@ -30,7 +32,7 @@ const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => {
<Button <Button
key={index} key={index}
text={question} text={question}
onClick={() => onSend?.({ message: question, type: InputMessageType.SYSTEM })}></Button> onClick={() => sendMessage?.(question, InputMessageType.SYSTEM )}></Button>
))} ))}
</div> </div>
) )
......
import { memo, FC, useEffect, ReactNode } from 'react'
import Answer from '../answer'
import Question from '../question'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
import { useChatContext } from '../context'
import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/state'
type ChatBodyProps = {
answerIcon?: ReactNode
questionIcon?: ReactNode
}
const ChatBody: FC<ChatBodyProps> = ({ answerIcon, questionIcon }) => {
// const chatList = useChatStore(state=>state.chatList)
const { chatList } = useChatContext()
return (
<>
{chatList.map((item, index) => {
if (item.isAnswer) {
const isLast = item.id === chatList[chatList.length - 1]?.id
return (
<Answer
key={item.id}
item={item}
question={chatList[index - 1]?.content}
index={index}
answerIcon={answerIcon}
isLast={isLast}
/>
)
}
return <Question key={item.id} item={item} questionIcon={questionIcon} />
})}
</>
)
}
export default memo(ChatBody)
...@@ -20,6 +20,7 @@ import { TransferMethod } from '@/types/app' ...@@ -20,6 +20,7 @@ import { TransferMethod } from '@/types/app'
import { InputMessageType } from '../../types' import { InputMessageType } from '../../types'
import { useChatContext } from '../context' import { useChatContext } from '../context'
import Confirm from '@/app/components/base/confirm' import Confirm from '@/app/components/base/confirm'
import { useChatStore } from '../../chat-with-history/store'
type ChatInputAreaProps = { type ChatInputAreaProps = {
showFeatureBar?: boolean showFeatureBar?: boolean
showFileUpload?: boolean showFileUpload?: boolean
...@@ -45,10 +46,16 @@ const ChatInputArea = ({ ...@@ -45,10 +46,16 @@ const ChatInputArea = ({
// disabled, // disabled,
}: ChatInputAreaProps) => { }: ChatInputAreaProps) => {
const { t } = useTranslation() const { t } = useTranslation()
const { onSend, onRestart, isResponding,config } = useChatContext() // const { onSend, onRestart, isResponding } = useChatContext()
// const config= useChatStore(state => state.config)
// console.log('config', config)
const { notify } = useToastContext() const { notify } = useToastContext()
const {isResponding, onSend:sendMessage, onRestart:restartChat,config} = useChatContext()
const visionConfig = config.file_upload const visionConfig = config.file_upload
const speechToTextConfig = config.speech_to_text const speechToTextConfig = config.speech_to_text
// const sendMessage = useChatStore(state => state.sendMessage)
// const isResponding = useChatStore(state => state.isResponding)
// const restartChat = useChatStore(state => state.restartChat)
const { const {
wrapperRef, wrapperRef,
textareaRef, textareaRef,
...@@ -85,7 +92,7 @@ const ChatInputArea = ({ ...@@ -85,7 +92,7 @@ const ChatInputArea = ({
return return
} }
if (onSend) { if (sendMessage) {
const { files, setFiles } = filesStore.getState() const { files, setFiles } = filesStore.getState()
if (files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)) { if (files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)) {
notify({ notify({
...@@ -102,7 +109,7 @@ const ChatInputArea = ({ ...@@ -102,7 +109,7 @@ const ChatInputArea = ({
return return
} }
// if (checkInputsForm(inputs, inputsForm)) { // if (checkInputsForm(inputs, inputsForm)) {
onSend({ message: query, type: InputMessageType.SELF }, files) sendMessage(query, InputMessageType.SELF, files)
setQuery('') setQuery('')
setFiles([]) setFiles([])
// } // }
...@@ -170,9 +177,9 @@ const ChatInputArea = ({ ...@@ -170,9 +177,9 @@ const ChatInputArea = ({
setShowConfirm(true) setShowConfirm(true)
}, [isResponding]) }, [isResponding])
const doRestart = useCallback(() => { const doRestart = useCallback(() => {
onRestart() restartChat()
setShowConfirm(false) setShowConfirm(false)
},[]) }, [])
const operation = ( const operation = (
<Operation <Operation
......
...@@ -7,6 +7,7 @@ import ActionButton from '@/app/components/base/action-button' ...@@ -7,6 +7,7 @@ import ActionButton from '@/app/components/base/action-button'
import { FileUploaderInChatInput } from '@/app/components/base/file-uploader' import { FileUploaderInChatInput } from '@/app/components/base/file-uploader'
import type { FileUpload } from '@/app/components/base/features/types' import type { FileUpload } from '@/app/components/base/features/types'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
import { import {
// SELF_INPUT, // SELF_INPUT,
SEND_BUTTON, SEND_BUTTON,
......
'use client' 'use client'
import type { ReactNode } from 'react' import { useMemo, type ReactNode } from 'react'
import { createContext, useContext } from 'use-context-selector' import { createContext, useContext } from 'use-context-selector'
import { noop } from 'lodash-es' import { noop } from 'lodash-es'
import { ChatConfig, ChatItem, Feedback, OnRegenerate, OnSend } from '../types' import { ChatConfig, ChatItem, Feedback, InputMessageProp, InputMessageType, OnRegenerate, OnSend } from '../types'
import { FileEntity } from '../../file-uploader/types'
export type OnSendMessage = (
message: string,
type?: InputMessageType,
files?: FileEntity[],
parentMessageId?: string,
) => void
export type ChatContextValue = { export type ChatContextValue = {
config: ChatConfig config: ChatConfig
chatList: ChatItem[] chatList: ChatItem[]
isResponding?: boolean isResponding?: boolean
onSend: OnSend onSend: OnSendMessage
onRegenerate?: OnRegenerate onRegenerate?: OnRegenerate
onStopResponding?: () => void onStopResponding?: () => void
onRestart: () => void onRestart: () => void
...@@ -21,7 +28,7 @@ const ChatContext = createContext<ChatContextValue>({ ...@@ -21,7 +28,7 @@ const ChatContext = createContext<ChatContextValue>({
onRestart: noop, onRestart: noop,
onSend: noop, onSend: noop,
chatList: [], chatList: [],
onFeedback:noop onFeedback: noop,
}) })
type ChatContextProviderProps = { type ChatContextProviderProps = {
......
...@@ -9,6 +9,8 @@ import ChatInputArea from '../chat-input-area' ...@@ -9,6 +9,8 @@ import ChatInputArea from '../chat-input-area'
import StopResponding from './stopResponding' import StopResponding from './stopResponding'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { useChatContext } from '../context' import { useChatContext } from '../context'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/state'
type FooterProps = { type FooterProps = {
chatFooterClassName?: string chatFooterClassName?: string
chatFooterInnerClassName?: string chatFooterInnerClassName?: string
...@@ -28,12 +30,13 @@ const Footer: FC<FooterProps> = ({ ...@@ -28,12 +30,13 @@ const Footer: FC<FooterProps> = ({
chatFooterRef, chatFooterRef,
chatFooterInnerRef, chatFooterInnerRef,
}) => { }) => {
// const config = useChatStore(state=> state.config)
// const {config} = useChatContext()
// const hasTryToAsk = useMemo(
// () => config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length,
// [config?.suggested_questions_after_answer?.enabled, suggestedQuestions]
// )
console.log('Footer') console.log('Footer')
const { config } = useChatContext()
const hasTryToAsk = useMemo(
() => config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length,
[config?.suggested_questions_after_answer?.enabled, suggestedQuestions]
)
return ( return (
<div <div
className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${chatFooterClassName}`} className={`absolute bottom-0 flex justify-center bg-chat-input-mask ${chatFooterClassName}`}
...@@ -43,7 +46,7 @@ const Footer: FC<FooterProps> = ({ ...@@ -43,7 +46,7 @@ const Footer: FC<FooterProps> = ({
{isShowPracticeButton && <Practice />} {isShowPracticeButton && <Practice />}
{ <StopResponding />} { <StopResponding />}
</div> </div>
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />} {!!suggestedQuestions?.length && <TryToAsk suggestedQuestions={suggestedQuestions} isMobile={isMobile} />}
{<ChatInputArea />} {<ChatInputArea />}
</div> </div>
</div> </div>
...@@ -51,11 +54,5 @@ const Footer: FC<FooterProps> = ({ ...@@ -51,11 +54,5 @@ const Footer: FC<FooterProps> = ({
} }
export default memo(Footer, (prevProps, nextProps) => { export default memo(Footer, (prevProps, nextProps) => {
return ( return true
prevProps.chatFooterClassName === nextProps.chatFooterClassName &&
prevProps.chatFooterInnerClassName === nextProps.chatFooterInnerClassName &&
prevProps.isMobile === nextProps.isMobile &&
prevProps.suggestedQuestions === nextProps.suggestedQuestions &&
prevProps.isShowPracticeButton === nextProps.isShowPracticeButton
)
}) })
...@@ -5,11 +5,12 @@ import { InputMessageType } from '@/app/components/base/chat/types' ...@@ -5,11 +5,12 @@ import { InputMessageType } from '@/app/components/base/chat/types'
import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons' import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons'
import { useChatContext } from '../context' import { useChatContext } from '../context'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
const Practice: FC = () => { const Practice: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { onSend } = useChatContext() // const sendMessage = useChatStore(state => state.sendMessage)
const { onSend: sendMessage } = useChatContext()
const question = t('appDebug.feature.practice.text') const question = t('appDebug.feature.practice.text')
console.log('question', question)
return ( return (
<div> <div>
{ {
...@@ -19,12 +20,7 @@ const Practice: FC = () => { ...@@ -19,12 +20,7 @@ const Practice: FC = () => {
className="mb-1 w-40 h-8 pl-2 className="mb-1 w-40 h-8 pl-2
rounded-8 rounded-8
shadow-[0_3px_8px_0_#7D94B840]" shadow-[0_3px_8px_0_#7D94B840]"
onClick={() => onClick={() => sendMessage?.(question, InputMessageType.SELF)}>
onSend?.({
message: question,
type: InputMessageType.SELF,
})
}>
<PracticeIcon className="size-4 mr-3" /> <PracticeIcon className="size-4 mr-3" />
{question} {question}
</Button> </Button>
......
...@@ -3,13 +3,17 @@ import Button from '@/app/components/base/button' ...@@ -3,13 +3,17 @@ import Button from '@/app/components/base/button'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices' import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useChatContext } from '../context' import { useChatContext } from '../context'
import { useChatStore } from '../../chat-with-history/store'
import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/state'
const StopRespondingButton: FC = () => { const StopRespondingButton: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { onStopResponding,isResponding } = useChatContext() // const isResponding = useChatStore(state => state.isResponding)
if(!isResponding) return null // const stopResponding = useChatStore(state => state.stopResponding)
const { isResponding, onStopResponding: stopResponding } = useChatContext()
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">
<Button onClick={onStopResponding}> <Button onClick={stopResponding}>
<StopCircle className="mr-[5px] h-3.5 w-3.5 text-gray-500" /> <StopCircle className="mr-[5px] h-3.5 w-3.5 text-gray-500" />
<span className="text-xs font-normal text-gray-500">{t('appDebug.operation.stopResponding')}</span> <span className="text-xs font-normal text-gray-500">{t('appDebug.operation.stopResponding')}</span>
</Button> </Button>
......
...@@ -11,37 +11,30 @@ type TryToAskProps = { ...@@ -11,37 +11,30 @@ type TryToAskProps = {
suggestedQuestions?: string[] suggestedQuestions?: string[]
isMobile?: boolean isMobile?: boolean
} }
const TryToAsk: FC<TryToAskProps> = ({ const TryToAsk: FC<TryToAskProps> = ({ suggestedQuestions, isMobile }) => {
suggestedQuestions,
isMobile,
}) => {
const { onSend } = useChatContext() const { onSend } = useChatContext()
const { t } = useTranslation() const { t } = useTranslation()
return ( return (
<div className='mb-2 py-2'> <div className="mb-2 py-2">
<div className={cn('mb-2.5 flex items-center justify-between gap-2', isMobile && 'justify-end')}> <div className={cn('mb-2.5 flex items-center justify-between gap-2', isMobile && 'justify-end')}>
<Divider bgStyle='gradient' className='h-px grow rotate-180' /> <Divider bgStyle="gradient" className="h-px grow rotate-180" />
<div className='system-xs-medium-uppercase shrink-0 text-text-tertiary'>{t('appDebug.feature.suggestedQuestionsAfterAnswer.tryToAsk')}</div> <div className="system-xs-medium-uppercase shrink-0 text-text-tertiary">
{!isMobile && <Divider bgStyle='gradient' className='h-px grow' />} {t('appDebug.feature.suggestedQuestionsAfterAnswer.tryToAsk')}
</div>
{!isMobile && <Divider bgStyle="gradient" className="h-px grow" />}
</div> </div>
<div className={cn('flex flex-wrap justify-center', isMobile && 'justify-end')}> <div className={cn('flex flex-wrap justify-center', isMobile && 'justify-end')}>
{ {suggestedQuestions?.map((suggestQuestion, index) => (
suggestedQuestions?.map((suggestQuestion, index) => (
<Button <Button
size='small' size="small"
key={index} key={index}
variant='secondary-accent' variant="secondary-accent"
className='mb-1 mr-1 last:mr-0' className="mb-1 mr-1 last:mr-0"
onClick={() => onSend({ onClick={() => onSend(suggestQuestion, InputMessageType.SELF)}>
message: suggestQuestion,
type: InputMessageType.SELF
})}
>
{suggestQuestion} {suggestQuestion}
</Button> </Button>
)) ))}
}
</div> </div>
</div> </div>
) )
......
...@@ -85,10 +85,11 @@ export enum PracticeStatus { ...@@ -85,10 +85,11 @@ export enum PracticeStatus {
Failed = '3', Failed = '3',
} }
export type OnSend = { export type OnSend = {
(message: InputMessageProp, files?: FileEntity[]): void (sendProps:SendProps): void
(message: InputMessageProp, files: FileEntity[] | undefined, isRegenerate: boolean, lastAnswer?: ChatItem | null): void
} }
export type SendProps = {messageObj?: InputMessageProp, files?: FileEntity[], parentMessageId?: string}
export type OnRegenerate = (chatItem: ChatItem) => void export type OnRegenerate = (chatItem: ChatItem) => void
export type Callback = { export type Callback = {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!