/** * features/chat/page/useChatPageMarkdown.ts * 用途:统一处理聊天页 Markdown 渲染、内嵌文件块提取、消息可见性判断与特殊链接点击。 * 依赖:Vue computed、marked、ChatMessageBubble handlers、聊天消息类型。 * 逻辑:由 useChatPage 组装上下文后创建页面级 Markdown API,再分发给 ChatMessageBubble 做消息渲染和交互。 */ import { computed } from 'vue'; import { marked } from 'marked'; import { useMessage } from '@/shared/composables/useMessage'; import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue'; import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../types/chat.types'; import type { ShippingMatchResultPayload } from '../types/shipping.types'; import type { Ref } from 'vue'; import { downloadFileCheckExcelByRunId, parseFileCheckExcelRunId, rewriteFileCheckExcelLinksForDisplay, } from '../utils/fileCheckExcelDownload'; 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; isThinking: Ref; prepareMarkdownDisplayText: (text: string) => string; handleLeaveMarkdownClick: (event: MouseEvent) => void; parsePlmPreviewLink: (href: string) => SourceFileLink | null; openPreview: (file: SourceFileLink) => Promise; openAssetHistory: (assetId: string, assetName?: string) => void; openAssetImage: (assetId: string, assetName?: string) => void; getMessageLinks: (message: Record) => SourceFileLink[]; getDisplayRetrieverResources: (msgItem: Record) => Record[]; getSourceLinks: (resources?: unknown[]) => SourceFileLink[]; shouldExpandSourceDetails: (msgItem: Record) => boolean; getSourceTitle: ChatMessageBubbleHandlers['getSourceTitle']; getSourceMeta: ChatMessageBubbleHandlers['getSourceMeta']; getSourceBrief: ChatMessageBubbleHandlers['getSourceBrief']; getShippingInventoryMappingPayload: ChatMessageBubbleHandlers['getShippingInventoryMappingPayload']; getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null; canOpenQueryPreview: ChatMessageBubbleHandlers['canOpenQueryPreview']; getQueryPreviewSummary: ChatMessageBubbleHandlers['getQueryPreviewSummary']; openQueryPreviewDialog: ChatMessageBubbleHandlers['openQueryPreviewDialog']; shippingActionButtonClass: ChatMessageBubbleHandlers['shippingActionButtonClass']; 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(); let cleanedText = text.replace(INLINE_FILE_BLOCK_REGEX, (_match, rawPayload: string) => { try { const parsed = JSON.parse(String(rawPayload || '').trim()) as Partial; 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); } function normalizeAssetHistoryText(value: string): string { const normalized = String(value || '').trim(); if (!normalized || normalized === '-' || normalized === '无') return ''; return normalized; } const FIXED_ASSET_TABLE_TARGET_HEADERS = [ '序号', '资产编号', '资产名称', '保管人', '保管部门', '图片', '账套', '供应商', '资产状态', '数量', '取得时间', ]; const FIXED_ASSET_TABLE_HEADER_ALIASES: Record = { 序号: ['序号', 'id'], 资产编号: ['资产编号', 'asset_id', 'asset_no'], 资产名称: ['资产名称', 'asset_name'], 保管人: ['保管人', '保管人姓名', 'custodian_name', 'custodian_person'], 保管部门: ['保管部门', '保管部门名称', 'department_name', 'custodian_dept'], 图片: ['图片', 'image', 'picture'], 账套: ['账套', 'account_period', 'operating_center_code'], 供应商: ['供应商', '供应厂商', 'supplier', 'vendor_name'], 资产状态: ['资产状态', 'asset_status'], 数量: ['数量', 'quantity'], 取得时间: ['取得时间', '取得日期', 'acquisition_date', 'acquired_date'], }; function normalizeFixedAssetHeader(value: string): string { const normalized = normalizeAssetHistoryText(value).toLowerCase(); if (!normalized) return ''; const targetHeader = FIXED_ASSET_TABLE_TARGET_HEADERS.find((header) => ( (FIXED_ASSET_TABLE_HEADER_ALIASES[header] || []).some((alias) => alias.toLowerCase() === normalized) )); return targetHeader || ''; } function isFixedAssetPreviewTable(headerLabels: string[]): boolean { const normalizedHeaders = headerLabels .map((label) => normalizeFixedAssetHeader(label)) .filter(Boolean); return ['资产编号', '资产名称', '保管人', '保管部门', '账套', '资产状态', '数量', '取得时间'] .every((header) => normalizedHeaders.includes(header)); } /** * 将 Dify 返回的旧版固定资产表格收敛成统一展示列顺序。 * 核心逻辑:按中文/英文别名识别表头后重建 thead/tbody,并补出“图片=查看”列,让旧会话与新会话都按同一业务结构展示。 */ function normalizeFixedAssetPreviewTables(container: HTMLElement): void { const tables = Array.from(container.querySelectorAll('table')); tables.forEach((table) => { const headerCells = Array.from(table.querySelectorAll('thead th')); if (headerCells.length === 0) return; const headerLabels = headerCells.map((cell) => normalizeAssetHistoryText(cell.textContent || '')); if (!isFixedAssetPreviewTable(headerLabels)) return; const headerIndexMap = new Map(); headerLabels.forEach((label, index) => { const normalized = normalizeFixedAssetHeader(label); if (normalized && !headerIndexMap.has(normalized)) { headerIndexMap.set(normalized, index); } }); const bodyRows = Array.from(table.querySelectorAll('tbody tr')); const normalizedRows = bodyRows.map((row, rowIndex) => { const cells = Array.from(row.querySelectorAll('td')); const pickCellText = (header: string): string => { if (header === '序号') return String(rowIndex + 1); if (header === '图片') { const assetIdIndex = headerIndexMap.get('资产编号'); const assetId = assetIdIndex !== undefined ? normalizeAssetHistoryText(cells[assetIdIndex]?.textContent || '') : ''; return assetId ? '查看' : '无'; } const cellIndex = headerIndexMap.get(header); return cellIndex !== undefined ? normalizeAssetHistoryText(cells[cellIndex]?.textContent || '') || '无' : '无'; }; return FIXED_ASSET_TABLE_TARGET_HEADERS.map((header) => pickCellText(header)); }); const thead = table.querySelector('thead'); const tbody = table.querySelector('tbody'); if (!thead || !tbody) return; thead.innerHTML = `${FIXED_ASSET_TABLE_TARGET_HEADERS.map((header) => ( `${header}` )).join('')}`; tbody.innerHTML = normalizedRows.map((row) => ( `${row.map((cell) => `${cell || '无'}`).join('')}` )).join(''); }); } /** * 把聊天结果表格里的“资产编号”和“图片”列增强为可点击入口。 * 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词;资产编号走履历检索,图片走图片预览检索。 */ function enhanceAssetHistoryTableLinks(html: string): string { if (!html || typeof document === 'undefined' || !html.includes(' { const headerCells = Array.from(table.querySelectorAll('thead th')); if (headerCells.length === 0) return; const headerLabels = headerCells.map((cell) => normalizeAssetHistoryText(cell.textContent || '')); const assetIdIndex = headerLabels.findIndex((label) => label === '资产编号'); if (assetIdIndex < 0) return; const assetNameIndex = headerLabels.findIndex((label) => label === '资产名称'); const imageIndex = headerLabels.findIndex((label) => label === '图片'); const rows = Array.from(table.querySelectorAll('tbody tr')); rows.forEach((row) => { const cells = Array.from(row.querySelectorAll('td')); const assetIdCell = cells[assetIdIndex]; if (!assetIdCell) return; const assetId = normalizeAssetHistoryText(assetIdCell.textContent || ''); if (!assetId) return; const assetName = assetNameIndex >= 0 ? normalizeAssetHistoryText(cells[assetNameIndex]?.textContent || '') : ''; const link = document.createElement('a'); link.href = `#asset-history?asset_id=${encodeURIComponent(assetId)}&asset_name=${encodeURIComponent(assetName)}`; link.className = 'chat-asset-history-link'; link.textContent = assetId; assetIdCell.innerHTML = ''; assetIdCell.appendChild(link); if (imageIndex >= 0) { const imageCell = cells[imageIndex]; if (!imageCell) return; const imageText = normalizeAssetHistoryText(imageCell.textContent || '') || '查看'; const imageLink = document.createElement('a'); imageLink.href = `#asset-image?asset_id=${encodeURIComponent(assetId)}&asset_name=${encodeURIComponent(assetName)}`; imageLink.className = 'chat-asset-history-link'; imageLink.textContent = imageText; imageCell.innerHTML = ''; imageCell.appendChild(imageLink); } }); }); return container.innerHTML; } export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) { const message = useMessage(); /** * 判断消息是否具备可展示内容。 * 核心逻辑:订单识别状态本身就是用户可见反馈,即使 Dify 正文尚未到达也必须渲染; * 其余消息继续沿用正文、链接、引用源和结构化消息的既有判断。 * @param msgItem - 当前聊天消息。 * @returns 消息是否应进入聊天列表渲染。 */ const shouldRenderMessage = (msgItem: ChatMessage): boolean => { if (msgItem?.role === 'user') return true; if (msgItem?.type === 'shipping-parse-review') return false; if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true; if (msgItem?.shipping_order_extraction_state) return true; const content = (msgItem?.content || '').trim(); if (content) return true; if (ctx.getMessageLinks(msgItem as unknown as Record).length > 0) return true; if (ctx.getDisplayRetrieverResources(msgItem as unknown as Record).length > 0) return true; 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?.shipping_order_extraction_state) return true; 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; for (let i = ctx.messages.value.length - 1; i >= 0; i--) { if (ctx.messages.value[i]?.role === 'user') { lastUserIndex = i; break; } } if (lastUserIndex < 0) return true; return !ctx.messages.value .slice(lastUserIndex + 1) .some((msgItem) => hasMeaningfulAssistantReply(msgItem)); }); const handleChatMarkdownClick = (event: MouseEvent) => { const target = event.target as HTMLElement | null; const anchor = target?.closest?.('a') as HTMLAnchorElement | null; const rawHref = anchor?.getAttribute('href') || ''; if (rawHref.startsWith('#asset-history?')) { event.preventDefault(); const params = new URLSearchParams(rawHref.slice('#asset-history?'.length)); ctx.openAssetHistory((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim()); return; } if (rawHref.startsWith('#asset-image?')) { event.preventDefault(); const params = new URLSearchParams(rawHref.slice('#asset-image?'.length)); ctx.openAssetImage((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim()); return; } const preview = ctx.parsePlmPreviewLink(rawHref); if (preview) { event.preventDefault(); void ctx.openPreview(preview); return; } const fileCheckRunId = parseFileCheckExcelRunId(rawHref); if (fileCheckRunId) { event.preventDefault(); void downloadFileCheckExcelByRunId(fileCheckRunId).catch((error: unknown) => { const text = error instanceof Error ? error.message : '下载 Excel 失败'; message.error(text); }); return; } ctx.handleLeaveMarkdownClick(event); }; /** * 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。 * 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。 * @param text - 原始聊天文本。 * @returns 供 v-html 使用的安全展示字符串。 */ const renderMarkdown = (text: string) => { if (!text) return ''; const extracted = safeExtractInlineDownloadFiles(text); const displayText = rewriteFileCheckExcelLinksForDisplay( ctx.prepareMarkdownDisplayText(extracted.cleanedText), ); try { const rendered = marked.parse(displayText); const html = typeof rendered === 'string' ? rendered : displayText; return enhanceAssetHistoryTableLinks(html) .replace(/<(td|th)\b([^>]*)>(?:\s| |)*<\/\1>/gi, (_match, tagName: string, attrs: string) => ( `<${tagName}${attrs}>无` )) .replace(//gi, (tableHtml: string) => ( `
${tableHtml}
` )); } catch { return displayText; } }; const messageBubbleHandlers: ChatMessageBubbleHandlers = { renderMarkdown, onMarkdownClick: handleChatMarkdownClick, openAssetHistory: ctx.openAssetHistory, openAssetImage: ctx.openAssetImage, getInlineDownloadFiles: safeExtractInlineDownloadFiles, downloadInlineFile, getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload, getShippingMatchResultPayload: ctx.getShippingMatchResultPayload, canOpenQueryPreview: ctx.canOpenQueryPreview, getQueryPreviewSummary: ctx.getQueryPreviewSummary, openQueryPreviewDialog: ctx.openQueryPreviewDialog, shippingActionButtonClass: ctx.shippingActionButtonClass, onShippingActionClick: ctx.onShippingActionClick, getDisplayRetrieverResources: (msgItem) => ctx.getDisplayRetrieverResources(msgItem as unknown as Record), getSourceLinks: (resources) => ctx.getSourceLinks(resources), shouldExpandSourceDetails: (msgItem) => ctx.shouldExpandSourceDetails(msgItem as unknown as Record), getSourceTitle: ctx.getSourceTitle, getSourceMeta: ctx.getSourceMeta, getSourceBrief: ctx.getSourceBrief, openPreview: ctx.openPreview, }; return { shouldRenderMessage, shouldShowThinkingBubble, messageBubbleHandlers, renderMarkdown, handleChatMarkdownClick, }; }