feat: Initial commit with full deployment architecture and scripts

This commit is contained in:
super committed 2026-02-24 16:45:11 +08:00
commit abb3efe114
96 files changed
+16789

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
# Environments
venv/
backend/venv/
env/
.env
.venv
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Python
__pycache__/
*.py[cod]
*$py.class
# Frontend
frontend/node_modules/
frontend/dist/
frontend/.DS_Store
frontend/.env.local
frontend/.env.*.local
# IDEs
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
+13
View File
@@ -0,0 +1,13 @@
# backend/Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# 使用 Gunicorn + Gevent 启动
CMD ["gunicorn", "-c", "gunicorn_config.py", "run:app"]
+38
View File
@@ -0,0 +1,38 @@
"""
backend/app/__init__.py
应用工厂
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from app.config import config
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_name='default'):
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
migrate.init_app(app, db)
CORS(app) # 允许跨域
# 注册 Blueprints
from app.api.chat import chat_bp
from app.api.admin import admin_bp
from app.api.agents import agents_bp
from app.api.user import user_bp
# 聊天相关接口
app.register_blueprint(chat_bp, url_prefix='/api/chat')
# 管理员相关接口
app.register_blueprint(admin_bp, url_prefix='/api/admin')
# 普通用户可见的 Agent 列表接口
app.register_blueprint(agents_bp, url_prefix='/api/agents')
# 当前用户相关接口(首页、常用问题等)
app.register_blueprint(user_bp, url_prefix='/api/user')
return app
+427
View File
@@ -0,0 +1,427 @@
"""
backend/app/api/admin.py
文件用途:管理员相关 API 路由
引用文件:flask, models, decorators
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
"""
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 import db
from sqlalchemy import func, desc, inspect
from datetime import datetime
import csv
import io
admin_bp = Blueprint('admin', __name__)
# --- Departments ---
@admin_bp.route('/departments', methods=['GET'])
@require_admin
def list_departments():
depts = db.session.query(Department).order_by(Department.name.asc()).all()
return jsonify([
{
'id': d.id,
'name': d.name,
'code': d.code,
'company': d.company,
'description': d.description
} for d in depts
])
@admin_bp.route('/departments', methods=['POST'])
@require_admin
def create_department():
data = request.get_json() or {}
if not data.get('name'): return jsonify({'error': 'Name is required'}), 400
if db.session.query(Department).filter_by(name=data['name']).first():
return jsonify({'error': 'Name exists'}), 400
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
return jsonify({'error': 'Code exists'}), 400
dept = Department(name=data['name'], code=data.get('code'), company=data.get('company'), description=data.get('description'))
db.session.add(dept)
db.session.commit()
return jsonify({'id': dept.id, 'name': dept.name}), 201
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
@require_admin
def update_department(id):
dept = db.session.get(Department, id)
if not dept: return jsonify({'error': 'Not found'}), 404
data = request.get_json() or {}
if 'name' in data:
if db.session.query(Department).filter(Department.name == data['name'], Department.id != id).first():
return jsonify({'error': 'Name exists'}), 400
dept.name = data['name']
if 'code' in data:
if data['code'] and db.session.query(Department).filter(Department.code == data['code'], Department.id != id).first():
return jsonify({'error': 'Code exists'}), 400
dept.code = data['code']
if 'company' in data: dept.company = data['company']
if 'description' in data: dept.description = data['description']
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/departments/<int:id>', methods=['DELETE'])
@require_admin
def delete_department(id):
dept = db.session.get(Department, id)
if dept:
db.session.delete(dept)
db.session.commit()
return jsonify({'status': 'ok'})
# --- Agents ---
@admin_bp.route('/agents', methods=['GET'])
@require_admin
def list_agents():
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
return jsonify([{
'id': a.id, 'name': a.name, 'dify_app_id': a.dify_app_id,
'dify_api_key': a.dify_api_key, 'is_active': a.is_active,
'description': a.description, 'type': a.type,
'api_base_url': a.api_base_url, 'extra_config': a.extra_config
} for a in agents])
@admin_bp.route('/agents', methods=['POST'])
@require_admin
def create_agent():
data = request.get_json() or {}
if not data.get('name'): return jsonify({'error': 'Name is required'}), 400
agent_type = data.get('type', 'api')
# 对于 API 类型,必须校验 dify_app_id
if agent_type == 'api' and not data.get('dify_app_id'):
return jsonify({'error': 'App ID is required for API agents'}), 400
agent = Agent(
name=data['name'],
dify_app_id=data.get('dify_app_id') or None, # nullable, convert empty string to None
dify_api_key=data.get('dify_api_key') or None, # nullable
description=data.get('description'),
type=agent_type,
api_base_url=data.get('api_base_url'),
extra_config=data.get('extra_config'),
is_active=data.get('is_active', True)
)
db.session.add(agent)
db.session.commit()
return jsonify({'id': agent.id}), 201
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
@require_admin
def update_agent(id):
agent = db.session.get(Agent, id)
if not agent: return jsonify({'error': 'Not found'}), 404
data = request.get_json() or {}
for k in ['name', 'dify_app_id', 'description', 'type', 'api_base_url', 'extra_config', 'is_active']:
if k in data: setattr(agent, k, data[k])
if 'dify_api_key' in data and data['dify_api_key']:
agent.dify_api_key = data['dify_api_key']
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
@require_admin
def delete_agent(id):
agent = db.session.get(Agent, id)
if agent:
db.session.delete(agent)
db.session.commit()
return jsonify({'status': 'ok'})
# --- Users ---
@admin_bp.route('/users', methods=['GET'])
@require_admin
def list_users():
users = db.session.query(User).order_by(User.id.asc()).all()
res = []
for u in users:
res.append({
'id': u.id, 'username': u.username, 'email': u.email,
'department': u.department, 'role': u.role, 'status': u.status,
'real_name': u.real_name, 'employee_id': u.employee_id, 'phone_number': u.phone_number,
'agent_ids': [a.id for a in u.agents]
})
return jsonify(res)
@admin_bp.route('/users', methods=['POST'])
@require_admin
def create_user():
data = request.get_json() or {}
if not data.get('username'): return jsonify({'error': 'Username is required'}), 400
if db.session.query(User).filter_by(username=data['username']).first():
return jsonify({'error': 'Username exists'}), 400
user = User(
username=data['username'],
email=data.get('email'),
department=data.get('department'),
role=data.get('role', 'user'),
status=data.get('status', 'active'),
real_name=data.get('real_name'),
employee_id=data.get('employee_id'),
phone_number=data.get('phone_number')
)
if data.get('password'): user.set_password(data['password'])
if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
db.session.add(user)
db.session.commit()
return jsonify({'id': user.id}), 201
@admin_bp.route('/users/<int:id>', methods=['PUT'])
@require_admin
def update_user(id):
user = db.session.get(User, id)
if not user: return jsonify({'error': 'Not found'}), 404
data = request.get_json() or {}
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
if k in data: setattr(user, k, data[k])
if data.get('password'): user.set_password(data['password'])
if 'agent_ids' in data:
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
@require_admin
def cleanup_rejected_users():
cnt = db.session.query(User).filter_by(status='rejected').delete()
db.session.commit()
return jsonify({'deleted_count': cnt})
@admin_bp.route('/users/batch-delete', methods=['POST'])
@require_admin
def batch_delete_users():
data = request.get_json() or {}
ids = data.get('user_ids', [])
current_user_id = request.headers.get('X-User-Id')
target_ids = [uid for uid in ids if str(uid) != str(current_user_id)]
if not target_ids: return jsonify({'error': 'No valid users'}), 400
cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False)
db.session.commit()
return jsonify({'deleted_count': cnt})
@admin_bp.route('/users/<int:id>/permissions', methods=['POST'])
@require_admin
def update_user_permissions(id):
user = db.session.get(User, id)
if not user: return jsonify({'error': 'Not found'}), 404
data = request.get_json() or {}
agent_ids = data.get('agent_ids', [])
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
user.agents = agents
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
@require_admin
def approve_user(id):
user = db.session.get(User, id)
if user:
user.status = 'active'
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
@require_admin
def reject_user(id):
user = db.session.get(User, id)
if user:
user.status = 'rejected'
db.session.commit()
return jsonify({'status': 'ok'})
# --- Permission Requests ---
@admin_bp.route('/permission-requests', methods=['GET'])
@require_admin
def list_permission_requests():
reqs = db.session.query(PermissionRequest).order_by(PermissionRequest.created_at.desc()).all()
return jsonify([{
'id': r.id, 'user_id': r.user_id, 'agent_id': r.agent_id,
'reason': r.reason, 'status': r.status, 'created_at': r.created_at.isoformat()
} for r in reqs])
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
@require_admin
def approve_request(id):
req = db.session.get(PermissionRequest, id)
if not req: return jsonify({'error': 'Not found'}), 404
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
# Grant permission
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if user and agent and agent not in user.agents:
user.agents.append(agent)
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
@require_admin
def reject_request(id):
req = db.session.get(PermissionRequest, id)
if not req: return jsonify({'error': 'Not found'}), 404
req.status = 'rejected'
req.reviewed_at = datetime.utcnow()
db.session.commit()
return jsonify({'status': 'ok'})
# --- Quick Questions (Common Questions) ---
@admin_bp.route('/quick-questions', methods=['GET'])
@require_admin
def list_quick_questions():
# Only return global questions (user_id is NULL)
qqs = db.session.query(QuickQuestion).filter(QuickQuestion.user_id == None).order_by(QuickQuestion.sort_order.asc()).all()
res = []
for q in qqs:
agent = db.session.get(Agent, q.agent_id)
res.append({
'id': q.id,
'title': q.title,
'question': q.question,
'agent_id': q.agent_id,
'agent_name': agent.name if agent else 'Unknown',
'sort_order': q.sort_order
})
return jsonify(res)
@admin_bp.route('/quick-questions', methods=['POST'])
@require_admin
def create_quick_question():
data = request.get_json() or {}
if not data.get('title') or not data.get('question') or not data.get('agent_id'):
return jsonify({'error': 'Missing required fields'}), 400
qq = QuickQuestion(
user_id=None, # Global
agent_id=data['agent_id'],
title=data['title'],
question=data['question'],
sort_order=data.get('sort_order', 0)
)
db.session.add(qq)
db.session.commit()
return jsonify({'id': qq.id}), 201
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
@require_admin
def update_quick_question(id):
qq = db.session.get(QuickQuestion, id)
if not qq: return jsonify({'error': 'Not found'}), 404
data = request.get_json() or {}
if 'title' in data: qq.title = data['title']
if 'question' in data: qq.question = data['question']
if 'agent_id' in data: qq.agent_id = data['agent_id']
if 'sort_order' in data: qq.sort_order = data['sort_order']
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/quick-questions/<int:id>', methods=['DELETE'])
@require_admin
def delete_quick_question(id):
qq = db.session.get(QuickQuestion, id)
if qq:
db.session.delete(qq)
db.session.commit()
return jsonify({'status': 'ok'})
# --- Reports ---
@admin_bp.route('/reports/usage', methods=['GET'])
@require_admin
def usage_report():
total = db.session.query(ChatLog).count()
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
return jsonify({
'total': total,
'by_user': [{'username': u, 'count': c} for u, c in by_user],
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]
})
@admin_bp.route('/reports/feedback', methods=['GET'])
@require_admin
def feedback_report():
total = db.session.query(Feedback).count()
avg = db.session.query(func.avg(Feedback.score)).scalar() or 0
dist = db.session.query(Feedback.score, func.count(Feedback.id)).group_by(Feedback.score).all()
return jsonify({
'total': total,
'avg_score': float(avg),
'distribution': [{'score': s, 'count': c} for s, c in dist]
})
# --- Database ---
@admin_bp.route('/database/<table>', methods=['GET'])
@require_admin
def get_table_data(table):
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
# Build query
query = db.session.query(model)
# Handle filters
for k, v in request.args.items():
if hasattr(model, k):
col = getattr(model, k)
query = query.filter(col.cast(db.String).ilike(f"%{v}%"))
# Use db.session.query instead of model.query to avoid ChatLog.query conflict
items = query.limit(100).all()
res = []
for item in items:
d = {}
for col in item.__table__.columns:
val = getattr(item, col.name)
if isinstance(val, datetime):
val = val.isoformat()
d[col.name] = val
res.append(d)
return jsonify(res)
+42
View File
@@ -0,0 +1,42 @@
"""
backend/app/api/agents.py
文件用途:普通用户可见的 Agent 列表接口
引用文件:flask, models, decorators
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
"""
from flask import Blueprint, jsonify, g
from app.models import Agent, User
from app.decorators import _get_current_user # 内部工具函数
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
@agents_bp.route('', methods=['GET'])
def list_user_agents():
"""
获取当前用户可见的 Agent 列表
用途:Workspace 页面展示应用网格
"""
# 获取当前用户(目前固定为 admin 用户,用于演示)
user: User = _get_current_user()
# 管理员:返回所有激活的 Agent
if user.role == 'admin':
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
else:
# 普通用户:仅返回多对多关系中已授权的 Agent
agents = [a for a in user.agents if a.is_active]
# 序列化为前端所需字段
data = [
{
'id': a.id,
'name': a.name,
'description': a.description,
'icon_url': a.icon_url,
}
for a in agents
]
return jsonify(data)
+195
View File
@@ -0,0 +1,195 @@
"""
backend/app/api/chat.py
文件用途:定义聊天相关 API 路由
引用文件:flask, services.dify, decorators, models
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
"""
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
from sqlalchemy import func, desc
from app.services.dify import DifyService
from app.decorators import require_agent_permission
from app.models import Agent, ChatLog, Feedback
from app import db
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
chat_bp = Blueprint('chat', __name__)
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
def get_chat_sessions():
"""
获取当前用户与当前 Agent 的历史会话列表
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500
# 聚合查询:按 conversation_id 分组,获取最新时间
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
# 更严谨的做法是先查出 conversation_ids,再查详情。
# 这里为了简单,我们假设 query 不为空
# 修正逻辑:先查出最近的 20 个 conversation_id
subquery = db.session.query(
ChatLog.conversation_id,
func.max(ChatLog.created_at).label('last_active')
).filter_by(
user_id=user.id,
agent_id=agent.id
).group_by(ChatLog.conversation_id).subquery()
# 联表查询获取详细信息,按时间倒序
results = db.session.query(
subquery.c.conversation_id,
subquery.c.last_active,
ChatLog.query
).join(
ChatLog,
(ChatLog.conversation_id == subquery.c.conversation_id) &
(ChatLog.created_at == subquery.c.last_active)
).order_by(desc(subquery.c.last_active)).limit(20).all()
sessions = []
for row in results:
if not row.conversation_id:
continue
sessions.append({
'id': 0, # 前端需要 id key
'conversation_id': row.conversation_id,
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
'created_at': row.last_active.isoformat()
})
return jsonify(sessions)
@chat_bp.route('/messages', methods=['GET'])
@require_agent_permission
def get_chat_messages():
"""
获取指定会话的消息记录
"""
conversation_id = request.args.get('conversation_id')
if not conversation_id:
return jsonify([])
logs = ChatLog.query.filter_by(
conversation_id=conversation_id
).order_by(ChatLog.created_at.asc()).all()
messages = []
for log in logs:
messages.append({'role': 'user', 'content': log.query})
messages.append({'role': 'assistant', 'content': log.answer})
return jsonify(messages)
@chat_bp.route('/completions', methods=['POST'])
@require_agent_permission
def chat_completions():
"""
SSE 流式聊天接口
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
核心逻辑:
1. 从请求体中读取 query / agent_id / conversation_id
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
传入参数:
无(从 request.json 读取)
返回值:
Flask Response 对象,mimetype=text/event-stream
"""
# 解析 JSON 请求体
data = request.get_json() or {}
# 提取用户提问内容
query = data.get('query')
# 提取会话 ID(可选)
conversation_id = data.get('conversation_id')
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
# 安全兜底:如果装饰器未正确注入,返回错误
if user is None or agent is None:
return jsonify({'error': 'Missing user or agent context'}), 500
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
stream_with_context(
DifyService.stream_chat(query, user.id, agent, conversation_id)
),
mimetype='text/event-stream',
headers={
'Cache-Control': 'no-cache',
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
'X-Accel-Buffering': 'no'
}
)
@chat_bp.route('/feedback', methods=['POST'])
@require_agent_permission
def submit_feedback():
"""
提交对回答的评分与评论
用途:在对话结束后,由前端发送评分(1~5)和文字意见
核心逻辑:
1. 从请求体中读取 score/comment/conversation_id
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
3. 为该 ChatLog 创建或更新 Feedback 记录
"""
data = request.get_json() or {}
score = data.get('score')
comment = data.get('comment') or ''
conversation_id = data.get('conversation_id')
if not current_app.config.get('FEEDBACK_ENABLED', True):
return jsonify({'error': 'feedback is disabled'}), 403
if score is None:
return jsonify({'error': 'score is required'}), 400
try:
score_value = int(score)
except (TypeError, ValueError):
return jsonify({'error': 'score must be an integer'}), 400
if score_value < 1 or score_value > 5:
return jsonify({'error': 'score must be between 1 and 5'}), 400
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
if user is None or agent is None:
return jsonify({'error': 'Missing user or agent context'}), 500
# 构造查询:限定在当前用户和 Agent 范围内
query = ChatLog.query.filter_by(user_id=user.id, agent_id=agent.id)
if conversation_id:
query = query.filter_by(conversation_id=conversation_id)
# 取最新一条对话日志
chat_log = query.order_by(ChatLog.created_at.desc()).first()
if not chat_log:
return jsonify({'error': 'ChatLog not found'}), 404
# 如果已存在反馈,则更新;否则新建
if chat_log.feedback:
chat_log.feedback.score = score_value
chat_log.feedback.comment = comment
else:
fb = Feedback(
chat_log_id=chat_log.id,
score=score_value,
comment=comment,
)
db.session.add(fb)
db.session.commit()
return jsonify({'status': 'ok'})
+191
View File
@@ -0,0 +1,191 @@
"""
backend/app/api/user.py
文件用途:用户相关 API 路由
引用文件:flask, models, decorators
逻辑关系:提供用户登录、首页配置、收藏夹、常用问题等接口
"""
from flask import Blueprint, jsonify, request, g, current_app
from app import db
from app.models import User, Agent, UserFavoriteAgent, UserHomepageConfig, QuickQuestion, UserDefaultAgent
from app.decorators import _get_current_user
user_bp = Blueprint('user', __name__)
@user_bp.route('/login', methods=['POST'])
def login():
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
return jsonify({
'id': user.id,
'username': user.username,
'role': user.role,
'token': 'dummy-token' # In real app use JWT
})
return jsonify({'error': 'Invalid credentials'}), 401
@user_bp.route('/home', methods=['GET'])
def get_user_home():
user = _get_current_user()
# Favorites
favorites = db.session.query(Agent).join(UserFavoriteAgent).filter(UserFavoriteAgent.user_id == user.id).all()
favorite_ids = [a.id for a in favorites]
# Layout
config = UserHomepageConfig.query.get(user.id)
layout = config.layout if config else {}
# Embedded agents
embedded_agents = []
udas = UserDefaultAgent.query.filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
for uda in udas:
agent = Agent.query.get(uda.agent_id)
if agent:
embedded_agents.append({
'id': agent.id,
'name': agent.name,
'icon_url': agent.icon_url,
'description': agent.description
})
# Quick questions
qqs = QuickQuestion.query.filter_by(user_id=user.id).all()
quick_questions = [{
'id': q.id,
'title': q.title,
'question': q.question,
'agent_id': q.agent_id
} for q in qqs]
# All active agents (for selection)
all_agents = Agent.query.filter_by(is_active=True).all()
agents_list = [{
'id': a.id,
'name': a.name
} for a in all_agents]
return jsonify({
'user': {
'id': user.id,
'username': user.username,
'role': user.role,
'real_name': user.real_name,
'department': user.department
},
'favorite_agent_ids': favorite_ids,
'layout': layout,
'embedded_agents': embedded_agents,
'quick_questions': quick_questions,
'agents': agents_list
})
@user_bp.route('/agents/<int:agent_id>', methods=['GET'])
def get_agent_details(agent_id):
"""
获取单个 Agent 详情
"""
user = _get_current_user()
agent = Agent.query.get(agent_id)
if not agent:
return jsonify({'error': 'Agent not found'}), 404
# Check permission (optional, but good practice)
# For now, allow if active or user is admin
if not agent.is_active and user.role != 'admin':
return jsonify({'error': 'Agent is not active'}), 403
return jsonify({
'id': agent.id,
'name': agent.name,
'description': agent.description,
'icon_url': agent.icon_url,
'type': agent.type,
'extra_config': agent.extra_config
})
@user_bp.route('/config', methods=['GET'])
def get_user_config():
"""
获取用户/系统配置
"""
user = _get_current_user()
return jsonify({
'feedback_enabled': current_app.config.get('FEEDBACK_ENABLED', True)
})
@user_bp.route('/favorites/<int:agent_id>', methods=['POST'])
def add_favorite(agent_id):
user = _get_current_user()
if not UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first():
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
db.session.add(fav)
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/favorites/<int:agent_id>', methods=['DELETE'])
def remove_favorite(agent_id):
user = _get_current_user()
fav = UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first()
if fav:
db.session.delete(fav)
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/homepage-layout', methods=['PUT'])
def update_layout():
user = _get_current_user()
data = request.get_json() or {}
config = UserHomepageConfig.query.get(user.id)
if not config:
config = UserHomepageConfig(user_id=user.id)
db.session.add(config)
config.layout = data.get('layout', {})
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/embedded-agents', methods=['PUT'])
def update_embedded_agents():
user = _get_current_user()
data = request.get_json() or {}
agent_ids = data.get('agent_ids', [])
if len(agent_ids) > 2:
return jsonify({'error': 'Max 2 embedded agents'}), 400
# Clear existing
UserDefaultAgent.query.filter_by(user_id=user.id).delete()
for i, aid in enumerate(agent_ids):
uda = UserDefaultAgent(user_id=user.id, agent_id=aid, sort_order=i)
db.session.add(uda)
db.session.commit()
return jsonify({'status': 'ok'})
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT'])
def update_quick_question(qq_id: int):
"""
更新常用问题
"""
user = _get_current_user()
data = request.get_json() or {}
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
if not qq:
return jsonify({"error": "QuickQuestion not found"}), 404
if 'title' in data:
qq.title = data['title']
if 'question' in data:
qq.question = data['question']
if 'agent_id' in data:
qq.agent_id = data['agent_id']
db.session.commit()
return jsonify({"status": "ok"})
+56
View File
@@ -0,0 +1,56 @@
"""
backend/app/config.py
配置类,区分开发/生产环境
"""
import os
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key')
# 数据库连接池配置
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': 20,
'max_overflow': 10,
'pool_recycle': 3600,
'pool_pre_ping': True
}
# Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
# Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL', 'redis://:difyai123456@localhost:6379/0')
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
HR_WORKFLOW_IFRAME_URL = os.getenv(
'HR_WORKFLOW_IFRAME_URL',
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
)
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
class DevelopmentConfig(Config):
DEBUG = True
# 本地 MacBook PostgreSQL 配置(数据库: hxops_db,用户: postgres, 密码: difyai123456)
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
'postgresql://postgres:difyai123456@localhost:5432/hxops_db'
)
class ProductionConfig(Config):
DEBUG = False
# 服务器 Ubuntu PostgreSQL 配置
# 注意:在服务器上通过环境变量覆盖,但此处保留默认模板
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://postgres:difyai123456@localhost:5432/hxops_prod')
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
+138
View File
@@ -0,0 +1,138 @@
"""
backend/app/decorators.py
文件用途:权限控制装饰器集合
引用文件:flask, functools, models, db
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
"""
from functools import wraps
from flask import request, jsonify, g
from app import db
from app.models import Agent, User
def _get_current_user() -> User:
"""
内部工具函数:获取当前登录用户
支持从请求头识别用户并创建用户,读取 X-User-Id / X-Username / X-Role。
"""
user_id = request.headers.get('X-User-Id')
username = request.headers.get('X-Username')
role = request.headers.get('X-Role', 'user')
user = None
if user_id:
try:
user = User.query.get(int(user_id))
except ValueError:
user = None
if user is None and username:
user = User.query.filter_by(username=username).first()
if not user:
if user_id:
safe_id = int(user_id)
user = User(
id=safe_id,
username=username or f'user_{safe_id}',
email=f'{username or f"user_{safe_id}"}@example.com',
department='IT',
role=role,
)
db.session.add(user)
db.session.commit()
elif username:
user = User(
username=username,
email=f'{username}@example.com',
department='IT',
role=role,
)
db.session.add(user)
db.session.commit()
else:
# Check if guest user exists
user = User.query.filter_by(username='guest').first()
if not user:
user = User(
username='guest',
email='guest@example.com',
department='',
role='guest',
)
db.session.add(user)
db.session.commit()
g.current_user = user
return user
def require_agent_permission(f):
"""
装饰器:检查当前用户是否有指定 Agent 的访问权限
核心逻辑:
1. 从请求体中读取 agent_id
2. 获取当前用户 (临时固定为 ID=1)
3. 如果用户是 admin,则放行
4. 否则检查 user.agents 是否包含该 agent
传入参数:
f: 被装饰的视图函数
返回值:
包装后的视图函数
"""
@wraps(f)
def decorated_function(*args, **kwargs):
# 从 JSON 请求体中解析数据
data = request.get_json() or {}
# 获取 agent_id
agent_id = data.get('agent_id')
# 如果未提供 agent_id,则返回 400 错误
if not agent_id:
return jsonify({'error': 'agent_id is required'}), 400
# 获取当前用户(此处固定为 admin 用户,用于演示)
user = _get_current_user()
# 查询目标 Agent 是否存在
agent = Agent.query.get(agent_id)
if not agent:
return jsonify({'error': 'Agent not found'}), 404
# 将 agent 对象挂在 g 上,方便下游使用
g.current_agent = agent
# 如果用户是管理员,跳过权限检查直接放行
if user.role == 'admin':
return f(*args, **kwargs)
# 非管理员:检查多对多关联表中是否存在权限
if agent not in user.agents:
return jsonify({'error': 'Permission denied for this agent'}), 403
# 鉴权通过,调用原始视图函数
return f(*args, **kwargs)
return decorated_function
def require_admin(f):
"""
装饰器:限制只有管理员角色才能访问的接口
核心逻辑:
1. 获取当前用户
2. 判断 user.role 是否为 'admin'
"""
@wraps(f)
def decorated_function(*args, **kwargs):
# 获取当前用户(自动创建 admin)
user = _get_current_user()
# 如果不是管理员,则返回 403
if user.role != 'admin':
return jsonify({'error': 'Admin privilege required'}), 403
# 是管理员则放行
return f(*args, **kwargs)
return decorated_function
+237
View File
@@ -0,0 +1,237 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app import db
class Base(db.Model):
"""
基础模型类,设置为抽象基类
"""
__abstract__ = True
# RBAC 关联表:用户与 Agent 的多对多关系
# 用于存储用户拥有哪些 Agent 的访问权限
user_agent_permissions = db.Table(
'user_agent_permissions',
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True)
)
from werkzeug.security import generate_password_hash, check_password_hash
class ZlLanguage(Base):
"""
多语言配置表
用途:存储系统支持的语言列表
"""
__tablename__ = 'zl_languages'
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(10), unique=True) # en, zh-CN, zh-TW, th
name: Mapped[str] = mapped_column(String(50)) # English, 简体中文, ...
is_active: Mapped[bool] = mapped_column(default=True)
class Department(Base):
"""
部门表
用途:存储公司部门列表
"""
__tablename__ = 'departments'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100), unique=True)
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True) # 部门编号
company: Mapped[Optional[str]] = mapped_column(String(100)) # 所属公司
description: Mapped[Optional[str]] = mapped_column(Text)
class UserHomepageConfig(Base):
"""
用户首页配置表
用途:存储用户自定义的首页布局与配置
"""
__tablename__ = 'user_homepage_configs'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
layout: Mapped[dict] = mapped_column(JSON, default={}) # 存储模块布局配置
# 示例: { "modules": [{"id": "favorites", "x": 0, "y": 0}, {"id": "agents", "x": 0, "y": 1}] }
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class UserFavoriteAgent(Base):
"""
用户收藏 Agent 表
用途:存储用户收藏的 Agent
"""
__tablename__ = 'user_favorite_agents'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class UserDefaultAgent(Base):
"""
用户默认 Agent 表 (嵌入首页)
用途:存储用户设置的默认嵌入 Agent (最多2个)
"""
__tablename__ = 'user_default_agents'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
sort_order: Mapped[int] = mapped_column(default=0) # 排序,0为第一个,1为第二个
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class User(Base):
"""
用户表
用途:存储系统用户信息
核心逻辑:包含部门、角色等字段,关联 Agent 权限
"""
__tablename__ = 'users'
# 主键 ID
id: Mapped[int] = mapped_column(primary_key=True)
# 用户名,唯一且带索引
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
# 邮箱,唯一
email: Mapped[str] = mapped_column(String(100), unique=True)
# 部门信息
department: Mapped[Optional[str]] = mapped_column(String(100))
# 角色:admin 或 user
role: Mapped[str] = mapped_column(String(20), default='user')
# 账号状态:active (正常), pending (待审批), disabled (禁用)
status: Mapped[str] = mapped_column(String(20), default='active')
# 密码哈希
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
# 首选语言
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
# 真实姓名
real_name: Mapped[Optional[str]] = mapped_column(String(50))
# 公司工号,唯一
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
# 手机号,唯一
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
# 默认嵌入的 Agent ID (忽略权限检查)
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
# 关系:用户拥有的 Agent 权限 (多对多)
agents: Mapped[List["Agent"]] = relationship(
secondary=user_agent_permissions,
back_populates="users"
)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
if not self.password_hash:
return False
return check_password_hash(self.password_hash, password)
class Agent(Base):
"""
AI 应用配置表
用途:存储接入的 Dify Agent 配置信息
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
"""
__tablename__ = 'agents'
id: Mapped[int] = mapped_column(primary_key=True)
# 应用名称
name: Mapped[str] = mapped_column(String(100))
# 应用描述
description: Mapped[Optional[str]] = mapped_column(Text)
# 图标 URL
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
# Dify 配置:App ID (唯一,对于 iframe 模式可选)
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
# Dify 配置:API Key (实际生产应加密存储,对于 iframe 模式可选)
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
# 类型:api (默认) 或 iframe
type: Mapped[str] = mapped_column(String(20), default='api')
# 自定义 API Base URL (覆盖全局配置)
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
# 额外配置 (JSON),用于存储 iframe_url 等
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
# 是否激活
is_active: Mapped[bool] = mapped_column(default=True)
# 创建时间
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# 关系:拥有该应用权限的用户 (多对多)
users: Mapped[List["User"]] = relationship(
secondary=user_agent_permissions,
back_populates="agents"
)
class ChatLog(Base):
"""
对话日志表
用途:存储用户与 Agent 的对话记录
"""
__tablename__ = 'chat_logs'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
query: Mapped[str] = mapped_column(Text)
answer: Mapped[str] = mapped_column(Text)
latency: Mapped[float] = mapped_column(default=0.0) # 响应耗时
conversation_id: Mapped[Optional[str]] = mapped_column(String(100)) # Dify 会话 ID
tokens_used: Mapped[Optional[int]] = mapped_column(Integer, default=0) # 消耗 token 数
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
# 关联 Feedback
feedback: Mapped[Optional["Feedback"]] = relationship(back_populates="chat_log", uselist=False)
class Feedback(Base):
"""
反馈表
用途:存储用户对回答的评分与评价
"""
__tablename__ = 'feedbacks'
id: Mapped[int] = mapped_column(primary_key=True)
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
score: Mapped[int] = mapped_column(Integer) # 1-5
comment: Mapped[Optional[str]] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
class PermissionRequest(Base):
"""
权限申请表
用途:存储用户的权限申请记录
"""
__tablename__ = 'permission_requests'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
reason: Mapped[str] = mapped_column(Text)
status: Mapped[str] = mapped_column(String(20), default='pending') # pending, approved, rejected
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
class QuickQuestion(Base):
"""
常用问题表
用途:存储用户自定义的常用问题
"""
__tablename__ = 'quick_questions'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
title: Mapped[str] = mapped_column(String(100))
question: Mapped[str] = mapped_column(Text)
sort_order: Mapped[int] = mapped_column(default=0)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
+137
View File
@@ -0,0 +1,137 @@
"""
backend/app/services/dify.py
文件用途:Dify API 集成服务
引用文件:requests, json, models, config
逻辑关系:负责与 Dify 平台进行 HTTP 通信,处理 SSE 流式响应,并记录审计日志
"""
import requests
import json
import time
from flask import current_app
from app.models import ChatLog, db
from app.config import Config
class DifyService:
"""
Dify 服务类
用途:封装与 Dify API 的交互逻辑
"""
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
"""
生成器函数:向 Dify 发起请求并流式返回
用途:处理 /v1/chat-messages 接口的流式响应
核心逻辑:
1. 构造请求头与 Payload
2. 使用 requests.post(stream=True) 发起请求
3. 逐行读取 SSE 数据
4. 解析 'data: ' 开头的行,透传给前端
5. 在 'message_end' 事件中记录完整日志到数据库
参数:
query: 用户提问内容
user_id: 当前用户 ID
agent: Agent 模型对象,包含 API Key
conversation_id: 会话 ID (可选)
输出:
Yields SSE 格式字符串 "data: {...}\n\n"
"""
# 使用 Agent 自定义的 API Base URL,若未配置则使用全局配置
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
# 移除末尾斜杠以避免双斜杠问题
base_url = base_url.rstrip('/')
url = f"{base_url}/chat-messages"
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
'Content-Type': 'application/json'
}
payload = {
"inputs": {},
"query": query,
"response_mode": "streaming",
"conversation_id": conversation_id,
"user": str(user_id)
}
# 记录开始时间,用于计算耗时
start_time = time.time()
# 用于收集流式片段拼接完整回答
full_answer = []
try:
# stream=True 关键参数,建立长连接
# 设置连接超时为 5 秒,读取超时为 60 秒
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
response.raise_for_status()
# 逐行迭代响应内容
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
# 识别 SSE 数据行
if decoded_line.startswith('data: '):
json_str = decoded_line[6:]
try:
data = json.loads(json_str)
event = data.get('event')
# 核心:将 Dify 的原始数据透传给前端
yield f"data: {json_str}\n\n"
# 收集完整回答用于日志
if event == 'message':
full_answer.append(data.get('answer', ''))
elif event == 'message_end':
# 对话结束,记录日志
# 异步或在此处记录日志(为了演示简单,此处同步记录,生产环境建议放入 Celery/RQ)
latency = int((time.time() - start_time) * 1000)
metadata = data.get('metadata', {})
usage = metadata.get('usage', {})
# 创建日志条目
# 注意:在生成器中操作 DB 需要确保应用上下文存在
DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id'),
query=query,
answer="".join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency
)
except json.JSONDecodeError:
continue
else:
# 处理 keep-alive 等其他行
pass
except requests.exceptions.RequestException as e:
# 异常处理:返回标准错误格式给前端
error_msg = json.dumps({"event": "error", "message": str(e)})
yield f"data: {error_msg}\n\n"
@staticmethod
def _log_chat(user_id, agent_id, conversation_id, query, answer, tokens, latency):
"""
内部方法:写入数据库日志
用途:将对话详情持久化到 ChatLog 表
"""
try:
# 确保在应用上下文中(Flask stream_with_context 会保持上下文)
chat_log = ChatLog(
user_id=user_id,
agent_id=agent_id,
conversation_id=conversation_id,
query=query,
answer=answer,
tokens_used=tokens,
latency=latency
)
db.session.add(chat_log)
db.session.commit()
except Exception as e:
current_app.logger.error(f"Failed to log chat: {e}")
db.session.rollback()
+9
View File
@@ -0,0 +1,9 @@
from app import create_app, db
from app.models import User
app = create_app()
with app.app_context():
users = User.query.all()
for u in users:
print(f"ID: {u.id}, User: {u.username}, Role: {u.role}")
+40
View File
@@ -0,0 +1,40 @@
"""
gunicorn_config.py
Gunicorn 生产环境配置文件
"""
import multiprocessing
import os
# 绑定地址
bind = "127.0.0.1:5000"
# 工作模式
# 使用 gevent 处理高并发和长连接 (SSE)
worker_class = "gevent"
# 进程数
# 公式: 2 * CPU核心数 + 1
workers = multiprocessing.cpu_count() * 2 + 1
# 每个 Worker 的最大并发连接数
worker_connections = 1000
# 超时设置 (秒)
# SSE 流式响应通常需要较长的超时时间
timeout = 120
keepalive = 5
# 日志
accesslog = "/var/log/hxops/access.log"
errorlog = "/var/log/hxops/error.log"
loglevel = "info"
# 守护进程模式 (由 Supervisor 管理时通常设为 False)
daemon = False
# 进程名称
proc_name = "hxops_backend"
# 预加载应用 (加快启动速度)
preload_app = True
+26
View File
@@ -0,0 +1,26 @@
from app import create_app, db
from app.models import User
app = create_app()
with app.app_context():
# Check for admin user
admin = User.query.filter_by(username='admin').first()
if admin:
print(f"Found admin user. Current role: {admin.role}")
if admin.role != 'admin':
admin.role = 'admin'
db.session.commit()
print("Updated admin user role to 'admin'")
else:
print("Admin user not found. Creating...")
admin = User(username='admin', email='admin@example.com', role='admin')
admin.set_password('Hxit@54321')
db.session.add(admin)
db.session.commit()
print("Created admin user with role 'admin'")
# Also check if there are other users that should be admin but aren't
users = User.query.all()
for u in users:
print(f"User: {u.username}, Role: {u.role}")
+28
View File
@@ -0,0 +1,28 @@
"""
backend/gunicorn_config.py
生产环境 Gunicorn 配置 (支持高并发)
"""
import multiprocessing
# 绑定地址
bind = "0.0.0.0:8000"
# 核心:使用 Gevent 异步 Worker
worker_class = "gevent"
# Worker 数量:通常 CPU 核数 * 2 + 1
workers = multiprocessing.cpu_count() * 2 + 1
# 核心:每个 Worker 最大并发连接数
# Gevent 下这个值可以设置得很高,支持海量 SSE 连接
worker_connections = 2000
# 超时设置 (SSE 长连接需要较长超时)
timeout = 120
keepalive = 5
# 日志
accesslog = "-"
errorlog = "-"
loglevel = "info"
+108
View File
@@ -0,0 +1,108 @@
"""
backend/init_db.py
文件用途:初始化 PostgreSQL 数据库 hxops_db 并创建所有表
引用文件:psycopg2, urllib.parse, app
逻辑关系:
1. 从配置中解析 SQLALCHEMY_DATABASE_URI
2. 连接 postgres 系统库,检查 hxops_db 是否存在,不存在则创建
3. 使用 Flask 应用上下文调用 db.create_all() 创建所有表结构
使用方式:
在项目根目录下执行:
cd backend
python init_db.py
"""
import urllib.parse
import psycopg2
from app import create_app, db
from app.config import DevelopmentConfig
def _parse_db_url(url: str):
"""
解析 SQLAlchemy 风格的数据库 URL
输入示例: postgresql://user:password@localhost:5432/hxops_db
输出:字典包含 user/password/host/port/dbname
"""
# 使用 urllib.parse 解析 URL
parsed = urllib.parse.urlparse(url)
# 从 netloc 中解析用户名和密码
if parsed.username:
user = urllib.parse.unquote(parsed.username)
else:
user = 'postgres'
if parsed.password:
password = urllib.parse.unquote(parsed.password)
else:
password = ''
host = parsed.hostname or 'localhost'
port = parsed.port or 5432
# 去掉路径前导斜杠得到数据库名
dbname = parsed.path.lstrip('/') or 'postgres'
return {
'user': user,
'password': password,
'host': host,
'port': port,
'dbname': dbname,
}
def ensure_database():
"""
确保 hxops_db 数据库存在
核心逻辑:
1. 解析 DevelopmentConfig.SQLALCHEMY_DATABASE_URI
2. 使用 psycopg2 连接到 postgres 系统数据库
3. 查询 pg_database,如果不存在则执行 CREATE DATABASE
"""
# 从开发配置中获取数据库 URL
url = DevelopmentConfig.SQLALCHEMY_DATABASE_URI
info = _parse_db_url(url)
target_db = info['dbname']
# 连接系统数据库 postgres
conn = psycopg2.connect(
dbname='postgres',
user=info['user'],
password=info['password'],
host=info['host'],
port=info['port'],
)
conn.autocommit = True
try:
cur = conn.cursor()
# 查询目标数据库是否已存在
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (target_db,))
exists = cur.fetchone() is not None
if not exists:
# 创建数据库
cur.execute(f'CREATE DATABASE "{target_db}"')
print(f'Created database {target_db}')
else:
print(f'Database {target_db} already exists')
cur.close()
finally:
conn.close()
def create_tables():
"""
在 hxops_db 中创建所有表结构
核心逻辑:
1. 创建 Flask 应用实例
2. 在应用上下文中调用 db.create_all()
"""
app = create_app('development')
with app.app_context():
db.create_all()
print('All tables created in hxops_db')
if __name__ == '__main__':
# 第一步:确保数据库存在
ensure_database()
# 第二步:创建所有表
create_tables()
+55
View File
@@ -0,0 +1,55 @@
from app import create_app, db
from app.models import Agent
import uuid
app = create_app()
with app.app_context():
# 1. 方式一:嵌入到网站中 (Iframe)
# <iframe src=" http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg " style="width: 100%; height: 100%; min-height: 700px" frameborder="0" allow="microphone"> </iframe>
agent_iframe = Agent.query.filter_by(name='人事规章(网页版)').first()
if not agent_iframe:
agent_iframe = Agent(
name='人事规章(网页版)',
description='嵌入式人事规章助手',
dify_app_id=str(uuid.uuid4()), # Placeholder unique ID
dify_api_key='placeholder',
type='iframe',
extra_config={'iframe_url': 'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'},
icon_url='ri-article-line'
)
db.session.add(agent_iframe)
print("Added Iframe Agent")
else:
agent_iframe.type = 'iframe'
agent_iframe.extra_config = {'iframe_url': 'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'}
agent_iframe.icon_url = 'ri-article-line'
print("Updated Iframe Agent")
# 2. 方式二:API
# 基础URL: http://127.0.0.1:5001/v1
# API密钥:app-xdiejQibWQy8ZQWXcdxJjS9I
agent_api = Agent.query.filter_by(name='人事规章(API版)').first()
if not agent_api:
agent_api = Agent(
name='人事规章(API版)',
description='API调用人事规章助手',
dify_app_id=str(uuid.uuid4()), # Placeholder unique ID
dify_api_key='app-xdiejQibWQy8ZQWXcdxJjS9I',
type='api',
api_base_url='http://127.0.0.1:5001/v1',
icon_url='ri-robot-line'
)
db.session.add(agent_api)
print("Added API Agent")
else:
agent_api.type = 'api'
agent_api.dify_api_key = 'app-xdiejQibWQy8ZQWXcdxJjS9I'
agent_api.api_base_url = 'http://127.0.0.1:5001/v1'
agent_api.icon_url = 'ri-robot-line'
print("Updated API Agent")
db.session.commit()
+15
View File
@@ -0,0 +1,15 @@
"""
backend/manage.py
数据库迁移管理脚本
"""
from app import create_app, db
from flask_migrate import Migrate
app = create_app('development')
migrate = Migrate(app, db)
if __name__ == '__main__':
# 仅作为 CLI 入口
# 使用: flask --app manage db init/migrate/upgrade
pass
+1
View File
@@ -0,0 +1 @@
Single-database configuration for Flask.
+50
View File
@@ -0,0 +1,50 @@
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+113
View File
@@ -0,0 +1,113 @@
import logging
from logging.config import fileConfig
from flask import current_app
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
def get_engine():
try:
# this works with Flask-SQLAlchemy<3 and Alchemical
return current_app.extensions['migrate'].db.get_engine()
except (TypeError, AttributeError):
# this works with Flask-SQLAlchemy>=3
return current_app.extensions['migrate'].db.engine
def get_engine_url():
try:
return get_engine().url.render_as_string(hide_password=False).replace(
'%', '%%')
except AttributeError:
return str(get_engine().url).replace('%', '%%')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
config.set_main_option('sqlalchemy.url', get_engine_url())
target_db = current_app.extensions['migrate'].db
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def get_metadata():
if hasattr(target_db, 'metadatas'):
return target_db.metadatas[None]
return target_db.metadata
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=get_metadata(), literal_binds=True
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
conf_args = current_app.extensions['migrate'].configure_args
if conf_args.get("process_revision_directives") is None:
conf_args["process_revision_directives"] = process_revision_directives
connectable = get_engine()
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=get_metadata(),
**conf_args
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+24
View File
@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
@@ -0,0 +1,34 @@
"""add phone_number to user
Revision ID: 08f34c125a73
Revises: 5b797d05f412
Create Date: 2026-02-23 17:10:37.613505
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '08f34c125a73'
down_revision = '5b797d05f412'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('phone_number', sa.String(length=20), nullable=True))
batch_op.create_unique_constraint(None, ['phone_number'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('phone_number')
# ### end Alembic commands ###
@@ -0,0 +1,32 @@
"""add_tokens_used_to_chatlog
Revision ID: 439e501ac52b
Revises: 7797942bfa85
Create Date: 2026-02-24 08:51:08.086113
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '439e501ac52b'
down_revision = '7797942bfa85'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('tokens_used', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.drop_column('tokens_used')
# ### end Alembic commands ###
@@ -0,0 +1,34 @@
"""Add default_agent_id to User
Revision ID: 48f1ca8fa73a
Revises: 08f34c125a73
Create Date: 2026-02-23 20:39:30.511482
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '48f1ca8fa73a'
down_revision = '08f34c125a73'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('default_agent_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(None, 'agents', ['default_agent_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='foreignkey')
batch_op.drop_column('default_agent_id')
# ### end Alembic commands ###
@@ -0,0 +1,50 @@
"""Initial migration
Revision ID: 510db8a4f806
Revises:
Create Date: 2026-02-23 11:16:09.218508
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '510db8a4f806'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'api'::character varying"))
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'active'::character varying"))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'active'::character varying"))
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'api'::character varying"))
# ### end Alembic commands ###
@@ -0,0 +1,36 @@
"""Add real_name and employee_id
Revision ID: 5b797d05f412
Revises: 80382a78c530
Create Date: 2026-02-23 12:43:47.707814
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5b797d05f412'
down_revision = '80382a78c530'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('real_name', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('employee_id', sa.String(length=50), nullable=True))
batch_op.create_unique_constraint(None, ['employee_id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('employee_id')
batch_op.drop_column('real_name')
# ### end Alembic commands ###
@@ -0,0 +1,34 @@
"""Add Department table
Revision ID: 60b4aee3ad2d
Revises: 48f1ca8fa73a
Create Date: 2026-02-23 20:56:21.095082
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '60b4aee3ad2d'
down_revision = '48f1ca8fa73a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('departments')
# ### end Alembic commands ###
@@ -0,0 +1,32 @@
"""add_conversation_id_to_chatlog
Revision ID: 7797942bfa85
Revises: b1246a8b37fa
Create Date: 2026-02-24 08:50:46.391292
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7797942bfa85'
down_revision = 'b1246a8b37fa'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('conversation_id', sa.String(length=100), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.drop_column('conversation_id')
# ### end Alembic commands ###
@@ -0,0 +1,97 @@
"""add_zl_language_and_user_lang
Revision ID: 80382a78c530
Revises: 510db8a4f806
Create Date: 2026-02-23 12:06:43.705586
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '80382a78c530'
down_revision = '510db8a4f806'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency', sa.Float(), nullable=False, server_default='0.0'))
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_chat_logs_agent_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_conversation_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_created_at'))
batch_op.drop_index(batch_op.f('ix_chat_logs_user_id'))
batch_op.drop_column('tokens_used')
batch_op.drop_column('conversation_id')
batch_op.drop_column('latency_ms')
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()))
batch_op.drop_column('tags')
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_permission_requests_agent_id'))
batch_op.drop_index(batch_op.f('ix_permission_requests_user_id'))
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_quick_questions_agent_id'))
batch_op.drop_index(batch_op.f('ix_quick_questions_user_id'))
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(length=10), nullable=False, server_default='zh-CN'))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('language')
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_quick_questions_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_quick_questions_agent_id'), ['agent_id'], unique=False)
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_permission_requests_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_permission_requests_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=True)
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('tags', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))
batch_op.drop_column('created_at')
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency_ms', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('conversation_id', sa.VARCHAR(length=100), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('tokens_used', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.create_index(batch_op.f('ix_chat_logs_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_conversation_id'), ['conversation_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=True)
batch_op.drop_column('latency')
op.drop_table('zl_languages')
# ### end Alembic commands ###
@@ -0,0 +1,205 @@
"""sync schema with global questions
Revision ID: a3dcfbe69b00
Revises: f0f24c20e91a
Create Date: 2026-02-23 22:28:18.892924
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = 'a3dcfbe69b00'
down_revision = 'f0f24c20e91a'
branch_labels = None
depends_on = None
def upgrade():
conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()
if 'agents' not in tables:
op.create_table('agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('icon_url', sa.String(length=255), nullable=True),
sa.Column('dify_app_id', sa.String(length=100), nullable=False),
sa.Column('dify_api_key', sa.String(length=100), nullable=False),
sa.Column('type', sa.String(length=20), nullable=False),
sa.Column('api_base_url', sa.String(length=255), nullable=True),
sa.Column('extra_config', sa.JSON(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('dify_app_id')
)
if 'departments' not in tables:
op.create_table('departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('code', sa.String(length=50), nullable=True),
sa.Column('company', sa.String(length=100), nullable=True),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code'),
sa.UniqueConstraint('name')
)
else:
columns = [c['name'] for c in inspector.get_columns('departments')]
if 'code' not in columns:
op.add_column('departments', sa.Column('code', sa.String(length=50), nullable=True))
op.create_unique_constraint(None, 'departments', ['code'])
if 'company' not in columns:
op.add_column('departments', sa.Column('company', sa.String(length=100), nullable=True))
if 'zl_languages' not in tables:
op.create_table('zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
if 'users' not in tables:
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=50), nullable=False),
sa.Column('email', sa.String(length=100), nullable=False),
sa.Column('department', sa.String(length=100), nullable=True),
sa.Column('role', sa.String(length=20), nullable=False),
sa.Column('status', sa.String(length=20), nullable=False),
sa.Column('password_hash', sa.String(length=255), nullable=True),
sa.Column('language', sa.String(length=10), nullable=False),
sa.Column('real_name', sa.String(length=50), nullable=True),
sa.Column('employee_id', sa.String(length=50), nullable=True),
sa.Column('phone_number', sa.String(length=20), nullable=True),
sa.Column('default_agent_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['default_agent_id'], ['agents.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email'),
sa.UniqueConstraint('employee_id'),
sa.UniqueConstraint('phone_number')
)
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_users_username'), ['username'], unique=True)
else:
columns = [c['name'] for c in inspector.get_columns('users')]
if 'default_agent_id' not in columns:
op.add_column('users', sa.Column('default_agent_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'users', 'agents', ['default_agent_id'], ['id'])
if 'real_name' not in columns:
op.add_column('users', sa.Column('real_name', sa.String(length=50), nullable=True))
if 'employee_id' not in columns:
op.add_column('users', sa.Column('employee_id', sa.String(length=50), nullable=True))
try:
op.create_unique_constraint(None, 'users', ['employee_id'])
except: pass
if 'phone_number' not in columns:
op.add_column('users', sa.Column('phone_number', sa.String(length=20), nullable=True))
try:
op.create_unique_constraint(None, 'users', ['phone_number'])
except: pass
if 'chat_logs' not in tables:
op.create_table('chat_logs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('query', sa.Text(), nullable=False),
sa.Column('answer', sa.Text(), nullable=False),
sa.Column('latency', sa.Float(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'permission_requests' not in tables:
op.create_table('permission_requests',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('reason', sa.Text(), nullable=False),
sa.Column('status', sa.String(length=20), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('reviewed_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'quick_questions' not in tables:
op.create_table('quick_questions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=100), nullable=False),
sa.Column('question', sa.Text(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'user_agent_permissions' not in tables:
op.create_table('user_agent_permissions',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
if 'user_default_agents' not in tables:
op.create_table('user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
if 'user_favorite_agents' not in tables:
op.create_table('user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
if 'user_homepage_configs' not in tables:
op.create_table('user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id')
)
if 'feedbacks' not in tables:
op.create_table('feedbacks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('chat_log_id', sa.Integer(), nullable=False),
sa.Column('score', sa.Integer(), nullable=False),
sa.Column('comment', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['chat_log_id'], ['chat_logs.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('chat_log_id')
)
def downgrade():
pass
@@ -0,0 +1,42 @@
"""make dify credentials nullable
Revision ID: b1246a8b37fa
Revises: a3dcfbe69b00
Create Date: 2026-02-23 22:43:26.470122
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b1246a8b37fa'
down_revision = 'a3dcfbe69b00'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('dify_app_id',
existing_type=sa.VARCHAR(length=100),
nullable=True)
batch_op.alter_column('dify_api_key',
existing_type=sa.VARCHAR(length=100),
nullable=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('dify_api_key',
existing_type=sa.VARCHAR(length=100),
nullable=False)
batch_op.alter_column('dify_app_id',
existing_type=sa.VARCHAR(length=100),
nullable=False)
# ### end Alembic commands ###
@@ -0,0 +1,64 @@
"""Add UserHomepageConfig, UserFavoriteAgent, UserDefaultAgent and Update Department
Revision ID: f0f24c20e91a
Revises: 60b4aee3ad2d
Create Date: 2026-02-23 21:13:19.814958
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f0f24c20e91a'
down_revision = '60b4aee3ad2d'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
op.create_table('user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id')
)
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.add_column(sa.Column('code', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('company', sa.String(length=100), nullable=True))
batch_op.create_unique_constraint(None, ['code'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('company')
batch_op.drop_column('code')
op.drop_table('user_homepage_configs')
op.drop_table('user_favorite_agents')
op.drop_table('user_default_agents')
# ### end Alembic commands ###
+12
View File
@@ -0,0 +1,12 @@
flask
flask-sqlalchemy
flask-migrate
flask-cors
psycopg2-binary
redis
requests
gunicorn
gevent
pydantic
python-dotenv
+17
View File
@@ -0,0 +1,17 @@
"""
backend/run.py
开发环境启动脚本
"""
from app import create_app, db
from app.models import User, Agent
app = create_app('development')
@app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Agent': Agent}
if __name__ == '__main__':
# MacOS ControlCenter uses port 5000, so we use 5002
app.run(host='0.0.0.0', port=5002)
+24
View File
@@ -0,0 +1,24 @@
from app import create_app, db
from app.models import ZlLanguage
app = create_app('development')
with app.app_context():
languages = [
{'code': 'zh-CN', 'name': '简体中文'},
{'code': 'zh-TW', 'name': '繁體中文'},
{'code': 'en', 'name': 'English'},
{'code': 'th', 'name': 'ไทย'},
]
for lang in languages:
exists = ZlLanguage.query.filter_by(code=lang['code']).first()
if not exists:
print(f"Adding language: {lang['name']}")
db.session.add(ZlLanguage(code=lang['code'], name=lang['name'], is_active=True))
else:
print(f"Language exists: {lang['name']}")
db.session.commit()
print("Done seeding languages.")
+32
View File
@@ -0,0 +1,32 @@
import pytest
from app import create_app, db
from app.models import User
@pytest.fixture
def app():
app = create_app('testing')
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def admin_headers():
return {
'X-Username': 'admin',
'X-Role': 'admin',
'Content-Type': 'application/json'
}
@pytest.fixture
def user_headers():
return {
'X-Username': 'user',
'X-Role': 'user',
'Content-Type': 'application/json'
}
+71
View File
@@ -0,0 +1,71 @@
import requests
import json
import sys
BASE_URL = "http://127.0.0.1:5001/api"
HEADERS = {
"X-Username": "admin",
"X-Role": "admin",
"Content-Type": "application/json"
}
def test_create_iframe_agent():
print("\n--- Testing Iframe Agent Creation ---")
payload = {
"name": "Test Iframe Agent",
"type": "iframe",
"description": "Auto-test Iframe Agent",
"extra_config": {
"iframe_url": "http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg"
}
}
try:
response = requests.post(f"{BASE_URL}/admin/agents", headers=HEADERS, json=payload)
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
if response.status_code == 201:
print("SUCCESS: Iframe Agent created")
return response.json()['id']
else:
print("FAILURE: Could not create Iframe Agent")
sys.exit(1)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
def test_create_api_agent():
print("\n--- Testing API Agent Creation ---")
payload = {
"name": "Test API Agent",
"type": "api",
"description": "Auto-test API Agent",
"dify_app_id": "test-app-id-123", # Dummy ID for testing constraint
"dify_api_key": "app-xdiejQibWQy8ZQWXcdxJjS9I",
"api_base_url": "http://127.0.0.1:5001/v1"
}
try:
response = requests.post(f"{BASE_URL}/admin/agents", headers=HEADERS, json=payload)
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
if response.status_code == 201:
print("SUCCESS: API Agent created")
return response.json()['id']
else:
# Handle unique constraint if it already exists from previous run
if "integrity error" in response.text.lower() or "unique" in response.text.lower():
print("WARNING: Agent likely already exists (Integrity Error).")
else:
print("FAILURE: Could not create API Agent")
sys.exit(1)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
if __name__ == "__main__":
iframe_id = test_create_iframe_agent()
api_id = test_create_api_agent()
print("\nAll automated tests passed!")
+112
View File
@@ -0,0 +1,112 @@
import pytest
from app import create_app, db
from app.models import Agent, User
import json
@pytest.fixture
def client():
# Use 'testing' config to ensure SQLite in-memory DB is used
app = create_app('testing')
with app.app_context():
db.create_all()
# Create admin user for auth
# Ensure all required fields are provided
admin = User(
username='admin',
email='admin@example.com',
role='admin'
)
admin.set_password('admin')
db.session.add(admin)
db.session.commit()
yield app.test_client()
db.session.remove()
db.drop_all()
def get_headers():
return {
'X-Username': 'admin',
'X-Role': 'admin',
'Content-Type': 'application/json'
}
def test_create_iframe_agent(client):
"""
Test creating an Iframe agent with user provided data.
"""
data = {
"name": "Test Iframe Agent",
"type": "iframe",
"description": "Auto-test Iframe Agent",
"iframe_url": "http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg"
}
# Frontend logic: extra_config = { iframe_url: ... }
payload = {
"name": data["name"],
"type": data["type"],
"description": data["description"],
"dify_app_id": "", # Frontend sends empty string
"dify_api_key": "", # Frontend sends empty string
"extra_config": {
"iframe_url": data["iframe_url"]
}
}
response = client.post('/api/admin/agents', json=payload, headers=get_headers())
assert response.status_code == 201, f"Failed to create Iframe agent: {response.text}"
resp_data = response.get_json()
assert 'id' in resp_data
# Verify DB
# Need to access DB within app context or use client application context if possible
# But db.session is bound to the app context.
# We can use client.application.app_context() if needed, but db.session should work if we are in the same thread/process and using shared memory (for sqlite).
# Since we yielded app.test_client(), the app context in fixture is gone.
# But we can access the app from client.application
with client.application.app_context():
agent = db.session.get(Agent, resp_data['id'])
assert agent is not None
assert agent.type == 'iframe'
# Ensure empty string was converted to None
assert agent.dify_app_id is None
assert agent.extra_config['iframe_url'] == data['iframe_url']
def test_create_api_agent(client):
"""
Test creating an API agent with user provided data.
"""
data = {
"name": "Test API Agent",
"type": "api",
"api_base_url": "http://127.0.0.1:5001/v1",
"dify_api_key": "app-xdiejQibWQy8ZQWXcdxJjS9I"
}
# We need to provide a dify_app_id because it is required for API agents
payload = {
"name": data["name"],
"type": data["type"],
"dify_app_id": "test-api-agent-id", # Dummy ID
"dify_api_key": data["dify_api_key"],
"api_base_url": data["api_base_url"]
}
response = client.post('/api/admin/agents', json=payload, headers=get_headers())
assert response.status_code == 201, f"Failed to create API agent: {response.text}"
resp_data = response.get_json()
assert 'id' in resp_data
# Verify DB
with client.application.app_context():
agent = db.session.get(Agent, resp_data['id'])
assert agent is not None
assert agent.type == 'api'
assert agent.dify_api_key == data['dify_api_key']
assert agent.api_base_url == data['api_base_url']
+91
View File
@@ -0,0 +1,91 @@
import requests
import json
from app import create_app, db
from app.models import Agent, ChatLog, User
def setup_data():
app = create_app()
with app.app_context():
# Create a user first (needed for chat log)
user = User.query.filter_by(username="repro_user").first()
if not user:
user = User(username="repro_user", email="repro@test.com", role="admin")
user.set_password("password")
db.session.add(user)
db.session.commit()
# Create the "Test Agent Report" agent
agent = Agent.query.filter_by(name="Test Agent Report").first()
if not agent:
agent = Agent(
name="Test Agent Report",
type="api",
dify_app_id="repro_app_id",
dify_api_key="repro_key",
is_active=True
)
db.session.add(agent)
db.session.commit()
print(f"Created Agent: {agent.id}")
else:
print(f"Agent exists: {agent.id}")
# Create a ChatLog to enforce FK constraint
chat = ChatLog(
user_id=user.id,
agent_id=agent.id,
query="test",
answer="test"
)
db.session.add(chat)
db.session.commit()
print("Created ChatLog dependency.")
return agent.id, user.username
def test_delete(agent_id, username):
print(f"\n--- Testing DELETE Agent {agent_id} ---")
headers = {
"X-Username": username,
"X-Role": "admin"
}
url = f"http://127.0.0.1:5000/api/admin/agents/{agent_id}"
try:
res = requests.delete(url, headers=headers)
print(f"Status: {res.status_code}")
print(f"Content: {res.text}")
except Exception as e:
print(f"Request failed: {e}")
def test_update(agent_id, username):
print(f"\n--- Testing UPDATE Agent {agent_id} ---")
headers = {
"X-Username": username,
"X-Role": "admin",
"Content-Type": "application/json"
}
url = f"http://127.0.0.1:5000/api/admin/agents/{agent_id}"
data = {
"dify_api_key": "updated_key_123",
"name": "Test Agent Report", # Send name as well
"dify_app_id": "repro_app_id",
"type": "api",
"is_active": True
}
try:
res = requests.put(url, headers=headers, json=data)
print(f"Status: {res.status_code}")
print(f"Content: {res.text}")
except Exception as e:
print(f"Request failed: {e}")
if __name__ == "__main__":
# Ensure data exists
try:
agent_id, username = setup_data()
# Test Delete (Expect fail due to FK)
test_delete(agent_id, username)
# Test Update (Expect success)
test_update(agent_id, username)
except Exception as e:
print(f"Setup failed: {e}")
@@ -0,0 +1,51 @@
import pytest
from app import create_app, db
from app.models import Agent, User
@pytest.fixture
def client():
app = create_app('testing')
with app.app_context():
db.create_all()
# Create an active agent
agent = Agent(name="Test Agent", type="api", is_active=True)
db.session.add(agent)
# Create a regular user (no permissions)
user = User(username='test_user', role='user', email='test@example.com')
db.session.add(user)
db.session.commit()
yield app.test_client()
db.session.remove()
db.drop_all()
def test_user_home_agents_visibility(client):
"""
Test that a regular user can see active agents in /api/user/home
even if they don't have explicit permission (visibility vs access).
"""
# Login as regular user
client.post('/api/user/login', json={'username': 'test_user', 'password': ''})
# Mock headers for auth (since login might not set session in test client depending on implementation)
# user.py uses _get_current_user which checks headers
headers = {
'X-Username': 'test_user',
'X-Role': 'user'
}
response = client.get('/api/user/home', headers=headers)
assert response.status_code == 200
data = response.get_json()
agents = data.get('agents', [])
# Current behavior (Bug): agents is empty for regular user
# Desired behavior: agents should contain the active agent
print(f"Agents found: {len(agents)}")
assert len(agents) > 0, "Agents list should not be empty for regular user"
+116
View File
@@ -0,0 +1,116 @@
import pytest
from app.models import Agent, User
from app import db
import uuid
def test_delete_user_success(client, admin_headers):
"""
Verify DELETE /api/admin/users/<id> works (after fix).
"""
# Create a user to delete
user = User(username=f"del_{uuid.uuid4().hex[:8]}", email=f"del_{uuid.uuid4().hex[:8]}@test.com", role="user")
user.set_password("password")
db.session.add(user)
db.session.commit()
user_id = user.id
print(f"\nCreated user {user_id} for DELETE test.")
# Test DELETE Endpoint
res = client.delete(f'/api/admin/users/{user_id}', headers=admin_headers)
print(f"DELETE /users/{user_id} status: {res.status_code}")
if res.status_code == 200:
print("DELETE /api/admin/users/<id> success.")
# Verify user is gone
assert User.query.get(user_id) is None
else:
print(f"DELETE failed with {res.status_code}: {res.text}")
pytest.fail(f"DELETE failed: {res.status_code}")
def test_update_agent_api_key_scenarios(client, admin_headers):
"""
Test various Agent API Key update scenarios.
"""
# Create an agent
app_id = f"app-{uuid.uuid4().hex[:8]}"
agent = Agent(
name="UpdateKeyTest",
type="api",
dify_app_id=app_id,
dify_api_key="orig_key",
is_active=True
)
db.session.add(agent)
db.session.commit()
agent_id = agent.id
print(f"\nCreated agent {agent_id} for update test.")
# Scenario 1: Update Key Success
new_key = "new_secret_key"
data = {
"dify_api_key": new_key
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
assert res.status_code == 200
updated_agent = Agent.query.get(agent_id)
assert updated_agent.dify_api_key == new_key
print("Scenario 1 (Success): Key updated.")
# Scenario 2: Update with Empty String (Should allow it? Or ignore?)
# Current behavior: updates to empty string.
data = {
"dify_api_key": ""
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
assert res.status_code == 200
updated_agent = Agent.query.get(agent_id)
assert updated_agent.dify_api_key == ""
print("Scenario 2 (Empty String): Key updated to empty string.")
# Scenario 3: Update with Duplicate App ID (Should fail)
# Create another agent first
other_app_id = f"app-{uuid.uuid4().hex[:8]}"
other_agent = Agent(
name="OtherAgent",
type="api",
dify_app_id=other_app_id,
dify_api_key="key2",
is_active=True
)
db.session.add(other_agent)
db.session.commit()
# Try to update first agent to use second agent's App ID
data = {
"dify_app_id": other_app_id
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
print(f"Scenario 3 (Duplicate App ID) status: {res.status_code}")
# This should fail with 400 (caught exception) or 500
# Our code catches Exception and returns 400
assert res.status_code == 400
assert "error" in res.json
print("Scenario 3 (Duplicate App ID): Correctly failed.")
# Scenario 4: Update with Very Long Key (Should fail if > 100)
long_key = "a" * 101
data = {
"dify_api_key": long_key
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
print(f"Scenario 4 (Long Key) status: {res.status_code}")
# Should fail due to DB constraint (String(100))
# Caught by try-except block -> 400
if res.status_code == 400:
print("Scenario 4 (Long Key): Correctly failed.")
else:
print(f"Scenario 4 (Long Key): Unexpected success? Status: {res.status_code}")
# If SQLite, it might not enforce length. If Postgres, it will.
# We are using SQLite (implied by file structure/lack of PG setup in context, but wait, env says postgres?)
# "mcp_PostgreSQL_query" tool suggests Postgres.
# But locally it might be SQLite.
pass
+194
View File
@@ -0,0 +1,194 @@
import pytest
from app.models import Agent, User, PermissionRequest
from app import db
def test_agent_lifecycle(client, admin_headers):
"""
Test complete lifecycle of an Agent: Create -> Read -> Update -> Delete
"""
# 1. Create Agent
new_agent = {
"name": "Test Agent",
"description": "Initial Description",
"type": "api",
"dify_app_id": "app-123",
"dify_api_key": "key-123",
"is_active": True
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
assert response.status_code == 201
agent_id = response.json['id']
# 2. Read Agent List
response = client.get('/api/admin/agents', headers=admin_headers)
assert response.status_code == 200
agents = response.json
assert len(agents) == 1
assert agents[0]['name'] == "Test Agent"
assert agents[0]['description'] == "Initial Description"
# 3. Update Agent
updated_data = {
"name": "Updated Agent",
"description": "Updated Description"
}
response = client.put(f'/api/admin/agents/{agent_id}', json=updated_data, headers=admin_headers)
assert response.status_code == 200
# Verify Update
response = client.get('/api/admin/agents', headers=admin_headers)
agents = response.json
assert agents[0]['name'] == "Updated Agent"
assert agents[0]['description'] == "Updated Description"
# 4. Delete Agent
response = client.delete(f'/api/admin/agents/{agent_id}', headers=admin_headers)
assert response.status_code == 200
# Verify Deletion
response = client.get('/api/admin/agents', headers=admin_headers)
assert len(response.json) == 0
def test_user_management(client, admin_headers):
"""
Test user creation, approval, and permission assignment
"""
# 1. Create User
new_user = {
"username": "newuser",
"email": "new@example.com",
"role": "user",
"password": "password123",
"real_name": "Test User",
"employee_id": "EMP001"
}
response = client.post('/api/admin/users', json=new_user, headers=admin_headers)
assert response.status_code == 201
user_id = response.json['id']
# 2. Approve User
response = client.post(f'/api/admin/users/{user_id}/approve', headers=admin_headers)
assert response.status_code == 200
# Verify Status and Fields
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
target_user = next(u for u in users if u['id'] == user_id)
assert target_user['status'] == 'active'
assert target_user['real_name'] == "Test User"
assert target_user['employee_id'] == "EMP001"
# 3. Assign Permissions (needs an Agent first)
agent_res = client.post('/api/admin/agents', json={
"name": "Permission Agent",
"type": "api",
"dify_app_id": "p1",
"dify_api_key": "k1"
}, headers=admin_headers)
agent_id = agent_res.json['id']
response = client.post(f'/api/admin/users/{user_id}/permissions', json={
"agent_ids": [agent_id]
}, headers=admin_headers)
assert response.status_code == 200
# Verify Permissions
response = client.get('/api/admin/users', headers=admin_headers)
target_user = next(u for u in response.json if u['id'] == user_id)
assert agent_id in target_user['agent_ids']
# 4. Delete User (New Endpoint)
response = client.delete(f'/api/admin/users/{user_id}', headers=admin_headers)
assert response.status_code == 200
# Verify Deletion
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
assert not any(u['id'] == user_id for u in users)
def test_agent_update_validation(client, admin_headers):
"""
Test validation when updating agents (especially API mode constraints)
"""
# Create Agent
new_agent = {
"name": "Validation Agent",
"type": "api",
"dify_app_id": "v-app-1",
"dify_api_key": "v-key-1",
"is_active": True
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
agent_id = response.json['id']
# 1. Update with Valid Data
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": "new-key"}, headers=admin_headers)
assert response.status_code == 200
# 2. Try to Clear Key for API Agent (Should Fail)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify API Key" in response.json['error']
# 3. Try to Clear App ID for API Agent (Should Fail)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_app_id": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify App ID" in response.json['error']
def test_permission_requests(client, app, admin_headers):
"""
Test permission request approval/rejection flow
"""
# Setup: Create User, Agent, and Request manually
with app.app_context():
user = User(username="requester", email="req@example.com", role="user")
agent = Agent(name="Requested Agent", type="api", dify_app_id="r1", dify_api_key="k1", is_active=True)
db.session.add(user)
db.session.add(agent)
db.session.commit()
req = PermissionRequest(user_id=user.id, agent_id=agent.id, reason="Need access", status="pending")
db.session.add(req)
db.session.commit()
req_id = req.id
user_id = user.id
agent_id = agent.id
# 1. List Requests
response = client.get('/api/admin/permission-requests', headers=admin_headers)
assert response.status_code == 200
requests = response.json
assert len(requests) == 1
assert requests[0]['reason'] == "Need access"
# 2. Approve Request
response = client.post(f'/api/admin/permission-requests/{req_id}/approve', headers=admin_headers)
assert response.status_code == 200
# Verify Request Status
response = client.get('/api/admin/permission-requests', headers=admin_headers)
requests = response.json
assert requests[0]['status'] == 'approved'
# Verify User Permission Updated
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
target_user = next(u for u in users if u['id'] == user_id)
assert agent_id in target_user['agent_ids']
def test_reports(client, admin_headers):
"""
Test report endpoints
"""
response = client.get('/api/admin/reports/usage', headers=admin_headers)
assert response.status_code == 200
data = response.json
assert 'total' in data
assert 'by_user' in data
assert 'by_agent' in data
response = client.get('/api/admin/reports/feedback', headers=admin_headers)
assert response.status_code == 200
data = response.json
assert 'avg_score' in data
assert 'distribution' in data
+149
View File
@@ -0,0 +1,149 @@
import pytest
from app import create_app, db
from app.models import User, Agent, Department, PermissionRequest
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create admin user
admin = User(username='admin', role='admin', email='admin@example.com')
admin.set_password('admin')
db.session.add(admin)
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def get_headers(client, username='admin', password='admin'):
res = client.post('/api/user/login', json={'username': username, 'password': password})
data = res.get_json()
return {
'X-User-Id': str(data['id']),
'X-Username': data['username'],
'X-Role': data['role']
}
def test_department_crud(client):
headers = get_headers(client)
# Create
res = client.post('/api/admin/departments', json={
'name': 'IT Dept',
'code': 'IT001',
'company': 'Tech Corp',
'description': 'Information Technology'
}, headers=headers)
assert res.status_code == 201
dept_id = res.get_json()['id']
# List
res = client.get('/api/admin/departments', headers=headers)
assert res.status_code == 200
depts = res.get_json()
assert len(depts) == 1
assert depts[0]['code'] == 'IT001'
assert depts[0]['company'] == 'Tech Corp'
# Update
res = client.put(f'/api/admin/departments/{dept_id}', json={
'name': 'IT Department',
'code': 'IT002'
}, headers=headers)
assert res.status_code == 200
# Verify Update
res = client.get('/api/admin/departments', headers=headers)
depts = res.get_json()
assert depts[0]['name'] == 'IT Department'
assert depts[0]['code'] == 'IT002'
# Delete
res = client.delete(f'/api/admin/departments/{dept_id}', headers=headers)
assert res.status_code == 200
res = client.get('/api/admin/departments', headers=headers)
assert len(res.get_json()) == 0
def test_agent_crud(client):
headers = get_headers(client)
# Create
res = client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123',
'description': 'Test Description'
}, headers=headers)
assert res.status_code == 201
agent_id = res.get_json()['id']
# List
res = client.get('/api/admin/agents', headers=headers)
assert res.status_code == 200
agents = res.get_json()
assert len(agents) == 1
assert agents[0]['name'] == 'Test Agent'
# Update
res = client.put(f'/api/admin/agents/{agent_id}', json={
'name': 'Updated Agent'
}, headers=headers)
assert res.status_code == 200
# Verify Update
res = client.get('/api/admin/agents', headers=headers)
assert res.get_json()[0]['name'] == 'Updated Agent'
# Delete
res = client.delete(f'/api/admin/agents/{agent_id}', headers=headers)
assert res.status_code == 200
res = client.get('/api/admin/agents', headers=headers)
assert len(res.get_json()) == 0
def test_permission_flow(client):
admin_headers = get_headers(client)
# Create Agent
client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123'
}, headers=admin_headers)
agent_id = 1
# Create User
client.post('/api/user/register', json={
'username': 'user1', 'password': 'password', 'email': 'u1@example.com',
'real_name': 'User One', 'employee_id': 'U001', 'phone_number': '1234567890'
})
# Approve User
client.post('/api/admin/users/2/approve', headers=admin_headers) # ID 2 because admin is 1
# User Login
user_headers = get_headers(client, 'user1', 'password')
# Request Permission
res = client.post('/api/user/permission-requests', json={
'agent_id': agent_id,
'reason': 'I need it'
}, headers=user_headers)
assert res.status_code == 201
req_id = res.get_json()['id']
# Admin List Requests
res = client.get('/api/admin/permission-requests', headers=admin_headers)
assert len(res.get_json()) == 1
# Admin Approve
res = client.post(f'/api/admin/permission-requests/{req_id}/approve', headers=admin_headers)
assert res.status_code == 200
# User Check Home (should have agent now)
res = client.get('/api/user/home', headers=user_headers)
data = res.get_json()
assert len(data['agents']) == 1
assert data['agents'][0]['id'] == agent_id
+131
View File
@@ -0,0 +1,131 @@
import pytest
from app import create_app, db
from app.models import User, Agent
from flask import json
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create Admin
admin = User(username='admin', role='admin', email='admin@example.com')
admin.set_password('password')
db.session.add(admin)
# Create Users
u1 = User(username='u1', role='user', email='u1@example.com')
u2 = User(username='u2', role='user', email='u2@example.com')
db.session.add_all([u1, u2])
# Create Agents
a1 = Agent(name='a1', dify_app_id='1', dify_api_key='1')
a2 = Agent(name='a2', dify_app_id='2', dify_api_key='2')
db.session.add_all([a1, a2])
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def login(client, username, password):
return client.post('/api/user/login', json={'username': username, 'password': password})
def test_batch_update_users(client):
login_res = login(client, 'admin', 'password')
token_headers = {
'X-Username': 'admin',
'X-Role': 'admin',
'X-User-Id': str(login_res.json['id'])
}
# Get user IDs
u1 = User.query.filter_by(username='u1').first()
u2 = User.query.filter_by(username='u2').first()
# Batch update
res = client.put('/api/admin/users/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'data': {'department': 'Engineering', 'status': 'disabled'}
})
assert res.status_code == 200
# Verify
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert u1.department == 'Engineering'
assert u1.status == 'disabled'
assert u2.department == 'Engineering'
assert u2.status == 'disabled'
def test_batch_update_permissions(client):
login_res = login(client, 'admin', 'password')
token_headers = {
'X-Username': 'admin',
'X-Role': 'admin',
'X-User-Id': str(login_res.json['id'])
}
u1 = User.query.filter_by(username='u1').first()
u2 = User.query.filter_by(username='u2').first()
a1 = Agent.query.filter_by(name='a1').first()
a2 = Agent.query.filter_by(name='a2').first()
# Grant a1 to u1 initially
u1.agents.append(a1)
db.session.commit()
# Batch Add a2 to u1, u2
res = client.post('/api/admin/permissions/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'agent_ids': [a2.id],
'action': 'add'
})
assert res.status_code == 200
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert a1 in u1.agents
assert a2 in u1.agents
assert a2 in u2.agents
# Batch Set a1 for u1, u2 (should remove a2)
res = client.post('/api/admin/permissions/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'agent_ids': [a1.id],
'action': 'set'
})
assert res.status_code == 200
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert len(u1.agents) == 1
assert u1.agents[0].id == a1.id
assert len(u2.agents) == 1
assert u2.agents[0].id == a1.id
def test_user_default_agent(client):
# Login as u1
u1 = User.query.filter_by(username='u1').first()
u1.set_password('password')
db.session.commit()
login_res = login(client, 'u1', 'password')
token_headers = {
'X-Username': 'u1',
'X-Role': 'user',
'X-User-Id': str(u1.id)
}
a1 = Agent.query.filter_by(name='a1').first()
# Set default agent
res = client.put('/api/user/profile', headers=token_headers, json={
'default_agent_id': a1.id
})
assert res.status_code == 200
# Verify via Home API
res = client.get('/api/user/home', headers=token_headers)
data = res.json
assert data['user']['default_agent_id'] == a1.id
+237
View File
@@ -0,0 +1,237 @@
import pytest
import json
from app.models import User, Agent
# -----------------------------------------------------------------------------
# Test File: backend/tests/test_comprehensive.py
# Purpose: Comprehensive automated tests for backend functionalities including
# User Management, Agent Management, and Permissions.
# References: backend/app/api/admin.py, backend/app/api/user.py, backend/app/models.py
# Logic:
# 1. Test User Registration (with new fields)
# 2. Test Admin User Approval
# 3. Test Admin User Rejection
# 4. Test Agent CRUD (Create, Update, Delete)
# 5. Test Permission Assignment (User-Agent linkage)
# -----------------------------------------------------------------------------
@pytest.fixture
def auth_headers(client):
"""
Helper fixture to get auth headers for a standard user.
Note: In real app, we might need a token, but here we use mock headers from conftest
or simulate login if needed. For admin, we use admin_headers fixture.
"""
return {
'Content-Type': 'application/json'
}
def test_user_registration_flow(client):
"""
Test the user registration process with all new fields.
Steps:
1. Register a new user with phone_number, real_name, employee_id.
2. Verify successful response.
3. Verify data in database.
4. Try to register with duplicate phone_number/employee_id and verify failure.
"""
# 1. Register a new user
payload = {
'username': 'testuser_new',
'password': 'password123',
'email': 'testuser_new@example.com',
'real_name': 'Test User Real',
'employee_id': 'EMP001',
'phone_number': '13800138000'
}
# Call /api/user/register (Assuming this is the public registration endpoint)
# If not, we might use /api/admin/users for admin creation.
# Let's check api/user.py for register endpoint, usually it is /api/user/register
response = client.post('/api/user/register', json=payload)
# 2. Verify response
assert response.status_code == 201 or response.status_code == 200
data = response.get_json()
assert 'id' in data or 'status' in data
# 3. Verify database
user = User.query.filter_by(username='testuser_new').first()
assert user is not None
assert user.real_name == 'Test User Real'
assert user.employee_id == 'EMP001'
assert user.phone_number == '13800138000'
assert user.status == 'pending' # Default status for registration
# 4. Duplicate checks
# Duplicate Phone
payload_dup_phone = payload.copy()
payload_dup_phone['username'] = 'testuser_dup_phone'
payload_dup_phone['email'] = 'dup_phone@example.com'
payload_dup_phone['employee_id'] = 'EMP002' # Different ID
# Same phone '13800138000'
response = client.post('/api/user/register', json=payload_dup_phone)
assert response.status_code == 400
assert 'Phone number already exists' in response.get_json()['error']
# Duplicate Employee ID
payload_dup_emp = payload.copy()
payload_dup_emp['username'] = 'testuser_dup_emp'
payload_dup_emp['email'] = 'dup_emp@example.com'
payload_dup_emp['phone_number'] = '13900139000' # Different phone
# Same employee_id 'EMP001'
response = client.post('/api/user/register', json=payload_dup_emp)
assert response.status_code == 400
assert 'Employee ID already exists' in response.get_json()['error']
def test_admin_approve_reject_user(client, admin_headers):
"""
Test Admin approval and rejection of users.
Steps:
1. Create two pending users (via register endpoint or direct DB).
2. Admin approves User A. Verify status 'active'.
3. Admin rejects User B. Verify status 'rejected'.
"""
# 1. Create users
# We can use the register endpoint or admin create endpoint
user_a = User(username='user_a', email='a@test.com', status='pending', role='user')
user_a.set_password('123')
user_b = User(username='user_b', email='b@test.com', status='pending', role='user')
user_b.set_password('123')
# Need to access db session. conftest app fixture handles db creation/drop
# but we need to import db from app to add
from app import db
db.session.add(user_a)
db.session.add(user_b)
db.session.commit()
# 2. Approve User A
response = client.post(f'/api/admin/users/{user_a.id}/approve', headers=admin_headers)
assert response.status_code == 200
# Refresh from DB
db.session.refresh(user_a)
assert user_a.status == 'active'
# 3. Reject User B
response = client.post(f'/api/admin/users/{user_b.id}/reject', headers=admin_headers)
assert response.status_code == 200
db.session.refresh(user_b)
assert user_b.status == 'rejected'
def test_agent_management(client, admin_headers):
"""
Test CRUD operations for Agents.
Steps:
1. Admin creates a new Agent.
2. Admin updates the Agent.
3. Admin deletes the Agent.
"""
from app import db
# 1. Create Agent
payload = {
'name': 'Test Agent',
'dify_app_id': 'app-uuid-123',
'dify_api_key': 'key-secret-123',
'description': 'A test agent',
'type': 'api'
}
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
assert response.status_code == 201
data = response.get_json()
agent_id = data['id']
# Verify DB
agent = Agent.query.get(agent_id)
assert agent.name == 'Test Agent'
# 2. Update Agent
update_payload = {
'name': 'Updated Agent Name',
'description': 'Updated description'
}
response = client.put(f'/api/admin/agents/{agent_id}', json=update_payload, headers=admin_headers)
assert response.status_code == 200
db.session.refresh(agent)
assert agent.name == 'Updated Agent Name'
assert agent.description == 'Updated description'
# 3. Delete Agent
response = client.delete(f'/api/admin/agents/{agent_id}', headers=admin_headers)
assert response.status_code == 200
agent = Agent.query.get(agent_id)
assert agent is None
def test_permission_management(client, admin_headers):
"""
Test assigning Agents to Users (Permissions).
Steps:
1. Create a User and an Agent.
2. Verify User initially has no agents.
3. Admin updates User to assign the Agent.
4. Verify User has the Agent.
5. Admin removes the Agent.
6. Verify User has no agents.
"""
from app import db
# 1. Setup Data
user = User(username='perm_user', email='perm@test.com', role='user', status='active')
user.set_password('123')
agent = Agent(name='Perm Agent', dify_app_id='app-perm', dify_api_key='key-perm')
db.session.add(user)
db.session.add(agent)
db.session.commit()
user_id = user.id
agent_id = agent.id
# 2. Verify initial state
assert len(user.agents) == 0
# 3. Assign Agent
# The update_user endpoint accepts 'agent_ids' list
payload = {
'agent_ids': [agent_id]
}
response = client.put(f'/api/admin/users/{user_id}', json=payload, headers=admin_headers)
assert response.status_code == 200
# 4. Verify assignment
# Need to expire/refresh to see changes in relationship
db.session.expire(user)
# Or query again
user = User.query.get(user_id)
assert len(user.agents) == 1
assert user.agents[0].id == agent_id
# 5. Remove Agent (assign empty list)
payload = {
'agent_ids': []
}
response = client.put(f'/api/admin/users/{user_id}', json=payload, headers=admin_headers)
assert response.status_code == 200
# 6. Verify removal
db.session.expire(user)
user = User.query.get(user_id)
assert len(user.agents) == 0
+56
View File
@@ -0,0 +1,56 @@
import pytest
from app import create_app, db
from app.models import Agent
@pytest.fixture
def app():
app = create_app('testing')
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
def test_public_agents_access(client):
"""
测试未登录用户访问公开应用列表
"""
# 1. 初始状态:无应用
res = client.get('/api/user/public-agents')
assert res.status_code == 200
assert len(res.json) == 0
# 2. 创建应用
with client.application.app_context():
a1 = Agent(name="Public Agent 1", dify_app_id="p1", dify_api_key="k1", is_active=True)
a2 = Agent(name="Public Agent 2", dify_app_id="p2", dify_api_key="k2", is_active=True)
a3 = Agent(name="Private Agent", dify_app_id="p3", dify_api_key="k3", is_active=False)
db.session.add_all([a1, a2, a3])
db.session.commit()
# 3. 再次访问,应只返回 Active 的应用
res = client.get('/api/user/public-agents')
assert res.status_code == 200
data = res.json
assert len(data) == 2
names = [a['name'] for a in data]
assert "Public Agent 1" in names
assert "Public Agent 2" in names
assert "Private Agent" not in names
def test_user_home_access_denied(client):
"""
测试未登录用户访问 /api/user/home 返回 Guest 身份
"""
# 无 Header 访问
res = client.get('/api/user/home')
assert res.status_code == 200
data = res.json
assert data['user']['role'] == 'guest'
# Guest 用户通常没有 Agents 权限
assert len(data['agents']) == 0
+55
View File
@@ -0,0 +1,55 @@
import pytest
from app import create_app, db
from app.models import User, Agent, QuickQuestion
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
with app.test_client() as client:
with app.app_context():
db.create_all()
yield client
db.session.remove()
db.drop_all()
def test_quick_question_crud(client):
# Setup
user = User(username='testuser', email='test@example.com', role='user')
user.set_password('password')
agent = Agent(name='Test Agent', dify_app_id='app-123', dify_api_key='key-123')
db.session.add(user)
db.session.add(agent)
db.session.commit()
# Login
login_res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'password'})
assert login_res.status_code == 200
user_data = login_res.get_json()
headers = {'X-User-Id': str(user_data['id']), 'X-Username': user_data['username'], 'X-Role': user_data['role']}
# Create
res = client.post('/api/user/quick-questions', json={
'title': 'Test Q',
'question': 'How are you?',
'agent_id': agent.id
}, headers=headers)
assert res.status_code == 201
qq_id = res.get_json()['id']
# Read (via Home)
res = client.get('/api/user/home', headers=headers)
assert res.status_code == 200
data = res.get_json()
assert len(data['quick_questions']) == 1
assert data['quick_questions'][0]['title'] == 'Test Q'
# Delete
res = client.delete(f'/api/user/quick-questions/{qq_id}', headers=headers)
assert res.status_code == 200
# Verify Delete
res = client.get('/api/user/home', headers=headers)
assert len(res.get_json()['quick_questions']) == 0
+624
View File
@@ -0,0 +1,624 @@
"""
backend/tests/test_unit_mock.py
文件用途:自动化单元测试,使用 Mock 技术隔离外部依赖
测试范围:User, Admin, Agent, Chat, Permission, QuickQuestion 等核心模块
技术栈:pytest, unittest.mock, flask
设计原则:AAA 模式 (Arrange-Act-Assert),全面 Mock,独立性
"""
import pytest
import json
from unittest.mock import MagicMock, patch
from flask import g
from app import create_app, db
from app.models import User, Agent, ChatLog, Feedback, PermissionRequest, QuickQuestion
# -----------------------------------------------------------------------------
# Fixtures (Setup & Teardown)
# -----------------------------------------------------------------------------
@pytest.fixture
def app_instance():
"""
创建 Flask 应用实例,配置为测试模式
"""
app = create_app('testing')
app.config['TESTING'] = True
# 禁用反馈功能检查,方便测试
app.config['FEEDBACK_ENABLED'] = True
return app
@pytest.fixture(autouse=True)
def app_context(app_instance):
"""
自动激活应用上下文,解决 "Working outside of application context" 问题
"""
with app_instance.app_context():
yield
@pytest.fixture
def client(app_instance):
"""
Flask 测试客户端
"""
return app_instance.test_client()
@pytest.fixture
def mock_db_session(mocker):
"""
Mock 数据库 Session
用途:拦截 db.session.add, commit, rollback, delete 等操作
"""
return mocker.patch('app.db.session')
@pytest.fixture
def mock_user_query(mocker):
"""Mock User.query"""
return mocker.patch('app.models.User.query')
@pytest.fixture
def mock_agent_query(mocker):
"""Mock Agent.query"""
return mocker.patch('app.models.Agent.query')
@pytest.fixture
def mock_chat_log_query(mocker):
"""Mock ChatLog.query"""
return mocker.patch('app.models.ChatLog.query')
@pytest.fixture
def mock_permission_request_query(mocker):
"""Mock PermissionRequest.query"""
return mocker.patch('app.models.PermissionRequest.query')
@pytest.fixture
def mock_quick_question_query(mocker):
"""Mock QuickQuestion.query"""
return mocker.patch('app.models.QuickQuestion.query')
@pytest.fixture
def admin_headers():
return {
'Content-Type': 'application/json',
'X-Role': 'admin',
'X-Username': 'admin'
}
@pytest.fixture
def user_headers():
return {
'Content-Type': 'application/json',
'X-Role': 'user',
'X-Username': 'test_user',
'X-User-Id': '1'
}
# -----------------------------------------------------------------------------
# 1. User Authentication & Management Tests
# -----------------------------------------------------------------------------
def test_user_register_success(client, mock_user_query, mock_db_session):
"""
[User] 注册成功 (Happy Path)
"""
# Arrange
payload = {
"username": "new_user",
"password": "password123",
"email": "new@example.com",
"real_name": "New User",
"employee_id": "EMP001",
"phone_number": "13800000001"
}
# Mock query to return None (no duplicate)
mock_user_query.filter_by.return_value.first.return_value = None
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
data = response.get_json()
assert data['status'] == 'pending'
def test_user_register_missing_fields(client):
"""
[User] 注册失败 - 缺少必填字段 (Boundary)
"""
# Arrange
payload = {
"username": "new_user"
# Missing password, email, etc.
}
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 400
assert "required" in response.get_json()['error']
def test_user_register_duplicate_username(client, mock_user_query):
"""
[User] 注册失败 - 用户名重复 (Error)
"""
# Arrange
payload = {
"username": "dup_user",
"password": "pwd",
"email": "dup@example.com",
"real_name": "Dup User",
"employee_id": "EMP002",
"phone_number": "13800000002"
}
# Mock existing user
mock_user_query.filter_by.return_value.first.return_value = User(username="dup_user")
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 400
assert "Username already exists" in response.get_json()['error']
def test_user_login_success(client, mock_user_query):
"""
[User] 登录成功 (Happy Path)
"""
# Arrange
mock_user = User(id=1, username="test_user", role="user", status="active", password_hash="hashed_pwd")
mock_user_query.filter_by.return_value.first.return_value = mock_user
# Mock check_password_hash via class method or instance
# Note: User.check_password logic uses check_password_hash internally.
# We can mock check_password method on the instance.
mock_user.check_password = MagicMock(return_value=True)
# Act
response = client.post('/api/user/login', json={"username": "test_user", "password": "correct_pwd"})
# Assert
assert response.status_code == 200
data = response.get_json()
assert data['username'] == "test_user"
assert data['role'] == "user"
def test_user_login_invalid_password(client, mock_user_query):
"""
[User] 登录失败 - 密码错误 (Error)
"""
# Arrange
mock_user = User(id=1, username="test_user", status="active", password_hash="hashed")
mock_user_query.filter_by.return_value.first.return_value = mock_user
# Ensure check_password returns False
mock_user.check_password = MagicMock(return_value=False)
# Act
response = client.post('/api/user/login', json={"username": "test_user", "password": "wrong_pwd"})
# Assert
assert response.status_code == 401
assert "Invalid password" in response.get_json()['error']
def test_user_login_inactive_user(client, mock_user_query):
"""
[User] 登录失败 - 账号未激活 (Error)
"""
# Arrange
# Explicitly set status to pending.
# Note: User constructor might set default 'active' if not handled by init (SQLAlchemy magic).
# So we set it explicitly after creation or ensure it's respected.
mock_user = User(id=1, username="pending_user", status="pending", password_hash="hashed")
mock_user_query.filter_by.return_value.first.return_value = mock_user
mock_user.check_password = MagicMock(return_value=True)
# Act
response = client.post('/api/user/login', json={"username": "pending_user", "password": "pwd"})
# Assert
assert response.status_code == 403
assert "Account is not active" in response.get_json()['error']
def test_get_user_home(client, mocker):
"""
[User] 获取首页数据 (Happy Path)
"""
# Arrange
mock_user = User(id=1, role='user', agents=[])
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
# Mock related queries using patching of models directly if fixtures not used,
# OR better: mock the DB session query if the code uses db.session.query
# app/api/user.py uses:
# agents = Agent.query.filter_by...
# quick_questions = db.session.query(QuickQuestion)...
# permission_requests = PermissionRequest.query...
# total_calls = db.session.query(ChatLog)...
# Mock Agent.query
mock_agent_query = mocker.patch('app.models.Agent.query')
mock_agent_query.filter_by.return_value.order_by.return_value.all.return_value = []
# Mock db.session.query for QuickQuestion and ChatLog
mock_query = mocker.patch('app.db.session.query')
# We need to handle different calls to db.session.query
# Since it's hard to distinguish by arg, we can make it return a generic mock that returns empty list/0
mock_query_obj = MagicMock()
mock_query.return_value = mock_query_obj
mock_query_obj.filter.return_value.count.return_value = 0
mock_query_obj.filter_by.return_value.order_by.return_value.all.return_value = []
mock_query_obj.filter_by.return_value.count.return_value = 0
mock_query_obj.filter_by.return_value.order_by.return_value.first.return_value = None
# Mock PermissionRequest.query
mock_pr_query = mocker.patch('app.models.PermissionRequest.query')
mock_pr_query.filter_by.return_value.order_by.return_value.all.return_value = []
# Act
response = client.get('/api/user/home')
# Assert
assert response.status_code == 200
data = response.get_json()
assert 'user' in data
assert 'agents' in data
assert 'report' in data
# -----------------------------------------------------------------------------
# 2. Admin Management Tests
# -----------------------------------------------------------------------------
def test_admin_create_agent_success(client, admin_headers, mock_db_session, mocker):
"""
[Admin] 创建 Agent (Happy Path)
"""
# Arrange
payload = {
"name": "HR Bot",
"type": "api",
"dify_app_id": "app-uuid",
"dify_api_key": "sk-secret"
}
# Mock _get_current_user for require_admin
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_admin_create_agent_missing_fields(client, admin_headers, mocker):
"""
[Admin] 创建 Agent 失败 - 缺少必要字段 (Boundary)
"""
# Arrange
payload = {
"name": "Bad Bot",
"type": "api"
# Missing dify_app_id and dify_api_key
}
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
# Assert
assert response.status_code == 400
assert "API mode requires app_id" in response.get_json()['error']
def test_admin_delete_agent(client, admin_headers, mock_agent_query, mock_db_session, mocker):
"""
[Admin] 删除 Agent (Happy Path)
"""
# Arrange
mock_agent = Agent(id=1, name="Old Bot")
mock_agent_query.get.return_value = mock_agent
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.delete('/api/admin/agents/1', headers=admin_headers)
# Assert
assert response.status_code == 200
mock_db_session.delete.assert_called_once_with(mock_agent)
mock_db_session.commit.assert_called_once()
def test_admin_approve_user(client, admin_headers, mock_user_query, mock_db_session, mocker):
"""
[Admin] 审批用户 (Happy Path)
"""
# Arrange
mock_user = User(id=2, status="pending")
mock_user_query.get.return_value = mock_user
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/users/2/approve', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_user.status == 'active'
mock_db_session.commit.assert_called_once()
def test_admin_reject_user(client, admin_headers, mock_user_query, mock_db_session, mocker):
"""
[Admin] 拒绝用户 (Happy Path)
"""
# Arrange
mock_user = User(id=3, status="pending")
mock_user_query.get.return_value = mock_user
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/users/3/reject', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_user.status == 'rejected'
mock_db_session.commit.assert_called_once()
# -----------------------------------------------------------------------------
# 3. Chat System Tests (Mocking External API)
# -----------------------------------------------------------------------------
def test_chat_completions_stream_success(client, mocker, mock_agent_query):
"""
[Chat] 发送消息并流式返回 (Happy Path)
核心:Mock requests.post 以避免真实网络请求
"""
# Arrange
mock_post = mocker.patch('requests.post')
mock_response = MagicMock()
mock_response.status_code = 200
# Mock SSE stream lines
mock_response.iter_lines.return_value = [
b'data: {"event": "message", "answer": "Hello"}',
b'',
b'data: {"event": "message", "answer": " World"}',
b'',
b'data: {"event": "message_end", "metadata": {"usage": {"total_tokens": 10}}}'
]
mock_post.return_value.__enter__.return_value = mock_response
# Mock DB logging
mocker.patch('app.services.dify.DifyService._log_chat')
# Setup decorator mocks
mock_user = User(id=1, username="test_user")
mock_agent = Agent(id=1, name="Test Agent", dify_api_key="key", api_base_url="http://mock-api")
mock_user.agents = [mock_agent] # Grant permission
# Mock decorator dependencies
# IMPORTANT: require_agent_permission calls _get_current_user() from app.decorators
# We use side_effect to ensure g.current_user is set, as the real function does
def mock_get_user():
g.current_user = mock_user
return mock_user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
# Mock Agent.query.get used in require_agent_permission
mock_agent_query.get.return_value = mock_agent
# Act
payload = {
"query": "Hello",
"agent_id": 1,
"response_mode": "streaming"
}
headers = {'Content-Type': 'application/json'}
response = client.post('/api/chat/completions', json=payload, headers=headers)
# Assert
assert response.status_code == 200
assert response.mimetype == 'text/event-stream'
assert b'data: {"event": "message", "answer": "Hello"}' in response.data
def test_chat_completions_no_permission(client, mocker, mock_agent_query):
"""
[Chat] 无权限访问 Agent (Error)
"""
# Arrange
mock_user = User(id=1, username="test_user")
mock_agent = Agent(id=2, name="Restricted Agent")
mock_user.agents = [] # No permission
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Act
payload = {"query": "Hello", "agent_id": 2}
response = client.post('/api/chat/completions', json=payload)
# Assert
assert response.status_code == 403
assert "Permission denied" in response.get_json()['error']
def test_submit_feedback_success(client, mocker, mock_chat_log_query, mock_agent_query, mock_db_session):
"""
[Chat] 提交反馈 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mock_agent = Agent(id=1)
mock_user.agents = [mock_agent]
def mock_get_user():
g.current_user = mock_user
return mock_user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
mock_agent_query.get.return_value = mock_agent
# Mock ChatLog query
mock_log = ChatLog(id=100, user_id=1, agent_id=1, feedback=None)
mock_chat_log_query.filter_by.return_value.filter_by.return_value.order_by.return_value.first.return_value = mock_log
# Act
payload = {
"agent_id": 1,
"conversation_id": "conv_123",
"score": 5,
"comment": "Great!"
}
response = client.post('/api/chat/feedback', json=payload)
# Assert
assert response.status_code == 200
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_submit_feedback_invalid_score(client, mocker, mock_agent_query):
"""
[Chat] 提交反馈 - 分数无效 (Boundary)
"""
# Arrange
mock_user = User(id=1)
mock_agent = Agent(id=1)
mock_user.agents = [mock_agent]
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Act
payload = {"agent_id": 1, "score": 6} # Score > 5
response = client.post('/api/chat/feedback', json=payload)
# Assert
assert response.status_code == 400
assert "between 1 and 5" in response.get_json()['error']
# -----------------------------------------------------------------------------
# 4. Permission Request Tests
# -----------------------------------------------------------------------------
def test_create_permission_request(client, mocker, mock_db_session, mock_agent_query, mock_permission_request_query):
"""
[Permission] 用户申请权限 (Happy Path)
"""
# Arrange
mock_user = User(id=1, agents=[])
mock_agent = Agent(id=5)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Ensure no existing pending request
mock_permission_request_query.filter_by.return_value.first.return_value = None
# Act
payload = {"agent_id": 5, "reason": "Need access"}
response = client.post('/api/user/permission-requests', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_create_permission_request_already_exists(client, mocker, mock_agent_query, mock_permission_request_query):
"""
[Permission] 用户重复申请权限 (Error)
"""
# Arrange
mock_user = User(id=1, agents=[])
mock_agent = Agent(id=5)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Mock existing pending request
mock_permission_request_query.filter_by.return_value.first.return_value = PermissionRequest(id=1)
# Act
payload = {"agent_id": 5}
response = client.post('/api/user/permission-requests', json=payload)
# Assert
assert response.status_code == 400
assert "Request already pending" in response.get_json()['error']
def test_admin_approve_permission_request(client, admin_headers, mock_permission_request_query, mock_user_query, mock_agent_query, mock_db_session, mocker):
"""
[Admin] 同意权限申请 (Happy Path)
"""
# Arrange
mock_pr = PermissionRequest(id=1, user_id=2, agent_id=5, status='pending')
mock_user = User(id=2, agents=[])
mock_agent = Agent(id=5)
# Mock PermissionRequest.query.get
mock_permission_request_query.get.return_value = mock_pr
# Mock User.query.get
mock_user_query.get.return_value = mock_user
# Mock Agent.query.get
mock_agent_query.get.return_value = mock_agent
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/permission-requests/1/approve', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_pr.status == 'approved'
assert mock_agent in mock_user.agents
mock_db_session.commit.assert_called_once()
# -----------------------------------------------------------------------------
# 5. Quick Question Tests
# -----------------------------------------------------------------------------
def test_add_quick_question(client, mocker, mock_db_session):
"""
[QuickQuestion] 添加常用问题 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
# Act
payload = {
"title": "Daily Report",
"question": "Generate report...",
"agent_id": 1
}
response = client.post('/api/user/quick-questions', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_delete_quick_question(client, mocker, mock_db_session):
"""
[QuickQuestion] 删除常用问题 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_qq = QuickQuestion(id=10, user_id=1)
# Mock query: filter_by(id=10, user_id=1).first() -> mock_qq
mocker.patch('app.db.session.query').return_value.filter_by.return_value.first.return_value = mock_qq
# Act
response = client.delete('/api/user/quick-questions/10')
# Assert
assert response.status_code == 200
mock_db_session.delete.assert_called_once_with(mock_qq)
mock_db_session.commit.assert_called_once()
+114
View File
@@ -0,0 +1,114 @@
import pytest
from app import create_app, db
from app.models import User, Agent, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create user
user = User(username='testuser', role='user', email='test@example.com')
user.set_password('password')
db.session.add(user)
# Create agents
a1 = Agent(name='Agent 1', dify_app_id='app-1', dify_api_key='key-1')
a2 = Agent(name='Agent 2', dify_app_id='app-2', dify_api_key='key-2')
a3 = Agent(name='Agent 3', dify_app_id='app-3', dify_api_key='key-3')
db.session.add_all([a1, a2, a3])
# Grant permission
user.agents.append(a1)
user.agents.append(a2)
user.agents.append(a3)
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def get_headers(client):
res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'password'})
data = res.get_json()
return {
'X-User-Id': str(data['id']),
'X-Username': data['username'],
'X-Role': data['role']
}
def get_agent_id(client, name):
# Helper to get agent ID by name (since we can't query DB directly easily outside context without binding)
# But we can use the API
# Or just rely on order since we are in a fresh DB
# Let's assume IDs are 1, 2, 3 for now if using SQLite.
# To be safe, let's fetch from public-agents or user-home
# But we need headers for user-home.
pass
def test_favorites(client):
headers = get_headers(client)
# Get agent ID
res = client.get('/api/user/home', headers=headers)
agents = res.get_json()['agents']
agent_id = agents[0]['id']
# Add favorite
res = client.post(f'/api/user/favorites/{agent_id}', headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert agent_id in data['favorite_agent_ids']
# Remove favorite
res = client.delete(f'/api/user/favorites/{agent_id}', headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert agent_id not in data['favorite_agent_ids']
def test_homepage_layout(client):
headers = get_headers(client)
layout = {'sections': [{'id': 'favorites'}, {'id': 'all_agents'}]}
# Update layout
res = client.put('/api/user/homepage-layout', json={'layout': layout}, headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert data['layout']['sections'][0]['id'] == 'favorites'
def test_embedded_agents(client):
headers = get_headers(client)
# Get agent IDs
res = client.get('/api/user/home', headers=headers)
agents = res.get_json()['agents']
id1 = agents[0]['id']
id2 = agents[1]['id']
id3 = agents[2]['id']
# Update embedded agents
res = client.put('/api/user/embedded-agents', json={'agent_ids': [id1, id2]}, headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert len(data['embedded_agents']) == 2
assert data['embedded_agents'][0]['id'] == id1
assert data['embedded_agents'][1]['id'] == id2
# Try more than 2
res = client.put('/api/user/embedded-agents', json={'agent_ids': [id1, id2, id3]}, headers=headers)
assert res.status_code == 400
+87
View File
@@ -0,0 +1,87 @@
import pytest
from app.models import User
from app import db
def test_register_fields_validation(client):
"""
Test user registration field validation
"""
# 1. Missing fields
response = client.post('/api/user/register', json={
"username": "missing",
"password": "pwd",
"email": "m@e.com"
})
assert response.status_code == 400
assert "Real name and Employee ID are required" in response.json['error']
# 2. Duplicate Employee ID
# First create a user (via admin to bypass check or register with valid data)
# Let's register one valid user
valid_user = {
"username": "user1",
"password": "pwd",
"email": "u1@e.com",
"real_name": "User One",
"employee_id": "EMP100",
"phone_number": "13800000001"
}
response = client.post('/api/user/register', json=valid_user)
assert response.status_code == 201
# Now try to register another user with SAME employee_id
dup_user = {
"username": "user2",
"password": "pwd",
"email": "u2@e.com",
"real_name": "User Two",
"employee_id": "EMP100",
"phone_number": "13800000002"
}
response = client.post('/api/user/register', json=dup_user)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
def test_admin_duplicate_employee_id(client, admin_headers):
"""
Test admin user creation duplicate employee_id check
"""
# 1. Create first user
u1 = {
"username": "adm_u1",
"password": "pwd",
"email": "au1@e.com",
"real_name": "Admin User 1",
"employee_id": "ADM001"
}
response = client.post('/api/admin/users', json=u1, headers=admin_headers)
assert response.status_code == 201
# 2. Create second user with same ID
u2 = {
"username": "adm_u2",
"password": "pwd",
"email": "au2@e.com",
"real_name": "Admin User 2",
"employee_id": "ADM001"
}
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
# 3. Update user to duplicate ID
# Create u3 with valid ID
u3 = {
"username": "adm_u3",
"password": "pwd",
"email": "au3@e.com",
"real_name": "Admin User 3",
"employee_id": "ADM003"
}
res = client.post('/api/admin/users', json=u3, headers=admin_headers)
u3_id = res.json['id']
# Update u3 to ADM001 (which exists)
res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers)
assert res.status_code == 400
assert "Employee ID already exists" in res.json['error']
Executable
+47
View File
@@ -0,0 +1,47 @@
#!/bin/bash
# deploy.sh
# 服务器部署脚本
SERVER_IP="192.168.100.230"
REMOTE_USER="inspur"
REMOTE_DIR="/data/hxops"
echo "=== 开始部署流程 ==="
# 1. 确保本地无未提交代码 (可选)
# git status
# 2. 将代码同步到服务器
echo ">> 同步代码到服务器..."
rsync -avz --exclude 'venv' --exclude 'node_modules' --exclude '.git' --exclude '__pycache__' \
./ $REMOTE_USER@$SERVER_IP:$REMOTE_DIR
# 3. 在服务器上构建并重启
echo ">> 远程构建并重启服务..."
ssh $REMOTE_USER@$SERVER_IP << EOF
cd $REMOTE_DIR
# 确保目录存在
mkdir -p backend/logs
# 加载环境变量 (如果存在 .env)
if [ -f .env ]; then
export \$(cat .env | xargs)
fi
# Docker Compose 重启
# 注意:首次运行需确保 hxops_prod 数据库已创建
# PGPASSWORD=difyai123456 createdb -h localhost -U postgres hxops_prod || true
sudo docker compose down
sudo docker compose build
sudo docker compose up -d
# 执行数据库迁移 (在 backend 容器内)
echo ">> 执行数据库迁移..."
sudo docker compose exec -T backend flask db upgrade
echo "=== 部署完成 ==="
sudo docker compose ps
EOF
+31
View File
@@ -0,0 +1,31 @@
version: '3.8'
services:
backend:
build: ./backend
container_name: hxops-backend
restart: always
environment:
- FLASK_APP=run.py
- FLASK_ENV=production
# 注意:在宿主机上通过 host.docker.internal 访问宿主机服务(仅限 Docker Desktop for Mac/Windows)
# Linux 服务器上通常用 172.17.0.1 或宿主机 IP
# 这里预填服务器 IP
- DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_prod
- REDIS_URL=redis://:difyai123456@192.168.100.230:6379/0
- DIFY_API_BASE=http://192.168.100.230:8882/v1
# 请在 .env 文件中配置 DIFY_API_KEY
volumes:
- ./backend:/app
expose:
- "8000"
frontend:
build: ./frontend
container_name: hxops-frontend
restart: always
ports:
- "8881:80"
depends_on:
- backend
File diff suppressed because it is too large. Load diff
+412
View File
@@ -0,0 +1,412 @@
# OpenClaw Gateway 启动问题排查记录
## 任务背景
用户遇到电脑启动问题,具体是在尝试启动 OpenClaw Gateway 服务时遇到了错误。本文档详细记录了排查过程中的每一步操作及其背后的用途与语法。
## 排查过程
### 步骤 1:检查项目结构并创建文档目录
**执行命令**:
```bash
mkdir -p docs
```
**命令用途**:
创建项目的文档目录,用于存放本次排查的知识记录文件。
**命令详细解释**:
- `mkdir`:创建目录的命令
- `-p`:递归创建目录,如果父目录不存在也会创建
- `docs`:要创建的目录名称
**执行输出**:
```
(TraeAI-1) ~/Documents/dev/AI/hxops [0] $ trae-sandbox 'mkdir -p docs'
(TraeAI-1) ~/Documents/dev/AI/hxops [0] $
```
### 步骤 2:检查 OpenClaw 版本
**执行命令**:
```bash
openclaw --version
```
**命令用途**:
确认 OpenClaw 工具是否正确安装,并查看其版本信息。
**命令详细解释**:
- `openclaw`:OpenClaw 命令行工具
- `--version`:显示版本信息的参数
**执行输出**:
```
(TraeAI-1) ~/Documents/dev/AI/hxops [0] $ trae-sandbox 'openclaw --version'
2026.2.15
(TraeAI-1) ~/Documents/dev/AI/hxops [0] $
```
### 步骤 3:尝试安装 Gateway 服务
**执行命令**:
```bash
openclaw gateway install
```
**命令用途**:
根据错误提示,尝试安装 Gateway 服务。
**命令详细解释**:
- `openclaw`:OpenClaw 命令行工具
- `gateway`:Gateway 服务子命令
- `install`:安装 Gateway 服务的参数
**执行输出**:
```
(TraeAI-1) ~/Documents/dev/AI/hxops [0] $ trae-sandbox 'openclaw gateway install'
🦞 OpenClaw 2026.2.15 (3fe22ea)
Automation with claws: minimal fuss, maximal pinch.
Gateway install failed: Error: EPERM: operation not permitted, open '/Users/teemo/Library/LaunchAgents/ai.openclaw.gateway.plist'
(TraeAI-1) ~/Documents/dev/AI/hxops [1] $
```
### 步骤 4:使用 sudo 权限安装 Gateway 服务
**执行命令**:
```bash
sudo openclaw gateway install
```
**命令用途**:
使用管理员权限尝试安装 Gateway 服务,解决权限不足的问题。
**命令详细解释**:
- `sudo`:以管理员权限执行命令
- `openclaw gateway install`:安装 Gateway 服务的命令
**执行输出**:
```
(TraeAI-1) ~/Documents/dev/AI/hxops [1] $ sudo openclaw gateway install
Password:
🦞 OpenClaw 2026.2.15 (3fe22ea)
Type the command with confidence—nature will provide the stack trace if needed.
Gateway install failed: Error: launchctl bootstrap failed: Bootstrap failed: 125: Domain does not support specified action
(TraeAI-1) ~/Documents/dev/AI/hxops [1] $
```
### 步骤 5:尝试使用 launchctl 手动安装
**执行命令**:
```bash
launchctl bootstrap gui/$UID ~/Library/LaunchAgents/ai.openclaw.gateway.plist
```
**命令用途**:
根据错误提示中的建议,尝试使用 launchctl 命令手动引导启动 Gateway 服务。
**命令详细解释**:
- `launchctl`:macOS 系统的服务管理工具
- `bootstrap`:引导加载服务的命令
- `gui/$UID`:指定用户会话域,$UID 是当前用户的 ID
- `~/Library/LaunchAgents/ai.openclaw.gateway.plist`:服务配置文件的路径
**执行输出**:
```
trae-sandbox 'launchctl bootstrap gui/$UID ~/Library/LaunchAgents/ai.openclaw.gateway.plist'
Bootstrap failed: 5: Input/output error
Try re-running the command as root for richer errors.
(TraeAI-1) ~/Documents/dev/AI/hxops [5] $
```
### 步骤 6:检查 LaunchAgents 目录中的 plist 文件
**执行命令**:
```bash
ls -la ~/Library/LaunchAgents/ | grep openclaw
```
**命令用途**:
检查 LaunchAgents 目录中是否存在 OpenClaw 的配置文件。
**命令详细解释**:
- `ls -la`:列出目录中的所有文件,包括隐藏文件和详细信息
- `~/Library/LaunchAgents/`:用户的 LaunchAgents 目录路径
- `|`:管道符号,将前一个命令的输出传递给后一个命令
- `grep openclaw`:筛选包含 "openclaw" 的行
**执行输出**:
```
ls -la ~/Library/LaunchAgents/ | grep openclaw
-rw-r--r--@ 1 teemo staff 1613 Feb 19 23:00 ai.openclaw.gateway.plist
(TraeAI-1) ~/Documents/dev/AI/hxops [0] $
```
### 步骤 7:查看 plist 文件内容
**执行命令**:
```bash
cat ~/Library/LaunchAgents/ai.openclaw.gateway.plist
```
**命令用途**:
查看 Gateway 服务的配置文件内容,了解服务的具体配置。
**命令详细解释**:
- `cat`:查看文件内容的命令
- `~/Library/LaunchAgents/ai.openclaw.gateway.plist`:配置文件的路径
**执行输出**:
```
cat ~/Library/LaunchAgents/ai.openclaw.gateway.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>ai.openclaw.gateway</string>
<key>Comment</key>
<string>OpenClaw Gateway (v2026.2.15)</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/node</string>
<string>/opt/homebrew/lib/node_modules/openclaw/dist/index.js</string>
<string>gateway</string>
<string>--port</string>
<string>18789</string>
</array>
<key>StandardOutPath</key>
<string>/Users/teemo/.openclaw/logs/gateway.log</string>
<key>StandardErrorPath</key>
<string>/Users/teemo/.openclaw/logs/gateway.err.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>/Users/teemo</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
<key>OPENCLAW_GATEWAY_PORT</key>
<string>18789</string>
<key>OPENCLAW_GATEWAY_TOKEN</key>
<string>a42c3bd4bf35ad4b10fed405e79a5b23c54d9b361933f9fd</string>
<key>OPENCLAW_LAUNCHD_LABEL</key>
<string>ai.openclaw.gateway</string>
<key>OPENCLAW_SYSTEMD_UNIT</key>
<string>openclaw-gateway.service</string>
<key>OPENCLAW_SERVICE_MARKER</key>
<string>openclaw</string>
<key>OPENCLAW_SERVICE_KIND</key>
<string>gateway</string>
<key>OPENCLAW_SERVICE_VERSION</key>
<string>2026.2.15</string>
</dict>
</dict>
</plist>
(TraeAI-1) ~/Documents/dev/AI/hxops [0] $
```
## 问题分析
### 问题现象
用户在尝试启动 OpenClaw Gateway 服务时遇到了以下错误:
```
Gateway service not loaded.
Start with: openclaw gateway install
Start with: openclaw gateway
Start with: launchctl bootstrap gui/$UID ~/Library/LaunchAgents/ai.openclaw.gateway.plist
```
### 排查结果
1. OpenClaw 工具已正确安装,版本为 2026.2.15
2. 尝试安装 Gateway 服务时遇到权限问题
3. 使用 sudo 权限安装时遇到 Bootstrap 失败错误
4. 尝试手动使用 launchctl 引导时遇到 I/O 错误
5. LaunchAgents 目录中已存在 ai.openclaw.gateway.plist 文件
6. plist 文件配置看起来正常,包含了正确的服务配置
### 可能的问题原因
1. 权限问题:虽然使用了 sudo,但可能仍存在权限不足的问题
2. 服务冲突:可能有其他服务占用了相同的端口或资源
3. 配置文件问题:plist 文件可能存在隐藏的格式问题
4. 系统兼容性问题:当前系统版本可能与 OpenClaw 版本不兼容
## 解决方案
### 日志分析
通过检查日志文件 `~/.openclaw/logs/gateway.err.log`,发现了具体的错误原因:
```
2026-02-17T18:36:59.818+08:00 Gateway start blocked: set gateway.mode=local (current: unset) or pass --allow-unconfigured.
2026-02-17T18:36:59.821+08:00 Config write audit: /Users/teemo/.openclaw/logs/config-audit.jsonl
```
**错误原因**:Gateway 服务启动被阻止,因为缺少 `gateway.mode` 配置,当前状态为 "unset"。
### 建议尝试的步骤
1. **设置 gateway.mode 配置**:
```bash
openclaw config set gateway.mode local
```
2. **或者使用 --allow-unconfigured 参数启动**:
```bash
openclaw gateway start --allow-unconfigured
```
3. **检查端口占用**:
```bash
lsof -i :18789
```
4. **检查日志文件**:
```bash
ls -la ~/.openclaw/logs/
cat ~/.openclaw/logs/gateway.err.log
```
5. **尝试重新创建 plist 文件**:
```bash
rm ~/Library/LaunchAgents/ai.openclaw.gateway.plist
openclaw gateway install
```
6. **检查 Node.js 安装**:
```bash
node --version
which node
```
7. **尝试直接启动 Gateway**:
```bash
openclaw gateway
```
## 总结
本次排查过程中,我们:
1. 创建了文档目录用于存放知识记录
2. 确认了 OpenClaw 工具的版本
3. 尝试了多种安装 Gateway 服务的方法
4. 检查了服务配置文件的状态和内容
5. 分析了可能的问题原因
6. 检查了日志文件,发现了具体的错误原因
7. 提供了详细的解决方案
通过检查日志文件,我们发现了 Gateway 服务启动失败的具体原因:缺少 `gateway.mode` 配置。这是一个关键的配置项,需要设置为 "local" 或者在启动时使用 `--allow-unconfigured` 参数。
### 关键知识点
1. **macOS 服务管理**:
- `launchctl` 是 macOS 系统的服务管理工具
- 服务配置文件通常存放在 `~/Library/LaunchAgents/` 目录
2. **OpenClaw 服务管理**:
- `openclaw gateway install` 用于安装 Gateway 服务
- `openclaw gateway start` 用于启动 Gateway 服务
- `openclaw config set` 用于设置配置项
3. **OpenClaw 配置管理**:
- `gateway.mode` 是 Gateway 服务的必要配置项
- 可以设置为 "local" 模式
- 或者使用 `--allow-unconfigured` 参数跳过配置检查
4. **权限管理**:
- `sudo` 命令可以临时获取管理员权限
- 某些系统操作需要管理员权限才能执行
5. **排错技巧**:
- 查看错误信息中的建议
- 检查配置文件的内容和权限
- 查看日志文件获取详细错误信息
- 检查端口占用情况
### 实际操作与解决方案
### 执行的操作步骤
1. **设置 gateway.mode 配置**(需要 sudo 权限):
```bash
sudo openclaw config set gateway.mode local
```
**执行输出**:
```
Config overwrite: /Users/teemo/.openclaw/openclaw.json (sha256 7f0b8d21cb7a93d63d1c88ac5283755466a910ca4e19d1437daf8db3059b1a84 -> b04724b773c7fa9308dd31b5e4fcb87de2f5dcffc4ed3dcb7eeb3b2e8ff4ce2f, backup=/Users/teemo/.openclaw/openclaw.json.bak)
Updated gateway.mode. Restart the gateway to apply.
```
2. **修复配置文件权限**:
```bash
sudo chown teemo:staff /Users/teemo/.openclaw/openclaw.json
```
3. **启动 Gateway 服务**:
```bash
openclaw gateway
```
**执行输出**:
```
15:07:33 [canvas] host mounted at http://127.0.0.1:18789/__openclaw__/canvas/ (root /Users/teemo/.openclaw/canvas)
15:07:34 [heartbeat] started
15:07:34 [gateway] agent model: vllm//data/ai-platform/models/Qwen2.5-72B-Instruct-GPTQ-Int4
15:07:34 [gateway] listening on ws://127.0.0.1:18789 (PID 95771)
15:07:34 [gateway] listening on ws://[::1]:18789
15:07:34 [gateway] log file: /tmp/openclaw/openclaw-2026-02-19.log
15:07:34 [browser/service] Browser control service ready (profiles=2)
```
### 最终解决方案
根据实际操作,解决 OpenClaw Gateway 服务启动问题的完整步骤是:
1. **设置 gateway.mode 配置**(需要 sudo 权限):
```bash
sudo openclaw config set gateway.mode local
```
2. **修复配置文件权限**:
```bash
sudo chown teemo:staff /Users/teemo/.openclaw/openclaw.json
```
3. **启动 Gateway 服务**:
```bash
openclaw gateway
```
**替代方案**:如果不想修改配置,也可以使用 `--allow-unconfigured` 参数启动:
```bash
openclaw gateway start --allow-unconfigured
```
### 服务状态
Gateway 服务已经成功启动,正在监听以下地址:
- ws://127.0.0.1:18789
- ws://[::1]:18789
服务运行正常,包含以下组件:
- Canvas 服务
- 心跳服务
- 浏览器控制服务
**注意**:虽然有一个关于 cron 服务的权限错误和版本更新提示,但这些都不影响 Gateway 服务的核心功能。
+124
View File
@@ -0,0 +1,124 @@
# Enterprise AI Gateway Project Context
## 1. 🚀 项目一句话概述
这是一个企业级 AI 聚合网关平台,旨在统一管理和分发各类 AI Agent(如 Dify 应用),为企业内部提供统一的 AI 对话入口、权限控制(RBAC)、审计日志及个性化工作台功能。
## 2. 🛠 核心技术栈 (Tech Stack)
### 前端 (Frontend)
- **框架**: Vue 3 (Composition API) + TypeScript
- **构建工具**: Vite
- **UI 框架**: TailwindCSS + Lucide Icons
- **路由**: Vue Router 4
- **国际化**: Vue I18n
- **网络请求**: 原生 Fetch API (用于 SSE 流式传输) + Axios (常规请求)
### 后端 (Backend)
- **框架**: Flask (Python 3.12)
- **ORM**: SQLAlchemy (Flask-SQLAlchemy)
- **数据库迁移**: Alembic (Flask-Migrate)
- **服务器**: Gunicorn (生产) / Werkzeug (开发)
- **依赖库**: `requests` (HTTP调用), `pydantic` (数据验证)
### 基础设施 (Infrastructure)
- **数据库**: PostgreSQL
- **缓存**: Redis (用于 Session 或 任务队列,可选)
- **容器化**: Docker + Docker Compose
## 3. 📂 核心目录结构 (Directory Structure)
```text
hxops/
├── backend/ # Flask 后端根目录
│ ├── app/
│ │ ├── api/ # API 路由蓝图 (Blueprints)
│ │ │ ├── admin.py # 管理员接口 (Agent管理, 部门管理)
│ │ │ ├── chat.py # 对话接口 (SSE流式代理)
│ │ │ ├── user.py # 用户端接口 (首页, 收藏, 常用问题)
│ │ │ └── ...
│ │ ├── services/ # 业务逻辑层
│ │ │ └── dify.py # Dify API 集成服务 (核心)
│ │ ├── models.py # 数据库模型定义
│ │ ├── decorators.py # 权限控制装饰器
│ │ └── __init__.py # App 工厂函数
│ ├── migrations/ # 数据库迁移脚本
│ ├── run.py # 启动入口 (端口 5002)
│ └── requirements.txt # Python 依赖
├── frontend/ # Vue 前端根目录
│ ├── src/
│ │ ├── composables/ # 组合式函数
│ │ │ └── useChat.ts # 聊天逻辑封装 (SSE 处理)
│ │ ├── views/ # 页面组件
│ │ │ ├── AdminView.vue # 管理后台
│ │ │ ├── ChatView.vue # 对话界面
│ │ │ └── WorkspaceView.vue # 用户工作台
│ │ ├── router/ # 路由配置
│ │ └── main.ts # 入口文件
│ └── vite.config.ts # Vite 配置 (含代理设置)
├── docs/ # 项目文档
│ └── k_Enterprise_AI_Gateway_Architecture_*.md # 架构文档
└── scripts/ # 运维与测试脚本
├── mock_dify_server.py # 模拟 Dify 服务
└── test_chat_flow.py # 对话流程测试脚本
```
## 4. 🔄 核心业务流与架构设计
### 4.1 前后端交互规范
- **API 前缀**: `/api` (如 `/api/chat/completions`, `/api/admin/agents`)
- **跨域处理**: 开发环境通过 Vite Proxy (`frontend/vite.config.ts`) 转发 `/api` 请求到后端端口 (5002)。
- **响应格式**: 标准 RESTful JSON,流式接口使用 Server-Sent Events (SSE)。
### 4.2 鉴权流程 (Simplified RBAC)
- **当前机制**: 基于 Header 的简易认证 (开发/网关模式)。
- **前端**: `useChat.ts` 或请求拦截器中自动注入 `X-User-Id`, `X-Username`, `X-Role` 头。
- **后端**: `app/decorators.py` 中的 `_get_current_user` 解析 Header,自动查找或创建(Lazy Create)数据库用户对象,并注入到 Flask全局变量 `g` 中。
### 4.3 核心链路:AI 对话流
1. **用户提问**: 前端 `ChatView` 调用 `useChat.sendMessage`,发起 `POST /api/chat/completions`。
2. **权限校验**: 后端 `chat.py` 使用 `@require_agent_permission` 校验用户是否有权访问该 Agent。
3. **代理转发**: 调用 `DifyService.stream_chat`,使用 Agent 配置的 API Key 向 Dify 服务发起请求。
4. **流式响应**: Dify 返回 SSE 数据流,后端通过 Python生成器 (`yield`) 逐块透传给前端。
5. **审计记录**: 对话结束 (`message_end` 事件) 时,后端自动将完整问答、Token 消耗、耗时写入 `chat_logs` 表。
## 5. 🗄️ 核心数据模型 (Database Models)
- **User**: 用户表 (id, username, role, department)。
- **Agent**: AI 应用配置表 (id, name, dify_app_id, dify_api_key, api_base_url)。
- *关键字段*: `type` (api/iframe), `is_active`。
- **user_agent_permissions**: 多对多关联表,控制 User 对 Agent 的访问权限。
- **ChatLog**: 审计日志表 (user_id, agent_id, query, answer, tokens_used, conversation_id)。
- **UserHomepageConfig**: 用户个性化配置 (收藏的 Agent, 首页布局)。
## 6. 📝 待办事项与技术债 (TODOs)
- [ ] **鉴权升级**: 目前使用 Header 透传用户信息,生产环境需对接 SSO (OAuth2/OIDC) 并发放真实 JWT。
- [ ] **网络连通性**: Dify 真实服务 (`192.168.100.230`) 目前不可达,暂时使用了本地 Mock Server (`127.0.0.1:5001`)。需解决网络/防火墙问题。
- [ ] **端口规范**: 后端已从 5000 迁至 5002 以避开 macOS 端口冲突,需确保部署脚本同步更新。
- [ ] **前端重构**: `fetch` 与 `axios` 混用,建议统一封装请求库。
## 7. 🤖 【重要】AI 接手专属 Context 提示词
```text
你好,我需要你帮我开发/调试一个“企业级 AI 聚合网关”项目。
以下是项目的基础上下文,请阅读并记住,后续你的所有代码生成都必须遵循以下架构和规范:
1. **技术栈**:
- 前端: Vue 3 + TypeScript + TailwindCSS + Vite。
- 后端: Flask + SQLAlchemy + PostgreSQL (端口 5002)。
2. **核心业务**:
- 这是一个 BFF (Backend for Frontend) 系统,代理用户请求转发给底层 LLM 服务 (如 Dify)。
- 核心功能是 SSE 流式对话、Agent 权限管理(RBAC)、审计日志记录。
3. **关键代码逻辑**:
- 对话逻辑: 前端 `useChat.ts` -> 后端 `api/chat.py` -> `services/dify.py`。
- 鉴权逻辑: 依赖 `X-User-Id` 请求头,通过 `decorators.py` 实现用户自动注入。
4. **数据模型**:
- `Agent` 表存储 Dify API Key 和 Base URL。
- `ChatLog` 表记录所有对话详情。
5. **注意事项**:
- 所有的 API 请求都必须通过 `/api` 前缀。
- 开发环境后端运行在 5002 端口 (5000 被 macOS 占用)。
- 当前连接的是本地 Mock Dify Server (5001),因远程服务网络不通。
- 修改数据库模型后必须生成并应用 Alembic 迁移。
```
+34
View File
@@ -0,0 +1,34 @@
# 企业 AI 网关功能测试矩阵 (Enterprise AI Gateway Test Matrix)
本文档旨在对系统的所有功能进行提炼,并规范化测试代码的撰写要求。
## 1. 测试代码撰写通用要求
所有测试代码必须遵循以下三层注释标准:
1. **文件层注释**:注明文件用途、引用的模块、逻辑关系。
2. **函数层注释**:在函数名上方说明其用途、核心逻辑与实现方式,对传参与输出进行说明。
3. **代码层注释**:在函数内部,对关键代码行进行注释,解释逻辑意图。
---
## 2. 功能测试矩阵
| 功能分类 | 功能子项 | 功能描述 | 测试代码撰写要求 | 测试输入数据 (示例) | 预期测试输出 (示例) |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **用户认证** | **用户注册** | 新用户通过填写表单提交注册申请,状态默认为 `pending`。需校验手机号、工号唯一性。 | 模拟 POST 请求 `/api/user/register`,验证必填字段缺失、字段重复等异常场景。 | `{ "username": "test_user", "password": "pwd", "email": "test@e.com", "real_name": "张三", "employee_id": "EMP001", "phone_number": "13800000000" }` | HTTP 201 Created; 返回 `{"id": 1}`;数据库中状态为 `pending`。 |
| **用户认证** | **用户登录** | 用户通过用户名/密码登录,系统校验状态是否为 `active`。 | 模拟 POST `/api/user/login`。测试:1. 正常登录; 2. 密码错误; 3. 未审批用户登录(403)。 | `{ "username": "test_user", "password": "pwd" }` | HTTP 200 OK; 返回 `{"id": 1, "username": "test_user", "role": "user"}`。 |
| **用户管理** | **审批用户** | 管理员将注册申请状态的用户置为 `active`。 | 模拟 Admin 身份 POST `/api/admin/users/{id}/approve`。 | Header: `X-Role: admin`, URL Path: `/api/admin/users/1/approve` | HTTP 200 OK; 数据库中该用户 `status` 变更为 `active`。 |
| **用户管理** | **拒绝用户** | 管理员拒绝注册申请,将用户状态置为 `rejected`。 | 模拟 Admin 身份 POST `/api/admin/users/{id}/reject`。验证非 Admin 调用应返回 403。 | Header: `X-Role: admin`, URL Path: `/api/admin/users/1/reject` | HTTP 200 OK; 数据库中该用户 `status` 变更为 `rejected`。 |
| **用户管理** | **用户列表** | 管理员查看所有用户,支持过滤状态。 | 模拟 Admin GET `/api/admin/users`。 | Header: `X-Role: admin` | HTTP 200 OK; 返回用户列表 JSON 数组。 |
| **Agent 管理** | **创建 Agent** | 管理员接入新的 Dify 应用 (API 模式或 Iframe 模式)。 | 模拟 Admin POST `/api/admin/agents`。测试必填项校验。 | `{ "name": "HR Assistant", "type": "api", "dify_app_id": "uuid", "dify_api_key": "sk-..." }` | HTTP 201 Created; 返回 `{"id": 1}`。 |
| **Agent 管理** | **更新 Agent** | 管理员修改 Agent 配置 (如名称、描述、API Key)。 | 模拟 Admin PUT `/api/admin/agents/{id}`。 | `{ "description": "Updated Desc" }` | HTTP 200 OK; 数据库中字段更新成功。 |
| **Agent 管理** | **删除 Agent** | 管理员删除不再使用的 Agent。 | 模拟 Admin DELETE `/api/admin/agents/{id}`。测试删除不存在的 ID (404)。 | URL Path: `/api/admin/agents/1` | HTTP 200 OK; 再次查询该 ID 返回 404 或空。 |
| **权限管理** | **分配权限** | 管理员为用户分配可访问的 Agent (多对多关系)。 | 模拟 Admin PUT `/api/admin/users/{id}` (带 `agent_ids`)。 | `{ "agent_ids": [1, 2] }` | HTTP 200 OK; 数据库 `user_agent_permissions` 表新增关联记录。 |
| **权限管理** | **权限验证** | 用户访问 Agent 列表或对话接口时,系统校验其是否有权访问该 Agent。 | 1. 模拟 User 登录; 2. 访问未授权 Agent 的对话接口。 | Header: `X-Username: user1`, URL: `/api/chat/messages` (agent_id=99) | HTTP 403 Forbidden; 返回错误提示 "Access denied"。 |
| **权限管理** | **我的应用** | 用户登录后,只展示其拥有权限的 Agent 列表。 | 模拟 User GET `/api/user/home`。 | Header: `X-Username: user1` | HTTP 200 OK; 返回 JSON 中 `agents` 列表仅包含已授权项。 |
| **对话系统** | **发送消息** | 用户向 Agent 发送对话,系统转发至 Dify 并流式返回。 | 模拟 User POST `/api/chat/messages`。需 Mock Dify API 的响应。 | `{ "query": "Hello", "agent_id": 1, "inputs": {}, "response_mode": "streaming" }` | HTTP 200 OK (Stream); 返回流式 SSE 数据或 JSON。 |
| **对话系统** | **对话历史** | 获取用户与 Agent 的历史对话记录。 | 模拟 User GET `/api/chat/history?agent_id=1`。 | Query Param: `agent_id=1` | HTTP 200 OK; 返回 `ChatLog` 列表。 |
| **对话系统** | **反馈评价** | 用户对某次对话结果进行评分 (1-5分) 和评论。 | 模拟 User POST `/api/chat/feedbacks`。 | `{ "message_id": "msg_123", "rating": 5, "content": "Good job" }` | HTTP 200 OK; 数据库 `feedbacks` 表新增记录。 |
| **个性化** | **常用问题** | 用户添加/删除自定义的常用问题 (Quick Questions)。 | 模拟 User POST/DELETE `/api/user/quick-questions`。 | `{ "title": "日报", "question": "写一份日报", "agent_id": 1 }` | HTTP 201 Created; 再次查询列表能看到该问题。 |
| **报表监控** | **仪表盘** | 管理员查看系统概览 (Agent 数、用户数、对话总数)。 | 模拟 Admin GET `/api/admin/dashboard` (或各统计接口)。 | Header: `X-Role: admin` | HTTP 200 OK; 返回 `{ "total_agents": 10, "total_users": 50 ... }`。 |
| **报表监控** | **数据导出** | 管理员导出用户、日志等数据为 Excel/CSV。 | 模拟 Admin GET `/api/admin/database/{table_name}`。 | URL Path: `/api/admin/database/chat_logs` | HTTP 200 OK; 返回完整数据列表。 |
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+15
View File
@@ -0,0 +1,15 @@
# frontend/Dockerfile
# Build Stage
FROM node:20-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# Production Stage
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
+5
View File
@@ -0,0 +1,5 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
Single-database configuration for Flask.
+50
View File
@@ -0,0 +1,50 @@
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic,flask_migrate
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[logger_flask_migrate]
level = INFO
handlers =
qualname = flask_migrate
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+113
View File
@@ -0,0 +1,113 @@
import logging
from logging.config import fileConfig
from flask import current_app
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
def get_engine():
try:
# this works with Flask-SQLAlchemy<3 and Alchemical
return current_app.extensions['migrate'].db.get_engine()
except (TypeError, AttributeError):
# this works with Flask-SQLAlchemy>=3
return current_app.extensions['migrate'].db.engine
def get_engine_url():
try:
return get_engine().url.render_as_string(hide_password=False).replace(
'%', '%%')
except AttributeError:
return str(get_engine().url).replace('%', '%%')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
config.set_main_option('sqlalchemy.url', get_engine_url())
target_db = current_app.extensions['migrate'].db
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def get_metadata():
if hasattr(target_db, 'metadatas'):
return target_db.metadatas[None]
return target_db.metadata
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=get_metadata(), literal_binds=True
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
conf_args = current_app.extensions['migrate'].configure_args
if conf_args.get("process_revision_directives") is None:
conf_args["process_revision_directives"] = process_revision_directives
connectable = get_engine()
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=get_metadata(),
**conf_args
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+24
View File
@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
@@ -0,0 +1,101 @@
"""Initial migration
Revision ID: 7e0f9be4da73
Revises:
Create Date: 2026-02-22 22:06:59.375138
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7e0f9be4da73'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('icon_url', sa.String(length=255), nullable=True),
sa.Column('dify_app_id', sa.String(length=100), nullable=False),
sa.Column('dify_api_key', sa.String(length=100), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('dify_app_id')
)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=50), nullable=False),
sa.Column('email', sa.String(length=100), nullable=False),
sa.Column('department', sa.String(length=100), nullable=True),
sa.Column('role', sa.String(length=20), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_users_username'), ['username'], unique=True)
op.create_table('chat_logs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('conversation_id', sa.String(length=100), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('query', sa.Text(), nullable=False),
sa.Column('answer', sa.Text(), nullable=True),
sa.Column('tokens_used', sa.Integer(), nullable=False),
sa.Column('latency_ms', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_chat_logs_agent_id'), ['agent_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_conversation_id'), ['conversation_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_user_id'), ['user_id'], unique=False)
op.create_table('user_agent_permissions',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
op.create_table('feedbacks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('chat_log_id', sa.Integer(), nullable=False),
sa.Column('score', sa.Integer(), nullable=False),
sa.Column('tags', sa.JSON(), nullable=True),
sa.Column('comment', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['chat_log_id'], ['chat_logs.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('chat_log_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('feedbacks')
op.drop_table('user_agent_permissions')
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_chat_logs_user_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_created_at'))
batch_op.drop_index(batch_op.f('ix_chat_logs_conversation_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_agent_id'))
op.drop_table('chat_logs')
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_users_username'))
op.drop_table('users')
op.drop_table('agents')
# ### end Alembic commands ###
+24
View File
@@ -0,0 +1,24 @@
# frontend/nginx.conf
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 反代 BFF
location /api/ {
proxy_pass http://backend:8000;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
+2741
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/typography": "^0.5.19",
"axios": "^1.13.5",
"lucide-vue-next": "^0.575.0",
"vue": "^3.5.25",
"vue-i18n": "^11.2.8",
"vue-router": "^4.6.4",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@types/node": "^24.10.1",
"@vitejs/plugin-vue": "^6.0.2",
"@vue/tsconfig": "^0.8.1",
"autoprefixer": "^10.4.24",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "~5.9.3",
"vite": "^8.0.0-beta.13",
"vue-tsc": "^3.1.5"
},
"overrides": {
"vite": "^8.0.0-beta.13"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+64
View File
@@ -0,0 +1,64 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
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<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
const updateLanguagePreference = async (lang: string) => {
const headers = getAuthHeaders();
if (Object.keys(headers).length === 0) return; // Not logged in
try {
await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify({ language: lang })
});
} catch (e) {
console.error('Failed to update language preference', e);
}
};
watch(locale, (newLang) => {
updateLanguagePreference(newLang as string);
});
onMounted(async () => {
const headers = getAuthHeaders();
if (Object.keys(headers).length > 0) {
try {
// Try to fetch profile to get language, or rely on WorkspaceView to load it?
// Since WorkspaceView loads user home which includes language now, we might want to sync from there?
// Or just fetch home here quickly.
const res = await fetch('/api/user/home', { headers });
if (res.ok) {
const data = await res.json();
if (data.user && data.user.language) {
locale.value = data.user.language;
}
}
} catch (e) {
console.error('Failed to sync language', e);
}
}
});
</script>
<template>
<router-view />
</template>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

+41
View File
@@ -0,0 +1,41 @@
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
+127
View File
@@ -0,0 +1,127 @@
/**
* frontend/src/composables/useChat.ts
* 文件用途:前端 SSE 聊天 Hook
* 引用文件:vue
* 逻辑关系:封装 Fetch API 处理流式响应,供 ChatView 组件使用
*/
import { ref } from 'vue';
export function useChat() {
/**
* messages: 响应式消息列表,用于 UI 渲染
* 结构: [{ role: 'user'|'assistant', content: string }]
*/
const messages = ref<any[]>([]);
/**
* isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用
*/
const isThinking = ref(false);
/**
* conversationId: 当前会话 ID
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
*/
const conversationId = ref<string | null>(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<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
/**
* sendMessage
* 用途:发送消息并处理 SSE 流式响应
* 核心逻辑:
* 1. 乐观更新 UI (立即显示用户消息)
* 2. 创建空的 AI 消息占位
* 3. 发起 Fetch POST 请求
* 4. 获取 Reader 流式读取
* 5. 逐块解码并追加到当前 AI 消息中
* 参数:
* query: 用户输入文本
* agentId: 目标 Agent ID
*/
const sendMessage = async (query: string, agentId: number) => {
// 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query });
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
const botMsgIndex = messages.value.push({ role: 'assistant', content: '' }) - 1;
isThinking.value = true;
try {
// 指向本地 Flask 端口 (需通过 Vite Proxy 转发到 5000)
const response = await fetch('/api/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
query,
agent_id: agentId,
conversation_id: conversationId.value,
})
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.error || `Request failed with status ${response.status}`);
}
// 获取 ReadableStream 读取器
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) throw new Error('No reader');
// 循环读取流数据
while (true) {
const { done, value } = await reader.read();
if (done) break;
// 解码二进制块为文本
const chunk = decoder.decode(value);
// SSE 数据可能包含多行,按双换行符分割
const lines = chunk.split('\n\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
// 解析 JSON 数据
const data = JSON.parse(line.slice(6));
// 仅处理 message 事件,追加 answer 到当前消息
if (data.event === 'message') {
messages.value[botMsgIndex].content += data.answer;
} else if (data.event === 'message_end') {
// 记录会话 ID,便于后续发送反馈
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
} else if (data.event === 'error') {
messages.value[botMsgIndex].content += `\n[Error: ${data.message}]`;
}
} catch (e) {
// 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON)
}
}
}
}
} catch (e: any) {
console.error(e);
messages.value[botMsgIndex].content += `\n[Error: ${e.message || 'Network Issue'}]`;
} finally {
isThinking.value = false;
}
};
return { messages, isThinking, conversationId, sendMessage };
}
+1558
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
import i18n from './i18n'
createApp(App)
.use(router)
.use(i18n)
.mount('#app')
+37
View File
@@ -0,0 +1,37 @@
import { createRouter, createWebHistory } from 'vue-router';
import WorkspaceView from '../views/WorkspaceView.vue';
import ChatView from '../views/ChatView.vue';
import AdminView from '../views/AdminView.vue';
const routes = [
{
path: '/',
redirect: '/workspace'
},
{
path: '/workspace',
name: 'Workspace',
component: WorkspaceView
},
{
path: '/chat/:agentId',
name: 'Chat',
component: ChatView,
props: true
},
{
path: '/admin',
name: 'Admin',
component: AdminView
},
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
+71
View File
@@ -0,0 +1,71 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
html {
font-family: 'Inter', system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@apply bg-gray-50 text-slate-800;
}
h1, h2, h3, h4, h5, h6 {
@apply tracking-tight font-semibold text-slate-900;
}
}
@layer components {
.btn {
@apply px-4 py-2 rounded-xl font-medium transition-all duration-200 active:scale-95 flex items-center justify-center gap-2;
}
.btn-primary {
@apply btn bg-brand-600 text-white hover:bg-brand-700 shadow-lg shadow-brand-500/20 hover:shadow-brand-500/30;
}
.btn-secondary {
@apply btn bg-white text-slate-700 border border-slate-200 hover:bg-slate-50 hover:border-slate-300 shadow-sm;
}
.btn-ghost {
@apply btn bg-transparent text-slate-600 hover:bg-slate-100 hover:text-slate-900 shadow-none;
}
.btn-danger {
@apply btn bg-red-50 text-red-600 hover:bg-red-100 border border-transparent;
}
.input-field {
@apply w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-900 placeholder-slate-400 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 outline-none transition-all duration-200;
}
.card {
@apply bg-white rounded-2xl border border-slate-100 shadow-soft hover:shadow-lg transition-all duration-300;
}
.badge {
@apply px-2.5 py-0.5 rounded-full text-xs font-medium border;
}
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
@apply bg-slate-200 rounded-full;
}
::-webkit-scrollbar-thumb:hover {
@apply bg-slate-300;
}
File diff suppressed because it is too large. Load diff
+405
View File
@@ -0,0 +1,405 @@
<script setup lang="ts">
/**
* ChatView.vue
* 文件用途:单个 Agent 的对话界面
* 引用文件:vue, vue-router, lucide-vue-next, useChat 组合函数
* 逻辑关系:
* - 使用 useChat 发送消息并接收 SSE 流
* - 支持从首页携带预设问题快速发起对话
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
*/
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat';
import { Send, User, Bot, Loader2, ArrowLeft, Plus, Menu, Star } from 'lucide-vue-next';
import { useRoute, useRouter } from 'vue-router';
const { t, locale } = useI18n();
const route = useRoute();
const router = useRouter();
const agentId = Number(route.params.agentId);
// Sidebar state for mobile
const isSidebarOpen = ref(false);
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref('');
const currentAgent = ref<any>(null);
interface ChatHistoryItem {
id: number;
conversation_id: string;
title: string;
created_at: string;
}
const history = ref<ChatHistoryItem[]>([]);
// 预设问题:从路由 query.preset 中读取(如果有)
const presetQuestion = computed(() => {
const q = route.query.preset;
return typeof q === 'string' ? q : '';
});
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<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
/**
* handleSend
* 用途:将输入框内容发送给当前 Agent
* 核心逻辑:
* 1. 校验输入非空且当前不在思考状态
* 2. 调用 sendMessage
* 3. 清空输入框
*/
const handleSend = async () => {
if (!input.value.trim() || isThinking.value) return;
const userInput = input.value;
input.value = '';
await sendMessage(userInput, agentId);
// 发送完成后刷新历史记录,确保新会话出现
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
} else if (conversationId.value) {
// Check if current conversation is in history, if not, reload
const exists = history.value.some(h => h.conversation_id === conversationId.value);
if (!exists) await loadHistory();
}
};
// 加载历史记录
const loadHistory = async () => {
try {
const res = await fetch(`/api/chat/sessions`, { headers: getAuthHeaders() });
if (res.ok) {
history.value = await res.json();
}
} catch (e) {
console.error('Failed to load history', e);
}
};
const loadConversation = async (id: string) => {
if (conversationId.value === id) return;
try {
const res = await fetch(`/api/chat/messages?conversation_id=${id}`, { headers: getAuthHeaders() });
if (res.ok) {
messages.value = await res.json();
conversationId.value = id;
// Reset feedback state
rating.value = null;
feedbackComment.value = '';
feedbackSubmitted.value = false;
}
} catch (e) {
console.error('Failed to load conversation', e);
}
};
const startNewChat = () => {
messages.value = [];
conversationId.value = null;
rating.value = null;
feedbackComment.value = '';
feedbackSubmitted.value = false;
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
// Fetch Agent Details
try {
const agentRes = await fetch(`/api/user/agents/${agentId}`, { headers: getAuthHeaders() });
if (agentRes.ok) {
currentAgent.value = await agentRes.json();
}
} catch (e) {
console.error('Failed to load agent details', e);
}
await loadHistory();
if (presetQuestion.value) {
input.value = presetQuestion.value;
handleSend();
}
const res = await fetch('/api/user/config', { headers: getAuthHeaders() });
if (res.ok) {
const data = await res.json();
enableFeedback.value = !!data.feedback_enabled;
}
});
/**
* 反馈相关状态
* enableFeedback:是否启用评分功能(后续可接入配置)
* rating:用户选择的评分(1-5)
* feedbackComment:用户输入的文字意见
* feedbackSubmitted:是否已经提交反馈
*/
const enableFeedback = ref(true);
const rating = ref<number | null>(null);
const feedbackComment = ref('');
const feedbackSubmitted = ref(false);
/**
* submitFeedback
* 用途:将评分与评论提交到后端 /api/chat/feedback
*/
const submitFeedback = async () => {
if (!enableFeedback.value || feedbackSubmitted.value) return;
if (!rating.value) {
alert(t('chat.feedback.selectRating'));
return;
}
const res = await fetch('/api/chat/feedback', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
agent_id: agentId,
score: rating.value,
comment: feedbackComment.value,
conversation_id: conversationId.value,
}),
});
if (res.ok) {
feedbackSubmitted.value = true;
}
};
</script>
<template>
<div class="flex h-screen bg-white font-sans text-slate-800">
<!-- Sidebar (History) -->
<!-- Mobile Overlay -->
<div
v-if="isSidebarOpen"
class="fixed inset-0 bg-slate-900/50 z-40 md:hidden backdrop-blur-sm transition-opacity"
@click="isSidebarOpen = false"
></div>
<aside
class="w-72 bg-slate-50 border-r border-slate-200 flex flex-col fixed inset-y-0 left-0 z-50 transition-transform duration-300 ease-in-out md:relative md:translate-x-0 shadow-xl md:shadow-none"
:class="isSidebarOpen ? 'translate-x-0' : '-translate-x-full'"
>
<div class="p-4 flex items-center justify-between">
<button @click="router.push('/workspace')" class="p-2 hover:bg-white hover:shadow-sm rounded-xl transition-all text-slate-500 hover:text-slate-900" title="Back to Workspace">
<ArrowLeft class="w-5 h-5" />
</button>
<span class="font-bold text-slate-700 tracking-tight">{{ $t('chat.history') }}</span>
<button class="p-2 hover:bg-brand-100 hover:text-brand-600 rounded-xl transition-all text-slate-500" title="New Chat" @click="startNewChat(); isSidebarOpen = false;">
<Plus class="w-5 h-5" />
</button>
</div>
<div class="px-3 pb-2">
<button @click="startNewChat(); isSidebarOpen = false;" class="w-full py-2.5 px-4 bg-brand-600 hover:bg-brand-700 text-white rounded-xl font-medium shadow-lg shadow-brand-500/20 transition-all flex items-center justify-center gap-2 mb-2">
<Plus class="w-4 h-4" /> {{ $t('chat.newChat') }}
</button>
</div>
<div class="flex-1 overflow-y-auto px-3 space-y-1 scrollbar-thin">
<div v-if="history.length === 0" class="text-center text-slate-400 text-sm py-8 italic">{{ $t('chat.noHistory') }}</div>
<button
v-for="item in history"
:key="item.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="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;"
>
{{ item.title || $t('chat.newChat') }}
</button>
</div>
<!-- Language Selector & Agent Info -->
<div class="p-4 border-t border-slate-200 bg-slate-50 space-y-3">
<select
v-model="locale"
class="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-sm shadow-sm outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 transition-all cursor-pointer"
>
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
<div class="flex items-center justify-center gap-2 text-xs text-slate-400 font-mono bg-slate-100 py-1.5 rounded-lg">
<span class="w-1.5 h-1.5 rounded-full bg-green-500"></span>
{{ $t('chat.agentId') }} {{ agentId }}
</div>
</div>
</aside>
<!-- Main Chat Area -->
<div class="flex-1 flex flex-col h-full relative w-full md:w-auto overflow-hidden bg-white">
<!-- Mobile Header -->
<header class="md:hidden bg-white/80 backdrop-blur-md border-b border-slate-100 px-4 py-3 flex items-center justify-between shrink-0 z-30 sticky top-0">
<div class="flex items-center gap-3">
<button @click="router.push('/workspace')" class="p-2 hover:bg-slate-50 rounded-lg transition-colors">
<ArrowLeft class="w-5 h-5 text-slate-600" />
</button>
<span class="font-bold text-slate-900 truncate max-w-[200px]">{{ currentAgent?.name || $t('chat.defaultTitle') }}</span>
</div>
<button @click="isSidebarOpen = !isSidebarOpen" class="p-2 hover:bg-slate-50 rounded-lg transition-colors">
<Menu class="w-6 h-6 text-slate-600" />
</button>
</header>
<!-- Chat Content -->
<div v-if="!currentAgent" class="flex-1 flex flex-col items-center justify-center space-y-4">
<Loader2 class="w-10 h-10 animate-spin text-brand-500" />
<p class="text-slate-400 text-sm animate-pulse">Loading agent...</p>
</div>
<div v-else-if="currentAgent.type === 'iframe'" class="flex-1 w-full h-full bg-white relative">
<iframe
:src="currentAgent.extra_config?.iframe_url"
class="w-full h-full border-0"
allow="microphone; camera; clipboard-read; clipboard-write"
></iframe>
</div>
<template v-else>
<main class="flex-1 overflow-y-auto p-4 md:p-8 space-y-8 scroll-smooth scrollbar-thin">
<div v-if="messages.length === 0" class="flex flex-col items-center justify-center h-full text-slate-400 pb-20">
<div class="w-20 h-20 bg-gradient-to-br from-brand-500 to-brand-700 rounded-3xl flex items-center justify-center mb-8 shadow-xl shadow-brand-500/20 animate-fade-in">
<Bot class="text-white w-10 h-10" />
</div>
<h2 class="text-3xl font-bold text-slate-900 mb-3 tracking-tight">{{ $t('chat.welcome.title') }}</h2>
<p class="text-slate-500 text-lg max-w-md text-center leading-relaxed">{{ $t('chat.welcome.subtitle') }}</p>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-12 w-full max-w-2xl">
<button v-for="suggestion in ['What can you do?', 'Help me write a report', 'Analyze this data', 'Creative writing']"
:key="suggestion"
@click="input = suggestion; handleSend()"
class="p-4 bg-white border border-slate-200 rounded-xl hover:border-brand-400 hover:shadow-md hover:text-brand-700 text-slate-600 text-sm font-medium transition-all text-left">
{{ suggestion }}
</button>
</div>
</div>
<div
v-for="(msg, index) in messages"
:key="index"
class="flex gap-4 max-w-4xl mx-auto group animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : ''"
>
<!-- Bot Avatar -->
<div v-if="msg.role === 'assistant'" class="w-10 h-10 rounded-xl bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shrink-0 shadow-sm mt-1">
<Bot class="text-white w-6 h-6" />
</div>
<!-- Message Bubble -->
<div
class="py-3.5 px-6 rounded-2xl shadow-sm max-w-[85%] md:max-w-[75%] leading-relaxed text-[15px]"
:class="msg.role === 'user' ? 'bg-brand-600 text-white rounded-tr-sm shadow-brand-500/20' : 'bg-white border border-slate-100 text-slate-800 rounded-tl-sm shadow-slate-200/50'"
>
<div class="whitespace-pre-wrap prose prose-sm max-w-none" :class="msg.role === 'user' ? 'prose-invert' : 'prose-slate'">{{ msg.content }}</div>
</div>
<!-- User Avatar -->
<div v-if="msg.role === 'user'" class="w-10 h-10 rounded-xl bg-slate-200 flex items-center justify-center shrink-0 shadow-sm mt-1">
<User class="text-slate-500 w-6 h-6" />
</div>
</div>
<!-- Loading -->
<div v-if="isThinking" class="flex gap-4 max-w-4xl mx-auto animate-pulse">
<div class="w-10 h-10 rounded-xl bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shrink-0 shadow-sm mt-1">
<Bot class="text-white w-6 h-6" />
</div>
<div class="py-3 px-5 bg-white border border-slate-100 rounded-2xl rounded-tl-sm shadow-sm flex items-center gap-3">
<div class="flex gap-1">
<span class="w-2 h-2 bg-brand-400 rounded-full animate-bounce"></span>
<span class="w-2 h-2 bg-brand-400 rounded-full animate-bounce delay-75"></span>
<span class="w-2 h-2 bg-brand-400 rounded-full animate-bounce delay-150"></span>
</div>
<span class="text-slate-400 text-sm font-medium">{{ $t('chat.thinking') }}</span>
</div>
</div>
<!-- Feedback -->
<div
v-if="enableFeedback && messages.length > 0 && !isThinking"
class="max-w-4xl mx-auto mt-8 pt-8 border-t border-slate-100"
>
<div class="flex flex-col items-center gap-4 bg-slate-50 p-6 rounded-2xl border border-slate-100">
<span class="text-sm font-medium text-slate-500">{{ $t('chat.rate') }}</span>
<div class="flex gap-3">
<button
v-for="n in 5"
:key="n"
class="w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200"
:class="rating && n <= rating ? 'bg-yellow-400 text-white scale-110 shadow-md shadow-yellow-400/30' : 'bg-white border border-slate-200 text-slate-400 hover:border-yellow-400 hover:text-yellow-400'"
@click="rating = n"
>
<Star v-if="rating && n <= rating" class="w-5 h-5 fill-current" />
<span v-else class="text-sm font-bold">{{ n }}</span>
</button>
</div>
<div v-if="rating" class="w-full max-w-lg flex gap-3 mt-2 animate-fade-in">
<input
v-model="feedbackComment"
type="text"
class="flex-1 input-field py-2 text-sm"
:placeholder="$t('chat.feedback.commentPlaceholder')"
/>
<button
class="px-6 py-2 bg-brand-600 text-white text-sm font-bold rounded-xl hover:bg-brand-700 disabled:opacity-50 transition-colors shadow-lg shadow-brand-500/30"
:disabled="feedbackSubmitted"
@click="submitFeedback"
>
{{ feedbackSubmitted ? $t('chat.feedback.sent') : $t('chat.send') }}
</button>
</div>
</div>
</div>
<div class="h-24"></div> <!-- Spacer for fixed footer -->
</main>
<!-- Input Area -->
<footer class="p-4 md:p-6 bg-white/80 backdrop-blur-xl border-t border-slate-100 absolute bottom-0 left-0 right-0 z-20">
<div class="max-w-4xl mx-auto relative">
<div class="relative bg-white rounded-2xl border border-slate-200 shadow-lg shadow-slate-200/50 focus-within:ring-2 focus-within:ring-brand-500/20 focus-within:border-brand-500 transition-all duration-300">
<textarea
v-model="input"
@keydown.enter.prevent="handleSend"
rows="1"
:placeholder="$t('chat.placeholder')"
class="w-full pl-5 pr-14 py-4 bg-transparent resize-none focus:outline-none text-slate-800 placeholder-slate-400 text-[15px] leading-relaxed"
style="min-height: 56px; max-height: 200px;"
:disabled="isThinking"
></textarea>
<button
@click="handleSend"
:disabled="!input.trim() || isThinking"
class="absolute right-2 bottom-2 p-2.5 bg-brand-600 text-white rounded-xl hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md shadow-brand-500/20 active:scale-95"
>
<Send class="w-5 h-5" />
</button>
</div>
<div class="text-center mt-3 text-xs font-medium text-slate-400">
{{ $t('chat.disclaimer') }}
</div>
</div>
</footer>
</template>
</div>
</div>
</template>
+728
View File
@@ -0,0 +1,728 @@
<script setup lang="ts">
/**
* WorkspaceView.vue
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口
*/
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
Settings,
LayoutGrid,
Star,
GripVertical,
Plus,
Trash2,
Edit,
ExternalLink,
Bot
} from 'lucide-vue-next';
const { t, locale } = useI18n();
const router = useRouter();
// Interfaces
interface Agent {
id: number;
name: string;
description: string;
icon_url?: string;
}
interface QuickQuestion {
id: number;
title: string;
question: string;
agent_id: number;
}
interface EmbeddedAgent {
id: number;
name: string;
iframe_url?: string;
}
interface LayoutSection {
id: string;
visible: boolean;
title?: string;
}
// State
const isLoading = ref(true);
const currentUser = ref<{ id: number; username: string; role: string; default_agent_id?: number | null } | null>(null);
const agents = ref<Agent[]>([]);
const publicAgents = ref<Agent[]>([]);
const quickQuestions = ref<QuickQuestion[]>([]);
const favoriteAgentIds = ref<number[]>([]);
const embeddedAgents = ref<EmbeddedAgent[]>([]);
const layoutSections = ref<LayoutSection[]>([
{ id: 'favorites', visible: true, title: 'workspace.favorites' },
{ id: 'quick_questions', visible: true, title: 'workspace.quickQuestions.title' },
{ id: 'embedded', visible: true, title: 'workspace.embedded' },
{ id: 'all_agents', visible: true, title: 'workspace.availableAgents' },
]);
const searchQuery = ref('');
const loginUsername = ref('');
const loginPassword = ref('');
const showRegisterModal = ref(false);
const registerForm = ref({ username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' });
const pendingAgentId = ref<number | null>(null);
const userReport = ref<any>(null);
// Quick Question Form State
const isAddingQuestion = ref(false);
const editingQuestionId = ref<number | null>(null);
const newQuestion = ref({
title: '',
question: '',
agent_id: null as number | null
});
// Drag & Drop State
const draggedSectionIndex = ref<number | null>(null);
// Computed
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
const favoriteAgents = computed(() => {
return agents.value.filter(a => favoriteAgentIds.value.includes(a.id));
});
const otherAgents = computed(() => {
// If we want to show ALL agents in the bottom list, just return filtered agents.
// Or if we want to exclude favorites, we can filter them out.
// Usually "All Applications" includes favorites too, or separates them.
// Let's keep all agents in the main list for completeness, or just non-favorites if preferred.
// For now, let's show all matching search.
if (!searchQuery.value.trim()) return agents.value;
const q = searchQuery.value.toLowerCase();
return agents.value.filter(
(a) => a.name.toLowerCase().includes(q) || a.description.toLowerCase().includes(q)
);
});
const filteredQuickQuestions = computed(() => {
if (!searchQuery.value.trim()) return quickQuestions.value;
const q = searchQuery.value.toLowerCase();
return quickQuestions.value.filter(
(qq) => qq.title.toLowerCase().includes(q) || qq.question.toLowerCase().includes(q)
);
});
// Methods
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<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
const fetchHome = async () => {
try {
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
if (res.status === 401) {
handleLogout();
return;
}
const data = await res.json();
currentUser.value = {
id: data.user.id,
username: data.user.username,
role: data.user.role,
default_agent_id: data.user.default_agent_id
};
agents.value = data.agents || [];
quickQuestions.value = data.quick_questions || [];
favoriteAgentIds.value = data.favorite_agent_ids || [];
embeddedAgents.value = data.embedded_agents || [];
// Merge layout from backend if exists
if (data.layout && data.layout.sections) {
// Ensure all required sections exist even if backend layout is old
const backendSections = data.layout.sections as LayoutSection[];
const defaultSections = [
{ id: 'favorites', visible: true },
{ id: 'quick_questions', visible: true },
{ id: 'embedded', visible: true },
{ id: 'all_agents', visible: true },
];
// Update local layout, preserving order from backend but ensuring all keys exist
const merged: LayoutSection[] = [];
const backendIds = new Set(backendSections.map(s => s.id));
// Add backend sections
backendSections.forEach(s => {
const def = defaultSections.find(d => d.id === s.id);
merged.push({ ...def, ...s });
});
// Add missing sections
defaultSections.forEach(d => {
if (!backendIds.has(d.id)) {
merged.push(d);
}
});
layoutSections.value = merged;
}
} catch (e) {
console.error('Failed to load user home', e);
} finally {
isLoading.value = false;
}
};
const fetchPublicAgents = async () => {
try {
const res = await fetch('/api/user/public-agents');
publicAgents.value = await res.json();
} catch (e) {
console.error('Failed to load public agents', e);
}
};
const loadAuthUser = () => {
const stored = localStorage.getItem('hxops_user');
if (!stored) return;
try {
const user = JSON.parse(stored) as { id?: number; username: string; role: string };
currentUser.value = {
id: user.id || 0,
username: user.username,
role: user.role,
};
} catch (e) {
localStorage.removeItem('hxops_user');
}
};
const handleLogin = async () => {
if (!loginUsername.value.trim()) {
alert(t('login.usernameRequired'));
return;
}
try {
const res = await fetch('/api/user/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: loginUsername.value.trim(),
password: loginPassword.value
})
});
if (!res.ok) {
const err = await res.json();
alert(err.error || t('login.failed'));
return;
}
const user = await res.json();
localStorage.setItem('hxops_user', JSON.stringify(user));
await fetchHome();
if (pendingAgentId.value) {
const targetId = pendingAgentId.value;
pendingAgentId.value = null;
if (agents.value.some(a => a.id === targetId)) {
navigateToChat(targetId);
} else {
alert(t('workspace.permission.denied'));
}
}
} catch (e) {
console.error(e);
alert(t('login.requestFailed'));
}
};
const handleRegister = async () => {
if (!registerForm.value.username || !registerForm.value.password || !registerForm.value.real_name || !registerForm.value.employee_id || !registerForm.value.phone_number) {
alert(t('register.inputError'));
return;
}
try {
const res = await fetch('/api/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(registerForm.value)
});
if (res.ok) {
alert(t('register.success'));
showRegisterModal.value = false;
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
} else {
const err = await res.json();
alert(err.error || t('register.failed'));
}
} catch (e) {
console.error('Register error:', e);
alert(t('register.requestFailed'));
}
};
const handleLogout = () => {
localStorage.removeItem('hxops_user');
currentUser.value = null;
agents.value = [];
quickQuestions.value = [];
favoriteAgentIds.value = [];
embeddedAgents.value = [];
userReport.value = null;
fetchPublicAgents();
};
const navigateToChat = (id: number) => {
if (!isLoggedIn.value) {
pendingAgentId.value = id;
alert(t('login.loginRequired'));
return;
}
const url = router.resolve(`/chat/${id}`).href;
window.open(url, '_blank');
};
const navigateWithQuickQuestion = (agentId: number, question: string) => {
if (!isLoggedIn.value) {
pendingAgentId.value = agentId;
alert(t('login.loginRequired'));
return;
}
const url = router.resolve({
path: `/chat/${agentId}`,
query: { preset: question },
}).href;
window.open(url, '_blank');
};
// Favorites
const toggleFavorite = async (agentId: number) => {
if (favoriteAgentIds.value.includes(agentId)) {
// Remove
await fetch(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
} else {
// Add
await fetch(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
favoriteAgentIds.value.push(agentId);
}
};
// Quick Questions
const getAgentName = (agentId: number) => {
const agent = agents.value.find(a => a.id === agentId);
return agent ? agent.name : t('workspace.unknownAgent', 'Unknown Agent');
};
const openAddQuestionForm = () => {
isAddingQuestion.value = true;
editingQuestionId.value = null;
newQuestion.value = { title: '', question: '', agent_id: null };
};
const editQuickQuestion = (qq: QuickQuestion) => {
isAddingQuestion.value = true;
editingQuestionId.value = qq.id;
newQuestion.value = {
title: qq.title,
question: qq.question,
agent_id: qq.agent_id
};
};
const cancelAddQuestion = () => {
isAddingQuestion.value = false;
editingQuestionId.value = null;
newQuestion.value = { title: '', question: '', agent_id: null };
};
const saveQuickQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
alert(t('workspace.quickQuestions.addTitle') + ' (Please fill all fields)');
return;
}
const url = editingQuestionId.value
? `/api/user/quick-questions/${editingQuestionId.value}`
: '/api/user/quick-questions';
const method = editingQuestionId.value ? 'PUT' : 'POST';
const res = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value),
});
if (res.ok) {
await fetchHome();
isAddingQuestion.value = false;
editingQuestionId.value = null;
} else {
alert(t('workspace.quickQuestions.msg.saveFailed'));
}
};
const removeQuickQuestion = async (id: number) => {
if (!window.confirm(t('workspace.quickQuestions.confirmDelete'))) return;
await fetch(`/api/user/quick-questions/${id}`, { method: 'DELETE', headers: getAuthHeaders() });
await fetchHome();
};
// Drag & Drop
const onDragStart = (index: number) => {
draggedSectionIndex.value = index;
};
const onDragOver = (event: DragEvent) => {
event.preventDefault();
};
const onDrop = async (index: number) => {
if (draggedSectionIndex.value === null) return;
const draggedItem = layoutSections.value[draggedSectionIndex.value];
if (!draggedItem) return;
layoutSections.value.splice(draggedSectionIndex.value, 1);
layoutSections.value.splice(index, 0, draggedItem);
draggedSectionIndex.value = null;
// Save layout
await fetch('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
};
onMounted(async () => {
loadAuthUser();
if (currentUser.value && currentUser.value.role !== 'guest') {
await fetchHome();
} else {
await fetchPublicAgents();
isLoading.value = false;
}
});
</script>
<template>
<div class="min-h-screen bg-gray-50 font-sans text-slate-800">
<!-- Header (Logged In) -->
<header v-if="isLoggedIn" class="sticky top-0 z-30 bg-white/80 backdrop-blur-md border-b border-gray-100 px-4 md:px-8 py-4 mb-8 transition-all duration-300">
<div class="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4">
<div class="flex items-center gap-3">
<div class="w-10 h-10 bg-gradient-to-br from-brand-500 to-brand-700 rounded-xl flex items-center justify-center text-white shadow-lg shadow-brand-500/30">
<Bot class="w-6 h-6" />
</div>
<div>
<h1 class="text-xl font-bold text-slate-900 tracking-tight">
{{ currentUser ? $t('workspace.userTitle', { username: currentUser.username }) : $t('workspace.title') }}
</h1>
<p class="text-slate-500 text-xs font-medium">{{ $t('workspace.subtitle') }}</p>
</div>
</div>
<div class="flex items-center gap-3">
<select v-model="locale" class="bg-white border border-slate-200 rounded-xl px-3 py-2 text-sm font-medium text-slate-600 outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 transition-all cursor-pointer hover:bg-slate-50">
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
<button v-if="currentUser?.role === 'admin'" @click="router.push('/admin')" class="btn-secondary">
<Settings class="w-4 h-4 mr-2" /> {{ $t('admin.title') }}
</button>
<button @click="handleLogout" class="btn-ghost hover:text-red-600 hover:bg-red-50">{{ $t('workspace.logout') }}</button>
</div>
</div>
</header>
<main class="max-w-7xl mx-auto px-4 md:px-8 pb-12">
<div v-if="isLoading" class="animate-pulse space-y-8">
<div class="h-48 bg-gray-200 rounded-2xl"></div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="h-40 bg-gray-200 rounded-2xl"></div>
<div class="h-40 bg-gray-200 rounded-2xl"></div>
<div class="h-40 bg-gray-200 rounded-2xl"></div>
</div>
</div>
<!-- Not Logged In (Login Screen) -->
<div v-else-if="!isLoggedIn" class="min-h-[calc(100vh-4rem)] flex items-center justify-center -mt-16 md:-mt-20">
<div class="w-full max-w-6xl grid grid-cols-1 lg:grid-cols-2 gap-12 items-center p-4">
<!-- Hero Section -->
<div class="hidden lg:block space-y-8 animate-slide-up">
<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-brand-50 text-brand-600 text-sm font-medium border border-brand-100">
<span class="relative flex h-2 w-2">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-brand-500"></span>
</span>
Enterprise AI Gateway
</div>
<h1 class="text-5xl font-bold text-slate-900 leading-tight">
Unleash the Power of <br/>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-purple-600">Generative AI</span>
</h1>
<p class="text-lg text-slate-600 max-w-md leading-relaxed">
Access a suite of powerful AI agents tailored for your enterprise needs. Secure, scalable, and intelligent.
</p>
<div class="grid grid-cols-2 gap-4">
<div v-for="agent in publicAgents.slice(0, 4)" :key="agent.id"
class="bg-white p-4 rounded-xl border border-slate-100 shadow-sm flex items-center gap-3">
<div class="w-10 h-10 bg-brand-50 rounded-lg flex items-center justify-center text-brand-600 shrink-0">
<Bot class="w-5 h-5" />
</div>
<div class="truncate">
<div class="font-semibold text-slate-900 text-sm truncate">{{ agent.name }}</div>
<div class="text-xs text-slate-500 truncate">AI Assistant</div>
</div>
</div>
</div>
</div>
<!-- Login Card -->
<div class="w-full max-w-md mx-auto">
<div class="bg-white rounded-3xl border border-slate-100 shadow-xl shadow-brand-900/5 p-8 md:p-10 animate-fade-in">
<div class="text-center mb-8">
<div class="w-12 h-12 bg-brand-600 rounded-xl mx-auto flex items-center justify-center text-white shadow-lg shadow-brand-600/30 mb-4 lg:hidden">
<Bot class="w-7 h-7" />
</div>
<h2 class="text-2xl font-bold text-slate-900">{{ $t('login.submit') }}</h2>
<p class="text-slate-500 text-sm mt-2">Welcome back! Please enter your details.</p>
</div>
<div class="space-y-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-700 uppercase ml-1">{{ $t('login.username') }}</label>
<input v-model="loginUsername" type="text" class="input-field" placeholder="Enter your username" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-700 uppercase ml-1">{{ $t('login.password') }}</label>
<input v-model="loginPassword" type="password" class="input-field" placeholder="••••••••" />
</div>
<button @click="handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all">
{{ $t('login.submit') }}
</button>
<div class="text-center pt-2">
<span class="text-sm text-slate-500">Don't have an account? </span>
<button @click="showRegisterModal = true" class="text-sm font-semibold text-brand-600 hover:text-brand-700 hover:underline transition-colors">{{ $t('login.register') }}</button>
</div>
</div>
<!-- Language Selector for Login -->
<div class="mt-8 pt-6 border-t border-slate-100 flex justify-center">
<select v-model="locale" class="bg-transparent text-xs font-medium text-slate-400 hover:text-slate-600 cursor-pointer outline-none text-center">
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
</div>
</div>
</div>
</div>
</div>
<!-- Logged In Layout -->
<div v-else class="space-y-8 animate-fade-in">
<!-- Draggable Sections -->
<div
v-for="(section, index) in layoutSections"
:key="section.id"
class="bg-transparent md:bg-white md:rounded-3xl md:border md:border-slate-100 md:p-8 md:shadow-soft relative group transition-all"
:class="{ 'opacity-50 border-brand-300 border-dashed': draggedSectionIndex === index }"
draggable="true"
@dragstart="onDragStart(index)"
@dragover="onDragOver"
@drop="onDrop(index)"
>
<!-- Drag Handle -->
<div class="absolute left-2 top-8 cursor-move opacity-0 group-hover:opacity-100 p-2 text-slate-300 hover:text-slate-500 transition-opacity hidden md:block">
<GripVertical class="w-5 h-5" />
</div>
<!-- Section Content -->
<div class="md:pl-6">
<!-- Header -->
<div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-bold text-slate-800 flex items-center gap-2.5">
<div class="p-2 rounded-lg" :class="{
'bg-yellow-50 text-yellow-600': section.id === 'favorites',
'bg-brand-50 text-brand-600': section.id === 'quick_questions',
'bg-purple-50 text-purple-600': section.id === 'embedded',
'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" />
</div>
{{ $t(section.title || section.id) }}
</h2>
<!-- Actions for Quick Questions -->
<button v-if="section.id === 'quick_questions' && !isAddingQuestion" @click="openAddQuestionForm" class="btn-ghost text-sm text-brand-600 hover:text-brand-700 hover:bg-brand-50">
<Plus class="w-4 h-4" /> {{ $t('workspace.quickQuestions.add') }}
</button>
</div>
<!-- Content: 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 class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
<div v-for="agent in favoriteAgents" :key="agent.id" @click="navigateToChat(agent.id)"
class="card p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:shadow-lg hover:border-brand-200 bg-gradient-to-br from-white to-slate-50/50">
<div class="w-12 h-12 bg-brand-100 rounded-xl flex items-center justify-center text-brand-600 mb-4 shadow-sm group-hover/card:scale-110 transition-transform duration-300">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-7 h-7" />
<Bot v-else class="w-7 h-7" />
</div>
<div class="font-bold text-slate-900 mb-1 group-hover/card:text-brand-700 transition-colors">{{ agent.name }}</div>
<div class="text-xs text-slate-500 truncate">{{ agent.description }}</div>
<button @click.stop="toggleFavorite(agent.id)" class="absolute top-3 right-3 text-yellow-400 hover:text-yellow-500 hover:scale-110 transition-all opacity-0 group-hover/card:opacity-100">
<Star class="w-5 h-5 fill-current" />
</button>
</div>
</div>
</div>
<!-- Content: Quick Questions -->
<div v-if="section.id === 'quick_questions'">
<!-- Add Question Form -->
<div v-if="isAddingQuestion" class="mb-6 p-6 bg-slate-50 border border-slate-200 rounded-2xl space-y-4 animate-fade-in">
<h3 class="font-bold text-slate-800">{{ editingQuestionId ? $t('workspace.quickQuestions.edit') : $t('workspace.quickQuestions.addNew') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-500 uppercase">{{ $t('workspace.quickQuestions.fields.title') }}</label>
<input v-model="newQuestion.title" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.titlePlaceholder')" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-500 uppercase">{{ $t('workspace.quickQuestions.fields.targetAgent') }}</label>
<select v-model="newQuestion.agent_id" class="input-field" :disabled="agents.length === 0">
<option :value="null" disabled>{{ agents.length === 0 ? $t('workspace.noAgents') : $t('workspace.quickQuestions.fields.selectAgent') }}</option>
<option v-for="agent in agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
</div>
<div class="col-span-1 md:col-span-2 space-y-1.5">
<label class="text-xs font-semibold text-slate-500 uppercase">{{ $t('workspace.quickQuestions.fields.content') }}</label>
<textarea v-model="newQuestion.question" rows="3" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.contentPlaceholder')"></textarea>
</div>
</div>
<div class="flex justify-end gap-3 pt-2">
<button @click="cancelAddQuestion" class="btn-secondary">{{ $t('workspace.cancel') }}</button>
<button @click="saveQuickQuestion" class="btn-primary">{{ $t('workspace.save') }}</button>
</div>
</div>
<div v-if="filteredQuickQuestions.length === 0 && !isAddingQuestion" class="text-slate-400 text-sm italic py-8 text-center bg-slate-50 rounded-xl border border-dashed border-slate-200">{{ $t('workspace.quickQuestions.noDefined') }}</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div v-for="qq in filteredQuickQuestions" :key="qq.id"
@click="navigateWithQuickQuestion(qq.agent_id, qq.question)"
class="group/item p-4 bg-white border border-slate-200 rounded-xl hover:border-brand-500 hover:shadow-md transition-all cursor-pointer flex flex-col gap-3 relative h-full">
<div class="flex justify-between items-start">
<h4 class="font-bold text-slate-900 group-hover/item:text-brand-600 transition-colors">{{ qq.title }}</h4>
<span class="text-[10px] font-bold px-2 py-0.5 bg-slate-100 text-slate-600 rounded-full uppercase tracking-wide">
{{ getAgentName(qq.agent_id) }}
</span>
</div>
<p class="text-sm text-slate-600 line-clamp-2 leading-relaxed">{{ qq.question }}</p>
<div class="absolute top-2 right-2 flex gap-1 opacity-0 group-hover/item:opacity-100 transition-opacity bg-white/90 backdrop-blur-sm p-1 rounded-lg">
<button @click.stop="editQuickQuestion(qq)" class="p-1.5 rounded-lg text-slate-400 hover:text-brand-600 hover:bg-brand-50 transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click.stop="removeQuickQuestion(qq.id)" class="p-1.5 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
</div>
</div>
<!-- Content: Embedded Agents -->
<div v-if="section.id === 'embedded'">
<div v-if="embeddedAgents.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.embedded.noData') }}</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div v-for="agent in embeddedAgents" :key="agent.id" class="border border-slate-200 rounded-2xl overflow-hidden bg-white shadow-sm hover:shadow-md transition-shadow h-[500px] flex flex-col">
<div class="bg-slate-50 px-4 py-3 text-sm font-bold text-slate-700 flex justify-between items-center border-b border-slate-100">
<span>{{ agent.name }}</span>
<a :href="`/chat/${agent.id}`" target="_blank" class="text-brand-600 hover:text-brand-700 hover:bg-brand-50 p-1.5 rounded-lg transition-colors"><ExternalLink class="w-4 h-4"/></a>
</div>
<iframe v-if="agent.iframe_url" :src="agent.iframe_url" class="w-full flex-1 border-none bg-white"></iframe>
<div v-else class="flex items-center justify-center flex-1 text-slate-400 bg-slate-50/50">{{ $t('workspace.embedded.noUrl') }}</div>
</div>
</div>
</div>
<!-- Content: All Agents -->
<div v-if="section.id === 'all_agents'">
<div class="mb-6">
<input v-model="searchQuery" type="text" :placeholder="$t('workspace.search')" class="input-field max-w-md shadow-sm" />
</div>
<div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
<div v-for="agent in otherAgents" :key="agent.id"
class="card p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:border-brand-200">
<div class="flex items-start justify-between mb-4">
<div class="w-10 h-10 bg-slate-50 rounded-xl flex items-center justify-center text-slate-500 group-hover/card:bg-brand-50 group-hover/card:text-brand-600 transition-colors">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-6 h-6" />
<Bot v-else class="w-6 h-6" />
</div>
<button @click.stop="toggleFavorite(agent.id)" class="text-slate-200 hover:text-yellow-400 transition-colors">
<Star class="w-5 h-5" :class="{ 'fill-yellow-400 text-yellow-400': favoriteAgentIds.includes(agent.id) }" />
</button>
</div>
<h3 class="font-bold text-slate-900 mb-1 group-hover/card:text-brand-700 transition-colors">{{ agent.name }}</h3>
<p class="text-xs text-slate-500 line-clamp-2 h-8 leading-relaxed">{{ agent.description }}</p>
<button @click="navigateToChat(agent.id)" class="mt-5 w-full py-2 bg-slate-50 text-slate-600 text-xs font-bold rounded-xl hover:bg-brand-600 hover:text-white transition-all duration-300">
{{ $t('workspace.startChatShort') }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<!-- Register Modal -->
<div v-if="showRegisterModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
<div class="bg-white rounded-3xl shadow-2xl w-full max-w-md p-8 animate-slide-up">
<h3 class="text-xl font-bold text-slate-900 mb-6 text-center">{{ $t('register.title') }}</h3>
<div class="space-y-4">
<input v-model="registerForm.real_name" :placeholder="$t('register.fields.realName')" class="input-field" />
<input v-model="registerForm.employee_id" :placeholder="$t('register.fields.employeeId')" class="input-field" />
<input v-model="registerForm.phone_number" :placeholder="$t('register.fields.phone')" class="input-field" />
<input v-model="registerForm.username" :placeholder="$t('register.username')" class="input-field" />
<input v-model="registerForm.email" :placeholder="$t('register.email')" class="input-field" />
<input v-model="registerForm.password" type="password" :placeholder="$t('register.password')" class="input-field" />
</div>
<div class="flex justify-end gap-3 mt-8">
<button @click="showRegisterModal = false" class="btn-secondary">{{ $t('register.cancel') }}</button>
<button @click="handleRegister" class="btn-primary">{{ $t('register.submit') }}</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
/* Scoped styles removed in favor of global utilities in style.css */
</style>
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue"
const component: DefineComponent<{}, {}, any>
export default component
}
+56
View File
@@ -0,0 +1,56 @@
/** @type {import('tailwindcss').Config} */
import defaultTheme from 'tailwindcss/defaultTheme';
import typography from '@tailwindcss/typography';
import forms from '@tailwindcss/forms';
export default {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
],
theme: {
extend: {
fontFamily: {
sans: ['Inter', ...defaultTheme.fontFamily.sans],
},
colors: {
brand: {
50: '#f0f9ff',
100: '#e0f2fe',
200: '#bae6fd',
300: '#7dd3fc',
400: '#38bdf8',
500: '#0ea5e9',
600: '#0284c7',
700: '#0369a1',
800: '#075985',
900: '#0c4a6e',
950: '#082f49',
},
},
boxShadow: {
'soft': '0 4px 20px -2px rgba(0, 0, 0, 0.05)',
'glow': '0 0 15px rgba(14, 165, 233, 0.3)',
},
animation: {
'fade-in': 'fadeIn 0.3s ease-out',
'slide-up': 'slideUp 0.4s ease-out',
'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
},
keyframes: {
fadeIn: {
'0%': { opacity: '0' },
'100%': { opacity: '1' },
},
slideUp: {
'0%': { transform: 'translateY(10px)', opacity: '0' },
'100%': { transform: 'translateY(0)', opacity: '1' },
},
},
},
},
plugins: [
typography,
forms,
],
}
+16
View File
@@ -0,0 +1,16 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"types": ["vite/client"],
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
port: 8881, // 前端开发端口,实际上我们会用 Nginx 反代,但本地开发先改这个方便
proxy: {
'/api': {
target: 'http://127.0.0.1:5002',
changeOrigin: true
}
}
}
})
+26
View File
@@ -0,0 +1,26 @@
import os
import sys
from sqlalchemy import create_engine, text
# Add backend directory to path
sys.path.append(os.path.join(os.getcwd(), 'backend'))
from app import create_app, db
from app.models import Agent
app = create_app()
with app.app_context():
try:
agent = Agent.query.filter_by(name='人事规章').first()
if agent:
print(f"Agent Found: {agent.name}")
print(f"ID: {agent.id}")
print(f"Type: {agent.type}")
print(f"API Base URL: {agent.api_base_url}")
print(f"API Key: {agent.dify_api_key}")
else:
print("Agent '人事规章' not found.")
except Exception as e:
print(f"Error: {e}")
+70
View File
@@ -0,0 +1,70 @@
#!/bin/bash
# deploy.sh
# 自动化部署脚本
# 用途: 在服务器上执行,用于更新代码并重启服务
set -e
# 配置
PROJECT_DIR="/opt/hxops"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"
VENV_DIR="$BACKEND_DIR/venv"
BRANCH="super"
echo "=== 开始部署 [$(date)] ==="
# 1. 更新代码
echo ">>> 拉取最新代码..."
cd $PROJECT_DIR
git fetch origin
git reset --hard origin/$BRANCH
# 2. 前端构建
echo ">>> 构建前端..."
cd $FRONTEND_DIR
# 仅当 package.json 变动时才安装依赖 (利用 npm ci 或 diff 检查)
if [ -f "package-lock.json" ]; then
npm ci --prefer-offline --no-audit
else
npm install --prefer-offline --no-audit
fi
npm run build
# 3. 后端更新
echo ">>> 更新后端..."
cd $BACKEND_DIR
if [ ! -d "$VENV_DIR" ]; then
echo "创建虚拟环境..."
python3 -m venv $VENV_DIR
fi
source $VENV_DIR/bin/activate
echo "安装 Python 依赖..."
pip install -r requirements.txt --upgrade --no-cache-dir
echo "执行数据库迁移..."
export FLASK_APP=run.py
flask db upgrade
# 4. 重启服务
echo ">>> 重启服务..."
# 更新 Nginx 配置 (如果有变动)
if [ -f "$PROJECT_DIR/scripts/nginx.conf" ]; then
cp $PROJECT_DIR/scripts/nginx.conf /etc/nginx/conf.d/hxops.conf
nginx -t && systemctl reload nginx
fi
# 更新 Supervisor 配置 (如果有变动)
if [ -f "$PROJECT_DIR/scripts/supervisord.conf" ]; then
cp $PROJECT_DIR/scripts/supervisord.conf /etc/supervisor/conf.d/hxops.conf
supervisorctl reread
supervisorctl update
fi
# 重启后端进程
supervisorctl restart hxops-backend
echo "=== 部署完成 [$(date)] ==="
echo "验证服务状态:"
supervisorctl status hxops-backend
+32
View File
@@ -0,0 +1,32 @@
import os
import sys
from sqlalchemy import text
# Add backend directory to path
sys.path.append(os.path.join(os.getcwd(), 'backend'))
from app import create_app, db
from app.models import Agent
app = create_app()
with app.app_context():
try:
# Check DB connection
db.session.execute(text('SELECT 1'))
print("Database connection successful.")
# Update Agent
agent = Agent.query.filter_by(name='人事规章').first()
if agent:
print(f"Updating Agent: {agent.name}")
agent.api_base_url = "http://192.168.100.230:5001/v1"
agent.dify_api_key = "app-xdiejQibWQy8ZQWXcdxJjS9I"
db.session.commit()
print("Agent updated successfully.")
else:
print("Agent '人事规章' not found.")
except Exception as e:
print(f"Error: {e}")
+49
View File
@@ -0,0 +1,49 @@
import time
import json
from flask import Flask, request, Response, stream_with_context
app = Flask(__name__)
@app.route('/v1/chat-messages', methods=['POST'])
def chat_messages():
print(f"Received request: {request.json}")
auth = request.headers.get('Authorization')
print(f"Authorization: {auth}")
# Check API Key if needed
if 'Bearer app-xdiejQibWQy8ZQWXcdxJjS9I' not in auth:
print("Invalid API Key")
# return {"code": "unauthorized", "message": "Invalid API Key"}, 401
def generate():
# Yield 'message' events
response_text = "这是来自人事规章助手的回复。根据公司规定,年假天数取决于工龄。"
# Initial chunk
yield f"data: {json.dumps({'event': 'message', 'answer': ''})}\n\n"
for char in response_text:
time.sleep(0.05)
data = {
'event': 'message',
'answer': char,
'conversation_id': 'conv-123',
'task_id': 'task-123'
}
yield f"data: {json.dumps(data)}\n\n"
# Message end
data = {
'event': 'message_end',
'conversation_id': 'conv-123',
'metadata': {
'usage': {'total_tokens': 100}
}
}
yield f"data: {json.dumps(data)}\n\n"
return Response(stream_with_context(generate()), mimetype='text/event-stream')
if __name__ == '__main__':
print("Starting Mock Dify Server on port 5001...")
app.run(host='127.0.0.1', port=5001, debug=True)
+53
View File
@@ -0,0 +1,53 @@
# hxops_nginx.conf
# 放置于 /etc/nginx/conf.d/hxops.conf
server {
listen 80;
server_name 192.168.100.230; # 或域名
# 1. 前端静态资源 (动静分离)
location / {
root /opt/hxops/frontend/dist;
index index.html;
try_files $uri $uri/ /index.html;
# 静态资源缓存策略
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
}
# 2. 后端 API 反向代理
location /api/ {
# 转发到 Gunicorn (Gevent)
proxy_pass http://127.0.0.1:5000;
# 关键配置:关闭缓冲以支持 SSE 流式输出
proxy_buffering off;
proxy_cache off;
# 传递客户端真实 IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 长连接配置
proxy_http_version 1.1;
proxy_set_header Connection "";
# 超时设置 (应对长对话)
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
}
# 开启 Gzip 压缩
gzip on;
gzip_min_length 1k;
gzip_comp_level 6;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
}
+34
View File
@@ -0,0 +1,34 @@
; hxops_supervisord.conf
; 放置于 /etc/supervisor/conf.d/hxops.conf
[program:hxops-backend]
; 启动命令:使用 Gunicorn 启动 Flask 应用
command=/opt/hxops/backend/venv/bin/gunicorn -c /opt/hxops/backend/deploy/gunicorn_config.py "app:create_app('production')"
; 工作目录
directory=/opt/hxops/backend
; 启动用户
user=root
; 自动启动
autostart=true
autorestart=true
; 启动重试次数
startretries=3
; 停止信号
stopsignal=QUIT
; 日志配置
stdout_logfile=/var/log/hxops/backend.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=10
stderr_logfile=/var/log/hxops/backend_err.log
stderr_logfile_maxbytes=50MB
stderr_logfile_backups=10
; 环境变量
environment=FLASK_APP=run.py,FLASK_ENV=production,DATABASE_URL="postgresql://hxops:password@localhost/hxops_prod"
+33
View File
@@ -0,0 +1,33 @@
import os
import sys
from sqlalchemy import text
# Add backend directory to path
sys.path.append(os.path.join(os.getcwd(), 'backend'))
from app import create_app, db
from app.models import Agent
app = create_app()
with app.app_context():
try:
# Check DB connection
db.session.execute(text('SELECT 1'))
print("Database connection successful.")
# Update Agent
agent = Agent.query.filter_by(name='人事规章').first()
if agent:
print(f"Updating Agent: {agent.name}")
# Switch back to local mock server
agent.api_base_url = "http://127.0.0.1:5001/v1"
agent.dify_api_key = "app-xdiejQibWQy8ZQWXcdxJjS9I"
db.session.commit()
print("Agent updated to use Mock Server (127.0.0.1:5001).")
else:
print("Agent '人事规章' not found.")
except Exception as e:
print(f"Error: {e}")
+60
View File
@@ -0,0 +1,60 @@
import os
import sys
import json
from flask import Flask
# Add backend directory to path
sys.path.append(os.path.join(os.getcwd(), 'backend'))
from app import create_app, db
from app.models import Agent, User
from app.services.dify import DifyService
app = create_app()
with app.app_context():
print("Testing Chat Flow...")
# Get Agent
agent = Agent.query.filter_by(name='人事规章').first()
if not agent:
print("Error: Agent '人事规章' not found.")
sys.exit(1)
print(f"Using Agent: {agent.name} (ID: {agent.id})")
print(f"API Base: {agent.api_base_url}")
# Get User (or create dummy)
user = User.query.first()
if not user:
print("Creating dummy user for test...")
user = User(username='test_chat_user', email='test_chat@example.com', role='user')
db.session.add(user)
db.session.commit()
print(f"Using User: {user.username} (ID: {user.id})")
# Test stream_chat
print("\n--- Starting Stream Chat ---")
try:
query = "请问年假有多少天?"
generator = DifyService.stream_chat(query, user.id, agent)
full_response = ""
for chunk in generator:
print(f"Chunk: {chunk.strip()}")
if chunk.startswith("data: "):
data = json.loads(chunk[6:])
if data.get('event') == 'message':
full_response += data.get('answer', '')
print("\n--- Stream Finished ---")
print(f"Full Response: {full_response}")
except Exception as e:
print(f"\nError during chat: {e}")
import traceback
traceback.print_exc()
print("\nTest Complete.")