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

@@ -42,6 +42,11 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
const prevConversationId = ctx.conversationId.value;
try {
/**
* 切换会话前先清空输入框草稿,避免 textarea DOM 里残留上一会话的可见文本,
* 但父级 `input` 已经是空字符串,最终出现“看起来输入了内容,发送时却被当成空串”的错觉。
*/
ctx.input.value = '';
ctx.onConversationIdChanging(id, prevConversationId);
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
@@ -1,15 +1,62 @@
/**
* 对话页:Markdown 渲染、消息可见性判断、PLM/请假链接点击。
* features/chat/page/useChatPageMarkdown.ts
* 用途:统一处理聊天页 Markdown 渲染、内嵌文件块提取、消息可见性判断与特殊链接点击。
* 依赖:Vue computed、marked、ChatMessageBubble handlers、聊天消息类型。
* 逻辑:由 useChatPage 组装上下文后创建页面级 Markdown API,再分发给 ChatMessageBubble 做消息渲染和交互。
*/
import { computed } from 'vue';
import { marked } from 'marked';
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
import type { ChatMessage, SourceFileLink } from '../types/chat.types';
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../types/chat.types';
import type { ShippingMatchResultPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
marked.setOptions({ gfm: true, breaks: true });
const INLINE_FILE_BLOCK_REGEX = /\[FILE_START\]([\s\S]*?)\[FILE_END\]/g;
const INLINE_ATTACHMENT_HINT_REGEX = /^.*(?:如果您需要查看全部数据,请下载附件。?|请下载附件。?).*$/gim;
interface InlineFileExtractResult {
cleanedText: string;
files: InlineDownloadFile[];
}
const INLINE_DOWNLOAD_LINK_LINE_REGEX = /^[ \t>*-]*\[[^\]]*下载(?:全部|全量)?数据[^\]]*\]\([^)]+\)\s*$/gim;
/**
* 在 JSON.parse 失败时兜底提取文件字段,兼容 Dify 偶发返回的近似 JSON 文本。
* 核心逻辑:优先抽取 name/data/mime_type 三个字段;若缺失关键字段则返回 null,避免伪造按钮。
* @param rawPayload - FILE_START/FILE_END 包裹的原始文本。
* @returns 尽力恢复后的文件对象;恢复失败时返回 null。
*/
function decodeLooseJsonString(rawValue: string): string {
return String(rawValue || '')
.replace(/\\u([0-9a-fA-F]{4})/g, (_match, code: string) => String.fromCharCode(Number.parseInt(code, 16)))
.replace(/\\r/g, '\r')
.replace(/\\n/g, '\n')
.replace(/\\t/g, '\t')
.replace(/\\f/g, '\f')
.replace(/\\b/g, '\b')
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
}
function tryParseInlineFileFallback(rawPayload: string): InlineDownloadFile | null {
const raw = String(rawPayload || '').trim();
const nameMatch = raw.match(/"name"\s*:\s*"((?:\\.|[^"\\])*)"/i);
const dataMatch = raw.match(/"data"\s*:\s*"([\s\S]*?)"\s*(?:,\s*"mime_type"|\s*}$)/i);
const mimeMatch = raw.match(/"mime_type"\s*:\s*"((?:\\.|[^"\\])*)"/i);
const name = nameMatch?.[1] ? decodeLooseJsonString(nameMatch[1]).trim() : '';
const data = dataMatch?.[1] ? decodeLooseJsonString(dataMatch[1]) : '';
const mimeType = mimeMatch?.[1] ? decodeLooseJsonString(mimeMatch[1]).trim() : '';
if (!name || !data) return null;
return {
name,
data,
mime_type: mimeType || 'application/octet-stream',
};
}
export interface ChatPageMarkdownContext {
messages: Ref<ChatMessage[]>;
isThinking: Ref<boolean>;
@@ -33,6 +80,104 @@ export interface ChatPageMarkdownContext {
onShippingActionClick: ChatMessageBubbleHandlers['onShippingActionClick'];
}
/**
* 提取 Dify 返回文本中的内嵌文件块,并把原始 JSON 从聊天正文里剥离。
* 核心逻辑:使用 FILE_START/FILE_END 正则定位片段,逐个 JSON.parse 成可下载文件;解析失败时保留原文避免误伤正常消息。
* @param text - 助手原始 answer 文本,可能混有 Markdown 与文件 JSON。
* @returns 清理后的展示文本与可下载文件列表。
*/
function extractInlineDownloadFiles(text: string): InlineFileExtractResult {
if (!text) {
return { cleanedText: '', files: [] };
}
const files: InlineDownloadFile[] = [];
const seenKeys = new Set<string>();
let cleanedText = text.replace(INLINE_FILE_BLOCK_REGEX, (_match, rawPayload: string) => {
try {
const parsed = JSON.parse(String(rawPayload || '').trim()) as Partial<InlineDownloadFile>;
const name = String(parsed.name || '').trim();
const data = typeof parsed.data === 'string' ? parsed.data : '';
const mimeType = String(parsed.mime_type || '').trim() || 'application/octet-stream';
if (!name || !data) {
return '';
}
const dedupeKey = `${name}::${mimeType}::${data}`;
if (!seenKeys.has(dedupeKey)) {
seenKeys.add(dedupeKey);
files.push({
name,
data,
mime_type: mimeType,
});
}
return '';
} catch {
const fallbackFile = tryParseInlineFileFallback(rawPayload);
if (fallbackFile) {
const dedupeKey = `${fallbackFile.name}::${fallbackFile.mime_type || ''}::${fallbackFile.data}`;
if (!seenKeys.has(dedupeKey)) {
seenKeys.add(dedupeKey);
files.push(fallbackFile);
}
}
return '';
}
});
// [STEP 1] 流式消息可能先到 FILE_START、后到 FILE_END,这一阶段先把未闭合块整体隐藏,避免原始 CSV/JSON 外露。
const danglingStartIndex = cleanedText.indexOf('[FILE_START]');
if (danglingStartIndex >= 0) {
cleanedText = cleanedText.slice(0, danglingStartIndex);
}
// [STEP 2] 如果消息正文已经内置了 Markdown 下载链接,保留说明文案但移除直接下载入口,统一交给预览卡片处理。
if (files.length > 0) {
cleanedText = cleanedText.replace(INLINE_DOWNLOAD_LINK_LINE_REGEX, '');
}
// [STEP 3] 无论是否存在附件按钮,都移除“请下载附件”类兜底文案,避免 <=5 条时误导用户,也避免 >5 条时重复提示。
cleanedText = cleanedText.replace(INLINE_ATTACHMENT_HINT_REGEX, '');
return {
cleanedText: cleanedText.trim(),
files,
};
}
function safeExtractInlineDownloadFiles(text: string): InlineFileExtractResult {
try {
return extractInlineDownloadFiles(text);
} catch {
return {
cleanedText: String(text || '').replace(/\[FILE_START\][\s\S]*$/g, '').trim(),
files: [],
};
}
}
/**
* 将内嵌文件内容转成浏览器本地下载。
* 核心逻辑:按 mime/type 生成 Blob 与 object URL,触发隐藏 a 标签点击后立即回收 URL,避免把大段 CSV 暴露在 DOM 中。
* @param file - 已从消息中解析出的单个可下载文件,要求 name/data 均非空。
*/
function downloadInlineFile(file: InlineDownloadFile): void {
if (!file.name || !file.data) return;
const blob = new Blob([file.data], { type: file.mime_type || 'application/octet-stream;charset=utf-8' });
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = file.name;
anchor.style.display = 'none';
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
}
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
@@ -44,6 +189,24 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
return Array.isArray(msgItem?.attribution_parts) && msgItem.attribution_parts.length > 0;
};
/**
* 判断某条 assistant 消息是否已经具备“正文已出现”的特征。
* 核心逻辑:仅把真正可读的正文或结构化子消息视为已开始回复;
* 单纯的引用源、空内容或中间元数据不应压掉“思考中”提示。
*/
const hasMeaningfulAssistantReply = (msgItem: ChatMessage): boolean => {
if (msgItem?.role !== 'assistant') return false;
if (msgItem?.type === 'leave-form'
|| msgItem?.type === 'leave-confirmation'
|| msgItem?.type === 'leave-result'
|| msgItem?.type === 'shipping-inventory-mapping'
|| msgItem?.type === 'shipping-parse-review'
|| msgItem?.type === 'shipping-match-result') {
return true;
}
return Boolean(String(msgItem?.content || '').trim());
};
const shouldShowThinkingBubble = computed(() => {
if (!ctx.isThinking.value) return false;
let lastUserIndex = -1;
@@ -56,7 +219,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
if (lastUserIndex < 0) return true;
return !ctx.messages.value
.slice(lastUserIndex + 1)
.some((msgItem) => msgItem?.role === 'assistant' && shouldRenderMessage(msgItem));
.some((msgItem) => hasMeaningfulAssistantReply(msgItem));
});
const handleChatMarkdownClick = (event: MouseEvent) => {
@@ -71,15 +234,26 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
ctx.handleLeaveMarkdownClick(event);
};
/**
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。
* @param text - 原始聊天文本。
* @returns 供 v-html 使用的安全展示字符串。
*/
const renderMarkdown = (text: string) => {
if (!text) return '';
const displayText = ctx.prepareMarkdownDisplayText(text);
const extracted = safeExtractInlineDownloadFiles(text);
const displayText = ctx.prepareMarkdownDisplayText(extracted.cleanedText);
try {
const rendered = marked.parse(displayText);
const html = typeof rendered === 'string' ? rendered : displayText;
return html.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
));
return html
.replace(/<(td|th)\b([^>]*)>(?:\s|&nbsp;|<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
`<${tagName}${attrs}>无</${tagName}>`
))
.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
));
} catch {
return displayText;
}
@@ -88,6 +262,8 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
renderMarkdown,
onMarkdownClick: handleChatMarkdownClick,
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
downloadInlineFile,
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
getShippingMatchResultPayload: ctx.getShippingMatchResultPayload,
canOpenQueryPreview: ctx.canOpenQueryPreview,
@@ -1,4 +1,4 @@
/**
/**
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
*/
import { computed } from 'vue';
@@ -28,6 +28,7 @@ export interface ChatPageSendContext {
context?: { task_id?: string; batch_no?: string },
) => Promise<void>;
refreshHistoryAfterSend: () => Promise<void>;
refreshConversationAfterSend?: () => Promise<void>;
tryHandleShippingAttachmentAutoFlow: (
textOrEvent: string | Event | undefined,
content: string,
@@ -61,8 +62,12 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
return;
}
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) return;
if (ctx.tryHandleLeaveSend(content)) return;
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) {
return;
}
if (ctx.tryHandleLeaveSend(content)) {
return;
}
if (await ctx.tryHandleShippingSend(textOrEvent, content, trimmed)) {
return;
}
@@ -100,6 +105,7 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
ctx.getChatContext?.(),
);
await ctx.refreshHistoryAfterSend();
await ctx.refreshConversationAfterSend?.();
await ctx.refreshToolRunProgressAfterSend();
};