diff --git a/.env.dev b/.env.dev index 5ac490a6..d4990ec8 100644 --- a/.env.dev +++ b/.env.dev @@ -48,9 +48,10 @@ GUNICORN_WORKERS=10 # MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO) # 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000 # 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致 -MINIO_ENDPOINT=host.docker.internal:9000 +MINIO_ENDPOINT=127.0.0.1:9000 MINIO_BUCKET=image-hosting-service MINIO_ACCESS_KEY=minio_testing_admin MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx MINIO_SECURE=false -MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 +MINIO_PUBLIC_BASE_URL=http://127.0.0.1:9000 +#MINIO_PUBLIC_BASE_URL=http://192.168.1.100/HX工作目录/0602/hxops/backend/data diff --git a/.env.shared b/.env.shared index a1620261..cf21c3e2 100644 --- a/.env.shared +++ b/.env.shared @@ -68,6 +68,8 @@ DIFY_API_BASE=https://api.dify.ai/v1 GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu GJL_API_BASE=https://api.siliconflow.cn/v1 GJL_MODEL=deepseek-ai/DeepSeek-V3 +# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR +ASR_MODEL=FunAudioLLM/SenseVoiceSmall # HR SQL Server Configuration HR_SQLSERVER_HOST=192.168.100.191 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index f7762e24..0f67bc06 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -56,6 +56,7 @@ def create_app(config_name='default'): from app.api.schedule_admin import schedule_admin_bp from app.api.workspace_schedule import workspace_schedule_bp from app.api.internal_jobs import internal_jobs_bp + from app.api.speech import speech_bp # 聊天相关接口 app.register_blueprint(chat_bp, url_prefix='/api/chat') @@ -72,6 +73,7 @@ def create_app(config_name='default'): app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') + app.register_blueprint(speech_bp, url_prefix='/api/speech') # Eagerly load persisted runtime settings so the very first request after # a worker boot already sees the admin-saved configuration (otherwise the diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index be75e3ab..7bb86df6 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -5,7 +5,8 @@ backend/app/api/admin.py 逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用 """ from flask import Blueprint, request, jsonify, current_app -from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit +from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide +from app.services.minio_service import minio_service from app.decorators import require_admin from app.config import Config from app import db @@ -154,19 +155,84 @@ def debug_wecom_user_by_code(): payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator) return jsonify(payload) +def _compute_dashboard_summary(): + """ + 聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。 + + 返回字段: + - agent_count: 启用中的 Agent 数量 + - user_count: 用户总数 + - total_conversations: 对话日志总数 + - avg_score: 反馈平均分(保留 1 位小数) + """ + total_users = db.session.query(func.count(User.id)).scalar() or 0 + active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0 + total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0 + avg_score = db.session.query(func.avg(Feedback.score)).scalar() + avg_score = round(float(avg_score), 1) if avg_score else 0.0 + return { + 'agent_count': active_agents, + 'user_count': total_users, + 'total_conversations': total_conversations, + 'avg_score': avg_score, + } + +def _compute_dashboard_badges(): + """ + 聚合侧栏角标所需的待办数量(仅 COUNT,不拉 users / permission_requests 全表)。 + + 返回字段: + - pending_approvals: status=pending 的注册用户数量(「用户审批」角标) + - pending_requests: status=pending 的权限申请数量(「权限申请」角标) + """ + pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0 + pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0 + return { + 'pending_approvals': pending_approvals, + 'pending_requests': pending_requests, + } + +@admin_bp.route('/dashboard/summary', methods=['GET']) +@require_admin +def dashboard_summary(): + """ + 管理后台仪表盘概览(供 Dashboard 页单次请求)。 + + GET /api/admin/dashboard/summary + 响应示例:{"agent_count": 5, "user_count": 120, "total_conversations": 3000, "avg_score": 4.2} + """ + return jsonify(_compute_dashboard_summary()) + +@admin_bp.route('/dashboard/badges', methods=['GET']) +@require_admin +def dashboard_badges(): + """ + 管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。 + + GET /api/admin/dashboard/badges + 响应示例:{"pending_approvals": 2, "pending_requests": 5} + """ + return jsonify(_compute_dashboard_badges()) + @admin_bp.route('/dashboard', methods=['GET']) @require_admin def dashboard_stats(): """ - Dashboard statistics + 仪表盘统计(遗留接口,字段名与早期前端兼容;新代码请用 /dashboard/summary 与 /dashboard/badges)。 + + GET /api/admin/dashboard + 响应含 summary 四指标 + pending_approvals / pending_requests。 """ - total_users = db.session.query(func.count(User.id)).scalar() - active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() - total_conversations = db.session.query(func.count(ChatLog.id)).scalar() - avg_score = db.session.query(func.avg(Feedback.score)).scalar() - avg_score = float(avg_score) if avg_score else 0.0 - pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() - return jsonify({'total_users': total_users, 'active_agents': active_agents, 'total_conversations': total_conversations, 'avg_score': round(avg_score, 1), 'pending_approvals': pending_approvals}) + summary = _compute_dashboard_summary() + badges = _compute_dashboard_badges() + return jsonify({ + 'total_users': summary['user_count'], + 'active_agents': summary['agent_count'], + 'total_conversations': summary['total_conversations'], + 'avg_score': summary['avg_score'], + 'pending_approvals': badges['pending_approvals'], + 'pending_requests': badges['pending_requests'], + }) @admin_bp.route('/departments', methods=['GET']) @require_admin @@ -782,6 +848,105 @@ def list_wecom_bindings(): users = query.order_by(User.id.asc()).all() return jsonify([{'id': u.id, 'username': u.username, 'real_name': u.real_name, 'email': u.email, 'role': u.role, 'status': u.status, 'wecom_userid': u.wecom_userid, 'wecom_unionid': u.wecom_unionid, 'bound': bool(u.wecom_userid)} for u in users]) +@admin_bp.route('/guides/upload', methods=['POST']) +@require_admin +def upload_guide(): + if 'file' not in request.files: + raise ValidationError('No file part') + file = request.files['file'] + if file.filename == '': + raise ValidationError('No selected file') + + content_type = file.content_type + file_size = len(file.read()) + file.seek(0) + + try: + object_name = minio_service.upload_file(file, file.filename, content_type, file_size) + return jsonify({ + 'file_path': object_name, + 'file_name': file.filename, + 'file_size': file_size, + 'file_type': 'video' if content_type.startswith('video') else 'pdf' if 'pdf' in content_type else 'image' + }) + except Exception as e: + import traceback + traceback.print_exc() + raise AppError(f"Upload failed: {str(e)}") + +@admin_bp.route('/guides', methods=['POST']) +@require_admin +def create_guide(): + data = request.json + guide = AgentGuide( + agent_id=data['agent_id'], + file_name=data['file_name'], + file_type=data['file_type'], + file_path=data['file_path'], + file_size=data.get('file_size'), + remark=data.get('remark'), + sort_order=data.get('sort_order', 0), + status=data.get('status', 1), + created_by=_get_auth_user().id + ) + db.session.add(guide) + db.session.commit() + return jsonify({'id': guide.id}) + +@admin_bp.route('/guides', methods=['GET']) +@require_admin +def list_guides(): + agent_id = request.args.get('agent_id') + query = db.session.query(AgentGuide) + if agent_id: + query = query.filter_by(agent_id=agent_id) + guides = query.order_by(AgentGuide.sort_order).all() + + result = [] + for g in guides: + result.append({ + 'id': g.id, + 'agent_id': g.agent_id, + 'file_name': g.file_name, + 'file_type': g.file_type, + 'file_path': g.file_path, + 'file_url': minio_service.get_public_url(g.file_path), + 'file_size': g.file_size, + 'remark': g.remark, + 'sort_order': g.sort_order, + 'status': g.status, + 'created_at': g.created_at.isoformat() + }) + return jsonify(result) + +@admin_bp.route('/guides/', methods=['PUT']) +@require_admin +def update_guide(id): + guide = db.session.query(AgentGuide).get(id) + if not guide: + raise NotFoundError('Guide not found') + + data = request.json + if 'file_name' in data: guide.file_name = data['file_name'] + if 'remark' in data: guide.remark = data['remark'] + if 'sort_order' in data: guide.sort_order = data['sort_order'] + if 'status' in data: guide.status = data['status'] + + db.session.commit() + return jsonify({'success': True}) + +@admin_bp.route('/guides/', methods=['DELETE']) +@require_admin +def delete_guide(id): + guide = db.session.query(AgentGuide).get(id) + if not guide: + raise NotFoundError('Guide not found') + + minio_service.delete_file(guide.file_path) + db.session.delete(guide) + db.session.commit() + return jsonify({'success': True}) + @admin_bp.route('/wecom/bind', methods=['POST']) @require_admin def bind_wecom_user(): diff --git a/backend/app/api/agents.py b/backend/app/api/agents.py index 650e1a96..d9a1633f 100644 --- a/backend/app/api/agents.py +++ b/backend/app/api/agents.py @@ -4,11 +4,13 @@ backend/app/api/agents.py 引用文件:flask, models, decorators 逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合 """ -from flask import Blueprint, jsonify +import os +from flask import Blueprint, jsonify, send_from_directory from app import db from app.decorators import _get_current_user # 内部工具函数 -from app.models import Agent, User +from app.models import Agent, User, AgentGuide +from app.services.minio_service import minio_service # 定义 Blueprint,将在应用工厂中注册为 /api/agents agents_bp = Blueprint('agents', __name__) @@ -58,6 +60,41 @@ def list_user_agents(): # 序列化为前端所需字段 return jsonify([_serialize_agent_row(row) for row in agent_rows]) +@agents_bp.route('//guides', methods=['GET']) +def list_agent_guides(agent_id): + """ + 获取指定应用的新手指南列表 (需登录) + 用途:客户端 Chat 界面点击新手指南 + """ + _get_current_user() # 确保已登录 + + if agent_id == 0: + generic_agent = db.session.query(Agent).filter_by(name='通用入口').first() + if generic_agent: + agent_id = generic_agent.id + else: + return jsonify([]) + + guides = ( + db.session.query(AgentGuide) + .filter_by(agent_id=agent_id, status=1) + .order_by(AgentGuide.sort_order.asc(), AgentGuide.created_at.desc()) + .all() + ) + + result = [] + for g in guides: + result.append({ + 'id': g.id, + 'file_name': g.file_name, + 'file_type': g.file_type, + 'file_url': minio_service.get_public_url(g.file_path), + 'file_size': g.file_size, + 'remark': g.remark, + 'updated_at': g.updated_at.isoformat() + }) + return jsonify(result) + @agents_bp.route('/public', methods=['GET']) def list_public_agents(): """ @@ -73,4 +110,9 @@ def list_public_agents(): ) return jsonify([_serialize_agent_row(row) for row in agent_rows]) +# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口 +@agents_bp.route('/guides/files/', methods=['GET']) +def serve_guide_file(filename): + return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename) + diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 8e969446..33a8c3a2 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -246,10 +246,13 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first() if log and log.retriever_resources: for r in log.retriever_resources: + if not isinstance(r, dict): + continue source_url = str(r.get('source_download_url') or '') if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]): - dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip() - remote_document_id = remote_document_id or str(r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '').strip() + resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r) + dataset_id = dataset_id or str(resolved_dataset_id or '').strip() + remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip() if dataset_id and remote_document_id: break except Exception as e: @@ -300,12 +303,26 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower() if resp.status_code == 401: return True + if resp.status_code in (403, 404) and 'token=' in file_url: + return True if ctype == 'application/json': body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower() if 'unauthorized' in body or '"error"' in body: return True return False - if base_url and file_url.startswith(base_url) and ('token=' in file_url): + + def _retry_with_refreshed_url(raw_url: str): + refreshed_url = _resolve_latest_integration_url(raw_url) + if not refreshed_url or refreshed_url == raw_url: + return None, raw_url + retry_headers = _build_headers(refreshed_url) + try: + return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url + except requests.RequestException as e: + current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e) + return None, refreshed_url + + if 'token=' in file_url: try: parsed = urlparse(file_url) qs = parse_qs(parsed.query) @@ -327,18 +344,20 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * except requests.RequestException as e: current_app.logger.warning('[file-preview] upstream request failed: %s', e) return (None, None, ('failed to fetch source file', 502)) - if base_url and file_url.startswith(base_url) and ('token=' in file_url) and _should_refresh_from_response(upstream): - refreshed_url = _resolve_latest_integration_url(file_url) - if refreshed_url != file_url: - headers = _build_headers(refreshed_url) - try: - upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20)) - file_url = refreshed_url - except requests.RequestException as e: - current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e) - return (None, None, ('failed to fetch source file', 502)) + if 'token=' in file_url and _should_refresh_from_response(upstream): + refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) + if refreshed_upstream is not None: + upstream = refreshed_upstream + file_url = refreshed_url if upstream.status_code != 200: + if 'token=' in file_url: + refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) + if refreshed_upstream is not None: + upstream = refreshed_upstream + file_url = refreshed_url current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}") + if upstream.status_code == 404: + return None, None, ('source file not found', 404) return None, None, (f'upstream returned status {upstream.status_code}', 502) content = upstream.content or b'' @@ -1411,12 +1430,6 @@ def resolve_source_file(): source_ext = str(payload.get('source_ext') or '').strip().lower() source_download_url = payload.get('source_download_url') - if source_ext in {'txt', 'md', 'markdown', 'csv', 'vtt', 'properties', 'html', 'htm'}: - current_agent = getattr(g, 'current_agent', None) - source_download_url = ( - f"{request.host_url.rstrip('/')}/api/chat/source-file-text" - f"?agent_id={getattr(current_agent, 'id', '')}&dataset_id={dataset_id}&remote_document_id={remote_document_id}" - ) return jsonify({ 'dataset_id': dataset_id, @@ -1649,7 +1662,6 @@ def preview_file_raw(): # 避免在服务端走旧版转换链路导致长时间卡住。 needs_pdf_conversion = ( request.args.get('download') != '1' - and original_ext in ('doc', 'ppt', 'pptx') and ext in ('doc', 'ppt', 'pptx') ) if needs_pdf_conversion: diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py index 3bfee934..dcd3c260 100644 --- a/backend/app/api/integration.py +++ b/backend/app/api/integration.py @@ -10,8 +10,98 @@ from sqlalchemy.orm import joinedload from app import db from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status +from app.services.integration_api import IntegrationApiService integration_bp = Blueprint('integration', __name__) + +def _integration_token_secret() -> str: + configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip() + return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip() + + +def _decode_integration_token(token: str | None) -> dict | None: + normalized_token = str(token or '').strip() + if not normalized_token: + return None + try: + import jwt + payload = jwt.decode( + normalized_token, + _integration_token_secret(), + algorithms=['HS256'], + ) + return payload if isinstance(payload, dict) else None + except Exception as e: + current_app.logger.warning(f"Integration API token validation failed: {e}") + return None + + +def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str: + base_url = _integration_base_url() + url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}' + if version_id is not None: + url += f'&version_id={version_id}' + return url + + +def _version_query(): + return ( + db.session.query(KbDocumentVersion) + .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) + .filter(KbDocument.is_deleted.is_(False)) + ) + + +def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]: + requested_version_id = request.args.get('version_id', type=int) + token_payload = _decode_integration_token(request.args.get('token')) + if isinstance(token_payload, dict): + token_version_id = token_payload.get('version_id') + if token_version_id is not None: + try: + requested_version_id = int(token_version_id) + except (TypeError, ValueError): + current_app.logger.warning( + 'Integration API token carried invalid version_id: %r', + token_version_id, + ) + dataset_id = str(token_payload.get('dataset_id') or '').strip() + remote_document_id = str(token_payload.get('remote_document_id') or '').strip() + if dataset_id and remote_document_id: + record = ( + db.session.query(KbDifySyncRecord) + .join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id) + .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) + .options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document)) + .filter( + KbDocument.is_deleted.is_(False), + KbDocument.id == file_id, + KbDifySyncRecord.dataset_id == dataset_id, + KbDifySyncRecord.remote_document_id == remote_document_id, + ) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + .first() + ) + if record and record.document_version and record.document_version.document: + return record.document_version, record.document_version.document + + if requested_version_id is not None: + version = ( + _version_query() + .filter( + KbDocumentVersion.id == requested_version_id, + KbDocumentVersion.document_id == file_id, + ) + .first() + ) + if version: + return version, version.document + + document = _document_query().filter(KbDocument.id == file_id).first() + if not document: + return None, None + return _current_version(document), document + def _require_integration_key(): configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip() incoming = str(request.headers.get('X-Integration-Key') or '').strip() @@ -24,25 +114,38 @@ def _require_integration_key(): return None token = request.args.get('token') - if token: - try: - import jwt - secret = configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip() - jwt.decode(token, secret, algorithms=['HS256']) - return None - except Exception as e: - current_app.logger.warning(f"Integration API token validation failed: {e}") - pass + if token and _decode_integration_token(token): + return None raise UnauthorizedError('Unauthorized') def _integration_base_url() -> str: + request_origin = IntegrationApiService._request_origin_url() + if request_origin: + return request_origin explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/') if explicit: return explicit return request.host_url.rstrip('/') +def _kb_storage_root() -> Path: + root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve() + root.mkdir(parents=True, exist_ok=True) + return root + +def _resolve_storage_path(path_value: str | None) -> Path | None: + if not path_value: + return None + raw_path = Path(str(path_value)) + candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve() + root = _kb_storage_root() + try: + candidate.relative_to(root) + except ValueError: + return None + return candidate + def _current_version(document: KbDocument) -> KbDocumentVersion | None: versions = list(getattr(document, 'versions', []) or []) if not versions: @@ -57,9 +160,8 @@ def _serialize_integration_document(document: KbDocument, *, version: KbDocument if not version: abort(404, description='No current version found.') sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None)) - base_url = _integration_base_url() - source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source' - markdown_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=md' if version.cleaned_file_path or version.cleaned_preview_path else None + source_download_url = _build_download_url(document.id, kind='source', version_id=version.id) + markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}} def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict: @@ -86,15 +188,16 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]: if kind == 'source': - path = Path(version.source_file_path) + path = _resolve_storage_path(version.source_file_path) + if path is None: + raise NotFoundError('File not found on disk.') filename = version.source_file_name or f'document-{version.document_id}' return (path, filename) - preferred = version.cleaned_file_path or version.cleaned_preview_path + preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path) if not preferred: abort(409, description='Markdown not ready.') - path = Path(preferred) filename = f'document-{version.document_id}-v{version.version_no}.md' - return (path, filename) + return (preferred, filename) @integration_bp.before_request def _verify_integration_access(): @@ -189,13 +292,12 @@ def resolve_files_by_dify(): @integration_bp.route('/files//download', methods=['GET']) def download_file(file_id: int): kind = str(request.args.get('kind') or 'md').strip().lower() - document = _document_query().filter(KbDocument.id == file_id).first() + version, document = _resolve_requested_version(file_id) if not document: raise NotFoundError('Document not found.') - version = _current_version(document) if not version: raise NotFoundError('No version found.') path, filename = _resolve_download_path(version, kind) if not path.exists(): raise NotFoundError('File not found on disk.') - return send_file(path, as_attachment=True, download_name=filename) \ No newline at end of file + return send_file(path, as_attachment=True, download_name=filename) diff --git a/backend/app/api/knowledge_base.py b/backend/app/api/knowledge_base.py index d0479035..450fd790 100644 --- a/backend/app/api/knowledge_base.py +++ b/backend/app/api/knowledge_base.py @@ -26,12 +26,9 @@ def _safe_upload_filename(raw_filename: str | None) -> str: original_name = Path(raw_filename or '').name.strip() if not original_name: return 'uploaded_file' - original_path = Path(original_name) - safe_stem = secure_filename(original_path.stem) - suffix = original_path.suffix.lower() - if not safe_stem: - safe_stem = 'uploaded_file' - return f'{safe_stem}{suffix}' + import re + safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name) + return safe_name or 'uploaded_file' def _require_user(): user = get_current_user() diff --git a/backend/app/api/speech.py b/backend/app/api/speech.py new file mode 100644 index 00000000..95e9d0d2 --- /dev/null +++ b/backend/app/api/speech.py @@ -0,0 +1,40 @@ +""" +Speech transcription API — forwards audio to SiliconFlow ASR. +""" +from flask import Blueprint, jsonify, request + +from app.auth_jwt import get_current_user +from app.errors import UnauthorizedError, ValidationError, ServiceUnavailableError +from app.services.speech_asr import SpeechAsrService + +speech_bp = Blueprint('speech', __name__) + + +@speech_bp.route('/transcribe', methods=['POST']) +def transcribe_audio(): + user = get_current_user() + if not user: + raise UnauthorizedError('Unauthorized') + + uploaded = request.files.get('audio') or request.files.get('file') + if not uploaded or not uploaded.filename: + raise ValidationError('audio file is required') + + audio_bytes = uploaded.read() + filename = uploaded.filename or 'recording.webm' + content_type = uploaded.content_type or '' + + try: + SpeechAsrService.validate_upload(filename, len(audio_bytes)) + except ValueError as exc: + raise ValidationError(str(exc)) from exc + + try: + text, model = SpeechAsrService.transcribe(audio_bytes, filename, content_type) + except RuntimeError as exc: + raise ServiceUnavailableError(str(exc)) from exc + + return jsonify({ + 'text': text, + 'model': model, + }) diff --git a/backend/app/config.py b/backend/app/config.py index e4bde29b..5d1921de 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -160,6 +160,14 @@ class Config: SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true' INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052') + # MinIO 配置 + MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000') + MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin') + MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin') + MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true' + MINIO_BUCKET_NAME = os.getenv('MINIO_BUCKET_NAME', 'agent-guides') + MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000') + class DevelopmentConfig(Config): DEBUG = True @@ -180,9 +188,11 @@ class TestingConfig(Config): config = { + 'dev': DevelopmentConfig, 'development': DevelopmentConfig, 'test': TestingConfig, 'testing': TestingConfig, # alias for create_app('testing') in pytest + 'prod': ProductionConfig, 'production': ProductionConfig, 'default': DevelopmentConfig, } diff --git a/backend/app/models.py b/backend/app/models.py index 6f8ca90c..be24f758 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -679,3 +679,26 @@ class ScheduleRun(Base): task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id]) +class AgentGuide(Base): + """ + 平台应用新手指南表 + 用途:存储 Agent 的新手指南文件信息 (如视频、PDF) + """ + __tablename__ = 'agent_guides' + + id: Mapped[int] = mapped_column(primary_key=True) + agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True) + file_name: Mapped[str] = mapped_column(String(255), nullable=False) + file_type: Mapped[str] = mapped_column(String(50), nullable=False) # video, pdf, image + file_path: Mapped[str] = mapped_column(String(500), nullable=False) + file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + sort_order: Mapped[int] = mapped_column(Integer, default=0) + status: Mapped[int] = mapped_column(Integer, default=1) # 1: 启用, 0: 禁用 + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[agent_id]) + + diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 19f30dd4..a9b759ce 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -867,22 +867,23 @@ class DifyService: remote_document_id = ( resource.get('remote_document_id') or resource.get('dify_document_id') - or resource.get('document_id') + or resource.get('source_document_id') or resource.get('doc_id') or metadata.get('remote_document_id') or metadata.get('dify_document_id') - or metadata.get('document_id') + or metadata.get('source_document_id') or metadata.get('doc_id') or DifyService._find_first_by_keys( resource, [ 'remote_document_id', 'dify_document_id', - 'document_id', - 'doc_id', 'source_document_id', + 'doc_id', ], ) + or resource.get('document_id') + or metadata.get('document_id') ) return dataset_id, remote_document_id diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py index 3227bc39..ce51e8dd 100644 --- a/backend/app/services/integration_api.py +++ b/backend/app/services/integration_api.py @@ -14,6 +14,28 @@ from app.config import Config class IntegrationApiService: _cache: Dict[Tuple[str, str], Dict[str, Any]] = {} + @staticmethod + def _request_origin_url() -> str: + if not has_request_context(): + return "" + + forwarded_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip() + forwarded_host = (request.headers.get("X-Forwarded-Host") or "").split(",")[0].strip() + if forwarded_proto and forwarded_host: + return f"{forwarded_proto}://{forwarded_host}".rstrip("/") + + origin = str(request.headers.get("Origin") or "").strip().rstrip("/") + if origin: + return origin + + referer = str(request.headers.get("Referer") or "").strip() + if referer: + parsed = urlparse(referer) + if parsed.scheme and parsed.netloc: + return f"{parsed.scheme}://{parsed.netloc}".rstrip("/") + + return request.host_url.rstrip("/") + @staticmethod def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]: """ @@ -152,6 +174,9 @@ class IntegrationApiService: return configured if mode != "external": + request_origin = IntegrationApiService._request_origin_url() + if request_origin: + return request_origin if public_base: return public_base if has_request_context(): @@ -203,13 +228,19 @@ class IntegrationApiService: from app import db from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument + normalized_dataset_id = str(dataset_id or '').strip() + normalized_remote_document_id = str(remote_document_id or '').strip() + if not normalized_dataset_id or not normalized_remote_document_id: + return None + record = ( db.session.query(KbDifySyncRecord) .join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id) .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) .filter( KbDocument.is_deleted.is_(False), - KbDifySyncRecord.remote_document_id == remote_document_id, + KbDifySyncRecord.dataset_id == normalized_dataset_id, + KbDifySyncRecord.remote_document_id == normalized_remote_document_id, ) .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) .first() @@ -220,13 +251,15 @@ class IntegrationApiService: version = record.document_version document = version.document - explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/') - if explicit: - base_url = explicit - elif has_request_context(): - base_url = request.host_url.rstrip('/') - else: - base_url = '' + base_url = IntegrationApiService._request_origin_url() + if not base_url: + explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/') + if explicit: + base_url = explicit + elif has_request_context(): + base_url = request.host_url.rstrip('/') + else: + base_url = '' import time import jwt @@ -236,13 +269,17 @@ class IntegrationApiService: secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip() exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens payload = { - 'dataset_id': 'local', - 'remote_document_id': remote_document_id, + 'dataset_id': normalized_dataset_id, + 'remote_document_id': normalized_remote_document_id, + 'version_id': version.id, 'exp': exp } token = jwt.encode(payload, secret, algorithm='HS256') - source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source&token={token}' + source_download_url = ( + f'{base_url}/api/integration/files/{document.id}/download' + f'?kind=source&version_id={version.id}&token={token}' + ) return { "source_download_url": source_download_url, @@ -266,7 +303,7 @@ class IntegrationApiService: base_url = IntegrationApiService.get_base_url() api_key = IntegrationApiService.get_api_key() if not base_url or not api_key: - return None + return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id) url = f"{base_url}/api/integration/dify-file" headers = {"X-Integration-Key": api_key} diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py index 36285771..e28f217a 100644 --- a/backend/app/services/knowledge_cleaning/dify_sync_service.py +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -177,6 +177,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | remote_document_id = None remote_document_name = None + upload_name = version.source_file_name or document.title if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash: try: payload = service.get_document( @@ -184,23 +185,23 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | document_id=existing_record.remote_document_id, ) remote_document_id = payload.get('id') or existing_record.remote_document_id - remote_document_name = payload.get('name') or existing_record.remote_document_name or document.title + remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name except KbDifySyncError as exc: if not _is_remote_document_missing(str(exc)): raise payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name elif existing_record and existing_record.dataset_id == dataset_id: try: payload = service.update_document_by_text( dataset_id=dataset_id, document_id=existing_record.remote_document_id, - name=document.title, + name=upload_name, text=text, ) except KbDifySyncError as exc: @@ -208,19 +209,19 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | raise payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name else: payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name if not remote_document_id: raise KbDifySyncError('Dify 未返回远端文档 ID') diff --git a/backend/app/services/minio_service.py b/backend/app/services/minio_service.py new file mode 100644 index 00000000..68ef5961 --- /dev/null +++ b/backend/app/services/minio_service.py @@ -0,0 +1,97 @@ +import os +import uuid +from typing import BinaryIO +from minio import Minio +from minio.error import S3Error +from werkzeug.utils import secure_filename +from app.config import config, ACTIVE_ENV_NAME + +cfg = config[ACTIVE_ENV_NAME] + +class MinioService: + def __init__(self): + self.client = Minio( + cfg.MINIO_ENDPOINT, + access_key=cfg.MINIO_ACCESS_KEY, + secret_key=cfg.MINIO_SECRET_KEY, + secure=cfg.MINIO_SECURE, + ) + self.bucket_name = cfg.MINIO_BUCKET_NAME + self._ensure_bucket_exists() + + def _ensure_bucket_exists(self): + try: + if not self.client.bucket_exists(self.bucket_name): + self.client.make_bucket(self.bucket_name) + # Set bucket policy to public read + policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": {"AWS": ["*"]}, + "Action": ["s3:GetObject"], + "Resource": [f"arn:aws:s3:::{self.bucket_name}/*"] + } + ] + } + import json + self.client.set_bucket_policy(self.bucket_name, json.dumps(policy)) + except Exception as e: + # log or print error + print(f"MinIO bucket error (or not reachable): {e}") + + def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str: + """ + Uploads a file to MinIO and returns the generated object name. + """ + # If MinIO is not running, we could fallback to local storage or raise clear error + try: + self._ensure_bucket_exists() + except Exception: + pass + + ext = os.path.splitext(filename)[1] + unique_filename = f"{uuid.uuid4().hex}{ext}" + + try: + self.client.put_object( + bucket_name=self.bucket_name, + object_name=unique_filename, + data=file_stream, + length=file_size, + content_type=content_type + ) + except Exception as e: + # For development, if minio is down, let's mock it so UI can continue + print(f"Warning: Minio upload failed ({e}). Fallback to local storage.") + + # fallback to local storage + os.makedirs('data/agent-guides', exist_ok=True) + local_path = os.path.join('data/agent-guides', unique_filename) + file_stream.seek(0) + with open(local_path, 'wb') as f: + f.write(file_stream.read()) + + return unique_filename + + def get_public_url(self, object_name: str) -> str: + """ + Returns the public URL for the given object name. + """ + if os.path.exists(os.path.join('data/agent-guides', object_name)): + # It's a local fallback file + # the backend needs a static route to serve this, we'll assume /api/agents/guides/files/ + # but since we want it public without auth: + return f"/api/agents/guides/files/{object_name}" + + base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/') + return f"{base_url}/{self.bucket_name}/{object_name}" + + def delete_file(self, object_name: str): + try: + self.client.remove_object(self.bucket_name, object_name) + except S3Error as e: + print(f"Error deleting file from MinIO: {e}") + +minio_service = MinioService() diff --git a/backend/app/services/speech_asr.py b/backend/app/services/speech_asr.py new file mode 100644 index 00000000..750482cc --- /dev/null +++ b/backend/app/services/speech_asr.py @@ -0,0 +1,75 @@ +""" +SiliconFlow ASR service (OpenAI-compatible /v1/audio/transcriptions). +""" +import io +import os +from typing import Tuple + +ALLOWED_AUDIO_EXTENSIONS = frozenset({ + 'webm', 'wav', 'mp3', 'm4a', 'mp4', 'mpeg', 'mpga', 'ogg', +}) +MAX_AUDIO_BYTES = int(os.getenv('ASR_MAX_AUDIO_BYTES', str(10 * 1024 * 1024))) + + +class SpeechAsrService: + @classmethod + def _get_client(cls): + try: + from openai import OpenAI + except ImportError as exc: + raise RuntimeError('OpenAI SDK not installed') from exc + + api_key = (os.getenv('GJL_API_KEY') or '').strip() + base_url = (os.getenv('GJL_API_BASE') or 'https://api.siliconflow.cn/v1').strip() + + if not api_key: + raise RuntimeError('Missing GJL_API_KEY. Configure it in .env to enable speech recognition') + + return OpenAI(api_key=api_key, base_url=base_url) + + @classmethod + def _resolve_model(cls) -> str: + return (os.getenv('ASR_MODEL') or 'FunAudioLLM/SenseVoiceSmall').strip() + + @classmethod + def _normalize_filename(cls, filename: str, content_type: str) -> str: + name = (filename or '').strip() or 'recording.webm' + if '.' not in name: + if 'wav' in content_type: + name = f'{name}.wav' + elif 'mp4' in content_type or 'm4a' in content_type: + name = f'{name}.m4a' + else: + name = f'{name}.webm' + return name + + @classmethod + def validate_upload(cls, filename: str, size: int) -> None: + ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else '' + if ext and ext not in ALLOWED_AUDIO_EXTENSIONS: + raise ValueError(f'Unsupported audio format: .{ext}') + if size <= 0: + raise ValueError('Audio file is empty') + if size > MAX_AUDIO_BYTES: + raise ValueError(f'Audio file exceeds {MAX_AUDIO_BYTES // (1024 * 1024)}MB limit') + + @classmethod + def transcribe(cls, audio_bytes: bytes, filename: str, content_type: str = '') -> Tuple[str, str]: + cls.validate_upload(filename, len(audio_bytes)) + + client = cls._get_client() + model = cls._resolve_model() + safe_name = cls._normalize_filename(filename, content_type) + file_obj = io.BytesIO(audio_bytes) + file_obj.name = safe_name + + try: + result = client.audio.transcriptions.create( + model=model, + file=file_obj, + ) + except Exception as exc: + raise RuntimeError(f'Speech recognition request failed: {exc}') from exc + + text = str(getattr(result, 'text', '') or '').strip() + return text, model diff --git a/backend/migrations/versions/d0e1f2a3b4c5_repair_schema_drift_indexes_and_.py b/backend/migrations/versions/d0e1f2a3b4c5_repair_schema_drift_indexes_and_.py new file mode 100644 index 00000000..42ff33e8 --- /dev/null +++ b/backend/migrations/versions/d0e1f2a3b4c5_repair_schema_drift_indexes_and_.py @@ -0,0 +1,52 @@ +"""repair schema drift indexes and constraints + +Revision ID: d0e1f2a3b4c5 +Revises: c9d8e7f6a5b4 +Create Date: 2026-06-03 12:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd0e1f2a3b4c5' +down_revision = 'c9d8e7f6a5b4' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_index('ix_kb_documents_group_id', 'kb_documents', ['group_id'], unique=False) + op.create_index( + 'ix_kb_document_versions_document_id', + 'kb_document_versions', + ['document_id'], + unique=False, + ) + op.create_index('ix_schedule_tasks_last_run_at', 'schedule_tasks', ['last_run_at'], unique=False) + op.create_index('ix_schedule_tasks_created_at', 'schedule_tasks', ['created_at'], unique=False) + + op.execute("UPDATE schedule_runs SET wecom_notified = false WHERE wecom_notified IS NULL") + op.alter_column( + 'schedule_runs', + 'wecom_notified', + existing_type=sa.Boolean(), + nullable=False, + existing_server_default=sa.text('false'), + ) + + +def downgrade(): + op.alter_column( + 'schedule_runs', + 'wecom_notified', + existing_type=sa.Boolean(), + nullable=True, + existing_server_default=sa.text('false'), + ) + + op.drop_index('ix_schedule_tasks_created_at', table_name='schedule_tasks') + op.drop_index('ix_schedule_tasks_last_run_at', table_name='schedule_tasks') + op.drop_index('ix_kb_document_versions_document_id', table_name='kb_document_versions') + op.drop_index('ix_kb_documents_group_id', table_name='kb_documents') diff --git a/backend/migrations/versions/f6f91cb46944_add_agent_guides_table.py b/backend/migrations/versions/f6f91cb46944_add_agent_guides_table.py new file mode 100644 index 00000000..bed4e28f --- /dev/null +++ b/backend/migrations/versions/f6f91cb46944_add_agent_guides_table.py @@ -0,0 +1,74 @@ +"""add agent_guides table + +Revision ID: f6f91cb46944 +Revises: d0e1f2a3b4c5 +Create Date: 2026-06-04 09:32:18.390108 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f6f91cb46944' +down_revision = 'd0e1f2a3b4c5' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('agent_guides', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('agent_id', sa.Integer(), nullable=False), + sa.Column('file_name', sa.String(length=255), nullable=False), + sa.Column('file_type', sa.String(length=50), nullable=False), + sa.Column('file_path', sa.String(length=500), nullable=False), + sa.Column('file_size', sa.Integer(), nullable=True), + sa.Column('remark', sa.Text(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('status', sa.Integer(), nullable=False), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('agent_guides', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_agent_guides_agent_id'), ['agent_id'], unique=False) + + with op.batch_alter_table('schedule_runs', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_schedule_runs_id')) + + with op.batch_alter_table('schedule_tasks', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_schedule_tasks_id')) + + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('uq_users_wecom_unionid')) + batch_op.drop_index(batch_op.f('uq_users_wecom_userid')) + batch_op.create_unique_constraint(None, ['wecom_unionid']) + batch_op.create_unique_constraint(None, ['wecom_userid']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='unique') + batch_op.drop_constraint(None, type_='unique') + batch_op.create_index(batch_op.f('uq_users_wecom_userid'), ['wecom_userid'], unique=True) + batch_op.create_index(batch_op.f('uq_users_wecom_unionid'), ['wecom_unionid'], unique=True) + + with op.batch_alter_table('schedule_tasks', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_schedule_tasks_id'), ['id'], unique=False) + + with op.batch_alter_table('schedule_runs', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_schedule_runs_id'), ['id'], unique=False) + + with op.batch_alter_table('agent_guides', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_agent_guides_agent_id')) + + op.drop_table('agent_guides') + # ### end Alembic commands ### diff --git a/backend/requirements.txt b/backend/requirements.txt index c6acd8ae..99abc2e2 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -35,4 +35,4 @@ lxml==6.0.2 typer==0.17.4 croniter pyyaml -minio>=7.2.0 +minio==7.2.20 diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 12f576a5..a6ea3a68 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -181,6 +181,22 @@ def test_reports(client, admin_headers): """ Test report endpoints """ + response = client.get('/api/admin/dashboard/summary', headers=admin_headers) + assert response.status_code == 200 + data = response.json + assert set(data.keys()) == {'agent_count', 'user_count', 'total_conversations', 'avg_score'} + assert isinstance(data['agent_count'], int) + assert isinstance(data['user_count'], int) + assert isinstance(data['total_conversations'], int) + assert isinstance(data['avg_score'], (int, float)) + + response = client.get('/api/admin/dashboard/badges', headers=admin_headers) + assert response.status_code == 200 + badges = response.json + assert set(badges.keys()) == {'pending_approvals', 'pending_requests'} + assert isinstance(badges['pending_approvals'], int) + assert isinstance(badges['pending_requests'], int) + response = client.get('/api/admin/reports/usage', headers=admin_headers) assert response.status_code == 200 data = response.json diff --git a/docs/demand.md b/docs/demand.md index eb592514..475bb082 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -336,3 +336,36 @@ 5. 移动端右上角可见个人设置图标按钮 6. 点击右上角按钮可进入个人设置页面 7. PC 端布局与行为无任何变化 + + +--- + +## 15. 平台应用新手指南需求 + +### 15.1 项目背景 + +目前用户在使用部分复杂的 Agent 应用时,由于缺乏直观的操作引导,容易产生困惑。通过在应用内提供视频、PDF 等多媒体说明文档,可以实现“即学即用”,降低用户学习成本。 + +### 15.2 需求目标 + +1. 管理后台支持为不同 Agent 应用上传和管理视频、PDF 等新手指南资料。 +2. 前端聊天界面根据后台配置,动态展示“新手指南”入口。 +3. 用户点击后可直接在系统内预览视频或 PDF 文档。 + +### 15.3 详细需求 + +#### NR-01 管理后台-平台应用说明管理 +- 支持选择系统内已发布的 Agent 应用。 +- 支持上传视频(MP4/WebM)和文档(PDF),上传至 MinIO(mimo)服务。 +- 维护资料信息:名称、备注、状态(启用/禁用)、排序等。 + +#### NR-02 客户端-新手指南入口与展示 +- 在 Chat 对话界面的左上角(应用 Title 旁边),新增【新手指南】按钮。 +- 根据后台接口返回,若存在启用状态的指南,则显示入口,否则隐藏。 +- 点击后弹出预览浮层(Modal/Drawer),支持多文件标签页切换。 +- 弹窗内直接内联播放视频或渲染 PDF(无需下载)。 + +### 15.4 验收标准 +1. 管理员能成功上传并管理应用的指南文件。 +2. 客户端正确根据配置动态展示或隐藏入口。 +3. 客户端能正常播放指南视频和预览 PDF 文档。 diff --git a/docs/frontend_architecture_refactor.md b/docs/frontend_architecture_refactor.md new file mode 100644 index 00000000..f31518f9 --- /dev/null +++ b/docs/frontend_architecture_refactor.md @@ -0,0 +1,453 @@ +# HXOPS 前端重构架构方案 + +> 更新时间:2026-06-02 +> 适用范围:`frontend/` 目录 +> 文档定位:定义推荐的目标架构(Feature-Module + Composables + Pinia),作为后续分阶段重构的基准。 + +--- + +## 1. 架构选型 + +在现有技术栈(Vue 3 + TypeScript + Vite + Vue Router + Vue I18n + TailwindCSS)基础上,采用 **Feature-Module 垂直切分 + Composables 逻辑封装 + Pinia 共享状态** 的组合架构。 + +**选型理由:** + +- 与 Vue 3 Composition API 天然契合,学习成本低 +- 业务域清晰(聊天 / 管理后台 / 知识库 / 认证),适合按 feature 垂直拆分 +- 相比 FSD(Feature-Sliced Design)目录层级更浅,迁移成本可控 +- 相比引入 Element Plus 等 UI 库,可继续沿用现有 Tailwind 设计体系(`tokens.css`、`components-ds.css`) + +**保持不变的技术栈:** + +| 层级 | 选型 | +|------|------| +| 框架 | Vue 3(Composition API + ` + + diff --git a/frontend/src/features/admin/composables/useAdminNavBadges.ts b/frontend/src/features/admin/composables/useAdminNavBadges.ts new file mode 100644 index 00000000..7e9beb7a --- /dev/null +++ b/frontend/src/features/admin/composables/useAdminNavBadges.ts @@ -0,0 +1,12 @@ +/** + * features/admin/composables/useAdminNavBadges.ts + * 暴露角标刷新入口;拉取与缓存放 admin-nav.store(不在此 composable 内 onMounted,避免子页面重复请求)。 + */ +import { useAdminNavStore } from '../stores/admin-nav.store'; + +export function useAdminNavBadges() { + const navStore = useAdminNavStore(); + return { + refreshBadges: () => navStore.refreshBadges(), + }; +} diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts new file mode 100644 index 00000000..027ced55 --- /dev/null +++ b/frontend/src/features/admin/constants/modules.ts @@ -0,0 +1,53 @@ +/** + * features/admin/constants/modules.ts + * 管理后台模块元数据,AdminNav 与子路由共用。 + */ + +import type { AdminModuleId, AdminReportTableId } from '../types/admin.types'; + +export interface AdminModuleMeta { + id: AdminModuleId; + routeName: string; + path: string; + labelKey: string; + configKey: keyof typeof import('@/config').config.admin.modules; +} + +/** 已独立拆分的模块(全部 admin 模块均已拆分) */ +export const STANDALONE_ADMIN_MODULES = new Set([ + 'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'reports', +]); + +export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [ + { id: 'dashboard', routeName: 'AdminDashboard', path: 'dashboard', labelKey: 'admin.nav.dashboard', configKey: 'dashboard' }, + { id: 'approvals', routeName: 'AdminApprovals', path: 'approvals', labelKey: 'admin.nav.approvals', configKey: 'approvals' }, + { id: 'users', routeName: 'AdminUsers', path: 'users', labelKey: 'admin.nav.users', configKey: 'users' }, + { id: 'departments', routeName: 'AdminDepartments', path: 'departments', labelKey: 'admin.nav.departments', configKey: 'departments' }, + { id: 'agents', routeName: 'AdminAgents', path: 'agents', labelKey: 'admin.nav.agents', configKey: 'agents' }, + { id: 'knowledge_base', routeName: 'AdminKnowledgeBase', path: 'knowledge-base', labelKey: 'admin.nav.knowledgeBase', configKey: 'knowledge_base' }, + { id: 'schedules', routeName: 'AdminSchedules', path: 'schedules', labelKey: 'admin.nav.schedules', configKey: 'schedules' }, + { id: 'announcements', routeName: 'AdminAnnouncements', path: 'announcements', labelKey: 'admin.nav.announcements', configKey: 'announcements' }, + { id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' }, + { id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' }, + { id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' }, + { id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' }, + { id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' }, +]; + +export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [ + 'users', + 'agents', + 'chat_logs', + 'permission_requests', + 'general_feedbacks', + 'feedbacks', +]; + +export const LEGACY_MODULE_QUERY_TO_PATH: Record = {}; + +export const adminModulePath = (moduleId: AdminModuleId | string): string => { + if (moduleId === 'reports') return '/admin/reports'; + const meta = ADMIN_MODULE_METAS.find((m) => m.id === moduleId); + if (meta) return `/admin/${meta.path}`; + return `/admin/${LEGACY_MODULE_QUERY_TO_PATH[moduleId] || moduleId}`; +}; diff --git a/frontend/src/features/admin/index.ts b/frontend/src/features/admin/index.ts new file mode 100644 index 00000000..5408d13e --- /dev/null +++ b/frontend/src/features/admin/index.ts @@ -0,0 +1,10 @@ +/** + * features/admin/index.ts + * + * 管理后台 feature 的公共导出入口,便于其他模块按需 import。 + */ + +export { default as AdminLayout } from './views/AdminLayout.vue'; +export { useAdminNavStore } from './stores/admin-nav.store'; +export { adminModulePath, ADMIN_MODULE_METAS } from './constants/modules'; +export type { AdminModuleId } from './types/admin.types'; diff --git a/frontend/src/features/admin/modules/agents/AgentsPage.vue b/frontend/src/features/admin/modules/agents/AgentsPage.vue new file mode 100644 index 00000000..e4c66bdd --- /dev/null +++ b/frontend/src/features/admin/modules/agents/AgentsPage.vue @@ -0,0 +1,253 @@ +/** + * features/admin/modules/agents/AgentsPage.vue + * + * Agent 管理独立页面(Phase 1 首个拆分模块)。 + * 路由:/admin/agents + */ + + + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue new file mode 100644 index 00000000..2b5d3685 --- /dev/null +++ b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue @@ -0,0 +1,94 @@ +/** + * features/admin/modules/agents/components/AgentPermissionModal.vue + * + * 为指定 Agent 批量勾选可访问用户的权限弹窗。 + */ + + + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue new file mode 100644 index 00000000..7ef7d6f4 --- /dev/null +++ b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue @@ -0,0 +1,82 @@ +/** + * features/admin/modules/agents/components/AgentTestModal.vue + * + * Agent 连通性测试弹窗:展示请求 URL、输出信息与分析结果。 + */ + + + + diff --git a/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts new file mode 100644 index 00000000..d96fa326 --- /dev/null +++ b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts @@ -0,0 +1,305 @@ +/** + * features/admin/modules/agents/composables/useAgentsAdmin.ts + * + * Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。 + * 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。 + */ + +import { ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { + createAdminAgent, + deleteAdminAgent, + listAdminAgents, + listAdminUsers, + saveAdminAgentPermissions, + testAdminAgent, + updateAdminAgent, +} from '@/api/admin'; +import { useMessage } from '@/composables/useMessage'; +import type { AdminUserRow } from '@/features/admin/types/admin.types'; +import type { AgentFormState, AgentRow, AgentTestResult } from '@/features/admin/types/agent.types'; +import { createEmptyAgentForm } from '@/features/admin/types/agent.types'; + +export function useAgentsAdmin() { + const { t } = useI18n(); + const msg = useMessage(); + + const agents = ref([]); + const users = ref([]); + const isLoading = ref(true); + const isSaving = ref(false); + const isEditing = ref(false); + const selectedAgentId = ref(null); + const form = ref(createEmptyAgentForm()); + + const showTestModal = ref(false); + const isTesting = ref(false); + const testingAgent = ref(null); + const testResult = ref(null); + + const showPermissionModal = ref(false); + const permissionAgent = ref(null); + const permissionUserIds = ref([]); + + const showDeleteConfirmDialog = ref(false); + const deleteConfirmMessage = ref(''); + let deleteConfirmAction: (() => Promise | void) | null = null; + + const activeUsers = () => users.value.filter((u) => u.status !== 'pending'); + + const loadAgents = async (): Promise => { + try { + agents.value = await listAdminAgents(); + } catch (e) { + console.error('Error loading agents:', e); + agents.value = []; + } + }; + + const loadUsers = async (): Promise => { + try { + users.value = await listAdminUsers(); + } catch (e) { + console.error('Error loading users:', e); + users.value = []; + } + }; + + const loadAll = async (): Promise => { + isLoading.value = true; + await Promise.all([loadAgents(), loadUsers()]); + isLoading.value = false; + }; + + const resetForm = (): void => { + selectedAgentId.value = null; + form.value = createEmptyAgentForm(); + isEditing.value = false; + }; + + const selectAgent = (agent: AgentRow): void => { + selectedAgentId.value = agent.id; + form.value = { + id: agent.id, + name: agent.name, + dify_app_id: agent.dify_app_id, + dify_api_key: agent.dify_api_key || '', + description: agent.description || '', + type: agent.type, + dify_app_type: agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow', + api_base_url: agent.api_base_url || '', + iframe_url: String(agent.extra_config?.iframe_url || ''), + is_active: agent.is_active, + }; + isEditing.value = true; + }; + + const openDeleteConfirm = ( + message: string, + action: () => Promise | void, + ): void => { + deleteConfirmMessage.value = message; + deleteConfirmAction = action; + showDeleteConfirmDialog.value = true; + }; + + const closeDeleteConfirm = (): void => { + showDeleteConfirmDialog.value = false; + deleteConfirmAction = null; + }; + + const confirmDelete = async (): Promise => { + if (!deleteConfirmAction) return; + try { + await deleteConfirmAction(); + } finally { + closeDeleteConfirm(); + } + }; + + const submitAgent = async (): Promise => { + if (!form.value.name) { + msg.warning(t('admin.dept.msg.nameRequired')); + return; + } + + isSaving.value = true; + const extra_config: Record = {}; + if (form.value.type === 'iframe' && form.value.iframe_url) { + extra_config.iframe_url = form.value.iframe_url; + } + if (form.value.type === 'api') { + extra_config.dify_app_type = form.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow'; + } + + try { + const editingId = isEditing.value ? Number(form.value.id) : null; + if (isEditing.value && form.value.id != null) { + const payload: Record = { + name: form.value.name, + dify_app_id: form.value.dify_app_id, + description: form.value.description, + type: form.value.type, + api_base_url: form.value.api_base_url, + extra_config, + is_active: form.value.is_active, + }; + if (form.value.dify_api_key) { + payload.dify_api_key = form.value.dify_api_key; + } + await updateAdminAgent(form.value.id, payload); + } else { + await createAdminAgent({ + name: form.value.name, + dify_app_id: form.value.dify_app_id, + dify_api_key: form.value.dify_api_key, + description: form.value.description, + type: form.value.type, + api_base_url: form.value.api_base_url, + extra_config, + }); + } + + await loadAgents(); + if (editingId) { + const updated = agents.value.find((a) => a.id === editingId); + if (updated) selectAgent(updated); + } else { + resetForm(); + } + } catch (e) { + console.error(e); + msg.error((e as Error).message || t('admin.msg.requestFailed')); + } finally { + isSaving.value = false; + } + }; + + const deleteAgent = async (id: number): Promise => { + openDeleteConfirm(t('admin.agent.confirmDelete'), async () => { + try { + await deleteAdminAgent(id); + await loadAgents(); + if (selectedAgentId.value === id) { + resetForm(); + } + } catch (e) { + console.error(e); + msg.error((e as Error).message || t('admin.msg.requestFailed')); + } + }); + }; + + const openTestModal = (agent: AgentRow): void => { + testingAgent.value = agent; + testResult.value = null; + showTestModal.value = true; + void runAgentTest(agent); + }; + + const runAgentTest = async (agent?: AgentRow): Promise => { + const target = agent || testingAgent.value; + if (!target) return; + isTesting.value = true; + try { + const data = await testAdminAgent(target.id); + testResult.value = { + success: !!data.success, + request_url: data.request_url || '', + output_info: data.output_info || '', + analysis: data.analysis || (data.success ? t('admin.agent.testDone') : t('admin.agent.testFailed')), + http_status: data.http_status, + tested_at: data.tested_at, + }; + + if (data.success) { + const idx = agents.value.findIndex((a) => a.id === target.id); + const row = idx >= 0 ? agents.value[idx] : undefined; + if (row) { + row.is_active = true; + } + if (selectedAgentId.value === target.id) { + form.value.is_active = true; + } + } + } catch (e) { + testResult.value = { + success: false, + request_url: '', + output_info: (e as Error).message || t('admin.agent.networkError'), + analysis: t('admin.agent.testFailedRequestException'), + http_status: 0, + }; + } finally { + isTesting.value = false; + } + }; + + const openPermissionModal = (agent: AgentRow): void => { + permissionAgent.value = agent; + permissionUserIds.value = users.value + .filter((u) => u.agent_ids.includes(agent.id)) + .map((u) => u.id); + showPermissionModal.value = true; + }; + + const togglePermissionUser = (userId: number): void => { + const index = permissionUserIds.value.indexOf(userId); + if (index === -1) { + permissionUserIds.value.push(userId); + } else { + permissionUserIds.value.splice(index, 1); + } + }; + + const savePermissions = async (): Promise => { + if (!permissionAgent.value) return; + isSaving.value = true; + try { + await saveAdminAgentPermissions( + permissionAgent.value.id, + permissionUserIds.value, + ); + await loadUsers(); + showPermissionModal.value = false; + } catch (e) { + console.error(e); + msg.error((e as Error).message || t('admin.msg.failed')); + } finally { + isSaving.value = false; + } + }; + + return { + agents, + users, + activeUsers, + isLoading, + isSaving, + isEditing, + selectedAgentId, + form, + showTestModal, + isTesting, + testingAgent, + testResult, + showPermissionModal, + permissionAgent, + permissionUserIds, + showDeleteConfirmDialog, + deleteConfirmMessage, + loadAll, + resetForm, + selectAgent, + submitAgent, + deleteAgent, + openTestModal, + runAgentTest, + openPermissionModal, + togglePermissionUser, + savePermissions, + closeDeleteConfirm, + confirmDelete, + }; +} diff --git a/frontend/src/features/admin/modules/announcements/AnnouncementsPage.vue b/frontend/src/features/admin/modules/announcements/AnnouncementsPage.vue new file mode 100644 index 00000000..7b28cbbc --- /dev/null +++ b/frontend/src/features/admin/modules/announcements/AnnouncementsPage.vue @@ -0,0 +1,107 @@ +/** + * features/admin/modules/announcements/AnnouncementsPage.vue + * 公告管理独立页面。路由:/admin/announcements + */ + + +