feat: пакет UX-быстрых-побед — демо-смета, авто-названия, бейджи движка, «что нового», черновик, regenerate/edit, 14-дн триал
По docs/TASK_2026-07-21_ux_quickwins.md (7 пунктов, red-green): 1) POST /api/demo-file + чип «▶ Попробовать на примере» в онбординге; синтетическая static/demo/demo_smeta.xlsx (8 позиций ГЭСН, числа сходятся) 2) стабильное авто-название диалога по ПЕРВОМУ вопросу (_maybe_autotitle; ручной rename и второй+ обмен не перезаписываются; db.get_session_title) 3) бейджи источника чисел: «⚙ посчитано движком» (панель сметы) и «числа только из офферов корпуса» (КА) с тултипами 4) «что нового»: static/changelog.json + тихая точка у версии, панель по клику 5) черновик ввода в localStorage per-tab (переживает F5, чистится при отправке) 6) «↻ Ответить заново» на AI-сообщениях + «✎ Изменить» на своих (без ветвления) 7) триал: TRIAL_DAYS (дефолт 14, 0=off) → paid_until при регистрации; гейт при истёкшем триале даёт честную приписку (_agent_gate_notice) Плюс fix найденного смоуком pre-existing бага: .est-panel (overflow:hidden) в flex-колонке #messages сжимался до 2px при переполнении чата → flex-shrink:0. Тесты: tests/test_ux_quickwins.py (17, red→green), полный suite 462 passed (5 collection-errors pre-existing: smeta_railway/pymorphy2). UI-смоук на живом chat.html через стаб-харнесс + Playwright (демо-флоу, черновик, кнопки, бейджи, «что нового», панели). Стаб-харнесс дополнен /api/version, changelog, demo-file. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+158
-1
@@ -104,11 +104,16 @@ button { font-family: inherit; }
|
||||
.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); }
|
||||
.ob-demo { border-color: var(--accent); color: var(--accent); font-weight: 600; }
|
||||
.ob-demo:disabled { opacity: .6; cursor: default; }
|
||||
#quick-actions { display: flex; flex-wrap: wrap; gap: .4rem; margin-top: .5rem; justify-content: center; }
|
||||
#quick-actions.hide { display: none; }
|
||||
.qa-chip { font-size: .8rem; padding: .35rem .7rem; border: 1px solid var(--border); border-radius: 999px; background: var(--bg-sunken); color: var(--text-muted); cursor: pointer; transition: border-color .15s, color .15s; }
|
||||
.qa-chip:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.est-panel { align-self: stretch; max-width: 100%; margin: .5rem 0; border: 1px solid var(--border); border-radius: 10px; background: var(--bg-card); overflow: hidden; }
|
||||
/* flex-shrink:0 обязателен: #messages — flex-колонка, а overflow:hidden обнуляет
|
||||
авто-min-size флекс-элемента → при переполнении чата панель сжималась до 2px
|
||||
(невидима в длинном диалоге). Найдено UI-смоуком 2026-07-21, баг был и до него. */
|
||||
.est-panel { align-self: stretch; flex-shrink: 0; max-width: 100%; margin: .5rem 0; border: 1px solid var(--border); border-radius: 10px; background: var(--bg-card); overflow: hidden; }
|
||||
.est-head { padding: .6rem .9rem; font-weight: 700; font-size: .95rem; color: var(--text); background: var(--bg-sunken); border-bottom: 1px solid var(--border); }
|
||||
.est-scroll { overflow: auto; max-height: 60vh; } /* большие сметы: внутр. скролл + липкий заголовок (срез 6.5) */
|
||||
.est-table { width: 100%; border-collapse: collapse; font-size: .82rem; }
|
||||
@@ -130,6 +135,16 @@ button { font-family: inherit; }
|
||||
.est-qty:focus { border-color: var(--accent); outline: none; }
|
||||
.est-panel.est-approved { border-color: var(--ok, #3fa066); }
|
||||
.est-badge { float: right; font-size: .72rem; font-weight: 700; color: #fff; background: var(--ok, #3fa066); padding: .1rem .5rem; border-radius: 999px; }
|
||||
/* Бейдж источника чисел (UX №3): пассивный, с тултипом — дифференциатор «числа не от LLM» */
|
||||
.engine-badge { float: right; font-size: .68rem; font-weight: 600; color: var(--text-muted); background: transparent; border: 1px solid var(--border); padding: .08rem .5rem; border-radius: 999px; cursor: help; margin-left: .5rem; }
|
||||
/* «Что нового» (UX №4): тихая точка у версии + маленькая панель по клику, не попап */
|
||||
.app-version.cl-clickable { cursor: pointer; }
|
||||
.app-version.has-news::after { content: '●'; color: var(--accent); font-size: .55rem; margin-left: .25rem; vertical-align: middle; }
|
||||
#changelog-panel { display: none; position: fixed; bottom: 3.2rem; left: 50%; transform: translateX(-50%); width: min(340px, calc(100vw - 2rem)); max-height: 45vh; overflow-y: auto; background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-md); padding: .7rem .9rem; font-size: .78rem; z-index: 60; text-align: left; }
|
||||
#changelog-panel h4 { font-size: .78rem; margin: .5rem 0 .15rem; color: var(--text); }
|
||||
#changelog-panel h4:first-child { margin-top: 0; }
|
||||
#changelog-panel ul { margin: 0 0 .3rem 1.1rem; padding: 0; color: var(--text-muted); }
|
||||
#changelog-panel li { margin: .1rem 0; }
|
||||
.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; }
|
||||
|
||||
@@ -392,8 +407,66 @@ applyThemeIcon();
|
||||
// --- Версия UI из единого источника (main.py APP_VERSION → /api/version) ---
|
||||
fetch('/api/version').then(function (r) { return r.json(); }).then(function (d) {
|
||||
document.querySelectorAll('.app-version').forEach(function (el) { el.textContent = 'v.' + d.version; });
|
||||
if (d.version) initChangelog(d.version);
|
||||
}).catch(function () {});
|
||||
|
||||
// «Что нового» (UX №4): точка у версии, если она изменилась с прошлого визита;
|
||||
// клик — маленькая панель с последними изменениями. Пассивно: без попапов и фокуса.
|
||||
function initChangelog(ver) {
|
||||
fetch('/static/changelog.json').then(function (r) { return r.json(); }).then(function (log) {
|
||||
if (!Array.isArray(log) || !log.length) return;
|
||||
var seen = null;
|
||||
try { seen = localStorage.getItem('seen_version'); } catch (e) {}
|
||||
document.querySelectorAll('.app-version').forEach(function (el) {
|
||||
el.classList.add('cl-clickable');
|
||||
el.setAttribute('role', 'button');
|
||||
el.tabIndex = 0;
|
||||
el.setAttribute('aria-label', 'Что нового в этой версии');
|
||||
if (seen !== ver) el.classList.add('has-news');
|
||||
el.addEventListener('click', function () { toggleChangelog(log, ver); });
|
||||
el.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleChangelog(log, ver); }
|
||||
});
|
||||
});
|
||||
}).catch(function () {});
|
||||
}
|
||||
function toggleChangelog(log, ver) {
|
||||
var panel = document.getElementById('changelog-panel');
|
||||
if (panel && panel.style.display === 'block') { closeChangelog(); return; }
|
||||
if (!panel) {
|
||||
panel = document.createElement('div');
|
||||
panel.id = 'changelog-panel';
|
||||
panel.setAttribute('aria-label', 'Что нового');
|
||||
log.slice(0, 5).forEach(function (entry) {
|
||||
var h = document.createElement('h4');
|
||||
h.textContent = 'v.' + entry.version + ' — ' + entry.date;
|
||||
panel.appendChild(h);
|
||||
var ul = document.createElement('ul');
|
||||
(entry.changes || []).forEach(function (c) {
|
||||
var li = document.createElement('li'); li.textContent = c; ul.appendChild(li);
|
||||
});
|
||||
panel.appendChild(ul);
|
||||
});
|
||||
document.body.appendChild(panel);
|
||||
}
|
||||
panel.style.display = 'block';
|
||||
try { localStorage.setItem('seen_version', ver); } catch (e) {}
|
||||
document.querySelectorAll('.app-version').forEach(function (el) { el.classList.remove('has-news'); });
|
||||
setTimeout(function () { document.addEventListener('mousedown', _clOutside, true); }, 0);
|
||||
document.addEventListener('keydown', _clEsc);
|
||||
}
|
||||
function closeChangelog() {
|
||||
var p = document.getElementById('changelog-panel');
|
||||
if (p) p.style.display = 'none';
|
||||
document.removeEventListener('mousedown', _clOutside, true);
|
||||
document.removeEventListener('keydown', _clEsc);
|
||||
}
|
||||
function _clOutside(e) {
|
||||
var p = document.getElementById('changelog-panel');
|
||||
if (p && !p.contains(e.target) && !e.target.classList.contains('app-version')) closeChangelog();
|
||||
}
|
||||
function _clEsc(e) { if (e.key === 'Escape') closeChangelog(); }
|
||||
|
||||
// Индикатор свежести данных: на какой ценовой период актуальна корпусная база.
|
||||
fetch('/api/data-version').then(function (r) { return r.json(); }).then(function (d) {
|
||||
if (!d.newest_period) return;
|
||||
@@ -667,6 +740,7 @@ let token = localStorage.getItem('token');
|
||||
let pendingFiles = [];
|
||||
let streaming = false;
|
||||
let abortCtrl = null; // срез 1.3: прерывание текущего ответа
|
||||
let lastUserText = ''; // последний вопрос юзера — для «Ответить заново» (UX №6)
|
||||
let streamStartedAt = 0;
|
||||
function setSendMode(streamingNow) {
|
||||
const b = document.getElementById('send-btn');
|
||||
@@ -743,6 +817,7 @@ function showChat() {
|
||||
document.getElementById('login-screen').style.display = 'none';
|
||||
document.getElementById('chat-screen').style.display = 'flex';
|
||||
document.getElementById('msg-input').focus();
|
||||
restoreDraft(); // черновик текущего диалога (UX №5)
|
||||
loadHistory();
|
||||
loadSessions();
|
||||
loadSessionDate(); // дата сметы текущего диалога → бейдж
|
||||
@@ -934,6 +1009,35 @@ function showOnboarding() {
|
||||
};
|
||||
chips.appendChild(c);
|
||||
});
|
||||
// Демо-смета (UX №1): один клик — синтетический файл-пример в work_dir диалога
|
||||
// и готовый запрос на проверку в поле ввода (не отправляем сами — юзер решает).
|
||||
const demo = document.createElement('button');
|
||||
demo.type = 'button'; demo.className = 'ob-chip ob-demo';
|
||||
demo.textContent = '▶ Попробовать на примере';
|
||||
demo.title = 'Положим синтетическую демо-смету в этот чат и подставим запрос на проверку';
|
||||
demo.onclick = async () => {
|
||||
if (demo.disabled) return;
|
||||
demo.disabled = true;
|
||||
const orig = demo.textContent;
|
||||
demo.textContent = 'Готовлю пример…';
|
||||
try {
|
||||
const r = await authFetch('/api/demo-file', {method: 'POST'});
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
const d = await r.json();
|
||||
addMsg('file', 'Загружен демо-файл: ' + d.filename +
|
||||
' (синтетический пример — удаляется как обычный файл)');
|
||||
const inp = document.getElementById('msg-input');
|
||||
// имя файла в тексте — роутер ведёт запрос агентным путём (mentions_file)
|
||||
inp.value = 'Проверь эту смету: ' + d.filename;
|
||||
inp.focus();
|
||||
inp.dispatchEvent(new Event('input'));
|
||||
} catch (e) {
|
||||
demo.textContent = 'Не получилось — попробуйте ещё раз';
|
||||
demo.disabled = false;
|
||||
setTimeout(() => { demo.textContent = orig; }, 2500);
|
||||
}
|
||||
};
|
||||
chips.insertBefore(demo, chips.firstChild);
|
||||
box.appendChild(chips);
|
||||
msgs.appendChild(box);
|
||||
}
|
||||
@@ -951,6 +1055,8 @@ function addMsg(type, text, ts) {
|
||||
div.appendChild(time);
|
||||
// Store raw text for copy and streaming
|
||||
div._rawText = text;
|
||||
// последний вопрос — для «Ответить заново» (живёт и после загрузки истории)
|
||||
if (type === 'user' && text) lastUserText = text;
|
||||
if (type === 'ai') {
|
||||
div.innerHTML = renderMarkdown(text);
|
||||
div.prepend(time);
|
||||
@@ -979,6 +1085,27 @@ function addMsg(type, text, ts) {
|
||||
rep.textContent = 'Сообщить об ошибке';
|
||||
rep.onclick = () => openFeedbackForm(rep, div._rawText || '');
|
||||
div.appendChild(rep);
|
||||
// «Ответить заново» (UX №6): повторить последний вопрос без перепечатывания
|
||||
const rg = document.createElement('button');
|
||||
rg.className = 'copy-btn regen-btn';
|
||||
rg.textContent = '↻ Ответить заново';
|
||||
rg.title = 'Задать последний вопрос ещё раз';
|
||||
rg.onclick = () => { if (!streaming && lastUserText) runChat(lastUserText); };
|
||||
div.appendChild(rg);
|
||||
}
|
||||
if (type === 'user') {
|
||||
// «Изменить» (UX №6): текст вопроса → в поле ввода для правки; без ветвления
|
||||
const ed = document.createElement('button');
|
||||
ed.className = 'copy-btn edit-btn';
|
||||
ed.textContent = '✎ Изменить';
|
||||
ed.title = 'Подставить текст в поле ввода для правки';
|
||||
ed.onclick = () => {
|
||||
const inp = document.getElementById('msg-input');
|
||||
inp.value = div._rawText || '';
|
||||
inp.focus();
|
||||
inp.dispatchEvent(new Event('input'));
|
||||
};
|
||||
div.appendChild(ed);
|
||||
}
|
||||
msgs.appendChild(div);
|
||||
scrollIfPinned();
|
||||
@@ -1234,11 +1361,13 @@ async function sendMessage() {
|
||||
addMsg('user', text);
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
try { localStorage.removeItem('draft_' + tabId); } catch (e) {} // черновик отправлен
|
||||
await runChat(text);
|
||||
}
|
||||
|
||||
async function runChat(text) {
|
||||
if (streaming) return; // единая защита от параллельного запуска (retry/двойная отправка)
|
||||
lastUserText = text; // и при retry/«Ответить заново» — актуальный вопрос
|
||||
streaming = true;
|
||||
const myCtrl = new AbortController();
|
||||
abortCtrl = myCtrl;
|
||||
@@ -1362,6 +1491,12 @@ function addEstimatePanel(data, prevData) {
|
||||
const head = document.createElement('div');
|
||||
head.className = 'est-head';
|
||||
head.textContent = data.title || 'Смета';
|
||||
// Дифференциатор (UX №3): числа в панели даёт детерминированный движок, не LLM
|
||||
const eng = document.createElement('span');
|
||||
eng.className = 'engine-badge';
|
||||
eng.textContent = '⚙ посчитано движком';
|
||||
eng.title = 'Числа посчитаны детерминированным движком по базе, не языковой моделью';
|
||||
head.appendChild(eng);
|
||||
panel.appendChild(head);
|
||||
|
||||
const scroll = document.createElement('div');
|
||||
@@ -1508,6 +1643,12 @@ function addKaPanel(form) {
|
||||
const head = document.createElement('div');
|
||||
head.className = 'est-head';
|
||||
head.textContent = 'КА: ' + (res.name || form.query || 'материал');
|
||||
// Тот же принцип, что на панели сметы (UX №3): цены не сочиняются моделью
|
||||
const eng = document.createElement('span');
|
||||
eng.className = 'engine-badge';
|
||||
eng.textContent = 'числа только из офферов корпуса';
|
||||
eng.title = 'Цены в форме взяты из офферов обезличенного корпуса реальных КА, не сгенерированы языковой моделью';
|
||||
head.appendChild(eng);
|
||||
panel.appendChild(head);
|
||||
if (res.code_tc) {
|
||||
const sub = document.createElement('div');
|
||||
@@ -1585,6 +1726,7 @@ async function newChat() {
|
||||
msgs.innerHTML = '';
|
||||
showOnboarding();
|
||||
renderSessions();
|
||||
restoreDraft(); // черновик per-диалог: у нового чата своё (пустое) поле
|
||||
document.getElementById('msg-input').focus();
|
||||
}
|
||||
|
||||
@@ -1780,6 +1922,7 @@ async function switchChat(id) {
|
||||
msgs.innerHTML = '';
|
||||
await loadHistory();
|
||||
renderSessions();
|
||||
restoreDraft(); // черновик выбранного диалога (UX №5)
|
||||
}
|
||||
|
||||
// Auto-resize textarea + скрыть быстрые действия, когда пользователь начал печатать
|
||||
@@ -1788,7 +1931,21 @@ document.getElementById('msg-input').addEventListener('input', function() {
|
||||
this.style.height = Math.min(this.scrollHeight, 150) + 'px';
|
||||
const qa = document.getElementById('quick-actions');
|
||||
if (qa) qa.classList.toggle('hide', this.value.trim().length > 0);
|
||||
// Черновик (UX №5): текст переживает F5/закрытие вкладки, свой на каждый диалог
|
||||
try {
|
||||
if (this.value) localStorage.setItem('draft_' + tabId, this.value);
|
||||
else localStorage.removeItem('draft_' + tabId);
|
||||
} catch (e) {}
|
||||
});
|
||||
// Восстановить черновик текущего диалога (вход, смена чата, новый чат)
|
||||
function restoreDraft() {
|
||||
const inp = document.getElementById('msg-input');
|
||||
let d = '';
|
||||
try { d = localStorage.getItem('draft_' + tabId) || ''; } catch (e) {}
|
||||
if (inp.value === d) return;
|
||||
inp.value = d;
|
||||
inp.dispatchEvent(new Event('input')); // авто-высота + скрытие быстрых чипов
|
||||
}
|
||||
// Быстрые действия: клик подставляет заготовку в поле (не отправляет — можно дополнить)
|
||||
document.querySelectorAll('#quick-actions .qa-chip').forEach(c => {
|
||||
c.onclick = () => {
|
||||
|
||||
Reference in New Issue
Block a user