feat(chat): multi-session chat support (up to 15), human-like auto-titling, line-clamp titles and sorted registries
This commit is contained in:
@@ -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
|
||||
};
|
||||
})();
|
||||
Reference in New Issue
Block a user