refactor(chat + workspace): chat和workspace重构,子路由、懒加载等
This commit is contained in:
1 parent
0a647a0b79
commit
1f1f7236b0
57 files changed
+4356
-3798
No files matched your search
@@ -0,0 +1,408 @@
|
||||
/**
|
||||
* features/chat/composables/useChatSourceFiles.ts
|
||||
* 检索来源 / 源文件链接解析与预览。
|
||||
*/
|
||||
import { ref, type ComputedRef, type Ref } from 'vue';
|
||||
import type { ComposerTranslation } from 'vue-i18n';
|
||||
import { resolveChatSourceFile } from '../api/chat.api';
|
||||
import type { SourceFileLink } from '../types/chat.types';
|
||||
import type { useMessage } from '@/composables/useMessage';
|
||||
|
||||
const PREFERRED_SOURCE_EXTS = new Set([
|
||||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
|
||||
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
|
||||
'txt', 'rtf', 'md', 'markdown',
|
||||
]);
|
||||
|
||||
const safeDecode = (value: string) => {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeUrl = (url: string) => {
|
||||
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 getUrlExt = (url: string) => {
|
||||
const clean = (url.split('?')[0] || '').toLowerCase();
|
||||
const idx = clean.lastIndexOf('.');
|
||||
if (idx < 0) return '';
|
||||
return clean.slice(idx + 1);
|
||||
};
|
||||
|
||||
const isChunkLikeLink = (url: string) => /segment|chunk|fragments?|split/i.test(url);
|
||||
|
||||
const isPreferredSourceLink = (url: string) => PREFERRED_SOURCE_EXTS.has(getUrlExt(url));
|
||||
|
||||
const isNoisySourceUrl = (_url: string) => false;
|
||||
|
||||
const isNoisySourceName = (_name: string) => false;
|
||||
|
||||
const looksLikeFileName = (name: string) => {
|
||||
const n = (name || '').trim();
|
||||
if (!n) return false;
|
||||
return /\.[A-Za-z0-9]{2,8}$/.test(n);
|
||||
};
|
||||
|
||||
const findFirstByKeys = (payload: unknown, keyCandidates: string[]): string => {
|
||||
if (payload == null) return '';
|
||||
if (Array.isArray(payload)) {
|
||||
for (const item of payload) {
|
||||
const found = findFirstByKeys(item, keyCandidates);
|
||||
if (found) return found;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
if (typeof payload !== 'object') return '';
|
||||
const obj = payload as Record<string, unknown>;
|
||||
for (const key of keyCandidates) {
|
||||
const value = obj[key];
|
||||
if (value != null && String(value).trim()) return String(value).trim();
|
||||
}
|
||||
for (const value of Object.values(obj)) {
|
||||
const found = findFirstByKeys(value, keyCandidates);
|
||||
if (found) return found;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const findDirectByKeys = (payloads: unknown[], keyCandidates: string[]): string => {
|
||||
for (const payload of payloads) {
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue;
|
||||
const obj = payload as Record<string, unknown>;
|
||||
for (const key of keyCandidates) {
|
||||
const value = obj[key];
|
||||
if (value != null && String(value).trim()) return String(value).trim();
|
||||
}
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const getResourceIds = (item: Record<string, unknown>) => {
|
||||
const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata)
|
||||
? (item.metadata as Record<string, unknown>)
|
||||
: null;
|
||||
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
|
||||
const remoteDocumentId = findDirectByKeys([item, metadata], [
|
||||
'remote_document_id', 'dify_document_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());
|
||||
|
||||
const extractUrlsFromText = (text: string) => {
|
||||
if (!text) return [];
|
||||
const urls: string[] = [];
|
||||
const normalizedText = text
|
||||
.replace(/\\\//g, '/')
|
||||
.replace(/\\u0026/gi, '&')
|
||||
.replace(/\\u003d/gi, '=')
|
||||
.replace(/\\u003a/gi, ':')
|
||||
.replace(/\\u002f/gi, '/');
|
||||
|
||||
const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = mdRegex.exec(normalizedText)) !== null) {
|
||||
const url = normalizeUrl(m[1] || '');
|
||||
if (url) urls.push(url);
|
||||
}
|
||||
|
||||
const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
|
||||
while ((m = htmlAttrRegex.exec(normalizedText)) !== null) {
|
||||
const url = normalizeUrl(m[1] || '');
|
||||
if (url) urls.push(url);
|
||||
}
|
||||
|
||||
const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi;
|
||||
while ((m = angleRegex.exec(normalizedText)) !== null) {
|
||||
const url = normalizeUrl(m[1] || '');
|
||||
if (url) urls.push(url);
|
||||
}
|
||||
|
||||
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 getSourceContent = (item: Record<string, unknown>) =>
|
||||
String(item?.content || item?.segment_content || item?.text || '');
|
||||
|
||||
export interface UseChatSourceFilesOptions {
|
||||
agentId: ComputedRef<number>;
|
||||
t: ComposerTranslation;
|
||||
msg: ReturnType<typeof useMessage>;
|
||||
isMobile: Ref<boolean>;
|
||||
}
|
||||
|
||||
export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceFilesOptions) {
|
||||
const filePreviewVisible = ref(false);
|
||||
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
|
||||
|
||||
const getSourceTitle = (item: Record<string, unknown>) =>
|
||||
String(item?.document_name || item?.title || item?.source || 'Untitled Source');
|
||||
|
||||
const getSourceMeta = (item: Record<string, unknown>) => {
|
||||
const parts: string[] = [];
|
||||
if (item?.dataset_name) parts.push(String(item.dataset_name));
|
||||
if (item?.segment_id) parts.push(`segment: ${item.segment_id}`);
|
||||
if (typeof item?.score === 'number') parts.push(`score: ${(item.score as number).toFixed(3)}`);
|
||||
return parts.join(' | ');
|
||||
};
|
||||
|
||||
const getSourceBrief = (item: Record<string, unknown>) => {
|
||||
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;
|
||||
};
|
||||
|
||||
const getSourceLinks = (resources: unknown[] = []): SourceFileLink[] => {
|
||||
const map = new Map<string, SourceFileLink>();
|
||||
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
|
||||
const existing = map.get(key);
|
||||
if (!existing) {
|
||||
map.set(key, nextLink);
|
||||
return;
|
||||
}
|
||||
map.set(key, {
|
||||
...existing,
|
||||
...(nextLink.url ? { url: nextLink.url } : {}),
|
||||
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
|
||||
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
|
||||
});
|
||||
};
|
||||
|
||||
for (const raw of resources) {
|
||||
const item = (raw || {}) as Record<string, unknown>;
|
||||
const { datasetId, remoteDocumentId } = getResourceIds(item);
|
||||
const directCandidates = [
|
||||
item?.source_download_url, item?.url, item?.file_url, item?.document_url,
|
||||
item?.source_url, item?.download_url,
|
||||
(item?.metadata as Record<string, unknown> | undefined)?.source_download_url,
|
||||
(item?.metadata as Record<string, unknown> | undefined)?.url,
|
||||
(item?.metadata as Record<string, unknown> | undefined)?.file_url,
|
||||
(item?.metadata as Record<string, unknown> | undefined)?.document_url,
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
const content = getSourceContent(item);
|
||||
const forceName = String(item?.source_filename || item?.document_name || item?.title || '');
|
||||
const forceUrl = normalizeUrl(String(item?.source_download_url || item?.url || ''));
|
||||
|
||||
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
|
||||
const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl);
|
||||
mergeSourceLink(key, {
|
||||
name: forceName,
|
||||
...(forceUrl ? { url: forceUrl } : {}),
|
||||
...(datasetId ? { datasetId } : {}),
|
||||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(item || {});
|
||||
const discovered = [
|
||||
...directCandidates.map(normalizeUrl).filter(Boolean),
|
||||
...extractUrlsFromText(content),
|
||||
...extractUrlsFromText(serialized),
|
||||
];
|
||||
|
||||
const files = Array.isArray(item?.files) ? item.files : [];
|
||||
for (const f of files) {
|
||||
const file = f as Record<string, unknown>;
|
||||
const fu = normalizeUrl(String(file?.url || file?.download_url || file?.file_url || ''));
|
||||
if (fu) discovered.push(fu);
|
||||
}
|
||||
|
||||
for (const url of discovered) {
|
||||
if (isChunkLikeLink(url)) continue;
|
||||
const name = String(item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file'));
|
||||
if (isNoisySourceName(name)) continue;
|
||||
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
|
||||
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
|
||||
mergeSourceLink(key, {
|
||||
name,
|
||||
url,
|
||||
...(datasetId ? { datasetId } : {}),
|
||||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(map.values()).filter((link) => canPreviewSourceLink(link));
|
||||
};
|
||||
|
||||
const getMessageLinks = (message: Record<string, unknown>): SourceFileLink[] => {
|
||||
const map = new Map<string, SourceFileLink>();
|
||||
const merge = (links: SourceFileLink[]) => {
|
||||
for (const link of links) {
|
||||
if (!canPreviewSourceLink(link)) continue;
|
||||
const linkUrl = link.url || '';
|
||||
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
|
||||
if (isNoisySourceName(link.name)) continue;
|
||||
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
|
||||
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
|
||||
const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl);
|
||||
const existing = map.get(key);
|
||||
if (!existing) {
|
||||
map.set(key, link);
|
||||
} else {
|
||||
map.set(key, {
|
||||
...existing,
|
||||
...(link.url ? { url: link.url } : {}),
|
||||
...(link.datasetId ? { datasetId: link.datasetId } : {}),
|
||||
...(link.remoteDocumentId ? { remoteDocumentId: link.remoteDocumentId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (message?.retriever_resources) {
|
||||
merge(getSourceLinks(message.retriever_resources as unknown[]));
|
||||
}
|
||||
|
||||
const links = Array.from(map.values());
|
||||
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
};
|
||||
|
||||
const getDisplayRetrieverResources = (message: Record<string, unknown>): Record<string, unknown>[] => {
|
||||
const list = Array.isArray(message?.retriever_resources) ? message.retriever_resources as Record<string, unknown>[] : [];
|
||||
return list.filter((doc) => {
|
||||
const name = String(doc?.source_filename || doc?.document_name || doc?.title || '');
|
||||
const url = String(doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '');
|
||||
return !(isMarkdownFileName(name) || isMarkdownByUrl(url));
|
||||
});
|
||||
};
|
||||
|
||||
const shouldExpandSourceDetails = (message: Record<string, unknown>): boolean =>
|
||||
getMessageLinks(message).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
|
||||
|
||||
const getSourcePreviewExt = (file: { name?: string; url?: string; actualExt?: string }) => {
|
||||
const actual = String(file?.actualExt || '').trim().toLowerCase();
|
||||
if (actual) return actual;
|
||||
const byName = getUrlExt(file?.name || '');
|
||||
if (byName) return byName;
|
||||
return getUrlExt(file?.url || '');
|
||||
};
|
||||
|
||||
const isWeComMobileWebView = () => {
|
||||
if (typeof navigator === 'undefined') return false;
|
||||
const ua = navigator.userAgent || '';
|
||||
return /wxwork/i.test(ua) && /mobile/i.test(ua);
|
||||
};
|
||||
|
||||
const shouldBypassEmbeddedPreview = (file: { name?: string; url?: string; actualExt?: string }) => {
|
||||
const ext = getSourcePreviewExt(file);
|
||||
if (!isMobile.value || !isWeComMobileWebView()) return false;
|
||||
if (!/^https?:\/\//i.test(file?.url || '')) return false;
|
||||
return ['pdf', 'xls', 'xlsx'].includes(ext);
|
||||
};
|
||||
|
||||
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => {
|
||||
if (file.datasetId && file.remoteDocumentId) {
|
||||
const data = await resolveChatSourceFile({
|
||||
agent_id: agentId.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.url) throw new Error('当前源文件暂未返回可预览链接');
|
||||
return { name: file.name, url: file.url, actualExt: file.actualExt };
|
||||
};
|
||||
|
||||
const openPreview = async (file: SourceFileLink) => {
|
||||
try {
|
||||
const resolvedFile = await resolveSourceLink(file);
|
||||
if (shouldBypassEmbeddedPreview(resolvedFile)) {
|
||||
window.location.href = resolvedFile.url;
|
||||
return;
|
||||
}
|
||||
previewFile.value = resolvedFile;
|
||||
filePreviewVisible.value = true;
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : t('chat.previewUnavailable');
|
||||
msg.warning(message);
|
||||
}
|
||||
};
|
||||
|
||||
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
|
||||
const rawHref = (href || '').trim();
|
||||
if (!rawHref.startsWith('#plm-preview?')) return null;
|
||||
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
|
||||
const name = (params.get('name') || '').trim();
|
||||
const url = (params.get('url') || '').trim();
|
||||
if (!name || !url) return null;
|
||||
return { name, url };
|
||||
};
|
||||
|
||||
return {
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
getSourceTitle,
|
||||
getSourceMeta,
|
||||
getSourceBrief,
|
||||
getSourceLinks,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
shouldExpandSourceDetails,
|
||||
openPreview,
|
||||
parsePlmPreviewLink,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user