From 5e8ea03b6c262174420932d18e27afcffaa26129 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=9A=E9=80=9A?= Date: Mon, 23 Mar 2026 00:54:14 +0800 Subject: [PATCH] 260323 function add report chat and front --- .gitignore | 4 + backend/app/api/admin.py | 187 ++++ backend/check_chat.py | 25 + backend/fix_agent_permission.py | 129 +++ backend/tests/test_auth_format.py | 80 ++ backend/tests/test_chat_api.py | 209 ++++ frontend/dist/index.html | 4 +- frontend/src/App.vue | 32 +- frontend/src/components/FilePreviewModal.vue | 133 +++ frontend/src/composables/useChat.ts | 146 ++- .../src/composables/useReportLayoutStorage.ts | 44 + frontend/src/config.ts | 2 + frontend/src/i18n.ts | 84 ++ frontend/src/views/AdminView.vue | 980 +++++++++++++++++- frontend/src/views/ChatView.vue | 299 +++++- frontend/src/views/WorkspaceView.vue | 93 +- 16 files changed, 2351 insertions(+), 100 deletions(-) create mode 100644 backend/check_chat.py create mode 100644 backend/fix_agent_permission.py create mode 100644 backend/tests/test_auth_format.py create mode 100644 backend/tests/test_chat_api.py create mode 100644 frontend/src/components/FilePreviewModal.vue create mode 100644 frontend/src/composables/useReportLayoutStorage.ts diff --git a/.gitignore b/.gitignore index 2d300e96..c83263d7 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,7 @@ frontend/.env.*.local # OS .DS_Store Thumbs.db + +/data/ai-platform/hxops/frontend/nginx.conf +/data/ai-platform/hxops/docker-compose.yml +/data/ai-platform/hxops/backend/deploy/gunicorn_config.py \ No newline at end of file diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 09244f7a..b6d8f10c 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -7,11 +7,13 @@ backend/app/api/admin.py from flask import Blueprint, request, jsonify from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig from app.decorators import require_admin +from app.config import Config from app import db from sqlalchemy import func, desc, inspect from datetime import datetime import csv import io +import requests admin_bp = Blueprint('admin', __name__) @@ -165,6 +167,138 @@ def delete_agent(id): return jsonify({'status': 'ok'}) +@admin_bp.route('/agents//test', methods=['POST']) +@require_admin +def test_agent(id): + """ + 测试应用连通性与基础响应质量。 + 返回:请求地址、输出信息、结果分析。 + 若测试通过,则自动将应用状态置为启用。 + """ + agent = db.session.get(Agent, id) + if not agent: + return jsonify({'error': 'Not found'}), 404 + + tested_at = datetime.utcnow().isoformat() + + if agent.type == 'iframe': + iframe_url = (agent.extra_config or {}).get('iframe_url') + if not iframe_url: + return jsonify({ + 'success': False, + 'request_url': '', + 'output_info': 'Missing iframe_url in extra_config.', + 'analysis': '测试失败:未配置 iframe URL。', + 'http_status': 0, + 'tested_at': tested_at + }), 400 + try: + resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True) + success = 200 <= resp.status_code < 400 + if success and not agent.is_active: + agent.is_active = True + db.session.commit() + return jsonify({ + 'success': success, + 'request_url': iframe_url, + 'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}', + 'analysis': '测试通过:iframe 地址可访问。' if success else '测试失败:iframe 地址不可访问或返回异常状态。', + 'http_status': resp.status_code, + 'tested_at': tested_at + }), 200 + except requests.RequestException as e: + return jsonify({ + 'success': False, + 'request_url': iframe_url, + 'output_info': str(e), + 'analysis': '测试失败:请求 iframe 地址异常。', + 'http_status': 0, + 'tested_at': tested_at + }), 200 + + if not agent.dify_api_key: + return jsonify({ + 'success': False, + 'request_url': '', + 'output_info': 'Missing dify_api_key.', + 'analysis': '测试失败:未配置 API Key。', + 'http_status': 0, + 'tested_at': tested_at + }), 400 + + base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/') + if not base_url: + return jsonify({ + 'success': False, + 'request_url': '', + 'output_info': 'Missing api_base_url.', + 'analysis': '测试失败:未配置 API Base URL。', + 'http_status': 0, + 'tested_at': tested_at + }), 400 + + request_url = f'{base_url}/chat-messages' + payload = { + 'inputs': {}, + 'query': '系统连通性测试,请简短回复OK。', + 'response_mode': 'blocking', + 'conversation_id': '', + 'user': 'admin_test' + } + headers = { + 'Authorization': f'Bearer {agent.dify_api_key}', + 'Content-Type': 'application/json' + } + + try: + resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25)) + raw_text = (resp.text or '')[:4000] + output_info = raw_text + success = False + analysis = f'测试失败:HTTP {resp.status_code}。' + + try: + data = resp.json() + answer = data.get('answer') if isinstance(data, dict) else None + if answer: + output_info = str(answer)[:4000] + if resp.ok and isinstance(answer, str) and answer.strip(): + success = True + analysis = '测试通过:接口连通正常,已成功返回回答。' + elif resp.ok: + analysis = '测试未通过:接口可访问,但未返回有效回答。' + else: + message = data.get('message') if isinstance(data, dict) else None + if message: + output_info = str(message)[:4000] + except ValueError: + if resp.ok and raw_text.strip(): + success = True + analysis = '测试通过:接口连通正常,返回了文本内容。' + + if success and not agent.is_active: + agent.is_active = True + db.session.commit() + + return jsonify({ + 'success': success, + 'request_url': request_url, + 'output_info': output_info, + 'analysis': analysis, + 'http_status': resp.status_code, + 'tested_at': tested_at + }), 200 + except requests.RequestException as e: + return jsonify({ + 'success': False, + 'request_url': request_url, + 'output_info': str(e), + 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', + 'http_status': 0, + 'tested_at': tested_at + }), 200 + + @admin_bp.route('/agents//permissions', methods=['POST']) @require_admin def update_agent_permissions(id): @@ -525,3 +659,56 @@ def get_table_data(table): res.append(d) return jsonify(res) + + +@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST']) +@require_admin +def batch_delete_chat_logs(): + """ + Batch delete chat logs by ids. + Only accepts chat_log ids to avoid accidental table-wide deletion. + """ + data = request.get_json() or {} + raw_ids = data.get('ids', []) + if not isinstance(raw_ids, list) or not raw_ids: + return jsonify({'error': 'ids is required'}), 400 + + ids = [] + for v in raw_ids: + try: + ids.append(int(v)) + except (TypeError, ValueError): + continue + + if not ids: + return jsonify({'error': 'No valid ids'}), 400 + + cnt = db.session.query(ChatLog).filter(ChatLog.id.in_(ids)).delete(synchronize_session=False) + db.session.commit() + return jsonify({'deleted_count': cnt}) + + +@admin_bp.route('/database//count', methods=['GET']) +@require_admin +def get_table_count(table): + """ + Return total row count for admin report tables. + """ + model_map = { + 'users': User, + 'agents': Agent, + 'chat_logs': ChatLog, + 'feedbacks': Feedback, + 'permission_requests': PermissionRequest, + 'departments': Department, + 'quick_questions': QuickQuestion, + 'user_homepage_configs': UserHomepageConfig, + 'user_favorite_agents': UserFavoriteAgent, + 'user_default_agents': UserDefaultAgent + } + model = model_map.get(table) + if not model: + return jsonify({'error': 'Invalid table'}), 400 + + total = db.session.query(func.count(model.id)).scalar() + return jsonify({'table': table, 'total': int(total or 0)}) diff --git a/backend/check_chat.py b/backend/check_chat.py new file mode 100644 index 00000000..49f1aec4 --- /dev/null +++ b/backend/check_chat.py @@ -0,0 +1,25 @@ +from app import create_app, db +from app.models import ChatLog, User +from sqlalchemy import func + +app = create_app('development') +with app.app_context(): + print('=== 数据库中的用户 ===') + users = db.session.query(User).all() + for u in users: + print(f'id={u.id}, username={u.username}, role={u.role}') + + print() + print('=== 各用户对 Agent 3 的会话统计 ===') + for uid in [1, 2, 3, 4, 5]: + count = db.session.query(func.count(ChatLog.id)).filter( + ChatLog.user_id == uid, + ChatLog.agent_id == 3 + ).scalar() + print(f'user_id={uid}: {count} logs') + + print() + print('=== ChatLog 样本 (Agent 3) ===') + logs = db.session.query(ChatLog).filter(ChatLog.agent_id == 3).order_by(ChatLog.created_at.desc()).limit(5).all() + for log in logs: + print(f'user_id={log.user_id}, conv_id={log.conversation_id}, query={log.query[:40]}...') \ No newline at end of file diff --git a/backend/fix_agent_permission.py b/backend/fix_agent_permission.py new file mode 100644 index 00000000..f9d6d42e --- /dev/null +++ b/backend/fix_agent_permission.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +""" +fix_agent_permission.py +文件用途:修复 Agent 权限问题 +关键逻辑: + 1. 根据 username 或 user_id 获取用户 + 2. 给用户分配指定的 agent 权限 + 3. 支持批量分配和查看当前权限 +语法实现:使用 SQLAlchemy relationship 操作多对多关联 +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from app import create_app, db +from app.models import User, Agent + + +def grant_agent_permission(username=None, user_id=None, agent_ids=None, grant_all=False): + """ + 给用户分配 Agent 权限 + + 参数: + username: 用户名 + user_id: 用户 ID + agent_ids: 要分配的 Agent ID 列表,如 [1, 2, 3] + grant_all: 是否授予所有 Agent 的权限 + """ + env = os.getenv('FLASK_ENV', 'production') + app = create_app(env) + + with app.app_context(): + user = None + if user_id: + user = User.query.get(int(user_id)) + elif username: + user = User.query.filter_by(username=username).first() + + if not user: + print(f"❌ 用户不存在: username={username}, user_id={user_id}") + return False + + print(f"✅ 找到用户: {user.username} (ID: {user.id}, Role: {user.role})") + + if grant_all: + agents = Agent.query.all() + agent_ids = [a.id for a in agents] + print(f"📋 所有可用 Agent: {agent_ids}") + + if not agent_ids: + print("⚠️ 未指定 agent_ids,使用 --grant-all 授予所有权限") + agents = Agent.query.all() + user.agents = agents + else: + agents = Agent.query.filter(Agent.id.in_(agent_ids)).all() + if not agents: + print(f"❌ 未找到 ID 为 {agent_ids} 的 Agent") + return False + user.agents = agents + + db.session.commit() + print(f"✅ 权限授予成功!用户 {user.username} 现在可以访问 Agent: {[a.id for a in user.agents]}") + return True + + +def list_user_permissions(username=None, user_id=None): + """查看用户的 Agent 权限""" + env = os.getenv('FLASK_ENV', 'production') + app = create_app(env) + + with app.app_context(): + user = None + if user_id: + user = User.query.get(int(user_id)) + elif username: + user = User.query.filter_by(username=username).first() + + if not user: + print(f"❌ 用户不存在: username={username}, user_id={user_id}") + return + + print(f"\n👤 用户: {user.username} (ID: {user.id}, Role: {user.role})") + print(f"📋 当前可访问的 Agent: {[a.id for a in user.agents]}") + print("\n📋 所有 Agent 列表:") + all_agents = Agent.query.all() + for a in all_agents: + has_access = a in user.agents + print(f" [{a.id}] {a.name} - {'✅ 有权限' if has_access else '❌ 无权限'}") + + +def list_all_users(): + """列出所有用户及其权限""" + env = os.getenv('FLASK_ENV', 'production') + app = create_app(env) + + with app.app_context(): + users = User.query.all() + print("\n👥 所有用户列表:") + for u in users: + print(f" [{u.id}] {u.username} (Role: {u.role}) - Agents: {[a.id for a in u.agents]}") + + +if __name__ == '__main__': + import argparse + + parser = argparse.ArgumentParser(description='修复 Agent 权限') + parser.add_argument('--username', '-u', type=str, help='用户名') + parser.add_argument('--user-id', '-i', type=int, help='用户 ID') + parser.add_argument('--agent-ids', '-a', type=int, nargs='+', help='Agent ID 列表,如: 1 2 3') + parser.add_argument('--grant-all', '-g', action='store_true', help='授予所有 Agent 权限') + parser.add_argument('--list', '-l', action='store_true', help='查看用户权限') + parser.add_argument('--list-users', action='store_true', help='列出所有用户') + + args = parser.parse_args() + + if args.list_users: + list_all_users() + elif args.list: + list_user_permissions(username=args.username, user_id=args.user_id) + elif args.grant_all or args.agent_ids: + grant_agent_permission( + username=args.username, + user_id=args.user_id, + agent_ids=args.agent_ids, + grant_all=args.grant_all + ) + else: + parser.print_help() diff --git a/backend/tests/test_auth_format.py b/backend/tests/test_auth_format.py new file mode 100644 index 00000000..85e76d20 --- /dev/null +++ b/backend/tests/test_auth_format.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +""" +测试认证头格式脚本 +用途:测试不同的认证头格式 +""" +import requests +import json + +BASE_URL = "http://127.0.0.1:5002" + +def test_auth_header_format(): + """测试不同的认证头格式""" + + test_cases = [ + { + "name": "格式1: 直接存储用户对象", + "user_data": {"id": 1, "username": "admin", "role": "admin"}, + "description": "localStorage.setItem('hxops_user', JSON.stringify(user))" + }, + { + "name": "格式2: 包装格式 {user, expiry}", + "user_data": {"user": {"id": 1, "username": "admin", "role": "admin"}, "expiry": 123456789}, + "description": "localStorage.setItem('hxops_user', JSON.stringify({user, expiry}))" + }, + ] + + for tc in test_cases: + print("\n" + "=" * 60) + print(f"测试: {tc['name']}") + print(f"描述: {tc['description']}") + print(f"存储数据: {json.dumps(tc['user_data'], ensure_ascii=False)}") + print("-" * 60) + + # 模拟前端 JSON.parse 后的结果 + user = tc['user_data'] + + # 如果是包装格式,提取 user + if 'user' in user: + user = user['user'] + + headers = { + 'X-Username': user.get('username', ''), + 'X-Role': user.get('role', ''), + } + if user.get('id'): + headers['X-User-Id'] = str(user['id']) + + print(f"生成的 Headers: {headers}") + + # 测试 API + url = f"{BASE_URL}/api/chat/sessions?agent_id=3" + response = requests.get(url, headers=headers, timeout=5) + print(f"响应状态: {response.status_code}") + if response.status_code != 200: + print(f"响应内容: {response.text}") + +def test_frontend_storage_format(): + """测试前端实际存储格式""" + print("\n" + "=" * 60) + print("分析前端存储格式") + print("=" * 60) + + # 前端代码分析 + # WorkspaceView.vue 登录成功后: + # localStorage.setItem('hxops_user', JSON.stringify({ user, expiry })); + # 其中 user 是登录 API 返回的对象: {id, username, role} + + print("前端存储逻辑分析:") + print("1. 登录成功后调用: localStorage.setItem('hxops_user', JSON.stringify({ user, expiry }))") + print("2. 其中 user 来自登录 API 返回: {id: 1, username: 'admin', role: 'admin'}") + print("3. 实际存储格式: {\"user\": {\"id\": 1, \"username\": \"admin\", \"role\": \"admin\"}, \"expiry\": 123456789}") + print("\n前端解析逻辑 (useChat.ts):") + print("1. 获取: localStorage.getItem('hxops_user')") + print("2. 解析: JSON.parse(stored)") + print("3. 直接当作用户对象使用,不检查是否有 'user' 键") + print("\n问题: 解析时没有处理包装格式,导致 username/role 为 undefined") + +if __name__ == "__main__": + test_frontend_storage_format() + test_auth_header_format() diff --git a/backend/tests/test_chat_api.py b/backend/tests/test_chat_api.py new file mode 100644 index 00000000..9bdc0929 --- /dev/null +++ b/backend/tests/test_chat_api.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +""" +测试聊天 API 脚本 +用途:验证后端聊天功能是否正常工作 +""" +import requests +import json +import sys + +BASE_URL = "http://127.0.0.1:5002" + +def test_login(): + """测试登录 API""" + print("=" * 50) + print("任务一:测试登录 API") + print("=" * 50) + + url = f"{BASE_URL}/api/user/login" + data = {"username": "admin", "password": "Hxit@54321"} + + print(f"请求 URL: {url}") + print(f"请求参数: {json.dumps(data, ensure_ascii=False)}") + + try: + response = requests.post(url, json=data, timeout=10) + print(f"响应状态码: {response.status_code}") + print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}") + + if response.status_code == 200: + user_data = response.json() + return { + "user_id": user_data.get("id"), + "username": user_data.get("username"), + "role": user_data.get("role") + } + except Exception as e: + print(f"错误: {e}") + + return None + +def test_chat_sessions(user_info, agent_id): + """测试获取聊天会话列表""" + print("\n" + "=" * 50) + print(f"任务二:测试获取聊天会话列表 (agent_id={agent_id})") + print("=" * 50) + + url = f"{BASE_URL}/api/chat/sessions" + headers = { + "X-Username": user_info["username"], + "X-Role": user_info["role"], + "X-User-Id": str(user_info["user_id"]) + } + + params = {"agent_id": agent_id} + + print(f"请求 URL: {url}") + print(f"请求 Headers: {headers}") + print(f"请求参数: {params}") + + try: + response = requests.get(url, headers=headers, params=params, timeout=10) + print(f"响应状态码: {response.status_code}") + print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}") + return response.status_code == 200 + except Exception as e: + print(f"错误: {e}") + return False + +def test_chat_completions(user_info, agent_id): + """测试发送聊天消息""" + print("\n" + "=" * 50) + print(f"任务三:测试发送聊天消息 (agent_id={agent_id})") + print("=" * 50) + + url = f"{BASE_URL}/api/chat/completions" + headers = { + "X-Username": user_info["username"], + "X-Role": user_info["role"], + "X-User-Id": str(user_info["user_id"]), + "Accept": "text/event-stream" + } + data = { + "query": "年假有多少天?", + "agent_id": agent_id, + "conversation_id": "" + } + + print(f"请求 URL: {url}") + print(f"请求 Headers: {headers}") + print(f"请求体: {json.dumps(data, ensure_ascii=False)}") + + full_response = [] + error_count = 0 + message_count = 0 + + try: + response = requests.post(url, headers=headers, json=data, stream=True, timeout=60) + print(f"响应状态码: {response.status_code}") + print("-" * 30) + print("流式响应内容:") + print("-" * 30) + + for line in response.iter_lines(): + if line: + decoded_line = line.decode('utf-8') + print(decoded_line) + full_response.append(decoded_line) + + if decoded_line.startswith('data: '): + try: + json_str = decoded_line[6:] + event_data = json.loads(json_str) + event = event_data.get("event") + + if event == "message": + message_count += 1 + answer = event_data.get("data", {}).get("answer", "") + if answer: + print(f"\n>>> 第 {message_count} 条消息: {answer[:100]}...") + elif event == "error": + error_count += 1 + error_msg = event_data.get("message", "") + print(f"\n!!! 错误事件: {error_msg}") + except json.JSONDecodeError: + pass + + print("-" * 30) + print(f"消息计数: {message_count}") + print(f"错误计数: {error_count}") + + if message_count > 0: + print("\n✅ 聊天功能测试成功!") + return True + elif error_count > 0: + print("\n⚠️ 聊天功能返回了错误,但连接正常") + return True + else: + print("\n❌ 聊天功能测试失败:无消息返回") + return False + + except requests.exceptions.Timeout: + print("❌ 错误: 请求超时") + return False + except requests.exceptions.ConnectionError as e: + print(f"❌ 错误: 连接失败 - {e}") + return False + except Exception as e: + print(f"❌ 错误: {e}") + return False + +def test_without_auth(): + """测试未带认证头的请求""" + print("\n" + "=" * 50) + print("任务四:测试未带认证头的请求") + print("=" * 50) + + url = f"{BASE_URL}/api/chat/sessions?agent_id=3" + + print(f"请求 URL: {url}") + print("请求 Headers: (无)") + + try: + response = requests.get(url, timeout=10) + print(f"响应状态码: {response.status_code}") + print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}") + + if response.status_code == 403: + print("✅ 未带认证头时正确返回 403 权限错误(预期行为)") + return True + except Exception as e: + print(f"错误: {e}") + + return False + +def main(): + print("=" * 60) + print("hxops 聊天功能测试脚本") + print("=" * 60) + + # 测试一:登录 + user_info = test_login() + if not user_info: + print("\n❌ 登录失败,请检查后端服务是否运行") + sys.exit(1) + + print(f"\n✅ 登录成功,用户: {user_info['username']}, 角色: {user_info['role']}") + + # 测试二:获取聊天会话列表 + agent_id = 3 # 人事规章 Agent + if not test_chat_sessions(user_info, agent_id): + print("\n❌ 获取聊天会话列表失败") + sys.exit(1) + + print(f"\n✅ 获取聊天会话列表成功") + + # 测试三:发送聊天消息 + if not test_chat_completions(user_info, agent_id): + print("\n❌ 发送聊天消息失败") + sys.exit(1) + + # 测试四:未带认证头 + test_without_auth() + + print("\n" + "=" * 60) + print("所有测试完成!") + print("=" * 60) + +if __name__ == "__main__": + main() diff --git a/frontend/dist/index.html b/frontend/dist/index.html index 7a9457a7..26c0755d 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -5,8 +5,8 @@ hxai - - + +
diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 213cf9c4..3dfdc39c 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -6,17 +6,29 @@ import { watch, onMounted } from 'vue'; const { locale } = useI18n(); const getAuthHeaders = () => { - const stored = localStorage.getItem('hxops_user'); - if (!stored) return {}; - const user = JSON.parse(stored) as { id?: number; username: string; role: string }; - const headers: Record = { - 'X-Username': user.username, - 'X-Role': user.role, - }; - if (user.id) { - headers['X-User-Id'] = String(user.id); + const candidates = [ + sessionStorage.getItem('hxops_user'), + localStorage.getItem('hxops_user'), + ]; + for (const stored of candidates) { + if (!stored) continue; + try { + const data = JSON.parse(stored) as any; + const user = data.user || data; + if (!user?.username || !user?.role) continue; + const headers: Record = { + 'X-Username': user.username, + 'X-Role': user.role, + }; + if (user.id) { + headers['X-User-Id'] = String(user.id); + } + return headers; + } catch (e) { + continue; + } } - return headers; + return {}; }; const updateLanguagePreference = async (lang: string) => { diff --git a/frontend/src/components/FilePreviewModal.vue b/frontend/src/components/FilePreviewModal.vue new file mode 100644 index 00000000..9d2ab2d7 --- /dev/null +++ b/frontend/src/components/FilePreviewModal.vue @@ -0,0 +1,133 @@ + + + diff --git a/frontend/src/composables/useChat.ts b/frontend/src/composables/useChat.ts index bfe0b512..aef2e831 100644 --- a/frontend/src/composables/useChat.ts +++ b/frontend/src/composables/useChat.ts @@ -7,12 +7,28 @@ */ import { ref } from 'vue'; +interface RetrieverResource { + dataset_name?: string; + document_name?: string; + segment_id?: string; + content?: string; + score?: number; + [key: string]: any; +} + +interface ChatMessage { + role: 'user' | 'assistant'; + content: string; + retriever_resources?: RetrieverResource[]; + attribution_parts?: string[]; +} + export function useChat() { /** * messages: 响应式消息列表,用于 UI 渲染 * 结构: [{ role: 'user'|'assistant', content: string }] */ - const messages = ref([]); + const messages = ref([]); /** * isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用 @@ -26,17 +42,29 @@ export function useChat() { const conversationId = ref(null); const getAuthHeaders = () => { - const stored = localStorage.getItem('hxops_user'); - if (!stored) return {}; - const user = JSON.parse(stored) as { id?: number; username: string; role: string }; - const headers: Record = { - 'X-Username': user.username, - 'X-Role': user.role, - }; - if (user.id) { - headers['X-User-Id'] = String(user.id); + const candidates = [ + sessionStorage.getItem('hxops_user'), + localStorage.getItem('hxops_user'), + ]; + for (const stored of candidates) { + if (!stored) continue; + try { + const data = JSON.parse(stored) as any; + const user = data.user || data; + if (!user?.username || !user?.role) continue; + const headers: Record = { + 'X-Username': user.username, + 'X-Role': user.role, + }; + if (user.id) { + headers['X-User-Id'] = String(user.id); + } + return headers; + } catch (e) { + continue; + } } - return headers; + return {}; }; /** @@ -56,7 +84,12 @@ export function useChat() { // 1. 乐观 UI 更新:立即将用户消息推入列表 messages.value.push({ role: 'user', content: query }); // 创建一个空的 Assistant 消息用于流式追加,并记录其索引 - const botMsgIndex = messages.value.push({ role: 'assistant', content: '' }) - 1; + const botMsgIndex = messages.value.push({ + role: 'assistant', + content: '', + retriever_resources: [], + attribution_parts: [] + }) - 1; isThinking.value = true; @@ -100,14 +133,26 @@ export function useChat() { const data = JSON.parse(line.slice(6)); // 仅处理 message 事件,追加 answer 到当前消息 if (data.event === 'message') { - messages.value[botMsgIndex].content += data.answer; + const botMsg = messages.value[botMsgIndex]; + if (!botMsg) continue; + botMsg.content += data.answer; + applyEventMetadata(botMsg, data); } else if (data.event === 'message_end') { // 记录会话 ID,便于后续发送反馈 if (data.conversation_id) { conversationId.value = data.conversation_id; } + const botMsg = messages.value[botMsgIndex]; + if (!botMsg) continue; + applyEventMetadata(botMsg, data); + } else if (data.event === 'agent_message' || data.event === 'workflow_finished') { + const botMsg = messages.value[botMsgIndex]; + if (!botMsg) continue; + applyEventMetadata(botMsg, data); } else if (data.event === 'error') { - messages.value[botMsgIndex].content += `\n[Error: ${data.message}]`; + const botMsg = messages.value[botMsgIndex]; + if (!botMsg) continue; + botMsg.content += `\n[Error: ${data.message}]`; } } catch (e) { // 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON) @@ -117,7 +162,10 @@ export function useChat() { } } catch (e: any) { console.error(e); - messages.value[botMsgIndex].content += `\n[Error: ${e.message || 'Network Issue'}]`; + const botMsg = messages.value[botMsgIndex]; + if (botMsg) { + botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`; + } } finally { isThinking.value = false; } @@ -125,3 +173,71 @@ export function useChat() { return { messages, isThinking, conversationId, sendMessage }; } + const normalizeResources = (resources: any): RetrieverResource[] => { + if (!resources) return []; + if (Array.isArray(resources)) return resources; + if (Array.isArray(resources.data)) return resources.data; + return []; + }; + + const addRetrieverResources = (msg: ChatMessage, resources: any) => { + const list = normalizeResources(resources); + if (list.length === 0) return; + if (!msg.retriever_resources) msg.retriever_resources = []; + for (const item of list) { + const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`; + const exists = msg.retriever_resources.some( + (r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key + ); + if (!exists) { + msg.retriever_resources.push(item); + } + } + }; + + const addAttributionParts = (msg: ChatMessage, value: any) => { + if (!value) return; + if (!msg.attribution_parts) msg.attribution_parts = []; + + const pushUnique = (text: string) => { + const v = text.trim(); + if (!v) return; + if (!msg.attribution_parts!.includes(v)) { + msg.attribution_parts!.push(v); + } + }; + + if (typeof value === 'string') { + pushUnique(value); + return; + } + + if (Array.isArray(value)) { + for (const item of value) { + if (typeof item === 'string') { + pushUnique(item); + } else if (item && typeof item === 'object') { + pushUnique(item.content || item.text || item.title || JSON.stringify(item)); + } + } + return; + } + + if (typeof value === 'object') { + pushUnique(value.content || value.text || value.title || JSON.stringify(value)); + } + }; + + const applyEventMetadata = (msg: ChatMessage, data: any) => { + const metadata = data?.metadata || {}; + addRetrieverResources(msg, data?.retriever_resources); + addRetrieverResources(msg, metadata?.retriever_resources); + addRetrieverResources(msg, metadata?.retrieverResources); + + addAttributionParts(msg, data?.annotations); + addAttributionParts(msg, data?.annotation_reply); + addAttributionParts(msg, metadata?.annotations); + addAttributionParts(msg, metadata?.annotation_reply); + addAttributionParts(msg, data?.citation); + addAttributionParts(msg, metadata?.citation); + }; diff --git a/frontend/src/composables/useReportLayoutStorage.ts b/frontend/src/composables/useReportLayoutStorage.ts new file mode 100644 index 00000000..ba95b686 --- /dev/null +++ b/frontend/src/composables/useReportLayoutStorage.ts @@ -0,0 +1,44 @@ +/** + * useReportLayoutStorage.ts + * 用途:为报表页面提供统一的布局偏好持久化能力(按用户 + 表名隔离) + */ + +const getCurrentAuthUser = () => { + let stored = localStorage.getItem('hxops_user'); + if (!stored) stored = sessionStorage.getItem('hxops_user'); + if (!stored) return null; + try { + const data = JSON.parse(stored); + return data.user || data; + } catch { + return null; + } +}; + +const getCurrentIdentity = () => { + const user = getCurrentAuthUser(); + return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`; +}; + +const getReportLayoutStorageKey = (table: string) => { + return `hxops_report_layout_v2_${getCurrentIdentity()}_${table}`; +}; + +export const loadReportLayoutPref = (table: string): T | null => { + try { + const raw = localStorage.getItem(getReportLayoutStorageKey(table)); + if (!raw) return null; + return JSON.parse(raw) as T; + } catch { + return null; + } +}; + +export const saveReportLayoutPref = (table: string, payload: unknown) => { + try { + localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload)); + } catch { + // Ignore storage write failure to avoid blocking core report flow. + } +}; + diff --git a/frontend/src/config.ts b/frontend/src/config.ts index 8256a947..e957545d 100644 --- a/frontend/src/config.ts +++ b/frontend/src/config.ts @@ -3,6 +3,7 @@ export const config = { workspace: { enableFeedback: true, modules: { + announcements: true, favorites: true, quickQuestions: true, embedded: true, @@ -16,6 +17,7 @@ export const config = { users: true, departments: true, agents: true, + announcements: true, questions: true, permissions: true, requests: true, diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index fee9ad80..1f57ccb7 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -96,6 +96,10 @@ const messages = { noData: 'No embedded agents configured.', noUrl: 'No iframe URL configured' }, + announcements: { + title: 'Company Announcements', + noData: 'No announcements yet.' + }, favorites: 'Favorites', myAgents: 'My Agents', availableAgents: 'Available Agents', @@ -148,6 +152,7 @@ const messages = { users: 'User Maintenance', departments: 'Departments', agents: 'Agent Management', + announcements: 'Announcements', questions: 'Common Questions', permissions: 'App Permissions', requests: 'Permission Requests', @@ -317,6 +322,22 @@ const messages = { } }, + announcement: { + title: 'Announcement Management', + subtitle: 'Publish company announcements for all users', + add: 'Publish Announcement', + publish: 'Publish', + noData: 'No announcements yet', + confirmDelete: 'Are you sure to delete this announcement?', + fields: { + title: 'Title', + content: 'Content' + }, + msg: { + fillAll: 'Please fill all fields' + } + }, + // Permissions perm: { title: 'App Permissions', @@ -556,6 +577,10 @@ const messages = { noData: '暂无嵌入式应用配置。', noUrl: '未配置 iframe URL' }, + announcements: { + title: '公司公告', + noData: '暂无公告' + }, favorites: '收藏应用', myAgents: '我的应用', availableAgents: '可用应用', @@ -609,6 +634,7 @@ const messages = { users: '用户管理', departments: '部门管理', agents: '应用管理', + announcements: '公告管理', questions: '常用问题', permissions: '应用权限', requests: '权限审批', @@ -778,6 +804,22 @@ const messages = { } }, + announcement: { + title: '公告管理', + subtitle: '面向全体用户发布公司资讯', + add: '发布公告', + publish: '发布', + noData: '暂无公告', + confirmDelete: '确认删除该公告吗?', + fields: { + title: '标题', + content: '内容' + }, + msg: { + fillAll: '请填写所有必填项' + } + }, + // Permissions perm: { title: '应用权限', @@ -999,6 +1041,10 @@ const messages = { noData: '暫無嵌入式應用配置。', noUrl: '未配置 iframe URL' }, + announcements: { + title: '公司公告', + noData: '暫無公告' + }, favorites: '收藏應用', myAgents: '我的應用', availableAgents: '可用應用', @@ -1052,6 +1098,7 @@ const messages = { users: '用戶管理', departments: '部門管理', agents: '應用管理', + announcements: '公告管理', questions: '常用問題', permissions: '應用權限', requests: '權限審批', @@ -1221,6 +1268,22 @@ const messages = { } }, + announcement: { + title: '公告管理', + subtitle: '面向全體用戶發布公司資訊', + add: '發布公告', + publish: '發布', + noData: '暫無公告', + confirmDelete: '確認刪除該公告嗎?', + fields: { + title: '標題', + content: '內容' + }, + msg: { + fillAll: '請填寫所有必填項' + } + }, + // Permissions perm: { title: '應用權限', @@ -1442,6 +1505,10 @@ const messages = { noData: 'ไม่มีตัวแทนแบบฝังที่กำหนดค่าไว้', noUrl: 'ไม่ได้กำหนดค่า URL iframe' }, + announcements: { + title: 'ประกาศบริษัท', + noData: 'ยังไม่มีประกาศ' + }, favorites: 'รายการโปรด', myAgents: 'ตัวแทนของฉัน', availableAgents: 'ตัวแทนที่ใช้ได้', @@ -1495,6 +1562,7 @@ const messages = { users: 'การจัดการผู้ใช้', departments: 'การจัดการแผนก', agents: 'การจัดการตัวแทน', + announcements: 'การจัดการประกาศ', questions: 'คำถามทั่วไป', permissions: 'สิทธิ์แอปพลิเคชัน', requests: 'คำขอสิทธิ์', @@ -1664,6 +1732,22 @@ const messages = { } }, + announcement: { + title: 'การจัดการประกาศ', + subtitle: 'เผยแพร่ข่าวสารบริษัทให้ผู้ใช้ทุกคน', + add: 'เผยแพร่ประกาศ', + publish: 'เผยแพร่', + noData: 'ยังไม่มีประกาศ', + confirmDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบประกาศนี้?', + fields: { + title: 'หัวข้อ', + content: 'เนื้อหา' + }, + msg: { + fillAll: 'กรุณากรอกข้อมูลให้ครบถ้วน' + } + }, + // Permissions perm: { title: 'สิทธิ์แอปพลิเคชัน', diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index e39b8a2e..1b7287b6 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -13,6 +13,7 @@ import { ref, onMounted, watch, computed } from 'vue'; import { useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { config } from '../config'; +import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage'; import { ArrowLeft, Save, @@ -31,7 +32,9 @@ import { Download, UserCog, Building, - MessageCircleQuestion + MessageCircleQuestion, + Settings2, + Megaphone } from 'lucide-vue-next'; import * as XLSX from 'xlsx'; @@ -44,6 +47,7 @@ const sidebarItems = computed(() => { { id: 'users', icon: UserCog, label: t('admin.nav.users') }, { id: 'departments', icon: Building, label: t('admin.nav.departments') }, { id: 'agents', icon: Bot, label: t('admin.nav.agents') }, + { id: 'announcements', icon: Megaphone, label: t('admin.nav.announcements') }, { id: 'questions', icon: MessageCircleQuestion, label: t('admin.nav.questions') }, { id: 'permissions', icon: Users, label: t('admin.nav.permissions') }, { id: 'requests', icon: ShieldCheck, label: t('admin.nav.requests'), badge: permissionRequests.value.filter(r => r.status === 'pending').length }, @@ -79,6 +83,15 @@ interface AgentRow { iframe_url?: string; // Frontend helper property } +interface AgentTestResult { + success: boolean; + request_url: string; + output_info: string; + analysis: string; + http_status?: number; + tested_at?: string; +} + // 定义 User 行的数据结构 interface UserRow { id: number; @@ -121,7 +134,7 @@ interface FeedbackReport { const router = useRouter(); // 当前左侧菜单激活的模块:dashboard / agents / permissions -const activeModule = ref<'dashboard' | 'agents' | 'permissions' | 'requests' | 'reports' | 'approvals' | 'users' | 'departments' | 'questions'>('dashboard'); +const activeModule = ref<'dashboard' | 'agents' | 'announcements' | 'permissions' | 'requests' | 'reports' | 'approvals' | 'users' | 'departments' | 'questions'>('dashboard'); const expandedReports = ref(true); // agents:管理员视角下的所有 Agent 列表 @@ -685,6 +698,76 @@ const newQuestion = ref>({ }); const isEditingQuestion = ref(false); +interface AnnouncementItem { + id: number; + title: string; + content: string; + created_at: string; +} +const adminAnnouncements = ref([]); +const newAnnouncement = ref({ title: '', content: '' }); + +const loadAnnouncementsAdmin = async () => { + try { + const res = await fetch('/api/user/announcements', { headers: getAuthHeaders() }); + if (res.ok) { + adminAnnouncements.value = await res.json(); + } else { + adminAnnouncements.value = []; + } + } catch (e) { + console.error('Failed to load announcements', e); + adminAnnouncements.value = []; + } +}; + +const createAnnouncementAdmin = async () => { + if (!newAnnouncement.value.title.trim() || !newAnnouncement.value.content.trim()) { + alert(t('admin.announcement.msg.fillAll')); + return; + } + isSaving.value = true; + try { + const res = await fetch('/api/user/announcements', { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify({ + title: newAnnouncement.value.title.trim(), + content: newAnnouncement.value.content.trim() + }) + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || t('admin.msg.failed')); + } + newAnnouncement.value = { title: '', content: '' }; + await loadAnnouncementsAdmin(); + } catch (e: any) { + console.error(e); + alert(e.message || t('admin.msg.requestFailed')); + } finally { + isSaving.value = false; + } +}; + +const deleteAnnouncementAdmin = async (id: number) => { + if (!confirm(t('admin.announcement.confirmDelete'))) return; + try { + const res = await fetch(`/api/user/announcements/${id}`, { + method: 'DELETE', + headers: getAuthHeaders() + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || t('admin.msg.failed')); + } + await loadAnnouncementsAdmin(); + } catch (e: any) { + console.error(e); + alert(e.message || t('admin.msg.requestFailed')); + } +}; + const loadQuickQuestions = async () => { try { const res = await fetch('/api/admin/quick-questions', { headers: getAuthHeaders() }); @@ -766,6 +849,7 @@ onMounted(async () => { loadReports(), loadPermissionRequests(), loadDepartments(), + loadAnnouncementsAdmin(), loadQuickQuestions() ]); isLoading.value = false; @@ -778,6 +862,9 @@ watch(activeModule, async (value) => { if (value === 'questions') { await loadQuickQuestions(); } + if (value === 'announcements') { + await loadAnnouncementsAdmin(); + } if (value === 'reports' || value === 'dashboard') { await loadReports(); } @@ -819,18 +906,26 @@ const filteredPermissionUsers = computed(() => { }); const isEditingAgent = ref(false); +const selectedAgentId = ref(null); +const showAgentTestModal = ref(false); +const isTestingAgent = ref(false); +const testingAgent = ref(null); +const agentTestResult = ref(null); const selectAgent = (agent: AgentRow) => { + selectedAgentId.value = agent.id; // Deep clone and ensure all fields are present newAgent.value = { ...agent, - dify_api_key: '', // Default to empty if not present (security) + // Show existing API key while editing selected row. + dify_api_key: agent.dify_api_key || '', iframe_url: agent.extra_config?.iframe_url || '' }; isEditingAgent.value = true; }; const resetAgentForm = () => { + selectedAgentId.value = null; newAgent.value = { name: '', dify_app_id: '', @@ -844,6 +939,57 @@ const resetAgentForm = () => { isEditingAgent.value = false; }; +const openAgentTestModal = (agent: AgentRow) => { + testingAgent.value = agent; + agentTestResult.value = null; + showAgentTestModal.value = true; + runAgentTest(agent); +}; + +const runAgentTest = async (agent?: AgentRow) => { + const target = agent || testingAgent.value; + if (!target) return; + isTestingAgent.value = true; + try { + const res = await fetch(`/api/admin/agents/${target.id}/test`, { + method: 'POST', + headers: getAuthHeaders() + }); + const data = await res.json().catch(() => ({})); + agentTestResult.value = { + success: !!data.success, + request_url: data.request_url || '', + output_info: data.output_info || '', + analysis: data.analysis || (res.ok ? '测试已完成。' : '测试失败。'), + http_status: data.http_status, + tested_at: data.tested_at + }; + + if (data.success) { + const idx = agents.value.findIndex(a => a.id === target.id); + if (idx >= 0) { + const updatedAgent = agents.value[idx]; + if (updatedAgent) { + updatedAgent.is_active = true; + } + } + if (selectedAgentId.value === target.id) { + newAgent.value.is_active = true; + } + } + } catch (e: any) { + agentTestResult.value = { + success: false, + request_url: '', + output_info: e?.message || 'Network error', + analysis: '测试失败:请求过程出现异常。', + http_status: 0 + }; + } finally { + isTestingAgent.value = false; + } +}; + /** * createAgent * 用途:使用表单一次性填写所有字段并创建 Agent @@ -860,6 +1006,7 @@ const createAgent = async () => { let res; try { + const editingId = isEditingAgent.value ? Number(newAgent.value.id) : null; if (isEditingAgent.value) { // Update const payload: any = { @@ -899,8 +1046,16 @@ const createAgent = async () => { } if (res.ok) { - resetAgentForm(); await loadAgents(); + // Keep current row selected after update; only reset after create. + if (editingId) { + const updated = agents.value.find(a => a.id === editingId); + if (updated) { + selectAgent(updated); + } + } else { + resetAgentForm(); + } } else { const text = await res.text(); try { @@ -960,6 +1115,40 @@ const currentTable = ref('users'); const tableData = ref([]); const isFullScreen = ref(false); const columnFilters = ref>({}); +const selectedReportRowIds = ref([]); +const isDeletingChatLogs = ref(false); +const chatLogsTotal = ref(0); +const showChatLogsColumnPanel = ref(false); +const chatLogsWrapEnabled = ref(false); +const chatLogsWrapMaxHeight = ref(120); +const showChatLogsSelection = ref(false); +const reportCurrentPage = ref(1); +const reportPageSize = ref(20); +const reportPageSizeOptions = [10, 20, 50, 100]; + +interface ReportColumnConfig { + key: string; + visible: boolean; + width: number; +} +interface ChatLogsLayoutPref { + columns: ReportColumnConfig[]; + wrapEnabled: boolean; + wrapMaxHeight: number; + sortRules?: SortRule[]; +} +type SortDirection = 'asc' | 'desc'; +interface SortRule { + key: string; + direction: SortDirection; +} +const chatLogsColumns = ref([]); +const chatLogsSortRules = ref([]); +const reportHeaderSort = ref(null); +const draggingColumnKey = ref(null); +const resizingColumnKey = ref(null); +let resizeStartX = 0; +let resizeStartWidth = 0; const loadTableData = async () => { // Construct query params from columnFilters @@ -973,8 +1162,155 @@ const loadTableData = async () => { }); if (res.ok) { tableData.value = await res.json(); + if (tableData.value.length > 0) { + initChatLogsColumns(Object.keys(tableData.value[0] || {})); + } + // Keep selection valid after reload/filter. + if (currentTable.value === 'chat_logs') { + const validIds = new Set( + tableData.value + .map((row: any) => Number(row?.id)) + .filter((id: number) => Number.isFinite(id)) + ); + selectedReportRowIds.value = selectedReportRowIds.value.filter(id => validIds.has(id)); + } else { + selectedReportRowIds.value = []; + } } else { tableData.value = []; + selectedReportRowIds.value = []; + } +}; + +const saveChatLogsColumns = () => { + if (chatLogsColumns.value.length === 0) return; + const payload: ChatLogsLayoutPref = { + columns: chatLogsColumns.value, + wrapEnabled: chatLogsWrapEnabled.value, + wrapMaxHeight: chatLogsWrapMaxHeight.value, + sortRules: chatLogsSortRules.value, + }; + saveReportLayoutPref(currentTable.value, payload); +}; + +const initChatLogsColumns = (keys: string[]) => { + chatLogsWrapEnabled.value = false; + chatLogsWrapMaxHeight.value = 120; + const defaults: ReportColumnConfig[] = keys.map((k) => ({ + key: k, + visible: true, + width: k === 'id' ? 90 : 180 + })); + + let merged = defaults; + try { + const parsed = loadReportLayoutPref(currentTable.value); + if (parsed) { + const saved = Array.isArray(parsed) ? parsed : (parsed.columns || []); + const savedMap = new Map(saved.map((c) => [c.key, c])); + const order = saved.map((c) => c.key).filter((k) => keys.includes(k)); + const missing = keys.filter((k) => !order.includes(k)); + merged = [...order, ...missing].map((k) => ({ + key: k, + visible: savedMap.get(k)?.visible ?? true, + width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : 180), + })); + if (!Array.isArray(parsed)) { + chatLogsWrapEnabled.value = !!parsed.wrapEnabled; + chatLogsWrapMaxHeight.value = Number(parsed.wrapMaxHeight || 120); + chatLogsSortRules.value = Array.isArray(parsed.sortRules) + ? parsed.sortRules + .filter((r: any) => r && typeof r.key === 'string' && (r.direction === 'asc' || r.direction === 'desc')) + : []; + } + } + } catch { + merged = defaults; + } + if (!Number.isFinite(chatLogsWrapMaxHeight.value)) chatLogsWrapMaxHeight.value = 120; + chatLogsColumns.value = merged; +}; + +const resetChatLogsColumns = () => { + if (tableData.value.length === 0) return; + chatLogsWrapEnabled.value = false; + chatLogsWrapMaxHeight.value = 120; + chatLogsSortRules.value = []; + reportHeaderSort.value = null; + initChatLogsColumns(Object.keys(tableData.value[0] || {})); + saveChatLogsColumns(); +}; + +const moveChatLogsColumn = (key: string, direction: -1 | 1) => { + const idx = chatLogsColumns.value.findIndex((c) => c.key === key); + if (idx < 0) return; + const target = idx + direction; + if (target < 0 || target >= chatLogsColumns.value.length) return; + const copy = [...chatLogsColumns.value]; + const [item] = copy.splice(idx, 1); + if (!item) return; + copy.splice(target, 0, item); + chatLogsColumns.value = copy; + saveChatLogsColumns(); +}; + +const onColumnDragStart = (key: string) => { + draggingColumnKey.value = key; +}; + +const onColumnDrop = (targetKey: string) => { + const sourceKey = draggingColumnKey.value; + draggingColumnKey.value = null; + if (!sourceKey || sourceKey === targetKey) return; + const sourceIdx = chatLogsColumns.value.findIndex((c) => c.key === sourceKey); + const targetIdx = chatLogsColumns.value.findIndex((c) => c.key === targetKey); + if (sourceIdx < 0 || targetIdx < 0) return; + const copy = [...chatLogsColumns.value]; + const [item] = copy.splice(sourceIdx, 1); + if (!item) return; + copy.splice(targetIdx, 0, item); + chatLogsColumns.value = copy; + saveChatLogsColumns(); +}; + +const onResizeMouseMove = (e: MouseEvent) => { + if (!resizingColumnKey.value) return; + const diff = e.clientX - resizeStartX; + const col = chatLogsColumns.value.find((c) => c.key === resizingColumnKey.value); + if (!col) return; + col.width = Math.max(80, resizeStartWidth + diff); +}; + +const onResizeMouseUp = () => { + if (!resizingColumnKey.value) return; + resizingColumnKey.value = null; + document.removeEventListener('mousemove', onResizeMouseMove); + document.removeEventListener('mouseup', onResizeMouseUp); + saveChatLogsColumns(); +}; + +const startResizeColumn = (key: string, e: MouseEvent) => { + e.preventDefault(); + e.stopPropagation(); + const col = chatLogsColumns.value.find((c) => c.key === key); + if (!col) return; + resizingColumnKey.value = key; + resizeStartX = e.clientX; + resizeStartWidth = col.width; + document.addEventListener('mousemove', onResizeMouseMove); + document.addEventListener('mouseup', onResizeMouseUp); +}; + +const loadTableCount = async (table: string) => { + try { + const res = await fetch(`/api/admin/database/${table}/count`, { + headers: getAuthHeaders() + }); + if (!res.ok) return 0; + const data = await res.json(); + return Number(data.total || 0); + } catch { + return 0; } }; @@ -995,10 +1331,216 @@ const handleFilterChange = () => { }, 500); }; +const isChatLogsTable = computed(() => currentTable.value === 'chat_logs'); +const visibleReportKeys = computed(() => { + if (chatLogsColumns.value.length === 0) return Object.keys(tableData.value[0] || {}); + return chatLogsColumns.value.filter((c) => c.visible).map((c) => c.key); +}); +const getReportRowId = (row: any) => Number(row?.id); +const allReportRowsSelected = computed(() => { + if (!isChatLogsTable.value || paginatedSortedTableData.value.length === 0) return false; + return paginatedSortedTableData.value.every((row: any) => selectedReportRowIds.value.includes(getReportRowId(row))); +}); + +const getColumnWidthStyle = (key: string) => { + const col = chatLogsColumns.value.find((c) => c.key === key); + if (!col) return {}; + return { + width: `${col.width}px`, + minWidth: `${col.width}px`, + maxWidth: `${col.width}px`, + }; +}; +const getReportCellValue = (row: any, key: string) => row?.[key]; +const normalizeSortValue = (v: any) => { + if (v === null || v === undefined) return null; + if (typeof v === 'number') return v; + if (typeof v === 'boolean') return v ? 1 : 0; + if (typeof v === 'string') { + const n = Number(v); + if (!Number.isNaN(n) && v.trim() !== '') return n; + const d = Date.parse(v); + if (!Number.isNaN(d)) return d; + return v.toLowerCase(); + } + return String(v).toLowerCase(); +}; +const compareByRule = (a: any, b: any, rule: SortRule) => { + const av = normalizeSortValue(getReportCellValue(a, rule.key)); + const bv = normalizeSortValue(getReportCellValue(b, rule.key)); + if (av === bv) return 0; + if (av === null) return 1; + if (bv === null) return -1; + const dir = rule.direction === 'asc' ? 1 : -1; + return av > bv ? dir : -dir; +}; +const sortedTableData = computed(() => { + const list = [...tableData.value]; + const advanced = chatLogsSortRules.value.length > 0 ? chatLogsSortRules.value : []; + const rules = advanced.length > 0 ? advanced : (reportHeaderSort.value ? [reportHeaderSort.value] : []); + if (rules.length === 0) return list; + return list.sort((a, b) => { + for (const r of rules) { + const c = compareByRule(a, b, r); + if (c !== 0) return c; + } + return 0; + }); +}); +// Front-end pagination over the already filtered/sorted dataset. +const reportTotalRows = computed(() => sortedTableData.value.length); +const reportTotalPages = computed(() => { + const size = Math.max(1, Number(reportPageSize.value) || 20); + return Math.max(1, Math.ceil(reportTotalRows.value / size)); +}); +const paginatedSortedTableData = computed(() => { + const size = Math.max(1, Number(reportPageSize.value) || 20); + // Clamp page number to avoid empty pages after filtering/deletion. + const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value); + const start = (safePage - 1) * size; + return sortedTableData.value.slice(start, start + size); +}); +const reportRangeStart = computed(() => { + if (reportTotalRows.value === 0) return 0; + const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value); + const size = Math.max(1, Number(reportPageSize.value) || 20); + return (safePage - 1) * size + 1; +}); +const reportRangeEnd = computed(() => { + if (reportTotalRows.value === 0) return 0; + const size = Math.max(1, Number(reportPageSize.value) || 20); + return Math.min(reportRangeStart.value + size - 1, reportTotalRows.value); +}); +const goToReportPage = (page: number) => { + reportCurrentPage.value = Math.min(Math.max(1, page), reportTotalPages.value); +}; +const prevReportPage = () => goToReportPage(reportCurrentPage.value - 1); +const nextReportPage = () => goToReportPage(reportCurrentPage.value + 1); +const reportPageButtons = computed(() => { + const total = reportTotalPages.value; + const current = Math.min(Math.max(1, reportCurrentPage.value), total); + if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1); + if (current <= 4) return [1, 2, 3, 4, 5, -1, total]; + if (current >= total - 3) return [1, -1, total - 4, total - 3, total - 2, total - 1, total]; + return [1, -1, current - 1, current, current + 1, -1, total]; +}); + +const onReportHeaderClick = (key: string) => { + // Column-header sorting is the quick mode; clear advanced rules to avoid precedence conflict. + if (chatLogsSortRules.value.length > 0) { + chatLogsSortRules.value = []; + } + if (reportHeaderSort.value?.key === key) { + reportHeaderSort.value = { key, direction: reportHeaderSort.value.direction === 'asc' ? 'desc' : 'asc' }; + } else { + reportHeaderSort.value = { key, direction: 'asc' }; + } + reportCurrentPage.value = 1; +}; +const getHeaderSortMark = (key: string) => { + if (reportHeaderSort.value?.key !== key) return ''; + return reportHeaderSort.value.direction === 'asc' ? '▲' : '▼'; +}; +const addChatLogsSortRule = () => { + const keys = visibleReportKeys.value; + const fallback = Object.keys(tableData.value[0] || {}); + const key = keys[0] || fallback[0]; + if (!key) return; + chatLogsSortRules.value.push({ key, direction: 'asc' }); +}; +const removeChatLogsSortRule = (idx: number) => { + chatLogsSortRules.value.splice(idx, 1); +}; +const moveChatLogsSortRule = (idx: number, direction: -1 | 1) => { + const target = idx + direction; + if (target < 0 || target >= chatLogsSortRules.value.length) return; + const copy = [...chatLogsSortRules.value]; + const [item] = copy.splice(idx, 1); + if (!item) return; + copy.splice(target, 0, item); + chatLogsSortRules.value = copy; +}; +const getReportCellDisplayStyle = (key: string) => { + // Width is applied on
; height clamp is applied to inner block container. + return { ...getColumnWidthStyle(key) } as any; +}; + +const getReportCellInnerStyle = () => { + const style: Record = { display: 'block' }; + if (!chatLogsWrapEnabled.value) { + style.whiteSpace = 'nowrap'; + style.overflow = 'hidden'; + style.textOverflow = 'ellipsis'; + return style; + } + const maxH = Number.isFinite(chatLogsWrapMaxHeight.value) ? chatLogsWrapMaxHeight.value : 120; + style.whiteSpace = 'normal'; + style.wordBreak = 'break-word'; + style.maxHeight = `${maxH}px`; + style.overflow = 'hidden'; + return style; +}; + +const toggleReportRowSelection = (rowId: number) => { + const idx = selectedReportRowIds.value.indexOf(rowId); + if (idx === -1) selectedReportRowIds.value.push(rowId); + else selectedReportRowIds.value.splice(idx, 1); +}; + +const toggleAllReportRows = () => { + if (!isChatLogsTable.value) return; + const ids = paginatedSortedTableData.value + .map((row: any) => getReportRowId(row)) + .filter((id: number) => Number.isFinite(id)); + const allSelected = ids.length > 0 && ids.every((id: number) => selectedReportRowIds.value.includes(id)); + if (allSelected) { + selectedReportRowIds.value = selectedReportRowIds.value.filter((id) => !ids.includes(id)); + return; + } + const merged = new Set([...selectedReportRowIds.value, ...ids]); + selectedReportRowIds.value = Array.from(merged); +}; + +const batchDeleteChatLogs = async () => { + if (!isChatLogsTable.value) return; + if (selectedReportRowIds.value.length === 0) return; + if (!confirm(`Delete ${selectedReportRowIds.value.length} selected chat logs?`)) return; + + isDeletingChatLogs.value = true; + try { + const res = await fetch('/api/admin/database/chat_logs/batch-delete', { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify({ ids: selectedReportRowIds.value }) + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + throw new Error(data.error || t('admin.msg.failed')); + } + alert(`Deleted ${data.deleted_count ?? 0} chat logs.`); + selectedReportRowIds.value = []; + await loadTableData(); + chatLogsTotal.value = await loadTableCount('chat_logs'); + } catch (e: any) { + console.error(e); + alert(e.message || t('admin.msg.failed')); + } finally { + isDeletingChatLogs.value = false; + } +}; + watch(currentTable, async () => { if (activeModule.value === 'reports') { columnFilters.value = {}; // Reset filters on table change + selectedReportRowIds.value = []; + showChatLogsColumnPanel.value = false; + showChatLogsSelection.value = false; + reportCurrentPage.value = 1; await loadTableData(); + reportHeaderSort.value = null; + if (currentTable.value === 'chat_logs') { + chatLogsTotal.value = await loadTableCount('chat_logs'); + } } }); @@ -1007,7 +1549,45 @@ watch(activeModule, async (value) => { await loadPermissionRequests(); } if (value === 'reports') { + reportCurrentPage.value = 1; await loadTableData(); + if (currentTable.value === 'chat_logs') { + chatLogsTotal.value = await loadTableCount('chat_logs'); + } else { + showChatLogsSelection.value = false; + } + } +}); + +watch(chatLogsColumns, () => { + saveChatLogsColumns(); +}, { deep: true }); + +watch([chatLogsWrapEnabled, chatLogsWrapMaxHeight], () => { + saveChatLogsColumns(); +}); + +watch(chatLogsSortRules, () => { + // Force row re-evaluation immediately when rule fields/order change. + tableData.value = [...tableData.value]; + reportCurrentPage.value = 1; + saveChatLogsColumns(); +}, { deep: true }); + +watch(showChatLogsSelection, (v) => { + if (!v) selectedReportRowIds.value = []; +}); + +watch(columnFilters, () => { + reportCurrentPage.value = 1; +}, { deep: true }); + +watch([reportPageSize, sortedTableData], () => { + if (reportCurrentPage.value > reportTotalPages.value) { + reportCurrentPage.value = reportTotalPages.value; + } + if (reportCurrentPage.value < 1) { + reportCurrentPage.value = 1; } }); @@ -1025,6 +1605,9 @@ const deleteAgent = async (id: number) => { }); if (res.ok) { await loadAgents(); + if (selectedAgentId.value === id) { + resetAgentForm(); + } } else { const text = await res.text(); try { @@ -1745,7 +2328,7 @@ const handlePermissionImport = async (event: Event) => { v-for="agent in agents" :key="agent.id" class="hover:bg-gray-50/50 transition-colors group cursor-pointer" - :class="{ 'bg-blue-50/50': newAgent.id === agent.id }" + :class="{ 'bg-blue-50/50': selectedAgentId === agent.id }" @click="selectAgent(agent)" > @@ -1766,12 +2349,22 @@ const handlePermissionImport = async (event: Event) => { - - - {{ t('admin.status.active') }} + + + {{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }} + + + + + +
+
+ {{ t('admin.announcement.noData') }} +
+
+
+
+
+

{{ ann.title }}

+

{{ new Date(ann.created_at).toLocaleString() }}

+
+ +
+

{{ ann.content }}

+
+
+
+ + +
@@ -2038,22 +2680,57 @@ const handlePermissionImport = async (event: Event) => {
-
-
-

- +
+
+

+ + + {{ t('admin.report.title', { table: currentTable.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) }) }}

-

{{ t('admin.report.subtitle') }}

+
+ + {{ t('admin.report.subtitle') }} + + + Total: {{ chatLogsTotal }} + + + Showing: {{ reportRangeStart }}-{{ reportRangeEnd }} / {{ reportTotalRows }} + +
-
+
+ + +
-
-
+
+
+
+
Table Settings
+ +
+
+ + +
+
+
+ 高级排序规则(按顺序优先) + +
+
未设置高级排序,将使用列头点击排序。
+
+
+ {{ ridx + 1 }}. + + +
+ + + +
+
+
+
+
+
+ +
+ + +
+
+
+
+ +

{{ t('admin.report.noData', { table: currentTable }) }}

-
+
- + - + - - - + + +
+ + +
- {{ key }} +
+
- {{ val }} +
+ + +
+ {{ getReportCellValue(row, String(key)) }} +
+ +
+
+ 共 {{ reportTotalRows }} 条,当前第 {{ reportCurrentPage }} / {{ reportTotalPages }} 页 +
+
+ + + + +
+
-
-

Usage Analytics

+
+

Usage Analytics

-
-

Requests by User

+
+

Requests by User

-
- {{ u.username }} +
+ {{ u.username }} {{ u.count }}
-
-

Requests by Agent

+
+

Requests by Agent

-
- {{ a.agent }} - {{ a.count }} +
+ {{ a.agent }} + {{ a.count }}
@@ -2249,6 +3098,59 @@ const handlePermissionImport = async (event: Event) => {
+ +
+
+
+
+

应用测试

+

应用:{{ testingAgent.name }}

+
+ +
+ +
+
+
+ 测试时间:{{ agentTestResult.tested_at }} +
+ +
+ +
正在执行测试,请稍候...
+ + +
+
+
+
diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 4d77b32a..1ec7d3ff 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -17,6 +17,7 @@ import { Send, User, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, Rot import { marked } from 'marked'; import { useRoute, useRouter } from 'vue-router'; import { config } from '../config'; +import FilePreviewModal from '../components/FilePreviewModal.vue'; const { t, locale } = useI18n(); @@ -28,6 +29,202 @@ const renderMarkdown = (text: string) => { return text; } }; + +const getSourceTitle = (item: any) => { + return item?.document_name || item?.title || item?.source || 'Untitled Source'; +}; + +const getSourceMeta = (item: any) => { + const parts: string[] = []; + if (item?.dataset_name) parts.push(item.dataset_name); + if (item?.segment_id) parts.push(`segment: ${item.segment_id}`); + if (typeof item?.score === 'number') parts.push(`score: ${item.score.toFixed(3)}`); + return parts.join(' | '); +}; + +const getSourceContent = (item: any) => { + return item?.content || item?.segment_content || item?.text || ''; +}; + +const getSourceBrief = (item: any) => { + const raw = getSourceContent(item); + const plain = raw + .replace(/\[[^\]]+\]\(([^)]+)\)/g, '$1') + .replace(/[#>*`]/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (!plain) return ''; + return plain.length > 180 ? `${plain.slice(0, 180)}...` : plain; +}; + +interface SourceFileLink { + name: string; + url: string; +} + +const safeDecode = (value: string) => { + try { + return decodeURIComponent(value); + } catch { + return value; + } +}; + +const normalizeUrl = (url: string) => { + // 统一清洗 URL:去掉包裹引号、还原转义字符、剔除末尾标点。 + // 目的:让后续提取逻辑面对 Dify 返回的不同转义形态时保持稳定。 + let v = url + .trim() + .replace(/^['"]|['"]$/g, '') + .replace(/\\\//g, '/') + .replace(/\\u0026/gi, '&') + .replace(/\\u003d/gi, '=') + .replace(/\\u003a/gi, ':') + .replace(/\\u002f/gi, '/') + .replace(/&/g, '&'); + v = v.replace(/[),.;]+$/g, ''); + if (!v) return ''; + if (v.startsWith('//')) return `${window.location.protocol}${v}`; + if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v; + if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\//.test(v)) return `http://${v}`; + if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//.test(v)) return `http://${v}`; + return ''; +}; + +const extractUrlsFromText = (text: string) => { + if (!text) return []; + const urls: string[] = []; + // 先把常见 JSON/Markdown 转义做一次反转义,避免 regex 漏抓。 + const normalizedText = text + .replace(/\\\//g, '/') + .replace(/\\u0026/gi, '&') + .replace(/\\u003d/gi, '=') + .replace(/\\u003a/gi, ':') + .replace(/\\u002f/gi, '/'); + + // 1) Markdown 链接: [name](url) + const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g; + let m; + while ((m = mdRegex.exec(normalizedText)) !== null) { + const url = normalizeUrl(m[1] || ''); + if (url) urls.push(url); + } + + // 2) HTML 链接: href/src 属性 + const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi; + while ((m = htmlAttrRegex.exec(normalizedText)) !== null) { + const url = normalizeUrl(m[1] || ''); + if (url) urls.push(url); + } + + // 3) 尖括号 URL: + const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi; + while ((m = angleRegex.exec(normalizedText)) !== null) { + const url = normalizeUrl(m[1] || ''); + if (url) urls.push(url); + } + + // 4) 原始 URL:支持带/不带协议、内网 IP、相对路径文件等 + const rawRegex = + /((?:https?:\/\/|\/\/)[^\s"'<>]+|(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\/[^\s"'<>]+|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\/[^\s"'<>]+|\/[^\s"'<>]+\.(?:md|markdown|txt|pdf|doc|docx|ppt|pptx|xls|xlsx|jpg|jpeg|png|gif|webp|svg|bmp))/gi; + while ((m = rawRegex.exec(normalizedText)) !== null) { + const url = normalizeUrl(m[1] || ''); + if (url) urls.push(url); + } + return urls; +}; + +const getSourceLinks = (resources: any[] = []): SourceFileLink[] => { + const map = new Map(); + for (const item of resources) { + const directCandidates = [ + item?.url, + item?.file_url, + item?.document_url, + item?.source_url, + item?.download_url, + item?.metadata?.url, + item?.metadata?.file_url, + item?.metadata?.document_url, + ].filter(Boolean) as string[]; + + const content = getSourceContent(item); + const serialized = JSON.stringify(item || {}); + const discovered = [ + ...directCandidates.map(normalizeUrl).filter(Boolean), + ...extractUrlsFromText(content), + ...extractUrlsFromText(serialized), + ]; + + // Parse explicit file URL array if Dify provides it. + const files = Array.isArray(item?.files) ? item.files : []; + for (const f of files) { + const fu = normalizeUrl(f?.url || f?.download_url || f?.file_url || ''); + if (fu) { + discovered.push(fu); + } + } + + for (const url of discovered) { + const name = item?.document_name || item?.title || decodeURIComponent(url.split('/').pop() || 'source-file'); + const key = `${name}|${url}`; + if (!map.has(key)) { + map.set(key, { name, url }); + } + } + } + return Array.from(map.values()); +}; + +const getMessageLinks = (msg: any): SourceFileLink[] => { + const map = new Map(); + + const merge = (links: SourceFileLink[]) => { + for (const link of links) { + const key = `${link.name}|${link.url}`; + if (!map.has(key)) map.set(key, link); + } + }; + + if (msg?.retriever_resources) { + merge(getSourceLinks(msg.retriever_resources)); + } + + const contentLinks = extractUrlsFromText(msg?.content || ''); + for (const url of contentLinks) { + const name = safeDecode(url.split('/').pop() || 'source-file'); + merge([{ name, url }]); + } + + if (Array.isArray(msg?.attribution_parts)) { + for (const part of msg.attribution_parts) { + const urls = extractUrlsFromText(typeof part === 'string' ? part : JSON.stringify(part)); + for (const url of urls) { + const name = safeDecode(url.split('/').pop() || 'source-file'); + merge([{ name, url }]); + } + } + } + + // 5) 最后兜底:扫描整条 assistant 消息的 JSON 字符串。 + // 用途:覆盖 Dify 在未知嵌套字段里返回链接但未被上面路径命中的情况。 + const fullMessageText = JSON.stringify(msg || {}); + const allUrls = extractUrlsFromText(fullMessageText); + for (const url of allUrls) { + const name = safeDecode(url.split('/').pop() || 'source-file'); + merge([{ name, url }]); + } + + return Array.from(map.values()); +}; + +const filePreviewVisible = ref(false); +const previewFile = ref(null); + +const openPreview = (file: SourceFileLink) => { + previewFile.value = file; + filePreviewVisible.value = true; +}; const route = useRoute(); const router = useRouter(); const agentId = Number(route.params.agentId); @@ -56,26 +253,30 @@ const presetQuestion = computed(() => { }); const getAuthHeaders = () => { - let stored = localStorage.getItem('hxops_user'); - if (!stored) stored = sessionStorage.getItem('hxops_user'); - - if (!stored) return {}; - - try { - const data = JSON.parse(stored); - const user = data.user || data; - - const headers: Record = { - 'X-Username': user.username, - 'X-Role': user.role, - }; - if (user.id) { - headers['X-User-Id'] = String(user.id); + const candidates = [ + sessionStorage.getItem('hxops_user'), + localStorage.getItem('hxops_user'), + ]; + + for (const stored of candidates) { + if (!stored) continue; + try { + const data = JSON.parse(stored); + const user = data.user || data; + if (!user?.username || !user?.role) continue; + const headers: Record = { + 'X-Username': user.username, + 'X-Role': user.role, + }; + if (user.id) { + headers['X-User-Id'] = String(user.id); + } + return headers; + } catch (e) { + continue; } - return headers; - } catch (e) { - return {}; } + return {}; }; /** @@ -264,7 +465,7 @@ const submitFeedback = async () => {
{{ $t('chat.noHistory') }}
+ +
+
+ +
+ +
+ + 源文档 ({{ msg.retriever_resources.length }}) + +
+
+
{{ getSourceTitle(doc) }}
+
{{ getSourceMeta(doc) }}
+
{{ getSourceBrief(doc) }}
+
+
+
+ +
+ + 生成内容归属部分 + +
    +
  • + {{ part }} +
  • +
+
+
{
+ + diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index 708e3ca3..dabd8e6f 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -4,7 +4,7 @@ * 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent * 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口 */ -import { ref, onMounted, computed } from 'vue'; +import { ref, onMounted, computed, watch } from 'vue'; import { useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { config } from '../config'; @@ -29,6 +29,21 @@ import { const { t, locale } = useI18n(); const router = useRouter(); +const loadLanguagePreference = () => { + const storedLang = localStorage.getItem('hxops_lang'); + if (storedLang) { + locale.value = storedLang; + } +}; + +const saveLanguagePreference = (lang: string) => { + localStorage.setItem('hxops_lang', lang); +}; + +watch(locale, (newLang) => { + saveLanguagePreference(newLang); +}); + // Interfaces interface Agent { id: number; @@ -73,10 +88,18 @@ const announcements = ref([]); const quickQuestions = ref([]); const favoriteAgentIds = ref([]); const embeddedAgents = ref([]); +const SECTION_TITLE_KEY_MAP: Record = { + announcements: 'workspace.announcements.title', + favorites: 'workspace.favorites', + quick_questions: 'workspace.quickQuestions.title', + embedded: 'workspace.embedded.title', + all_agents: 'workspace.availableAgents', +}; const layoutSections = ref([ + { id: 'announcements', visible: true, collapsed: false, title: 'workspace.announcements.title' }, { id: 'favorites', visible: true, collapsed: false, title: 'workspace.favorites' }, { id: 'quick_questions', visible: true, collapsed: false, title: 'workspace.quickQuestions.title' }, - { id: 'embedded', visible: true, collapsed: false, title: 'workspace.embedded' }, + { id: 'embedded', visible: true, collapsed: false, title: 'workspace.embedded.title' }, { id: 'all_agents', visible: true, collapsed: false, title: 'workspace.availableAgents' }, ]); @@ -162,6 +185,16 @@ const filteredQuickQuestions = computed(() => { ); }); +const normalizeSectionId = (id: string) => { + if (id === 'quice_questions' || id === 'quickQuestions') return 'quick_questions'; + if (id === 'allAgents') return 'all_agents'; + return id; +}; + +const getSectionTitleKey = (sectionId: string) => { + return SECTION_TITLE_KEY_MAP[normalizeSectionId(sectionId)] || normalizeSectionId(sectionId); +}; + // Methods const getAuthHeaders = () => { let stored = localStorage.getItem('hxops_user'); @@ -206,24 +239,28 @@ const fetchHome = async () => { embeddedAgents.value = data.embedded_agents || []; if (data.layout && data.layout.sections) { - const backendSections = data.layout.sections as LayoutSection[]; + const backendSections = (data.layout.sections as LayoutSection[]).map((s) => ({ + ...s, + id: normalizeSectionId(s.id), + })); const defaultSections = [ - { id: 'favorites', visible: true }, - { id: 'quick_questions', visible: true }, - { id: 'embedded', visible: true }, - { id: 'all_agents', visible: true }, + { id: 'announcements', visible: true, title: getSectionTitleKey('announcements') }, + { id: 'favorites', visible: true, title: getSectionTitleKey('favorites') }, + { id: 'quick_questions', visible: true, title: getSectionTitleKey('quick_questions') }, + { id: 'embedded', visible: true, title: getSectionTitleKey('embedded') }, + { id: 'all_agents', visible: true, title: getSectionTitleKey('all_agents') }, ]; const merged: LayoutSection[] = []; const backendIds = new Set(backendSections.map(s => s.id)); - const mapKey = (id: string) => (id === 'quick_questions' ? 'quickQuestions' : id === 'all_agents' ? 'allAgents' : id); + const mapKey = (id: string) => (normalizeSectionId(id) === 'quick_questions' ? 'quickQuestions' : normalizeSectionId(id) === 'all_agents' ? 'allAgents' : normalizeSectionId(id)); backendSections.forEach(s => { const def = defaultSections.find(d => d.id === s.id); if (config.workspace.modules[mapKey(s.id) as keyof typeof config.workspace.modules] === false) { return; } - merged.push({ ...def, ...s }); + merged.push({ ...def, ...s, title: getSectionTitleKey(s.id) }); }); defaultSections.forEach(d => { @@ -248,10 +285,11 @@ const fetchHome = async () => { } else { // Fallback for no layout data const defaultSections = [ - { id: 'favorites', visible: true, collapsed: false }, - { id: 'quick_questions', visible: true, collapsed: false }, - { id: 'embedded', visible: true, collapsed: false }, - { id: 'all_agents', visible: true, collapsed: false }, + { id: 'announcements', visible: true, collapsed: false, title: getSectionTitleKey('announcements') }, + { id: 'favorites', visible: true, collapsed: false, title: getSectionTitleKey('favorites') }, + { id: 'quick_questions', visible: true, collapsed: false, title: getSectionTitleKey('quick_questions') }, + { id: 'embedded', visible: true, collapsed: false, title: getSectionTitleKey('embedded') }, + { id: 'all_agents', visible: true, collapsed: false, title: getSectionTitleKey('all_agents') }, ]; layoutSections.value = defaultSections.filter(s => { @@ -363,9 +401,13 @@ const handleLogin = async () => { // Store in localStorage with 30 days expiry const expiry = new Date().getTime() + 30 * 24 * 60 * 60 * 1000; localStorage.setItem('hxops_user', JSON.stringify({ user, expiry })); + // Avoid stale session user overriding current login. + sessionStorage.removeItem('hxops_user'); } else { // Store in sessionStorage (cleared when tab closed) sessionStorage.setItem('hxops_user', JSON.stringify({ user })); + // Avoid stale remembered user overriding current login. + localStorage.removeItem('hxops_user'); } await fetchHome(); @@ -570,6 +612,7 @@ const openAnnouncement = (ann: Announcement) => { }; onMounted(async () => { + loadLanguagePreference(); loadAuthUser(); fetchAnnouncements(); if (currentUser.value && currentUser.value.role !== 'guest') { @@ -798,14 +841,15 @@ onMounted(async () => {

- +
- {{ $t(section.title || section.id) }} + {{ $t(getSectionTitleKey(section.id)) }}

@@ -815,6 +859,25 @@ onMounted(async () => {
+ +
+
{{ $t('workspace.announcements.noData') }}
+
+
+
+

{{ ann.title }}

+ {{ new Date(ann.created_at).toLocaleDateString() }} +
+

{{ ann.content }}

+
+
+
+
{{ $t('workspace.noFavorites') }}