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 268 additions and 254 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}>
<Chat /> <ChatListProvider chatList={chatList}>
</ChatRuntimeProvider> <Chat />
</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,49 +92,46 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -92,49 +92,46 @@ 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([])
setClearChatList(true) chatListRef.current = []
} setClearChatList(true)
}, }
[], }, [])
) const handleNewConversationCompleted = useCallback((newConversationId: string) => {
const handleNewConversationCompleted = useCallback( conversationId.current = newConversationId
(newConversationId: string) => { }, [])
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`, body: { rating: feedback.rating },
body: { rating: feedback.rating }, },
}, isInstalledApp,
isInstalledApp, 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 (parentMessageId) { if (conversationId.current) {
const question = threadMessages.find(item => item.id === parentMessageId)! if (parentMessageId) {
parentMessage = threadMessages.find(item => item.id === question.parentMessageId) const question = chatListRef.current.find(item => item.id === parentMessageId)!
Object.assign(data, { parentMessage = chatListRef.current.find(item => item.id === question.parentMessageId)
query: question.content, Object.assign(data, {
files: question.message_files, query: question.content,
}) files: question.message_files,
} else { })
parentMessage = getLastAnswer(chatList) } else {
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,29 +584,26 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -585,29 +584,26 @@ 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, type: type || InputMessageType.BY_HAND,
type: type || InputMessageType.BY_HAND, },
}, files,
files, 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,25 +612,41 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -616,25 +612,41 @@ 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, () => ({
chatList, config,
handleStop, chatList,
sendMessage, handleStop,
doRegenerate, sendMessage,
appInfoError, doRegenerate,
isResponding, appInfoError,
handleRestart, isResponding,
handleFeedback, handleRestart,
appInfoLoading, handleFeedback,
suggestedQuestions, appInfoLoading,
handleNewConversation, suggestedQuestions,
} 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
...@@ -7,29 +7,25 @@ import { useChatContext } from '../../../../chat-with-history/context/chat-conte ...@@ -7,29 +7,25 @@ import { useChatContext } from '../../../../chat-with-history/context/chat-conte
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context' import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
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')}> <RiThumbUpLine className="h-4 w-4" />
<RiThumbUpLine className="h-4 w-4" /> </ActionButton>
</ActionButton> <ActionButton onClick={() => handleFeedback('dislike')}>
<ActionButton onClick={() => handleFeedback('dislike')}> <RiThumbDownLine className="h-4 w-4" />
<RiThumbDownLine className="h-4 w-4" /> </ActionButton>
</ActionButton> </div>
</div> )
)
}
}, [feedbackEnabled])
} }
export default Feedback export default Feedback
...@@ -6,15 +6,13 @@ import Regenerate from './regenerate' ...@@ -6,15 +6,13 @@ 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"> <Copy />
<Copy /> <Regenerate />
<Regenerate /> <Reply />
<Reply /> </div>
</div> )
)
}, [isOpeningStatement])
}) })
export default OperationButtons export default OperationButtons
...@@ -13,19 +13,17 @@ const OperationWrapper: FC<OperationWrapperProps> = ({ children }) => { ...@@ -13,19 +13,17 @@ 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', hasWorkflowProcess && '-bottom-4 right-2',
hasWorkflowProcess && '-bottom-4 right-2', !positionRight && '-bottom-4 right-2',
!positionRight && '-bottom-4 right-2', !hasWorkflowProcess && positionRight && '!top-[9px]',
!hasWorkflowProcess && positionRight && '!top-[9px]', !hasWorkflowProcess && positionRight ? 'left-auto' : '',
!hasWorkflowProcess && positionRight ? 'left-auto' : '', )}
)} 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,42 +120,38 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -121,42 +120,38 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
resizeObserver.disconnect() resizeObserver.disconnect()
} }
}, []) }, [])
const value = useMemo(() =>({ const value = useMemo(
id, () => ({
isOpeningStatement: !!isOpeningStatement, id,
containerWidth, isOpeningStatement: !!isOpeningStatement,
contentWidth, containerWidth,
responding: !!responding, contentWidth,
hasAgentThoughts, responding: !!responding,
citation, hasAgentThoughts,
more, citation,
annotation, more,
workflowProcess, annotation,
allFiles, workflowProcess,
message_files, allFiles,
index, message_files,
question, index,
isLast, question,
noChatInput, isLast,
showPromptLog, noChatInput,
containerRef, showPromptLog,
contentRef, containerRef,
agent_thoughts, contentRef,
feedback, agent_thoughts,
adminFeedback, feedback,
isError, adminFeedback,
theme, isError,
isAnswer, theme,
content, isAnswer,
parentMessageId content,
}),[ parentMessageId,
id, }),
content, [content, isAnswer, isLast, isError, responding],
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,25 +2,20 @@ import { FC, memo, useMemo } from 'react' ...@@ -2,25 +2,20 @@ 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()
if (!isResponding) return null
const mc = useMemo(() => { return (
if (!isResponding) return null <div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
return ( <Button onClick={stopResponding}>
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2"> <StopCircle className="mr-[5px] h-3.5 w-3.5 text-gray-500" />
<Button onClick={stopResponding}> <span className="text-xs font-normal text-gray-500">{t('appDebug.operation.stopResponding')}</span>
<StopCircle className="mr-[5px] h-3.5 w-3.5 text-gray-500" /> </Button>
<span className="text-xs font-normal text-gray-500">{t('appDebug.operation.stopResponding')}</span> </div>
</Button> )
</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,28 +18,22 @@ import AnswerIcon from '@/app/components/base/answer-icon' ...@@ -18,28 +18,22 @@ 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(() => { return (
if (content && !isAnswer) { <div className="mb-2 flex justify-end pl-14 last:mb-0">
return ( <div className="group relative mr-4 max-w-full">
<div className="mb-2 flex justify-end pl-14 last:mb-0"> <div
<div className="group relative mr-4 max-w-full"> className="rounded-2xl bg-[#D1E9FF]/50 px-4 py-3 text-sm text-gray-900"
<div style={theme?.chatBubbleColorStyle ? CssTransform(theme?.chatBubbleColorStyle) : {}}>
className="rounded-2xl bg-[#D1E9FF]/50 px-4 py-3 text-sm text-gray-900" {/* {!!message_files?.length && <FileList files={message_files} showDeleteAction={false} showDownloadAction={true} />} */}
style={theme?.chatBubbleColorStyle ? CssTransform(theme?.chatBubbleColorStyle) : {}}> <Markdown content={content} />
{/* {!!message_files?.length && <FileList files={message_files} showDeleteAction={false} showDownloadAction={true} />} */}
<Markdown content={content} />
</div>
<div className="mt-1 h-[8px]" />
</div>
<div className="h-10 w-10 shrink-0">
<AnswerIcon imageUrl={AVATAR_USER_URL} />
</div>
</div> </div>
) <div className="mt-1 h-[8px]" />
} else { </div>
return null <div className="h-10 w-10 shrink-0">
} <AnswerIcon imageUrl={AVATAR_USER_URL} />
}, [content, isAnswer]) </div>
</div>
)
} }
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!