Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c3f7604c9 | |||
| 0086eaa1d6 | |||
| 8e17ef5e15 | |||
| 773fb89b01 | |||
| 8199773ef6 | |||
| d153986f3d |
303
backend/app.py
303
backend/app.py
@@ -166,6 +166,35 @@ def init_db():
|
||||
)
|
||||
''')
|
||||
|
||||
# 用户智能体配置表(我的智能体)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS user_agents (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
agent_id TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
is_pinned INTEGER DEFAULT 0,
|
||||
is_favorite INTEGER DEFAULT 0,
|
||||
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
UNIQUE(user_id, agent_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# 对话表(用户对话数据)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS conversations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
agent_id TEXT,
|
||||
messages TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
)
|
||||
''')
|
||||
|
||||
# 初始化默认大模型配置
|
||||
cursor.execute('SELECT COUNT(*) FROM llm_configs')
|
||||
if cursor.fetchone()[0] == 0:
|
||||
@@ -581,6 +610,280 @@ def change_user_password(id):
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 用户对话数据同步 ====================
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations', methods=['GET'])
|
||||
def get_user_conversations(user_id):
|
||||
"""获取用户所有对话"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT id, title, agent_id, messages, created_at, updated_at
|
||||
FROM conversations WHERE user_id = ? ORDER BY updated_at DESC
|
||||
''', (user_id,))
|
||||
|
||||
conversations = []
|
||||
for row in cursor.fetchall():
|
||||
conv = dict(row)
|
||||
# 解析消息JSON
|
||||
try:
|
||||
conv['messages'] = json.loads(conv['messages']) if conv['messages'] else []
|
||||
except:
|
||||
conv['messages'] = []
|
||||
# 转换为前端格式(使用字符串ID)
|
||||
conv['id'] = str(conv['id'])
|
||||
conv['createdAt'] = int(datetime.strptime(conv['created_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['created_at'] else 0
|
||||
conv['updatedAt'] = int(datetime.strptime(conv['updated_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['updated_at'] else 0
|
||||
conv['agentId'] = conv['agent_id']
|
||||
conversations.append(conv)
|
||||
|
||||
conn.close()
|
||||
return jsonify(conversations)
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations/<int:conv_id>', methods=['GET'])
|
||||
def get_user_conversation_detail(user_id, conv_id):
|
||||
"""获取单个对话详情"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT id, title, agent_id, messages, created_at, updated_at
|
||||
FROM conversations WHERE id = ? AND user_id = ?
|
||||
''', (conv_id, user_id))
|
||||
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
|
||||
if not row:
|
||||
return jsonify({'error': '对话不存在'}), 404
|
||||
|
||||
conv = dict(row)
|
||||
try:
|
||||
conv['messages'] = json.loads(conv['messages']) if conv['messages'] else []
|
||||
except:
|
||||
conv['messages'] = []
|
||||
|
||||
conv['id'] = str(conv['id'])
|
||||
conv['createdAt'] = int(datetime.strptime(conv['created_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['created_at'] else 0
|
||||
conv['updatedAt'] = int(datetime.strptime(conv['updated_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['updated_at'] else 0
|
||||
conv['agentId'] = conv['agent_id']
|
||||
|
||||
return jsonify(conv)
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations', methods=['POST'])
|
||||
def create_user_conversation(user_id):
|
||||
"""创建新对话"""
|
||||
data = request.json
|
||||
title = data.get('title', '新对话')
|
||||
agent_id = data.get('agentId') or data.get('agent_id')
|
||||
messages = data.get('messages', [])
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO conversations (user_id, title, agent_id, messages)
|
||||
VALUES (?, ?, ?, ?)
|
||||
''', (user_id, title, agent_id, json.dumps(messages)))
|
||||
conn.commit()
|
||||
|
||||
conv_id = cursor.lastrowid
|
||||
conn.close()
|
||||
|
||||
return jsonify({'success': True, 'id': str(conv_id)})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations/<int:conv_id>', methods=['PUT'])
|
||||
def update_user_conversation(user_id, conv_id):
|
||||
"""更新对话(添加消息、修改标题等)"""
|
||||
data = request.json
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 验证对话属于该用户
|
||||
cursor.execute('SELECT id FROM conversations WHERE id = ? AND user_id = ?', (conv_id, user_id))
|
||||
if not cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '对话不存在'}), 404
|
||||
|
||||
# 更新字段
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if 'title' in data:
|
||||
updates.append('title = ?')
|
||||
values.append(data['title'])
|
||||
|
||||
if 'messages' in data:
|
||||
updates.append('messages = ?')
|
||||
values.append(json.dumps(data['messages']))
|
||||
|
||||
if 'agentId' in data or 'agent_id' in data:
|
||||
updates.append('agent_id = ?')
|
||||
values.append(data.get('agentId') or data.get('agent_id'))
|
||||
|
||||
if updates:
|
||||
updates.append('updated_at = CURRENT_TIMESTAMP')
|
||||
sql = f'UPDATE conversations SET {", ".join(updates)} WHERE id = ?'
|
||||
values.append(conv_id)
|
||||
cursor.execute(sql, values)
|
||||
conn.commit()
|
||||
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations/<int:conv_id>', methods=['DELETE'])
|
||||
def delete_user_conversation(user_id, conv_id):
|
||||
"""删除对话"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 验证对话属于该用户
|
||||
cursor.execute('SELECT id FROM conversations WHERE id = ? AND user_id = ?', (conv_id, user_id))
|
||||
if not cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '对话不存在'}), 404
|
||||
|
||||
cursor.execute('DELETE FROM conversations WHERE id = ?', (conv_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 用户智能体数据同步 ====================
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents', methods=['GET'])
|
||||
def get_user_agents(user_id):
|
||||
"""获取用户智能体配置"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT agent_id, category, is_pinned, is_favorite, added_at
|
||||
FROM user_agents WHERE user_id = ?
|
||||
''', (user_id,))
|
||||
|
||||
agents_data = {
|
||||
'myAgents': {}, # {category: [agent_ids]}
|
||||
'favoriteAgents': [], # [agent_ids]
|
||||
'pinnedAgents': {} # {category: [agent_ids]}
|
||||
}
|
||||
|
||||
for row in cursor.fetchall():
|
||||
agent_id = row['agent_id']
|
||||
category = row['category']
|
||||
is_pinned = row['is_pinned']
|
||||
is_favorite = row['is_favorite']
|
||||
|
||||
# 添加到 myAgents
|
||||
if category not in agents_data['myAgents']:
|
||||
agents_data['myAgents'][category] = []
|
||||
agents_data['myAgents'][category].append(agent_id)
|
||||
|
||||
# 添加到 pinnedAgents
|
||||
if is_pinned:
|
||||
if category not in agents_data['pinnedAgents']:
|
||||
agents_data['pinnedAgents'][category] = []
|
||||
agents_data['pinnedAgents'][category].append(agent_id)
|
||||
|
||||
# 添加到 favoriteAgents
|
||||
if is_favorite:
|
||||
agents_data['favoriteAgents'].append(agent_id)
|
||||
|
||||
conn.close()
|
||||
return jsonify(agents_data)
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>', methods=['POST'])
|
||||
def add_user_agent(user_id, agent_id):
|
||||
"""添加智能体到用户列表"""
|
||||
data = request.json
|
||||
category = data.get('category', 'basic')
|
||||
is_pinned = data.get('is_pinned', 0)
|
||||
is_favorite = data.get('is_favorite', 0)
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO user_agents (user_id, agent_id, category, is_pinned, is_favorite)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
''', (user_id, agent_id, category, is_pinned, is_favorite))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
except:
|
||||
# 已存在,更新
|
||||
cursor.execute('''
|
||||
UPDATE user_agents SET category=?, is_pinned=?, is_favorite=?
|
||||
WHERE user_id=? AND agent_id=?
|
||||
''', (category, is_pinned, is_favorite, user_id, agent_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>', methods=['DELETE'])
|
||||
def remove_user_agent(user_id, agent_id):
|
||||
"""从用户列表移除智能体"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('DELETE FROM user_agents WHERE user_id=? AND agent_id=?', (user_id, agent_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>/pin', methods=['POST'])
|
||||
def toggle_user_agent_pin(user_id, agent_id):
|
||||
"""切换智能体置顶状态"""
|
||||
data = request.json
|
||||
is_pinned = data.get('is_pinned', 1)
|
||||
category = data.get('category', 'basic')
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 检查是否存在
|
||||
cursor.execute('SELECT id FROM user_agents WHERE user_id=? AND agent_id=?', (user_id, agent_id))
|
||||
if cursor.fetchone():
|
||||
cursor.execute('UPDATE user_agents SET is_pinned=? WHERE user_id=? AND agent_id=?',
|
||||
(is_pinned, user_id, agent_id))
|
||||
else:
|
||||
cursor.execute('INSERT INTO user_agents (user_id, agent_id, category, is_pinned) VALUES (?, ?, ?, ?)',
|
||||
(user_id, agent_id, category, is_pinned))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>/favorite', methods=['POST'])
|
||||
def toggle_user_agent_favorite(user_id, agent_id):
|
||||
"""切换智能体收藏状态"""
|
||||
data = request.json
|
||||
is_favorite = data.get('is_favorite', 1)
|
||||
category = data.get('category', 'basic')
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 检查是否存在
|
||||
cursor.execute('SELECT id FROM user_agents WHERE user_id=? AND agent_id=?', (user_id, agent_id))
|
||||
if cursor.fetchone():
|
||||
cursor.execute('UPDATE user_agents SET is_favorite=? WHERE user_id=? AND agent_id=?',
|
||||
(is_favorite, user_id, agent_id))
|
||||
else:
|
||||
cursor.execute('INSERT INTO user_agents (user_id, agent_id, category, is_favorite) VALUES (?, ?, ?, ?)',
|
||||
(user_id, agent_id, category, is_favorite))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 大模型接口管理 ====================
|
||||
|
||||
@app.route('/api/admin/llm', methods=['GET'])
|
||||
|
||||
145
www/admin.js
145
www/admin.js
@@ -250,6 +250,7 @@ async function loadUsersPage(content) {
|
||||
<td>
|
||||
<div class="action-btns">
|
||||
<button class="action-btn edit" onclick="showEditUserModal(${u.id})">编辑</button>
|
||||
<button class="action-btn" style="background: #8b5cf6; color: white;" onclick="showUserConversations(${u.id}, '${u.username}')">查看对话</button>
|
||||
<button class="action-btn" style="background: #f59e0b; color: white;" onclick="showResetPasswordModal(${u.id})">重置密码</button>
|
||||
<button class="action-btn delete" onclick="deleteUser(${u.id})">删除</button>
|
||||
</div>
|
||||
@@ -396,6 +397,150 @@ async function deleteUser(id) {
|
||||
loadPage('users');
|
||||
}
|
||||
|
||||
// ==================== 查看用户对话记录 ====================
|
||||
|
||||
async function showUserConversations(userId, username) {
|
||||
// 加载用户对话列表
|
||||
const conversations = await fetchAPI(`/api/user/${userId}/conversations`);
|
||||
|
||||
const content = document.getElementById('mainContent');
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="content-header">
|
||||
<h1 class="content-title">用户对话记录 - ${username}</h1>
|
||||
<button class="add-btn" style="background: #718096;" onclick="loadPage('users')">返回用户列表</button>
|
||||
</div>
|
||||
|
||||
<div class="stats-grid" style="grid-template-columns: repeat(3, 1fr);">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">💬</div>
|
||||
<div class="stat-value">${conversations.length}</div>
|
||||
<div class="stat-label">对话总数</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">🤖</div>
|
||||
<div class="stat-value">${conversations.filter(c => c.agentId).length}</div>
|
||||
<div class="stat-label">智能体对话</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">📝</div>
|
||||
<div class="stat-value">${conversations.reduce((sum, c) => sum + (c.messages?.length || 0), 0)}</div>
|
||||
<div class="stat-label">消息总数</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="data-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>标题</th>
|
||||
<th>智能体</th>
|
||||
<th>消息数</th>
|
||||
<th>创建时间</th>
|
||||
<th>更新时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${conversations.length === 0 ? '<tr><td colspan="7" style="text-align: center; color: #999;">暂无对话记录</td></tr>' :
|
||||
conversations.map(conv => `
|
||||
<tr>
|
||||
<td>${conv.id}</td>
|
||||
<td>${conv.title || '新对话'}</td>
|
||||
<td>${conv.agentId ? getAgentName(conv.agentId) : '普通对话'}</td>
|
||||
<td>${conv.messages?.length || 0}</td>
|
||||
<td>${formatDate(conv.createdAt || conv.created_at)}</td>
|
||||
<td>${formatDate(conv.updatedAt || conv.updated_at)}</td>
|
||||
<td>
|
||||
<div class="action-btns">
|
||||
<button class="action-btn edit" onclick="showConversationMessages(${userId}, ${conv.id}, '${conv.title || '新对话'}')">查看详情</button>
|
||||
<button class="action-btn delete" onclick="deleteUserConversation(${userId}, ${conv.id})">删除</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function getAgentName(agentId) {
|
||||
const agent = agents.find(a => a.agent_id === agentId);
|
||||
return agent ? `${agent.avatar} ${agent.name}` : agentId;
|
||||
}
|
||||
|
||||
async function showConversationMessages(userId, convId, title) {
|
||||
// 获取对话详情
|
||||
const conv = await fetchAPI(`/api/user/${userId}/conversations/${convId}`);
|
||||
|
||||
const content = document.getElementById('mainContent');
|
||||
|
||||
const messages = conv.messages || [];
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="content-header">
|
||||
<h1 class="content-title">对话详情 - ${title}</h1>
|
||||
<button class="add-btn" style="background: #718096;" onclick="showUserConversations(${userId}, '用户')">返回对话列表</button>
|
||||
</div>
|
||||
|
||||
<div style="background: white; padding: 16px; border-radius: 12px; margin-bottom: 16px;">
|
||||
<div style="display: flex; gap: 16px; color: #718096;">
|
||||
<span>💬 消息数: ${messages.length}</span>
|
||||
<span>🤖 智能体: ${conv.agentId ? getAgentName(conv.agentId) : '普通对话'}</span>
|
||||
<span>📅 创建: ${formatDate(conv.createdAt || conv.created_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="data-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 60px;">序号</th>
|
||||
<th style="width: 80px;">角色</th>
|
||||
<th>内容</th>
|
||||
<th style="width: 150px;">时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${messages.length === 0 ? '<tr><td colspan="4" style="text-align: center; color: #999;">暂无消息</td></tr>' :
|
||||
messages.map((msg, idx) => `
|
||||
<tr>
|
||||
<td>${idx + 1}</td>
|
||||
<td style="color: ${msg.role === 'user' ? '#3b82f6' : '#10b981'};">
|
||||
${msg.role === 'user' ? '👤 用户' : '🤖 AI'}
|
||||
</td>
|
||||
<td style="max-width: 500px; white-space: pre-wrap; word-break: break-all;">
|
||||
${escapeHtml(msg.content?.slice(0, 500) || '')}${msg.content?.length > 500 ? '...' : ''}
|
||||
${msg.thinking ? `<div style="color: #f59e0b; margin-top: 8px; font-size: 12px;">💭 思考: ${escapeHtml(msg.thinking?.slice(0, 200) || '')}...</div>` : ''}
|
||||
</td>
|
||||
<td>${formatDate(msg.timestamp || msg.createdAt)}</td>
|
||||
</tr>
|
||||
`).join('')
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function deleteUserConversation(userId, convId) {
|
||||
if (!confirm('确定删除此对话?此操作不可恢复!')) return;
|
||||
|
||||
await fetchAPI(`/api/user/${userId}/conversations/${convId}`, 'DELETE');
|
||||
showToast('删除成功');
|
||||
showUserConversations(userId, '用户');
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// ==================== 大模型配置页面 ====================
|
||||
|
||||
async function loadLLMPage(content) {
|
||||
|
||||
447
www/app.js
447
www/app.js
@@ -294,14 +294,47 @@ let thinkingBtn = null;
|
||||
let searchBtn = null;
|
||||
|
||||
// 初始化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
// 初始化 appContainer
|
||||
appContainer = document.getElementById('app');
|
||||
|
||||
// 从本地存储加载对话列表
|
||||
const saved = localStorage.getItem('conversations');
|
||||
if (saved) {
|
||||
conversations = JSON.parse(saved);
|
||||
// 加载用户登录状态(优先检查)
|
||||
const savedUser = localStorage.getItem('currentUser');
|
||||
if (savedUser) {
|
||||
currentUser = JSON.parse(savedUser);
|
||||
}
|
||||
|
||||
// 如果用户已登录且有ID,从 backend 加载对话数据
|
||||
if (currentUser && currentUser.id) {
|
||||
try {
|
||||
const res = await fetch(`/api/user/${currentUser.id}/conversations`);
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
// 使用 backend 数据替换本地数据
|
||||
conversations = data;
|
||||
// 更新本地存储(离线可用)
|
||||
localStorage.setItem('conversations', JSON.stringify(conversations));
|
||||
} else {
|
||||
// backend 无数据,使用本地数据
|
||||
const saved = localStorage.getItem('conversations');
|
||||
if (saved) {
|
||||
conversations = JSON.parse(saved);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// backend 加载失败,使用本地数据
|
||||
console.error('加载 backend 对话失败:', e);
|
||||
const saved = localStorage.getItem('conversations');
|
||||
if (saved) {
|
||||
conversations = JSON.parse(saved);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 未登录用户,从本地存储加载对话列表
|
||||
const saved = localStorage.getItem('conversations');
|
||||
if (saved) {
|
||||
conversations = JSON.parse(saved);
|
||||
}
|
||||
}
|
||||
|
||||
// 兼容旧数据格式(chat_history)
|
||||
@@ -323,7 +356,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 加载用户智能体数据
|
||||
// 加载用户智能体数据(我的智能体)
|
||||
const savedMyAgents = localStorage.getItem('myAgents');
|
||||
if (savedMyAgents) {
|
||||
myAgents = JSON.parse(savedMyAgents);
|
||||
@@ -341,10 +374,26 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
pinnedAgents = JSON.parse(savedPinnedAgents);
|
||||
}
|
||||
|
||||
// 加载用户登录状态
|
||||
const savedUser = localStorage.getItem('currentUser');
|
||||
if (savedUser) {
|
||||
currentUser = JSON.parse(savedUser);
|
||||
// 如果用户已登录且有ID,从 backend 加载智能体配置
|
||||
if (currentUser && currentUser.id) {
|
||||
try {
|
||||
const res = await fetch(`/api/user/${currentUser.id}/agents`);
|
||||
const data = await res.json();
|
||||
if (data.myAgents) {
|
||||
myAgents = data.myAgents;
|
||||
localStorage.setItem('myAgents', JSON.stringify(myAgents));
|
||||
}
|
||||
if (data.favoriteAgents) {
|
||||
favoriteAgents = data.favoriteAgents;
|
||||
localStorage.setItem('favoriteAgents', JSON.stringify(favoriteAgents));
|
||||
}
|
||||
if (data.pinnedAgents) {
|
||||
pinnedAgents = data.pinnedAgents;
|
||||
localStorage.setItem('pinnedAgents', JSON.stringify(pinnedAgents));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('加载智能体配置失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// 加载每日使用统计
|
||||
@@ -1001,10 +1050,12 @@ function toggleAgentPin(agentId) {
|
||||
|
||||
const category = agent.category;
|
||||
|
||||
let is_pinned;
|
||||
if (pinnedAgents[category]?.includes(agentId)) {
|
||||
// 取消置顶
|
||||
pinnedAgents[category] = pinnedAgents[category].filter(id => id !== agentId);
|
||||
agent.is_pinned = false;
|
||||
is_pinned = 0;
|
||||
showToast('已取消置顶');
|
||||
} else {
|
||||
// 置顶
|
||||
@@ -1013,11 +1064,21 @@ function toggleAgentPin(agentId) {
|
||||
}
|
||||
pinnedAgents[category].push(agentId);
|
||||
agent.is_pinned = true;
|
||||
is_pinned = 1;
|
||||
showToast('已置顶');
|
||||
}
|
||||
|
||||
savePinnedAgents();
|
||||
saveMyAgents(); // 更新显示
|
||||
|
||||
// 同步到 backend
|
||||
if (currentUser && currentUser.id) {
|
||||
fetch(`/api/user/${currentUser.id}/agents/${agentId}/pin`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ is_pinned, category })
|
||||
}).catch(e => console.error('同步置顶失败:', e));
|
||||
}
|
||||
}
|
||||
|
||||
// 收藏/取消收藏智能体
|
||||
@@ -1025,20 +1086,32 @@ function toggleAgentFavorite(agentId) {
|
||||
const agent = agents.find(a => a.id === agentId);
|
||||
if (!agent) return;
|
||||
|
||||
let is_favorite;
|
||||
if (favoriteAgents.includes(agentId)) {
|
||||
// 取消收藏
|
||||
favoriteAgents = favoriteAgents.filter(id => id !== agentId);
|
||||
agent.is_favorite = false;
|
||||
is_favorite = 0;
|
||||
showToast('已取消收藏');
|
||||
} else {
|
||||
// 收藏
|
||||
favoriteAgents.push(agentId);
|
||||
agent.is_favorite = true;
|
||||
is_favorite = 1;
|
||||
showToast('已收藏');
|
||||
}
|
||||
|
||||
saveFavoriteAgents();
|
||||
saveMyAgents(); // 更新显示
|
||||
|
||||
// 同步到 backend
|
||||
if (currentUser && currentUser.id) {
|
||||
fetch(`/api/user/${currentUser.id}/agents/${agentId}/favorite`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ is_favorite, category: agent.category })
|
||||
}).catch(e => console.error('同步收藏失败:', e));
|
||||
}
|
||||
}
|
||||
|
||||
// 从用户智能体列表移除
|
||||
@@ -1067,6 +1140,13 @@ function removeAgentFromMyAgents(agentId) {
|
||||
savePinnedAgents();
|
||||
saveFavoriteAgents();
|
||||
showToast('已移除');
|
||||
|
||||
// 同步到 backend
|
||||
if (currentUser && currentUser.id) {
|
||||
fetch(`/api/user/${currentUser.id}/agents/${agentId}`, {
|
||||
method: 'DELETE'
|
||||
}).catch(e => console.error('同步移除失败:', e));
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 智能体发现页面 ====================
|
||||
@@ -1303,6 +1383,15 @@ function addAgentToMyAgents(agentId) {
|
||||
|
||||
saveMyAgents();
|
||||
showToast(`已添加 ${agent.name}`);
|
||||
|
||||
// 同步到 backend
|
||||
if (currentUser && currentUser.id) {
|
||||
fetch(`/api/user/${currentUser.id}/agents/${agentId}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ category: agent.category })
|
||||
}).catch(e => console.error('同步添加智能体失败:', e));
|
||||
}
|
||||
}
|
||||
|
||||
// 从发现页面收藏智能体
|
||||
@@ -1620,14 +1709,43 @@ function showEditProfilePage() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取完整用户信息
|
||||
const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
|
||||
const fullUser = users.find(u => u.username === currentUser.username);
|
||||
|
||||
// 如果用户已登录且有ID,从 backend 获取完整用户信息
|
||||
if (currentUser.id) {
|
||||
fetch(`/api/admin/users/${currentUser.id}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data && data.id) {
|
||||
// 更新 currentUser 的完整信息
|
||||
currentUser.avatar = data.avatar || '👤';
|
||||
currentUser.signature = data.signature || '';
|
||||
currentUser.email = data.email || '';
|
||||
currentUser.gender = data.gender || '';
|
||||
currentUser.age = data.age || '';
|
||||
currentUser.region = data.region || '';
|
||||
currentUser.phone = data.phone || '';
|
||||
|
||||
// 渲染编辑页面
|
||||
renderEditProfilePage();
|
||||
} else {
|
||||
// 使用本地数据
|
||||
renderEditProfilePage();
|
||||
}
|
||||
})
|
||||
.catch(e => {
|
||||
// 使用本地数据
|
||||
renderEditProfilePage();
|
||||
});
|
||||
} else {
|
||||
// 游客用户,使用本地数据
|
||||
renderEditProfilePage();
|
||||
}
|
||||
}
|
||||
|
||||
function renderEditProfilePage() {
|
||||
const avatar = currentUser.avatar || '👤';
|
||||
const signature = currentUser.signature || '';
|
||||
const phone = fullUser?.phone || '';
|
||||
const email = fullUser?.email || '';
|
||||
const phone = currentUser.phone || '';
|
||||
const email = currentUser.email || '';
|
||||
const gender = currentUser.gender || '';
|
||||
const age = currentUser.age || '';
|
||||
const region = currentUser.region || '';
|
||||
@@ -1773,26 +1891,6 @@ function handleSaveProfile() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查用户名是否被其他人占用
|
||||
const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
|
||||
if (newUsername !== currentUser.username) {
|
||||
if (users.find(u => u.username === newUsername)) {
|
||||
showToast('用户名已被占用');
|
||||
return;
|
||||
}
|
||||
// 更新用户名
|
||||
const userIndex = users.findIndex(u => u.username === currentUser.username);
|
||||
if (userIndex >= 0) {
|
||||
users[userIndex].username = newUsername;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新邮箱
|
||||
const userIndex = users.findIndex(u => u.username === currentUser.username);
|
||||
if (userIndex >= 0) {
|
||||
users[userIndex].email = newEmail;
|
||||
}
|
||||
|
||||
// 更新 currentUser
|
||||
currentUser.avatar = newAvatar;
|
||||
currentUser.username = newUsername;
|
||||
@@ -1800,12 +1898,42 @@ function handleSaveProfile() {
|
||||
currentUser.gender = newGender;
|
||||
currentUser.age = newAge ? parseInt(newAge) : '';
|
||||
currentUser.region = newRegion;
|
||||
currentUser.email = newEmail;
|
||||
|
||||
saveCurrentUser();
|
||||
localStorage.setItem('registeredUsers', JSON.stringify(users));
|
||||
|
||||
showToast('保存成功');
|
||||
switchPage('profile');
|
||||
// 如果用户已登录,调用 backend API 更新
|
||||
if (currentUser.id) {
|
||||
fetch(`/api/user/${currentUser.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: newUsername,
|
||||
email: newEmail,
|
||||
avatar: newAvatar,
|
||||
signature: newSignature,
|
||||
gender: newGender,
|
||||
age: newAge ? parseInt(newAge) : null,
|
||||
region: newRegion
|
||||
})
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
saveCurrentUser();
|
||||
showToast('保存成功');
|
||||
switchPage('profile');
|
||||
} else {
|
||||
showToast(data.error || '保存失败');
|
||||
}
|
||||
})
|
||||
.catch(e => {
|
||||
showToast('网络错误,请重试');
|
||||
});
|
||||
} else {
|
||||
// 未登录用户,保存到本地
|
||||
saveCurrentUser();
|
||||
showToast('保存成功');
|
||||
switchPage('profile');
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 消息通知页面 ====================
|
||||
@@ -2463,11 +2591,18 @@ function handleLogin() {
|
||||
email: data.user.email || '',
|
||||
avatar: data.user.avatar || '👤',
|
||||
signature: data.user.signature || '',
|
||||
gender: data.user.gender || '',
|
||||
age: data.user.age || '',
|
||||
region: data.user.region || '',
|
||||
registeredAt: Date.now()
|
||||
};
|
||||
saveCurrentUser();
|
||||
showToast('登录成功');
|
||||
showMainPage();
|
||||
|
||||
// 从 backend 加载用户对话数据
|
||||
loadUserConversations().then(() => {
|
||||
showToast('登录成功');
|
||||
showMainPage();
|
||||
});
|
||||
} else {
|
||||
showToast(data.error || '用户名或密码错误');
|
||||
}
|
||||
@@ -2499,15 +2634,6 @@ function showRegisterPage() {
|
||||
<label>手机号 <span class="required">*</span></label>
|
||||
<input type="tel" id="registerPhone" placeholder="请输入手机号" maxlength="11" autocomplete="tel">
|
||||
</div>
|
||||
<div class="auth-input-group" style="display: flex; gap: 8px;">
|
||||
<div style="flex: 1;">
|
||||
<label>验证码 <span class="required">*</span></label>
|
||||
<input type="text" id="registerCode" placeholder="请输入验证码" maxlength="6">
|
||||
</div>
|
||||
<div style="flex-shrink: 0; align-self: flex-end;">
|
||||
<button class="send-code-btn" id="getCodeBtn">获取验证码</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-input-group">
|
||||
<label>邮箱 <span class="optional">(可选)</span></label>
|
||||
<input type="email" id="registerEmail" placeholder="请输入邮箱(可选)" autocomplete="email">
|
||||
@@ -2552,12 +2678,6 @@ function showRegisterPage() {
|
||||
});
|
||||
}
|
||||
|
||||
// 获取验证码按钮
|
||||
const getCodeBtn = document.getElementById('getCodeBtn');
|
||||
if (getCodeBtn) {
|
||||
getCodeBtn.addEventListener('click', handleGetCode);
|
||||
}
|
||||
|
||||
// 回车注册
|
||||
document.getElementById('registerPasswordConfirm')?.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') handleRegister();
|
||||
@@ -2570,50 +2690,6 @@ function showRegisterPage() {
|
||||
e.target.value = e.target.value.replace(/\D/g, '');
|
||||
});
|
||||
}
|
||||
|
||||
// 验证码输入限制(只允许数字)
|
||||
const codeInput = document.getElementById('registerCode');
|
||||
if (codeInput) {
|
||||
codeInput.addEventListener('input', (e) => {
|
||||
e.target.value = e.target.value.replace(/\D/g, '');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 获取验证码(模拟)
|
||||
let verifyCode = '';
|
||||
let codeExpireTime = 0;
|
||||
|
||||
function handleGetCode() {
|
||||
const phone = document.getElementById('registerPhone')?.value.trim();
|
||||
|
||||
if (!validatePhone(phone)) {
|
||||
showToast('请先输入正确的手机号');
|
||||
return;
|
||||
}
|
||||
|
||||
// 生成6位随机验证码
|
||||
verifyCode = Math.floor(100000 + Math.random() * 900000).toString();
|
||||
codeExpireTime = Date.now() + 5 * 60 * 1000; // 5分钟有效
|
||||
|
||||
// 模拟发送(实际项目中应调用短信API)
|
||||
showToast(`验证码已发送: ${verifyCode}(演示)`);
|
||||
|
||||
// 60秒倒计时
|
||||
const getCodeBtn = document.getElementById('getCodeBtn');
|
||||
if (getCodeBtn) {
|
||||
getCodeBtn.disabled = true;
|
||||
let countdown = 60;
|
||||
const timer = setInterval(() => {
|
||||
getCodeBtn.textContent = `${countdown}s`;
|
||||
countdown--;
|
||||
if (countdown <= 0) {
|
||||
clearInterval(timer);
|
||||
getCodeBtn.disabled = false;
|
||||
getCodeBtn.textContent = '获取验证码';
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
// 验证手机号格式
|
||||
@@ -2634,7 +2710,6 @@ function handleRegister() {
|
||||
const username = document.getElementById('registerUsername')?.value.trim();
|
||||
const phone = document.getElementById('registerPhone')?.value.trim();
|
||||
const email = document.getElementById('registerEmail')?.value.trim();
|
||||
const code = document.getElementById('registerCode')?.value.trim();
|
||||
const password = document.getElementById('registerPassword')?.value;
|
||||
const passwordConfirm = document.getElementById('registerPasswordConfirm')?.value;
|
||||
|
||||
@@ -2650,18 +2725,6 @@ function handleRegister() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证验证码
|
||||
if (!code || code.length !== 6) {
|
||||
showToast('请输入6位验证码');
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查验证码是否正确(模拟)
|
||||
if (code !== verifyCode || Date.now() > codeExpireTime) {
|
||||
showToast('验证码不正确或已过期');
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证邮箱(可选)
|
||||
if (email && !validateEmail(email)) {
|
||||
showToast('请输入正确的邮箱格式');
|
||||
@@ -2679,7 +2742,9 @@ function handleRegister() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 调用后台注册API
|
||||
// 调用后台注册API(验证码暂时跳过,传随机值)
|
||||
const code = Math.floor(100000 + Math.random() * 900000).toString();
|
||||
|
||||
fetch('/api/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -2703,8 +2768,12 @@ function handleRegister() {
|
||||
registeredAt: Date.now()
|
||||
};
|
||||
saveCurrentUser();
|
||||
showToast('注册成功');
|
||||
showMainPage();
|
||||
|
||||
// 加载对话数据(新用户为空)
|
||||
loadUserConversations().then(() => {
|
||||
showToast('注册成功');
|
||||
showMainPage();
|
||||
});
|
||||
} else {
|
||||
showToast(data.error || '注册失败');
|
||||
}
|
||||
@@ -2846,7 +2915,7 @@ function showAgentHistoryPage() {
|
||||
}
|
||||
|
||||
// 打开智能体对话
|
||||
function openAgent(agentId) {
|
||||
async function openAgent(agentId) {
|
||||
currentAgent = systemAgents.find(a => a.id === agentId);
|
||||
if (!currentAgent) return;
|
||||
|
||||
@@ -2867,9 +2936,31 @@ function openAgent(agentId) {
|
||||
setAgentUsed(agentId);
|
||||
}
|
||||
|
||||
// 如果用户已登录,先在 backend 创建对话
|
||||
let backendId = null;
|
||||
if (currentUser && currentUser.id) {
|
||||
try {
|
||||
const res = await fetch(`/api/user/${currentUser.id}/conversations`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: currentAgent.name,
|
||||
messages: [],
|
||||
agentId: agentId
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success && data.id) {
|
||||
backendId = data.id;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('创建智能体对话失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新对话并设置智能体
|
||||
const newConv = {
|
||||
id: Date.now().toString(),
|
||||
id: backendId || Date.now().toString(),
|
||||
title: currentAgent.name,
|
||||
messages: [],
|
||||
agentId: agentId,
|
||||
@@ -3320,15 +3411,33 @@ function togglePinConversation(convId) {
|
||||
}
|
||||
|
||||
// 创建新对话
|
||||
function createNewConversation() {
|
||||
async function createNewConversation() {
|
||||
// 检查未登录用户的对话限制
|
||||
if (!currentUser && !canCreateNewChat()) {
|
||||
showLimitDialog('chat_session');
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果用户已登录,先在 backend 创建对话
|
||||
let backendId = null;
|
||||
if (currentUser && currentUser.id) {
|
||||
try {
|
||||
const res = await fetch(`/api/user/${currentUser.id}/conversations`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '新对话', messages: [] })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success && data.id) {
|
||||
backendId = data.id;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('创建对话失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
const newConv = {
|
||||
id: Date.now().toString(),
|
||||
id: backendId || Date.now().toString(), // 使用 backend ID 或本地 ID
|
||||
title: '新对话',
|
||||
messages: [],
|
||||
createdAt: Date.now(),
|
||||
@@ -3566,6 +3675,17 @@ function deleteConversation(id) {
|
||||
|
||||
conversations = conversations.filter(c => c.id !== id);
|
||||
saveConversations();
|
||||
|
||||
// 如果用户已登录,从 backend 删除
|
||||
if (currentUser && currentUser.id) {
|
||||
const convId = parseInt(id);
|
||||
if (convId > 0) {
|
||||
fetch(`/api/user/${currentUser.id}/conversations/${convId}`, {
|
||||
method: 'DELETE'
|
||||
}).catch(e => console.error('删除对话失败:', e));
|
||||
}
|
||||
}
|
||||
|
||||
showConversationList();
|
||||
}
|
||||
|
||||
@@ -3634,6 +3754,9 @@ async function sendMessage() {
|
||||
currentConversation.updatedAt = Date.now();
|
||||
saveConversations();
|
||||
|
||||
// 同步当前对话到 backend(用户已登录)
|
||||
syncConversationToBackend(currentConversation);
|
||||
|
||||
// 增加消息计数(未登录用户)
|
||||
if (!currentUser) {
|
||||
if (currentConversation.agentId) {
|
||||
@@ -3754,6 +3877,7 @@ async function streamGenerate(userMsgIndex) {
|
||||
contentEl.innerHTML = renderMarkdown(currentConversation.messages[aiMessageIndex].content);
|
||||
currentConversation.updatedAt = Date.now();
|
||||
saveConversations();
|
||||
syncConversationToBackend(currentConversation);
|
||||
renderMessages();
|
||||
};
|
||||
}
|
||||
@@ -3830,6 +3954,7 @@ async function streamGenerate(userMsgIndex) {
|
||||
hideStopGenerateBtn();
|
||||
currentConversation.updatedAt = Date.now();
|
||||
saveConversations();
|
||||
syncConversationToBackend(currentConversation);
|
||||
renderMessages();
|
||||
|
||||
// 自动总结标题:第一次对话和每隔5次对话
|
||||
@@ -4236,9 +4361,87 @@ function setupScrollListener() {
|
||||
|
||||
// 保存对话列表
|
||||
function saveConversations() {
|
||||
// 保存到本地存储(离线可用)
|
||||
localStorage.setItem('conversations', JSON.stringify(conversations));
|
||||
}
|
||||
|
||||
// 同步单个对话到 backend(新创建或更新)
|
||||
async function syncConversationToBackend(conv) {
|
||||
if (!currentUser || !currentUser.id) return;
|
||||
|
||||
const convId = parseInt(conv.id);
|
||||
|
||||
try {
|
||||
if (convId > 0 && convId < 1e12) {
|
||||
// 已有 backend ID,更新对话
|
||||
await fetch(`/api/user/${currentUser.id}/conversations/${convId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: conv.title,
|
||||
messages: conv.messages,
|
||||
agentId: conv.agentId
|
||||
})
|
||||
});
|
||||
} else {
|
||||
// 新对话(本地 ID 是时间戳),创建
|
||||
const res = await fetch(`/api/user/${currentUser.id}/conversations`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: conv.title,
|
||||
messages: conv.messages,
|
||||
agentId: conv.agentId
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success && data.id) {
|
||||
// 更新本地 ID 为 backend ID
|
||||
conv.id = data.id;
|
||||
// 更新 localStorage
|
||||
localStorage.setItem('conversations', JSON.stringify(conversations));
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('同步对话失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// 从 backend 加载用户对话数据
|
||||
async function loadUserConversations() {
|
||||
if (!currentUser || !currentUser.id) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/user/${currentUser.id}/conversations`);
|
||||
const data = await res.json();
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
// 合并本地和云端数据(云端优先)
|
||||
const localConvIds = conversations.map(c => c.id);
|
||||
|
||||
for (const cloudConv of data) {
|
||||
const localIdx = localConvIds.indexOf(cloudConv.id);
|
||||
if (localIdx >= 0) {
|
||||
// 更新本地对话(云端数据优先)
|
||||
conversations[localIdx] = cloudConv;
|
||||
} else {
|
||||
// 添加云端对话
|
||||
conversations.push(cloudConv);
|
||||
}
|
||||
}
|
||||
|
||||
// 按更新时间排序
|
||||
conversations.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
|
||||
// 保存到本地
|
||||
localStorage.setItem('conversations', JSON.stringify(conversations));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('加载对话失败:', e);
|
||||
// 使用本地数据
|
||||
}
|
||||
}
|
||||
|
||||
// 显示提示
|
||||
function showToast(message) {
|
||||
const toast = document.createElement('div');
|
||||
|
||||
Reference in New Issue
Block a user