Commit cf47d227 by Liu

fix:还原chat.tsx

parent 9f3fb994
......@@ -14,7 +14,7 @@ import type { ChatRecord } from '@/types/chat'
import { fetchSessionConversationId, fetchUserQaRecordPage } from '@/api/conversation'
import { fetchCheckTokenApi, fetchStreamResponse } from '@/api/chat'
import { fetchToolList } from '@/api/home'
import { clearCurrentToolId, fetchConversations, setCurrentToolId } from '@/store/conversationSlice'
import { clearCurrentToolId, clearShouldSendQuestion, fetchConversations, setCurrentToolId } from '@/store/conversationSlice'
import { getUserRolesForApi, safeSessionStorageGetItem, waitForToken } from '@/lib/utils'
import type { RootState } from '@/store'
import { useAppDispatch, useAppSelector } from '@/store/hook'
......@@ -37,13 +37,13 @@ export const Chat: React.FC = () => {
const initialToolId = toolIdFromUrl !== null ? toolIdFromUrl : toolIdFromState
const [isLoading, setIsLoading] = useState(false)
const [allItems, setAllItems] = useState<ChatRecord[]>([])
// 标记当前会话是否已有历史记录;null 表示尚未完成查询
const [hasHistory, setHasHistory] = useState<boolean | null>(null)
const dispatch = useAppDispatch()
const { currentToolId, conversations } = useAppSelector((state: RootState) => state.conversation)
const { shouldSendQuestion, currentToolId, conversations } = useAppSelector((state: RootState) => state.conversation)
const isAsking = useAppSelector((state: RootState) => state.chat.isAsking)
// 标记历史记录是否已加载完成,用于确保自动发送问题在历史记录加载后执行
const historyLoadedRef = useRef<{ conversationId: string | null }>({ conversationId: null })
// 保存待发送的问题,用于在历史记录加载完成后发送
const pendingQuestionRef = useRef<string | null>(null)
const scrollableRef = useRef<HTMLDivElement | any>(null)
const position = useScroll(scrollableRef)
const currentIdRef = useRef<string | undefined>(id)
......@@ -577,7 +577,6 @@ export const Chat: React.FC = () => {
const res = await fetchUserQaRecordPage(finalConversationId, toolId || safeSessionStorageGetItem('currentToolId') || '')
console.log('qaRes chatEditor2222222', res)
const qaRecords = res.data || []
const hasHistoryFlag = qaRecords.length > 0
const messages = [{ role: 'system' } as ChatRecord, ...processApiResponse(qaRecords)]
// 处理历史记录中的参考文档标记
const processedMessages = messages.map((item) => {
......@@ -596,7 +595,6 @@ export const Chat: React.FC = () => {
return item
})
setAllItems(processedMessages)
setHasHistory(hasHistoryFlag)
// 优先从 qaRecords 中查找 toolId(这是实际使用的)
const latestToolId = [...qaRecords].reverse().find(item => Boolean(item.toolId))?.toolId?.trim?.()
const hasQaRecords = qaRecords.length > 0
......@@ -670,18 +668,53 @@ export const Chat: React.FC = () => {
}
catch {
// 错误处理
// 拉取失败时视为无历史记录,后续可按需触发自动提问
setHasHistory(false)
}
finally {
setIsLoading(false)
// 标记该会话的历史记录已加载完成
historyLoadedRef.current.conversationId = finalConversationId
console.log('[Chat] 历史记录加载完成:', {
finalConversationId,
currentIdRef: currentIdRef.current,
pendingQuestion: pendingQuestionRef.current,
lastSentQuestion: lastSentQuestionRef.current,
})
// 清除处理标记(支持新会话ID的情况)
// finalConversationId 可能是新会话ID(从收藏返回时)或原来的 conversationId
if (processingConversationIdRef.current === finalConversationId) {
processingConversationIdRef.current = null
}
// 如果历史记录加载完成且有待发送的问题,触发自动发送
if (pendingQuestionRef.current && finalConversationId === currentIdRef.current) {
const questionToSend = pendingQuestionRef.current
console.log('[Chat] 历史记录加载完成,检查待发送问题:', {
questionToSend,
lastSentQuestion: lastSentQuestionRef.current,
})
// 检查是否已经发送过相同的问题
if (questionToSend !== lastSentQuestionRef.current) {
console.log('[Chat] 触发待发送问题的自动发送:', questionToSend)
lastSentQuestionRef.current = questionToSend
pendingQuestionRef.current = null
// 清除 shouldSendQuestion(如果还存在)
dispatch(clearShouldSendQuestion())
// 延迟发送,确保状态已更新
setTimeout(() => {
console.log('[Chat] 执行待发送问题的提交:', questionToSend)
handleSubmitQuestion(questionToSend, undefined, currentToolId)
}, 100)
}
else {
console.log('[Chat] 待发送问题与已发送问题相同,跳过发送')
}
}
else if (pendingQuestionRef.current) {
console.log('[Chat] 有待发送问题但 conversationId 不匹配,等待:', {
pendingQuestion: pendingQuestionRef.current,
finalConversationId,
currentIdRef: currentIdRef.current,
})
}
}
}, [dispatch, currentToolId, conversations, location.state])
......@@ -768,8 +801,8 @@ export const Chat: React.FC = () => {
console.log('[Chat] 开始加载历史记录,重置相关状态')
currentIdRef.current = id
// 每次切换会话时重置历史标记,等待新会话的历史查询结果
setHasHistory(null)
lastSentQuestionRef.current = '' // 重置标记
pendingQuestionRef.current = null // 清除待发送的问题
// 重置历史记录加载标记,确保新会话时能正确触发自动发送
historyLoadedRef.current.conversationId = null
// 保存 fromCollect 标记到 ref,避免 location.state 被清除后丢失
......@@ -788,59 +821,52 @@ export const Chat: React.FC = () => {
}
}, [id, location.state])
// 进入会话后自动触发一次提交(无论是否有历史记录)
const hasAutoSubmittedRef = useRef(false)
useEffect(() => {
if (id) {
// 当 id 变化时,重置自动提交标志
hasAutoSubmittedRef.current = false
}
}, [id])
useEffect(() => {
// 历史记录加载完成后自动触发(无论是否有历史记录)
// 注意:提质增效模式(toolId === '6712395743241')使用 autoSubmitQuestion 事件机制,不在此处触发
const hasHistoryLoaded = hasHistory !== null
const isQualityImprovement = currentToolId === '6712395743241'
const shouldTrigger = hasHistoryLoaded && !isLoading && !isQualityImprovement
if (currentIdRef.current && shouldTrigger && !hasAutoSubmittedRef.current) {
hasAutoSubmittedRef.current = true
// 自动触发提交(空问题,不显示用户问题)
handleSubmitQuestion('', undefined, currentToolId)
}
}, [isLoading, handleSubmitQuestion, id, hasHistory, currentToolId])
// 监听自动提问事件(提质增效模式下使用)
// 处理shouldSendQuestion的变化 - 自动发送问题
useEffect(() => {
const handleAutoSubmitQuestion = (event: CustomEvent) => {
const { conversationId, question, toolId, recordType, busiType } = event.detail
console.log('[Chat] 收到 autoSubmitQuestion 事件', {
eventConversationId: conversationId,
currentIdRef: currentIdRef.current,
match: conversationId === currentIdRef.current,
toolId,
recordType,
busiType,
console.log('[Chat] shouldSendQuestion 变化检查:', {
shouldSendQuestion,
currentIdRef: currentIdRef.current,
isLoading,
lastSentQuestion: lastSentQuestionRef.current,
historyLoadedId: historyLoadedRef.current.conversationId,
allItemsLength: allItems.length,
pendingQuestion: pendingQuestionRef.current,
})
if (
shouldSendQuestion
&& currentIdRef.current
&& !isLoading
&& shouldSendQuestion !== lastSentQuestionRef.current
) {
// 如果当前会话已有历史记录(allItems.length > 1),需要等待历史记录加载完成
// 如果历史记录已加载完成(historyLoadedRef.current.conversationId === currentIdRef.current),可以立即发送
// 如果是新会话(allItems.length <= 1),可以立即发送
const canSend = historyLoadedRef.current.conversationId === currentIdRef.current || allItems.length <= 1
console.log('[Chat] 自动发送问题判断:', {
canSend,
historyLoaded: historyLoadedRef.current.conversationId === currentIdRef.current,
isNewSession: allItems.length <= 1,
})
// 确保当前会话ID匹配
if (conversationId === currentIdRef.current) {
console.log('[Chat] conversationId 匹配,调用 handleSubmitQuestion')
// 标记已通过事件触发,避免新的自动触发逻辑重复触发
hasAutoSubmittedRef.current = true
handleSubmitQuestion(question, undefined, toolId, { recordType, busiType })
if (canSend) {
const questionToSend = shouldSendQuestion
console.log('[Chat] 可以立即发送,准备发送问题:', questionToSend)
lastSentQuestionRef.current = questionToSend
pendingQuestionRef.current = null
// 立即清除shouldSendQuestion,防止重复发送
dispatch(clearShouldSendQuestion())
// 确保历史记录加载完成后再发送问题
setTimeout(() => {
console.log('[Chat] 执行自动发送问题:', questionToSend)
handleSubmitQuestion(questionToSend, undefined, currentToolId)
}, 100)
}
else {
console.warn('[Chat] conversationId 不匹配,跳过自动提交', {
eventConversationId: conversationId,
currentIdRef: currentIdRef.current,
})
console.log('[Chat] 历史记录还在加载中,保存待发送问题到 pendingQuestionRef:', shouldSendQuestion)
// 如果历史记录还在加载中,保存待发送的问题,等待历史记录加载完成后再发送
pendingQuestionRef.current = shouldSendQuestion
}
}
window.addEventListener('autoSubmitQuestion', handleAutoSubmitQuestion as EventListener)
return () => {
window.removeEventListener('autoSubmitQuestion', handleAutoSubmitQuestion as EventListener)
}
}, [handleSubmitQuestion])
}, [shouldSendQuestion, isLoading, allItems.length, currentToolId, id])
// 根据 currentToolId 获取对应的 toolName
useEffect(() => {
......@@ -972,6 +998,35 @@ export const Chat: React.FC = () => {
}
}, [dispatch])
// 监听自动提问事件(提质增效模式下使用)
useEffect(() => {
const handleAutoSubmitQuestion = (event: CustomEvent) => {
const { conversationId, question, toolId, recordType, busiType } = event.detail
console.log('[Chat] 收到 autoSubmitQuestion 事件', {
eventConversationId: conversationId,
currentIdRef: currentIdRef.current,
match: conversationId === currentIdRef.current,
toolId,
recordType,
busiType,
})
// 确保当前会话ID匹配
if (conversationId === currentIdRef.current) {
console.log('[Chat] conversationId 匹配,调用 handleSubmitQuestion')
handleSubmitQuestion(question, undefined, toolId, { recordType, busiType })
}
else {
console.warn('[Chat] conversationId 不匹配,跳过自动提交', {
eventConversationId: conversationId,
currentIdRef: currentIdRef.current,
})
}
}
window.addEventListener('autoSubmitQuestion', handleAutoSubmitQuestion as EventListener)
return () => {
window.removeEventListener('autoSubmitQuestion', handleAutoSubmitQuestion as EventListener)
}
}, [handleSubmitQuestion])
return (
<div className={styles.scrollView}>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment