Commit 38201494 by 李伟康

feat(chat): 添加手动停止功能并优化思考组件

- 添加 isManuallyStopped 状态跟踪手动停止操作
- 在 ChatListProvider 中传递手动停止状态
- 优化 handleStop 函数清除最后一个空回答节点
- 新对话时重置手动停止状态
- 修复 Think 组件展开收起逻辑
- 改进 Markdown 组件自动滚动行为
- 调整代码块处理逻辑保留换行符
1 parent 392a01fd
...@@ -54,6 +54,7 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) = ...@@ -54,6 +54,7 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) =
handleFeedback, handleFeedback,
// appInfoLoading, // appInfoLoading,
handleNewConversation, handleNewConversation,
isManuallyStopped, // 添加这个状态
} = useChat(inputs) } = useChat(inputs)
useEffect(() => { useEffect(() => {
if (autoSendQuestion && config.initial_message !== undefined && isAutoSend) { if (autoSendQuestion && config.initial_message !== undefined && isAutoSend) {
...@@ -110,7 +111,7 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) = ...@@ -110,7 +111,7 @@ const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) =
onFeedback={handleFeedback} onFeedback={handleFeedback}
onStopResponding={handleStop}> onStopResponding={handleStop}>
<ChatRespondingProvider isResponding={isResponding}> <ChatRespondingProvider isResponding={isResponding}>
<ChatListProvider chatList={chatList}> <ChatListProvider chatList={chatList} isManuallyStopped={isManuallyStopped}>
<Chat /> <Chat />
</ChatListProvider> </ChatListProvider>
</ChatRespondingProvider> </ChatRespondingProvider>
......
...@@ -7,10 +7,12 @@ import { useMemo } from 'react' ...@@ -7,10 +7,12 @@ import { useMemo } from 'react'
type ChatListContext = { type ChatListContext = {
chatList: ChatItem[] chatList: ChatItem[]
isManuallyStopped?: boolean // 添加手动停止标记
} }
const ChatListContext = createContext<ChatListContext>({ const ChatListContext = createContext<ChatListContext>({
chatList: [], chatList: [],
isManuallyStopped: false,
}) })
export const useChatListContext = () => useContext(ChatListContext) export const useChatListContext = () => useContext(ChatListContext)
...@@ -19,7 +21,7 @@ type Props = { ...@@ -19,7 +21,7 @@ type Props = {
children: React.ReactNode children: React.ReactNode
} & ChatListContext } & ChatListContext
export const ChatListProvider = ({ children, chatList }: Props) => { export const ChatListProvider = ({ children, chatList, isManuallyStopped }: Props) => {
const value = { chatList } const value = { chatList, isManuallyStopped }
return <ChatListContext.Provider value={value}>{children}</ChatListContext.Provider> return <ChatListContext.Provider value={value}>{children}</ChatListContext.Provider>
} }
\ No newline at end of file \ No newline at end of file
...@@ -52,6 +52,7 @@ interface ChatState { ...@@ -52,6 +52,7 @@ interface ChatState {
isResponding: boolean isResponding: boolean
suggestedQuestions: string[] suggestedQuestions: string[]
targetMessageId?: string targetMessageId?: string
isManuallyStopped?: boolean // 标记是否手动停止
// newConversationInputs: Record<string, any> // newConversationInputs: Record<string, any>
} }
...@@ -80,6 +81,7 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -80,6 +81,7 @@ export const useChat = (inputs: Inputs = {}) => {
isResponding: false, isResponding: false,
suggestedQuestions: [], suggestedQuestions: [],
targetMessageId: undefined, targetMessageId: undefined,
isManuallyStopped: false, // 初始化为 false
// newConversationInputs: inputs, // newConversationInputs: inputs,
}) })
...@@ -151,13 +153,27 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -151,13 +153,27 @@ export const useChat = (inputs: Inputs = {}) => {
// 处理停止响应 // 处理停止响应
const handleStop = useCallback(() => { const handleStop = useCallback(() => {
refs.current.hasStopResponded = true refs.current.hasStopResponded = true
setState(prev => ({ ...prev, isResponding: false })) refs.current.isResponding = false
setState(prev => ({
...prev,
isResponding: false,
isManuallyStopped: true // 标记为手动停止
}))
setTimeout(() => { setTimeout(() => {
if (stopChat && refs.current.taskId) stopChat(refs.current.taskId) if (stopChat && refs.current.taskId) stopChat(refs.current.taskId)
if (refs.current.conversationMessagesAbortController) refs.current.conversationMessagesAbortController.abort() if (refs.current.conversationMessagesAbortController) refs.current.conversationMessagesAbortController.abort()
if (refs.current.suggestedQuestionsAbortController) refs.current.suggestedQuestionsAbortController.abort() if (refs.current.suggestedQuestionsAbortController) refs.current.suggestedQuestionsAbortController.abort()
}, 100)
// 清除最后一个空回答节点
const lastAnswer = getLastAnswer(refs.current.chatTree)
if (lastAnswer && !lastAnswer.content.trim()) {
setState(prev => ({
...prev,
chatTree: prev.chatTree.filter(item => item.id !== lastAnswer.id),
}))
}
}, 50)
}, [stopChat]) }, [stopChat])
// 初始化 handleStop // 初始化 handleStop
...@@ -180,15 +196,13 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -180,15 +196,13 @@ export const useChat = (inputs: Inputs = {}) => {
if (inputs) { if (inputs) {
refs.current.inputs = inputs refs.current.inputs = inputs
} }
if (!isSkipClear) {
setState(prev => ({ setState(prev => ({
...prev, ...prev,
chatTree: [], chatTree: [],
targetMessageId: undefined,
suggestedQuestions: [], suggestedQuestions: [],
targetMessageId: undefined,
isManuallyStopped: false, // 新对话时重置
})) }))
refs.current.chatList = []
}
}, []) }, [])
// 处理新对话完成 // 处理新对话完成
...@@ -385,7 +399,11 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -385,7 +399,11 @@ export const useChat = (inputs: Inputs = {}) => {
setState(prev => ({ ...prev, isResponding: true })) setState(prev => ({ ...prev, isResponding: true }))
refs.current.isResponding = true refs.current.isResponding = true
// 只有在非手动停止状态下才重置 hasStopResponded
// 如果当前是手动停止状态,说明用户刚停止了上一个回答,现在开始新的回答
if (!refs.current.hasStopResponded || state.isManuallyStopped) {
refs.current.hasStopResponded = false refs.current.hasStopResponded = false
}
const { query, files, inputs, ...restData } = data const { query, files, inputs, ...restData } = data
const bodyParams = { const bodyParams = {
...@@ -440,7 +458,10 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -440,7 +458,10 @@ export const useChat = (inputs: Inputs = {}) => {
}) })
}, },
async onCompleted(hasError?: boolean) { async onCompleted(hasError?: boolean) {
setState(prev => ({ ...prev, isResponding: false })) setState(prev => ({
...prev,
isResponding: false
}))
refs.current.isResponding = false refs.current.isResponding = false
if (hasError) return if (hasError) return
...@@ -660,7 +681,8 @@ export const useChat = (inputs: Inputs = {}) => { ...@@ -660,7 +681,8 @@ export const useChat = (inputs: Inputs = {}) => {
handleFeedback, handleFeedback,
suggestedQuestions, suggestedQuestions,
handleNewConversation, handleNewConversation,
isManuallyStopped: state.isManuallyStopped, // 添加手动停止状态
}), }),
[config, chatList, isResponding, suggestedQuestions], [config, chatList, isResponding, suggestedQuestions, state.isManuallyStopped],
) )
} }
...@@ -16,16 +16,13 @@ const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady, onThinkComple ...@@ -16,16 +16,13 @@ const BasicContent: FC<BasicContentProps> = ({ onJsonContentReady, onThinkComple
if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} /> if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} />
// 如果不应显示(已停止),且内容可能只包含 Think 标签,则不渲染
const shouldHideThink = !responding
return ( return (
<Markdown <Markdown
className={cn(isError && '!text-[#F04438]')} className={cn(isError && '!text-[#F04438]')}
content={content} content={content}
onJsonContentReady={onJsonContentReady} onJsonContentReady={onJsonContentReady}
onThinkComplete={onThinkComplete} onThinkComplete={onThinkComplete}
hideThink={shouldHideThink} responding={responding} // 传递 responding 状态
/> />
) )
} }
......
...@@ -29,6 +29,7 @@ interface ChatBodyContextType { ...@@ -29,6 +29,7 @@ interface ChatBodyContextType {
theme?: any theme?: any
isAnswer: boolean isAnswer: boolean
parentMessageId: ChatItem['parentMessageId'] parentMessageId: ChatItem['parentMessageId']
isManuallyStopped?: boolean // 添加手动停止标记
} }
// 创建 AnswerContext // 创建 AnswerContext
...@@ -85,7 +86,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -85,7 +86,7 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null) const contentRef = useRef<HTMLDivElement>(null)
const { isResponding } = useChatRespondingContext() const { isResponding } = useChatRespondingContext()
const { chatList } = useChatListContext() const { chatList, isManuallyStopped } = useChatListContext() as any
const isLast = useMemo(() => isAnswer && item.id === chatList[chatList.length - 1]?.id, [chatList.length, isAnswer]) const isLast = useMemo(() => isAnswer && item.id === chatList[chatList.length - 1]?.id, [chatList.length, isAnswer])
const responding = isLast && isResponding const responding = isLast && isResponding
...@@ -116,8 +117,9 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({ ...@@ -116,8 +117,9 @@ export const ChatBodyProvider: React.FC<ChatBodyProviderProps> = ({
isAnswer, isAnswer,
content, content,
parentMessageId, parentMessageId,
isManuallyStopped, // 添加到 context
}), }),
[content, isAnswer, isLast, isError, responding], [content, isAnswer, isLast, isError, responding, isManuallyStopped],
) )
return <ChatBodyContext.Provider value={value}>{children}</ChatBodyContext.Provider> return <ChatBodyContext.Provider value={value}>{children}</ChatBodyContext.Provider>
......
...@@ -42,6 +42,7 @@ const useThinkTimer = (children: any) => { ...@@ -42,6 +42,7 @@ const useThinkTimer = (children: any) => {
const [elapsedTime, setElapsedTime] = useState(0) const [elapsedTime, setElapsedTime] = useState(0)
const [isComplete, setIsComplete] = useState(false) const [isComplete, setIsComplete] = useState(false)
const timerRef = useRef<NodeJS.Timeout>() const timerRef = useRef<NodeJS.Timeout>()
const [isOpen, setIsOpen] = useState(false)
useEffect(() => { useEffect(() => {
if (isComplete) return if (isComplete) return
...@@ -59,11 +60,18 @@ const useThinkTimer = (children: any) => { ...@@ -59,11 +60,18 @@ const useThinkTimer = (children: any) => {
if (hasEndThink(children)) setIsComplete(true) if (hasEndThink(children)) setIsComplete(true)
}, [children]) }, [children])
return { elapsedTime, isComplete } // Initialize open state based on completion status
useEffect(() => {
if (!isComplete) {
setIsOpen(true)
}
}, [isComplete])
return { elapsedTime, isComplete, isOpen, setIsOpen }
} }
export const Think = ({ children, ...props }: any) => { export const Think = ({ children, ...props }: any) => {
const { elapsedTime, isComplete } = useThinkTimer(children) const { elapsedTime, isComplete, isOpen, setIsOpen } = useThinkTimer(children)
const displayContent = removeEndThink(children) const displayContent = removeEndThink(children)
const { t } = useTranslation() const { t } = useTranslation()
...@@ -78,11 +86,26 @@ export const Think = ({ children, ...props }: any) => { ...@@ -78,11 +86,26 @@ export const Think = ({ children, ...props }: any) => {
} }
}, [isComplete, props.onThinkComplete]) }, [isComplete, props.onThinkComplete])
// Handle summary click to toggle without scrolling
const handleSummaryClick = (e: React.MouseEvent<HTMLElement>) => {
e.preventDefault()
e.stopPropagation()
// Toggle the open state manually
setIsOpen(!isOpen)
}
if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details> if (!(props['data-think'] ?? false)) return <details {...props}>{children}</details>
return ( return (
<details {...(!isComplete && { open: true })} className="group"> <details
<summary className="flex cursor-pointer select-none list-none items-center whitespace-nowrap font-bold text-text-secondary"> open={isOpen}
className="group"
>
<summary
className="flex cursor-pointer select-none list-none items-center whitespace-nowrap font-bold text-text-secondary"
onClick={handleSummaryClick}
>
<div className="flex shrink-0 items-center think-class"> <div className="flex shrink-0 items-center think-class">
{/* <svg {/* <svg
className="mr-2 h-3 w-3 transition-transform duration-500 group-open:rotate-90" className="mr-2 h-3 w-3 transition-transform duration-500 group-open:rotate-90"
...@@ -96,7 +119,7 @@ export const Think = ({ children, ...props }: any) => { ...@@ -96,7 +119,7 @@ export const Think = ({ children, ...props }: any) => {
{isComplete ? `${t('common.chat.thought')}\t(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}`} {isComplete ? `${t('common.chat.thought')}\t(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}`}
</span> </span>
{isComplete ? ( {isComplete ? (
<div className={cn(s['arrow'], 'transition-transform duration-500 group-open:rotate-180')}> <div className={cn(s['arrow'], 'transition-transform duration-500', isOpen ? 'rotate-180' : '')}>
<img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" /> <img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" />
</div> </div>
) : ( ) : (
...@@ -104,7 +127,7 @@ export const Think = ({ children, ...props }: any) => { ...@@ -104,7 +127,7 @@ export const Think = ({ children, ...props }: any) => {
)} )}
</div> </div>
</summary> </summary>
{displayContent ? ( {displayContent && isOpen ? (
<div className="pt-2 border-l border-components-panel-border pl-2 text-text-secondary think-class"> <div className="pt-2 border-l border-components-panel-border pl-2 text-text-secondary think-class">
{displayContent} {displayContent}
</div> </div>
......
...@@ -39,6 +39,7 @@ type MarkdownProps = { ...@@ -39,6 +39,7 @@ type MarkdownProps = {
onJsonContentReady?: (jsonContent: any) => React.ReactNode, onJsonContentReady?: (jsonContent: any) => React.ReactNode,
onThinkComplete?: (isComplete: boolean) => void onThinkComplete?: (isComplete: boolean) => void
hideThink?: boolean hideThink?: boolean
responding?: boolean // 添加 responding 状态
} }
type MarkdownContent = { type MarkdownContent = {
...@@ -73,17 +74,16 @@ export function Markdown(props: MarkdownProps) { ...@@ -73,17 +74,16 @@ export function Markdown(props: MarkdownProps) {
jsonContent = allJsonBlocks[allJsonBlocks.length - 1] jsonContent = allJsonBlocks[allJsonBlocks.length - 1]
} }
// 第二步:彻底移除所有代码块 // 第二步:彻底移除所有代码块,但保留换行符
mainContent = mainContent mainContent = mainContent
// 移除 ```json 代码块(支持多种格式) // 移除 ```json 代码块(支持多种格式),替换为单个换行
.replace(/```json\r?\n([\s\S]*?)\r?\n```/g, '') .replace(/```json\r?\n([\s\S]*?)\r?\n```/g, '\n')
.replace(/```json([\s\S]*?)```/g, '') .replace(/```json([\s\S]*?)```/g, '\n')
// 移除其他代码块 // 移除其他代码块,替换为单个换行
.replace(/```\r?\n([\s\S]*?)\r?\n```/g, '') .replace(/```\r?\n([\s\S]*?)\r?\n```/g, '\n')
.replace(/```([\s\S]*?)```/g, '') .replace(/```([\s\S]*?)```/g, '\n')
// 清理空行 // 只清理连续3个以上的空行,保留正常的换行
.replace(/\n\s*\n\s*\n/g, '\n\n') .replace(/\n{3,}/g, '\n\n')
.replace(/^\s*\n/gm, '')
.trim() .trim()
return { mainContent, jsonContent } return { mainContent, jsonContent }
...@@ -100,25 +100,14 @@ export function Markdown(props: MarkdownProps) { ...@@ -100,25 +100,14 @@ export function Markdown(props: MarkdownProps) {
// 如果需要隐藏 Think,则移除所有 <details> 标签及其内容 // 如果需要隐藏 Think,则移除所有 <details> 标签及其内容
if (props.hideThink) { if (props.hideThink) {
console.log('Hiding Think tags, original content length:', filtered.length)
// 更宽松的正则表达式,匹配各种格式的 details 标签 // 更宽松的正则表达式,匹配各种格式的 details 标签
const beforeLength = filtered.length
filtered = filtered.replace(/<details[^>]*data-think[^>]*>[\s\S]*?<\/details>/gi, '') filtered = filtered.replace(/<details[^>]*data-think[^>]*>[\s\S]*?<\/details>/gi, '')
filtered = filtered.replace(/<details[^>]*data-think[^>]*>[\s\S]*/gi, '') filtered = filtered.replace(/<details[^>]*data-think[^>]*>[\s\S]*/gi, '')
console.log('After removing Think tags, content length:', filtered.length, 'removed:', beforeLength - filtered.length)
} }
// 移除所有 ```json 代码块 // 移除所有 ```json 和 ``` 标记,无论它们是否成对出现
filtered = filtered.replace(/```json\s*[\s\S]*?```/g, '') filtered = filtered.replace(/```json\s*/gi, '')
filtered = filtered.replace(/```\s*/gi, '')
// 移除所有其他代码块
filtered = filtered.replace(/```\s*[\s\S]*?```/g, '')
// 清理连续空行
filtered = filtered.replace(/\n{3,}/g, '\n\n')
// 移除行首的空白行
filtered = filtered.replace(/^\s*\n/gm, '')
return filtered.trim() return filtered.trim()
}, [latexContent, props.hideThink]) }, [latexContent, props.hideThink])
...@@ -126,23 +115,24 @@ export function Markdown(props: MarkdownProps) { ...@@ -126,23 +115,24 @@ export function Markdown(props: MarkdownProps) {
// 创建 ref 来引用 markdown 容器 // 创建 ref 来引用 markdown 容器
const markdownRef = useRef<HTMLDivElement>(null) const markdownRef = useRef<HTMLDivElement>(null)
const [shouldAutoScroll, setShouldAutoScroll] = useState(true) const [shouldAutoScroll, setShouldAutoScroll] = useState(true)
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null)
// 检测用户是否正在手动滚动 // 暴露禁用自动滚动的方法给子组件
useEffect(() => { useEffect(() => {
const handleUserScroll = () => { // 将方法挂载到 window 上,供 Think 组件调用
// 用户手动滚动时,暂时禁用自动滚动 ;(window as any).__disableMarkdownAutoScroll = () => {
setShouldAutoScroll(false) setShouldAutoScroll(false)
}
// 清除之前的定时器 return () => {
if (scrollTimeoutRef.current) { delete (window as any).__disableMarkdownAutoScroll
clearTimeout(scrollTimeoutRef.current)
} }
}, [])
// 设置一个新的定时器,在一段时间没有用户交互后重新启用自动滚动 // 检测用户是否正在手动滚动
scrollTimeoutRef.current = setTimeout(() => { useEffect(() => {
setShouldAutoScroll(true) const handleUserScroll = () => {
}, 2000) // 2秒后重新启用自动滚动 // 用户手动滚动时,禁用自动滚动
setShouldAutoScroll(false)
} }
// 添加滚动事件监听器 // 添加滚动事件监听器
...@@ -151,21 +141,37 @@ export function Markdown(props: MarkdownProps) { ...@@ -151,21 +141,37 @@ export function Markdown(props: MarkdownProps) {
window.addEventListener('scroll', handleUserScroll, { passive: true }) window.addEventListener('scroll', handleUserScroll, { passive: true })
return () => { return () => {
// 清理事件监听器和定时器 // 清理事件监听器
window.removeEventListener('wheel', handleUserScroll) window.removeEventListener('wheel', handleUserScroll)
window.removeEventListener('touchmove', handleUserScroll) window.removeEventListener('touchmove', handleUserScroll)
window.removeEventListener('scroll', handleUserScroll) window.removeEventListener('scroll', handleUserScroll)
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current)
}
} }
}, []) }, [])
// 当内容更新时,自动滚动到底部(仅在允许自动滚动时) // 当 responding 状态变化时,重置自动滚动标志
useEffect(() => {
if (props.responding) {
// 开始新的回复时,重新启用自动滚动
setShouldAutoScroll(true)
} else {
// 回复完成后,禁用自动滚动
setShouldAutoScroll(false)
}
}, [props.responding])
// 当内容更新且允许自动滚动时,自动滚动到底部
useEffect(() => { useEffect(() => {
if (markdownRef.current && shouldAutoScroll) { // 如果用户正在点击 Think 组件,不执行自动滚动
// 找到最近的滚动容器并滚动到底部 if ((window as any).__isUserClickingThink) {
return
}
if (!shouldAutoScroll || !props.responding) {
return
}
if (markdownRef.current) {
// 找到最近的滚动容器
let scrollContainer = markdownRef.current.parentElement let scrollContainer = markdownRef.current.parentElement
while (scrollContainer && scrollContainer.scrollHeight <= scrollContainer.clientHeight) { while (scrollContainer && scrollContainer.scrollHeight <= scrollContainer.clientHeight) {
scrollContainer = scrollContainer.parentElement scrollContainer = scrollContainer.parentElement
...@@ -180,7 +186,7 @@ export function Markdown(props: MarkdownProps) { ...@@ -180,7 +186,7 @@ export function Markdown(props: MarkdownProps) {
}) })
} }
} }
}, [filteredContent, contentObj.jsonContent, shouldAutoScroll]) }, [filteredContent, contentObj.jsonContent, shouldAutoScroll, props.responding])
// 如果过滤后内容为空且没有 JSON 内容,则不渲染任何内容 // 如果过滤后内容为空且没有 JSON 内容,则不渲染任何内容
if (!filteredContent && !contentObj.jsonContent) { if (!filteredContent && !contentObj.jsonContent) {
......
...@@ -420,7 +420,9 @@ ...@@ -420,7 +420,9 @@
margin-top: 0; margin-top: 0;
margin-bottom: 12px; margin-bottom: 12px;
} }
.markdown-body details{
margin-bottom: 0;
}
.markdown-body ul, .markdown-body ul,
.markdown-body ol { .markdown-body ol {
padding-left: 2em; padding-left: 2em;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!