Commit d5e9c1d3 by liimin

refactor(chat): 重构聊天组件

- 拆分 chat-runtime-context 为多个独立的 context
- 优化 chat-wrapper 和 chat 组件的结构
- 调整 chat-body 和 chat-footer 组件的实现
- 重构 useChat hook,提高性能和可维护性
1 parent d4cafcfe
Showing 22 changed files with 139 additions and 125 deletions
...@@ -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-07-15 23:45:09 * @LastEditTime: 2025-07-16 20:12:53
* @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
*/ */
...@@ -15,9 +15,12 @@ import AppUnavailable from '@/app/components/base/app-unavailable' ...@@ -15,9 +15,12 @@ import AppUnavailable from '@/app/components/base/app-unavailable'
import { stopChatMessageResponding } from '@/service/share' import { stopChatMessageResponding } from '@/service/share'
import { InputMessageType } from '../types' import { InputMessageType } from '../types'
import { useChatWithHistory } from './hooks' import { useChatWithHistory } from './hooks'
import { ChatContextProvider } from '@/app/components/base/chat/chat-with-history/context/chat-context' import {
import { ChatRuntimeProvider } from './context/chat-runtime-context' ChatContextProvider,
import { ChatConfigProvider } from './context/chat-config-context' ChatConfigProvider,
ChatListProvider,
ChatRespondingProvider,
} from '@/app/components/base/chat/chat-with-history/context'
enum MessageListenerType { enum MessageListenerType {
RESET_CHAT = 'reset_chat', RESET_CHAT = 'reset_chat',
...@@ -85,6 +88,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -85,6 +88,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
} }
} }
}, []) }, [])
return ( return (
<div className="h-full overflow-hidden"> <div className="h-full overflow-hidden">
<ChatConfigProvider config={config}> <ChatConfigProvider config={config}>
...@@ -92,11 +96,13 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -92,11 +96,13 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
onSend={sendMessage} onSend={sendMessage}
onRegenerate={doRegenerate} onRegenerate={doRegenerate}
onRestart={handleRestart} onRestart={handleRestart}
onStopResponding={handleStop} onFeedback={handleFeedback}
onFeedback={handleFeedback}> onStopResponding={handleStop}>
<ChatRuntimeProvider chatList={chatList} isResponding={isResponding}> <ChatRespondingProvider isResponding={isResponding}>
<ChatListProvider chatList={chatList}>
<Chat /> <Chat />
</ChatRuntimeProvider> </ChatListProvider>
</ChatRespondingProvider>
</ChatContextProvider> </ChatContextProvider>
</ChatConfigProvider> </ChatConfigProvider>
</div> </div>
......
'use client' 'use client'
import { useMemo } from 'react' import { useCallback, useMemo } 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 type { Feedback, InputMessageType, OnRegenerate } from '@/app/components/base/chat/types' import type { ChatItem, Feedback, InputMessageType, OnRegenerate } from '@/app/components/base/chat/types'
import { FileEntity } from '@/app/components/base/file-uploader/types' import { FileEntity } from '@/app/components/base/file-uploader/types'
export type OnSendMessage = ( export type OnSendMessage = (
message: string, message: string,
...@@ -45,9 +45,8 @@ export const ChatContextProvider = ({ ...@@ -45,9 +45,8 @@ export const ChatContextProvider = ({
onFeedback, onFeedback,
onStopResponding, onStopResponding,
}), }),
[onSend, onRegenerate, onRestart, onFeedback, onStopResponding], [],
) )
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider> return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
} }
......
...@@ -3,24 +3,23 @@ ...@@ -3,24 +3,23 @@
import { createContext, useContext } from 'use-context-selector' import { createContext, useContext } from 'use-context-selector'
import type { ChatItem } from '../../types' import type { ChatItem } from '../../types'
import { useMemo } from 'react'
type RuntimeContext = { type ChatListContext = {
chatList: ChatItem[] chatList: ChatItem[]
isResponding?: boolean
} }
const ChatRuntimeContext = createContext<RuntimeContext>({ const ChatListContext = createContext<ChatListContext>({
chatList: [], chatList: [],
isResponding: false,
}) })
export const useChatRuntimeContext = () => useContext(ChatRuntimeContext) export const useChatListContext = () => useContext(ChatListContext)
type Props = { type Props = {
children: React.ReactNode children: React.ReactNode
} & RuntimeContext } & ChatListContext
export const ChatRuntimeProvider = ({ children, chatList, isResponding }: Props) => { export const ChatListProvider = ({ children, chatList }: Props) => {
const value = { chatList, isResponding } const value = { chatList }
return <ChatRuntimeContext.Provider value={value}>{children}</ChatRuntimeContext.Provider> return <ChatListContext.Provider value={value}>{children}</ChatListContext.Provider>
} }
// app/components/base/chat/chat/chat-runtime-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ChatItem } from '../../types'
import { useMemo } from 'react'
type RespondingContext = {
isResponding?: boolean
}
const ChatRespondingContext = createContext<RespondingContext>({
isResponding: false,
})
export const useChatRespondingContext = () => useContext(ChatRespondingContext)
type Props = {
children: React.ReactNode
} & RespondingContext
export const ChatRespondingProvider = ({ children, isResponding }: Props) => {
const __isResponding = useMemo(() => isResponding, [isResponding])
const value = useMemo(() => ({ isResponding:__isResponding }), [ __isResponding])
return <ChatRespondingContext.Provider value={value}>{children}</ChatRespondingContext.Provider>
}
export { ChatConfigProvider, useChatConfigContext } from './chat-config-context'
export { ChatContextProvider, useChatContext } from './chat-context'
export { ChatListProvider, useChatListContext } from './chat-list-context'
export { ChatRespondingProvider, useChatRespondingContext } from './chat-responding-context'
...@@ -31,10 +31,10 @@ type SendCallback = { ...@@ -31,10 +31,10 @@ type SendCallback = {
onConversationComplete?: (conversationId: string) => void onConversationComplete?: (conversationId: string) => void
isPublicAPI?: boolean isPublicAPI?: boolean
} }
type UpdateChatTreeNode = { type UpdateChatTreeNode = {
(id: string, fields: Partial<ChatItemInTree>): void (id: string, fields: Partial<ChatItemInTree>): void
(id: string, update: (node: ChatItemInTree) => void): void (id: string, update: (node: ChatItemInTree) => void): void
} }
export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, any> = {}) => { export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, any> = {}) => {
const { t } = useTranslation() const { t } = useTranslation()
const { notify } = useToastContext() const { notify } = useToastContext()
...@@ -79,7 +79,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -79,7 +79,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
{ revalidateOnFocus: false }, { revalidateOnFocus: false },
) )
const config = useMemo(() => { const config = useMemo(() => {
const cfg = cloneDeep(appParams) || {} const cfg = appParams || {}
return { return {
...cfg, ...cfg,
file_upload: { file_upload: {
...@@ -92,32 +92,27 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -92,32 +92,27 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
} as ChatConfig } as ChatConfig
}, [appParams]) }, [appParams])
const handleNewConversation = useCallback( const handleNewConversation = useCallback((inputs?: Record<string, any>, isSkipClear: boolean = false) => {
(inputs?: Record<string, any>, isSkipClear: boolean = false) => {
currentChatInstanceRef.current.handleStop() currentChatInstanceRef.current.handleStop()
conversationId.current = '' conversationId.current = ''
if (inputs) { if (inputs) {
setNewConversationInputs(inputs) setNewConversationInputs(inputs)
} }
if (!isSkipClear) { if (!isSkipClear) {
setChatTree([])
chatListRef.current = []
setClearChatList(true) setClearChatList(true)
} }
}, }, [])
[], const handleNewConversationCompleted = useCallback((newConversationId: string) => {
)
const handleNewConversationCompleted = useCallback(
(newConversationId: string) => {
conversationId.current = newConversationId conversationId.current = newConversationId
}, }, [])
[conversationId],
)
useEffect(() => { useEffect(() => {
if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop
}, []) }, [])
const handleFeedback = useCallback( const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
async (messageId: string, feedback: Feedback) => {
await updateFeedback( await updateFeedback(
{ {
url: `/messages/${messageId}/feedbacks`, url: `/messages/${messageId}/feedbacks`,
...@@ -127,14 +122,16 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -127,14 +122,16 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
appId, appId,
) )
notify({ type: 'success', message: t('common.api.success') }) notify({ type: 'success', message: t('common.api.success') })
}, }, [])
[appId, t, notify],
)
/** Final chat list that will be rendered */ /** Final chat list that will be rendered */
const chatList = useMemo(() => { const chatList = useMemo(() => {
return [...threadMessages] return [...threadMessages]
}, [threadMessages]) }, [threadMessages])
const chatListRef = useRef<ChatItemInTree[]>(chatList)
useEffect(() => {
chatListRef.current = chatList
}, [chatList])
useEffect(() => { useEffect(() => {
setAutoFreeze(false) setAutoFreeze(false)
...@@ -194,6 +191,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -194,6 +191,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
(cb?: any) => { (cb?: any) => {
conversationId.current = '' conversationId.current = ''
taskIdRef.current = '' taskIdRef.current = ''
chatListRef.current = []
handleStop() handleStop()
setChatTree([]) setChatTree([])
setSuggestQuestions([]) setSuggestQuestions([])
...@@ -268,18 +266,19 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -268,18 +266,19 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
* 判断是否重新生成 parentMessageId 有值则为重新生成,如果不是则为正常问题 * 判断是否重新生成 parentMessageId 有值则为重新生成,如果不是则为正常问题
*/ */
let parentMessage = null let parentMessage = null
if (conversationId.current) {
if (parentMessageId) { if (parentMessageId) {
const question = threadMessages.find(item => item.id === parentMessageId)! const question = chatListRef.current.find(item => item.id === parentMessageId)!
parentMessage = threadMessages.find(item => item.id === question.parentMessageId) parentMessage = chatListRef.current.find(item => item.id === question.parentMessageId)
Object.assign(data, { Object.assign(data, {
query: question.content, query: question.content,
files: question.message_files, files: question.message_files,
}) })
} else { } else {
parentMessage = getLastAnswer(chatList) parentMessage = getLastAnswer(chatListRef.current)
} }
data.parent_message_id = parentMessage?.id data.parent_message_id = parentMessage?.id
}
// const parentMessage = threadMessages.find( // const parentMessage = threadMessages.find(
// (item) => item.id === data.parent_message_id // (item) => item.id === data.parent_message_id
// ); // );
...@@ -551,9 +550,9 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -551,9 +550,9 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
[ [
t, t,
// chatTree.length, // chatTree.length,
threadMessages, // threadMessages,
// config?.suggested_questions_after_answer, // config?.suggested_questions_after_answer,
// updateCurrentQAOnTree, updateCurrentQAOnTree,
// updateChatTreeNode, // updateChatTreeNode,
notify, notify,
// handleResponding, // handleResponding,
...@@ -585,17 +584,16 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -585,17 +584,16 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
) )
}, },
[ [
handleSend, // handleSend,
// appId, // appId,
// newConversationInputs, // newConversationInputs,
// getUrl, // getUrl,
// fetchSuggestedQuestions, // fetchSuggestedQuestions,
handleNewConversationCompleted, // handleNewConversationCompleted,
], ],
) )
const sendMessage: OnSendMessage = useCallback( const sendMessage: OnSendMessage = useCallback((message, type, files, parentMessageId) => {
(message, type, files, parentMessageId) => {
doSend({ doSend({
messageObj: { messageObj: {
message, message,
...@@ -605,9 +603,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -605,9 +603,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
parentMessageId, parentMessageId,
}) })
disablePracticeTags() disablePracticeTags()
}, }, [])
[doSend],
)
const disablePracticeTags = useCallback(() => { const disablePracticeTags = useCallback(() => {
const lastTag = Array.from(document.querySelectorAll('.practice-tags')).pop() const lastTag = Array.from(document.querySelectorAll('.practice-tags')).pop()
...@@ -616,14 +612,15 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -616,14 +612,15 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
}, []) }, [])
const doRegenerate = useCallback( const doRegenerate = useCallback(
(chatItem: ChatItemInTree) => sendMessage('', undefined, undefined, chatItem.parentMessageId!), (chatItem: ChatItemInTree) => sendMessage('', undefined, undefined, chatItem.parentMessageId!),
[sendMessage], [],
) )
useEffect(() => { useEffect(() => {
if (clearChatList) handleRestart(() => setClearChatList?.(false)) if (clearChatList) handleRestart(() => setClearChatList?.(false))
}, [clearChatList, setClearChatList, handleRestart]) }, [clearChatList, setClearChatList, handleRestart])
return { return useMemo(
() => ({
config, config,
chatList, chatList,
handleStop, handleStop,
...@@ -636,5 +633,20 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -636,5 +633,20 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
appInfoLoading, appInfoLoading,
suggestedQuestions, suggestedQuestions,
handleNewConversation, handleNewConversation,
} }),
[
config,
chatList,
handleStop,
sendMessage,
doRegenerate,
appInfoError,
isResponding,
handleRestart,
handleFeedback,
appInfoLoading,
suggestedQuestions,
handleNewConversation,
],
)
} }
...@@ -5,7 +5,7 @@ import cn from '@/utils/classnames' ...@@ -5,7 +5,7 @@ import cn from '@/utils/classnames'
import { useChatBodyContext } from '../../body/context' import { useChatBodyContext } from '../../body/context'
const BasicContent: FC = () => { const BasicContent: FC = () => {
const { annotation, content,isError,hasAgentThoughts } = useChatBodyContext() const { annotation, content,isError,hasAgentThoughts } = useChatBodyContext()
if(!content || hasAgentThoughts) return null if(!content.trim() || hasAgentThoughts) return null
if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} /> if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} />
return <Markdown className={cn(isError && '!text-[#F04438]')} content={content} /> return <Markdown className={cn(isError && '!text-[#F04438]')} content={content} />
} }
......
...@@ -4,7 +4,7 @@ import LoadingAnim from '@/app/components/base/chat/chat/answer/components/loadi ...@@ -4,7 +4,7 @@ import LoadingAnim from '@/app/components/base/chat/chat/answer/components/loadi
import { useChatBodyContext } from '../../body/context' import { useChatBodyContext } from '../../body/context'
const LoadingText: FC = () => { const LoadingText: FC = () => {
const { responding,content ,hasAgentThoughts } = useChatBodyContext() const { responding,content ,hasAgentThoughts } = useChatBodyContext()
if (!responding || content|| hasAgentThoughts) return null if (!responding || content.trim()|| hasAgentThoughts) return null
return ( return (
<div className="flex h-5 w-6 items-center justify-center"> <div className="flex h-5 w-6 items-center justify-center">
<LoadingAnim type="text" /> <LoadingAnim type="text" />
......
...@@ -15,7 +15,6 @@ const FeedbackActive: FC = () => { ...@@ -15,7 +15,6 @@ const FeedbackActive: FC = () => {
() => supportFeedback && localFeedback?.rating && !isOpeningStatement, () => supportFeedback && localFeedback?.rating && !isOpeningStatement,
[supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement], [supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
) )
return useMemo(() => {
if (!feedbackActive) return null if (!feedbackActive) return null
return ( return (
<div className="ml-1 flex items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm"> <div className="ml-1 flex items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm">
...@@ -31,7 +30,6 @@ const FeedbackActive: FC = () => { ...@@ -31,7 +30,6 @@ const FeedbackActive: FC = () => {
)} )}
</div> </div>
) )
}, [feedbackActive])
} }
export default FeedbackActive export default FeedbackActive
...@@ -9,15 +9,13 @@ import { useChatConfigContext } from '../../../../chat-with-history/context/chat ...@@ -9,15 +9,13 @@ import { useChatConfigContext } from '../../../../chat-with-history/context/chat
const Feedback: FC = () => { const Feedback: FC = () => {
const { onFeedback } = useChatContext() const { onFeedback } = useChatContext()
const { supportFeedback } = useChatConfigContext() const { supportFeedback } = useChatConfigContext()
const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext() const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext()
// 判断反馈按钮是否启用 // 判断反馈按钮是否启用
const feedbackEnabled = useMemo( const feedbackEnabled = useMemo(
() => supportFeedback && !localFeedback?.rating && !isOpeningStatement, () => supportFeedback && !localFeedback?.rating && !isOpeningStatement,
[supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement], [supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
) )
return useMemo(() => { if (!feedbackEnabled) return null
if (feedbackEnabled) {
return ( return (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex"> <div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
<ActionButton onClick={() => handleFeedback('like')}> <ActionButton onClick={() => handleFeedback('like')}>
...@@ -28,8 +26,6 @@ const Feedback: FC = () => { ...@@ -28,8 +26,6 @@ const Feedback: FC = () => {
</ActionButton> </ActionButton>
</div> </div>
) )
}
}, [feedbackEnabled])
} }
export default Feedback export default Feedback
...@@ -6,7 +6,6 @@ import Regenerate from './regenerate' ...@@ -6,7 +6,6 @@ import Regenerate from './regenerate'
import Reply from './reply' import Reply from './reply'
const OperationButtons: FC = memo(() => { const OperationButtons: FC = memo(() => {
const { isOpeningStatement } = useOperationContext() const { isOpeningStatement } = useOperationContext()
return useMemo(() => {
if (isOpeningStatement) return null if (isOpeningStatement) return null
return ( return (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex"> <div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
...@@ -15,6 +14,5 @@ const OperationButtons: FC = memo(() => { ...@@ -15,6 +14,5 @@ const OperationButtons: FC = memo(() => {
<Reply /> <Reply />
</div> </div>
) )
}, [isOpeningStatement])
}) })
export default OperationButtons export default OperationButtons
...@@ -13,7 +13,6 @@ const OperationWrapper: FC<OperationWrapperProps> = ({ children }) => { ...@@ -13,7 +13,6 @@ const OperationWrapper: FC<OperationWrapperProps> = ({ children }) => {
const { contentWidth, workflowProcess } = useChatBodyContext() const { contentWidth, workflowProcess } = useChatBodyContext()
const hasWorkflowProcess = !!workflowProcess const hasWorkflowProcess = !!workflowProcess
return ( return (
<>
<div <div
className={cn( className={cn(
'absolute flex justify-end gap-1', 'absolute flex justify-end gap-1',
...@@ -25,7 +24,6 @@ const OperationWrapper: FC<OperationWrapperProps> = ({ children }) => { ...@@ -25,7 +24,6 @@ const OperationWrapper: FC<OperationWrapperProps> = ({ children }) => {
style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}> style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}>
{children} {children}
</div> </div>
</>
) )
} }
......
...@@ -2,7 +2,7 @@ import React, { createContext, useContext, useState, useEffect, useRef } from 'r ...@@ -2,7 +2,7 @@ import React, { createContext, useContext, useState, useEffect, useRef } from 'r
import { useChatContext } from '../../../chat-with-history/context/chat-context' import { useChatContext } from '../../../chat-with-history/context/chat-context'
import { MessageMore } from '../../type' import { MessageMore } from '../../type'
import { ChatItem } from '../../../types' import { ChatItem } from '../../../types'
import { useChatRuntimeContext } from '../../../chat-with-history/context/chat-runtime-context' import { useChatRespondingContext } from '@/app/components/base/chat/chat-with-history/context'
// 定义 AnswerContext 的类型 // 定义 AnswerContext 的类型
interface AnswerContextType { interface AnswerContextType {
...@@ -71,7 +71,7 @@ export const AnswerProvider: React.FC<AnswerProviderProps> = ({ ...@@ -71,7 +71,7 @@ export const AnswerProvider: React.FC<AnswerProviderProps> = ({
const [contentWidth, setContentWidth] = useState(0) const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null) const contentRef = useRef<HTMLDivElement>(null)
const { isResponding } = useChatRuntimeContext() const { isResponding } = useChatRespondingContext()
const responding = isLast && isResponding const responding = isLast && isResponding
const getContainerWidth = () => { const getContainerWidth = () => {
......
import React, { createContext, useContext, useState, useEffect, useRef, use, useCallback, useMemo } from 'react' import React, { createContext, useContext, useState, useEffect, useRef, use, useCallback, useMemo } from 'react'
import { useChatContext } from '../../chat-with-history/context/chat-context'
import { MessageMore } from '../type' import { MessageMore } from '../type'
import { ChatItem } from '../../types' import { ChatItem } from '../../types'
import { useChatRuntimeContext } from '../../chat-with-history/context/chat-runtime-context' import { useChatListContext, useChatRespondingContext } from '@/app/components/base/chat/chat-with-history/context'
// 定义 AnswerContext 的类型 // 定义 AnswerContext 的类型
interface ChatBodyContextType { interface ChatBodyContextType {
containerWidth: number containerWidth: number
...@@ -30,9 +28,9 @@ interface ChatBodyContextType { ...@@ -30,9 +28,9 @@ interface ChatBodyContextType {
isOpeningStatement: boolean isOpeningStatement: boolean
isError: ChatItem['isError'] isError: ChatItem['isError']
more: MessageMore | undefined more: MessageMore | undefined
theme?: any, theme?: any
isAnswer: boolean, isAnswer: boolean
parentMessageId:ChatItem['parentMessageId'] parentMessageId: ChatItem['parentMessageId']
} }
// 创建 AnswerContext // 创建 AnswerContext
...@@ -90,13 +88,14 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -90,13 +88,14 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
const [contentWidth, setContentWidth] = useState(0) const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null) const contentRef = useRef<HTMLDivElement>(null)
const { isResponding, chatList } = useChatRuntimeContext() const { isResponding } = useChatRespondingContext()
const { chatList } = useChatListContext()
const isLast = isAnswer && item.id === chatList[chatList.length - 1]?.id const isLast = isAnswer && item.id === chatList[chatList.length - 1]?.id
const responding = isLast && isResponding const responding = isLast && isResponding
const getContainerWidth = useCallback(() => { const getContainerWidth = useCallback(() => {
if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16) if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16)
},[containerRef,setContainerWidth]) }, [containerRef, setContainerWidth])
useEffect(() => { useEffect(() => {
getContainerWidth() getContainerWidth()
...@@ -104,7 +103,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -104,7 +103,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
const getContentWidth = useCallback(() => { const getContentWidth = useCallback(() => {
if (contentRef.current) setContentWidth(contentRef.current?.clientWidth) if (contentRef.current) setContentWidth(contentRef.current?.clientWidth)
},[contentRef,setContentWidth]) }, [contentRef, setContentWidth])
useEffect(() => { useEffect(() => {
if (!responding) getContentWidth() if (!responding) getContentWidth()
...@@ -121,7 +120,8 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -121,7 +120,8 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
resizeObserver.disconnect() resizeObserver.disconnect()
} }
}, []) }, [])
const value = useMemo(() =>({ const value = useMemo(
() => ({
id, id,
isOpeningStatement: !!isOpeningStatement, isOpeningStatement: !!isOpeningStatement,
containerWidth, containerWidth,
...@@ -148,15 +148,10 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -148,15 +148,10 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
theme, theme,
isAnswer, isAnswer,
content, content,
parentMessageId parentMessageId,
}),[ }),
id, [content, isAnswer, isLast, isError, responding],
content, )
isAnswer,
isLast,
isError,
responding
])
return <ChatBodyContext.Provider value={value}>{children}</ChatBodyContext.Provider> return <ChatBodyContext.Provider value={value}>{children}</ChatBodyContext.Provider>
} }
import { memo, FC, useEffect, ReactNode } from 'react' import { memo, FC, useEffect, ReactNode } from 'react'
import Answer from '@/app/components/base/chat/chat/answer' import Answer from '@/app/components/base/chat/chat/answer'
import Question from '@/app/components/base/chat/chat/question/question' import Question from '@/app/components/base/chat/chat/question/question'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { ChatBodyProvider } from '@/app/components/base/chat/chat/body/context' import { ChatBodyProvider } from '@/app/components/base/chat/chat/body/context'
import { useChatRuntimeContext } from '../../chat-with-history/context/chat-runtime-context' import { useChatListContext } from '@/app/components/base/chat/chat-with-history/context'
type ChatBodyProps = { type ChatBodyProps = {
noChatInput?: boolean noChatInput?: boolean
} }
const ChatBody: FC<ChatBodyProps> = ({ noChatInput }) => { const ChatBody: FC<ChatBodyProps> = ({ noChatInput }) => {
// const chatList = useChatStore(state=>state.chatList) const { chatList } = useChatListContext()
const { chatList } = useChatRuntimeContext()
return ( return (
<> <>
{chatList.map((item, index) => ( {chatList.map((item, index) => (
......
import Confirm from '@/app/components/base/confirm' import Confirm from '@/app/components/base/confirm'
import { useToastContext } from '@/app/components/base/toast' import { useToastContext } from '@/app/components/base/toast'
import { FC, memo, useCallback, useState } from 'react' import { FC, memo, useCallback, useState } from 'react'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
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 { useChatRuntimeContext } from '@/app/components/base/chat/chat-with-history/context/chat-runtime-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()
const { onRestart: restartChat } = useChatContext() const { onRestart: restartChat } = useChatContext()
const { isResponding } = useChatRuntimeContext () const { isResponding } = useChatRespondingContext()
const [showConfirm, setShowConfirm] = useState<boolean>(false) const [showConfirm, setShowConfirm] = useState<boolean>(false)
const handleRestart = useCallback(() => { const handleRestart = useCallback(() => {
if (isResponding) { if (isResponding) {
......
...@@ -2,14 +2,11 @@ import { FC, memo, useMemo } from 'react' ...@@ -2,14 +2,11 @@ import { FC, memo, useMemo } from 'react'
import Button from '@/app/components/base/button' 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 '@/app/components/base/chat/chat-with-history/context/chat-context' import { useChatRespondingContext,useChatContext } from '@/app/components/base/chat/chat-with-history/context'
import { useChatRuntimeContext } from '../../../chat-with-history/context/chat-runtime-context'
const StopRespondingButton: FC = () => { const StopRespondingButton: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { onStopResponding: stopResponding } = useChatContext() const { onStopResponding: stopResponding } = useChatContext()
const { isResponding } = useChatRuntimeContext() const { isResponding } = useChatRespondingContext()
const mc = useMemo(() => {
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">
...@@ -19,8 +16,6 @@ const StopRespondingButton: FC = () => { ...@@ -19,8 +16,6 @@ const StopRespondingButton: FC = () => {
</Button> </Button>
</div> </div>
) )
}, [isResponding])
return mc
} }
export default StopRespondingButton export default StopRespondingButton
import { createContext, useContext, useState, useCallback, useMemo } from 'react' import { createContext, useContext, useState, useCallback, useMemo } from 'react'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { useChatContext } from '../../chat-with-history/context/chat-context'
import { useToastContext } from '@/app/components/base/toast' import { useToastContext } from '@/app/components/base/toast'
import { useFileStore } from '@/app/components/base/file-uploader/store' import { useFileStore } from '@/app/components/base/file-uploader/store'
import { TransferMethod } from '@/types/app' import { TransferMethod } from '@/types/app'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { InputMessageType } from '../../types' import { InputMessageType } from '../../types'
import { useChatRuntimeContext } from '../../chat-with-history/context/chat-runtime-context' import { useChatContext, useChatRespondingContext } from '@/app/components/base/chat/chat-with-history/context/index'
// 定义消息上下文类型 // 定义消息上下文类型
interface MessageContextType { interface MessageContextType {
query: string query: string
...@@ -36,7 +34,7 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => { ...@@ -36,7 +34,7 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => {
const { t } = useTranslation() const { t } = useTranslation()
const [query, setQuery] = useState('') const [query, setQuery] = useState('')
const [showVoiceInput, setShowVoiceInput] = useState(false) const [showVoiceInput, setShowVoiceInput] = useState(false)
const { isResponding } = useChatRuntimeContext() const { isResponding } = useChatRespondingContext()
const { onSend: sendMessage } = useChatContext() const { onSend: sendMessage } = useChatContext()
const { notify } = useToastContext() const { notify } = useToastContext()
const filesStore = useFileStore() const filesStore = useFileStore()
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @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-15 20:45:57 * @LastEditTime: 2025-07-16 18:48:45
* @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
*/ */
...@@ -25,19 +25,18 @@ const Chat: FC<ChatProps> = () => { ...@@ -25,19 +25,18 @@ const Chat: FC<ChatProps> = () => {
const chatContainerInnerRef = useRef<HTMLDivElement>(null) const chatContainerInnerRef = useRef<HTMLDivElement>(null)
const chatFooterRef = useRef<HTMLDivElement>(null) const chatFooterRef = useRef<HTMLDivElement>(null)
const chatFooterInnerRef = useRef<HTMLDivElement>(null) const chatFooterInnerRef = useRef<HTMLDivElement>(null)
const userScrolledRef = useRef(false)
const tickingRef = useRef(false)
const lastScrollHeightRef = useRef(0) const lastScrollHeightRef = useRef(0)
const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} /> // const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} />
const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} /> // const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} />
const isMobile = useBreakpoints() === MediaType.mobile const isMobile = useBreakpoints() === MediaType.mobile
const handleScrollToBottom = () => { const handleScrollToBottom = () => {
const container = chatContainerRef.current const container = chatContainerRef.current
if (!container) return if (!container) return
const curScrollHeight = container.scrollHeight const curScrollHeight = container.scrollHeight
if (curScrollHeight > lastScrollHeightRef.current) { const lastScrollHeigh = lastScrollHeightRef.current
if (curScrollHeight !== lastScrollHeigh) {
lastScrollHeightRef.current = curScrollHeight lastScrollHeightRef.current = curScrollHeight
requestAnimationFrame(() => { requestAnimationFrame(() => {
// 添加平滑滚动效果 // 添加平滑滚动效果
...@@ -86,7 +85,7 @@ const Chat: FC<ChatProps> = () => { ...@@ -86,7 +85,7 @@ const Chat: FC<ChatProps> = () => {
chatFooterInnerRef={chatFooterInnerRef} chatFooterInnerRef={chatFooterInnerRef}
chatFooterClassName={chatFooterClassName} chatFooterClassName={chatFooterClassName}
chatFooterInnerClassName={chatFooterInnerClassName} chatFooterInnerClassName={chatFooterInnerClassName}
suggestedQuestions={[]} // suggestedQuestions={[]}
isMobile={isMobile} isMobile={isMobile}
// isShowPracticeButton={isShowPracticeButton} // isShowPracticeButton={isShowPracticeButton}
/> />
......
...@@ -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-07-16 00:00:32 * @LastEditTime: 2025-07-16 19:29:27
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-suggest.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\question\init-suggest.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
*/ */
...@@ -15,14 +15,14 @@ type InitSuggestProps = { ...@@ -15,14 +15,14 @@ type InitSuggestProps = {
suggestedQuestions?: string[] suggestedQuestions?: string[]
} }
const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions = [] }) => { const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions = [] }) => {
const { onSend: sendMessage } = useChatContext() const { onSend } = useChatContext()
return ( return (
<div className="w-[fit-content]"> <div className="w-[fit-content]">
{suggestedQuestions.map((question, index) => ( {suggestedQuestions.map((question, index) => (
<Button <Button
key={index} key={index}
text={question} text={question}
onClick={() => sendMessage?.(question, InputMessageType.QUESTION_IN_WELCOME)}></Button> onClick={() => onSend?.(question, InputMessageType.QUESTION_IN_WELCOME)}></Button>
))} ))}
</div> </div>
) )
......
...@@ -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-07-15 10:59:21 * @LastEditTime: 2025-07-16 20:36:58
* @FilePath: \ai-assistant\app\components\base\chat\chat\question\question.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\question\question.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
*/ */
...@@ -18,9 +18,7 @@ import AnswerIcon from '@/app/components/base/answer-icon' ...@@ -18,9 +18,7 @@ import AnswerIcon from '@/app/components/base/answer-icon'
// icon:ReactNode // icon:ReactNode
// } // }
const Question: FC = () => { const Question: FC = () => {
const { content, theme, isAnswer } = useChatBodyContext() const { content, theme } = useChatBodyContext()
return useMemo(() => {
if (content && !isAnswer) {
return ( return (
<div className="mb-2 flex justify-end pl-14 last:mb-0"> <div className="mb-2 flex justify-end pl-14 last:mb-0">
<div className="group relative mr-4 max-w-full"> <div className="group relative mr-4 max-w-full">
...@@ -37,9 +35,5 @@ const Question: FC = () => { ...@@ -37,9 +35,5 @@ const Question: FC = () => {
</div> </div>
</div> </div>
) )
} else {
return null
}
}, [content, isAnswer])
} }
export default memo(Question) export default memo(Question)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!