Commit 5b99a30e by liimin

refactor(chat): 重构聊天页面

- 优化了 ChatWrapper 组件的结构和逻辑
- 移除了未使用的 InputsForm 组件
- 简化了 ChatWithHistoryContext 的定义
- 删除了未使用的 HeaderInMobile 组件
- 优化了 page.tsx 中的导出
1 parent b75fd32d
...@@ -8,4 +8,4 @@ const Chat = () => { ...@@ -8,4 +8,4 @@ const Chat = () => {
) )
} }
export default React.memo(Chat) export default React.memo(Chat, () => true)
...@@ -5,7 +5,6 @@ import { createContext, useContext } from "use-context-selector"; ...@@ -5,7 +5,6 @@ import { createContext, useContext } from "use-context-selector";
import type { Callback, ChatConfig, ChatItemInTree, Feedback } from "../types"; import type { Callback, ChatConfig, ChatItemInTree, Feedback } from "../types";
import type { ThemeBuilder } from "../embedded-chatbot/theme/theme-context"; import type { ThemeBuilder } from "../embedded-chatbot/theme/theme-context";
import type { import type {
AppConversationData,
AppData, AppData,
AppMeta, AppMeta,
ConversationItem, ConversationItem,
...@@ -22,43 +21,22 @@ export type ChatWithHistoryContextValue = { ...@@ -22,43 +21,22 @@ export type ChatWithHistoryContextValue = {
currentConversationId: string; currentConversationId: string;
currentConversationItem?: ConversationItem; currentConversationItem?: ConversationItem;
appPrevChatTree: ChatItemInTree[]; appPrevChatTree: ChatItemInTree[];
// pinnedConversationList: AppConversationData["data"];
// conversationList: AppConversationData["data"];
newConversationInputs: Record<string, any>; newConversationInputs: Record<string, any>;
newConversationInputsRef: RefObject<Record<string, any>>; newConversationInputsRef: RefObject<Record<string, any>>;
// handleNewConversationInputsChange: (v: Record<string, any>) => void;
// inputsForms: any[];
handleNewConversation: (v?: Record<string, any>,skipClear?:boolean) => void; handleNewConversation: (v?: Record<string, any>,skipClear?:boolean) => void;
// handleStartChat: (callback?: any) => void; handleNewConversationCompleted?: (newConversationId: string) => void;
handleChangeConversation: (conversationId: string) => void; chatShouldReloadKey?: string;
// handlePinConversation: (conversationId: string) => void; isMobile?: boolean;
// handleUnpinConversation: (conversationId: string) => void;
// handleDeleteConversation: (
// conversationId: string,
// callback: Callback
// ) => void;
// conversationRenaming: boolean;
// handleRenameConversation: (
// conversationId: string,
// newName: string,
// callback: Callback
// ) => void;
handleNewConversationCompleted: (newConversationId: string) => void;
chatShouldReloadKey: string;
isMobile: boolean;
isInstalledApp: boolean; isInstalledApp: boolean;
appId?: string; appId?: string;
handleFeedback: (messageId: string, feedback: Feedback) => void; handleFeedback: (messageId: string, feedback: Feedback) => void;
currentChatInstanceRef: RefObject<{ handleStop: () => void }>; currentChatInstanceRef: RefObject<{ handleStop: () => void }>;
themeBuilder?: ThemeBuilder; themeBuilder?: ThemeBuilder;
// sidebarCollapseState?: boolean;
// handleSidebarCollapse: (state: boolean) => void;
clearChatList?: boolean; clearChatList?: boolean;
setClearChatList: (state: boolean) => void; setClearChatList?: (state: boolean) => void;
isResponding?: boolean; isResponding?: boolean;
setIsResponding: (state: boolean) => void; setIsResponding: (state: boolean) => void;
currentConversationInputs: Record<string, any> | null; currentConversationInputs?: Record<string, any> | null;
// setCurrentConversationInputs: (v: Record<string, any>) => void;
isShowPracticeButton: boolean; isShowPracticeButton: boolean;
}; };
...@@ -66,34 +44,20 @@ export const ChatWithHistoryContext = ...@@ -66,34 +44,20 @@ export const ChatWithHistoryContext =
createContext<ChatWithHistoryContextValue>({ createContext<ChatWithHistoryContextValue>({
currentConversationId: "", currentConversationId: "",
appPrevChatTree: [], appPrevChatTree: [],
// pinnedConversationList: [],
// conversationList: [],
newConversationInputs: {}, newConversationInputs: {},
newConversationInputsRef: { current: {} }, newConversationInputsRef: { current: {} },
// handleNewConversationInputsChange: noop,
// inputsForms: [],
handleNewConversation: noop, handleNewConversation: noop,
// handleStartChat: noop,
handleChangeConversation: noop,
// handlePinConversation: noop,
// handleUnpinConversation: noop,
// handleDeleteConversation: noop,
// conversationRenaming: false,
// handleRenameConversation: noop,
handleNewConversationCompleted: noop, handleNewConversationCompleted: noop,
chatShouldReloadKey: "", chatShouldReloadKey: "",
isMobile: false, isMobile: false,
isInstalledApp: false, isInstalledApp: false,
handleFeedback: noop, handleFeedback: noop,
currentChatInstanceRef: { current: { handleStop: noop } }, currentChatInstanceRef: { current: { handleStop: noop } },
// sidebarCollapseState: false,
// handleSidebarCollapse: noop,
clearChatList: false, clearChatList: false,
setClearChatList: noop, setClearChatList: noop,
isResponding: false, isResponding: false,
setIsResponding: noop, setIsResponding: noop,
currentConversationInputs: {}, currentConversationInputs: {},
// setCurrentConversationInputs: noop,
isShowPracticeButton: false, isShowPracticeButton: false,
}); });
export const useChatWithHistoryContext = () => export const useChatWithHistoryContext = () =>
......
import type { FC } from 'react' import type { FC } from 'react'
import { useEffect, useState, useCallback, useRef } from 'react' import { useEffect, useState, useCallback, useRef, memo } from 'react'
import { useAsyncEffect } from 'ahooks' import { useAsyncEffect } from 'ahooks'
import { useThemeContext } from '../embedded-chatbot/theme/theme-context' import { useThemeContext } from '../embedded-chatbot/theme/theme-context'
import { ChatWithHistoryContext, useChatWithHistoryContext } from './context' import { ChatWithHistoryContext, useChatWithHistoryContext } from './context'
...@@ -50,11 +50,14 @@ const getQueryParams = function (): urlProps { ...@@ -50,11 +50,14 @@ const getQueryParams = function (): urlProps {
} }
} }
const inputs = getQueryParams() const inputs = getQueryParams()
const { avatar, domain, presuppositionProblem, practice_status, ...newInputs } = inputs let { avatar, domain, presuppositionProblem, practice_status, ...newInputs } = inputs
const isShowPracticeButton = practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed const isShowPracticeButton = practice_status === PracticeStatus.Practicing || practice_status === PracticeStatus.Failed
const avatarUrl: string = avatar ?? AVATAR_USER_URL; const avatarUrl: string = avatar ?? AVATAR_USER_URL
const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => { const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } = useChatWithHistoryContext() const { appInfoError, appInfoLoading, appChatListDataLoading, chatShouldReloadKey, isMobile, handleNewConversation } =
useChatWithHistoryContext()
if (appInfoLoading) { if (appInfoLoading) {
return <Loading type="app" /> return <Loading type="app" />
...@@ -72,6 +75,7 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => { ...@@ -72,6 +75,7 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
<ChatWrapper <ChatWrapper
presuppositionQuestion={presuppositionProblem} presuppositionQuestion={presuppositionProblem}
// doClear={doClear} // doClear={doClear}
// hasAutoSended={hasAutoSended}
key={chatShouldReloadKey} key={chatShouldReloadKey}
avatar={avatarUrl} avatar={avatarUrl}
aiAvatar={AVATAR_AI_URL} aiAvatar={AVATAR_AI_URL}
...@@ -84,27 +88,48 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => { ...@@ -84,27 +88,48 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {
} }
export type ChatWithHistoryWrapProps = { export type ChatWithHistoryWrapProps = {
installedAppInfo?: any//InstalledApp installedAppInfo?: any //InstalledApp
className?: string className?: string
} }
const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => { const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, className }) => {
const media = useBreakpoints() // const media = useBreakpoints()
const isMobile = media === MediaType.mobile // const isMobile = media === MediaType.mobile
const themeBuilder = useThemeContext() // const themeBuilder = useThemeContext()
const {
const { appInfoError, appInfoLoading, appData, appParams, appMeta, appChatListDataLoading, currentConversationId, appPrevChatTree, newConversationInputs, newConversationInputsRef, handleNewConversation, handleChangeConversation, handleNewConversationCompleted, chatShouldReloadKey, isInstalledApp, appId, handleFeedback, currentChatInstanceRef, clearChatList, setClearChatList, isResponding, setIsResponding} = // appInfoError,
useChatWithHistory(installedAppInfo,newInputs) // appInfoLoading,
// appData,
appParams,
// appMeta,
// appChatListDataLoading,
currentConversationId,
appPrevChatTree,
newConversationInputs,
newConversationInputsRef,
handleNewConversation,
// handleChangeConversation,
handleNewConversationCompleted,
// chatShouldReloadKey,
isInstalledApp,
// appId,
handleFeedback,
currentChatInstanceRef,
// clearChatList,
// setClearChatList,
isResponding,
setIsResponding,
} = useChatWithHistory(installedAppInfo, newInputs)
return ( return (
<ChatWithHistoryContext.Provider <ChatWithHistoryContext.Provider
value={{ value={{
appInfoError, // appInfoError,
appInfoLoading, // appInfoLoading,
appData, // appData,
appParams, appParams,
appMeta, // appMeta,
appChatListDataLoading, // appChatListDataLoading,
currentConversationId, currentConversationId,
currentConversationItem:undefined, currentConversationItem: undefined,
appPrevChatTree, appPrevChatTree,
// pinnedConversationList, // pinnedConversationList,
// conversationList, // conversationList,
...@@ -114,29 +139,29 @@ const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, c ...@@ -114,29 +139,29 @@ const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({ installedAppInfo, c
// inputsForms, // inputsForms,
handleNewConversation, handleNewConversation,
// handleStartChat, // handleStartChat,
handleChangeConversation, // handleChangeConversation,
// handlePinConversation, // handlePinConversation,
// handleUnpinConversation, // handleUnpinConversation,
// handleDeleteConversation, // handleDeleteConversation,
// conversationRenaming, // conversationRenaming,
// handleRenameConversation, // handleRenameConversation,
handleNewConversationCompleted, handleNewConversationCompleted,
chatShouldReloadKey, // chatShouldReloadKey,
isMobile, // isMobile,
isInstalledApp, isInstalledApp,
appId, // appId,
handleFeedback, handleFeedback,
currentChatInstanceRef, currentChatInstanceRef,
themeBuilder, // themeBuilder,
// sidebarCollapseState, // sidebarCollapseState,
// handleSidebarCollapse, // handleSidebarCollapse,
clearChatList, // clearChatList,
setClearChatList, // setClearChatList,
isResponding, isResponding,
setIsResponding, setIsResponding,
currentConversationInputs:null, currentConversationInputs: null,
// setCurrentConversationInputs, // setCurrentConversationInputs,
isShowPracticeButton isShowPracticeButton,
}}> }}>
<ChatWithHistory className={className} /> <ChatWithHistory className={className} />
</ChatWithHistoryContext.Provider> </ChatWithHistoryContext.Provider>
...@@ -147,7 +172,6 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta ...@@ -147,7 +172,6 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
const [initialized, setInitialized] = useState(false) const [initialized, setInitialized] = useState(false)
const [appUnavailable, setAppUnavailable] = useState<boolean>(false) const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
const [isUnknownReason, setIsUnknownReason] = useState<boolean>(false) const [isUnknownReason, setIsUnknownReason] = useState<boolean>(false)
useAsyncEffect(async () => { useAsyncEffect(async () => {
if (!initialized) { if (!initialized) {
if (!installedAppInfo) { if (!installedAppInfo) {
...@@ -164,13 +188,10 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta ...@@ -164,13 +188,10 @@ const ChatWithHistoryWrapWithCheckToken: FC<ChatWithHistoryWrapProps> = ({ insta
} }
setInitialized(true) setInitialized(true)
} }
}, []) }, [initialized, installedAppInfo]) // 添加正确依赖
if (!initialized) return null if (!initialized) return null
else if (appUnavailable) return <AppUnavailable isUnknownReason={isUnknownReason} />
if (appUnavailable) return <AppUnavailable isUnknownReason={isUnknownReason} /> else return <ChatWithHistoryWrap installedAppInfo={installedAppInfo} className={className} />
return <ChatWithHistoryWrap installedAppInfo={installedAppInfo} className={className} />
} }
export default ChatWithHistoryWrapWithCheckToken export default ChatWithHistoryWrapWithCheckToken
...@@ -7,31 +7,16 @@ import cn from '@/utils/classnames' ...@@ -7,31 +7,16 @@ import cn from '@/utils/classnames'
type BasicContentProps = { type BasicContentProps = {
item: ChatItem item: ChatItem
} }
const BasicContent: FC<BasicContentProps> = ({ const BasicContent: FC<BasicContentProps> = ({ item }) => {
item, const { id, annotation, content } = item
}) => { // console.log(content)
const { if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} />
annotation,
content,
} = item
if (annotation?.logAnnotation)
return <Markdown content={annotation?.logAnnotation.content || ''} />
return ( return <Markdown className={cn(item.isError && '!text-[#F04438]')} content={content} id={id} />
<Markdown
className={cn(
item.isError && '!text-[#F04438]',
)}
content={content}
/>
)
} }
const MemoizedBasicContent = memo(BasicContent, (prev, next) => { const MemoizedBasicContent = memo(BasicContent, (prev, next) => {
return ( return prev.item.content === next.item.content
prev.item.content === next.item.content &&
prev.item.annotation?.logAnnotation?.content === next.item.annotation?.logAnnotation?.content
)
}) })
export default MemoizedBasicContent export default memo(MemoizedBasicContent)
...@@ -28,15 +28,29 @@ type AnswerProps = { ...@@ -28,15 +28,29 @@ type AnswerProps = {
isLast?: boolean isLast?: boolean
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
hideProcessDetail?: boolean hideProcessDetail?: boolean
appData?: AppData // appData?: AppData
noChatInput?: boolean noChatInput?: boolean
switchSibling?: (siblingMessageId: string) => void switchSibling?: (siblingMessageId: string) => void
} }
const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, responding, showPromptLog, isLast, chatAnswerContainerInner, hideProcessDetail, appData, noChatInput, switchSibling }) => { const Answer: FC<AnswerProps> = ({
item,
question,
index,
config,
answerIcon,
responding,
showPromptLog,
isLast,
chatAnswerContainerInner,
hideProcessDetail,
// appData,
noChatInput,
switchSibling,
}) => {
const { t } = useTranslation() const { t } = useTranslation()
const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item
const hasAgentThoughts = !!agent_thoughts?.length const hasAgentThoughts = !!agent_thoughts?.length
// console.log(content)
const [containerWidth, setContainerWidth] = useState(0) const [containerWidth, setContainerWidth] = useState(0)
const [contentWidth, setContentWidth] = useState(0) const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
...@@ -68,7 +82,6 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re ...@@ -68,7 +82,6 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
resizeObserver.disconnect() resizeObserver.disconnect()
} }
}, []) }, [])
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"> <div className="relative h-10 w-10 shrink-0">
...@@ -81,8 +94,25 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re ...@@ -81,8 +94,25 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
</div> </div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2" ref={containerRef}> <div className="chat-answer-container group ml-4 w-0 grow pb-2" ref={containerRef}>
<div className={cn('group relative pr-14', chatAnswerContainerInner)}> <div className={cn('group relative pr-14', chatAnswerContainerInner)}>
<div ref={contentRef} className={cn('body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary', workflowProcess && 'w-full')}> <div
{!responding && <Operation hasWorkflowProcess={!!workflowProcess} maxSize={containerWidth - contentWidth - 4} contentWidth={contentWidth} item={item} isLast={isLast} question={question} index={index} showPromptLog={showPromptLog} noChatInput={noChatInput} />} ref={contentRef}
className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
workflowProcess && 'w-full',
)}>
{!responding && (
<Operation
hasWorkflowProcess={!!workflowProcess}
maxSize={containerWidth - contentWidth - 4}
contentWidth={contentWidth}
item={item}
isLast={isLast}
question={question}
index={index}
showPromptLog={showPromptLog}
noChatInput={noChatInput}
/>
)}
{/** Render the normal steps */} {/** Render the normal steps */}
{/* {workflowProcess && !hideProcessDetail && ( {/* {workflowProcess && !hideProcessDetail && (
<WorkflowProcessItem <WorkflowProcessItem
...@@ -107,8 +137,12 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re ...@@ -107,8 +137,12 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
)} )}
{content && !hasAgentThoughts && <BasicContent item={item} />} {content && !hasAgentThoughts && <BasicContent item={item} />}
{hasAgentThoughts && <AgentContent item={item} responding={responding} content={content} />} {hasAgentThoughts && <AgentContent item={item} responding={responding} content={content} />}
{!!allFiles?.length && <FileList className="my-1" files={allFiles} showDeleteAction={false} showDownloadAction canPreview />} {!!allFiles?.length && (
{!!message_files?.length && <FileList className="my-1" files={message_files} showDeleteAction={false} showDownloadAction canPreview />} <FileList className="my-1" files={allFiles} showDeleteAction={false} showDownloadAction canPreview />
)}
{!!message_files?.length && (
<FileList className="my-1" files={message_files} showDeleteAction={false} showDownloadAction canPreview />
)}
{/* {annotation?.id && annotation.authorName && ( {/* {annotation?.id && annotation.authorName && (
<EditTitle <EditTitle
className="mt-1" className="mt-1"
...@@ -118,7 +152,9 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re ...@@ -118,7 +152,9 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
/> />
)} */} )} */}
{/* <SuggestedQuestions item={item} /> */} {/* <SuggestedQuestions item={item} /> */}
{!!citation?.length && !responding && <Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />} {!!citation?.length && !responding && (
<Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />
)}
{/* {item.siblingCount && item.siblingCount > 1 && item.siblingIndex !== undefined && ( {/* {item.siblingCount && item.siblingCount > 1 && item.siblingIndex !== undefined && (
<div className="flex items-center justify-center pt-3.5 text-sm"> <div className="flex items-center justify-center pt-3.5 text-sm">
<button className={`${item.prevSibling ? 'opacity-100' : 'opacity-30'}`} disabled={!item.prevSibling} onClick={() => item.prevSibling && switchSibling?.(item.prevSibling)}> <button className={`${item.prevSibling ? 'opacity-100' : 'opacity-30'}`} disabled={!item.prevSibling} onClick={() => item.prevSibling && switchSibling?.(item.prevSibling)}>
...@@ -140,11 +176,14 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re ...@@ -140,11 +176,14 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
) )
} }
const AnswerMemo = memo(Answer,(prevProps: AnswerProps, nextProps: AnswerProps) => { // const AnswerMemo = memo(Answer, (prevProps: AnswerProps, nextProps: AnswerProps) => {
return (
prevProps.item.content === nextProps.item.content && // return true
prevProps.isLast === nextProps.isLast && // // return (
prevProps.responding === nextProps.responding // // !nextProps.item.content ||
) // // (prevProps.item.content === nextProps.item.content &&
}) // // prevProps.isLast === nextProps.isLast &&
export default AnswerMemo // // prevProps.responding === nextProps.responding)
// // )
// })
export default memo(Answer)
...@@ -29,9 +29,9 @@ type ChatInputAreaProps = { ...@@ -29,9 +29,9 @@ type ChatInputAreaProps = {
speechToTextConfig?: EnableType speechToTextConfig?: EnableType
onSend?: OnSend onSend?: OnSend
onRestart: () => void onRestart: () => void
inputs?: Record<string, any> // inputs?: Record<string, any>
inputsForm?: InputForm[] // inputsForm?: InputForm[]
theme?: Theme | null // theme?: Theme | null
isResponding?: boolean isResponding?: boolean
disabled?: boolean disabled?: boolean
} }
...@@ -43,11 +43,11 @@ const ChatInputArea = ({ ...@@ -43,11 +43,11 @@ const ChatInputArea = ({
visionConfig, visionConfig,
speechToTextConfig = { enabled: true }, speechToTextConfig = { enabled: true },
onRestart, onRestart,
inputs = {}, // inputs = {},
inputsForm = [], // inputsForm = [],
theme, // theme,
isResponding, isResponding,
disabled, // disabled,
}: ChatInputAreaProps) => { }: ChatInputAreaProps) => {
const { t } = useTranslation() const { t } = useTranslation()
const { notify } = useToastContext() const { notify } = useToastContext()
...@@ -183,7 +183,7 @@ const ChatInputArea = ({ ...@@ -183,7 +183,7 @@ const ChatInputArea = ({
onShowVoiceInput={handleShowVoiceInput} onShowVoiceInput={handleShowVoiceInput}
onRestart={handleRestart} onRestart={handleRestart}
onSend={handleSend} onSend={handleSend}
theme={theme} // theme={theme}
/> />
) )
// const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} /> // const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} />
......
...@@ -25,14 +25,14 @@ type FooterProps = { ...@@ -25,14 +25,14 @@ type FooterProps = {
onRestart: () => void onRestart: () => void
inputs?: Record<string, any> inputs?: Record<string, any>
inputsForm?: InputForm[] inputsForm?: InputForm[]
themeBuilder?: ThemeBuilder // themeBuilder?: ThemeBuilder
config?: ChatConfig config?: ChatConfig
chatFooterRef: React.RefObject<HTMLDivElement> chatFooterRef: React.RefObject<HTMLDivElement>
chatFooterInnerRef: React.RefObject<HTMLDivElement> chatFooterInnerRef: React.RefObject<HTMLDivElement>
isResponding?: boolean isResponding?: boolean
} }
const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onRestart, inputs, inputsForm, themeBuilder, config, suggestedQuestions, isShowPracticeButton, chatFooterRef, chatFooterInnerRef, isResponding }) => { const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onRestart, inputs, inputsForm, config, suggestedQuestions, isShowPracticeButton, chatFooterRef, chatFooterInnerRef, isResponding }) => {
const { t } = useTranslation() const { t } = useTranslation()
const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend
return ( return (
...@@ -43,7 +43,7 @@ const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName ...@@ -43,7 +43,7 @@ const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName
{isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />} {isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />}
</div> </div>
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} isMobile={isMobile} />} {hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} isMobile={isMobile} />}
{!noChatInput && <ChatInputArea disabled={inputDisabled} showFeatureBar={showFeatureBar} showFileUpload={showFileUpload} featureBarDisabled={isResponding} onFeatureBarClick={onFeatureBarClick} visionConfig={config?.file_upload} speechToTextConfig={config?.speech_to_text} onSend={onSend} onRestart={onRestart} inputs={inputs} inputsForm={inputsForm} theme={themeBuilder?.theme} isResponding={isResponding} />} {!noChatInput && <ChatInputArea disabled={inputDisabled} showFeatureBar={showFeatureBar} showFileUpload={showFileUpload} featureBarDisabled={isResponding} onFeatureBarClick={onFeatureBarClick} visionConfig={config?.file_upload} speechToTextConfig={config?.speech_to_text} onSend={onSend} onRestart={onRestart} isResponding={isResponding} />}
</div> </div>
</div> </div>
) )
......
...@@ -44,7 +44,8 @@ export const useChat = ( ...@@ -44,7 +44,8 @@ export const useChat = (
prevChatTree?: ChatItemInTree[], prevChatTree?: ChatItemInTree[],
stopChat?: (taskId: string) => void, stopChat?: (taskId: string) => void,
clearChatList?: boolean, clearChatList?: boolean,
clearChatListCallback?: (state: boolean) => void clearChatListCallback?: (state: boolean) => void,
currentConversationId?: string,
) => { ) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { formatTime } = useTimestamp(); const { formatTime } = useTimestamp();
...@@ -306,7 +307,7 @@ export const useChat = ( ...@@ -306,7 +307,7 @@ export const useChat = (
const { query, files, inputs, ...restData } = data; const { query, files, inputs, ...restData } = data;
const bodyParams = { const bodyParams = {
response_mode: "streaming", response_mode: "streaming",
conversation_id: conversationId.current, conversation_id:currentConversationId, //conversationId.current,
files: getProcessedFiles(files || []), files: getProcessedFiles(files || []),
query, query,
inputs: getProcessedInputs( inputs: getProcessedInputs(
...@@ -315,39 +316,39 @@ export const useChat = ( ...@@ -315,39 +316,39 @@ export const useChat = (
), ),
...restData, ...restData,
}; };
if (bodyParams?.files?.length) { // if (bodyParams?.files?.length) {
bodyParams.files = bodyParams.files.map((item) => { // bodyParams.files = bodyParams.files.map((item) => {
if (item.transfer_method === TransferMethod.local_file) { // if (item.transfer_method === TransferMethod.local_file) {
return { // return {
...item, // ...item,
url: "", // url: "",
}; // };
} // }
return item; // return item;
}); // });
} // }
let isAgentMode = false; let isAgentMode = false;
let hasSetResponseId = false; let hasSetResponseId = false;
let ttsUrl = ""; // let ttsUrl = "";
let ttsIsPublic = false; // let ttsIsPublic = false;
if (params.token) { // if (params.token) {
ttsUrl = "/text-to-audio"; // ttsUrl = "/text-to-audio";
ttsIsPublic = true; // ttsIsPublic = true;
} else if (params.appId) { // } else if (params.appId) {
if (pathname.search("explore/installed") > -1) // if (pathname.search("explore/installed") > -1)
ttsUrl = `/installed-apps/${params.appId}/text-to-audio`; // ttsUrl = `/installed-apps/${params.appId}/text-to-audio`;
else ttsUrl = `/apps/${params.appId}/text-to-audio`; // else ttsUrl = `/apps/${params.appId}/text-to-audio`;
} // }
const player = AudioPlayerManager.getInstance().getAudioPlayer( // const player = AudioPlayerManager.getInstance().getAudioPlayer(
ttsUrl, // ttsUrl,
ttsIsPublic, // ttsIsPublic,
uuidV4(), // uuidV4(),
"none", // "none",
"none", // "none",
(_: any): any => {} // (_: any): any => {}
); // );
ssePost( ssePost(
url, url,
{ {
......
...@@ -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-06-29 02:06:50 * @LastEditTime: 2025-07-02 20:51:53
* @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
*/ */
...@@ -27,7 +27,7 @@ import chatStyles from './chat.module.css' ...@@ -27,7 +27,7 @@ import chatStyles from './chat.module.css'
import { FileEntity } from '../../file-uploader/types' import { FileEntity } from '../../file-uploader/types'
export type ChatProps = { export type ChatProps = {
appData?: AppData // appData?: AppData
chatList: ChatItem[] chatList: ChatItem[]
config?: ChatConfig config?: ChatConfig
isResponding?: boolean isResponding?: boolean
...@@ -47,7 +47,7 @@ export type ChatProps = { ...@@ -47,7 +47,7 @@ export type ChatProps = {
// showPromptLog?: boolean // showPromptLog?: boolean
questionIcon?: ReactNode questionIcon?: ReactNode
answerIcon?: ReactNode answerIcon?: ReactNode
allToolIcons?: Record<string, string | Emoji> // allToolIcons?: Record<string, string | Emoji>
// onAnnotationEdited?: (question: string, answer: string, index: number) => void // onAnnotationEdited?: (question: string, answer: string, index: number) => void
// onAnnotationAdded?: ( // onAnnotationAdded?: (
// annotationId: string, // annotationId: string,
...@@ -57,7 +57,7 @@ export type ChatProps = { ...@@ -57,7 +57,7 @@ export type ChatProps = {
// index: number, // index: number,
// ) => void // ) => void
// onAnnotationRemoved?: (index: number) => void // onAnnotationRemoved?: (index: number) => void
chatNode?: ReactNode // chatNode?: ReactNode
onFeedback?: (messageId: string, feedback: Feedback) => void onFeedback?: (messageId: string, feedback: Feedback) => void
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
// hideProcessDetail?: boolean // hideProcessDetail?: boolean
...@@ -75,7 +75,7 @@ export type ChatProps = { ...@@ -75,7 +75,7 @@ export type ChatProps = {
} }
const Chat: FC<ChatProps> = ({ const Chat: FC<ChatProps> = ({
appData, // appData,
config, config,
onSend, onSend,
onRestart, onRestart,
...@@ -88,9 +88,9 @@ const Chat: FC<ChatProps> = ({ ...@@ -88,9 +88,9 @@ const Chat: FC<ChatProps> = ({
onStopResponding, onStopResponding,
noChatInput, noChatInput,
chatContainerClassName, chatContainerClassName,
chatContainerInnerClassName, // chatContainerInnerClassName,
chatFooterClassName, // chatFooterClassName,
chatFooterInnerClassName, // chatFooterInnerClassName,
suggestedQuestions, suggestedQuestions,
// showPromptLog, // showPromptLog,
questionIcon, questionIcon,
...@@ -98,7 +98,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -98,7 +98,7 @@ const Chat: FC<ChatProps> = ({
// onAnnotationAdded, // onAnnotationAdded,
// onAnnotationEdited, // onAnnotationEdited,
// onAnnotationRemoved, // onAnnotationRemoved,
chatNode, // chatNode,
onFeedback, onFeedback,
chatAnswerContainerInner, chatAnswerContainerInner,
// hideProcessDetail, // hideProcessDetail,
...@@ -189,7 +189,9 @@ const Chat: FC<ChatProps> = ({ ...@@ -189,7 +189,9 @@ const Chat: FC<ChatProps> = ({
// }) // })
// } // }
// }) // })
const chatContainerInnerClassName=`mx-auto pt-6 w-full max-w-[800px] ${isMobile && 'px-4'}`
const chatFooterClassName="pb-4"
const chatFooterInnerClassName=`mx-auto w-full max-w-[800px] ${isMobile ? 'px-2' : 'px-4'}`
// 使用 MutationObserver 监听 DOM 变化 // 使用 MutationObserver 监听 DOM 变化
useEffect(() => { useEffect(() => {
const container = chatContainerRef.current const container = chatContainerRef.current
...@@ -279,16 +281,11 @@ const Chat: FC<ChatProps> = ({ ...@@ -279,16 +281,11 @@ const Chat: FC<ChatProps> = ({
config={config} config={config}
chatList={chatList} chatList={chatList}
isResponding={isResponding} isResponding={isResponding}
// showPromptLog={showPromptLog}
questionIcon={questionIcon} questionIcon={questionIcon}
answerIcon={answerIcon} answerIcon={answerIcon}
onSend={handleSend} onSend={handleSend}
onRegenerate={onRegenerate} onRegenerate={onRegenerate}
onRestart={onRestart} onRestart={onRestart}
// onStopResponding={onStopResponding}
// onAnnotationAdded={onAnnotationAdded}
// onAnnotationEdited={onAnnotationEdited}
// onAnnotationRemoved={onAnnotationRemoved}
onFeedback={onFeedback}> onFeedback={onFeedback}>
<div className="relative h-full"> <div className="relative h-full">
<div <div
...@@ -298,7 +295,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -298,7 +295,7 @@ const Chat: FC<ChatProps> = ({
chatContainerClassName, chatContainerClassName,
chatStyles.chatContainer, chatStyles.chatContainer,
)}> )}>
{chatNode} {/* {chatNode} */}
<div ref={chatContainerInnerRef} className={cn('w-full', !noSpacing && 'px-8', chatContainerInnerClassName)}> <div ref={chatContainerInnerRef} className={cn('w-full', !noSpacing && 'px-8', chatContainerInnerClassName)}>
{config?.initial_message && ( {config?.initial_message && (
<InitQuestions <InitQuestions
...@@ -312,7 +309,6 @@ const Chat: FC<ChatProps> = ({ ...@@ -312,7 +309,6 @@ const Chat: FC<ChatProps> = ({
const isLast = item.id === chatList[chatList.length - 1]?.id const isLast = item.id === chatList[chatList.length - 1]?.id
return ( return (
<Answer <Answer
appData={appData}
key={item.id} key={item.id}
item={item} item={item}
question={chatList[index - 1]?.content} question={chatList[index - 1]?.content}
...@@ -321,9 +317,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -321,9 +317,7 @@ const Chat: FC<ChatProps> = ({
answerIcon={answerIcon} answerIcon={answerIcon}
isLast={isLast} isLast={isLast}
responding={isLast && isResponding} responding={isLast && isResponding}
// showPromptLog={showPromptLog}
chatAnswerContainerInner={chatAnswerContainerInner} chatAnswerContainerInner={chatAnswerContainerInner}
// hideProcessDetail={hideProcessDetail}
noChatInput={noChatInput} noChatInput={noChatInput}
switchSibling={switchSibling} switchSibling={switchSibling}
/> />
...@@ -341,7 +335,7 @@ const Chat: FC<ChatProps> = ({ ...@@ -341,7 +335,7 @@ const Chat: FC<ChatProps> = ({
chatFooterInnerClassName={chatFooterInnerClassName} chatFooterInnerClassName={chatFooterInnerClassName}
onSend={handleSend} onSend={handleSend}
inputs={inputs} inputs={inputs}
inputsForm={inputsForm} // inputsForm={inputsForm}
onRestart={onRestart} onRestart={onRestart}
noStopResponding={noStopResponding} noStopResponding={noStopResponding}
onStopResponding={onStopResponding} onStopResponding={onStopResponding}
......
...@@ -2,29 +2,34 @@ import { useChatContext } from '@/app/components/base/chat/chat/context' ...@@ -2,29 +2,34 @@ import { useChatContext } from '@/app/components/base/chat/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'
const MarkdownButton = ({ node }: any) => { import { InputMessageType } from '@/app/components/base/chat/types'
const MarkdownButton = ({ node, messageId }:any) => {
const { onSend } = useChatContext() const { onSend } = useChatContext()
const variant = node.properties.dataVariant const variant = node.properties.dataVariant
const message = node.properties.dataMessage const message = node.properties.dataMessage
const link = node.properties.dataLink const link = node.properties.dataLink
const size = node.properties.dataSize const size = node.properties.dataSize
return (
return <Button <Button
variant={variant} variant={variant}
size={size} size={size}
className={cn('!h-auto min-h-8 select-none whitespace-normal !px-3')} className={cn('!h-auto min-h-8 select-none whitespace-normal !px-3')}
onClick={() => { onClick={() => {
if (isValidUrl(link)) { if (isValidUrl(link || '')) {
window.open(link, '_blank') window.open(link, '_blank')
return return
} }
if(!message) if (message) {
onSend?.({ message: message, type: InputMessageType.SYSTEM })
if (messageId) {
document.getElementById(messageId)?.classList.add('pointer-events-none', 'opacity-50')
}
return return
onSend?.(message) }
}} }}>
> <span className="text-[13px]">{node.children[0]?.value || ''}</span>
<span className='text-[13px]'>{node.children[0]?.value || ''}</span>
</Button> </Button>
)
} }
MarkdownButton.displayName = 'MarkdownButton' MarkdownButton.displayName = 'MarkdownButton'
......
/**
* @fileoverview Paragraph component for rendering <p> tags in Markdown.
* Extracted from the main markdown renderer for modularity.
* Handles special rendering for paragraphs that directly contain an image.
*/
import React from 'react'
const Div = (paragraph: any) => {
console.log(paragraph)
return <div>{paragraph.children}</div>
}
export default Div
...@@ -7,21 +7,23 @@ import React from 'react' ...@@ -7,21 +7,23 @@ import React from 'react'
import ImageGallery from '@/app/components/base/image-gallery' import ImageGallery from '@/app/components/base/image-gallery'
const Paragraph = (paragraph: any) => { const Paragraph = (paragraph: any) => {
const { node }: any = paragraph const { node,messageId,children }: any = paragraph
const children_node = node.children const children_node = node.children
if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') { if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
return ( return (
<div className="markdown-img-wrapper"> <div className="markdown-img-wrapper">
<ImageGallery srcs={[children_node[0].properties.src]} /> <ImageGallery srcs={[children_node[0].properties.src]} />
{ {
Array.isArray(paragraph.children) && paragraph.children.length > 1 && ( Array.isArray(children) && children.length > 1 && (
<div className="mt-2">{paragraph.children.slice(1)}</div> <div className="mt-2">{children.slice(1)}</div>
) )
} }
</div> </div>
) )
} }
return <p>{paragraph.children}</p> if(node.properties.dataDisable==='disable' && messageId){
return <div id={messageId}>{children}</div>
}
return <p>{children}</p>
} }
export default Paragraph export default Paragraph
.chatContainer {
scroll-behavior: smooth;
overflow-y: auto;
height: 100%;
}
.streaming_text {
transition: opacity 3s ease, transform 3s ease;
}
...@@ -19,7 +19,13 @@ import { useMemo } from 'react' ...@@ -19,7 +19,13 @@ import { useMemo } from 'react'
* are noted in their respective files if applicable. * are noted in their respective files if applicable.
*/ */
export function Markdown(props: { content: string; className?: string; customDisallowedElements?: string[] }) { type MarkdownProps = {
content: string
className?: string
customDisallowedElements?: string[]
id?: string
}
export function Markdown(props: MarkdownProps) {
const markdown = useMemo(() => { const markdown = useMemo(() => {
const latexContent = flow([preprocessThinkTag, preprocessLaTeX])(props.content) const latexContent = flow([preprocessThinkTag, preprocessLaTeX])(props.content)
return ( return (
...@@ -47,15 +53,24 @@ export function Markdown(props: { content: string; className?: string; customDis ...@@ -47,15 +53,24 @@ export function Markdown(props: { content: string; className?: string; customDis
}, },
]} ]}
urlTransform={customUrlTransform} urlTransform={customUrlTransform}
disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body', ...(props.customDisallowedElements || [])]} disallowedElements={[
'iframe',
'head',
'html',
'meta',
'link',
'style',
'body',
...(props.customDisallowedElements || []),
]}
components={{ components={{
code: Code, code: Code,
img: Img, img: Img,
video: Video, video: Video,
audio: Audio, audio: Audio,
a: Link, a: Link,
p: Paragraph, p: properties => <Paragraph {...properties} messageId={props.id} />,
button: MarkdownButton, button: properties => <MarkdownButton {...properties} messageId={props.id} />,
form: MarkdownForm, form: MarkdownForm,
script: Script as any, script: Script as any,
details: Think, details: Think,
...@@ -66,5 +81,5 @@ export function Markdown(props: { content: string; className?: string; customDis ...@@ -66,5 +81,5 @@ export function Markdown(props: { content: string; className?: string; customDis
</div> </div>
) )
}, [props.content]) }, [props.content])
return (markdown) return markdown
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!