chat中源文件没用的问题
This commit is contained in:
1 parent
3d4b2647ae
commit
b745a9c803
6 files changed
+490
-99
No files matched your search
@@ -93,7 +93,9 @@ const needsOfficeFallback = computed(() => {
|
||||
* - 其余返回原始 URL,由浏览器自行处理。
|
||||
*/
|
||||
const iframeSrc = computed(() => {
|
||||
if (!props.file?.url || !props.agentId) return '';
|
||||
if (!props.file?.url) return '';
|
||||
if (officeObjectUrl.value) return officeObjectUrl.value;
|
||||
if (!props.agentId) return '';
|
||||
if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) {
|
||||
// These formats must use the authenticated fetch -> blob flow only.
|
||||
// Never fallback to a protected iframe URL, otherwise it returns Unauthorized.
|
||||
@@ -102,6 +104,8 @@ const iframeSrc = computed(() => {
|
||||
return props.file.url;
|
||||
});
|
||||
|
||||
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
|
||||
|
||||
const close = () => emit('update:modelValue', false);
|
||||
|
||||
const isDownloading = ref(false);
|
||||
@@ -198,19 +202,34 @@ const loadPdfContent = async () => {
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const buf = await res.arrayBuffer();
|
||||
// const head = new TextDecoder().decode(buf.slice(0, 5));
|
||||
// 暂时取消对 PDF header 的强校验,因为 docx 等文件也会调用该函数生成 Blob 并渲染在 iframe 或下载中
|
||||
// if (head !== '%PDF-') {
|
||||
// throw new Error('Invalid PDF binary from preview API');
|
||||
// }
|
||||
|
||||
const blob = await res.blob();
|
||||
clearOfficeObjectUrl();
|
||||
let type = 'application/octet-stream';
|
||||
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) type = 'application/pdf';
|
||||
else if (ext.value === 'docx') type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
||||
let fallbackType = 'application/octet-stream';
|
||||
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
|
||||
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
||||
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
|
||||
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
|
||||
};
|
||||
|
||||
const blob = new Blob([buf], { type });
|
||||
const loadBinaryContent = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for binary preview');
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
clearOfficeObjectUrl();
|
||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
||||
};
|
||||
|
||||
@@ -297,6 +316,20 @@ const loadContent = async () => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredMode.value === 'image' || (preferredMode.value === 'iframe' && !/^https?:\/\//i.test(props.file.url || ''))) {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
await loadBinaryContent();
|
||||
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || 'Failed to load file preview';
|
||||
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredMode.value !== 'markdown') return;
|
||||
|
||||
isLoading.value = true;
|
||||
@@ -435,7 +468,7 @@ watch(
|
||||
/>
|
||||
</div>
|
||||
<div v-else-if="resolvedMode === 'image'" class="h-full flex items-center justify-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-2">
|
||||
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
|
||||
<img :src="imageSrc" :alt="file.name" class="max-w-full max-h-full object-contain" />
|
||||
</div>
|
||||
<div
|
||||
v-else-if="['pdf', 'doc', 'ppt', 'pptx'].includes(ext) && officeObjectUrl"
|
||||
|
||||
@@ -40,7 +40,7 @@ const normalizeResources = (resources: any): RetrieverResource[] => {
|
||||
return [];
|
||||
};
|
||||
|
||||
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重
|
||||
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重和更新
|
||||
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
const list = normalizeResources(resources);
|
||||
if (list.length === 0) return;
|
||||
@@ -48,11 +48,17 @@ const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
for (const item of list) {
|
||||
// 使用稳定键进行去重,避免同一条来源在多事件中重复展示
|
||||
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
|
||||
const exists = msg.retriever_resources.some(
|
||||
const existingIndex = msg.retriever_resources.findIndex(
|
||||
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
|
||||
);
|
||||
if (!exists) {
|
||||
if (existingIndex < 0) {
|
||||
msg.retriever_resources.push(item);
|
||||
} else {
|
||||
// 存在则合并,确保后续带有 enrich 链接的字段能覆盖进去
|
||||
msg.retriever_resources[existingIndex] = {
|
||||
...msg.retriever_resources[existingIndex],
|
||||
...item
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+175
-29
@@ -143,7 +143,9 @@ const getSourceBrief = (item: any) => {
|
||||
|
||||
interface SourceFileLink {
|
||||
name: string;
|
||||
url: string;
|
||||
url?: string;
|
||||
datasetId?: string;
|
||||
remoteDocumentId?: string;
|
||||
}
|
||||
|
||||
// 源文件展示配置(来自 config.ts)
|
||||
@@ -208,15 +210,18 @@ const isPreferredSourceLink = (url: string) => {
|
||||
return PREFERRED_SOURCE_EXTS.has(ext);
|
||||
};
|
||||
|
||||
const isNoisySourceUrl = (url: string) => {
|
||||
const isNoisySourceUrl = (_url: string) => {
|
||||
// 带签名参数的下载链接在 UI 中可读性差(如 download?version_id=...&token=...)。
|
||||
return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
|
||||
// 暂时注释掉这段校验逻辑,保证有元数据能被展示出来
|
||||
// return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
|
||||
return false;
|
||||
};
|
||||
|
||||
const isNoisySourceName = (name: string) => {
|
||||
const isNoisySourceName = (_name: string) => {
|
||||
// 兜底过滤:名称如果本质是查询串而不是文件名,则不展示。
|
||||
const n = (name || '').trim().toLowerCase();
|
||||
return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
|
||||
// 注释掉,允许带参数的链接在没有文件名时也可以显示(作为退路)
|
||||
// return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
|
||||
return false;
|
||||
};
|
||||
|
||||
const looksLikeFileName = (name: string) => {
|
||||
@@ -226,6 +231,41 @@ const looksLikeFileName = (name: string) => {
|
||||
return /\.[A-Za-z0-9]{2,8}$/.test(n);
|
||||
};
|
||||
|
||||
const findFirstByKeys = (payload: any, 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 '';
|
||||
for (const key of keyCandidates) {
|
||||
const value = payload?.[key];
|
||||
if (value != null && String(value).trim()) {
|
||||
return String(value).trim();
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(payload)) {
|
||||
const found = findFirstByKeys(value, keyCandidates);
|
||||
if (found) return found;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const getResourceIds = (item: any) => {
|
||||
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
|
||||
const remoteDocumentId = findFirstByKeys(item, [
|
||||
'remote_document_id',
|
||||
'dify_document_id',
|
||||
'document_id',
|
||||
'doc_id',
|
||||
'source_document_id',
|
||||
]);
|
||||
return { datasetId, remoteDocumentId };
|
||||
};
|
||||
|
||||
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
|
||||
|
||||
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
|
||||
@@ -275,7 +315,21 @@ const extractUrlsFromText = (text: string) => {
|
||||
|
||||
const getSourceLinks = (resources: any[] = []): 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 item of resources) {
|
||||
const { datasetId, remoteDocumentId } = getResourceIds(item);
|
||||
const directCandidates = [
|
||||
item?.source_download_url,
|
||||
item?.url,
|
||||
@@ -290,6 +344,20 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
const content = getSourceContent(item);
|
||||
// 直接强制从对象的顶层属性里获取文件名和链接
|
||||
const forceName = item?.source_filename || item?.document_name || item?.title;
|
||||
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
|
||||
|
||||
if (forceName) {
|
||||
const key = forceName;
|
||||
mergeSourceLink(key, {
|
||||
name: forceName,
|
||||
...(forceUrl ? { url: forceUrl } : {}),
|
||||
...(datasetId ? { datasetId } : {}),
|
||||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(item || {});
|
||||
const discovered = [
|
||||
...directCandidates.map(normalizeUrl).filter(Boolean),
|
||||
@@ -309,23 +377,29 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
for (const url of discovered) {
|
||||
if (isChunkLikeLink(url)) continue;
|
||||
// URL 若为噪声签名链接,且没有可用文件名元数据,则跳过。
|
||||
if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
|
||||
// 这里去掉 isNoisySourceUrl 判断的直接 continue,让有名的链接能过
|
||||
// if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
|
||||
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
|
||||
// Skip links whose display name itself is noisy.
|
||||
if (isNoisySourceName(name)) continue;
|
||||
// 根据配置决定是否显示 MD 文件
|
||||
if ( (isMarkdownFileName(name) || isMarkdownByUrl(url))) continue;
|
||||
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]}`;
|
||||
if (!map.has(key)) {
|
||||
map.set(key, { name, url });
|
||||
}
|
||||
mergeSourceLink(key, {
|
||||
name,
|
||||
url,
|
||||
...(datasetId ? { datasetId } : {}),
|
||||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
const links = Array.from(map.values());
|
||||
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
|
||||
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
// return preferred.length > 0 ? preferred : links;
|
||||
return links;
|
||||
};
|
||||
|
||||
const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
@@ -336,19 +410,33 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
const map = new Map<string, SourceFileLink>();
|
||||
|
||||
const merge = (links: SourceFileLink[]) => {
|
||||
const mergeMessageLink = (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 link of links) {
|
||||
if (isChunkLikeLink(link.url)) continue;
|
||||
const linkUrl = link.url || '';
|
||||
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
|
||||
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
|
||||
if (isNoisySourceName(link.name)) continue;
|
||||
if ( (isMarkdownFileName(link.name) || isMarkdownByUrl(link.url))) continue;
|
||||
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
|
||||
if (isMarkdownFileName(link.name)) {
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${link.url.split('?')[0]}`;
|
||||
if (!map.has(key)) map.set(key, link);
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
|
||||
mergeMessageLink(key, link);
|
||||
continue;
|
||||
}
|
||||
if (isNoisySourceUrl(link.url) && !looksLikeFileName(link.name)) continue;
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${link.url.split('?')[0]}`;
|
||||
if (!map.has(key)) map.set(key, link);
|
||||
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
|
||||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
|
||||
mergeMessageLink(key, link);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -359,7 +447,7 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
}
|
||||
|
||||
const links = Array.from(map.values());
|
||||
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
};
|
||||
|
||||
@@ -381,7 +469,7 @@ const shouldExpandSourceDetails = (msg: any): boolean => {
|
||||
// }
|
||||
|
||||
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
|
||||
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url));
|
||||
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
|
||||
};
|
||||
|
||||
const shouldRenderMessage = (msg: any): boolean => {
|
||||
@@ -413,11 +501,62 @@ const shouldShowThinkingBubble = computed(() => {
|
||||
});
|
||||
|
||||
const filePreviewVisible = ref(false);
|
||||
const previewFile = ref<SourceFileLink | null>(null);
|
||||
const previewFile = ref<{ name: string; url: string } | null>(null);
|
||||
|
||||
const openPreview = (file: SourceFileLink) => {
|
||||
previewFile.value = file;
|
||||
filePreviewVisible.value = true;
|
||||
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string }> => {
|
||||
if (file.url) {
|
||||
return {
|
||||
name: file.name,
|
||||
url: file.url,
|
||||
};
|
||||
}
|
||||
if (!file.datasetId || !file.remoteDocumentId) {
|
||||
throw new Error('当前源文件暂未返回可预览链接');
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(agentId),
|
||||
dataset_id: file.datasetId,
|
||||
remote_document_id: file.remoteDocumentId,
|
||||
});
|
||||
const response = await fetch(`/api/chat/source-file?${params.toString()}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.error || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
|
||||
if (!resolvedUrl) {
|
||||
throw new Error('未查询到源文件下载地址');
|
||||
}
|
||||
|
||||
return {
|
||||
...file,
|
||||
url: resolvedUrl,
|
||||
name: data?.source_filename || file.name,
|
||||
};
|
||||
};
|
||||
|
||||
const openPreview = async (file: SourceFileLink) => {
|
||||
try {
|
||||
const resolvedFile = await resolveSourceLink(file);
|
||||
previewFile.value = resolvedFile;
|
||||
filePreviewVisible.value = true;
|
||||
} catch (error: any) {
|
||||
showMessageDialog('warning', error?.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 };
|
||||
};
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -810,6 +949,13 @@ const startLocalLeaveFlow = async (content: string) => {
|
||||
|
||||
const handleChatMarkdownClick = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
|
||||
const previewFile = parsePlmPreviewLink(anchor?.getAttribute('href') || '');
|
||||
if (previewFile) {
|
||||
event.preventDefault();
|
||||
openPreview(previewFile);
|
||||
return;
|
||||
}
|
||||
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
|
||||
if (!actionElement) return;
|
||||
const action = actionElement.getAttribute('data-leave-action');
|
||||
@@ -1801,13 +1947,13 @@ const showChatRating = ref(false);
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
|
||||
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getSourceLinks(getDisplayRetrieverResources(msg)).length > 0)"
|
||||
class="mt-2 space-y-2"
|
||||
>
|
||||
<!-- 带有URL链接的源文件名称,支持预览 -->
|
||||
<div v-if="getMessageLinks(msg).length > 0" class="flex flex-wrap gap-2">
|
||||
<div v-if="getSourceLinks(getDisplayRetrieverResources(msg)).length > 0" class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(file, linkIndex) in getMessageLinks(msg)"
|
||||
v-for="(file, linkIndex) in getSourceLinks(getDisplayRetrieverResources(msg))"
|
||||
:key="`src-link-top-${linkIndex}-${file.url}`"
|
||||
@click="openPreview(file)"
|
||||
class="break-all rounded-lg border border-brand-200 bg-brand-50 px-2.5 py-1.5 text-xs text-brand-700 transition-colors hover:bg-brand-100 dark:border-brand-500/30 dark:bg-brand-500/10 dark:text-brand-200 dark:hover:bg-brand-500/20"
|
||||
|
||||
Reference in new issue
Block a user