const SessionManager = { sessions: [], currentSessionId: null, async loadSessions() { try { const res = await api.get('/sessions'); this.sessions = res.data || []; this.renderSessionList(); } catch (err) { console.error('加载会话失败:', err); } }, renderSessionList() { const list = document.getElementById('sessionList'); if (!list) return; list.innerHTML = this.sessions.map(s => `
${this.escapeHtml(s.name)}
`).join(''); }, async createSession() { try { const res = await api.post('/sessions', {}); this.sessions.unshift(res.data); this.currentSessionId = res.data.id; this.renderSessionList(); ChatManager.clearMessages(); return res.data; } catch (err) { console.error('创建会话失败:', err); } }, async switchSession(id) { this.currentSessionId = id; this.renderSessionList(); await ChatManager.loadMessages(id); }, async deleteSession(id) { if (!confirm('确定要删除这个会话吗?')) return; try { await api.delete('/sessions/' + id); this.sessions = this.sessions.filter(s => s.id !== id); Storage.clearCachedMessages(id); if (this.currentSessionId === id) { this.currentSessionId = null; ChatManager.clearMessages(); if (this.sessions.length > 0) { await this.switchSession(this.sessions[0].id); } } this.renderSessionList(); } catch (err) { alert('删除会话失败: ' + err.message); } }, escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } };