Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9eeeace88c | |||
| ba5d49005b | |||
| c71f27072a | |||
| 22a109d6c0 |
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI Chat App - 后台管理服务
|
||||
端口: 19020 (与前端同一端口)
|
||||
端口: 19021 (与前端同一端口)
|
||||
"""
|
||||
|
||||
from flask import Flask, jsonify, request, send_from_directory
|
||||
@@ -11,6 +11,7 @@ import json
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import base64
|
||||
|
||||
app = Flask(__name__, static_folder='../www')
|
||||
CORS(app)
|
||||
@@ -18,6 +19,11 @@ CORS(app)
|
||||
# 数据库路径
|
||||
DB_PATH = os.path.join(os.path.dirname(__file__), 'data.db')
|
||||
|
||||
# 头像存储目录
|
||||
AVATAR_DIR = os.path.join(os.path.dirname(__file__), 'avatars')
|
||||
if not os.path.exists(AVATAR_DIR):
|
||||
os.makedirs(AVATAR_DIR)
|
||||
|
||||
# 管理员账户(默认)
|
||||
ADMIN_USERNAME = 'admin'
|
||||
ADMIN_PASSWORD_HASH = hashlib.sha256('admin123'.encode()).hexdigest()
|
||||
@@ -254,13 +260,19 @@ def init_db():
|
||||
if cursor.fetchone()[0] == 0:
|
||||
default_configs = [
|
||||
('app_name', 'AI助手', '应用名称'),
|
||||
('app_version', '3.5.1', '应用版本'),
|
||||
('app_version', '3.10.0', '应用版本'),
|
||||
('llm_provider', 'zhipu', '默认大模型提供商'),
|
||||
('enable_search', 'true', '是否启用联网搜索'),
|
||||
('guest_chat_sessions', '1', '游客每日对话会话限制'),
|
||||
('guest_chat_messages', '20', '游客每日对话消息限制'),
|
||||
('guest_agent_messages', '20', '游客每日智能体消息限制'),
|
||||
('admin_password', 'admin123', '管理员密码'),
|
||||
('app_developer', 'OpenClaw Team', '开发者'),
|
||||
('app_update_date', '2026-04-27', '更新日期'),
|
||||
('app_technology', '智谱 GLM-4.5-Air 大模型', '技术基础'),
|
||||
('app_description', '提供智能对话、多种智能体服务', '应用简介'),
|
||||
('privacy_policy_url', '', '隐私政策链接'),
|
||||
('user_agreement_url', '', '用户协议链接'),
|
||||
]
|
||||
for key, value, desc in default_configs:
|
||||
cursor.execute('INSERT INTO system_configs (key, value, description) VALUES (?, ?, ?)', (key, value, desc))
|
||||
@@ -610,6 +622,74 @@ def change_user_password(id):
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 用户头像上传 ====================
|
||||
|
||||
@app.route('/api/user/<int:user_id>/avatar', methods=['POST'])
|
||||
def upload_user_avatar(user_id):
|
||||
"""上传用户头像"""
|
||||
data = request.json
|
||||
avatar_data = data.get('avatar') # base64 格式图片
|
||||
|
||||
if not avatar_data:
|
||||
return jsonify({'error': '头像数据不能为空'}), 400
|
||||
|
||||
# 解析 base64 数据
|
||||
try:
|
||||
# 支持两种格式:
|
||||
# 1. data:image/png;base64,xxxxx
|
||||
# 2. 纯 base64 字符串
|
||||
|
||||
if avatar_data.startswith('data:'):
|
||||
# 提取格式和内容
|
||||
header, content = avatar_data.split(',', 1)
|
||||
# 提取图片格式
|
||||
mime_type = header.split(':')[1].split(';')[0]
|
||||
ext = mime_type.split('/')[1] if '/' in mime_type else 'png'
|
||||
else:
|
||||
content = avatar_data
|
||||
ext = 'png'
|
||||
|
||||
# 解码 base64
|
||||
image_bytes = base64.b64decode(content)
|
||||
|
||||
# 验证图片大小(最大 2MB)
|
||||
if len(image_bytes) > 2 * 1024 * 1024:
|
||||
return jsonify({'error': '头像大小不能超过2MB'}), 400
|
||||
|
||||
# 生成文件名
|
||||
filename = f'user_{user_id}_{int(datetime.now().timestamp())}.{ext}'
|
||||
filepath = os.path.join(AVATAR_DIR, filename)
|
||||
|
||||
# 保存文件
|
||||
with open(filepath, 'wb') as f:
|
||||
f.write(image_bytes)
|
||||
|
||||
# 更新数据库(存储文件名)
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('UPDATE users SET avatar=?, updated_at=CURRENT_TIMESTAMP WHERE id=?',
|
||||
(filename, user_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return jsonify({'success': True, 'avatar': filename, 'avatar_url': f'/api/avatars/{filename}'})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'error': f'头像上传失败: {str(e)}'}), 500
|
||||
|
||||
|
||||
@app.route('/api/avatars/<filename>', methods=['GET'])
|
||||
def get_avatar(filename):
|
||||
"""获取头像图片"""
|
||||
return send_from_directory(AVATAR_DIR, filename)
|
||||
|
||||
|
||||
@app.route('/api/admin/users/<int:user_id>/avatar', methods=['POST'])
|
||||
def admin_upload_user_avatar(user_id):
|
||||
"""管理员上传用户头像"""
|
||||
return upload_user_avatar(user_id)
|
||||
|
||||
|
||||
# ==================== 用户对话数据同步 ====================
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations', methods=['GET'])
|
||||
@@ -1252,6 +1332,10 @@ def get_frontend_config():
|
||||
cursor.execute('SELECT * FROM tool_configs WHERE is_default=1 AND is_active=1')
|
||||
tools = [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
# 获取所有活跃的工具配置(供前端选择)
|
||||
cursor.execute('SELECT tool_id, name, type, provider, is_active FROM tool_configs WHERE is_active=1')
|
||||
allTools = [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
# 获取所有智能体(上线且活跃)
|
||||
cursor.execute('SELECT agent_id, name, avatar, category, description, system_prompt, heat, tags, enable_tools FROM agents WHERE is_online=1 AND is_active=1')
|
||||
agents = [dict(row) for row in cursor.fetchall()]
|
||||
@@ -1269,17 +1353,24 @@ def get_frontend_config():
|
||||
config = {
|
||||
'llm': dict(llm) if llm else None,
|
||||
'tools': tools,
|
||||
'allTools': allTools, # 所有活跃的工具(供前端选择)
|
||||
'agents': agents,
|
||||
'chat_config': dict(chat_config) if chat_config else None,
|
||||
'system': {
|
||||
'appName': system.get('app_name', 'AI助手'),
|
||||
'version': system.get('app_version', '3.6.0'),
|
||||
'version': system.get('app_version', '3.10.0'),
|
||||
'enableSearch': system.get('enable_search', 'true') == 'true',
|
||||
'guestLimits': {
|
||||
'chatSessions': int(system.get('guest_chat_sessions', '1')),
|
||||
'chatMessages': int(system.get('guest_chat_messages', '20')),
|
||||
'agentMessages': int(system.get('guest_agent_messages', '20')),
|
||||
}
|
||||
},
|
||||
'developer': system.get('app_developer', 'OpenClaw Team'),
|
||||
'updateDate': system.get('app_update_date', '2026-04-27'),
|
||||
'technology': system.get('app_technology', '智谱 GLM-4.5-Air 大模型'),
|
||||
'description': system.get('app_description', '提供智能对话、多种智能体服务'),
|
||||
'privacyPolicyUrl': system.get('privacy_policy_url', ''),
|
||||
'userAgreementUrl': system.get('user_agreement_url', ''),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
40
www/admin.js
40
www/admin.js
@@ -1355,6 +1355,26 @@ async function loadSystemPage(content) {
|
||||
<input type="text" class="form-input" id="appVersion" value="${systemConfigs.app_version?.value || ''}">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">应用简介</label>
|
||||
<input type="text" class="form-input" id="appDescription" value="${systemConfigs.app_description?.value || ''}" placeholder="如:提供智能对话、多种智能体服务">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">技术基础</label>
|
||||
<input type="text" class="form-input" id="appTechnology" value="${systemConfigs.app_technology?.value || ''}" placeholder="如:智谱 GLM-4.5-Air 大模型">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">开发者</label>
|
||||
<input type="text" class="form-input" id="appDeveloper" value="${systemConfigs.app_developer?.value || ''}" placeholder="如:OpenClaw Team">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">更新日期</label>
|
||||
<input type="text" class="form-input" id="appUpdateDate" value="${systemConfigs.app_update_date?.value || ''}" placeholder="如:2026-04-27">
|
||||
</div>
|
||||
|
||||
<h3 style="margin: 24px 0 16px; padding-top: 16px; border-top: 1px solid #e2e8f0;">游客使用限制</h3>
|
||||
|
||||
<div class="form-group">
|
||||
@@ -1379,6 +1399,18 @@ async function loadSystemPage(content) {
|
||||
<input type="text" class="form-input" id="adminPassword" value="${systemConfigs.admin_password?.value || ''}" placeholder="修改管理员密码">
|
||||
</div>
|
||||
|
||||
<h3 style="margin: 24px 0 16px; padding-top: 16px; border-top: 1px solid #e2e8f0;">链接配置</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">隐私政策链接</label>
|
||||
<input type="text" class="form-input" id="privacyPolicyUrl" value="${systemConfigs.privacy_policy_url?.value || ''}" placeholder="隐私政策页面URL">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">用户协议链接</label>
|
||||
<input type="text" class="form-input" id="userAgreementUrl" value="${systemConfigs.user_agreement_url?.value || ''}" placeholder="用户协议页面URL">
|
||||
</div>
|
||||
|
||||
<button class="form-submit" onclick="saveSystemConfig()">保存设置</button>
|
||||
</div>
|
||||
|
||||
@@ -1394,10 +1426,16 @@ async function saveSystemConfig() {
|
||||
const data = {
|
||||
app_name: document.getElementById('appName').value,
|
||||
app_version: document.getElementById('appVersion').value,
|
||||
app_description: document.getElementById('appDescription').value,
|
||||
app_technology: document.getElementById('appTechnology').value,
|
||||
app_developer: document.getElementById('appDeveloper').value,
|
||||
app_update_date: document.getElementById('appUpdateDate').value,
|
||||
guest_chat_sessions: document.getElementById('guestChatSessions').value,
|
||||
guest_chat_messages: document.getElementById('guestChatMessages').value,
|
||||
guest_agent_messages: document.getElementById('guestAgentMessages').value,
|
||||
admin_password: document.getElementById('adminPassword').value
|
||||
admin_password: document.getElementById('adminPassword').value,
|
||||
privacy_policy_url: document.getElementById('privacyPolicyUrl').value,
|
||||
user_agreement_url: document.getElementById('userAgreementUrl').value,
|
||||
};
|
||||
|
||||
await fetchAPI('/api/admin/system', 'POST', data);
|
||||
|
||||
359
www/app.js
359
www/app.js
@@ -116,6 +116,14 @@ async function loadBackendConfig() {
|
||||
};
|
||||
}
|
||||
|
||||
// 加载工具列表
|
||||
if (backendConfig.allTools) {
|
||||
// 过滤掉联网搜索(已有单独按钮)
|
||||
allTools = backendConfig.allTools.filter(t => t.type !== 'search');
|
||||
}
|
||||
|
||||
// 不加载默认启用的工具,所有工具默认未启用
|
||||
|
||||
updateAgentsDisplay();
|
||||
console.log('后台配置已加载', backendConfig);
|
||||
} catch (e) {
|
||||
@@ -282,6 +290,8 @@ function getAgentConversationHistory(limit = 5) {
|
||||
let enableThinking = false; // 深度思考
|
||||
let enableSearch = false; // 联网搜索
|
||||
let autoScrollEnabled = true; // 自动滚动(用户滚动后可关闭)
|
||||
let enabledTools = []; // 启用的工具列表(多选)
|
||||
let allTools = []; // 所有可用的工具列表
|
||||
|
||||
// DOM 元素(初始为 null,在 openConversation 时重新获取)
|
||||
let appContainer = null;
|
||||
@@ -1493,6 +1503,9 @@ function renderProfilePage() {
|
||||
const userAvatar = currentUser?.avatar || '👤';
|
||||
const userSignature = currentUser?.signature || '这个人很懒,什么都没写~';
|
||||
|
||||
// 渲染头像(支持 emoji 和上传图片)
|
||||
const avatarHtml = renderAvatar(userAvatar);
|
||||
|
||||
return `
|
||||
<div class="profile-page">
|
||||
<header class="page-header">
|
||||
@@ -1502,7 +1515,7 @@ function renderProfilePage() {
|
||||
<div class="profile-content">
|
||||
<!-- 用户卡片 -->
|
||||
<div class="profile-user-card" id="userCard">
|
||||
<div class="profile-avatar-large" id="profileAvatar">${userAvatar}</div>
|
||||
<div class="profile-avatar-large" id="profileAvatar">${avatarHtml}</div>
|
||||
<div class="profile-user-info">
|
||||
<div class="profile-name">${currentUser ? currentUser.username : '游客'}</div>
|
||||
<div class="profile-signature">${currentUser ? userSignature : '登录后解锁更多功能'}</div>
|
||||
@@ -1599,8 +1612,8 @@ function renderProfilePage() {
|
||||
</div>
|
||||
|
||||
<div class="profile-footer">
|
||||
<p>AI助手 v3.6.0</p>
|
||||
<p>基于智谱 GLM-4.5-Air</p>
|
||||
<p>${CONFIG?.system?.appName || 'AI助手'} v${CONFIG?.system?.version || '3.10.0'}</p>
|
||||
<p>基于 ${CONFIG?.system?.technology || '智谱 GLM-4.5-Air'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1750,6 +1763,9 @@ function renderEditProfilePage() {
|
||||
const age = currentUser.age || '';
|
||||
const region = currentUser.region || '';
|
||||
|
||||
// 渲染头像预览(支持 emoji 和上传图片)
|
||||
const avatarPreviewHtml = renderAvatar(avatar);
|
||||
|
||||
const editHtml = `
|
||||
<div class="edit-profile-page">
|
||||
<header class="edit-header">
|
||||
@@ -1763,9 +1779,16 @@ function renderEditProfilePage() {
|
||||
<!-- 头像选择 -->
|
||||
<div class="edit-section">
|
||||
<div class="edit-avatar-section">
|
||||
<div class="edit-avatar-preview" id="editAvatarPreview">${avatar}</div>
|
||||
<div class="edit-avatar-preview" id="editAvatarPreview">${avatarPreviewHtml}</div>
|
||||
<div class="edit-avatar-label">点击更换头像</div>
|
||||
</div>
|
||||
<div class="avatar-upload-section">
|
||||
<input type="file" id="avatarUploadInput" accept="image/*" style="display: none;">
|
||||
<button class="avatar-upload-btn" id="avatarUploadBtn">
|
||||
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z"/></svg>
|
||||
上传头像
|
||||
</button>
|
||||
</div>
|
||||
<div class="avatar-selector" id="avatarSelector">
|
||||
${['👤', '😊', '😎', '🤓', '🧑', '👨', '👩', '🧒', '👴', '👵', '🦸', '🧙', '🤖', '👽', '🥷'].map(a => `
|
||||
<div class="avatar-option ${a === avatar ? 'selected' : ''}" data-avatar="${a}">${a}</div>
|
||||
@@ -1846,9 +1869,28 @@ function renderEditProfilePage() {
|
||||
document.getElementById('editAvatarPreview').textContent = newAvatar;
|
||||
document.querySelectorAll('.avatar-option').forEach(o => o.classList.remove('selected'));
|
||||
option.classList.add('selected');
|
||||
// 清除上传的头像标记
|
||||
uploadedAvatarData = null;
|
||||
});
|
||||
});
|
||||
|
||||
// 绑定头像上传按钮
|
||||
const uploadBtn = document.getElementById('avatarUploadBtn');
|
||||
const uploadInput = document.getElementById('avatarUploadInput');
|
||||
|
||||
if (uploadBtn && uploadInput) {
|
||||
uploadBtn.addEventListener('click', () => {
|
||||
uploadInput.click();
|
||||
});
|
||||
|
||||
uploadInput.addEventListener('change', (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (file) {
|
||||
handleAvatarUpload(file);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 绑定性别选择
|
||||
document.querySelectorAll('.gender-option').forEach(option => {
|
||||
option.addEventListener('click', () => {
|
||||
@@ -1864,8 +1906,58 @@ function renderEditProfilePage() {
|
||||
}
|
||||
}
|
||||
|
||||
function handleSaveProfile() {
|
||||
const newAvatar = document.querySelector('.avatar-option.selected')?.getAttribute('data-avatar') || '👤';
|
||||
// 上传头像变量
|
||||
let uploadedAvatarData = null;
|
||||
|
||||
// 处理头像上传
|
||||
async function handleAvatarUpload(file) {
|
||||
// 验证文件类型
|
||||
if (!file.type.startsWith('image/')) {
|
||||
showToast('请上传图片文件');
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证文件大小(最大 2MB)
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
showToast('图片大小不能超过2MB');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 读取文件为 base64
|
||||
const reader = new FileReader();
|
||||
reader.onload = async (e) => {
|
||||
const base64Data = e.target.result;
|
||||
|
||||
// 显示预览
|
||||
const previewEl = document.getElementById('editAvatarPreview');
|
||||
if (previewEl) {
|
||||
previewEl.innerHTML = `<img src="${base64Data}" style="width: 80px; height: 80px; border-radius: 50%; object-fit: cover;">`;
|
||||
}
|
||||
|
||||
// 清除预设头像选中状态
|
||||
document.querySelectorAll('.avatar-option').forEach(o => o.classList.remove('selected'));
|
||||
|
||||
// 保存上传的头像数据
|
||||
uploadedAvatarData = base64Data;
|
||||
|
||||
showToast('头像已加载,保存后生效');
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
} catch (e) {
|
||||
showToast('头像加载失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveProfile() {
|
||||
// 检查是否有上传的头像
|
||||
let newAvatar = uploadedAvatarData;
|
||||
|
||||
// 如果没有上传头像,使用预设头像
|
||||
if (!newAvatar) {
|
||||
newAvatar = document.querySelector('.avatar-option.selected')?.getAttribute('data-avatar') || currentUser.avatar || '👤';
|
||||
}
|
||||
|
||||
const newUsername = document.getElementById('editUsername')?.value.trim();
|
||||
const newSignature = document.getElementById('editSignature')?.value.trim();
|
||||
const newEmail = document.getElementById('editEmail')?.value.trim();
|
||||
@@ -1874,8 +1966,8 @@ function handleSaveProfile() {
|
||||
const newRegion = document.getElementById('editRegion')?.value.trim();
|
||||
|
||||
// 验证用户名
|
||||
if (!newUsername || newUsername.length < 3 || newUsername.length > 20) {
|
||||
showToast('用户名需要3-20个字符');
|
||||
if (!newUsername || newUsername.length < 2 || newUsername.length > 20) {
|
||||
showToast('用户名需要2-20个字符');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1902,6 +1994,30 @@ function handleSaveProfile() {
|
||||
|
||||
// 如果用户已登录,调用 backend API 更新
|
||||
if (currentUser.id) {
|
||||
// 先处理头像上传(如果有上传的头像)
|
||||
if (uploadedAvatarData) {
|
||||
try {
|
||||
const avatarRes = await fetch(`/api/user/${currentUser.id}/avatar`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ avatar: uploadedAvatarData })
|
||||
});
|
||||
const avatarData = await avatarRes.json();
|
||||
if (avatarData.success && avatarData.avatar_url) {
|
||||
// 使用上传后的头像 URL
|
||||
newAvatar = avatarData.avatar;
|
||||
currentUser.avatar = newAvatar;
|
||||
} else {
|
||||
showToast(avatarData.error || '头像上传失败');
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('头像上传失败,请重试');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新用户资料
|
||||
fetch(`/api/user/${currentUser.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -2418,6 +2534,13 @@ function showHelpPage() {
|
||||
// ==================== 关于页面 ====================
|
||||
|
||||
function showAboutPage() {
|
||||
const appName = CONFIG?.system?.appName || 'AI助手';
|
||||
const version = CONFIG?.system?.version || '3.10.0';
|
||||
const developer = CONFIG?.system?.developer || 'OpenClaw Team';
|
||||
const updateDate = CONFIG?.system?.updateDate || '2026-04-27';
|
||||
const technology = CONFIG?.system?.technology || '智谱 GLM-4.5-Air 大模型';
|
||||
const description = CONFIG?.system?.description || '提供智能对话、多种智能体服务';
|
||||
|
||||
const aboutHtml = `
|
||||
<div class="settings-page">
|
||||
<header class="settings-header">
|
||||
@@ -2429,22 +2552,22 @@ function showAboutPage() {
|
||||
|
||||
<div class="settings-content about-content">
|
||||
<div class="about-logo">🤖</div>
|
||||
<div class="about-name">AI助手</div>
|
||||
<div class="about-version">v3.5.0</div>
|
||||
<div class="about-name">${appName}</div>
|
||||
<div class="about-version">v${version}</div>
|
||||
|
||||
<div class="about-info">
|
||||
<p>基于智谱 GLM-4.5-Air 大模型</p>
|
||||
<p>提供智能对话、多种智能体服务</p>
|
||||
<p>基于 ${technology}</p>
|
||||
<p>${description}</p>
|
||||
</div>
|
||||
|
||||
<div class="about-section">
|
||||
<div class="about-item">
|
||||
<span class="about-label">开发者</span>
|
||||
<span class="about-value">OpenClaw Team</span>
|
||||
<span class="about-value">${developer}</span>
|
||||
</div>
|
||||
<div class="about-item">
|
||||
<span class="about-label">更新日期</span>
|
||||
<span class="about-value">2026-04-27</span>
|
||||
<span class="about-value">${updateDate}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2919,6 +3042,9 @@ async function openAgent(agentId) {
|
||||
currentAgent = systemAgents.find(a => a.id === agentId);
|
||||
if (!currentAgent) return;
|
||||
|
||||
// 加载该智能体的工具选择状态
|
||||
loadToolsState();
|
||||
|
||||
// 检查未登录用户的智能体限制
|
||||
if (!currentUser) {
|
||||
const check = canUseAgent(agentId);
|
||||
@@ -3016,6 +3142,11 @@ function showAgentChatPage() {
|
||||
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 7 9.5 7 14 9.01 14 9.5 11.99 14 9.5 14z"/></svg>
|
||||
<span>联网搜索</span>
|
||||
</button>
|
||||
<button class="feature-btn tools-btn" id="moreToolsBtn">
|
||||
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"/></svg>
|
||||
<span>更多工具</span>
|
||||
${enabledTools.length > 0 ? `<span class="tools-count">${enabledTools.length}</span>` : ''}
|
||||
</button>
|
||||
</div>
|
||||
<div class="feature-right">
|
||||
<button class="feature-btn nav-btn" id="scrollTopBtn">
|
||||
@@ -3107,6 +3238,14 @@ function showAgentChatPage() {
|
||||
});
|
||||
}
|
||||
|
||||
// 绑定更多工具按钮
|
||||
const moreToolsBtn = document.getElementById('moreToolsBtn');
|
||||
if (moreToolsBtn) {
|
||||
moreToolsBtn.addEventListener('click', () => {
|
||||
showToolsSelector();
|
||||
});
|
||||
}
|
||||
|
||||
// 绑定输入事件
|
||||
userInput.addEventListener('keydown', handleKeyDown);
|
||||
userInput.addEventListener('input', (e) => autoResize(e.target));
|
||||
@@ -3461,6 +3600,10 @@ function openConversation(id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 普通对话,加载普通对话的工具状态
|
||||
currentAgent = null;
|
||||
loadToolsState();
|
||||
|
||||
// 渲染对话页面
|
||||
const chatHtml = `
|
||||
<div id="chatPage">
|
||||
@@ -3502,6 +3645,11 @@ function openConversation(id) {
|
||||
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 7 9.5 7 14 9.01 14 9.5 11.99 14 9.5 14z"/></svg>
|
||||
<span>联网搜索</span>
|
||||
</button>
|
||||
<button class="feature-btn tools-btn" id="moreToolsBtn">
|
||||
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"/></svg>
|
||||
<span>更多工具</span>
|
||||
${enabledTools.length > 0 ? `<span class="tools-count">${enabledTools.length}</span>` : ''}
|
||||
</button>
|
||||
</div>
|
||||
<div class="feature-right">
|
||||
<button class="feature-btn nav-btn" id="scrollTopBtn" title="回到顶部">
|
||||
@@ -3584,6 +3732,14 @@ function openConversation(id) {
|
||||
});
|
||||
}
|
||||
|
||||
// 绑定更多工具按钮
|
||||
const moreToolsBtn = document.getElementById('moreToolsBtn');
|
||||
if (moreToolsBtn) {
|
||||
moreToolsBtn.addEventListener('click', () => {
|
||||
showToolsSelector();
|
||||
});
|
||||
}
|
||||
|
||||
// 绑定置顶置底按钮事件
|
||||
const scrollTopBtn = document.getElementById('scrollTopBtn');
|
||||
const scrollBottomBtn = document.getElementById('scrollBottomBtn');
|
||||
@@ -3978,6 +4134,181 @@ function logStatsToBackend(type, key, value = 1) {
|
||||
}).catch(e => console.error('统计记录失败:', e));
|
||||
}
|
||||
|
||||
// 显示工具选择弹窗
|
||||
function showToolsSelector() {
|
||||
if (allTools.length === 0) {
|
||||
showToast('暂无可用工具');
|
||||
return;
|
||||
}
|
||||
|
||||
// 工具类型图标映射
|
||||
const toolIcons = {
|
||||
search: '🔍',
|
||||
calculator: '🧮',
|
||||
image: '🎨',
|
||||
code: '💻',
|
||||
weather: '🌤️',
|
||||
custom: '🔧'
|
||||
};
|
||||
|
||||
const toolsHtml = allTools.map(tool => `
|
||||
<div class="tool-option ${enabledTools.includes(tool.tool_id) ? 'selected' : ''}" data-tool-id="${tool.tool_id}">
|
||||
<div class="tool-checkbox">
|
||||
<svg viewBox="0 0 24 24" width="20" height="20">
|
||||
${enabledTools.includes(tool.tool_id)
|
||||
? '<path fill="currentColor" d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 14l-5-5 1.41-1.41L12 14.17l4.59-4.58L18 10l-6 6z"/>'
|
||||
: '<path fill="currentColor" d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/>'
|
||||
}
|
||||
</svg>
|
||||
</div>
|
||||
<div class="tool-icon">${toolIcons[tool.type] || '🔧'}</div>
|
||||
<div class="tool-info">
|
||||
<div class="tool-name">${tool.name}</div>
|
||||
<div class="tool-type">${tool.type}</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
const popupHtml = `
|
||||
<div class="tools-popup" id="toolsPopup">
|
||||
<div class="tools-popup-content">
|
||||
<div class="tools-popup-header">
|
||||
<h3>选择工具</h3>
|
||||
<button class="tools-popup-close" id="toolsPopupClose">×</button>
|
||||
</div>
|
||||
<div class="tools-popup-body">
|
||||
<p class="tools-popup-tip">勾选要启用的工具(多选)</p>
|
||||
<div class="tools-list">
|
||||
${toolsHtml}
|
||||
</div>
|
||||
</div>
|
||||
<div class="tools-popup-footer">
|
||||
<button class="tools-popup-btn cancel" id="toolsCancelBtn">取消</button>
|
||||
<button class="tools-popup-btn confirm" id="toolsConfirmBtn">确认</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 添加到页面
|
||||
const existingPopup = document.getElementById('toolsPopup');
|
||||
if (existingPopup) existingPopup.remove();
|
||||
|
||||
document.body.appendChild(document.createElement('div'));
|
||||
document.body.lastElementChild.outerHTML = popupHtml;
|
||||
|
||||
// 绑定事件
|
||||
document.querySelectorAll('.tool-option').forEach(option => {
|
||||
option.addEventListener('click', () => {
|
||||
option.classList.toggle('selected');
|
||||
// 更新复选框图标
|
||||
const checkbox = option.querySelector('.tool-checkbox svg');
|
||||
const isSelected = option.classList.contains('selected');
|
||||
checkbox.innerHTML = isSelected
|
||||
? '<path fill="currentColor" d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 14l-5-5 1.41-1.41L12 14.17l4.59-4.58L18 10l-6 6z"/>'
|
||||
: '<path fill="currentColor" d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/>';
|
||||
});
|
||||
});
|
||||
|
||||
// 关闭按钮
|
||||
document.getElementById('toolsPopupClose').addEventListener('click', closeToolsPopup);
|
||||
document.getElementById('toolsCancelBtn').addEventListener('click', closeToolsPopup);
|
||||
document.getElementById('toolsConfirmBtn').addEventListener('click', confirmToolsSelection);
|
||||
|
||||
// 点击背景关闭
|
||||
document.getElementById('toolsPopup').addEventListener('click', (e) => {
|
||||
if (e.target.id === 'toolsPopup') {
|
||||
closeToolsPopup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function closeToolsPopup() {
|
||||
const popup = document.getElementById('toolsPopup');
|
||||
if (popup) popup.remove();
|
||||
}
|
||||
|
||||
function confirmToolsSelection() {
|
||||
// 获取选中的工具
|
||||
const selectedTools = [];
|
||||
document.querySelectorAll('.tool-option.selected').forEach(option => {
|
||||
selectedTools.push(option.getAttribute('data-tool-id'));
|
||||
});
|
||||
|
||||
enabledTools = selectedTools;
|
||||
|
||||
// 保存工具选择状态
|
||||
saveToolsState();
|
||||
|
||||
// 更新按钮显示
|
||||
const moreToolsBtn = document.getElementById('moreToolsBtn');
|
||||
if (moreToolsBtn) {
|
||||
const countSpan = moreToolsBtn.querySelector('.tools-count');
|
||||
if (enabledTools.length > 0) {
|
||||
if (countSpan) {
|
||||
countSpan.textContent = enabledTools.length;
|
||||
} else {
|
||||
const span = document.createElement('span');
|
||||
span.className = 'tools-count';
|
||||
span.textContent = enabledTools.length;
|
||||
moreToolsBtn.appendChild(span);
|
||||
}
|
||||
} else if (countSpan) {
|
||||
countSpan.remove();
|
||||
}
|
||||
}
|
||||
|
||||
closeToolsPopup();
|
||||
showToast(`已启用 ${enabledTools.length} 个工具`);
|
||||
}
|
||||
|
||||
// 保存工具选择状态
|
||||
function saveToolsState() {
|
||||
if (currentAgent) {
|
||||
// 智能体对话:保存到 localStorage(按智能体ID)
|
||||
localStorage.setItem(`agentEnabledTools_${currentAgent.id}`, JSON.stringify(enabledTools));
|
||||
} else {
|
||||
// 普通对话:保存到 localStorage
|
||||
localStorage.setItem('chatEnabledTools', JSON.stringify(enabledTools));
|
||||
}
|
||||
}
|
||||
|
||||
// 加载工具选择状态
|
||||
function loadToolsState() {
|
||||
if (currentAgent) {
|
||||
// 智能体对话:加载该智能体的工具状态
|
||||
const saved = localStorage.getItem(`agentEnabledTools_${currentAgent.id}`);
|
||||
if (saved) {
|
||||
enabledTools = JSON.parse(saved);
|
||||
} else {
|
||||
enabledTools = [];
|
||||
}
|
||||
} else {
|
||||
// 普通对话:加载普通对话的工具状态
|
||||
const saved = localStorage.getItem('chatEnabledTools');
|
||||
if (saved) {
|
||||
enabledTools = JSON.parse(saved);
|
||||
} else {
|
||||
enabledTools = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染头像(支持 emoji 和上传的图片)
|
||||
function renderAvatar(avatar) {
|
||||
if (!avatar) return '👤';
|
||||
|
||||
// 检查是否是 emoji(单个字符或者预设列表中的)
|
||||
const emojiAvatars = ['👤', '😊', '😎', '🤓', '🧑', '👨', '👩', '🧒', '👴', '👵', '🦸', '🧙', '🤖', '👽', '🥷'];
|
||||
|
||||
if (emojiAvatars.includes(avatar) || avatar.length <= 4) {
|
||||
return avatar;
|
||||
}
|
||||
|
||||
// 否则认为是上传的文件名
|
||||
return `<img src="/api/avatars/${avatar}" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;" onerror="this.parentElement.textContent='👤'">`;
|
||||
}
|
||||
|
||||
// 执行 Tavily 搜索
|
||||
async function performSearch(query) {
|
||||
try {
|
||||
|
||||
212
www/style.css
212
www/style.css
@@ -1049,6 +1049,31 @@ body {
|
||||
box-shadow: 0 0 8px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.avatar-upload-section {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.avatar-upload-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px 24px;
|
||||
background: linear-gradient(135deg, var(--primary) 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.avatar-upload-btn:hover {
|
||||
transform: scale(1.02);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.edit-input-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
@@ -2715,6 +2740,193 @@ body {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* 更多工具按钮 */
|
||||
.tools-btn {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tools-count {
|
||||
position: absolute;
|
||||
top: -4px;
|
||||
right: -4px;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
background: #ef4444;
|
||||
color: white;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* 工具选择弹窗 */
|
||||
.tools-popup {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.tools-popup-content {
|
||||
width: 90%;
|
||||
max-width: 400px;
|
||||
background: white;
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tools-popup-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
background: linear-gradient(135deg, var(--primary) 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.tools-popup-header h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.tools-popup-close {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border: none;
|
||||
border-radius: 14px;
|
||||
color: white;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.tools-popup-close:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
.tools-popup-body {
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
.tools-popup-tip {
|
||||
color: #718096;
|
||||
font-size: 13px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.tools-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.tool-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
background: #f5f7fa;
|
||||
border: 2px solid transparent;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.tool-option:hover {
|
||||
background: #e8ecf1;
|
||||
}
|
||||
|
||||
.tool-option.selected {
|
||||
background: rgba(102, 126, 234, 0.1);
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.tool-checkbox {
|
||||
flex-shrink: 0;
|
||||
color: #718096;
|
||||
}
|
||||
|
||||
.tool-option.selected .tool-checkbox {
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.tool-icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.tool-info {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.tool-name {
|
||||
font-weight: 500;
|
||||
color: #2d3748;
|
||||
}
|
||||
|
||||
.tool-type {
|
||||
font-size: 12px;
|
||||
color: #718096;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.tools-popup-footer {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 16px 20px;
|
||||
background: #f5f7fa;
|
||||
}
|
||||
|
||||
.tools-popup-btn {
|
||||
flex: 1;
|
||||
padding: 12px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.tools-popup-btn.cancel {
|
||||
background: #e2e8f0;
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
.tools-popup-btn.cancel:hover {
|
||||
background: #cbd5e0;
|
||||
}
|
||||
|
||||
.tools-popup-btn.confirm {
|
||||
background: linear-gradient(135deg, var(--primary) 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.tools-popup-btn.confirm:hover {
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
/* 导航按钮样式 */
|
||||
.nav-btn {
|
||||
padding: 6px 8px;
|
||||
|
||||
Reference in New Issue
Block a user