fix(chat): 修复固资管理首轮问答残留中断与历史会话异常

This commit is contained in:
runny committed 2026-06-28 13:11:13 +08:00
1 parent 25876f94bd
commit 3b771fc0b6
16 files changed
+1042 -35

No files matched your search

@@ -124,6 +124,94 @@ export function useChat() {
const activeRunId = ref<number | null>(null);
let runSeq = 0;
const conversationId = ref<string | null>(null);
const activeStreamController = ref<AbortController | null>(null);
let likelyCompletedStreamTimer: ReturnType<typeof setTimeout> | null = null;
/**
* 取消当前仍在进行的流式请求。
*
* 说明:
* - 固资管理这类长文本/文件回答有时会在答案已经完整展示后,SSE 连接迟迟不结束;
* - 若不主动取消,`isThinking` 可能持续为 true,导致输入栏、重新提问和切换 Agent 都像“卡死”。
*/
const cancelActiveStream = () => {
if (!activeStreamController.value) return;
activeStreamController.value.abort();
activeStreamController.value = null;
};
/**
* 将当前流式请求从可见视图脱离,但不主动中止网络连接。
*
* 说明:
* - 用户切换历史会话时,旧会话回答往往已经接近完成,只是上游 SSE 还没来得及收尾;
* - 若这里直接 abort,浏览器会把 `/api/chat/completions` 记成 `ERR_ABORTED`;
* - 改为“脱离当前视图”后,旧流可以在后台自然结束,当前页面也能立即切到目标历史会话。
*/
const detachActiveStreamFromView = () => {
activeStreamController.value = null;
};
/**
* 清理“疑似已完成回答”的静默定时器。
* 说明:固资管理的完整报告有时已经展示出来,但上游流连接没有及时结束,
* 这里需要在收到新帧或完成收尾时把旧定时器清掉,避免重复收尾。
*/
const clearLikelyCompletedStreamTimer = () => {
if (!likelyCompletedStreamTimer) return;
clearTimeout(likelyCompletedStreamTimer);
likelyCompletedStreamTimer = null;
};
/**
* 判断当前助手内容是否已经像一份完整报告。
*
* 说明:
* - 固资管理 / ERP 问数最终答案通常会携带 `<details>`、结果表格或导出文件块;
* - 若这些终态标记已经出现,而连接仍未结束,说明前端可以在短暂静默后主动解锁输入区。
*/
const looksLikeCompletedAssistantReply = (content: string) => {
if (!content) return false;
return (
content.includes('<details>')
|| content.includes('**查询结果如下:**')
|| content.includes('**错误详情**')
|| content.includes('[FILE_START]')
|| content.includes('【💡 数据概述】')
|| content.includes('【📊 数据预览】')
|| content.includes('【📈 数据分析汇总报告】')
|| content.includes('系统为您从数据库中检索到共计')
);
};
/**
* 对“已看到完整报告但流未结束”的情况做兜底收尾。
*
* 核心逻辑:
* - 仅当当前回答内容已具备终态标记时才启动;
* - 若短时间内没有任何新帧到来,则主动将 run 标记为 done 并中止挂起连接;
* - 这样可以修复固资管理首轮问答后输入框一直被锁住的问题。
*/
const armLikelyCompletedStreamTimer = (
controller: AbortController,
run: ChatRun,
runMessages: ChatMessage[],
currentAssistantContent: string,
onUnlock: () => void,
) => {
clearLikelyCompletedStreamTimer();
if (!looksLikeCompletedAssistantReply(currentAssistantContent)) return;
likelyCompletedStreamTimer = setTimeout(() => {
likelyCompletedStreamTimer = null;
if (activeStreamController.value !== controller) return;
if (run.status !== 'running') return;
run.status = 'done';
if (messages.value === runMessages) {
isThinking.value = false;
}
onUnlock();
}, 600);
};
const activateRun = (runId: number) => {
const run = runs.value.find((r) => r.runId === runId);
@@ -135,6 +223,8 @@ export function useChat() {
};
const createNewChatView = () => {
clearLikelyCompletedStreamTimer();
cancelActiveStream();
viewId.value += 1;
messages.value = [];
conversationId.value = null;
@@ -143,6 +233,8 @@ export function useChat() {
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
clearLikelyCompletedStreamTimer();
detachActiveStreamFromView();
viewId.value += 1;
activeRunId.value = null;
isThinking.value = false;
@@ -193,6 +285,10 @@ export function useChat() {
>,
context?: { task_id?: string; batch_no?: string },
) => {
clearLikelyCompletedStreamTimer();
cancelActiveStream();
const controller = new AbortController();
activeStreamController.value = controller;
const runViewId = viewId.value;
const runMessages = messages.value;
const run: ChatRun = {
@@ -213,6 +309,7 @@ export function useChat() {
let botMsgIndex: number | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
let ignoreFurtherStreamEvents = false;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
@@ -231,6 +328,7 @@ export function useChat() {
const response = await fetch('/api/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
signal: controller.signal,
body: JSON.stringify({
query,
agent_id: agentId,
@@ -255,6 +353,10 @@ export function useChat() {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (ignoreFurtherStreamEvents) {
continue;
}
clearLikelyCompletedStreamTimer();
buffer += decoder.decode(value, { stream: true });
buffer = buffer.replace(/\r\n/g, '\n');
@@ -297,6 +399,10 @@ export function useChat() {
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
ignoreFurtherStreamEvents = true;
detachActiveStreamFromView();
});
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
@@ -304,6 +410,7 @@ export function useChat() {
}
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
hasTerminalEvent = true;
ignoreFurtherStreamEvents = true;
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
if (relay.total_relay_ms != null) {
// eslint-disable-next-line no-console
@@ -312,14 +419,30 @@ export function useChat() {
);
}
run.status = 'done';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
const normalizedAnswer = normalizeStreamText(data.answer);
hasAssistantContent = true;
const currentContent = botMsg.content || '';
if (data.replace_answer) {
botMsg.content = normalizedAnswer;
} else if (
normalizedAnswer
&& currentContent
&& normalizedAnswer.length >= currentContent.length
&& normalizedAnswer.includes(currentContent)
) {
// [STEP 1] 某些 Dify 结束事件会重复携带整段完整 answer,这里直接替换,避免正文和内嵌文件按钮重复。
botMsg.content = normalizedAnswer;
} else if (
normalizedAnswer
&& currentContent
&& currentContent.includes(normalizedAnswer)
) {
botMsg.content = currentContent;
} else {
botMsg.content += normalizedAnswer;
}
@@ -333,29 +456,46 @@ export function useChat() {
if (!botMsg) continue;
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
run.status = 'error';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
armLikelyCompletedStreamTimer(controller, run, runMessages, botMsg.content || '', () => {
ignoreFurtherStreamEvents = true;
detachActiveStreamFromView();
});
}
} catch {
// ignore malformed SSE frames
}
}
}
if (!hasTerminalEvent && hasAssistantContent && run.status === 'running') {
run.status = 'done';
}
} catch (e: unknown) {
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue';
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
clearLikelyCompletedStreamTimer();
if (controller.signal.aborted) {
if (run.status === 'running') {
run.status = hasAssistantContent || hasTerminalEvent ? 'done' : 'error';
}
} else {
run.status = 'error';
const botMsg = ensureBotMessage();
if (botMsg) {
const message = e instanceof Error ? e.message : 'Network Issue';
applyStreamErrorToMessage(botMsg, message, streamErrorLabels());
}
}
} finally {
clearLikelyCompletedStreamTimer();
if (activeStreamController.value === controller) {
activeStreamController.value = null;
}
if (messages.value === runMessages) {
isThinking.value = false;
}
@@ -10,6 +10,7 @@ import { config } from '@/config';
import { useMessage } from '@/shared/composables/useMessage';
import { useIsMobile } from '@/shared/composables/useIsMobile';
import { useTheme } from '@/shared/composables/useTheme';
import { listChatMessages } from '../api/chat.api';
import { stripReasoningPrelude } from '../utils/chatText';
import type { ChatDeps } from './chat.deps';
import { useChat } from './useChat';
@@ -38,6 +39,39 @@ import {
useChatPageVoice,
useChatPageToolRun,
} from '../page';
import type { ChatMessage } from '../types/chat.types';
const getLatestAssistantMessage = (items: ChatMessage[]) => {
for (let i = items.length - 1; i >= 0; i -= 1) {
if (items[i]?.role === 'assistant') {
return items[i];
}
}
return null;
};
const hasMeaningfulAssistantMessage = (message: ChatMessage | null | undefined) => {
if (!message) return false;
if (String(message.content || '').trim()) return true;
return Boolean(message.type && message.type !== 'text');
};
const shouldApplyServerConversationSnapshot = (localMessages: ChatMessage[], serverMessages: ChatMessage[]) => {
if (serverMessages.length < localMessages.length) return false;
const localAssistant = getLatestAssistantMessage(localMessages);
if (!hasMeaningfulAssistantMessage(localAssistant)) return true;
const serverAssistant = getLatestAssistantMessage(serverMessages);
if (!hasMeaningfulAssistantMessage(serverAssistant)) return false;
const localContent = String(localAssistant?.content || '').trim();
const serverContent = String(serverAssistant?.content || '').trim();
if (!localContent) return true;
if (!serverContent) return false;
if (serverContent.length < localContent.length) return false;
return serverContent.includes(localContent);
};
export function useChatPage() {
const { t, locale } = useI18n();
@@ -290,6 +324,28 @@ export function useChatPage() {
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
refreshHistoryAfterSend,
refreshConversationAfterSend: async () => {
const currentConversationId = conversationId.value;
const currentAgent = currentAgentId.value;
if (!currentConversationId || !currentAgent) return;
// [STEP 1] 发送刚结束时先保留当前内存快照,避免服务端尚未完整落库的旧消息把新回答覆盖掉。
const localSnapshot = [...messages.value];
const loaded = await listChatMessages(currentConversationId, currentAgent);
const serverMessages = Array.isArray(loaded) ? loaded : [];
// [STEP 2] 若用户已切到其他 Agent/会话,丢弃这个迟到的刷新结果,避免把右侧问答区又切回旧会话。
if (conversationId.value !== currentConversationId || currentAgentId.value !== currentAgent) {
return;
}
// [STEP 3] 仅当服务端快照不比本地旧时才覆盖,修复“答案刚出来就消失”和后续发送被锁死的问题。
if (!shouldApplyServerConversationSnapshot(localSnapshot, serverMessages)) {
return;
}
loadConversationState(currentConversationId, serverMessages);
},
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
tryHandleLeaveSend: leave.tryHandleLeaveSend,
tryHandleShippingSend: shipping.tryHandleShippingSend,
@@ -121,13 +121,17 @@ export function useChatSessions(options: UseChatSessionsOptions) {
return;
}
await loadConversation(item.conversation_id, { force: true });
isSidebarOpen.value = false;
if (item.conversation_id.startsWith('pending:')) return;
const currentConvId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
if (currentConvId === item.conversation_id) return;
if (currentConvId === item.conversation_id) {
if (conversationId.value !== item.conversation_id || activeRunId.value) {
await loadConversation(item.conversation_id, { force: true });
}
return;
}
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
delete nextQuery.task_id;