chat中源文件没用的问题
This commit is contained in:
1 parent
3d4b2647ae
commit
b745a9c803
6 files changed
+490
-99
No files matched your search
+65
-2
@@ -7,6 +7,7 @@ backend/app/api/chat.py
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
@@ -25,6 +26,25 @@ from app import db
|
||||
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
|
||||
if normalized.startswith("\\\\"):
|
||||
return "\\\\" + normalized[2:].rstrip("\\")
|
||||
return normalized.rstrip("\\")
|
||||
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
|
||||
return bool(
|
||||
normalized_root
|
||||
and normalized_target.startswith("\\\\")
|
||||
and normalized_target.lower().startswith(normalized_root.lower())
|
||||
)
|
||||
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -35,6 +55,8 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
3) 私网 IP 或常见内网域名(.local/.lan)。
|
||||
"""
|
||||
try:
|
||||
if _is_allowed_share_path(target_url):
|
||||
return True
|
||||
parsed = urlparse(target_url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
return False
|
||||
@@ -75,6 +97,25 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return None, None, ('source file not found', 404)
|
||||
file_size = os.path.getsize(normalized_path)
|
||||
if max_size is not None and file_size > max_size:
|
||||
return None, None, ('file too large for online preview', 413)
|
||||
with open(normalized_path, 'rb') as fh:
|
||||
content = fh.read()
|
||||
except OSError as exc:
|
||||
current_app.logger.warning("[file-preview] failed to read share path %s: %s", normalized_path, exc)
|
||||
return None, None, ('failed to read source file', 502)
|
||||
|
||||
guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower()
|
||||
if _extract_placeholder_text(content):
|
||||
guessed_type = 'text/plain; charset=utf-8'
|
||||
return content, guessed_type, None
|
||||
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
@@ -188,6 +229,24 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
return None, None, ('upstream returned invalid preview payload', 502)
|
||||
return content, content_type, None
|
||||
|
||||
|
||||
def _extract_placeholder_text(content: bytes) -> str:
|
||||
sample = content[:2048]
|
||||
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
try:
|
||||
text = sample.decode(enc).replace('\x00', '').strip()
|
||||
except Exception:
|
||||
continue
|
||||
if not text:
|
||||
continue
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if not lines:
|
||||
continue
|
||||
first_line = lines[0][:160]
|
||||
if any(token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密')):
|
||||
return first_line
|
||||
return ''
|
||||
|
||||
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 将 office 文件转为 PDF
|
||||
@@ -909,9 +968,13 @@ def preview_file_raw():
|
||||
'htm': 'text/html',
|
||||
}
|
||||
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
||||
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
|
||||
placeholder_text = _extract_placeholder_text(content)
|
||||
if placeholder_text:
|
||||
content = placeholder_text.encode('utf-8')
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
|
||||
|
||||
mime = fallback_types.get(ext) or content_type or 'application/octet-stream'
|
||||
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
|
||||
|
||||
from urllib.parse import quote
|
||||
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
|
||||
|
||||
@@ -14,6 +14,32 @@ from app.config import Config
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id or not row.get("found"):
|
||||
return None
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
return key, normalized
|
||||
|
||||
@staticmethod
|
||||
def _is_loopback_url(url: str) -> bool:
|
||||
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
|
||||
@@ -37,14 +63,13 @@ class IntegrationApiService:
|
||||
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
|
||||
public_base = ""
|
||||
|
||||
# For server-side lookups, always prefer the explicitly configured
|
||||
# integration service endpoint when present. Falling back to the current
|
||||
# request host would incorrectly call this backend itself.
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if mode != "external":
|
||||
# For server-side lookups inside containers/workers, an explicit integration
|
||||
# endpoint is more reliable than a public loopback URL like 127.0.0.1:5002.
|
||||
if configured and (
|
||||
not has_request_context()
|
||||
or IntegrationApiService._is_loopback_url(public_base)
|
||||
):
|
||||
return configured
|
||||
if public_base:
|
||||
return public_base
|
||||
if has_request_context():
|
||||
@@ -113,16 +138,55 @@ class IntegrationApiService:
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
payload = resp.json()
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
if isinstance(payload, dict):
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
elif has_app_context():
|
||||
current_app.logger.info(
|
||||
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
resp.status_code,
|
||||
)
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
|
||||
batch_url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
batch_headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
batch_body = {
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
]
|
||||
}
|
||||
try:
|
||||
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if not isinstance(data, list):
|
||||
return None
|
||||
for row in data:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
if key == cache_key:
|
||||
return normalized
|
||||
return None
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
@@ -199,28 +263,10 @@ class IntegrationApiService:
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
if not row.get("found"):
|
||||
continue
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
continue
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from html import escape
|
||||
from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
|
||||
@@ -13,6 +15,8 @@ from app.services.text2sql import Text2SQLService
|
||||
class PLMOracleService:
|
||||
_ALLOWED_AGENT_NAMES = {"通用入口", "生产sop"}
|
||||
_MAX_RESULT_ROWS = 50
|
||||
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
|
||||
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
|
||||
_EXPLICIT_LABEL_PATTERN = re.compile(
|
||||
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
|
||||
@@ -184,6 +188,114 @@ select *
|
||||
return f"{size / 1024:.1f} KB"
|
||||
return f"{size / 1024 / 1024:.2f} MB"
|
||||
|
||||
@classmethod
|
||||
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
|
||||
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
|
||||
for value in (storage_id, file_path, file_id):
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
parts.append(text.replace("/", "\\").strip("\\"))
|
||||
return "\\".join(part for part in parts if part)
|
||||
|
||||
@classmethod
|
||||
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
|
||||
def raw(column_name: str):
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return None
|
||||
value = row[idx]
|
||||
return None if value in (None, "") else value
|
||||
|
||||
file_name = str(raw("NAME") or "").strip()
|
||||
if not file_name:
|
||||
return "-"
|
||||
|
||||
storage_id = raw("STORAGEID")
|
||||
file_path = raw("FILEPATH")
|
||||
file_id = str(raw("ID") or "").strip()
|
||||
if not storage_id or file_path is None or not file_id:
|
||||
return escape(file_name)
|
||||
|
||||
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
|
||||
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
|
||||
return f'<a href="{preview_href}">{escape(file_name)}</a>'
|
||||
|
||||
@staticmethod
|
||||
def _escape_markdown_cell(value: str) -> str:
|
||||
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@staticmethod
|
||||
def _escape_html_text(value) -> str:
|
||||
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@classmethod
|
||||
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return "-"
|
||||
value = row[idx]
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
upper_name = column_name.upper()
|
||||
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if upper_name == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
if upper_name == "NAME":
|
||||
return cls._render_file_name(row, index_map)
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
|
||||
parts = [f"记录 {row_no}"]
|
||||
for column_name in cls._SUMMARY_COLUMNS:
|
||||
if column_name.upper() not in index_map:
|
||||
continue
|
||||
rendered = cls._render_column_value(row, column_name, index_map)
|
||||
label = {
|
||||
"NAME": "文件名",
|
||||
"EXTENTIONNAME": "扩展名",
|
||||
"FILETYPE": "文件类型",
|
||||
"FILESIZE": "文件大小",
|
||||
"RELATIVEPATH": "相对路径",
|
||||
"LASTACCESSTIME": "最后访问时间",
|
||||
}.get(column_name.upper(), column_name)
|
||||
if column_name.upper() == "NAME":
|
||||
parts.append(f"{label}: {rendered}")
|
||||
else:
|
||||
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
|
||||
return " | ".join(parts)
|
||||
|
||||
@classmethod
|
||||
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
|
||||
rows_html = []
|
||||
for column_name in columns:
|
||||
rendered_value = cls._render_column_value(row, column_name, index_map)
|
||||
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
|
||||
rows_html.append(
|
||||
"<tr>"
|
||||
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
|
||||
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
|
||||
summary_html = cls._build_record_summary(row, index_map, row_no)
|
||||
return (
|
||||
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
|
||||
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
|
||||
"<div style=\"margin-top:10px;overflow:auto;\">"
|
||||
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
|
||||
"<thead><tr>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
|
||||
"</tr></thead>"
|
||||
f"<tbody>{''.join(rows_html)}</tbody>"
|
||||
"</table>"
|
||||
"</div>"
|
||||
"</details>"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
|
||||
if not rows:
|
||||
@@ -193,29 +305,14 @@ select *
|
||||
visible_rows = rows[: cls._MAX_RESULT_ROWS]
|
||||
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
|
||||
|
||||
def pick(row: tuple, column_name: str, default: str = "-") -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return default
|
||||
value = row[idx]
|
||||
if column_name.upper() in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if column_name.upper() == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
return "-" if value in (None, "") else str(value)
|
||||
|
||||
lines = [
|
||||
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
|
||||
+ ("(仅展示前 50 条)" if overflow else "。"),
|
||||
"",
|
||||
"| 序号 | 文件名 | 扩展名 | 文件类型 | 文件大小 | 相对路径 | 最后访问时间 |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- |",
|
||||
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
|
||||
]
|
||||
for idx, row in enumerate(visible_rows, start=1):
|
||||
lines.append(
|
||||
f"| {idx} | {pick(row, 'NAME')} | {pick(row, 'EXTENTIONNAME')} | {pick(row, 'FILETYPE')} | "
|
||||
f"{pick(row, 'FILESIZE')} | {pick(row, 'RELATIVEPATH')} | {pick(row, 'LASTACCESSTIME')} |"
|
||||
)
|
||||
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
|
||||
|
||||
if overflow:
|
||||
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
|
||||
|
||||
@@ -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