import { sessionId, setSessionId, setCurrentPersona, currentPersona, dom } from './state.js'; import { clearMessages, addMessage, initChat } from './chat.js'; import { highlightPersona } from './personas.js'; function escapeTitle(t) { const d = document.createElement('div'); d.textContent = t; return d.innerHTML; } export async function loadSessions() { const res = await fetch('/sessions/'); const sessions = await res.json(); dom.sessionList.innerHTML = ''; sessions.forEach(s => { const item = document.createElement('div'); item.className = 'session-item' + (s.session_id === sessionId ? ' active' : ''); item.innerHTML = `
${escapeTitle(s.title || 'Новый чат')}
${s.message_count} сообщ.
`; item.addEventListener('click', () => switchSession(s.session_id)); item.querySelector('.s-del').addEventListener('click', async (e) => { e.stopPropagation(); await fetch(`/sessions/${s.session_id}`, { method: 'DELETE' }); if (s.session_id === sessionId) createNewChat(); else loadSessions(); }); dom.sessionList.appendChild(item); }); } export async function switchSession(id) { setSessionId(id); clearMessages(); await loadSessions(); await loadChatHistory(id); } export async function loadChatHistory(id) { const sessionRes = await fetch(`/sessions/${id}`); if (sessionRes.ok) { const s = await sessionRes.json(); dom.headerTitle.textContent = s.title || 'Новый чат'; if (s.persona_id) { setCurrentPersona(s.persona_id); highlightPersona(s.persona_id); } } const histRes = await fetch(`/chat/history/${id}`); if (!histRes.ok) return; const messages = await histRes.json(); clearMessages(); messages.filter(m => m.role !== 'system').forEach(m => { addMessage( m.role === 'user' ? 'user' : 'assistant', m.content, m.image_prompt, m.image_path ? `/static/${m.image_path}` : null, ); }); } export async function createNewChat() { setSessionId('sess_' + Math.random().toString(36).slice(2, 10)); clearMessages(); dom.headerTitle.textContent = 'Новый чат'; highlightPersona(currentPersona); await initChat(); loadSessions(); } export async function initSessions() { await loadSessions(); if (sessionId) { const check = await fetch(`/sessions/${sessionId}`); if (check.ok) await switchSession(sessionId); else createNewChat(); } else { createNewChat(); } }