feat(chat): multi-session chat support (up to 15), human-like auto-titling, line-clamp titles and sorted registries

This commit is contained in:
2026-10-23 20:18:14 +03:00
parent b5c993486d
commit 09bd66923b
12 changed files with 1114 additions and 650 deletions
+189
View File
@@ -0,0 +1,189 @@
/**
* ===============================================================================
* FILE: modules/web_api/static/js/chat/cards.js
* ROLE: Рендеринг специализированных карточек чата:
* - Скачивание Word-документов
* - Инспекция срезов (таблица сотрудников)
* - Инлайн-редакторы промпта и правил
* ===============================================================================
*/
window.ChatCardsRenderer = {
renderActionPayload(actionPayload) {
if (!actionPayload) return '';
if (actionPayload.type === 'SNAPSHOTS_CARD' && typeof renderSnapshotsCard === 'function') {
return renderSnapshotsCard(actionPayload.data);
}
if (actionPayload.type === 'TASK_INTERACTIVE_CARD' && typeof renderInteractiveTaskCard === 'function') {
return renderInteractiveTaskCard(actionPayload.tasks);
}
if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
const dlUrl = actionPayload.download_url || '#';
const fName = actionPayload.filename || 'document.docx';
const count = actionPayload.tasks_count || '';
return `
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-200 rounded-xl flex items-center justify-between gap-3 shadow-xs">
<div class="flex items-center gap-3 min-w-0">
<div class="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center shrink-0 shadow-sm">
<i class="fa-solid fa-file-word text-lg"></i>
</div>
<div class="min-w-0">
<div class="text-sm font-bold text-slate-800 truncate">${escapeHtml(fName)}</div>
<div class="text-xs text-slate-500">${count ? count + ' · ' : ''}Документ MS Word (.docx)</div>
</div>
</div>
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white font-bold rounded-xl text-xs shadow-sm transition flex items-center gap-2 shrink-0">
<i class="fa-solid fa-arrow-down-to-line text-sm text-white"></i>
<span class="text-white tracking-wide">Скачать файл</span>
</a>
</div>
`;
}
if (actionPayload.type === 'SNAPSHOT_INSPECT_CARD') {
const records = actionPayload.records || [];
const inspectTableId = 'inspect-table-' + Date.now();
const searchInputId = 'inspect-search-' + Date.now();
const rowsHtml = records.map((r, idx) => `
<tr class="inspect-row border-b border-slate-100 text-xs ${r.is_present ? 'bg-white' : 'bg-slate-50/60'} hover:bg-indigo-50/40"
data-fio="${escapeHtml(r.fio).toLowerCase()}" data-dept="${escapeHtml(r.department).toLowerCase()}">
<td class="p-2.5 text-slate-400 text-center font-mono w-10">${idx + 1}</td>
<td class="p-2.5 font-medium text-slate-800">${escapeHtml(r.fio)}</td>
<td class="p-2.5 text-slate-500 text-center">${escapeHtml(r.department)}</td>
<td class="p-2.5 text-center ${r.time_in !== 'Нет входа' ? 'font-bold text-emerald-700' : 'text-slate-400'}">${escapeHtml(r.time_in)}</td>
<td class="p-2.5 text-center text-slate-500">${escapeHtml(r.first_activity)}</td>
<td class="p-2.5 text-center ${r.time_out !== 'Нет выхода' ? 'font-bold text-slate-800' : 'text-slate-400'}">${escapeHtml(r.time_out)}</td>
<td class="p-2.5 text-center font-mono text-slate-600">${escapeHtml(r.in_building)}</td>
<td class="p-2.5 text-center font-bold">${r.is_present ? '<span class="text-emerald-600">✓ Да</span>' : '<span class="text-slate-400">Нет</span>'}</td>
</tr>
`).join('');
return `
<div class="mt-3 bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm flex flex-col">
<div class="px-4 py-3 bg-slate-100/90 border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
<div class="flex items-center gap-2">
<span class="text-sm font-bold text-slate-800">Срез #${escapeHtml(actionPayload.snapshot_id)}</span>
<span class="text-xs text-slate-500">· Всего: ${records.length} чел. (Присутствуют: ${actionPayload.present_count || 0})</span>
</div>
<div class="flex items-center gap-2">
<input type="text" id="${searchInputId}" placeholder="Поиск в срезе (ФИО / отдел)..."
oninput="window.filterInspectTable('${inspectTableId}', this.value)"
class="text-xs px-3 py-1.5 bg-white border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 w-60" />
<button onclick="window.sendChatAction('покажи срезы')" class="text-xs text-indigo-600 hover:underline font-semibold">Все срезы</button>
</div>
</div>
<div class="max-h-96 overflow-y-auto">
<table id="${inspectTableId}" class="w-full text-left border-collapse">
<thead class="bg-slate-50 text-[11px] uppercase text-slate-500 sticky top-0 border-b border-slate-200 shadow-xs">
<tr>
<th class="p-2.5 text-center w-10">№</th>
<th class="p-2.5">Сотрудник</th>
<th class="p-2.5 text-center">Отдел</th>
<th class="p-2.5 text-center">Вход</th>
<th class="p-2.5 text-center">Активность</th>
<th class="p-2.5 text-center">Выход</th>
<th class="p-2.5 text-center">В здании</th>
<th class="p-2.5 text-center">Статус</th>
</tr>
</thead>
<tbody>${rowsHtml}</tbody>
</table>
</div>
</div>
`;
}
if (actionPayload.type === 'PROMPT_EDITOR') {
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
const editorId = 'prompt-editor-' + Date.now();
return `
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
<span><i class="fa-solid fa-pen-to-square text-indigo-600 mr-1"></i> Инлайн-редактор системного промпта:</span>
<span class="text-[11px] text-slate-400 font-normal">Прямое редактирование текста</span>
</div>
<textarea id="${editorId}" rows="14"
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
<div class="flex items-center justify-end gap-2 pt-1">
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
<button type="button" onclick="window.submitPromptDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
<i class="fa-solid fa-eye text-xs"></i>
<span>Показать превью изменений</span>
</button>
</div>
</div>
`;
}
if (actionPayload.type === 'RULES_EDITOR') {
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
const editorId = 'rules-editor-' + Date.now();
return `
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
<span><i class="fa-solid fa-book-bookmark text-emerald-600 mr-1"></i> Редактор базы знаний:</span>
<span class="text-[11px] text-slate-400 font-normal">Прямое изменение правил</span>
</div>
<textarea id="${editorId}" rows="12"
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
<div class="flex items-center justify-end gap-2 pt-1">
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
<button type="button" onclick="window.submitRulesDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
<i class="fa-solid fa-eye text-xs"></i>
<span>Показать превью изменений</span>
</button>
</div>
</div>
`;
}
return '';
}
};
window.filterInspectTable = function(tableId, query) {
const table = document.getElementById(tableId);
if (!table) return;
const q = (query || '').trim().toLowerCase();
const rows = table.querySelectorAll('.inspect-row');
rows.forEach(r => {
const fio = r.getAttribute('data-fio') || '';
const dept = r.getAttribute('data-dept') || '';
if (!q || fio.includes(q) || dept.includes(q)) {
r.classList.remove('hidden');
} else {
r.classList.add('hidden');
}
});
};
window.submitPromptDraftToDiff = function(editorId) {
const textarea = document.getElementById(editorId);
if (!textarea) return;
const newText = textarea.value.trim();
if (!newText) {
alert("Текст системного промпта не может быть пустым");
return;
}
const input = document.getElementById("user-input");
if (input) input.value = `action:save_draft_prompt:::${newText}`;
window.sendMessage();
};
window.submitRulesDraftToDiff = function(editorId) {
const textarea = document.getElementById(editorId);
if (!textarea) return;
const newText = textarea.value.trim();
if (!newText) {
alert("Правила не могут быть пустыми");
return;
}
const input = document.getElementById("user-input");
if (input) input.value = `action:save_draft_rules:::${newText}`;
window.sendMessage();
};
+27 -200
View File
@@ -1,8 +1,8 @@
/**
* ===============================================================================
* FILE: modules/web_api/static/js/chat/core.js
* ROLE: Ядро чата: полноэкранный Drag-and-Drop оверлей, авто-высота инпута (24px),
* надежный расчет скролла вопроса к верху окна, крупный шрифт text-sm.
* ROLE: Ядро чата: сессии (TopicsManager), отправка сообщений,
* индикатор загрузки, Drag-and-Drop и автоскролл.
* ===============================================================================
*/
@@ -25,7 +25,6 @@ function saveCommandToHistory(commandText) {
chatHistoryIndex = -1;
}
// ⭐️ ЕДИНАЯ ФУНКЦИЯ СКРОЛЛА: выравнивание вопроса к верхней границе
function scrollToUserMessageTop() {
const container = document.getElementById("chat-messages-container");
if (!container) return;
@@ -36,7 +35,6 @@ function scrollToUserMessageTop() {
requestAnimationFrame(() => {
const targetScroll = targetEl.offsetTop - container.offsetTop - 12;
container.scrollTo({
top: Math.max(0, targetScroll),
behavior: 'smooth'
@@ -133,132 +131,11 @@ function appendAssistantMessage(text, buttons = [], actionPayload = null) {
const container = document.getElementById("chat-messages-container");
if (!container) return;
let payloadHtml = '';
let isHtmlBody = false;
const payloadHtml = window.ChatCardsRenderer
? window.ChatCardsRenderer.renderActionPayload(actionPayload)
: '';
if (actionPayload) {
if (actionPayload.type === 'SNAPSHOTS_CARD' && typeof renderSnapshotsCard === 'function') {
payloadHtml = renderSnapshotsCard(actionPayload.data);
} else if (actionPayload.type === 'TASK_INTERACTIVE_CARD' && typeof renderInteractiveTaskCard === 'function') {
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
const dlUrl = actionPayload.download_url || '#';
const fName = actionPayload.filename || 'document.docx';
const count = actionPayload.tasks_count || '';
payloadHtml = `
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-200 rounded-xl flex items-center justify-between gap-3 shadow-xs">
<div class="flex items-center gap-3 min-w-0">
<div class="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center shrink-0 shadow-sm">
<i class="fa-solid fa-file-word text-lg"></i>
</div>
<div class="min-w-0">
<div class="text-sm font-bold text-slate-800 truncate">${escapeHtml(fName)}</div>
<div class="text-xs text-slate-500">${count ? count + ' · ' : ''}Документ MS Word (.docx)</div>
</div>
</div>
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white font-bold rounded-xl text-xs shadow-sm transition flex items-center gap-2 shrink-0">
<i class="fa-solid fa-arrow-down-to-line text-sm text-white"></i>
<span class="text-white tracking-wide">Скачать файл</span>
</a>
</div>
`;
} else if (actionPayload.type === 'SNAPSHOT_INSPECT_CARD') {
const records = actionPayload.records || [];
const inspectTableId = 'inspect-table-' + Date.now();
const searchInputId = 'inspect-search-' + Date.now();
const rowsHtml = records.map((r, idx) => `
<tr class="inspect-row border-b border-slate-100 text-xs ${r.is_present ? 'bg-white' : 'bg-slate-50/60'} hover:bg-indigo-50/40"
data-fio="${escapeHtml(r.fio).toLowerCase()}" data-dept="${escapeHtml(r.department).toLowerCase()}">
<td class="p-2.5 text-slate-400 text-center font-mono w-10">${idx + 1}</td>
<td class="p-2.5 font-medium text-slate-800">${escapeHtml(r.fio)}</td>
<td class="p-2.5 text-slate-500 text-center">${escapeHtml(r.department)}</td>
<td class="p-2.5 text-center ${r.time_in !== 'Нет входа' ? 'font-bold text-emerald-700' : 'text-slate-400'}">${escapeHtml(r.time_in)}</td>
<td class="p-2.5 text-center text-slate-500">${escapeHtml(r.first_activity)}</td>
<td class="p-2.5 text-center ${r.time_out !== 'Нет выхода' ? 'font-bold text-slate-800' : 'text-slate-400'}">${escapeHtml(r.time_out)}</td>
<td class="p-2.5 text-center font-mono text-slate-600">${escapeHtml(r.in_building)}</td>
<td class="p-2.5 text-center font-bold">${r.is_present ? '<span class="text-emerald-600">✓ Да</span>' : '<span class="text-slate-400">Нет</span>'}</td>
</tr>
`).join('');
payloadHtml = `
<div class="mt-3 bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm flex flex-col">
<div class="px-4 py-3 bg-slate-100/90 border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
<div class="flex items-center gap-2">
<span class="text-sm font-bold text-slate-800">Срез #${escapeHtml(actionPayload.snapshot_id)}</span>
<span class="text-xs text-slate-500">· Всего: ${records.length} чел. (Присутствуют: ${actionPayload.present_count || 0})</span>
</div>
<div class="flex items-center gap-2">
<input type="text" id="${searchInputId}" placeholder="Поиск в срезе (ФИО / отдел)..."
oninput="window.filterInspectTable('${inspectTableId}', this.value)"
class="text-xs px-3 py-1.5 bg-white border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 w-60" />
<button onclick="window.sendChatAction('покажи срезы')" class="text-xs text-indigo-600 hover:underline font-semibold">Все срезы</button>
</div>
</div>
<div class="max-h-96 overflow-y-auto">
<table id="${inspectTableId}" class="w-full text-left border-collapse">
<thead class="bg-slate-50 text-[11px] uppercase text-slate-500 sticky top-0 border-b border-slate-200 shadow-xs">
<tr>
<th class="p-2.5 text-center w-10">№</th>
<th class="p-2.5">Сотрудник</th>
<th class="p-2.5 text-center">Отдел</th>
<th class="p-2.5 text-center">Вход</th>
<th class="p-2.5 text-center">Активность</th>
<th class="p-2.5 text-center">Выход</th>
<th class="p-2.5 text-center">В здании</th>
<th class="p-2.5 text-center">Статус</th>
</tr>
</thead>
<tbody>${rowsHtml}</tbody>
</table>
</div>
</div>
`;
} else if (actionPayload.type === 'PROMPT_EDITOR') {
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
const editorId = 'prompt-editor-' + Date.now();
payloadHtml = `
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
<span><i class="fa-solid fa-pen-to-square text-indigo-600 mr-1"></i> Инлайн-редактор системного промпта:</span>
<span class="text-[11px] text-slate-400 font-normal">Прямое редактирование текста</span>
</div>
<textarea id="${editorId}" rows="14"
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
<div class="flex items-center justify-end gap-2 pt-1">
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
<button type="button" onclick="window.submitPromptDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
<i class="fa-solid fa-eye text-xs"></i>
<span>Показать превью изменений</span>
</button>
</div>
</div>
`;
} else if (actionPayload.type === 'RULES_EDITOR') {
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
const editorId = 'rules-editor-' + Date.now();
payloadHtml = `
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
<span><i class="fa-solid fa-book-bookmark text-emerald-600 mr-1"></i> Редактор базы знаний и правил компании:</span>
<span class="text-[11px] text-slate-400 font-normal">Прямое изменение правил кадрового арбитража</span>
</div>
<textarea id="${editorId}" rows="12"
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
<div class="flex items-center justify-end gap-2 pt-1">
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
<button type="button" onclick="window.submitRulesDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
<i class="fa-solid fa-eye text-xs"></i>
<span>Показать превью изменений</span>
</button>
</div>
</div>
`;
} else if (actionPayload.type === 'PROMPT_PREVIEW') {
isHtmlBody = true;
}
}
const isHtmlBody = actionPayload && actionPayload.type === 'PROMPT_PREVIEW';
let buttonsHtml = '';
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
@@ -295,22 +172,6 @@ function appendAssistantMessage(text, buttons = [], actionPayload = null) {
container.insertAdjacentHTML("beforeend", html);
}
window.filterInspectTable = function(tableId, query) {
const table = document.getElementById(tableId);
if (!table) return;
const q = (query || '').trim().toLowerCase();
const rows = table.querySelectorAll('.inspect-row');
rows.forEach(r => {
const fio = r.getAttribute('data-fio') || '';
const dept = r.getAttribute('data-dept') || '';
if (!q || fio.includes(q) || dept.includes(q)) {
r.classList.remove('hidden');
} else {
r.classList.add('hidden');
}
});
};
window.sendChatAction = function(actionText) {
if (!actionText || !actionText.trim()) return;
const input = document.getElementById("user-input");
@@ -321,36 +182,6 @@ window.sendChatAction = function(actionText) {
window.sendMessage();
};
window.submitPromptDraftToDiff = function(editorId) {
const textarea = document.getElementById(editorId);
if (!textarea) return;
const newText = textarea.value.trim();
if (!newText) {
alert("Текст системного промпта не может быть пустым");
return;
}
const command = `action:save_draft_prompt:::${newText}`;
const input = document.getElementById("user-input");
if (input) input.value = command;
window.sendMessage();
};
window.submitRulesDraftToDiff = function(editorId) {
const textarea = document.getElementById(editorId);
if (!textarea) return;
const newText = textarea.value.trim();
if (!newText) {
alert("Правила не могут быть пустыми");
return;
}
const command = `action:save_draft_rules:::${newText}`;
const input = document.getElementById("user-input");
if (input) input.value = command;
window.sendMessage();
};
window.sendMessage = async function() {
const input = document.getElementById("user-input");
if (!input) return;
@@ -369,7 +200,10 @@ window.sendMessage = async function() {
input.style.webkitMaskImage = 'none';
window.clearAttachedFile();
// 1. Отрисовка сообщения пользователя в ленте
const activeSessionId = (window.TopicsManager && typeof window.TopicsManager.getActiveSessionId === "function")
? window.TopicsManager.getActiveSessionId()
: "session_main";
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
appendUserMessage(
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
@@ -379,10 +213,7 @@ window.sendMessage = async function() {
appendUserMessage("Сформировать предпросмотр изменений");
}
// 2. Вставка лоадера
const loadingId = appendAssistantLoading();
// 3. Вызов точного скролла
scrollToUserMessageTop();
try {
@@ -391,13 +222,11 @@ window.sendMessage = async function() {
const formData = new FormData();
formData.append("file", fileToSend);
formData.append("message", messageText);
formData.append("session_id", "web_session_main");
formData.append("session_id", activeSessionId);
res = await fetch("/api/v1/chat/upload", {
method: "POST",
headers: {
"Authorization": AuthManager.getAuthHeaders()["Authorization"]
},
headers: { "Authorization": AuthManager.getAuthHeaders()["Authorization"] },
body: formData
});
@@ -407,7 +236,7 @@ window.sendMessage = async function() {
headers: AuthManager.getAuthHeaders(),
body: JSON.stringify({
message: messageText || `Загружен файл: ${fileToSend.name}`,
session_id: "web_session_main"
session_id: activeSessionId
})
});
}
@@ -417,7 +246,7 @@ window.sendMessage = async function() {
headers: AuthManager.getAuthHeaders(),
body: JSON.stringify({
message: messageText,
session_id: "web_session_main"
session_id: activeSessionId
})
});
}
@@ -436,6 +265,14 @@ window.sendMessage = async function() {
if (window.SidebarManager) {
SidebarManager.renderContent();
}
if (window.TopicsManager && typeof window.TopicsManager.loadTopics === "function") {
window.TopicsManager.loadTopics();
// ⭐️ Повторный запрос через 2.5 сек, когда фоновая LLM завершит суммаризацию заголовка:
setTimeout(() => {
window.TopicsManager.loadTopics();
}, 2500);
}
} else {
const err = await res.json().catch(() => ({}));
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
@@ -542,13 +379,10 @@ document.addEventListener("DOMContentLoaded", () => {
}
let dragCounter = 0;
window.addEventListener('dragenter', (e) => {
e.preventDefault();
dragCounter++;
if (overlay) {
overlay.classList.remove('hidden');
}
if (overlay) overlay.classList.remove('hidden');
}, false);
window.addEventListener('dragleave', (e) => {
@@ -556,26 +390,19 @@ document.addEventListener("DOMContentLoaded", () => {
dragCounter--;
if (dragCounter <= 0) {
dragCounter = 0;
if (overlay) {
overlay.classList.add('hidden');
}
if (overlay) overlay.classList.add('hidden');
}
}, false);
window.addEventListener('dragover', (e) => {
e.preventDefault();
}, false);
window.addEventListener('dragover', (e) => { e.preventDefault(); }, false);
window.addEventListener('drop', (e) => {
e.preventDefault();
dragCounter = 0;
if (overlay) {
overlay.classList.add('hidden');
}
if (overlay) overlay.classList.add('hidden');
const dt = e.dataTransfer;
if (dt && dt.files && dt.files[0]) {
handleFileSelected(dt.files[0]);
}
}, false);
});
});
+286
View File
@@ -0,0 +1,286 @@
/**
* ===============================================================================
* FILE: modules/web_api/static/js/chat/topics.js
* ROLE: Управление списком сессий чатов (до 15), мгновенный "Новый чат"
* и стильное встроенное подтверждение удаления без alert/confirm.
* ===============================================================================
*/
window.TopicsManager = (function() {
let activeSessionId = localStorage.getItem("scud_active_chat_session") || "session_main";
let sessionsCache = [];
let pendingDeleteSessionId = null;
function getActiveSessionId() {
return activeSessionId;
}
async function init() {
await loadTopics();
await loadTopicHistory(activeSessionId);
}
async function loadTopics() {
const container = document.getElementById("topics-list-container");
const badge = document.getElementById("topics-count-badge");
if (!container) return;
try {
const res = await fetch("/api/v1/chat/sessions", {
headers: AuthManager.getAuthHeaders()
});
if (!res.ok) {
if (res.status === 401) return;
container.innerHTML = `<div class="p-3 text-xs text-rose-500 text-center">Ошибка загрузки чатов (${res.status})</div>`;
return;
}
const data = await res.json();
sessionsCache = data.sessions || [];
if (sessionsCache.length === 0) {
await createDefaultTopic();
return;
}
const exists = sessionsCache.some(s => s.id === activeSessionId);
if (!exists && sessionsCache.length > 0) {
activeSessionId = sessionsCache[0].id;
localStorage.setItem("scud_active_chat_session", activeSessionId);
}
if (badge) {
badge.innerText = `${sessionsCache.length}/15`;
}
renderTopicsList();
} catch (err) {
console.error("Ошибка загрузки списка чатов:", err);
container.innerHTML = `<div class="p-3 text-xs text-rose-500 text-center">Ошибка соединения с сервером</div>`;
}
}
async function createDefaultTopic() {
try {
const res = await fetch("/api/v1/chat/sessions", {
method: "POST",
headers: {
...AuthManager.getAuthHeaders(),
"Content-Type": "application/json"
},
body: JSON.stringify({
session_id: "session_main",
title: "Основной чат"
})
});
if (res.ok) {
activeSessionId = "session_main";
localStorage.setItem("scud_active_chat_session", activeSessionId);
await loadTopics();
}
} catch (e) {
console.error("Не удалось создать базовый чат:", e);
}
}
function renderTopicsList() {
const container = document.getElementById("topics-list-container");
if (!container) return;
if (sessionsCache.length === 0) {
container.innerHTML = `<div class="p-4 text-xs text-slate-400 text-center">Нет активных чатов</div>`;
return;
}
container.innerHTML = sessionsCache.map(session => {
const isActive = session.id === activeSessionId;
const activeClasses = isActive
? "bg-indigo-50 border-indigo-200 text-indigo-900 shadow-xs"
: "bg-white hover:bg-slate-50 border-slate-200 text-slate-700";
const title = escapeHtml(session.title || "Новый чат");
const timeStr = session.updated_at ? (session.updated_at.split(" ")[1] || "").slice(0, 5) : "";
return `
<div class="topic-item group flex items-center justify-between p-2.5 rounded-xl border transition cursor-pointer ${activeClasses}"
onclick="window.TopicsManager.switchTopic('${session.id}')">
<div class="flex items-start gap-2.5 min-w-0 flex-1 pr-1">
<i class="fa-solid fa-message text-xs ${isActive ? 'text-indigo-600' : 'text-slate-400'} shrink-0 mt-1"></i>
<div class="min-w-0 flex-1">
<div class="text-xs font-semibold leading-snug text-slate-800 break-words"
title="${title}"
style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; word-break: break-word;">
${title}
</div>
<div class="text-[10px] text-slate-400 flex items-center gap-1.5 mt-1">
${timeStr ? `<span>${timeStr}</span>` : '<span>Недавно</span>'}
</div>
</div>
</div>
<button type="button"
onclick="event.stopPropagation(); window.TopicsManager.askDeleteTopic('${session.id}', '${escapeHtml(title)}')"
class="opacity-0 group-hover:opacity-100 p-1 text-slate-400 hover:text-rose-600 rounded transition shrink-0"
title="Удалить чат">
<i class="fa-solid fa-trash-can text-xs"></i>
</button>
</div>
`;
}).join("");
}
async function switchTopic(sessionId) {
if (!sessionId || sessionId === activeSessionId) return;
activeSessionId = sessionId;
localStorage.setItem("scud_active_chat_session", activeSessionId);
renderTopicsList();
await loadTopicHistory(sessionId);
}
async function loadTopicHistory(sessionId) {
const container = document.getElementById("chat-messages-container");
if (!container) return;
container.innerHTML = `
<div class="flex items-center justify-center py-12 text-xs text-slate-400 gap-2">
<i class="fa-solid fa-spinner fa-spin text-indigo-600 text-sm"></i>
<span>Загрузка сообщений...</span>
</div>
`;
try {
const res = await fetch(`/api/v1/chat/history?session_id=${encodeURIComponent(sessionId)}&limit=50`, {
headers: AuthManager.getAuthHeaders()
});
if (res.ok) {
const data = await res.json();
const history = data.history || [];
container.innerHTML = "";
container.insertAdjacentHTML("beforeend", `
<div class="flex gap-3 max-w-4xl mx-auto w-full">
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
<i class="fa-solid fa-robot text-sm"></i>
</div>
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
<div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
<div class="text-sm text-slate-700 leading-relaxed">
Чат готов к работе. Вы можете задать вопрос по кадровому аудиту, сформировать срез или прикрепить документ.
</div>
</div>
</div>
`);
for (const msg of history) {
if (msg.role === "user") {
appendUserMessage(msg.content);
} else if (msg.role === "assistant") {
appendAssistantMessage(msg.content);
}
}
container.scrollTop = container.scrollHeight;
} else {
container.innerHTML = `<div class="p-4 text-center text-xs text-rose-500">Не удалось загрузить историю диалога</div>`;
}
} catch (e) {
console.error("Ошибка загрузки истории сообщений:", e);
container.innerHTML = `<div class="p-4 text-center text-xs text-rose-500">Ошибка соединения при загрузке истории</div>`;
}
}
async function createNewTopic() {
if (sessionsCache.length >= 15) {
alert("Достигнут лимит параллельных диалогов (максимум 15 чатов). Удалите неактуальные чаты.");
return;
}
const newSessionId = `chat_${Date.now().toString(36)}`;
try {
const res = await fetch("/api/v1/chat/sessions", {
method: "POST",
headers: {
...AuthManager.getAuthHeaders(),
"Content-Type": "application/json"
},
body: JSON.stringify({
session_id: newSessionId,
title: "Новый чат"
})
});
if (res.ok) {
activeSessionId = newSessionId;
localStorage.setItem("scud_active_chat_session", activeSessionId);
await loadTopics();
await loadTopicHistory(activeSessionId);
const input = document.getElementById("user-input");
if (input) input.focus();
}
} catch (err) {
console.error("Ошибка создания чата:", err);
}
}
function askDeleteTopic(sessionId, title) {
pendingDeleteSessionId = sessionId;
const modal = document.getElementById("confirm-modal");
const msgEl = document.getElementById("confirm-modal-message");
if (msgEl) msgEl.innerText = `Удалить диалог «${title}» и всю историю сообщений?`;
if (modal) modal.classList.remove("hidden");
}
function hideDeleteModal() {
pendingDeleteSessionId = null;
const modal = document.getElementById("confirm-modal");
if (modal) modal.classList.add("hidden");
}
async function executeDeleteTopic() {
if (!pendingDeleteSessionId) return;
const sessionId = pendingDeleteSessionId;
hideDeleteModal();
try {
const res = await fetch(`/api/v1/chat/sessions/${encodeURIComponent(sessionId)}`, {
method: "DELETE",
headers: AuthManager.getAuthHeaders()
});
if (res.ok) {
sessionsCache = sessionsCache.filter(s => s.id !== sessionId);
if (activeSessionId === sessionId) {
activeSessionId = sessionsCache.length > 0 ? sessionsCache[0].id : "session_main";
localStorage.setItem("scud_active_chat_session", activeSessionId);
await loadTopicHistory(activeSessionId);
}
await loadTopics();
}
} catch (e) {
console.error("Ошибка удаления чата:", e);
}
}
// ⭐️ Делегирование событий на document: срабатывает всегда, даже если модалка загрузилась позже!
document.addEventListener("click", (e) => {
if (e.target.closest("#confirm-modal-btn-cancel")) {
hideDeleteModal();
} else if (e.target.closest("#confirm-modal-btn-ok")) {
executeDeleteTopic();
}
});
return {
init,
loadTopics,
getActiveSessionId,
switchTopic,
createNewTopic,
askDeleteTopic
};
})();