feat: 重构管理后台前端架构并新增完整功能

This commit is contained in:
hugo committed 2026-06-03 11:49:14 +08:00
commit 93304a1803
88 files changed
+9941 -6500

No files matched your search

+153 -78
View File
@@ -26,7 +26,7 @@ import { useTheme } from '../composables/useTheme';
import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth';
import { copyTextToClipboard } from '../utils/clipboard';
import { setLastChatAgentId } from '../utils/lastChatAgent';
import { openAgentChatTab, registerOpenAgentId } from '../utils/agentTabs';
import { registerOpenAgentId } from '../utils/agentTabs';
import ChatShell from '../layouts/ChatShell.vue';
import { BusinessError } from '../api/client';
import {
@@ -317,18 +317,57 @@ const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
return '';
};
const findDirectByKeys = (payloads: any[], keyCandidates: string[]): string => {
for (const payload of payloads) {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue;
for (const key of keyCandidates) {
const value = payload?.[key];
if (value != null && String(value).trim()) {
return String(value).trim();
}
}
}
return '';
};
const getResourceIds = (item: any) => {
const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata)
? item.metadata
: null;
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
const remoteDocumentId = findFirstByKeys(item, [
const remoteDocumentId = findDirectByKeys([item, metadata], [
'remote_document_id',
'dify_document_id',
'document_id',
'doc_id',
'source_document_id',
]);
'doc_id',
]) || findFirstByKeys(item, [
'remote_document_id',
'dify_document_id',
'source_document_id',
'doc_id',
]) || findDirectByKeys([item, metadata], ['document_id']);
return { datasetId, remoteDocumentId };
};
const canPreviewSourceLink = (link: Partial<SourceFileLink> | null | undefined) => {
if (!link) return false;
return Boolean(link.url || (link.datasetId && link.remoteDocumentId));
};
const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => {
const normalizedName = String(name || '').trim();
const normalizedDatasetId = String(datasetId || '').trim();
const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim();
const normalizedUrl = String(url || '').split('?')[0];
if (normalizedDatasetId && normalizedRemoteDocumentId) {
return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`;
}
if (looksLikeFileName(normalizedName)) {
return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName;
}
return `${normalizedName}|${normalizedUrl}`;
};
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
@@ -411,8 +450,8 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
const forceName = item?.source_filename || item?.document_name || item?.title;
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
if (forceName) {
const key = forceName;
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
mergeSourceLink(key, {
name: forceName,
...(forceUrl ? { url: forceUrl } : {}),
@@ -448,8 +487,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
// 根据配置决定是否显示 MD 文件
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
// Deduplicate by name if it looks like a filename, else by name + base URL
const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`;
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
mergeSourceLink(key, {
name,
url,
@@ -458,7 +496,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
});
}
}
const links = Array.from(map.values());
const links = Array.from(map.values()).filter((link) => canPreviewSourceLink(link));
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
// return preferred.length > 0 ? preferred : links;
@@ -487,18 +525,19 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
});
};
for (const link of links) {
if (!canPreviewSourceLink(link)) continue;
const linkUrl = link.url || '';
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
if (isNoisySourceName(link.name)) continue;
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
if (isMarkdownFileName(link.name)) {
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
continue;
}
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
mergeMessageLink(key, link);
}
};
@@ -567,33 +606,32 @@ const filePreviewVisible = ref(false);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
if (file.url) {
return {
name: file.name,
url: file.url,
actualExt: file.actualExt,
};
if (file.datasetId && file.remoteDocumentId) {
const data = await resolveChatSourceFile({
agent_id: currentAgentId.value,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (resolvedUrl) {
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
}
}
if (!file.datasetId || !file.remoteDocumentId) {
if (!file.url) {
throw new Error('当前源文件暂未返回可预览链接');
}
const data = await resolveChatSourceFile({
agent_id: agentId,
dataset_id: file.datasetId,
remote_document_id: file.remoteDocumentId,
});
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
if (!resolvedUrl) {
throw new Error('未查询到源文件下载地址');
}
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
name: file.name,
url: file.url,
actualExt: file.actualExt,
};
};
@@ -618,7 +656,10 @@ const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
};
const route = useRoute();
const router = useRouter();
const agentId = Number(route.params.agentId);
const currentAgentId = computed(() => {
const id = Number(route.params.agentId);
return Number.isFinite(id) && id > 0 ? id : 0;
});
// Sidebar state for mobile
const isSidebarOpen = ref(false);
@@ -1017,7 +1058,7 @@ const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
isUploadingAttachments.value = true;
try {
for (const item of locals) {
const uploaded = await uploadChatFile(agentId, item.file);
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
}
@@ -1272,7 +1313,7 @@ const fetchLeaveAgents = async (isLoadMore = false) => {
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(agentId, {
const data = await listOaEmployees(currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: leaveAgentPage.value,
page_size: 20,
@@ -1304,7 +1345,7 @@ const loadAllAgents = async () => {
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(agentId, {
const data = await listOaEmployees(currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: 1,
page_size: 100000,
@@ -1606,7 +1647,7 @@ const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
content: msg.content,
payload: msg.payload,
query: userQuery,
agent_id: agentId,
agent_id: currentAgentId.value,
});
if (!conversationId.value && data.conversation_id) {
conversationId.value = data.conversation_id;
@@ -1715,7 +1756,7 @@ const startLocalLeaveFlow = async (content: string) => {
try {
const keyword = payload.form.applicantName || payload.form.employeeId;
if (keyword) {
const data = await listOaEmployees(agentId, { keyword, page: 1, page_size: 1 });
const data = await listOaEmployees(currentAgentId.value, { keyword, page: 1, page_size: 1 });
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
if (match) {
payload.form.fillerJobTitle = match.jobtitle || '';
@@ -2029,6 +2070,7 @@ const displayHistory = computed<DisplayHistoryItem[]>(() => {
const server = history.value || [];
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.agentId === currentAgentId.value)
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
@@ -2049,7 +2091,7 @@ const handleHistorySelect = (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
} else {
const run = runs.value.find((r) => r.conversationId === item.conversation_id);
const run = runs.value.find((r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id);
if (run && run.status === 'running') {
activateRun(run.runId);
} else {
@@ -2561,7 +2603,7 @@ const handleSend = async (textOrEvent?: string | Event) => {
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await sendMessage(content, agentId, selectedKb.value, files);
await sendMessage(content, currentAgentId.value, selectedKb.value, files);
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
@@ -2778,7 +2820,7 @@ const regenerate = () => {
// 加载历史记录
const loadHistory = async () => {
try {
history.value = await listChatSessions(agentId);
history.value = await listChatSessions(currentAgentId.value);
} catch (e) {
console.error('Failed to load history', e);
}
@@ -2787,7 +2829,7 @@ const loadHistory = async () => {
const clearAllHistory = async () => {
openDeleteConfirmDialog(t('chat.confirmClearHistory'), async () => {
try {
await deleteAllChatSessions(agentId);
await deleteAllChatSessions(currentAgentId.value);
history.value = [];
runs.value = [];
if (conversationId.value || activeRunId.value) {
@@ -2803,7 +2845,7 @@ const deleteHistoryItem = async (id: string, event: Event) => {
event.stopPropagation();
openDeleteConfirmDialog(t('chat.confirmDeleteHistoryItem'), async () => {
try {
await deleteChatSession(id, agentId);
await deleteChatSession(id, currentAgentId.value);
history.value = history.value.filter(h => h.conversation_id !== id);
if (conversationId.value === id) {
startNewChat();
@@ -2820,7 +2862,7 @@ const loadConversation = async (id: string) => {
try {
activeRunId.value = null;
isThinking.value = false;
messages.value = await listChatMessages(id, agentId);
messages.value = await listChatMessages(id, currentAgentId.value);
conversationId.value = id;
} catch (e) {
console.error('Failed to load conversation', e);
@@ -2833,7 +2875,7 @@ const startNewChat = () => {
const loadAgent = async () => {
try {
currentAgent.value = await getUserAgent(agentId);
currentAgent.value = await getUserAgent(currentAgentId.value);
} catch (e) {
if (e instanceof BusinessError && e.status === 403) {
msg.error(t('workspace.permission.denied') || 'Access denied');
@@ -2849,7 +2891,7 @@ const loadUserAgents = async () => {
try {
const agents = await listUserAgents();
userAgents.value = Array.isArray(agents)
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
@@ -2861,10 +2903,9 @@ const loadUserAgents = async () => {
};
const switchToAgent = (agent: { id: number; name: string }) => {
if (agent.id === agentId) return;
if (agent.id === currentAgentId.value) return;
setLastChatAgentId(agent.id);
const url = router.resolve(`/chat/${agent.id}`).href;
openAgentChatTab(url, agent.id);
router.push(`/chat/${agent.id}`);
};
const syncOpenAgentRegistration = () => {
@@ -2877,16 +2918,63 @@ const onPageHide = () => {
};
const goToWorkspace = (view?: string) => {
setLastChatAgentId(Number(route.params.agentId));
setLastChatAgentId(currentAgentId.value);
registerOpenAgentId(null);
const query: Record<string, string> = { no_redirect: '1' };
if (view) query.view = view;
router.push({ path: '/workspace', query });
};
const resetChatStateForAgentChange = () => {
createNewChatView();
history.value = [];
attachments.value = [];
input.value = '';
currentAgent.value = null;
copiedIndex.value = null;
showAttachmentMenu.value = false;
filePreviewVisible.value = false;
previewFile.value = null;
};
let routeSyncToken = 0;
const syncChatStateForRoute = async () => {
const agentId = currentAgentId.value;
if (!agentId) return;
const syncToken = ++routeSyncToken;
resetChatStateForAgentChange();
stopVoiceInput();
setLastChatAgentId(agentId);
syncOpenAgentRegistration();
await syncCurrentUserProfile();
if (syncToken !== routeSyncToken) return;
await loadAgent();
if (syncToken !== routeSyncToken) return;
await loadUserAgents();
if (syncToken !== routeSyncToken) return;
await loadHistory();
if (syncToken !== routeSyncToken) return;
const convId = route.query.conversation_id as string;
if (convId) {
await loadConversation(convId);
if (syncToken !== routeSyncToken) return;
}
if (presetQuestion.value) {
input.value = presetQuestion.value;
await handleSend();
}
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
syncOpenAgentRegistration();
window.addEventListener('pagehide', onPageHide);
window.addEventListener('hxops:logout', onAuthLogout);
document.addEventListener('mousedown', handleDocumentPointerDown);
@@ -2894,36 +2982,23 @@ onMounted(async () => {
document.addEventListener('mousedown', handleMobileAgentPopoverClickOutside);
document.addEventListener('touchstart', handleMobileAgentPopoverClickOutside, { passive: true });
window.addEventListener('resize', syncViewportWidth);
await syncCurrentUserProfile();
setLastChatAgentId(Number(route.params.agentId));
await loadAgent();
await loadUserAgents();
await loadHistory();
const convId = route.query.conversation_id as string;
if (convId) {
await loadConversation(convId);
}
if (presetQuestion.value) {
input.value = presetQuestion.value;
handleSend();
} else if (shippingCaseIdFromQuery.value) {
input.value = t('chat.shippingNoticeContinue', { caseId: shippingCaseIdFromQuery.value });
handleSend();
}
await syncChatStateForRoute();
// Use config from config.ts instead of API
showChatRating.value = config.workspace?.showChatRating ?? true;
scheduleScrollChatToBottom();
});
watch(
() => route.params.agentId,
(id) => {
const nextId = Number(id);
if (Number.isFinite(nextId) && nextId > 0) setLastChatAgentId(nextId);
syncOpenAgentRegistration();
() => [route.params.agentId, route.query.conversation_id, route.query.preset],
async ([nextAgentId, nextConversationId, nextPreset], [prevAgentId, prevConversationId, prevPreset]) => {
if (
nextAgentId === prevAgentId
&& nextConversationId === prevConversationId
&& nextPreset === prevPreset
) {
return;
}
await syncChatStateForRoute();
}
);
@@ -3950,7 +4025,7 @@ const showChatRating = ref(false);
<FilePreviewModal
v-model="filePreviewVisible"
:file="previewFile"
:agent-id="agentId"
:agent-id="currentAgentId"
:auth-headers="getAuthHeaders()"
/>
<GeneralFeedbackDialog