addEstimatePanel рендерит структурированную смету (событие estimate стрима, как files): таблица позиций, итоги СТРОГО из data.totals (JS не считает), нерассчитанные позиции подсвечены, warnings/missing показаны честно, XSS-safe (textContent), таблица со своим горизонт-скроллом. Инфраструктура для панели — инертна пока бэкенд не эмитит estimate. APP_VERSION 2026-07-17m. Браузер-verified.
105 lines
5.6 KiB
Python
105 lines
5.6 KiB
Python
"""UI-smoke харнесс (срез UI 0.1): гоняем РЕАЛЬНЫЙ static/chat.html в браузере
|
|
без поднятия полного бэкенда (нет .env/venv локально — см. memory
|
|
feedback_chat_html_local_smoke).
|
|
|
|
Идея: берём настоящий static/chat.html и инъектим в <head> стаб, который
|
|
подменяет window.fetch поддельными /api-эндпоинтами и кладёт токен в localStorage.
|
|
Так браузер исполняет НАСТОЯЩИЕ функции (sendMessage/runChat/openFeedbackForm/…),
|
|
а не их копию — регрессии ловятся на живом коде.
|
|
|
|
Использование:
|
|
python3 tests/ui_smoke_harness.py # печатает путь к сгенерированному stub
|
|
python3 tests/ui_smoke_harness.py /tmp/x.html # свой путь вывода
|
|
|
|
Дальше stub раздаётся любым статик-сервером (`python3 -m http.server`) и
|
|
драйвится Playwright (file:// заблокирован в MCP-Playwright — только http).
|
|
|
|
SSE-стаб /api/chat уважает opts.signal — поэтому корректно тестируется abort
|
|
(кнопка «Стоп», newChat/switchChat мид-стрим).
|
|
"""
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
CHAT_HTML = Path(__file__).resolve().parent.parent / "static" / "chat.html"
|
|
|
|
# Стаб: авторизация + поддельные /api. SSE /api/chat отдаёт tool→text→text→done
|
|
# с задержками, уважает signal (abort роняет поток AbortError'ом).
|
|
STUB = r"""<script>
|
|
localStorage.setItem('token','stub-token'); localStorage.setItem('tabId','stub-tab');
|
|
const _enc = new TextEncoder();
|
|
window._fb = 0; // счётчик POST /api/feedback (для теста дублей)
|
|
function _sse(events, signal){
|
|
return new ReadableStream({start(controller){
|
|
let i = 0;
|
|
const abort = () => { try { controller.error(new DOMException('Aborted','AbortError')); } catch(e){} };
|
|
if (signal) { if (signal.aborted) { abort(); return; } signal.addEventListener('abort', abort); }
|
|
const tick = () => {
|
|
if (signal && signal.aborted) return;
|
|
if (i >= events.length) { controller.close(); return; }
|
|
controller.enqueue(_enc.encode(events[i])); i++; setTimeout(tick, 300);
|
|
};
|
|
setTimeout(tick, 120);
|
|
}});
|
|
}
|
|
// Stateful сессии — для тестов панели чатов (rename/delete/поиск)
|
|
window._sessions = [
|
|
{tab_id:'t-dom', last_ts: 1752700000, msg_count: 4, last_question:'Смета по дому', title: null},
|
|
{tab_id:'t-garaj', last_ts: 1752600000, msg_count: 2, last_question:'Смета по гаражу', title: null},
|
|
];
|
|
window._calls = {del: [], title: []};
|
|
function _json(o, status=200){ return new Response(JSON.stringify(o),{status,headers:{'Content-Type':'application/json'}}); }
|
|
window.fetch = async (url, opts={}) => {
|
|
url = String(url); opts = opts || {};
|
|
if (url.includes('/api/chat')) {
|
|
const msg = (()=>{ try { return JSON.parse(opts.body||'{}').message||''; } catch(e){ return ''; } })();
|
|
const evs = [
|
|
'event: tool\ndata: {"tool":"mcp__smeta__verify_estimate_file"}\n\n',
|
|
'event: text\ndata: {"text":"Считаю смету"}\n\n',
|
|
'event: text\ndata: {"text":" — готово."}\n\n',
|
|
];
|
|
if (/смет|estimate/i.test(msg)) {
|
|
const est = {title:'Смета №1', ok:false,
|
|
positions:[
|
|
{code:'01-01-001-01', name:'Разработка грунта', unit:'м3', qty:100, unit_cost:150.5, total:15050},
|
|
{code:'06-01-001-02', name:'Бетон', unit:'м3', qty:20, unit_cost:5000, total:100000, unresolved:true}],
|
|
totals:{grand_pz:115050, grand_nr:10000, grand_sp:5000, grand_total:130050, vat:28611, total_with_vat:158661},
|
|
warnings:['Проверьте объёмы по ведомости'],
|
|
missing:[{code:'06-01-001-02', reason:'цена материала не найдена'}]};
|
|
evs.push('event: estimate\ndata: ' + JSON.stringify(est) + '\n\n');
|
|
}
|
|
evs.push('event: done\ndata: {"result":"ok"}\n\n');
|
|
return new Response(_sse(evs, opts.signal), {status:200, headers:{'Content-Type':'text/event-stream'}});
|
|
}
|
|
if (url.includes('/api/feedback')) { window._fb++; return _json({}); }
|
|
if (url.includes('/api/history')) return _json([]);
|
|
// /api/sessions/{tab}/title (POST)
|
|
let m = url.match(/\/api\/sessions\/([^/]+)\/title/);
|
|
if (m) { const tab = decodeURIComponent(m[1]); const b = JSON.parse(opts.body||'{}');
|
|
window._calls.title.push({tab, title:b.title});
|
|
const s = window._sessions.find(x=>x.tab_id===tab); if (s) s.title = b.title;
|
|
return _json({ok:true, title:b.title}); }
|
|
// /api/sessions/{tab} (DELETE)
|
|
m = url.match(/\/api\/sessions\/([^/]+)$/);
|
|
if (m && (opts.method||'GET').toUpperCase()==='DELETE') {
|
|
const tab = decodeURIComponent(m[1]); window._calls.del.push(tab);
|
|
window._sessions = window._sessions.filter(x=>x.tab_id!==tab);
|
|
return _json({ok:true, removed:1}); }
|
|
if (url.includes('/api/sessions')) return _json(window._sessions);
|
|
return _json({});
|
|
};
|
|
</script>
|
|
"""
|
|
|
|
|
|
def build_stub(out_path: Path) -> Path:
|
|
html = CHAT_HTML.read_text(encoding="utf-8")
|
|
if "</head>" not in html:
|
|
raise SystemExit("chat.html: нет </head> — некуда инъектить стаб")
|
|
out_path.write_text(html.replace("</head>", STUB + "</head>", 1), encoding="utf-8")
|
|
return out_path
|
|
|
|
|
|
if __name__ == "__main__":
|
|
out = Path(sys.argv[1]) if len(sys.argv) > 1 else CHAT_HTML.parent.parent / "tests" / ".ui_smoke_stub.html"
|
|
print(build_stub(out))
|