490 lines
19 KiB
TypeScript
490 lines
19 KiB
TypeScript
/**
|
|
* 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 '@/shared/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);
|
|
};
|
|
|
|
/**
|
|
* 判断源文件名是否为知识库上传链路生成的兜底名。
|
|
* AI 触发时机:当 Dify 文档名与 HXOPS 源文件名不一致时,用它识别 `uploaded_file.*`
|
|
* 这类无业务含义的占位名,避免聊天源文件按钮展示错误名称。
|
|
*/
|
|
const isFallbackUploadedFileName = (name: string) => {
|
|
const base = String(name || '').trim().split(/[\\/]/).pop() || '';
|
|
return /^uploaded_file(?:\.[A-Za-z0-9]{1,8})?$/i.test(base);
|
|
};
|
|
|
|
/**
|
|
* 选择聊天源文件按钮/预览弹窗的展示名称。
|
|
* AI 触发时机:构建 source file link 时调用;若本地源文件名是兜底名,
|
|
* 优先使用 Dify 检索返回的 document_name/title,下载链接仍沿用后端解析结果。
|
|
*/
|
|
const pickSourceDisplayName = (item: Record<string, unknown>, fallback = '') => {
|
|
const sourceFilename = String(item?.source_filename || '').trim();
|
|
const documentName = String(item?.document_name || item?.title || '').trim();
|
|
if (sourceFilename && !isFallbackUploadedFileName(sourceFilename)) return sourceFilename;
|
|
return documentName || sourceFilename || fallback;
|
|
};
|
|
|
|
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 previewFiles = ref<Array<{ name: string; url: string; actualExt?: string }>>([]);
|
|
const currentPreviewIndex = ref(0);
|
|
|
|
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 = pickSourceDisplayName(item);
|
|
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 = pickSourceDisplayName(item, 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 = pickSourceDisplayName(doc);
|
|
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 && !isFallbackUploadedFileName(data.source_filename)
|
|
? 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;
|
|
}
|
|
previewFiles.value = [resolvedFile];
|
|
currentPreviewIndex.value = 0;
|
|
previewFile.value = resolvedFile;
|
|
filePreviewVisible.value = true;
|
|
} catch (error: unknown) {
|
|
const message = error instanceof Error ? error.message : t('chat.previewUnavailable');
|
|
msg.warning(message);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 打开多文件预览组,并支持在同一弹窗内切换。
|
|
* AI 触发时机:当后端一次返回同资产的多张图片,需要在当前系统内左右切换查看时调用。
|
|
* 核心逻辑:先解析每个文件的可预览 URL,再把文件列表和初始索引写入共享弹窗状态。
|
|
* 参数与输出约束:files 必须至少有 1 个可预览项;initialIndex 会被钳制到合法范围。
|
|
*/
|
|
const openPreviewGallery = async (files: SourceFileLink[], initialIndex = 0) => {
|
|
const normalizedFiles = Array.isArray(files) ? files : [];
|
|
if (!normalizedFiles.length) {
|
|
msg.warning(t('chat.previewUnavailable'));
|
|
return;
|
|
}
|
|
try {
|
|
const resolvedFiles = await Promise.all(normalizedFiles.map((file) => resolveSourceLink(file)));
|
|
if (!resolvedFiles.length) {
|
|
msg.warning(t('chat.previewUnavailable'));
|
|
return;
|
|
}
|
|
const safeIndex = Math.min(Math.max(initialIndex, 0), resolvedFiles.length - 1);
|
|
const initialFile = resolvedFiles[safeIndex] || resolvedFiles[0];
|
|
if (!initialFile) {
|
|
msg.warning(t('chat.previewUnavailable'));
|
|
return;
|
|
}
|
|
if (shouldBypassEmbeddedPreview(initialFile)) {
|
|
window.location.href = initialFile.url;
|
|
return;
|
|
}
|
|
previewFiles.value = resolvedFiles;
|
|
currentPreviewIndex.value = safeIndex;
|
|
previewFile.value = initialFile;
|
|
filePreviewVisible.value = true;
|
|
} catch (error: unknown) {
|
|
const message = error instanceof Error ? error.message : t('chat.previewUnavailable');
|
|
msg.warning(message);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 切换当前预览中的文件索引。
|
|
* 用途:供 FilePreviewModal 在多图模式下切换上一张、下一张或缩略图点击时回写当前文件。
|
|
*/
|
|
const setPreviewFileIndex = (nextIndex: number) => {
|
|
if (!previewFiles.value.length) return;
|
|
const safeIndex = Math.min(Math.max(nextIndex, 0), previewFiles.value.length - 1);
|
|
currentPreviewIndex.value = safeIndex;
|
|
previewFile.value = previewFiles.value[safeIndex] || null;
|
|
};
|
|
|
|
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,
|
|
previewFiles,
|
|
currentPreviewIndex,
|
|
getSourceTitle,
|
|
getSourceMeta,
|
|
getSourceBrief,
|
|
getSourceLinks,
|
|
getMessageLinks,
|
|
getDisplayRetrieverResources,
|
|
shouldExpandSourceDetails,
|
|
openPreview,
|
|
openPreviewGallery,
|
|
setPreviewFileIndex,
|
|
parsePlmPreviewLink,
|
|
};
|
|
}
|