feat(ui/core): срез 6.1 end-to-end — агент показывает смету панелью (show_estimate)

MCP-tool show_estimate пишет _estimate_panel.json → _stream_and_save эмитит событие
estimate + сохраняет role='estimate' (восстановление из истории) + удаляет файл (не в
кнопки, не повторно). Панель рендерит числа из данных (JS не считает). role='estimate'
исключён из контекста LLM (как files). allowedTools + браузер-verified (рендер + restore).
APP_VERSION 2026-07-17n.
This commit is contained in:
anor
2026-07-17 23:27:57 +10:00
parent 8f2bbc551b
commit 9e62e8422a
4 changed files with 55 additions and 1 deletions
+1
View File
@@ -220,6 +220,7 @@ async def stream_claude(
"mcp__smeta__parse_gge_file,"
"mcp__smeta__verify_estimate_file,"
"mcp__smeta__precheck_estimate,"
"mcp__smeta__show_estimate,"
"mcp__smeta__export_estimate_gge,"
"mcp__smeta__update_xlsx_cells,"
"mcp__smeta__find_in_real_estimates,"
+17 -1
View File
@@ -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-17m"
APP_VERSION = "2026-07-17n"
# Audit: path → action name mapping
_AUDIT_MAP = [
@@ -495,6 +495,22 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
return
if full_response:
save_message(user, tab_id, "assistant", full_response)
# Структурированная смета от агента (tool show_estimate пишет _estimate_panel.json) →
# событие estimate + панель. Файл читаем, эмитим, удаляем (не в кнопки, не повторно).
est_file = work_dir / "_estimate_panel.json"
if est_file.exists():
try:
est_data = json.loads(est_file.read_text(encoding="utf-8"))
if isinstance(est_data, dict) and est_data.get("positions"):
save_message(user, tab_id, "estimate", json.dumps(est_data, ensure_ascii=False))
yield f"event: estimate\ndata: {json.dumps(est_data, ensure_ascii=False)}\n\n"
except Exception:
pass
finally:
try:
est_file.unlink()
except OSError:
pass
# Новые/изменённые файлы за время ответа → кнопки скачивания в чате.
# .md включён: агент отдаёт отчёты и в markdown. Служебные *_csv/ —
# директории, отсекаются is_file().
+34
View File
@@ -374,6 +374,22 @@ def tool_precheck_estimate(*, filename: str) -> dict:
return {"error": f"Ошибка pre-check: {type(e).__name__}: {e}"}
def tool_show_estimate(*, estimate: dict) -> dict:
"""Показать смету пользователю красивой таблицей-панелью (не текстом).
estimate: {title?, positions:[{code,name,unit,qty,unit_cost,total,unresolved?}],
totals:{grand_pz,grand_nr,grand_sp,grand_total,vat,total_with_vat}, ok?, warnings?, missing?}.
Числа — из расчёта, панель их только отображает."""
import json as _json
user, tab = _user_tab()
work_dir = _work_dir(user, tab)
try:
(work_dir / "_estimate_panel.json").write_text(
_json.dumps(estimate, ensure_ascii=False), encoding="utf-8")
return {"shown": True, "positions": len(estimate.get("positions") or [])}
except Exception as e:
return {"error": f"Не удалось показать смету: {type(e).__name__}: {e}"}
def tool_export_estimate_gge(*, filename: str, estimate: dict) -> dict:
"""Экспортировать структурированную смету в .gge XML (формат экспертизы).
estimate: {code, name, positions:[{name,code,quantity,unit,price_total_cur,direct}], totals:{}}.
@@ -723,6 +739,24 @@ TOOLS: dict[str, dict] = {
"required": ["filename"],
},
},
"show_estimate": {
"fn": tool_show_estimate,
"description": (
"Показать рассчитанную смету пользователю КРАСИВОЙ ТАБЛИЦЕЙ-панелью "
"(вместо простыни текста). Вызывай ПОСЛЕ того как посчитал смету, чтобы "
"человек увидел позиции и итоги наглядно. estimate: {title, positions:"
"[{code,name,unit,qty,unit_cost,total,unresolved}], totals:{grand_pz,"
"grand_nr,grand_sp,grand_total,vat,total_with_vat}, ok, warnings, missing}. "
"Числа — из расчёта; нерассчитанные позиции помечай unresolved=true."
),
"inputSchema": {
"type": "object",
"properties": {
"estimate": {"type": "object", "description": "Структура сметы (позиции + итоги)"},
},
"required": ["estimate"],
},
},
"export_estimate_gge": {
"fn": tool_export_estimate_gge,
"description": (
+3
View File
@@ -1385,6 +1385,9 @@ async function loadHistory() {
else if (m.role === 'files') {
try { addFilesMsg(JSON.parse(m.content), m.timestamp); } catch {}
}
else if (m.role === 'estimate') {
try { addEstimatePanel(JSON.parse(m.content)); } catch {}
}
}
} catch { if (!msgs.children.length) showOnboarding(); }
}