260323 function add report chat and front

This commit is contained in:
super committed 2026-03-23 00:54:14 +08:00
1 parent 605317c2b2
commit 5e8ea03b6c
16 files changed
+2351 -100

No files matched your search

+4
View File
@@ -46,3 +46,7 @@ frontend/.env.*.local
# OS # OS
.DS_Store .DS_Store
Thumbs.db 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
+187
View File
@@ -7,11 +7,13 @@ backend/app/api/admin.py
from flask import Blueprint, request, jsonify from flask import Blueprint, request, jsonify
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig
from app.decorators import require_admin from app.decorators import require_admin
from app.config import Config
from app import db from app import db
from sqlalchemy import func, desc, inspect from sqlalchemy import func, desc, inspect
from datetime import datetime from datetime import datetime
import csv import csv
import io import io
import requests
admin_bp = Blueprint('admin', __name__) admin_bp = Blueprint('admin', __name__)
@@ -165,6 +167,138 @@ def delete_agent(id):
return jsonify({'status': 'ok'}) return jsonify({'status': 'ok'})
@admin_bp.route('/agents/<int:id>/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/<int:id>/permissions', methods=['POST']) @admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
@require_admin @require_admin
def update_agent_permissions(id): def update_agent_permissions(id):
@@ -525,3 +659,56 @@ def get_table_data(table):
res.append(d) res.append(d)
return jsonify(res) 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/<table>/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)})
+25
View File
@@ -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]}...')
+129
View File
@@ -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()
+80
View File
@@ -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()
+209
View File
@@ -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()
+2 -2
View File
@@ -5,8 +5,8 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>hxai</title> <title>hxai</title>
<script type="module" crossorigin src="/assets/index-ZKeQWaOJ.js"></script> <script type="module" crossorigin src="/assets/index-DQ14cr0B.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CsuXWz4X.css"> <link rel="stylesheet" crossorigin href="/assets/index-BDWnMpnR.css">
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+22 -10
View File
@@ -6,17 +6,29 @@ import { watch, onMounted } from 'vue';
const { locale } = useI18n(); const { locale } = useI18n();
const getAuthHeaders = () => { const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user'); const candidates = [
if (!stored) return {}; sessionStorage.getItem('hxops_user'),
const user = JSON.parse(stored) as { id?: number; username: string; role: string }; localStorage.getItem('hxops_user'),
const headers: Record<string, string> = { ];
'X-Username': user.username, for (const stored of candidates) {
'X-Role': user.role, if (!stored) continue;
}; try {
if (user.id) { const data = JSON.parse(stored) as any;
headers['X-User-Id'] = String(user.id); const user = data.user || data;
if (!user?.username || !user?.role) continue;
const headers: Record<string, string> = {
'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) => { const updateLanguagePreference = async (lang: string) => {
@@ -0,0 +1,133 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { marked } from 'marked';
interface PreviewFile {
name: string;
url: string;
}
const props = defineProps<{
modelValue: boolean;
file: PreviewFile | null;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
}>();
const isLoading = ref(false);
const error = ref('');
const markdownHtml = ref('');
const getExt = (raw: string) => {
const clean = (raw.split('?')[0] ?? '').toLowerCase();
const i = clean.lastIndexOf('.');
return i >= 0 ? clean.slice(i + 1) : '';
};
const ext = computed(() => {
// URL extension has higher priority than display name.
const byUrl = getExt(props.file?.url || '');
if (byUrl) return byUrl;
return getExt(props.file?.name || '');
});
const preferredMode = computed<'markdown' | 'image' | 'iframe'>(() => {
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
if (['md', 'markdown', 'txt'].includes(ext.value)) return 'markdown';
return 'iframe';
});
const resolvedMode = ref<'markdown' | 'image' | 'iframe'>('iframe');
const iframeSrc = computed(() => {
if (!props.file?.url) return '';
if (['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value)) {
return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(props.file.url)}`;
}
return props.file.url;
});
const close = () => emit('update:modelValue', false);
const loadContent = async () => {
error.value = '';
markdownHtml.value = '';
if (!props.modelValue || !props.file) return;
if (!props.file?.url) return;
resolvedMode.value = preferredMode.value;
if (preferredMode.value !== 'markdown') return;
isLoading.value = true;
try {
const res = await fetch(props.file.url);
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const contentType = (res.headers.get('content-type') || '').toLowerCase();
if (contentType.startsWith('image/')) {
resolvedMode.value = 'image';
return;
}
if (
contentType &&
!contentType.includes('text/') &&
!contentType.includes('markdown') &&
!contentType.includes('application/json')
) {
resolvedMode.value = 'iframe';
return;
}
const text = await res.text();
markdownHtml.value = marked.parse(text) as string;
} catch (e: any) {
error.value = e?.message || 'Failed to load file';
} finally {
isLoading.value = false;
}
};
watch(
() => [props.modelValue, props.file?.url, props.file?.name],
() => {
loadContent();
},
{ immediate: true }
);
</script>
<template>
<div v-if="modelValue && file" class="fixed inset-0 z-[80] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div class="bg-white rounded-2xl shadow-xl w-full max-w-5xl h-[85vh] flex flex-col overflow-hidden">
<div class="px-6 py-4 border-b border-slate-200 flex items-center justify-between gap-4">
<div class="min-w-0">
<div class="text-sm text-slate-500 uppercase tracking-wide">文件预览</div>
<div class="font-semibold text-slate-900 truncate">{{ file.name }}</div>
<a :href="file.url" target="_blank" class="text-xs text-brand-600 hover:text-brand-700 break-all">{{ file.url }}</a>
</div>
<button @click="close" class="px-3 py-1.5 rounded-lg text-slate-600 hover:bg-slate-100">关闭</button>
</div>
<div class="flex-1 overflow-auto p-4 bg-slate-50">
<div v-if="isLoading" class="text-sm text-slate-500">加载中...</div>
<div v-else-if="error" class="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg p-3">
预览失败:{{ error }}
</div>
<div
v-else-if="resolvedMode === 'markdown'"
class="prose prose-sm max-w-none bg-white border border-slate-200 rounded-lg p-5"
v-html="markdownHtml"
></div>
<div v-else-if="resolvedMode === 'image'" class="h-full flex items-center justify-center bg-white border border-slate-200 rounded-lg p-2">
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
</div>
<iframe
v-else
:src="iframeSrc"
class="w-full h-full min-h-[480px] bg-white rounded-lg border border-slate-200"
allow="clipboard-read; clipboard-write"
></iframe>
</div>
</div>
</div>
</template>
+131 -15
View File
@@ -7,12 +7,28 @@
*/ */
import { ref } from 'vue'; 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() { export function useChat() {
/** /**
* messages: 响应式消息列表,用于 UI 渲染 * messages: 响应式消息列表,用于 UI 渲染
* 结构: [{ role: 'user'|'assistant', content: string }] * 结构: [{ role: 'user'|'assistant', content: string }]
*/ */
const messages = ref<any[]>([]); const messages = ref<ChatMessage[]>([]);
/** /**
* isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用 * isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用
@@ -26,17 +42,29 @@ export function useChat() {
const conversationId = ref<string | null>(null); const conversationId = ref<string | null>(null);
const getAuthHeaders = () => { const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user'); const candidates = [
if (!stored) return {}; sessionStorage.getItem('hxops_user'),
const user = JSON.parse(stored) as { id?: number; username: string; role: string }; localStorage.getItem('hxops_user'),
const headers: Record<string, string> = { ];
'X-Username': user.username, for (const stored of candidates) {
'X-Role': user.role, if (!stored) continue;
}; try {
if (user.id) { const data = JSON.parse(stored) as any;
headers['X-User-Id'] = String(user.id); const user = data.user || data;
if (!user?.username || !user?.role) continue;
const headers: Record<string, string> = {
'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 更新:立即将用户消息推入列表 // 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query }); messages.value.push({ role: 'user', content: query });
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引 // 创建一个空的 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; isThinking.value = true;
@@ -100,14 +133,26 @@ export function useChat() {
const data = JSON.parse(line.slice(6)); const data = JSON.parse(line.slice(6));
// 仅处理 message 事件,追加 answer 到当前消息 // 仅处理 message 事件,追加 answer 到当前消息
if (data.event === 'message') { 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') { } else if (data.event === 'message_end') {
// 记录会话 ID,便于后续发送反馈 // 记录会话 ID,便于后续发送反馈
if (data.conversation_id) { if (data.conversation_id) {
conversationId.value = 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') { } 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) { } catch (e) {
// 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON) // 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON)
@@ -117,7 +162,10 @@ export function useChat() {
} }
} catch (e: any) { } catch (e: any) {
console.error(e); 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 { } finally {
isThinking.value = false; isThinking.value = false;
} }
@@ -125,3 +173,71 @@ export function useChat() {
return { messages, isThinking, conversationId, sendMessage }; 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);
};
@@ -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 = <T = any>(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.
}
};
+2
View File
@@ -3,6 +3,7 @@ export const config = {
workspace: { workspace: {
enableFeedback: true, enableFeedback: true,
modules: { modules: {
announcements: true,
favorites: true, favorites: true,
quickQuestions: true, quickQuestions: true,
embedded: true, embedded: true,
@@ -16,6 +17,7 @@ export const config = {
users: true, users: true,
departments: true, departments: true,
agents: true, agents: true,
announcements: true,
questions: true, questions: true,
permissions: true, permissions: true,
requests: true, requests: true,
+84
View File
@@ -96,6 +96,10 @@ const messages = {
noData: 'No embedded agents configured.', noData: 'No embedded agents configured.',
noUrl: 'No iframe URL configured' noUrl: 'No iframe URL configured'
}, },
announcements: {
title: 'Company Announcements',
noData: 'No announcements yet.'
},
favorites: 'Favorites', favorites: 'Favorites',
myAgents: 'My Agents', myAgents: 'My Agents',
availableAgents: 'Available Agents', availableAgents: 'Available Agents',
@@ -148,6 +152,7 @@ const messages = {
users: 'User Maintenance', users: 'User Maintenance',
departments: 'Departments', departments: 'Departments',
agents: 'Agent Management', agents: 'Agent Management',
announcements: 'Announcements',
questions: 'Common Questions', questions: 'Common Questions',
permissions: 'App Permissions', permissions: 'App Permissions',
requests: 'Permission Requests', 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 // Permissions
perm: { perm: {
title: 'App Permissions', title: 'App Permissions',
@@ -556,6 +577,10 @@ const messages = {
noData: '暂无嵌入式应用配置。', noData: '暂无嵌入式应用配置。',
noUrl: '未配置 iframe URL' noUrl: '未配置 iframe URL'
}, },
announcements: {
title: '公司公告',
noData: '暂无公告'
},
favorites: '收藏应用', favorites: '收藏应用',
myAgents: '我的应用', myAgents: '我的应用',
availableAgents: '可用应用', availableAgents: '可用应用',
@@ -609,6 +634,7 @@ const messages = {
users: '用户管理', users: '用户管理',
departments: '部门管理', departments: '部门管理',
agents: '应用管理', agents: '应用管理',
announcements: '公告管理',
questions: '常用问题', questions: '常用问题',
permissions: '应用权限', permissions: '应用权限',
requests: '权限审批', requests: '权限审批',
@@ -778,6 +804,22 @@ const messages = {
} }
}, },
announcement: {
title: '公告管理',
subtitle: '面向全体用户发布公司资讯',
add: '发布公告',
publish: '发布',
noData: '暂无公告',
confirmDelete: '确认删除该公告吗?',
fields: {
title: '标题',
content: '内容'
},
msg: {
fillAll: '请填写所有必填项'
}
},
// Permissions // Permissions
perm: { perm: {
title: '应用权限', title: '应用权限',
@@ -999,6 +1041,10 @@ const messages = {
noData: '暫無嵌入式應用配置。', noData: '暫無嵌入式應用配置。',
noUrl: '未配置 iframe URL' noUrl: '未配置 iframe URL'
}, },
announcements: {
title: '公司公告',
noData: '暫無公告'
},
favorites: '收藏應用', favorites: '收藏應用',
myAgents: '我的應用', myAgents: '我的應用',
availableAgents: '可用應用', availableAgents: '可用應用',
@@ -1052,6 +1098,7 @@ const messages = {
users: '用戶管理', users: '用戶管理',
departments: '部門管理', departments: '部門管理',
agents: '應用管理', agents: '應用管理',
announcements: '公告管理',
questions: '常用問題', questions: '常用問題',
permissions: '應用權限', permissions: '應用權限',
requests: '權限審批', requests: '權限審批',
@@ -1221,6 +1268,22 @@ const messages = {
} }
}, },
announcement: {
title: '公告管理',
subtitle: '面向全體用戶發布公司資訊',
add: '發布公告',
publish: '發布',
noData: '暫無公告',
confirmDelete: '確認刪除該公告嗎?',
fields: {
title: '標題',
content: '內容'
},
msg: {
fillAll: '請填寫所有必填項'
}
},
// Permissions // Permissions
perm: { perm: {
title: '應用權限', title: '應用權限',
@@ -1442,6 +1505,10 @@ const messages = {
noData: 'ไม่มีตัวแทนแบบฝังที่กำหนดค่าไว้', noData: 'ไม่มีตัวแทนแบบฝังที่กำหนดค่าไว้',
noUrl: 'ไม่ได้กำหนดค่า URL iframe' noUrl: 'ไม่ได้กำหนดค่า URL iframe'
}, },
announcements: {
title: 'ประกาศบริษัท',
noData: 'ยังไม่มีประกาศ'
},
favorites: 'รายการโปรด', favorites: 'รายการโปรด',
myAgents: 'ตัวแทนของฉัน', myAgents: 'ตัวแทนของฉัน',
availableAgents: 'ตัวแทนที่ใช้ได้', availableAgents: 'ตัวแทนที่ใช้ได้',
@@ -1495,6 +1562,7 @@ const messages = {
users: 'การจัดการผู้ใช้', users: 'การจัดการผู้ใช้',
departments: 'การจัดการแผนก', departments: 'การจัดการแผนก',
agents: 'การจัดการตัวแทน', agents: 'การจัดการตัวแทน',
announcements: 'การจัดการประกาศ',
questions: 'คำถามทั่วไป', questions: 'คำถามทั่วไป',
permissions: 'สิทธิ์แอปพลิเคชัน', permissions: 'สิทธิ์แอปพลิเคชัน',
requests: 'คำขอสิทธิ์', requests: 'คำขอสิทธิ์',
@@ -1664,6 +1732,22 @@ const messages = {
} }
}, },
announcement: {
title: 'การจัดการประกาศ',
subtitle: 'เผยแพร่ข่าวสารบริษัทให้ผู้ใช้ทุกคน',
add: 'เผยแพร่ประกาศ',
publish: 'เผยแพร่',
noData: 'ยังไม่มีประกาศ',
confirmDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบประกาศนี้?',
fields: {
title: 'หัวข้อ',
content: 'เนื้อหา'
},
msg: {
fillAll: 'กรุณากรอกข้อมูลให้ครบถ้วน'
}
},
// Permissions // Permissions
perm: { perm: {
title: 'สิทธิ์แอปพลิเคชัน', title: 'สิทธิ์แอปพลิเคชัน',
File diff suppressed because it is too large. Load diff
+280 -19
View File
@@ -17,6 +17,7 @@ import { Send, User, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, Rot
import { marked } from 'marked'; import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { config } from '../config'; import { config } from '../config';
import FilePreviewModal from '../components/FilePreviewModal.vue';
const { t, locale } = useI18n(); const { t, locale } = useI18n();
@@ -28,6 +29,202 @@ const renderMarkdown = (text: string) => {
return text; 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(/&amp;/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: <http://...>
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<string, SourceFileLink>();
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<string, SourceFileLink>();
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<SourceFileLink | null>(null);
const openPreview = (file: SourceFileLink) => {
previewFile.value = file;
filePreviewVisible.value = true;
};
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const agentId = Number(route.params.agentId); const agentId = Number(route.params.agentId);
@@ -56,26 +253,30 @@ const presetQuestion = computed(() => {
}); });
const getAuthHeaders = () => { const getAuthHeaders = () => {
let stored = localStorage.getItem('hxops_user'); const candidates = [
if (!stored) stored = sessionStorage.getItem('hxops_user'); sessionStorage.getItem('hxops_user'),
localStorage.getItem('hxops_user'),
if (!stored) return {}; ];
try { for (const stored of candidates) {
const data = JSON.parse(stored); if (!stored) continue;
const user = data.user || data; try {
const data = JSON.parse(stored);
const headers: Record<string, string> = { const user = data.user || data;
'X-Username': user.username, if (!user?.username || !user?.role) continue;
'X-Role': user.role, const headers: Record<string, string> = {
}; 'X-Username': user.username,
if (user.id) { 'X-Role': user.role,
headers['X-User-Id'] = String(user.id); };
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 () => {
<div v-if="history.length === 0" class="text-center text-slate-400 text-sm py-8 italic">{{ $t('chat.noHistory') }}</div> <div v-if="history.length === 0" class="text-center text-slate-400 text-sm py-8 italic">{{ $t('chat.noHistory') }}</div>
<button <button
v-for="item in history" v-for="item in history"
:key="item.id" :key="item.conversation_id"
class="w-full text-left px-4 py-3 rounded-xl text-sm text-slate-600 hover:bg-white hover:shadow-sm truncate transition-all border border-transparent hover:border-slate-100" class="w-full text-left px-4 py-3 rounded-xl text-sm text-slate-600 hover:bg-white hover:shadow-sm truncate transition-all border border-transparent hover:border-slate-100"
:class="conversationId === item.conversation_id ? 'bg-white shadow-sm border-slate-100 text-brand-600 font-medium ring-1 ring-brand-500/10' : ''" :class="conversationId === item.conversation_id ? 'bg-white shadow-sm border-slate-100 text-brand-600 font-medium ring-1 ring-brand-500/10' : ''"
@click="loadConversation(item.conversation_id); isSidebarOpen = false;" @click="loadConversation(item.conversation_id); isSidebarOpen = false;"
@@ -371,6 +572,64 @@ const submitFeedback = async () => {
v-html="renderMarkdown(msg.content)" v-html="renderMarkdown(msg.content)"
></div> ></div>
</div> </div>
<div
v-if="msg.role === 'assistant' && ((msg.retriever_resources && msg.retriever_resources.length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
class="mt-2 space-y-2"
>
<div
v-if="getMessageLinks(msg).length > 0"
class="flex flex-wrap gap-2"
>
<button
v-for="(file, linkIndex) in getMessageLinks(msg)"
:key="`src-link-top-${linkIndex}-${file.url}`"
@click="openPreview(file)"
class="text-xs px-2.5 py-1.5 rounded-lg bg-brand-50 border border-brand-200 text-brand-700 hover:bg-brand-100 transition-colors break-all"
>
{{ file.name }}
</button>
</div>
<details
v-if="msg.retriever_resources && msg.retriever_resources.length > 0"
class="bg-slate-50 border border-slate-200 rounded-xl px-4 py-3"
>
<summary class="cursor-pointer text-xs font-semibold tracking-wide text-slate-600 uppercase">
源文档 ({{ msg.retriever_resources.length }})
</summary>
<div class="mt-3 space-y-2">
<div
v-for="(doc, docIndex) in msg.retriever_resources"
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
class="bg-white border border-slate-200 rounded-lg p-3"
>
<div class="text-sm font-semibold text-slate-800 break-all">{{ getSourceTitle(doc) }}</div>
<div v-if="getSourceMeta(doc)" class="text-xs text-slate-500 mt-1">{{ getSourceMeta(doc) }}</div>
<div v-if="getSourceBrief(doc)" class="text-xs text-slate-600 mt-2 whitespace-pre-wrap break-all">{{ getSourceBrief(doc) }}</div>
</div>
</div>
</details>
<details
v-if="msg.attribution_parts && msg.attribution_parts.length > 0"
class="bg-slate-50 border border-slate-200 rounded-xl px-4 py-3"
open
>
<summary class="cursor-pointer text-xs font-semibold tracking-wide text-slate-600 uppercase">
生成内容归属部分
</summary>
<ul class="mt-3 space-y-2">
<li
v-for="(part, partIndex) in msg.attribution_parts"
:key="`attr-${partIndex}`"
class="text-xs text-slate-700 bg-white border border-slate-200 rounded-lg p-3 whitespace-pre-wrap break-all"
>
{{ part }}
</li>
</ul>
</details>
</div>
<!-- Message Actions --> <!-- Message Actions -->
<div <div
@@ -505,4 +764,6 @@ const submitFeedback = async () => {
</template> </template>
</div> </div>
</div> </div>
<FilePreviewModal v-model="filePreviewVisible" :file="previewFile" />
</template> </template>
+78 -15
View File
@@ -4,7 +4,7 @@
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent * 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口 * 引用文件: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 { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { config } from '../config'; import { config } from '../config';
@@ -29,6 +29,21 @@ import {
const { t, locale } = useI18n(); const { t, locale } = useI18n();
const router = useRouter(); 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 // Interfaces
interface Agent { interface Agent {
id: number; id: number;
@@ -73,10 +88,18 @@ const announcements = ref<Announcement[]>([]);
const quickQuestions = ref<QuickQuestion[]>([]); const quickQuestions = ref<QuickQuestion[]>([]);
const favoriteAgentIds = ref<number[]>([]); const favoriteAgentIds = ref<number[]>([]);
const embeddedAgents = ref<EmbeddedAgent[]>([]); const embeddedAgents = ref<EmbeddedAgent[]>([]);
const SECTION_TITLE_KEY_MAP: Record<string, string> = {
announcements: 'workspace.announcements.title',
favorites: 'workspace.favorites',
quick_questions: 'workspace.quickQuestions.title',
embedded: 'workspace.embedded.title',
all_agents: 'workspace.availableAgents',
};
const layoutSections = ref<LayoutSection[]>([ const layoutSections = ref<LayoutSection[]>([
{ id: 'announcements', visible: true, collapsed: false, title: 'workspace.announcements.title' },
{ id: 'favorites', visible: true, collapsed: false, title: 'workspace.favorites' }, { id: 'favorites', visible: true, collapsed: false, title: 'workspace.favorites' },
{ id: 'quick_questions', visible: true, collapsed: false, title: 'workspace.quickQuestions.title' }, { 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' }, { 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 // Methods
const getAuthHeaders = () => { const getAuthHeaders = () => {
let stored = localStorage.getItem('hxops_user'); let stored = localStorage.getItem('hxops_user');
@@ -206,24 +239,28 @@ const fetchHome = async () => {
embeddedAgents.value = data.embedded_agents || []; embeddedAgents.value = data.embedded_agents || [];
if (data.layout && data.layout.sections) { 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 = [ const defaultSections = [
{ id: 'favorites', visible: true }, { id: 'announcements', visible: true, title: getSectionTitleKey('announcements') },
{ id: 'quick_questions', visible: true }, { id: 'favorites', visible: true, title: getSectionTitleKey('favorites') },
{ id: 'embedded', visible: true }, { id: 'quick_questions', visible: true, title: getSectionTitleKey('quick_questions') },
{ id: 'all_agents', visible: true }, { id: 'embedded', visible: true, title: getSectionTitleKey('embedded') },
{ id: 'all_agents', visible: true, title: getSectionTitleKey('all_agents') },
]; ];
const merged: LayoutSection[] = []; const merged: LayoutSection[] = [];
const backendIds = new Set(backendSections.map(s => s.id)); 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 => { backendSections.forEach(s => {
const def = defaultSections.find(d => d.id === s.id); const def = defaultSections.find(d => d.id === s.id);
if (config.workspace.modules[mapKey(s.id) as keyof typeof config.workspace.modules] === false) { if (config.workspace.modules[mapKey(s.id) as keyof typeof config.workspace.modules] === false) {
return; return;
} }
merged.push({ ...def, ...s }); merged.push({ ...def, ...s, title: getSectionTitleKey(s.id) });
}); });
defaultSections.forEach(d => { defaultSections.forEach(d => {
@@ -248,10 +285,11 @@ const fetchHome = async () => {
} else { } else {
// Fallback for no layout data // Fallback for no layout data
const defaultSections = [ const defaultSections = [
{ id: 'favorites', visible: true, collapsed: false }, { id: 'announcements', visible: true, collapsed: false, title: getSectionTitleKey('announcements') },
{ id: 'quick_questions', visible: true, collapsed: false }, { id: 'favorites', visible: true, collapsed: false, title: getSectionTitleKey('favorites') },
{ id: 'embedded', visible: true, collapsed: false }, { id: 'quick_questions', visible: true, collapsed: false, title: getSectionTitleKey('quick_questions') },
{ id: 'all_agents', visible: true, collapsed: false }, { 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 => { layoutSections.value = defaultSections.filter(s => {
@@ -363,9 +401,13 @@ const handleLogin = async () => {
// Store in localStorage with 30 days expiry // Store in localStorage with 30 days expiry
const expiry = new Date().getTime() + 30 * 24 * 60 * 60 * 1000; const expiry = new Date().getTime() + 30 * 24 * 60 * 60 * 1000;
localStorage.setItem('hxops_user', JSON.stringify({ user, expiry })); localStorage.setItem('hxops_user', JSON.stringify({ user, expiry }));
// Avoid stale session user overriding current login.
sessionStorage.removeItem('hxops_user');
} else { } else {
// Store in sessionStorage (cleared when tab closed) // Store in sessionStorage (cleared when tab closed)
sessionStorage.setItem('hxops_user', JSON.stringify({ user })); sessionStorage.setItem('hxops_user', JSON.stringify({ user }));
// Avoid stale remembered user overriding current login.
localStorage.removeItem('hxops_user');
} }
await fetchHome(); await fetchHome();
@@ -570,6 +612,7 @@ const openAnnouncement = (ann: Announcement) => {
}; };
onMounted(async () => { onMounted(async () => {
loadLanguagePreference();
loadAuthUser(); loadAuthUser();
fetchAnnouncements(); fetchAnnouncements();
if (currentUser.value && currentUser.value.role !== 'guest') { if (currentUser.value && currentUser.value.role !== 'guest') {
@@ -798,14 +841,15 @@ onMounted(async () => {
<div class="flex justify-between items-center mb-6"> <div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-bold text-slate-800 flex items-center gap-2.5 cursor-pointer select-none" @click="toggleSectionCollapse(section)"> <h2 class="text-xl font-bold text-slate-800 flex items-center gap-2.5 cursor-pointer select-none" @click="toggleSectionCollapse(section)">
<div class="p-2 rounded-lg" :class="{ <div class="p-2 rounded-lg" :class="{
'bg-emerald-50 text-emerald-600': section.id === 'announcements',
'bg-yellow-50 text-yellow-600': section.id === 'favorites', 'bg-yellow-50 text-yellow-600': section.id === 'favorites',
'bg-brand-50 text-brand-600': section.id === 'quick_questions', 'bg-brand-50 text-brand-600': section.id === 'quick_questions',
'bg-purple-50 text-purple-600': section.id === 'embedded', 'bg-purple-50 text-purple-600': section.id === 'embedded',
'bg-slate-100 text-slate-600': section.id === 'all_agents' 'bg-slate-100 text-slate-600': section.id === 'all_agents'
}"> }">
<component :is="section.id === 'favorites' ? Star : (section.id === 'embedded' ? Bot : LayoutGrid)" class="w-5 h-5" /> <component :is="section.id === 'announcements' ? Megaphone : (section.id === 'favorites' ? Star : (section.id === 'embedded' ? Bot : LayoutGrid))" class="w-5 h-5" />
</div> </div>
{{ $t(section.title || section.id) }} {{ $t(getSectionTitleKey(section.id)) }}
<component :is="section.collapsed ? ChevronDown : ChevronUp" class="w-4 h-4 text-slate-400" /> <component :is="section.collapsed ? ChevronDown : ChevronUp" class="w-4 h-4 text-slate-400" />
</h2> </h2>
<!-- Actions for Quick Questions --> <!-- Actions for Quick Questions -->
@@ -815,6 +859,25 @@ onMounted(async () => {
</div> </div>
<div v-show="!section.collapsed" class="animate-fade-in"> <div v-show="!section.collapsed" class="animate-fade-in">
<!-- Content: Announcements -->
<div v-if="section.id === 'announcements'">
<div v-if="announcements.length === 0" class="text-slate-400 text-sm italic py-8 text-center bg-slate-50 rounded-xl border border-dashed border-slate-200">{{ $t('workspace.announcements.noData') }}</div>
<div v-else class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
<div
v-for="ann in announcements"
:key="ann.id"
class="group border border-slate-200 rounded-2xl bg-white p-5 hover:border-emerald-300 hover:shadow-md transition-all cursor-pointer"
@click="openAnnouncement(ann)"
>
<div class="flex items-start justify-between gap-3 mb-2">
<h4 class="font-bold text-slate-900 line-clamp-2 group-hover:text-emerald-700 transition-colors">{{ ann.title }}</h4>
<span class="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full whitespace-nowrap">{{ new Date(ann.created_at).toLocaleDateString() }}</span>
</div>
<p class="text-sm text-slate-600 line-clamp-3">{{ ann.content }}</p>
</div>
</div>
</div>
<!-- Content: Favorites --> <!-- Content: Favorites -->
<div v-if="section.id === 'favorites'"> <div v-if="section.id === 'favorites'">
<div v-if="favoriteAgents.length === 0" class="text-slate-400 text-sm italic py-4 bg-slate-50 rounded-xl text-center border border-dashed border-slate-200">{{ $t('workspace.noFavorites') }}</div> <div v-if="favoriteAgents.length === 0" class="text-slate-400 text-sm italic py-4 bg-slate-50 rounded-xl text-center border border-dashed border-slate-200">{{ $t('workspace.noFavorites') }}</div>