first commit

This commit is contained in:
Grigo
2026-05-28 08:42:46 +03:00
commit e5c0df308f
38 changed files with 2753 additions and 0 deletions
+306
View File
@@ -0,0 +1,306 @@
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #1a1a2e;
color: #e0e0e0;
font-family: 'Segoe UI', sans-serif;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
header {
width: 100%;
padding: 12px 20px;
background: #16213e;
border-bottom: 1px solid #0f3460;
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
z-index: 10;
}
header h1 { font-size: 1.1rem; color: #e94560; }
#sidebarToggle {
background: none;
border: 1px solid #0f3460;
border-radius: 8px;
color: #888;
padding: 4px 10px;
cursor: pointer;
font-size: 1rem;
transition: all 0.2s;
}
#sidebarToggle:hover { border-color: #e94560; color: #e94560; }
.header-title {
flex: 1;
font-size: 0.9rem;
color: #ccc;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.app-body { display: flex; flex: 1; overflow: hidden; }
.sidebar {
width: 260px;
background: #16213e;
border-right: 1px solid #0f3460;
display: flex;
flex-direction: column;
flex-shrink: 0;
transition: width 0.25s ease, opacity 0.25s ease;
overflow: hidden;
}
.sidebar.collapsed { width: 0; opacity: 0; pointer-events: none; }
.sidebar-header {
padding: 12px 14px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #0f3460;
}
.sidebar-header span {
font-size: 0.8rem;
color: #888;
text-transform: uppercase;
letter-spacing: 0.05em;
}
#newChatBtn {
background: #e94560;
border: none;
border-radius: 8px;
color: white;
padding: 5px 12px;
font-size: 0.8rem;
cursor: pointer;
}
#newChatBtn:hover { background: #c73652; }
.session-list { flex: 1; overflow-y: auto; padding: 8px 0; }
.session-item {
display: flex;
align-items: center;
gap: 8px;
padding: 9px 14px;
cursor: pointer;
border-left: 3px solid transparent;
}
.session-item:hover { background: #1a1a2e; }
.session-item.active { background: #1a1a2e; border-left-color: #e94560; }
.session-item .s-title { flex: 1; font-size: 0.82rem; color: #ccc; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.session-item .s-meta { font-size: 0.7rem; color: #555; }
.session-item .s-del { background: none; border: none; color: #555; cursor: pointer; opacity: 0; }
.session-item:hover .s-del { opacity: 1; }
.session-item .s-del:hover { color: #e94560; }
.main { flex: 1; display: flex; flex-direction: column; overflow: hidden; }
.persona-bar {
display: flex;
gap: 8px;
padding: 8px 16px;
overflow-x: auto;
border-bottom: 1px solid #0f3460;
}
.persona-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding: 6px 12px;
background: #16213e;
border: 1px solid #0f3460;
border-radius: 10px;
cursor: pointer;
position: relative;
flex-shrink: 0;
}
.persona-card:hover { border-color: #e94560; }
.persona-card.active { border-color: #e94560; background: #1f1535; }
.persona-card .emoji { font-size: 1.2rem; }
.persona-card .pname { font-size: 0.7rem; color: #ccc; }
.persona-card .del-btn {
position: absolute; top: -5px; right: -5px;
width: 14px; height: 14px;
background: #e94560; border: none; border-radius: 50%;
color: white; font-size: 0.55rem; cursor: pointer;
display: none;
}
.persona-card .edit-btn {
position: absolute; top: -5px; left: -5px;
width: 16px; height: 16px;
background: #0f3460; border: 1px solid #e94560; border-radius: 50%;
color: white; font-size: 0.55rem; cursor: pointer;
display: none; align-items: center; justify-content: center;
}
.persona-card:hover .del-btn { display: flex; align-items: center; justify-content: center; }
.persona-card:hover .edit-btn { display: flex; }
.persona-add, .card-import-btn {
display: flex; flex-direction: column; align-items: center;
padding: 6px 12px;
background: transparent;
border: 1px dashed #0f3460; border-radius: 10px;
cursor: pointer; color: #555; font-size: 0.7rem;
flex-shrink: 0;
}
.persona-add:hover, .card-import-btn:hover { border-color: #e94560; color: #e94560; }
.messages {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px;
}
.message { display: flex; flex-direction: column; max-width: 75%; animation: fadeIn 0.2s ease; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
.message.user { align-self: flex-end; }
.message.assistant { align-self: flex-start; }
.bubble {
padding: 10px 14px;
border-radius: 16px;
line-height: 1.5;
font-size: 0.95rem;
white-space: pre-wrap;
word-break: break-word;
}
.bubble.typing-active::after { content: '▋'; animation: blink 0.7s infinite; color: #e94560; }
@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
.message.user .bubble { background: #0f3460; border-bottom-right-radius: 4px; }
.message.assistant .bubble { background: #16213e; border: 1px solid #0f3460; border-bottom-left-radius: 4px; }
.label { font-size: 0.7rem; color: #888; margin-bottom: 4px; padding: 0 4px; }
.message.user .label { text-align: right; }
.image-prompt-block {
margin-top: 8px; padding: 8px 12px;
background: #1a1a2e;
border: 1px dashed #e94560;
border-radius: 8px;
font-size: 0.8rem; color: #e94560;
}
.image-prompt-header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.image-prompt-block .prompt-text { display: block; color: #aaa; margin-top: 4px; font-style: italic; white-space: pre-wrap; }
.copy-prompt-btn, .gen-image-btn {
background: #0f3460;
border: 1px solid #e94560;
border-radius: 6px;
color: #e94560;
font-size: 0.7rem;
padding: 2px 8px;
cursor: pointer;
}
.copy-prompt-btn:hover, .gen-image-btn:hover { background: #e94560; color: white; }
.translate-btn {
align-self: flex-end;
background: #0f3460;
border: 1px solid #4a90d9;
border-radius: 6px;
color: #4a90d9;
font-size: 0.7rem;
padding: 2px 8px;
cursor: pointer;
margin-top: 4px;
}
.translate-btn:hover { background: #4a90d9; color: white; }
.translate-btn:disabled { opacity: 0.5; cursor: default; }
.chat-image { margin-top: 8px; max-width: 100%; border-radius: 8px; border: 1px solid #0f3460; }
.image-error { margin-top: 6px; font-size: 0.75rem; color: #888; }
.typing {
align-self: flex-start;
display: flex; gap: 4px;
padding: 12px 16px;
background: #16213e;
border: 1px solid #0f3460;
border-radius: 16px;
}
.typing span { width: 6px; height: 6px; background: #888; border-radius: 50%; animation: bounce 1.2s infinite; }
.typing span:nth-child(2) { animation-delay: 0.2s; }
.typing span:nth-child(3) { animation-delay: 0.4s; }
@keyframes bounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-6px); } }
.input-area {
display: flex; gap: 10px;
padding: 12px 16px;
border-top: 1px solid #0f3460;
}
textarea {
flex: 1;
background: #16213e;
border: 1px solid #0f3460;
border-radius: 12px;
color: #e0e0e0;
font-size: 0.95rem;
padding: 10px 14px;
resize: none; outline: none;
font-family: inherit;
max-height: 120px;
}
textarea:focus { border-color: #e94560; }
#sendBtn {
background: #e94560; border: none;
border-radius: 12px; color: white;
padding: 0 20px; cursor: pointer;
}
#sendBtn:disabled { background: #555; cursor: not-allowed; }
#clearBtn {
background: transparent;
border: 1px solid #0f3460;
border-radius: 12px; color: #888;
padding: 0 14px; cursor: pointer;
}
#clearBtn:hover { border-color: #e94560; color: #e94560; }
.modal-overlay {
display: none; position: fixed; inset: 0;
background: rgba(0,0,0,0.7);
z-index: 100; align-items: center; justify-content: center;
}
.modal-overlay.open { display: flex; }
.modal {
background: #16213e; border: 1px solid #0f3460;
border-radius: 16px; padding: 24px;
width: 100%; max-width: 440px;
display: flex; flex-direction: column; gap: 12px;
}
.modal h2 { font-size: 1.1rem; color: #e94560; }
.modal label { display: flex; flex-direction: column; gap: 4px; font-size: 0.8rem; color: #888; }
.modal input, .modal textarea {
background: #1a1a2e; border: 1px solid #0f3460;
border-radius: 8px; color: #e0e0e0;
padding: 8px 10px; outline: none; font-family: inherit;
}
.modal-buttons { display: flex; gap: 8px; justify-content: flex-end; }
.modal-buttons button { padding: 8px 18px; border-radius: 8px; border: none; cursor: pointer; }
#modalCancel, #cardModalCancel { background: #0f3460; color: #aaa; }
#modalSave, #cardModalImport { background: #e94560; color: white; }
.empty-state {
flex: 1; display: flex;
align-items: center; justify-content: center;
color: #444; flex-direction: column; gap: 8px;
}
.empty-state .big { font-size: 2.5rem; }
.hidden { display: none !important; }
+116
View File
@@ -0,0 +1,116 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat</title>
<link rel="stylesheet" href="/static/css/app.css">
</head>
<body>
<header>
<button id="sidebarToggle" type="button"></button>
<h1>🤖 AI Chat</h1>
<span class="header-title" id="headerTitle">Новый чат</span>
</header>
<div class="app-body">
<aside class="sidebar" id="sidebar">
<div class="sidebar-header">
<span>Чаты</span>
<button id="newChatBtn" type="button">+ Новый</button>
</div>
<div class="session-list" id="sessionList"></div>
</aside>
<div class="main">
<div class="persona-bar" id="personaBar"></div>
<div class="messages" id="messages">
<div class="empty-state" id="emptyState">
<span class="big">💬</span>
<span>Начни новый чат</span>
</div>
</div>
<div class="input-area">
<button id="clearBtn" type="button" title="Очистить историю">🗑</button>
<textarea id="input" rows="1"
placeholder="Напиши сообщение... (Enter — отправить, Shift+Enter — новая строка)"></textarea>
<button id="sendBtn" type="button"></button>
</div>
</div>
</div>
<div class="modal-overlay" id="modalOverlay">
<div class="modal">
<h2>✨ Новый персонаж</h2>
<label>ID (латиницей)
<input type="text" id="pId" placeholder="my_hero">
</label>
<label>Имя
<input type="text" id="pName" placeholder="Мой герой">
</label>
<label>Эмодзи
<input type="text" id="pEmoji" placeholder="🦸" maxlength="4">
</label>
<label>Описание
<input type="text" id="pDesc" placeholder="Краткое описание">
</label>
<label>Системный промт
<textarea id="pPrompt" rows="4" placeholder="Ты — ..."></textarea>
</label>
<label><input type="checkbox" id="pSdEnabled"> Генерировать SD-промпт</label>
<label>LoRA
<input type="text" id="pLora" placeholder="CharacterLoRA">
</label>
<label>Теги внешности (SD)
<input type="text" id="pAppearance" placeholder="blue hair, elf ears">
</label>
<div class="modal-buttons">
<button id="modalCancel" type="button">Отмена</button>
<button id="modalSave" type="button">Создать</button>
</div>
</div>
</div>
<div class="modal-overlay" id="cardModalOverlay">
<div class="modal">
<h2>📥 Импорт карточки (chub.io / V2)</h2>
<label>Файл JSON или PNG
<input type="file" id="cardFile" accept=".json,.png">
</label>
<label>LoRA
<input type="text" id="cardLora" placeholder="CharacterLoRA">
</label>
<label>Вес LoRA
<input type="number" id="cardLoraWeight" value="0.8" min="0" max="2" step="0.1">
</label>
<div class="modal-buttons">
<button id="cardModalCancel" type="button">Отмена</button>
<button id="cardModalImport" type="button">Импорт</button>
</div>
</div>
</div>
<div class="modal-overlay" id="cardEditOverlay">
<div class="modal" style="max-width:560px;max-height:90vh;overflow-y:auto">
<h2>✏️ Редактор карточки</h2>
<input type="hidden" id="editCardId">
<label>Имя <input type="text" id="editName"></label>
<label>Описание <textarea id="editDescription" rows="4"></textarea></label>
<label>Личность <textarea id="editPersonality" rows="3"></textarea></label>
<label>Сценарий <textarea id="editScenario" rows="3"></textarea></label>
<label>Первое сообщение <textarea id="editFirstMes" rows="3"></textarea></label>
<label>Пример диалога <textarea id="editMesExample" rows="3"></textarea></label>
<label>Теги внешности (SD) <input type="text" id="editAppearance" placeholder="silver hair, yellow eyes, wolf ears, black cloak"></label>
<label>LoRA <input type="text" id="editLora" placeholder="CharacterLoRA"></label>
<label>Вес LoRA <input type="number" id="editLoraWeight" value="0.8" min="0" max="2" step="0.1"></label>
<div class="modal-buttons">
<button id="cardEditCancel" type="button">Отмена</button>
<button id="cardEditSave" type="button" style="background:#e94560;color:white">Сохранить</button>
</div>
</div>
</div>
<script type="module" src="/static/js/app.js"></script>
</body>
</html>
+30
View File
@@ -0,0 +1,30 @@
import { toggleSidebar, dom } from './state.js';
import { initSessions, createNewChat } from './sessions.js';
import { loadPersonas, initPersonaModals } from './personas.js';
import { sendMessage, clearHistory } from './chat.js';
document.getElementById('sidebarToggle').addEventListener('click', () => {
const open = toggleSidebar();
document.getElementById('sidebar').classList.toggle('collapsed', !open);
});
document.getElementById('newChatBtn').addEventListener('click', createNewChat);
dom.inputEl.addEventListener('input', () => {
dom.inputEl.style.height = 'auto';
dom.inputEl.style.height = dom.inputEl.scrollHeight + 'px';
});
dom.inputEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
dom.sendBtn.addEventListener('click', sendMessage);
dom.clearBtn.addEventListener('click', clearHistory);
initPersonaModals();
await initSessions();
loadPersonas();
+260
View File
@@ -0,0 +1,260 @@
import { sessionId, currentPersona, dom } from './state.js';
import { parseImagePromptFromContent, copyToClipboard } from './utils.js';
export async function initChat() {
if (!sessionId || !currentPersona) return;
const res = await fetch('/chat/init', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: '', session_id: sessionId, persona_id: currentPersona }),
});
if (!res.ok) return;
const data = await res.json();
if (data.first_mes) addMessage('assistant', data.first_mes);
}
export function updateEmptyState() {
const hasMessages = dom.messagesEl.querySelector('.message');
dom.emptyState?.classList.toggle('hidden', !!hasMessages);
}
export function createImagePromptBlock(promptText) {
const block = document.createElement('div');
block.className = 'image-prompt-block';
const header = document.createElement('div');
header.className = 'image-prompt-header';
header.innerHTML = '<span>🎨 SD prompt</span>';
const copyBtn = document.createElement('button');
copyBtn.type = 'button';
copyBtn.className = 'copy-prompt-btn';
copyBtn.textContent = 'Копировать';
copyBtn.addEventListener('click', async () => {
const ok = await copyToClipboard(promptText);
copyBtn.textContent = ok ? 'Скопировано' : 'Ошибка';
setTimeout(() => { copyBtn.textContent = 'Копировать'; }, 1500);
});
header.appendChild(copyBtn);
const genBtn = document.createElement('button');
genBtn.type = 'button';
genBtn.className = 'gen-image-btn';
genBtn.textContent = '🖼 Генерировать';
genBtn.addEventListener('click', () => generateImageViaA1111(promptText, block));
header.appendChild(genBtn);
const textEl = document.createElement('span');
textEl.className = 'prompt-text';
textEl.textContent = promptText;
block.appendChild(header);
block.appendChild(textEl);
return block;
}
async function generateImageViaA1111(promptText, block) {
block.parentElement.querySelector('.chat-image')?.remove();
block.parentElement.querySelector('.image-error')?.remove();
try {
const res = await fetch('/images/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ session_id: sessionId, prompt: promptText }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.detail || res.statusText);
const img = document.createElement('img');
img.className = 'chat-image';
img.src = data.image_path;
block.parentElement.appendChild(img);
} catch (e) {
const err = document.createElement('div');
err.className = 'image-error';
err.textContent = '🖼 ' + e.message;
block.parentElement.appendChild(err);
}
}
export function appendChatImage(wrapper, imagePath) {
if (!imagePath) return;
const img = document.createElement('img');
img.className = 'chat-image';
img.src = imagePath;
wrapper.appendChild(img);
}
export function addMessage(role, content = '', imagePrompt = null, imagePath = null) {
updateEmptyState();
const wrapper = document.createElement('div');
wrapper.className = `message ${role}`;
const label = document.createElement('div');
label.className = 'label';
label.textContent = role === 'user' ? 'Вы' : 'AI';
wrapper.appendChild(label);
let displayContent = content;
let prompt = imagePrompt;
if (role === 'assistant' && !prompt) {
const parsed = parseImagePromptFromContent(content);
displayContent = parsed.text;
prompt = parsed.prompt;
}
const bubble = document.createElement('div');
bubble.className = 'bubble';
bubble.textContent = displayContent;
wrapper.appendChild(bubble);
if (role === 'assistant') {
const translateBtn = document.createElement('button');
translateBtn.type = 'button';
translateBtn.className = 'translate-btn';
translateBtn.textContent = '🌐 RU';
let originalText = null;
translateBtn.addEventListener('click', async () => {
if (originalText !== null) {
bubble.textContent = originalText;
originalText = null;
translateBtn.textContent = '🌐 RU';
return;
}
originalText = bubble.textContent;
translateBtn.disabled = true;
translateBtn.textContent = '…';
try {
const res = await fetch('/translate/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: originalText }),
});
if (!res.ok) throw new Error(res.statusText);
const data = await res.json();
bubble.textContent = data.translated;
translateBtn.textContent = '↩ Оригинал';
} catch {
originalText = null;
translateBtn.textContent = '⚠️';
setTimeout(() => { translateBtn.textContent = '🌐 RU'; }, 2000);
}
translateBtn.disabled = false;
});
wrapper.appendChild(translateBtn);
}
if (prompt) wrapper.appendChild(createImagePromptBlock(prompt));
if (imagePath) appendChatImage(wrapper, imagePath);
dom.messagesEl.appendChild(wrapper);
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
return bubble;
}
export function showTyping() {
const typing = document.createElement('div');
typing.className = 'typing';
typing.id = 'typing';
typing.innerHTML = '<span></span><span></span><span></span>';
dom.messagesEl.appendChild(typing);
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
}
export function removeTyping() {
document.getElementById('typing')?.remove();
}
export function clearMessages() {
dom.messagesEl.innerHTML = '';
if (dom.emptyState) {
dom.messagesEl.appendChild(dom.emptyState);
dom.emptyState.classList.remove('hidden');
}
}
export async function sendMessage() {
const text = dom.inputEl.value.trim();
if (!text || !sessionId) return;
dom.inputEl.value = '';
dom.inputEl.style.height = 'auto';
dom.sendBtn.disabled = true;
addMessage('user', text);
showTyping();
try {
const res = await fetch('/chat/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text, session_id: sessionId, persona_id: currentPersona }),
});
if (!res.ok) throw new Error('Ошибка сервера: ' + res.status);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let bubble = null;
removeTyping();
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
try {
const data = JSON.parse(line.slice(6));
if (data.chunk !== undefined) {
if (!bubble) {
bubble = addMessage('assistant', '');
bubble.classList.add('typing-active');
}
bubble.textContent += data.chunk;
bubble.textContent = bubble.textContent.replace(/\[IMAGE_PROMPT:.*?\]/gs, '').trim();
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
}
if (data.done) {
bubble?.classList.remove('typing-active');
if (data.image_prompt && bubble) {
bubble.parentElement.appendChild(createImagePromptBlock(data.image_prompt));
}
if (data.image_path && bubble) {
appendChatImage(bubble.parentElement, data.image_path);
}
if (data.image_error && bubble) {
const err = document.createElement('div');
err.className = 'image-error';
err.textContent = '🖼 ' + data.image_error;
bubble.parentElement.appendChild(err);
}
const { loadSessions } = await import('./sessions.js');
loadSessions();
}
} catch { /* skip */ }
}
}
} catch (err) {
removeTyping();
addMessage('assistant', '⚠️ Ошибка: ' + err.message);
} finally {
dom.sendBtn.disabled = false;
dom.inputEl.focus();
}
}
export async function clearHistory() {
if (!sessionId) return;
await fetch(`/chat/${sessionId}`, { method: 'DELETE' });
clearMessages();
}
+164
View File
@@ -0,0 +1,164 @@
import { currentPersona, setCurrentPersona, sessionId } from './state.js';
import { initChat } from './chat.js';
export function highlightPersona(personaId) {
document.querySelectorAll('.persona-card').forEach(c => {
c.classList.toggle('active', c.dataset.id === personaId);
});
}
export async function loadPersonas() {
const res = await fetch('/personas/');
const personas = await res.json();
const bar = document.getElementById('personaBar');
bar.innerHTML = '';
personas.forEach(p => {
const card = document.createElement('div');
card.className = 'persona-card' + (p.persona_id === currentPersona ? ' active' : '');
card.dataset.id = p.persona_id;
const isCard = p.persona_id.startsWith('card_');
card.innerHTML = `
<span class="emoji">${p.emoji}</span>
<span class="pname">${p.name}</span>
${p.custom ? `<button class="del-btn" type="button">✕</button>` : ''}
${isCard ? `<button class="edit-btn" type="button">✏️</button>` : ''}
`;
card.addEventListener('click', () => selectPersona(p.persona_id));
card.querySelector('.del-btn')?.addEventListener('click', async (e) => {
e.stopPropagation();
await fetch(`/personas/${p.persona_id}`, { method: 'DELETE' });
if (currentPersona === p.persona_id) await selectPersona('default');
loadPersonas();
});
card.querySelector('.edit-btn')?.addEventListener('click', async (e) => {
e.stopPropagation();
const cardId = p.persona_id.slice(5);
const r = await fetch(`/characters/${cardId}`);
const data = await r.json();
document.getElementById('editCardId').value = cardId;
document.getElementById('editName').value = data.name || '';
document.getElementById('editDescription').value = data.description || '';
document.getElementById('editPersonality').value = data.personality || '';
document.getElementById('editScenario').value = data.scenario || '';
document.getElementById('editFirstMes').value = data.first_mes || '';
document.getElementById('editMesExample').value = data.mes_example || '';
document.getElementById('editAppearance').value = data.appearance_tags || '';
document.getElementById('editLora').value = data.lora_name || '';
document.getElementById('editLoraWeight').value = data.lora_weight ?? 0.8;
document.getElementById('cardEditOverlay').classList.add('open');
});
bar.appendChild(card);
});
const addBtn = document.createElement('button');
addBtn.type = 'button';
addBtn.className = 'persona-add';
addBtn.innerHTML = '<span>Создать</span>';
addBtn.addEventListener('click', () => document.getElementById('modalOverlay').classList.add('open'));
bar.appendChild(addBtn);
const importBtn = document.createElement('button');
importBtn.type = 'button';
importBtn.className = 'card-import-btn';
importBtn.innerHTML = '📥<span>Chub</span>';
importBtn.addEventListener('click', () => document.getElementById('cardModalOverlay').classList.add('open'));
bar.appendChild(importBtn);
}
export async function selectPersona(personaId) {
setCurrentPersona(personaId);
highlightPersona(personaId);
if (sessionId) {
await fetch(`/sessions/${sessionId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ persona_id: personaId }),
});
await initChat();
}
}
export function initPersonaModals() {
document.getElementById('modalCancel').addEventListener('click', () => {
document.getElementById('modalOverlay').classList.remove('open');
});
document.getElementById('cardModalCancel').addEventListener('click', () => {
document.getElementById('cardModalOverlay').classList.remove('open');
});
document.getElementById('cardEditCancel').addEventListener('click', () => {
document.getElementById('cardEditOverlay').classList.remove('open');
});
document.getElementById('modalSave').addEventListener('click', async () => {
const data = {
persona_id: document.getElementById('pId').value.trim(),
name: document.getElementById('pName').value.trim(),
emoji: document.getElementById('pEmoji').value.trim() || '🤖',
description: document.getElementById('pDesc').value.trim(),
prompt: document.getElementById('pPrompt').value.trim(),
sd_enabled: document.getElementById('pSdEnabled').checked,
lora_name: document.getElementById('pLora').value.trim(),
appearance_tags: document.getElementById('pAppearance').value.trim(),
};
if (!data.persona_id || !data.name || !data.prompt) {
alert('Заполни ID, имя и промт');
return;
}
await fetch('/personas/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
document.getElementById('modalOverlay').classList.remove('open');
await loadPersonas();
await selectPersona(data.persona_id);
});
document.getElementById('cardEditSave').addEventListener('click', async () => {
const cardId = document.getElementById('editCardId').value;
const body = {
name: document.getElementById('editName').value.trim() || undefined,
description: document.getElementById('editDescription').value.trim() || undefined,
personality: document.getElementById('editPersonality').value.trim() || undefined,
scenario: document.getElementById('editScenario').value.trim() || undefined,
first_mes: document.getElementById('editFirstMes').value.trim() || undefined,
mes_example: document.getElementById('editMesExample').value.trim() || undefined,
appearance_tags: document.getElementById('editAppearance').value.trim() || undefined,
lora_name: document.getElementById('editLora').value.trim() || undefined,
lora_weight: parseFloat(document.getElementById('editLoraWeight').value) || undefined,
};
const res = await fetch(`/characters/${cardId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) { alert('Ошибка сохранения'); return; }
document.getElementById('cardEditOverlay').classList.remove('open');
await loadPersonas();
});
document.getElementById('cardModalImport').addEventListener('click', async () => {
const fileInput = document.getElementById('cardFile');
if (!fileInput.files?.length) {
alert('Выберите файл карточки (JSON или PNG)');
return;
}
const form = new FormData();
form.append('file', fileInput.files[0]);
form.append('lora_name', document.getElementById('cardLora').value.trim());
form.append('lora_weight', document.getElementById('cardLoraWeight').value || '0.8');
const res = await fetch('/characters/import', { method: 'POST', body: form });
const data = await res.json();
if (!res.ok) {
alert(data.detail || 'Ошибка импорта');
return;
}
document.getElementById('cardModalOverlay').classList.remove('open');
fileInput.value = '';
await loadPersonas();
await selectPersona(data.persona_id);
});
}
+86
View File
@@ -0,0 +1,86 @@
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 = `
<div class="s-title">${escapeTitle(s.title || 'Новый чат')}</div>
<div class="s-meta">${s.message_count} сообщ.</div>
<button class="s-del" type="button">🗑</button>
`;
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();
}
}
+24
View File
@@ -0,0 +1,24 @@
export let sessionId = localStorage.getItem('chat_session_id') || null;
export let currentPersona = localStorage.getItem('persona_id') || 'default';
export let sidebarOpen = true;
export function toggleSidebar() { sidebarOpen = !sidebarOpen; return sidebarOpen; }
export function setSessionId(id) {
sessionId = id;
if (id) localStorage.setItem('chat_session_id', id);
}
export function setCurrentPersona(id) {
currentPersona = id;
localStorage.setItem('persona_id', id);
}
export const dom = {
messagesEl: document.getElementById('messages'),
inputEl: document.getElementById('input'),
sendBtn: document.getElementById('sendBtn'),
clearBtn: document.getElementById('clearBtn'),
sessionList: document.getElementById('sessionList'),
headerTitle: document.getElementById('headerTitle'),
emptyState: document.getElementById('emptyState'),
};
+16
View File
@@ -0,0 +1,16 @@
export function parseImagePromptFromContent(content) {
if (!content || !content.includes('[IMAGE_PROMPT:')) return { text: content, prompt: null };
const match = content.match(/\[IMAGE_PROMPT:(.*?)\]/s);
const prompt = match ? match[1].trim() : null;
const text = content.replace(/\[IMAGE_PROMPT:.*?\]/gs, '').trim();
return { text, prompt };
}
export async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
}