feat(llm): двухфазный жизненный цикл сессий, двусторонний Diff, Topic Drift Guard и актуализация документации
This commit is contained in:
@@ -1,568 +0,0 @@
|
||||
/**
|
||||
===============================================================================
|
||||
FILE: modules/web_api/static/js/chat.js
|
||||
ROLE: Клиентский интерфейс диалога, Drag-and-Drop вложений, генерация динамических
|
||||
кнопок подтверждений и блокировка ввода при активном действии.
|
||||
===============================================================================
|
||||
*/
|
||||
|
||||
function updateInputHeight(el) {
|
||||
if (!el) return;
|
||||
el.style.height = "24px";
|
||||
const newHeight = Math.min(el.scrollHeight, 120);
|
||||
el.style.height = newHeight + "px";
|
||||
}
|
||||
|
||||
let selectedFile = null;
|
||||
|
||||
function handleFileSelect(e) {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
if (file.size > 15 * 1024 * 1024) {
|
||||
alert("Файл слишком большой. Максимальный размер: 15 МБ");
|
||||
e.target.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
selectedFile = file;
|
||||
const fileNameEl = document.getElementById("file-name-display");
|
||||
const fileSizeEl = document.getElementById("file-size-display");
|
||||
const previewContainer = document.getElementById("file-preview-container");
|
||||
|
||||
if (fileNameEl) fileNameEl.innerText = file.name;
|
||||
if (fileSizeEl) fileSizeEl.innerText = `(${(file.size / 1024).toFixed(1)} KB)`;
|
||||
if (previewContainer) previewContainer.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function clearAttachedFile() {
|
||||
selectedFile = null;
|
||||
const fileInput = document.getElementById("file-input");
|
||||
const previewContainer = document.getElementById("file-preview-container");
|
||||
if (fileInput) fileInput.value = "";
|
||||
if (previewContainer) previewContainer.classList.add("hidden");
|
||||
}
|
||||
|
||||
function setInputLocked(isLocked) {
|
||||
const input = document.getElementById("user-input");
|
||||
const sendBtn = document.getElementById("send-btn");
|
||||
if (input) {
|
||||
input.disabled = isLocked;
|
||||
if (isLocked) {
|
||||
input.placeholder = "Выберите действие с помощью кнопок выше...";
|
||||
input.classList.add("cursor-not-allowed", "opacity-60");
|
||||
} else {
|
||||
input.placeholder = "Команда, вопрос или перетащите файл сюда...";
|
||||
input.classList.remove("cursor-not-allowed", "opacity-60");
|
||||
}
|
||||
}
|
||||
if (sendBtn) {
|
||||
sendBtn.disabled = isLocked;
|
||||
if (isLocked) {
|
||||
sendBtn.classList.add("opacity-40", "cursor-not-allowed");
|
||||
} else {
|
||||
sendBtn.classList.remove("opacity-40", "cursor-not-allowed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function disableAllActionButtons() {
|
||||
const allBtnContainers = document.querySelectorAll(".action-buttons-container");
|
||||
allBtnContainers.forEach(container => {
|
||||
container.querySelectorAll("button").forEach(btn => {
|
||||
btn.disabled = true;
|
||||
btn.classList.add("opacity-40", "cursor-not-allowed");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function handleActionButtonClick(text) {
|
||||
disableAllActionButtons();
|
||||
setInputLocked(false);
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) {
|
||||
input.value = text;
|
||||
sendMessage();
|
||||
}
|
||||
}
|
||||
|
||||
// --- [INTERACTIVE TASK WIDGET] ---
|
||||
let activeWidgetTasksMap = new Map();
|
||||
|
||||
function renderTaskItemsHtml(tasks, filterStatus) {
|
||||
const filtered = tasks.filter(t => {
|
||||
if (filterStatus === "ALL") return true;
|
||||
return t.status === filterStatus;
|
||||
});
|
||||
|
||||
if (filtered.length === 0) {
|
||||
const label = filterStatus === 'BACKLOG' ? 'В планах' : filterStatus === 'IN_PROGRESS' ? 'В работе' : filterStatus === 'COMPLETED' ? 'Завершенные' : 'Все';
|
||||
return `<div class="text-slate-400 text-xs py-4 text-center">Нет задач со статусом «${label}»</div>`;
|
||||
}
|
||||
|
||||
return filtered.map(t => {
|
||||
const isDone = t.status === "COMPLETED";
|
||||
const isProgress = t.status === "IN_PROGRESS";
|
||||
const checkedAttr = isDone ? "checked" : "";
|
||||
const textClass = isDone ? "line-through text-slate-400" : "text-slate-800 font-medium";
|
||||
|
||||
let statusPill = `<span class="text-[10px] bg-slate-100 text-slate-600 px-2 py-0.5 rounded border border-slate-200">В планах</span>`;
|
||||
if (isDone) {
|
||||
statusPill = `<span class="text-[10px] bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded border border-emerald-300 font-semibold">Завершено</span>`;
|
||||
} else if (isProgress) {
|
||||
statusPill = `<span class="text-[10px] bg-amber-50 text-amber-700 px-2 py-0.5 rounded border border-amber-300 font-semibold">В работе</span>`;
|
||||
}
|
||||
|
||||
let prioPill = "";
|
||||
if (t.priority === "HIGH") {
|
||||
prioPill = `<span class="text-[9px] bg-red-50 text-red-700 font-bold px-1.5 py-0.5 rounded border border-red-200 uppercase">HIGH</span>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="flex items-center justify-between p-2.5 bg-slate-50 hover:bg-slate-100/80 rounded-xl border border-slate-200 transition gap-2" id="widget-task-${t.task_id}">
|
||||
<div class="flex items-center gap-2.5 flex-1 min-w-0">
|
||||
<input type="checkbox" ${checkedAttr} onchange="toggleTaskStatusInline('${t.task_id}', this.checked)"
|
||||
class="w-4 h-4 text-indigo-600 rounded border-slate-300 focus:ring-indigo-500 cursor-pointer">
|
||||
<div class="flex flex-col min-w-0 flex-1">
|
||||
<div class="flex items-center gap-1.5 mb-0.5">
|
||||
<span class="font-mono text-[11px] font-bold text-slate-700">${t.task_id}</span>
|
||||
${prioPill}
|
||||
${statusPill}
|
||||
</div>
|
||||
<span class="text-xs ${textClass} truncate leading-tight">${escapeHtml(t.title)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onclick="deleteTaskInline('${t.task_id}')" class="text-slate-400 hover:text-red-500 p-1.5 transition rounded-lg hover:bg-red-50" title="Удалить задачу">
|
||||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function renderInteractiveTaskCard(tasks) {
|
||||
if (!tasks || !Array.isArray(tasks)) return "";
|
||||
const widgetId = "task_widget_" + Date.now();
|
||||
activeWidgetTasksMap.set(widgetId, { tasks: tasks, filter: "ALL" });
|
||||
|
||||
const itemsHtml = renderTaskItemsHtml(tasks, "ALL");
|
||||
|
||||
return `
|
||||
<div class="task-widget-card mt-3 bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm space-y-3" id="${widgetId}">
|
||||
<div class="flex items-center gap-1 pb-2 border-b border-slate-100 overflow-x-auto no-scrollbar text-xs font-semibold">
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'ALL', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-600 font-bold border border-indigo-200">Все</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'IN_PROGRESS', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">В работе</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'BACKLOG', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">В планах</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'COMPLETED', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">Завершенные</button>
|
||||
</div>
|
||||
|
||||
<div class="widget-items-container space-y-2 max-h-72 overflow-y-auto pr-1">
|
||||
${itemsHtml}
|
||||
</div>
|
||||
|
||||
<div class="pt-2 border-t border-slate-100 flex items-center gap-2">
|
||||
<input type="text" placeholder="Новая задача..." class="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs text-slate-800 focus:outline-none focus:border-indigo-600 focus:bg-white transition" onkeydown="if(event.key==='Enter') addTaskInline('${widgetId}', this)">
|
||||
<button type="button" onclick="addTaskInline('${widgetId}', this.previousElementSibling)" class="bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white px-3 py-1.5 rounded-xl text-xs font-semibold shadow-sm transition flex items-center gap-1">
|
||||
<i class="fa-solid fa-plus text-[10px]"></i> Добавить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function filterTaskWidget(widgetId, status, btnEl) {
|
||||
const state = activeWidgetTasksMap.get(widgetId);
|
||||
if (!state) return;
|
||||
state.filter = status;
|
||||
|
||||
const widgetEl = document.getElementById(widgetId);
|
||||
if (!widgetEl) return;
|
||||
|
||||
widgetEl.querySelectorAll(".widget-tab-btn").forEach(b => {
|
||||
b.className = "widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700";
|
||||
});
|
||||
btnEl.className = "widget-tab-btn px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-600 font-bold border border-indigo-200";
|
||||
|
||||
const container = widgetEl.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, status);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleTaskStatusInline(taskId, isChecked) {
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const newStatus = isChecked ? "COMPLETED" : "BACKLOG";
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${taskId}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
for (let [wId, state] of activeWidgetTasksMap.entries()) {
|
||||
const targetTask = state.tasks.find(t => t.task_id === taskId);
|
||||
if (targetTask) {
|
||||
targetTask.status = newStatus;
|
||||
const widgetEl = document.getElementById(wId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Patch Error]", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteTaskInline(taskId) {
|
||||
if (!confirm(`Удалить задачу ${taskId}?`)) return;
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${taskId}`, {
|
||||
method: "DELETE",
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
for (let [wId, state] of activeWidgetTasksMap.entries()) {
|
||||
state.tasks = state.tasks.filter(t => t.task_id !== taskId);
|
||||
const widgetEl = document.getElementById(wId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter);
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Delete Error]", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function addTaskInline(widgetId, inputEl) {
|
||||
if (!inputEl) return;
|
||||
const title = inputEl.value.trim();
|
||||
if (!title) return;
|
||||
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/tasks", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ title: title, priority: "MEDIUM", module: "general" })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
inputEl.value = "";
|
||||
const tasksRes = await fetch("/api/v1/tasks", {
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
});
|
||||
const updatedTasks = await tasksRes.json();
|
||||
|
||||
const state = activeWidgetTasksMap.get(widgetId);
|
||||
if (state) {
|
||||
state.tasks = updatedTasks;
|
||||
const widgetEl = document.getElementById(widgetId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(updatedTasks, state.filter);
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Add Error]", err);
|
||||
}
|
||||
}
|
||||
|
||||
// --- [CHAT SEND PIPELINE] ---
|
||||
async function sendMessage(e) {
|
||||
if (e && e.preventDefault) e.preventDefault();
|
||||
|
||||
const input = document.getElementById("user-input");
|
||||
const chatWindow = document.getElementById("chat-window");
|
||||
const sendBtn = document.getElementById("send-btn");
|
||||
|
||||
if (!input || !chatWindow) return;
|
||||
const text = input.value.trim();
|
||||
|
||||
if (!text && !selectedFile) return;
|
||||
|
||||
disableAllActionButtons();
|
||||
|
||||
let userDisplayHtml = escapeHtml(text);
|
||||
if (selectedFile) {
|
||||
userDisplayHtml = `<div class="font-bold border-b border-indigo-400/40 pb-1 mb-1 text-[11px] flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-file"></i> ${escapeHtml(selectedFile.name)}
|
||||
</div>` + userDisplayHtml;
|
||||
}
|
||||
|
||||
const userMsgHtml = `
|
||||
<div class="flex justify-end mb-3">
|
||||
<div class="bg-indigo-600 text-white rounded-2xl px-4 py-2.5 max-w-2xl text-xs sm:text-sm shadow-sm">
|
||||
${userDisplayHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
chatWindow.insertAdjacentHTML("beforeend", userMsgHtml);
|
||||
|
||||
input.value = "";
|
||||
updateInputHeight(input);
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
|
||||
if (sendBtn) {
|
||||
sendBtn.disabled = true;
|
||||
sendBtn.classList.add("opacity-50");
|
||||
}
|
||||
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const isGuest = typeof IS_GUEST !== 'undefined' ? IS_GUEST : (localStorage.getItem("scud_is_guest") === "true");
|
||||
|
||||
const endpoint = isGuest ? "/api/v1/chat/guest" : "/api/v1/chat";
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("session_id", "web_session_main");
|
||||
formData.append("message", text || "Проанализируй прикрепленный файл");
|
||||
|
||||
if (selectedFile instanceof File) {
|
||||
formData.append("file", selectedFile, selectedFile.name);
|
||||
}
|
||||
|
||||
const headers = {};
|
||||
if (!isGuest && token) {
|
||||
headers["Authorization"] = "Bearer " + token;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (res.status === 401 && !isGuest) {
|
||||
if (typeof logout === 'function') logout();
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const assistantTitle = isGuest ? "Локальная нейросеть (Гость)" : "ИИ-Ассистент SCUD Orion AI";
|
||||
const replyText = data.reply || "Пустой ответ от нейросети";
|
||||
|
||||
let actionButtonsHtml = "";
|
||||
const actionData = data.action_type || data.action;
|
||||
|
||||
if (actionData && actionData.buttons && actionData.buttons.length > 0) {
|
||||
const buttonsMarkup = actionData.buttons.map(btn => {
|
||||
let btnClasses = "bg-slate-100 hover:bg-slate-200 active:bg-slate-300 text-slate-700 border border-slate-300";
|
||||
let iconMarkup = '<i class="fa-solid fa-arrow-right text-[10px] opacity-60"></i>';
|
||||
|
||||
const labelLower = (btn.label || "").toLowerCase();
|
||||
const isPrimary = btn.style === "primary" || labelLower.includes("подтверд") || labelLower.startsWith("да");
|
||||
const isDanger = btn.style === "danger" || labelLower.includes("отмен") || labelLower.startsWith("нет") || labelLower.includes("законч") || labelLower.includes("заверш");
|
||||
|
||||
if (isPrimary) {
|
||||
btnClasses = "bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white shadow-sm";
|
||||
iconMarkup = '<i class="fa-solid fa-check"></i>';
|
||||
} else if (isDanger) {
|
||||
btnClasses = "bg-rose-50 hover:bg-rose-100 active:bg-rose-200 text-rose-700 border border-rose-300";
|
||||
iconMarkup = '<i class="fa-solid fa-xmark"></i>';
|
||||
}
|
||||
|
||||
return `
|
||||
<button type="button" onclick="handleActionButtonClick('${escapeHtml(btn.value)}')"
|
||||
class="${btnClasses} font-semibold px-3 py-1.5 rounded-xl text-xs flex items-center gap-1.5 transition cursor-pointer">
|
||||
${iconMarkup}
|
||||
<span>${escapeHtml(btn.label)}</span>
|
||||
</button>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
actionButtonsHtml = `
|
||||
<div class="action-buttons-container flex flex-wrap items-center gap-2 mt-3 pt-2.5 border-t border-slate-100">
|
||||
${buttonsMarkup}
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Если выведены кнопки подтверждения превью — блокируем ввод с клавиатуры
|
||||
if (actionData.type === "PROMPT_PREVIEW") {
|
||||
setInputLocked(true);
|
||||
} else {
|
||||
setInputLocked(false);
|
||||
}
|
||||
} else {
|
||||
setInputLocked(false);
|
||||
}
|
||||
|
||||
let interactiveWidgetHtml = "";
|
||||
if (actionData && actionData.type === "TASK_INTERACTIVE_CARD" && Array.isArray(actionData.tasks)) {
|
||||
interactiveWidgetHtml = renderInteractiveTaskCard(actionData.tasks);
|
||||
}
|
||||
|
||||
const botMsgHtml = `
|
||||
<div class="bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm max-w-2xl mb-3">
|
||||
<p class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">
|
||||
<i class="fa-solid fa-robot mr-1"></i> ${assistantTitle}
|
||||
</p>
|
||||
<p class="text-slate-800 text-xs sm:text-sm whitespace-pre-wrap leading-relaxed">${escapeHtml(replyText)}</p>
|
||||
${interactiveWidgetHtml}
|
||||
${actionButtonsHtml}
|
||||
</div>
|
||||
`;
|
||||
chatWindow.insertAdjacentHTML("beforeend", botMsgHtml);
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
|
||||
clearAttachedFile();
|
||||
|
||||
if (!isGuest && typeof loadTasks === 'function') {
|
||||
loadTasks();
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("[Chat Error]", err);
|
||||
const errorHtml = `
|
||||
<div class="bg-red-50 border border-red-200 rounded-2xl p-3.5 max-w-2xl text-red-700 text-xs sm:text-sm mb-3">
|
||||
Ошибка связи с сервером.
|
||||
</div>
|
||||
`;
|
||||
chatWindow.insertAdjacentHTML("beforeend", errorHtml);
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
setInputLocked(false);
|
||||
} finally {
|
||||
if (sendBtn && !document.getElementById("user-input")?.disabled) {
|
||||
sendBtn.disabled = false;
|
||||
sendBtn.classList.remove("opacity-50");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const input = document.getElementById("user-input");
|
||||
const dropZone = document.getElementById("chat-window")?.parentElement;
|
||||
const dropOverlay = document.getElementById("drop-overlay");
|
||||
|
||||
if (input) {
|
||||
let historyIndex = -1;
|
||||
let localHistory = JSON.parse(localStorage.getItem("scud_chat_input_history") || "[]");
|
||||
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (input.disabled) return;
|
||||
const text = input.value.trim();
|
||||
if (text) {
|
||||
if (localHistory.length === 0 || localHistory[0] !== text) {
|
||||
localHistory.unshift(text);
|
||||
if (localHistory.length > 50) localHistory.pop();
|
||||
localStorage.setItem("scud_chat_input_history", JSON.stringify(localHistory));
|
||||
}
|
||||
historyIndex = -1;
|
||||
}
|
||||
sendMessage(e);
|
||||
updateInputHeight(input);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
const textBeforeCursor = input.value.substring(0, input.selectionStart);
|
||||
const isFirstLine = !textBeforeCursor.includes("\n");
|
||||
|
||||
if (isFirstLine && input.selectionStart === 0 && localHistory.length > 0) {
|
||||
if (historyIndex < localHistory.length - 1) {
|
||||
e.preventDefault();
|
||||
if (historyIndex === -1) {
|
||||
input.dataset.draft = input.value;
|
||||
}
|
||||
historyIndex++;
|
||||
input.value = localHistory[historyIndex];
|
||||
updateInputHeight(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === "ArrowDown") {
|
||||
const textAfterCursor = input.value.substring(input.selectionEnd);
|
||||
const isLastLine = !textAfterCursor.includes("\n");
|
||||
|
||||
if (isLastLine && input.selectionEnd === input.value.length && historyIndex >= 0) {
|
||||
e.preventDefault();
|
||||
if (historyIndex > 0) {
|
||||
historyIndex--;
|
||||
input.value = localHistory[historyIndex];
|
||||
} else {
|
||||
historyIndex = -1;
|
||||
input.value = input.dataset.draft || "";
|
||||
}
|
||||
updateInputHeight(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (dropZone && dropOverlay) {
|
||||
["dragenter", "dragover", "dragleave", "drop"].forEach(eventName => {
|
||||
dropZone.addEventListener(eventName, (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}, false);
|
||||
});
|
||||
|
||||
["dragenter", "dragover"].forEach(eventName => {
|
||||
dropZone.addEventListener(eventName, () => {
|
||||
dropOverlay.classList.remove("hidden");
|
||||
dropOverlay.classList.add("flex");
|
||||
}, false);
|
||||
});
|
||||
|
||||
["dragleave", "drop"].forEach(eventName => {
|
||||
dropZone.addEventListener(eventName, (e) => {
|
||||
if (eventName === "drop" || e.target === dropZone || !dropZone.contains(e.relatedTarget)) {
|
||||
dropOverlay.classList.add("hidden");
|
||||
dropOverlay.classList.remove("flex");
|
||||
}
|
||||
}, false);
|
||||
});
|
||||
|
||||
dropZone.addEventListener("drop", (e) => {
|
||||
const dt = e.dataTransfer;
|
||||
const files = dt.files;
|
||||
|
||||
if (files && files.length > 0) {
|
||||
const file = files[0];
|
||||
handleFileSelect({ target: { files: [file] } });
|
||||
|
||||
const fileInput = document.getElementById("file-input");
|
||||
if (fileInput) {
|
||||
const dataTransfer = new DataTransfer();
|
||||
dataTransfer.items.add(file);
|
||||
fileInput.files = dataTransfer.files;
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
});
|
||||
@@ -4,7 +4,7 @@ FILE: modules/web_api/static/js/chat/core.js
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / static / js / chat
|
||||
ROLE: Клиентский интерфейс диалога, Drag-and-Drop вложений, блокировка ввода
|
||||
при активных кнопках, вызов онлайн-редактора и отправка правок.
|
||||
при активных кнопках, динамический вызов инлайн-редактора и двусторонний Diff.
|
||||
===============================================================================
|
||||
*/
|
||||
|
||||
@@ -79,11 +79,6 @@ function disableAllActionButtons() {
|
||||
}
|
||||
|
||||
function handleActionButtonClick(text) {
|
||||
if (text === "action:open_editor") {
|
||||
openInlinePromptEditor();
|
||||
return;
|
||||
}
|
||||
|
||||
disableAllActionButtons();
|
||||
setInputLocked(false);
|
||||
const input = document.getElementById("user-input");
|
||||
@@ -93,22 +88,123 @@ function handleActionButtonClick(text) {
|
||||
}
|
||||
}
|
||||
|
||||
function openInlinePromptEditor() {
|
||||
const editorContainer = document.getElementById("inline-prompt-editor-container");
|
||||
if (editorContainer) {
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
// --- [INLINE PROMPT EDITOR & FULL DIFF BUILDER] ---
|
||||
function openInlinePromptEditor(btnEl) {
|
||||
const cardContainer = btnEl.closest(".chat-message-card");
|
||||
if (!cardContainer) return;
|
||||
|
||||
const editorContainer = cardContainer.querySelector(".inline-prompt-editor-container");
|
||||
const diffView = cardContainer.querySelector(".prompt-preview-diff-view");
|
||||
const textarea = cardContainer.querySelector(".inline-prompt-textarea");
|
||||
|
||||
if (editorContainer && textarea) {
|
||||
editorContainer.classList.remove("hidden");
|
||||
const textarea = document.getElementById("inline-prompt-textarea");
|
||||
if (textarea) textarea.focus();
|
||||
|
||||
if (diffView) {
|
||||
const targetHeight = Math.max(diffView.offsetHeight, 320);
|
||||
textarea.style.height = `${targetHeight}px`;
|
||||
}
|
||||
|
||||
textarea.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function closeInlinePromptEditor() {
|
||||
const editorContainer = document.getElementById("inline-prompt-editor-container");
|
||||
function closeInlinePromptEditor(btnEl) {
|
||||
const cardContainer = btnEl.closest(".chat-message-card");
|
||||
if (!cardContainer) return;
|
||||
const editorContainer = cardContainer.querySelector(".inline-prompt-editor-container");
|
||||
if (editorContainer) editorContainer.classList.add("hidden");
|
||||
}
|
||||
|
||||
async function saveManualPromptDraft() {
|
||||
const textarea = document.getElementById("inline-prompt-textarea");
|
||||
function parsePromptIntoMap(text) {
|
||||
const map = new Map();
|
||||
if (!text) return map;
|
||||
const lines = text.split("\n");
|
||||
for (let line of lines) {
|
||||
let trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
const match = trimmed.match(/^(\d+)[\.\s]+(\d+)[\.\s\:\-]*(.*)$/);
|
||||
if (match) {
|
||||
const key = `${match[1]}.${match[2]}`;
|
||||
map.set(key, { sec: parseInt(match[1]), itm: parseInt(match[2]), content: match[3].trim(), full: trimmed });
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function buildHighlightedPromptHtml(newRawText, originalBaselineText) {
|
||||
const origMap = parsePromptIntoMap(originalBaselineText);
|
||||
const newMap = parsePromptIntoMap(newRawText);
|
||||
|
||||
const formattedLines = [];
|
||||
const rawLines = newRawText.split("\n");
|
||||
const handledNewKeys = new Set();
|
||||
|
||||
let currentSection = null;
|
||||
|
||||
for (let line of rawLines) {
|
||||
let trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
formattedLines.push("");
|
||||
continue;
|
||||
}
|
||||
|
||||
const secMatch = trimmed.match(/^(\d+)[\.\s\:\-]+([^\d].*)$/);
|
||||
const subMatch = trimmed.match(/^(\d+)[\.\s]+(\d+)[\.\s\:\-]*(.*)$/);
|
||||
|
||||
if (subMatch) {
|
||||
const key = `${subMatch[1]}.${subMatch[2]}`;
|
||||
handledNewKeys.add(key);
|
||||
currentSection = parseInt(subMatch[1]);
|
||||
const cleanContent = subMatch[3].trim();
|
||||
const fullItemStr = `${subMatch[1]}.${subMatch[2]}. ${cleanContent}`;
|
||||
|
||||
if (!origMap.has(key) || origMap.get(key).content !== cleanContent) {
|
||||
// Добавленный или изменённый пункт
|
||||
formattedLines.push(` <span class="text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300">${escapeHtml(fullItemStr)}</span>`);
|
||||
} else {
|
||||
formattedLines.push(` ${escapeHtml(fullItemStr)}`);
|
||||
}
|
||||
} else if (secMatch && !anyLower(secMatch[2].slice(0, 15))) {
|
||||
// Заголовок раздела
|
||||
currentSection = parseInt(secMatch[1]);
|
||||
formattedLines.push(escapeHtml(trimmed));
|
||||
} else {
|
||||
formattedLines.push(escapeHtml(trimmed));
|
||||
}
|
||||
}
|
||||
|
||||
// Добавляем удаленные пункты (были в оригинале, но отсутствуют в новом тексте)
|
||||
for (let [origKey, origObj] of origMap.entries()) {
|
||||
if (!handledNewKeys.has(origKey)) {
|
||||
const strikeMarkup = ` <span class="line-through text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300 opacity-80">${origKey}. ${escapeHtml(origObj.content)} [УДАЛЕНИЕ]</span>`;
|
||||
formattedLines.push(strikeMarkup);
|
||||
}
|
||||
}
|
||||
|
||||
return formattedLines.join("\n");
|
||||
}
|
||||
|
||||
function anyLower(str) {
|
||||
return /[а-яa-z]/.test(str);
|
||||
}
|
||||
|
||||
async function saveManualPromptDraft(btnEl) {
|
||||
const cardContainer = btnEl.closest(".chat-message-card");
|
||||
if (!cardContainer) return;
|
||||
|
||||
const textarea = cardContainer.querySelector(".inline-prompt-textarea");
|
||||
const previewTextEl = cardContainer.querySelector(".prompt-preview-diff-view");
|
||||
if (!textarea) return;
|
||||
|
||||
const newText = textarea.value.trim();
|
||||
@@ -130,28 +226,18 @@ async function saveManualPromptDraft() {
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
closeInlinePromptEditor();
|
||||
const previewTextEl = document.getElementById("prompt-preview-diff-view");
|
||||
closeInlinePromptEditor(btnEl);
|
||||
if (previewTextEl) {
|
||||
previewTextEl.innerText = newText;
|
||||
const baseline = cardContainer.dataset.originalBaseline || "";
|
||||
const highlightedHtml = buildHighlightedPromptHtml(newText, baseline);
|
||||
previewTextEl.innerHTML = highlightedHtml;
|
||||
}
|
||||
alert("✓ Правки сохранены в черновике! Нажмите «Подтвердить» для применения в БД.");
|
||||
}
|
||||
} catch (err) {
|
||||
alert("Ошибка сохранения черновика: " + err);
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
// --- [CHAT SEND PIPELINE] ---
|
||||
async function sendMessage(e) {
|
||||
if (e && e.preventDefault) e.preventDefault();
|
||||
@@ -250,8 +336,10 @@ async function sendMessage(e) {
|
||||
iconMarkup = '<i class="fa-solid fa-pen-to-square text-xs"></i>';
|
||||
}
|
||||
|
||||
const clickHandler = isEdit ? "openInlinePromptEditor(this)" : `handleActionButtonClick('${escapeHtml(btn.value)}')`;
|
||||
|
||||
return `
|
||||
<button type="button" onclick="handleActionButtonClick('${escapeHtml(btn.value)}')"
|
||||
<button type="button" onclick="${clickHandler}"
|
||||
class="${btnClasses} font-semibold px-3 py-1.5 rounded-xl text-xs flex items-center gap-1.5 transition cursor-pointer">
|
||||
${iconMarkup}
|
||||
<span>${escapeHtml(btn.label)}</span>
|
||||
@@ -265,21 +353,25 @@ async function sendMessage(e) {
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Блокируем ввод при наличии кнопок
|
||||
setInputLocked(true);
|
||||
} else {
|
||||
setInputLocked(false);
|
||||
}
|
||||
|
||||
let previewEditorHtml = "";
|
||||
if (actionData && actionData.type === "PROMPT_PREVIEW" && actionData.raw_draft) {
|
||||
let rawDraftText = "";
|
||||
let baselineText = "";
|
||||
|
||||
if (actionData && actionData.type === "PROMPT_PREVIEW") {
|
||||
rawDraftText = actionData.raw_draft || "";
|
||||
baselineText = actionData.baseline_prompt || rawDraftText;
|
||||
previewEditorHtml = `
|
||||
<div id="inline-prompt-editor-container" class="hidden mt-3 p-3 bg-slate-50 border border-slate-300 rounded-xl space-y-2">
|
||||
<div class="inline-prompt-editor-container hidden mt-3 p-3 bg-slate-50 border border-slate-300 rounded-xl space-y-2">
|
||||
<p class="text-[11px] font-bold text-slate-700 uppercase"><i class="fa-solid fa-pen-to-square mr-1"></i> Ручное редактирование текста промпта:</p>
|
||||
<textarea id="inline-prompt-textarea" rows="10" class="w-full bg-white border border-slate-300 rounded-lg p-2.5 text-xs font-mono text-slate-800 focus:outline-none focus:border-indigo-600">${escapeHtml(actionData.raw_draft)}</textarea>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button type="button" onclick="closeInlinePromptEditor()" class="px-3 py-1.5 rounded-lg text-xs text-slate-600 bg-slate-200 hover:bg-slate-300">Свернуть</button>
|
||||
<button type="button" onclick="saveManualPromptDraft()" class="px-3 py-1.5 rounded-lg text-xs font-semibold text-white bg-indigo-600 hover:bg-indigo-700 shadow-sm">Сохранить правки</button>
|
||||
<textarea class="inline-prompt-textarea w-full bg-white border border-slate-300 rounded-lg p-3 text-xs font-mono text-slate-800 focus:outline-none focus:border-indigo-600 resize-y shadow-inner leading-relaxed">${escapeHtml(rawDraftText)}</textarea>
|
||||
<div class="flex justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="closeInlinePromptEditor(this)" class="px-3 py-1.5 rounded-lg text-xs text-slate-600 bg-slate-200 hover:bg-slate-300 transition">Свернуть</button>
|
||||
<button type="button" onclick="saveManualPromptDraft(this)" class="px-3.5 py-1.5 rounded-lg text-xs font-semibold text-white bg-indigo-600 hover:bg-indigo-700 shadow-sm transition">Сохранить правки</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -291,11 +383,11 @@ async function sendMessage(e) {
|
||||
}
|
||||
|
||||
const botMsgHtml = `
|
||||
<div class="bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm max-w-2xl mb-3">
|
||||
<div class="chat-message-card bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm max-w-2xl mb-3" data-original-baseline="${escapeHtml(baselineText)}">
|
||||
<p class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">
|
||||
<i class="fa-solid fa-robot mr-1"></i> ${assistantTitle}
|
||||
</p>
|
||||
<div class="text-slate-800 text-xs sm:text-sm whitespace-pre-wrap leading-relaxed" id="prompt-preview-diff-view">${replyText}</div>
|
||||
<div class="prompt-preview-diff-view text-slate-800 text-xs sm:text-sm whitespace-pre-wrap leading-relaxed">${replyText}</div>
|
||||
${previewEditorHtml}
|
||||
${interactiveWidgetHtml}
|
||||
${actionButtonsHtml}
|
||||
|
||||
Reference in New Issue
Block a user