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

File diff suppressed because it is too large. Load diff
+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>
+78 -15
View File
@@ -4,7 +4,7 @@
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口
*/
import { ref, onMounted, computed } from 'vue';
import { ref, onMounted, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '../config';
@@ -29,6 +29,21 @@ import {
const { t, locale } = useI18n();
const router = useRouter();
const loadLanguagePreference = () => {
const storedLang = localStorage.getItem('hxops_lang');
if (storedLang) {
locale.value = storedLang;
}
};
const saveLanguagePreference = (lang: string) => {
localStorage.setItem('hxops_lang', lang);
};
watch(locale, (newLang) => {
saveLanguagePreference(newLang);
});
// Interfaces
interface Agent {
id: number;
@@ -73,10 +88,18 @@ const announcements = ref<Announcement[]>([]);
const quickQuestions = ref<QuickQuestion[]>([]);
const favoriteAgentIds = ref<number[]>([]);
const embeddedAgents = ref<EmbeddedAgent[]>([]);
const SECTION_TITLE_KEY_MAP: Record<string, string> = {
announcements: 'workspace.announcements.title',
favorites: 'workspace.favorites',
quick_questions: 'workspace.quickQuestions.title',
embedded: 'workspace.embedded.title',
all_agents: 'workspace.availableAgents',
};
const layoutSections = ref<LayoutSection[]>([
{ id: 'announcements', visible: true, collapsed: false, title: 'workspace.announcements.title' },
{ id: 'favorites', visible: true, collapsed: false, title: 'workspace.favorites' },
{ id: 'quick_questions', visible: true, collapsed: false, title: 'workspace.quickQuestions.title' },
{ id: 'embedded', visible: true, collapsed: false, title: 'workspace.embedded' },
{ id: 'embedded', visible: true, collapsed: false, title: 'workspace.embedded.title' },
{ id: 'all_agents', visible: true, collapsed: false, title: 'workspace.availableAgents' },
]);
@@ -162,6 +185,16 @@ const filteredQuickQuestions = computed(() => {
);
});
const normalizeSectionId = (id: string) => {
if (id === 'quice_questions' || id === 'quickQuestions') return 'quick_questions';
if (id === 'allAgents') return 'all_agents';
return id;
};
const getSectionTitleKey = (sectionId: string) => {
return SECTION_TITLE_KEY_MAP[normalizeSectionId(sectionId)] || normalizeSectionId(sectionId);
};
// Methods
const getAuthHeaders = () => {
let stored = localStorage.getItem('hxops_user');
@@ -206,24 +239,28 @@ const fetchHome = async () => {
embeddedAgents.value = data.embedded_agents || [];
if (data.layout && data.layout.sections) {
const backendSections = data.layout.sections as LayoutSection[];
const backendSections = (data.layout.sections as LayoutSection[]).map((s) => ({
...s,
id: normalizeSectionId(s.id),
}));
const defaultSections = [
{ id: 'favorites', visible: true },
{ id: 'quick_questions', visible: true },
{ id: 'embedded', visible: true },
{ id: 'all_agents', visible: true },
{ id: 'announcements', visible: true, title: getSectionTitleKey('announcements') },
{ id: 'favorites', visible: true, title: getSectionTitleKey('favorites') },
{ id: 'quick_questions', visible: true, title: getSectionTitleKey('quick_questions') },
{ id: 'embedded', visible: true, title: getSectionTitleKey('embedded') },
{ id: 'all_agents', visible: true, title: getSectionTitleKey('all_agents') },
];
const merged: LayoutSection[] = [];
const backendIds = new Set(backendSections.map(s => s.id));
const mapKey = (id: string) => (id === 'quick_questions' ? 'quickQuestions' : id === 'all_agents' ? 'allAgents' : id);
const mapKey = (id: string) => (normalizeSectionId(id) === 'quick_questions' ? 'quickQuestions' : normalizeSectionId(id) === 'all_agents' ? 'allAgents' : normalizeSectionId(id));
backendSections.forEach(s => {
const def = defaultSections.find(d => d.id === s.id);
if (config.workspace.modules[mapKey(s.id) as keyof typeof config.workspace.modules] === false) {
return;
}
merged.push({ ...def, ...s });
merged.push({ ...def, ...s, title: getSectionTitleKey(s.id) });
});
defaultSections.forEach(d => {
@@ -248,10 +285,11 @@ const fetchHome = async () => {
} else {
// Fallback for no layout data
const defaultSections = [
{ id: 'favorites', visible: true, collapsed: false },
{ id: 'quick_questions', visible: true, collapsed: false },
{ id: 'embedded', visible: true, collapsed: false },
{ id: 'all_agents', visible: true, collapsed: false },
{ id: 'announcements', visible: true, collapsed: false, title: getSectionTitleKey('announcements') },
{ id: 'favorites', visible: true, collapsed: false, title: getSectionTitleKey('favorites') },
{ id: 'quick_questions', visible: true, collapsed: false, title: getSectionTitleKey('quick_questions') },
{ id: 'embedded', visible: true, collapsed: false, title: getSectionTitleKey('embedded') },
{ id: 'all_agents', visible: true, collapsed: false, title: getSectionTitleKey('all_agents') },
];
layoutSections.value = defaultSections.filter(s => {
@@ -363,9 +401,13 @@ const handleLogin = async () => {
// Store in localStorage with 30 days expiry
const expiry = new Date().getTime() + 30 * 24 * 60 * 60 * 1000;
localStorage.setItem('hxops_user', JSON.stringify({ user, expiry }));
// Avoid stale session user overriding current login.
sessionStorage.removeItem('hxops_user');
} else {
// Store in sessionStorage (cleared when tab closed)
sessionStorage.setItem('hxops_user', JSON.stringify({ user }));
// Avoid stale remembered user overriding current login.
localStorage.removeItem('hxops_user');
}
await fetchHome();
@@ -570,6 +612,7 @@ const openAnnouncement = (ann: Announcement) => {
};
onMounted(async () => {
loadLanguagePreference();
loadAuthUser();
fetchAnnouncements();
if (currentUser.value && currentUser.value.role !== 'guest') {
@@ -798,14 +841,15 @@ onMounted(async () => {
<div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-bold text-slate-800 flex items-center gap-2.5 cursor-pointer select-none" @click="toggleSectionCollapse(section)">
<div class="p-2 rounded-lg" :class="{
'bg-emerald-50 text-emerald-600': section.id === 'announcements',
'bg-yellow-50 text-yellow-600': section.id === 'favorites',
'bg-brand-50 text-brand-600': section.id === 'quick_questions',
'bg-purple-50 text-purple-600': section.id === 'embedded',
'bg-slate-100 text-slate-600': section.id === 'all_agents'
}">
<component :is="section.id === 'favorites' ? Star : (section.id === 'embedded' ? Bot : LayoutGrid)" class="w-5 h-5" />
<component :is="section.id === 'announcements' ? Megaphone : (section.id === 'favorites' ? Star : (section.id === 'embedded' ? Bot : LayoutGrid))" class="w-5 h-5" />
</div>
{{ $t(section.title || section.id) }}
{{ $t(getSectionTitleKey(section.id)) }}
<component :is="section.collapsed ? ChevronDown : ChevronUp" class="w-4 h-4 text-slate-400" />
</h2>
<!-- Actions for Quick Questions -->
@@ -815,6 +859,25 @@ onMounted(async () => {
</div>
<div v-show="!section.collapsed" class="animate-fade-in">
<!-- Content: Announcements -->
<div v-if="section.id === 'announcements'">
<div v-if="announcements.length === 0" class="text-slate-400 text-sm italic py-8 text-center bg-slate-50 rounded-xl border border-dashed border-slate-200">{{ $t('workspace.announcements.noData') }}</div>
<div v-else class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
<div
v-for="ann in announcements"
:key="ann.id"
class="group border border-slate-200 rounded-2xl bg-white p-5 hover:border-emerald-300 hover:shadow-md transition-all cursor-pointer"
@click="openAnnouncement(ann)"
>
<div class="flex items-start justify-between gap-3 mb-2">
<h4 class="font-bold text-slate-900 line-clamp-2 group-hover:text-emerald-700 transition-colors">{{ ann.title }}</h4>
<span class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full whitespace-nowrap">{{ new Date(ann.created_at).toLocaleDateString() }}</span>
</div>
<p class="text-sm text-slate-600 line-clamp-3">{{ ann.content }}</p>
</div>
</div>
</div>
<!-- Content: Favorites -->
<div v-if="section.id === 'favorites'">
<div v-if="favoriteAgents.length === 0" class="text-slate-400 text-sm italic py-4 bg-slate-50 rounded-xl text-center border border-dashed border-slate-200">{{ $t('workspace.noFavorites') }}</div>