From a1e0fa94042fd9c0f7d9a8d0be6380eeade40daa Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 2 Jun 2026 10:15:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(chat):=20=E4=B8=BA=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E6=B7=BB=E5=8A=A0=E4=B8=8A=E4=BC=A0=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=E6=96=87=E4=BB=B6=E5=92=8C=E8=BF=9C=E7=A8=8BURL?= =?UTF-8?q?=E9=99=84=E4=BB=B6=E7=9A=84=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/chat.py | 250 +++++++++++++- backend/app/api/user.py | 30 +- backend/app/services/dify.py | 204 ++++++++++- frontend/src/api/chat.ts | 20 ++ frontend/src/api/client.ts | 19 +- frontend/src/composables/useChat.ts | 13 +- frontend/src/views/ChatView.vue | 505 +++++++++++++++++++++++++++- 7 files changed, 1024 insertions(+), 17 deletions(-) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 73e681a5..8e969446 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -954,6 +954,7 @@ def chat_completions(): # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') kb_type = data.get('kb_type', '企业知识库') + files = data.get('files') request_id = uuid.uuid4().hex[:12] user = getattr(g, 'current_user', None) agent = getattr(g, 'current_agent', None) @@ -1007,21 +1008,56 @@ def chat_completions(): else: session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running') + normalized_files: list[dict] | None = None + if files is not None: + if not isinstance(files, list): + raise ValidationError('files must be a list') + normalized_files = [] + for item in files: + if not isinstance(item, dict): + continue + transfer_method = str(item.get('transfer_method') or '').strip() + ftype = str(item.get('type') or '').strip() + if transfer_method not in ('local_file', 'remote_url'): + continue + if ftype not in ('image', 'document', 'audio', 'video', 'custom'): + continue + if transfer_method == 'local_file': + upload_file_id = str(item.get('upload_file_id') or '').strip() + if not upload_file_id: + continue + normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id}) + else: + url = str(item.get('url') or '').strip() + if not url: + continue + normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url}) + if not normalized_files: + normalized_files = None + + if normalized_files and PLMOracleService.supports(query, agent_proxy): + raise ValidationError('This route does not support attachments') if PLMOracleService.supports(query, agent_proxy): generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) elif kb_type == 'ERP知识库': from app.services.hr_leave_sqlserver import HRLeaveSQLServerService from app.services.text2sql import Text2SQLService if HRLeaveSQLServerService.supports(query): + if normalized_files: + raise ValidationError('This route does not support attachments') generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) else: + if normalized_files: + raise ValidationError('This route does not support attachments') generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id) else: from app.services.hr_leave_sqlserver import HRLeaveSQLServerService if HRLeaveSQLServerService.supports(query): + if normalized_files: + raise ValidationError('This route does not support attachments') generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) else: - generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id) + generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files) def relay_stream(): created_event = { @@ -1098,6 +1134,218 @@ def chat_completions(): ) +@chat_bp.route('/files/upload', methods=['POST']) +@require_agent_permission +def upload_chat_file(): + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500) + if str(getattr(agent, 'type', '') or '').strip().lower() != 'api': + raise ValidationError('This agent does not support file upload') + if not getattr(agent, 'dify_api_key', None): + raise ValidationError('This agent does not support file upload') + + upload = request.files.get('file') + if not upload: + raise ValidationError('file is required') + + from app.services.dify import DifyService + from app.config import Config + + params = DifyService.get_app_parameters(agent, force_refresh=True) + file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {} + system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {} + + filename = str(getattr(upload, 'filename', '') or '').strip() + mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip() + detected_type, ext = DifyService.detect_file_type(filename, mimetype) + file_type = None + normalized_allowed_types = None + normalized_allowed_methods = None + normalized_allowed_exts = None + is_new_schema = False + if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list): + is_new_schema = True + normalized_allowed_types = set( + ( + str(v or '').strip().lower() + for v in (file_upload_cfg.get('allowed_file_types') or []) + if str(v or '').strip() + ) + ) + normalized_allowed_methods = set( + ( + str(v or '').strip().lower() + for v in (file_upload_cfg.get('allowed_file_upload_methods') or []) + if str(v or '').strip() + ) + ) + exts = [] + for v in (file_upload_cfg.get('allowed_file_extensions') or []): + s = str(v or '').strip() + if not s: + continue + if s.startswith('.'): + s = s[1:] + s = s.lower().strip() + if s: + exts.append(s) + normalized_allowed_exts = set(exts) if exts else None + + if detected_type: + file_type = detected_type + else: + if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)): + file_type = 'custom' + else: + custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None + if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)): + file_type = 'custom' + else: + raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})') + + def _effective_type_methods(target_type: str) -> set[str]: + if not isinstance(file_upload_cfg, dict): + return set(normalized_allowed_methods or set()) + cfg = file_upload_cfg.get(target_type) + transfer_methods = [] + if isinstance(cfg, dict): + transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or [] + if isinstance(transfer_methods, str): + transfer_methods = [transfer_methods] + if isinstance(transfer_methods, list) and len(transfer_methods) > 0: + return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip()) + return set(normalized_allowed_methods or set()) + + def _is_type_enabled_in_new_schema(target_type: str) -> bool: + if not (is_new_schema and normalized_allowed_types): + return False + if not isinstance(file_upload_cfg, dict): + return target_type in normalized_allowed_types + cfg = file_upload_cfg.get(target_type) + if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool): + if cfg.get('enabled') is False: + return False + if cfg.get('enabled') is True: + return True + return target_type in normalized_allowed_types + + if is_new_schema and normalized_allowed_types: + if not _is_type_enabled_in_new_schema(file_type): + raise ValidationError(f'File type not enabled: {file_type}') + type_methods = _effective_type_methods(file_type) + if 'local_file' not in type_methods: + raise ValidationError('local_file upload is not enabled') + if normalized_allowed_exts: + allowed_for_type = set() + for e in normalized_allowed_exts: + t, _ = DifyService.detect_file_type(f'file.{e}', None) + if t is None: + if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)): + allowed_for_type.add(e) + continue + if t == file_type: + allowed_for_type.add(e) + if allowed_for_type and (not ext or ext not in allowed_for_type): + raise ValidationError(f'Unsupported file extension: .{ext or ""}') + else: + # legacy schema checks + type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None + if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'): + raise ValidationError(f'File type not enabled: {file_type}') + transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or [] + if isinstance(transfer_methods, str): + transfer_methods = [transfer_methods] + if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)): + raise ValidationError('local_file upload is not enabled') + + def _mb_limit_for_type() -> float | None: + merged = {} + if isinstance(system_params, dict): + merged.update(system_params) + if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict): + merged.update(file_upload_cfg.get('fileUploadConfig') or {}) + if file_type == 'image': + return merged.get('image_file_size_limit') or merged.get('file_size_limit') + if file_type == 'audio': + return merged.get('audio_file_size_limit') or merged.get('file_size_limit') + if file_type == 'video': + return merged.get('video_file_size_limit') or merged.get('file_size_limit') + return merged.get('file_size_limit') + + size_limit_mb = _mb_limit_for_type() + if size_limit_mb is not None: + try: + import os + stream = getattr(upload, 'stream', None) + if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'): + cur = stream.tell() + stream.seek(0, os.SEEK_END) + size_bytes = stream.tell() + stream.seek(cur) + limit_bytes = int(float(size_limit_mb) * 1024 * 1024) + if size_bytes > limit_bytes: + raise ValidationError(f'File too large (limit {size_limit_mb}MB)') + except ValidationError: + raise + except Exception: + pass + + base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE + dify_url = DifyService._build_files_upload_url(base_url) + headers = {'Authorization': f'Bearer {agent.dify_api_key}'} + + try: + try: + upload.stream.seek(0) + except Exception: + pass + resp = requests.post( + dify_url, + headers=headers, + files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')}, + data={'user': str(getattr(user, 'id', 'system'))}, + timeout=(5, 60), + ) + except requests.RequestException as exc: + raise ServiceUnavailableError(f'Upload failed: {exc}') + + if not resp.ok: + body = (resp.text or '')[:1500] + header_snapshot = {} + try: + for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'): + v = resp.headers.get(k) or resp.headers.get(k.title()) + if v: + header_snapshot[k] = v + except Exception: + header_snapshot = {} + current_app.logger.warning( + '[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s', + resp.status_code, + dify_url, + header_snapshot, + body, + ) + raise AppError( + code='DIFY.UPLOAD_FAILED', + message='Upload failed', + http_status=502, + details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot}, + ) + + data = resp.json() if resp.content else {} + return jsonify({ + 'id': data.get('id'), + 'name': data.get('name') or filename, + 'size': data.get('size'), + 'extension': data.get('extension') or ext, + 'mime_type': data.get('mime_type') or mimetype, + 'type': file_type, + }) + + @chat_bp.route('/feedback', methods=['POST']) @require_agent_permission def submit_feedback(): diff --git a/backend/app/api/user.py b/backend/app/api/user.py index d8b5e0eb..bffb24f3 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -1442,7 +1442,33 @@ def get_agent_details(id): has_permission = agent in user.agents if not has_permission: raise ForbiddenError('Access denied') - return jsonify({'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.extra_config.get('icon_url') if agent.extra_config else None, 'welcome_message': agent.extra_config.get('welcome_message') if agent.extra_config else None, 'suggested_questions': agent.extra_config.get('suggested_questions', []) if agent.extra_config else []}) + extra_config = agent.extra_config or {} + dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None + + dify_parameters = None + agent_type = str(getattr(agent, 'type', '') or '').strip().lower() + if agent_type == 'api' and getattr(agent, 'dify_api_key', None): + from app.services.dify import DifyService + + params = DifyService.get_app_parameters(agent) + if isinstance(params, dict): + dify_parameters = { + 'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {}, + 'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {}, + } + + return jsonify({ + 'id': agent.id, + 'name': agent.name, + 'description': agent.description, + 'type': agent.type, + 'icon_url': agent.icon_url, + 'extra_config': extra_config if isinstance(extra_config, dict) else {}, + 'dify_app_type': dify_app_type, + 'welcome_message': extra_config.get('welcome_message') if isinstance(extra_config, dict) else None, + 'suggested_questions': extra_config.get('suggested_questions', []) if isinstance(extra_config, dict) else [], + 'dify_parameters': dify_parameters, + }) @user_bp.route('/db', methods=['GET']) def get_db(): @@ -1491,4 +1517,4 @@ def delete_announcement(id): if ann: db.session.delete(ann) db.session.commit() - return jsonify({'message': 'Deleted'}) \ No newline at end of file + return jsonify({'message': 'Deleted'}) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 60ca0f96..8a8a205a 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -26,6 +26,8 @@ import json import os import time import uuid +from datetime import datetime, timedelta +from threading import Lock from typing import Any, List, Optional import requests @@ -39,6 +41,119 @@ from app.services.integration_api import IntegrationApiService class DifyService: """Dify service wrapper.""" VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on") + SUPPORTED_FILE_EXTS: dict[str, set[str]] = { + "document": { + "txt", + "md", + "markdown", + "mdx", + "pdf", + "html", + "htm", + "xlsx", + "xls", + "vtt", + "properties", + "doc", + "docx", + "csv", + "eml", + "msg", + "pptx", + "ppt", + "xml", + "epub", + }, + "image": {"jpg", "jpeg", "png", "gif", "webp", "svg"}, + "audio": {"mp3", "m4a", "wav", "webm", "mpga"}, + "video": {"mp4", "mov", "mpeg", "webm"}, + } + + @staticmethod + def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None: + if not isinstance(data, dict): + return None + file_upload = data.get("file_upload") + if not isinstance(file_upload, dict): + return data + + allowed_types = file_upload.get("allowed_file_types") or [] + allowed_types_set = set( + str(v or "").strip().lower() + for v in (allowed_types if isinstance(allowed_types, list) else []) + if str(v or "").strip() + ) + allowed_exts = file_upload.get("allowed_file_extensions") or [] + normalized_exts = [] + for v in (allowed_exts if isinstance(allowed_exts, list) else []): + s = str(v or "").strip() + if not s: + continue + if s.startswith("."): + s = s[1:] + s = s.strip() + if not s: + continue + normalized_exts.append(s.lower()) + normalized_exts_set = set(normalized_exts) + + has_doc_ext = any(DifyService.detect_file_type(f"file.{e}", None)[0] == "document" for e in normalized_exts_set) + doc_cfg = file_upload.get("document") if isinstance(file_upload, dict) else None + doc_enabled = None + if isinstance(doc_cfg, dict) and isinstance(doc_cfg.get("enabled"), bool): + doc_enabled = bool(doc_cfg.get("enabled")) + + if "document" in allowed_types_set and doc_enabled is not False and not has_doc_ext: + add_exts = sorted(DifyService.SUPPORTED_FILE_EXTS.get("document") or []) + use_upper = any(str(v or "").strip().startswith(".") and str(v or "").strip().upper() == str(v or "").strip() for v in allowed_exts) + expanded = list(allowed_exts) if isinstance(allowed_exts, list) else [] + for e in add_exts: + if e in normalized_exts_set: + continue + expanded.append(f".{e.upper()}" if use_upper else f".{e}") + normalized_exts_set.add(e) + file_upload = dict(file_upload) + file_upload["allowed_file_extensions"] = expanded + data = dict(data) + data["file_upload"] = file_upload + + return data + + @staticmethod + def is_known_file_extension(ext: str | None) -> bool: + value = str(ext or "").strip().lower() + if not value: + return False + return any(value in s for s in DifyService.SUPPORTED_FILE_EXTS.values()) + + @staticmethod + def detect_file_type(filename: str | None, mimetype: str | None) -> tuple[str | None, str]: + name = str(filename or "").strip() + mime = str(mimetype or "").strip().lower() + ext = "" + if "." in name: + ext = name.rsplit(".", 1)[-1].lower().strip() + + if mime.startswith("image/"): + return "image", ext + if mime.startswith("audio/"): + return "audio", ext + if mime.startswith("video/"): + return "video", ext + + if ext in DifyService.SUPPORTED_FILE_EXTS["image"]: + return "image", ext + if ext in DifyService.SUPPORTED_FILE_EXTS["document"]: + return "document", ext + + in_audio = ext in DifyService.SUPPORTED_FILE_EXTS["audio"] + in_video = ext in DifyService.SUPPORTED_FILE_EXTS["video"] + if in_audio and not in_video: + return "audio", ext + if in_video: + return "video", ext + + return None, ext @staticmethod def _normalize_dify_conversation_id(conversation_id: str | None) -> str: @@ -114,6 +229,83 @@ class DifyService: return f"{base}/workflows/run" return f"{base}/v1/workflows/run" + @staticmethod + def _build_parameters_url(base_url: str) -> str: + base = str(base_url or "").strip().rstrip("/") + if not base: + return "/v1/parameters" + if base.endswith("/v1/parameters"): + base = base[: -len("/v1/parameters")].rstrip("/") + elif base.endswith("/parameters"): + base = base[: -len("/parameters")].rstrip("/") + if base.endswith("/v1"): + return f"{base}/parameters" + return f"{base}/v1/parameters" + + @staticmethod + def _build_files_upload_url(base_url: str) -> str: + base = str(base_url or "").strip().rstrip("/") + if not base: + return "/v1/files/upload" + if base.endswith("/v1/files/upload"): + base = base[: -len("/v1/files/upload")].rstrip("/") + elif base.endswith("/files/upload"): + base = base[: -len("/files/upload")].rstrip("/") + if base.endswith("/v1"): + return f"{base}/files/upload" + return f"{base}/v1/files/upload" + + _PARAMETERS_CACHE: dict[str, dict[str, Any]] = {} + _PARAMETERS_CACHE_LOCK = Lock() + + @staticmethod + def get_app_parameters(agent, *, ttl_seconds: int = 300, timeout: int = 8, force_refresh: bool = False) -> dict[str, Any] | None: + agent_id = str(getattr(agent, "id", "") or "") + api_key = str(getattr(agent, "dify_api_key", "") or "").strip() + base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE + url = DifyService._build_parameters_url(base_url) + cache_key = f"{agent_id}:{url}" + now = datetime.utcnow() + stale_data: dict[str, Any] | None = None + + with DifyService._PARAMETERS_CACHE_LOCK: + cached = DifyService._PARAMETERS_CACHE.get(cache_key) + if cached and isinstance(cached.get("data"), dict): + stale_data = cached.get("data") + if (not force_refresh) and cached and isinstance(cached.get("_expires_at"), datetime) and cached["_expires_at"] > now: + return cached.get("data") + + if not api_key: + return stale_data + + headers = {"Authorization": f"Bearer {api_key}"} + try: + resp = requests.get(url, headers=headers, timeout=timeout) + if not resp.ok: + if current_app: + current_app.logger.warning( + "[dify] get parameters failed agent_id=%s status=%s url=%s body=%s", + agent_id, + resp.status_code, + url, + (resp.text or "")[:500], + ) + return DifyService._normalize_parameters_payload(stale_data) or stale_data + data = resp.json() if resp.content else {} + except Exception as exc: + if current_app: + current_app.logger.warning("[dify] get parameters exception agent_id=%s url=%s err=%s", agent_id, url, exc) + return DifyService._normalize_parameters_payload(stale_data) or stale_data + + data = DifyService._normalize_parameters_payload(data) or data + + with DifyService._PARAMETERS_CACHE_LOCK: + DifyService._PARAMETERS_CACHE[cache_key] = { + "_expires_at": now + timedelta(seconds=ttl_seconds), + "data": data, + } + return data + @staticmethod def run_workflow_streaming( *, @@ -292,7 +484,15 @@ class DifyService: return {} @staticmethod - def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None, session_id: str | None = None): + def stream_chat( + query: str, + user_id: int, + agent, + conversation_id: str = None, + request_id: str | None = None, + session_id: str | None = None, + files: list[dict[str, Any]] | None = None, + ): """ 主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE Stream chat completion from Dify and relay SSE events to caller. @@ -328,6 +528,8 @@ class DifyService: 'conversation_id': normalized_conversation_id, 'user': str(user_id), } + if files: + payload['files'] = files if current_app: current_app.logger.info( diff --git a/frontend/src/api/chat.ts b/frontend/src/api/chat.ts index 42be8750..84d0b8f4 100644 --- a/frontend/src/api/chat.ts +++ b/frontend/src/api/chat.ts @@ -34,6 +34,15 @@ export interface ChatSourceFileResult { source_ext?: string; } +export interface ChatUploadResult { + id: string; + name?: string; + size?: number; + extension?: string; + mime_type?: string; + type?: 'image' | 'document' | 'audio' | 'video' | 'custom'; +} + export const listChatSessions = (agentId: number) => requestJson(`/api/chat/sessions?agent_id=${agentId}`, auth()); @@ -78,3 +87,14 @@ export const listOaEmployees = ( }); return requestJson(`/api/chat/oa/employees?${qs.toString()}`, auth()); }; + +export const uploadChatFile = (agentId: number, file: File) => { + const qs = new URLSearchParams({ agent_id: String(agentId) }); + const fd = new FormData(); + fd.append('file', file); + return requestJson(`/api/chat/files/upload?${qs.toString()}`, { + method: 'POST', + body: fd, + headers: getAuthHeaders(), + }); +}; diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 550d8595..4ac01447 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -1,4 +1,4 @@ -/** +/** * frontend/src/api/client.ts * 用途:封装前端统一 API 访问与响应解析逻辑。 * 说明: @@ -50,10 +50,23 @@ export class BusinessError extends Error { function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string { const normalizedCode = code ? code.replace(/\./g, '_') : ''; const key = normalizedCode ? `errors.codes.${normalizedCode}` : ''; + const fallback = String(fallbackMessage || '').trim(); + const isGenericFallback = (msg: string) => { + const v = msg.trim().toLowerCase(); + if (!v) return true; + if (v === 'invalid request parameters' || v === 'invalid request parameters.') return true; + if (v === 'request failed' || v === 'request failed.') return true; + if (v.startsWith('http ')) return true; + return false; + }; if (key && i18n.global.te(key)) { - return String(i18n.global.t(key)); + const localized = String(i18n.global.t(key)); + if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) { + return `${localized} ${fallback}`; + } + return localized; } - if (fallbackMessage) return fallbackMessage; + if (fallback) return fallback; if (i18n.global.te('errors.generic')) { return String(i18n.global.t('errors.generic')); } diff --git a/frontend/src/composables/useChat.ts b/frontend/src/composables/useChat.ts index dc08fe5b..2b13106a 100644 --- a/frontend/src/composables/useChat.ts +++ b/frontend/src/composables/useChat.ts @@ -179,7 +179,15 @@ export function useChat() { * query: 用户输入文本 * agentId: 目标 Agent ID */ - const sendMessage = async (query: string, agentId: number, kbType: string = '企业知识库') => { + const sendMessage = async ( + query: string, + agentId: number, + kbType: string = '企业知识库', + files?: Array< + | { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string } + | { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string } + >, + ) => { const runViewId = viewId.value; const runMessages = messages.value; const run: ChatRun = { @@ -227,7 +235,8 @@ export function useChat() { query, agent_id: agentId, conversation_id: conversationId.value, - kb_type: kbType + kb_type: kbType, + files: files && files.length > 0 ? files : undefined, }) }); diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index ad2e1f0c..810ff965 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -11,7 +11,7 @@ import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue'; import { useI18n } from 'vue-i18n'; import { useChat } from '../composables/useChat'; -import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building } from 'lucide-vue-next'; +import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, Briefcase, History, Sun, Moon, CalendarDays, Building, Paperclip, Link2 } from 'lucide-vue-next'; import LocaleToggleButton from '../components/LocaleToggleButton.vue'; import { marked } from 'marked'; import { useRoute, useRouter } from 'vue-router'; @@ -37,6 +37,7 @@ import { saveLocalChatMessage, resolveChatSourceFile, listOaEmployees, + uploadChatFile, } from '../api/chat'; import { getUserProfile, @@ -113,6 +114,9 @@ const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => { if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) { showKbDropdown.value = false; } + if (showAttachmentMenu.value && attachmentMenuRef.value && !attachmentMenuRef.value.contains(target)) { + closeAttachmentMenu(); + } }; const onAuthLogout = () => { @@ -654,6 +658,375 @@ const deleteConfirmMessage = ref(''); let pendingDeleteAction: (() => Promise | void) | null = null; const showAgentPanel = ref(true); +type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom'; + +type ChatUploadFileSpec = + | { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string } + | { type: ChatUploadFileType; transfer_method: 'remote_url'; url: string }; + +const DIFY_SUPPORTED_EXTS: Record, Set> = { + document: new Set([ + 'txt', 'md', 'markdown', 'mdx', 'pdf', 'html', 'htm', 'xlsx', 'xls', 'vtt', 'properties', + 'doc', 'docx', 'csv', 'eml', 'msg', 'pptx', 'ppt', 'xml', 'epub', + ]), + image: new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']), + audio: new Set(['mp3', 'm4a', 'wav', 'webm', 'mpga']), + video: new Set(['mp4', 'mov', 'mpeg', 'webm']), +}; + +const extractExt = (value: string) => { + const text = (value || '').trim().toLowerCase(); + const withoutQuery = (text.split('?')[0] || '').split('#')[0] || ''; + const idx = withoutQuery.lastIndexOf('.'); + if (idx < 0) return ''; + return withoutQuery.slice(idx + 1).trim(); +}; + +const isKnownDifyExt = (ext: string) => { + if (!ext) return false; + return ( + DIFY_SUPPORTED_EXTS.image.has(ext) + || DIFY_SUPPORTED_EXTS.document.has(ext) + || DIFY_SUPPORTED_EXTS.audio.has(ext) + || DIFY_SUPPORTED_EXTS.video.has(ext) + ); +}; + +const resolveDifyType = (ext: string, mime?: string): Exclude | null => { + const m = (mime || '').toLowerCase(); + if (m.startsWith('image/')) return 'image'; + if (m.startsWith('audio/')) return 'audio'; + if (m.startsWith('video/')) return 'video'; + if (DIFY_SUPPORTED_EXTS.image.has(ext)) return 'image'; + if (DIFY_SUPPORTED_EXTS.document.has(ext)) return 'document'; + const inAudio = DIFY_SUPPORTED_EXTS.audio.has(ext); + const inVideo = DIFY_SUPPORTED_EXTS.video.has(ext); + if (inAudio && !inVideo) return 'audio'; + if (inVideo) return 'video'; + return null; +}; + +type PendingAttachment = + | { id: string; kind: 'local'; file: File; type: ChatUploadFileType } + | { id: string; kind: 'remote'; url: string; type: ChatUploadFileType }; + +const attachments = ref([]); +const attachmentUrlInput = ref(''); +const isUploadingAttachments = ref(false); +const filePickerRef = ref(null); +const attachmentMenuRef = ref(null); +const attachmentUrlInputRef = ref(null); +const showAttachmentMenu = ref(false); +const showAttachmentUrlPanel = ref(false); + +const closeAttachmentMenu = () => { + showAttachmentMenu.value = false; + showAttachmentUrlPanel.value = false; + attachmentUrlInput.value = ''; +}; + +const toggleAttachmentMenu = async () => { + if (isThinking.value || isUploadingAttachments.value) return; + showAttachmentMenu.value = !showAttachmentMenu.value; + if (!showAttachmentMenu.value) { + showAttachmentUrlPanel.value = false; + attachmentUrlInput.value = ''; + } +}; + +const selectAttachmentLocal = () => { + if (!attachmentPolicy.value.canLocal) return; + closeAttachmentMenu(); + filePickerRef.value?.click(); +}; + +const selectAttachmentUrl = async () => { + if (!attachmentPolicy.value.canRemote) return; + showAttachmentMenu.value = true; + showAttachmentUrlPanel.value = true; + await nextTick(); + attachmentUrlInputRef.value?.focus(); +}; + +const difyFileUploadConfig = computed>(() => { + return (currentAgent.value?.dify_parameters?.file_upload as any) || {}; +}); + +const difySystemParameters = computed>(() => { + return (currentAgent.value?.dify_parameters?.system_parameters as any) || {}; +}); + +const attachmentPolicy = computed(() => { + const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom']; + const enabled: Record = { + image: { local: false, remote: false }, + document: { local: false, remote: false }, + audio: { local: false, remote: false }, + video: { local: false, remote: false }, + custom: { local: false, remote: false }, + }; + const raw = difyFileUploadConfig.value as any; + const normalizedAllowedExts = Array.isArray(raw?.allowed_file_extensions) + ? raw.allowed_file_extensions + .map((v: any) => String(v || '').trim()) + .filter(Boolean) + .map((v: string) => (v.startsWith('.') ? v.slice(1) : v).toLowerCase()) + .filter(Boolean) + : []; + const allowedExts: Set | null = normalizedAllowedExts.length > 0 ? new Set(normalizedAllowedExts) : null; + + const allowedTypes = Array.isArray(raw?.allowed_file_types) + ? raw.allowed_file_types + .map((v: any) => String(v || '').trim().toLowerCase()) + .filter(Boolean) + : []; + const allowedTypeSet = allowedTypes.length > 0 ? new Set(allowedTypes) : null; + + const allowedMethods = Array.isArray(raw?.allowed_file_upload_methods) + ? raw.allowed_file_upload_methods + .map((v: any) => String(v || '').trim().toLowerCase()) + .filter(Boolean) + : []; + const allowedMethodSet = allowedMethods.length > 0 ? new Set(allowedMethods) : null; + + const isNewSchema = Boolean(raw && raw.enabled === true && allowedTypeSet && allowedMethodSet); + if (isNewSchema && allowedTypeSet && allowedMethodSet) { + for (const t of types) { + const cfg = raw?.[t]; + const cfgEnabled = typeof cfg?.enabled === 'boolean' ? Boolean(cfg.enabled) : null; + const typeAllowed = allowedTypeSet.has(t); + if (cfgEnabled === false) continue; + if (cfgEnabled !== true && !typeAllowed) continue; + + const transferMethods = Array.isArray(cfg?.transfer_methods) + ? cfg.transfer_methods + .map((v: any) => String(v || '').trim().toLowerCase()) + .filter(Boolean) + : []; + const methodSet = transferMethods.length > 0 ? new Set(transferMethods) : allowedMethodSet; + + enabled[t] = { + local: methodSet.has('local_file'), + remote: methodSet.has('remote_url'), + limit: Number.isFinite(Number(cfg?.number_limits)) + ? Number(cfg.number_limits) + : (Number.isFinite(Number(raw?.number_limits)) ? Number(raw.number_limits) : undefined), + }; + } + } else { + for (const t of types) { + const cfg = raw?.[t]; + if (!cfg || !cfg.enabled) continue; + const transferMethods = Array.isArray(cfg.transfer_methods) ? cfg.transfer_methods : []; + enabled[t] = { + local: transferMethods.includes('local_file'), + remote: transferMethods.includes('remote_url'), + limit: Number.isFinite(Number(cfg.number_limits)) ? Number(cfg.number_limits) : undefined, + }; + } + } + + const mergedLimits = { + ...(difySystemParameters.value || {}), + ...(raw?.fileUploadConfig || {}), + } as any; + const system = mergedLimits || {}; + const sizeLimitMb: Record = { + image: Number.isFinite(Number(system.image_file_size_limit)) ? Number(system.image_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null), + audio: Number.isFinite(Number(system.audio_file_size_limit)) ? Number(system.audio_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null), + video: Number.isFinite(Number(system.video_file_size_limit)) ? Number(system.video_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null), + document: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null, + custom: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null, + }; + + const anyEnabled = Object.values(enabled).some((v) => v.local || v.remote); + const canLocal = Object.values(enabled).some((v) => v.local); + const canRemote = Object.values(enabled).some((v) => v.remote); + const totalLimit = (() => { + const v1 = raw?.fileUploadConfig?.file_upload_limit; + if (Number.isFinite(Number(v1))) return Number(v1); + const v2 = raw?.number_limits; + if (Number.isFinite(Number(v2))) return Number(v2); + return null; + })(); + + const effectiveAllowedExts: Set | null = (() => { + if (!allowedExts) return null; + const filtered = new Set(); + for (const ext of allowedExts) { + const t = resolveDifyType(ext); + if (!t) { + if (enabled.custom.local || enabled.custom.remote) filtered.add(ext); + continue; + } + if (enabled[t]?.local || enabled[t]?.remote) filtered.add(ext); + } + return filtered.size > 0 ? filtered : null; + })(); + + const accept = (() => { + if (enabled.custom.local) return ''; + if (effectiveAllowedExts) { + return Array.from(effectiveAllowedExts).map((e) => `.${e}`).join(','); + } + const parts = new Set(); + const pushExts = (exts: Set) => { + for (const e of exts) parts.add(`.${e}`); + }; + if (enabled.image.local) pushExts(DIFY_SUPPORTED_EXTS.image); + if (enabled.audio.local) pushExts(DIFY_SUPPORTED_EXTS.audio); + if (enabled.video.local) pushExts(DIFY_SUPPORTED_EXTS.video); + if (enabled.document.local) pushExts(DIFY_SUPPORTED_EXTS.document); + return Array.from(parts).join(','); + })(); + + return { + anyEnabled, + enabled, + sizeLimitMb, + canLocal, + canRemote, + accept, + allowedExts: effectiveAllowedExts, + totalLimit, + }; +}); + +const inferFileTypeFromUrl = (url: string): ChatUploadFileType | null => { + const ext = extractExt(url); + const resolved = resolveDifyType(ext); + return resolved; +}; + +const inferFileTypeFromFile = (file: File): ChatUploadFileType | null => { + const ext = extractExt(file.name || ''); + const resolved = resolveDifyType(ext, file.type || ''); + return resolved; +}; + +const removeAttachment = (id: string) => { + attachments.value = attachments.value.filter((a) => a.id !== id); +}; + +const handleLocalFilesSelected = (event: Event) => { + const inputEl = event.target as HTMLInputElement | null; + const fileList = inputEl?.files; + if (!fileList) return; + const files = Array.from(fileList); + for (const f of files) { + if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) { + msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`); + break; + } + const ext = extractExt(f.name || ''); + if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) { + msg.warning(`不支持的附件类型:${f.name}`); + continue; + } + let type = inferFileTypeFromFile(f); + if (!type) { + if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) { + type = 'custom'; + } else { + msg.warning(`不支持的附件类型:${f.name}`); + continue; + } + } + const caps = attachmentPolicy.value.enabled[type]; + if (!caps?.local) { + msg.warning(`当前应用不支持上传此类型附件:${type}`); + continue; + } + const limit = attachmentPolicy.value.sizeLimitMb[type]; + if (limit && f.size > limit * 1024 * 1024) { + msg.warning(`附件过大(上限 ${limit}MB):${f.name}`); + continue; + } + const countSameType = attachments.value.filter((a) => a.type === type).length; + if (caps.limit && countSameType >= caps.limit) { + msg.warning(`该类型附件数量已达上限(${caps.limit})`); + continue; + } + attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type }); + } + if (inputEl) inputEl.value = ''; +}; + +const addRemoteUrlAttachment = () => { + const raw = attachmentUrlInput.value.trim(); + if (!raw) return; + const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw; + if (!/^https?:\/\//i.test(url)) { + msg.warning('仅支持 http/https URL'); + return; + } + if (!attachmentPolicy.value.canRemote) { + msg.warning('当前应用不支持 URL 附件'); + return; + } + if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) { + msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`); + return; + } + const ext = extractExt(url); + if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) { + msg.warning('不支持的 URL 附件类型'); + return; + } + let type = inferFileTypeFromUrl(url); + if (!type) { + if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) { + type = 'custom'; + } else { + msg.warning('不支持的 URL 附件类型'); + return; + } + } + const caps = attachmentPolicy.value.enabled[type]; + if (!caps?.remote) { + msg.warning(`当前应用不支持该类型 URL 附件:${type}`); + return; + } + const countSameType = attachments.value.filter((a) => a.type === type).length; + if (caps.limit && countSameType >= caps.limit) { + msg.warning(`该类型附件数量已达上限(${caps.limit})`); + return; + } + attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type }); + attachmentUrlInput.value = ''; + closeAttachmentMenu(); +}; + +const buildFileSpecsForSend = async (): Promise => { + if (!attachmentPolicy.value.anyEnabled) return []; + if (attachments.value.length === 0) return []; + + const specs: ChatUploadFileSpec[] = []; + const locals = attachments.value.filter((a) => a.kind === 'local') as Array>; + const remotes = attachments.value.filter((a) => a.kind === 'remote') as Array>; + + if (locals.length > 0) { + isUploadingAttachments.value = true; + try { + for (const item of locals) { + const uploaded = await uploadChatFile(agentId, item.file); + if (!uploaded?.id) { + throw new Error('Missing upload id'); + } + specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id }); + } + } finally { + isUploadingAttachments.value = false; + } + } + + for (const item of remotes) { + specs.push({ type: item.type, transfer_method: 'remote_url', url: item.url }); + } + + return specs; +}; + const openDeleteConfirmDialog = ( message: string, onConfirm: () => Promise | void @@ -1690,16 +2063,43 @@ const presetQuestion = computed(() => { const handleSend = async (textOrEvent?: string | Event) => { const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value; - if (!content.trim() || isThinking.value) return; - - if (typeof textOrEvent !== 'string') input.value = ''; + if (!content.trim() || isThinking.value || isUploadingAttachments.value) return; if (isStrongLeaveIntent(content)) { startLocalLeaveFlow(content); return; } - await sendMessage(content, agentId, selectedKb.value); + let files: ChatUploadFileSpec[] = []; + if (attachmentPolicy.value.anyEnabled && attachments.value.length > 0) { + try { + files = await buildFileSpecsForSend(); + } catch (e: any) { + let suffix = ''; + if (e instanceof BusinessError) { + const headers = e.details?.headers; + const requestId = headers?.['x-request-id'] + || headers?.['x-requestid'] + || headers?.['request-id'] + || headers?.['trace-id'] + || headers?.['cf-ray']; + if (requestId) { + suffix = `(rid=${requestId})`; + } + try { + console.warn('[chat] attachment upload failed', { message: e.message, code: e.code, requestId, details: e.details }); + } catch { + } + } + msg.warning(`附件处理失败:${e?.message || 'unknown error'}${suffix}`); + return; + } + } + + if (typeof textOrEvent !== 'string') input.value = ''; + attachments.value = []; + + await sendMessage(content, agentId, selectedKb.value, files); if (!conversationId.value && history.value.length === 0) { await loadHistory(); @@ -2814,6 +3214,30 @@ const showChatRating = ref(false); autocorrect="off" autocapitalize="off" > + + + +
+
+ + {{ a.kind === 'local' ? a.file.name : a.url }} + + +
+
@@ -2827,6 +3251,70 @@ const showChatRating = ref(false); > +
+ +
+ + +
+
+ + + +
+
+
+