Commit 14c4bc50 by weiyudumei

feat: 工单添加自动触发逻辑,无论是否有历史记录都触发

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