Fixed RPG
This commit is contained in:
+331
-54
@@ -53,6 +53,102 @@ export function createImagePromptBlock(promptText) {
|
||||
return block;
|
||||
}
|
||||
|
||||
const OUTCOME_CLASS = {
|
||||
'critical failure': 'outcome-crit-fail',
|
||||
'failure': 'outcome-fail',
|
||||
'success': 'outcome-success',
|
||||
'critical success': 'outcome-crit-success',
|
||||
};
|
||||
|
||||
function renderNarratorMessage(narrator) {
|
||||
// narrator = { roll, outcome, text }
|
||||
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);
|
||||
dom.messagesEl.appendChild(wrapper);
|
||||
dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight;
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function renderChoices(wrapper, choices) {
|
||||
if (!choices || !choices.length) return;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'choice-row';
|
||||
for (const c of choices) {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'choice-btn';
|
||||
btn.textContent = c.label;
|
||||
btn.addEventListener('click', () => {
|
||||
sendMessage(c.label, true);
|
||||
});
|
||||
row.appendChild(btn);
|
||||
}
|
||||
wrapper.appendChild(row);
|
||||
}
|
||||
|
||||
function renderDebugBlocks(wrapper, blocks) {
|
||||
if (!blocks || !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');
|
||||
lbl.className = 'label';
|
||||
lbl.textContent = '📖 Рассказчик';
|
||||
const bub = document.createElement('div');
|
||||
bub.className = 'bubble';
|
||||
bub.textContent = b.text;
|
||||
w.appendChild(lbl);
|
||||
w.appendChild(bub);
|
||||
dom.messagesEl.appendChild(w);
|
||||
}
|
||||
// facts/status_quo/plot_arc — silently skip (debug only, not shown to user)
|
||||
}
|
||||
}
|
||||
|
||||
export function updateQuestPanel(quests) {
|
||||
const list = document.getElementById('questList');
|
||||
if (!list) return;
|
||||
list.innerHTML = '';
|
||||
for (const q of quests) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `quest-item quest-${q.status}`;
|
||||
el.textContent = (q.status === 'done' ? '✅ ' : q.status === 'failed' ? '❌ ' : '🔸 ') + q.title;
|
||||
list.appendChild(el);
|
||||
}
|
||||
}
|
||||
|
||||
export function updateAffinityDisplay(affinity) {
|
||||
const el = dom.affinityDisplay;
|
||||
if (!el) return;
|
||||
el.classList.remove('hidden');
|
||||
const hearts = affinity >= 10 ? '❤️❤️❤️' : affinity >= 5 ? '❤️❤️' : affinity >= 1 ? '❤️' : affinity <= -5 ? '💔' : '🤍';
|
||||
el.textContent = `${hearts} ${affinity > 0 ? '+' : ''}${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();
|
||||
@@ -86,7 +182,208 @@ export function appendChatImage(wrapper, imagePath) {
|
||||
wrapper.appendChild(img);
|
||||
}
|
||||
|
||||
export function addMessage(role, content = '', imagePrompt = null, imagePath = null) {
|
||||
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';
|
||||
regenBtn.textContent = '🔄';
|
||||
regenBtn.title = 'Перегенерировать';
|
||||
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);
|
||||
}
|
||||
|
||||
async function startEditMessage(wrapper, messageId) {
|
||||
const bubble = wrapper.querySelector('.bubble');
|
||||
if (!bubble || wrapper.querySelector('.bubble-edit')) return;
|
||||
const original = bubble.textContent;
|
||||
const ta = document.createElement('textarea');
|
||||
ta.className = 'bubble-edit';
|
||||
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');
|
||||
saveBtn.textContent = 'Сохранить';
|
||||
const cancelBtn = document.createElement('button');
|
||||
cancelBtn.textContent = 'Отмена';
|
||||
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 res = await fetch(`/chat/messages/${messageId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: ta.value.trim(), truncate_after: doTruncate }),
|
||||
});
|
||||
if (!res.ok) { alert('Ошибка сохранения'); return; }
|
||||
await reloadChatFromServer(sessionId);
|
||||
const { loadSessions } = await import('./sessions.js');
|
||||
loadSessions();
|
||||
});
|
||||
}
|
||||
|
||||
async function regenerateMessage(messageId, wrapper) {
|
||||
if (!sessionId) return;
|
||||
wrapper?.remove();
|
||||
showTyping();
|
||||
dom.sendBtn.disabled = true;
|
||||
try {
|
||||
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,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error('Ошибка: ' + res.status);
|
||||
removeTyping();
|
||||
await consumeStream(res);
|
||||
} catch (err) {
|
||||
removeTyping();
|
||||
addMessage('assistant', '⚠️ ' + err.message);
|
||||
} finally {
|
||||
dom.sendBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function forkFromMessage(messageId) {
|
||||
if (!sessionId) return;
|
||||
const res = await fetch(`/sessions/${sessionId}/fork`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ until_message_id: messageId }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { alert(data.detail || 'Ошибка'); return; }
|
||||
const { switchSession, loadSessions } = await import('./sessions.js');
|
||||
await switchSession(data.session_id);
|
||||
await loadSessions();
|
||||
}
|
||||
|
||||
export async function reloadChatFromServer(id) {
|
||||
const sid = id || sessionId;
|
||||
if (!sid) return;
|
||||
const histRes = await fetch(`/chat/history/${sid}`);
|
||||
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,
|
||||
m.id,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function consumeStream(res) {
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
let bubble = null;
|
||||
|
||||
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.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();
|
||||
}
|
||||
} catch { /* skip */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function addMessage(role, content = '', imagePrompt = null, imagePath = null, messageId = null) {
|
||||
updateEmptyState();
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
@@ -149,6 +446,8 @@ 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;
|
||||
@@ -175,75 +474,32 @@ export function clearMessages() {
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendMessage() {
|
||||
const text = dom.inputEl.value.trim();
|
||||
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', text);
|
||||
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 }),
|
||||
body: JSON.stringify({
|
||||
message: text,
|
||||
session_id: sessionId,
|
||||
persona_id: currentPersona,
|
||||
is_narrator_choice: isNarratorChoice,
|
||||
}),
|
||||
});
|
||||
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 */ }
|
||||
}
|
||||
}
|
||||
await consumeStream(res);
|
||||
} catch (err) {
|
||||
removeTyping();
|
||||
addMessage('assistant', '⚠️ Ошибка: ' + err.message);
|
||||
@@ -253,6 +509,27 @@ export async function sendMessage() {
|
||||
}
|
||||
}
|
||||
|
||||
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' });
|
||||
|
||||
Reference in New Issue
Block a user