260323 function add report chat and front

This commit is contained in:
super committed 2026-03-23 00:54:14 +08:00
1 parent 605317c2b2
commit 5e8ea03b6c
16 files changed
+2351 -100

No files matched your search

+280 -19
View File
@@ -17,6 +17,7 @@ import { Send, User, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, Rot
import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router';
import { config } from '../config';
import FilePreviewModal from '../components/FilePreviewModal.vue';
const { t, locale } = useI18n();
@@ -28,6 +29,202 @@ const renderMarkdown = (text: string) => {
return text;
}
};
const getSourceTitle = (item: any) => {
return item?.document_name || item?.title || item?.source || 'Untitled Source';
};
const getSourceMeta = (item: any) => {
const parts: string[] = [];
if (item?.dataset_name) parts.push(item.dataset_name);
if (item?.segment_id) parts.push(`segment: ${item.segment_id}`);
if (typeof item?.score === 'number') parts.push(`score: ${item.score.toFixed(3)}`);
return parts.join(' | ');
};
const getSourceContent = (item: any) => {
return item?.content || item?.segment_content || item?.text || '';
};
const getSourceBrief = (item: any) => {
const raw = getSourceContent(item);
const plain = raw
.replace(/\[[^\]]+\]\(([^)]+)\)/g, '$1')
.replace(/[#>*`]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!plain) return '';
return plain.length > 180 ? `${plain.slice(0, 180)}...` : plain;
};
interface SourceFileLink {
name: string;
url: string;
}
const safeDecode = (value: string) => {
try {
return decodeURIComponent(value);
} catch {
return value;
}
};
const normalizeUrl = (url: string) => {
// 统一清洗 URL:去掉包裹引号、还原转义字符、剔除末尾标点。
// 目的:让后续提取逻辑面对 Dify 返回的不同转义形态时保持稳定。
let v = url
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/')
.replace(/&/g, '&');
v = v.replace(/[),.;]+$/g, '');
if (!v) return '';
if (v.startsWith('//')) return `${window.location.protocol}${v}`;
if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\//.test(v)) return `http://${v}`;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//.test(v)) return `http://${v}`;
return '';
};
const extractUrlsFromText = (text: string) => {
if (!text) return [];
const urls: string[] = [];
// 先把常见 JSON/Markdown 转义做一次反转义,避免 regex 漏抓。
const normalizedText = text
.replace(/\\\//g, '/')
.replace(/\\u0026/gi, '&')
.replace(/\\u003d/gi, '=')
.replace(/\\u003a/gi, ':')
.replace(/\\u002f/gi, '/');
// 1) Markdown 链接: [name](url)
const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g;
let m;
while ((m = mdRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 2) HTML 链接: href/src 属性
const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
while ((m = htmlAttrRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 3) 尖括号 URL: <http://...>
const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi;
while ((m = angleRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
// 4) 原始 URL:支持带/不带协议、内网 IP、相对路径文件等
const rawRegex =
/((?:https?:\/\/|\/\/)[^\s"'<>]+|(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\/[^\s"'<>]+|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\/[^\s"'<>]+|\/[^\s"'<>]+\.(?:md|markdown|txt|pdf|doc|docx|ppt|pptx|xls|xlsx|jpg|jpeg|png|gif|webp|svg|bmp))/gi;
while ((m = rawRegex.exec(normalizedText)) !== null) {
const url = normalizeUrl(m[1] || '');
if (url) urls.push(url);
}
return urls;
};
const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
for (const item of resources) {
const directCandidates = [
item?.url,
item?.file_url,
item?.document_url,
item?.source_url,
item?.download_url,
item?.metadata?.url,
item?.metadata?.file_url,
item?.metadata?.document_url,
].filter(Boolean) as string[];
const content = getSourceContent(item);
const serialized = JSON.stringify(item || {});
const discovered = [
...directCandidates.map(normalizeUrl).filter(Boolean),
...extractUrlsFromText(content),
...extractUrlsFromText(serialized),
];
// Parse explicit file URL array if Dify provides it.
const files = Array.isArray(item?.files) ? item.files : [];
for (const f of files) {
const fu = normalizeUrl(f?.url || f?.download_url || f?.file_url || '');
if (fu) {
discovered.push(fu);
}
}
for (const url of discovered) {
const name = item?.document_name || item?.title || decodeURIComponent(url.split('/').pop() || 'source-file');
const key = `${name}|${url}`;
if (!map.has(key)) {
map.set(key, { name, url });
}
}
}
return Array.from(map.values());
};
const getMessageLinks = (msg: any): SourceFileLink[] => {
const map = new Map<string, SourceFileLink>();
const merge = (links: SourceFileLink[]) => {
for (const link of links) {
const key = `${link.name}|${link.url}`;
if (!map.has(key)) map.set(key, link);
}
};
if (msg?.retriever_resources) {
merge(getSourceLinks(msg.retriever_resources));
}
const contentLinks = extractUrlsFromText(msg?.content || '');
for (const url of contentLinks) {
const name = safeDecode(url.split('/').pop() || 'source-file');
merge([{ name, url }]);
}
if (Array.isArray(msg?.attribution_parts)) {
for (const part of msg.attribution_parts) {
const urls = extractUrlsFromText(typeof part === 'string' ? part : JSON.stringify(part));
for (const url of urls) {
const name = safeDecode(url.split('/').pop() || 'source-file');
merge([{ name, url }]);
}
}
}
// 5) 最后兜底:扫描整条 assistant 消息的 JSON 字符串。
// 用途:覆盖 Dify 在未知嵌套字段里返回链接但未被上面路径命中的情况。
const fullMessageText = JSON.stringify(msg || {});
const allUrls = extractUrlsFromText(fullMessageText);
for (const url of allUrls) {
const name = safeDecode(url.split('/').pop() || 'source-file');
merge([{ name, url }]);
}
return Array.from(map.values());
};
const filePreviewVisible = ref(false);
const previewFile = ref<SourceFileLink | null>(null);
const openPreview = (file: SourceFileLink) => {
previewFile.value = file;
filePreviewVisible.value = true;
};
const route = useRoute();
const router = useRouter();
const agentId = Number(route.params.agentId);
@@ -56,26 +253,30 @@ const presetQuestion = computed(() => {
});
const getAuthHeaders = () => {
let stored = localStorage.getItem('hxops_user');
if (!stored) stored = sessionStorage.getItem('hxops_user');
if (!stored) return {};
try {
const data = JSON.parse(stored);
const user = data.user || data;
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
const candidates = [
sessionStorage.getItem('hxops_user'),
localStorage.getItem('hxops_user'),
];
for (const stored of candidates) {
if (!stored) continue;
try {
const data = JSON.parse(stored);
const user = data.user || data;
if (!user?.username || !user?.role) continue;
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
} catch (e) {
continue;
}
return headers;
} catch (e) {
return {};
}
return {};
};
/**
@@ -264,7 +465,7 @@ const submitFeedback = async () => {
<div v-if="history.length === 0" class="text-center text-slate-400 text-sm py-8 italic">{{ $t('chat.noHistory') }}</div>
<button
v-for="item in history"
:key="item.id"
:key="item.conversation_id"
class="w-full text-left px-4 py-3 rounded-xl text-sm text-slate-600 hover:bg-white hover:shadow-sm truncate transition-all border border-transparent hover:border-slate-100"
:class="conversationId === item.conversation_id ? 'bg-white shadow-sm border-slate-100 text-brand-600 font-medium ring-1 ring-brand-500/10' : ''"
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
@@ -371,6 +572,64 @@ const submitFeedback = async () => {
v-html="renderMarkdown(msg.content)"
></div>
</div>
<div
v-if="msg.role === 'assistant' && ((msg.retriever_resources && msg.retriever_resources.length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
class="mt-2 space-y-2"
>
<div
v-if="getMessageLinks(msg).length > 0"
class="flex flex-wrap gap-2"
>
<button
v-for="(file, linkIndex) in getMessageLinks(msg)"
:key="`src-link-top-${linkIndex}-${file.url}`"
@click="openPreview(file)"
class="text-xs px-2.5 py-1.5 rounded-lg bg-brand-50 border border-brand-200 text-brand-700 hover:bg-brand-100 transition-colors break-all"
>
{{ file.name }}
</button>
</div>
<details
v-if="msg.retriever_resources && msg.retriever_resources.length > 0"
class="bg-slate-50 border border-slate-200 rounded-xl px-4 py-3"
>
<summary class="cursor-pointer text-xs font-semibold tracking-wide text-slate-600 uppercase">
源文档 ({{ msg.retriever_resources.length }})
</summary>
<div class="mt-3 space-y-2">
<div
v-for="(doc, docIndex) in msg.retriever_resources"
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
class="bg-white border border-slate-200 rounded-lg p-3"
>
<div class="text-sm font-semibold text-slate-800 break-all">{{ getSourceTitle(doc) }}</div>
<div v-if="getSourceMeta(doc)" class="text-xs text-slate-500 mt-1">{{ getSourceMeta(doc) }}</div>
<div v-if="getSourceBrief(doc)" class="text-xs text-slate-600 mt-2 whitespace-pre-wrap break-all">{{ getSourceBrief(doc) }}</div>
</div>
</div>
</details>
<details
v-if="msg.attribution_parts && msg.attribution_parts.length > 0"
class="bg-slate-50 border border-slate-200 rounded-xl px-4 py-3"
open
>
<summary class="cursor-pointer text-xs font-semibold tracking-wide text-slate-600 uppercase">
生成内容归属部分
</summary>
<ul class="mt-3 space-y-2">
<li
v-for="(part, partIndex) in msg.attribution_parts"
:key="`attr-${partIndex}`"
class="text-xs text-slate-700 bg-white border border-slate-200 rounded-lg p-3 whitespace-pre-wrap break-all"
>
{{ part }}
</li>
</ul>
</details>
</div>
<!-- Message Actions -->
<div
@@ -505,4 +764,6 @@ const submitFeedback = async () => {
</template>
</div>
</div>
<FilePreviewModal v-model="filePreviewVisible" :file="previewFile" />
</template>