feat(ui): срезы 1.2/1.3/1.6 — онбординг + стоп-кнопка + статус агента; +9 фиксов Fable
- 1.2 онбординг: приветствие + примеры-подсказки на пустом чате (клик подставляет в поле) - 1.3 стоп: кнопка «Отправить»↔«Стоп», AbortController, задержка 400мс от случайного прерывания - 1.6 статус: человеко-понятные подписи инструментов агента (verify/find/mcp→осмысленный текст) - Fable-фиксы: Enter/двойной клик не прерывают ответ; форма фидбека переоткрывается после стрим-перерисовки; newChat/switchChat тихо прерывают живой стрим; retry без гонки; финализация таблиц/ссылок и при обрыве; онбординг убирается любым сообщением; без пустого экрана при ошибке /api/history; без дублей POST фидбека - APP_VERSION 2026-07-17i
This commit is contained in:
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-07-17h"
|
||||
APP_VERSION = "2026-07-17i"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
|
||||
+111
-22
@@ -92,6 +92,14 @@ button { font-family: inherit; }
|
||||
.fb-actions { display: flex; gap: .4rem; }
|
||||
.fb-send, .fb-cancel { font-size: .78rem; padding: .25rem .7rem; border-radius: 6px; cursor: pointer; border: 1px solid var(--border); background: transparent; color: var(--text); }
|
||||
.fb-send { background: #4c5b9a; color: #fff; border-color: transparent; }
|
||||
#send-btn.is-stop { background: #b3402e; }
|
||||
#send-btn.is-stop:hover { background: #9a3626; }
|
||||
.onboarding { max-width: 640px; margin: 2rem auto; padding: 1.5rem; text-align: center; }
|
||||
.ob-title { font-size: 1.35rem; font-weight: 700; color: var(--text); margin-bottom: .4rem; }
|
||||
.ob-sub { font-size: .95rem; color: var(--text-light); margin-bottom: 1.1rem; }
|
||||
.ob-chips { display: flex; flex-wrap: wrap; gap: .5rem; justify-content: center; }
|
||||
.ob-chip { font-size: .88rem; padding: .5rem .85rem; border: 1.5px solid var(--border); border-radius: 999px; background: var(--bg-sunken); color: var(--text); cursor: pointer; transition: border-color .15s, background .15s; }
|
||||
.ob-chip:hover { border-color: var(--accent); background: var(--bg-card); }
|
||||
.msg-system { align-self: center; background: var(--system-bg); border: none; font-size: .8rem; color: var(--system-text); box-shadow: none; padding: .4rem .8rem; }
|
||||
.typing { align-self: flex-start; color: var(--text-light); font-style: italic; font-size: .85rem; padding: .4rem 0; }
|
||||
|
||||
@@ -273,7 +281,7 @@ html { color-scheme: light; }
|
||||
<div id="input-row">
|
||||
<button id="file-btn" onclick="document.getElementById('file-input').click()" title="Прикрепить файл">📎</button>
|
||||
<textarea id="msg-input" placeholder="Напишите сообщение..." rows="1" onkeydown="handleKey(event)"></textarea>
|
||||
<button id="send-btn" onclick="sendMessage()">Отправить</button>
|
||||
<button id="send-btn" onclick="onSendClick()">Отправить</button>
|
||||
</div>
|
||||
</div>
|
||||
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
||||
@@ -582,6 +590,21 @@ const API = '';
|
||||
let token = localStorage.getItem('token');
|
||||
let pendingFiles = [];
|
||||
let streaming = false;
|
||||
let abortCtrl = null; // срез 1.3: прерывание текущего ответа
|
||||
let streamStartedAt = 0;
|
||||
function setSendMode(streamingNow) {
|
||||
const b = document.getElementById('send-btn');
|
||||
if (!b) return;
|
||||
b.disabled = false;
|
||||
b.textContent = streamingNow ? 'Стоп' : 'Отправить';
|
||||
b.classList.toggle('is-stop', streamingNow);
|
||||
}
|
||||
// Клик по кнопке: отправка или стоп. Стоп с задержкой 400мс, чтобы случайный
|
||||
// двойной клик по «Отправить» не убивал только что отправленный запрос.
|
||||
function onSendClick() {
|
||||
if (streaming) { if (abortCtrl && (performance.now() - streamStartedAt) > 400) abortCtrl.abort(); }
|
||||
else sendMessage();
|
||||
}
|
||||
// crypto.randomUUID работает только в secure context (HTTPS / localhost),
|
||||
// под голым HTTP по IP его нет — используем fallback
|
||||
function genUUID() {
|
||||
@@ -649,8 +672,7 @@ async function doLogin(e) {
|
||||
localStorage.setItem('token', token);
|
||||
if (data.refresh_token) localStorage.setItem('refresh_token', data.refresh_token);
|
||||
checkAdmin();
|
||||
showChat();
|
||||
addMsg('system', 'Добро пожаловать! Напишите вопрос или прикрепите файл.');
|
||||
showChat(); // loadHistory сам покажет онбординг на пустом чате
|
||||
} catch {
|
||||
document.getElementById('login-error').style.display = 'block';
|
||||
}
|
||||
@@ -700,7 +722,46 @@ jumpBtn.style.display = 'none';
|
||||
jumpBtn.onclick = () => { msgs.scrollTop = msgs.scrollHeight; jumpBtn.style.display = 'none'; };
|
||||
document.body.appendChild(jumpBtn);
|
||||
msgs.addEventListener('scroll', () => { jumpBtn.style.display = isPinned() ? 'none' : 'flex'; });
|
||||
|
||||
// Онбординг (срез 1.2): приветствие + примеры-подсказки на пустом чате.
|
||||
// Клик по подсказке подставляет её в поле ввода. Убирается при первом сообщении.
|
||||
const ONBOARD_EXAMPLES = [
|
||||
'Проверь смету на ошибки',
|
||||
'Найди расценку ГЭСН по описанию работ',
|
||||
'Что такое накладные расходы и сметная прибыль?',
|
||||
'Сделай конъюнктурный анализ по прайсу',
|
||||
];
|
||||
function showOnboarding() {
|
||||
if (document.getElementById('onboarding')) return;
|
||||
if (msgs.querySelector('.msg-user, .msg-ai')) return; // уже есть реальный диалог
|
||||
const box = document.createElement('div');
|
||||
box.id = 'onboarding';
|
||||
box.className = 'onboarding';
|
||||
const h = document.createElement('div');
|
||||
h.className = 'ob-title';
|
||||
h.textContent = 'Чем помочь со сметой?';
|
||||
const sub = document.createElement('div');
|
||||
sub.className = 'ob-sub';
|
||||
sub.textContent = 'Задайте вопрос, прикрепите файл сметы или начните с примера:';
|
||||
box.appendChild(h); box.appendChild(sub);
|
||||
const chips = document.createElement('div');
|
||||
chips.className = 'ob-chips';
|
||||
ONBOARD_EXAMPLES.forEach(ex => {
|
||||
const c = document.createElement('button');
|
||||
c.type = 'button'; c.className = 'ob-chip'; c.textContent = ex;
|
||||
c.onclick = () => {
|
||||
const inp = document.getElementById('msg-input');
|
||||
inp.value = ex; inp.focus();
|
||||
inp.dispatchEvent(new Event('input')); // авто-высота textarea
|
||||
};
|
||||
chips.appendChild(c);
|
||||
});
|
||||
box.appendChild(chips);
|
||||
msgs.appendChild(box);
|
||||
}
|
||||
|
||||
function addMsg(type, text, ts) {
|
||||
const ob = document.getElementById('onboarding'); if (ob) ob.remove(); // любое сообщение убирает приветствие
|
||||
const div = document.createElement('div');
|
||||
div.className = 'msg msg-' + type;
|
||||
// Timestamp
|
||||
@@ -904,7 +965,8 @@ async function uploadFilesLegacy() {
|
||||
|
||||
// --- Send Message ---
|
||||
function handleKey(e) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
|
||||
// Enter отправляет, но НИКОГДА не прерывает идущий ответ (стоп — только кнопкой).
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (!streaming) sendMessage(); }
|
||||
}
|
||||
|
||||
// Честный текст ошибки по HTTP-статусу: констатируем факт + одно действие,
|
||||
@@ -924,16 +986,18 @@ function addErrorRetry(msg, retryText) {
|
||||
const btn = document.createElement('button');
|
||||
btn.textContent = 'Повторить';
|
||||
btn.className = 'retry-btn';
|
||||
btn.onclick = () => { div.remove(); runChat(retryText); };
|
||||
btn.onclick = () => { if (streaming) return; div.remove(); runChat(retryText); };
|
||||
div.appendChild(btn);
|
||||
}
|
||||
|
||||
// Инлайн-форма фидбека вместо prompt(): категория + текст, Esc закрывает, фокус в поле.
|
||||
function openFeedbackForm(btn, answerText) {
|
||||
if (btn._fbOpen) return;
|
||||
btn._fbOpen = true;
|
||||
// isConnected: если стрим-перерисовка снесла старую форму — разрешаем открыть заново
|
||||
// (иначе флаг «открыто» застревал бы навсегда, см. срез 1.5 fix).
|
||||
if (btn._fbForm && btn._fbForm.isConnected) return;
|
||||
const form = document.createElement('div');
|
||||
form.className = 'fb-form';
|
||||
btn._fbForm = form;
|
||||
form.innerHTML =
|
||||
'<div class="fb-cats">' +
|
||||
'<button type="button" class="fb-cat" data-c="Ответ неверный">Ответ неверный</button>' +
|
||||
@@ -948,10 +1012,13 @@ function openFeedbackForm(btn, answerText) {
|
||||
form.querySelectorAll('.fb-cat').forEach(x => x.classList.remove('sel'));
|
||||
c.classList.add('sel'); cat = c.dataset.c; ta.focus();
|
||||
});
|
||||
const close = () => { form.remove(); btn._fbOpen = false; };
|
||||
const close = () => { form.remove(); };
|
||||
form.querySelector('.fb-cancel').onclick = close;
|
||||
ta.addEventListener('keydown', e => { if (e.key === 'Escape') close(); });
|
||||
form.querySelector('.fb-send').onclick = async () => {
|
||||
const sendBtnFb = form.querySelector('.fb-send');
|
||||
sendBtnFb.onclick = async () => {
|
||||
if (sendBtnFb.disabled) return; // не плодить дубли POST при двойном клике
|
||||
sendBtnFb.disabled = true;
|
||||
const comment = (cat ? cat + ': ' : '') + ta.value.trim();
|
||||
try {
|
||||
const r = await authFetch('/api/feedback', {
|
||||
@@ -967,7 +1034,8 @@ function openFeedbackForm(btn, answerText) {
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
if (streaming) return;
|
||||
if (streaming) return; // стоп — только через кнопку (onSendClick)
|
||||
if (uploadingActive) return; // идёт загрузка файла — не плодить параллельные отправки
|
||||
const input = document.getElementById('msg-input');
|
||||
let text = input.value.trim();
|
||||
if (!text && pendingFiles.length === 0) return;
|
||||
@@ -991,22 +1059,27 @@ async function sendMessage() {
|
||||
}
|
||||
|
||||
async function runChat(text) {
|
||||
if (streaming) return; // единая защита от параллельного запуска (retry/двойная отправка)
|
||||
streaming = true;
|
||||
document.getElementById('send-btn').disabled = true;
|
||||
const myCtrl = new AbortController();
|
||||
abortCtrl = myCtrl;
|
||||
streamStartedAt = performance.now();
|
||||
setSendMode(true);
|
||||
addTyping();
|
||||
let aiDiv = null;
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/api/chat', {
|
||||
method: 'POST',
|
||||
headers: {...authHeaders(), 'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({message: text}),
|
||||
signal: myCtrl.signal,
|
||||
});
|
||||
|
||||
if (r.status === 401) { logout(); return; }
|
||||
if (!r.ok) { removeTyping(); addErrorRetry(httpErrText(r.status), text); return; }
|
||||
|
||||
removeTyping();
|
||||
let aiDiv = null;
|
||||
let aiText = '';
|
||||
const reader = r.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
@@ -1041,9 +1114,16 @@ async function runChat(text) {
|
||||
ctrlBtns.forEach(b => aiDiv.appendChild(b));
|
||||
scrollIfPinned();
|
||||
} else if (eventType === 'tool') {
|
||||
// Show minimal status, not raw code
|
||||
const toolNames = {Bash: 'Выполняю...', Read: 'Читаю файл...', Write: 'Создаю файл...', Edit: 'Редактирую...', Glob: 'Ищу файлы...', Grep: 'Ищу в файлах...'};
|
||||
const label = toolNames[data.tool] || 'Обрабатываю...';
|
||||
// Статус агента (срез 1.6): человеко-понятная подпись вместо сырого имени тула
|
||||
const toolNames = {Bash: 'Считаю...', Read: 'Читаю файл...', Write: 'Готовлю файл...', Edit: 'Редактирую смету...', Glob: 'Ищу файлы...', Grep: 'Ищу в файлах...', WebSearch: 'Ищу в интернете...', WebFetch: 'Читаю страницу...', TodoWrite: 'Планирую шаги...'};
|
||||
let label = toolNames[data.tool];
|
||||
if (!label) {
|
||||
const t = String(data.tool || '');
|
||||
if (t.includes('verify')) label = 'Проверяю смету...';
|
||||
else if (t.includes('find') || t.includes('search') || t.includes('corpus') || t.includes('price')) label = 'Ищу в базе смет...';
|
||||
else if (t.startsWith('mcp__')) label = 'Работаю с данными сметы...';
|
||||
else label = 'Обрабатываю...';
|
||||
}
|
||||
removeTyping();
|
||||
addTyping().textContent = label;
|
||||
} else if (eventType === 'done') {
|
||||
@@ -1061,14 +1141,21 @@ async function runChat(text) {
|
||||
}
|
||||
}
|
||||
if (!aiDiv && !aiText) addMsg('ai', '(пустой ответ)');
|
||||
if (aiDiv) { enhanceTables(aiDiv); typografAI(aiDiv); externalizeLinks(aiDiv); } // streaming re-renders innerHTML each chunk → finalize once at the end
|
||||
|
||||
} catch (err) {
|
||||
removeTyping();
|
||||
addErrorRetry('Нет связи с сервисом. ' + (err.message || ''), text);
|
||||
if (err && err.name === 'AbortError') {
|
||||
// при переключении/новом чате abort «тихий» — не сорим системным сообщением
|
||||
if (!myCtrl._silent) addMsg('system', '⏹ Остановлено. Ответ мог сгенерироваться не полностью.');
|
||||
} else {
|
||||
addErrorRetry('Нет связи с сервисом. ' + (err.message || ''), text);
|
||||
}
|
||||
} finally {
|
||||
// финализация таблиц/ссылок и при обрыве (Стоп) — иначе оборванный ответ без скролла/скачивания
|
||||
if (aiDiv) { enhanceTables(aiDiv); typografAI(aiDiv); externalizeLinks(aiDiv); }
|
||||
streaming = false;
|
||||
document.getElementById('send-btn').disabled = false;
|
||||
if (abortCtrl === myCtrl) abortCtrl = null;
|
||||
setSendMode(false);
|
||||
document.getElementById('msg-input').focus();
|
||||
loadSessions(); // обновить превью/порядок чатов в панели
|
||||
}
|
||||
@@ -1078,10 +1165,11 @@ async function runChat(text) {
|
||||
async function newChat() {
|
||||
// New tab = new session, old one stays in DB and in the sidebar
|
||||
closeSidebar();
|
||||
if (abortCtrl) { abortCtrl._silent = true; abortCtrl.abort(); } // не тащить хвост стрима в новый чат
|
||||
tabId = genUUID();
|
||||
localStorage.setItem('tabId', tabId);
|
||||
msgs.innerHTML = '';
|
||||
addMsg('system', 'Новый диалог начат.');
|
||||
showOnboarding();
|
||||
renderSessions();
|
||||
document.getElementById('msg-input').focus();
|
||||
}
|
||||
@@ -1140,9 +1228,9 @@ async function listFiles() {
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const r = await fetch(API + '/api/history', {headers: authHeaders()});
|
||||
if (!r.ok) return;
|
||||
if (!r.ok) { if (!msgs.children.length) showOnboarding(); return; }
|
||||
const history = await r.json();
|
||||
if (history.length === 0) return;
|
||||
if (history.length === 0) { showOnboarding(); return; }
|
||||
msgs.innerHTML = '';
|
||||
for (const m of history) {
|
||||
if (m.role === 'user') addMsg('user', m.content, m.timestamp);
|
||||
@@ -1152,7 +1240,7 @@ async function loadHistory() {
|
||||
try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
} catch { if (!msgs.children.length) showOnboarding(); }
|
||||
}
|
||||
|
||||
// --- Chat sidebar (Claude-desktop style left panel) ---
|
||||
@@ -1196,6 +1284,7 @@ function makeChatItem(s, active) {
|
||||
async function switchChat(id) {
|
||||
closeSidebar();
|
||||
if (id === tabId) return;
|
||||
if (abortCtrl) { abortCtrl._silent = true; abortCtrl.abort(); } // не тащить хвост стрима в другой чат
|
||||
tabId = id;
|
||||
localStorage.setItem('tabId', tabId);
|
||||
msgs.innerHTML = '';
|
||||
|
||||
Reference in New Issue
Block a user