From 8866176be6c9a11bd9f28905d253d9273677c79a Mon Sep 17 00:00:00 2001 From: dctouch Date: Wed, 15 Apr 2026 09:15:35 +0300 Subject: [PATCH] =?UTF-8?q?=D0=90=D0=A0=D0=A7=20-=20UI=20=D0=B8=20domain?= =?UTF-8?q?=20loop:=20=D1=81=D0=B8=D0=BD=D1=85=D1=80=D0=BE=D0=BD=D0=B8?= =?UTF-8?q?=D0=B7=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D1=82=D1=8C=20=D0=BB=D0=BE?= =?UTF-8?q?=D0=BA=D0=B0=D0=BB=D1=8C=D0=BD=D1=83=D1=8E=20LLM-=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D1=8C=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20sha?= =?UTF-8?q?red=20config=20+=20=D0=9A=D0=92=D0=98=D0=9D=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../orchestration/active_domain_contract.json | 60 ++++++++- llm_normalizer/backend/dist/config.js | 3 +- .../backend/dist/routes/sharedLlmConfig.js | 107 +++++++++++++++ llm_normalizer/backend/dist/server.js | 2 + .../dist/services/addressIntentResolver.js | 4 +- .../dist/services/addressQueryClassifier.js | 2 +- .../address_runtime/decomposeStage.js | 4 +- llm_normalizer/backend/src/config.ts | 1 + .../backend/src/routes/sharedLlmConfig.ts | 124 ++++++++++++++++++ llm_normalizer/backend/src/server.ts | 2 + .../src/services/addressIntentResolver.ts | 4 +- .../src/services/addressQueryClassifier.ts | 2 +- .../address_runtime/decomposeStage.ts | 4 +- ...essInventorySelectedObjectFollowup.test.ts | 54 ++++++++ .../assistantAddressFollowupContext.test.ts | 106 +++++++++++++++ .../data/shared_llm_connection.json | 11 ++ .../frontend/dist/assets/index-B9mz4jx4.js | 26 ---- .../frontend/dist/assets/index-Qq5WpuqR.js | 26 ++++ llm_normalizer/frontend/dist/index.html | 2 +- llm_normalizer/frontend/src/App.tsx | 82 +++++++++--- llm_normalizer/frontend/src/api/client.ts | 26 ++++ .../src/components/ConnectionPanel.tsx | 106 +++++++++++++-- scripts/domain_case_loop.py | 56 +++++++- tests/test_domain_case_loop.py | 60 +++++++++ 24 files changed, 801 insertions(+), 73 deletions(-) create mode 100644 llm_normalizer/backend/dist/routes/sharedLlmConfig.js create mode 100644 llm_normalizer/backend/src/routes/sharedLlmConfig.ts create mode 100644 llm_normalizer/data/shared_llm_connection.json delete mode 100644 llm_normalizer/frontend/dist/assets/index-B9mz4jx4.js create mode 100644 llm_normalizer/frontend/dist/assets/index-Qq5WpuqR.js diff --git a/docs/orchestration/active_domain_contract.json b/docs/orchestration/active_domain_contract.json index 0528486..cc9a035 100644 --- a/docs/orchestration/active_domain_contract.json +++ b/docs/orchestration/active_domain_contract.json @@ -41,8 +41,8 @@ "buyer_candidate": "Департамент капитального ремонта города Москвы" }, "question_pool": { - "total_questions": 30, - "core_questions_total": 21, + "total_questions": 31, + "core_questions_total": 22, "followup_checkpoints_total": 9, "questions": [ { @@ -279,6 +279,15 @@ "wording_family": "ui_selected_object_colloquial", "semantic_goal": "проверить разговорный selected-object follow-up про поставщика без слова `поставщик`" }, + { + "question_id": "Q31", + "text": "По выбранному объекту \"...\": у кого куплено", + "layer": "selected_item_provenance", + "node_id": "N03_selected_item_supplier", + "role": "critical_child", + "wording_family": "ui_selected_object_colloquial", + "semantic_goal": "проверить selected-object follow-up с краткой страдательной формой `у кого куплено`, который должен оставаться в supplier provenance и наследовать историческую дату root-среза" + }, { "question_id": "Q29", "text": "По выбранному объекту \"...\": где мы купили это", @@ -1032,6 +1041,51 @@ "organization_scope" ] }, + { + "step_id": "step_03bb_selected_item_supplier_u_kogo_kupleno", + "question_id": "Q31", + "node_id": "N03_selected_item_supplier", + "node_role": "critical_child", + "paraphrase_family": "ui_selected_object_colloquial", + "title": "Selected item supplier passive colloquial wording", + "question": "По выбранному объекту \"{{bindings.focus_item_historical}}\": у кого куплено", + "depends_on": [ + "step_01_snapshot_historical" + ], + "analysis_context": { + "as_of_date": "2019-03-31", + "source": "binding_target_date_historical" + }, + "expected_capability": "inventory_purchase_provenance_for_item", + "forbidden_capabilities": [ + "confirmed_inventory_on_hand_as_of_date" + ], + "forbidden_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "required_state_objects": [ + "focus_object" + ], + "required_carryover_invariants": [ + "selected_object", + "focus_object", + "date_scope", + "warehouse_scope", + "organization_scope" + ], + "required_filters": { + "as_of_date": "2019-03-31", + "period_from": "2019-03-01", + "period_to": "2019-03-31" + }, + "invariant_severity": { + "wrong_as_of_date": "P0", + "wrong_period_from": "P0", + "wrong_period_to": "P0", + "forbidden_route_selected": "P0", + "focus_object_missing": "P0" + } + }, { "step_id": "step_03c_selected_item_supplier_gde_my_kupili", "question_id": "Q29", @@ -1852,7 +1906,7 @@ }, { "pattern_id": "F12b_selected_object_supplier_u_kogo_kupili_misroute", - "symptom": "selected-object follow-up such as `у кого купили` stays on the root stock snapshot instead of switching to selected-item provenance", + "symptom": "selected-object follow-up such as `у кого купили` or `у кого куплено` stays on the root stock snapshot instead of switching to selected-item provenance", "defect_class": "followup_action_resolution_gap" }, { diff --git a/llm_normalizer/backend/dist/config.js b/llm_normalizer/backend/dist/config.js index 9dc1cbd..f1b1b27 100644 --- a/llm_normalizer/backend/dist/config.js +++ b/llm_normalizer/backend/dist/config.js @@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TRACES_DIR = exports.DATA_DIR = exports.VAT_PAYABLE_19_PREFIXES = exports.VAT_PAYABLE_68_PREFIXES = exports.ASSISTANT_MCP_LIVE_LIMIT = exports.ASSISTANT_MCP_TIMEOUT_MS = exports.ASSISTANT_MCP_CHANNEL = exports.ASSISTANT_MCP_PROXY_URL = exports.FEATURE_ASSISTANT_LIVING_CHAT_ROUTER_V1 = exports.FEATURE_ASSISTANT_ROUTE_EXPECTATION_HARD_GUARD_V1 = exports.FEATURE_ASSISTANT_ROUTE_EXPECTATION_AUDIT_V1 = exports.FEATURE_ASSISTANT_ROUTE_SHADOW_PAYABLES_EXACT_V1 = exports.FEATURE_ASSISTANT_ROUTE_RECEIVABLES_HEURISTIC_V1 = exports.FEATURE_ASSISTANT_ROUTE_PAYABLES_HEURISTIC_V1 = exports.FEATURE_ASSISTANT_ROUTE_RECEIVABLES_CONFIRMED_V1 = exports.FEATURE_ASSISTANT_ROUTE_PAYABLES_CONFIRMED_V1 = exports.FEATURE_ASSISTANT_ROUTE_BALANCE_EXACT_V1 = exports.FEATURE_ASSISTANT_ROUTE_DRILLDOWN_V1 = exports.FEATURE_ASSISTANT_ROUTE_ADDRESS_GENERIC_V1 = exports.FEATURE_ASSISTANT_CAPABILITY_ROUTE_GUARD_V1 = exports.FEATURE_ASSISTANT_ADDRESS_NAVIGATION_STATE_V1 = exports.FEATURE_ASSISTANT_ADDRESS_QUERY_LIVE_V1 = exports.FEATURE_ASSISTANT_ADDRESS_QUERY_LLM_PREDECOMPOSE_V1 = exports.FEATURE_ASSISTANT_ADDRESS_QUERY_V1 = exports.FEATURE_ASSISTANT_MCP_RUNTIME_V1 = exports.FEATURE_ASSISTANT_GRAPH_RUNTIME_V1 = exports.FEATURE_ASSISTANT_LIFECYCLE_ANSWER_V1 = exports.FEATURE_ASSISTANT_LIFECYCLE_RUNTIME_V1 = exports.FEATURE_ASSISTANT_STAGE2_EVAL_V1 = exports.FEATURE_ASSISTANT_PROBLEM_UNIT_CONTINUITY_V1 = exports.FEATURE_ASSISTANT_PROBLEM_CENTRIC_ANSWER_V1 = exports.FEATURE_ASSISTANT_PROBLEM_UNITS_V1 = exports.FEATURE_ASSISTANT_ACCOUNTANT_EVAL_V1 = exports.FEATURE_ASSISTANT_ANSWER_POLICY_V11 = exports.FEATURE_ASSISTANT_ANTI_GENERIC_RANKING_GUARD_V1 = exports.FEATURE_ASSISTANT_MIN_EVIDENCE_GATE_V1 = exports.FEATURE_ASSISTANT_BROAD_GUARD_V1 = exports.FEATURE_ASSISTANT_EVIDENCE_ENRICHMENT_V1 = exports.FEATURE_ASSISTANT_STATE_FOLLOWUP_BINDING_V1 = exports.FEATURE_ASSISTANT_CONTRACTS_V11 = exports.FEATURE_ASSISTANT_INVESTIGATION_STATE_V1 = exports.DEFAULT_PROMPT_VERSION = exports.DEFAULT_MAX_OUTPUT_TOKENS = exports.DEFAULT_TEMPERATURE = exports.DEFAULT_MODEL = exports.DEFAULT_OPENAI_BASE_URL = exports.TIMEZONE = exports.PORT = exports.MODULE_ROOT = exports.BACKEND_ROOT = void 0; -exports.MANUAL_CASE_DECISION_SCHEMA_FILE = exports.ASSISTANT_CAPABILITIES_REGISTRY_FILE = exports.ASSISTANT_CANON_FILE = exports.ARCH_EXPORT_2020_DIR = exports.SCHEMAS_DIR = exports.EVAL_DATASETS_DIR = exports.REPORTS_DIR = exports.PROMPTS_DIR = exports.AUTORUN_GENERATOR_HISTORY_FILE = exports.AUTORUN_GENERATOR_DIR = exports.AUTORUN_ANNOTATIONS_FILE = exports.AUTORUN_ANNOTATIONS_DIR = exports.ASSISTANT_ANNOTATIONS_FILE = exports.ASSISTANT_ANNOTATIONS_DIR = exports.ASSISTANT_SESSIONS_DIR = exports.EVAL_CASES_DIR = exports.PRESETS_DIR = void 0; +exports.MANUAL_CASE_DECISION_SCHEMA_FILE = exports.ASSISTANT_CAPABILITIES_REGISTRY_FILE = exports.ASSISTANT_CANON_FILE = exports.ARCH_EXPORT_2020_DIR = exports.SCHEMAS_DIR = exports.EVAL_DATASETS_DIR = exports.REPORTS_DIR = exports.PROMPTS_DIR = exports.SHARED_LLM_CONNECTION_FILE = exports.AUTORUN_GENERATOR_HISTORY_FILE = exports.AUTORUN_GENERATOR_DIR = exports.AUTORUN_ANNOTATIONS_FILE = exports.AUTORUN_ANNOTATIONS_DIR = exports.ASSISTANT_ANNOTATIONS_FILE = exports.ASSISTANT_ANNOTATIONS_DIR = exports.ASSISTANT_SESSIONS_DIR = exports.EVAL_CASES_DIR = exports.PRESETS_DIR = void 0; const path_1 = __importDefault(require("path")); exports.BACKEND_ROOT = path_1.default.resolve(__dirname, ".."); exports.MODULE_ROOT = path_1.default.resolve(exports.BACKEND_ROOT, ".."); @@ -90,6 +90,7 @@ exports.AUTORUN_ANNOTATIONS_DIR = path_1.default.resolve(exports.DATA_DIR, "auto exports.AUTORUN_ANNOTATIONS_FILE = path_1.default.resolve(exports.AUTORUN_ANNOTATIONS_DIR, "annotations.json"); exports.AUTORUN_GENERATOR_DIR = path_1.default.resolve(exports.DATA_DIR, "autorun_generators"); exports.AUTORUN_GENERATOR_HISTORY_FILE = path_1.default.resolve(exports.AUTORUN_GENERATOR_DIR, "history.json"); +exports.SHARED_LLM_CONNECTION_FILE = path_1.default.resolve(exports.DATA_DIR, "shared_llm_connection.json"); exports.PROMPTS_DIR = path_1.default.resolve(exports.MODULE_ROOT, "prompts"); exports.REPORTS_DIR = path_1.default.resolve(exports.MODULE_ROOT, "reports"); exports.EVAL_DATASETS_DIR = path_1.default.resolve(exports.MODULE_ROOT, "eval_cases"); diff --git a/llm_normalizer/backend/dist/routes/sharedLlmConfig.js b/llm_normalizer/backend/dist/routes/sharedLlmConfig.js new file mode 100644 index 0000000..addb5b5 --- /dev/null +++ b/llm_normalizer/backend/dist/routes/sharedLlmConfig.js @@ -0,0 +1,107 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.buildSharedLlmConfigRouter = buildSharedLlmConfigRouter; +const express_1 = require("express"); +const config_1 = require("../config"); +const http_1 = require("../utils/http"); +const files_1 = require("../utils/files"); +const path_1 = __importDefault(require("path")); +function sanitizeString(value, fallback) { + if (typeof value !== "string") { + return fallback; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : fallback; +} +function sanitizeNumber(value, fallback) { + if (typeof value === "number" && Number.isFinite(value)) { + return value; + } + if (typeof value === "string" && value.trim().length > 0) { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + return parsed; + } + } + return fallback; +} +function buildFallbackRecord() { + return { + schema_version: "shared_llm_connection_v1", + updated_at: "", + connection: { + llmProvider: "local", + model: "qwen2.5-14b-instruct-1m", + baseUrl: "http://127.0.0.1:1234/v1", + temperature: 0, + maxOutputTokens: 900 + } + }; +} +function loadSharedRecord() { + const fallback = buildFallbackRecord(); + const parsed = (0, files_1.readJsonFile)(config_1.SHARED_LLM_CONNECTION_FILE, null); + if (!parsed || typeof parsed !== "object" || !("connection" in parsed) || !parsed.connection) { + return null; + } + const connection = parsed.connection; + return { + schema_version: "shared_llm_connection_v1", + updated_at: sanitizeString(parsed.updated_at, ""), + connection: { + llmProvider: connection.llmProvider === "local" ? "local" : "openai", + model: sanitizeString(connection.model, fallback.connection.model), + baseUrl: sanitizeString(connection.baseUrl, fallback.connection.baseUrl), + temperature: sanitizeNumber(connection.temperature, fallback.connection.temperature), + maxOutputTokens: Math.max(1, Math.trunc(sanitizeNumber(connection.maxOutputTokens, fallback.connection.maxOutputTokens))) + } + }; +} +function buildSharedLlmConfigRouter() { + const router = (0, express_1.Router)(); + router.get("/api/llm/shared-connection", (_req, res, next) => { + try { + const record = loadSharedRecord(); + (0, http_1.ok)(res, { + ok: true, + connection: record?.connection ?? null, + updated_at: record?.updated_at ?? null, + exists: Boolean(record) + }); + } + catch (error) { + next(error); + } + }); + router.post("/api/llm/shared-connection", (req, res, next) => { + try { + const body = (req.body ?? {}); + const fallback = buildFallbackRecord(); + const record = { + schema_version: "shared_llm_connection_v1", + updated_at: new Date().toISOString(), + connection: { + llmProvider: body.llmProvider === "local" ? "local" : "openai", + model: sanitizeString(body.model, fallback.connection.model), + baseUrl: sanitizeString(body.baseUrl, fallback.connection.baseUrl), + temperature: sanitizeNumber(body.temperature, fallback.connection.temperature), + maxOutputTokens: Math.max(1, Math.trunc(sanitizeNumber(body.maxOutputTokens, fallback.connection.maxOutputTokens))) + } + }; + (0, files_1.ensureDir)(path_1.default.dirname(config_1.SHARED_LLM_CONNECTION_FILE)); + (0, files_1.writeJsonFile)(config_1.SHARED_LLM_CONNECTION_FILE, record); + (0, http_1.ok)(res, { + ok: true, + connection: record.connection, + updated_at: record.updated_at + }); + } + catch (error) { + next(error); + } + }); + return router; +} diff --git a/llm_normalizer/backend/dist/server.js b/llm_normalizer/backend/dist/server.js index 7dbd252..5f07467 100644 --- a/llm_normalizer/backend/dist/server.js +++ b/llm_normalizer/backend/dist/server.js @@ -15,6 +15,7 @@ const eval_1 = require("./routes/eval"); const history_1 = require("./routes/history"); const normalize_1 = require("./routes/normalize"); const presets_1 = require("./routes/presets"); +const sharedLlmConfig_1 = require("./routes/sharedLlmConfig"); const testConnection_1 = require("./routes/testConnection"); const inMemoryRuntimeAdapter_1 = require("./runtime/inMemoryRuntimeAdapter"); const assistantService_1 = require("./services/assistantService"); @@ -59,6 +60,7 @@ function createApp() { }); }); app.use((0, testConnection_1.buildTestConnectionRouter)(openaiClient)); + app.use((0, sharedLlmConfig_1.buildSharedLlmConfigRouter)()); app.use((0, normalize_1.buildNormalizeRouter)(services)); app.use((0, eval_1.buildEvalRouter)(services)); app.use((0, assistant_1.buildAssistantRouter)(services)); diff --git a/llm_normalizer/backend/dist/services/addressIntentResolver.js b/llm_normalizer/backend/dist/services/addressIntentResolver.js index 2fecb07..7b49328 100644 --- a/llm_normalizer/backend/dist/services/addressIntentResolver.js +++ b/llm_normalizer/backend/dist/services/addressIntentResolver.js @@ -1345,7 +1345,7 @@ function hasSelectedObjectInventoryCue(text) { } function hasSelectedObjectInventoryProvenanceSignal(text) { return (hasSelectedObjectInventoryCue(text) && - /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test(text)); + /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test(text)); } function hasSelectedObjectInventoryPurchaseDocumentsSignal(text) { return (hasSelectedObjectInventoryCue(text) && @@ -1353,7 +1353,7 @@ function hasSelectedObjectInventoryPurchaseDocumentsSignal(text) { } function hasInventoryProvenanceSignalV2(text) { const hasItemCue = /(?:товар|номенклатур|sku|item|product|остат(?:ок|ки)|склад)/iu.test(text); - const hasSupplierCue = /(?:от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:нам\s+)?поставил|кем\s+поставлен|поставщик|supplier|vendor)/iu.test(text); + const hasSupplierCue = /(?:от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:нам\s+)?поставил|кем\s+поставлен|поставщик|supplier|vendor)/iu.test(text); const hasPurchaseCue = /(?:куплен(?:ы|а|о)?|закупк|происхождени|откуда|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|когда\s+был\s+куплен|когда\s+куплен|дата\s+закупк|кто\s+(?:нам\s+)?поставил|кем\s+поставлен|поставлен(?:ы|а)?|purchase\s+provenance|purchase\s+date)/iu.test(text); return hasItemCue && hasSupplierCue && hasPurchaseCue; } diff --git a/llm_normalizer/backend/dist/services/addressQueryClassifier.js b/llm_normalizer/backend/dist/services/addressQueryClassifier.js index c230035..6906d78 100644 --- a/llm_normalizer/backend/dist/services/addressQueryClassifier.js +++ b/llm_normalizer/backend/dist/services/addressQueryClassifier.js @@ -269,7 +269,7 @@ function hasSelectedObjectInventoryFollowupSignal(text) { if (!/(?:по\s+выбранному\s+объекту|по\s+выбранной\s+позиции)/iu.test(text)) { return false; } - return /(?:у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:поставил|продал)|кому\s+(?:продали|реализовали)|когда\s+(?:примерно\s+)?купили|по\s+каким\s+документам\s+.*купили)/iu.test(text); + return /(?:у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:поставил|продал)|кому\s+(?:продали|реализовали)|когда\s+(?:примерно\s+)?купили|по\s+каким\s+документам\s+.*купили)/iu.test(text); } function hasDocsOrBankSignal(text) { return /(?:док(?:и|умент|ументы|ументов)|docs?|documents?|банк|выписк|платеж|платёж|оплат|поступлен|списан|транзак|transactions?|bank\s+ops|bank\s+operations?)/iu.test(text); diff --git a/llm_normalizer/backend/dist/services/address_runtime/decomposeStage.js b/llm_normalizer/backend/dist/services/address_runtime/decomposeStage.js index 64fb5f7..336f31a 100644 --- a/llm_normalizer/backend/dist/services/address_runtime/decomposeStage.js +++ b/llm_normalizer/backend/dist/services/address_runtime/decomposeStage.js @@ -25,7 +25,7 @@ function hasSameDateHint(text) { return /(?:на\s+ту\s+же\s+дат[ауеы]|на\s+эту\s+же\s+дат[ауеы]|на\s+эту\s+дат[ауеы]|эту\s+дат[ауеы]|та\s+же\s+дата|same\s+date|as\s+of\s+same\s+date|the\s+same\s+date)/iu.test(String(text ?? "")); } function hasExplicitPeriodLiteral(text) { - return /\b(?:19|20)\d{2}(?:[./-](?:0?[1-9]|1[0-2]))?\b/.test(String(text ?? "")); + return /(?:^|[^\d*×xх])((?:19|20)\d{2}(?:[./-](?:0?[1-9]|1[0-2]))?)(?=$|[^\d*×xх])/iu.test(String(text ?? "")); } function hasExplicitCurrentDateHint(text) { return /(?:на\s+текущ(?:ую|ая|ий|ее|ей|ем|его)\s+дат(?:у|а|е|ой|ою)|на\s+сегодняшн(?:юю|ий|ей|ем|его)\s+дат(?:у|а|е|ой|ою)|на\s+сегодня|сегодня|на\s+текущ(?:ий|ую)\s+момент|today|as\s+of\s+today|current\s+date|as\s+of\s+current\s+date)/iu.test(String(text ?? "")); @@ -257,7 +257,7 @@ function hasSelectedObjectInventorySignal(text) { return /(?:по\s+выбранному\s+объекту|for\s+selected\s+object)/iu.test(String(text ?? "")); } function hasInventorySupplierFollowupCue(text) { - return /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test(String(text ?? "")); + return /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test(String(text ?? "")); } function hasInventoryPurchaseDocumentsFollowupCue(text) { return /(?:по\s+каким\s+документам\s+(?:это|его|этот\s+товар|эту\s+позицию)\s+купили|по\s+каким\s+документам\s+(?:был\s+)?куплен|какими\s+документами\s+(?:это|его|этот\s+товар|эту\s+позицию)\s+купили|какими\s+документами\s+(?:был\s+)?куплен|покажи\s+документы\s+по\s+(?:этой\s+позиции|этому\s+товару|ней|нему)|документы\s+по\s+(?:этой\s+позиции|этому\s+товару|ней|нему)|purchase\s+documents|documents\s+of\s+purchase|through\s+which\s+documents)/iu.test(String(text ?? "")); diff --git a/llm_normalizer/backend/src/config.ts b/llm_normalizer/backend/src/config.ts index 933f898..0326c64 100644 --- a/llm_normalizer/backend/src/config.ts +++ b/llm_normalizer/backend/src/config.ts @@ -188,6 +188,7 @@ export const AUTORUN_ANNOTATIONS_DIR = path.resolve(DATA_DIR, "autorun_annotatio export const AUTORUN_ANNOTATIONS_FILE = path.resolve(AUTORUN_ANNOTATIONS_DIR, "annotations.json"); export const AUTORUN_GENERATOR_DIR = path.resolve(DATA_DIR, "autorun_generators"); export const AUTORUN_GENERATOR_HISTORY_FILE = path.resolve(AUTORUN_GENERATOR_DIR, "history.json"); +export const SHARED_LLM_CONNECTION_FILE = path.resolve(DATA_DIR, "shared_llm_connection.json"); export const PROMPTS_DIR = path.resolve(MODULE_ROOT, "prompts"); export const REPORTS_DIR = path.resolve(MODULE_ROOT, "reports"); diff --git a/llm_normalizer/backend/src/routes/sharedLlmConfig.ts b/llm_normalizer/backend/src/routes/sharedLlmConfig.ts new file mode 100644 index 0000000..f91b5ba --- /dev/null +++ b/llm_normalizer/backend/src/routes/sharedLlmConfig.ts @@ -0,0 +1,124 @@ +import { NextFunction, Request, Response, Router } from "express"; +import { SHARED_LLM_CONNECTION_FILE } from "../config"; +import { ok } from "../utils/http"; +import { ensureDir, readJsonFile, writeJsonFile } from "../utils/files"; +import path from "path"; + +type LlmProvider = "openai" | "local"; + +interface SharedLlmConnectionRecord { + schema_version: "shared_llm_connection_v1"; + updated_at: string; + connection: { + llmProvider: LlmProvider; + model: string; + baseUrl: string; + temperature: number; + maxOutputTokens: number; + }; +} + +function sanitizeString(value: unknown, fallback: string): string { + if (typeof value !== "string") { + return fallback; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : fallback; +} + +function sanitizeNumber(value: unknown, fallback: number): number { + if (typeof value === "number" && Number.isFinite(value)) { + return value; + } + if (typeof value === "string" && value.trim().length > 0) { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + return parsed; + } + } + return fallback; +} + +function buildFallbackRecord(): SharedLlmConnectionRecord { + return { + schema_version: "shared_llm_connection_v1", + updated_at: "", + connection: { + llmProvider: "local", + model: "qwen2.5-14b-instruct-1m", + baseUrl: "http://127.0.0.1:1234/v1", + temperature: 0, + maxOutputTokens: 900 + } + }; +} + +function loadSharedRecord(): SharedLlmConnectionRecord | null { + const fallback = buildFallbackRecord(); + const parsed = readJsonFile(SHARED_LLM_CONNECTION_FILE, null); + if (!parsed || typeof parsed !== "object" || !("connection" in parsed) || !parsed.connection) { + return null; + } + const connection = parsed.connection; + return { + schema_version: "shared_llm_connection_v1", + updated_at: sanitizeString(parsed.updated_at, ""), + connection: { + llmProvider: connection.llmProvider === "local" ? "local" : "openai", + model: sanitizeString(connection.model, fallback.connection.model), + baseUrl: sanitizeString(connection.baseUrl, fallback.connection.baseUrl), + temperature: sanitizeNumber(connection.temperature, fallback.connection.temperature), + maxOutputTokens: Math.max(1, Math.trunc(sanitizeNumber(connection.maxOutputTokens, fallback.connection.maxOutputTokens))) + } + }; +} + +export function buildSharedLlmConfigRouter(): Router { + const router = Router(); + + router.get("/api/llm/shared-connection", (_req: Request, res: Response, next: NextFunction) => { + try { + const record = loadSharedRecord(); + ok(res, { + ok: true, + connection: record?.connection ?? null, + updated_at: record?.updated_at ?? null, + exists: Boolean(record) + }); + } catch (error) { + next(error); + } + }); + + router.post("/api/llm/shared-connection", (req: Request, res: Response, next: NextFunction) => { + try { + const body = (req.body ?? {}) as Record; + const fallback = buildFallbackRecord(); + const record: SharedLlmConnectionRecord = { + schema_version: "shared_llm_connection_v1", + updated_at: new Date().toISOString(), + connection: { + llmProvider: body.llmProvider === "local" ? "local" : "openai", + model: sanitizeString(body.model, fallback.connection.model), + baseUrl: sanitizeString(body.baseUrl, fallback.connection.baseUrl), + temperature: sanitizeNumber(body.temperature, fallback.connection.temperature), + maxOutputTokens: Math.max( + 1, + Math.trunc(sanitizeNumber(body.maxOutputTokens, fallback.connection.maxOutputTokens)) + ) + } + }; + ensureDir(path.dirname(SHARED_LLM_CONNECTION_FILE)); + writeJsonFile(SHARED_LLM_CONNECTION_FILE, record); + ok(res, { + ok: true, + connection: record.connection, + updated_at: record.updated_at + }); + } catch (error) { + next(error); + } + }); + + return router; +} diff --git a/llm_normalizer/backend/src/server.ts b/llm_normalizer/backend/src/server.ts index ae699a8..f715445 100644 --- a/llm_normalizer/backend/src/server.ts +++ b/llm_normalizer/backend/src/server.ts @@ -20,6 +20,7 @@ import { buildEvalRouter } from "./routes/eval"; import { buildHistoryRouter } from "./routes/history"; import { buildNormalizeRouter } from "./routes/normalize"; import { buildPresetsRouter } from "./routes/presets"; +import { buildSharedLlmConfigRouter } from "./routes/sharedLlmConfig"; import { buildTestConnectionRouter } from "./routes/testConnection"; import { InMemoryRuntimeAdapter } from "./runtime/inMemoryRuntimeAdapter"; import { AssistantService } from "./services/assistantService"; @@ -71,6 +72,7 @@ export function createApp(): express.Express { }); app.use(buildTestConnectionRouter(openaiClient)); + app.use(buildSharedLlmConfigRouter()); app.use(buildNormalizeRouter(services)); app.use(buildEvalRouter(services)); app.use(buildAssistantRouter(services)); diff --git a/llm_normalizer/backend/src/services/addressIntentResolver.ts b/llm_normalizer/backend/src/services/addressIntentResolver.ts index a370fcf..d61026f 100644 --- a/llm_normalizer/backend/src/services/addressIntentResolver.ts +++ b/llm_normalizer/backend/src/services/addressIntentResolver.ts @@ -1612,7 +1612,7 @@ function hasSelectedObjectInventoryCue(text: string): boolean { function hasSelectedObjectInventoryProvenanceSignal(text: string): boolean { return ( hasSelectedObjectInventoryCue(text) && - /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test( + /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test( text ) ); @@ -1630,7 +1630,7 @@ function hasSelectedObjectInventoryPurchaseDocumentsSignal(text: string): boolea function hasInventoryProvenanceSignalV2(text: string): boolean { const hasItemCue = /(?:товар|номенклатур|sku|item|product|остат(?:ок|ки)|склад)/iu.test(text); const hasSupplierCue = - /(?:от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:нам\s+)?поставил|кем\s+поставлен|поставщик|supplier|vendor)/iu.test( + /(?:от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:нам\s+)?поставил|кем\s+поставлен|поставщик|supplier|vendor)/iu.test( text ); const hasPurchaseCue = diff --git a/llm_normalizer/backend/src/services/addressQueryClassifier.ts b/llm_normalizer/backend/src/services/addressQueryClassifier.ts index 5b58c75..a475366 100644 --- a/llm_normalizer/backend/src/services/addressQueryClassifier.ts +++ b/llm_normalizer/backend/src/services/addressQueryClassifier.ts @@ -278,7 +278,7 @@ function hasSelectedObjectInventoryFollowupSignal(text: string): boolean { if (!/(?:по\s+выбранному\s+объекту|по\s+выбранной\s+позиции)/iu.test(text)) { return false; } - return /(?:у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:поставил|продал)|кому\s+(?:продали|реализовали)|когда\s+(?:примерно\s+)?купили|по\s+каким\s+документам\s+.*купили)/iu.test( + return /(?:у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|товар|позицию))?|где\s+куплено|кто\s+(?:поставил|продал)|кому\s+(?:продали|реализовали)|когда\s+(?:примерно\s+)?купили|по\s+каким\s+документам\s+.*купили)/iu.test( text ); } diff --git a/llm_normalizer/backend/src/services/address_runtime/decomposeStage.ts b/llm_normalizer/backend/src/services/address_runtime/decomposeStage.ts index 10f92ee..08cbb37 100644 --- a/llm_normalizer/backend/src/services/address_runtime/decomposeStage.ts +++ b/llm_normalizer/backend/src/services/address_runtime/decomposeStage.ts @@ -59,7 +59,7 @@ function hasSameDateHint(text: string): boolean { } function hasExplicitPeriodLiteral(text: string): boolean { - return /\b(?:19|20)\d{2}(?:[./-](?:0?[1-9]|1[0-2]))?\b/.test(String(text ?? "")); + return /(?:^|[^\d*×xх])((?:19|20)\d{2}(?:[./-](?:0?[1-9]|1[0-2]))?)(?=$|[^\d*×xх])/iu.test(String(text ?? "")); } function hasExplicitCurrentDateHint(text: string): boolean { @@ -323,7 +323,7 @@ function hasSelectedObjectInventorySignal(text: string): boolean { } function hasInventorySupplierFollowupCue(text: string): boolean { - return /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test( + return /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test( String(text ?? "") ); } diff --git a/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts b/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts index db1f1c8..0e24036 100644 --- a/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts +++ b/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts @@ -245,6 +245,60 @@ describe("inventory selected-object follow-up", () => { expect(String(result?.reply_text ?? "")).toContain("ООО \\Производство мебели\\"); }); + it("handles selected-object colloquial supplier wording 'у кого куплено' as provenance follow-up", async () => { + executeAddressMcpQueryMock.mockResolvedValueOnce({ + fetched_rows: 1, + matched_rows: 1, + raw_rows: [ + { + Period: "2020-06-18T00:00:00Z", + Registrator: "Поступление товаров и услуг 00000000101 от 18.06.2020 0:00:00", + AccountDt: "41.01", + AccountKt: "60.01", + Amount: 498472.5, + SubcontoDt1: "Конструкция трансформер рабочей станции 1300*900*2000", + SubcontoDt3: "Основной склад", + SubcontoKt1: "ООО \\Гамма-мебель\\", + SubcontoKt2: "Договор поставки № 11 от 15.06.2020", + Organization: "ООО \\Альтернатива Плюс\\" + } + ], + rows: [], + error: null + }); + + const service = new AddressQueryService(); + const result = await service.tryHandle( + 'По выбранному объекту "Конструкция трансформер рабочей станции 1300*900*2000": у кого куплено', + { + followupContext: { + previous_intent: "inventory_on_hand_as_of_date", + previous_filters: { + as_of_date: "2020-06-30", + period_from: "2020-06-01", + period_to: "2020-06-30", + warehouse: "Основной склад", + organization: "ООО \\Альтернатива Плюс\\" + }, + previous_anchor_type: "unknown", + previous_anchor_value: null + } + } + ); + + expect(result?.handled).toBe(true); + expect(result?.response_type).toBe("FACTUAL_SUMMARY"); + expect(result?.debug.detected_intent).toBe("inventory_purchase_provenance_for_item"); + expect(result?.debug.selected_recipe).toBe("address_inventory_purchase_provenance_for_item_v1"); + expect(result?.debug.extracted_filters?.item).toBe("Конструкция трансформер рабочей станции 1300*900*2000"); + expect(result?.debug.extracted_filters?.as_of_date).toBe("2020-06-30"); + expect(result?.debug.extracted_filters?.period_from).toBe("2020-06-01"); + expect(result?.debug.extracted_filters?.period_to).toBe("2020-06-30"); + expect(result?.debug.capability_id).toBe("inventory_inventory_purchase_provenance_for_item"); + expect(result?.debug.capability_route_mode).toBe("exact"); + expect(String(result?.reply_text ?? "")).toContain("ООО \\Гамма-мебель\\"); + }); + it("handles selected-object wording 'где мы купили это' as provenance follow-up", async () => { executeAddressMcpQueryMock.mockResolvedValueOnce({ fetched_rows: 1, diff --git a/llm_normalizer/backend/tests/assistantAddressFollowupContext.test.ts b/llm_normalizer/backend/tests/assistantAddressFollowupContext.test.ts index b3bbcce..6967215 100644 --- a/llm_normalizer/backend/tests/assistantAddressFollowupContext.test.ts +++ b/llm_normalizer/backend/tests/assistantAddressFollowupContext.test.ts @@ -373,6 +373,112 @@ describe("assistant address follow-up carryover", () => { expect(normalizerService.normalize).not.toHaveBeenCalled(); }); + it("keeps historical stock date window for selected-object supplier wording 'у кого куплено'", async () => { + const calls: Array<{ message: string; options?: any }> = []; + const rootMessage = 'какие у нас остатки на складе на июнь 2020'; + const followupMessage = 'По выбранному объекту "Конструкция трансформер рабочей станции 1300*900*2000": у кого куплено'; + + const addressQueryService = { + tryHandle: vi.fn(async (message: string, options?: any) => { + calls.push({ message, options }); + if (message === rootMessage) { + return { + handled: true, + reply_text: + "На 30.06.2020 на складе подтверждено 12 позиций с остатком на 755.392,33 ₽.\n1. Конструкция трансформер рабочей станции 1300*900*2000 | склад: Основной склад", + reply_type: "factual", + response_type: "FACTUAL_LIST", + debug: { + detected_mode: "address_query", + detected_intent: "inventory_on_hand_as_of_date", + detected_intent_confidence: "high", + extracted_filters: { + as_of_date: "2020-06-30", + period_from: "2020-06-01", + period_to: "2020-06-30", + warehouse: "Основной склад", + organization: "ООО \\Альтернатива Плюс\\" + }, + selected_recipe: "address_inventory_on_hand_as_of_date_v1", + capability_id: "confirmed_inventory_on_hand_as_of_date", + capability_route_mode: "exact", + anchor_type: "unknown", + anchor_value_raw: null, + anchor_value_resolved: null, + reasons: ["address_action_detected", "address_entity_detected"] + } + }; + } + return { + handled: true, + reply_text: + "Поставщик по позиции Конструкция трансформер рабочей станции 1300*900*2000: ООО \\Гамма-мебель\\.", + reply_type: "factual", + response_type: "FACTUAL_SUMMARY", + debug: { + detected_mode: "address_query", + detected_intent: "inventory_purchase_provenance_for_item", + detected_intent_confidence: "medium", + extracted_filters: { + item: "Конструкция трансформер рабочей станции 1300*900*2000", + as_of_date: "2020-06-30", + period_from: "2020-06-01", + period_to: "2020-06-30" + }, + selected_recipe: "address_inventory_purchase_provenance_for_item_v1", + capability_id: "inventory_inventory_purchase_provenance_for_item", + capability_route_mode: "exact", + reasons: ["address_action_detected", "address_entity_detected", "address_followup_context_applied"] + }, + ...(options?.followupContext ? {} : {}) + }; + }) + } as any; + + const normalizerService = { + normalize: vi.fn(async () => ({ + assistant_reply: "normalizer_fallback_should_not_be_used", + reply_type: "partial_coverage", + debug: {} + })) + } as any; + + const sessions = new AssistantSessionStore(); + const service = new AssistantService( + normalizerService, + sessions as any, + {} as any, + { persistSession: vi.fn() } as any, + addressQueryService + ); + + const sessionId = `asst-address-followup-u-kogo-kupleno-${Date.now()}`; + const first = await service.handleMessage({ + session_id: sessionId, + user_message: rootMessage, + useMock: true + } as any); + expect(first.ok).toBe(true); + expect(first.reply_type).toBe("factual"); + + const second = await service.handleMessage({ + session_id: sessionId, + user_message: followupMessage, + useMock: true + } as any); + + expect(second.ok).toBe(true); + expect(second.reply_type).toBe("factual"); + expect(calls).toHaveLength(2); + expect(calls[1].message).toBe(followupMessage); + expect(calls[1].options?.followupContext?.previous_intent).toBe("inventory_on_hand_as_of_date"); + expect(calls[1].options?.followupContext?.previous_filters?.as_of_date).toBe("2020-06-30"); + expect(calls[1].options?.followupContext?.previous_filters?.period_from).toBe("2020-06-01"); + expect(calls[1].options?.followupContext?.previous_filters?.period_to).toBe("2020-06-30"); + expect(calls[1].options?.followupContext?.previous_filters?.warehouse).toBe("Основной склад"); + expect(normalizerService.normalize).not.toHaveBeenCalled(); + }); + it("treats typo imperative 'показывыай' as implicit continuation and switches to suggested follow-up intent", async () => { const calls: Array<{ message: string; options?: any }> = []; const firstMessage = "покажи документы по свк за 2020"; diff --git a/llm_normalizer/data/shared_llm_connection.json b/llm_normalizer/data/shared_llm_connection.json new file mode 100644 index 0000000..5beee2c --- /dev/null +++ b/llm_normalizer/data/shared_llm_connection.json @@ -0,0 +1,11 @@ +{ + "schema_version": "shared_llm_connection_v1", + "updated_at": "2026-04-15T06:12:46.714Z", + "connection": { + "llmProvider": "local", + "model": "unsloth/qwen3-30b-a3b-instruct-2507", + "baseUrl": "http://127.0.0.1:1234/v1", + "temperature": 0.8, + "maxOutputTokens": 900 + } +} \ No newline at end of file diff --git a/llm_normalizer/frontend/dist/assets/index-B9mz4jx4.js b/llm_normalizer/frontend/dist/assets/index-B9mz4jx4.js deleted file mode 100644 index 1bba361..0000000 --- a/llm_normalizer/frontend/dist/assets/index-B9mz4jx4.js +++ /dev/null @@ -1,26 +0,0 @@ -(function(){const p=document.createElement("link").relList;if(p&&p.supports&&p.supports("modulepreload"))return;for(const j of document.querySelectorAll('link[rel="modulepreload"]'))R(j);new MutationObserver(j=>{for(const T of j)if(T.type==="childList")for(const $ of T.addedNodes)$.tagName==="LINK"&&$.rel==="modulepreload"&&R($)}).observe(document,{childList:!0,subtree:!0});function m(j){const T={};return j.integrity&&(T.integrity=j.integrity),j.referrerPolicy&&(T.referrerPolicy=j.referrerPolicy),j.crossOrigin==="use-credentials"?T.credentials="include":j.crossOrigin==="anonymous"?T.credentials="omit":T.credentials="same-origin",T}function R(j){if(j.ep)return;j.ep=!0;const T=m(j);fetch(j.href,T)}})();function Oc(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Oi={exports:{}},to={},$i={exports:{}},he={};var mc;function yf(){if(mc)return he;mc=1;var i=Symbol.for("react.element"),p=Symbol.for("react.portal"),m=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),j=Symbol.for("react.profiler"),T=Symbol.for("react.provider"),$=Symbol.for("react.context"),Y=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),I=Symbol.for("react.memo"),W=Symbol.for("react.lazy"),z=Symbol.iterator;function U(h){return h===null||typeof h!="object"?null:(h=z&&h[z]||h["@@iterator"],typeof h=="function"?h:null)}var oe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Me=Object.assign,te={};function se(h,C,G){this.props=h,this.context=C,this.refs=te,this.updater=G||oe}se.prototype.isReactComponent={},se.prototype.setState=function(h,C){if(typeof h!="object"&&typeof h!="function"&&h!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,h,C,"setState")},se.prototype.forceUpdate=function(h){this.updater.enqueueForceUpdate(this,h,"forceUpdate")};function q(){}q.prototype=se.prototype;function re(h,C,G){this.props=h,this.context=C,this.refs=te,this.updater=G||oe}var Se=re.prototype=new q;Se.constructor=re,Me(Se,se.prototype),Se.isPureReactComponent=!0;var Pe=Array.isArray,Ae=Object.prototype.hasOwnProperty,De={current:null},$e={key:!0,ref:!0,__self:!0,__source:!0};function We(h,C,G){var ae,ce={},de=null,xe=null;if(C!=null)for(ae in C.ref!==void 0&&(xe=C.ref),C.key!==void 0&&(de=""+C.key),C)Ae.call(C,ae)&&!$e.hasOwnProperty(ae)&&(ce[ae]=C[ae]);var ge=arguments.length-2;if(ge===1)ce.children=G;else if(1>>1,C=D[h];if(0>>1;hj(ce,O))dej(xe,ce)?(D[h]=xe,D[de]=O,h=de):(D[h]=ce,D[ae]=O,h=ae);else if(dej(xe,O))D[h]=xe,D[de]=O,h=de;else break e}}return Q}function j(D,Q){var O=D.sortIndex-Q.sortIndex;return O!==0?O:D.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var T=performance;i.unstable_now=function(){return T.now()}}else{var $=Date,Y=$.now();i.unstable_now=function(){return $.now()-Y}}var F=[],I=[],W=1,z=null,U=3,oe=!1,Me=!1,te=!1,se=typeof setTimeout=="function"?setTimeout:null,q=typeof clearTimeout=="function"?clearTimeout:null,re=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function Se(D){for(var Q=m(I);Q!==null;){if(Q.callback===null)R(I);else if(Q.startTime<=D)R(I),Q.sortIndex=Q.expirationTime,p(F,Q);else break;Q=m(I)}}function Pe(D){if(te=!1,Se(D),!Me)if(m(F)!==null)Me=!0,Re(Ae);else{var Q=m(I);Q!==null&&me(Pe,Q.startTime-D)}}function Ae(D,Q){Me=!1,te&&(te=!1,q(We),We=-1),oe=!0;var O=U;try{for(Se(Q),z=m(F);z!==null&&(!(z.expirationTime>Q)||D&&!rt());){var h=z.callback;if(typeof h=="function"){z.callback=null,U=z.priorityLevel;var C=h(z.expirationTime<=Q);Q=i.unstable_now(),typeof C=="function"?z.callback=C:z===m(F)&&R(F),Se(Q)}else R(F);z=m(F)}if(z!==null)var G=!0;else{var ae=m(I);ae!==null&&me(Pe,ae.startTime-Q),G=!1}return G}finally{z=null,U=O,oe=!1}}var De=!1,$e=null,We=-1,Ge=5,Ze=-1;function rt(){return!(i.unstable_now()-ZeD||125h?(D.sortIndex=O,p(I,D),m(F)===null&&D===m(I)&&(te?(q(We),We=-1):te=!0,me(Pe,O-h))):(D.sortIndex=C,p(F,D),Me||oe||(Me=!0,Re(Ae))),D},i.unstable_shouldYield=rt,i.unstable_wrapCallback=function(D){var Q=U;return function(){var O=U;U=Q;try{return D.apply(this,arguments)}finally{U=O}}}})(Bi)),Bi}var yc;function jf(){return yc||(yc=1,Ui.exports=wf()),Ui.exports}var xc;function kf(){if(xc)return $t;xc=1;var i=Yi(),p=jf();function m(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),F=Object.prototype.hasOwnProperty,I=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,W={},z={};function U(e){return F.call(z,e)?!0:F.call(W,e)?!1:I.test(e)?z[e]=!0:(W[e]=!0,!1)}function oe(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Me(e,t,n,r){if(t===null||typeof t>"u"||oe(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function te(e,t,n,r,s,l,u){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=u}var se={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){se[e]=new te(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];se[t]=new te(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){se[e]=new te(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){se[e]=new te(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){se[e]=new te(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){se[e]=new te(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){se[e]=new te(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){se[e]=new te(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){se[e]=new te(e,5,!1,e.toLowerCase(),null,!1,!1)});var q=/[\-:]([a-z])/g;function re(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(q,re);se[t]=new te(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(q,re);se[t]=new te(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(q,re);se[t]=new te(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){se[e]=new te(e,1,!1,e.toLowerCase(),null,!1,!1)}),se.xlinkHref=new te("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){se[e]=new te(e,1,!1,e.toLowerCase(),null,!0,!0)});function Se(e,t,n,r){var s=se.hasOwnProperty(t)?se[t]:null;(s!==null?s.type!==0:r||!(2f||s[u]!==l[f]){var g=` -`+s[u].replace(" at new "," at ");return e.displayName&&g.includes("")&&(g=g.replace("",e.displayName)),g}while(1<=u&&0<=f);break}}}finally{G=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?C(e):""}function ce(e){switch(e.tag){case 5:return C(e.type);case 16:return C("Lazy");case 13:return C("Suspense");case 19:return C("SuspenseList");case 0:case 2:case 15:return e=ae(e.type,!1),e;case 11:return e=ae(e.type.render,!1),e;case 1:return e=ae(e.type,!0),e;default:return""}}function de(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case $e:return"Fragment";case De:return"Portal";case Ge:return"Profiler";case We:return"StrictMode";case Te:return"Suspense";case Fe:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case rt:return(e.displayName||"Context")+".Consumer";case Ze:return(e._context.displayName||"Context")+".Provider";case ie:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case fe:return t=e.displayName||null,t!==null?t:de(e.type)||"Memo";case Re:t=e._payload,e=e._init;try{return de(e(t))}catch{}}return null}function xe(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return de(t);case 8:return t===We?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ge(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ee(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ke(e){var t=ee(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,l=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(u){r=""+u,l.call(this,u)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(u){r=""+u},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ft(e){e._valueTracker||(e._valueTracker=ke(e))}function qn(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ee(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function An(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Tn(e,t){var n=t.checked;return O({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function dr(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ge(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Jt(e,t){t=t.checked,t!=null&&Se(e,"checked",t,!1)}function Yt(e,t){Jt(e,t);var n=ge(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?mn(e,t.type,n):t.hasOwnProperty("defaultValue")&&mn(e,t.type,ge(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Gn(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function mn(e,t,n){(t!=="number"||An(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Ut=Array.isArray;function Xt(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=en.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Bt(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var hn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Be=["Webkit","ms","Moz","O"];Object.keys(hn).forEach(function(e){Be.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),hn[t]=hn[e]})});function st(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||hn.hasOwnProperty(e)&&hn[e]?(""+t).trim():t+"px"}function gn(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=st(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var vn=O({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function tn(e,t){if(t){if(vn[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(m(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(m(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(m(61))}if(t.style!=null&&typeof t.style!="object")throw Error(m(62))}}function nn(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ct=null;function Dn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var rn=null,bt=null,vt=null;function Jn(e){if(e=Us(e)){if(typeof rn!="function")throw Error(m(280));var t=e.stateNode;t&&(t=yo(t),rn(e.stateNode,e.type,t))}}function Ke(e){bt?vt?vt.push(e):vt=[e]:bt=e}function hr(){if(bt){var e=bt,t=vt;if(vt=bt=null,Jn(e),t)for(e=0;e>>=0,e===0?32:31-(Cs(e)/Zr|0)|0}var Xn=64,Bn=4194304;function At(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function wt(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,l=e.pingedLanes,u=n&268435455;if(u!==0){var f=u&~s;f!==0?r=At(f):(l&=u,l!==0&&(r=At(l)))}else u=n&~s,u!==0?r=At(u):l!==0&&(r=At(l));if(r===0)return 0;if(t!==0&&t!==r&&(t&s)===0&&(s=r&-r,l=t&-t,s>=l||s===16&&(l&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ht(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-St(t),e[t]=n}function Vt(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=As),la=" ",ia=!1;function aa(e,t){switch(e){case"keyup":return fd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ua(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var rs=!1;function pd(e,t){switch(e){case"compositionend":return ua(t);case"keypress":return t.which!==32?null:(ia=!0,la);case"textInput":return e=t.data,e===la&&ia?null:e;default:return null}}function hd(e,t){if(rs)return e==="compositionend"||!vl&&aa(e,t)?(e=ea(),lo=dl=Sr=null,rs=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=ga(n)}}function ya(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ya(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xa(){for(var e=window,t=An();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=An(e.document)}return t}function _l(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function kd(e){var t=xa(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ya(n.ownerDocument.documentElement,n)){if(r!==null&&_l(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,l=Math.min(r.start,s);r=r.end===void 0?l:Math.min(r.end,s),!e.extend&&l>r&&(s=r,r=l,l=s),s=va(n,l);var u=va(n,r);s&&u&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),l>r?(e.addRange(t),e.extend(u.node,u.offset)):(t.setEnd(u.node,u.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ss=null,Sl=null,Ds=null,wl=!1;function _a(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;wl||ss==null||ss!==An(r)||(r=ss,"selectionStart"in r&&_l(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ds&&Ls(Ds,r)||(Ds=r,r=ho(Sl,"onSelect"),0us||(e.current=Ll[us],Ll[us]=null,us--)}function Le(e,t){us++,Ll[us]=e.current,e.current=t}var Cr={},ft=kr(Cr),It=kr(!1),Fr=Cr;function cs(e,t){var n=e.type.contextTypes;if(!n)return Cr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},l;for(l in n)s[l]=t[l];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Lt(e){return e=e.childContextTypes,e!=null}function xo(){Oe(It),Oe(ft)}function Da(e,t,n){if(ft.current!==Cr)throw Error(m(168));Le(ft,t),Le(It,n)}function za(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(m(108,xe(e)||"Unknown",s));return O({},n,r)}function _o(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cr,Fr=ft.current,Le(ft,e),Le(It,It.current),!0}function Oa(e,t,n){var r=e.stateNode;if(!r)throw Error(m(169));n?(e=za(e,t,Fr),r.__reactInternalMemoizedMergedChildContext=e,Oe(It),Oe(ft),Le(ft,e)):Oe(It),Le(It,n)}var nr=null,So=!1,Dl=!1;function $a(e){nr===null?nr=[e]:nr.push(e)}function zd(e){So=!0,$a(e)}function Nr(){if(!Dl&&nr!==null){Dl=!0;var e=0,t=d;try{var n=nr;for(d=1;e>=u,s-=u,rr=1<<32-St(t)+s|n<ne?(nt=Z,Z=null):nt=Z.sibling;var je=N(_,Z,S[ne],L);if(je===null){Z===null&&(Z=nt);break}e&&Z&&je.alternate===null&&t(_,Z),v=l(je,v,ne),X===null?K=je:X.sibling=je,X=je,Z=nt}if(ne===S.length)return n(_,Z),Ue&&Br(_,ne),K;if(Z===null){for(;nene?(nt=Z,Z=null):nt=Z.sibling;var Dr=N(_,Z,je.value,L);if(Dr===null){Z===null&&(Z=nt);break}e&&Z&&Dr.alternate===null&&t(_,Z),v=l(Dr,v,ne),X===null?K=Dr:X.sibling=Dr,X=Dr,Z=nt}if(je.done)return n(_,Z),Ue&&Br(_,ne),K;if(Z===null){for(;!je.done;ne++,je=S.next())je=M(_,je.value,L),je!==null&&(v=l(je,v,ne),X===null?K=je:X.sibling=je,X=je);return Ue&&Br(_,ne),K}for(Z=r(_,Z);!je.done;ne++,je=S.next())je=B(Z,_,ne,je.value,L),je!==null&&(e&&je.alternate!==null&&Z.delete(je.key===null?ne:je.key),v=l(je,v,ne),X===null?K=je:X.sibling=je,X=je);return e&&Z.forEach(function(vf){return t(_,vf)}),Ue&&Br(_,ne),K}function qe(_,v,S,L){if(typeof S=="object"&&S!==null&&S.type===$e&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case Ae:e:{for(var K=S.key,X=v;X!==null;){if(X.key===K){if(K=S.type,K===$e){if(X.tag===7){n(_,X.sibling),v=s(X,S.props.children),v.return=_,_=v;break e}}else if(X.elementType===K||typeof K=="object"&&K!==null&&K.$$typeof===Re&&Va(K)===X.type){n(_,X.sibling),v=s(X,S.props),v.ref=Bs(_,X,S),v.return=_,_=v;break e}n(_,X);break}else t(_,X);X=X.sibling}S.type===$e?(v=Gr(S.props.children,_.mode,L,S.key),v.return=_,_=v):(L=Go(S.type,S.key,S.props,null,_.mode,L),L.ref=Bs(_,v,S),L.return=_,_=L)}return u(_);case De:e:{for(X=S.key;v!==null;){if(v.key===X)if(v.tag===4&&v.stateNode.containerInfo===S.containerInfo&&v.stateNode.implementation===S.implementation){n(_,v.sibling),v=s(v,S.children||[]),v.return=_,_=v;break e}else{n(_,v);break}else t(_,v);v=v.sibling}v=Ti(S,_.mode,L),v.return=_,_=v}return u(_);case Re:return X=S._init,qe(_,v,X(S._payload),L)}if(Ut(S))return H(_,v,S,L);if(Q(S))return V(_,v,S,L);Co(_,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,v!==null&&v.tag===6?(n(_,v.sibling),v=s(v,S),v.return=_,_=v):(n(_,v),v=Ai(S,_.mode,L),v.return=_,_=v),u(_)):n(_,v)}return qe}var ps=Qa(!0),Wa=Qa(!1),No=kr(null),Eo=null,hs=null,Bl=null;function bl(){Bl=hs=Eo=null}function Hl(e){var t=No.current;Oe(No),e._currentValue=t}function Vl(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function gs(e,t){Eo=e,Bl=hs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Dt=!0),e.firstContext=null)}function un(e){var t=e._currentValue;if(Bl!==e)if(e={context:e,memoizedValue:t,next:null},hs===null){if(Eo===null)throw Error(m(308));hs=e,Eo.dependencies={lanes:0,firstContext:e}}else hs=hs.next=e;return t}var br=null;function Ql(e){br===null?br=[e]:br.push(e)}function Ka(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Ql(t)):(n.next=s.next,s.next=n),t.interleaved=n,or(e,r)}function or(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Er=!1;function Wl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function qa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function lr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Pr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(_e&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,or(e,n)}return s=r.interleaved,s===null?(t.next=t,Ql(r)):(t.next=s.next,s.next=t),r.interleaved=t,or(e,n)}function Po(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zn(e,n)}}function Ga(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,l=null;if(n=n.firstBaseUpdate,n!==null){do{var u={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};l===null?s=l=u:l=l.next=u,n=n.next}while(n!==null);l===null?s=l=t:l=l.next=t}else s=l=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:l,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ro(e,t,n,r){var s=e.updateQueue;Er=!1;var l=s.firstBaseUpdate,u=s.lastBaseUpdate,f=s.shared.pending;if(f!==null){s.shared.pending=null;var g=f,w=g.next;g.next=null,u===null?l=w:u.next=w,u=g;var E=e.alternate;E!==null&&(E=E.updateQueue,f=E.lastBaseUpdate,f!==u&&(f===null?E.firstBaseUpdate=w:f.next=w,E.lastBaseUpdate=g))}if(l!==null){var M=s.baseState;u=0,E=w=g=null,f=l;do{var N=f.lane,B=f.eventTime;if((r&N)===N){E!==null&&(E=E.next={eventTime:B,lane:0,tag:f.tag,payload:f.payload,callback:f.callback,next:null});e:{var H=e,V=f;switch(N=t,B=n,V.tag){case 1:if(H=V.payload,typeof H=="function"){M=H.call(B,M,N);break e}M=H;break e;case 3:H.flags=H.flags&-65537|128;case 0:if(H=V.payload,N=typeof H=="function"?H.call(B,M,N):H,N==null)break e;M=O({},M,N);break e;case 2:Er=!0}}f.callback!==null&&f.lane!==0&&(e.flags|=64,N=s.effects,N===null?s.effects=[f]:N.push(f))}else B={eventTime:B,lane:N,tag:f.tag,payload:f.payload,callback:f.callback,next:null},E===null?(w=E=B,g=M):E=E.next=B,u|=N;if(f=f.next,f===null){if(f=s.shared.pending,f===null)break;N=f,f=N.next,N.next=null,s.lastBaseUpdate=N,s.shared.pending=null}}while(!0);if(E===null&&(g=M),s.baseState=g,s.firstBaseUpdate=w,s.lastBaseUpdate=E,t=s.shared.interleaved,t!==null){s=t;do u|=s.lane,s=s.next;while(s!==t)}else l===null&&(s.shared.lanes=0);Qr|=u,e.lanes=u,e.memoizedState=M}}function Ja(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Yl.transition;Yl.transition={};try{e(!1),t()}finally{d=n,Yl.transition=r}}function hu(){return cn().memoizedState}function Ud(e,t,n){var r=Tr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},gu(e))vu(t,n);else if(n=Ka(e,t,n,r),n!==null){var s=kt();Rn(n,e,r,s),yu(n,t,r)}}function Bd(e,t,n){var r=Tr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(gu(e))vu(t,s);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var u=t.lastRenderedState,f=l(u,n);if(s.hasEagerState=!0,s.eagerState=f,kn(f,u)){var g=t.interleaved;g===null?(s.next=s,Ql(t)):(s.next=g.next,g.next=s),t.interleaved=s;return}}catch{}n=Ka(e,t,s,r),n!==null&&(s=kt(),Rn(n,e,r,s),yu(n,t,r))}}function gu(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function vu(e,t){Qs=To=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function yu(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zn(e,n)}}var Do={readContext:un,useCallback:mt,useContext:mt,useEffect:mt,useImperativeHandle:mt,useInsertionEffect:mt,useLayoutEffect:mt,useMemo:mt,useReducer:mt,useRef:mt,useState:mt,useDebugValue:mt,useDeferredValue:mt,useTransition:mt,useMutableSource:mt,useSyncExternalStore:mt,useId:mt,unstable_isNewReconciler:!1},bd={readContext:un,useCallback:function(e,t){return Wn().memoizedState=[e,t===void 0?null:t],e},useContext:un,useEffect:iu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Io(4194308,4,cu.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Io(4194308,4,e,t)},useInsertionEffect:function(e,t){return Io(4,2,e,t)},useMemo:function(e,t){var n=Wn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Wn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Ud.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=Wn();return e={current:e},t.memoizedState=e},useState:ou,useDebugValue:si,useDeferredValue:function(e){return Wn().memoizedState=e},useTransition:function(){var e=ou(!1),t=e[0];return e=Fd.bind(null,e[1]),Wn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,s=Wn();if(Ue){if(n===void 0)throw Error(m(407));n=n()}else{if(n=t(),tt===null)throw Error(m(349));(Vr&30)!==0||eu(r,t,n)}s.memoizedState=n;var l={value:n,getSnapshot:t};return s.queue=l,iu(nu.bind(null,r,l,e),[e]),r.flags|=2048,qs(9,tu.bind(null,r,l,n,t),void 0,null),n},useId:function(){var e=Wn(),t=tt.identifierPrefix;if(Ue){var n=sr,r=rr;n=(r&~(1<<32-St(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ws++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=u.createElement(n,{is:r.is}):(e=u.createElement(n),n==="select"&&(u=e,r.multiple?u.multiple=!0:r.size&&(u.size=r.size))):e=u.createElementNS(e,n),e[Vn]=t,e[Fs]=r,$u(e,t,!1,!1),t.stateNode=e;e:{switch(u=nn(n,r),n){case"dialog":ze("cancel",e),ze("close",e),s=r;break;case"iframe":case"object":case"embed":ze("load",e),s=r;break;case"video":case"audio":for(s=0;sSs&&(t.flags|=128,r=!0,Gs(l,!1),t.lanes=4194304)}else{if(!r)if(e=Mo(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Gs(l,!0),l.tail===null&&l.tailMode==="hidden"&&!u.alternate&&!Ue)return pt(t),null}else 2*Ie()-l.renderingStartTime>Ss&&n!==1073741824&&(t.flags|=128,r=!0,Gs(l,!1),t.lanes=4194304);l.isBackwards?(u.sibling=t.child,t.child=u):(n=l.last,n!==null?n.sibling=u:t.child=u,l.last=u)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=Ie(),t.sibling=null,n=He.current,Le(He,r?n&1|2:n&1),t):(pt(t),null);case 22:case 23:return Pi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(qt&1073741824)!==0&&(pt(t),t.subtreeFlags&6&&(t.flags|=8192)):pt(t),null;case 24:return null;case 25:return null}throw Error(m(156,t.tag))}function Jd(e,t){switch(Ol(t),t.tag){case 1:return Lt(t.type)&&xo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return vs(),Oe(It),Oe(ft),Jl(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return ql(t),null;case 13:if(Oe(He),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(m(340));ms()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Oe(He),null;case 4:return vs(),null;case 10:return Hl(t.type._context),null;case 22:case 23:return Pi(),null;case 24:return null;default:return null}}var Fo=!1,ht=!1,Yd=typeof WeakSet=="function"?WeakSet:Set,b=null;function xs(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Qe(e,t,r)}else n.current=null}function gi(e,t,n){try{n()}catch(r){Qe(e,t,r)}}var Bu=!1;function Xd(e,t){if(Pl=so,e=xa(),_l(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,l=r.focusNode;r=r.focusOffset;try{n.nodeType,l.nodeType}catch{n=null;break e}var u=0,f=-1,g=-1,w=0,E=0,M=e,N=null;t:for(;;){for(var B;M!==n||s!==0&&M.nodeType!==3||(f=u+s),M!==l||r!==0&&M.nodeType!==3||(g=u+r),M.nodeType===3&&(u+=M.nodeValue.length),(B=M.firstChild)!==null;)N=M,M=B;for(;;){if(M===e)break t;if(N===n&&++w===s&&(f=u),N===l&&++E===r&&(g=u),(B=M.nextSibling)!==null)break;M=N,N=M.parentNode}M=B}n=f===-1||g===-1?null:{start:f,end:g}}else n=null}n=n||{start:0,end:0}}else n=null;for(Rl={focusedElem:e,selectionRange:n},so=!1,b=t;b!==null;)if(t=b,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,b=e;else for(;b!==null;){t=b;try{var H=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(H!==null){var V=H.memoizedProps,qe=H.memoizedState,_=t.stateNode,v=_.getSnapshotBeforeUpdate(t.elementType===t.type?V:Nn(t.type,V),qe);_.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var S=t.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(m(163))}}catch(L){Qe(t,t.return,L)}if(e=t.sibling,e!==null){e.return=t.return,b=e;break}b=t.return}return H=Bu,Bu=!1,H}function Js(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var l=s.destroy;s.destroy=void 0,l!==void 0&&gi(t,n,l)}s=s.next}while(s!==r)}}function Uo(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function vi(e){var t=e.ref;if(t!==null){var n=e.stateNode;e.tag,e=n,typeof t=="function"?t(e):t.current=e}}function bu(e){var t=e.alternate;t!==null&&(e.alternate=null,bu(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Vn],delete t[Fs],delete t[Il],delete t[Ld],delete t[Dd])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Hu(e){return e.tag===5||e.tag===3||e.tag===4}function Vu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Hu(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function yi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=vo));else if(r!==4&&(e=e.child,e!==null))for(yi(e,t,n),e=e.sibling;e!==null;)yi(e,t,n),e=e.sibling}function xi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(xi(e,t,n),e=e.sibling;e!==null;)xi(e,t,n),e=e.sibling}var it=null,En=!1;function Rr(e,t,n){for(n=n.child;n!==null;)Qu(e,t,n),n=n.sibling}function Qu(e,t,n){if(ct&&typeof ct.onCommitFiberUnmount=="function")try{ct.onCommitFiberUnmount(Mt,n)}catch{}switch(n.tag){case 5:ht||xs(n,t);case 6:var r=it,s=En;it=null,Rr(e,t,n),it=r,En=s,it!==null&&(En?(e=it,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):it.removeChild(n.stateNode));break;case 18:it!==null&&(En?(e=it,n=n.stateNode,e.nodeType===8?Tl(e.parentNode,n):e.nodeType===1&&Tl(e,n),Ps(e)):Tl(it,n.stateNode));break;case 4:r=it,s=En,it=n.stateNode.containerInfo,En=!0,Rr(e,t,n),it=r,En=s;break;case 0:case 11:case 14:case 15:if(!ht&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var l=s,u=l.destroy;l=l.tag,u!==void 0&&((l&2)!==0||(l&4)!==0)&&gi(n,t,u),s=s.next}while(s!==r)}Rr(e,t,n);break;case 1:if(!ht&&(xs(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(f){Qe(n,t,f)}Rr(e,t,n);break;case 21:Rr(e,t,n);break;case 22:n.mode&1?(ht=(r=ht)||n.memoizedState!==null,Rr(e,t,n),ht=r):Rr(e,t,n);break;default:Rr(e,t,n)}}function Wu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Yd),t.forEach(function(r){var s=af.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Pn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~l}if(r=s,r=Ie()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*ef(r/1960))-r,10e?16:e,Ar===null)var r=!1;else{if(e=Ar,Ar=null,Qo=0,(_e&6)!==0)throw Error(m(331));var s=_e;for(_e|=4,b=e.current;b!==null;){var l=b,u=l.child;if((b.flags&16)!==0){var f=l.deletions;if(f!==null){for(var g=0;gIe()-wi?Kr(e,0):Si|=n),Ot(e,t)}function oc(e,t){t===0&&((e.mode&1)===0?t=1:(t=Bn,Bn<<=1,(Bn&130023424)===0&&(Bn=4194304)));var n=kt();e=or(e,t),e!==null&&(Ht(e,t,n),Ot(e,n))}function lf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),oc(e,n)}function af(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(m(314))}r!==null&&r.delete(t),oc(e,n)}var lc;lc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||It.current)Dt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Dt=!1,qd(e,t,n);Dt=(e.flags&131072)!==0}else Dt=!1,Ue&&(t.flags&1048576)!==0&&Fa(t,jo,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;$o(e,t),e=t.pendingProps;var s=cs(t,ft.current);gs(t,n),s=Zl(null,t,r,e,s,n);var l=ei();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Lt(r)?(l=!0,_o(t)):l=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Wl(t),s.updater=zo,t.stateNode=s,s._reactInternals=t,li(t,r,e,n),t=ci(null,t,r,!0,l,n)):(t.tag=0,Ue&&l&&zl(t),jt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch($o(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=cf(r),e=Nn(r,e),s){case 0:t=ui(null,t,r,e,n);break e;case 1:t=Tu(null,t,r,e,n);break e;case 11:t=Eu(null,t,r,e,n);break e;case 14:t=Pu(null,t,r,Nn(r.type,e),n);break e}throw Error(m(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),ui(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),Tu(e,t,r,s,n);case 3:e:{if(Iu(t),e===null)throw Error(m(387));r=t.pendingProps,l=t.memoizedState,s=l.element,qa(e,t),Ro(t,r,null,n);var u=t.memoizedState;if(r=u.element,l.isDehydrated)if(l={element:r,isDehydrated:!1,cache:u.cache,pendingSuspenseBoundaries:u.pendingSuspenseBoundaries,transitions:u.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){s=ys(Error(m(423)),t),t=Lu(e,t,r,n,s);break e}else if(r!==s){s=ys(Error(m(424)),t),t=Lu(e,t,r,n,s);break e}else for(Kt=jr(t.stateNode.containerInfo.firstChild),Wt=t,Ue=!0,Cn=null,n=Wa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ms(),r===s){t=ir(e,t,n);break e}jt(e,t,r,n)}t=t.child}return t;case 5:return Ya(t),e===null&&Fl(t),r=t.type,s=t.pendingProps,l=e!==null?e.memoizedProps:null,u=s.children,Ml(r,s)?u=null:l!==null&&Ml(r,l)&&(t.flags|=32),Au(e,t),jt(e,t,u,n),t.child;case 6:return e===null&&Fl(t),null;case 13:return Du(e,t,n);case 4:return Kl(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ps(t,null,r,n):jt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),Eu(e,t,r,s,n);case 7:return jt(e,t,t.pendingProps,n),t.child;case 8:return jt(e,t,t.pendingProps.children,n),t.child;case 12:return jt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,l=t.memoizedProps,u=s.value,Le(No,r._currentValue),r._currentValue=u,l!==null)if(kn(l.value,u)){if(l.children===s.children&&!It.current){t=ir(e,t,n);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var f=l.dependencies;if(f!==null){u=l.child;for(var g=f.firstContext;g!==null;){if(g.context===r){if(l.tag===1){g=lr(-1,n&-n),g.tag=2;var w=l.updateQueue;if(w!==null){w=w.shared;var E=w.pending;E===null?g.next=g:(g.next=E.next,E.next=g),w.pending=g}}l.lanes|=n,g=l.alternate,g!==null&&(g.lanes|=n),Vl(l.return,n,t),f.lanes|=n;break}g=g.next}}else if(l.tag===10)u=l.type===t.type?null:l.child;else if(l.tag===18){if(u=l.return,u===null)throw Error(m(341));u.lanes|=n,f=u.alternate,f!==null&&(f.lanes|=n),Vl(u,n,t),u=l.sibling}else u=l.child;if(u!==null)u.return=l;else for(u=l;u!==null;){if(u===t){u=null;break}if(l=u.sibling,l!==null){l.return=u.return,u=l;break}u=u.return}l=u}jt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,gs(t,n),s=un(s),r=r(s),t.flags|=1,jt(e,t,r,n),t.child;case 14:return r=t.type,s=Nn(r,t.pendingProps),s=Nn(r.type,s),Pu(e,t,r,s,n);case 15:return Ru(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Nn(r,s),$o(e,t),t.tag=1,Lt(r)?(e=!0,_o(t)):e=!1,gs(t,n),_u(t,r,s),li(t,r,s,n),ci(null,t,r,!0,e,n);case 19:return Ou(e,t,n);case 22:return Mu(e,t,n)}throw Error(m(156,t.tag))};function ic(e,t){return Ne(e,t)}function uf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function fn(e,t,n,r){return new uf(e,t,n,r)}function Mi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function cf(e){if(typeof e=="function")return Mi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ie)return 11;if(e===fe)return 14}return 2}function Lr(e,t){var n=e.alternate;return n===null?(n=fn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Go(e,t,n,r,s,l){var u=2;if(r=e,typeof e=="function")Mi(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case $e:return Gr(n.children,s,l,t);case We:u=8,s|=8;break;case Ge:return e=fn(12,n,t,s|2),e.elementType=Ge,e.lanes=l,e;case Te:return e=fn(13,n,t,s),e.elementType=Te,e.lanes=l,e;case Fe:return e=fn(19,n,t,s),e.elementType=Fe,e.lanes=l,e;case me:return Jo(n,s,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Ze:u=10;break e;case rt:u=9;break e;case ie:u=11;break e;case fe:u=14;break e;case Re:u=16,r=null;break e}throw Error(m(130,e==null?e:typeof e,""))}return t=fn(u,n,t,s),t.elementType=e,t.type=r,t.lanes=l,t}function Gr(e,t,n,r){return e=fn(7,e,r,t),e.lanes=n,e}function Jo(e,t,n,r){return e=fn(22,e,r,t),e.elementType=me,e.lanes=n,e.stateNode={isHidden:!1},e}function Ai(e,t,n){return e=fn(6,e,null,t),e.lanes=n,e}function Ti(e,t,n){return t=fn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function df(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Tt(0),this.expirationTimes=Tt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Tt(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Ii(e,t,n,r,s,l,u,f,g){return e=new df(e,t,n,f,g),t===1?(t=1,l===!0&&(t|=8)):t=0,l=fn(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Wl(l),e}function ff(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(p){console.error(p)}}return i(),Fi.exports=kf(),Fi.exports}var Sc;function Nf(){if(Sc)return rl;Sc=1;var i=Cf();return rl.createRoot=i.createRoot,rl.hydrateRoot=i.hydrateRoot,rl}var Ef=Nf();const Pf=Oc(Ef),Rf="/api";async function Ee(i,p){const m=await fetch(`${Rf}${i}`,{...p,headers:{"Content-Type":"application/json",...p?.headers??{}}}),R=await m.json();if(!m.ok){const j=R.error?.message??"Ошибка запроса";throw new Error(j)}return R}const Ce={async listModels(i){return Ee("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async testConnection(i){return Ee("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async normalize(i){return Ee("/normalize",{method:"POST",body:JSON.stringify({llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,userQuestion:i.query.userQuestion,context:{period_hint:i.query.periodHint??"",business_context:i.query.businessContext??"",expected_route:i.query.expectedRoute??""},saveAsTestCase:!!i.saveAsTestCase,useMock:!!i.useMock})})},async loadHistory(){return Ee("/history")},async loadTrace(i){return Ee(`/history/${i}`)},async loadPresets(){return Ee("/presets")},async savePreset(i){return Ee("/presets/save",{method:"POST",body:JSON.stringify(i)})},async runEval(i){return Ee("/eval/run",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,analysis_date:i.analysisDate})})},async startEvalRunAsync(i){return Ee("/eval/run-async/start",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,questions:i.questions,analysis_date:i.analysisDate})})},async loadEvalRunAsyncStatus(i){return Ee(`/eval/run-async/${encodeURIComponent(i)}`)},async startRun(){return Ee("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(i){return Ee("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:i,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return Ee("/accounting-agent/v1/runs")},async listResults(){return Ee("/accounting-agent/v1/results")},async runTrace(i){return Ee(`/accounting-agent/v1/trace/run/${i}`)},async sendAssistantMessage(i){return Ee("/assistant/message",{method:"POST",body:JSON.stringify({session_id:i.sessionId??"",mode:"assistant",message:i.userMessage,user_message:i.userMessage,llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion??"address_query_runtime_v1",systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,context:{period_hint:i.context?.periodHint??"",business_context:i.context?.businessContext??""},useMock:!!i.useMock})})},async loadAssistantSession(i){return Ee(`/assistant/session/${i}`)},async loadAssistantAnnotations(i){const p=new URLSearchParams;i?.session_id&&p.set("session_id",i.session_id),typeof i?.limit=="number"&&p.set("limit",String(i.limit));const m=p.toString();return Ee(`/assistant/annotations${m?`?${m}`:""}`)},async saveAssistantAnnotation(i){return Ee("/assistant/annotations",{method:"POST",body:JSON.stringify(i)})},async loadAutoRunsHistory(i){const p=new URLSearchParams;i?.from&&p.set("from",i.from),i?.to&&p.set("to",i.to),i?.target&&p.set("target",i.target),i?.mode&&p.set("mode",i.mode),i?.use_mock&&p.set("use_mock",i.use_mock),i?.prompt_contains&&p.set("prompt_contains",i.prompt_contains),typeof i?.limit=="number"&&p.set("limit",String(i.limit)),typeof i?.scan_limit=="number"&&p.set("scan_limit",String(i.scan_limit));const m=p.toString();return Ee(`/autoruns/history${m?`?${m}`:""}`)},async loadAutoRunDetail(i){return Ee(`/autoruns/history/${encodeURIComponent(i)}`)},async loadAutoRunCaseDialog(i,p){return Ee(`/autoruns/history/${encodeURIComponent(i)}/case/${encodeURIComponent(p)}/dialog`)},async loadAutoRunAnnotations(i){const p=new URLSearchParams;i?.run_id&&p.set("run_id",i.run_id),i?.case_id&&p.set("case_id",i.case_id),typeof i?.min_rating=="number"&&p.set("min_rating",String(i.min_rating)),i?.manual_case_decision&&p.set("manual_case_decision",i.manual_case_decision),typeof i?.limit=="number"&&p.set("limit",String(i.limit));const m=p.toString();return Ee(`/autoruns/annotations${m?`?${m}`:""}`)},async saveAutoRunAnnotation(i){return Ee("/autoruns/annotations",{method:"POST",body:JSON.stringify(i)})},async updateAutoRunAnnotation(i){return Ee(`/autoruns/annotations/${encodeURIComponent(i.annotation_id)}`,{method:"PATCH",body:JSON.stringify({resolved:i.resolved,resolved_by:i.resolved_by})})},async loadAutoRunPostAnalysis(i){const p=new URLSearchParams;i?.run_id&&p.set("run_id",i.run_id),typeof i?.limit_per_queue=="number"&&p.set("limit_per_queue",String(i.limit_per_queue)),typeof i?.annotation_limit=="number"&&p.set("annotation_limit",String(i.annotation_limit)),typeof i?.scan_limit=="number"&&p.set("scan_limit",String(i.scan_limit)),i?.from&&p.set("from",i.from),i?.to&&p.set("to",i.to),i?.target&&p.set("target",i.target),i?.mode&&p.set("mode",i.mode),i?.use_mock&&p.set("use_mock",i.use_mock),i?.prompt_contains&&p.set("prompt_contains",i.prompt_contains);const m=p.toString();return Ee(`/autoruns/post-analysis${m?`?${m}`:""}`)},async loadAutoRunAutogenHistory(i){const p=new URLSearchParams;i?.mode&&p.set("mode",i.mode),typeof i?.limit=="number"&&p.set("limit",String(i.limit));const m=p.toString();return Ee(`/autoruns/autogen/history${m?`?${m}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return Ee("/autoruns/autogen/personality-catalog")},async generateAutoRunQuestions(i){return Ee("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(i)})}};function Gt({value:i}){return o.jsx("pre",{className:"json-view",children:JSON.stringify(i??{},null,2)})}function Mn({title:i,subtitle:p,actions:m,className:R,hideHeader:j,children:T}){return o.jsxs("section",{className:R?`panel-frame ${R}`:"panel-frame",children:[j?null:o.jsxs("header",{className:"panel-header",children:[o.jsxs("div",{children:[o.jsx("h2",{children:i}),p?o.jsx("p",{children:p}):null]}),m?o.jsx("div",{className:"panel-actions",children:m}):null]}),o.jsx("div",{className:"panel-body",children:T})]})}function Mf(i){const p=new Date(i);return Number.isNaN(p.getTime())?i:p.toLocaleString("ru-RU")}function Af({sessionId:i,conversation:p,statusText:m,errorMessage:R,useMock:j,appLogs:T}){const $=p.filter(I=>I.role==="assistant").length,Y=p.filter(I=>I.role==="user").length,F=p.length>0?p[p.length-1]:null;return o.jsxs(Mn,{title:"SAM",subtitle:"System Assistant Monitor: срез по текущей сессии и логам.",children:[o.jsxs("div",{className:"metrics-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"session_id"}),o.jsx("strong",{children:i||"новая сессия"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"mock_mode"}),o.jsx("strong",{children:j?"on":"off"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"сообщений пользователя"}),o.jsx("strong",{children:Y})]}),o.jsxs("div",{children:[o.jsx("span",{children:"ответов ассистента"}),o.jsx("strong",{children:$})]}),o.jsxs("div",{children:[o.jsx("span",{children:"статус"}),o.jsx("strong",{children:m||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"ошибка"}),o.jsx("strong",{children:R||"нет"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"последнее сообщение"}),o.jsx("strong",{children:F?.created_at?Mf(F.created_at):"нет данных"})]})]}),o.jsx("h3",{style:{marginTop:12},children:"Последние системные логи"}),o.jsx(Gt,{value:T.slice(0,120)})]})}const Tf=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,If=[/\b(?:debug_payload_json|technical_breakdown_json)\b/i,/\b(?:route_summary|semantic_profile|domain_scope|relation_patterns|account_scope)\b/i,/\b(?:coverage_report|retrieval_status|problem_unit_state|candidate_evidence)\b/i,/\b(?:graph_domain_scope|graph_runtime|selection_reason|why_included)\b/i];function Lf(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function Df(i){const p=String(i??""),m=p.match(Tf);return(m?p.slice(0,m.index):p).replace(/###\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)[\s\S]*?(?:```[\s\S]*?```|$)/gi,"").replace(/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)\b[\s\S]*$/gi,"").split(/\r?\n/g).map($=>$.trimEnd()).filter($=>$.trim().length>0).filter($=>!If.some(Y=>Y.test($))).join(` -`).trim()}function zf(i,p,m="default"){const R=m==="technical",j=[];j.push("# Assistant conversation export"),j.push(`session_id: ${i||"n/a"}`),j.push(`export_mode: ${m}`),j.push(`exported_at: ${new Date().toISOString()}`),j.push("");for(let T=0;T{j.length!==0&&(R.push(j.join(` -`)),j=[])};for(const $ of m){const Y=$.trimEnd(),F=Y.trim();if(!F){T();continue}const I=/^Блок\s+\d+\./i.test(F),W=/^\d+\.\s/.test(F);(I||W)&&j.length>0&&T(),j.push(Y)}return T(),R.length>0?R:[i]}function Hf(i,p){const m=[],R=/\*\*(.+?)\*\*/g;let j=0,T=0,$;for(;($=R.exec(i))!==null;)$.index>j&&(m.push(o.jsx("span",{children:i.slice(j,$.index)},`${p}-t-${T}`)),T+=1),m.push(o.jsx("strong",{children:$[1]},`${p}-b-${T}`)),T+=1,j=R.lastIndex;return j0?m:[o.jsx("span",{children:i},`${p}-raw`)]}function Vf(i){const p=i.trimStart();return/^Блок\s+\d+\./i.test(p)?"assistant-msg-line heading":/^\d+\.\s/.test(p)?"assistant-msg-line numbered":/^-\s/.test(p)?"assistant-msg-line bullet":"assistant-msg-line"}function Qf(i,p=40){const m=i.replace(/\s+/g," ").trim();if(m.length<=p)return m;const R=m.split(" ").slice(0,3).join(" ").trim();return R.length>=10&&R.length<=p?`${R}…`:`${m.slice(0,p-1).trimEnd()}…`}function $c(i){return i.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Wf(i){const p=i.replace(/\r\n?/g,` -`).split(` -`).map(j=>j.trim()).find(Boolean),m=$c(p??"");return(m.split("|")[0]?.trim()??m).replace(/\s+/g," ").trim()}function Kf(i){const p=i.replace(/\r\n?/g,` -`).split(` -`).map(R=>R.trim()).find(Boolean);return!p||!/^\d+\.\s/.test(p)?!1:$c(p).includes("|")}function qf(i,p){const m=p.replace(/\r\n?/g,` -`).replace(/\*\*(.+?)\*\*/g,"$1").split(` -`).map((j,T)=>{const $=j.trim();return T===0?$.replace(/^\d+\.\s*/,""):$}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!m)return null;const R=Wf(p)||m;return{message_id:i.message_id,source_text:m,anchor_text:R,preview_text:Qf(R)}}function Gf(i,p,m,R){return bf(i.text).map((T,$)=>{const Y=T.split(` -`),F=i.role==="assistant"&&Kf(T),I=F?qf(i,T):null,W=!!I&&p?.message_id===I?.message_id&&p?.source_text===I?.source_text,z=Y.map((U,oe)=>o.jsx("p",{className:Vf(U),children:Hf(U,`line-${$}-${oe}`)},`line-${$}-${oe}`));return!F||!I?o.jsx("div",{className:"assistant-msg-block",children:z},`block-${$}`):o.jsx("div",{className:W?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(W){R();return}m(I)},onKeyDown:U=>{if(!(U.key!=="Enter"&&U.key!==" ")){if(U.preventDefault(),W){R();return}m(I)}},children:z},`block-${$}`)})}function Fc({sessionId:i,conversation:p,inputValue:m,onInputChange:R,selectedContextChip:j,onSelectContextChip:T,onClearContextChip:$,useMock:Y,onUseMockChange:F,onSend:I,onClear:W,busy:z,statusText:U,errorMessage:oe,showCommentAction:Me=!1,onCommentAssistantMessage:te,isAssistantMessageCommented:se,canCommentAssistantMessage:q}){const re=x.useRef(null),Se=x.useRef(!0),Pe=x.useRef(null),[Ae,De]=x.useState("idle"),[$e,We]=x.useState("чат");function Ge(ie=!1){re.current&&(ie&&(Se.current=!0),re.current.scrollTop=re.current.scrollHeight)}x.useEffect(()=>{Se.current&&Ge()},[p]),x.useEffect(()=>()=>{Pe.current!==null&&window.clearTimeout(Pe.current)},[]);async function Ze(ie){if(p.length===0)return;const Te=zf(i,p,ie),Fe=await Ff(Te);We(ie==="technical"?"тех":"чат"),De(Fe?"success":"error"),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{De("idle")},2200)}function rt(){if(!re.current)return;const ie=re.current,Te=ie.scrollHeight-ie.scrollTop-ie.clientHeight;Se.current=Te<16}return o.jsx(Mn,{className:"assistant-panel-frame",title:"Режим ассистента",children:o.jsxs("div",{className:"assistant-live-shell",children:[o.jsxs("div",{className:"assistant-toolbar",children:[o.jsxs("div",{className:"assistant-toolbar-actions",children:[o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Ze("default")},disabled:p.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Ze("technical")},disabled:p.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>W(),disabled:z&&p.length===0,children:"Сбросить сессию"})]}),o.jsxs("div",{className:"assistant-toolbar-meta",children:[i?o.jsx("span",{className:"status-chip",children:`session: ${i}`}):null,o.jsxs("div",{className:"assistant-toolbar-meta-right",children:[U?o.jsx("span",{className:"assistant-live-status",children:U}):null,Ae==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",$e,")"]}):null,Ae==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),oe?o.jsx("p",{className:"error-text assistant-toolbar-error",children:oe}):null]}),o.jsx("div",{ref:re,className:"assistant-chat-list",onScroll:rt,children:p.map((ie,Te)=>{const Fe=ie.role==="assistant"&&Me&&typeof te=="function"&&(typeof q=="function"?q(ie,Te):!0),fe=ie.role==="assistant"&&typeof se=="function"?se(ie,Te):!1;return o.jsxs("article",{className:`assistant-msg ${ie.role}`,children:[o.jsxs("header",{className:"assistant-msg-head",children:[o.jsxs("div",{className:"assistant-msg-head-main",children:[o.jsx("strong",{children:Of(ie.role)}),o.jsx("span",{children:$f(ie.created_at)})]}),ie.role==="assistant"&&Me?o.jsx("div",{className:"assistant-msg-head-actions",children:o.jsx("button",{type:"button",className:fe?"autoruns-comment-icon assistant-comment-btn commented":"autoruns-comment-icon assistant-comment-btn",onClick:()=>te?.(ie,Te),disabled:!Fe,title:Fe?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":Fe?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:o.jsx(Uf,{commented:fe})})}):null]}),o.jsx("div",{className:"assistant-msg-body",children:Gf(ie,j,T,$)}),ie.role==="assistant"&&ie.debug?o.jsxs("details",{className:"assistant-debug",children:[o.jsx("summary",{children:"Показать технический разбор"}),o.jsx(Gt,{value:ie.debug})]}):null]},ie.message_id)})}),o.jsxs("div",{className:"assistant-compose",children:[j?o.jsxs("div",{className:"assistant-compose-context",children:[o.jsx("span",{className:"assistant-compose-context-label",children:"Выбранный объект"}),o.jsxs("div",{className:"assistant-compose-context-pill",title:j.source_text,children:[o.jsx("span",{className:"assistant-compose-context-pill-text",children:j.preview_text}),o.jsx("button",{type:"button",className:"assistant-compose-context-clear",onClick:$,"aria-label":"Убрать выбранный объект",title:"Убрать выбранный объект",children:"×"})]})]}):null,o.jsxs("label",{className:"full-width",children:["Сообщение",o.jsx("textarea",{className:"assistant-input-textarea",value:m,onChange:ie=>R(ie.target.value),rows:4,placeholder:j?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),o.jsxs("div",{className:"button-row assistant-send-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:Y,onChange:ie=>F(ie.target.checked)}),"Mock-режим"]}),o.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{Ge(!0),I()},disabled:z||!m.trim(),children:z?"Выполняю...":"Отправить"})]})]})]})})}const bi={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},sl="needs_dialog_policy_fix",gt="__all__",al="__live__:",wc="ndc_autoruns_ui_config_v1",jc="ndc-autoruns-save",Hi=["Анализ запроса","Получение данных","Подготовка ответа"];function Jf(i,p){const m=i.trim();if(!m)return"";if(!p)return m;const R=m.toLowerCase(),j=p.anchor_text.trim(),T=j.toLowerCase();return T&&R.includes(T)?m:`По выбранному объекту "${j}": ${m}`}const Ji=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function Yf(i=Ji){return i.reduce((p,m)=>(p[m.id]=m.defaultPrompt,p),{})}const kc={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:Yf(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function Vi(i){const p=String(i??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(p)?p:""}function Cc(i){const p=typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):160;return Math.max(110,Math.min(520,p))}function Xf(i){const p=i.getFullYear(),m=String(i.getMonth()+1).padStart(2,"0"),R=String(i.getDate()).padStart(2,"0"),j=String(i.getHours()).padStart(2,"0"),T=String(i.getMinutes()).padStart(2,"0");return`${p}-${m}-${R}T${j}:${T}`}function Nc(){const i=new Date;return i.setDate(i.getDate()-14),Xf(i)}function ol(i){if(!i.trim())return;const p=Date.parse(i);if(Number.isFinite(p))return new Date(p).toISOString()}function ur(i){if(!i)return"нет данных";const p=Date.parse(i);return Number.isFinite(p)?new Date(p).toLocaleString("ru-RU"):i}function Zf(i,p){return p<=0?0:Math.max(0,Math.min(100,Number((i/p*100).toFixed(1))))}function ll(i){return typeof i!="number"?"нет данных":`${i.toFixed(1)}%`}function em(i){return i==="assistant_stage1"?"assistant/s1":i==="assistant_stage2"?"assistant/s2":i==="assistant_p0"?"assistant/p0":i}function Ec(i){return i==="up"?"Рост":i==="down"?"Регресс":"Без изменений"}function tm(i,p){return i.find(m=>m.case_id===p)??null}function Qi(i){const p=Math.max(1,Math.min(5,Math.round(i)));return`${"●".repeat(p)}${"○".repeat(5-p)}`}function Pc(i){return i.length===0?o.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):o.jsx("div",{className:"autoruns-coverage-list",children:i.map(p=>{const m=Zf(p.closed_cases,p.total_cases);return o.jsxs("div",{className:"autoruns-coverage-item",children:[o.jsxs("div",{className:"autoruns-coverage-head",children:[o.jsx("strong",{children:p.domain}),o.jsxs("span",{children:[p.closed_cases,"/",p.total_cases," (",m,"%)"]})]}),o.jsx("div",{className:"autoruns-coverage-bar",children:o.jsx("div",{style:{width:`${m}%`}})})]},p.domain)})})}function il(i){return`${al}${i}`}function js(i){return i.startsWith(al)}function Rc(i){return i.startsWith(al)?i.slice(al.length):""}function Uc(i){const p=i.report_summary?.run_timestamp??i.created_at,m=Math.max(0,i.total_cases-i.completed_cases);return{run_id:il(i.job_id),eval_target:i.eval_target,run_timestamp:p,mode:"single-pass-strict",llm_provider:null,model:null,use_mock:null,analysis_date:i.report_summary?.analysis_date??i.analysis_date??null,prompt_version:null,schema_version:null,suite_id:i.case_set_file,cases_total:i.total_cases,requests_total:null,report_path:`async_job:${i.job_id}`,score_index:i.report_summary?.score_index??null,blocking_failures:0,quality_failures:0,closed_cases:i.completed_cases,open_cases:m,domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]}}function no(i,p){const m=Uc(i),R=i.cases.map(W=>({case_id:W.case_id,domain:null,query_class:null,status:W.status==="completed"?"closed":W.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${i.run_id}-${W.case_id}`,dialog_available:W.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),T=p!==gt&&R.some(W=>W.case_id===p)?p:R.length>0?gt:"",$={ok:!0,run:m,coverage:{closed_cases:i.completed_cases,open_cases:Math.max(0,i.total_cases-i.completed_cases),domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]},cases:R,annotations_summary:{total:0},report:i.report_summary?{run_id:i.report_summary.run_id,run_timestamp:i.report_summary.run_timestamp,score_index:i.report_summary.score_index,cases_total:i.report_summary.cases_total,analysis_date:i.report_summary.analysis_date??i.analysis_date??null}:{}},Y=[];let F=0;if(T===gt)for(const W of i.cases)for(let z=0;zz.case_id===T)??null;for(let z=0;z<(W?.messages.length??0);z+=1){const U=W?.messages[z];U&&Y.push({...U,message_index:z,case_id:T,case_message_index:z,commented:!1,annotation:null})}}const I={ok:!0,run_id:m.run_id,case_id:T,source:"assistant_session",session_id:T===gt?`${i.run_id}::__all__`:`${i.run_id}-${T}`,messages:Y,decomposition:[],assistant_mode:{status:i.status,completed_cases:i.completed_cases,total_cases:i.total_cases},annotations:[]};return{detail:$,dialog:I,caseId:T}}function nm({commented:i}){const p=i?"comment-icon-svg commented":"comment-icon-svg";return o.jsx("svg",{className:p,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M5 6.5h14v9H11.5l-4.5 3v-3H5z"})})}function Mc({resolved:i}){return o.jsxs("svg",{className:i?"resolve-icon-svg resolved":"resolve-icon-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[o.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),i?o.jsx("path",{d:"M5.1 8.2 7.2 10.3 11 6.5"}):null]})}function rm(){return o.jsxs("svg",{className:"autoruns-copy-icon-svg",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2.2"}),o.jsx("path",{d:"M15 7V5.8a1.8 1.8 0 0 0-1.8-1.8H5.8A1.8 1.8 0 0 0 4 5.8v7.4A1.8 1.8 0 0 0 5.8 15H7"})]})}function sm({connection:i,prompts:p,assistantPromptVersion:m,decompositionPromptVersion:R,showAssistantMode:j,showDecompositionMode:T,showProgressMode:$,showCommentsMode:Y,onLog:F}){const[I,W]=x.useState({...bi,fromLocal:Nc()}),[z,U]=x.useState(""),[oe,Me]=x.useState(null),[te,se]=x.useState(null),[q,re]=x.useState(null),[Se,Pe]=x.useState([]),[Ae,De]=x.useState("all"),[$e,We]=x.useState(!1),[Ge,Ze]=x.useState(null),[rt,ie]=x.useState([]),[Te,Fe]=x.useState(""),[fe,Re]=x.useState(""),[me,D]=x.useState(""),[Q,O]=x.useState(Ji),[h,C]=x.useState(kc),[G,ae]=x.useState([]),[ce,de]=x.useState(""),[xe,ge]=x.useState([]),[ee,ke]=x.useState(null),[Ft,qn]=x.useState(null),[An,Tn]=x.useState(!1),[dr,Jt]=x.useState(!1),[Yt,Gn]=x.useState(!1),[mn,Ut]=x.useState(!1),[Xt,pn]=x.useState(!1),[fr,In]=x.useState(!1),[mr,Ln]=x.useState(!1),[Zt,en]=x.useState(!1),[pr,Bt]=x.useState(""),[hn,Be]=x.useState(""),[st,gn]=x.useState(""),[vn,tn]=x.useState([]),[nn,Ct]=x.useState([]),[Dn,rn]=x.useState(""),[bt,vt]=x.useState(null),[Jn,Ke]=x.useState(!1),[hr,yn]=x.useState(!1),[gr,sn]=x.useState(""),[vr,Nt]=x.useState(""),[Yn,yt]=x.useState(String(bi.limit)),[Jr,xt]=x.useState(String(kc.count)),[Et,zn]=x.useState(160),[ue,ot]=x.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:sl,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[ve,_t]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),Pt=x.useRef(!1),we=x.useRef(null),lt=x.useMemo(()=>Q.find(a=>a.id===h.personalityId)??Q[0]??Ji[0],[h.personalityId,Q]),Rt=x.useMemo(()=>G.find(a=>a.generation_id===ce)??G[0]??null,[G,ce]),On=te?tm(te.cases,me):null,J=x.useMemo(()=>$e?Se.filter(a=>!a.resolved):Se,[Se,$e]),Ne=J.find(a=>a.annotation_id===Te)??null,$n=q?.messages.find(a=>a.message_index===ue.messageIndex)??null,Yr=x.useMemo(()=>{if(!q||ue.messageIndex<0)return null;for(let a=ue.messageIndex-1;a>=0;a-=1){const c=q.messages[a];if(c?.role==="user")return c}return null},[ue.messageIndex,q]),xn=x.useMemo(()=>{const a=new Map;for(const c of nn)c.message_id&&a.set(c.message_id,c);return a},[nn]),Ie=ve.messageIndex>=0?vn[ve.messageIndex]??null:null,Xr=x.useMemo(()=>{if(ve.messageIndex<0)return null;for(let a=ve.messageIndex-1;a>=0;a-=1){const c=vn[a];if(c?.role==="user")return c}return null},[ve.messageIndex,vn]),ut=x.useMemo(()=>{const a=J.map(y=>({source:"autorun",key:`autorun:${y.annotation_id}`,updated_at:y.updated_at,rating:y.rating,autorun:y,assistant:null})),c=nn.map(y=>({source:"assistant_live",key:`assistant:${y.annotation_id}`,updated_at:y.updated_at,rating:y.rating,autorun:null,assistant:y}));return[...a,...c].sort((y,A)=>Date.parse(A.updated_at)-Date.parse(y.updated_at))},[nn,J]),yr=x.useMemo(()=>{if(ut.length===0)return null;const a=ut.reduce((c,y)=>c+y.rating,0)/ut.length;return Number(a.toFixed(2))},[ut]),Fn=x.useMemo(()=>{const a=[...oe?.items??[]];return ee&&a.unshift(Uc(ee)),fe&&!a.some(c=>c.run_id===fe)&&te?.run&&a.unshift(te.run),a},[ee,oe?.items,te?.run,fe]),le=x.useCallback(a=>{F?.(`[autoruns] ${a}`)},[F]),Un=x.useCallback(async a=>{const c=String(a??"").trim();if(!c){Ct([]);return}try{const y=await Ce.loadAssistantAnnotations({session_id:c,limit:400});Ct(y.items??[])}catch(y){const A=y instanceof Error?y.message:String(y);le(`Assistant live annotations load error: ${A}`)}},[le]),Mt=x.useCallback(a=>{_t(c=>c.saving&&!a?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),ct=x.useCallback(async(a,c)=>{a.stopPropagation(),a.preventDefault();const y=String(c??"").trim();if(y)try{if(navigator?.clipboard?.writeText)await navigator.clipboard.writeText(y);else{const A=document.createElement("textarea");A.value=y,A.setAttribute("readonly","true"),A.style.position="fixed",A.style.opacity="0",document.body.appendChild(A),A.select(),document.execCommand("copy"),document.body.removeChild(A)}le(`run id copied: ${y}`)}catch(A){const pe=A instanceof Error?A.message:String(A);Be(`Копирование run id: ${pe}`),le(`copy run id error: ${pe}`)}},[le]);function ks(){let a=0;sn(Hi[0]);const c=window.setInterval(()=>{a=Math.min(a+1,Hi.length-1),sn(Hi[a])},650);return()=>window.clearInterval(c)}const St=x.useCallback(()=>{gn(""),tn([]),Ct([]),rn(""),vt(null),sn(""),Nt(""),Mt({force:!0}),le("Live-чат ассистента в истории автопрогонов сброшен.")},[Mt,le]),Cs=x.useCallback(async()=>{const a=Jf(Dn,bt);if(!a)return;yn(!0),Nt(""),rn(""),tn(y=>[...y,{message_id:`autoruns-live-${Date.now()}`,session_id:st||"pending",role:"user",text:a,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=ks();try{const y=await Ce.sendAssistantMessage({connection:i,prompts:p,userMessage:a,sessionId:st||void 0,promptVersion:m,useMock:Jn});gn(y.session_id),tn(y.conversation),await Un(y.session_id),sn("Ответ готов"),le(`Live-ответ ассистента получен: trace=${y.debug.trace_id}`)}catch(y){const A=y instanceof Error?y.message:String(y);Nt(A),sn("Ошибка ассистента"),le(`Live-чат ассистента: ошибка отправки сообщения: ${A}`)}finally{c(),yn(!1)}},[Dn,bt,st,Jn,m,i,Un,le,p]),Zr=x.useCallback(a=>{const c=a.trim();if(!c){yt(String(I.limit));return}if(!/^\d+$/.test(c)){yt(String(I.limit));return}const y=Number.parseInt(c,10);if(!Number.isFinite(y)){yt(String(I.limit));return}const A=Math.max(1,Math.min(500,y));A!==I.limit&&W(pe=>({...pe,limit:A})),yt(String(A))},[I.limit]),es=x.useCallback(a=>{const c=a.trim();if(!c){xt(String(h.count));return}if(!/^\d+$/.test(c)){xt(String(h.count));return}const y=Number.parseInt(c,10);if(!Number.isFinite(y)){xt(String(h.count));return}const A=Math.max(1,Math.min(200,y));A!==h.count&&C(pe=>({...pe,count:A})),xt(String(A))},[h.count]),Xn=x.useCallback(a=>{zn(Cc(a))},[]),Bn=x.useCallback(a=>{const c=a.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&Xn(c)},[Xn]),At=x.useCallback(async()=>{en(!0);try{const a=await Ce.loadAutoRunAnnotations({limit:800,manual_case_decision:Ae});Pe(a.items),Ze(a.manual_case_decision_schema??null),ie(a.available_manual_case_decisions??[]),Fe(c=>a.items.length===0?"":a.items.some(y=>y.annotation_id===c)?c:a.items[0].annotation_id)}catch(a){le(`Annotations load error: ${a instanceof Error?a.message:String(a)}`)}finally{en(!1)}},[Ae,le]),wt=x.useCallback(async()=>{Ut(!0);try{const a=await Ce.loadAutoRunAutogenHistory({limit:180});ae(a.items)}catch(a){le(`Autogen history load error: ${a instanceof Error?a.message:String(a)}`)}finally{Ut(!1)}},[le]),xr=x.useCallback(async()=>{try{const c=(await Ce.loadAutoRunAutogenPersonalityCatalog()).items.map(y=>({id:String(y.id??"").trim(),label:String(y.label??"").trim(),domain:typeof y.domain=="string"?y.domain.trim():"",defaultPrompt:String(y.default_prompt??"").trim()})).filter(y=>y.id.length>0&&y.label.length>0);if(c.length===0)return;O(c.map(y=>({id:y.id,label:y.label,domain:y.domain||"",defaultPrompt:y.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(a){le(`Autogen personality catalog load error: ${a instanceof Error?a.message:String(a)}`)}},[le]),dt=x.useCallback(async()=>{Gn(!0);try{const a=await Ce.loadAutoRunPostAnalysis({run_id:fe&&!js(fe)?fe:void 0,limit_per_queue:30,annotation_limit:1500,from:ol(I.fromLocal),to:ol(I.toLocal),target:I.target,mode:I.mode,use_mock:I.useMock,prompt_contains:I.promptContains.trim()||void 0});qn(a)}catch(a){le(`Post-analysis load error: ${a instanceof Error?a.message:String(a)}`),qn(null)}finally{Gn(!1)}},[I.fromLocal,I.mode,I.promptContains,I.target,I.toLocal,I.useMock,le,fe]),zr=x.useCallback(async()=>{Tn(!0),Be("");try{const a=h.personalityPrompts[h.personalityId]??"",c=[p.systemPrompt,p.developerPrompt,p.domainPrompt,p.schemaNotes,p.fewShotExamples].join(` -`).slice(0,900),y=await Ce.generateAutoRunQuestions({mode:h.mode,count:h.count,domain:lt.domain||void 0,persist_to_eval_cases:h.persistToEvalCases,generated_by:h.generatedBy.trim()||void 0,llm:{llm_provider:i.llmProvider,api_key:i.apiKey,model:i.model,base_url:i.baseUrl,temperature:i.temperature,max_output_tokens:i.maxOutputTokens},context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:m,decomposition_prompt_version:R,prompt_fingerprint:c,autogen_personality_id:lt.id,autogen_personality_prompt:a.trim()||void 0}});le(`Generated ${y.generation.count} questions (${y.generation.mode}) id=${y.generation.generation_id}`+(y.generation.saved_case_set_file?` saved=${y.generation.saved_case_set_file}`:"")),de(y.generation.generation_id),ge([...y.generation.questions??[]]),await wt()}catch(a){const c=a instanceof Error?a.message:String(a);Be(`Автогенерация: ${c}`),le(`Autogen generate error: ${c}`)}finally{Tn(!1)}},[m,h.count,h.generatedBy,h.mode,h.personalityId,h.personalityPrompts,h.persistToEvalCases,i.apiKey,i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature,R,wt,le,p.developerPrompt,p.domainPrompt,p.fewShotExamples,p.schemaNotes,p.systemPrompt,lt.domain,lt.id]),bn=x.useCallback(async(a,c)=>{if(js(a)){const y=Rc(a);if(ee&&ee.job_id===y){const A=no(ee,c);Re(a),D(A.caseId),re(A.dialog);return}re(null);return}Ln(!0);try{const y=await Ce.loadAutoRunCaseDialog(a,c);re(y)}catch(y){const A=y instanceof Error?y.message:String(y);Be(`Диалог кейса: ${A}`),re(null),le(`Dialog load error for ${a}/${c}: ${A}`)}finally{Ln(!1)}},[ee,le]),Tt=x.useCallback(async(a,c)=>{if(js(a)){const y=Rc(a);if(ee&&ee.job_id===y){const A=no(ee,c??gt);Re(a),D(A.caseId),se(A.detail),re(A.dialog);return}Re(a),D(""),se(null),re(null);return}In(!0);try{const y=await Ce.loadAutoRunDetail(a);se(y);const A=(c&&(c===gt||y.cases.some(pe=>pe.case_id===c))?c:"")||(y.cases.length>0?gt:"")||"";Re(a),D(A),A?await bn(a,A):re(null)}catch(y){const A=y instanceof Error?y.message:String(y);Be(`Детализация прогона: ${A}`),se(null),re(null),le(`Run detail load error for ${a}: ${A}`)}finally{In(!1)}},[ee,bn,le]),Ht=x.useCallback(async a=>{pn(!0),Be("");try{const c=await Ce.loadAutoRunsHistory({from:ol(I.fromLocal),to:ol(I.toLocal),target:I.target,mode:I.mode,use_mock:I.useMock,prompt_contains:I.promptContains.trim()||void 0,limit:I.limit});if(Me(c),c.items.length===0){Re(""),D(""),se(null),re(null);return}const y=a?.keepSelection??!0,A=a?.preferredRunId??"",pe=a?.preferredCaseId??"",be=y&&A&&c.items.some(on=>on.run_id===A)?A:c.items[0].run_id;await Tt(be,y?pe:void 0),dt()}catch(c){const y=c instanceof Error?c.message:String(c);Be(`История прогонов: ${y}`),le(`History load error: ${y}`)}finally{pn(!1)}},[I.fromLocal,I.limit,I.mode,I.promptContains,I.target,I.toLocal,I.useMock,dt,Tt,le]),Vt=x.useCallback(()=>{we.current!==null&&(window.clearTimeout(we.current),we.current=null)},[]),Zn=x.useCallback(async a=>{try{const c=await Ce.loadEvalRunAsyncStatus(a);ke(c.job);const y=il(a);if(fe===y){const A=no(c.job,me||gt);se(A.detail),re(A.dialog),D(A.caseId)}if(c.job.status==="completed"){Vt(),Jt(!1);const A=c.job.report_summary?.run_id??c.job.run_id;await Ht({keepSelection:!0,preferredRunId:A||fe,preferredCaseId:gt}),await wt(),ke(null);return}if(c.job.status==="failed"){Vt(),Jt(!1),Be(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),le(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}Vt(),we.current=window.setTimeout(()=>{Zn(a)},500)}catch(c){Vt(),Jt(!1);const y=c instanceof Error?c.message:String(c);Be(`Запуск прогонов: ${y}`),le(`Autogen async status error: ${y}`)}},[wt,Ht,le,me,fe,Vt]),d=x.useCallback(async()=>{Vt(),Jt(!0),Be("");try{const a=Rt;if(!a)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const c=xe.map(_r=>_r.trim()).filter(_r=>_r.length>0);if(c.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const y=I.useMock==="true",A=Vi(z),be=(await Ce.startEvalRunAsync({connection:i,prompts:p,promptVersion:m,mode:"single-pass-strict",caseSetFile:a.saved_case_set_file??void 0,useMock:y,evalTarget:"assistant_stage1",questions:c,analysisDate:A||void 0})).job;ke(be);const on=il(be.job_id),jn=no(be,gt);Re(on),D(jn.caseId),se(jn.detail),re(jn.dialog),le(`Запущен async-прогон job=${be.job_id}, run_id=${be.run_id}, вопросов=${c.length}`+(a.saved_case_set_file?`, base_case_set=${a.saved_case_set_file}`:"")+(A?`, analysis_date=${A}`:", analysis_date=current_state")),Zn(be.job_id)}catch(a){const c=a instanceof Error?a.message:String(a);Be(`Запуск прогонов: ${c}`),le(`Autogen run error: ${c}`),Jt(!1)}},[z,m,i,xe,I.useMock,le,Zn,p,Rt,Vt]),P=x.useCallback(a=>{if(a.role!=="assistant")return;const c=a.case_id??me,y=a.case_message_index??a.message_index;ot({open:!0,caseId:c,caseMessageIndex:y,messageIndex:a.message_index,rating:a.annotation?.rating??3,comment:a.annotation?.comment??"",manualCaseDecision:a.annotation?.manual_case_decision??sl,annotationAuthor:a.annotation?.annotation_author??h.generatedBy,saving:!1,error:""})},[h.generatedBy,me]),k=x.useCallback(a=>{ot(c=>c.saving&&!a?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:sl,annotationAuthor:h.generatedBy,saving:!1,error:""})},[h.generatedBy]),ye=x.useCallback(async()=>{const a=fe,c=ue.caseId,y=ue.caseMessageIndex;if(!(!a||!c||y<0)){if(js(a)){ot(A=>({...A,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ue.comment.trim()){ot(A=>({...A,error:"Добавьте комментарий."}));return}ot(A=>({...A,saving:!0,error:""}));try{await Ce.saveAutoRunAnnotation({run_id:a,case_id:c,message_index:y,rating:ue.rating,comment:ue.comment.trim(),manual_case_decision:ue.manualCaseDecision,annotation_author:ue.annotationAuthor.trim()||void 0}),k({force:!0}),Promise.all([Tt(a,me),At(),dt()]).catch(A=>{const pe=A instanceof Error?A.message:String(A);Be(`Обновление после комментария: ${pe}`),le(`Comment refresh error: ${pe}`)})}catch(A){ot(pe=>({...pe,saving:!1,error:A instanceof Error?A.message:String(A)}))}}},[k,ue.annotationAuthor,ue.caseId,ue.caseMessageIndex,ue.comment,ue.manualCaseDecision,ue.rating,At,dt,Tt,le,me,fe]),er=x.useCallback(a=>a.role==="assistant",[]),Hn=x.useCallback(a=>a.role==="assistant"&&xn.has(a.message_id),[xn]),ro=x.useCallback((a,c)=>{if(a.role!=="assistant")return;const y=st.trim(),A=String(a.session_id??"").trim();if(!(y||A)){Nt("Сначала получите ответ ассистента в активной сессии.");return}!y&&A&&gn(A);const be=xn.get(a.message_id)??null;Nt(""),_t({open:!0,messageIndex:c,rating:be?.rating??3,comment:be?.comment??"",annotationAuthor:be?.annotation_author??"manual_reviewer",saving:!1,error:""})},[xn,st]),Ns=x.useCallback(async()=>{if(ve.messageIndex<0)return;if(!ve.comment.trim()){_t(y=>({...y,error:"Добавьте комментарий."}));return}const a=vn[ve.messageIndex]??null,c=st.trim()||(a?.role==="assistant"?String(a.session_id??"").trim():"");if(!c){_t(y=>({...y,error:"Сессия ассистента не найдена."}));return}_t(y=>({...y,saving:!0,error:""}));try{const y=await Ce.saveAssistantAnnotation({session_id:c,message_index:ve.messageIndex,rating:ve.rating,comment:ve.comment.trim(),annotation_author:ve.annotationAuthor.trim()||void 0});Ct(A=>{const pe=[...A],be=pe.findIndex(on=>on.annotation_id===y.annotation.annotation_id);return be>=0?pe[be]=y.annotation:pe.unshift(y.annotation),pe.sort((on,jn)=>Date.parse(jn.updated_at)-Date.parse(on.updated_at))}),Mt({force:!0})}catch(y){const A=y instanceof Error?y.message:String(y);_t(pe=>({...pe,saving:!1,error:A}))}},[ve.annotationAuthor,ve.comment,ve.messageIndex,ve.rating,vn,st,Mt]),Or=x.useCallback(a=>{Pe(c=>c.map(y=>y.annotation_id===a.annotation_id?{...y,...a}:y)),re(c=>c&&{...c,annotations:c.annotations.map(y=>y.annotation_id===a.annotation_id?a:y),messages:c.messages.map(y=>!y.annotation||y.annotation.annotation_id!==a.annotation_id?y:{...y,commented:!0,annotation:a})})},[]),_n=x.useCallback(async(a,c)=>{if(a.annotation_id){if(js(a.run_id)){Be("Статус выполнения можно менять только для завершённых прогонов.");return}Bt(a.annotation_id);try{const y=await Ce.updateAutoRunAnnotation({annotation_id:a.annotation_id,resolved:c,resolved_by:h.generatedBy||void 0});Or(y.annotation),dt()}catch(y){const A=y instanceof Error?y.message:String(y);Be(`Смена статуса кейса: ${A}`),le(`Annotation resolve toggle error: ${A}`)}finally{Bt("")}}},[Or,h.generatedBy,dt,le]),Sn=x.useCallback(async a=>{Fe(a.annotation_id),await Tt(a.run_id,a.case_id),oe?.items.some(c=>c.run_id===a.run_id)||Be("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[oe?.items,Tt]);x.useEffect(()=>{Pt.current||(Pt.current=!0,Ht({keepSelection:!1}),wt(),xr(),dt())},[wt,xr,Ht,dt]),x.useEffect(()=>{Pt.current&&At()},[Ae,At]),x.useEffect(()=>{Fe(a=>J.length===0?"":J.some(c=>c.annotation_id===a)?a:J[0].annotation_id)},[J]),x.useEffect(()=>{de(a=>G.length===0?"":a&&G.some(c=>c.generation_id===a)?a:G[0].generation_id)},[G]),x.useEffect(()=>{if(!Rt){ge([]);return}ge([...Rt.questions])},[Rt?.generation_id]),x.useEffect(()=>{yt(String(I.limit))},[I.limit]),x.useEffect(()=>{xt(String(h.count))},[h.count]),x.useEffect(()=>{if(!st.trim()){Ct([]);return}Un(st)},[st,Un]),x.useEffect(()=>{if(!ee)return;const a=il(ee.job_id);if(fe!==a)return;const c=no(ee,me||gt);se(c.detail),re(c.dialog),D(c.caseId)},[ee,me,fe]),x.useEffect(()=>()=>{Vt()},[Vt]),x.useEffect(()=>{Q.length!==0&&C(a=>{let c=!1;const y={...a.personalityPrompts};for(const pe of Q)(typeof y[pe.id]!="string"||y[pe.id].trim().length===0)&&(y[pe.id]=pe.defaultPrompt,c=!0);let A=a.personalityId;return Q.some(pe=>pe.id===a.personalityId)||(A=Q[0].id,c=!0),c?{...a,personalityId:A,personalityPrompts:y}:a})},[Q]),x.useEffect(()=>{const a=localStorage.getItem(wc);if(a)try{const c=JSON.parse(a);if(c.filters){const y=c.filters;W(A=>({...A,...y,limit:typeof y.limit=="number"?Math.max(1,Math.min(500,y.limit)):A.limit}))}typeof c.analysisDate=="string"&&U(Vi(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&zn(Cc(c.autogenPersonalityPromptHeight)),c.autoGenSettings&&C(y=>{const A={...y.personalityPrompts},pe=c.autoGenSettings?.personalityPrompts??{};for(const[on,jn]of Object.entries(pe))typeof jn=="string"&&on.trim().length>0&&(A[on.trim()]=jn);const be=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():y.personalityId;return{...y,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"?c.autoGenSettings.mode:y.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):y.count,personalityId:be,personalityPrompts:A,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:y.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:y.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&De(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&We(c.hideResolvedAnnotations)}catch{}},[]);const wn=x.useCallback(()=>{const a={filters:I,analysisDate:z,autogenPersonalityPromptHeight:Et,autoGenSettings:{mode:h.mode,count:h.count,personalityId:h.personalityId,personalityPrompts:h.personalityPrompts,persistToEvalCases:h.persistToEvalCases,generatedBy:h.generatedBy},annotationDecisionFilter:Ae,hideResolvedAnnotations:$e};localStorage.setItem(wc,JSON.stringify(a))},[z,Ae,h,Et,I,$e]);return x.useEffect(()=>{const a=()=>{wn(),le("Сохранены настройки панели автопрогонов.")};return window.addEventListener(jc,a),()=>{window.removeEventListener(jc,a)}},[le,wn]),o.jsxs(Mn,{className:"autoruns-frame",title:"",hideHeader:!0,children:[o.jsxs("div",{className:"autoruns-columns",children:[o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Настройки"})}),o.jsx("h4",{children:"Настройки выборки"}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата с",o.jsx("input",{type:"datetime-local",value:I.fromLocal,onChange:a=>W(c=>({...c,fromLocal:a.target.value}))})]}),o.jsxs("label",{children:["Дата по",o.jsx("input",{type:"datetime-local",value:I.toLocal,onChange:a=>W(c=>({...c,toLocal:a.target.value}))})]}),o.jsxs("label",{children:["Целевой контур",o.jsxs("select",{value:I.target,onChange:a=>W(c=>({...c,target:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(oe?.available.targets??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Режим",o.jsxs("select",{value:I.mode,onChange:a=>W(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(oe?.available.modes??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Использовать mock",o.jsxs("select",{value:I.useMock,onChange:a=>W(c=>({...c,useMock:a.target.value})),children:[o.jsx("option",{value:"any",children:"любой"}),o.jsx("option",{value:"true",children:"да"}),o.jsx("option",{value:"false",children:"нет"})]})]}),o.jsxs("label",{children:["Лимит",o.jsx("input",{type:"number",min:1,max:500,value:Yn,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&yt(c)},onBlur:a=>Zr(a.target.value),onKeyDown:a=>{a.key==="Enter"&&Zr(a.target.value)}})]}),o.jsxs("label",{className:"full-width",children:["Версия промпта содержит",o.jsx("input",{value:I.promptContains,onChange:a=>W(c=>({...c,promptContains:a.target.value})),placeholder:"normalizer_v2_0_2 / address_query_runtime_v1",list:"autoruns-prompt-versions"})]})]}),o.jsx("datalist",{id:"autoruns-prompt-versions",children:(oe?.available.prompt_versions??[]).map(a=>o.jsx("option",{value:a},a))}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Xt,onClick:()=>{Ht({keepSelection:!1})},children:Xt?"Обновляю...":"Применить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{W({...bi,fromLocal:Nc()}),Be("")},children:"Сбросить фильтры"})]}),o.jsx("h4",{children:"Контур генерации"}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Провайдер:"}),o.jsx("strong",{children:i.llmProvider})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Модель:"}),o.jsx("strong",{children:i.model||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт ассистента:"}),o.jsx("strong",{children:m})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт декомпозиции:"}),o.jsx("strong",{children:R})]})]}),o.jsx("h4",{children:"Автогенерация вопросов"}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Режим генерации",o.jsxs("select",{value:h.mode,onChange:a=>C(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"codex_creative",children:"codex_creative"}),o.jsx("option",{value:"qwen_seed",children:"qwen_seed"})]})]}),o.jsxs("label",{children:["Кол-во",o.jsx("input",{type:"number",min:1,max:200,value:Jr,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&xt(c)},onBlur:a=>es(a.target.value),onKeyDown:a=>{a.key==="Enter"&&es(a.target.value)}})]}),o.jsxs("label",{children:["Личность автогенерации",o.jsx("select",{value:h.personalityId,onChange:a=>C(c=>({...c,personalityId:a.target.value})),children:Q.map(a=>o.jsx("option",{value:a.id,children:a.label},a.id))})]}),o.jsxs("label",{children:["Кто генерирует",o.jsx("input",{value:h.generatedBy,onChange:a=>C(c=>({...c,generatedBy:a.target.value})),placeholder:"manual_reviewer"})]}),o.jsxs("label",{className:"full-width",children:["Промпт личности",o.jsx("textarea",{className:"autoruns-personality-prompt",value:h.personalityPrompts[h.personalityId]??"",onChange:a=>C(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:a.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${Et}px`},onMouseUp:Bn,onTouchEnd:Bn})]}),o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:h.persistToEvalCases,onChange:a=>C(c=>({...c,persistToEvalCases:a.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата анализа (срез)",o.jsx("input",{type:"date",value:z,onChange:a=>U(Vi(a.target.value))})]}),o.jsx("div",{className:"button-row",children:o.jsx("button",{type:"button",className:"tab",disabled:!z,onClick:()=>U(""),children:"Сбросить дату среза"})})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:An,onClick:()=>{zr()},children:An?"Генерирую...":"Сгенерировать пачку"}),o.jsx("button",{type:"button",className:"tab",disabled:mn,onClick:()=>{wt()},children:mn?"Обновляю...":"Обновить историю"}),o.jsx("button",{type:"button",className:"autoruns-run-launch-btn",disabled:dr||xe.length===0,onClick:()=>{d()},children:dr?"Запускаю...":"Запустить прогоны"})]}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{className:"full-width",children:["Кейс-сет для запуска",o.jsxs("select",{value:ce,onChange:a=>de(a.target.value),disabled:G.length===0,children:[G.length===0?o.jsx("option",{value:"",children:"нет генераций"}):null,G.map(a=>o.jsxs("option",{value:a.generation_id,children:[ur(a.created_at)," | ",a.mode," | ",a.count," | ",a.saved_case_set_file??"без файла"]},a.generation_id))]})]})}),o.jsxs("div",{className:"autoruns-generated-questions",children:[o.jsxs("div",{className:"autoruns-generated-questions-head",children:[o.jsxs("strong",{children:["Вопросы к запуску: ",xe.length]}),o.jsx("button",{type:"button",className:"tab",onClick:()=>ge([...Rt?.questions??[]]),disabled:!Rt,children:"Восстановить"})]}),xe.length===0?o.jsx("p",{className:"muted",children:"Список вопросов пуст. Сгенерируйте пачку или восстановите из выбранной генерации."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:xe.map((a,c)=>o.jsxs("div",{className:"autoruns-generated-question-item",children:[o.jsxs("span",{children:[c+1,". ",a]}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onClick:()=>ge(y=>y.filter((A,pe)=>pe!==c)),title:"Удалить вопрос из запуска","aria-label":"Удалить вопрос из запуска",children:"+"})]},`${c}-${a.slice(0,24)}`))})]}),o.jsx("p",{className:"muted",children:"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."}),o.jsxs("div",{className:"autoruns-autogen-list",children:[mn?o.jsx("p",{className:"muted",children:"Загружаю историю автогенераций..."}):null,!mn&&G.length===0?o.jsx("p",{className:"muted",children:"История автогенераций пока пустая."}):null,G.slice(0,30).map(a=>o.jsxs("article",{className:ce===a.generation_id?"autoruns-autogen-item selected":"autoruns-autogen-item",onClick:()=>de(a.generation_id),children:[o.jsxs("header",{children:[o.jsx("strong",{children:ur(a.created_at)}),o.jsx("span",{children:a.mode})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["id=",a.generation_id," | count=",a.count]}),o.jsxs("div",{className:"autoruns-run-meta",children:["домен=",a.domain??"общий",a.generated_by?` | автор=${a.generated_by}`:""]}),a.saved_case_set_file?o.jsxs("div",{className:"autoruns-run-meta",children:["кейс-сет=",a.saved_case_set_file]}):null,(a.questions??[]).length>0?o.jsx("p",{children:a.questions[0]}):null]},a.generation_id))]}),o.jsxs("details",{className:"autoruns-prompt-details",children:[o.jsx("summary",{children:"Копия активного промпта (только чтение)"}),o.jsxs("label",{children:["Системный",o.jsx("textarea",{readOnly:!0,value:p.systemPrompt})]}),o.jsxs("label",{children:["Разработчика",o.jsx("textarea",{readOnly:!0,value:p.developerPrompt})]}),o.jsxs("label",{children:["Доменный",o.jsx("textarea",{readOnly:!0,value:p.domainPrompt})]}),o.jsxs("label",{children:["Заметки по схеме",o.jsx("textarea",{readOnly:!0,value:p.schemaNotes})]}),o.jsxs("label",{children:["Примеры few-shot",o.jsx("textarea",{readOnly:!0,value:p.fewShotExamples})]})]}),hn?o.jsx("p",{className:"error-text",children:hn}):null]}),o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Выдача прогонов"})}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Всего"}),o.jsx("strong",{children:(oe?.stats.runs_total??0)+(ee?1:0)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний score"}),o.jsx("strong",{children:ll(oe?.stats.avg_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:oe?Ec(oe.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Блокеры"}),o.jsx("strong",{children:oe?.stats.blocking_runs??0})]})]}),o.jsxs("div",{className:"autoruns-run-list",children:[Fn.map(a=>o.jsxs("button",{type:"button",className:fe===a.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{Tt(a.run_id)},children:[o.jsxs("div",{className:"autoruns-run-head",children:[o.jsx("strong",{children:ur(a.run_timestamp)}),o.jsx("span",{children:em(a.eval_target)})]}),o.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[o.jsx("span",{children:a.run_id}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{ct(c,a.run_id)},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),ct(c,a.run_id))},title:"Скопировать run id","aria-label":`Скопировать run id ${a.run_id}`,children:o.jsx(rm,{})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["режим=",a.mode??"нет данных"," | mock=",String(a.use_mock)]}),o.jsxs("div",{className:"autoruns-run-meta",children:["analysis_date=",a.analysis_date??"current_state"]}),a.llm_provider||a.model?o.jsxs("div",{className:"autoruns-run-meta",children:["llm=",a.llm_provider??"нет данных"," | модель=",a.model??"нет данных"]}):null,o.jsxs("div",{className:"autoruns-run-meta",children:["промпт=",a.prompt_version??"нет данных"]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["оценка: ",ll(a.score_index)]}),o.jsxs("span",{children:["закрыто/открыто: ",a.closed_cases,"/",a.open_cases]})]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["блокеры: ",a.blocking_failures]}),o.jsxs("span",{children:["качество: ",a.quality_failures]})]})]},a.run_id)),Fn.length===0?o.jsx("p",{className:"muted",children:"За выбранный диапазон прогонов нет."}):null]})]}),o.jsxs("section",{className:"autoruns-col",children:[o.jsxs("div",{className:"autoruns-col-header",children:[o.jsx("h3",{children:"Диалог прогона"}),o.jsxs("div",{className:"autoruns-dialog-toolbar",children:[o.jsxs("label",{children:["Прогон",o.jsx("select",{value:fe,onChange:a=>{const c=a.target.value;Tt(c)},children:Fn.map(a=>o.jsxs("option",{value:a.run_id,children:[ur(a.run_timestamp)," | ",a.run_id]},a.run_id))})]}),o.jsxs("label",{children:["Кейс",o.jsxs("select",{value:me,onChange:a=>{const c=a.target.value;D(c),fe&&c&&bn(fe,c)},children:[(te?.cases.length??0)>0?o.jsx("option",{value:gt,children:"ВСЕ кейсы подряд"}):null,(te?.cases??[]).map(a=>o.jsxs("option",{value:a.case_id,children:[a.case_id," | ",a.status]},a.case_id))]})]})]})]}),o.jsxs("div",{className:"autoruns-case-list",children:[(te?.cases.length??0)>0?o.jsxs("button",{type:"button",className:me===gt?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{D(gt),fe&&bn(fe,gt)},children:[o.jsx("span",{children:"ВСЕ кейсы подряд"}),o.jsx("span",{children:te?.cases.length})]},gt):null,(te?.cases??[]).map(a=>o.jsxs("button",{type:"button",className:me===a.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{D(a.case_id),fe&&bn(fe,a.case_id)},children:[o.jsx("span",{children:a.case_id}),o.jsxs("span",{children:[a.status,a.commented_count>0?` | комм=${a.commented_count}`:""]})]},a.case_id))]}),o.jsxs("div",{className:"autoruns-dialog-view",children:[mr||fr?o.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!mr&&!fr&&(q?.messages.length??0)===0?o.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(q?.messages??[]).map((a,c)=>{const y=a.role==="assistant"?"assistant":"user";return o.jsxs("article",{className:`autoruns-msg ${y}`,children:[o.jsxs("header",{children:[o.jsx("strong",{children:y==="assistant"?"Система":"Модель/вопрос"}),o.jsxs("div",{className:"autoruns-msg-head-actions",children:[a.case_id?o.jsx("span",{className:"autoruns-msg-case-tag",children:a.case_id}):null,o.jsx("span",{children:a.created_at?ur(a.created_at):"нет данных"}),y==="assistant"&&!js(fe)?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:a.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>P(a),title:"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b","aria-label":"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b",children:o.jsx(nm,{commented:a.commented})}),a.annotation?o.jsx("button",{type:"button",className:a.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{_n(a.annotation,!a.annotation.resolved)},disabled:pr===a.annotation.annotation_id,title:a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Mc,{resolved:a.annotation.resolved})}):null]}):null]})]}),o.jsx("p",{children:a.text}),y==="assistant"&&a.annotation?o.jsxs("div",{className:"autoruns-msg-annotation",children:[o.jsx("strong",{children:Qi(a.annotation.rating)}),o.jsx("span",{children:a.annotation.comment}),o.jsxs("span",{className:"muted",children:[a.annotation.manual_case_decision,a.annotation.annotation_author?` | ${a.annotation.annotation_author}`:""]})]}):null,(a.trace_id||a.reply_type)&&o.jsxs("footer",{children:[a.trace_id?o.jsxs("span",{children:["trace=",a.trace_id]}):null,a.reply_type?o.jsxs("span",{children:["reply_type=",a.reply_type]}):null]})]},a.message_id??`${y}-${c}`)})]})]}),j?o.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:o.jsx(Fc,{sessionId:st,conversation:vn,inputValue:Dn,onInputChange:rn,selectedContextChip:bt,onSelectContextChip:vt,onClearContextChip:()=>vt(null),useMock:Jn,onUseMockChange:Ke,onSend:Cs,onClear:St,busy:hr,statusText:gr,errorMessage:vr,showCommentAction:!0,onCommentAssistantMessage:ro,isAssistantMessageCommented:Hn,canCommentAssistantMessage:er})}):null,T?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Режим декомпозиции"})}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"кейс:"}),o.jsx("strong",{children:On?.case_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"домен:"}),o.jsx("strong",{children:On?.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"класс запроса:"}),o.jsx("strong",{children:On?.query_class??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"trace:"}),o.jsx("strong",{children:On?.trace_id??"нет данных"})]})]}),o.jsx("h4",{children:"Шаги декомпозиции"}),(q?.decomposition.length??0)>0?o.jsx("ol",{className:"autoruns-decomposition-list",children:(q?.decomposition??[]).map((a,c)=>o.jsx("li",{children:a},`${c}-${a.slice(0,24)}`))}):o.jsx("p",{className:"muted",children:"В логах кейса нет явной декомпозиции."})]}):null,$?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Прогресс / регресс"})}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Последний score"}),o.jsx("strong",{children:ll(oe?.stats.latest_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Предыдущий"}),o.jsx("strong",{children:ll(oe?.stats.previous_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:oe?Ec(oe.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Пробелы качества"}),o.jsx("strong",{children:oe?.stats.quality_gap_runs??0})]})]}),o.jsx("h4",{children:"Покрытие доменов (история)"}),Pc(oe?.stats.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),Pc(te?.coverage.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),Yt?o.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,Yt?null:o.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(Ft?.post_analysis.stats.by_queue??{}).map(([a,c])=>o.jsxs("div",{children:[o.jsx("span",{children:a}),o.jsx("strong",{children:c})]},a))}),o.jsxs("div",{className:"autoruns-autogen-list",children:[(Ft?.post_analysis.recommended_regression_candidates??[]).slice(0,12).map(a=>o.jsxs("article",{className:"autoruns-autogen-item",children:[o.jsxs("header",{children:[o.jsx("strong",{children:a.manual_case_decision}),o.jsxs("span",{children:[a.rating,"/5"]})]}),o.jsxs("div",{className:"autoruns-run-meta",children:[a.domain??"неизвестно"," / ",a.query_class??"неизвестно"]}),o.jsx("p",{children:a.comment})]},a.annotation_id)),!Yt&&(Ft?.post_analysis.recommended_regression_candidates.length??0)===0?o.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Y?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Комментарии"})}),o.jsx("h4",{children:"Размеченные ответы"}),o.jsxs("div",{className:"autoruns-comment-filter-row",children:[o.jsxs("label",{children:["Фильтр решений",o.jsxs("select",{value:Ae,onChange:a=>De(a.target.value),children:[o.jsx("option",{value:"all",children:"все"}),(rt.length>0?rt:Ge?.enum??[]).map(a=>o.jsx("option",{value:a,children:String(Ge?.labels?.[a]??a)},a))]})]}),o.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>We(a=>!a),children:$e?"Показать выполненные":"Скрыть выполненные"})]}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Комментариев"}),o.jsx("strong",{children:ut.length})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний рейтинг"}),o.jsx("strong",{children:yr===null?"нет данных":`${yr.toFixed(2)} / 5`})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Последний"}),o.jsx("strong",{children:ut.length>0?ur(ut[0].updated_at):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Статус"}),o.jsx("strong",{children:Zt?"обновляю":"готово"})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Zt,onClick:()=>{At()},children:Zt?"Обновляю...":"Обновить список"}),o.jsx("button",{type:"button",className:"tab",disabled:Yt,onClick:()=>{dt()},children:Yt?"Идет пост-анализ...":"Обновить пост-анализ"})]}),o.jsxs("div",{className:"autoruns-comments-list",children:[Zt?o.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!Zt&&ut.length===0?o.jsx("p",{className:"muted",children:Se.length===0&&nn.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,ut.map(a=>{if(a.source==="assistant_live"){const y=a.assistant;return o.jsxs("article",{className:"autoruns-comment-item",children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Qi(y.rating)}),o.jsx("div",{className:"autoruns-comment-head-actions",children:o.jsx("span",{children:ur(y.updated_at)})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",y.session_id]}),o.jsxs("div",{className:"autoruns-run-meta",children:["msg=",y.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",y.annotation_author?` | author=${y.annotation_author}`:""]}),y.context.question_text?o.jsxs("p",{children:["Q: ",y.context.question_text]}):null,y.context.answer_text?o.jsxs("p",{children:["A: ",y.context.answer_text]}):null,o.jsx("p",{children:y.comment})]},a.key)}const c=a.autorun;return o.jsxs("article",{className:Te===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{Sn(c)},role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),Sn(c))},children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Qi(c.rating)}),o.jsxs("div",{className:"autoruns-comment-head-actions",children:[o.jsx("span",{children:ur(c.updated_at)}),o.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:y=>{y.preventDefault(),y.stopPropagation(),_n(c,!c.resolved)},disabled:pr===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Mc,{resolved:c.resolved})})]})]}),o.jsx("div",{className:"autoruns-run-meta",children:c.run_id}),o.jsxs("div",{className:"autoruns-run-meta",children:["case=",c.case_id," | msg=",c.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["decision=",c.manual_case_decision,c.annotation_author?` | author=${c.annotation_author}`:""]}),c.resolved_at?o.jsxs("div",{className:"autoruns-run-meta",children:["выполнено",": ",ur(c.resolved_at),c.resolved_by?` | by=${c.resolved_by}`:""]}):null,c.context.question_text?o.jsxs("p",{children:["Q: ",c.context.question_text]}):null,c.context.answer_text?o.jsxs("p",{children:["A: ",c.context.answer_text]}):null,o.jsx("p",{children:c.comment})]},a.key)})]}),Ne?o.jsxs(o.Fragment,{children:[o.jsx("h4",{children:"Тех-контекст брака"}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"trace:"}),o.jsx("strong",{children:Ne.technical_context.trace_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"reply_type:"}),o.jsx("strong",{children:Ne.technical_context.reply_type??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"domain:"}),o.jsx("strong",{children:Ne.technical_context.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"query_class:"}),o.jsx("strong",{children:Ne.technical_context.query_class??"нет данных"})]})]}),o.jsx("h4",{children:"JSON разбор"}),o.jsx(Gt,{value:{annotation_id:Ne.annotation_id,run_id:Ne.run_id,case_id:Ne.case_id,message_index:Ne.message_index,rating:Ne.rating,comment:Ne.comment,manual_case_decision:Ne.manual_case_decision,annotation_author:Ne.annotation_author,resolved:Ne.resolved,resolved_at:Ne.resolved_at,resolved_by:Ne.resolved_by,context:Ne.context,technical_context:Ne.technical_context,case_summary:Ne.case_summary?{case_id:Ne.case_summary.case_id,domain:Ne.case_summary.domain,query_class:Ne.case_summary.query_class,checks:Ne.case_summary.checks,metric_subscores:Ne.case_summary.metric_subscores}:null}})]}):null]}):null]}),ve.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Mt()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),Xr?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:Xr.text})]}):null,Ie?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:Ie.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа ассистента",children:[1,2,3,4,5].map(a=>o.jsx("button",{type:"button",className:ve.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>_t(c=>({...c,rating:a})),disabled:ve.saving,"aria-label":`Оценка ${a}`,children:ve.rating>=a?"●":"○"},a))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ve.annotationAuthor,onChange:a=>_t(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ve.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ve.comment,onChange:a=>_t(c=>({...c,comment:a.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:ve.saving})]}),ve.error?o.jsx("p",{className:"error-text",children:ve.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{Ns()},disabled:ve.saving,children:ve.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Mt(),disabled:ve.saving,children:"Отмена"})]})]})}):null,ue.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&k()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу системы"}),o.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),$n?o.jsxs(o.Fragment,{children:[o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:Yr?.text??"Вопрос в диалоге не найден."})]}),o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ системы"}),o.jsx("p",{className:"autoruns-comment-quote",children:$n.text})]})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(a=>o.jsx("button",{type:"button",className:ue.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>ot(c=>({...c,rating:a})),disabled:ue.saving,"aria-label":`Оценка ${a}`,children:ue.rating>=a?"●":"○"},a))}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Решение по кейсу",o.jsx("select",{value:ue.manualCaseDecision,onChange:a=>ot(c=>({...c,manualCaseDecision:a.target.value})),disabled:ue.saving,children:(rt.length>0?rt:Ge?.enum??[sl]).map(a=>o.jsx("option",{value:a,children:String(Ge?.labels?.[a]??a)},a))})]}),o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ue.annotationAuthor,onChange:a=>ot(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ue.saving})]})]}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ue.comment,onChange:a=>ot(c=>({...c,comment:a.target.value})),placeholder:"Почему ответ бракованный, что именно пошло не так, какие технические детали проверить.",rows:4,disabled:ue.saving})]}),ue.error?o.jsx("p",{className:"error-text",children:ue.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ye()},disabled:ue.saving,children:ue.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>k(),disabled:ue.saving,children:"Отмена"})]})]})}):null]})}function Ac({value:i,modelOptions:p,modelsBusy:m,onChange:R,onReloadModels:j,onTestConnection:T,onSaveLocalConfig:$,lastStatus:Y,busy:F}){const I=i.llmProvider==="local",W=p.includes(i.model),[z,U]=x.useState(String(i.temperature)),[oe,Me]=x.useState(String(i.maxOutputTokens));x.useEffect(()=>{U(String(i.temperature))},[i.temperature]),x.useEffect(()=>{Me(String(i.maxOutputTokens))},[i.maxOutputTokens]);const te=q=>{const re=q.replace(",",".").trim();if(!re){U(String(i.temperature));return}const Se=Number(re);if(!Number.isFinite(Se)){U(String(i.temperature));return}R({...i,temperature:Se}),U(String(Se))},se=q=>{const re=q.trim();if(!re){Me(String(i.maxOutputTokens));return}const Se=Number.parseInt(re,10);if(!Number.isFinite(Se)||Se<=0){Me(String(i.maxOutputTokens));return}R({...i,maxOutputTokens:Se}),Me(String(Se))};return o.jsxs(Mn,{title:"LLM Connection",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:o.jsx("span",{className:"status-chip",children:Y||"Status: not checked"}),children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{children:["Provider",o.jsxs("select",{value:i.llmProvider,onChange:q=>{const re=q.target.value==="local"?"local":"openai";R({...i,llmProvider:re,baseUrl:re==="local"?"http://127.0.0.1:1234/v1":"https://api.openai.com/v1"})},children:[o.jsx("option",{value:"openai",children:"OpenAI (token)"}),o.jsx("option",{value:"local",children:"Local (LM Studio / OpenAI-compatible)"})]})]}),o.jsxs("label",{children:["Model",o.jsxs("select",{value:W?i.model:"__manual__",onChange:q=>{const re=q.target.value;re!=="__manual__"&&R({...i,model:re})},children:[o.jsx("option",{value:"__manual__",children:"Manual input"}),p.map(q=>o.jsx("option",{value:q,children:q},q))]})]}),o.jsxs("label",{children:["Model ID (manual)",o.jsx("input",{value:i.model,onChange:q=>R({...i,model:q.target.value}),placeholder:"qwen2.5-14b-instruct or lmstudio loaded model id"})]}),I?null:o.jsxs("label",{className:"full-width",children:["OpenAI API Key",o.jsx("input",{type:"password",value:i.apiKey,onChange:q=>R({...i,apiKey:q.target.value}),placeholder:"sk-..."})]}),o.jsxs("label",{className:I?"full-width":void 0,children:[I?"Local server base URL":"Base URL",o.jsx("input",{value:i.baseUrl,onChange:q=>R({...i,baseUrl:q.target.value}),placeholder:I?"http://127.0.0.1:1234/v1":"https://api.openai.com/v1"})]}),o.jsxs("label",{children:["Temperature",o.jsx("input",{type:"number",step:"0.1",value:z,onChange:q=>U(q.target.value),onBlur:q=>te(q.target.value),onKeyDown:q=>{q.key==="Enter"&&te(q.target.value)}})]}),o.jsxs("label",{children:["Max output tokens",o.jsx("input",{type:"number",value:oe,onChange:q=>Me(q.target.value),onBlur:q=>se(q.target.value),onKeyDown:q=>{q.key==="Enter"&&se(q.target.value)}})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>$(),children:"Save local config"}),o.jsx("button",{type:"button",onClick:()=>j(),disabled:F||m,children:m?"Loading models...":"Load model list"}),o.jsx("button",{type:"button",onClick:()=>T(),disabled:F,children:F?"Checking...":"Test connection"})]})]})}function om({items:i,onRefresh:p,onOpenTrace:m}){return o.jsx(Mn,{title:"История нормализаций",subtitle:"Короткий вопрос, confidence, route hint и статус валидации.",actions:o.jsx("button",{type:"button",onClick:()=>p(),children:"Обновить"}),children:o.jsxs("div",{className:"history-list",children:[i.length===0?o.jsx("p",{className:"muted",children:"История пока пустая."}):null,i.map(R=>o.jsxs("button",{type:"button",className:"history-item",onClick:()=>m(R.trace_id),children:[o.jsxs("div",{className:"history-row",children:[o.jsx("strong",{children:R.route_hint??"route: n/a"}),o.jsx("span",{children:R.validation_passed?"schema: ok":"schema: fail"})]}),o.jsx("p",{children:R.question_short}),o.jsxs("div",{className:"history-row",children:[o.jsx("span",{children:R.model}),o.jsx("span",{children:new Date(R.timestamp).toLocaleString("ru-RU")})]})]},R.trace_id))]})})}function cr(i){return i==null||i===""?"—":String(i)}function lm({result:i}){return o.jsx(Mn,{title:"Runtime метрики",subtitle:"trace_id, токены, latency и статус валидации.",children:o.jsxs("div",{className:"metrics-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"trace_id"}),o.jsx("strong",{children:cr(i?.trace_id)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"request_started_at"}),o.jsx("strong",{children:cr(i?new Date(Date.now()-i.latency_ms).toISOString():null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"request_finished_at"}),o.jsx("strong",{children:cr(i?new Date().toISOString():null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"latency_ms"}),o.jsx("strong",{children:cr(i?.latency_ms)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"input_tokens"}),o.jsx("strong",{children:cr(i?.usage?.input_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"output_tokens"}),o.jsx("strong",{children:cr(i?.usage?.output_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"total_tokens"}),o.jsx("strong",{children:cr(i?.usage?.total_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"validation_status"}),o.jsx("strong",{children:i?.validation?.passed?"passed":"failed"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"prompt_version"}),o.jsx("strong",{children:cr(i?.prompt_version)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"schema_version"}),o.jsx("strong",{children:cr(i?.schema_version)})]})]})})}const im={normalized:"Normalized JSON",fragments:"Fragment View",scope:"Scope View",flags:"Flags View",route:"Route Simulation",raw:"Raw model output",validation:"Validation",logs:"Logs"};function am(i){return i&&typeof i=="object"?i:null}function um({tab:i,onTabChange:p,result:m,appLogs:R}){const j=["normalized","fragments","scope","flags","route","raw","validation","logs"],T=am(m?.normalized),$=String(T?.schema_version??""),Y=$==="normalized_query_v2"||$==="normalized_query_v2_0_1"||$==="normalized_query_v2_0_2",F=Y?{fragments:T?.fragments??[],discarded_fragments:T?.discarded_fragments??[]}:{note:"Fragment View доступен для normalized_query_v2."},I=Y?{message_in_scope:T?.message_in_scope??null,scope_confidence:T?.scope_confidence??null,contains_multiple_tasks:T?.contains_multiple_tasks??null,global_notes:T?.global_notes??null}:{note:"Scope View доступен для normalized_query_v2."},W=Y?Array.isArray(T?.fragments)?(T?.fragments).map(z=>({fragment_id:z.fragment_id??null,domain_relevance:z.domain_relevance??null,candidate_labels:z.candidate_labels??[],execution_readiness:z.execution_readiness??null,clarification_reason:z.clarification_reason??null,soft_assumption_used:z.soft_assumption_used??[],route_status:z.route_status??null,no_route_reason:z.no_route_reason??null,flags:z.flags??{}})):[]:{note:"Flags View доступен для normalized_query_v2."};return o.jsxs(Mn,{title:"Выходные данные",subtitle:"Structured output и диагностические вкладки.",children:[o.jsx("div",{className:"tab-row",children:j.map(z=>o.jsx("button",{type:"button",className:i===z?"tab active":"tab",onClick:()=>p(z),children:im[z]},z))}),i==="normalized"?o.jsx(Gt,{value:m?.normalized??{note:"Нет данных."}}):null,i==="fragments"?o.jsx(Gt,{value:F}):null,i==="scope"?o.jsx(Gt,{value:I}):null,i==="flags"?o.jsx(Gt,{value:W}):null,i==="route"?o.jsx(Gt,{value:m?.route_hint_summary??{note:"Нет данных."}}):null,i==="raw"?o.jsx(Gt,{value:m?.raw_model_output??{note:"Нет данных."}}):null,i==="validation"?o.jsx(Gt,{value:m?.validation??{note:"Нет данных."}}):null,i==="logs"?o.jsx(Gt,{value:R}):null]})}function Tc({value:i,onChange:p,presets:m,selectedPresetId:R,onSelectPreset:j,onLoadPreset:T,onSavePreset:$,onResetDefaults:Y,onDiffPrevious:F,presetName:I,onPresetNameChange:W,diffSummary:z}){return o.jsxs(Mn,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:[o.jsxs("div",{className:"prompt-manager-grid",children:[o.jsxs("label",{children:["Системный prompt",o.jsx("textarea",{value:i.systemPrompt,onChange:U=>p({...i,systemPrompt:U.target.value}),rows:6})]}),o.jsxs("label",{children:["Developer / Instruction prompt",o.jsx("textarea",{value:i.developerPrompt,onChange:U=>p({...i,developerPrompt:U.target.value}),rows:6})]}),o.jsxs("label",{children:["Domain prompt",o.jsx("textarea",{value:i.domainPrompt,onChange:U=>p({...i,domainPrompt:U.target.value}),rows:6})]}),o.jsxs("label",{children:["Schema notes",o.jsx("textarea",{value:i.schemaNotes,onChange:U=>p({...i,schemaNotes:U.target.value}),rows:6})]}),o.jsxs("label",{className:"full-width",children:["Few-shot examples",o.jsx("textarea",{value:i.fewShotExamples,onChange:U=>p({...i,fewShotExamples:U.target.value}),rows:8})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("select",{value:R,onChange:U=>j(U.target.value),children:[o.jsx("option",{value:"",children:"Выберите preset..."}),m.map(U=>o.jsx("option",{value:U.id,children:U.name},U.id))]}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Загрузить preset"}),o.jsx("input",{value:I,onChange:U=>W(U.target.value),placeholder:"Имя для сохранения"}),o.jsx("button",{type:"button",onClick:()=>$(),children:"Сохранить preset"}),o.jsx("button",{type:"button",onClick:()=>F(),children:"Diff с предыдущим"}),o.jsx("button",{type:"button",onClick:()=>Y(),children:"Сбросить к default"})]}),z?o.jsx("p",{className:"diff-summary",children:z}):null]})}function cm({value:i,onChange:p,onApplyBatchFormat:m,onNormalize:R,busy:j,useMock:T,onUseMockChange:$,errorMessage:Y}){return o.jsxs(Mn,{title:"Запрос пользователя",subtitle:"NDC semantic front-end: нормализуем, но не отвечаем за бухгалтерскую суть.",children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{className:"full-width",children:["Raw user question",o.jsx("textarea",{value:i.userQuestion,onChange:F=>p({...i,userQuestion:F.target.value}),rows:6,placeholder:"Например: По каким покупателям у нас на конец июня висят отгрузки без оплаты..."})]}),o.jsxs("label",{className:"full-width",children:["Batch queries (`;` separator)",o.jsx("textarea",{value:i.batchQuestionsRaw,onChange:F=>p({...i,batchQuestionsRaw:F.target.value}),onBlur:()=>m(),rows:8,placeholder:"Вопрос 1; Вопрос 2; Вопрос 3"})]}),o.jsxs("label",{children:["Optional period context",o.jsx("input",{value:i.periodHint,onChange:F=>p({...i,periodHint:F.target.value})})]}),o.jsxs("label",{children:["Optional business context",o.jsx("input",{value:i.businessContext,onChange:F=>p({...i,businessContext:F.target.value})})]}),o.jsxs("label",{children:["Optional expected route (eval)",o.jsx("input",{value:i.expectedRoute,onChange:F=>p({...i,expectedRoute:F.target.value})})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:T,onChange:F=>$(F.target.checked)}),"Mock-режим (без вызова OpenAI)"]}),o.jsx("button",{type:"button",onClick:()=>m(),disabled:j||!i.batchQuestionsRaw.trim(),children:"Применить `;` в переносы"}),o.jsx("button",{type:"button",onClick:()=>R(!1),disabled:j||!i.userQuestion.trim(),children:j?"Нормализуем...":"Normalize"}),o.jsx("button",{type:"button",onClick:()=>R(!0),disabled:j||!i.userQuestion.trim(),children:j?"Сохраняем...":"Normalize + Save as test case"})]}),Y?o.jsx("p",{className:"error-text",children:Y}):null]})}function dm({runs:i,selectedRunId:p,onSelectRun:m,onStartRun:R,onFinishRun:j,onRefreshRuns:T,onRunEval:$,onCopyEvalReport:Y,evalBusy:F,traceItems:I,evalReport:W}){return o.jsxs(Mn,{title:"NDC Run Monitor",subtitle:"Важно: кнопка Запустить run создает только run-сущность. Кнопка eval запускает batch-проверку normalizer v2.0.2.",children:[o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>R(),children:"Запустить run"}),o.jsx("button",{type:"button",onClick:()=>j(),disabled:!p,children:"Завершить выбранный run"}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Обновить runs"}),o.jsx("button",{type:"button",onClick:()=>$(),disabled:F,children:F?"Идет eval v2.0.2...":"Запустить eval v2.0.2"})]}),o.jsxs("div",{className:"runtime-stack",children:[o.jsxs("div",{className:"runtime-runs",children:[i.map(z=>o.jsxs("button",{type:"button",className:p===z.runId?"history-item selected":"history-item",onClick:()=>m(z.runId),children:[o.jsxs("div",{className:"history-row",children:[o.jsx("strong",{children:z.status}),o.jsx("span",{children:z.runId})]}),o.jsxs("div",{className:"history-row",children:[o.jsx("span",{children:z.sessionId}),o.jsx("span",{children:new Date(z.updatedAt).toLocaleString("ru-RU")})]})]},z.runId)),i.length===0?o.jsx("p",{className:"muted",children:"Нет активных запусков."}):null]}),o.jsxs("div",{className:"runtime-details",children:[o.jsx("h3",{children:"Trace выбранного run"}),o.jsx(Gt,{value:I}),o.jsxs("div",{className:"eval-report-wrap",children:[o.jsx("h3",{style:{marginTop:12},children:"Отчет eval"}),o.jsx(Gt,{value:W??{note:"Eval пока не запускался"}}),o.jsx("button",{type:"button",className:"copy-cube-button",title:"Скопировать отчет eval",onClick:()=>Y(),children:"⧉"})]})]})]})]})}const fm={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},Ic={systemPrompt:"Ты semantic-normalizer для бухгалтерского ассистента NDC. Возвращай только JSON по схеме normalized_query_v2_0_2.",developerPrompt:"Сначала делай decomposition сообщения на task fragments, затем определяй domain scope и route-critical flags. Для каждого fragment заполняй execution_readiness + route_status + no_route_reason. Если fragment routable, не оставляй его в no_route.",domainPrompt:"Контур: данные текущего предприятия в 1С/NDC. In-scope: документы, проводки, взаиморасчеты, остатки, периодное закрытие, аномалии и контрольные проверки. Out-of-scope: общая теория, законы и оффтоп.",schemaNotes:"schema_version: normalized_query_v2_0_2. Строгий JSON без дополнительных полей.",fewShotExamples:"Q: Проверь по поставщикам хвосты и разложи цепочку документов/оплат. => fragment in_scope, flags: multi_entity + chain_explanation. Q: Как вообще по ФСБУ? => out_of_scope/generic_accounting."},mm={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},Wi={colors:{backgroundRgb:"18, 18, 18",mainSurfaceRgb:"25, 25, 25",horizontalSurfaceRgb:"30, 30, 30",focusSurfaceRgb:"35, 35, 35",assistantChipRgb:"18, 18, 18",assistantChipHoverRgb:"44, 44, 44",assistantChipSelectedRgb:"167, 59, 255",assistantChipSelectedTextRgb:"240, 240, 240",activeRgb:"167, 59, 255",activeTextRgb:"240, 240, 240",textMainRgb:"240, 240, 240",textMutedRgb:"166, 166, 166",dangerRgb:"126, 126, 126",scrollbarTrackRgb:"20, 20, 20",scrollbarThumbRgb:"30, 30, 30",scrollbarThumbHoverRgb:"30, 50, 30"},layout:{modeColumnWidthPx:406,modeToggleWidthPx:188}},Lc="ndc_normalizer_session_config_v1",Dc="ndc_autoruns_layout_config_v1",pm="ndc-autoruns-save",Ki=["Анализ запроса","Получение данных","Подготовка ответа"],hm="assistant",qi="normalizer_v2_0_2",zc="address_query_runtime_v1",gm=["normalized","fragments","scope","flags","route","raw","validation","logs"],Gi="manual_reviewer";function vm(i){return`[${new Date().toLocaleTimeString("ru-RU")}] ${i}`}function ym(i,p){if(!p)return"Previous preset is not selected.";const R=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(j=>i[j]!==p[j]).map(j=>`${j}: ${Math.abs(i[j].length-p[j].length)} chars delta`);return R.length===0?"No changes against previous preset.":`Changed fields: ${R.length}. ${R.join(" | ")}`}function xm(i,p){const m=i.trim();if(!m)return"";if(!p)return m;const R=m.toLowerCase(),j=p.anchor_text.trim(),T=j.toLowerCase();return T&&R.includes(T)?m:`По выбранному объекту "${j}": ${m}`}function _m(){const[i,p]=x.useState(fm),[m,R]=x.useState(Ic),[j,T]=x.useState(mm),[$,Y]=x.useState(null),[F,I]=x.useState([]),[W,z]=x.useState([]),[U,oe]=x.useState("normalized"),[Me,te]=x.useState(!1),[se,q]=x.useState(!1),[re,Se]=x.useState([]),[Pe,Ae]=x.useState(""),[De,$e]=x.useState([]),[We,Ge]=x.useState(""),[Ze,rt]=x.useState("NDC custom preset"),[ie,Te]=x.useState(null),[Fe,fe]=x.useState(""),[Re,me]=x.useState(!1),[D,Q]=x.useState([]),[O,h]=x.useState(""),[C,G]=x.useState([]),[ae,ce]=x.useState(!1),[de,xe]=x.useState(null),[ge,ee]=x.useState(""),[ke,Ft]=x.useState(hm),[qn,An]=x.useState(!0),[Tn,dr]=x.useState(!0),[Jt,Yt]=x.useState(!0),[Gn,mn]=x.useState(!0),[Ut,Xt]=x.useState(!0),[pn,fr]=x.useState(!0),[In,mr]=x.useState(!0),[Ln,Zt]=x.useState(!0),[en,pr]=x.useState(!0),[Bt,hn]=x.useState(!0),[Be,st]=x.useState(!0),[gn,vn]=x.useState(!0),[tn,nn]=x.useState(!0),[Ct,Dn]=x.useState(!0),[rn,bt]=x.useState(!0),[vt,Jn]=x.useState(!0),[Ke,hr]=x.useState(""),[yn,gr]=x.useState([]),[sn,vr]=x.useState(""),[Nt,Yn]=x.useState(null),[yt,Jr]=x.useState(!1),[xt,Et]=x.useState(""),[zn,ue]=x.useState(""),[ot,ve]=x.useState([]),[_t,Pt]=x.useState(!1),[we,lt]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:Gi,saving:!1,error:""}),Rt=x.useRef(!1),On=x.useRef(!1);x.useEffect(()=>{const d=document.documentElement,{colors:P}=Wi;d.style.setProperty("--rgb-background",P.backgroundRgb),d.style.setProperty("--rgb-surface-main",P.mainSurfaceRgb),d.style.setProperty("--rgb-surface-horizontal",P.horizontalSurfaceRgb),d.style.setProperty("--rgb-surface-focus",P.focusSurfaceRgb),d.style.setProperty("--rgb-assistant-chip",P.assistantChipRgb),d.style.setProperty("--rgb-assistant-chip-hover",P.assistantChipHoverRgb),d.style.setProperty("--rgb-assistant-chip-selected",P.assistantChipSelectedRgb),d.style.setProperty("--rgb-assistant-chip-selected-text",P.assistantChipSelectedTextRgb),d.style.setProperty("--rgb-active",P.activeRgb),d.style.setProperty("--rgb-active-text",P.activeTextRgb),d.style.setProperty("--rgb-text-main",P.textMainRgb),d.style.setProperty("--rgb-text-muted",P.textMutedRgb),d.style.setProperty("--rgb-danger",P.dangerRgb),d.style.setProperty("--rgb-scrollbar-track",P.scrollbarTrackRgb),d.style.setProperty("--rgb-scrollbar-thumb",P.scrollbarThumbRgb),d.style.setProperty("--rgb-scrollbar-thumb-hover",P.scrollbarThumbHoverRgb),d.style.setProperty("--mode-column-width",`${Wi.layout.modeColumnWidthPx}px`),d.style.setProperty("--mode-toggle-width",`${Wi.layout.modeToggleWidthPx}px`)},[]);const J=d=>{z(P=>[vm(d),...P].slice(0,300))};function Ne(){let d=0;Et(Ki[0]);const P=window.setInterval(()=>{d=Math.min(d+1,Ki.length-1),Et(Ki[d])},650);return()=>window.clearInterval(P)}x.useEffect(()=>{const d=localStorage.getItem(Lc);if(d)try{const k=JSON.parse(d);p(ye=>({...ye,llmProvider:k.llmProvider==="local"?"local":"openai",model:k.model??ye.model,baseUrl:k.baseUrl??ye.baseUrl,temperature:k.temperature??ye.temperature,maxOutputTokens:k.maxOutputTokens??ye.maxOutputTokens}))}catch{}const P=localStorage.getItem(Dc);if(P)try{const k=JSON.parse(P);(k.uiMode==="assistant"||k.uiMode==="decomposition"||k.uiMode==="autoruns")&&Ft(k.uiMode),k.activeTab&&gm.includes(k.activeTab)&&oe(k.activeTab),typeof k.showAutorunsAssistantMode=="boolean"&&An(k.showAutorunsAssistantMode),typeof k.showAutorunsDecompositionMode=="boolean"&&dr(k.showAutorunsDecompositionMode),typeof k.showAutorunsProgressMode=="boolean"&&Yt(k.showAutorunsProgressMode),typeof k.showAutorunsCommentsMode=="boolean"&&mn(k.showAutorunsCommentsMode),typeof k.showAssistantConnectionMode=="boolean"&&Xt(k.showAssistantConnectionMode),typeof k.showAssistantPromptMode=="boolean"&&fr(k.showAssistantPromptMode),typeof k.showAssistantChatMode=="boolean"&&mr(k.showAssistantChatMode),typeof k.showAssistantCommentsMode=="boolean"&&Zt(k.showAssistantCommentsMode),typeof k.showAssistantSamMode=="boolean"&&pr(k.showAssistantSamMode),typeof k.showDecompositionConnectionMode=="boolean"&&hn(k.showDecompositionConnectionMode),typeof k.showDecompositionPromptMode=="boolean"&&st(k.showDecompositionPromptMode),typeof k.showDecompositionQueryMode=="boolean"&&vn(k.showDecompositionQueryMode),typeof k.showDecompositionOutputMode=="boolean"&&nn(k.showDecompositionOutputMode),typeof k.showDecompositionMetricsMode=="boolean"&&Dn(k.showDecompositionMetricsMode),typeof k.showDecompositionHistoryMode=="boolean"&&bt(k.showDecompositionHistoryMode),typeof k.showDecompositionRuntimeMode=="boolean"&&Jn(k.showDecompositionRuntimeMode),k.prompts&&(R(ye=>({...ye,...k.prompts})),On.current=!0)}catch{}$n(),Yr(),xn()},[]);async function $n(){try{const d=await Ce.loadHistory();I(d.items??[])}catch(d){J(`History load error: ${d instanceof Error?d.message:String(d)}`)}}async function Yr(){try{const P=(await Ce.loadPresets()).presets??[];if($e(P),On.current){Rt.current=!0;return}if(Rt.current)return;const k=P.find(ye=>ye.prompt_version===qi)??P.find(ye=>ye.id==="default-normalizer-v2_0_2");if(!k){Rt.current=!0,J(`Preset autoload skipped: ${qi} not found.`);return}Ge(k.id),Te(m),R({systemPrompt:k.systemPrompt,developerPrompt:k.developerPrompt,domainPrompt:k.domainPrompt,schemaNotes:k.schemaNotes??"",fewShotExamples:k.fewShotExamples??""}),Rt.current=!0,J(`Preset autoloaded: ${k.name} (${k.prompt_version}).`)}catch(d){J(`Presets load error: ${d instanceof Error?d.message:String(d)}`)}}async function xn(){try{const d=await Ce.listRuns();Q(d.items??[])}catch(d){J(`Runs load error: ${d instanceof Error?d.message:String(d)}`)}}function Ie(){localStorage.setItem(Lc,JSON.stringify({model:i.model,llmProvider:i.llmProvider,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})),J("Local config saved (without API key).")}function Xr(){localStorage.setItem(Dc,JSON.stringify({uiMode:ke,activeTab:U,showAutorunsAssistantMode:qn,showAutorunsDecompositionMode:Tn,showAutorunsProgressMode:Jt,showAutorunsCommentsMode:Gn,showAssistantConnectionMode:Ut,showAssistantPromptMode:pn,showAssistantChatMode:In,showAssistantCommentsMode:Ln,showAssistantSamMode:en,showDecompositionConnectionMode:Bt,showDecompositionPromptMode:Be,showDecompositionQueryMode:gn,showDecompositionOutputMode:tn,showDecompositionMetricsMode:Ct,showDecompositionHistoryMode:rn,showDecompositionRuntimeMode:vt,prompts:m})),window.dispatchEvent(new CustomEvent(pm)),J("UI layout and prompts saved.")}async function ut(){te(!0),ee("");try{const d=await Ce.testConnection(i);d.provider==="local"?d.model_found===!0?(Ae(`LOCAL OK - ${d.model}`),J(`Local model is available: ${d.model} (catalog size=${d.models_count??"n/a"}).`)):d.model_found===!1?(Ae(`LOCAL OK, model not loaded - ${d.model}`),J(`Local server is reachable, but model '${d.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(Ae(`LOCAL OK (model list unavailable) - ${d.model}`),J("Local server is reachable, but model catalog could not be verified.")):(Ae(`OPENAI OK - ${d.model}`),J(`OpenAI connection ok: ${d.model}`))}catch(d){const P=d instanceof Error?d.message:String(d);Ae("Connection error"),ee(`Test connection: ${P}`),J(`Test connection error: ${P}`)}finally{te(!1)}}async function yr(){q(!0);try{const P=(await Ce.listModels(i)).models??[];Se(P),P.length>0&&p(k=>k.model&&P.includes(k.model)?k:{...k,model:P[0]}),J(`Model catalog loaded (${i.llmProvider}): ${P.length} items.`)}catch(d){const P=d instanceof Error?d.message:String(d);J(`Load model list error: ${P}`)}finally{q(!1)}}x.useEffect(()=>{Se([])},[i.llmProvider,i.baseUrl]);async function Fn(d){te(!0),ee("");try{const P=await Ce.normalize({connection:i,prompts:m,promptVersion:"normalizer_v2_0_2",query:{userQuestion:j.userQuestion,periodHint:j.periodHint,businessContext:j.businessContext,expectedRoute:j.expectedRoute},saveAsTestCase:d,useMock:Re});Y(P),oe("normalized"),J(`Normalize done: trace=${P.trace_id}, validation=${P.validation.passed?"passed":"failed"}`),$n()}catch(P){const k=P instanceof Error?P.message:String(P);ee(`Normalize: ${k}`),J(`Normalize error: ${k}`)}finally{te(!1)}}function le(){const d=De.find(P=>P.id===We);if(!d){J("Preset is not selected.");return}Te(m),R({systemPrompt:d.systemPrompt,developerPrompt:d.developerPrompt,domainPrompt:d.domainPrompt,schemaNotes:d.schemaNotes??"",fewShotExamples:d.fewShotExamples??""}),J(`Preset loaded: ${d.name}`)}async function Un(){try{await Ce.savePreset({name:Ze||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:m.systemPrompt,developerPrompt:m.developerPrompt,domainPrompt:m.domainPrompt,schemaNotes:m.schemaNotes,fewShotExamples:m.fewShotExamples}),J("Preset saved."),await Yr()}catch(d){J(`Preset save error: ${d instanceof Error?d.message:String(d)}`)}}function Mt(){R(Ic),J("Prompt panel reset to defaults.")}function ct(){const d=ym(m,ie);fe(d),J(d)}function ks(){const d=j.batchQuestionsRaw.split(";").map(P=>P.trim()).filter(Boolean).join(` - -`);d&&(T(P=>({...P,batchQuestionsRaw:d})),J("Batch field formatted: `;` converted to blank-line separators."))}async function St(d){try{const k=(await Ce.loadTrace(d)).trace,ye=k.parsed_normalized_json??null;Y({trace_id:String(k.trace_id??d),ok:!!k.validation_result?.passed,normalized:ye,route_hint_summary:k.route_hint_summary??(ye?{route_hint:ye.route_hint??null,confidence:ye.confidence?.route_hint??null}:null),raw_model_output:k.raw_model_response??{},validation:k.validation_result??{passed:!1,errors:["validation not found"]},usage:k.usage??{input_tokens:0,output_tokens:0,total_tokens:0},latency_ms:Number(k.latency_ms??0),prompt_version:String(k.prompt_version??"unknown"),schema_version:String(k.schema_version??"unknown")}),oe("raw"),ee(""),J(`Trace opened: ${d}`)}catch(P){const k=P instanceof Error?P.message:String(P);ee(`Trace: ${k}`),J(`Trace open error ${d}: ${k}`)}}async function Cs(){try{const d=await Ce.startRun();h(d.run.runId),J(`Run started: ${d.run.runId}`),J("Tip: start run does not execute normalize by itself. Use 'Run eval v2.0.2' button."),await xn()}catch(d){J(`Run start error: ${d instanceof Error?d.message:String(d)}`)}}async function Zr(){if(O)try{await Ce.finishRun(O),J(`Run finished: ${O}`),await xn()}catch(d){J(`Run finish error: ${d instanceof Error?d.message:String(d)}`)}}async function es(){ce(!0),ee("");try{J("Starting eval in v2 contour.");const d=j.batchQuestionsRaw.trim()||j.userQuestion.trim();if(!d)throw new Error("Fill batch field or Raw user question first.");const P=await Ce.runEval({connection:i,prompts:m,promptVersion:"normalizer_v2_0_2",mode:"single-pass-strict",rawQuestions:d,useMock:Re});xe(P.report),J("Eval v2.0.2 run finished.");const k=P.report;if(k.run_id&&J(`Eval run id: ${k.run_id}`),k.metrics){const ye=k.metrics;J(`Eval metrics v2.0.2: schema=${ye.schema_validation_pass_rate??"n/a"}%, route_accuracy=${ye.route_resolution_accuracy??"n/a"}%, no_route_precision=${ye.no_route_precision??"n/a"}%, state_consistency=${ye.execution_state_consistency_rate??"n/a"}%`)}await $n()}catch(d){const P=d instanceof Error?d.message:String(d);P.includes("Legacy eval runner supports normalized_query_v1 only")?(xe({status:"plan_only",prompt_version:"normalizer_v2",reason:"backend eval runner is still legacy-v1 only",plan_file:"reports/v2_pilot_eval_plan.md",next_steps:["run cheap mock sanity for schema/fragment/scope","run small real batch (10-15 messages, temperature=0)","run challenge-30 replay with v2 metrics"]}),J("Backend is legacy-only for eval right now. Showing v2 pilot plan.")):(ee(`Eval: ${P}`),J(`Eval run error: ${P}`))}finally{ce(!1)}}async function Xn(){try{const d=JSON.stringify(de??{},null,2);await navigator.clipboard.writeText(d),J("Eval report copied to clipboard.")}catch(d){J(`Eval report copy error: ${d instanceof Error?d.message:String(d)}`)}}const Bn=x.useMemo(()=>{const d=new Map;for(const P of ot)P.message_id&&d.set(P.message_id,P);return d},[ot]),At=we.messageIndex>=0?yn[we.messageIndex]??null:null,wt=x.useMemo(()=>{if(we.messageIndex<0)return null;for(let d=we.messageIndex-1;d>=0;d-=1){const P=yn[d];if(P?.role==="user")return P}return null},[we.messageIndex,yn]);async function xr(d){if(!d.trim()){ve([]);return}Pt(!0);try{const P=await Ce.loadAssistantAnnotations({session_id:d,limit:400});ve(P.items??[])}catch(P){const k=P instanceof Error?P.message:String(P);J(`Assistant annotations load error: ${k}`)}finally{Pt(!1)}}function dt(d){lt(P=>P.saving&&!d?.force?P:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:Gi,saving:!1,error:""})}function zr(d,P){if(d.role!=="assistant")return;const k=Ke.trim(),ye=String(d.session_id??"").trim();if(!(k||ye)){ue("Сначала получите ответ ассистента в активной сессии.");return}!k&&ye&&hr(ye);const Hn=Bn.get(d.message_id)??null;lt({open:!0,messageIndex:P,rating:Hn?.rating??3,comment:Hn?.comment??"",annotationAuthor:Hn?.annotation_author??Gi,saving:!1,error:""})}function bn(d){return d.role==="assistant"}function Tt(d){return d.role==="assistant"&&Bn.has(d.message_id)}async function Ht(){if(!Ke.trim()){lt(d=>({...d,error:"Сессия ассистента не найдена."}));return}if(!(we.messageIndex<0)){if(!we.comment.trim()){lt(d=>({...d,error:"Добавьте комментарий."}));return}lt(d=>({...d,saving:!0,error:""}));try{const d=await Ce.saveAssistantAnnotation({session_id:Ke,message_index:we.messageIndex,rating:we.rating,comment:we.comment.trim(),annotation_author:we.annotationAuthor.trim()||void 0});ve(P=>{const k=[...P],ye=k.findIndex(er=>er.annotation_id===d.annotation.annotation_id);return ye>=0?k[ye]=d.annotation:k.unshift(d.annotation),k.sort((er,Hn)=>Date.parse(Hn.updated_at)-Date.parse(er.updated_at))}),dt({force:!0})}catch(d){const P=d instanceof Error?d.message:String(d);lt(k=>({...k,saving:!1,error:P}))}}}function Vt(){hr(""),gr([]),vr(""),Yn(null),Et(""),ue(""),ve([]),dt({force:!0}),J("Assistant session reset.")}async function Zn(){const d=xm(sn,Nt);if(!d)return;Jr(!0),ue(""),vr(""),gr(k=>[...k,{message_id:`local-${Date.now()}`,session_id:Ke||"pending",role:"user",text:d,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const P=Ne();try{const k=await Ce.sendAssistantMessage({connection:i,prompts:m,userMessage:d,sessionId:Ke||void 0,promptVersion:zc,useMock:Re});hr(k.session_id),gr(k.conversation),Et("Ответ готов"),await xr(k.session_id),J(`Assistant reply received: trace=${k.debug.trace_id}`)}catch(k){const ye=k instanceof Error?k.message:String(k);ue(ye),Et("Ошибка ассистента"),J(`Assistant error: ${ye}`)}finally{P(),Jr(!1)}}return x.useEffect(()=>{if(!Ke.trim()){ve([]);return}xr(Ke)},[Ke]),x.useEffect(()=>{if(!O){G([]);return}Ce.runTrace(O).then(d=>G(d.items)).catch(d=>J(`Run trace error: ${d instanceof Error?d.message:String(d)}`))},[O]),o.jsxs("main",{className:`app-root ${ke==="assistant"||ke==="decomposition"||ke==="autoruns"?"app-root-autoruns":""}`,children:[o.jsxs("header",{className:"app-topbar",children:[o.jsxs("div",{className:"mode-switch-row",children:[o.jsx("button",{type:"button",className:ke==="assistant"?"tab active":"tab",onClick:()=>Ft("assistant"),children:"Ассистент"}),o.jsx("button",{type:"button",className:ke==="decomposition"?"tab active":"tab",onClick:()=>Ft("decomposition"),children:"Декомпозиция"}),o.jsx("button",{type:"button",className:ke==="autoruns"?"tab active":"tab",onClick:()=>Ft("autoruns"),children:"История автопрогонов"}),o.jsx("button",{type:"button",className:"tab",onClick:Xr,children:"Сохранить"})]}),ke==="assistant"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:Ut?"tab active":"tab",onClick:()=>Xt(d=>!d),children:"LLM Connector"}),o.jsx("button",{type:"button",className:pn?"tab active":"tab",onClick:()=>fr(d=>!d),children:"Prompt Manager"}),o.jsx("button",{type:"button",className:In?"tab active":"tab",onClick:()=>mr(d=>!d),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:Ln?"tab active":"tab",onClick:()=>Zt(d=>!d),children:"Комментарии ассистента"}),o.jsx("button",{type:"button",className:en?"tab active":"tab",onClick:()=>pr(d=>!d),children:"SAM"})]}):ke==="decomposition"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:Bt?"tab active":"tab",onClick:()=>hn(d=>!d),children:"LLM"}),o.jsx("button",{type:"button",className:Be?"tab active":"tab",onClick:()=>st(d=>!d),children:"Prompt"}),o.jsx("button",{type:"button",className:gn?"tab active":"tab",onClick:()=>vn(d=>!d),children:"Запрос"}),o.jsx("button",{type:"button",className:tn?"tab active":"tab",onClick:()=>nn(d=>!d),children:"Выход"}),o.jsx("button",{type:"button",className:Ct?"tab active":"tab",onClick:()=>Dn(d=>!d),children:"Метрики"}),o.jsx("button",{type:"button",className:rn?"tab active":"tab",onClick:()=>bt(d=>!d),children:"История"}),o.jsx("button",{type:"button",className:vt?"tab active":"tab",onClick:()=>Jn(d=>!d),children:"NDC Run Monitor"})]}):ke==="autoruns"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:qn?"tab active":"tab",onClick:()=>An(d=>!d),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:Tn?"tab active":"tab",onClick:()=>dr(d=>!d),children:"Режим декомпозиции"}),o.jsx("button",{type:"button",className:Jt?"tab active":"tab",onClick:()=>Yt(d=>!d),children:"Прогресс/регресс"}),o.jsx("button",{type:"button",className:Gn?"tab active":"tab",onClick:()=>mn(d=>!d),children:"Комментарии"})]}):null]}),ke==="assistant"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[Ut?o.jsx("div",{className:"mode-col",children:o.jsx(Ac,{value:i,modelOptions:re,modelsBusy:se,onChange:p,onReloadModels:yr,onSaveLocalConfig:Ie,onTestConnection:ut,lastStatus:Pe,busy:Me||yt})}):null,pn?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(Tc,{value:m,onChange:R,presets:De,selectedPresetId:We,onSelectPreset:Ge,onLoadPreset:le,onSavePreset:Un,onResetDefaults:Mt,onDiffPrevious:ct,presetName:Ze,onPresetNameChange:rt,diffSummary:Fe})}):null,In?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(Fc,{sessionId:Ke,conversation:yn,inputValue:sn,onInputChange:vr,selectedContextChip:Nt,onSelectContextChip:Yn,onClearContextChip:()=>Yn(null),useMock:Re,onUseMockChange:me,onSend:Zn,onClear:Vt,busy:yt,statusText:xt,errorMessage:zn,showCommentAction:!0,onCommentAssistantMessage:zr,isAssistantMessageCommented:Tt,canCommentAssistantMessage:bn})}):null,Ln?o.jsx("div",{className:"mode-col",children:o.jsx(Mn,{className:"assistant-comments-frame",title:"Комментарии ассистента",children:o.jsxs("div",{className:"assistant-comments-shell",children:[o.jsxs("div",{className:"assistant-comments-toolbar",children:[o.jsx("span",{className:"muted",children:Ke?`session: ${Ke}`:"Сессия не запущена"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{xr(Ke)},disabled:!Ke||_t,children:_t?"Обновляю...":"Обновить"})]}),o.jsxs("div",{className:"assistant-comments-list",children:[Ke?null:o.jsx("p",{className:"muted",children:"Появится после первого ответа ассистента."}),Ke&&ot.length===0&&!_t?o.jsx("p",{className:"muted",children:"Комментариев по этой сессии пока нет."}):null,ot.map(d=>o.jsxs("article",{className:"assistant-comment-item",children:[o.jsxs("div",{className:"assistant-comment-head",children:[o.jsx("strong",{children:`${"●".repeat(Math.max(1,Math.min(5,Math.round(d.rating))))}${"○".repeat(Math.max(0,5-Math.round(d.rating)))}`}),o.jsx("span",{children:new Date(d.updated_at).toLocaleString("ru-RU")})]}),d.context.question_text?o.jsxs("p",{children:["Q: ",d.context.question_text]}):null,d.context.answer_text?o.jsxs("p",{children:["A: ",d.context.answer_text]}):null,o.jsx("p",{children:d.comment}),o.jsxs("div",{className:"assistant-comment-meta",children:[d.context.trace_id?o.jsx("span",{children:`trace=${d.context.trace_id}`}):null,d.context.reply_type?o.jsx("span",{children:`reply_type=${d.context.reply_type}`}):null]})]},d.annotation_id))]})]})})}):null,en?o.jsx("div",{className:"mode-col",children:o.jsx(Af,{sessionId:Ke,conversation:yn,statusText:xt,errorMessage:zn,useMock:Re,appLogs:W})}):null,!Ut&&!pn&&!In&&!Ln&&!en?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима ассистента скрыты. Включите нужные блоки справа в шапке."}):null]})}):ke==="decomposition"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[Bt?o.jsx("div",{className:"mode-col",children:o.jsx(Ac,{value:i,modelOptions:re,modelsBusy:se,onChange:p,onReloadModels:yr,onSaveLocalConfig:Ie,onTestConnection:ut,lastStatus:Pe,busy:Me})}):null,Be?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(Tc,{value:m,onChange:R,presets:De,selectedPresetId:We,onSelectPreset:Ge,onLoadPreset:le,onSavePreset:Un,onResetDefaults:Mt,onDiffPrevious:ct,presetName:Ze,onPresetNameChange:rt,diffSummary:Fe})}):null,gn?o.jsx("div",{className:"mode-col",children:o.jsx(cm,{value:j,onChange:T,onApplyBatchFormat:ks,onNormalize:Fn,busy:Me,useMock:Re,onUseMockChange:me,errorMessage:ge})}):null,tn?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(um,{tab:U,onTabChange:oe,result:$,appLogs:W})}):null,Ct?o.jsx("div",{className:"mode-col",children:o.jsx(lm,{result:$})}):null,rn?o.jsx("div",{className:"mode-col",children:o.jsx(om,{items:F,onRefresh:$n,onOpenTrace:St})}):null,vt?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(dm,{runs:D,selectedRunId:O,onSelectRun:h,onStartRun:Cs,onFinishRun:Zr,onRefreshRuns:xn,onRunEval:es,onCopyEvalReport:Xn,evalBusy:ae,traceItems:C,evalReport:de})}):null,!Bt&&!Be&&!gn&&!tn&&!Ct&&!rn&&!vt?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима декомпозиции скрыты. Включите нужные блоки справа в шапке."}):null]})}):o.jsx("div",{className:"layout-grid layout-grid-autoruns",children:o.jsx(sm,{connection:i,prompts:m,assistantPromptVersion:zc,decompositionPromptVersion:qi,showAssistantMode:qn,showDecompositionMode:Tn,showProgressMode:Jt,showCommentsMode:Gn,onLog:J})}),we.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:d=>{d.target===d.currentTarget&&dt()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Эта разметка хранится отдельно от комментариев автопрогонов."}),wt?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:wt.text})]}):null,At?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:At.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(d=>o.jsx("button",{type:"button",className:we.rating>=d?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>lt(P=>({...P,rating:d})),disabled:we.saving,"aria-label":`Оценка ${d}`,children:we.rating>=d?"●":"○"},d))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:we.annotationAuthor,onChange:d=>lt(P=>({...P,annotationAuthor:d.target.value})),placeholder:"manual_reviewer",disabled:we.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:we.comment,onChange:d=>lt(P=>({...P,comment:d.target.value})),placeholder:"Что именно не так в ответе и что проверить.",rows:4,disabled:we.saving})]}),we.error?o.jsx("p",{className:"error-text",children:we.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{Ht()},disabled:we.saving,children:we.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>dt(),disabled:we.saving,children:"Отмена"})]})]})}):null]})}Pf.createRoot(document.getElementById("root")).render(o.jsx(Sf.StrictMode,{children:o.jsx(_m,{})})); diff --git a/llm_normalizer/frontend/dist/assets/index-Qq5WpuqR.js b/llm_normalizer/frontend/dist/assets/index-Qq5WpuqR.js new file mode 100644 index 0000000..5b8b117 --- /dev/null +++ b/llm_normalizer/frontend/dist/assets/index-Qq5WpuqR.js @@ -0,0 +1,26 @@ +(function(){const m=document.createElement("link").relList;if(m&&m.supports&&m.supports("modulepreload"))return;for(const j of document.querySelectorAll('link[rel="modulepreload"]'))N(j);new MutationObserver(j=>{for(const T of j)if(T.type==="childList")for(const F of T.addedNodes)F.tagName==="LINK"&&F.rel==="modulepreload"&&N(F)}).observe(document,{childList:!0,subtree:!0});function f(j){const T={};return j.integrity&&(T.integrity=j.integrity),j.referrerPolicy&&(T.referrerPolicy=j.referrerPolicy),j.crossOrigin==="use-credentials"?T.credentials="include":j.crossOrigin==="anonymous"?T.credentials="omit":T.credentials="same-origin",T}function N(j){if(j.ep)return;j.ep=!0;const T=f(j);fetch(j.href,T)}})();function bc(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Fi={exports:{}},no={},Ui={exports:{}},ge={};var gc;function wf(){if(gc)return ge;gc=1;var i=Symbol.for("react.element"),m=Symbol.for("react.portal"),f=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),j=Symbol.for("react.profiler"),T=Symbol.for("react.provider"),F=Symbol.for("react.context"),Y=Symbol.for("react.forward_ref"),U=Symbol.for("react.suspense"),I=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),D=Symbol.iterator;function B(h){return h===null||typeof h!="object"?null:(h=D&&h[D]||h["@@iterator"],typeof h=="function"?h:null)}var oe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ae=Object.assign,se={};function te(h,k,J){this.props=h,this.context=k,this.refs=se,this.updater=J||oe}te.prototype.isReactComponent={},te.prototype.setState=function(h,k){if(typeof h!="object"&&typeof h!="function"&&h!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,h,k,"setState")},te.prototype.forceUpdate=function(h){this.updater.enqueueForceUpdate(this,h,"forceUpdate")};function Te(){}Te.prototype=te.prototype;function ve(h,k,J){this.props=h,this.context=k,this.refs=se,this.updater=J||oe}var G=ve.prototype=new Te;G.constructor=ve,Ae(G,te.prototype),G.isPureReactComponent=!0;var ae=Array.isArray,_e=Object.prototype.hasOwnProperty,Oe={current:null},$e={key:!0,ref:!0,__self:!0,__source:!0};function We(h,k,J){var ue,de={},fe=null,Se=null;if(k!=null)for(ue in k.ref!==void 0&&(Se=k.ref),k.key!==void 0&&(fe=""+k.key),k)_e.call(k,ue)&&!$e.hasOwnProperty(ue)&&(de[ue]=k[ue]);var ye=arguments.length-2;if(ye===1)de.children=J;else if(1>>1,k=O[h];if(0>>1;hj(de,$))fej(Se,de)?(O[h]=Se,O[fe]=$,h=fe):(O[h]=de,O[ue]=$,h=ue);else if(fej(Se,$))O[h]=Se,O[fe]=$,h=fe;else break e}}return W}function j(O,W){var $=O.sortIndex-W.sortIndex;return $!==0?$:O.id-W.id}if(typeof performance=="object"&&typeof performance.now=="function"){var T=performance;i.unstable_now=function(){return T.now()}}else{var F=Date,Y=F.now();i.unstable_now=function(){return F.now()-Y}}var U=[],I=[],q=1,D=null,B=3,oe=!1,Ae=!1,se=!1,te=typeof setTimeout=="function"?setTimeout:null,Te=typeof clearTimeout=="function"?clearTimeout:null,ve=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(O){for(var W=f(I);W!==null;){if(W.callback===null)N(I);else if(W.startTime<=O)N(I),W.sortIndex=W.expirationTime,m(U,W);else break;W=f(I)}}function ae(O){if(se=!1,G(O),!Ae)if(f(U)!==null)Ae=!0,Re(_e);else{var W=f(I);W!==null&&pe(ae,W.startTime-O)}}function _e(O,W){Ae=!1,se&&(se=!1,Te(We),We=-1),oe=!0;var $=B;try{for(G(W),D=f(U);D!==null&&(!(D.expirationTime>W)||O&&!st());){var h=D.callback;if(typeof h=="function"){D.callback=null,B=D.priorityLevel;var k=h(D.expirationTime<=W);W=i.unstable_now(),typeof k=="function"?D.callback=k:D===f(U)&&N(U),G(W)}else N(U);D=f(U)}if(D!==null)var J=!0;else{var ue=f(I);ue!==null&&pe(ae,ue.startTime-W),J=!1}return J}finally{D=null,B=$,oe=!1}}var Oe=!1,$e=null,We=-1,Je=5,et=-1;function st(){return!(i.unstable_now()-etO||125h?(O.sortIndex=$,m(I,O),f(U)===null&&O===f(I)&&(se?(Te(We),We=-1):se=!0,pe(ae,$-h))):(O.sortIndex=k,m(U,O),Ae||oe||(Ae=!0,Re(_e))),O},i.unstable_shouldYield=st,i.unstable_wrapCallback=function(O){var W=B;return function(){var $=B;B=W;try{return O.apply(this,arguments)}finally{B=$}}}})(Hi)),Hi}var Sc;function Ef(){return Sc||(Sc=1,Bi.exports=Nf()),Bi.exports}var wc;function Pf(){if(wc)return Ft;wc=1;var i=Zi(),m=Ef();function f(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),U=Object.prototype.hasOwnProperty,I=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,q={},D={};function B(e){return U.call(D,e)?!0:U.call(q,e)?!1:I.test(e)?D[e]=!0:(q[e]=!0,!1)}function oe(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ae(e,t,n,r){if(t===null||typeof t>"u"||oe(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function se(e,t,n,r,s,l,u){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=u}var te={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){te[e]=new se(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];te[t]=new se(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){te[e]=new se(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){te[e]=new se(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){te[e]=new se(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){te[e]=new se(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){te[e]=new se(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){te[e]=new se(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){te[e]=new se(e,5,!1,e.toLowerCase(),null,!1,!1)});var Te=/[\-:]([a-z])/g;function ve(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Te,ve);te[t]=new se(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Te,ve);te[t]=new se(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Te,ve);te[t]=new se(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){te[e]=new se(e,1,!1,e.toLowerCase(),null,!1,!1)}),te.xlinkHref=new se("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){te[e]=new se(e,1,!1,e.toLowerCase(),null,!0,!0)});function G(e,t,n,r){var s=te.hasOwnProperty(t)?te[t]:null;(s!==null?s.type!==0:r||!(2d||s[u]!==l[d]){var g=` +`+s[u].replace(" at new "," at ");return e.displayName&&g.includes("")&&(g=g.replace("",e.displayName)),g}while(1<=u&&0<=d);break}}}finally{J=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?k(e):""}function de(e){switch(e.tag){case 5:return k(e.type);case 16:return k("Lazy");case 13:return k("Suspense");case 19:return k("SuspenseList");case 0:case 2:case 15:return e=ue(e.type,!1),e;case 11:return e=ue(e.type.render,!1),e;case 1:return e=ue(e.type,!0),e;default:return""}}function fe(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case $e:return"Fragment";case Oe:return"Portal";case Je:return"Profiler";case We:return"StrictMode";case Ie:return"Suspense";case Fe:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case st:return(e.displayName||"Context")+".Consumer";case et:return(e._context.displayName||"Context")+".Provider";case ie:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case me:return t=e.displayName||null,t!==null?t:fe(e.type)||"Memo";case Re:t=e._payload,e=e._init;try{return fe(e(t))}catch{}}return null}function Se(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return fe(t);case 8:return t===We?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ye(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ee(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Pe(e){var t=ee(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,l=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(u){r=""+u,l.call(this,u)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(u){r=""+u},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ut(e){e._valueTracker||(e._valueTracker=Pe(e))}function Kn(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ee(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function In(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Ln(e,t){var n=t.checked;return $({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function fr(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ye(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Xt(e,t){t=t.checked,t!=null&&G(e,"checked",t,!1)}function Zt(e,t){Xt(e,t);var n=ye(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?hn(e,t.type,n):t.hasOwnProperty("defaultValue")&&hn(e,t.type,ye(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Gn(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function hn(e,t,n){(t!=="number"||In(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var bt=Array.isArray;function en(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=nn.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Bt(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},be=["Webkit","ms","Moz","O"];Object.keys(vn).forEach(function(e){be.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vn[t]=vn[e]})});function ot(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vn.hasOwnProperty(e)&&vn[e]?(""+t).trim():t+"px"}function yn(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=ot(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var xn=$({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function rn(e,t){if(t){if(xn[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(f(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(f(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(f(61))}if(t.style!=null&&typeof t.style!="object")throw Error(f(62))}}function sn(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Nt=null;function zn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var on=null,Ht=null,gt=null;function Jn(e){if(e=bs(e)){if(typeof on!="function")throw Error(f(280));var t=e.stateNode;t&&(t=yo(t),on(e.stateNode,e.type,t))}}function qe(e){Ht?gt?gt.push(e):gt=[e]:Ht=e}function gr(){if(Ht){var e=Ht,t=gt;if(gt=Ht=null,Jn(e),t)for(e=0;e>>=0,e===0?32:31-(Ns(e)/ts|0)|0}var Zn=64,er=4194304;function Tt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function wt(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,l=e.pingedLanes,u=n&268435455;if(u!==0){var d=u&~s;d!==0?r=Tt(d):(l&=u,l!==0&&(r=Tt(l)))}else u=n&~s,u!==0?r=Tt(u):l!==0&&(r=Tt(l));if(r===0)return 0;if(t!==0&&t!==r&&(t&s)===0&&(s=r&-r,l=t&-t,s>=l||s===16&&(l&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Qt(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-St(t),e[t]=n}function Wt(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Ts),ua=" ",ca=!1;function da(e,t){switch(e){case"keyup":return gd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fa(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var os=!1;function yd(e,t){switch(e){case"compositionend":return fa(t);case"keypress":return t.which!==32?null:(ca=!0,ua);case"textInput":return e=t.data,e===ua&&ca?null:e;default:return null}}function xd(e,t){if(os)return e==="compositionend"||!xl&&da(e,t)?(e=ra(),lo=ml=wr=null,os=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=xa(n)}}function Sa(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Sa(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function wa(){for(var e=window,t=In();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=In(e.document)}return t}function wl(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Pd(e){var t=wa(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Sa(n.ownerDocument.documentElement,n)){if(r!==null&&wl(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,l=Math.min(r.start,s);r=r.end===void 0?l:Math.min(r.end,s),!e.extend&&l>r&&(s=r,r=l,l=s),s=_a(n,l);var u=_a(n,r);s&&u&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),l>r?(e.addRange(t),e.extend(u.node,u.offset)):(t.setEnd(u.node,u.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ls=null,jl=null,Ds=null,kl=!1;function ja(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;kl||ls==null||ls!==In(r)||(r=ls,"selectionStart"in r&&wl(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ds&&Os(Ds,r)||(Ds=r,r=ho(jl,"onSelect"),0ds||(e.current=Dl[ds],Dl[ds]=null,ds--)}function Le(e,t){ds++,Dl[ds]=e.current,e.current=t}var Nr={},dt=Cr(Nr),Lt=Cr(!1),Br=Nr;function fs(e,t){var n=e.type.contextTypes;if(!n)return Nr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},l;for(l in n)s[l]=t[l];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Ot(e){return e=e.childContextTypes,e!=null}function xo(){ze(Lt),ze(dt)}function $a(e,t,n){if(dt.current!==Nr)throw Error(f(168));Le(dt,t),Le(Lt,n)}function Fa(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(f(108,Se(e)||"Unknown",s));return $({},n,r)}function _o(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Nr,Br=dt.current,Le(dt,e),Le(Lt,Lt.current),!0}function Ua(e,t,n){var r=e.stateNode;if(!r)throw Error(f(169));n?(e=Fa(e,t,Br),r.__reactInternalMemoizedMergedChildContext=e,ze(Lt),ze(dt),Le(dt,e)):ze(Lt),Le(Lt,n)}var rr=null,So=!1,zl=!1;function ba(e){rr===null?rr=[e]:rr.push(e)}function Ud(e){So=!0,ba(e)}function Er(){if(!zl&&rr!==null){zl=!0;var e=0,t=we;try{var n=rr;for(we=1;e>=u,s-=u,sr=1<<32-St(t)+s|n<re?(rt=Z,Z=null):rt=Z.sibling;var Ne=P(_,Z,S[re],L);if(Ne===null){Z===null&&(Z=rt);break}e&&Z&&Ne.alternate===null&&t(_,Z),v=l(Ne,v,re),X===null?K=Ne:X.sibling=Ne,X=Ne,Z=rt}if(re===S.length)return n(_,Z),Ue&&Vr(_,re),K;if(Z===null){for(;rere?(rt=Z,Z=null):rt=Z.sibling;var Dr=P(_,Z,Ne.value,L);if(Dr===null){Z===null&&(Z=rt);break}e&&Z&&Dr.alternate===null&&t(_,Z),v=l(Dr,v,re),X===null?K=Dr:X.sibling=Dr,X=Dr,Z=rt}if(Ne.done)return n(_,Z),Ue&&Vr(_,re),K;if(Z===null){for(;!Ne.done;re++,Ne=S.next())Ne=R(_,Ne.value,L),Ne!==null&&(v=l(Ne,v,re),X===null?K=Ne:X.sibling=Ne,X=Ne);return Ue&&Vr(_,re),K}for(Z=r(_,Z);!Ne.done;re++,Ne=S.next())Ne=b(Z,_,re,Ne.value,L),Ne!==null&&(e&&Ne.alternate!==null&&Z.delete(Ne.key===null?re:Ne.key),v=l(Ne,v,re),X===null?K=Ne:X.sibling=Ne,X=Ne);return e&&Z.forEach(function(Sf){return t(_,Sf)}),Ue&&Vr(_,re),K}function Ge(_,v,S,L){if(typeof S=="object"&&S!==null&&S.type===$e&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case _e:e:{for(var K=S.key,X=v;X!==null;){if(X.key===K){if(K=S.type,K===$e){if(X.tag===7){n(_,X.sibling),v=s(X,S.props.children),v.return=_,_=v;break e}}else if(X.elementType===K||typeof K=="object"&&K!==null&&K.$$typeof===Re&&qa(K)===X.type){n(_,X.sibling),v=s(X,S.props),v.ref=Bs(_,X,S),v.return=_,_=v;break e}n(_,X);break}else t(_,X);X=X.sibling}S.type===$e?(v=Xr(S.props.children,_.mode,L,S.key),v.return=_,_=v):(L=Go(S.type,S.key,S.props,null,_.mode,L),L.ref=Bs(_,v,S),L.return=_,_=L)}return u(_);case Oe:e:{for(X=S.key;v!==null;){if(v.key===X)if(v.tag===4&&v.stateNode.containerInfo===S.containerInfo&&v.stateNode.implementation===S.implementation){n(_,v.sibling),v=s(v,S.children||[]),v.return=_,_=v;break e}else{n(_,v);break}else t(_,v);v=v.sibling}v=Li(S,_.mode,L),v.return=_,_=v}return u(_);case Re:return X=S._init,Ge(_,v,X(S._payload),L)}if(bt(S))return V(_,v,S,L);if(W(S))return Q(_,v,S,L);Co(_,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,v!==null&&v.tag===6?(n(_,v.sibling),v=s(v,S),v.return=_,_=v):(n(_,v),v=Ii(S,_.mode,L),v.return=_,_=v),u(_)):n(_,v)}return Ge}var gs=Ka(!0),Ga=Ka(!1),No=Cr(null),Eo=null,vs=null,Hl=null;function Vl(){Hl=vs=Eo=null}function Ql(e){var t=No.current;ze(No),e._currentValue=t}function Wl(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ys(e,t){Eo=e,Hl=vs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Dt=!0),e.firstContext=null)}function dn(e){var t=e._currentValue;if(Hl!==e)if(e={context:e,memoizedValue:t,next:null},vs===null){if(Eo===null)throw Error(f(308));vs=e,Eo.dependencies={lanes:0,firstContext:e}}else vs=vs.next=e;return t}var Qr=null;function ql(e){Qr===null?Qr=[e]:Qr.push(e)}function Ja(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,ql(t)):(n.next=s.next,s.next=n),t.interleaved=n,lr(e,r)}function lr(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Pr=!1;function Kl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ya(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ir(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Mr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(je&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,lr(e,n)}return s=r.interleaved,s===null?(t.next=t,ql(r)):(t.next=s.next,s.next=t),r.interleaved=t,lr(e,n)}function Po(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,tr(e,n)}}function Xa(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,l=null;if(n=n.firstBaseUpdate,n!==null){do{var u={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};l===null?s=l=u:l=l.next=u,n=n.next}while(n!==null);l===null?s=l=t:l=l.next=t}else s=l=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:l,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Mo(e,t,n,r){var s=e.updateQueue;Pr=!1;var l=s.firstBaseUpdate,u=s.lastBaseUpdate,d=s.shared.pending;if(d!==null){s.shared.pending=null;var g=d,w=g.next;g.next=null,u===null?l=w:u.next=w,u=g;var M=e.alternate;M!==null&&(M=M.updateQueue,d=M.lastBaseUpdate,d!==u&&(d===null?M.firstBaseUpdate=w:d.next=w,M.lastBaseUpdate=g))}if(l!==null){var R=s.baseState;u=0,M=w=g=null,d=l;do{var P=d.lane,b=d.eventTime;if((r&P)===P){M!==null&&(M=M.next={eventTime:b,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var V=e,Q=d;switch(P=t,b=n,Q.tag){case 1:if(V=Q.payload,typeof V=="function"){R=V.call(b,R,P);break e}R=V;break e;case 3:V.flags=V.flags&-65537|128;case 0:if(V=Q.payload,P=typeof V=="function"?V.call(b,R,P):V,P==null)break e;R=$({},R,P);break e;case 2:Pr=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,P=s.effects,P===null?s.effects=[d]:P.push(d))}else b={eventTime:b,lane:P,tag:d.tag,payload:d.payload,callback:d.callback,next:null},M===null?(w=M=b,g=R):M=M.next=b,u|=P;if(d=d.next,d===null){if(d=s.shared.pending,d===null)break;P=d,d=P.next,P.next=null,s.lastBaseUpdate=P,s.shared.pending=null}}while(!0);if(M===null&&(g=R),s.baseState=g,s.firstBaseUpdate=w,s.lastBaseUpdate=M,t=s.shared.interleaved,t!==null){s=t;do u|=s.lane,s=s.next;while(s!==t)}else l===null&&(s.shared.lanes=0);Kr|=u,e.lanes=u,e.memoizedState=R}}function Za(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Zl.transition;Zl.transition={};try{e(!1),t()}finally{we=n,Zl.transition=r}}function yu(){return fn().memoizedState}function Vd(e,t,n){var r=Ir(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},xu(e))_u(t,n);else if(n=Ja(e,t,n,r),n!==null){var s=Ct();An(n,e,r,s),Su(n,t,r)}}function Qd(e,t,n){var r=Ir(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(xu(e))_u(t,s);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var u=t.lastRenderedState,d=l(u,n);if(s.hasEagerState=!0,s.eagerState=d,Nn(d,u)){var g=t.interleaved;g===null?(s.next=s,ql(t)):(s.next=g.next,g.next=s),t.interleaved=s;return}}catch{}n=Ja(e,t,s,r),n!==null&&(s=Ct(),An(n,e,r,s),Su(n,t,r))}}function xu(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function _u(e,t){Ws=To=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Su(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,tr(e,n)}}var Oo={readContext:dn,useCallback:ft,useContext:ft,useEffect:ft,useImperativeHandle:ft,useInsertionEffect:ft,useLayoutEffect:ft,useMemo:ft,useReducer:ft,useRef:ft,useState:ft,useDebugValue:ft,useDeferredValue:ft,useTransition:ft,useMutableSource:ft,useSyncExternalStore:ft,useId:ft,unstable_isNewReconciler:!1},Wd={readContext:dn,useCallback:function(e,t){return Wn().memoizedState=[e,t===void 0?null:t],e},useContext:dn,useEffect:cu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Io(4194308,4,mu.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Io(4194308,4,e,t)},useInsertionEffect:function(e,t){return Io(4,2,e,t)},useMemo:function(e,t){var n=Wn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Wn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Vd.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=Wn();return e={current:e},t.memoizedState=e},useState:au,useDebugValue:li,useDeferredValue:function(e){return Wn().memoizedState=e},useTransition:function(){var e=au(!1),t=e[0];return e=Hd.bind(null,e[1]),Wn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,s=Wn();if(Ue){if(n===void 0)throw Error(f(407));n=n()}else{if(n=t(),nt===null)throw Error(f(349));(qr&30)!==0||ru(r,t,n)}s.memoizedState=n;var l={value:n,getSnapshot:t};return s.queue=l,cu(ou.bind(null,r,l,e),[e]),r.flags|=2048,Gs(9,su.bind(null,r,l,n,t),void 0,null),n},useId:function(){var e=Wn(),t=nt.identifierPrefix;if(Ue){var n=or,r=sr;n=(r&~(1<<32-St(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qs++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=u.createElement(n,{is:r.is}):(e=u.createElement(n),n==="select"&&(u=e,r.multiple?u.multiple=!0:r.size&&(u.size=r.size))):e=u.createElementNS(e,n),e[Vn]=t,e[Us]=r,bu(e,t,!1,!1),t.stateNode=e;e:{switch(u=sn(n,r),n){case"dialog":De("cancel",e),De("close",e),s=r;break;case"iframe":case"object":case"embed":De("load",e),s=r;break;case"video":case"audio":for(s=0;sjs&&(t.flags|=128,r=!0,Js(l,!1),t.lanes=4194304)}else{if(!r)if(e=Ro(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Js(l,!0),l.tail===null&&l.tailMode==="hidden"&&!u.alternate&&!Ue)return mt(t),null}else 2*Me()-l.renderingStartTime>js&&n!==1073741824&&(t.flags|=128,r=!0,Js(l,!1),t.lanes=4194304);l.isBackwards?(u.sibling=t.child,t.child=u):(n=l.last,n!==null?n.sibling=u:t.child=u,l.last=u)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=Me(),t.sibling=null,n=He.current,Le(He,r?n&1|2:n&1),t):(mt(t),null);case 22:case 23:return Ri(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(Jt&1073741824)!==0&&(mt(t),t.subtreeFlags&6&&(t.flags|=8192)):mt(t),null;case 24:return null;case 25:return null}throw Error(f(156,t.tag))}function ef(e,t){switch(Fl(t),t.tag){case 1:return Ot(t.type)&&xo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return xs(),ze(Lt),ze(dt),Xl(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return Jl(t),null;case 13:if(ze(He),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(f(340));hs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ze(He),null;case 4:return xs(),null;case 10:return Ql(t.type._context),null;case 22:case 23:return Ri(),null;case 24:return null;default:return null}}var Fo=!1,pt=!1,tf=typeof WeakSet=="function"?WeakSet:Set,H=null;function Ss(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Qe(e,t,r)}else n.current=null}function yi(e,t,n){try{n()}catch(r){Qe(e,t,r)}}var Vu=!1;function nf(e,t){if(Rl=so,e=wa(),wl(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,l=r.focusNode;r=r.focusOffset;try{n.nodeType,l.nodeType}catch{n=null;break e}var u=0,d=-1,g=-1,w=0,M=0,R=e,P=null;t:for(;;){for(var b;R!==n||s!==0&&R.nodeType!==3||(d=u+s),R!==l||r!==0&&R.nodeType!==3||(g=u+r),R.nodeType===3&&(u+=R.nodeValue.length),(b=R.firstChild)!==null;)P=R,R=b;for(;;){if(R===e)break t;if(P===n&&++w===s&&(d=u),P===l&&++M===r&&(g=u),(b=R.nextSibling)!==null)break;R=P,P=R.parentNode}R=b}n=d===-1||g===-1?null:{start:d,end:g}}else n=null}n=n||{start:0,end:0}}else n=null;for(Al={focusedElem:e,selectionRange:n},so=!1,H=t;H!==null;)if(t=H,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,H=e;else for(;H!==null;){t=H;try{var V=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(V!==null){var Q=V.memoizedProps,Ge=V.memoizedState,_=t.stateNode,v=_.getSnapshotBeforeUpdate(t.elementType===t.type?Q:Pn(t.type,Q),Ge);_.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var S=t.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(f(163))}}catch(L){Qe(t,t.return,L)}if(e=t.sibling,e!==null){e.return=t.return,H=e;break}H=t.return}return V=Vu,Vu=!1,V}function Ys(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var l=s.destroy;s.destroy=void 0,l!==void 0&&yi(t,n,l)}s=s.next}while(s!==r)}}function Uo(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function xi(e){var t=e.ref;if(t!==null){var n=e.stateNode;e.tag,e=n,typeof t=="function"?t(e):t.current=e}}function Qu(e){var t=e.alternate;t!==null&&(e.alternate=null,Qu(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Vn],delete t[Us],delete t[Ol],delete t[$d],delete t[Fd])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Wu(e){return e.tag===5||e.tag===3||e.tag===4}function qu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Wu(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function _i(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=vo));else if(r!==4&&(e=e.child,e!==null))for(_i(e,t,n),e=e.sibling;e!==null;)_i(e,t,n),e=e.sibling}function Si(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Si(e,t,n),e=e.sibling;e!==null;)Si(e,t,n),e=e.sibling}var at=null,Mn=!1;function Rr(e,t,n){for(n=n.child;n!==null;)Ku(e,t,n),n=n.sibling}function Ku(e,t,n){if(ct&&typeof ct.onCommitFiberUnmount=="function")try{ct.onCommitFiberUnmount(At,n)}catch{}switch(n.tag){case 5:pt||Ss(n,t);case 6:var r=at,s=Mn;at=null,Rr(e,t,n),at=r,Mn=s,at!==null&&(Mn?(e=at,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):at.removeChild(n.stateNode));break;case 18:at!==null&&(Mn?(e=at,n=n.stateNode,e.nodeType===8?Ll(e.parentNode,n):e.nodeType===1&&Ll(e,n),Ms(e)):Ll(at,n.stateNode));break;case 4:r=at,s=Mn,at=n.stateNode.containerInfo,Mn=!0,Rr(e,t,n),at=r,Mn=s;break;case 0:case 11:case 14:case 15:if(!pt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var l=s,u=l.destroy;l=l.tag,u!==void 0&&((l&2)!==0||(l&4)!==0)&&yi(n,t,u),s=s.next}while(s!==r)}Rr(e,t,n);break;case 1:if(!pt&&(Ss(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(d){Qe(n,t,d)}Rr(e,t,n);break;case 21:Rr(e,t,n);break;case 22:n.mode&1?(pt=(r=pt)||n.memoizedState!==null,Rr(e,t,n),pt=r):Rr(e,t,n);break;default:Rr(e,t,n)}}function Gu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new tf),t.forEach(function(r){var s=ff.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Rn(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~l}if(r=s,r=Me()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*sf(r/1960))-r,10e?16:e,Tr===null)var r=!1;else{if(e=Tr,Tr=null,Qo=0,(je&6)!==0)throw Error(f(331));var s=je;for(je|=4,H=e.current;H!==null;){var l=H,u=l.child;if((H.flags&16)!==0){var d=l.deletions;if(d!==null){for(var g=0;gMe()-ki?Jr(e,0):ji|=n),$t(e,t)}function ac(e,t){t===0&&((e.mode&1)===0?t=1:(t=er,er<<=1,(er&130023424)===0&&(er=4194304)));var n=Ct();e=lr(e,t),e!==null&&(Qt(e,t,n),$t(e,n))}function df(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ac(e,n)}function ff(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(f(314))}r!==null&&r.delete(t),ac(e,n)}var uc;uc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Lt.current)Dt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Dt=!1,Xd(e,t,n);Dt=(e.flags&131072)!==0}else Dt=!1,Ue&&(t.flags&1048576)!==0&&Ba(t,jo,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;$o(e,t),e=t.pendingProps;var s=fs(t,dt.current);ys(t,n),s=ti(null,t,r,e,s,n);var l=ni();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ot(r)?(l=!0,_o(t)):l=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Kl(t),s.updater=Do,t.stateNode=s,s._reactInternals=t,ai(t,r,e,n),t=fi(null,t,r,!0,l,n)):(t.tag=0,Ue&&l&&$l(t),kt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch($o(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=pf(r),e=Pn(r,e),s){case 0:t=di(null,t,r,e,n);break e;case 1:t=Ou(null,t,r,e,n);break e;case 11:t=Ru(null,t,r,e,n);break e;case 14:t=Au(null,t,r,Pn(r.type,e),n);break e}throw Error(f(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Pn(r,s),di(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Pn(r,s),Ou(e,t,r,s,n);case 3:e:{if(Du(t),e===null)throw Error(f(387));r=t.pendingProps,l=t.memoizedState,s=l.element,Ya(e,t),Mo(t,r,null,n);var u=t.memoizedState;if(r=u.element,l.isDehydrated)if(l={element:r,isDehydrated:!1,cache:u.cache,pendingSuspenseBoundaries:u.pendingSuspenseBoundaries,transitions:u.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){s=_s(Error(f(423)),t),t=zu(e,t,r,n,s);break e}else if(r!==s){s=_s(Error(f(424)),t),t=zu(e,t,r,n,s);break e}else for(Gt=kr(t.stateNode.containerInfo.firstChild),Kt=t,Ue=!0,En=null,n=Ga(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(hs(),r===s){t=ar(e,t,n);break e}kt(e,t,r,n)}t=t.child}return t;case 5:return eu(t),e===null&&bl(t),r=t.type,s=t.pendingProps,l=e!==null?e.memoizedProps:null,u=s.children,Tl(r,s)?u=null:l!==null&&Tl(r,l)&&(t.flags|=32),Lu(e,t),kt(e,t,u,n),t.child;case 6:return e===null&&bl(t),null;case 13:return $u(e,t,n);case 4:return Gl(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=gs(t,null,r,n):kt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Pn(r,s),Ru(e,t,r,s,n);case 7:return kt(e,t,t.pendingProps,n),t.child;case 8:return kt(e,t,t.pendingProps.children,n),t.child;case 12:return kt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,l=t.memoizedProps,u=s.value,Le(No,r._currentValue),r._currentValue=u,l!==null)if(Nn(l.value,u)){if(l.children===s.children&&!Lt.current){t=ar(e,t,n);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var d=l.dependencies;if(d!==null){u=l.child;for(var g=d.firstContext;g!==null;){if(g.context===r){if(l.tag===1){g=ir(-1,n&-n),g.tag=2;var w=l.updateQueue;if(w!==null){w=w.shared;var M=w.pending;M===null?g.next=g:(g.next=M.next,M.next=g),w.pending=g}}l.lanes|=n,g=l.alternate,g!==null&&(g.lanes|=n),Wl(l.return,n,t),d.lanes|=n;break}g=g.next}}else if(l.tag===10)u=l.type===t.type?null:l.child;else if(l.tag===18){if(u=l.return,u===null)throw Error(f(341));u.lanes|=n,d=u.alternate,d!==null&&(d.lanes|=n),Wl(u,n,t),u=l.sibling}else u=l.child;if(u!==null)u.return=l;else for(u=l;u!==null;){if(u===t){u=null;break}if(l=u.sibling,l!==null){l.return=u.return,u=l;break}u=u.return}l=u}kt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,ys(t,n),s=dn(s),r=r(s),t.flags|=1,kt(e,t,r,n),t.child;case 14:return r=t.type,s=Pn(r,t.pendingProps),s=Pn(r.type,s),Au(e,t,r,s,n);case 15:return Tu(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Pn(r,s),$o(e,t),t.tag=1,Ot(r)?(e=!0,_o(t)):e=!1,ys(t,n),ju(t,r,s),ai(t,r,s,n),fi(null,t,r,!0,e,n);case 19:return Uu(e,t,n);case 22:return Iu(e,t,n)}throw Error(f(156,t.tag))};function cc(e,t){return z(e,t)}function mf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function pn(e,t,n,r){return new mf(e,t,n,r)}function Ti(e){return e=e.prototype,!(!e||!e.isReactComponent)}function pf(e){if(typeof e=="function")return Ti(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ie)return 11;if(e===me)return 14}return 2}function Or(e,t){var n=e.alternate;return n===null?(n=pn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Go(e,t,n,r,s,l){var u=2;if(r=e,typeof e=="function")Ti(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case $e:return Xr(n.children,s,l,t);case We:u=8,s|=8;break;case Je:return e=pn(12,n,t,s|2),e.elementType=Je,e.lanes=l,e;case Ie:return e=pn(13,n,t,s),e.elementType=Ie,e.lanes=l,e;case Fe:return e=pn(19,n,t,s),e.elementType=Fe,e.lanes=l,e;case pe:return Jo(n,s,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case et:u=10;break e;case st:u=9;break e;case ie:u=11;break e;case me:u=14;break e;case Re:u=16,r=null;break e}throw Error(f(130,e==null?e:typeof e,""))}return t=pn(u,n,t,s),t.elementType=e,t.type=r,t.lanes=l,t}function Xr(e,t,n,r){return e=pn(7,e,r,t),e.lanes=n,e}function Jo(e,t,n,r){return e=pn(22,e,r,t),e.elementType=pe,e.lanes=n,e.stateNode={isHidden:!1},e}function Ii(e,t,n){return e=pn(6,e,null,t),e.lanes=n,e}function Li(e,t,n){return t=pn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function hf(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=It(0),this.expirationTimes=It(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=It(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Oi(e,t,n,r,s,l,u,d,g){return e=new hf(e,t,n,d,g),t===1?(t=1,l===!0&&(t|=8)):t=0,l=pn(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Kl(l),e}function gf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(m){console.error(m)}}return i(),bi.exports=Pf(),bi.exports}var kc;function Rf(){if(kc)return rl;kc=1;var i=Mf();return rl.createRoot=i.createRoot,rl.hydrateRoot=i.hydrateRoot,rl}var Af=Rf();const Tf=bc(Af),If="/api";async function Ee(i,m){const f=await fetch(`${If}${i}`,{...m,headers:{"Content-Type":"application/json",...m?.headers??{}}}),N=await f.json();if(!f.ok){const j=N.error?.message??"Ошибка запроса";throw new Error(j)}return N}const ke={async loadSharedConnectionConfig(){return Ee("/llm/shared-connection")},async saveSharedConnectionConfig(i){return Ee("/llm/shared-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,model:i.model,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})})},async listModels(i){return Ee("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async testConnection(i){return Ee("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async normalize(i){return Ee("/normalize",{method:"POST",body:JSON.stringify({llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,userQuestion:i.query.userQuestion,context:{period_hint:i.query.periodHint??"",business_context:i.query.businessContext??"",expected_route:i.query.expectedRoute??""},saveAsTestCase:!!i.saveAsTestCase,useMock:!!i.useMock})})},async loadHistory(){return Ee("/history")},async loadTrace(i){return Ee(`/history/${i}`)},async loadPresets(){return Ee("/presets")},async savePreset(i){return Ee("/presets/save",{method:"POST",body:JSON.stringify(i)})},async runEval(i){return Ee("/eval/run",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,analysis_date:i.analysisDate})})},async startEvalRunAsync(i){return Ee("/eval/run-async/start",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,questions:i.questions,analysis_date:i.analysisDate})})},async loadEvalRunAsyncStatus(i){return Ee(`/eval/run-async/${encodeURIComponent(i)}`)},async startRun(){return Ee("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(i){return Ee("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:i,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return Ee("/accounting-agent/v1/runs")},async listResults(){return Ee("/accounting-agent/v1/results")},async runTrace(i){return Ee(`/accounting-agent/v1/trace/run/${i}`)},async sendAssistantMessage(i){return Ee("/assistant/message",{method:"POST",body:JSON.stringify({session_id:i.sessionId??"",mode:"assistant",message:i.userMessage,user_message:i.userMessage,llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion??"address_query_runtime_v1",systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,context:{period_hint:i.context?.periodHint??"",business_context:i.context?.businessContext??""},useMock:!!i.useMock})})},async loadAssistantSession(i){return Ee(`/assistant/session/${i}`)},async loadAssistantAnnotations(i){const m=new URLSearchParams;i?.session_id&&m.set("session_id",i.session_id),typeof i?.limit=="number"&&m.set("limit",String(i.limit));const f=m.toString();return Ee(`/assistant/annotations${f?`?${f}`:""}`)},async saveAssistantAnnotation(i){return Ee("/assistant/annotations",{method:"POST",body:JSON.stringify(i)})},async loadAutoRunsHistory(i){const m=new URLSearchParams;i?.from&&m.set("from",i.from),i?.to&&m.set("to",i.to),i?.target&&m.set("target",i.target),i?.mode&&m.set("mode",i.mode),i?.use_mock&&m.set("use_mock",i.use_mock),i?.prompt_contains&&m.set("prompt_contains",i.prompt_contains),typeof i?.limit=="number"&&m.set("limit",String(i.limit)),typeof i?.scan_limit=="number"&&m.set("scan_limit",String(i.scan_limit));const f=m.toString();return Ee(`/autoruns/history${f?`?${f}`:""}`)},async loadAutoRunDetail(i){return Ee(`/autoruns/history/${encodeURIComponent(i)}`)},async loadAutoRunCaseDialog(i,m){return Ee(`/autoruns/history/${encodeURIComponent(i)}/case/${encodeURIComponent(m)}/dialog`)},async loadAutoRunAnnotations(i){const m=new URLSearchParams;i?.run_id&&m.set("run_id",i.run_id),i?.case_id&&m.set("case_id",i.case_id),typeof i?.min_rating=="number"&&m.set("min_rating",String(i.min_rating)),i?.manual_case_decision&&m.set("manual_case_decision",i.manual_case_decision),typeof i?.limit=="number"&&m.set("limit",String(i.limit));const f=m.toString();return Ee(`/autoruns/annotations${f?`?${f}`:""}`)},async saveAutoRunAnnotation(i){return Ee("/autoruns/annotations",{method:"POST",body:JSON.stringify(i)})},async updateAutoRunAnnotation(i){return Ee(`/autoruns/annotations/${encodeURIComponent(i.annotation_id)}`,{method:"PATCH",body:JSON.stringify({resolved:i.resolved,resolved_by:i.resolved_by})})},async loadAutoRunPostAnalysis(i){const m=new URLSearchParams;i?.run_id&&m.set("run_id",i.run_id),typeof i?.limit_per_queue=="number"&&m.set("limit_per_queue",String(i.limit_per_queue)),typeof i?.annotation_limit=="number"&&m.set("annotation_limit",String(i.annotation_limit)),typeof i?.scan_limit=="number"&&m.set("scan_limit",String(i.scan_limit)),i?.from&&m.set("from",i.from),i?.to&&m.set("to",i.to),i?.target&&m.set("target",i.target),i?.mode&&m.set("mode",i.mode),i?.use_mock&&m.set("use_mock",i.use_mock),i?.prompt_contains&&m.set("prompt_contains",i.prompt_contains);const f=m.toString();return Ee(`/autoruns/post-analysis${f?`?${f}`:""}`)},async loadAutoRunAutogenHistory(i){const m=new URLSearchParams;i?.mode&&m.set("mode",i.mode),typeof i?.limit=="number"&&m.set("limit",String(i.limit));const f=m.toString();return Ee(`/autoruns/autogen/history${f?`?${f}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return Ee("/autoruns/autogen/personality-catalog")},async generateAutoRunQuestions(i){return Ee("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(i)})}};function Yt({value:i}){return o.jsx("pre",{className:"json-view",children:JSON.stringify(i??{},null,2)})}function Tn({title:i,subtitle:m,actions:f,className:N,hideHeader:j,children:T}){return o.jsxs("section",{className:N?`panel-frame ${N}`:"panel-frame",children:[j?null:o.jsxs("header",{className:"panel-header",children:[o.jsxs("div",{children:[o.jsx("h2",{children:i}),m?o.jsx("p",{children:m}):null]}),f?o.jsx("div",{className:"panel-actions",children:f}):null]}),o.jsx("div",{className:"panel-body",children:T})]})}function Lf(i){const m=new Date(i);return Number.isNaN(m.getTime())?i:m.toLocaleString("ru-RU")}function Of({sessionId:i,conversation:m,statusText:f,errorMessage:N,useMock:j,appLogs:T}){const F=m.filter(I=>I.role==="assistant").length,Y=m.filter(I=>I.role==="user").length,U=m.length>0?m[m.length-1]:null;return o.jsxs(Tn,{title:"SAM",subtitle:"System Assistant Monitor: срез по текущей сессии и логам.",children:[o.jsxs("div",{className:"metrics-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"session_id"}),o.jsx("strong",{children:i||"новая сессия"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"mock_mode"}),o.jsx("strong",{children:j?"on":"off"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"сообщений пользователя"}),o.jsx("strong",{children:Y})]}),o.jsxs("div",{children:[o.jsx("span",{children:"ответов ассистента"}),o.jsx("strong",{children:F})]}),o.jsxs("div",{children:[o.jsx("span",{children:"статус"}),o.jsx("strong",{children:f||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"ошибка"}),o.jsx("strong",{children:N||"нет"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"последнее сообщение"}),o.jsx("strong",{children:U?.created_at?Lf(U.created_at):"нет данных"})]})]}),o.jsx("h3",{style:{marginTop:12},children:"Последние системные логи"}),o.jsx(Yt,{value:T.slice(0,120)})]})}const Df=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,zf=[/\b(?:debug_payload_json|technical_breakdown_json)\b/i,/\b(?:route_summary|semantic_profile|domain_scope|relation_patterns|account_scope)\b/i,/\b(?:coverage_report|retrieval_status|problem_unit_state|candidate_evidence)\b/i,/\b(?:graph_domain_scope|graph_runtime|selection_reason|why_included)\b/i];function $f(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function Ff(i){const m=String(i??""),f=m.match(Df);return(f?m.slice(0,f.index):m).replace(/###\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)[\s\S]*?(?:```[\s\S]*?```|$)/gi,"").replace(/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)\b[\s\S]*$/gi,"").split(/\r?\n/g).map(F=>F.trimEnd()).filter(F=>F.trim().length>0).filter(F=>!zf.some(Y=>Y.test(F))).join(` +`).trim()}function Uf(i,m,f="default"){const N=f==="technical",j=[];j.push("# Assistant conversation export"),j.push(`session_id: ${i||"n/a"}`),j.push(`export_mode: ${f}`),j.push(`exported_at: ${new Date().toISOString()}`),j.push("");for(let T=0;T{j.length!==0&&(N.push(j.join(` +`)),j=[])};for(const F of f){const Y=F.trimEnd(),U=Y.trim();if(!U){T();continue}const I=/^Блок\s+\d+\./i.test(U),q=/^\d+\.\s/.test(U);(I||q)&&j.length>0&&T(),j.push(Y)}return T(),N.length>0?N:[i]}function qf(i,m){const f=[],N=/\*\*(.+?)\*\*/g;let j=0,T=0,F;for(;(F=N.exec(i))!==null;)F.index>j&&(f.push(o.jsx("span",{children:i.slice(j,F.index)},`${m}-t-${T}`)),T+=1),f.push(o.jsx("strong",{children:F[1]},`${m}-b-${T}`)),T+=1,j=N.lastIndex;return j0?f:[o.jsx("span",{children:i},`${m}-raw`)]}function Kf(i){const m=i.trimStart();return/^Блок\s+\d+\./i.test(m)?"assistant-msg-line heading":/^\d+\.\s/.test(m)?"assistant-msg-line numbered":/^-\s/.test(m)?"assistant-msg-line bullet":"assistant-msg-line"}function Gf(i,m=40){const f=i.replace(/\s+/g," ").trim();if(f.length<=m)return f;const N=f.split(" ").slice(0,3).join(" ").trim();return N.length>=10&&N.length<=m?`${N}…`:`${f.slice(0,m-1).trimEnd()}…`}function Bc(i){return i.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Jf(i){const m=i.replace(/\r\n?/g,` +`).split(` +`).map(j=>j.trim()).find(Boolean),f=Bc(m??"");return(f.split("|")[0]?.trim()??f).replace(/\s+/g," ").trim()}function Yf(i){const m=i.replace(/\r\n?/g,` +`).split(` +`).map(N=>N.trim()).find(Boolean);return!m||!/^\d+\.\s/.test(m)?!1:Bc(m).includes("|")}function Xf(i,m){const f=m.replace(/\r\n?/g,` +`).replace(/\*\*(.+?)\*\*/g,"$1").split(` +`).map((j,T)=>{const F=j.trim();return T===0?F.replace(/^\d+\.\s*/,""):F}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!f)return null;const N=Jf(m)||f;return{message_id:i.message_id,source_text:f,anchor_text:N,preview_text:Gf(N)}}function Zf(i,m,f,N){return Wf(i.text).map((T,F)=>{const Y=T.split(` +`),U=i.role==="assistant"&&Yf(T),I=U?Xf(i,T):null,q=!!I&&m?.message_id===I?.message_id&&m?.source_text===I?.source_text,D=Y.map((B,oe)=>o.jsx("p",{className:Kf(B),children:qf(B,`line-${F}-${oe}`)},`line-${F}-${oe}`));return!U||!I?o.jsx("div",{className:"assistant-msg-block",children:D},`block-${F}`):o.jsx("div",{className:q?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(q){N();return}f(I)},onKeyDown:B=>{if(!(B.key!=="Enter"&&B.key!==" ")){if(B.preventDefault(),q){N();return}f(I)}},children:D},`block-${F}`)})}function Hc({sessionId:i,conversation:m,inputValue:f,onInputChange:N,selectedContextChip:j,onSelectContextChip:T,onClearContextChip:F,useMock:Y,onUseMockChange:U,onSend:I,onClear:q,busy:D,statusText:B,errorMessage:oe,showCommentAction:Ae=!1,onCommentAssistantMessage:se,isAssistantMessageCommented:te,canCommentAssistantMessage:Te}){const ve=x.useRef(null),G=x.useRef(!0),ae=x.useRef(null),[_e,Oe]=x.useState("idle"),[$e,We]=x.useState("чат");function Je(ie=!1){ve.current&&(ie&&(G.current=!0),ve.current.scrollTop=ve.current.scrollHeight)}x.useEffect(()=>{G.current&&Je()},[m]),x.useEffect(()=>()=>{ae.current!==null&&window.clearTimeout(ae.current)},[]);async function et(ie){if(m.length===0)return;const Ie=Uf(i,m,ie),Fe=await Hf(Ie);We(ie==="technical"?"тех":"чат"),Oe(Fe?"success":"error"),ae.current!==null&&window.clearTimeout(ae.current),ae.current=window.setTimeout(()=>{Oe("idle")},2200)}function st(){if(!ve.current)return;const ie=ve.current,Ie=ie.scrollHeight-ie.scrollTop-ie.clientHeight;G.current=Ie<16}return o.jsx(Tn,{className:"assistant-panel-frame",title:"Режим ассистента",children:o.jsxs("div",{className:"assistant-live-shell",children:[o.jsxs("div",{className:"assistant-toolbar",children:[o.jsxs("div",{className:"assistant-toolbar-actions",children:[o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{et("default")},disabled:m.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{et("technical")},disabled:m.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>q(),disabled:D&&m.length===0,children:"Сбросить сессию"})]}),o.jsxs("div",{className:"assistant-toolbar-meta",children:[i?o.jsx("span",{className:"status-chip",children:`session: ${i}`}):null,o.jsxs("div",{className:"assistant-toolbar-meta-right",children:[B?o.jsx("span",{className:"assistant-live-status",children:B}):null,_e==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",$e,")"]}):null,_e==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),oe?o.jsx("p",{className:"error-text assistant-toolbar-error",children:oe}):null]}),o.jsx("div",{ref:ve,className:"assistant-chat-list",onScroll:st,children:m.map((ie,Ie)=>{const Fe=ie.role==="assistant"&&Ae&&typeof se=="function"&&(typeof Te=="function"?Te(ie,Ie):!0),me=ie.role==="assistant"&&typeof te=="function"?te(ie,Ie):!1;return o.jsxs("article",{className:`assistant-msg ${ie.role}`,children:[o.jsxs("header",{className:"assistant-msg-head",children:[o.jsxs("div",{className:"assistant-msg-head-main",children:[o.jsx("strong",{children:bf(ie.role)}),o.jsx("span",{children:Bf(ie.created_at)})]}),ie.role==="assistant"&&Ae?o.jsx("div",{className:"assistant-msg-head-actions",children:o.jsx("button",{type:"button",className:me?"autoruns-comment-icon assistant-comment-btn commented":"autoruns-comment-icon assistant-comment-btn",onClick:()=>se?.(ie,Ie),disabled:!Fe,title:Fe?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":Fe?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:o.jsx(Vf,{commented:me})})}):null]}),o.jsx("div",{className:"assistant-msg-body",children:Zf(ie,j,T,F)}),ie.role==="assistant"&&ie.debug?o.jsxs("details",{className:"assistant-debug",children:[o.jsx("summary",{children:"Показать технический разбор"}),o.jsx(Yt,{value:ie.debug})]}):null]},ie.message_id)})}),o.jsxs("div",{className:"assistant-compose",children:[j?o.jsxs("div",{className:"assistant-compose-context",children:[o.jsx("span",{className:"assistant-compose-context-label",children:"Выбранный объект"}),o.jsxs("div",{className:"assistant-compose-context-pill",title:j.source_text,children:[o.jsx("span",{className:"assistant-compose-context-pill-text",children:j.preview_text}),o.jsx("button",{type:"button",className:"assistant-compose-context-clear",onClick:F,"aria-label":"Убрать выбранный объект",title:"Убрать выбранный объект",children:"×"})]})]}):null,o.jsxs("label",{className:"full-width",children:["Сообщение",o.jsx("textarea",{className:"assistant-input-textarea",value:f,onChange:ie=>N(ie.target.value),rows:4,placeholder:j?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),o.jsxs("div",{className:"button-row assistant-send-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:Y,onChange:ie=>U(ie.target.checked)}),"Mock-режим"]}),o.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{Je(!0),I()},disabled:D||!f.trim(),children:D?"Выполняю...":"Отправить"})]})]})]})})}const Vi={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},sl="needs_dialog_policy_fix",ht="__all__",ul="__live__:",Cc="ndc_autoruns_ui_config_v1",Nc="ndc-autoruns-save",Qi=["Анализ запроса","Получение данных","Подготовка ответа"];function em(i,m){const f=i.trim();if(!f)return"";if(!m)return f;const N=f.toLowerCase(),j=m.anchor_text.trim(),T=j.toLowerCase();return T&&N.includes(T)?f:`По выбранному объекту "${j}": ${f}`}const Xi=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function tm(i=Xi){return i.reduce((m,f)=>(m[f.id]=f.defaultPrompt,m),{})}const Ec={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:tm(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function Wi(i){const m=String(i??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(m)?m:""}function Pc(i){const m=typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):160;return Math.max(110,Math.min(520,m))}function nm(i){const m=i.getFullYear(),f=String(i.getMonth()+1).padStart(2,"0"),N=String(i.getDate()).padStart(2,"0"),j=String(i.getHours()).padStart(2,"0"),T=String(i.getMinutes()).padStart(2,"0");return`${m}-${f}-${N}T${j}:${T}`}function Mc(){const i=new Date;return i.setDate(i.getDate()-14),nm(i)}function ol(i){if(!i.trim())return;const m=Date.parse(i);if(Number.isFinite(m))return new Date(m).toISOString()}function cr(i){if(!i)return"нет данных";const m=Date.parse(i);return Number.isFinite(m)?new Date(m).toLocaleString("ru-RU"):i}function rm(i,m){return m<=0?0:Math.max(0,Math.min(100,Number((i/m*100).toFixed(1))))}function ll(i){return typeof i!="number"?"нет данных":`${i.toFixed(1)}%`}function sm(i){return i==="assistant_stage1"?"assistant/s1":i==="assistant_stage2"?"assistant/s2":i==="assistant_p0"?"assistant/p0":i}function Rc(i){return i==="up"?"Рост":i==="down"?"Регресс":"Без изменений"}function om(i,m){return i.find(f=>f.case_id===m)??null}function qi(i){const m=Math.max(1,Math.min(5,Math.round(i)));return`${"●".repeat(m)}${"○".repeat(5-m)}`}function Ac(i){return i.length===0?o.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):o.jsx("div",{className:"autoruns-coverage-list",children:i.map(m=>{const f=rm(m.closed_cases,m.total_cases);return o.jsxs("div",{className:"autoruns-coverage-item",children:[o.jsxs("div",{className:"autoruns-coverage-head",children:[o.jsx("strong",{children:m.domain}),o.jsxs("span",{children:[m.closed_cases,"/",m.total_cases," (",f,"%)"]})]}),o.jsx("div",{className:"autoruns-coverage-bar",children:o.jsx("div",{style:{width:`${f}%`}})})]},m.domain)})})}function al(i){return`${ul}${i}`}function Cs(i){return i.startsWith(ul)}function Tc(i){return i.startsWith(ul)?i.slice(ul.length):""}function Vc(i){const m=i.report_summary?.run_timestamp??i.created_at,f=Math.max(0,i.total_cases-i.completed_cases);return{run_id:al(i.job_id),eval_target:i.eval_target,run_timestamp:m,mode:"single-pass-strict",llm_provider:null,model:null,use_mock:null,analysis_date:i.report_summary?.analysis_date??i.analysis_date??null,prompt_version:null,schema_version:null,suite_id:i.case_set_file,cases_total:i.total_cases,requests_total:null,report_path:`async_job:${i.job_id}`,score_index:i.report_summary?.score_index??null,blocking_failures:0,quality_failures:0,closed_cases:i.completed_cases,open_cases:f,domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]}}function ro(i,m){const f=Vc(i),N=i.cases.map(q=>({case_id:q.case_id,domain:null,query_class:null,status:q.status==="completed"?"closed":q.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${i.run_id}-${q.case_id}`,dialog_available:q.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),T=m!==ht&&N.some(q=>q.case_id===m)?m:N.length>0?ht:"",F={ok:!0,run:f,coverage:{closed_cases:i.completed_cases,open_cases:Math.max(0,i.total_cases-i.completed_cases),domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]},cases:N,annotations_summary:{total:0},report:i.report_summary?{run_id:i.report_summary.run_id,run_timestamp:i.report_summary.run_timestamp,score_index:i.report_summary.score_index,cases_total:i.report_summary.cases_total,analysis_date:i.report_summary.analysis_date??i.analysis_date??null}:{}},Y=[];let U=0;if(T===ht)for(const q of i.cases)for(let D=0;DD.case_id===T)??null;for(let D=0;D<(q?.messages.length??0);D+=1){const B=q?.messages[D];B&&Y.push({...B,message_index:D,case_id:T,case_message_index:D,commented:!1,annotation:null})}}const I={ok:!0,run_id:f.run_id,case_id:T,source:"assistant_session",session_id:T===ht?`${i.run_id}::__all__`:`${i.run_id}-${T}`,messages:Y,decomposition:[],assistant_mode:{status:i.status,completed_cases:i.completed_cases,total_cases:i.total_cases},annotations:[]};return{detail:F,dialog:I,caseId:T}}function lm({commented:i}){const m=i?"comment-icon-svg commented":"comment-icon-svg";return o.jsx("svg",{className:m,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M5 6.5h14v9H11.5l-4.5 3v-3H5z"})})}function Ic({resolved:i}){return o.jsxs("svg",{className:i?"resolve-icon-svg resolved":"resolve-icon-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[o.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),i?o.jsx("path",{d:"M5.1 8.2 7.2 10.3 11 6.5"}):null]})}function im(){return o.jsxs("svg",{className:"autoruns-copy-icon-svg",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2.2"}),o.jsx("path",{d:"M15 7V5.8a1.8 1.8 0 0 0-1.8-1.8H5.8A1.8 1.8 0 0 0 4 5.8v7.4A1.8 1.8 0 0 0 5.8 15H7"})]})}function am({connection:i,prompts:m,assistantPromptVersion:f,decompositionPromptVersion:N,showAssistantMode:j,showDecompositionMode:T,showProgressMode:F,showCommentsMode:Y,onLog:U}){const[I,q]=x.useState({...Vi,fromLocal:Mc()}),[D,B]=x.useState(""),[oe,Ae]=x.useState(null),[se,te]=x.useState(null),[Te,ve]=x.useState(null),[G,ae]=x.useState([]),[_e,Oe]=x.useState("all"),[$e,We]=x.useState(!1),[Je,et]=x.useState(null),[st,ie]=x.useState([]),[Ie,Fe]=x.useState(""),[me,Re]=x.useState(""),[pe,O]=x.useState(""),[W,$]=x.useState(Xi),[h,k]=x.useState(Ec),[J,ue]=x.useState([]),[de,fe]=x.useState(""),[Se,ye]=x.useState([]),[ee,Pe]=x.useState(null),[Ut,Kn]=x.useState(null),[In,Ln]=x.useState(!1),[fr,Xt]=x.useState(!1),[Zt,Gn]=x.useState(!1),[hn,bt]=x.useState(!1),[en,gn]=x.useState(!1),[mr,On]=x.useState(!1),[pr,Dn]=x.useState(!1),[tn,nn]=x.useState(!1),[hr,Bt]=x.useState(""),[vn,be]=x.useState(""),[ot,yn]=x.useState(""),[xn,rn]=x.useState([]),[sn,Nt]=x.useState([]),[zn,on]=x.useState(""),[Ht,gt]=x.useState(null),[Jn,qe]=x.useState(!1),[gr,_n]=x.useState(!1),[vr,ln]=x.useState(""),[yr,Et]=x.useState(""),[Yn,vt]=x.useState(String(Vi.limit)),[Zr,yt]=x.useState(String(Ec.count)),[Pt,$n]=x.useState(160),[ce,lt]=x.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:sl,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[xe,xt]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),Mt=x.useRef(!1),Ce=x.useRef(null),it=x.useMemo(()=>W.find(a=>a.id===h.personalityId)??W[0]??Xi[0],[h.personalityId,W]),Rt=x.useMemo(()=>J.find(a=>a.generation_id===de)??J[0]??null,[J,de]),Fn=se?om(se.cases,pe):null,Vt=x.useMemo(()=>$e?G.filter(a=>!a.resolved):G,[G,$e]),z=Vt.find(a=>a.annotation_id===Ie)??null,zr=Te?.messages.find(a=>a.message_index===ce.messageIndex)??null,xr=x.useMemo(()=>{if(!Te||ce.messageIndex<0)return null;for(let a=ce.messageIndex-1;a>=0;a-=1){const c=Te.messages[a];if(c?.role==="user")return c}return null},[ce.messageIndex,Te]),Xn=x.useMemo(()=>{const a=new Map;for(const c of sn)c.message_id&&a.set(c.message_id,c);return a},[sn]),Me=xe.messageIndex>=0?xn[xe.messageIndex]??null:null,$r=x.useMemo(()=>{if(xe.messageIndex<0)return null;for(let a=xe.messageIndex-1;a>=0;a-=1){const c=xn[a];if(c?.role==="user")return c}return null},[xe.messageIndex,xn]),_t=x.useMemo(()=>{const a=Vt.map(y=>({source:"autorun",key:`autorun:${y.annotation_id}`,updated_at:y.updated_at,rating:y.rating,autorun:y,assistant:null})),c=sn.map(y=>({source:"assistant_live",key:`assistant:${y.annotation_id}`,updated_at:y.updated_at,rating:y.rating,autorun:null,assistant:y}));return[...a,...c].sort((y,A)=>Date.parse(A.updated_at)-Date.parse(y.updated_at))},[sn,Vt]),_r=x.useMemo(()=>{if(_t.length===0)return null;const a=_t.reduce((c,y)=>c+y.rating,0)/_t.length;return Number(a.toFixed(2))},[_t]),Sn=x.useMemo(()=>{const a=[...oe?.items??[]];return ee&&a.unshift(Vc(ee)),me&&!a.some(c=>c.run_id===me)&&se?.run&&a.unshift(se.run),a},[ee,oe?.items,se?.run,me]),le=x.useCallback(a=>{U?.(`[autoruns] ${a}`)},[U]),Un=x.useCallback(async a=>{const c=String(a??"").trim();if(!c){Nt([]);return}try{const y=await ke.loadAssistantAnnotations({session_id:c,limit:400});Nt(y.items??[])}catch(y){const A=y instanceof Error?y.message:String(y);le(`Assistant live annotations load error: ${A}`)}},[le]),At=x.useCallback(a=>{xt(c=>c.saving&&!a?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),ct=x.useCallback(async(a,c)=>{a.stopPropagation(),a.preventDefault();const y=String(c??"").trim();if(y)try{if(navigator?.clipboard?.writeText)await navigator.clipboard.writeText(y);else{const A=document.createElement("textarea");A.value=y,A.setAttribute("readonly","true"),A.style.position="fixed",A.style.opacity="0",document.body.appendChild(A),A.select(),document.execCommand("copy"),document.body.removeChild(A)}le(`run id copied: ${y}`)}catch(A){const he=A instanceof Error?A.message:String(A);be(`Копирование run id: ${he}`),le(`copy run id error: ${he}`)}},[le]);function es(){let a=0;ln(Qi[0]);const c=window.setInterval(()=>{a=Math.min(a+1,Qi.length-1),ln(Qi[a])},650);return()=>window.clearInterval(c)}const St=x.useCallback(()=>{yn(""),rn([]),Nt([]),on(""),gt(null),ln(""),Et(""),At({force:!0}),le("Live-чат ассистента в истории автопрогонов сброшен.")},[At,le]),Ns=x.useCallback(async()=>{const a=em(zn,Ht);if(!a)return;_n(!0),Et(""),on(""),rn(y=>[...y,{message_id:`autoruns-live-${Date.now()}`,session_id:ot||"pending",role:"user",text:a,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=es();try{const y=await ke.sendAssistantMessage({connection:i,prompts:m,userMessage:a,sessionId:ot||void 0,promptVersion:f,useMock:Jn});yn(y.session_id),rn(y.conversation),await Un(y.session_id),ln("Ответ готов"),le(`Live-ответ ассистента получен: trace=${y.debug.trace_id}`)}catch(y){const A=y instanceof Error?y.message:String(y);Et(A),ln("Ошибка ассистента"),le(`Live-чат ассистента: ошибка отправки сообщения: ${A}`)}finally{c(),_n(!1)}},[zn,Ht,ot,Jn,f,i,Un,le,m]),ts=x.useCallback(a=>{const c=a.trim();if(!c){vt(String(I.limit));return}if(!/^\d+$/.test(c)){vt(String(I.limit));return}const y=Number.parseInt(c,10);if(!Number.isFinite(y)){vt(String(I.limit));return}const A=Math.max(1,Math.min(500,y));A!==I.limit&&q(he=>({...he,limit:A})),vt(String(A))},[I.limit]),ns=x.useCallback(a=>{const c=a.trim();if(!c){yt(String(h.count));return}if(!/^\d+$/.test(c)){yt(String(h.count));return}const y=Number.parseInt(c,10);if(!Number.isFinite(y)){yt(String(h.count));return}const A=Math.max(1,Math.min(200,y));A!==h.count&&k(he=>({...he,count:A})),yt(String(A))},[h.count]),Zn=x.useCallback(a=>{$n(Pc(a))},[]),er=x.useCallback(a=>{const c=a.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&Zn(c)},[Zn]),Tt=x.useCallback(async()=>{nn(!0);try{const a=await ke.loadAutoRunAnnotations({limit:800,manual_case_decision:_e});ae(a.items),et(a.manual_case_decision_schema??null),ie(a.available_manual_case_decisions??[]),Fe(c=>a.items.length===0?"":a.items.some(y=>y.annotation_id===c)?c:a.items[0].annotation_id)}catch(a){le(`Annotations load error: ${a instanceof Error?a.message:String(a)}`)}finally{nn(!1)}},[_e,le]),wt=x.useCallback(async()=>{bt(!0);try{const a=await ke.loadAutoRunAutogenHistory({limit:180});ue(a.items)}catch(a){le(`Autogen history load error: ${a instanceof Error?a.message:String(a)}`)}finally{bt(!1)}},[le]),Fr=x.useCallback(async()=>{try{const c=(await ke.loadAutoRunAutogenPersonalityCatalog()).items.map(y=>({id:String(y.id??"").trim(),label:String(y.label??"").trim(),domain:typeof y.domain=="string"?y.domain.trim():"",defaultPrompt:String(y.default_prompt??"").trim()})).filter(y=>y.id.length>0&&y.label.length>0);if(c.length===0)return;$(c.map(y=>({id:y.id,label:y.label,domain:y.domain||"",defaultPrompt:y.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(a){le(`Autogen personality catalog load error: ${a instanceof Error?a.message:String(a)}`)}},[le]),jt=x.useCallback(async()=>{Gn(!0);try{const a=await ke.loadAutoRunPostAnalysis({run_id:me&&!Cs(me)?me:void 0,limit_per_queue:30,annotation_limit:1500,from:ol(I.fromLocal),to:ol(I.toLocal),target:I.target,mode:I.mode,use_mock:I.useMock,prompt_contains:I.promptContains.trim()||void 0});Kn(a)}catch(a){le(`Post-analysis load error: ${a instanceof Error?a.message:String(a)}`),Kn(null)}finally{Gn(!1)}},[I.fromLocal,I.mode,I.promptContains,I.target,I.toLocal,I.useMock,le,me]),bn=x.useCallback(async()=>{Ln(!0),be("");try{const a=h.personalityPrompts[h.personalityId]??"",c=[m.systemPrompt,m.developerPrompt,m.domainPrompt,m.schemaNotes,m.fewShotExamples].join(` +`).slice(0,900),y=await ke.generateAutoRunQuestions({mode:h.mode,count:h.count,domain:it.domain||void 0,persist_to_eval_cases:h.persistToEvalCases,generated_by:h.generatedBy.trim()||void 0,llm:{llm_provider:i.llmProvider,api_key:i.apiKey,model:i.model,base_url:i.baseUrl,temperature:i.temperature,max_output_tokens:i.maxOutputTokens},context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:f,decomposition_prompt_version:N,prompt_fingerprint:c,autogen_personality_id:it.id,autogen_personality_prompt:a.trim()||void 0}});le(`Generated ${y.generation.count} questions (${y.generation.mode}) id=${y.generation.generation_id}`+(y.generation.saved_case_set_file?` saved=${y.generation.saved_case_set_file}`:"")),fe(y.generation.generation_id),ye([...y.generation.questions??[]]),await wt()}catch(a){const c=a instanceof Error?a.message:String(a);be(`Автогенерация: ${c}`),le(`Autogen generate error: ${c}`)}finally{Ln(!1)}},[f,h.count,h.generatedBy,h.mode,h.personalityId,h.personalityPrompts,h.persistToEvalCases,i.apiKey,i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature,N,wt,le,m.developerPrompt,m.domainPrompt,m.fewShotExamples,m.schemaNotes,m.systemPrompt,it.domain,it.id]),Bn=x.useCallback(async(a,c)=>{if(Cs(a)){const y=Tc(a);if(ee&&ee.job_id===y){const A=ro(ee,c);Re(a),O(A.caseId),ve(A.dialog);return}ve(null);return}Dn(!0);try{const y=await ke.loadAutoRunCaseDialog(a,c);ve(y)}catch(y){const A=y instanceof Error?y.message:String(y);be(`Диалог кейса: ${A}`),ve(null),le(`Dialog load error for ${a}/${c}: ${A}`)}finally{Dn(!1)}},[ee,le]),It=x.useCallback(async(a,c)=>{if(Cs(a)){const y=Tc(a);if(ee&&ee.job_id===y){const A=ro(ee,c??ht);Re(a),O(A.caseId),te(A.detail),ve(A.dialog);return}Re(a),O(""),te(null),ve(null);return}On(!0);try{const y=await ke.loadAutoRunDetail(a);te(y);const A=(c&&(c===ht||y.cases.some(he=>he.case_id===c))?c:"")||(y.cases.length>0?ht:"")||"";Re(a),O(A),A?await Bn(a,A):ve(null)}catch(y){const A=y instanceof Error?y.message:String(y);be(`Детализация прогона: ${A}`),te(null),ve(null),le(`Run detail load error for ${a}: ${A}`)}finally{On(!1)}},[ee,Bn,le]),Qt=x.useCallback(async a=>{gn(!0),be("");try{const c=await ke.loadAutoRunsHistory({from:ol(I.fromLocal),to:ol(I.toLocal),target:I.target,mode:I.mode,use_mock:I.useMock,prompt_contains:I.promptContains.trim()||void 0,limit:I.limit});if(Ae(c),c.items.length===0){Re(""),O(""),te(null),ve(null);return}const y=a?.keepSelection??!0,A=a?.preferredRunId??"",he=a?.preferredCaseId??"",Be=y&&A&&c.items.some(an=>an.run_id===A)?A:c.items[0].run_id;await It(Be,y?he:void 0),jt()}catch(c){const y=c instanceof Error?c.message:String(c);be(`История прогонов: ${y}`),le(`History load error: ${y}`)}finally{gn(!1)}},[I.fromLocal,I.limit,I.mode,I.promptContains,I.target,I.toLocal,I.useMock,jt,It,le]),Wt=x.useCallback(()=>{Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null)},[]),tr=x.useCallback(async a=>{try{const c=await ke.loadEvalRunAsyncStatus(a);Pe(c.job);const y=al(a);if(me===y){const A=ro(c.job,pe||ht);te(A.detail),ve(A.dialog),O(A.caseId)}if(c.job.status==="completed"){Wt(),Xt(!1);const A=c.job.report_summary?.run_id??c.job.run_id;await Qt({keepSelection:!0,preferredRunId:A||me,preferredCaseId:ht}),await wt(),Pe(null);return}if(c.job.status==="failed"){Wt(),Xt(!1),be(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),le(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}Wt(),Ce.current=window.setTimeout(()=>{tr(a)},500)}catch(c){Wt(),Xt(!1);const y=c instanceof Error?c.message:String(c);be(`Запуск прогонов: ${y}`),le(`Autogen async status error: ${y}`)}},[wt,Qt,le,pe,me,Wt]),we=x.useCallback(async()=>{Wt(),Xt(!0),be("");try{const a=Rt;if(!a)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const c=Se.map(Sr=>Sr.trim()).filter(Sr=>Sr.length>0);if(c.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const y=I.useMock==="true",A=Wi(D),Be=(await ke.startEvalRunAsync({connection:i,prompts:m,promptVersion:f,mode:"single-pass-strict",caseSetFile:a.saved_case_set_file??void 0,useMock:y,evalTarget:"assistant_stage1",questions:c,analysisDate:A||void 0})).job;Pe(Be);const an=al(Be.job_id),Cn=ro(Be,ht);Re(an),O(Cn.caseId),te(Cn.detail),ve(Cn.dialog),le(`Запущен async-прогон job=${Be.job_id}, run_id=${Be.run_id}, вопросов=${c.length}`+(a.saved_case_set_file?`, base_case_set=${a.saved_case_set_file}`:"")+(A?`, analysis_date=${A}`:", analysis_date=current_state")),tr(Be.job_id)}catch(a){const c=a instanceof Error?a.message:String(a);be(`Запуск прогонов: ${c}`),le(`Autogen run error: ${c}`),Xt(!1)}},[D,f,i,Se,I.useMock,le,tr,m,Rt,Wt]),p=x.useCallback(a=>{if(a.role!=="assistant")return;const c=a.case_id??pe,y=a.case_message_index??a.message_index;lt({open:!0,caseId:c,caseMessageIndex:y,messageIndex:a.message_index,rating:a.annotation?.rating??3,comment:a.annotation?.comment??"",manualCaseDecision:a.annotation?.manual_case_decision??sl,annotationAuthor:a.annotation?.annotation_author??h.generatedBy,saving:!1,error:""})},[h.generatedBy,pe]),E=x.useCallback(a=>{lt(c=>c.saving&&!a?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:sl,annotationAuthor:h.generatedBy,saving:!1,error:""})},[h.generatedBy]),C=x.useCallback(async()=>{const a=me,c=ce.caseId,y=ce.caseMessageIndex;if(!(!a||!c||y<0)){if(Cs(a)){lt(A=>({...A,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ce.comment.trim()){lt(A=>({...A,error:"Добавьте комментарий."}));return}lt(A=>({...A,saving:!0,error:""}));try{await ke.saveAutoRunAnnotation({run_id:a,case_id:c,message_index:y,rating:ce.rating,comment:ce.comment.trim(),manual_case_decision:ce.manualCaseDecision,annotation_author:ce.annotationAuthor.trim()||void 0}),E({force:!0}),Promise.all([It(a,pe),Tt(),jt()]).catch(A=>{const he=A instanceof Error?A.message:String(A);be(`Обновление после комментария: ${he}`),le(`Comment refresh error: ${he}`)})}catch(A){lt(he=>({...he,saving:!1,error:A instanceof Error?A.message:String(A)}))}}},[E,ce.annotationAuthor,ce.caseId,ce.caseMessageIndex,ce.comment,ce.manualCaseDecision,ce.rating,Tt,jt,It,le,pe,me]),ne=x.useCallback(a=>a.role==="assistant",[]),Ke=x.useCallback(a=>a.role==="assistant"&&Xn.has(a.message_id),[Xn]),Hn=x.useCallback((a,c)=>{if(a.role!=="assistant")return;const y=ot.trim(),A=String(a.session_id??"").trim();if(!(y||A)){Et("Сначала получите ответ ассистента в активной сессии.");return}!y&&A&&yn(A);const Be=Xn.get(a.message_id)??null;Et(""),xt({open:!0,messageIndex:c,rating:Be?.rating??3,comment:Be?.comment??"",annotationAuthor:Be?.annotation_author??"manual_reviewer",saving:!1,error:""})},[Xn,ot]),Es=x.useCallback(async()=>{if(xe.messageIndex<0)return;if(!xe.comment.trim()){xt(y=>({...y,error:"Добавьте комментарий."}));return}const a=xn[xe.messageIndex]??null,c=ot.trim()||(a?.role==="assistant"?String(a.session_id??"").trim():"");if(!c){xt(y=>({...y,error:"Сессия ассистента не найдена."}));return}xt(y=>({...y,saving:!0,error:""}));try{const y=await ke.saveAssistantAnnotation({session_id:c,message_index:xe.messageIndex,rating:xe.rating,comment:xe.comment.trim(),annotation_author:xe.annotationAuthor.trim()||void 0});Nt(A=>{const he=[...A],Be=he.findIndex(an=>an.annotation_id===y.annotation.annotation_id);return Be>=0?he[Be]=y.annotation:he.unshift(y.annotation),he.sort((an,Cn)=>Date.parse(Cn.updated_at)-Date.parse(an.updated_at))}),At({force:!0})}catch(y){const A=y instanceof Error?y.message:String(y);xt(he=>({...he,saving:!1,error:A}))}},[xe.annotationAuthor,xe.comment,xe.messageIndex,xe.rating,xn,ot,At]),Ur=x.useCallback(a=>{ae(c=>c.map(y=>y.annotation_id===a.annotation_id?{...y,...a}:y)),ve(c=>c&&{...c,annotations:c.annotations.map(y=>y.annotation_id===a.annotation_id?a:y),messages:c.messages.map(y=>!y.annotation||y.annotation.annotation_id!==a.annotation_id?y:{...y,commented:!0,annotation:a})})},[]),wn=x.useCallback(async(a,c)=>{if(a.annotation_id){if(Cs(a.run_id)){be("Статус выполнения можно менять только для завершённых прогонов.");return}Bt(a.annotation_id);try{const y=await ke.updateAutoRunAnnotation({annotation_id:a.annotation_id,resolved:c,resolved_by:h.generatedBy||void 0});Ur(y.annotation),jt()}catch(y){const A=y instanceof Error?y.message:String(y);be(`Смена статуса кейса: ${A}`),le(`Annotation resolve toggle error: ${A}`)}finally{Bt("")}}},[Ur,h.generatedBy,jt,le]),jn=x.useCallback(async a=>{Fe(a.annotation_id),await It(a.run_id,a.case_id),oe?.items.some(c=>c.run_id===a.run_id)||be("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[oe?.items,It]);x.useEffect(()=>{Mt.current||(Mt.current=!0,Qt({keepSelection:!1}),wt(),Fr(),jt())},[wt,Fr,Qt,jt]),x.useEffect(()=>{Mt.current&&Tt()},[_e,Tt]),x.useEffect(()=>{Fe(a=>Vt.length===0?"":Vt.some(c=>c.annotation_id===a)?a:Vt[0].annotation_id)},[Vt]),x.useEffect(()=>{fe(a=>J.length===0?"":a&&J.some(c=>c.generation_id===a)?a:J[0].generation_id)},[J]),x.useEffect(()=>{if(!Rt){ye([]);return}ye([...Rt.questions])},[Rt?.generation_id]),x.useEffect(()=>{vt(String(I.limit))},[I.limit]),x.useEffect(()=>{yt(String(h.count))},[h.count]),x.useEffect(()=>{if(!ot.trim()){Nt([]);return}Un(ot)},[ot,Un]),x.useEffect(()=>{if(!ee)return;const a=al(ee.job_id);if(me!==a)return;const c=ro(ee,pe||ht);te(c.detail),ve(c.dialog),O(c.caseId)},[ee,pe,me]),x.useEffect(()=>()=>{Wt()},[Wt]),x.useEffect(()=>{W.length!==0&&k(a=>{let c=!1;const y={...a.personalityPrompts};for(const he of W)(typeof y[he.id]!="string"||y[he.id].trim().length===0)&&(y[he.id]=he.defaultPrompt,c=!0);let A=a.personalityId;return W.some(he=>he.id===a.personalityId)||(A=W[0].id,c=!0),c?{...a,personalityId:A,personalityPrompts:y}:a})},[W]),x.useEffect(()=>{const a=localStorage.getItem(Cc);if(a)try{const c=JSON.parse(a);if(c.filters){const y=c.filters;q(A=>({...A,...y,limit:typeof y.limit=="number"?Math.max(1,Math.min(500,y.limit)):A.limit}))}typeof c.analysisDate=="string"&&B(Wi(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&$n(Pc(c.autogenPersonalityPromptHeight)),c.autoGenSettings&&k(y=>{const A={...y.personalityPrompts},he=c.autoGenSettings?.personalityPrompts??{};for(const[an,Cn]of Object.entries(he))typeof Cn=="string"&&an.trim().length>0&&(A[an.trim()]=Cn);const Be=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():y.personalityId;return{...y,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"?c.autoGenSettings.mode:y.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):y.count,personalityId:Be,personalityPrompts:A,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:y.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:y.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&Oe(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&We(c.hideResolvedAnnotations)}catch{}},[]);const kn=x.useCallback(()=>{const a={filters:I,analysisDate:D,autogenPersonalityPromptHeight:Pt,autoGenSettings:{mode:h.mode,count:h.count,personalityId:h.personalityId,personalityPrompts:h.personalityPrompts,persistToEvalCases:h.persistToEvalCases,generatedBy:h.generatedBy},annotationDecisionFilter:_e,hideResolvedAnnotations:$e};localStorage.setItem(Cc,JSON.stringify(a))},[D,_e,h,Pt,I,$e]);return x.useEffect(()=>{const a=()=>{kn(),le("Сохранены настройки панели автопрогонов.")};return window.addEventListener(Nc,a),()=>{window.removeEventListener(Nc,a)}},[le,kn]),o.jsxs(Tn,{className:"autoruns-frame",title:"",hideHeader:!0,children:[o.jsxs("div",{className:"autoruns-columns",children:[o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Настройки"})}),o.jsx("h4",{children:"Настройки выборки"}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата с",o.jsx("input",{type:"datetime-local",value:I.fromLocal,onChange:a=>q(c=>({...c,fromLocal:a.target.value}))})]}),o.jsxs("label",{children:["Дата по",o.jsx("input",{type:"datetime-local",value:I.toLocal,onChange:a=>q(c=>({...c,toLocal:a.target.value}))})]}),o.jsxs("label",{children:["Целевой контур",o.jsxs("select",{value:I.target,onChange:a=>q(c=>({...c,target:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(oe?.available.targets??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Режим",o.jsxs("select",{value:I.mode,onChange:a=>q(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(oe?.available.modes??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Использовать mock",o.jsxs("select",{value:I.useMock,onChange:a=>q(c=>({...c,useMock:a.target.value})),children:[o.jsx("option",{value:"any",children:"любой"}),o.jsx("option",{value:"true",children:"да"}),o.jsx("option",{value:"false",children:"нет"})]})]}),o.jsxs("label",{children:["Лимит",o.jsx("input",{type:"number",min:1,max:500,value:Yn,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&vt(c)},onBlur:a=>ts(a.target.value),onKeyDown:a=>{a.key==="Enter"&&ts(a.target.value)}})]}),o.jsxs("label",{className:"full-width",children:["Версия промпта содержит",o.jsx("input",{value:I.promptContains,onChange:a=>q(c=>({...c,promptContains:a.target.value})),placeholder:"normalizer_v2_0_2 / address_query_runtime_v1",list:"autoruns-prompt-versions"})]})]}),o.jsx("datalist",{id:"autoruns-prompt-versions",children:(oe?.available.prompt_versions??[]).map(a=>o.jsx("option",{value:a},a))}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:en,onClick:()=>{Qt({keepSelection:!1})},children:en?"Обновляю...":"Применить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{q({...Vi,fromLocal:Mc()}),be("")},children:"Сбросить фильтры"})]}),o.jsx("h4",{children:"Контур генерации"}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Провайдер:"}),o.jsx("strong",{children:i.llmProvider})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Модель:"}),o.jsx("strong",{children:i.model||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт ассистента:"}),o.jsx("strong",{children:f})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт декомпозиции:"}),o.jsx("strong",{children:N})]})]}),o.jsx("h4",{children:"Автогенерация вопросов"}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Режим генерации",o.jsxs("select",{value:h.mode,onChange:a=>k(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"codex_creative",children:"codex_creative"}),o.jsx("option",{value:"qwen_seed",children:"qwen_seed"})]})]}),o.jsxs("label",{children:["Кол-во",o.jsx("input",{type:"number",min:1,max:200,value:Zr,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&yt(c)},onBlur:a=>ns(a.target.value),onKeyDown:a=>{a.key==="Enter"&&ns(a.target.value)}})]}),o.jsxs("label",{children:["Личность автогенерации",o.jsx("select",{value:h.personalityId,onChange:a=>k(c=>({...c,personalityId:a.target.value})),children:W.map(a=>o.jsx("option",{value:a.id,children:a.label},a.id))})]}),o.jsxs("label",{children:["Кто генерирует",o.jsx("input",{value:h.generatedBy,onChange:a=>k(c=>({...c,generatedBy:a.target.value})),placeholder:"manual_reviewer"})]}),o.jsxs("label",{className:"full-width",children:["Промпт личности",o.jsx("textarea",{className:"autoruns-personality-prompt",value:h.personalityPrompts[h.personalityId]??"",onChange:a=>k(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:a.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${Pt}px`},onMouseUp:er,onTouchEnd:er})]}),o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:h.persistToEvalCases,onChange:a=>k(c=>({...c,persistToEvalCases:a.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата анализа (срез)",o.jsx("input",{type:"date",value:D,onChange:a=>B(Wi(a.target.value))})]}),o.jsx("div",{className:"button-row",children:o.jsx("button",{type:"button",className:"tab",disabled:!D,onClick:()=>B(""),children:"Сбросить дату среза"})})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:In,onClick:()=>{bn()},children:In?"Генерирую...":"Сгенерировать пачку"}),o.jsx("button",{type:"button",className:"tab",disabled:hn,onClick:()=>{wt()},children:hn?"Обновляю...":"Обновить историю"}),o.jsx("button",{type:"button",className:"autoruns-run-launch-btn",disabled:fr||Se.length===0,onClick:()=>{we()},children:fr?"Запускаю...":"Запустить прогоны"})]}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{className:"full-width",children:["Кейс-сет для запуска",o.jsxs("select",{value:de,onChange:a=>fe(a.target.value),disabled:J.length===0,children:[J.length===0?o.jsx("option",{value:"",children:"нет генераций"}):null,J.map(a=>o.jsxs("option",{value:a.generation_id,children:[cr(a.created_at)," | ",a.mode," | ",a.count," | ",a.saved_case_set_file??"без файла"]},a.generation_id))]})]})}),o.jsxs("div",{className:"autoruns-generated-questions",children:[o.jsxs("div",{className:"autoruns-generated-questions-head",children:[o.jsxs("strong",{children:["Вопросы к запуску: ",Se.length]}),o.jsx("button",{type:"button",className:"tab",onClick:()=>ye([...Rt?.questions??[]]),disabled:!Rt,children:"Восстановить"})]}),Se.length===0?o.jsx("p",{className:"muted",children:"Список вопросов пуст. Сгенерируйте пачку или восстановите из выбранной генерации."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:Se.map((a,c)=>o.jsxs("div",{className:"autoruns-generated-question-item",children:[o.jsxs("span",{children:[c+1,". ",a]}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onClick:()=>ye(y=>y.filter((A,he)=>he!==c)),title:"Удалить вопрос из запуска","aria-label":"Удалить вопрос из запуска",children:"+"})]},`${c}-${a.slice(0,24)}`))})]}),o.jsx("p",{className:"muted",children:"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."}),o.jsxs("div",{className:"autoruns-autogen-list",children:[hn?o.jsx("p",{className:"muted",children:"Загружаю историю автогенераций..."}):null,!hn&&J.length===0?o.jsx("p",{className:"muted",children:"История автогенераций пока пустая."}):null,J.slice(0,30).map(a=>o.jsxs("article",{className:de===a.generation_id?"autoruns-autogen-item selected":"autoruns-autogen-item",onClick:()=>fe(a.generation_id),children:[o.jsxs("header",{children:[o.jsx("strong",{children:cr(a.created_at)}),o.jsx("span",{children:a.mode})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["id=",a.generation_id," | count=",a.count]}),o.jsxs("div",{className:"autoruns-run-meta",children:["домен=",a.domain??"общий",a.generated_by?` | автор=${a.generated_by}`:""]}),a.saved_case_set_file?o.jsxs("div",{className:"autoruns-run-meta",children:["кейс-сет=",a.saved_case_set_file]}):null,(a.questions??[]).length>0?o.jsx("p",{children:a.questions[0]}):null]},a.generation_id))]}),o.jsxs("details",{className:"autoruns-prompt-details",children:[o.jsx("summary",{children:"Копия активного промпта (только чтение)"}),o.jsxs("label",{children:["Системный",o.jsx("textarea",{readOnly:!0,value:m.systemPrompt})]}),o.jsxs("label",{children:["Разработчика",o.jsx("textarea",{readOnly:!0,value:m.developerPrompt})]}),o.jsxs("label",{children:["Доменный",o.jsx("textarea",{readOnly:!0,value:m.domainPrompt})]}),o.jsxs("label",{children:["Заметки по схеме",o.jsx("textarea",{readOnly:!0,value:m.schemaNotes})]}),o.jsxs("label",{children:["Примеры few-shot",o.jsx("textarea",{readOnly:!0,value:m.fewShotExamples})]})]}),vn?o.jsx("p",{className:"error-text",children:vn}):null]}),o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Выдача прогонов"})}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Всего"}),o.jsx("strong",{children:(oe?.stats.runs_total??0)+(ee?1:0)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний score"}),o.jsx("strong",{children:ll(oe?.stats.avg_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:oe?Rc(oe.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Блокеры"}),o.jsx("strong",{children:oe?.stats.blocking_runs??0})]})]}),o.jsxs("div",{className:"autoruns-run-list",children:[Sn.map(a=>o.jsxs("button",{type:"button",className:me===a.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{It(a.run_id)},children:[o.jsxs("div",{className:"autoruns-run-head",children:[o.jsx("strong",{children:cr(a.run_timestamp)}),o.jsx("span",{children:sm(a.eval_target)})]}),o.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[o.jsx("span",{children:a.run_id}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{ct(c,a.run_id)},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),ct(c,a.run_id))},title:"Скопировать run id","aria-label":`Скопировать run id ${a.run_id}`,children:o.jsx(im,{})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["режим=",a.mode??"нет данных"," | mock=",String(a.use_mock)]}),o.jsxs("div",{className:"autoruns-run-meta",children:["analysis_date=",a.analysis_date??"current_state"]}),a.llm_provider||a.model?o.jsxs("div",{className:"autoruns-run-meta",children:["llm=",a.llm_provider??"нет данных"," | модель=",a.model??"нет данных"]}):null,o.jsxs("div",{className:"autoruns-run-meta",children:["промпт=",a.prompt_version??"нет данных"]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["оценка: ",ll(a.score_index)]}),o.jsxs("span",{children:["закрыто/открыто: ",a.closed_cases,"/",a.open_cases]})]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["блокеры: ",a.blocking_failures]}),o.jsxs("span",{children:["качество: ",a.quality_failures]})]})]},a.run_id)),Sn.length===0?o.jsx("p",{className:"muted",children:"За выбранный диапазон прогонов нет."}):null]})]}),o.jsxs("section",{className:"autoruns-col",children:[o.jsxs("div",{className:"autoruns-col-header",children:[o.jsx("h3",{children:"Диалог прогона"}),o.jsxs("div",{className:"autoruns-dialog-toolbar",children:[o.jsxs("label",{children:["Прогон",o.jsx("select",{value:me,onChange:a=>{const c=a.target.value;It(c)},children:Sn.map(a=>o.jsxs("option",{value:a.run_id,children:[cr(a.run_timestamp)," | ",a.run_id]},a.run_id))})]}),o.jsxs("label",{children:["Кейс",o.jsxs("select",{value:pe,onChange:a=>{const c=a.target.value;O(c),me&&c&&Bn(me,c)},children:[(se?.cases.length??0)>0?o.jsx("option",{value:ht,children:"ВСЕ кейсы подряд"}):null,(se?.cases??[]).map(a=>o.jsxs("option",{value:a.case_id,children:[a.case_id," | ",a.status]},a.case_id))]})]})]})]}),o.jsxs("div",{className:"autoruns-case-list",children:[(se?.cases.length??0)>0?o.jsxs("button",{type:"button",className:pe===ht?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{O(ht),me&&Bn(me,ht)},children:[o.jsx("span",{children:"ВСЕ кейсы подряд"}),o.jsx("span",{children:se?.cases.length})]},ht):null,(se?.cases??[]).map(a=>o.jsxs("button",{type:"button",className:pe===a.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{O(a.case_id),me&&Bn(me,a.case_id)},children:[o.jsx("span",{children:a.case_id}),o.jsxs("span",{children:[a.status,a.commented_count>0?` | комм=${a.commented_count}`:""]})]},a.case_id))]}),o.jsxs("div",{className:"autoruns-dialog-view",children:[pr||mr?o.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!pr&&!mr&&(Te?.messages.length??0)===0?o.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(Te?.messages??[]).map((a,c)=>{const y=a.role==="assistant"?"assistant":"user";return o.jsxs("article",{className:`autoruns-msg ${y}`,children:[o.jsxs("header",{children:[o.jsx("strong",{children:y==="assistant"?"Система":"Модель/вопрос"}),o.jsxs("div",{className:"autoruns-msg-head-actions",children:[a.case_id?o.jsx("span",{className:"autoruns-msg-case-tag",children:a.case_id}):null,o.jsx("span",{children:a.created_at?cr(a.created_at):"нет данных"}),y==="assistant"&&!Cs(me)?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:a.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>p(a),title:"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b","aria-label":"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b",children:o.jsx(lm,{commented:a.commented})}),a.annotation?o.jsx("button",{type:"button",className:a.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{wn(a.annotation,!a.annotation.resolved)},disabled:hr===a.annotation.annotation_id,title:a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Ic,{resolved:a.annotation.resolved})}):null]}):null]})]}),o.jsx("p",{children:a.text}),y==="assistant"&&a.annotation?o.jsxs("div",{className:"autoruns-msg-annotation",children:[o.jsx("strong",{children:qi(a.annotation.rating)}),o.jsx("span",{children:a.annotation.comment}),o.jsxs("span",{className:"muted",children:[a.annotation.manual_case_decision,a.annotation.annotation_author?` | ${a.annotation.annotation_author}`:""]})]}):null,(a.trace_id||a.reply_type)&&o.jsxs("footer",{children:[a.trace_id?o.jsxs("span",{children:["trace=",a.trace_id]}):null,a.reply_type?o.jsxs("span",{children:["reply_type=",a.reply_type]}):null]})]},a.message_id??`${y}-${c}`)})]})]}),j?o.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:o.jsx(Hc,{sessionId:ot,conversation:xn,inputValue:zn,onInputChange:on,selectedContextChip:Ht,onSelectContextChip:gt,onClearContextChip:()=>gt(null),useMock:Jn,onUseMockChange:qe,onSend:Ns,onClear:St,busy:gr,statusText:vr,errorMessage:yr,showCommentAction:!0,onCommentAssistantMessage:Hn,isAssistantMessageCommented:Ke,canCommentAssistantMessage:ne})}):null,T?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Режим декомпозиции"})}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"кейс:"}),o.jsx("strong",{children:Fn?.case_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"домен:"}),o.jsx("strong",{children:Fn?.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"класс запроса:"}),o.jsx("strong",{children:Fn?.query_class??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"trace:"}),o.jsx("strong",{children:Fn?.trace_id??"нет данных"})]})]}),o.jsx("h4",{children:"Шаги декомпозиции"}),(Te?.decomposition.length??0)>0?o.jsx("ol",{className:"autoruns-decomposition-list",children:(Te?.decomposition??[]).map((a,c)=>o.jsx("li",{children:a},`${c}-${a.slice(0,24)}`))}):o.jsx("p",{className:"muted",children:"В логах кейса нет явной декомпозиции."})]}):null,F?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Прогресс / регресс"})}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Последний score"}),o.jsx("strong",{children:ll(oe?.stats.latest_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Предыдущий"}),o.jsx("strong",{children:ll(oe?.stats.previous_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:oe?Rc(oe.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Пробелы качества"}),o.jsx("strong",{children:oe?.stats.quality_gap_runs??0})]})]}),o.jsx("h4",{children:"Покрытие доменов (история)"}),Ac(oe?.stats.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),Ac(se?.coverage.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),Zt?o.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,Zt?null:o.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(Ut?.post_analysis.stats.by_queue??{}).map(([a,c])=>o.jsxs("div",{children:[o.jsx("span",{children:a}),o.jsx("strong",{children:c})]},a))}),o.jsxs("div",{className:"autoruns-autogen-list",children:[(Ut?.post_analysis.recommended_regression_candidates??[]).slice(0,12).map(a=>o.jsxs("article",{className:"autoruns-autogen-item",children:[o.jsxs("header",{children:[o.jsx("strong",{children:a.manual_case_decision}),o.jsxs("span",{children:[a.rating,"/5"]})]}),o.jsxs("div",{className:"autoruns-run-meta",children:[a.domain??"неизвестно"," / ",a.query_class??"неизвестно"]}),o.jsx("p",{children:a.comment})]},a.annotation_id)),!Zt&&(Ut?.post_analysis.recommended_regression_candidates.length??0)===0?o.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Y?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Комментарии"})}),o.jsx("h4",{children:"Размеченные ответы"}),o.jsxs("div",{className:"autoruns-comment-filter-row",children:[o.jsxs("label",{children:["Фильтр решений",o.jsxs("select",{value:_e,onChange:a=>Oe(a.target.value),children:[o.jsx("option",{value:"all",children:"все"}),(st.length>0?st:Je?.enum??[]).map(a=>o.jsx("option",{value:a,children:String(Je?.labels?.[a]??a)},a))]})]}),o.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>We(a=>!a),children:$e?"Показать выполненные":"Скрыть выполненные"})]}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Комментариев"}),o.jsx("strong",{children:_t.length})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний рейтинг"}),o.jsx("strong",{children:_r===null?"нет данных":`${_r.toFixed(2)} / 5`})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Последний"}),o.jsx("strong",{children:_t.length>0?cr(_t[0].updated_at):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Статус"}),o.jsx("strong",{children:tn?"обновляю":"готово"})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:tn,onClick:()=>{Tt()},children:tn?"Обновляю...":"Обновить список"}),o.jsx("button",{type:"button",className:"tab",disabled:Zt,onClick:()=>{jt()},children:Zt?"Идет пост-анализ...":"Обновить пост-анализ"})]}),o.jsxs("div",{className:"autoruns-comments-list",children:[tn?o.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!tn&&_t.length===0?o.jsx("p",{className:"muted",children:G.length===0&&sn.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,_t.map(a=>{if(a.source==="assistant_live"){const y=a.assistant;return o.jsxs("article",{className:"autoruns-comment-item",children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:qi(y.rating)}),o.jsx("div",{className:"autoruns-comment-head-actions",children:o.jsx("span",{children:cr(y.updated_at)})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",y.session_id]}),o.jsxs("div",{className:"autoruns-run-meta",children:["msg=",y.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",y.annotation_author?` | author=${y.annotation_author}`:""]}),y.context.question_text?o.jsxs("p",{children:["Q: ",y.context.question_text]}):null,y.context.answer_text?o.jsxs("p",{children:["A: ",y.context.answer_text]}):null,o.jsx("p",{children:y.comment})]},a.key)}const c=a.autorun;return o.jsxs("article",{className:Ie===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{jn(c)},role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),jn(c))},children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:qi(c.rating)}),o.jsxs("div",{className:"autoruns-comment-head-actions",children:[o.jsx("span",{children:cr(c.updated_at)}),o.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:y=>{y.preventDefault(),y.stopPropagation(),wn(c,!c.resolved)},disabled:hr===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(Ic,{resolved:c.resolved})})]})]}),o.jsx("div",{className:"autoruns-run-meta",children:c.run_id}),o.jsxs("div",{className:"autoruns-run-meta",children:["case=",c.case_id," | msg=",c.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["decision=",c.manual_case_decision,c.annotation_author?` | author=${c.annotation_author}`:""]}),c.resolved_at?o.jsxs("div",{className:"autoruns-run-meta",children:["выполнено",": ",cr(c.resolved_at),c.resolved_by?` | by=${c.resolved_by}`:""]}):null,c.context.question_text?o.jsxs("p",{children:["Q: ",c.context.question_text]}):null,c.context.answer_text?o.jsxs("p",{children:["A: ",c.context.answer_text]}):null,o.jsx("p",{children:c.comment})]},a.key)})]}),z?o.jsxs(o.Fragment,{children:[o.jsx("h4",{children:"Тех-контекст брака"}),o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"trace:"}),o.jsx("strong",{children:z.technical_context.trace_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"reply_type:"}),o.jsx("strong",{children:z.technical_context.reply_type??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"domain:"}),o.jsx("strong",{children:z.technical_context.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"query_class:"}),o.jsx("strong",{children:z.technical_context.query_class??"нет данных"})]})]}),o.jsx("h4",{children:"JSON разбор"}),o.jsx(Yt,{value:{annotation_id:z.annotation_id,run_id:z.run_id,case_id:z.case_id,message_index:z.message_index,rating:z.rating,comment:z.comment,manual_case_decision:z.manual_case_decision,annotation_author:z.annotation_author,resolved:z.resolved,resolved_at:z.resolved_at,resolved_by:z.resolved_by,context:z.context,technical_context:z.technical_context,case_summary:z.case_summary?{case_id:z.case_summary.case_id,domain:z.case_summary.domain,query_class:z.case_summary.query_class,checks:z.case_summary.checks,metric_subscores:z.case_summary.metric_subscores}:null}})]}):null]}):null]}),xe.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&At()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),$r?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:$r.text})]}):null,Me?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:Me.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа ассистента",children:[1,2,3,4,5].map(a=>o.jsx("button",{type:"button",className:xe.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>xt(c=>({...c,rating:a})),disabled:xe.saving,"aria-label":`Оценка ${a}`,children:xe.rating>=a?"●":"○"},a))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:xe.annotationAuthor,onChange:a=>xt(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:xe.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:xe.comment,onChange:a=>xt(c=>({...c,comment:a.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:xe.saving})]}),xe.error?o.jsx("p",{className:"error-text",children:xe.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{Es()},disabled:xe.saving,children:xe.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>At(),disabled:xe.saving,children:"Отмена"})]})]})}):null,ce.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&E()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу системы"}),o.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),zr?o.jsxs(o.Fragment,{children:[o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:xr?.text??"Вопрос в диалоге не найден."})]}),o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ системы"}),o.jsx("p",{className:"autoruns-comment-quote",children:zr.text})]})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(a=>o.jsx("button",{type:"button",className:ce.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>lt(c=>({...c,rating:a})),disabled:ce.saving,"aria-label":`Оценка ${a}`,children:ce.rating>=a?"●":"○"},a))}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Решение по кейсу",o.jsx("select",{value:ce.manualCaseDecision,onChange:a=>lt(c=>({...c,manualCaseDecision:a.target.value})),disabled:ce.saving,children:(st.length>0?st:Je?.enum??[sl]).map(a=>o.jsx("option",{value:a,children:String(Je?.labels?.[a]??a)},a))})]}),o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ce.annotationAuthor,onChange:a=>lt(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ce.saving})]})]}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ce.comment,onChange:a=>lt(c=>({...c,comment:a.target.value})),placeholder:"Почему ответ бракованный, что именно пошло не так, какие технические детали проверить.",rows:4,disabled:ce.saving})]}),ce.error?o.jsx("p",{className:"error-text",children:ce.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{C()},disabled:ce.saving,children:ce.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>E(),disabled:ce.saving,children:"Отмена"})]})]})}):null]})}const il="http://127.0.0.1:1234/v1",Lc="https://api.openai.com/v1",cl="qwen2.5-14b-instruct-1m",ea="unsloth/qwen3-30b-a3b-instruct-2507",um=[{value:cl,label:"Qwen2.5 14B Instruct 1M"},{value:ea,label:"Qwen3 30B A3B Instruct 2507"}];function cm(i){return i.llmProvider!=="local"?"openai":i.model===ea?"local_qwen3":i.model===cl?"local_qwen25":"local_custom"}function dm(i,m){const f=new Map;if(m)for(const N of um)f.set(N.value,N);for(const N of i)f.has(N)||f.set(N,{value:N,label:N});return Array.from(f.values())}function Oc({value:i,modelOptions:m,modelsBusy:f,onChange:N,onReloadModels:j,onTestConnection:T,onSaveLocalConfig:F,lastStatus:Y,busy:U}){const I=i.llmProvider==="local",q=cm(i),D=dm(m,I),B=D.some(G=>G.value===i.model),[oe,Ae]=x.useState(String(i.temperature)),[se,te]=x.useState(String(i.maxOutputTokens));x.useEffect(()=>{Ae(String(i.temperature))},[i.temperature]),x.useEffect(()=>{te(String(i.maxOutputTokens))},[i.maxOutputTokens]);const Te=G=>{const ae=G.replace(",",".").trim();if(!ae){Ae(String(i.temperature));return}const _e=Number(ae);if(!Number.isFinite(_e)){Ae(String(i.temperature));return}N({...i,temperature:_e}),Ae(String(_e))},ve=G=>{const ae=G.trim();if(!ae){te(String(i.maxOutputTokens));return}const _e=Number.parseInt(ae,10);if(!Number.isFinite(_e)||_e<=0){te(String(i.maxOutputTokens));return}N({...i,maxOutputTokens:_e}),te(String(_e))};return o.jsxs(Tn,{title:"LLM Connection",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:o.jsx("span",{className:"status-chip",children:Y||"Status: not checked"}),children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{children:["Provider",o.jsxs("select",{value:q,onChange:G=>{const ae=G.target.value;if(ae==="openai"){N({...i,llmProvider:"openai",baseUrl:Lc});return}if(ae==="local_qwen25"){N({...i,llmProvider:"local",model:cl,baseUrl:il});return}if(ae==="local_qwen3"){N({...i,llmProvider:"local",model:ea,baseUrl:il});return}N({...i,llmProvider:"local",model:i.llmProvider==="local"?i.model:cl,baseUrl:il})},children:[o.jsx("option",{value:"openai",children:"OpenAI (token)"}),o.jsx("option",{value:"local_qwen25",children:"Qwen2.5 14B Instruct 1M (Local LM Studio)"}),o.jsx("option",{value:"local_qwen3",children:"Qwen3 30B A3B Instruct 2507 (Local LM Studio)"}),o.jsx("option",{value:"local_custom",children:"Local custom (LM Studio / OpenAI-compatible)"})]})]}),o.jsxs("label",{children:["Model",o.jsxs("select",{value:B?i.model:"__manual__",onChange:G=>{const ae=G.target.value;ae!=="__manual__"&&N({...i,model:ae})},children:[o.jsx("option",{value:"__manual__",children:"Manual input"}),D.map(G=>o.jsx("option",{value:G.value,children:G.label},G.value))]})]}),o.jsxs("label",{children:["Model ID (manual / current)",o.jsx("input",{value:i.model,onChange:G=>N({...i,model:G.target.value}),placeholder:"qwen2.5-14b-instruct-1m or unsloth/qwen3-30b-a3b-instruct-2507"})]}),I?null:o.jsxs("label",{className:"full-width",children:["OpenAI API Key",o.jsx("input",{type:"password",value:i.apiKey,onChange:G=>N({...i,apiKey:G.target.value}),placeholder:"sk-..."})]}),o.jsxs("label",{className:I?"full-width":void 0,children:[I?"Local server base URL":"Base URL",o.jsx("input",{value:i.baseUrl,onChange:G=>N({...i,baseUrl:G.target.value}),placeholder:I?il:Lc})]}),o.jsxs("label",{children:["Temperature",o.jsx("input",{type:"number",step:"0.1",value:oe,onChange:G=>Ae(G.target.value),onBlur:G=>Te(G.target.value),onKeyDown:G=>{G.key==="Enter"&&Te(G.target.value)}})]}),o.jsxs("label",{children:["Max output tokens",o.jsx("input",{type:"number",value:se,onChange:G=>te(G.target.value),onBlur:G=>ve(G.target.value),onKeyDown:G=>{G.key==="Enter"&&ve(G.target.value)}})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>F(),children:"Save local config"}),o.jsx("button",{type:"button",onClick:()=>j(),disabled:U||f,children:f?"Loading models...":"Load model list"}),o.jsx("button",{type:"button",onClick:()=>T(),disabled:U,children:U?"Checking...":"Test connection"})]})]})}function fm({items:i,onRefresh:m,onOpenTrace:f}){return o.jsx(Tn,{title:"История нормализаций",subtitle:"Короткий вопрос, confidence, route hint и статус валидации.",actions:o.jsx("button",{type:"button",onClick:()=>m(),children:"Обновить"}),children:o.jsxs("div",{className:"history-list",children:[i.length===0?o.jsx("p",{className:"muted",children:"История пока пустая."}):null,i.map(N=>o.jsxs("button",{type:"button",className:"history-item",onClick:()=>f(N.trace_id),children:[o.jsxs("div",{className:"history-row",children:[o.jsx("strong",{children:N.route_hint??"route: n/a"}),o.jsx("span",{children:N.validation_passed?"schema: ok":"schema: fail"})]}),o.jsx("p",{children:N.question_short}),o.jsxs("div",{className:"history-row",children:[o.jsx("span",{children:N.model}),o.jsx("span",{children:new Date(N.timestamp).toLocaleString("ru-RU")})]})]},N.trace_id))]})})}function dr(i){return i==null||i===""?"—":String(i)}function mm({result:i}){return o.jsx(Tn,{title:"Runtime метрики",subtitle:"trace_id, токены, latency и статус валидации.",children:o.jsxs("div",{className:"metrics-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"trace_id"}),o.jsx("strong",{children:dr(i?.trace_id)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"request_started_at"}),o.jsx("strong",{children:dr(i?new Date(Date.now()-i.latency_ms).toISOString():null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"request_finished_at"}),o.jsx("strong",{children:dr(i?new Date().toISOString():null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"latency_ms"}),o.jsx("strong",{children:dr(i?.latency_ms)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"input_tokens"}),o.jsx("strong",{children:dr(i?.usage?.input_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"output_tokens"}),o.jsx("strong",{children:dr(i?.usage?.output_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"total_tokens"}),o.jsx("strong",{children:dr(i?.usage?.total_tokens)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"validation_status"}),o.jsx("strong",{children:i?.validation?.passed?"passed":"failed"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"prompt_version"}),o.jsx("strong",{children:dr(i?.prompt_version)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"schema_version"}),o.jsx("strong",{children:dr(i?.schema_version)})]})]})})}const pm={normalized:"Normalized JSON",fragments:"Fragment View",scope:"Scope View",flags:"Flags View",route:"Route Simulation",raw:"Raw model output",validation:"Validation",logs:"Logs"};function hm(i){return i&&typeof i=="object"?i:null}function gm({tab:i,onTabChange:m,result:f,appLogs:N}){const j=["normalized","fragments","scope","flags","route","raw","validation","logs"],T=hm(f?.normalized),F=String(T?.schema_version??""),Y=F==="normalized_query_v2"||F==="normalized_query_v2_0_1"||F==="normalized_query_v2_0_2",U=Y?{fragments:T?.fragments??[],discarded_fragments:T?.discarded_fragments??[]}:{note:"Fragment View доступен для normalized_query_v2."},I=Y?{message_in_scope:T?.message_in_scope??null,scope_confidence:T?.scope_confidence??null,contains_multiple_tasks:T?.contains_multiple_tasks??null,global_notes:T?.global_notes??null}:{note:"Scope View доступен для normalized_query_v2."},q=Y?Array.isArray(T?.fragments)?(T?.fragments).map(D=>({fragment_id:D.fragment_id??null,domain_relevance:D.domain_relevance??null,candidate_labels:D.candidate_labels??[],execution_readiness:D.execution_readiness??null,clarification_reason:D.clarification_reason??null,soft_assumption_used:D.soft_assumption_used??[],route_status:D.route_status??null,no_route_reason:D.no_route_reason??null,flags:D.flags??{}})):[]:{note:"Flags View доступен для normalized_query_v2."};return o.jsxs(Tn,{title:"Выходные данные",subtitle:"Structured output и диагностические вкладки.",children:[o.jsx("div",{className:"tab-row",children:j.map(D=>o.jsx("button",{type:"button",className:i===D?"tab active":"tab",onClick:()=>m(D),children:pm[D]},D))}),i==="normalized"?o.jsx(Yt,{value:f?.normalized??{note:"Нет данных."}}):null,i==="fragments"?o.jsx(Yt,{value:U}):null,i==="scope"?o.jsx(Yt,{value:I}):null,i==="flags"?o.jsx(Yt,{value:q}):null,i==="route"?o.jsx(Yt,{value:f?.route_hint_summary??{note:"Нет данных."}}):null,i==="raw"?o.jsx(Yt,{value:f?.raw_model_output??{note:"Нет данных."}}):null,i==="validation"?o.jsx(Yt,{value:f?.validation??{note:"Нет данных."}}):null,i==="logs"?o.jsx(Yt,{value:N}):null]})}function Dc({value:i,onChange:m,presets:f,selectedPresetId:N,onSelectPreset:j,onLoadPreset:T,onSavePreset:F,onResetDefaults:Y,onDiffPrevious:U,presetName:I,onPresetNameChange:q,diffSummary:D}){return o.jsxs(Tn,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:[o.jsxs("div",{className:"prompt-manager-grid",children:[o.jsxs("label",{children:["Системный prompt",o.jsx("textarea",{value:i.systemPrompt,onChange:B=>m({...i,systemPrompt:B.target.value}),rows:6})]}),o.jsxs("label",{children:["Developer / Instruction prompt",o.jsx("textarea",{value:i.developerPrompt,onChange:B=>m({...i,developerPrompt:B.target.value}),rows:6})]}),o.jsxs("label",{children:["Domain prompt",o.jsx("textarea",{value:i.domainPrompt,onChange:B=>m({...i,domainPrompt:B.target.value}),rows:6})]}),o.jsxs("label",{children:["Schema notes",o.jsx("textarea",{value:i.schemaNotes,onChange:B=>m({...i,schemaNotes:B.target.value}),rows:6})]}),o.jsxs("label",{className:"full-width",children:["Few-shot examples",o.jsx("textarea",{value:i.fewShotExamples,onChange:B=>m({...i,fewShotExamples:B.target.value}),rows:8})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("select",{value:N,onChange:B=>j(B.target.value),children:[o.jsx("option",{value:"",children:"Выберите preset..."}),f.map(B=>o.jsx("option",{value:B.id,children:B.name},B.id))]}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Загрузить preset"}),o.jsx("input",{value:I,onChange:B=>q(B.target.value),placeholder:"Имя для сохранения"}),o.jsx("button",{type:"button",onClick:()=>F(),children:"Сохранить preset"}),o.jsx("button",{type:"button",onClick:()=>U(),children:"Diff с предыдущим"}),o.jsx("button",{type:"button",onClick:()=>Y(),children:"Сбросить к default"})]}),D?o.jsx("p",{className:"diff-summary",children:D}):null]})}function vm({value:i,onChange:m,onApplyBatchFormat:f,onNormalize:N,busy:j,useMock:T,onUseMockChange:F,errorMessage:Y}){return o.jsxs(Tn,{title:"Запрос пользователя",subtitle:"NDC semantic front-end: нормализуем, но не отвечаем за бухгалтерскую суть.",children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{className:"full-width",children:["Raw user question",o.jsx("textarea",{value:i.userQuestion,onChange:U=>m({...i,userQuestion:U.target.value}),rows:6,placeholder:"Например: По каким покупателям у нас на конец июня висят отгрузки без оплаты..."})]}),o.jsxs("label",{className:"full-width",children:["Batch queries (`;` separator)",o.jsx("textarea",{value:i.batchQuestionsRaw,onChange:U=>m({...i,batchQuestionsRaw:U.target.value}),onBlur:()=>f(),rows:8,placeholder:"Вопрос 1; Вопрос 2; Вопрос 3"})]}),o.jsxs("label",{children:["Optional period context",o.jsx("input",{value:i.periodHint,onChange:U=>m({...i,periodHint:U.target.value})})]}),o.jsxs("label",{children:["Optional business context",o.jsx("input",{value:i.businessContext,onChange:U=>m({...i,businessContext:U.target.value})})]}),o.jsxs("label",{children:["Optional expected route (eval)",o.jsx("input",{value:i.expectedRoute,onChange:U=>m({...i,expectedRoute:U.target.value})})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:T,onChange:U=>F(U.target.checked)}),"Mock-режим (без вызова OpenAI)"]}),o.jsx("button",{type:"button",onClick:()=>f(),disabled:j||!i.batchQuestionsRaw.trim(),children:"Применить `;` в переносы"}),o.jsx("button",{type:"button",onClick:()=>N(!1),disabled:j||!i.userQuestion.trim(),children:j?"Нормализуем...":"Normalize"}),o.jsx("button",{type:"button",onClick:()=>N(!0),disabled:j||!i.userQuestion.trim(),children:j?"Сохраняем...":"Normalize + Save as test case"})]}),Y?o.jsx("p",{className:"error-text",children:Y}):null]})}function ym({runs:i,selectedRunId:m,onSelectRun:f,onStartRun:N,onFinishRun:j,onRefreshRuns:T,onRunEval:F,onCopyEvalReport:Y,evalBusy:U,traceItems:I,evalReport:q}){return o.jsxs(Tn,{title:"NDC Run Monitor",subtitle:"Важно: кнопка Запустить run создает только run-сущность. Кнопка eval запускает batch-проверку normalizer v2.0.2.",children:[o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>N(),children:"Запустить run"}),o.jsx("button",{type:"button",onClick:()=>j(),disabled:!m,children:"Завершить выбранный run"}),o.jsx("button",{type:"button",onClick:()=>T(),children:"Обновить runs"}),o.jsx("button",{type:"button",onClick:()=>F(),disabled:U,children:U?"Идет eval v2.0.2...":"Запустить eval v2.0.2"})]}),o.jsxs("div",{className:"runtime-stack",children:[o.jsxs("div",{className:"runtime-runs",children:[i.map(D=>o.jsxs("button",{type:"button",className:m===D.runId?"history-item selected":"history-item",onClick:()=>f(D.runId),children:[o.jsxs("div",{className:"history-row",children:[o.jsx("strong",{children:D.status}),o.jsx("span",{children:D.runId})]}),o.jsxs("div",{className:"history-row",children:[o.jsx("span",{children:D.sessionId}),o.jsx("span",{children:new Date(D.updatedAt).toLocaleString("ru-RU")})]})]},D.runId)),i.length===0?o.jsx("p",{className:"muted",children:"Нет активных запусков."}):null]}),o.jsxs("div",{className:"runtime-details",children:[o.jsx("h3",{children:"Trace выбранного run"}),o.jsx(Yt,{value:I}),o.jsxs("div",{className:"eval-report-wrap",children:[o.jsx("h3",{style:{marginTop:12},children:"Отчет eval"}),o.jsx(Yt,{value:q??{note:"Eval пока не запускался"}}),o.jsx("button",{type:"button",className:"copy-cube-button",title:"Скопировать отчет eval",onClick:()=>Y(),children:"⧉"})]})]})]})]})}const xm={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},zc={systemPrompt:"Ты semantic-normalizer для бухгалтерского ассистента NDC. Возвращай только JSON по схеме normalized_query_v2_0_2.",developerPrompt:"Сначала делай decomposition сообщения на task fragments, затем определяй domain scope и route-critical flags. Для каждого fragment заполняй execution_readiness + route_status + no_route_reason. Если fragment routable, не оставляй его в no_route.",domainPrompt:"Контур: данные текущего предприятия в 1С/NDC. In-scope: документы, проводки, взаиморасчеты, остатки, периодное закрытие, аномалии и контрольные проверки. Out-of-scope: общая теория, законы и оффтоп.",schemaNotes:"schema_version: normalized_query_v2_0_2. Строгий JSON без дополнительных полей.",fewShotExamples:"Q: Проверь по поставщикам хвосты и разложи цепочку документов/оплат. => fragment in_scope, flags: multi_entity + chain_explanation. Q: Как вообще по ФСБУ? => out_of_scope/generic_accounting."},_m={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},Ki={colors:{backgroundRgb:"18, 18, 18",mainSurfaceRgb:"25, 25, 25",horizontalSurfaceRgb:"30, 30, 30",focusSurfaceRgb:"35, 35, 35",assistantChipRgb:"18, 18, 18",assistantChipHoverRgb:"44, 44, 44",assistantChipSelectedRgb:"167, 59, 255",assistantChipSelectedTextRgb:"240, 240, 240",activeRgb:"167, 59, 255",activeTextRgb:"240, 240, 240",textMainRgb:"240, 240, 240",textMutedRgb:"166, 166, 166",dangerRgb:"126, 126, 126",scrollbarTrackRgb:"20, 20, 20",scrollbarThumbRgb:"30, 30, 30",scrollbarThumbHoverRgb:"30, 50, 30"},layout:{modeColumnWidthPx:406,modeToggleWidthPx:188}},$c="ndc_normalizer_session_config_v1",Fc="ndc_autoruns_layout_config_v1",Sm="ndc-autoruns-save",Gi=["Анализ запроса","Получение данных","Подготовка ответа"],wm="assistant",Ji="normalizer_v2_0_2",Uc="address_query_runtime_v1",jm=["normalized","fragments","scope","flags","route","raw","validation","logs"],Yi="manual_reviewer";function km(i){return`[${new Date().toLocaleTimeString("ru-RU")}] ${i}`}function Cm(i,m){if(!m)return"Previous preset is not selected.";const N=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(j=>i[j]!==m[j]).map(j=>`${j}: ${Math.abs(i[j].length-m[j].length)} chars delta`);return N.length===0?"No changes against previous preset.":`Changed fields: ${N.length}. ${N.join(" | ")}`}function Nm(i,m){const f=i.trim();if(!f)return"";if(!m)return f;const N=f.toLowerCase(),j=m.anchor_text.trim(),T=j.toLowerCase();return T&&N.includes(T)?f:`По выбранному объекту "${j}": ${f}`}function Em(){const[i,m]=x.useState(xm),[f,N]=x.useState(zc),[j,T]=x.useState(_m),[F,Y]=x.useState(null),[U,I]=x.useState([]),[q,D]=x.useState([]),[B,oe]=x.useState("normalized"),[Ae,se]=x.useState(!1),[te,Te]=x.useState(!1),[ve,G]=x.useState([]),[ae,_e]=x.useState(""),[Oe,$e]=x.useState([]),[We,Je]=x.useState(""),[et,st]=x.useState("NDC custom preset"),[ie,Ie]=x.useState(null),[Fe,me]=x.useState(""),[Re,pe]=x.useState(!1),[O,W]=x.useState([]),[$,h]=x.useState(""),[k,J]=x.useState([]),[ue,de]=x.useState(!1),[fe,Se]=x.useState(null),[ye,ee]=x.useState(""),[Pe,Ut]=x.useState(wm),[Kn,In]=x.useState(!0),[Ln,fr]=x.useState(!0),[Xt,Zt]=x.useState(!0),[Gn,hn]=x.useState(!0),[bt,en]=x.useState(!0),[gn,mr]=x.useState(!0),[On,pr]=x.useState(!0),[Dn,tn]=x.useState(!0),[nn,hr]=x.useState(!0),[Bt,vn]=x.useState(!0),[be,ot]=x.useState(!0),[yn,xn]=x.useState(!0),[rn,sn]=x.useState(!0),[Nt,zn]=x.useState(!0),[on,Ht]=x.useState(!0),[gt,Jn]=x.useState(!0),[qe,gr]=x.useState(""),[_n,vr]=x.useState([]),[ln,yr]=x.useState(""),[Et,Yn]=x.useState(null),[vt,Zr]=x.useState(!1),[yt,Pt]=x.useState(""),[$n,ce]=x.useState(""),[lt,xe]=x.useState([]),[xt,Mt]=x.useState(!1),[Ce,it]=x.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:Yi,saving:!1,error:""}),Rt=x.useRef(!1),Fn=x.useRef(!1),Vt=x.useRef(!1);x.useEffect(()=>{const p=document.documentElement,{colors:E}=Ki;p.style.setProperty("--rgb-background",E.backgroundRgb),p.style.setProperty("--rgb-surface-main",E.mainSurfaceRgb),p.style.setProperty("--rgb-surface-horizontal",E.horizontalSurfaceRgb),p.style.setProperty("--rgb-surface-focus",E.focusSurfaceRgb),p.style.setProperty("--rgb-assistant-chip",E.assistantChipRgb),p.style.setProperty("--rgb-assistant-chip-hover",E.assistantChipHoverRgb),p.style.setProperty("--rgb-assistant-chip-selected",E.assistantChipSelectedRgb),p.style.setProperty("--rgb-assistant-chip-selected-text",E.assistantChipSelectedTextRgb),p.style.setProperty("--rgb-active",E.activeRgb),p.style.setProperty("--rgb-active-text",E.activeTextRgb),p.style.setProperty("--rgb-text-main",E.textMainRgb),p.style.setProperty("--rgb-text-muted",E.textMutedRgb),p.style.setProperty("--rgb-danger",E.dangerRgb),p.style.setProperty("--rgb-scrollbar-track",E.scrollbarTrackRgb),p.style.setProperty("--rgb-scrollbar-thumb",E.scrollbarThumbRgb),p.style.setProperty("--rgb-scrollbar-thumb-hover",E.scrollbarThumbHoverRgb),p.style.setProperty("--mode-column-width",`${Ki.layout.modeColumnWidthPx}px`),p.style.setProperty("--mode-toggle-width",`${Ki.layout.modeToggleWidthPx}px`)},[]);const z=p=>{D(E=>[km(p),...E].slice(0,300))};function zr(){let p=0;Pt(Gi[0]);const E=window.setInterval(()=>{p=Math.min(p+1,Gi.length-1),Pt(Gi[p])},650);return()=>window.clearInterval(E)}x.useEffect(()=>{(async()=>{const C=localStorage.getItem($c);if(C)try{const ne=JSON.parse(C);m(Ke=>({...Ke,llmProvider:ne.llmProvider==="local"?"local":"openai",model:ne.model??Ke.model,baseUrl:ne.baseUrl??Ke.baseUrl,temperature:ne.temperature??Ke.temperature,maxOutputTokens:ne.maxOutputTokens??Ke.maxOutputTokens}))}catch{}try{const ne=await ke.loadSharedConnectionConfig();ne.connection&&ne.connection.llmProvider==="local"&&(m(Ke=>({...Ke,llmProvider:"local",model:ne.connection?.model??Ke.model,baseUrl:ne.connection?.baseUrl??Ke.baseUrl,temperature:ne.connection?.temperature??Ke.temperature,maxOutputTokens:ne.connection?.maxOutputTokens??Ke.maxOutputTokens})),z(`Shared local LLM config loaded: ${ne.connection.model}`))}catch(ne){z(`Shared local config load error: ${ne instanceof Error?ne.message:String(ne)}`)}finally{Vt.current=!0}})();const E=localStorage.getItem(Fc);if(E)try{const C=JSON.parse(E);(C.uiMode==="assistant"||C.uiMode==="decomposition"||C.uiMode==="autoruns")&&Ut(C.uiMode),C.activeTab&&jm.includes(C.activeTab)&&oe(C.activeTab),typeof C.showAutorunsAssistantMode=="boolean"&&In(C.showAutorunsAssistantMode),typeof C.showAutorunsDecompositionMode=="boolean"&&fr(C.showAutorunsDecompositionMode),typeof C.showAutorunsProgressMode=="boolean"&&Zt(C.showAutorunsProgressMode),typeof C.showAutorunsCommentsMode=="boolean"&&hn(C.showAutorunsCommentsMode),typeof C.showAssistantConnectionMode=="boolean"&&en(C.showAssistantConnectionMode),typeof C.showAssistantPromptMode=="boolean"&&mr(C.showAssistantPromptMode),typeof C.showAssistantChatMode=="boolean"&&pr(C.showAssistantChatMode),typeof C.showAssistantCommentsMode=="boolean"&&tn(C.showAssistantCommentsMode),typeof C.showAssistantSamMode=="boolean"&&hr(C.showAssistantSamMode),typeof C.showDecompositionConnectionMode=="boolean"&&vn(C.showDecompositionConnectionMode),typeof C.showDecompositionPromptMode=="boolean"&&ot(C.showDecompositionPromptMode),typeof C.showDecompositionQueryMode=="boolean"&&xn(C.showDecompositionQueryMode),typeof C.showDecompositionOutputMode=="boolean"&&sn(C.showDecompositionOutputMode),typeof C.showDecompositionMetricsMode=="boolean"&&zn(C.showDecompositionMetricsMode),typeof C.showDecompositionHistoryMode=="boolean"&&Ht(C.showDecompositionHistoryMode),typeof C.showDecompositionRuntimeMode=="boolean"&&Jn(C.showDecompositionRuntimeMode),C.prompts&&(N(ne=>({...ne,...C.prompts})),Fn.current=!0)}catch{}xr(),Xn(),Me()},[]),x.useEffect(()=>{if(!Vt.current||i.llmProvider!=="local")return;const p=window.setTimeout(()=>{ke.saveSharedConnectionConfig(i).catch(E=>z(`Shared local config sync error: ${E instanceof Error?E.message:String(E)}`))},250);return()=>window.clearTimeout(p)},[i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature]);async function xr(){try{const p=await ke.loadHistory();I(p.items??[])}catch(p){z(`History load error: ${p instanceof Error?p.message:String(p)}`)}}async function Xn(){try{const E=(await ke.loadPresets()).presets??[];if($e(E),Fn.current){Rt.current=!0;return}if(Rt.current)return;const C=E.find(ne=>ne.prompt_version===Ji)??E.find(ne=>ne.id==="default-normalizer-v2_0_2");if(!C){Rt.current=!0,z(`Preset autoload skipped: ${Ji} not found.`);return}Je(C.id),Ie(f),N({systemPrompt:C.systemPrompt,developerPrompt:C.developerPrompt,domainPrompt:C.domainPrompt,schemaNotes:C.schemaNotes??"",fewShotExamples:C.fewShotExamples??""}),Rt.current=!0,z(`Preset autoloaded: ${C.name} (${C.prompt_version}).`)}catch(p){z(`Presets load error: ${p instanceof Error?p.message:String(p)}`)}}async function Me(){try{const p=await ke.listRuns();W(p.items??[])}catch(p){z(`Runs load error: ${p instanceof Error?p.message:String(p)}`)}}function $r(){if(localStorage.setItem($c,JSON.stringify({model:i.model,llmProvider:i.llmProvider,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})),i.llmProvider==="local"){ke.saveSharedConnectionConfig(i).then(()=>{z("Local config saved and synced to shared agent config (without API key).")}).catch(p=>{z(`Local config saved, but shared sync failed: ${p instanceof Error?p.message:String(p)}`)});return}z("Local config saved (without API key).")}function _t(){localStorage.setItem(Fc,JSON.stringify({uiMode:Pe,activeTab:B,showAutorunsAssistantMode:Kn,showAutorunsDecompositionMode:Ln,showAutorunsProgressMode:Xt,showAutorunsCommentsMode:Gn,showAssistantConnectionMode:bt,showAssistantPromptMode:gn,showAssistantChatMode:On,showAssistantCommentsMode:Dn,showAssistantSamMode:nn,showDecompositionConnectionMode:Bt,showDecompositionPromptMode:be,showDecompositionQueryMode:yn,showDecompositionOutputMode:rn,showDecompositionMetricsMode:Nt,showDecompositionHistoryMode:on,showDecompositionRuntimeMode:gt,prompts:f})),window.dispatchEvent(new CustomEvent(Sm)),z("UI layout and prompts saved.")}async function _r(){se(!0),ee("");try{const p=await ke.testConnection(i);p.provider==="local"?p.model_found===!0?(_e(`LOCAL OK - ${p.model}`),z(`Local model is available: ${p.model} (catalog size=${p.models_count??"n/a"}).`)):p.model_found===!1?(_e(`LOCAL OK, model not loaded - ${p.model}`),z(`Local server is reachable, but model '${p.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(_e(`LOCAL OK (model list unavailable) - ${p.model}`),z("Local server is reachable, but model catalog could not be verified.")):(_e(`OPENAI OK - ${p.model}`),z(`OpenAI connection ok: ${p.model}`))}catch(p){const E=p instanceof Error?p.message:String(p);_e("Connection error"),ee(`Test connection: ${E}`),z(`Test connection error: ${E}`)}finally{se(!1)}}async function Sn(){Te(!0);try{const E=(await ke.listModels(i)).models??[];G(E),E.length>0&&m(C=>C.model&&E.includes(C.model)?C:{...C,model:E[0]}),z(`Model catalog loaded (${i.llmProvider}): ${E.length} items.`)}catch(p){const E=p instanceof Error?p.message:String(p);z(`Load model list error: ${E}`)}finally{Te(!1)}}x.useEffect(()=>{G([])},[i.llmProvider,i.baseUrl]);async function le(p){se(!0),ee("");try{const E=await ke.normalize({connection:i,prompts:f,promptVersion:"normalizer_v2_0_2",query:{userQuestion:j.userQuestion,periodHint:j.periodHint,businessContext:j.businessContext,expectedRoute:j.expectedRoute},saveAsTestCase:p,useMock:Re});Y(E),oe("normalized"),z(`Normalize done: trace=${E.trace_id}, validation=${E.validation.passed?"passed":"failed"}`),xr()}catch(E){const C=E instanceof Error?E.message:String(E);ee(`Normalize: ${C}`),z(`Normalize error: ${C}`)}finally{se(!1)}}function Un(){const p=Oe.find(E=>E.id===We);if(!p){z("Preset is not selected.");return}Ie(f),N({systemPrompt:p.systemPrompt,developerPrompt:p.developerPrompt,domainPrompt:p.domainPrompt,schemaNotes:p.schemaNotes??"",fewShotExamples:p.fewShotExamples??""}),z(`Preset loaded: ${p.name}`)}async function At(){try{await ke.savePreset({name:et||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:f.systemPrompt,developerPrompt:f.developerPrompt,domainPrompt:f.domainPrompt,schemaNotes:f.schemaNotes,fewShotExamples:f.fewShotExamples}),z("Preset saved."),await Xn()}catch(p){z(`Preset save error: ${p instanceof Error?p.message:String(p)}`)}}function ct(){N(zc),z("Prompt panel reset to defaults.")}function es(){const p=Cm(f,ie);me(p),z(p)}function St(){const p=j.batchQuestionsRaw.split(";").map(E=>E.trim()).filter(Boolean).join(` + +`);p&&(T(E=>({...E,batchQuestionsRaw:p})),z("Batch field formatted: `;` converted to blank-line separators."))}async function Ns(p){try{const C=(await ke.loadTrace(p)).trace,ne=C.parsed_normalized_json??null;Y({trace_id:String(C.trace_id??p),ok:!!C.validation_result?.passed,normalized:ne,route_hint_summary:C.route_hint_summary??(ne?{route_hint:ne.route_hint??null,confidence:ne.confidence?.route_hint??null}:null),raw_model_output:C.raw_model_response??{},validation:C.validation_result??{passed:!1,errors:["validation not found"]},usage:C.usage??{input_tokens:0,output_tokens:0,total_tokens:0},latency_ms:Number(C.latency_ms??0),prompt_version:String(C.prompt_version??"unknown"),schema_version:String(C.schema_version??"unknown")}),oe("raw"),ee(""),z(`Trace opened: ${p}`)}catch(E){const C=E instanceof Error?E.message:String(E);ee(`Trace: ${C}`),z(`Trace open error ${p}: ${C}`)}}async function ts(){try{const p=await ke.startRun();h(p.run.runId),z(`Run started: ${p.run.runId}`),z("Tip: start run does not execute normalize by itself. Use 'Run eval v2.0.2' button."),await Me()}catch(p){z(`Run start error: ${p instanceof Error?p.message:String(p)}`)}}async function ns(){if($)try{await ke.finishRun($),z(`Run finished: ${$}`),await Me()}catch(p){z(`Run finish error: ${p instanceof Error?p.message:String(p)}`)}}async function Zn(){de(!0),ee("");try{z("Starting eval in v2 contour.");const p=j.batchQuestionsRaw.trim()||j.userQuestion.trim();if(!p)throw new Error("Fill batch field or Raw user question first.");const E=await ke.runEval({connection:i,prompts:f,promptVersion:"normalizer_v2_0_2",mode:"single-pass-strict",rawQuestions:p,useMock:Re});Se(E.report),z("Eval v2.0.2 run finished.");const C=E.report;if(C.run_id&&z(`Eval run id: ${C.run_id}`),C.metrics){const ne=C.metrics;z(`Eval metrics v2.0.2: schema=${ne.schema_validation_pass_rate??"n/a"}%, route_accuracy=${ne.route_resolution_accuracy??"n/a"}%, no_route_precision=${ne.no_route_precision??"n/a"}%, state_consistency=${ne.execution_state_consistency_rate??"n/a"}%`)}await xr()}catch(p){const E=p instanceof Error?p.message:String(p);E.includes("Legacy eval runner supports normalized_query_v1 only")?(Se({status:"plan_only",prompt_version:"normalizer_v2",reason:"backend eval runner is still legacy-v1 only",plan_file:"reports/v2_pilot_eval_plan.md",next_steps:["run cheap mock sanity for schema/fragment/scope","run small real batch (10-15 messages, temperature=0)","run challenge-30 replay with v2 metrics"]}),z("Backend is legacy-only for eval right now. Showing v2 pilot plan.")):(ee(`Eval: ${E}`),z(`Eval run error: ${E}`))}finally{de(!1)}}async function er(){try{const p=JSON.stringify(fe??{},null,2);await navigator.clipboard.writeText(p),z("Eval report copied to clipboard.")}catch(p){z(`Eval report copy error: ${p instanceof Error?p.message:String(p)}`)}}const Tt=x.useMemo(()=>{const p=new Map;for(const E of lt)E.message_id&&p.set(E.message_id,E);return p},[lt]),wt=Ce.messageIndex>=0?_n[Ce.messageIndex]??null:null,Fr=x.useMemo(()=>{if(Ce.messageIndex<0)return null;for(let p=Ce.messageIndex-1;p>=0;p-=1){const E=_n[p];if(E?.role==="user")return E}return null},[Ce.messageIndex,_n]);async function jt(p){if(!p.trim()){xe([]);return}Mt(!0);try{const E=await ke.loadAssistantAnnotations({session_id:p,limit:400});xe(E.items??[])}catch(E){const C=E instanceof Error?E.message:String(E);z(`Assistant annotations load error: ${C}`)}finally{Mt(!1)}}function bn(p){it(E=>E.saving&&!p?.force?E:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:Yi,saving:!1,error:""})}function Bn(p,E){if(p.role!=="assistant")return;const C=qe.trim(),ne=String(p.session_id??"").trim();if(!(C||ne)){ce("Сначала получите ответ ассистента в активной сессии.");return}!C&&ne&&gr(ne);const Hn=Tt.get(p.message_id)??null;it({open:!0,messageIndex:E,rating:Hn?.rating??3,comment:Hn?.comment??"",annotationAuthor:Hn?.annotation_author??Yi,saving:!1,error:""})}function It(p){return p.role==="assistant"}function Qt(p){return p.role==="assistant"&&Tt.has(p.message_id)}async function Wt(){if(!qe.trim()){it(p=>({...p,error:"Сессия ассистента не найдена."}));return}if(!(Ce.messageIndex<0)){if(!Ce.comment.trim()){it(p=>({...p,error:"Добавьте комментарий."}));return}it(p=>({...p,saving:!0,error:""}));try{const p=await ke.saveAssistantAnnotation({session_id:qe,message_index:Ce.messageIndex,rating:Ce.rating,comment:Ce.comment.trim(),annotation_author:Ce.annotationAuthor.trim()||void 0});xe(E=>{const C=[...E],ne=C.findIndex(Ke=>Ke.annotation_id===p.annotation.annotation_id);return ne>=0?C[ne]=p.annotation:C.unshift(p.annotation),C.sort((Ke,Hn)=>Date.parse(Hn.updated_at)-Date.parse(Ke.updated_at))}),bn({force:!0})}catch(p){const E=p instanceof Error?p.message:String(p);it(C=>({...C,saving:!1,error:E}))}}}function tr(){gr(""),vr([]),yr(""),Yn(null),Pt(""),ce(""),xe([]),bn({force:!0}),z("Assistant session reset.")}async function we(){const p=Nm(ln,Et);if(!p)return;Zr(!0),ce(""),yr(""),vr(C=>[...C,{message_id:`local-${Date.now()}`,session_id:qe||"pending",role:"user",text:p,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const E=zr();try{const C=await ke.sendAssistantMessage({connection:i,prompts:f,userMessage:p,sessionId:qe||void 0,promptVersion:Uc,useMock:Re});gr(C.session_id),vr(C.conversation),Pt("Ответ готов"),await jt(C.session_id),z(`Assistant reply received: trace=${C.debug.trace_id}`)}catch(C){const ne=C instanceof Error?C.message:String(C);ce(ne),Pt("Ошибка ассистента"),z(`Assistant error: ${ne}`)}finally{E(),Zr(!1)}}return x.useEffect(()=>{if(!qe.trim()){xe([]);return}jt(qe)},[qe]),x.useEffect(()=>{if(!$){J([]);return}ke.runTrace($).then(p=>J(p.items)).catch(p=>z(`Run trace error: ${p instanceof Error?p.message:String(p)}`))},[$]),o.jsxs("main",{className:`app-root ${Pe==="assistant"||Pe==="decomposition"||Pe==="autoruns"?"app-root-autoruns":""}`,children:[o.jsxs("header",{className:"app-topbar",children:[o.jsxs("div",{className:"mode-switch-row",children:[o.jsx("button",{type:"button",className:Pe==="assistant"?"tab active":"tab",onClick:()=>Ut("assistant"),children:"Ассистент"}),o.jsx("button",{type:"button",className:Pe==="decomposition"?"tab active":"tab",onClick:()=>Ut("decomposition"),children:"Декомпозиция"}),o.jsx("button",{type:"button",className:Pe==="autoruns"?"tab active":"tab",onClick:()=>Ut("autoruns"),children:"История автопрогонов"}),o.jsx("button",{type:"button",className:"tab",onClick:_t,children:"Сохранить"})]}),Pe==="assistant"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:bt?"tab active":"tab",onClick:()=>en(p=>!p),children:"LLM Connector"}),o.jsx("button",{type:"button",className:gn?"tab active":"tab",onClick:()=>mr(p=>!p),children:"Prompt Manager"}),o.jsx("button",{type:"button",className:On?"tab active":"tab",onClick:()=>pr(p=>!p),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:Dn?"tab active":"tab",onClick:()=>tn(p=>!p),children:"Комментарии ассистента"}),o.jsx("button",{type:"button",className:nn?"tab active":"tab",onClick:()=>hr(p=>!p),children:"SAM"})]}):Pe==="decomposition"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:Bt?"tab active":"tab",onClick:()=>vn(p=>!p),children:"LLM"}),o.jsx("button",{type:"button",className:be?"tab active":"tab",onClick:()=>ot(p=>!p),children:"Prompt"}),o.jsx("button",{type:"button",className:yn?"tab active":"tab",onClick:()=>xn(p=>!p),children:"Запрос"}),o.jsx("button",{type:"button",className:rn?"tab active":"tab",onClick:()=>sn(p=>!p),children:"Выход"}),o.jsx("button",{type:"button",className:Nt?"tab active":"tab",onClick:()=>zn(p=>!p),children:"Метрики"}),o.jsx("button",{type:"button",className:on?"tab active":"tab",onClick:()=>Ht(p=>!p),children:"История"}),o.jsx("button",{type:"button",className:gt?"tab active":"tab",onClick:()=>Jn(p=>!p),children:"NDC Run Monitor"})]}):Pe==="autoruns"?o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:Kn?"tab active":"tab",onClick:()=>In(p=>!p),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:Ln?"tab active":"tab",onClick:()=>fr(p=>!p),children:"Режим декомпозиции"}),o.jsx("button",{type:"button",className:Xt?"tab active":"tab",onClick:()=>Zt(p=>!p),children:"Прогресс/регресс"}),o.jsx("button",{type:"button",className:Gn?"tab active":"tab",onClick:()=>hn(p=>!p),children:"Комментарии"})]}):null]}),Pe==="assistant"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[bt?o.jsx("div",{className:"mode-col",children:o.jsx(Oc,{value:i,modelOptions:ve,modelsBusy:te,onChange:m,onReloadModels:Sn,onSaveLocalConfig:$r,onTestConnection:_r,lastStatus:ae,busy:Ae||vt})}):null,gn?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(Dc,{value:f,onChange:N,presets:Oe,selectedPresetId:We,onSelectPreset:Je,onLoadPreset:Un,onSavePreset:At,onResetDefaults:ct,onDiffPrevious:es,presetName:et,onPresetNameChange:st,diffSummary:Fe})}):null,On?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(Hc,{sessionId:qe,conversation:_n,inputValue:ln,onInputChange:yr,selectedContextChip:Et,onSelectContextChip:Yn,onClearContextChip:()=>Yn(null),useMock:Re,onUseMockChange:pe,onSend:we,onClear:tr,busy:vt,statusText:yt,errorMessage:$n,showCommentAction:!0,onCommentAssistantMessage:Bn,isAssistantMessageCommented:Qt,canCommentAssistantMessage:It})}):null,Dn?o.jsx("div",{className:"mode-col",children:o.jsx(Tn,{className:"assistant-comments-frame",title:"Комментарии ассистента",children:o.jsxs("div",{className:"assistant-comments-shell",children:[o.jsxs("div",{className:"assistant-comments-toolbar",children:[o.jsx("span",{className:"muted",children:qe?`session: ${qe}`:"Сессия не запущена"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{jt(qe)},disabled:!qe||xt,children:xt?"Обновляю...":"Обновить"})]}),o.jsxs("div",{className:"assistant-comments-list",children:[qe?null:o.jsx("p",{className:"muted",children:"Появится после первого ответа ассистента."}),qe&<.length===0&&!xt?o.jsx("p",{className:"muted",children:"Комментариев по этой сессии пока нет."}):null,lt.map(p=>o.jsxs("article",{className:"assistant-comment-item",children:[o.jsxs("div",{className:"assistant-comment-head",children:[o.jsx("strong",{children:`${"●".repeat(Math.max(1,Math.min(5,Math.round(p.rating))))}${"○".repeat(Math.max(0,5-Math.round(p.rating)))}`}),o.jsx("span",{children:new Date(p.updated_at).toLocaleString("ru-RU")})]}),p.context.question_text?o.jsxs("p",{children:["Q: ",p.context.question_text]}):null,p.context.answer_text?o.jsxs("p",{children:["A: ",p.context.answer_text]}):null,o.jsx("p",{children:p.comment}),o.jsxs("div",{className:"assistant-comment-meta",children:[p.context.trace_id?o.jsx("span",{children:`trace=${p.context.trace_id}`}):null,p.context.reply_type?o.jsx("span",{children:`reply_type=${p.context.reply_type}`}):null]})]},p.annotation_id))]})]})})}):null,nn?o.jsx("div",{className:"mode-col",children:o.jsx(Of,{sessionId:qe,conversation:_n,statusText:yt,errorMessage:$n,useMock:Re,appLogs:q})}):null,!bt&&!gn&&!On&&!Dn&&!nn?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима ассистента скрыты. Включите нужные блоки справа в шапке."}):null]})}):Pe==="decomposition"?o.jsx("div",{className:"layout-grid layout-grid-mode-columns",children:o.jsxs("div",{className:"mode-columns",children:[Bt?o.jsx("div",{className:"mode-col",children:o.jsx(Oc,{value:i,modelOptions:ve,modelsBusy:te,onChange:m,onReloadModels:Sn,onSaveLocalConfig:$r,onTestConnection:_r,lastStatus:ae,busy:Ae})}):null,be?o.jsx("div",{className:"mode-col mode-col-wide",children:o.jsx(Dc,{value:f,onChange:N,presets:Oe,selectedPresetId:We,onSelectPreset:Je,onLoadPreset:Un,onSavePreset:At,onResetDefaults:ct,onDiffPrevious:es,presetName:et,onPresetNameChange:st,diffSummary:Fe})}):null,yn?o.jsx("div",{className:"mode-col",children:o.jsx(vm,{value:j,onChange:T,onApplyBatchFormat:St,onNormalize:le,busy:Ae,useMock:Re,onUseMockChange:pe,errorMessage:ye})}):null,rn?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(gm,{tab:B,onTabChange:oe,result:F,appLogs:q})}):null,Nt?o.jsx("div",{className:"mode-col",children:o.jsx(mm,{result:F})}):null,on?o.jsx("div",{className:"mode-col",children:o.jsx(fm,{items:U,onRefresh:xr,onOpenTrace:Ns})}):null,gt?o.jsx("div",{className:"mode-col mode-col-xwide",children:o.jsx(ym,{runs:O,selectedRunId:$,onSelectRun:h,onStartRun:ts,onFinishRun:ns,onRefreshRuns:Me,onRunEval:Zn,onCopyEvalReport:er,evalBusy:ue,traceItems:k,evalReport:fe})}):null,!Bt&&!be&&!yn&&!rn&&!Nt&&!on&&!gt?o.jsx("div",{className:"mode-columns-empty",children:"Все панели режима декомпозиции скрыты. Включите нужные блоки справа в шапке."}):null]})}):o.jsx("div",{className:"layout-grid layout-grid-autoruns",children:o.jsx(am,{connection:i,prompts:f,assistantPromptVersion:Uc,decompositionPromptVersion:Ji,showAssistantMode:Kn,showDecompositionMode:Ln,showProgressMode:Xt,showCommentsMode:Gn,onLog:z})}),Ce.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:p=>{p.target===p.currentTarget&&bn()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Эта разметка хранится отдельно от комментариев автопрогонов."}),Fr?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:Fr.text})]}):null,wt?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:wt.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(p=>o.jsx("button",{type:"button",className:Ce.rating>=p?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>it(E=>({...E,rating:p})),disabled:Ce.saving,"aria-label":`Оценка ${p}`,children:Ce.rating>=p?"●":"○"},p))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:Ce.annotationAuthor,onChange:p=>it(E=>({...E,annotationAuthor:p.target.value})),placeholder:"manual_reviewer",disabled:Ce.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:Ce.comment,onChange:p=>it(E=>({...E,comment:p.target.value})),placeholder:"Что именно не так в ответе и что проверить.",rows:4,disabled:Ce.saving})]}),Ce.error?o.jsx("p",{className:"error-text",children:Ce.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{Wt()},disabled:Ce.saving,children:Ce.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>bn(),disabled:Ce.saving,children:"Отмена"})]})]})}):null]})}Tf.createRoot(document.getElementById("root")).render(o.jsx(Cf.StrictMode,{children:o.jsx(Em,{})})); diff --git a/llm_normalizer/frontend/dist/index.html b/llm_normalizer/frontend/dist/index.html index ebd74c8..ce8d203 100644 --- a/llm_normalizer/frontend/dist/index.html +++ b/llm_normalizer/frontend/dist/index.html @@ -4,7 +4,7 @@ NDC AI Normalizer Playground - + diff --git a/llm_normalizer/frontend/src/App.tsx b/llm_normalizer/frontend/src/App.tsx index 50bd6f4..7ad256e 100644 --- a/llm_normalizer/frontend/src/App.tsx +++ b/llm_normalizer/frontend/src/App.tsx @@ -153,6 +153,7 @@ export default function App() { }); const presetAutoloadDoneRef = useRef(false); const skipPresetAutoloadRef = useRef(false); + const sharedConnectionSyncReadyRef = useRef(false); useEffect(() => { const root = document.documentElement; @@ -192,22 +193,45 @@ export default function App() { } useEffect(() => { - const cached = localStorage.getItem(SESSION_CONFIG_KEY); - if (cached) { - try { - const parsed = JSON.parse(cached) as Partial; - setConnection((prev) => ({ - ...prev, - llmProvider: parsed.llmProvider === "local" ? "local" : "openai", - model: parsed.model ?? prev.model, - baseUrl: parsed.baseUrl ?? prev.baseUrl, - temperature: parsed.temperature ?? prev.temperature, - maxOutputTokens: parsed.maxOutputTokens ?? prev.maxOutputTokens - })); - } catch { - // ignore broken local cache + const bootstrapSharedConnection = async () => { + const cached = localStorage.getItem(SESSION_CONFIG_KEY); + if (cached) { + try { + const parsed = JSON.parse(cached) as Partial; + setConnection((prev) => ({ + ...prev, + llmProvider: parsed.llmProvider === "local" ? "local" : "openai", + model: parsed.model ?? prev.model, + baseUrl: parsed.baseUrl ?? prev.baseUrl, + temperature: parsed.temperature ?? prev.temperature, + maxOutputTokens: parsed.maxOutputTokens ?? prev.maxOutputTokens + })); + } catch { + // ignore broken local cache + } } - } + + try { + const payload = await apiClient.loadSharedConnectionConfig(); + if (payload.connection && payload.connection.llmProvider === "local") { + setConnection((prev) => ({ + ...prev, + llmProvider: "local", + model: payload.connection?.model ?? prev.model, + baseUrl: payload.connection?.baseUrl ?? prev.baseUrl, + temperature: payload.connection?.temperature ?? prev.temperature, + maxOutputTokens: payload.connection?.maxOutputTokens ?? prev.maxOutputTokens + })); + log(`Shared local LLM config loaded: ${payload.connection.model}`); + } + } catch (error) { + log(`Shared local config load error: ${error instanceof Error ? error.message : String(error)}`); + } finally { + sharedConnectionSyncReadyRef.current = true; + } + }; + + void bootstrapSharedConnection(); const cachedAutorunsLayout = localStorage.getItem(AUTORUNS_LAYOUT_CONFIG_KEY); if (cachedAutorunsLayout) { @@ -304,6 +328,23 @@ export default function App() { void refreshRuns(); }, []); + useEffect(() => { + if (!sharedConnectionSyncReadyRef.current) { + return; + } + if (connection.llmProvider !== "local") { + return; + } + const timer = window.setTimeout(() => { + void apiClient + .saveSharedConnectionConfig(connection) + .catch((error) => + log(`Shared local config sync error: ${error instanceof Error ? error.message : String(error)}`) + ); + }, 250); + return () => window.clearTimeout(timer); + }, [connection.baseUrl, connection.llmProvider, connection.maxOutputTokens, connection.model, connection.temperature]); + async function refreshHistory() { try { const payload = await apiClient.loadHistory(); @@ -369,6 +410,17 @@ export default function App() { maxOutputTokens: connection.maxOutputTokens }) ); + if (connection.llmProvider === "local") { + void apiClient + .saveSharedConnectionConfig(connection) + .then(() => { + log("Local config saved and synced to shared agent config (without API key)."); + }) + .catch((error) => { + log(`Local config saved, but shared sync failed: ${error instanceof Error ? error.message : String(error)}`); + }); + return; + } log("Local config saved (without API key)."); } diff --git a/llm_normalizer/frontend/src/api/client.ts b/llm_normalizer/frontend/src/api/client.ts index 8ef9d79..d0bcb4b 100644 --- a/llm_normalizer/frontend/src/api/client.ts +++ b/llm_normalizer/frontend/src/api/client.ts @@ -41,6 +41,32 @@ async function request(path: string, init?: RequestInit): Promise { } export const apiClient = { + async loadSharedConnectionConfig(): Promise<{ + ok: boolean; + connection: Omit | null; + updated_at: string | null; + exists: boolean; + }> { + return request("/llm/shared-connection"); + }, + + async saveSharedConnectionConfig(connection: ConnectionState): Promise<{ + ok: boolean; + connection: Omit; + updated_at: string; + }> { + return request("/llm/shared-connection", { + method: "POST", + body: JSON.stringify({ + llmProvider: connection.llmProvider, + model: connection.model, + baseUrl: connection.baseUrl, + temperature: connection.temperature, + maxOutputTokens: connection.maxOutputTokens + }) + }); + }, + async listModels(connection: ConnectionState): Promise<{ ok: boolean; models: string[]; count: number; timestamp: string }> { return request("/llm/models", { method: "POST", diff --git a/llm_normalizer/frontend/src/components/ConnectionPanel.tsx b/llm_normalizer/frontend/src/components/ConnectionPanel.tsx index 4eaa6da..330f8dd 100644 --- a/llm_normalizer/frontend/src/components/ConnectionPanel.tsx +++ b/llm_normalizer/frontend/src/components/ConnectionPanel.tsx @@ -2,6 +2,57 @@ import { useEffect, useState } from "react"; import { PanelFrame } from "./PanelFrame"; import type { ConnectionState } from "../state/types"; +const LOCAL_BASE_URL = "http://127.0.0.1:1234/v1"; +const OPENAI_BASE_URL = "https://api.openai.com/v1"; +const LOCAL_QWEN25_MODEL = "qwen2.5-14b-instruct-1m"; +const LOCAL_QWEN3_MODEL = "unsloth/qwen3-30b-a3b-instruct-2507"; + +type ProviderPreset = "openai" | "local_qwen25" | "local_qwen3" | "local_custom"; + +interface ModelOptionDescriptor { + value: string; + label: string; +} + +const BUILTIN_LOCAL_MODEL_OPTIONS: ModelOptionDescriptor[] = [ + { + value: LOCAL_QWEN25_MODEL, + label: "Qwen2.5 14B Instruct 1M" + }, + { + value: LOCAL_QWEN3_MODEL, + label: "Qwen3 30B A3B Instruct 2507" + } +]; + +function deriveProviderPreset(value: ConnectionState): ProviderPreset { + if (value.llmProvider !== "local") { + return "openai"; + } + if (value.model === LOCAL_QWEN3_MODEL) { + return "local_qwen3"; + } + if (value.model === LOCAL_QWEN25_MODEL) { + return "local_qwen25"; + } + return "local_custom"; +} + +function buildModelOptions(modelOptions: string[], isLocal: boolean): ModelOptionDescriptor[] { + const merged = new Map(); + if (isLocal) { + for (const option of BUILTIN_LOCAL_MODEL_OPTIONS) { + merged.set(option.value, option); + } + } + for (const modelId of modelOptions) { + if (!merged.has(modelId)) { + merged.set(modelId, { value: modelId, label: modelId }); + } + } + return Array.from(merged.values()); +} + interface ConnectionPanelProps { value: ConnectionState; modelOptions: string[]; @@ -26,7 +77,9 @@ export function ConnectionPanel({ busy }: ConnectionPanelProps) { const isLocal = value.llmProvider === "local"; - const modelInCatalog = modelOptions.includes(value.model); + const providerPreset = deriveProviderPreset(value); + const availableModelOptions = buildModelOptions(modelOptions, isLocal); + const modelInCatalog = availableModelOptions.some((option) => option.value === value.model); const [temperatureInput, setTemperatureInput] = useState(String(value.temperature)); const [maxOutputTokensInput, setMaxOutputTokensInput] = useState(String(value.maxOutputTokens)); @@ -78,18 +131,47 @@ export function ConnectionPanel({ @@ -106,20 +188,20 @@ export function ConnectionPanel({ }} > - {modelOptions.map((modelId) => ( - ))} @@ -140,7 +222,7 @@ export function ConnectionPanel({ onChange({ ...value, baseUrl: event.target.value })} - placeholder={isLocal ? "http://127.0.0.1:1234/v1" : "https://api.openai.com/v1"} + placeholder={isLocal ? LOCAL_BASE_URL : OPENAI_BASE_URL} /> diff --git a/scripts/domain_case_loop.py b/scripts/domain_case_loop.py index bb38981..774fb1f 100644 --- a/scripts/domain_case_loop.py +++ b/scripts/domain_case_loop.py @@ -19,14 +19,15 @@ DEFAULT_ARTIFACTS_ROOT = REPO_ROOT / "artifacts" / "domain_runs" DEFAULT_SESSIONS_DIR = REPO_ROOT / "llm_normalizer" / "data" / "assistant_sessions" DEFAULT_REPORTS_DIR = REPO_ROOT / "llm_normalizer" / "reports" DEFAULT_LOOP_SCHEMA_DIR = REPO_ROOT / "docs" / "orchestration" / "schemas" +SHARED_LLM_CONNECTION_CONFIG = REPO_ROOT / "llm_normalizer" / "data" / "shared_llm_connection.json" DEFAULT_BACKEND_URL = "http://127.0.0.1:8787" DEFAULT_PROMPT_VERSION = "address_query_runtime_v1" -DEFAULT_LLM_PROVIDER = "local" -DEFAULT_LLM_MODEL = "qwen2.5-14b-instruct-1m" -DEFAULT_LLM_BASE_URL = "http://127.0.0.1:1234/v1" +BASE_DEFAULT_LLM_PROVIDER = "local" +BASE_DEFAULT_LLM_MODEL = "qwen2.5-14b-instruct-1m" +BASE_DEFAULT_LLM_BASE_URL = "http://127.0.0.1:1234/v1" DEFAULT_LLM_API_KEY = "" -DEFAULT_TEMPERATURE = 0.0 -DEFAULT_MAX_OUTPUT_TOKENS = 900 +BASE_DEFAULT_TEMPERATURE = 0.0 +BASE_DEFAULT_MAX_OUTPUT_TOKENS = 900 TECH_SECTION_HEADER = "### technical_debug_payload_json" SCENARIO_MANIFEST_SCHEMA_VERSION = "domain_scenario_manifest_v1" SCENARIO_STATE_SCHEMA_VERSION = "domain_scenario_state_v1" @@ -35,6 +36,51 @@ SCENARIO_PACK_SCHEMA_VERSION = "domain_scenario_pack_v1" ACTIVE_DOMAIN_CONTRACT_SCHEMA_VERSION = "active_domain_contract_v1" AUTONOMOUS_LOOP_SCHEMA_VERSION = "domain_autonomous_loop_v1" + +def load_shared_local_llm_defaults(config_path: Path | None = None) -> dict[str, Any]: + defaults: dict[str, Any] = { + "llm_provider": BASE_DEFAULT_LLM_PROVIDER, + "llm_model": BASE_DEFAULT_LLM_MODEL, + "llm_base_url": BASE_DEFAULT_LLM_BASE_URL, + "temperature": BASE_DEFAULT_TEMPERATURE, + "max_output_tokens": BASE_DEFAULT_MAX_OUTPUT_TOKENS, + } + target = config_path or SHARED_LLM_CONNECTION_CONFIG + if not target.exists(): + return defaults + try: + raw = json.loads(target.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return defaults + connection = raw.get("connection") + if not isinstance(connection, dict): + return defaults + if str(connection.get("llmProvider") or "").strip().lower() != "local": + return defaults + + model = str(connection.get("model") or "").strip() + base_url = str(connection.get("baseUrl") or "").strip() + temperature = connection.get("temperature") + max_output_tokens = connection.get("maxOutputTokens") + + if model: + defaults["llm_model"] = model + if base_url: + defaults["llm_base_url"] = base_url + if isinstance(temperature, (int, float)) and not isinstance(temperature, bool): + defaults["temperature"] = float(temperature) + if isinstance(max_output_tokens, (int, float)) and not isinstance(max_output_tokens, bool): + defaults["max_output_tokens"] = max(1, int(max_output_tokens)) + return defaults + + +SHARED_LLM_DEFAULTS = load_shared_local_llm_defaults() +DEFAULT_LLM_PROVIDER = str(SHARED_LLM_DEFAULTS["llm_provider"]) +DEFAULT_LLM_MODEL = str(SHARED_LLM_DEFAULTS["llm_model"]) +DEFAULT_LLM_BASE_URL = str(SHARED_LLM_DEFAULTS["llm_base_url"]) +DEFAULT_TEMPERATURE = float(SHARED_LLM_DEFAULTS["temperature"]) +DEFAULT_MAX_OUTPUT_TOKENS = int(SHARED_LLM_DEFAULTS["max_output_tokens"]) + TOP_LEVEL_NOISE_PATTERNS = ( re.compile(r"^(?:status|статус(?: результата)?)\b", re.IGNORECASE), re.compile(r"^(?:что учтено|сводка)\b", re.IGNORECASE), diff --git a/tests/test_domain_case_loop.py b/tests/test_domain_case_loop.py index 0a62103..dbd3e9b 100644 --- a/tests/test_domain_case_loop.py +++ b/tests/test_domain_case_loop.py @@ -17,6 +17,7 @@ from scripts.domain_case_loop import ( evaluate_analyst_gate, evaluate_deterministic_loop_gate, load_scenario_pack, + load_shared_local_llm_defaults, merge_scenario_date_scope, select_primary_repair_focus, restore_line_collapsed_files_from_snapshot, @@ -66,6 +67,65 @@ def test_merge_scenario_date_scope_preserves_historical_anchor_on_followup() -> assert merged["source"] == "current_analysis" +def test_load_shared_local_llm_defaults_uses_ui_selected_local_model(tmp_path) -> None: + config_path = tmp_path / "shared_llm_connection.json" + config_path.write_text( + json.dumps( + { + "schema_version": "shared_llm_connection_v1", + "updated_at": "2026-04-15T06:00:00Z", + "connection": { + "llmProvider": "local", + "model": "unsloth/qwen3-30b-a3b-instruct-2507", + "baseUrl": "http://127.0.0.1:1234/v1", + "temperature": 0.2, + "maxOutputTokens": 1200, + }, + }, + ensure_ascii=False, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + defaults = load_shared_local_llm_defaults(config_path) + + assert defaults["llm_provider"] == "local" + assert defaults["llm_model"] == "unsloth/qwen3-30b-a3b-instruct-2507" + assert defaults["llm_base_url"] == "http://127.0.0.1:1234/v1" + assert defaults["temperature"] == 0.2 + assert defaults["max_output_tokens"] == 1200 + + +def test_load_shared_local_llm_defaults_ignores_non_local_provider(tmp_path) -> None: + config_path = tmp_path / "shared_llm_connection.json" + config_path.write_text( + json.dumps( + { + "schema_version": "shared_llm_connection_v1", + "updated_at": "2026-04-15T06:00:00Z", + "connection": { + "llmProvider": "openai", + "model": "gpt-4o-mini", + "baseUrl": "https://api.openai.com/v1", + "temperature": 0, + "maxOutputTokens": 700, + }, + }, + ensure_ascii=False, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + defaults = load_shared_local_llm_defaults(config_path) + + assert defaults["llm_provider"] == "local" + assert defaults["llm_model"] == "qwen2.5-14b-instruct-1m" + + def test_load_scenario_pack_accepts_active_domain_contract(tmp_path) -> None: manifest_path = tmp_path / "active_domain_contract.json" manifest_path.write_text(