Fixed RPG

This commit is contained in:
2026-06-01 07:44:38 +03:00
parent 600ad78f05
commit d4cd8f02f4
30 changed files with 1516 additions and 816 deletions
+131 -160
View File
@@ -1,13 +1,11 @@
import { sessionId, currentPersona, dom } from './state.js';
import { parseImagePromptFromContent, copyToClipboard } from './utils.js';
export async function initChat() {
export async function initChat(options = {}) {
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 }),
});
const payload = { message: '', session_id: sessionId, persona_id: currentPersona };
if (options.first_mes_override?.trim()) payload.first_mes_override = options.first_mes_override.trim();
const res = await fetch('/chat/init', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
if (!res.ok) return;
const data = await res.json();
if (data.first_mes) addMessage('assistant', data.first_mes);
@@ -21,7 +19,6 @@ export function updateEmptyState() {
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>';
@@ -37,17 +34,43 @@ export function createImagePromptBlock(promptText) {
});
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 regenBtn = document.createElement('button');
regenBtn.type = 'button';
regenBtn.className = 'copy-prompt-btn';
regenBtn.textContent = '🖼 Перегенерировать';
regenBtn.addEventListener('click', async () => {
const wrapper = block.parentElement;
regenBtn.disabled = true;
regenBtn.textContent = '⏳…';
wrapper?.querySelector('.chat-image')?.remove();
wrapper?.querySelector('.image-error')?.remove();
showImageGenerating(wrapper);
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);
removeImageGenerating(wrapper);
appendChatImage(wrapper, data.image_path);
} catch (e) {
removeImageGenerating(wrapper);
const err = document.createElement('div');
err.className = 'image-error';
err.textContent = '🖼 ' + e.message;
wrapper?.appendChild(err);
} finally {
regenBtn.disabled = false;
regenBtn.textContent = '🖼 Перегенерировать';
}
});
header.appendChild(regenBtn);
const textEl = document.createElement('span');
textEl.className = 'prompt-text';
textEl.textContent = promptText;
block.appendChild(header);
block.appendChild(textEl);
return block;
@@ -60,37 +83,38 @@ const OUTCOME_CLASS = {
'critical success': 'outcome-crit-success',
};
function renderNarratorMessage(narrator) {
// narrator = { roll, outcome, text }
function buildNarratorEl(narrator) {
const wrapper = document.createElement('div');
wrapper.className = 'message narrator';
const label = document.createElement('div');
label.className = 'label';
label.textContent = '📖 Рассказчик';
wrapper.appendChild(label);
const bubble = document.createElement('div');
bubble.className = 'bubble';
const diceBlock = document.createElement('div');
diceBlock.className = `dice-block ${OUTCOME_CLASS[narrator.outcome] || ''}`;
diceBlock.innerHTML = `<span class="dice-icon">🎲</span><span class="dice-roll">${narrator.roll}</span><span class="dice-outcome">${narrator.outcome}</span>`;
bubble.appendChild(diceBlock);
if (narrator.roll != null) {
const diceBlock = document.createElement('div');
diceBlock.className = `dice-block ${OUTCOME_CLASS[narrator.outcome] || ''}`;
diceBlock.innerHTML = `<span class="dice-icon">🎲</span><span class="dice-roll">${narrator.roll}</span><span class="dice-outcome">${narrator.outcome}</span>`;
bubble.appendChild(diceBlock);
}
const textEl = document.createElement('div');
textEl.className = 'narrator-text';
textEl.textContent = narrator.text;
bubble.appendChild(textEl);
wrapper.appendChild(bubble);
dom.messagesEl.appendChild(wrapper);
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
return wrapper;
}
function renderNarratorMessage(narrator) {
const el = buildNarratorEl(narrator);
dom.messagesEl.appendChild(el);
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
return el;
}
function renderChoices(wrapper, choices) {
if (!choices || !choices.length) return;
if (!choices?.length) return;
const row = document.createElement('div');
row.className = 'choice-row';
for (const c of choices) {
@@ -98,20 +122,17 @@ function renderChoices(wrapper, choices) {
btn.type = 'button';
btn.className = 'choice-btn';
btn.textContent = c.label;
btn.addEventListener('click', () => {
sendMessage(c.label, true);
});
btn.addEventListener('click', () => sendMessage(c.label, true));
row.appendChild(btn);
}
wrapper.appendChild(row);
}
function renderDebugBlocks(wrapper, blocks) {
if (!blocks || !blocks.length) return;
if (!blocks?.length) return;
for (const b of blocks) {
if (!b?.text) continue;
if (b.type === 'narrator_injection') {
// Show beat injections as narrator bubbles (no dice)
const w = document.createElement('div');
w.className = 'message narrator';
const lbl = document.createElement('div');
@@ -124,7 +145,6 @@ function renderDebugBlocks(wrapper, blocks) {
w.appendChild(bub);
dom.messagesEl.appendChild(w);
}
// facts/status_quo/plot_arc — silently skip (debug only, not shown to user)
}
}
@@ -149,31 +169,6 @@ export function updateAffinityDisplay(affinity) {
el.className = `affinity-display ${affinity > 5 ? 'affinity-high' : affinity < -3 ? 'affinity-low' : ''}`;
}
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');
@@ -182,20 +177,31 @@ export function appendChatImage(wrapper, imagePath) {
wrapper.appendChild(img);
}
export function showImageGenerating(wrapper) {
if (!wrapper || wrapper.querySelector('.image-generating')) return;
const el = document.createElement('div');
el.className = 'image-generating';
el.setAttribute('role', 'status');
el.innerHTML = '<span class="image-generating-spinner" aria-hidden="true"></span><span class="image-generating-text">Генерация изображения в ComfyUI…</span>';
wrapper.appendChild(el);
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
}
export function removeImageGenerating(wrapper) {
wrapper?.querySelector('.image-generating')?.remove();
}
function attachMessageActions(wrapper, messageId, role) {
if (!messageId) return;
wrapper.dataset.messageId = String(messageId);
const actions = document.createElement('div');
actions.className = 'message-actions';
const editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.textContent = '✏️';
editBtn.title = 'Редактировать';
editBtn.addEventListener('click', () => startEditMessage(wrapper, messageId));
actions.appendChild(editBtn);
if (role === 'assistant') {
const regenBtn = document.createElement('button');
regenBtn.type = 'button';
@@ -204,14 +210,12 @@ function attachMessageActions(wrapper, messageId, role) {
regenBtn.addEventListener('click', () => regenerateMessage(messageId, wrapper));
actions.appendChild(regenBtn);
}
const branchBtn = document.createElement('button');
branchBtn.type = 'button';
branchBtn.textContent = '🌿';
branchBtn.title = 'Ветка отсюда';
branchBtn.addEventListener('click', () => forkFromMessage(messageId));
actions.appendChild(branchBtn);
wrapper.appendChild(actions);
}
@@ -224,7 +228,6 @@ async function startEditMessage(wrapper, messageId) {
ta.value = original;
bubble.replaceWith(ta);
wrapper.querySelector('.message-actions')?.remove();
const saveRow = document.createElement('div');
saveRow.className = 'message-actions';
const saveBtn = document.createElement('button');
@@ -234,17 +237,10 @@ async function startEditMessage(wrapper, messageId) {
saveRow.appendChild(saveBtn);
saveRow.appendChild(cancelBtn);
wrapper.appendChild(saveRow);
const truncate = role => confirm(
role === 'user'
? 'Удалить все сообщения после этого? (рекомендуется)'
: 'Удалить все сообщения после этого?',
);
cancelBtn.addEventListener('click', () => reloadChatFromServer(sessionId));
saveBtn.addEventListener('click', async () => {
const role = wrapper.classList.contains('user') ? 'user' : 'assistant';
const doTruncate = truncate(role);
const doTruncate = confirm(role === 'user' ? 'Удалить все сообщения после этого? (рекомендуется)' : 'Удалить все сообщения после этого?');
const res = await fetch(`/chat/messages/${messageId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
@@ -266,11 +262,7 @@ async function regenerateMessage(messageId, wrapper) {
const res = await fetch('/chat/regenerate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
session_id: sessionId,
persona_id: currentPersona,
message_id: messageId,
}),
body: JSON.stringify({ session_id: sessionId, persona_id: currentPersona, message_id: messageId }),
});
if (!res.ok) throw new Error('Ошибка: ' + res.status);
removeTyping();
@@ -315,6 +307,8 @@ export async function reloadChatFromServer(id) {
});
}
const IMAGE_PROMPT_RE = /\[IMAGE_PROMPT:.*?\]/gs;
async function consumeStream(res) {
const reader = res.body.getReader();
const decoder = new TextDecoder();
@@ -324,71 +318,80 @@ async function consumeStream(res) {
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;
let data;
try { data = JSON.parse(line.slice(6)); } catch { continue; }
// Narrator arrives BEFORE chunks — render immediately
if (data.narrator) {
renderNarratorMessage(data.narrator);
}
if (data.chunk !== undefined) {
if (!bubble) {
bubble = addMessage('assistant', '');
bubble.classList.add('typing-active');
}
if (data.done) {
bubble?.classList.remove('typing-active');
if (data.narrator && !bubble) {
renderNarratorMessage(data.narrator);
} else if (data.narrator && bubble) {
const assistantWrapper = bubble.parentElement;
dom.messagesEl.insertBefore(buildNarratorWrapper(data.narrator), assistantWrapper);
}
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);
}
if (data.choices && bubble) {
renderChoices(bubble.parentElement, data.choices);
}
if (data.debug) {
renderDebugBlocks(bubble?.parentElement || dom.messagesEl, data.debug);
}
if (data.affinity !== undefined) {
updateAffinityDisplay(data.affinity);
}
if (data.quests?.length) {
updateQuestPanel(data.quests);
}
await reloadChatFromServer(sessionId);
const { loadSessions } = await import('./sessions.js');
loadSessions();
bubble.textContent += data.chunk;
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
}
if (data.image_generating && bubble) {
bubble.classList.remove('typing-active');
const wrapper = bubble.parentElement;
if (data.image_prompt && !wrapper.querySelector('.image-prompt-block')) {
wrapper.appendChild(createImagePromptBlock(data.image_prompt));
}
} catch { /* skip */ }
showImageGenerating(wrapper);
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
}
if (data.done) {
const wrapper = bubble?.parentElement;
removeImageGenerating(wrapper);
bubble?.classList.remove('typing-active');
// Strip IMAGE_PROMPT tag from final text
if (bubble) {
bubble.textContent = bubble.textContent.replace(IMAGE_PROMPT_RE, '').trim();
}
if (data.image_prompt && wrapper && !wrapper.querySelector('.image-prompt-block')) {
wrapper.appendChild(createImagePromptBlock(data.image_prompt));
}
if (data.image_path && wrapper) {
console.log('[image] appending', data.image_path, 'to', wrapper);
appendChatImage(wrapper, data.image_path);
} else {
console.log('[image] skip: image_path=', data.image_path, 'wrapper=', wrapper);
}
if (data.image_error && wrapper) {
const err = document.createElement('div');
err.className = 'image-error';
err.textContent = '🖼 ' + data.image_error;
wrapper.appendChild(err);
}
if (data.choices?.length && bubble) renderChoices(bubble.parentElement, data.choices);
if (data.debug) renderDebugBlocks(bubble?.parentElement || dom.messagesEl, data.debug);
if (data.affinity !== undefined) updateAffinityDisplay(data.affinity);
if (data.quests?.length) updateQuestPanel(data.quests);
const { loadSessions } = await import('./sessions.js');
loadSessions();
}
}
}
}
export function addMessage(role, content = '', imagePrompt = null, imagePath = null, messageId = null) {
updateEmptyState();
const wrapper = document.createElement('div');
wrapper.className = `message ${role}`;
const label = document.createElement('div');
label.className = 'label';
label.textContent = role === 'user' ? 'Вы' : 'AI';
@@ -445,9 +448,7 @@ export function addMessage(role, content = '', imagePrompt = null, imagePath = n
if (prompt) wrapper.appendChild(createImagePromptBlock(prompt));
if (imagePath) appendChatImage(wrapper, imagePath);
attachMessageActions(wrapper, messageId, role);
dom.messagesEl.appendChild(wrapper);
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
return bubble;
@@ -477,27 +478,18 @@ export function clearMessages() {
export async function sendMessage(text, isNarratorChoice = false) {
if (typeof text !== 'string') text = dom.inputEl.value.trim();
if (!text || !sessionId) return;
dom.inputEl.value = '';
dom.inputEl.style.height = 'auto';
dom.sendBtn.disabled = true;
addMessage('user', isNarratorChoice ? `[${text}]` : 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,
is_narrator_choice: isNarratorChoice,
}),
body: JSON.stringify({ message: text, session_id: sessionId, persona_id: currentPersona, is_narrator_choice: isNarratorChoice }),
});
if (!res.ok) throw new Error('Ошибка сервера: ' + res.status);
removeTyping();
await consumeStream(res);
} catch (err) {
@@ -509,27 +501,6 @@ export async function sendMessage(text, isNarratorChoice = false) {
}
}
function buildNarratorWrapper(narrator) {
const wrapper = document.createElement('div');
wrapper.className = 'message narrator';
const label = document.createElement('div');
label.className = 'label';
label.textContent = '📖 Рассказчик';
wrapper.appendChild(label);
const bubble = document.createElement('div');
bubble.className = 'bubble';
const diceBlock = document.createElement('div');
diceBlock.className = `dice-block ${OUTCOME_CLASS[narrator.outcome] || ''}`;
diceBlock.innerHTML = `<span class="dice-icon">🎲</span><span class="dice-roll">${narrator.roll}</span><span class="dice-outcome">${narrator.outcome}</span>`;
bubble.appendChild(diceBlock);
const textEl = document.createElement('div');
textEl.className = 'narrator-text';
textEl.textContent = narrator.text;
bubble.appendChild(textEl);
wrapper.appendChild(bubble);
return wrapper;
}
export async function clearHistory() {
if (!sessionId) return;
await fetch(`/chat/${sessionId}`, { method: 'DELETE' });