fix(platform): 汇总知识库问答与图表展示修复
This commit is contained in:
1 parent
f615e56bb9
commit
87ea4ed8a9
41 files changed
+4569
-770
No files matched your search
@@ -5,7 +5,7 @@
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;合同审查结果卡自带边框,外层不再套 chat-msg-assistant 气泡以免双层框。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
@@ -19,6 +19,7 @@ import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingEx
|
||||
import TrainingVideoMessage from './TrainingVideoMessage.vue';
|
||||
import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
|
||||
import TrainingResultCard from './TrainingResultCard.vue';
|
||||
import { buildMermaidFlowFallbackHtml } from '../../utils/mermaidChart';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
@@ -126,6 +127,33 @@ const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
message.role === 'assistant' ? handlers.renderMarkdown(message.content) : ''
|
||||
));
|
||||
const markdownContainer = ref<HTMLElement | null>(null);
|
||||
|
||||
/**
|
||||
* 用途:将回答中的 Mermaid 流程图代码块转换成内嵌流程卡片。
|
||||
* 依赖:useChatPageMarkdown 为 `mermaid` 代码块保留 `.chat-mermaid` 标记。
|
||||
* 逻辑:不直接执行 Mermaid,避免 Dify 非标准图语法使 Mermaid 在页面根节点注入错误 SVG;
|
||||
* 对可提取的主流程展示节点卡片和箭头,其余图表代码块静默隐藏,不影响普通文本与表格。
|
||||
*/
|
||||
const renderMermaidCharts = async () => {
|
||||
await nextTick();
|
||||
const container = markdownContainer.value;
|
||||
if (!container) return;
|
||||
const nodes = Array.from(container.querySelectorAll<HTMLElement>('pre.chat-mermaid:not([data-mermaid-rendered])'));
|
||||
if (!nodes.length) return;
|
||||
for (const node of nodes) {
|
||||
node.dataset.mermaidRendered = 'pending';
|
||||
const fallbackHtml = buildMermaidFlowFallbackHtml(node.textContent || '');
|
||||
if (fallbackHtml) {
|
||||
node.outerHTML = fallbackHtml;
|
||||
continue;
|
||||
}
|
||||
node.remove();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => { void renderMermaidCharts(); });
|
||||
watch(renderedMarkdown, () => { void renderMermaidCharts(); });
|
||||
const inlineDownloadFiles = computed(() => (
|
||||
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
|
||||
));
|
||||
@@ -1055,6 +1083,71 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-diagram) {
|
||||
max-width: 100%;
|
||||
overflow: auto;
|
||||
margin: 1rem 0;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgb(219 234 254);
|
||||
border-radius: 0.75rem;
|
||||
background: linear-gradient(135deg, rgb(248 250 252), rgb(239 246 255));
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-diagram svg) {
|
||||
display: block;
|
||||
min-width: 36rem;
|
||||
max-width: none;
|
||||
height: auto;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-error) {
|
||||
white-space: pre;
|
||||
overflow: auto;
|
||||
color: rgb(127 29 29);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-mermaid-error-tip) {
|
||||
margin: 0.75rem 0 0.25rem;
|
||||
color: rgb(185 28 28);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-flow-fallback) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
margin: 1rem 0;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgb(191 219 254);
|
||||
border-radius: 0.75rem;
|
||||
background: linear-gradient(135deg, rgb(248 250 252), rgb(239 246 255));
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-flow-fallback-card) {
|
||||
flex: 0 0 auto;
|
||||
min-width: 8.5rem;
|
||||
max-width: 13rem;
|
||||
padding: 0.75rem 1rem;
|
||||
border: 1px solid rgb(96 165 250);
|
||||
border-radius: 0.625rem;
|
||||
background: white;
|
||||
color: rgb(30 64 175);
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
text-align: center;
|
||||
box-shadow: 0 2px 8px rgb(59 130 246 / 0.12);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-flow-fallback-arrow) {
|
||||
flex: 0 0 auto;
|
||||
color: rgb(37 99 235);
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-table-scroll) {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
|
||||
@@ -41,8 +41,13 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
||||
|
||||
const stopContainerWatch = watch(container, syncScrollListener, { immediate: true });
|
||||
|
||||
/**
|
||||
* 判断是否显示“回到最新消息”按钮。
|
||||
* 核心逻辑:只要用户离开底部就提供入口;流式回复只有两条消息时同样需要可恢复跟随。
|
||||
* @returns 用户是否正在查看历史内容。
|
||||
*/
|
||||
const showScrollToBottom = computed(() =>
|
||||
messages.value.length >= 4 && !isNearBottom.value,
|
||||
messages.value.length > 0 && !isNearBottom.value,
|
||||
);
|
||||
|
||||
const scrollToBottom = async () => {
|
||||
@@ -118,9 +123,15 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
||||
stopContainerWatch();
|
||||
};
|
||||
|
||||
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
|
||||
/**
|
||||
* 监听流式消息与会话状态,决定是否继续贴底跟随。
|
||||
* 核心逻辑:用户在底部时显示最新生成内容;用户手动向上阅读后停止自动滚动,
|
||||
* 直到其主动点击“回到最新消息”。
|
||||
* @param isThinking - 当前回复是否仍在生成,用于纳入监听依赖。
|
||||
* @param conversationId - 当前会话标识,用于在切换会话后重新评估滚动状态。
|
||||
* @returns 无返回值;监听会在 composable 卸载时自动清理。
|
||||
*/
|
||||
const setupThinkingScrollWatch = (isThinking: Ref<boolean>, conversationId?: Ref<string | null>) => {
|
||||
let wasThinking = false;
|
||||
watch(
|
||||
() => ({
|
||||
messageCount: messages.value.length,
|
||||
@@ -130,14 +141,14 @@ export function useChatScroll(options: UseChatScrollOptions) {
|
||||
conversationId: conversationId?.value || '',
|
||||
}),
|
||||
() => {
|
||||
if (wasThinking && !isThinking.value) {
|
||||
wasThinking = false;
|
||||
void scrollToUserQuestion();
|
||||
} else {
|
||||
if (isThinking.value) wasThinking = true;
|
||||
if (isNearBottom.value) scheduleScrollToBottom();
|
||||
else window.requestAnimationFrame(updateNearBottomState);
|
||||
// [STEP 1] 用户停留在底部时随新内容向下滚动;离开底部后保留阅读位置。
|
||||
if (isNearBottom.value) {
|
||||
scheduleScrollToBottom();
|
||||
return;
|
||||
}
|
||||
|
||||
// [STEP 2] 内容高度变化可能使“接近底部”状态恢复,重新计算但不主动移动视口。
|
||||
window.requestAnimationFrame(updateNearBottomState);
|
||||
},
|
||||
{ deep: false },
|
||||
);
|
||||
|
||||
@@ -12,6 +12,12 @@ describe('isStrongLeaveIntent', () => {
|
||||
// 断言:规则咨询不应触发本地请假表单,应继续走 Dify 问答。
|
||||
expect(isStrongLeaveIntent('年假可以按照小时请假吗?')).toBe(false);
|
||||
expect(isStrongLeaveIntent('怎么请年假?年假可以按照小时请假吗?')).toBe(false);
|
||||
// 断言:扣薪/薪资计算属于知识库制度问答,不应弹出请假申请表单。
|
||||
expect(isStrongLeaveIntent('请假扣多少薪资')).toBe(false);
|
||||
expect(isStrongLeaveIntent('请假如何扣除薪资')).toBe(false);
|
||||
expect(isStrongLeaveIntent('请病假怎么扣钱')).toBe(false);
|
||||
expect(isStrongLeaveIntent('请假扣多少钱,计算公式是什么')).toBe(false);
|
||||
expect(isStrongLeaveIntent('薪资福利中的请假扣款怎么算')).toBe(false);
|
||||
});
|
||||
|
||||
it('保留强请假意图触发表单', () => {
|
||||
|
||||
@@ -140,6 +140,10 @@ export function getLeaveIntentNormalized(content: string): string {
|
||||
/** 区分「真请假」与「咨询流程/材料」类弱意图 */
|
||||
export function isStrongLeaveIntent(content: string): boolean {
|
||||
const normalized = getLeaveIntentNormalized(content);
|
||||
// [STEP 1] 薪资/扣薪属于制度计算问答,必须交给 Dify/FAQ,不能被“请假”关键词抢先拦截为申请表单。
|
||||
// [PROMPT_UPDATE] 保留知识库中的计算公式、适用条件和口径,由知识库回答而非前端自行生成。
|
||||
const leaveSalaryConsultationIntent = /(请假|休假|年假|事假|病假).{0,12}(薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算|公式)|(?:薪资|工资|薪酬|扣薪|扣钱|扣款|扣除|多少钱|福利|计算公式).{0,12}(请假|休假|年假|事假|病假)/;
|
||||
if (leaveSalaryConsultationIntent.test(normalized)) return false;
|
||||
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
|
||||
const weakLeaveQuestionIntent = /((怎么|如何).{0,8}(请假|请年假|休假|休年假|年假)|(请假|年假|休假).{0,12}(可以|可否|能否|是否|支持).{0,8}(按小时|按照小时|小时请|小时休))/;
|
||||
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
|
||||
|
||||
@@ -55,7 +55,23 @@ function displayFixedAssetHeader(header: string): string {
|
||||
const key = FIXED_ASSET_HEADER_I18N_KEYS[header as keyof typeof FIXED_ASSET_HEADER_I18N_KEYS];
|
||||
return key ? tt(key) : header;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:为聊天中的 Mermaid 代码块保留可识别标记,交由消息组件渲染为 SVG 图表。
|
||||
* 逻辑:仅处理明确标为 `mermaid` 的代码块;其余代码仍保持 marked 的默认安全展示,
|
||||
* 避免把普通文本或 ASCII 图误当作可执行图表语法。
|
||||
*/
|
||||
const chatMarkdownRenderer = new marked.Renderer();
|
||||
chatMarkdownRenderer.code = ({ text, lang }: { text: string; lang?: string | null }) => {
|
||||
if (String(lang || '').trim().toLowerCase() === 'mermaid') {
|
||||
return `<pre class="chat-mermaid">${text}</pre>`;
|
||||
}
|
||||
const escaped = String(text || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
const languageClass = String(lang || '').trim().replace(/[^a-zA-Z0-9_-]/g, '');
|
||||
return `<pre><code${languageClass ? ` class="language-${languageClass}"` : ''}>${escaped}</code></pre>`;
|
||||
};
|
||||
const INLINE_FILE_BLOCK_REGEX = /\[FILE_START\]([\s\S]*?)\[FILE_END\]/g;
|
||||
const INLINE_ATTACHMENT_HINT_REGEX = /^.*(?:如果您需要查看全部数据,请下载附件。?|请下载附件。?).*$/gim;
|
||||
|
||||
@@ -462,7 +478,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
ctx.prepareMarkdownDisplayText(extracted.cleanedText),
|
||||
);
|
||||
try {
|
||||
const rendered = marked.parse(displayText);
|
||||
const rendered = marked.parse(displayText, { renderer: chatMarkdownRenderer });
|
||||
const html = typeof rendered === 'string' ? rendered : displayText;
|
||||
return enhanceAssetHistoryTableLinks(html)
|
||||
.replace(/<(td|th)\b([^>]*)>(?:\s| |<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* 用途:验证 Mermaid 兼容规范化,防止中文分组标题再次导致流程图解析失败。
|
||||
* 依赖:vitest、mermaidChart。
|
||||
* 逻辑:覆盖无 ID 中文 subgraph 的标准化以及原本标准语法的不变性。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildMermaidFlowFallbackHtml, normalizeMermaidChart } from './mermaidChart';
|
||||
|
||||
describe('normalizeMermaidChart', () => {
|
||||
it('为中文 subgraph 标题补齐可解析的 ASCII ID', () => {
|
||||
// 断言:Dify 常见的中文分组写法被转为 Mermaid 标准分组声明。
|
||||
expect(normalizeMermaidChart('graph TD\nsubgraph 项目启动阶段\nA[接单]\nend'))
|
||||
.toContain('subgraph group_1["项目启动阶段"]');
|
||||
});
|
||||
|
||||
it('保留已有 ID 的标准 subgraph', () => {
|
||||
// 断言:已规范的 Mermaid 不被重复改写。
|
||||
expect(normalizeMermaidChart('subgraph phase_start["项目启动阶段"]'))
|
||||
.toBe('subgraph phase_start["项目启动阶段"]');
|
||||
});
|
||||
|
||||
it('将无法解析的主流程降级为可视化卡片', () => {
|
||||
// 断言:即使 Mermaid 语法异常,用户仍能看到节点和顺序,而不是红色源码。
|
||||
const html = buildMermaidFlowFallbackHtml('A[接单] --> B[项目立项]\nB --> C[项目启动阶段]');
|
||||
expect(html).toContain('接单');
|
||||
expect(html).toContain('项目启动阶段');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 用途:规范化智能体输出的 Mermaid 图表文本,兼容中文分组标题等常见非标准写法。
|
||||
* 依赖:由 ChatMessageBubble 在调用 mermaid.render 前使用。
|
||||
* 逻辑:保留合法语句不变;仅为没有 ID 的 subgraph 补充稳定 ASCII ID 与带引号标题,
|
||||
* 避免 Mermaid 把中文标题解析为图语法 token 而导致整张流程图无法显示。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 用途:将常见的中文 Mermaid 分组语法转换为 Mermaid 可稳定解析的标准形式。
|
||||
* AI 触发时机:智能体返回 `subgraph 项目启动阶段` 等没有 ASCII 节点 ID 的分组标题时调用。
|
||||
* 核心逻辑:逐行识别 subgraph;已经包含 ID、方括号或引号的标准写法不变;其余标题生成唯一 ID。
|
||||
* 参数与输出约束:输入必须为 Mermaid 文本;输出只调整 subgraph 声明,不修改节点、连线及 end 语句。
|
||||
*/
|
||||
export function normalizeMermaidChart(source: string): string {
|
||||
let subgraphIndex = 0;
|
||||
return String(source || '')
|
||||
.replace(/^\s*graph\s+/im, (matched) => matched.replace(/graph/i, 'flowchart'))
|
||||
.split('\n')
|
||||
.map((line) => {
|
||||
const match = line.match(/^(\s*)subgraph\s+(.+?)\s*$/i);
|
||||
if (!match) return line;
|
||||
const indent = match[1] || '';
|
||||
const rawTitle = (match[2] || '').trim();
|
||||
if (!rawTitle || /[\[\]"']/.test(rawTitle) || /^[A-Za-z_][A-Za-z0-9_-]*\s/.test(rawTitle)) return line;
|
||||
subgraphIndex += 1;
|
||||
return `${indent}subgraph group_${subgraphIndex}["${rawTitle.replace(/"/g, '\\"')}"]`;
|
||||
})
|
||||
.join('\n')
|
||||
// Mermaid 对含括号、标点或中文的节点标签需要显式引号;Dify 常会遗漏它。
|
||||
.replace(/([A-Za-z][A-Za-z0-9_-]*)\[([^\]"\n]+)\]/g, (_matched, nodeId: string, label: string) => (
|
||||
`${nodeId}["${label.trim().replace(/"/g, '\\"')}"]`
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:在 Mermaid 仍无法解析时,将简单流程图转换为可读的流程卡片。
|
||||
* AI 触发时机:图表库抛出语法异常且原文中存在 `A[节点] --> B[节点]` 这类链路时调用。
|
||||
* 核心逻辑:提取节点顺序和标签,输出已转义的 HTML 卡片;忽略不影响主流程的 subgraph 细节。
|
||||
* 参数与输出约束:只用于展示兜底,不执行任何模型输出中的 HTML 或脚本。
|
||||
*/
|
||||
export function buildMermaidFlowFallbackHtml(source: string): string | null {
|
||||
const labels = new Map<string, string>();
|
||||
const order: string[] = [];
|
||||
const text = String(source || '');
|
||||
const nodePattern = /([A-Za-z][A-Za-z0-9_-]*)\s*\[\s*"?([^\]\n"]+)"?\s*\]/g;
|
||||
const edgePattern = /([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?\s*--+>\s*([A-Za-z][A-Za-z0-9_-]*)(?:\s*\[[^\]\n]*\])?/g;
|
||||
const escapeHtml = (value: string) => String(value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
for (const match of text.matchAll(nodePattern)) {
|
||||
const nodeId = match[1];
|
||||
const label = match[2];
|
||||
if (nodeId && label) labels.set(nodeId, label.trim());
|
||||
}
|
||||
for (const match of text.matchAll(edgePattern)) {
|
||||
const fromId = match[1];
|
||||
const toId = match[2];
|
||||
if (!fromId || !toId) continue;
|
||||
if (!order.includes(fromId)) order.push(fromId);
|
||||
if (!order.includes(toId)) order.push(toId);
|
||||
}
|
||||
if (order.length < 2) return null;
|
||||
const cards = order.map((id, index) => {
|
||||
const card = `<div class="chat-flow-fallback-card">${escapeHtml(labels.get(id) || id)}</div>`;
|
||||
return index < order.length - 1 ? `${card}<div class="chat-flow-fallback-arrow" aria-hidden="true">↓</div>` : card;
|
||||
});
|
||||
return `<div class="chat-flow-fallback" role="img" aria-label="流程图">${cards.join('')}</div>`;
|
||||
}
|
||||
@@ -122,12 +122,16 @@ export const getDocumentWorkflowState = (
|
||||
let syncStage: WorkflowStageState;
|
||||
if (!doc.latest_version || cleanStage.code === 'failed') {
|
||||
syncStage = { code: 'idle', label: t('kbWorkspace.status.idle'), className: IDLE_BADGE_CLASS };
|
||||
} else if (syncJob?.status === 'failed') {
|
||||
} else if (syncJob?.status === 'failed' || (latestStatus === 'ready' && Boolean(doc.latest_version?.error_message))) {
|
||||
syncStage = {
|
||||
code: 'failed',
|
||||
label: t('kbWorkspace.status.failed'),
|
||||
className: getStatusBadgeClass('failed'),
|
||||
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync', t),
|
||||
errorMessage: normalizeWorkflowErrorMessage(
|
||||
syncJob?.error_message || syncJob?.message || doc.latest_version?.error_message,
|
||||
'sync',
|
||||
t,
|
||||
),
|
||||
};
|
||||
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
|
||||
syncStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
|
||||
|
||||
Reference in new issue
Block a user