From 9e62e8422aeaea3450680a13a77ff6550d69a2aa Mon Sep 17 00:00:00 2001 From: anor Date: Fri, 17 Jul 2026 23:27:57 +1000 Subject: [PATCH] =?UTF-8?q?feat(ui/core):=20=D1=81=D1=80=D0=B5=D0=B7=206.1?= =?UTF-8?q?=20end-to-end=20=E2=80=94=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=BA=D0=B0=D0=B7=D1=8B=D0=B2=D0=B0=D0=B5=D1=82=20?= =?UTF-8?q?=D1=81=D0=BC=D0=B5=D1=82=D1=83=20=D0=BF=D0=B0=D0=BD=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D1=8E=20(show=5Festimate)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- claude_bridge.py | 1 + main.py | 18 +++++++++++++++++- smeta_mcp.py | 34 ++++++++++++++++++++++++++++++++++ static/chat.html | 3 +++ 4 files changed, 55 insertions(+), 1 deletion(-) diff --git a/claude_bridge.py b/claude_bridge.py index 56b3602..7976b26 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -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," diff --git a/main.py b/main.py index 9474dcc..8be27d6 100644 --- a/main.py +++ b/main.py @@ -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(). diff --git a/smeta_mcp.py b/smeta_mcp.py index dba21b8..65b41b3 100644 --- a/smeta_mcp.py +++ b/smeta_mcp.py @@ -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": ( diff --git a/static/chat.html b/static/chat.html index 0ff48ae..9355323 100644 --- a/static/chat.html +++ b/static/chat.html @@ -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(); } }