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 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @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
* @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'
import { stopChatMessageResponding } from '@/service/share'
import { InputMessageType } from '../types'
import { useChatWithHistory } from './hooks'
import { ChatContextProvider } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { ChatRuntimeProvider } from './context/chat-runtime-context'
import { ChatConfigProvider } from './context/chat-config-context'
import {
ChatContextProvider,
ChatConfigProvider,
ChatListProvider,
ChatRespondingProvider,
} from '@/app/components/base/chat/chat-with-history/context'
enum MessageListenerType {
RESET_CHAT = 'reset_chat',
......@@ -85,6 +88,7 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
}
}
}, [])
return (
<div className="h-full overflow-hidden">
<ChatConfigProvider config={config}>
......@@ -92,11 +96,13 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
onSend={sendMessage}
onRegenerate={doRegenerate}
onRestart={handleRestart}
onStopResponding={handleStop}
onFeedback={handleFeedback}>
<ChatRuntimeProvider chatList={chatList} isResponding={isResponding}>
<Chat />
</ChatRuntimeProvider>
onFeedback={handleFeedback}
onStopResponding={handleStop}>
<ChatRespondingProvider isResponding={isResponding}>
<ChatListProvider chatList={chatList}>
<Chat />
</ChatListProvider>
</ChatRespondingProvider>
</ChatContextProvider>
</ChatConfigProvider>
</div>
......
'use client'
import { useMemo } from 'react'
import { useCallback, useMemo } from 'react'
import { createContext, useContext } from 'use-context-selector'
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'
export type OnSendMessage = (
message: string,
......@@ -45,9 +45,8 @@ export const ChatContextProvider = ({
onFeedback,
onStopResponding,
}),
[onSend, onRegenerate, onRestart, onFeedback, onStopResponding],
[],
)
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
}
......
......@@ -3,24 +3,23 @@
import { createContext, useContext } from 'use-context-selector'
import type { ChatItem } from '../../types'
import { useMemo } from 'react'
type RuntimeContext = {
type ChatListContext = {
chatList: ChatItem[]
isResponding?: boolean
}
const ChatRuntimeContext = createContext<RuntimeContext>({
const ChatListContext = createContext<ChatListContext>({
chatList: [],
isResponding: false,
})
export const useChatRuntimeContext = () => useContext(ChatRuntimeContext)
export const useChatListContext = () => useContext(ChatListContext)
type Props = {
children: React.ReactNode
} & RuntimeContext
} & ChatListContext
export const ChatRuntimeProvider = ({ children, chatList, isResponding }: Props) => {
const value = { chatList, isResponding }
return <ChatRuntimeContext.Provider value={value}>{children}</ChatRuntimeContext.Provider>
export const ChatListProvider = ({ children, chatList }: Props) => {
const value = { chatList }
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 = {
onConversationComplete?: (conversationId: string) => void
isPublicAPI?: boolean
}
type UpdateChatTreeNode = {
(id: string, fields: Partial<ChatItemInTree>): void
(id: string, update: (node: ChatItemInTree) => void): void
}
type UpdateChatTreeNode = {
(id: string, fields: Partial<ChatItemInTree>): void
(id: string, update: (node: ChatItemInTree) => void): void
}
export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, any> = {}) => {
const { t } = useTranslation()
const { notify } = useToastContext()
......@@ -79,7 +79,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
{ revalidateOnFocus: false },
)
const config = useMemo(() => {
const cfg = cloneDeep(appParams) || {}
const cfg = appParams || {}
return {
...cfg,
file_upload: {
......@@ -92,49 +92,46 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
} as ChatConfig
}, [appParams])
const handleNewConversation = useCallback(
(inputs?: Record<string, any>, isSkipClear: boolean = false) => {
currentChatInstanceRef.current.handleStop()
conversationId.current = ''
if (inputs) {
setNewConversationInputs(inputs)
}
if (!isSkipClear) {
setClearChatList(true)
}
},
[],
)
const handleNewConversationCompleted = useCallback(
(newConversationId: string) => {
conversationId.current = newConversationId
},
[conversationId],
)
const handleNewConversation = useCallback((inputs?: Record<string, any>, isSkipClear: boolean = false) => {
currentChatInstanceRef.current.handleStop()
conversationId.current = ''
if (inputs) {
setNewConversationInputs(inputs)
}
if (!isSkipClear) {
setChatTree([])
chatListRef.current = []
setClearChatList(true)
}
}, [])
const handleNewConversationCompleted = useCallback((newConversationId: string) => {
conversationId.current = newConversationId
}, [])
useEffect(() => {
if (currentChatInstanceRef.current) currentChatInstanceRef.current.handleStop = handleStop
}, [])
const handleFeedback = useCallback(
async (messageId: string, feedback: Feedback) => {
await updateFeedback(
{
url: `/messages/${messageId}/feedbacks`,
body: { rating: feedback.rating },
},
isInstalledApp,
appId,
)
notify({ type: 'success', message: t('common.api.success') })
},
[appId, t, notify],
)
const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
await updateFeedback(
{
url: `/messages/${messageId}/feedbacks`,
body: { rating: feedback.rating },
},
isInstalledApp,
appId,
)
notify({ type: 'success', message: t('common.api.success') })
}, [])
/** Final chat list that will be rendered */
const chatList = useMemo(() => {
return [...threadMessages]
}, [threadMessages])
const chatListRef = useRef<ChatItemInTree[]>(chatList)
useEffect(() => {
chatListRef.current = chatList
}, [chatList])
useEffect(() => {
setAutoFreeze(false)
......@@ -194,6 +191,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
(cb?: any) => {
conversationId.current = ''
taskIdRef.current = ''
chatListRef.current = []
handleStop()
setChatTree([])
setSuggestQuestions([])
......@@ -268,18 +266,19 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
* 判断是否重新生成 parentMessageId 有值则为重新生成,如果不是则为正常问题
*/
let parentMessage = null
if (parentMessageId) {
const question = threadMessages.find(item => item.id === parentMessageId)!
parentMessage = threadMessages.find(item => item.id === question.parentMessageId)
Object.assign(data, {
query: question.content,
files: question.message_files,
})
} else {
parentMessage = getLastAnswer(chatList)
if (conversationId.current) {
if (parentMessageId) {
const question = chatListRef.current.find(item => item.id === parentMessageId)!
parentMessage = chatListRef.current.find(item => item.id === question.parentMessageId)
Object.assign(data, {
query: question.content,
files: question.message_files,
})
} else {
parentMessage = getLastAnswer(chatListRef.current)
}
data.parent_message_id = parentMessage?.id
}
data.parent_message_id = parentMessage?.id
// const parentMessage = threadMessages.find(
// (item) => item.id === data.parent_message_id
// );
......@@ -551,9 +550,9 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
[
t,
// chatTree.length,
threadMessages,
// threadMessages,
// config?.suggested_questions_after_answer,
// updateCurrentQAOnTree,
updateCurrentQAOnTree,
// updateChatTreeNode,
notify,
// handleResponding,
......@@ -585,29 +584,26 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
)
},
[
handleSend,
// handleSend,
// appId,
// newConversationInputs,
// getUrl,
// fetchSuggestedQuestions,
handleNewConversationCompleted,
// handleNewConversationCompleted,
],
)
const sendMessage: OnSendMessage = useCallback(
(message, type, files, parentMessageId) => {
doSend({
messageObj: {
message,
type: type || InputMessageType.BY_HAND,
},
files,
parentMessageId,
})
disablePracticeTags()
},
[doSend],
)
const sendMessage: OnSendMessage = useCallback((message, type, files, parentMessageId) => {
doSend({
messageObj: {
message,
type: type || InputMessageType.BY_HAND,
},
files,
parentMessageId,
})
disablePracticeTags()
}, [])
const disablePracticeTags = useCallback(() => {
const lastTag = Array.from(document.querySelectorAll('.practice-tags')).pop()
......@@ -616,25 +612,41 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
}, [])
const doRegenerate = useCallback(
(chatItem: ChatItemInTree) => sendMessage('', undefined, undefined, chatItem.parentMessageId!),
[sendMessage],
[],
)
useEffect(() => {
if (clearChatList) handleRestart(() => setClearChatList?.(false))
}, [clearChatList, setClearChatList, handleRestart])
return {
config,
chatList,
handleStop,
sendMessage,
doRegenerate,
appInfoError,
isResponding,
handleRestart,
handleFeedback,
appInfoLoading,
suggestedQuestions,
handleNewConversation,
}
return useMemo(
() => ({
config,
chatList,
handleStop,
sendMessage,
doRegenerate,
appInfoError,
isResponding,
handleRestart,
handleFeedback,
appInfoLoading,
suggestedQuestions,
handleNewConversation,
}),
[
config,
chatList,
handleStop,
sendMessage,
doRegenerate,
appInfoError,
isResponding,
handleRestart,
handleFeedback,
appInfoLoading,
suggestedQuestions,
handleNewConversation,
],
)
}
......@@ -5,7 +5,7 @@ import cn from '@/utils/classnames'
import { useChatBodyContext } from '../../body/context'
const BasicContent: FC = () => {
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 || ''} />
return <Markdown className={cn(isError && '!text-[#F04438]')} content={content} />
}
......
......@@ -4,7 +4,7 @@ import LoadingAnim from '@/app/components/base/chat/chat/answer/components/loadi
import { useChatBodyContext } from '../../body/context'
const LoadingText: FC = () => {
const { responding,content ,hasAgentThoughts } = useChatBodyContext()
if (!responding || content|| hasAgentThoughts) return null
if (!responding || content.trim()|| hasAgentThoughts) return null
return (
<div className="flex h-5 w-6 items-center justify-center">
<LoadingAnim type="text" />
......
......@@ -15,7 +15,6 @@ const FeedbackActive: FC = () => {
() => supportFeedback && localFeedback?.rating && !isOpeningStatement,
[supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
)
return useMemo(() => {
if (!feedbackActive) return null
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">
......@@ -31,7 +30,6 @@ const FeedbackActive: FC = () => {
)}
</div>
)
}, [feedbackActive])
}
export default FeedbackActive
......@@ -7,29 +7,25 @@ import { useChatContext } from '../../../../chat-with-history/context/chat-conte
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const Feedback: FC = () => {
const { onFeedback } = useChatContext()
const { onFeedback } = useChatContext()
const { supportFeedback } = useChatConfigContext()
const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext()
// 判断反馈按钮是否启用
const feedbackEnabled = useMemo(
() => supportFeedback && !localFeedback?.rating && !isOpeningStatement,
[supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
)
return useMemo(() => {
if (feedbackEnabled) {
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">
<ActionButton onClick={() => handleFeedback('like')}>
<RiThumbUpLine className="h-4 w-4" />
</ActionButton>
<ActionButton onClick={() => handleFeedback('dislike')}>
<RiThumbDownLine className="h-4 w-4" />
</ActionButton>
</div>
)
}
}, [feedbackEnabled])
if (!feedbackEnabled) return null
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">
<ActionButton onClick={() => handleFeedback('like')}>
<RiThumbUpLine className="h-4 w-4" />
</ActionButton>
<ActionButton onClick={() => handleFeedback('dislike')}>
<RiThumbDownLine className="h-4 w-4" />
</ActionButton>
</div>
)
}
export default Feedback
......@@ -6,15 +6,13 @@ import Regenerate from './regenerate'
import Reply from './reply'
const OperationButtons: FC = memo(() => {
const { isOpeningStatement } = useOperationContext()
return useMemo(() => {
if (isOpeningStatement) return null
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">
<Copy />
<Regenerate />
<Reply />
</div>
)
}, [isOpeningStatement])
if (isOpeningStatement) return null
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">
<Copy />
<Regenerate />
<Reply />
</div>
)
})
export default OperationButtons
......@@ -13,19 +13,17 @@ const OperationWrapper: FC<OperationWrapperProps> = ({ children }) => {
const { contentWidth, workflowProcess } = useChatBodyContext()
const hasWorkflowProcess = !!workflowProcess
return (
<>
<div
className={cn(
'absolute flex justify-end gap-1',
hasWorkflowProcess && '-bottom-4 right-2',
!positionRight && '-bottom-4 right-2',
!hasWorkflowProcess && positionRight && '!top-[9px]',
!hasWorkflowProcess && positionRight ? 'left-auto' : '',
)}
style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}>
{children}
</div>
</>
<div
className={cn(
'absolute flex justify-end gap-1',
hasWorkflowProcess && '-bottom-4 right-2',
!positionRight && '-bottom-4 right-2',
!hasWorkflowProcess && positionRight && '!top-[9px]',
!hasWorkflowProcess && positionRight ? 'left-auto' : '',
)}
style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}>
{children}
</div>
)
}
......
......@@ -2,7 +2,7 @@ import React, { createContext, useContext, useState, useEffect, useRef } from 'r
import { useChatContext } from '../../../chat-with-history/context/chat-context'
import { MessageMore } from '../../type'
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 的类型
interface AnswerContextType {
......@@ -71,7 +71,7 @@ export const AnswerProvider: React.FC<AnswerProviderProps> = ({
const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const { isResponding } = useChatRuntimeContext()
const { isResponding } = useChatRespondingContext()
const responding = isLast && isResponding
const getContainerWidth = () => {
......
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 { 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 的类型
interface ChatBodyContextType {
containerWidth: number
......@@ -30,9 +28,9 @@ interface ChatBodyContextType {
isOpeningStatement: boolean
isError: ChatItem['isError']
more: MessageMore | undefined
theme?: any,
isAnswer: boolean,
parentMessageId:ChatItem['parentMessageId']
theme?: any
isAnswer: boolean
parentMessageId: ChatItem['parentMessageId']
}
// 创建 AnswerContext
......@@ -90,13 +88,14 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
const [contentWidth, setContentWidth] = useState(0)
const containerRef = 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 responding = isLast && isResponding
const getContainerWidth = useCallback(() => {
if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16)
},[containerRef,setContainerWidth])
}, [containerRef, setContainerWidth])
useEffect(() => {
getContainerWidth()
......@@ -104,7 +103,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
const getContentWidth = useCallback(() => {
if (contentRef.current) setContentWidth(contentRef.current?.clientWidth)
},[contentRef,setContentWidth])
}, [contentRef, setContentWidth])
useEffect(() => {
if (!responding) getContentWidth()
......@@ -121,42 +120,38 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
resizeObserver.disconnect()
}
}, [])
const value = useMemo(() =>({
id,
isOpeningStatement: !!isOpeningStatement,
containerWidth,
contentWidth,
responding: !!responding,
hasAgentThoughts,
citation,
more,
annotation,
workflowProcess,
allFiles,
message_files,
index,
question,
isLast,
noChatInput,
showPromptLog,
containerRef,
contentRef,
agent_thoughts,
feedback,
adminFeedback,
isError,
theme,
isAnswer,
content,
parentMessageId
}),[
id,
content,
isAnswer,
isLast,
isError,
responding
])
const value = useMemo(
() => ({
id,
isOpeningStatement: !!isOpeningStatement,
containerWidth,
contentWidth,
responding: !!responding,
hasAgentThoughts,
citation,
more,
annotation,
workflowProcess,
allFiles,
message_files,
index,
question,
isLast,
noChatInput,
showPromptLog,
containerRef,
contentRef,
agent_thoughts,
feedback,
adminFeedback,
isError,
theme,
isAnswer,
content,
parentMessageId,
}),
[content, isAnswer, isLast, isError, responding],
)
return <ChatBodyContext.Provider value={value}>{children}</ChatBodyContext.Provider>
}
import { memo, FC, useEffect, ReactNode } from 'react'
import Answer from '@/app/components/base/chat/chat/answer'
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 { useChatRuntimeContext } from '../../chat-with-history/context/chat-runtime-context'
import { useChatListContext } from '@/app/components/base/chat/chat-with-history/context'
type ChatBodyProps = {
noChatInput?: boolean
}
const ChatBody: FC<ChatBodyProps> = ({ noChatInput }) => {
// const chatList = useChatStore(state=>state.chatList)
const { chatList } = useChatRuntimeContext()
const { chatList } = useChatListContext()
return (
<>
{chatList.map((item, index) => (
......
import Confirm from '@/app/components/base/confirm'
import { useToastContext } from '@/app/components/base/toast'
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 { 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 { t } = useTranslation()
const { notify } = useToastContext()
const { onRestart: restartChat } = useChatContext()
const { isResponding } = useChatRuntimeContext ()
const { isResponding } = useChatRespondingContext()
const [showConfirm, setShowConfirm] = useState<boolean>(false)
const handleRestart = useCallback(() => {
if (isResponding) {
......
......@@ -2,25 +2,20 @@ import { FC, memo, useMemo } from 'react'
import Button from '@/app/components/base/button'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import { useTranslation } from 'react-i18next'
import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatRuntimeContext } from '../../../chat-with-history/context/chat-runtime-context'
import { useChatRespondingContext,useChatContext } from '@/app/components/base/chat/chat-with-history/context'
const StopRespondingButton: FC = () => {
const { t } = useTranslation()
const { onStopResponding: stopResponding } = useChatContext()
const { isResponding } = useChatRuntimeContext()
const mc = useMemo(() => {
if (!isResponding) return null
return (
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
<Button onClick={stopResponding}>
<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>
</Button>
</div>
)
}, [isResponding])
return mc
const { isResponding } = useChatRespondingContext()
if (!isResponding) return null
return (
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
<Button onClick={stopResponding}>
<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>
</Button>
</div>
)
}
export default StopRespondingButton
import { createContext, useContext, useState, useCallback, useMemo } from 'react'
import type { ReactNode } from 'react'
import { useChatContext } from '../../chat-with-history/context/chat-context'
import { useToastContext } from '@/app/components/base/toast'
import { useFileStore } from '@/app/components/base/file-uploader/store'
import { TransferMethod } from '@/types/app'
import { useTranslation } from 'react-i18next'
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 {
query: string
......@@ -36,7 +34,7 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => {
const { t } = useTranslation()
const [query, setQuery] = useState('')
const [showVoiceInput, setShowVoiceInput] = useState(false)
const { isResponding } = useChatRuntimeContext()
const { isResponding } = useChatRespondingContext()
const { onSend: sendMessage } = useChatContext()
const { notify } = useToastContext()
const filesStore = useFileStore()
......
......@@ -2,7 +2,7 @@
* @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38
* @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
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
......@@ -25,19 +25,18 @@ const Chat: FC<ChatProps> = () => {
const chatContainerInnerRef = useRef<HTMLDivElement>(null)
const chatFooterRef = useRef<HTMLDivElement>(null)
const chatFooterInnerRef = useRef<HTMLDivElement>(null)
const userScrolledRef = useRef(false)
const tickingRef = useRef(false)
const lastScrollHeightRef = useRef(0)
const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} />
const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} />
// const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} />
// const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} />
const isMobile = useBreakpoints() === MediaType.mobile
const handleScrollToBottom = () => {
const container = chatContainerRef.current
if (!container) return
const curScrollHeight = container.scrollHeight
if (curScrollHeight > lastScrollHeightRef.current) {
const lastScrollHeigh = lastScrollHeightRef.current
if (curScrollHeight !== lastScrollHeigh) {
lastScrollHeightRef.current = curScrollHeight
requestAnimationFrame(() => {
// 添加平滑滚动效果
......@@ -86,7 +85,7 @@ const Chat: FC<ChatProps> = () => {
chatFooterInnerRef={chatFooterInnerRef}
chatFooterClassName={chatFooterClassName}
chatFooterInnerClassName={chatFooterInnerClassName}
suggestedQuestions={[]}
// suggestedQuestions={[]}
isMobile={isMobile}
// isShowPracticeButton={isShowPracticeButton}
/>
......
......@@ -2,7 +2,7 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @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
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
......@@ -15,14 +15,14 @@ type InitSuggestProps = {
suggestedQuestions?: string[]
}
const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions = [] }) => {
const { onSend: sendMessage } = useChatContext()
const { onSend } = useChatContext()
return (
<div className="w-[fit-content]">
{suggestedQuestions.map((question, index) => (
<Button
key={index}
text={question}
onClick={() => sendMessage?.(question, InputMessageType.QUESTION_IN_WELCOME)}></Button>
onClick={() => onSend?.(question, InputMessageType.QUESTION_IN_WELCOME)}></Button>
))}
</div>
)
......
......@@ -2,7 +2,7 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @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
* @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'
// icon:ReactNode
// }
const Question: FC = () => {
const { content, theme, isAnswer } = useChatBodyContext()
return useMemo(() => {
if (content && !isAnswer) {
return (
<div className="mb-2 flex justify-end pl-14 last:mb-0">
<div className="group relative mr-4 max-w-full">
<div
className="rounded-2xl bg-[#D1E9FF]/50 px-4 py-3 text-sm text-gray-900"
style={theme?.chatBubbleColorStyle ? CssTransform(theme?.chatBubbleColorStyle) : {}}>
{/* {!!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>
const { content, theme } = useChatBodyContext()
return (
<div className="mb-2 flex justify-end pl-14 last:mb-0">
<div className="group relative mr-4 max-w-full">
<div
className="rounded-2xl bg-[#D1E9FF]/50 px-4 py-3 text-sm text-gray-900"
style={theme?.chatBubbleColorStyle ? CssTransform(theme?.chatBubbleColorStyle) : {}}>
{/* {!!message_files?.length && <FileList files={message_files} showDeleteAction={false} showDownloadAction={true} />} */}
<Markdown content={content} />
</div>
)
} else {
return null
}
}, [content, isAnswer])
<div className="mt-1 h-[8px]" />
</div>
<div className="h-10 w-10 shrink-0">
<AnswerIcon imageUrl={AVATAR_USER_URL} />
</div>
</div>
)
}
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!