Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-06-02 13:20:41 +08:00
commit 86d1bd4588
13 files changed
+1149 -102

No files matched your search

+13 -5
View File
@@ -397,16 +397,24 @@ def list_users():
@require_admin @require_admin
def create_user(): def create_user():
data = request.get_json() or {} data = request.get_json() or {}
if not data.get('username'): required_field_errors = (
raise AppError(code='USER.USERNAME_REQUIRED', message='Username is required', http_status=400, details={'field': 'username'}) ('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
('password', 'USER.PASSWORD_REQUIRED', 'Password is required'),
('email', 'USER.EMAIL_REQUIRED', 'Email is required'),
('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'),
('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'),
('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'),
)
for field, code, message in required_field_errors:
if _empty_to_none(data.get(field)) is None:
raise AppError(code=code, message=message, http_status=400, details={'field': field})
if db.session.query(User).filter_by(username=data['username']).first(): if db.session.query(User).filter_by(username=data['username']).first():
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'}) raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'})
email = _empty_to_none(data.get('email')) email = _empty_to_none(data.get('email'))
if email is not None and (not _is_valid_email(email)): if not _is_valid_email(email):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number'))) user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number')))
if data.get('password'): user.set_password(data['password'])
user.set_password(data['password'])
if data.get('agent_ids'): if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents user.agents = agents
+249 -1
View File
@@ -954,6 +954,7 @@ def chat_completions():
# 前端传入的 conversation_id 在 B2 里代表本地 session_id # 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id') conversation_id = data.get('conversation_id')
kb_type = data.get('kb_type', '企业知识库') kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12] request_id = uuid.uuid4().hex[:12]
user = getattr(g, 'current_user', None) user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None) agent = getattr(g, 'current_agent', None)
@@ -1007,21 +1008,56 @@ def chat_completions():
else: else:
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running') 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): if PLMOracleService.supports(query, agent_proxy):
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif kb_type == 'ERP知识库': elif kb_type == 'ERP知识库':
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from app.services.text2sql import Text2SQLService from app.services.text2sql import Text2SQLService
if HRLeaveSQLServerService.supports(query): 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) generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else: 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) generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
else: else:
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
if HRLeaveSQLServerService.supports(query): 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) generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else: 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(): def relay_stream():
created_event = { 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']) @chat_bp.route('/feedback', methods=['POST'])
@require_agent_permission @require_agent_permission
def submit_feedback(): def submit_feedback():
+32 -4
View File
@@ -632,15 +632,15 @@ def login():
if not user: if not user:
_write_login_audit('password', 'failed', username=username, reason='user_not_found') _write_login_audit('password', 'failed', username=username, reason='user_not_found')
db.session.commit() db.session.commit()
raise NotFoundError('User not found') raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
if not user.check_password(password): if not user.check_password(password):
_write_login_audit('password', 'failed', user=user, reason='incorrect_password') _write_login_audit('password', 'failed', user=user, reason='incorrect_password')
db.session.commit() db.session.commit()
raise UnauthorizedError('Incorrect password') raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
if user.status != 'active': if user.status != 'active':
_write_login_audit('password', 'failed', user=user, reason='account_disabled') _write_login_audit('password', 'failed', user=user, reason='account_disabled')
db.session.commit() db.session.commit()
raise ForbiddenError('Account is disabled') raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
_write_login_audit('password', 'success', user=user) _write_login_audit('password', 'success', user=user)
db.session.commit() db.session.commit()
return jsonify(_build_login_payload(user, 'password')) return jsonify(_build_login_payload(user, 'password'))
@@ -662,6 +662,8 @@ def login():
except (OperationalError, DatabaseError) as retry_exc: except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc) current_app.logger.warning('Password login retry failed: %s', retry_exc)
raise ServiceUnavailableError('Database connection failed') raise ServiceUnavailableError('Database connection failed')
except AppError:
raise
except Exception as e: except Exception as e:
db.session.rollback() db.session.rollback()
current_app.logger.exception('Login error: %s', e) current_app.logger.exception('Login error: %s', e)
@@ -1442,7 +1444,33 @@ def get_agent_details(id):
has_permission = agent in user.agents has_permission = agent in user.agents
if not has_permission: if not has_permission:
raise ForbiddenError('Access denied') 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']) @user_bp.route('/db', methods=['GET'])
def get_db(): def get_db():
+203 -1
View File
@@ -26,6 +26,8 @@ import json
import os import os
import time import time
import uuid import uuid
from datetime import datetime, timedelta
from threading import Lock
from typing import Any, List, Optional from typing import Any, List, Optional
import requests import requests
@@ -39,6 +41,119 @@ from app.services.integration_api import IntegrationApiService
class DifyService: class DifyService:
"""Dify service wrapper.""" """Dify service wrapper."""
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on") 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 @staticmethod
def _normalize_dify_conversation_id(conversation_id: str | None) -> str: def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
@@ -114,6 +229,83 @@ class DifyService:
return f"{base}/workflows/run" return f"{base}/workflows/run"
return f"{base}/v1/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 @staticmethod
def run_workflow_streaming( def run_workflow_streaming(
*, *,
@@ -292,7 +484,15 @@ class DifyService:
return {} return {}
@staticmethod @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 主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
Stream chat completion from Dify and relay SSE events to caller. Stream chat completion from Dify and relay SSE events to caller.
@@ -328,6 +528,8 @@ class DifyService:
'conversation_id': normalized_conversation_id, 'conversation_id': normalized_conversation_id,
'user': str(user_id), 'user': str(user_id),
} }
if files:
payload['files'] = files
if current_app: if current_app:
current_app.logger.info( current_app.logger.info(
+2 -1
View File
@@ -60,7 +60,8 @@ def test_user_management(client, admin_headers):
"role": "user", "role": "user",
"password": "password123", "password": "password123",
"real_name": "Test User", "real_name": "Test User",
"employee_id": "EMP001" "employee_id": "EMP001",
"phone_number": "13800000001"
} }
response = client.post('/api/admin/users', json=new_user, headers=admin_headers) response = client.post('/api/admin/users', json=new_user, headers=admin_headers)
assert response.status_code == 201 assert response.status_code == 201
+6 -2
View File
@@ -100,8 +100,12 @@ def test_login_success(client):
def test_login_fail(client): def test_login_fail(client):
res = client.post('/api/user/login', json={'username': 'test1', 'password': 'wrongpassword'}) res = client.post('/api/user/login', json={'username': 'test1', 'password': 'wrongpassword'})
assert res.status_code == 401 assert res.status_code == 401
assert 'Incorrect password' in res.get_json()['error'] body = res.get_json()
assert body['error']['code'] == 'AUTH.INCORRECT_PASSWORD'
assert 'Incorrect password' in body['error']['message']
res = client.post('/api/user/login', json={'username': 'nonexistent', 'password': 'password'}) res = client.post('/api/user/login', json={'username': 'nonexistent', 'password': 'password'})
assert res.status_code == 404 assert res.status_code == 404
assert 'User not found' in res.get_json()['error'] body = res.get_json()
assert body['error']['code'] == 'AUTH.USER_NOT_FOUND'
assert 'User not found' in body['error']['message']
+6 -3
View File
@@ -52,7 +52,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"password": "pwd", "password": "pwd",
"email": "au1@e.com", "email": "au1@e.com",
"real_name": "Admin User 1", "real_name": "Admin User 1",
"employee_id": "ADM001" "employee_id": "ADM001",
"phone_number": "13800000011"
} }
response = client.post('/api/admin/users', json=u1, headers=admin_headers) response = client.post('/api/admin/users', json=u1, headers=admin_headers)
assert response.status_code == 201 assert response.status_code == 201
@@ -63,7 +64,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"password": "pwd", "password": "pwd",
"email": "au2@e.com", "email": "au2@e.com",
"real_name": "Admin User 2", "real_name": "Admin User 2",
"employee_id": "ADM001" "employee_id": "ADM001",
"phone_number": "13800000012"
} }
response = client.post('/api/admin/users', json=u2, headers=admin_headers) response = client.post('/api/admin/users', json=u2, headers=admin_headers)
assert response.status_code == 400 assert response.status_code == 400
@@ -76,7 +78,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
"password": "pwd", "password": "pwd",
"email": "au3@e.com", "email": "au3@e.com",
"real_name": "Admin User 3", "real_name": "Admin User 3",
"employee_id": "ADM003" "employee_id": "ADM003",
"phone_number": "13800000013"
} }
res = client.post('/api/admin/users', json=u3, headers=admin_headers) res = client.post('/api/admin/users', json=u3, headers=admin_headers)
u3_id = res.json['id'] u3_id = res.json['id']
+20
View File
@@ -34,6 +34,15 @@ export interface ChatSourceFileResult {
source_ext?: string; 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) => export const listChatSessions = (agentId: number) =>
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth()); requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
@@ -78,3 +87,14 @@ export const listOaEmployees = (
}); });
return requestJson<OaEmployeesResponse>(`/api/chat/oa/employees?${qs.toString()}`, auth()); return requestJson<OaEmployeesResponse>(`/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<ChatUploadResult>(`/api/chat/files/upload?${qs.toString()}`, {
method: 'POST',
body: fd,
headers: getAuthHeaders(),
});
};
+16 -3
View File
@@ -1,4 +1,4 @@
/** /**
* frontend/src/api/client.ts * frontend/src/api/client.ts
* 用途:封装前端统一 API 访问与响应解析逻辑。 * 用途:封装前端统一 API 访问与响应解析逻辑。
* 说明: * 说明:
@@ -50,10 +50,23 @@ export class BusinessError extends Error {
function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string { function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
const normalizedCode = code ? code.replace(/\./g, '_') : ''; const normalizedCode = code ? code.replace(/\./g, '_') : '';
const key = normalizedCode ? `errors.codes.${normalizedCode}` : ''; 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)) { 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')) { if (i18n.global.te('errors.generic')) {
return String(i18n.global.t('errors.generic')); return String(i18n.global.t('errors.generic'));
} }
+11 -2
View File
@@ -179,7 +179,15 @@ export function useChat() {
* query: 用户输入文本 * query: 用户输入文本
* agentId: 目标 Agent ID * 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 runViewId = viewId.value;
const runMessages = messages.value; const runMessages = messages.value;
const run: ChatRun = { const run: ChatRun = {
@@ -227,7 +235,8 @@ export function useChat() {
query, query,
agent_id: agentId, agent_id: agentId,
conversation_id: conversationId.value, conversation_id: conversationId.value,
kb_type: kbType kb_type: kbType,
files: files && files.length > 0 ? files : undefined,
}) })
}); });
+28
View File
@@ -156,6 +156,9 @@ const messages = {
generic: 'Request failed.', generic: 'Request failed.',
codes: { codes: {
AUTH_UNAUTHORIZED: 'Please log in first.', AUTH_UNAUTHORIZED: 'Please log in first.',
AUTH_INCORRECT_PASSWORD: 'Incorrect password',
AUTH_USER_NOT_FOUND: 'User not found',
AUTH_ACCOUNT_DISABLED: 'Account is disabled',
AUTH_FORBIDDEN: 'You do not have permission to perform this action.', AUTH_FORBIDDEN: 'You do not have permission to perform this action.',
RESOURCE_NOT_FOUND: 'The requested resource was not found.', RESOURCE_NOT_FOUND: 'The requested resource was not found.',
RESOURCE_CONFLICT: 'Request conflict. Please refresh and try again.', RESOURCE_CONFLICT: 'Request conflict. Please refresh and try again.',
@@ -543,7 +546,11 @@ const messages = {
confirmClean: 'Are you sure you want to delete all REJECTED users?', confirmClean: 'Are you sure you want to delete all REJECTED users?',
confirmBatchDelete: 'Are you sure you want to delete {count} users?', confirmBatchDelete: 'Are you sure you want to delete {count} users?',
msgs: { msgs: {
realNameRequired: 'Real name is required',
employeeIdRequired: 'Employee ID is required',
phoneRequired: 'Phone number is required',
usernameRequired: 'Username is required', usernameRequired: 'Username is required',
emailRequired: 'Email is required',
passwordRequired: 'Password is required for new users', passwordRequired: 'Password is required for new users',
invalidEmail: 'Invalid email format', invalidEmail: 'Invalid email format',
created: 'User created successfully', created: 'User created successfully',
@@ -1639,6 +1646,9 @@ const messages = {
generic: '请求失败。', generic: '请求失败。',
codes: { codes: {
AUTH_UNAUTHORIZED: '请先登录。', AUTH_UNAUTHORIZED: '请先登录。',
AUTH_INCORRECT_PASSWORD: '密码错误',
AUTH_USER_NOT_FOUND: '用户不存在',
AUTH_ACCOUNT_DISABLED: '账号已禁用',
AUTH_FORBIDDEN: '你没有权限执行该操作。', AUTH_FORBIDDEN: '你没有权限执行该操作。',
RESOURCE_NOT_FOUND: '请求的资源不存在。', RESOURCE_NOT_FOUND: '请求的资源不存在。',
RESOURCE_CONFLICT: '请求冲突,请刷新后重试。', RESOURCE_CONFLICT: '请求冲突,请刷新后重试。',
@@ -2027,7 +2037,11 @@ const messages = {
confirmClean: '确定要删除所有“已拒绝”的用户吗?', confirmClean: '确定要删除所有“已拒绝”的用户吗?',
confirmBatchDelete: '确定要删除选中的 {count} 个用户吗?', confirmBatchDelete: '确定要删除选中的 {count} 个用户吗?',
msgs: { msgs: {
realNameRequired: '真实姓名必填',
employeeIdRequired: '工号必填',
phoneRequired: '手机号必填',
usernameRequired: '用户名必填', usernameRequired: '用户名必填',
emailRequired: '邮箱必填',
passwordRequired: '新用户必须设置密码', passwordRequired: '新用户必须设置密码',
invalidEmail: '邮箱格式不正确', invalidEmail: '邮箱格式不正确',
created: '用户创建成功', created: '用户创建成功',
@@ -3086,6 +3100,9 @@ const messages = {
generic: '請求失敗。', generic: '請求失敗。',
codes: { codes: {
AUTH_UNAUTHORIZED: '請先登入。', AUTH_UNAUTHORIZED: '請先登入。',
AUTH_INCORRECT_PASSWORD: '密碼錯誤',
AUTH_USER_NOT_FOUND: '用戶不存在',
AUTH_ACCOUNT_DISABLED: '帳號已禁用',
AUTH_FORBIDDEN: '你沒有權限執行此操作。', AUTH_FORBIDDEN: '你沒有權限執行此操作。',
RESOURCE_NOT_FOUND: '請求的資源不存在。', RESOURCE_NOT_FOUND: '請求的資源不存在。',
RESOURCE_CONFLICT: '請求衝突,請刷新後重試。', RESOURCE_CONFLICT: '請求衝突,請刷新後重試。',
@@ -3474,7 +3491,11 @@ const messages = {
confirmClean: '確定要刪除所有“已拒絕”的用戶嗎?', confirmClean: '確定要刪除所有“已拒絕”的用戶嗎?',
confirmBatchDelete: '確定要刪除選中的 {count} 個用戶嗎?', confirmBatchDelete: '確定要刪除選中的 {count} 個用戶嗎?',
msgs: { msgs: {
realNameRequired: '真實姓名必填',
employeeIdRequired: '工號必填',
phoneRequired: '手機號必填',
usernameRequired: '用戶名必填', usernameRequired: '用戶名必填',
emailRequired: '郵箱必填',
passwordRequired: '新用戶必須設置密碼', passwordRequired: '新用戶必須設置密碼',
invalidEmail: '郵箱格式不正確', invalidEmail: '郵箱格式不正確',
created: '用戶創建成功', created: '用戶創建成功',
@@ -4408,6 +4429,9 @@ const messages = {
generic: 'คำขอล้มเหลว', generic: 'คำขอล้มเหลว',
codes: { codes: {
AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน', AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน',
AUTH_INCORRECT_PASSWORD: 'รหัสผ่านไม่ถูกต้อง',
AUTH_USER_NOT_FOUND: 'ไม่พบผู้ใช้',
AUTH_ACCOUNT_DISABLED: 'บัญชีถูกปิดใช้งาน',
AUTH_FORBIDDEN: 'คุณไม่มีสิทธิ์ดำเนินการนี้', AUTH_FORBIDDEN: 'คุณไม่มีสิทธิ์ดำเนินการนี้',
RESOURCE_NOT_FOUND: 'ไม่พบทรัพยากรที่ร้องขอ', RESOURCE_NOT_FOUND: 'ไม่พบทรัพยากรที่ร้องขอ',
RESOURCE_CONFLICT: 'คำขอขัดแย้ง โปรดรีเฟรชแล้วลองใหม่', RESOURCE_CONFLICT: 'คำขอขัดแย้ง โปรดรีเฟรชแล้วลองใหม่',
@@ -4713,7 +4737,11 @@ const messages = {
confirmClean: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ที่ถูกปฏิเสธทั้งหมด?', confirmClean: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ที่ถูกปฏิเสธทั้งหมด?',
confirmBatchDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ {count} คน?', confirmBatchDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ {count} คน?',
msgs: { msgs: {
realNameRequired: 'กรุณากรอกชื่อจริง',
employeeIdRequired: 'กรุณากรอกรหัสพนักงาน',
phoneRequired: 'กรุณากรอกเบอร์โทรศัพท์',
usernameRequired: 'กรุณากรอกชื่อผู้ใช้', usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
emailRequired: 'กรุณากรอกอีเมล',
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่', passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง', invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง',
created: 'สร้างผู้ใช้สำเร็จ', created: 'สร้างผู้ใช้สำเร็จ',
+64 -71
View File
@@ -366,20 +366,48 @@ const openEditUserModal = (user: UserRow) => {
}; };
const saveUser = async () => { const saveUser = async () => {
if (!editingUser.value.username) { const isCreate = !editingUser.value.id;
msg.warning(t('admin.user.msgs.usernameRequired'));
return;
}
const email = (editingUser.value.email || '').trim(); if (isCreate) {
if (email && !EMAIL_PATTERN.test(email)) { if (!(editingUser.value.real_name || '').trim()) {
msg.warning(t('admin.user.msgs.invalidEmail')); msg.warning(t('admin.user.msgs.realNameRequired'));
return; return;
} }
if (!(editingUser.value.employee_id || '').trim()) {
if (!editingUser.value.id && !editingUser.value.password) { msg.warning(t('admin.user.msgs.employeeIdRequired'));
msg.warning(t('admin.user.msgs.passwordRequired')); return;
return; }
if (!(editingUser.value.phone_number || '').trim()) {
msg.warning(t('admin.user.msgs.phoneRequired'));
return;
}
if (!(editingUser.value.username || '').trim()) {
msg.warning(t('admin.user.msgs.usernameRequired'));
return;
}
const email = (editingUser.value.email || '').trim();
if (!email) {
msg.warning(t('admin.user.msgs.emailRequired'));
return;
}
if (!EMAIL_PATTERN.test(email)) {
msg.warning(t('admin.user.msgs.invalidEmail'));
return;
}
if (!(editingUser.value.password || '').trim()) {
msg.warning(t('admin.user.msgs.passwordRequired'));
return;
}
} else {
if (!editingUser.value.username) {
msg.warning(t('admin.user.msgs.usernameRequired'));
return;
}
const email = (editingUser.value.email || '').trim();
if (email && !EMAIL_PATTERN.test(email)) {
msg.warning(t('admin.user.msgs.invalidEmail'));
return;
}
} }
isSaving.value = true; isSaving.value = true;
@@ -1350,7 +1378,6 @@ interface Department {
} }
const departments = ref<Department[]>([]); const departments = ref<Department[]>([]);
const editingDept = ref<Partial<Department>>({}); const editingDept = ref<Partial<Department>>({});
const isManagingDepts = ref(false);
const loadDepartments = async () => { const loadDepartments = async () => {
try { try {
@@ -3427,12 +3454,6 @@ const handlePermissionImport = async (event: Event) => {
<p class="section-desc mt-1">{{ t('admin.user.subtitle') }}</p> <p class="section-desc mt-1">{{ t('admin.user.subtitle') }}</p>
</div> </div>
<div class="flex flex-wrap gap-3"> <div class="flex flex-wrap gap-3">
<button
@click="isManagingDepts = true"
class="btn-secondary text-sm"
>
<span>{{ t('admin.user.manageDepts') }}</span>
</button>
<button <button
@click="cleanRejectedUsers" @click="cleanRejectedUsers"
class="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition-all border border-red-200 text-sm font-medium" class="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition-all border border-red-200 text-sm font-medium"
@@ -5304,27 +5325,36 @@ const handlePermissionImport = async (event: Event) => {
<!-- 内容滚动区域:字段较多时在此区域滚动,不挤压底部操作按钮 --> <!-- 内容滚动区域:字段较多时在此区域滚动,不挤压底部操作按钮 -->
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto"> <div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-1.5"> <div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.realName') }}</label> <label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!editingUser.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.realName') }}
</label>
<input <input
v-model="editingUser.real_name" v-model="editingUser.real_name"
type="text" type="text"
class="w-full border-default rounded-xl px-4 py-3 text-sm " class="w-full border-default rounded-xl px-4 py-3 text-sm "
:required="!editingUser.id"
/> />
</div> </div>
<div class="space-y-1.5"> <div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.employeeId') }}</label> <label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!editingUser.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.employeeId') }}
</label>
<input <input
v-model="editingUser.employee_id" v-model="editingUser.employee_id"
type="text" type="text"
class="w-full border-default rounded-xl px-4 py-3 text-sm " class="w-full border-default rounded-xl px-4 py-3 text-sm "
:required="!editingUser.id"
/> />
</div> </div>
<div class="space-y-1.5"> <div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.phone') }}</label> <label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!editingUser.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.phone') }}
</label>
<input <input
v-model="editingUser.phone_number" v-model="editingUser.phone_number"
type="text" type="text"
class="w-full border-default rounded-xl px-4 py-3 text-sm " class="w-full border-default rounded-xl px-4 py-3 text-sm "
:required="!editingUser.id"
/> />
</div> </div>
@@ -5351,20 +5381,26 @@ const handlePermissionImport = async (event: Event) => {
</div> </div>
<div class="space-y-1.5"> <div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.username') }}</label> <label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!editingUser.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.username') }}
</label>
<input <input
v-model="editingUser.username" v-model="editingUser.username"
type="text" type="text"
class="w-full border-default rounded-xl px-4 py-3 text-sm " class="w-full border-default rounded-xl px-4 py-3 text-sm "
:disabled="!!editingUser.id" :disabled="!!editingUser.id"
:required="!editingUser.id"
/> />
</div> </div>
<div class="space-y-1.5"> <div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.email') }}</label> <label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!editingUser.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.email') }}
</label>
<input <input
v-model="editingUser.email" v-model="editingUser.email"
type="email" type="email"
class="w-full border-default rounded-xl px-4 py-3 text-sm " class="w-full border-default rounded-xl px-4 py-3 text-sm "
:required="!editingUser.id"
/> />
</div> </div>
<div class="space-y-1.5"> <div class="space-y-1.5">
@@ -5389,12 +5425,14 @@ const handlePermissionImport = async (event: Event) => {
</div> </div>
<div class="space-y-1.5"> <div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider"> <label class="block text-xs font-semibold text-muted uppercase tracking-wider">
{{ t('admin.user.fields.password') }} <span v-if="editingUser.id" class="text-muted font-normal lowercase">{{ t('admin.user.fields.passwordHint') }}</span> <span v-if="!editingUser.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.password') }}
<span v-if="editingUser.id" class="text-muted font-normal lowercase">{{ t('admin.user.fields.passwordHint') }}</span>
</label> </label>
<input <input
v-model="editingUser.password" v-model="editingUser.password"
type="password" type="password"
class="w-full border-default rounded-xl px-4 py-3 text-sm " class="w-full border-default rounded-xl px-4 py-3 text-sm "
:required="!editingUser.id"
/> />
</div> </div>
</div> </div>
@@ -6234,51 +6272,6 @@ const handlePermissionImport = async (event: Event) => {
</div> </div>
</div> </div>
<!-- Department Management Modal -->
<div v-if="isManagingDepts" class="admin-modal-overlay items-center animate-fade-in">
<div class="admin-modal-panel max-w-lg p-6 animate-fade-in-up">
<h3 class="section-title mb-6">{{ t('admin.user.manageDepts') }}</h3>
<div class="flex gap-2 mb-6">
<input
v-model="editingDept.name"
:placeholder="t('admin.dept.fields.name')"
class="input-field flex-1 text-sm"
@keyup.enter="saveDepartment"
/>
<button
@click="saveDepartment"
class="btn-primary btn-sm"
>
{{ t('admin.add') }}
</button>
</div>
<div class="max-h-[50vh] overflow-y-auto border border-subtle rounded-xl divide-y divide-subtle bg-surface-soft/50">
<div v-if="departments.length === 0" class="p-8 text-center text-muted text-sm">{{ t('admin.dept.noDepts') }}</div>
<div v-for="d in departments" :key="d.id" class="p-3 flex justify-between items-center hover-surface-soft transition-colors group">
<span class="text-sm font-medium text-secondary ml-2">{{ d.name }}</span>
<button
@click="deleteDepartment(d.id)"
class="text-muted hover:text-red-500 hover:bg-red-50 p-1.5 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
:title="t('admin.delete')"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
<div class="mt-6 flex justify-end">
<button
@click="isManagingDepts = false"
class="btn-ghost"
>
{{ t('admin.close') }}
</button>
</div>
</div>
</div>
<DeleteConfirmDialog <DeleteConfirmDialog
v-model="showDeleteConfirmDialog" v-model="showDeleteConfirmDialog"
:title="deleteConfirmTitle" :title="deleteConfirmTitle"
+499 -9
View File
@@ -11,7 +11,7 @@
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue'; import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat'; 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 LocaleToggleButton from '../components/LocaleToggleButton.vue';
import { marked } from 'marked'; import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
@@ -37,6 +37,7 @@ import {
saveLocalChatMessage, saveLocalChatMessage,
resolveChatSourceFile, resolveChatSourceFile,
listOaEmployees, listOaEmployees,
uploadChatFile,
} from '../api/chat'; } from '../api/chat';
import { import {
getUserProfile, getUserProfile,
@@ -113,6 +114,9 @@ const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) { if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) {
showKbDropdown.value = false; showKbDropdown.value = false;
} }
if (showAttachmentMenu.value && attachmentMenuRef.value && !attachmentMenuRef.value.contains(target)) {
closeAttachmentMenu();
}
}; };
const onAuthLogout = () => { const onAuthLogout = () => {
@@ -654,6 +658,375 @@ const deleteConfirmMessage = ref('');
let pendingDeleteAction: (() => Promise<void> | void) | null = null; let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const showAgentPanel = ref(true); 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<Exclude<ChatUploadFileType, 'custom'>, Set<string>> = {
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<ChatUploadFileType, 'custom'> | 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<PendingAttachment[]>([]);
const attachmentUrlInput = ref('');
const isUploadingAttachments = ref(false);
const filePickerRef = ref<HTMLInputElement | null>(null);
const attachmentMenuRef = ref<HTMLElement | null>(null);
const attachmentUrlInputRef = ref<HTMLInputElement | null>(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<Record<string, any>>(() => {
return (currentAgent.value?.dify_parameters?.file_upload as any) || {};
});
const difySystemParameters = computed<Record<string, any>>(() => {
return (currentAgent.value?.dify_parameters?.system_parameters as any) || {};
});
const attachmentPolicy = computed(() => {
const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom'];
const enabled: Record<ChatUploadFileType, { local: boolean; remote: boolean; limit?: number }> = {
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<string> | null = normalizedAllowedExts.length > 0 ? new Set<string>(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<ChatUploadFileType, number | null> = {
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<string> | null = (() => {
if (!allowedExts) return null;
const filtered = new Set<string>();
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<string>();
const pushExts = (exts: Set<string>) => {
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<ChatUploadFileSpec[]> => {
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<Extract<PendingAttachment, { kind: 'local' }>>;
const remotes = attachments.value.filter((a) => a.kind === 'remote') as Array<Extract<PendingAttachment, { kind: 'remote' }>>;
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 = ( const openDeleteConfirmDialog = (
message: string, message: string,
onConfirm: () => Promise<void> | void onConfirm: () => Promise<void> | void
@@ -1204,11 +1577,12 @@ const syncLeaveDuration = (form: LeaveRequestFormData) => {
} }
}; };
const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, ''); const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, '');
const isStrongLeaveIntent = (content: string) => { const isStrongLeaveIntent = (content: string) => {
const normalized = getLeaveIntentNormalized(content); const normalized = getLeaveIntentNormalized(content);
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/; const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/; const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
if (weakConsultationIntent.test(normalized)) return false; if (weakConsultationIntent.test(normalized)) return false;
if (materialConsultationIntent.test(normalized)) return false; if (materialConsultationIntent.test(normalized)) return false;
@@ -1690,16 +2064,43 @@ const presetQuestion = computed(() => {
const handleSend = async (textOrEvent?: string | Event) => { const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value; const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value) return; if (!content.trim() || isThinking.value || isUploadingAttachments.value) return;
if (typeof textOrEvent !== 'string') input.value = '';
if (isStrongLeaveIntent(content)) { if (isStrongLeaveIntent(content)) {
startLocalLeaveFlow(content); startLocalLeaveFlow(content);
return; 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) { if (!conversationId.value && history.value.length === 0) {
await loadHistory(); await loadHistory();
@@ -2815,6 +3216,30 @@ const showChatRating = ref(false);
autocapitalize="off" autocapitalize="off"
></textarea> ></textarea>
<input
ref="filePickerRef"
type="file"
multiple
class="hidden"
:accept="attachmentPolicy.accept || undefined"
@change="handleLocalFilesSelected"
/>
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
<div
v-for="a in attachments"
:key="a.id"
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
>
<span class="max-w-[220px] truncate">
{{ a.kind === 'local' ? a.file.name : a.url }}
</span>
<button type="button" class="text-muted hover:text-red-500" @click="removeAttachment(a.id)">
<X class="h-3.5 w-3.5" />
</button>
</div>
</div>
<div class="mt-2 flex items-center justify-between px-2 pb-1"> <div class="mt-2 flex items-center justify-between px-2 pb-1">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<button <button
@@ -2827,6 +3252,70 @@ const showChatRating = ref(false);
> >
<Mic class="h-5 w-5" /> <Mic class="h-5 w-5" />
</button> </button>
<div v-if="attachmentPolicy.anyEnabled" ref="attachmentMenuRef" class="relative">
<button
@click="toggleAttachmentMenu"
type="button"
:disabled="isThinking || isUploadingAttachments"
title="附件"
class="text-muted transition-colors hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
>
<Paperclip class="h-5 w-5" />
</button>
<div
v-if="showAttachmentMenu"
class="absolute bottom-full left-0 mb-2 w-72 overflow-hidden rounded-xl border border-subtle bg-surface py-1 shadow-xl animate-fade-in"
>
<button
v-if="attachmentPolicy.canLocal"
type="button"
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
@click="selectAttachmentLocal"
>
<Paperclip class="h-4 w-4 text-brand-500" />
上传本地文件
</button>
<button
v-if="attachmentPolicy.canRemote"
type="button"
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
@click="selectAttachmentUrl"
>
<Link2 class="h-4 w-4 text-brand-500" />
粘贴 URL
</button>
<div v-if="showAttachmentUrlPanel" class="px-3 py-2">
<div class="flex items-center gap-2">
<input
ref="attachmentUrlInputRef"
v-model="attachmentUrlInput"
:disabled="isThinking || isUploadingAttachments"
placeholder="粘贴附件 URL(http/https)"
class="flex-1 rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary placeholder-slate-400 focus:outline-none focus:ring-0"
@keydown.enter.prevent="addRemoteUrlAttachment"
/>
<button
type="button"
:disabled="isThinking || isUploadingAttachments"
@click="addRemoteUrlAttachment"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="添加"
>
<Check class="h-4 w-4" />
</button>
<button
type="button"
:disabled="isThinking || isUploadingAttachments"
@click="closeAttachmentMenu"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="取消"
>
<X class="h-4 w-4" />
</button>
</div>
</div>
</div>
</div>
<div class="relative" ref="kbMenuRef"> <div class="relative" ref="kbMenuRef">
<button <button
@click="showKbDropdown = !showKbDropdown" @click="showKbDropdown = !showKbDropdown"
@@ -2861,13 +3350,14 @@ const showChatRating = ref(false);
</div> </div>
<button <button
@click="handleSend" @click="handleSend"
:disabled="!input.trim() || isThinking" :disabled="!input.trim() || isThinking || isUploadingAttachments"
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50" class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
:class="!input.trim() || isThinking :class="!input.trim() || isThinking || isUploadingAttachments
? 'border-default bg-slate-100 text-muted' ? 'border-default bg-slate-100 text-muted'
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'" : 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
> >
<Send class="h-4 w-4" /> <Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
<Send v-else class="h-4 w-4" />
</button> </button>
</div> </div>
</div> </div>