Commit d4cafcfe by liimin

refactor(chat): 重构聊天组件的上下文结构

- 将 ChatContext 分为三个独立的上下文:
  - ChatConfigContext: 包含聊天配置
  - ChatRuntimeContext: 包含聊天运行时数据和方法
  - ChatOperationContext: 包含聊天操作相关数据
- 更新了相关组件和文件,使其使用新的上下文结构
- 删除了不必要的代码和导入,简化了代码结构
1 parent c09e9442
Showing 36 changed files with 226 additions and 579 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-10 19:56:41 * @LastEditTime: 2025-07-15 23:45:09
* @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,7 +15,9 @@ import AppUnavailable from '@/app/components/base/app-unavailable' ...@@ -15,7 +15,9 @@ 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/context' 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'
enum MessageListenerType { enum MessageListenerType {
RESET_CHAT = 'reset_chat', RESET_CHAT = 'reset_chat',
...@@ -44,14 +46,14 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -44,14 +46,14 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
handleStop, handleStop,
sendMessage, sendMessage,
doRegenerate, doRegenerate,
appInfoError, // appInfoError,
isResponding, isResponding,
handleRestart, handleRestart,
handleFeedback, handleFeedback,
appInfoLoading, // appInfoLoading,
handleNewConversation, handleNewConversation,
} = useChat(undefined, inputs) } = useChat(undefined, inputs)
useEffect(() => { useEffect(() => {
if (presuppositionQuestion) { if (presuppositionQuestion) {
sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO) sendMessage(presuppositionQuestion, InputMessageType.BY_AUTO)
...@@ -84,25 +86,20 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice ...@@ -84,25 +86,20 @@ const ChatWrapper: FC<Props> = ({ presuppositionQuestion, inputs, isShowPractice
} }
}, []) }, [])
return ( return (
<> <div className="h-full overflow-hidden">
{appInfoLoading && <Loading type="app" />} <ChatConfigProvider config={config}>
{appInfoError && <AppUnavailable />} <ChatContextProvider
{!appInfoLoading && !appInfoError && ( onSend={sendMessage}
<div className="h-full overflow-hidden"> onRegenerate={doRegenerate}
<ChatContextProvider onRestart={handleRestart}
config={config} onStopResponding={handleStop}
chatList={chatList} onFeedback={handleFeedback}>
isResponding={isResponding} <ChatRuntimeProvider chatList={chatList} isResponding={isResponding}>
onSend={sendMessage} <Chat />
onRegenerate={doRegenerate} </ChatRuntimeProvider>
onRestart={handleRestart} </ChatContextProvider>
onStopResponding={handleStop} </ChatConfigProvider>
onFeedback={handleFeedback}> </div>
<Chat/>
</ChatContextProvider>
</div>
)}
</>
) )
} }
......
// app/components/base/chat/chat/chat-config-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ChatConfig } from '../../types'
import { useMemo } from 'react'
const ChatConfigContext = createContext<ChatConfig>({} as ChatConfig)
type Props = {
children: React.ReactNode
config: ChatConfig
}
export const ChatConfigProvider = ({ children, config }: Props) => {
// 只暴露你真正关心的字段(可根据需要扩展)
const value = useMemo(
() => ({
appId: config.appId,
initial_message: config.initial_message,
suggested_questions: config.suggested_questions,
file_upload: config.file_upload,
supportFeedback: config.supportFeedback,
opening_statement: config.opening_statement,
supportAnnotation: config.supportAnnotation,
supportCitationHitInfo: config.supportCitationHitInfo,
speech_to_text: config.speech_to_text,
}),
[config.initial_message],
) as ChatConfig
return <ChatConfigContext.Provider value={value}>{children}</ChatConfigContext.Provider>
}
export const useChatConfigContext = () => useContext(ChatConfigContext)
'use client' 'use client'
import { useMemo, type ReactNode } from 'react' import { 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 { ChatConfig, ChatItem, Feedback, InputMessageProp, InputMessageType, OnRegenerate, OnSend } from '../types' import type { Feedback, InputMessageType, OnRegenerate } from '@/app/components/base/chat/types'
import { FileEntity } from '../../file-uploader/types' import { FileEntity } from '@/app/components/base/file-uploader/types'
export type OnSendMessage = ( export type OnSendMessage = (
message: string, message: string,
type?: InputMessageType, type?: InputMessageType,
files?: FileEntity[], files?: FileEntity[],
parentMessageId?: string, parentMessageId?: string,
) => void ) => void
export type ChatContextValue = { export type ChatContextValue = {
config: ChatConfig
chatList: ChatItem[]
isResponding?: boolean
onSend: OnSendMessage onSend: OnSendMessage
onRegenerate?: OnRegenerate onRegenerate?: OnRegenerate
onStopResponding?: () => void
onRestart: () => void onRestart: () => void
onFeedback?: (messageId: string, feedback: Feedback) => void onFeedback?: (messageId: string, feedback: Feedback) => void
onStopResponding?: () => void
} }
const ChatContext = createContext<ChatContextValue>({ const ChatContext = createContext<ChatContextValue>({
config: {} as ChatConfig,
onRestart: noop, onRestart: noop,
onSend: noop, onSend: noop,
chatList: [],
onFeedback: noop, onFeedback: noop,
}) })
type ChatContextProviderProps = { type ChatContextProviderProps = {
children: ReactNode children: React.ReactNode
} & ChatContextValue } & ChatContextValue
export const ChatContextProvider = ({ export const ChatContextProvider = ({
children, children,
config,
isResponding,
chatList,
onSend, onSend,
onRegenerate, onRegenerate,
onRestart, onRestart,
onFeedback, onFeedback,
onStopResponding, onStopResponding,
}: ChatContextProviderProps) => { }: ChatContextProviderProps) => {
return ( const value = useMemo(
<ChatContext.Provider () => ({
value={{ onSend,
config, onRegenerate,
isResponding, onRestart,
chatList: chatList || [], onFeedback,
onSend, onStopResponding,
onRegenerate, }),
onRestart, [onSend, onRegenerate, onRestart, onFeedback, onStopResponding],
onFeedback,
onStopResponding,
}}>
{children}
</ChatContext.Provider>
) )
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>
} }
export const useChatContext = () => useContext(ChatContext) export const useChatContext = () => useContext(ChatContext)
export default ChatContext export default ChatContext
// app/components/base/chat/chat/chat-runtime-context.tsx
'use client'
import { createContext, useContext } from 'use-context-selector'
import type { ChatItem } from '../../types'
type RuntimeContext = {
chatList: ChatItem[]
isResponding?: boolean
}
const ChatRuntimeContext = createContext<RuntimeContext>({
chatList: [],
isResponding: false,
})
export const useChatRuntimeContext = () => useContext(ChatRuntimeContext)
type Props = {
children: React.ReactNode
} & RuntimeContext
export const ChatRuntimeProvider = ({ children, chatList, isResponding }: Props) => {
const value = { chatList, isResponding }
return <ChatRuntimeContext.Provider value={value}>{children}</ChatRuntimeContext.Provider>
}
...@@ -13,8 +13,8 @@ import { ...@@ -13,8 +13,8 @@ import {
import type { InstalledApp } from '@/models/app' import type { InstalledApp } from '@/models/app'
import { useToastContext } from '@/app/components/base/toast' import { useToastContext } from '@/app/components/base/toast'
import { useAppFavicon } from '@/hooks/use-app-favicon' import { useAppFavicon } from '@/hooks/use-app-favicon'
import { noop, uniqBy } from 'lodash-es' import { cloneDeep, noop, uniqBy } from 'lodash-es'
import { OnSendMessage } from '../../chat/context' import { OnSendMessage } from '../context/chat-context'
import { getProcessedFiles, getProcessedFilesFromResponse } from '../../../file-uploader/utils' import { getProcessedFiles, getProcessedFilesFromResponse } from '../../../file-uploader/utils'
import { getProcessedInputs } from '../../chat/utils' import { getProcessedInputs } from '../../chat/utils'
import { getLastAnswer, getThreadMessages } from '../../utils' import { getLastAnswer, getThreadMessages } from '../../utils'
...@@ -31,6 +31,10 @@ type SendCallback = { ...@@ -31,6 +31,10 @@ type SendCallback = {
onConversationComplete?: (conversationId: string) => void onConversationComplete?: (conversationId: string) => void
isPublicAPI?: boolean isPublicAPI?: boolean
} }
type UpdateChatTreeNode = {
(id: string, fields: Partial<ChatItemInTree>): 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()
...@@ -75,16 +79,16 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -75,16 +79,16 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
{ revalidateOnFocus: false }, { revalidateOnFocus: false },
) )
const config = useMemo(() => { const config = useMemo(() => {
const config = appParams || {} const cfg = cloneDeep(appParams) || {}
return { return {
...config, ...cfg,
file_upload: { file_upload: {
...(config as any).file_upload, ...(cfg as any).file_upload,
fileUploadConfig: (config as any).system_parameters, fileUploadConfig: (cfg as any).system_parameters,
}, },
supportFeedback: true, supportFeedback: true,
opening_statement: (config as any).opening_statement, opening_statement: (cfg as any).opening_statement,
initial_message: (config as any).opening_statement, initial_message: (cfg as any).opening_statement,
} as ChatConfig } as ChatConfig
}, [appParams]) }, [appParams])
...@@ -99,7 +103,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -99,7 +103,7 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
setClearChatList(true) setClearChatList(true)
} }
}, },
[setClearChatList], [],
) )
const handleNewConversationCompleted = useCallback( const handleNewConversationCompleted = useCallback(
(newConversationId: string) => { (newConversationId: string) => {
...@@ -154,11 +158,6 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -154,11 +158,6 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
}) })
}, []) }, [])
type UpdateChatTreeNode = {
(id: string, fields: Partial<ChatItemInTree>): void
(id: string, update: (node: ChatItemInTree) => void): void
}
const updateChatTreeNode: UpdateChatTreeNode = useCallback( const updateChatTreeNode: UpdateChatTreeNode = useCallback(
(id: string, fieldsOrUpdate: Partial<ChatItemInTree> | ((node: ChatItemInTree) => void)) => { (id: string, fieldsOrUpdate: Partial<ChatItemInTree> | ((node: ChatItemInTree) => void)) => {
const nextState = produceChatTreeNode(id, node => { const nextState = produceChatTreeNode(id, node => {
...@@ -551,14 +550,14 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -551,14 +550,14 @@ 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,
formatTime, // formatTime,
// params.token, // params.token,
// params.appId, // params.appId,
// pathname, // pathname,
...@@ -587,11 +586,10 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string, ...@@ -587,11 +586,10 @@ export const useChat = (installedAppInfo?: InstalledApp, inputs: Record<string,
}, },
[ [
handleSend, handleSend,
isInstalledApp, // appId,
appId, // newConversationInputs,
newConversationInputs, // getUrl,
getUrl, // fetchSuggestedQuestions,
fetchSuggestedQuestions,
handleNewConversationCompleted, handleNewConversationCompleted,
], ],
) )
......
import { create } from 'zustand' import { create } from 'zustand'
import { ChatConfig, ChatItemInTree, Feedback } from '@/app/components/base/chat/types' import { ChatConfig, ChatItemInTree, Feedback } from '@/app/components/base/chat/types'
import { OnSendMessage } from '@/app/components/base/chat/chat/context' import { OnSendMessage } from '@/app/components/base/chat/chat-with-history/context/chat-context'
type OnRegenerate = (chatItem: ChatItemInTree) => void type OnRegenerate = (chatItem: ChatItemInTree) => void
type State = { type State = {
......
...@@ -3,15 +3,17 @@ import { memo, useMemo } from 'react' ...@@ -3,15 +3,17 @@ import { memo, useMemo } from 'react'
import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react' import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button' import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
import { useOperationContext } from '../../context/operation' import { useOperationContext } from '../../context/operation'
import { useChatContext } from '../../../context' import { useChatContext } from '../../../../chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const FeedbackActive: FC = () => { const FeedbackActive: FC = () => {
const { config, onFeedback } = useChatContext() const { onFeedback } = useChatContext()
const { supportFeedback } = useChatConfigContext()
const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext() const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext()
// 判断是否已点赞 // 判断是否已点赞
const feedbackActive = useMemo( const feedbackActive = useMemo(
() => config?.supportFeedback && localFeedback?.rating && !isOpeningStatement, () => supportFeedback && localFeedback?.rating && !isOpeningStatement,
[config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement], [supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
) )
return useMemo(() => { return useMemo(() => {
if (!feedbackActive) return null if (!feedbackActive) return null
......
...@@ -3,15 +3,18 @@ import { memo, useMemo } from 'react' ...@@ -3,15 +3,18 @@ import { memo, useMemo } from 'react'
import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react' import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button' import ActionButton from '@/app/components/base/action-button'
import { useOperationContext } from '../../context/operation' import { useOperationContext } from '../../context/operation'
import { useChatContext } from '../../../context' import { useChatContext } from '../../../../chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const Feedback: FC = () => { const Feedback: FC = () => {
const { config, onFeedback } = useChatContext() const { onFeedback } = useChatContext()
const { supportFeedback } = useChatConfigContext()
const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext() const { handleFeedback, localFeedback, isOpeningStatement } = useOperationContext()
// 判断反馈按钮是否启用 // 判断反馈按钮是否启用
const feedbackEnabled = useMemo( const feedbackEnabled = useMemo(
() => config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement, () => supportFeedback && !localFeedback?.rating && !isOpeningStatement,
[config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement], [supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
) )
return useMemo(() => { return useMemo(() => {
if (feedbackEnabled) { if (feedbackEnabled) {
......
...@@ -6,7 +6,6 @@ import { useOperationContext } from '../../context/operation' ...@@ -6,7 +6,6 @@ import { useOperationContext } from '../../context/operation'
const Regenerate: FC = memo(() => { const Regenerate: FC = memo(() => {
const { noChatInput, isLast, handleRegenerate } = useOperationContext() const { noChatInput, isLast, handleRegenerate } = useOperationContext()
if (noChatInput|| !isLast) return null if (noChatInput|| !isLast) return null
return ( return (
<ActionButton onClick={() => handleRegenerate()}> <ActionButton onClick={() => handleRegenerate()}>
......
...@@ -2,12 +2,12 @@ import type { FC } from 'react' ...@@ -2,12 +2,12 @@ import type { FC } from 'react'
import { memo } from 'react' import { memo } from 'react'
import { RiEditLine } from '@remixicon/react' import { RiEditLine } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button' import ActionButton from '@/app/components/base/action-button'
import { useChatContext } from '../../../context' import { useOperationContext } from '@/app/components/base/chat/chat/answer/context/operation'
import { useOperationContext } from '../../context/operation' import { useChatConfigContext } from '@/app/components/base/chat/chat-with-history/context/chat-config-context'
const Reply: FC = memo(() => { const Reply: FC = memo(() => {
const { setIsShowReplyModal } = useOperationContext() const { setIsShowReplyModal } = useOperationContext()
const { config } = useChatContext() const { annotation_reply,supportAnnotation } = useChatConfigContext()
if (!config?.supportAnnotation || !config.annotation_reply?.enabled) return null if (!supportAnnotation || !annotation_reply?.enabled) return null
return ( return (
<ActionButton onClick={() => setIsShowReplyModal(true)}> <ActionButton onClick={() => setIsShowReplyModal(true)}>
<RiEditLine className="h-4 w-4" /> <RiEditLine className="h-4 w-4" />
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
import type { FC } from 'react' import type { FC } from 'react'
import { memo, useMemo } from 'react' import { memo, useMemo } from 'react'
import type { ChatItem } from '../../../types' import type { ChatItem } from '../../../types'
import { useChatContext } from '../../context' import { useChatContext } from '../../../chat-with-history/context/chat-context'
import Button from '@/app/components/base/button/next-button' import Button from '@/app/components/base/button/next-button'
// import { AUTO_INPUT } from '@/app/components/base/chat/constants' // import { AUTO_INPUT } from '@/app/components/base/chat/constants'
import { InputMessageType } from '../../../types' import { InputMessageType } from '../../../types'
......
import React, { createContext, useContext, useState, useEffect, useRef } from 'react' import React, { createContext, useContext, useState, useEffect, useRef } from 'react'
import { useChatContext } from '../../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'
// 定义 AnswerContext 的类型 // 定义 AnswerContext 的类型
interface AnswerContextType { interface AnswerContextType {
...@@ -70,7 +71,7 @@ export const AnswerProvider: React.FC<AnswerProviderProps> = ({ ...@@ -70,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 } = useChatContext() const { isResponding } = useChatRuntimeContext()
const responding = isLast && isResponding const responding = isLast && isResponding
const getContainerWidth = () => { const getContainerWidth = () => {
......
...@@ -2,10 +2,11 @@ ...@@ -2,10 +2,11 @@
import type { FC } from 'react' import type { FC } from 'react'
import React, { createContext, useCallback, useContext, useMemo, useState } from 'react' import React, { createContext, useCallback, useContext, useMemo, useState } from 'react'
import { useChatContext } from '../../context' import { useChatContext } from '../../../chat-with-history/context/chat-context'
import Toast from '@/app/components/base/toast' import Toast from '@/app/components/base/toast'
import { useChatBodyContext } from '../../body/context' import { useChatBodyContext } from '../../body/context'
import { ChatItem, OnRegenerate } from '../../../types' import { ChatItem, OnRegenerate } from '../../../types'
import { useChatConfigContext } from '../../../chat-with-history/context/chat-config-context'
interface OperationContextType { interface OperationContextType {
content: string content: string
...@@ -35,10 +36,11 @@ export const OperationProvider: FC<OperationProviderProps> = ({ ...@@ -35,10 +36,11 @@ export const OperationProvider: FC<OperationProviderProps> = ({
// noChatInput, // noChatInput,
children, children,
}) => { }) => {
const { config, onFeedback,onRegenerate } = useChatContext() const {onFeedback,onRegenerate } = useChatContext()
const {supportFeedback,text_to_speech,annotation_reply,supportAnnotation} = useChatConfigContext()
const [showLike, setShowLike] = useState(false) const [showLike, setShowLike] = useState(false)
const { id, isOpeningStatement, content: messageContent, isLast,noChatInput,annotation,parentMessageId,containerWidth,contentWidth, showPromptLog,feedback, adminFeedback, agent_thoughts, } = useChatBodyContext() const { id, isOpeningStatement, content: messageContent, isLast,noChatInput,annotation,parentMessageId,containerWidth,contentWidth, showPromptLog,feedback, adminFeedback, agent_thoughts, } = useChatBodyContext()
const [localFeedback, setLocalFeedback] = useState(config?.supportAnnotation ? adminFeedback : feedback) const [localFeedback, setLocalFeedback] = useState(supportAnnotation ? adminFeedback : feedback)
const [isShowReplyModal, setIsShowReplyModal] = useState(false) const [isShowReplyModal, setIsShowReplyModal] = useState(false)
const maxSize = containerWidth - contentWidth - 4 const maxSize = containerWidth - contentWidth - 4
// 计算内容 // 计算内容
...@@ -49,7 +51,7 @@ export const OperationProvider: FC<OperationProviderProps> = ({ ...@@ -49,7 +51,7 @@ export const OperationProvider: FC<OperationProviderProps> = ({
// 处理反馈 // 处理反馈
const handleFeedback = async (rating: 'like' | 'dislike' | null) => { const handleFeedback = async (rating: 'like' | 'dislike' | null) => {
if (!config?.supportFeedback || !onFeedback || showLike) return if (!supportFeedback || !onFeedback || showLike) return
try { try {
setShowLike(true) setShowLike(true)
await onFeedback(id, { rating }) await onFeedback(id, { rating })
...@@ -72,18 +74,18 @@ export const OperationProvider: FC<OperationProviderProps> = ({ ...@@ -72,18 +74,18 @@ export const OperationProvider: FC<OperationProviderProps> = ({
let width = 0 let width = 0
if (!isOpeningStatement) width += 26 if (!isOpeningStatement) width += 26
if (!isOpeningStatement && showPromptLog) width += 28 + 8 if (!isOpeningStatement && showPromptLog) width += 28 + 8
if (!isOpeningStatement && config?.text_to_speech?.enabled) width += 26 if (!isOpeningStatement && text_to_speech?.enabled) width += 26
if (!isOpeningStatement && config?.supportAnnotation && config?.annotation_reply?.enabled) width += 26 if (!isOpeningStatement && supportAnnotation && annotation_reply?.enabled) width += 26
if (config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement) width += 60 + 8 if (supportFeedback && !localFeedback?.rating && !isOpeningStatement) width += 60 + 8
if (config?.supportFeedback && localFeedback?.rating && !isOpeningStatement) width += 28 + 8 if (supportFeedback && localFeedback?.rating && !isOpeningStatement) width += 28 + 8
return width return width
}, [ }, [
isOpeningStatement, isOpeningStatement,
showPromptLog, showPromptLog,
config?.text_to_speech?.enabled, text_to_speech?.enabled,
config?.supportAnnotation, supportAnnotation,
config?.annotation_reply?.enabled, annotation_reply?.enabled,
config?.supportFeedback, supportFeedback,
localFeedback?.rating, localFeedback?.rating,
onFeedback, onFeedback,
]) ])
......
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 '../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'
// 定义 AnswerContext 的类型 // 定义 AnswerContext 的类型
interface ChatBodyContextType { interface ChatBodyContextType {
...@@ -89,8 +90,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -89,8 +90,7 @@ 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 } = useChatContext() const { isResponding, chatList } = useChatRuntimeContext()
const { chatList } = useChatContext()
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
......
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/context' 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'
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 = useChatStore(state=>state.chatList)
const { chatList } = useChatContext() const { chatList } = useChatRuntimeContext()
return ( return (
<> <>
{chatList.map((item, index) => ( {chatList.map((item, index) => (
......
import {
useCallback,
useRef,
useState,
} from 'react'
export const useTextAreaHeight = () => {
const wrapperRef = useRef<HTMLDivElement>(null)
const textareaRef = useRef<HTMLTextAreaElement | undefined>(undefined)
const textValueRef = useRef<HTMLDivElement>(null)
const holdSpaceRef = useRef<HTMLDivElement>(null)
const [isMultipleLine, setIsMultipleLine] = useState(false)
const handleComputeHeight = useCallback(() => {
const textareaElement = textareaRef.current
if (wrapperRef.current && textareaElement && textValueRef.current && holdSpaceRef.current) {
const { width: wrapperWidth } = wrapperRef.current.getBoundingClientRect()
const { height: textareaHeight } = textareaElement.getBoundingClientRect()
const { width: textValueWidth } = textValueRef.current.getBoundingClientRect()
const { width: holdSpaceWidth } = holdSpaceRef.current.getBoundingClientRect()
if (textareaHeight > 32) {
setIsMultipleLine(true)
}
else {
if (textValueWidth + holdSpaceWidth >= wrapperWidth)
setIsMultipleLine(true)
else
setIsMultipleLine(false)
}
}
}, [])
const handleTextareaResize = useCallback(() => {
handleComputeHeight()
}, [handleComputeHeight])
return {
wrapperRef,
textareaRef,
textValueRef,
holdSpaceRef,
handleTextareaResize,
isMultipleLine,
setIsMultipleLine
}
}
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import Textarea from 'react-textarea-autosize'
import { useTranslation } from 'react-i18next'
import Recorder from 'js-audio-recorder'
import type { EnableType, OnSend } from '../../types'
import type { Theme } from '../../embedded-chatbot/theme/theme-context'
import type { InputForm } from '../type'
import { useCheckInputsForms } from '../check-input-forms-hooks'
import { useTextAreaHeight } from './hooks'
import Operation from './operation'
import cn from '@/utils/classnames'
import { FileListInChatInput } from '@/app/components/base/file-uploader'
import { useFile } from '@/app/components/base/file-uploader/hooks'
import { FileContextProvider, useFileStore } from '@/app/components/base/file-uploader/store'
import VoiceInput from '@/app/components/base/voice-input'
import { useToastContext } from '@/app/components/base/toast'
import FeatureBar from '@/app/components/base/features/new-feature-panel/feature-bar'
import type { FileUpload } from '@/app/components/base/features/types'
import { TransferMethod } from '@/types/app'
import { InputMessageType } from '../../types'
import { useChatContext } from '../context'
import Confirm from '@/app/components/base/confirm'
import { useChatStore } from '../../chat-with-history/store'
type ChatInputAreaProps = {
showFeatureBar?: boolean
showFileUpload?: boolean
// featureBarDisabled?: boolean
onFeatureBarClick?: (state: boolean) => void
// visionConfig?: FileUpload
// speechToTextConfig?: EnableType
// inputs?: Record<string, any>
// inputsForm?: InputForm[]
// theme?: Theme | null
disabled?: boolean
}
const ChatInputArea = ({
showFeatureBar,
showFileUpload,
// featureBarDisabled,
onFeatureBarClick,
// visionConfig,
// speechToTextConfig = { enabled: true },
// inputs = {},
// inputsForm = [],
// theme,
// disabled,
}: ChatInputAreaProps) => {
const { t } = useTranslation()
// const { onSend, onRestart, isResponding } = useChatContext()
// const config= useChatStore(state => state.config)
// console.log('config', config)
const { notify } = useToastContext()
const {isResponding, onSend:sendMessage, onRestart:restartChat,config} = useChatContext()
const visionConfig = config.file_upload
const speechToTextConfig = config.speech_to_text
// const sendMessage = useChatStore(state => state.sendMessage)
// const isResponding = useChatStore(state => state.isResponding)
// const restartChat = useChatStore(state => state.restartChat)
const {
wrapperRef,
textareaRef,
textValueRef,
holdSpaceRef,
handleTextareaResize,
isMultipleLine,
setIsMultipleLine,
} = useTextAreaHeight()
const [query, setQuery] = useState('')
const [showVoiceInput, setShowVoiceInput] = useState(false)
const filesStore = useFileStore()
const {
handleDragFileEnter,
handleDragFileLeave,
handleDragFileOver,
handleDropFile,
handleClipboardPasteFile,
isDragActive,
} = useFile(visionConfig!)
const { checkInputsForm } = useCheckInputsForms()
const historyRef = useRef([''])
const [currentIndex, setCurrentIndex] = useState(-1)
const isComposingRef = useRef(false)
// const { onSend } = useChatContext()
const [showConfirm, setShowConfirm] = useState<boolean>(false)
const featureBarDisabled = isResponding
const handleSend = () => {
if (isResponding) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForResponse'),
})
return
}
if (sendMessage) {
const { files, setFiles } = filesStore.getState()
if (files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForFileUpload'),
})
return
}
if (!query || !query.trim()) {
notify({
type: 'info',
message: t('appAnnotation.errorMessage.queryRequired'),
})
return
}
// if (checkInputsForm(inputs, inputsForm)) {
sendMessage(query, InputMessageType.BY_HAND, files)
setQuery('')
setFiles([])
// }
}
}
const handleCompositionStart = () => {
// e: React.CompositionEvent<HTMLTextAreaElement>
isComposingRef.current = true
}
const handleCompositionEnd = () => {
// safari or some browsers will trigger compositionend before keydown.
// delay 50ms for safari.
setTimeout(() => {
isComposingRef.current = false
}, 50)
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
// if isComposing, exit
if (isComposingRef.current) return
e.preventDefault()
setQuery(query.replace(/\n$/, ''))
historyRef.current.push(query)
setCurrentIndex(historyRef.current.length)
handleSend()
} else if (e.key === 'ArrowUp' && !e.shiftKey && !e.nativeEvent.isComposing && e.metaKey) {
// When the cmd + up key is pressed, output the previous element
if (currentIndex > 0) {
setCurrentIndex(currentIndex - 1)
setQuery(historyRef.current[currentIndex - 1])
}
} else if (e.key === 'ArrowDown' && !e.shiftKey && !e.nativeEvent.isComposing && e.metaKey) {
// When the cmd + down key is pressed, output the next element
if (currentIndex < historyRef.current.length - 1) {
setCurrentIndex(currentIndex + 1)
setQuery(historyRef.current[currentIndex + 1])
} else if (currentIndex === historyRef.current.length - 1) {
// If it is the last element, clear the input box
setCurrentIndex(historyRef.current.length)
setQuery('')
}
}
}
const handleShowVoiceInput = useCallback(() => {
;(Recorder as any).getPermission().then(
() => {
setShowVoiceInput(true)
},
() => {
notify({ type: 'error', message: t('common.voiceInput.notAllow') })
},
)
}, [t, notify])
const handleRestart = useCallback(() => {
if (isResponding) {
notify({
type: 'info',
message: t('appDebug.errorMessage.waitForResponse'),
})
return
}
setShowConfirm(true)
}, [isResponding])
const doRestart = useCallback(() => {
restartChat()
setShowConfirm(false)
}, [])
const operation = (
<Operation
ref={holdSpaceRef}
fileConfig={visionConfig}
speechToTextConfig={speechToTextConfig}
onShowVoiceInput={handleShowVoiceInput}
onRestart={handleRestart}
onSend={handleSend}
// theme={theme}
/>
)
// const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} />
const hasQuery = useMemo(() => query.length > 0, [query])
useEffect(() => {
if (!hasQuery) {
setIsMultipleLine(false)
}
}, [hasQuery, setIsMultipleLine])
const maxRow = useMemo(() => {
return hasQuery ? undefined : 1
}, [hasQuery])
return (
<>
{showConfirm && (
<Confirm
title="重置对话"
confirmText="确认"
cancelText="取消"
content="您确定要重置此对话吗?"
isShow
onCancel={() => setShowConfirm(false)}
onConfirm={doRestart}
/>
)}
<div
className={cn(
'relative z-10 rounded-xl border border-components-chat-input-border bg-[#fff] pb-[9px] shadow-md',
isDragActive && 'border border-dashed border-components-option-card-option-selected-border',
)}>
<div className="relative max-h-[158px] overflow-y-auto overflow-x-hidden px-[9px] pt-[9px]">
<FileListInChatInput fileConfig={visionConfig!} />
<div ref={wrapperRef} className="flex items-center justify-between">
<div className="relative flex w-full grow items-center ml-8">
<div
ref={textValueRef}
className="body-lg-regular pointer-events-none invisible absolute h-auto w-auto whitespace-pre p-1 leading-6">
{query}
</div>
<Textarea
ref={ref => (textareaRef.current = ref as any)}
className={cn(
'body-lg-regular w-full resize-none bg-transparent p-1 leading-6 text-text-tertiary outline-none',
)}
placeholder={t('common.chat.inputPlaceholder') || ''}
autoFocus
maxRows={maxRow}
onResize={handleTextareaResize}
value={query}
onChange={e => {
setQuery(e.target.value)
setTimeout(handleTextareaResize, 0)
}}
onKeyDown={handleKeyDown}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
onPaste={handleClipboardPasteFile}
onDragEnter={handleDragFileEnter}
onDragLeave={handleDragFileLeave}
onDragOver={handleDragFileOver}
onDrop={handleDropFile}
/>
</div>
{!isMultipleLine && operation}
</div>
{showVoiceInput && (
<VoiceInput onCancel={() => setShowVoiceInput(false)} onConverted={text => setQuery(text)} />
)}
</div>
{isMultipleLine && <div className="px-[9px]">{operation}</div>}
</div>
{showFeatureBar && (
<FeatureBar
showFileUpload={showFileUpload}
disabled={featureBarDisabled}
onFeatureBarClick={onFeatureBarClick}
/>
)}
</>
)
}
const ChatInputAreaWrapper = (props: ChatInputAreaProps) => {
return (
<FileContextProvider>
<ChatInputArea {...props} />
</FileContextProvider>
)
}
export default ChatInputAreaWrapper
import { Dispatch, memo, SetStateAction, use, useMemo } from 'react'
import { RiMicLine, RiSendPlane2Fill } from '@remixicon/react'
import type { EnableType } from '../../types'
import type { Theme } from '../../embedded-chatbot/theme/theme-context'
import Button from '@/app/components/base/button'
import ActionButton from '@/app/components/base/action-button'
import { FileUploaderInChatInput } from '@/app/components/base/file-uploader'
import type { FileUpload } from '@/app/components/base/features/types'
import cn from '@/utils/classnames'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
import {
// SELF_INPUT,
SEND_BUTTON,
CLEAR_BUTTON,
} from '@/app/components/base/chat/constants'
type OperationProps = {
fileConfig?: FileUpload
speechToTextConfig?: EnableType
onShowVoiceInput?: () => void
onSend: () => void
imgUrl?: string
theme?: Theme | null
onRestart: () => void
}
const Operation = ({
ref,
onSend,
speechToTextConfig,
onShowVoiceInput,
onRestart,
}: OperationProps & {
ref: React.RefObject<HTMLDivElement>
}) => {
return (
<div className={cn('flex shrink-0 items-center justify-end')}>
<div className="absolute left-3">
<img onClick={onRestart} src={CLEAR_BUTTON} className="size-6 hover:cursor-pointer" alt="icon" />
</div>
<div className="flex items-center pl-1" ref={ref}>
<div className="flex items-center space-x-1 pr-2">
{/* {fileConfig?.enabled && <FileUploaderInChatInput fileConfig={fileConfig} />} */}
{speechToTextConfig?.enabled && (
<ActionButton size="l" onClick={onShowVoiceInput}>
<RiMicLine className="h-5 w-5" />
</ActionButton>
)}
</div>
<img onClick={onSend} src={SEND_BUTTON} className="size-6 hover:cursor-pointer" alt="icon" />
</div>
</div>
)
}
Operation.displayName = 'Operation'
export default memo(Operation)
import { FC, memo } from 'react' import { FC, memo } from 'react'
import { FileListInChatInput } from '@/app/components/base/file-uploader' import { FileListInChatInput } from '@/app/components/base/file-uploader'
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const FileList: FC = () => { const FileList: FC = () => {
const { config } = useChatContext() const { file_upload } = useChatConfigContext ()
return <FileListInChatInput fileConfig={config.file_upload} /> return <FileListInChatInput fileConfig={file_upload} />
} }
export default memo(FileList) export default memo(FileList)
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 '../../../context' 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'
const ReStart: FC = () => { const ReStart: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { notify } = useToastContext() const { notify } = useToastContext()
const { isResponding, onRestart: restartChat } = useChatContext() const { onRestart: restartChat } = useChatContext()
const { isResponding } = useChatRuntimeContext ()
const [showConfirm, setShowConfirm] = useState<boolean>(false) const [showConfirm, setShowConfirm] = useState<boolean>(false)
const handleRestart = useCallback(() => { const handleRestart = useCallback(() => {
if (isResponding) { if (isResponding) {
......
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 '../../../context' import { useChatContext } from '../../../../chat-with-history/context/chat-context'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import ActionButton from '@/app/components/base/action-button' import ActionButton from '@/app/components/base/action-button'
import { RiMicLine } from '@remixicon/react' import { RiMicLine } from '@remixicon/react'
import Recorder from 'js-audio-recorder' import Recorder from 'js-audio-recorder'
import { useMessageContext } from '../../context' import { useMessageContext } from '../../context'
import { useChatConfigContext } from '../../../../chat-with-history/context/chat-config-context'
const SpeechToText: FC = () => { const SpeechToText: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { notify } = useToastContext() const { notify } = useToastContext()
const { config } = useChatContext() const { speech_to_text } = useChatConfigContext()
const speechToTextConfig = config.speech_to_text const speechToTextConfig = speech_to_text
const { setShowVoiceInput } = useMessageContext() const { setShowVoiceInput } = useMessageContext()
const handleShowVoiceInput = useCallback(() => { const handleShowVoiceInput = useCallback(() => {
;(Recorder as any).getPermission().then( ;(Recorder as any).getPermission().then(
......
...@@ -3,7 +3,7 @@ import { memo } from 'react' ...@@ -3,7 +3,7 @@ import { memo } from 'react'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons' import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons'
import { useChatContext } from '../../context' import { useChatContext } from '../../../chat-with-history/context/chat-context'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useChatStore } from '@/app/components/base/chat/chat-with-history/store' import { useChatStore } from '@/app/components/base/chat/chat-with-history/store'
const Practice: FC = () => { const Practice: FC = () => {
......
...@@ -2,10 +2,13 @@ import { FC, memo, useMemo } from 'react' ...@@ -2,10 +2,13 @@ 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/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatRuntimeContext } from '../../../chat-with-history/context/chat-runtime-context'
const StopRespondingButton: FC = () => { const StopRespondingButton: FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { isResponding, onStopResponding: stopResponding } = useChatContext() const { onStopResponding: stopResponding } = useChatContext()
const { isResponding } = useChatRuntimeContext()
const mc = useMemo(() => { const mc = useMemo(() => {
if (!isResponding) return null if (!isResponding) return null
return ( return (
......
...@@ -5,7 +5,7 @@ import Button from '@/app/components/base/button' ...@@ -5,7 +5,7 @@ import Button from '@/app/components/base/button'
import Divider from '@/app/components/base/divider' import Divider from '@/app/components/base/divider'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
import { useChatContext } from '../../context' import { useChatContext } from '../../../chat-with-history/context/chat-context'
type TryToAskProps = { type TryToAskProps = {
suggestedQuestions?: string[] suggestedQuestions?: string[]
isMobile?: boolean isMobile?: boolean
......
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 '../context' 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'
// 定义消息上下文类型 // 定义消息上下文类型
interface MessageContextType { interface MessageContextType {
...@@ -35,7 +36,8 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => { ...@@ -35,7 +36,8 @@ 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, onSend: sendMessage } = useChatContext() const { isResponding } = useChatRuntimeContext()
const { onSend: sendMessage } = useChatContext()
const { notify } = useToastContext() const { notify } = useToastContext()
const filesStore = useFileStore() const filesStore = useFileStore()
const [isMultipleLine, setIsMultipleLine] = useState(false) const [isMultipleLine, setIsMultipleLine] = useState(false)
...@@ -72,26 +74,18 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => { ...@@ -72,26 +74,18 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => {
}, [query, isResponding, sendMessage, filesStore, notify, t]) }, [query, isResponding, sendMessage, filesStore, notify, t])
// 提供上下文值 // 提供上下文值
const value = useMemo(() => ({ const value = useMemo(
query, () => ({
setQuery, query,
handleSend, setQuery,
showVoiceInput, handleSend,
setShowVoiceInput, showVoiceInput,
isMultipleLine, setShowVoiceInput,
setIsMultipleLine isMultipleLine,
}), [ setIsMultipleLine,
query, }),
showVoiceInput, [query, showVoiceInput, handleSend, setShowVoiceInput, isMultipleLine, setIsMultipleLine],
handleSend,
setShowVoiceInput,
isMultipleLine,
setIsMultipleLine
])
return (
<MessageContext.Provider value={value}>
{children}
</MessageContext.Provider>
) )
}
\ No newline at end of file \ No newline at end of file
return <MessageContext.Provider value={value}>{children}</MessageContext.Provider>
}
import { useFile } from '@/app/components/base/file-uploader/hooks' import { useFile } from '@/app/components/base/file-uploader/hooks'
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatConfigContext } from '../../../chat-with-history/context/chat-config-context'
const useFileOperation = () => { const useFileOperation = () => {
const { config } = useChatContext() const { file_upload } = useChatConfigContext ()
const visionConfig = config.file_upload const visionConfig = file_upload
const { const {
handleDragFileEnter, handleDragFileEnter,
handleDragFileLeave, handleDragFileLeave,
......
...@@ -28,7 +28,7 @@ import type { FileEntity } from '@/app/components/base/file-uploader/types' ...@@ -28,7 +28,7 @@ import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { getProcessedFiles, getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils' import { getProcessedFiles, getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
import { useChatStore } from '../chat-with-history/store' import { useChatStore } from '../chat-with-history/store'
import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/state' import { state } from 'mermaid/dist/rendering-util/rendering-elements/shapes/state'
import { OnSendMessage } from './context' import { OnSendMessage } from '../chat-with-history/context/chat-context'
import { fetchSuggestedQuestions, getUrl } from '@/service/share' import { fetchSuggestedQuestions, getUrl } from '@/service/share'
import { set } from 'immer/dist/internal' import { set } from 'immer/dist/internal'
type GetAbortController = (abortController: AbortController) => void type GetAbortController = (abortController: AbortController) => void
......
...@@ -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 15:35:35 * @LastEditTime: 2025-07-15 20:45:57
* @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
*/ */
......
...@@ -5,31 +5,19 @@ import InitSuggest from './init-suggest' ...@@ -5,31 +5,19 @@ import InitSuggest from './init-suggest'
// import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item"; // import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item";
import AnswerIcon from '@/app/components/base/answer-icon' import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { Markdown } from '@/app/components/base/markdown' import { Markdown } from '@/app/components/base/markdown'
import { useChatConfigContext } from '../../chat-with-history/context/chat-config-context'
type InitQuestionsProps = { type InitQuestionsProps = {
// config: ChatConfig
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
// icon:ReactNode
} }
const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => { const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => {
// const config = useChatStore(state => state.config) const { suggested_questions, initial_message } = useChatConfigContext()
const { config } = useChatContext() if (!suggested_questions) return null
const questions = useMemo(() => { const suggestedQuestions = suggested_questions
const { suggested_questions, initial_message } = config .filter(q => !!q && q.trim())
const suggestedQuestions = suggested_questions .sort(() => Math.random() - 0.5)
?.filter(q => !!q && q.trim()) .slice(0, 3)
.sort(() => Math.random() - 0.5)
.slice(0, 3)
const initQuestions: ChatItem = {
content: initial_message || '',
suggestedQuestions,
isAnswer: true,
id: 'initial_message',
}
return initQuestions
}, [config.initial_message])
if (!questions.content) return null
return ( return (
<div className="mb-2 flex last:mb-0"> <div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div> <div className="relative h-10 w-10 shrink-0">{<AnswerIcon />}</div>
...@@ -39,8 +27,8 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) => ...@@ -39,8 +27,8 @@ const InitQuestions: FC<InitQuestionsProps> = ({ chatAnswerContainerInner }) =>
className={cn( className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary', 'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
)}> )}>
<Markdown content={questions.content} /> {initial_message && <Markdown content={initial_message} />}
<InitSuggest suggestedQuestions={questions.suggestedQuestions} /> <InitSuggest suggestedQuestions={suggestedQuestions} />
</div> </div>
</div> </div>
</div> </div>
......
...@@ -2,22 +2,20 @@ ...@@ -2,22 +2,20 @@
* @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 09:22:21 * @LastEditTime: 2025-07-16 00:00:32
* @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
*/ */
import type { FC } from 'react' import type { FC } from 'react'
import { memo, useMemo } from 'react' import { memo } from 'react'
import type { ChatItem } from '@/app/components/base/chat/types' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import Button from '@/app/components/base/button/next-button' import Button from '@/app/components/base/button/next-button'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
type InitSuggestProps = { type InitSuggestProps = {
suggestedQuestions?: string[] suggestedQuestions?: string[]
} }
const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions }) => { const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions = [] }) => {
const { onSend: sendMessage } = useChatContext() const { onSend: sendMessage } = useChatContext()
if (!suggestedQuestions?.length) return null
return ( return (
<div className="w-[fit-content]"> <div className="w-[fit-content]">
{suggestedQuestions.map((question, index) => ( {suggestedQuestions.map((question, index) => (
...@@ -30,8 +28,4 @@ const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions }) => { ...@@ -30,8 +28,4 @@ const InitSuggest: FC<InitSuggestProps> = ({ suggestedQuestions }) => {
) )
} }
const MemoizedSuggestedQuestions = memo(InitSuggest, (prev, next) => { export default memo(InitSuggest)
return prev.suggestedQuestions?.length === next.suggestedQuestions?.length
})
export default MemoizedSuggestedQuestions
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
......
...@@ -6,7 +6,7 @@ import DatePicker from '@/app/components/base/date-and-time-picker/date-picker' ...@@ -6,7 +6,7 @@ import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'
import TimePicker from '@/app/components/base/date-and-time-picker/time-picker' import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'
import Checkbox from '@/app/components/base/checkbox' import Checkbox from '@/app/components/base/checkbox'
import Select from '@/app/components/base/select' import Select from '@/app/components/base/select'
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
enum DATA_FORMAT { enum DATA_FORMAT {
TEXT = 'text', TEXT = 'text',
......
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { isValidUrl } from './utils' import { isValidUrl } from './utils'
......
...@@ -6,7 +6,7 @@ import DatePicker from '@/app/components/base/date-and-time-picker/date-picker' ...@@ -6,7 +6,7 @@ import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'
import TimePicker from '@/app/components/base/date-and-time-picker/time-picker' import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'
import Checkbox from '@/app/components/base/checkbox' import Checkbox from '@/app/components/base/checkbox'
import Select from '@/app/components/base/select' import Select from '@/app/components/base/select'
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
enum DATA_FORMAT { enum DATA_FORMAT {
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* Handles special rendering for "abbr:" type links for interactive chat actions. * Handles special rendering for "abbr:" type links for interactive chat actions.
*/ */
import React, { useState } from 'react' import React, { useState } from 'react'
import { useChatContext } from '@/app/components/base/chat/chat/context' import { useChatContext } from '@/app/components/base/chat/chat-with-history/context/chat-context'
import { isValidUrl } from './utils' import { isValidUrl } from './utils'
import ImagePreview from '@/app/components/base/image-uploader/image-preview' import ImagePreview from '@/app/components/base/image-uploader/image-preview'
import { InputMessageType } from '@/app/components/base/chat/types' import { InputMessageType } from '@/app/components/base/chat/types'
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!