From a14eee4976d23f1627a16875378f80061b7cf12e Mon Sep 17 00:00:00 2001 From: dctouch Date: Tue, 26 May 2026 00:54:18 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A3=D0=BF=D1=80=D0=BE=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D1=84=D1=80=D0=BE=D0=BD=D1=82=D0=B5=D0=BD=D0=B4?= =?UTF-8?q?=20=D1=81=D0=BE=D1=85=D1=80=D0=B0=D0=BD=D1=91=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D1=85=20=D1=81=D0=B5=D1=81=D1=81=D0=B8=D0=B9=20=D0=B0=D1=81?= =?UTF-8?q?=D1=81=D0=B8=D1=81=D1=82=D0=B5=D0=BD=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../frontend/dist/assets/index-B26u5hxP.js | 24 +++ .../frontend/dist/assets/index-BdTHVNKv.js | 25 --- llm_normalizer/frontend/dist/index.html | 2 +- llm_normalizer/frontend/src/api/client.ts | 36 ---- .../src/components/AutoRunsHistoryPanel.tsx | 181 ++++-------------- .../frontend/src/components/PromptPanel.tsx | 6 +- 6 files changed, 62 insertions(+), 212 deletions(-) create mode 100644 llm_normalizer/frontend/dist/assets/index-B26u5hxP.js delete mode 100644 llm_normalizer/frontend/dist/assets/index-BdTHVNKv.js diff --git a/llm_normalizer/frontend/dist/assets/index-B26u5hxP.js b/llm_normalizer/frontend/dist/assets/index-B26u5hxP.js new file mode 100644 index 0000000..d15cce7 --- /dev/null +++ b/llm_normalizer/frontend/dist/assets/index-B26u5hxP.js @@ -0,0 +1,24 @@ +(function(){const m=document.createElement("link").relList;if(m&&m.supports&&m.supports("modulepreload"))return;for(const C of document.querySelectorAll('link[rel="modulepreload"]'))S(C);new MutationObserver(C=>{for(const M of C)if(M.type==="childList")for(const $ of M.addedNodes)$.tagName==="LINK"&&$.rel==="modulepreload"&&S($)}).observe(document,{childList:!0,subtree:!0});function p(C){const M={};return C.integrity&&(M.integrity=C.integrity),C.referrerPolicy&&(M.referrerPolicy=C.referrerPolicy),C.crossOrigin==="use-credentials"?M.credentials="include":C.crossOrigin==="anonymous"?M.credentials="omit":M.credentials="same-origin",M}function S(C){if(C.ep)return;C.ep=!0;const M=p(C);fetch(C.href,M)}})();function kd(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var bi={exports:{}},Qo={},Ui={exports:{}},ve={};var Xc;function Nf(){if(Xc)return ve;Xc=1;var i=Symbol.for("react.element"),m=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),S=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),M=Symbol.for("react.provider"),$=Symbol.for("react.context"),re=Symbol.for("react.forward_ref"),Z=Symbol.for("react.suspense"),se=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),J=Symbol.iterator;function X(y){return y===null||typeof y!="object"?null:(y=J&&y[J]||y["@@iterator"],typeof y=="function"?y:null)}var Re={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},me=Object.assign,he={};function ye(y,k,te){this.props=y,this.context=k,this.refs=he,this.updater=te||Re}ye.prototype.isReactComponent={},ye.prototype.setState=function(y,k){if(typeof y!="object"&&typeof y!="function"&&y!=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,y,k,"setState")},ye.prototype.forceUpdate=function(y){this.updater.enqueueForceUpdate(this,y,"forceUpdate")};function Ge(){}Ge.prototype=ye.prototype;function Ze(y,k,te){this.props=y,this.context=k,this.refs=he,this.updater=te||Re}var We=Ze.prototype=new Ge;We.constructor=Ze,me(We,ye.prototype),We.isPureReactComponent=!0;var Ae=Array.isArray,U=Object.prototype.hasOwnProperty,oe={current:null},Ee={key:!0,ref:!0,__self:!0,__source:!0};function Qe(y,k,te){var ae,ce={},xe=null,we=null;if(k!=null)for(ae in k.ref!==void 0&&(we=k.ref),k.key!==void 0&&(xe=""+k.key),k)U.call(k,ae)&&!Ee.hasOwnProperty(ae)&&(ce[ae]=k[ae]);var je=arguments.length-2;if(je===1)ce.children=te;else if(1>>1,k=A[y];if(0>>1;yC(ce,L))xeC(we,ce)?(A[y]=we,A[xe]=L,y=xe):(A[y]=ce,A[ae]=L,y=ae);else if(xeC(we,L))A[y]=we,A[xe]=L,y=xe;else break e}}return O}function C(A,O){var L=A.sortIndex-O.sortIndex;return L!==0?L:A.id-O.id}if(typeof performance=="object"&&typeof performance.now=="function"){var M=performance;i.unstable_now=function(){return M.now()}}else{var $=Date,re=$.now();i.unstable_now=function(){return $.now()-re}}var Z=[],se=[],K=1,J=null,X=3,Re=!1,me=!1,he=!1,ye=typeof setTimeout=="function"?setTimeout:null,Ge=typeof clearTimeout=="function"?clearTimeout:null,Ze=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function We(A){for(var O=p(se);O!==null;){if(O.callback===null)S(se);else if(O.startTime<=A)S(se),O.sortIndex=O.expirationTime,m(Z,O);else break;O=p(se)}}function Ae(A){if(he=!1,We(A),!me)if(p(Z)!==null)me=!0,ee(U);else{var O=p(se);O!==null&&Y(Ae,O.startTime-A)}}function U(A,O){me=!1,he&&(he=!1,Ge(Qe),Qe=-1),Re=!0;var L=X;try{for(We(O),J=p(Z);J!==null&&(!(J.expirationTime>O)||A&&!Gt());){var y=J.callback;if(typeof y=="function"){J.callback=null,X=J.priorityLevel;var k=y(J.expirationTime<=O);O=i.unstable_now(),typeof k=="function"?J.callback=k:J===p(Z)&&S(Z),We(O)}else S(Z);J=p(Z)}if(J!==null)var te=!0;else{var ae=p(se);ae!==null&&Y(Ae,ae.startTime-O),te=!1}return te}finally{J=null,X=L,Re=!1}}var oe=!1,Ee=null,Qe=-1,St=5,pt=-1;function Gt(){return!(i.unstable_now()-ptA||125y?(A.sortIndex=L,m(se,A),p(Z)===null&&A===p(se)&&(he?(Ge(Qe),Qe=-1):he=!0,Y(Ae,L-y))):(A.sortIndex=k,m(Z,A),me||Re||(me=!0,ee(U))),A},i.unstable_shouldYield=Gt,i.unstable_wrapCallback=function(A){var O=X;return function(){var L=X;X=O;try{return A.apply(this,arguments)}finally{X=L}}}})(Hi)),Hi}var rd;function Mf(){return rd||(rd=1,Qi.exports=Rf()),Qi.exports}var sd;function Af(){if(sd)return Vt;sd=1;var i=Zi(),m=Mf();function p(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"),Z=Object.prototype.hasOwnProperty,se=/^[: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]*$/,K={},J={};function X(e){return Z.call(J,e)?!0:Z.call(K,e)?!1:se.test(e)?J[e]=!0:(K[e]=!0,!1)}function Re(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"||Re(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 he(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 ye={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ye[e]=new he(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ye[t]=new he(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){ye[e]=new he(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ye[e]=new he(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){ye[e]=new he(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){ye[e]=new he(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){ye[e]=new he(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){ye[e]=new he(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){ye[e]=new he(e,5,!1,e.toLowerCase(),null,!1,!1)});var Ge=/[\-:]([a-z])/g;function Ze(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(Ge,Ze);ye[t]=new he(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(Ge,Ze);ye[t]=new he(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(Ge,Ze);ye[t]=new he(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){ye[e]=new he(e,1,!1,e.toLowerCase(),null,!1,!1)}),ye.xlinkHref=new he("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){ye[e]=new he(e,1,!1,e.toLowerCase(),null,!0,!0)});function We(e,t,n,r){var s=ye.hasOwnProperty(t)?ye[t]:null;(s!==null?s.type!==0:r||!(2d||s[u]!==l[d]){var h=` +`+s[u].replace(" at new "," at ");return e.displayName&&h.includes("")&&(h=h.replace("",e.displayName)),h}while(1<=u&&0<=d);break}}}finally{te=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?k(e):""}function ce(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=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 xe(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 Ee:return"Fragment";case oe:return"Portal";case St:return"Profiler";case Qe:return"StrictMode";case b:return"Suspense";case Ie:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Gt:return(e.displayName||"Context")+".Consumer";case pt:return(e._context.displayName||"Context")+".Provider";case mt:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Je:return t=e.displayName||null,t!==null?t:xe(e.type)||"Memo";case ee:t=e._payload,e=e._init;try{return xe(e(t))}catch{}}return null}function we(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 xe(t);case 8:return t===Qe?"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 je(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Ce(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ht(e){var t=Ce(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 nn(e){e._valueTracker||(e._valueTracker=ht(e))}function xr(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Ce(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Tn(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 mn(e,t){var n=t.checked;return L({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function _e(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=je(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 Wt(e,t){t=t.checked,t!=null&&We(e,"checked",t,!1)}function qe(e,t){Wt(e,t);var n=je(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")?rn(e,t.type,n):t.hasOwnProperty("defaultValue")&&rn(e,t.type,je(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function wt(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 rn(e,t,n){(t!=="number"||Tn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var hn=Array.isArray;function le(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=jt.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function gn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var de={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},Mn=["Webkit","ms","Moz","O"];Object.keys(de).forEach(function(e){Mn.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),de[t]=de[e]})});function vt(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||de.hasOwnProperty(e)&&de[e]?(""+t).trim():t+"px"}function Yr(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=vt(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var at=L({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 An(e,t){if(t){if(at[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(p(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(p(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(p(61))}if(t.style!=null&&typeof t.style!="object")throw Error(p(62))}}function In(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 Rt=null;function vn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var sn=null,pe=null,Mt=null;function Ue(e){if(e=Po(e)){if(typeof sn!="function")throw Error(p(280));var t=e.stateNode;t&&(t=gl(t),sn(e.stateNode,e.type,t))}}function yn(e){pe?Mt?Mt.push(e):Mt=[e]:pe=e}function Sr(){if(pe){var e=pe,t=Mt;if(Mt=pe=null,Ue(e),t)for(e=0;e>>=0,e===0?32:31-(Yo(e)/Xo|0)|0}var Un=64,Ss=4194304;function Jt(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 ws(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=Jt(d):(l&=u,l!==0&&(r=Jt(l)))}else u=n&~s,u!==0?r=Jt(u):l!==0&&(r=Jt(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 Nr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Kt(t),e[t]=n}function Qn(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=Ar),mo=" ",ho=!1;function go(e,t){switch(e){case"keyup":return Yn.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function vo(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ur=!1;function xa(e,t){switch(e){case"compositionend":return vo(t);case"keypress":return t.which!==32?null:(ho=!0,mo);case"textInput":return e=t.data,e===mo&&ho?null:e;default:return null}}function ul(e,t){if(ur)return e==="compositionend"||!Mr&&go(e,t)?(e=Ts(),ss=Xt=xn=null,ur=!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=tu(n)}}function ru(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ru(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function su(){for(var e=window,t=Tn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Tn(e.document)}return t}function ja(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 Ad(e){var t=su(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ru(n.ownerDocument.documentElement,n)){if(r!==null&&ja(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=nu(n,l);var u=nu(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,ka=null,jo=null,Ca=!1;function ou(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ca||Ls==null||Ls!==Tn(r)||(r=Ls,"selectionStart"in r&&ja(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}),jo&&wo(jo,r)||(jo=r,r=pl(ka,"onSelect"),0Fs||(e.current=za[Fs],za[Fs]=null,Fs--)}function ze(e,t){Fs++,za[Fs]=e.current,e.current=t}var Fr={},Ct=$r(Fr),bt=$r(!1),us=Fr;function bs(e,t){var n=e.type.contextTypes;if(!n)return Fr;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 Ut(e){return e=e.childContextTypes,e!=null}function vl(){be(bt),be(Ct)}function _u(e,t,n){if(Ct.current!==Fr)throw Error(p(168));ze(Ct,t),ze(bt,n)}function Su(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(p(108,we(e)||"Unknown",s));return L({},n,r)}function yl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Fr,us=Ct.current,ze(Ct,e),ze(bt,bt.current),!0}function wu(e,t,n){var r=e.stateNode;if(!r)throw Error(p(169));n?(e=Su(e,t,us),r.__reactInternalMemoizedMergedChildContext=e,be(bt),be(Ct),ze(Ct,e)):be(bt),ze(bt,n)}var dr=null,xl=!1,$a=!1;function ju(e){dr===null?dr=[e]:dr.push(e)}function Hd(e){xl=!0,ju(e)}function br(){if(!$a&&dr!==null){$a=!0;var e=0,t=fe;try{var n=dr;for(fe=1;e>=u,s-=u,fr=1<<32-Kt(t)+s|n<ne?(ft=W,W=null):ft=W.sibling;var Ne=N(x,W,_[ne],R);if(Ne===null){W===null&&(W=ft);break}e&&W&&Ne.alternate===null&&t(x,W),v=l(Ne,v,ne),G===null?V=Ne:G.sibling=Ne,G=Ne,W=ft}if(ne===_.length)return n(x,W),Be&&ds(x,ne),V;if(W===null){for(;ne<_.length;ne++)W=T(x,_[ne],R),W!==null&&(v=l(W,v,ne),G===null?V=W:G.sibling=W,G=W);return Be&&ds(x,ne),V}for(W=r(x,W);ne<_.length;ne++)ft=D(W,x,ne,_[ne],R),ft!==null&&(e&&ft.alternate!==null&&W.delete(ft.key===null?ne:ft.key),v=l(ft,v,ne),G===null?V=ft:G.sibling=ft,G=ft);return e&&W.forEach(function(Kr){return t(x,Kr)}),Be&&ds(x,ne),V}function Q(x,v,_,R){var V=O(_);if(typeof V!="function")throw Error(p(150));if(_=V.call(_),_==null)throw Error(p(151));for(var G=V=null,W=v,ne=v=0,ft=null,Ne=_.next();W!==null&&!Ne.done;ne++,Ne=_.next()){W.index>ne?(ft=W,W=null):ft=W.sibling;var Kr=N(x,W,Ne.value,R);if(Kr===null){W===null&&(W=ft);break}e&&W&&Kr.alternate===null&&t(x,W),v=l(Kr,v,ne),G===null?V=Kr:G.sibling=Kr,G=Kr,W=ft}if(Ne.done)return n(x,W),Be&&ds(x,ne),V;if(W===null){for(;!Ne.done;ne++,Ne=_.next())Ne=T(x,Ne.value,R),Ne!==null&&(v=l(Ne,v,ne),G===null?V=Ne:G.sibling=Ne,G=Ne);return Be&&ds(x,ne),V}for(W=r(x,W);!Ne.done;ne++,Ne=_.next())Ne=D(W,x,ne,Ne.value,R),Ne!==null&&(e&&Ne.alternate!==null&&W.delete(Ne.key===null?ne:Ne.key),v=l(Ne,v,ne),G===null?V=Ne:G.sibling=Ne,G=Ne);return e&&W.forEach(function(Cf){return t(x,Cf)}),Be&&ds(x,ne),V}function Xe(x,v,_,R){if(typeof _=="object"&&_!==null&&_.type===Ee&&_.key===null&&(_=_.props.children),typeof _=="object"&&_!==null){switch(_.$$typeof){case U:e:{for(var V=_.key,G=v;G!==null;){if(G.key===V){if(V=_.type,V===Ee){if(G.tag===7){n(x,G.sibling),v=s(G,_.props.children),v.return=x,x=v;break e}}else if(G.elementType===V||typeof V=="object"&&V!==null&&V.$$typeof===ee&&Tu(V)===G.type){n(x,G.sibling),v=s(G,_.props),v.ref=To(x,G,_),v.return=x,x=v;break e}n(x,G);break}else t(x,G);G=G.sibling}_.type===Ee?(v=xs(_.props.children,x.mode,R,_.key),v.return=x,x=v):(R=Wl(_.type,_.key,_.props,null,x.mode,R),R.ref=To(x,v,_),R.return=x,x=R)}return u(x);case oe:e:{for(G=_.key;v!==null;){if(v.key===G)if(v.tag===4&&v.stateNode.containerInfo===_.containerInfo&&v.stateNode.implementation===_.implementation){n(x,v.sibling),v=s(v,_.children||[]),v.return=x,x=v;break e}else{n(x,v);break}else t(x,v);v=v.sibling}v=Di(_,x.mode,R),v.return=x,x=v}return u(x);case ee:return G=_._init,Xe(x,v,G(_._payload),R)}if(hn(_))return F(x,v,_,R);if(O(_))return Q(x,v,_,R);jl(x,_)}return typeof _=="string"&&_!==""||typeof _=="number"?(_=""+_,v!==null&&v.tag===6?(n(x,v.sibling),v=s(v,_),v.return=x,x=v):(n(x,v),v=Li(_,x.mode,R),v.return=x,x=v),u(x)):n(x,v)}return Xe}var Hs=Ru(!0),Mu=Ru(!1),kl=$r(null),Cl=null,Vs=null,Ha=null;function Va(){Ha=Vs=Cl=null}function Ga(e){var t=kl.current;be(kl),e._currentValue=t}function Wa(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){Cl=e,Ha=Vs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Bt=!0),e.firstContext=null)}function un(e){var t=e._currentValue;if(Ha!==e)if(e={context:e,memoizedValue:t,next:null},Vs===null){if(Cl===null)throw Error(p(308));Vs=e,Cl.dependencies={lanes:0,firstContext:e}}else Vs=Vs.next=e;return t}var fs=null;function qa(e){fs===null?fs=[e]:fs.push(e)}function Au(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,qa(t)):(n.next=s.next,s.next=n),t.interleaved=n,mr(e,r)}function mr(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 Ur=!1;function Ka(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Iu(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 hr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Br(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(ke&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,mr(e,n)}return s=r.interleaved,s===null?(t.next=t,qa(r)):(t.next=s.next,s.next=t),r.interleaved=t,mr(e,n)}function Nl(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,ts(e,n)}}function Lu(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 El(e,t,n,r){var s=e.updateQueue;Ur=!1;var l=s.firstBaseUpdate,u=s.lastBaseUpdate,d=s.shared.pending;if(d!==null){s.shared.pending=null;var h=d,j=h.next;h.next=null,u===null?l=j:u.next=j,u=h;var P=e.alternate;P!==null&&(P=P.updateQueue,d=P.lastBaseUpdate,d!==u&&(d===null?P.firstBaseUpdate=j:d.next=j,P.lastBaseUpdate=h))}if(l!==null){var T=s.baseState;u=0,P=j=h=null,d=l;do{var N=d.lane,D=d.eventTime;if((r&N)===N){P!==null&&(P=P.next={eventTime:D,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var F=e,Q=d;switch(N=t,D=n,Q.tag){case 1:if(F=Q.payload,typeof F=="function"){T=F.call(D,T,N);break e}T=F;break e;case 3:F.flags=F.flags&-65537|128;case 0:if(F=Q.payload,N=typeof F=="function"?F.call(D,T,N):F,N==null)break e;T=L({},T,N);break e;case 2:Ur=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,N=s.effects,N===null?s.effects=[d]:N.push(d))}else D={eventTime:D,lane:N,tag:d.tag,payload:d.payload,callback:d.callback,next:null},P===null?(j=P=D,h=T):P=P.next=D,u|=N;if(d=d.next,d===null){if(d=s.shared.pending,d===null)break;N=d,d=N.next,N.next=null,s.lastBaseUpdate=N,s.shared.pending=null}}while(!0);if(P===null&&(h=T),s.baseState=h,s.firstBaseUpdate=j,s.lastBaseUpdate=P,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);hs|=u,e.lanes=u,e.memoizedState=T}}function Du(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=ei.transition;ei.transition={};try{e(!1),t()}finally{fe=n,ei.transition=r}}function ec(){return cn().memoizedState}function qd(e,t,n){var r=Gr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},tc(e))nc(t,n);else if(n=Au(e,t,n,r),n!==null){var s=Ot();Pn(n,e,r,s),rc(n,t,r)}}function Kd(e,t,n){var r=Gr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(tc(e))nc(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,jn(d,u)){var h=t.interleaved;h===null?(s.next=s,qa(t)):(s.next=h.next,h.next=s),t.interleaved=s;return}}catch{}n=Au(e,t,s,r),n!==null&&(s=Ot(),Pn(n,e,r,s),rc(n,t,r))}}function tc(e){var t=e.alternate;return e===Ve||t!==null&&t===Ve}function nc(e,t){Io=Rl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function rc(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ts(e,n)}}var Il={readContext:un,useCallback:Nt,useContext:Nt,useEffect:Nt,useImperativeHandle:Nt,useInsertionEffect:Nt,useLayoutEffect:Nt,useMemo:Nt,useReducer:Nt,useRef:Nt,useState:Nt,useDebugValue:Nt,useDeferredValue:Nt,useTransition:Nt,useMutableSource:Nt,useSyncExternalStore:Nt,useId:Nt,unstable_isNewReconciler:!1},Jd={readContext:un,useCallback:function(e,t){return er().memoizedState=[e,t===void 0?null:t],e},useContext:un,useEffect:Gu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ml(4194308,4,Ku.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ml(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ml(4,2,e,t)},useMemo:function(e,t){var n=er();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=er();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=qd.bind(null,Ve,e),[r.memoizedState,e]},useRef:function(e){var t=er();return e={current:e},t.memoizedState=e},useState:Hu,useDebugValue:ai,useDeferredValue:function(e){return er().memoizedState=e},useTransition:function(){var e=Hu(!1),t=e[0];return e=Wd.bind(null,e[1]),er().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ve,s=er();if(Be){if(n===void 0)throw Error(p(407));n=n()}else{if(n=t(),dt===null)throw Error(p(349));(ms&30)!==0||Fu(r,t,n)}s.memoizedState=n;var l={value:n,getSnapshot:t};return s.queue=l,Gu(Uu.bind(null,r,l,e),[e]),r.flags|=2048,Oo(9,bu.bind(null,r,l,n,t),void 0,null),n},useId:function(){var e=er(),t=dt.identifierPrefix;if(Be){var n=pr,r=fr;n=(r&~(1<<32-Kt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Lo++,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[Xn]=t,e[Eo]=r,jc(e,t,!1,!1),t.stateNode=e;e:{switch(u=In(n,r),n){case"dialog":Fe("cancel",e),Fe("close",e),s=r;break;case"iframe":case"object":case"embed":Fe("load",e),s=r;break;case"video":case"audio":for(s=0;sYs&&(t.flags|=128,r=!0,zo(l,!1),t.lanes=4194304)}else{if(!r)if(e=Pl(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),zo(l,!0),l.tail===null&&l.tailMode==="hidden"&&!u.alternate&&!Be)return Et(t),null}else 2*$e()-l.renderingStartTime>Ys&&n!==1073741824&&(t.flags|=128,r=!0,zo(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=$e(),t.sibling=null,n=He.current,ze(He,r?n&1|2:n&1),t):(Et(t),null);case 22:case 23:return Mi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(tn&1073741824)!==0&&(Et(t),t.subtreeFlags&6&&(t.flags|=8192)):Et(t),null;case 24:return null;case 25:return null}throw Error(p(156,t.tag))}function sf(e,t){switch(ba(t),t.tag){case 1:return Ut(t.type)&&vl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ws(),be(bt),be(Ct),Za(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return Ya(t),null;case 13:if(be(He),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(p(340));Qs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return be(He),null;case 4:return Ws(),null;case 10:return Ga(t.type._context),null;case 22:case 23:return Mi(),null;case 24:return null;default:return null}}var zl=!1,Pt=!1,of=typeof WeakSet=="function"?WeakSet:Set,z=null;function Ks(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ke(e,t,r)}else n.current=null}function xi(e,t,n){try{n()}catch(r){Ke(e,t,r)}}var Nc=!1;function lf(e,t){if(Ma=Me,e=su(),ja(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,h=-1,j=0,P=0,T=e,N=null;t:for(;;){for(var D;T!==n||s!==0&&T.nodeType!==3||(d=u+s),T!==l||r!==0&&T.nodeType!==3||(h=u+r),T.nodeType===3&&(u+=T.nodeValue.length),(D=T.firstChild)!==null;)N=T,T=D;for(;;){if(T===e)break t;if(N===n&&++j===s&&(d=u),N===l&&++P===r&&(h=u),(D=T.nextSibling)!==null)break;T=N,N=T.parentNode}T=D}n=d===-1||h===-1?null:{start:d,end:h}}else n=null}n=n||{start:0,end:0}}else n=null;for(Aa={focusedElem:e,selectionRange:n},Me=!1,z=t;z!==null;)if(t=z,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,z=e;else for(;z!==null;){t=z;try{var F=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(F!==null){var Q=F.memoizedProps,Xe=F.memoizedState,x=t.stateNode,v=x.getSnapshotBeforeUpdate(t.elementType===t.type?Q:Cn(t.type,Q),Xe);x.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var _=t.stateNode.containerInfo;_.nodeType===1?_.textContent="":_.nodeType===9&&_.documentElement&&_.removeChild(_.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163))}}catch(R){Ke(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,z=e;break}z=t.return}return F=Nc,Nc=!1,F}function $o(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&&xi(t,n,l)}s=s.next}while(s!==r)}}function $l(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 _i(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 Ec(e){var t=e.alternate;t!==null&&(e.alternate=null,Ec(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Xn],delete t[Eo],delete t[Oa],delete t[Bd],delete t[Qd])),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 Pc(e){return e.tag===5||e.tag===3||e.tag===4}function Tc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Pc(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 Si(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=hl));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}function wi(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(wi(e,t,n),e=e.sibling;e!==null;)wi(e,t,n),e=e.sibling}var xt=null,Nn=!1;function Qr(e,t,n){for(n=n.child;n!==null;)Rc(e,t,n),n=n.sibling}function Rc(e,t,n){if($t&&typeof $t.onCommitFiberUnmount=="function")try{$t.onCommitFiberUnmount(kr,n)}catch{}switch(n.tag){case 5:Pt||Ks(n,t);case 6:var r=xt,s=Nn;xt=null,Qr(e,t,n),xt=r,Nn=s,xt!==null&&(Nn?(e=xt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):xt.removeChild(n.stateNode));break;case 18:xt!==null&&(Nn?(e=xt,n=n.stateNode,e.nodeType===8?Da(e.parentNode,n):e.nodeType===1&&Da(e,n),Pr(e)):Da(xt,n.stateNode));break;case 4:r=xt,s=Nn,xt=n.stateNode.containerInfo,Nn=!0,Qr(e,t,n),xt=r,Nn=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)&&xi(n,t,u),s=s.next}while(s!==r)}Qr(e,t,n);break;case 1:if(!Pt&&(Ks(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(d){Ke(n,t,d)}Qr(e,t,n);break;case 21:Qr(e,t,n);break;case 22:n.mode&1?(Pt=(r=Pt)||n.memoizedState!==null,Qr(e,t,n),Pt=r):Qr(e,t,n);break;default:Qr(e,t,n)}}function Mc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new of),t.forEach(function(r){var s=gf.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function En(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~l}if(r=s,r=$e()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*uf(r/1960))-r,10e?16:e,Vr===null)var r=!1;else{if(e=Vr,Vr=null,Ql=0,(ke&6)!==0)throw Error(p(331));var s=ke;for(ke|=4,z=e.current;z!==null;){var l=z,u=l.child;if((z.flags&16)!==0){var d=l.deletions;if(d!==null){for(var h=0;h$e()-Ci?vs(e,0):ki|=n),Ht(e,t)}function Hc(e,t){t===0&&((e.mode&1)===0?t=1:(t=Ss,Ss<<=1,(Ss&130023424)===0&&(Ss=4194304)));var n=Ot();e=mr(e,t),e!==null&&(Nr(e,t,n),Ht(e,n))}function hf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Hc(e,n)}function gf(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(p(314))}r!==null&&r.delete(t),Hc(e,n)}var Vc;Vc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||bt.current)Bt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Bt=!1,nf(e,t,n);Bt=(e.flags&131072)!==0}else Bt=!1,Be&&(t.flags&1048576)!==0&&ku(t,Sl,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ol(e,t),e=t.pendingProps;var s=bs(t,Ct.current);Gs(t,n),s=ni(null,t,r,e,s,n);var l=ri();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,Ut(r)?(l=!0,yl(t)):l=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Ka(t),s.updater=Ll,t.stateNode=s,s._reactInternals=t,ui(t,r,e,n),t=pi(null,t,r,!0,l,n)):(t.tag=0,Be&&l&&Fa(t),Dt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ol(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=yf(r),e=Cn(r,e),s){case 0:t=fi(null,t,r,e,n);break e;case 1:t=vc(null,t,r,e,n);break e;case 11:t=fc(null,t,r,e,n);break e;case 14:t=pc(null,t,r,Cn(r.type,e),n);break e}throw Error(p(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Cn(r,s),fi(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Cn(r,s),vc(e,t,r,s,n);case 3:e:{if(yc(t),e===null)throw Error(p(387));r=t.pendingProps,l=t.memoizedState,s=l.element,Iu(e,t),El(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=qs(Error(p(423)),t),t=xc(e,t,r,n,s);break e}else if(r!==s){s=qs(Error(p(424)),t),t=xc(e,t,r,n,s);break e}else for(en=zr(t.stateNode.containerInfo.firstChild),Zt=t,Be=!0,kn=null,n=Mu(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Qs(),r===s){t=gr(e,t,n);break e}Dt(e,t,r,n)}t=t.child}return t;case 5:return Ou(t),e===null&&Ba(t),r=t.type,s=t.pendingProps,l=e!==null?e.memoizedProps:null,u=s.children,Ia(r,s)?u=null:l!==null&&Ia(r,l)&&(t.flags|=32),gc(e,t),Dt(e,t,u,n),t.child;case 6:return e===null&&Ba(t),null;case 13:return _c(e,t,n);case 4:return Ja(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Hs(t,null,r,n):Dt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Cn(r,s),fc(e,t,r,s,n);case 7:return Dt(e,t,t.pendingProps,n),t.child;case 8:return Dt(e,t,t.pendingProps.children,n),t.child;case 12:return Dt(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,ze(kl,r._currentValue),r._currentValue=u,l!==null)if(jn(l.value,u)){if(l.children===s.children&&!bt.current){t=gr(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 h=d.firstContext;h!==null;){if(h.context===r){if(l.tag===1){h=hr(-1,n&-n),h.tag=2;var j=l.updateQueue;if(j!==null){j=j.shared;var P=j.pending;P===null?h.next=h:(h.next=P.next,P.next=h),j.pending=h}}l.lanes|=n,h=l.alternate,h!==null&&(h.lanes|=n),Wa(l.return,n,t),d.lanes|=n;break}h=h.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(p(341));u.lanes|=n,d=u.alternate,d!==null&&(d.lanes|=n),Wa(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}Dt(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,Dt(e,t,r,n),t.child;case 14:return r=t.type,s=Cn(r,t.pendingProps),s=Cn(r.type,s),pc(e,t,r,s,n);case 15:return mc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Cn(r,s),Ol(e,t),t.tag=1,Ut(r)?(e=!0,yl(t)):e=!1,Gs(t,n),oc(t,r,s),ui(t,r,s,n),pi(null,t,r,!0,e,n);case 19:return wc(e,t,n);case 22:return hc(e,t,n)}throw Error(p(156,t.tag))};function Gc(e,t){return Jo(e,t)}function vf(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 vf(e,t,n,r)}function Ii(e){return e=e.prototype,!(!e||!e.isReactComponent)}function yf(e){if(typeof e=="function")return Ii(e)?1:0;if(e!=null){if(e=e.$$typeof,e===mt)return 11;if(e===Je)return 14}return 2}function qr(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 Wl(e,t,n,r,s,l){var u=2;if(r=e,typeof e=="function")Ii(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Ee:return xs(n.children,s,l,t);case Qe:u=8,s|=8;break;case St:return e=fn(12,n,t,s|2),e.elementType=St,e.lanes=l,e;case b:return e=fn(13,n,t,s),e.elementType=b,e.lanes=l,e;case Ie:return e=fn(19,n,t,s),e.elementType=Ie,e.lanes=l,e;case Y:return ql(n,s,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case pt:u=10;break e;case Gt:u=9;break e;case mt:u=11;break e;case Je:u=14;break e;case ee:u=16,r=null;break e}throw Error(p(130,e==null?e:typeof e,""))}return t=fn(u,n,t,s),t.elementType=e,t.type=r,t.lanes=l,t}function xs(e,t,n,r){return e=fn(7,e,r,t),e.lanes=n,e}function ql(e,t,n,r){return e=fn(22,e,r,t),e.elementType=Y,e.lanes=n,e.stateNode={isHidden:!1},e}function Li(e,t,n){return e=fn(6,e,null,t),e.lanes=n,e}function Di(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 xf(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=ks(0),this.expirationTimes=ks(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ks(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Oi(e,t,n,r,s,l,u,d,h){return e=new xf(e,t,n,d,h),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},Ka(l),e}function _f(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=Af(),Bi.exports}var ld;function Lf(){if(ld)return ta;ld=1;var i=If();return ta.createRoot=i.createRoot,ta.hydrateRoot=i.hydrateRoot,ta}var Df=Lf();const Of=kd(Df),zf="/api";async function Se(i,m){const p=await fetch(`${zf}${i}`,{...m,headers:{"Content-Type":"application/json",...m?.headers??{}}}),S=await p.json();if(!p.ok){const C=S.error?.message??"Ошибка запроса";throw new Error(C)}return S}const Te={async loadSharedConnectionConfig(){return Se("/llm/shared-connection")},async saveSharedConnectionConfig(i){return Se("/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 Se("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async testConnection(i){return Se("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async normalize(i){return Se("/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 Se("/history")},async loadTrace(i){return Se(`/history/${i}`)},async loadPresets(){return Se("/presets")},async savePreset(i){return Se("/presets/save",{method:"POST",body:JSON.stringify(i)})},async runEval(i){return Se("/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 Se("/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,scenarioQuestions:i.scenarioQuestions,scenarioTitle:i.scenarioTitle,analysis_date:i.analysisDate})})},async loadEvalRunAsyncStatus(i){return Se(`/eval/run-async/${encodeURIComponent(i)}`)},async cancelEvalRunAsync(i){return Se(`/eval/run-async/${encodeURIComponent(i)}/cancel`,{method:"POST"})},async startRun(){return Se("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(i){return Se("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:i,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return Se("/accounting-agent/v1/runs")},async listResults(){return Se("/accounting-agent/v1/results")},async runTrace(i){return Se(`/accounting-agent/v1/trace/run/${i}`)},async sendAssistantMessage(i){return Se("/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",context:{period_hint:i.context?.periodHint??"",business_context:i.context?.businessContext??""},useMock:!!i.useMock})})},async loadAssistantSession(i){return Se(`/assistant/session/${i}`)},async saveAutoRunAssistantSession(i){return Se("/autoruns/autogen/save-assistant-session",{method:"POST",body:JSON.stringify(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 p=m.toString();return Se(`/assistant/annotations${p?`?${p}`:""}`)},async saveAssistantAnnotation(i){return Se("/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 p=m.toString();return Se(`/autoruns/history${p?`?${p}`:""}`)},async loadAutoRunDetail(i){return Se(`/autoruns/history/${encodeURIComponent(i)}`)},async loadAutoRunCaseDialog(i,m){return Se(`/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 p=m.toString();return Se(`/autoruns/annotations${p?`?${p}`:""}`)},async saveAutoRunAnnotation(i){return Se("/autoruns/annotations",{method:"POST",body:JSON.stringify(i)})},async updateAutoRunAnnotation(i){return Se(`/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 p=m.toString();return Se(`/autoruns/post-analysis${p?`?${p}`:""}`)},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 p=m.toString();return Se(`/autoruns/autogen/history${p?`?${p}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return Se("/autoruns/autogen/personality-catalog")},async updateAutoRunAutogenQuestions(i){return Se(`/autoruns/autogen/history/${encodeURIComponent(i.generation_id)}/questions`,{method:"PATCH",body:JSON.stringify({questions:i.questions})})},async deleteAutoRunAutogenHistoryRecord(i){return Se(`/autoruns/autogen/history/${encodeURIComponent(i)}`,{method:"DELETE"})}},$f=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,Ff=[/\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 yr(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function bf(i){return i==="assistant"?"assistant":"user"}function Cd(i){const m=String(i??""),p=m.match($f);return(p?m.slice(0,p.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($=>$.trimEnd()).filter($=>$.trim().length>0).filter($=>!Ff.some(re=>re.test($))).join(` +`).trim()}function Uf(i,m,p="default"){const S=p==="technical",C=[];C.push("# Assistant conversation export"),C.push(`session_id: ${i||"n/a"}`),C.push(`export_mode: ${p}`),C.push(`exported_at: ${new Date().toISOString()}`),C.push("");for(let M=0;M0&&(S.push("### decomposition_json"),S.push("```json"),S.push(yr(i.decomposition)),S.push("```"),S.push("")),i.assistantMode&&(S.push("### assistant_mode_json"),S.push("```json"),S.push(yr(i.assistantMode)),S.push("```"),S.push("")),(i.annotations??[]).length>0&&(S.push("### annotations_json"),S.push("```json"),S.push(yr(i.annotations)),S.push("```"),S.push("")),i.runSummary&&(S.push("### run_summary_json"),S.push("```json"),S.push(yr(i.runSummary)),S.push("```"),S.push("")),i.coverage&&(S.push("### coverage_json"),S.push("```json"),S.push(yr(i.coverage)),S.push("```"),S.push("")),i.report&&(S.push("### run_report_json"),S.push("```json"),S.push(yr(i.report)),S.push("```"),S.push(""))),S.join(` +`)}function Nd({value:i}){return o.jsx("pre",{className:"json-view",children:JSON.stringify(i??{},null,2)})}function ca({title:i,subtitle:m,actions:p,className:S,hideHeader:C,children:M}){return o.jsxs("section",{className:S?`panel-frame ${S}`:"panel-frame",children:[C?null:o.jsxs("header",{className:"panel-header",children:[o.jsxs("div",{children:[o.jsx("h2",{children:i}),m?o.jsx("p",{children:m}):null]}),p?o.jsx("div",{className:"panel-actions",children:p}):null]}),o.jsx("div",{className:"panel-body",children:M})]})}function Qf(i){return i==="assistant"?"Ассистент":"Вы"}function Hf(i){const m=new Date(i);return Number.isNaN(m.getTime())?i:m.toLocaleTimeString("ru-RU")}async function Vf(i){if(navigator.clipboard&&window.isSecureContext)try{return await navigator.clipboard.writeText(i),!0}catch{}const m=document.createElement("textarea");m.value=i,m.setAttribute("readonly","true"),m.style.position="fixed",m.style.opacity="0",m.style.pointerEvents="none",document.body.appendChild(m),m.select();let p=!1;try{p=document.execCommand("copy")}catch{p=!1}finally{document.body.removeChild(m)}return p}function Gf({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 Wf(i){return i.replace(/\r\n?/g,` +`).replace(/([^\n])\s+(Блок\s+\d+\.)/gi,`$1 + +$2`).replace(/([^\n])\s+(\d+\.\s)/g,`$1 +$2`)}function qf(i){const p=Wf(i).split(` +`),S=[];let C=[];const M=()=>{C.length!==0&&(S.push(C.join(` +`)),C=[])};for(const $ of p){const re=$.trimEnd(),Z=re.trim();if(!Z){M();continue}const se=/^Блок\s+\d+\./i.test(Z),K=/^\d+\.\s/.test(Z);(se||K)&&C.length>0&&M(),C.push(re)}return M(),S.length>0?S:[i]}function Kf(i,m){const p=[],S=/\*\*(.+?)\*\*/g;let C=0,M=0,$;for(;($=S.exec(i))!==null;)$.index>C&&(p.push(o.jsx("span",{children:i.slice(C,$.index)},`${m}-t-${M}`)),M+=1),p.push(o.jsx("strong",{children:$[1]},`${m}-b-${M}`)),M+=1,C=S.lastIndex;return C0?p:[o.jsx("span",{children:i},`${m}-raw`)]}function Jf(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 Yf(i,m=40){const p=i.replace(/\s+/g," ").trim();if(p.length<=m)return p;const S=p.split(" ").slice(0,3).join(" ").trim();return S.length>=10&&S.length<=m?`${S}…`:`${p.slice(0,m-1).trimEnd()}…`}function Ed(i){return i.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Xf(i){const m=i.replace(/\r\n?/g,` +`).split(` +`).map(C=>C.trim()).find(Boolean),p=Ed(m??"");return(p.split("|")[0]?.trim()??p).replace(/\s+/g," ").trim()}function Zf(i){const m=i.replace(/\r\n?/g,` +`).split(` +`).map(S=>S.trim()).find(Boolean);return!m||!/^\d+\.\s/.test(m)?!1:Ed(m).includes("|")}function ep(i,m){const p=m.replace(/\r\n?/g,` +`).replace(/\*\*(.+?)\*\*/g,"$1").split(` +`).map((C,M)=>{const $=C.trim();return M===0?$.replace(/^\d+\.\s*/,""):$}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!p)return null;const S=Xf(m)||p;return{message_id:i.message_id,source_text:p,anchor_text:S,preview_text:Yf(S)}}function tp(i,m,p,S){return qf(i.text).map((M,$)=>{const re=M.split(` +`),Z=i.role==="assistant"&&Zf(M),se=Z?ep(i,M):null,K=!!se&&m?.message_id===se?.message_id&&m?.source_text===se?.source_text,J=re.map((X,Re)=>o.jsx("p",{className:Jf(X),children:Kf(X,`line-${$}-${Re}`)},`line-${$}-${Re}`));return!Z||!se?o.jsx("div",{className:"assistant-msg-block",children:J},`block-${$}`):o.jsx("div",{className:K?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(K){S();return}p(se)},onKeyDown:X=>{if(!(X.key!=="Enter"&&X.key!==" ")){if(X.preventDefault(),K){S();return}p(se)}},children:J},`block-${$}`)})}function np({sessionId:i,conversation:m,inputValue:p,onInputChange:S,selectedContextChip:C,onSelectContextChip:M,onClearContextChip:$,useMock:re,onUseMockChange:Z,onSend:se,onClear:K,onSaveSession:J,busy:X,saveBusy:Re=!1,saveDisabled:me=!1,statusText:he,errorMessage:ye,showSaveAction:Ge=!1,showCommentAction:Ze=!1,onCommentAssistantMessage:We,isAssistantMessageCommented:Ae,canCommentAssistantMessage:U}){const oe=g.useRef(null),Ee=g.useRef(!0),Qe=g.useRef(null),[St,pt]=g.useState("idle"),[Gt,mt]=g.useState("чат");function b(ee=!1){oe.current&&(ee&&(Ee.current=!0),oe.current.scrollTop=oe.current.scrollHeight)}g.useEffect(()=>{Ee.current&&b()},[m]),g.useEffect(()=>()=>{Qe.current!==null&&window.clearTimeout(Qe.current)},[]);async function Ie(ee){if(m.length===0)return;const Y=Uf(i,m,ee),A=await Vf(Y);mt(ee==="technical"?"тех":"чат"),pt(A?"success":"error"),Qe.current!==null&&window.clearTimeout(Qe.current),Qe.current=window.setTimeout(()=>{pt("idle")},2200)}function Je(){if(!oe.current)return;const ee=oe.current,Y=ee.scrollHeight-ee.scrollTop-ee.clientHeight;Ee.current=Y<16}return o.jsx(ca,{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:()=>{Ie("default")},disabled:m.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Ie("technical")},disabled:m.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),Ge?o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>J?.(),disabled:Re||me,children:Re?"Сохраняю...":"Сохранить"}):null,o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>K(),disabled:X&&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:[he?o.jsx("span",{className:"assistant-live-status",children:he}):null,St==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Gt,")"]}):null,St==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),ye?o.jsx("p",{className:"error-text assistant-toolbar-error",children:ye}):null]}),o.jsx("div",{ref:oe,className:"assistant-chat-list",onScroll:Je,children:m.map((ee,Y)=>{const A=ee.role==="assistant"&&Ze&&typeof We=="function"&&(typeof U=="function"?U(ee,Y):!0),O=ee.role==="assistant"&&typeof Ae=="function"?Ae(ee,Y):!1;return o.jsxs("article",{className:`assistant-msg ${ee.role}`,children:[o.jsxs("header",{className:"assistant-msg-head",children:[o.jsxs("div",{className:"assistant-msg-head-main",children:[o.jsx("strong",{children:Qf(ee.role)}),o.jsx("span",{children:Hf(ee.created_at)})]}),ee.role==="assistant"&&Ze?o.jsx("div",{className:"assistant-msg-head-actions",children:o.jsx("button",{type:"button",className:O?"autoruns-comment-icon assistant-comment-btn commented":"autoruns-comment-icon assistant-comment-btn",onClick:()=>We?.(ee,Y),disabled:!A,title:A?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":A?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:o.jsx(Gf,{commented:O})})}):null]}),o.jsx("div",{className:"assistant-msg-body",children:tp(ee,C,M,$)}),ee.role==="assistant"&&ee.debug?o.jsxs("details",{className:"assistant-debug",children:[o.jsx("summary",{children:"Показать технический разбор"}),o.jsx(Nd,{value:ee.debug})]}):null]},ee.message_id)})}),o.jsxs("div",{className:"assistant-compose",children:[C?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:C.source_text,children:[o.jsx("span",{className:"assistant-compose-context-pill-text",children:C.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:p,onChange:ee=>S(ee.target.value),rows:4,placeholder:C?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),o.jsxs("div",{className:"button-row assistant-send-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:re,onChange:ee=>Z(ee.target.checked)}),"Mock-режим"]}),o.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{b(!0),se()},disabled:X||!p.trim(),children:X?"Выполняю...":"Отправить"})]})]})]})})}const na="http://127.0.0.1:1234/v1",ad="https://api.openai.com/v1",ia="qwen2.5-14b-instruct-1m",eu="unsloth/qwen3-30b-a3b-instruct-2507",rp=[{value:ia,label:"Qwen2.5 14B Instruct 1M"},{value:eu,label:"Qwen3 30B A3B Instruct 2507"}];function sp(i){return i.llmProvider!=="local"?"openai":i.model===eu?"local_qwen3":i.model===ia?"local_qwen25":"local_custom"}function op(i,m){const p=new Map;if(m)for(const S of rp)p.set(S.value,S);for(const S of i)p.has(S)||p.set(S,{value:S,label:S});return Array.from(p.values())}function lp({value:i,modelOptions:m,modelsBusy:p,onChange:S,onReloadModels:C,onTestConnection:M,onSaveLocalConfig:$,lastStatus:re,busy:Z,embedded:se=!1}){const K=i.llmProvider==="local",J=sp(i),X=op(m,K),Re=X.some(U=>U.value===i.model),[me,he]=g.useState(String(i.temperature)),[ye,Ge]=g.useState(String(i.maxOutputTokens));g.useEffect(()=>{he(String(i.temperature))},[i.temperature]),g.useEffect(()=>{Ge(String(i.maxOutputTokens))},[i.maxOutputTokens]);const Ze=U=>{const oe=U.replace(",",".").trim();if(!oe){he(String(i.temperature));return}const Ee=Number(oe);if(!Number.isFinite(Ee)){he(String(i.temperature));return}S({...i,temperature:Ee}),he(String(Ee))},We=U=>{const oe=U.trim();if(!oe){Ge(String(i.maxOutputTokens));return}const Ee=Number.parseInt(oe,10);if(!Number.isFinite(Ee)||Ee<=0){Ge(String(i.maxOutputTokens));return}S({...i,maxOutputTokens:Ee}),Ge(String(Ee))},Ae=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{children:["Provider",o.jsxs("select",{value:J,onChange:U=>{const oe=U.target.value;if(oe==="openai"){S({...i,llmProvider:"openai",baseUrl:ad});return}if(oe==="local_qwen25"){S({...i,llmProvider:"local",model:ia,baseUrl:na});return}if(oe==="local_qwen3"){S({...i,llmProvider:"local",model:eu,baseUrl:na});return}S({...i,llmProvider:"local",model:i.llmProvider==="local"?i.model:ia,baseUrl:na})},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:Re?i.model:"__manual__",onChange:U=>{const oe=U.target.value;oe!=="__manual__"&&S({...i,model:oe})},children:[o.jsx("option",{value:"__manual__",children:"Manual input"}),X.map(U=>o.jsx("option",{value:U.value,children:U.label},U.value))]})]}),o.jsxs("label",{children:["Model ID (manual / current)",o.jsx("input",{value:i.model,onChange:U=>S({...i,model:U.target.value}),placeholder:"qwen2.5-14b-instruct-1m or unsloth/qwen3-30b-a3b-instruct-2507"})]}),K?null:o.jsxs("label",{className:"full-width",children:["OpenAI API Key",o.jsx("input",{type:"password",value:i.apiKey,onChange:U=>S({...i,apiKey:U.target.value}),placeholder:"sk-..."})]}),o.jsxs("label",{className:K?"full-width":void 0,children:[K?"Local server base URL":"Base URL",o.jsx("input",{value:i.baseUrl,onChange:U=>S({...i,baseUrl:U.target.value}),placeholder:K?na:ad})]}),o.jsxs("label",{children:["Temperature",o.jsx("input",{type:"number",step:"0.1",value:me,onChange:U=>he(U.target.value),onBlur:U=>Ze(U.target.value),onKeyDown:U=>{U.key==="Enter"&&Ze(U.target.value)}})]}),o.jsxs("label",{children:["Max output tokens",o.jsx("input",{type:"number",value:ye,onChange:U=>Ge(U.target.value),onBlur:U=>We(U.target.value),onKeyDown:U=>{U.key==="Enter"&&We(U.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:()=>C(),disabled:Z||p,children:p?"Loading models...":"Load model list"}),o.jsx("button",{type:"button",onClick:()=>M(),disabled:Z,children:Z?"Checking...":"Test connection"})]})]});return se?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsxs("div",{className:"embedded-panel-section-header",children:[o.jsxs("div",{children:[o.jsx("h4",{children:"LLM Connector"}),o.jsx("p",{children:"Switch between OpenAI cloud and local OpenAI-compatible server."})]}),o.jsx("span",{className:"status-chip",children:re||"Status: not checked"})]}),Ae]}):o.jsx(ca,{title:"LLM Connector",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:o.jsx("span",{className:"status-chip",children:re||"Status: not checked"}),children:Ae})}function ap({value:i,onChange:m,presets:p,selectedPresetId:S,onSelectPreset:C,onLoadPreset:M,onSavePreset:$,onResetDefaults:re,onDiffPrevious:Z,presetName:se,onPresetNameChange:K,diffSummary:J,embedded:X=!1}){const Re=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"prompt-manager-grid",children:[o.jsxs("label",{children:["Системный prompt",o.jsx("textarea",{value:i.systemPrompt,onChange:me=>m({...i,systemPrompt:me.target.value}),rows:6})]}),o.jsxs("label",{children:["Developer / Instruction prompt",o.jsx("textarea",{value:i.developerPrompt,onChange:me=>m({...i,developerPrompt:me.target.value}),rows:6})]}),o.jsxs("label",{children:["Domain prompt",o.jsx("textarea",{value:i.domainPrompt,onChange:me=>m({...i,domainPrompt:me.target.value}),rows:6})]}),o.jsxs("label",{children:["Schema notes",o.jsx("textarea",{value:i.schemaNotes,onChange:me=>m({...i,schemaNotes:me.target.value}),rows:6})]}),o.jsxs("label",{className:"full-width",children:["Few-shot examples",o.jsx("textarea",{value:i.fewShotExamples,onChange:me=>m({...i,fewShotExamples:me.target.value}),rows:8})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("select",{value:S,onChange:me=>C(me.target.value),children:[o.jsx("option",{value:"",children:"Выберите preset..."}),p.map(me=>o.jsx("option",{value:me.id,children:me.name},me.id))]}),o.jsx("button",{type:"button",onClick:()=>M(),children:"Загрузить preset"}),o.jsx("input",{value:se,onChange:me=>K(me.target.value),placeholder:"Имя для сохранения"}),o.jsx("button",{type:"button",onClick:()=>$(),children:"Сохранить preset"}),o.jsx("button",{type:"button",onClick:()=>Z(),children:"Diff с предыдущим"}),o.jsx("button",{type:"button",onClick:()=>re(),children:"Сбросить к default"})]}),J?o.jsx("p",{className:"diff-summary",children:J}):null]});return X?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsx("div",{className:"embedded-panel-section-header",children:o.jsxs("div",{children:[o.jsx("h4",{children:"Normalizer / eval prompts"}),o.jsx("p",{children:"Эти поля управляют декомпозицией и eval-прогонами, а не live-ответом ассистента."})]})}),Re]}):o.jsx(ca,{title:"Normalizer / eval prompts",subtitle:"Эти поля управляют декомпозицией и eval-прогонами, а не live-ответом ассистента.",children:Re})}const Vi={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},ra="needs_dialog_policy_fix",Tt="__all__",ua="__live__:",id="ndc_autoruns_ui_config_v1",ud="ndc-autoruns-save",ip=180,Ho=30,Gi=["Анализ запроса","Получение данных","Подготовка ответа"];function up(i,m){const p=i.trim();if(!p)return"";if(!m)return p;const S=p.toLowerCase(),C=m.anchor_text.trim(),M=C.toLowerCase();return M&&S.includes(M)?p:`По выбранному объекту "${C}": ${p}`}const Pd=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function cp(i=Pd){return i.reduce((m,p)=>(m[p.id]=p.defaultPrompt,m),{})}const cd={mode:"saved_user_sessions",count:24,personalityId:"general",personalityPrompts:cp(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function Wi(i){const m=String(i??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(m)?m:""}function dd(i){const m=typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):160;return Math.max(110,Math.min(520,m))}function dp(i){const m=i.getFullYear(),p=String(i.getMonth()+1).padStart(2,"0"),S=String(i.getDate()).padStart(2,"0"),C=String(i.getHours()).padStart(2,"0"),M=String(i.getMinutes()).padStart(2,"0");return`${m}-${p}-${S}T${C}:${M}`}function fd(){const i=new Date;return i.setDate(i.getDate()-14),dp(i)}function sa(i){if(!i.trim())return;const m=Date.parse(i);if(Number.isFinite(m))return new Date(m).toISOString()}function pn(i){if(!i)return"нет данных";const m=Date.parse(i);return Number.isFinite(m)?new Date(m).toLocaleString("ru-RU"):i}function pd(i){const m=typeof i.case_message_index=="number"?i.case_message_index:typeof i.message_index=="number"?i.message_index:null;if(m===null||m<0)return null;const p=Math.floor(m/2)+1,S=String(p).padStart(3,"0"),C=i.role==="assistant"?"ответ":"вопрос";return`${S} ${C}`}function qi(i){return i==="saved_user_sessions"?"Пользовательские сессии":i}function Td(i){return i?i.context?.agent_run===!0||i.context?.saved_case_set_kind==="agent_semantic_scenario"?!0:typeof i.title=="string"&&i.title.trim().toUpperCase().startsWith("AGENT"):!1}function Ki(i){const m=i.title??pn(i.created_at);return Td(i)&&!m.trim().toUpperCase().startsWith("AGENT")?`AGENT | ${m}`:m}function fp(i){const m=i[i.length-1];return`Ручная сессия ${pn(m?.created_at??new Date().toISOString())}`}function pp(i,m){return m<=0?0:Math.max(0,Math.min(100,Number((i/m*100).toFixed(1))))}function oa(i){return typeof i!="number"?"нет данных":`${i.toFixed(1)}%`}function mp(i){return i==="assistant_stage1"?"assistant/s1":i==="assistant_stage2"?"assistant/s2":i==="assistant_p0"?"assistant/p0":i}function md(i){return i==="up"?"Рост":i==="down"?"Регресс":"Без изменений"}function Ji(i){const m=Math.max(1,Math.min(5,Math.round(i)));return`${"●".repeat(m)}${"○".repeat(5-m)}`}function hd(i){return i.length===0?o.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):o.jsx("div",{className:"autoruns-coverage-list",children:i.map(m=>{const p=pp(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," (",p,"%)"]})]}),o.jsx("div",{className:"autoruns-coverage-bar",children:o.jsx("div",{style:{width:`${p}%`}})})]},m.domain)})})}function aa(i){return`${ua}${i}`}function Zs(i){return i.startsWith(ua)}function gd(i){return i.startsWith(ua)?i.slice(ua.length):""}function Rd(i){const m=i.report_summary?.run_timestamp??i.created_at,p=Math.max(0,i.total_cases-i.completed_cases);return{run_id:aa(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:p,domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]}}function Vo(i,m){const p=Rd(i),S=i.cases.map(K=>({case_id:K.case_id,domain:null,query_class:null,status:K.status==="completed"?"closed":K.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${i.run_id}-${K.case_id}`,dialog_available:K.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),M=m!==Tt&&S.some(K=>K.case_id===m)?m:S.length>0?Tt:"",$={ok:!0,run:p,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:S,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}:{}},re=[];let Z=0;if(M===Tt)for(const K of i.cases)for(let J=0;JJ.case_id===M)??null;for(let J=0;J<(K?.messages.length??0);J+=1){const X=K?.messages[J];X&&re.push({...X,message_index:J,case_id:M,case_message_index:J,commented:!1,annotation:null})}}const se={ok:!0,run_id:p.run_id,case_id:M,source:"assistant_session",session_id:M===Tt?`${i.run_id}::__all__`:`${i.run_id}-${M}`,messages:re,decomposition:[],assistant_mode:{status:i.status,completed_cases:i.completed_cases,total_cases:i.total_cases},annotations:[]};return{detail:$,dialog:se,caseId:M}}function hp({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 vd({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 yd(){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 xd(){return o.jsxs("svg",{className:"autoruns-question-grip-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[o.jsx("circle",{cx:"4",cy:"4",r:"1"}),o.jsx("circle",{cx:"8",cy:"4",r:"1"}),o.jsx("circle",{cx:"12",cy:"4",r:"1"}),o.jsx("circle",{cx:"4",cy:"8",r:"1"}),o.jsx("circle",{cx:"8",cy:"8",r:"1"}),o.jsx("circle",{cx:"12",cy:"8",r:"1"}),o.jsx("circle",{cx:"4",cy:"12",r:"1"}),o.jsx("circle",{cx:"8",cy:"12",r:"1"}),o.jsx("circle",{cx:"12",cy:"12",r:"1"})]})}function gp({expanded:i}){return o.jsx("svg",{className:i?"autoruns-card-chevron-svg expanded":"autoruns-card-chevron-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M3.5 6.2 8 10.4l4.5-4.2"})})}function vp(){return o.jsx("svg",{className:"autoruns-card-launch-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M5 3.8 12 8l-7 4.2Z"})})}function yp(){return o.jsx("svg",{className:"autoruns-card-stop-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("rect",{x:"4.2",y:"4.2",width:"7.6",height:"7.6",rx:"0.8"})})}async function _d(i){if(navigator.clipboard&&window.isSecureContext)try{return await navigator.clipboard.writeText(i),!0}catch{}const m=document.createElement("textarea");m.value=i,m.setAttribute("readonly","true"),m.style.position="fixed",m.style.opacity="0",m.style.pointerEvents="none",document.body.appendChild(m),m.select();let p=!1;try{p=document.execCommand("copy")}catch{p=!1}finally{document.body.removeChild(m)}return p}function la({expanded:i}){return o.jsx("svg",{className:i?"autoruns-group-chevron-svg expanded":"autoruns-group-chevron-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M3.5 6.2 8 10.4l4.5-4.2"})})}function xp({connection:i,modelOptions:m,modelsBusy:p,connectionStatus:S,connectionBusy:C,onConnectionChange:M,onReloadModels:$,onSaveLocalConfig:re,onTestConnection:Z,prompts:se,onPromptsChange:K,promptPresets:J,selectedPresetId:X,onSelectPreset:Re,onLoadPreset:me,onSavePreset:he,onResetDefaults:ye,onDiffPrevious:Ge,presetName:Ze,onPresetNameChange:We,diffSummary:Ae,assistantPromptVersion:U,decompositionPromptVersion:oe,showSettingsMode:Ee,showAutoRunsMode:Qe,showAssistantMode:St,showProgressMode:pt,showCommentsMode:Gt,onLog:mt}){const[b,Ie]=g.useState({...Vi,fromLocal:fd()}),[Je,ee]=g.useState(""),[Y,A]=g.useState(null),[O,L]=g.useState(null),[y,k]=g.useState(null),[te,ae]=g.useState([]),[ce,xe]=g.useState("all"),[we,je]=g.useState(!1),[Ce,ht]=g.useState(null),[nn,xr]=g.useState([]),[Tn,mn]=g.useState(""),[_e,Wt]=g.useState(""),[qe,wt]=g.useState(""),[rn,hn]=g.useState(Pd),[le,gt]=g.useState(cd),[_r,Rn]=g.useState([]),[Jr,nr]=g.useState(Ho),[Le,jt]=g.useState(""),[qt,gn]=g.useState(""),[de,Mn]=g.useState([]),[vt,Yr]=g.useState(!1),[at,An]=g.useState(null),[In,Rt]=g.useState(""),[vn,sn]=g.useState(null),[pe,Mt]=g.useState(null),[Ue,yn]=g.useState(null),[Sr,Xr]=g.useState(null),[Ln,zt]=g.useState(!1),[Dn,On]=g.useState(!1),[zn,$n]=g.useState(!1),[E,q]=g.useState(!1),[B,Pe]=g.useState(!1),[et,Go]=g.useState(!1),[Zr,Wo]=g.useState(!1),[Fn,eo]=g.useState(""),wr=g.useRef(null),[qo,to]=g.useState("idle"),[Ko,Jo]=g.useState("чат"),[no,tt]=g.useState(""),[it,$e]=g.useState(""),[on,es]=g.useState([]),[jr,bn]=g.useState([]),[ro,_s]=g.useState(""),[kr,$t]=g.useState(null),[so,Kt]=g.useState(!1),[Yo,Xo]=g.useState(!1),[da,Un]=g.useState(""),[Ss,Jt]=g.useState(""),[ws,Cr]=g.useState(String(Vi.limit)),[fa,Bn]=g.useState(String(cd.count)),[js,ks]=g.useState(160),[Nr,Qn]=g.useState(""),[ts,fe]=g.useState(!1),[rr,oo]=g.useState(!0),[Hn,lo]=g.useState(!0),[sr,ao]=g.useState(!0),[Vn,ns]=g.useState(!0),[ie,st]=g.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:ra,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[ge,At]=g.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),[yt,kt]=g.useState({open:!1,title:"",saving:!1,error:""}),[Yt,Er]=g.useState({open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""}),[It,Cs]=g.useState({open:!1,generationId:"",title:"",saving:!1,error:""}),Ns=g.useRef(!1),or=g.useRef(null),rs=g.useRef(null),Ye=le.mode==="saved_user_sessions",De=g.useMemo(()=>_r.filter(a=>a.mode===le.mode),[_r,le.mode]),Pr=g.useMemo(()=>De.slice(0,Jr),[Jr,De]),Gn=Math.max(0,De.length-Pr.length),Me=g.useMemo(()=>De.find(a=>a.generation_id===Le)??De[0]??null,[Le,De]),lr=g.useMemo(()=>we?te.filter(a=>!a.resolved):te,[te,we]),Oe=lr.find(a=>a.annotation_id===Tn)??null,Es=y?.messages.find(a=>a.message_index===ie.messageIndex)??null,Ps=g.useMemo(()=>{if(!y||ie.messageIndex<0)return null;for(let a=ie.messageIndex-1;a>=0;a-=1){const c=y.messages[a];if(c?.role==="user")return c}return null},[ie.messageIndex,y]),Tr=g.useMemo(()=>{const a=new Map;for(const c of jr)c.message_id&&a.set(c.message_id,c);return a},[jr]),io=ge.messageIndex>=0?on[ge.messageIndex]??null:null,xn=g.useMemo(()=>{if(ge.messageIndex<0)return null;for(let a=ge.messageIndex-1;a>=0;a-=1){const c=on[a];if(c?.role==="user")return c}return null},[ge.messageIndex,on]),Xt=g.useMemo(()=>{const a=lr.map(f=>({source:"autorun",key:`autorun:${f.annotation_id}`,updated_at:f.updated_at,rating:f.rating,autorun:f,assistant:null})),c=jr.map(f=>({source:"assistant_live",key:`assistant:${f.annotation_id}`,updated_at:f.updated_at,rating:f.rating,autorun:null,assistant:f}));return[...a,...c].sort((f,w)=>Date.parse(w.updated_at)-Date.parse(f.updated_at))},[jr,lr]),ss=g.useMemo(()=>{if(Xt.length===0)return null;const a=Xt.reduce((c,f)=>c+f.rating,0)/Xt.length;return Number(a.toFixed(2))},[Xt]),Ts=g.useMemo(()=>{const a=[...Y?.items??[]];return Ue&&a.unshift(Rd(Ue)),_e&&!a.some(c=>c.run_id===_e)&&O?.run&&a.unshift(O.run),a},[Ue,Y?.items,O?.run,_e]),H=g.useCallback(a=>{mt?.(`[autoruns] ${a}`)},[mt]),ar=g.useCallback(async a=>{const c=String(a??"").trim();if(!c){bn([]);return}try{const f=await Te.loadAssistantAnnotations({session_id:c,limit:400});bn(f.items??[])}catch(f){const w=f instanceof Error?f.message:String(f);H(`Assistant live annotations load error: ${w}`)}},[H]),ir=g.useCallback(a=>{At(c=>c.saving&&!a?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),ut=g.useCallback(a=>{kt(c=>c.saving&&!a?.force?c:{open:!1,title:"",saving:!1,error:""})},[]),_n=g.useCallback(a=>{Er(c=>c.saving&&!a?.force?c:{open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""})},[]),Rr=g.useCallback(a=>{Cs(c=>c.saving&&!a?.force?c:{open:!1,generationId:"",title:"",saving:!1,error:""})},[]);g.useEffect(()=>()=>{wr.current!==null&&window.clearTimeout(wr.current)},[]);const Wn=g.useCallback(async(a,c,f)=>{a.stopPropagation(),a.preventDefault();const w=String(c??"").trim();if(w)try{await _d(w),H(`${f} copied: ${w}`)}catch(I){const ue=I instanceof Error?I.message:String(I);tt(`Копирование ${f}: ${ue}`),H(`copy ${f} error: ${ue}`)}},[H]),Zo=g.useCallback(async a=>{if(!y||y.messages.length===0||!_e)return;const c=Bf({runId:_e,caseId:qe||y.case_id||"n/a",sessionId:y.session_id,source:y.source,messages:y.messages,decomposition:y.decomposition,assistantMode:y.assistant_mode,annotations:y.annotations,runSummary:O?.run??null,coverage:O?.coverage??null,report:O?.report??null},a),f=await _d(c);Jo(a==="technical"?"тех":"чат"),to(f?"success":"error"),wr.current!==null&&window.clearTimeout(wr.current),wr.current=window.setTimeout(()=>{to("idle")},2200),H(f?`Dialog ${a==="technical"?"technical":"chat"} copied: run=${_e} case=${qe||y.case_id}`:`Dialog copy failed: run=${_e} case=${qe||y.case_id}`)},[y,H,O,qe,_e]);function uo(){let a=0;Un(Gi[0]);const c=window.setInterval(()=>{a=Math.min(a+1,Gi.length-1),Un(Gi[a])},650);return()=>window.clearInterval(c)}const co=g.useCallback(()=>{$e(""),es([]),bn([]),_s(""),$t(null),Un(""),Jt(""),ir({force:!0}),H("Live-чат ассистента в истории автопрогонов сброшен.")},[ir,H]),os=g.useCallback(async()=>{const a=up(ro,kr);if(!a)return;Xo(!0),Jt(""),_s(""),es(f=>[...f,{message_id:`autoruns-live-${Date.now()}`,session_id:it||"pending",role:"user",text:a,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=uo();try{const f=await Te.sendAssistantMessage({connection:i,userMessage:a,sessionId:it||void 0,promptVersion:U,useMock:so});$e(f.session_id),es(f.conversation),await ar(f.session_id),Un("Ответ готов"),H(`Live-ответ ассистента получен: trace=${f.debug.trace_id}`)}catch(f){const w=f instanceof Error?f.message:String(f);Jt(w),Un("Ошибка ассистента"),H(`Live-чат ассистента: ошибка отправки сообщения: ${w}`)}finally{c(),Xo(!1)}},[ro,kr,it,so,U,i,ar,H]),Rs=g.useCallback(()=>{if(!it.trim()||on.length===0){Jt("Сначала получите хотя бы один ответ в живой сессии ассистента.");return}Jt(""),kt({open:!0,title:fp(on),saving:!1,error:""})},[on,it]),el=g.useCallback(async()=>{const a=it.trim(),c=yt.title.trim();if(!a){kt(f=>({...f,error:"Активная сессия ассистента не найдена."}));return}if(!c){kt(f=>({...f,error:"Укажите название сессии."}));return}kt(f=>({...f,saving:!0,error:""}));try{const f=await Te.saveAutoRunAssistantSession({session_id:a,title:c,generated_by:le.generatedBy.trim()||void 0,context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:U,decomposition_prompt_version:oe}});Rn(w=>[f.generation,...w.filter(I=>I.generation_id!==f.generation.generation_id)]),gt(w=>({...w,mode:"saved_user_sessions"})),jt(f.generation.generation_id),ut({force:!0}),H(`Живая сессия сохранена в автопрогоны: ${f.generation.generation_id}`)}catch(f){const w=f instanceof Error?f.message:String(f);kt(I=>({...I,saving:!1,error:w})),H(`Assistant live save error: ${w}`)}},[yt.title,it,U,le.generatedBy,ut,i.llmProvider,i.model,oe,H]),tl=g.useCallback(a=>{const c=a.trim();if(!c){Cr(String(b.limit));return}if(!/^\d+$/.test(c)){Cr(String(b.limit));return}const f=Number.parseInt(c,10);if(!Number.isFinite(f)){Cr(String(b.limit));return}const w=Math.max(1,Math.min(500,f));w!==b.limit&&Ie(I=>({...I,limit:w})),Cr(String(w))},[b.limit]),nl=g.useCallback(a=>{const c=a.trim();if(!c){Bn(String(le.count));return}if(!/^\d+$/.test(c)){Bn(String(le.count));return}const f=Number.parseInt(c,10);if(!Number.isFinite(f)){Bn(String(le.count));return}const w=Math.max(1,Math.min(200,f));w!==le.count&>(I=>({...I,count:w})),Bn(String(w))},[le.count]),rl=g.useCallback(a=>{ks(dd(a))},[]),Ms=g.useCallback(a=>{const c=a.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&rl(c)},[rl]),ls=g.useCallback(async()=>{Wo(!0);try{const a=await Te.loadAutoRunAnnotations({limit:800,manual_case_decision:ce});ae(a.items),ht(a.manual_case_decision_schema??null),xr(a.available_manual_case_decisions??[]),mn(c=>a.items.length===0?"":a.items.some(f=>f.annotation_id===c)?c:a.items[0].annotation_id)}catch(a){H(`Annotations load error: ${a instanceof Error?a.message:String(a)}`)}finally{Wo(!1)}},[ce,H]),qn=g.useCallback(async()=>{$n(!0);try{const a=await Te.loadAutoRunAutogenHistory({limit:ip});Rn(a.items),nr(Ho)}catch(a){H(`Autogen history load error: ${a instanceof Error?a.message:String(a)}`)}finally{$n(!1)}},[H]),sl=g.useCallback(async()=>{try{const c=(await Te.loadAutoRunAutogenPersonalityCatalog()).items.map(f=>({id:String(f.id??"").trim(),label:String(f.label??"").trim(),domain:typeof f.domain=="string"?f.domain.trim():"",defaultPrompt:String(f.default_prompt??"").trim()})).filter(f=>f.id.length>0&&f.label.length>0);if(c.length===0)return;hn(c.map(f=>({id:f.id,label:f.label,domain:f.domain||"",defaultPrompt:f.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(a){H(`Autogen personality catalog load error: ${a instanceof Error?a.message:String(a)}`)}},[H]),Sn=g.useCallback(async()=>{On(!0);try{const a=await Te.loadAutoRunPostAnalysis({run_id:_e&&!Zs(_e)?_e:void 0,limit_per_queue:30,annotation_limit:1500,from:sa(b.fromLocal),to:sa(b.toLocal),target:b.target,mode:b.mode,use_mock:b.useMock,prompt_contains:b.promptContains.trim()||void 0});Xr(a)}catch(a){H(`Post-analysis load error: ${a instanceof Error?a.message:String(a)}`),Xr(null)}finally{On(!1)}},[b.fromLocal,b.mode,b.promptContains,b.target,b.toLocal,b.useMock,H,_e]),as=g.useCallback(async(a,c)=>{if(Zs(a)){const f=gd(a);if(Ue&&Ue.job_id===f){const w=Vo(Ue,c);Wt(a),wt(w.caseId),k(w.dialog);return}k(null);return}Go(!0);try{const f=await Te.loadAutoRunCaseDialog(a,c);k(f)}catch(f){const w=f instanceof Error?f.message:String(f);tt(`Диалог кейса: ${w}`),k(null),H(`Dialog load error for ${a}/${c}: ${w}`)}finally{Go(!1)}},[Ue,H]),wn=g.useCallback(async(a,c)=>{if(Zs(a)){const f=gd(a);if(Ue&&Ue.job_id===f){const w=Vo(Ue,c??Tt);Wt(a),wt(w.caseId),L(w.detail),k(w.dialog);return}Wt(a),wt(""),L(null),k(null);return}Pe(!0);try{const f=await Te.loadAutoRunDetail(a);L(f);const w=(c&&(c===Tt||f.cases.some(I=>I.case_id===c))?c:"")||(f.cases.length>0?Tt:"")||"";Wt(a),wt(w),w?await as(a,w):k(null)}catch(f){const w=f instanceof Error?f.message:String(f);tt(`Детализация прогона: ${w}`),L(null),k(null),H(`Run detail load error for ${a}: ${w}`)}finally{Pe(!1)}},[Ue,as,H]),Kn=g.useCallback(async a=>{q(!0),tt("");try{const c=await Te.loadAutoRunsHistory({from:sa(b.fromLocal),to:sa(b.toLocal),target:b.target,mode:b.mode,use_mock:b.useMock,prompt_contains:b.promptContains.trim()||void 0,limit:b.limit});if(A(c),c.items.length===0){Wt(""),wt(""),L(null),k(null);return}const f=a?.keepSelection??!0,w=a?.preferredRunId??"",I=a?.preferredCaseId??"",ue=f&&w&&c.items.some(nt=>nt.run_id===w)?w:c.items[0].run_id;await wn(ue,f?I:void 0),Sn()}catch(c){const f=c instanceof Error?c.message:String(c);tt(`История прогонов: ${f}`),H(`History load error: ${f}`)}finally{q(!1)}},[b.fromLocal,b.limit,b.mode,b.promptContains,b.target,b.toLocal,b.useMock,Sn,wn,H]),Lt=g.useCallback(()=>{or.current!==null&&(window.clearTimeout(or.current),or.current=null)},[]),fo=g.useCallback(async a=>{try{const c=await Te.loadEvalRunAsyncStatus(a);yn(c.job);const f=aa(a);if(_e===f){const w=Vo(c.job,qe||Tt);L(w.detail),k(w.dialog),wt(w.caseId)}if(c.job.status==="completed"){Lt(),zt(!1),fe(!1),Qn("");const w=c.job.report_summary?.run_id??c.job.run_id;await Kn({keepSelection:!0,preferredRunId:w||_e,preferredCaseId:Tt}),await qn(),yn(null);return}if(c.job.status==="failed"){Lt(),zt(!1),fe(!1),Qn(""),tt(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),H(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}if(c.job.status==="canceled"){Lt(),zt(!1),fe(!1),Qn(""),yn(null),await Kn({keepSelection:!1}),await qn(),H(`Autogen async run canceled: job=${c.job.job_id}`);return}Lt(),or.current=window.setTimeout(()=>{fo(a)},500)}catch(c){Lt(),zt(!1),fe(!1),Qn("");const f=c instanceof Error?c.message:String(c);tt(`Запуск прогонов: ${f}`),H(`Autogen async status error: ${f}`)}},[qn,Kn,H,qe,_e,Lt]),ol=g.useCallback(async(a,c)=>{Lt(),zt(!0),tt("");try{const f=a??Me;if(!f)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const I=(c??(Me?.generation_id===f.generation_id?de:f.questions)).map(So=>So.trim()).filter(So=>So.length>0);if(I.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const ue=b.useMock==="true",nt=Wi(Je),Ft=f.mode==="saved_user_sessions",Dr=(await Te.startEvalRunAsync({connection:i,prompts:se,promptVersion:U,mode:"single-pass-strict",caseSetFile:Ft?void 0:f.saved_case_set_file??void 0,useMock:ue,evalTarget:"assistant_stage1",questions:Ft?void 0:I,scenarioQuestions:Ft?I:void 0,scenarioTitle:Ft?f.title??void 0:void 0,analysisDate:Ft?void 0:nt||void 0})).job;Qn(f.generation_id),fe(!1),yn(Dr);const wa=aa(Dr.job_id),_o=Vo(Dr,Tt);Wt(wa),wt(_o.caseId),L(_o.detail),k(_o.dialog),H(`Запущен async-прогон job=${Dr.job_id}, run_id=${Dr.run_id}, вопросов=${I.length}`+(f.saved_case_set_file?`, base_case_set=${f.saved_case_set_file}`:"")+(Ft?", replay_mode=saved_user_session_scenario":nt?`, analysis_date=${nt}`:", analysis_date=current_state")),fo(Dr.job_id)}catch(f){const w=f instanceof Error?f.message:String(f);tt(`Запуск прогонов: ${w}`),H(`Autogen run error: ${w}`),zt(!1),fe(!1),Qn("")}},[Je,U,i,de,b.useMock,H,fo,se,Me,Lt]),As=g.useCallback(async()=>{const a=Ue?.job_id??"";if(!a){zt(!1),fe(!1),Qn(""),yn(null),Lt();return}fe(!0),tt("");try{const c=await Te.cancelEvalRunAsync(a);Lt(),yn(null),zt(!1),fe(!1),Qn(""),await Kn({keepSelection:!1}),await qn(),H(`Autogen async run stopped: job=${c.job.job_id}`)}catch(c){const f=c instanceof Error?c.message:String(c);fe(!1),tt(`Остановка прогона: ${f}`),H(`Autogen stop error: ${f}`)}},[Ue,qn,Kn,H,Lt]),pa=g.useCallback(a=>{if(a.role!=="assistant")return;const c=a.case_id??qe,f=a.case_message_index??a.message_index;st({open:!0,caseId:c,caseMessageIndex:f,messageIndex:a.message_index,rating:a.annotation?.rating??3,comment:a.annotation?.comment??"",manualCaseDecision:a.annotation?.manual_case_decision??ra,annotationAuthor:a.annotation?.annotation_author??le.generatedBy,saving:!1,error:""})},[le.generatedBy,qe]),Is=g.useCallback(a=>{st(c=>c.saving&&!a?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:ra,annotationAuthor:le.generatedBy,saving:!1,error:""})},[le.generatedBy]),ma=g.useCallback(async()=>{const a=_e,c=ie.caseId,f=ie.caseMessageIndex;if(!(!a||!c||f<0)){if(Zs(a)){st(w=>({...w,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ie.comment.trim()){st(w=>({...w,error:"Добавьте комментарий."}));return}st(w=>({...w,saving:!0,error:""}));try{await Te.saveAutoRunAnnotation({run_id:a,case_id:c,message_index:f,rating:ie.rating,comment:ie.comment.trim(),manual_case_decision:ie.manualCaseDecision,annotation_author:ie.annotationAuthor.trim()||void 0}),Is({force:!0}),Promise.all([wn(a,qe),ls(),Sn()]).catch(w=>{const I=w instanceof Error?w.message:String(w);tt(`Обновление после комментария: ${I}`),H(`Comment refresh error: ${I}`)})}catch(w){st(I=>({...I,saving:!1,error:w instanceof Error?w.message:String(w)}))}}},[Is,ie.annotationAuthor,ie.caseId,ie.caseMessageIndex,ie.comment,ie.manualCaseDecision,ie.rating,ls,Sn,wn,H,qe,_e]),ll=g.useCallback(a=>a.role==="assistant",[]),ha=g.useCallback(a=>a.role==="assistant"&&Tr.has(a.message_id),[Tr]),ga=g.useCallback((a,c)=>{if(a.role!=="assistant")return;const f=it.trim(),w=String(a.session_id??"").trim();if(!(f||w)){Jt("Сначала получите ответ ассистента в активной сессии.");return}!f&&w&&$e(w);const ue=Tr.get(a.message_id)??null;Jt(""),At({open:!0,messageIndex:c,rating:ue?.rating??3,comment:ue?.comment??"",annotationAuthor:ue?.annotation_author??"manual_reviewer",saving:!1,error:""})},[Tr,it]),va=g.useCallback(async()=>{if(ge.messageIndex<0)return;if(!ge.comment.trim()){At(f=>({...f,error:"Добавьте комментарий."}));return}const a=on[ge.messageIndex]??null,c=it.trim()||(a?.role==="assistant"?String(a.session_id??"").trim():"");if(!c){At(f=>({...f,error:"Сессия ассистента не найдена."}));return}At(f=>({...f,saving:!0,error:""}));try{const f=await Te.saveAssistantAnnotation({session_id:c,message_index:ge.messageIndex,rating:ge.rating,comment:ge.comment.trim(),annotation_author:ge.annotationAuthor.trim()||void 0});bn(w=>{const I=[...w],ue=I.findIndex(nt=>nt.annotation_id===f.annotation.annotation_id);return ue>=0?I[ue]=f.annotation:I.unshift(f.annotation),I.sort((nt,Ft)=>Date.parse(Ft.updated_at)-Date.parse(nt.updated_at))}),ir({force:!0})}catch(f){const w=f instanceof Error?f.message:String(f);At(I=>({...I,saving:!1,error:w}))}},[ge.annotationAuthor,ge.comment,ge.messageIndex,ge.rating,on,it,ir]);g.useCallback(a=>{if(!Me||Me.mode!=="saved_user_sessions")return;const c=de[a]??"";Er({open:!0,generationId:Me.generation_id,questionIndex:a,questionText:c,saving:!1,error:""})},[de,Me]);const ya=g.useCallback(async()=>{const a=Yt.generationId,c=Yt.questionIndex;if(!a||c<0)return;const f=de.filter((w,I)=>I!==c);if(f.length===0){Er(w=>({...w,error:"Нельзя удалить последний вопрос из сохраненной сессии."}));return}Er(w=>({...w,saving:!0,error:""}));try{const w=await Te.updateAutoRunAutogenQuestions({generation_id:a,questions:f});Rn(I=>I.map(ue=>ue.generation_id===a?w.generation:ue)),Mn(w.generation.questions),_n({force:!0}),H(`Обновлена сохраненная сессия: ${a}`)}catch(w){const I=w instanceof Error?w.message:String(w);Er(ue=>({...ue,saving:!1,error:I})),H(`Saved session question delete error: ${I}`)}},[_n,de,H,Yt.generationId,Yt.questionIndex]),Jn=g.useCallback(async(a,c)=>{const f=Me?.generation_id??"",w=c?.revertQuestions??de;if(Mn(a),!f)return!0;Yr(!0);try{const I=await Te.updateAutoRunAutogenQuestions({generation_id:f,questions:a});return Rn(ue=>ue.map(nt=>nt.generation_id===f?I.generation:nt)),Mn([...I.generation.questions??[]]),c?.successLog&&H(c.successLog),!0}catch(I){const ue=I instanceof Error?I.message:String(I);return Mn(w),tt(`Вопросы к запуску: ${ue}`),H(`Autogen questions update error: ${ue}`),!1}finally{Yr(!1)}},[de,H,Me]),al=g.useCallback(a=>{An(a),Rt(de[a]??"")},[de]),Yn=g.useCallback(()=>{An(null),Rt("")},[]),Mr=g.useCallback(async a=>{if(a===null)return;const c=de[a]??"",f=In.trim();if(!f||f===c){Yn();return}const w=de.map((ue,nt)=>nt===a?f:ue);await Jn(w,{successLog:`Список вопросов обновлен: ${Me?.generation_id??"local"}`,revertQuestions:de})&&Yn()},[de,In,Me,Yn,Jn]),Ar=g.useCallback(()=>{Mr(at)},[Mr,at]),il=g.useCallback(a=>{if(a.key==="Enter"){a.preventDefault(),Mr(at);return}a.key==="Escape"&&(a.preventDefault(),Yn())},[Mr,at,Yn]),po=g.useCallback(async()=>{const a=[...de,"Новый вопрос"],c=a.length-1;await Jn(a,{successLog:`В список добавлен вопрос: ${Me?.generation_id??"local"}`,revertQuestions:de})&&(An(c),Rt(a[c]))},[de,Me,Jn]),mo=g.useCallback(async a=>{if(de.length<=1){tt("В списке должен остаться хотя бы один вопрос.");return}const c=de.filter((w,I)=>I!==a);await Jn(c,{successLog:`Из списка удален вопрос: ${Me?.generation_id??"local"}`,revertQuestions:de})&&(An(w=>w===null?w:w===a?null:w>a?w-1:w),Rt(""))},[de,Me,Jn]),ho=g.useCallback((a,c)=>{if(vt){a.preventDefault();return}sn(c),Mt(c),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",String(c))},[vt]),go=g.useCallback((a,c)=>{a.preventDefault(),pe!==c&&Mt(c),a.dataTransfer.dropEffect="move"},[pe]),vo=g.useCallback(async(a,c)=>{a.preventDefault();const f=vn;if(Mt(null),sn(null),f===null||f===c)return;const w=[...de],[I]=w.splice(f,1);w.splice(c,0,I),await Jn(w,{successLog:`Порядок вопросов обновлен: ${Me?.generation_id??"local"}`,revertQuestions:de})},[vn,de,Me,Jn]),ur=g.useCallback(()=>{sn(null),Mt(null)},[]),xa=g.useCallback(a=>{jt(a),gn(c=>c===a?"":a)},[]),ul=g.useCallback(a=>{Cs({open:!0,generationId:a.generation_id,title:a.title??`${qi(a.mode)} ${pn(a.created_at)}`,saving:!1,error:""})},[]),_a=g.useCallback(async()=>{const a=It.generationId.trim();if(a){Cs(c=>({...c,saving:!0,error:""}));try{const c=await Te.deleteAutoRunAutogenHistoryRecord(a);Rn(f=>f.filter(w=>w.generation_id!==c.generation_id)),Rr({force:!0}),H(`Удален набор автопрогона: ${c.generation_id}`+(c.deleted_files.length>0?`, files=${c.deleted_files.length}`:""))}catch(c){const f=c instanceof Error?c.message:String(c);Cs(w=>({...w,saving:!1,error:f})),H(`Autogen record delete error: ${f}`)}}},[It.generationId,Rr,H]),yo=g.useCallback(a=>{ae(c=>c.map(f=>f.annotation_id===a.annotation_id?{...f,...a}:f)),k(c=>c&&{...c,annotations:c.annotations.map(f=>f.annotation_id===a.annotation_id?a:f),messages:c.messages.map(f=>!f.annotation||f.annotation.annotation_id!==a.annotation_id?f:{...f,commented:!0,annotation:a})})},[]),xo=g.useCallback(async(a,c)=>{if(a.annotation_id){if(Zs(a.run_id)){tt("Статус выполнения можно менять только для завершённых прогонов.");return}eo(a.annotation_id);try{const f=await Te.updateAutoRunAnnotation({annotation_id:a.annotation_id,resolved:c,resolved_by:le.generatedBy||void 0});yo(f.annotation),Sn()}catch(f){const w=f instanceof Error?f.message:String(f);tt(`Смена статуса кейса: ${w}`),H(`Annotation resolve toggle error: ${w}`)}finally{eo("")}}},[yo,le.generatedBy,Sn,H]),Ir=g.useCallback(async a=>{mn(a.annotation_id),await wn(a.run_id,a.case_id),Y?.items.some(c=>c.run_id===a.run_id)||tt("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[Y?.items,wn]);g.useEffect(()=>{Ns.current||(Ns.current=!0,Kn({keepSelection:!1}),qn(),sl(),Sn())},[qn,sl,Kn,Sn]),g.useEffect(()=>{Ns.current&&ls()},[ce,ls]),g.useEffect(()=>{mn(a=>lr.length===0?"":lr.some(c=>c.annotation_id===a)?a:lr[0].annotation_id)},[lr]),g.useEffect(()=>{jt(a=>De.length===0?"":a&&De.some(c=>c.generation_id===a)?a:De[0].generation_id)},[De]),g.useEffect(()=>{nr(Ho)},[le.mode]),g.useEffect(()=>{if(!Le)return;const a=De.findIndex(c=>c.generation_id===Le);a<0||nr(c=>Math.max(c,Math.min(De.length,a+1)))},[Le,De]),g.useEffect(()=>{if(!Me){Mn([]),Yn(),sn(null),Mt(null);return}Mn([...Me.questions]),Yn(),sn(null),Mt(null)},[Me,Yn]),g.useEffect(()=>{if(at===null)return;const a=window.setTimeout(()=>{rs.current?.focus(),rs.current?.select()},0);return()=>window.clearTimeout(a)},[at]),g.useEffect(()=>{if(!Ye){gn("");return}qt&&!De.some(a=>a.generation_id===qt)&&gn("")},[qt,Ye,De]),g.useEffect(()=>{Cr(String(b.limit))},[b.limit]),g.useEffect(()=>{Bn(String(le.count))},[le.count]),g.useEffect(()=>{if(!it.trim()){bn([]);return}ar(it)},[it,ar]),g.useEffect(()=>{if(!Ue)return;const a=aa(Ue.job_id);if(_e!==a)return;const c=Vo(Ue,qe||Tt);L(c.detail),k(c.dialog),wt(c.caseId)},[Ue,qe,_e]),g.useEffect(()=>()=>{Lt()},[Lt]),g.useEffect(()=>{rn.length!==0&>(a=>{let c=!1;const f={...a.personalityPrompts};for(const I of rn)(typeof f[I.id]!="string"||f[I.id].trim().length===0)&&(f[I.id]=I.defaultPrompt,c=!0);let w=a.personalityId;return rn.some(I=>I.id===a.personalityId)||(w=rn[0].id,c=!0),c?{...a,personalityId:w,personalityPrompts:f}:a})},[rn]),g.useEffect(()=>{const a=localStorage.getItem(id);if(a)try{const c=JSON.parse(a);if(c.filters){const f=c.filters;Ie(w=>({...w,...f,limit:typeof f.limit=="number"?Math.max(1,Math.min(500,f.limit)):w.limit}))}typeof c.analysisDate=="string"&&ee(Wi(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&ks(dd(c.autogenPersonalityPromptHeight)),c.groupsExpanded&&(typeof c.groupsExpanded.filters=="boolean"&&oo(c.groupsExpanded.filters),typeof c.groupsExpanded.generationContext=="boolean"&&lo(c.groupsExpanded.generationContext),typeof c.groupsExpanded.autogen=="boolean"&&ao(c.groupsExpanded.autogen),typeof c.groupsExpanded.savedSessions=="boolean"&&ns(c.groupsExpanded.savedSessions)),c.autoGenSettings&>(f=>{const w={...f.personalityPrompts},I=c.autoGenSettings?.personalityPrompts??{};for(const[nt,Ft]of Object.entries(I))typeof Ft=="string"&&nt.trim().length>0&&(w[nt.trim()]=Ft);const ue=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():f.personalityId;return{...f,mode:"saved_user_sessions",count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):f.count,personalityId:ue,personalityPrompts:w,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:f.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:f.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&xe(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&je(c.hideResolvedAnnotations)}catch{}},[]);const Lr=g.useCallback(()=>{const a={filters:b,analysisDate:Je,autogenPersonalityPromptHeight:js,groupsExpanded:{filters:rr,generationContext:Hn,autogen:sr,savedSessions:Vn},autoGenSettings:{mode:le.mode,count:le.count,personalityId:le.personalityId,personalityPrompts:le.personalityPrompts,persistToEvalCases:le.persistToEvalCases,generatedBy:le.generatedBy},annotationDecisionFilter:ce,hideResolvedAnnotations:we};localStorage.setItem(id,JSON.stringify(a))},[Je,ce,le,sr,js,b,rr,Hn,we,Vn]);return g.useEffect(()=>{const a=()=>{Lr(),H("Сохранены настройки панели автопрогонов.")};return window.addEventListener(ud,a),()=>{window.removeEventListener(ud,a)}},[H,Lr]),o.jsxs(ca,{className:"autoruns-frame",title:"",hideHeader:!0,children:[o.jsxs("div",{className:"autoruns-columns",children:[Ee?o.jsxs("section",{className:"autoruns-col autoruns-settings-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Настройки"})}),o.jsxs("div",{className:"autoruns-settings-stack",children:[o.jsx(lp,{embedded:!0,value:i,modelOptions:m,modelsBusy:p,onChange:M,onReloadModels:$,onSaveLocalConfig:re,onTestConnection:Z,lastStatus:S,busy:C}),o.jsx(ap,{embedded:!0,value:se,onChange:K,presets:J,selectedPresetId:X,onSelectPreset:Re,onLoadPreset:me,onSavePreset:he,onResetDefaults:ye,onDiffPrevious:Ge,presetName:Ze,onPresetNameChange:We,diffSummary:Ae})]})]}):null,Qe?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Автопрогоны"})}),o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Настройки выборки"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>oo(a=>!a),"aria-label":rr?"Скрыть группу настройки выборки":"Показать группу настройки выборки",title:rr?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:rr})})]}),rr?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата с",o.jsx("input",{type:"datetime-local",value:b.fromLocal,onChange:a=>Ie(c=>({...c,fromLocal:a.target.value}))})]}),o.jsxs("label",{children:["Дата по",o.jsx("input",{type:"datetime-local",value:b.toLocal,onChange:a=>Ie(c=>({...c,toLocal:a.target.value}))})]}),o.jsxs("label",{children:["Целевой контур",o.jsxs("select",{value:b.target,onChange:a=>Ie(c=>({...c,target:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(Y?.available.targets??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Режим",o.jsxs("select",{value:b.mode,onChange:a=>Ie(c=>({...c,mode:a.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(Y?.available.modes??[]).map(a=>o.jsx("option",{value:a,children:a},a))]})]}),o.jsxs("label",{children:["Использовать mock",o.jsxs("select",{value:b.useMock,onChange:a=>Ie(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:ws,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&Cr(c)},onBlur:a=>tl(a.target.value),onKeyDown:a=>{a.key==="Enter"&&tl(a.target.value)}})]}),o.jsxs("label",{className:"full-width",children:["Версия промпта содержит",o.jsx("input",{value:b.promptContains,onChange:a=>Ie(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:(Y?.available.prompt_versions??[]).map(a=>o.jsx("option",{value:a},a))}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:E,onClick:()=>{Kn({keepSelection:!1})},children:E?"Обновляю...":"Применить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{Ie({...Vi,fromLocal:fd()}),tt("")},children:"Сбросить фильтры"})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Контур генерации"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>lo(a=>!a),"aria-label":Hn?"Скрыть группу контура генерации":"Показать группу контура генерации",title:Hn?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:Hn})})]}),Hn?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:U})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт декомпозиции:"}),o.jsx("strong",{children:oe})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Сохранённые сессии"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>ao(a=>!a),"aria-label":sr?"Скрыть группу автопрогонов":"Показать группу автопрогонов",title:sr?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:sr})})]}),sr?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Режим",o.jsx("select",{value:le.mode,disabled:!0,onChange:a=>gt(c=>({...c,mode:a.target.value})),children:o.jsx("option",{value:"saved_user_sessions",children:"Пользовательские сессии"})})]}),Ye?null:o.jsxs(o.Fragment,{children:[o.jsxs("label",{children:["Кол-во",o.jsx("input",{type:"number",min:1,max:200,value:fa,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&Bn(c)},onBlur:a=>nl(a.target.value),onKeyDown:a=>{a.key==="Enter"&&nl(a.target.value)}})]}),o.jsxs("label",{children:["Личность автогенерации",o.jsx("select",{value:le.personalityId,onChange:a=>gt(c=>({...c,personalityId:a.target.value})),children:rn.map(a=>o.jsx("option",{value:a.id,children:a.label},a.id))})]}),o.jsxs("label",{children:["Кто генерирует",o.jsx("input",{value:le.generatedBy,onChange:a=>gt(c=>({...c,generatedBy:a.target.value})),placeholder:"manual_reviewer"})]}),o.jsxs("label",{className:"full-width",children:["Промпт личности",o.jsx("textarea",{className:"autoruns-personality-prompt",value:le.personalityPrompts[le.personalityId]??"",onChange:a=>gt(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:a.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${js}px`},onMouseUp:Ms,onTouchEnd:Ms})]}),o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:le.persistToEvalCases,onChange:a=>gt(c=>({...c,persistToEvalCases:a.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]})]}),Ye?null:o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата анализа (срез)",o.jsx("input",{type:"date",value:Je,onChange:a=>ee(Wi(a.target.value))})]}),o.jsx("div",{className:"button-row",children:o.jsx("button",{type:"button",className:"tab",disabled:!Je,onClick:()=>ee(""),children:"Сбросить дату среза"})})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",className:"tab",disabled:zn,onClick:()=>{qn()},children:zn?"Обновляю...":"Обновить историю"}),Ye?null:o.jsx("button",{type:"button",className:"autoruns-run-launch-btn",disabled:ts||!Ln&&(de.length===0||!Me),onClick:()=>{Ln?As():ol()},children:Ln?ts?"Останавливаю...":"Остановить прогон":"Запустить прогон"})]}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{className:"full-width",children:[Ye?"Сохраненная сессия":"Кейс-сет для запуска",o.jsxs("select",{value:Le,onChange:a=>jt(a.target.value),disabled:De.length===0,children:[De.length===0?o.jsx("option",{value:"",children:Ye?"нет сохраненных сессий":"нет генераций"}):null,De.map(a=>o.jsxs("option",{value:a.generation_id,children:[pn(a.created_at)," | ",Ki(a)??qi(a.mode)," | ",a.count]},a.generation_id))]})]})}),o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-generated-questions",style:Ye?{display:"none"}:void 0,children:[o.jsx("div",{className:"autoruns-generated-questions-head",children:o.jsxs("strong",{children:["Вопросы к запуску: ",de.length]})}),de.length===0?o.jsx("p",{className:"muted",children:Ye?"Список вопросов пуст. Сначала сохраните живую пользовательскую сессию.":"Список вопросов пуст. Сгенерируйте пачку или добавьте вопрос вручную."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:de.map((a,c)=>o.jsxs("div",{className:["autoruns-generated-question-item",pe===c?"drag-over":"",vn===c?"dragging":"",at===c?"editing":""].filter(Boolean).join(" "),onDragOver:f=>go(f,c),onDrop:f=>{vo(f,c)},children:[o.jsx("button",{type:"button",className:"autoruns-question-grip-btn",draggable:!vt&&at!==c,disabled:vt||at===c,onDragStart:f=>ho(f,c),onDragEnd:ur,title:"Перетащить вопрос","aria-label":`Перетащить вопрос ${c+1}`,children:o.jsx(xd,{})}),at===c?o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:rs,className:"autoruns-generated-question-input",value:In,onChange:f=>Rt(f.target.value),onBlur:Ar,onKeyDown:il,placeholder:"Текст вопроса",disabled:vt}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onMouseDown:f=>f.preventDefault(),onClick:()=>{mo(c)},title:"Удалить вопрос","aria-label":`Удалить вопрос ${c+1}`,disabled:vt,children:"×"})]}):o.jsxs("button",{type:"button",className:"autoruns-generated-question-text",onDoubleClick:()=>al(c),title:"Двойной клик для редактирования",children:[c+1,". ",a]})]},`${c}-${a.slice(0,24)}`))}),o.jsx("button",{type:"button",className:"autoruns-add-question-btn",onClick:()=>{po()},disabled:!Me||vt,children:"+"})]}),Ye?null:o.jsx("p",{className:"muted",children:"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:Ye?"Сохраненные пользовательские сессии":"История автогенераций"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>ns(a=>!a),"aria-label":Vn?Ye?"Скрыть группу сохраненных пользовательских сессий":"Скрыть группу истории автогенераций":Ye?"Показать группу сохраненных пользовательских сессий":"Показать группу истории автогенераций",title:Vn?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:Vn})})]}),Vn?o.jsxs("div",{className:"autoruns-autogen-list",children:[zn?o.jsx("p",{className:"muted",children:Ye?"Загружаю сохраненные пользовательские сессии...":"Загружаю историю автогенераций..."}):null,!zn&&De.length===0?o.jsx("p",{className:"muted",children:Ye?"Сохраненные пользовательские сессии пока пусты.":"История автогенераций пока пустая."}):null,Pr.map(a=>{const c=Ln&&Nr===a.generation_id,f=Ln&&Nr!==a.generation_id;return o.jsxs("article",{className:["autoruns-autogen-item",Le===a.generation_id?"selected":"",qt===a.generation_id?"expanded":"",Ye?"saved-session":""].filter(Boolean).join(" "),onClick:Ye?void 0:()=>jt(a.generation_id),children:[Ye?o.jsxs("div",{className:"autoruns-saved-session-topbar",children:[o.jsx("button",{type:"button",className:"autoruns-saved-session-icon-btn",disabled:ts||f,onClick:w=>{if(w.preventDefault(),w.stopPropagation(),c){As();return}jt(a.generation_id),ol(a,Le===a.generation_id?de:a.questions)},title:c?"Остановить прогон":"Запустить прогон","aria-label":`${c?"Остановить прогон":"Запустить прогон"} для ${Ki(a)}`,children:c?o.jsx(yp,{}):o.jsx(vp,{})}),o.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),ul(a)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${a.generation_id}`,children:"×"})]}):null,o.jsxs("header",{children:[o.jsx("strong",{children:Ki(a)}),o.jsx("div",{className:"autoruns-autogen-card-actions",children:o.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),ul(a)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${a.generation_id}`,children:"×"})})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Дата и время"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",pn(a.created_at)]})]}),o.jsxs("div",{className:"autoruns-saved-session-meta autoruns-saved-session-meta-id",children:[o.jsxs("div",{className:"autoruns-saved-session-meta-id-main",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"ID"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",a.generation_id]})]}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:w=>{Wn(w,a.generation_id,"set id")},onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),Wn(w,a.generation_id,"set id"))},title:"Скопировать id набора","aria-label":`Скопировать id набора ${a.generation_id}`,children:o.jsx(yd,{})})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Режим"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",qi(a.mode)]})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Тип"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",Td(a)?"АГЕНТНЫЙ ПРОГОН":"АВТОПРОГОН"]})]}),Ye?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Количество вопросов"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",a.questions.length]})]}),o.jsx("div",{className:"autoruns-saved-session-footer",children:o.jsx("button",{type:"button",className:"autoruns-saved-session-icon-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),xa(a.generation_id)},title:qt===a.generation_id?"Скрыть вопросы":"Показать вопросы","aria-label":qt===a.generation_id?"Скрыть вопросы":"Показать вопросы",children:o.jsx(gp,{expanded:qt===a.generation_id})})}),o.jsx("div",{className:qt===a.generation_id?"autoruns-saved-session-questions expanded":"autoruns-saved-session-questions",children:o.jsxs("div",{className:"autoruns-generated-questions autoruns-generated-questions-embedded",children:[o.jsx("div",{className:"autoruns-generated-questions-head",children:o.jsxs("strong",{children:["Вопросы к запуску:"," ",Le===a.generation_id?de.length:a.questions.length]})}),(Le===a.generation_id?de:a.questions).length===0?o.jsx("p",{className:"muted",children:"Список вопросов пуст."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:(Le===a.generation_id?de:a.questions).map((w,I)=>o.jsxs("div",{className:["autoruns-generated-question-item",pe===I&&Le===a.generation_id?"drag-over":"",vn===I&&Le===a.generation_id?"dragging":"",at===I&&Le===a.generation_id?"editing":""].filter(Boolean).join(" "),onDragOver:ue=>Le===a.generation_id?go(ue,I):void 0,onDrop:ue=>Le===a.generation_id?void vo(ue,I):void 0,children:[o.jsx("button",{type:"button",className:"autoruns-question-grip-btn",draggable:Le===a.generation_id&&!vt&&at!==I,disabled:Le!==a.generation_id||vt||at===I,onDragStart:ue=>{jt(a.generation_id),ho(ue,I)},onDragEnd:ur,title:"Перетащить вопрос","aria-label":`Перетащить вопрос ${I+1}`,children:o.jsx(xd,{})}),Le===a.generation_id&&at===I?o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:rs,className:"autoruns-generated-question-input",value:In,onChange:ue=>Rt(ue.target.value),onBlur:Ar,onKeyDown:il,placeholder:"Текст вопроса",disabled:vt}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onMouseDown:ue=>ue.preventDefault(),onClick:()=>{mo(I)},title:"Удалить вопрос","aria-label":`Удалить вопрос ${I+1}`,disabled:vt,children:"×"})]}):o.jsxs("button",{type:"button",className:"autoruns-generated-question-text",onDoubleClick:()=>{jt(a.generation_id),al(I)},title:"Двойной клик для редактирования",children:[I+1,". ",w]})]},`${a.generation_id}-${I}-${w.slice(0,24)}`))}),o.jsx("button",{type:"button",className:"autoruns-add-question-btn",onClick:()=>{jt(a.generation_id),po()},disabled:Le!==a.generation_id||vt,children:"+"})]})})]}):null]},a.generation_id)}),Gn>0?o.jsxs("button",{type:"button",className:"autoruns-autogen-load-more-btn",onClick:()=>nr(a=>Math.min(a+Ho,De.length)),children:["Показать еще ",Math.min(Ho,Gn)," из ",Gn]}):null]}):null,o.jsxs("details",{className:"autoruns-prompt-details",children:[o.jsx("summary",{children:"Копия активного промпта (только чтение)"}),o.jsxs("label",{children:["Системный",o.jsx("textarea",{readOnly:!0,value:se.systemPrompt})]}),o.jsxs("label",{children:["Разработчика",o.jsx("textarea",{readOnly:!0,value:se.developerPrompt})]}),o.jsxs("label",{children:["Доменный",o.jsx("textarea",{readOnly:!0,value:se.domainPrompt})]}),o.jsxs("label",{children:["Заметки по схеме",o.jsx("textarea",{readOnly:!0,value:se.schemaNotes})]}),o.jsxs("label",{children:["Примеры few-shot",o.jsx("textarea",{readOnly:!0,value:se.fewShotExamples})]})]}),no?o.jsx("p",{className:"error-text",children:no}):null]}):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:(Y?.stats.runs_total??0)+(Ue?1:0)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний score"}),o.jsx("strong",{children:oa(Y?.stats.avg_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:Y?md(Y.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Блокеры"}),o.jsx("strong",{children:Y?.stats.blocking_runs??0})]})]}),o.jsxs("div",{className:"autoruns-run-list",children:[Ts.map(a=>o.jsxs("button",{type:"button",className:_e===a.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{wn(a.run_id)},children:[o.jsxs("div",{className:"autoruns-run-head",children:[o.jsx("strong",{children:pn(a.run_timestamp)}),o.jsx("span",{children:mp(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=>{Wn(c,a.run_id,"run id")},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Wn(c,a.run_id,"run id"))},title:"Скопировать run id","aria-label":`Скопировать run id ${a.run_id}`,children:o.jsx(yd,{})})]}),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:["оценка: ",oa(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)),Ts.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:_e,onChange:a=>{const c=a.target.value;wn(c)},children:Ts.map(a=>o.jsxs("option",{value:a.run_id,children:[pn(a.run_timestamp)," | ",a.run_id]},a.run_id))})]}),o.jsxs("label",{children:["Кейс",o.jsxs("select",{value:qe,onChange:a=>{const c=a.target.value;wt(c),_e&&c&&as(_e,c)},children:[(O?.cases.length??0)>0?o.jsx("option",{value:Tt,children:"ВСЕ кейсы подряд"}):null,(O?.cases??[]).map(a=>o.jsxs("option",{value:a.case_id,children:[a.case_id," | ",a.status]},a.case_id))]})]}),o.jsxs("div",{className:"autoruns-dialog-copy-actions",children:[o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Zo("default")},disabled:et||B||(y?.messages.length??0)===0,title:"Скопировать question-answer диалог текущего прогона",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Zo("technical")},disabled:et||B||(y?.messages.length??0)===0,title:"Скопировать диалог вместе с debug JSON и метаданными прогона",children:"Скопировать техчат"}),o.jsxs("div",{className:"autoruns-dialog-copy-status",children:[qo==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Ko,")"]}):null,qo==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]})]})]}),o.jsxs("div",{className:"autoruns-case-list",children:[(O?.cases.length??0)>0?o.jsxs("button",{type:"button",className:qe===Tt?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{wt(Tt),_e&&as(_e,Tt)},children:[o.jsx("span",{children:"ВСЕ кейсы подряд"}),o.jsx("span",{children:O?.cases.length})]},Tt):null,(O?.cases??[]).map(a=>o.jsxs("button",{type:"button",className:qe===a.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{wt(a.case_id),_e&&as(_e,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:[et||B?o.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!et&&!B&&(y?.messages.length??0)===0?o.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(y?.messages??[]).map((a,c)=>{const f=a.role==="assistant"?"assistant":"user";return o.jsxs("article",{className:`autoruns-msg ${f}`,children:[o.jsxs("header",{children:[o.jsx("strong",{children:f==="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,pd(a)?o.jsx("span",{className:"autoruns-msg-case-tag",children:pd(a)}):null,o.jsx("span",{children:a.created_at?pn(a.created_at):"нет данных"}),f==="assistant"&&!Zs(_e)?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:a.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>pa(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(hp,{commented:a.commented})}),a.annotation?o.jsx("button",{type:"button",className:a.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{xo(a.annotation,!a.annotation.resolved)},disabled:Fn===a.annotation.annotation_id,title:a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(vd,{resolved:a.annotation.resolved})}):null]}):null]})]}),o.jsx("p",{children:a.text}),f==="assistant"&&a.annotation?o.jsxs("div",{className:"autoruns-msg-annotation",children:[o.jsx("strong",{children:Ji(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??`${f}-${c}`)})]})]}),St?o.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:o.jsx(np,{sessionId:it,conversation:on,inputValue:ro,onInputChange:_s,selectedContextChip:kr,onSelectContextChip:$t,onClearContextChip:()=>$t(null),useMock:so,onUseMockChange:Kt,onSend:os,onClear:co,onSaveSession:Rs,busy:Yo,saveBusy:yt.saving,saveDisabled:!it.trim()||on.length===0||Yo,statusText:da,errorMessage:Ss,showSaveAction:!0,showCommentAction:!0,onCommentAssistantMessage:ga,isAssistantMessageCommented:ha,canCommentAssistantMessage:ll})}):null,pt?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:oa(Y?.stats.latest_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Предыдущий"}),o.jsx("strong",{children:oa(Y?.stats.previous_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:Y?md(Y.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Пробелы качества"}),o.jsx("strong",{children:Y?.stats.quality_gap_runs??0})]})]}),o.jsx("h4",{children:"Покрытие доменов (история)"}),hd(Y?.stats.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),hd(O?.coverage.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),Dn?o.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,Dn?null:o.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(Sr?.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:[(Sr?.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)),!Dn&&(Sr?.post_analysis.recommended_regression_candidates.length??0)===0?o.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Gt?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:ce,onChange:a=>xe(a.target.value),children:[o.jsx("option",{value:"all",children:"все"}),(nn.length>0?nn:Ce?.enum??[]).map(a=>o.jsx("option",{value:a,children:String(Ce?.labels?.[a]??a)},a))]})]}),o.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>je(a=>!a),children:we?"Показать выполненные":"Скрыть выполненные"})]}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Комментариев"}),o.jsx("strong",{children:Xt.length})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний рейтинг"}),o.jsx("strong",{children:ss===null?"нет данных":`${ss.toFixed(2)} / 5`})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Последний"}),o.jsx("strong",{children:Xt.length>0?pn(Xt[0].updated_at):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Статус"}),o.jsx("strong",{children:Zr?"обновляю":"готово"})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Zr,onClick:()=>{ls()},children:Zr?"Обновляю...":"Обновить список"}),o.jsx("button",{type:"button",className:"tab",disabled:Dn,onClick:()=>{Sn()},children:Dn?"Идет пост-анализ...":"Обновить пост-анализ"})]}),o.jsxs("div",{className:"autoruns-comments-list",children:[Zr?o.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!Zr&&Xt.length===0?o.jsx("p",{className:"muted",children:te.length===0&&jr.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,Xt.map(a=>{if(a.source==="assistant_live"){const f=a.assistant;return o.jsxs("article",{className:"autoruns-comment-item",children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Ji(f.rating)}),o.jsx("div",{className:"autoruns-comment-head-actions",children:o.jsx("span",{children:pn(f.updated_at)})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",f.session_id]}),o.jsxs("div",{className:"autoruns-run-meta",children:["msg=",f.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",f.annotation_author?` | author=${f.annotation_author}`:""]}),f.context.question_text?o.jsxs("p",{children:["Q: ",f.context.question_text]}):null,f.context.answer_text?o.jsxs("p",{children:["A: ",f.context.answer_text]}):null,o.jsx("p",{children:f.comment})]},a.key)}const c=a.autorun;return o.jsxs("article",{className:Tn===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{Ir(c)},role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),Ir(c))},children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Ji(c.rating)}),o.jsxs("div",{className:"autoruns-comment-head-actions",children:[o.jsx("span",{children:pn(c.updated_at)}),o.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:f=>{f.preventDefault(),f.stopPropagation(),xo(c,!c.resolved)},disabled:Fn===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(vd,{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:["выполнено",": ",pn(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)})]}),Oe?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:Oe.technical_context.trace_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"reply_type:"}),o.jsx("strong",{children:Oe.technical_context.reply_type??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"domain:"}),o.jsx("strong",{children:Oe.technical_context.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"query_class:"}),o.jsx("strong",{children:Oe.technical_context.query_class??"нет данных"})]})]}),o.jsx("h4",{children:"JSON разбор"}),o.jsx(Nd,{value:{annotation_id:Oe.annotation_id,run_id:Oe.run_id,case_id:Oe.case_id,message_index:Oe.message_index,rating:Oe.rating,comment:Oe.comment,manual_case_decision:Oe.manual_case_decision,annotation_author:Oe.annotation_author,resolved:Oe.resolved,resolved_at:Oe.resolved_at,resolved_by:Oe.resolved_by,context:Oe.context,technical_context:Oe.technical_context,case_summary:Oe.case_summary?{case_id:Oe.case_summary.case_id,domain:Oe.case_summary.domain,query_class:Oe.case_summary.query_class,checks:Oe.case_summary.checks,metric_subscores:Oe.case_summary.metric_subscores}:null}})]}):null]}):null]}),yt.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&ut()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Сохранить ручную сессию"}),o.jsx("p",{className:"muted",children:"Технический чат будет сохранен в автопрогоны как пользовательская multi-turn сессия."}),o.jsxs("label",{children:["Название",o.jsx("input",{value:yt.title,onChange:a=>kt(c=>({...c,title:a.target.value})),placeholder:"Например: НДС и склад на март 2020",disabled:yt.saving})]}),yt.error?o.jsx("p",{className:"error-text",children:yt.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{el()},disabled:yt.saving,children:yt.saving?"Сохраняю...":"Сохранить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>ut(),disabled:yt.saving,children:"Отмена"})]})]})}):null,Yt.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&_n()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Удалить вопрос"}),o.jsx("p",{className:"muted",children:"Действительно удалить вопрос из сохраненной пользовательской сессии?"}),o.jsx("p",{className:"autoruns-comment-quote",children:Yt.questionText}),Yt.error?o.jsx("p",{className:"error-text",children:Yt.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ya()},disabled:Yt.saving,children:Yt.saving?"Удаляю...":"Да"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>_n(),disabled:Yt.saving,children:"Нет"})]})]})}):null,It.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Rr()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Удалить сохраненный набор"}),o.jsx("p",{className:"muted",children:"Будет удалена карточка истории и связанный файл кейс-сета на бэке."}),o.jsx("p",{className:"autoruns-comment-quote",children:It.title}),It.error?o.jsx("p",{className:"error-text",children:It.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{_a()},disabled:It.saving,children:It.saving?"Удаляю...":"Да"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Rr(),disabled:It.saving,children:"Нет"})]})]})}):null,ge.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&ir()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),xn?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:xn.text})]}):null,io?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:io.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:ge.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>At(c=>({...c,rating:a})),disabled:ge.saving,"aria-label":`Оценка ${a}`,children:ge.rating>=a?"●":"○"},a))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ge.annotationAuthor,onChange:a=>At(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ge.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ge.comment,onChange:a=>At(c=>({...c,comment:a.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:ge.saving})]}),ge.error?o.jsx("p",{className:"error-text",children:ge.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{va()},disabled:ge.saving,children:ge.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>ir(),disabled:ge.saving,children:"Отмена"})]})]})}):null,ie.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Is()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу системы"}),o.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),Es?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:Ps?.text??"Вопрос в диалоге не найден."})]}),o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ системы"}),o.jsx("p",{className:"autoruns-comment-quote",children:Es.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:ie.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>st(c=>({...c,rating:a})),disabled:ie.saving,"aria-label":`Оценка ${a}`,children:ie.rating>=a?"●":"○"},a))}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Решение по кейсу",o.jsx("select",{value:ie.manualCaseDecision,onChange:a=>st(c=>({...c,manualCaseDecision:a.target.value})),disabled:ie.saving,children:(nn.length>0?nn:Ce?.enum??[ra]).map(a=>o.jsx("option",{value:a,children:String(Ce?.labels?.[a]??a)},a))})]}),o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ie.annotationAuthor,onChange:a=>st(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ie.saving})]})]}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ie.comment,onChange:a=>st(c=>({...c,comment:a.target.value})),placeholder:"Почему ответ бракованный, что именно пошло не так, какие технические детали проверить.",rows:4,disabled:ie.saving})]}),ie.error?o.jsx("p",{className:"error-text",children:ie.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ma()},disabled:ie.saving,children:ie.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Is(),disabled:ie.saving,children:"Отмена"})]})]})}):null]})}const _p={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},Sd={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."},Sp={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},Yi={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}},wd="ndc_normalizer_session_config_v1",jd="ndc_autoruns_layout_config_v1",wp="ndc-autoruns-save",jp="autoruns",Xi="normalizer_v2_0_2",kp="address_query_runtime_v1",Cp=["normalized","fragments","scope","flags","route","raw","validation","logs"];function Np(i){return`[${new Date().toLocaleTimeString("ru-RU")}] ${i}`}function Ep(i,m){if(!m)return"Previous preset is not selected.";const S=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(C=>i[C]!==m[C]).map(C=>`${C}: ${Math.abs(i[C].length-m[C].length)} chars delta`);return S.length===0?"No changes against previous preset.":`Changed fields: ${S.length}. ${S.join(" | ")}`}function Pp(){const[i,m]=g.useState(_p),[p,S]=g.useState(Sd),[C,M]=g.useState(Sp),[$,re]=g.useState(null),[Z,se]=g.useState([]),[K,J]=g.useState([]),[X,Re]=g.useState("normalized"),[me,he]=g.useState(!1),[ye,Ge]=g.useState(!1),[Ze,We]=g.useState([]),[Ae,U]=g.useState(""),[oe,Ee]=g.useState([]),[Qe,St]=g.useState(""),[pt,Gt]=g.useState("NDC custom preset"),[mt,b]=g.useState(null),[Ie,Je]=g.useState(""),[ee,Y]=g.useState(!1),[A,O]=g.useState([]),[L,y]=g.useState(""),[k,te]=g.useState([]),[ae,ce]=g.useState(!1),[xe,we]=g.useState(null),[je,Ce]=g.useState(""),[ht,nn]=g.useState(jp),[xr,Tn]=g.useState(!0),[mn,_e]=g.useState(!0),[Wt,qe]=g.useState(!0),[wt,rn]=g.useState(!0),[hn,le]=g.useState(!0),[gt,_r]=g.useState(!0),[Rn,Jr]=g.useState(!0),[nr,Le]=g.useState(!0),[jt,qt]=g.useState(!0),[gn,de]=g.useState(!0),[Mn,vt]=g.useState(!0),[Yr,at]=g.useState(!0),[An,In]=g.useState(!0),Rt=g.useRef(!1),vn=g.useRef(!1),sn=g.useRef(!1);g.useEffect(()=>{const E=document.documentElement,{colors:q}=Yi;E.style.setProperty("--rgb-background",q.backgroundRgb),E.style.setProperty("--rgb-surface-main",q.mainSurfaceRgb),E.style.setProperty("--rgb-surface-horizontal",q.horizontalSurfaceRgb),E.style.setProperty("--rgb-surface-focus",q.focusSurfaceRgb),E.style.setProperty("--rgb-assistant-chip",q.assistantChipRgb),E.style.setProperty("--rgb-assistant-chip-hover",q.assistantChipHoverRgb),E.style.setProperty("--rgb-assistant-chip-selected",q.assistantChipSelectedRgb),E.style.setProperty("--rgb-assistant-chip-selected-text",q.assistantChipSelectedTextRgb),E.style.setProperty("--rgb-active",q.activeRgb),E.style.setProperty("--rgb-active-text",q.activeTextRgb),E.style.setProperty("--rgb-text-main",q.textMainRgb),E.style.setProperty("--rgb-text-muted",q.textMutedRgb),E.style.setProperty("--rgb-danger",q.dangerRgb),E.style.setProperty("--rgb-scrollbar-track",q.scrollbarTrackRgb),E.style.setProperty("--rgb-scrollbar-thumb",q.scrollbarThumbRgb),E.style.setProperty("--rgb-scrollbar-thumb-hover",q.scrollbarThumbHoverRgb),E.style.setProperty("--mode-column-width",`${Yi.layout.modeColumnWidthPx}px`),E.style.setProperty("--mode-toggle-width",`${Yi.layout.modeToggleWidthPx}px`)},[]);const pe=E=>{J(q=>[Np(E),...q].slice(0,300))};g.useEffect(()=>{(async()=>{const B=localStorage.getItem(wd);if(B)try{const Pe=JSON.parse(B);m(et=>({...et,llmProvider:Pe.llmProvider==="local"?"local":"openai",model:Pe.model??et.model,baseUrl:Pe.baseUrl??et.baseUrl,temperature:Pe.temperature??et.temperature,maxOutputTokens:Pe.maxOutputTokens??et.maxOutputTokens}))}catch{}try{const Pe=await Te.loadSharedConnectionConfig();Pe.connection&&Pe.connection.llmProvider==="local"&&(m(et=>({...et,llmProvider:"local",model:Pe.connection?.model??et.model,baseUrl:Pe.connection?.baseUrl??et.baseUrl,temperature:Pe.connection?.temperature??et.temperature,maxOutputTokens:Pe.connection?.maxOutputTokens??et.maxOutputTokens})),pe(`Shared local LLM config loaded: ${Pe.connection.model}`))}catch(Pe){pe(`Shared local config load error: ${Pe instanceof Error?Pe.message:String(Pe)}`)}finally{sn.current=!0}})();const q=localStorage.getItem(jd);if(q)try{const B=JSON.parse(q);(B.uiMode==="assistant"||B.uiMode==="autoruns"||B.uiMode==="decomposition")&&nn("autoruns"),B.activeTab&&Cp.includes(B.activeTab)&&Re(B.activeTab),typeof B.showAutorunsSettingsMode=="boolean"&&Tn(B.showAutorunsSettingsMode),typeof B.showAutorunsAutoRunsMode=="boolean"&&_e(B.showAutorunsAutoRunsMode),typeof B.showAutorunsAssistantMode=="boolean"&&qe(B.showAutorunsAssistantMode),typeof B.showAutorunsDecompositionMode=="boolean"&&rn(B.showAutorunsDecompositionMode),typeof B.showAutorunsProgressMode=="boolean"&&le(B.showAutorunsProgressMode),typeof B.showAutorunsCommentsMode=="boolean"&&_r(B.showAutorunsCommentsMode),typeof B.showDecompositionConnectionMode=="boolean"&&Jr(B.showDecompositionConnectionMode),typeof B.showDecompositionPromptMode=="boolean"&&Le(B.showDecompositionPromptMode),typeof B.showDecompositionQueryMode=="boolean"&&qt(B.showDecompositionQueryMode),typeof B.showDecompositionOutputMode=="boolean"&&de(B.showDecompositionOutputMode),typeof B.showDecompositionMetricsMode=="boolean"&&vt(B.showDecompositionMetricsMode),typeof B.showDecompositionHistoryMode=="boolean"&&at(B.showDecompositionHistoryMode),typeof B.showDecompositionRuntimeMode=="boolean"&&In(B.showDecompositionRuntimeMode),B.prompts&&(S(Pe=>({...Pe,...B.prompts})),vn.current=!0)}catch{}Mt(),Ue(),yn()},[]),g.useEffect(()=>{if(!sn.current||i.llmProvider!=="local")return;const E=window.setTimeout(()=>{Te.saveSharedConnectionConfig(i).catch(q=>pe(`Shared local config sync error: ${q instanceof Error?q.message:String(q)}`))},250);return()=>window.clearTimeout(E)},[i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature]);async function Mt(){try{const E=await Te.loadHistory();se(E.items??[])}catch(E){pe(`History load error: ${E instanceof Error?E.message:String(E)}`)}}async function Ue(){try{const q=(await Te.loadPresets()).presets??[];if(Ee(q),vn.current){Rt.current=!0;return}if(Rt.current)return;const B=q.find(Pe=>Pe.prompt_version===Xi)??q.find(Pe=>Pe.id==="default-normalizer-v2_0_2");if(!B){Rt.current=!0,pe(`Preset autoload skipped: ${Xi} not found.`);return}St(B.id),b(p),S({systemPrompt:B.systemPrompt,developerPrompt:B.developerPrompt,domainPrompt:B.domainPrompt,schemaNotes:B.schemaNotes??"",fewShotExamples:B.fewShotExamples??""}),Rt.current=!0,pe(`Preset autoloaded: ${B.name} (${B.prompt_version}).`)}catch(E){pe(`Presets load error: ${E instanceof Error?E.message:String(E)}`)}}async function yn(){try{const E=await Te.listRuns();O(E.items??[])}catch(E){pe(`Runs load error: ${E instanceof Error?E.message:String(E)}`)}}function Sr(){if(localStorage.setItem(wd,JSON.stringify({model:i.model,llmProvider:i.llmProvider,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})),i.llmProvider==="local"){Te.saveSharedConnectionConfig(i).then(()=>{pe("Local config saved and synced to shared agent config (without API key).")}).catch(E=>{pe(`Local config saved, but shared sync failed: ${E instanceof Error?E.message:String(E)}`)});return}pe("Local config saved (without API key).")}function Xr(){localStorage.setItem(jd,JSON.stringify({uiMode:ht,activeTab:X,showAutorunsSettingsMode:xr,showAutorunsAutoRunsMode:mn,showAutorunsAssistantMode:Wt,showAutorunsDecompositionMode:wt,showAutorunsProgressMode:hn,showAutorunsCommentsMode:gt,showDecompositionConnectionMode:Rn,showDecompositionPromptMode:nr,showDecompositionQueryMode:jt,showDecompositionOutputMode:gn,showDecompositionMetricsMode:Mn,showDecompositionHistoryMode:Yr,showDecompositionRuntimeMode:An,prompts:p})),window.dispatchEvent(new CustomEvent(wp)),pe("UI layout and prompts saved.")}async function Ln(){he(!0),Ce("");try{const E=await Te.testConnection(i);E.provider==="local"?E.model_found===!0?(U(`LOCAL OK - ${E.model}`),pe(`Local model is available: ${E.model} (catalog size=${E.models_count??"n/a"}).`)):E.model_found===!1?(U(`LOCAL OK, model not loaded - ${E.model}`),pe(`Local server is reachable, but model '${E.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(U(`LOCAL OK (model list unavailable) - ${E.model}`),pe("Local server is reachable, but model catalog could not be verified.")):(U(`OPENAI OK - ${E.model}`),pe(`OpenAI connection ok: ${E.model}`))}catch(E){const q=E instanceof Error?E.message:String(E);U("Connection error"),Ce(`Test connection: ${q}`),pe(`Test connection error: ${q}`)}finally{he(!1)}}async function zt(){Ge(!0);try{const q=(await Te.listModels(i)).models??[];We(q),q.length>0&&m(B=>B.model&&q.includes(B.model)?B:{...B,model:q[0]}),pe(`Model catalog loaded (${i.llmProvider}): ${q.length} items.`)}catch(E){const q=E instanceof Error?E.message:String(E);pe(`Load model list error: ${q}`)}finally{Ge(!1)}}g.useEffect(()=>{We([])},[i.llmProvider,i.baseUrl]);function Dn(){const E=oe.find(q=>q.id===Qe);if(!E){pe("Preset is not selected.");return}b(p),S({systemPrompt:E.systemPrompt,developerPrompt:E.developerPrompt,domainPrompt:E.domainPrompt,schemaNotes:E.schemaNotes??"",fewShotExamples:E.fewShotExamples??""}),pe(`Preset loaded: ${E.name}`)}async function On(){try{await Te.savePreset({name:pt||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:p.systemPrompt,developerPrompt:p.developerPrompt,domainPrompt:p.domainPrompt,schemaNotes:p.schemaNotes,fewShotExamples:p.fewShotExamples}),pe("Preset saved."),await Ue()}catch(E){pe(`Preset save error: ${E instanceof Error?E.message:String(E)}`)}}function zn(){S(Sd),pe("Prompt panel reset to defaults.")}function $n(){const E=Ep(p,mt);Je(E),pe(E)}return g.useEffect(()=>{if(!L){te([]);return}Te.runTrace(L).then(E=>te(E.items)).catch(E=>pe(`Run trace error: ${E instanceof Error?E.message:String(E)}`))},[L]),o.jsxs("main",{className:"app-root 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:"tab active",onClick:()=>nn("autoruns"),children:"Управление ассистентом"}),o.jsx("button",{type:"button",className:"tab",onClick:Xr,children:"Сохранить"})]}),o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:xr?"tab active":"tab",onClick:()=>Tn(E=>!E),children:"Настройки"}),o.jsx("button",{type:"button",className:mn?"tab active":"tab",onClick:()=>_e(E=>!E),children:"Автопрогоны"}),o.jsx("button",{type:"button",className:Wt?"tab active":"tab",onClick:()=>qe(E=>!E),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:hn?"tab active":"tab",onClick:()=>le(E=>!E),children:"Прогресс/регресс"}),o.jsx("button",{type:"button",className:gt?"tab active":"tab",onClick:()=>_r(E=>!E),children:"Комментарии"})]})]}),o.jsx("div",{className:"layout-grid layout-grid-autoruns",children:o.jsx(xp,{connection:i,modelOptions:Ze,modelsBusy:ye,connectionStatus:Ae,connectionBusy:me,onConnectionChange:m,onReloadModels:zt,onSaveLocalConfig:Sr,onTestConnection:Ln,prompts:p,onPromptsChange:S,promptPresets:oe,selectedPresetId:Qe,onSelectPreset:St,onLoadPreset:Dn,onSavePreset:On,onResetDefaults:zn,onDiffPrevious:$n,presetName:pt,onPresetNameChange:Gt,diffSummary:Ie,assistantPromptVersion:kp,decompositionPromptVersion:Xi,showSettingsMode:xr,showAutoRunsMode:mn,showAssistantMode:Wt,showProgressMode:hn,showCommentsMode:gt,onLog:pe})})]})}Of.createRoot(document.getElementById("root")).render(o.jsx(Tf.StrictMode,{children:o.jsx(Pp,{})})); diff --git a/llm_normalizer/frontend/dist/assets/index-BdTHVNKv.js b/llm_normalizer/frontend/dist/assets/index-BdTHVNKv.js deleted file mode 100644 index 135bcdd..0000000 --- a/llm_normalizer/frontend/dist/assets/index-BdTHVNKv.js +++ /dev/null @@ -1,25 +0,0 @@ -(function(){const m=document.createElement("link").relList;if(m&&m.supports&&m.supports("modulepreload"))return;for(const C of document.querySelectorAll('link[rel="modulepreload"]'))S(C);new MutationObserver(C=>{for(const M of C)if(M.type==="childList")for(const b of M.addedNodes)b.tagName==="LINK"&&b.rel==="modulepreload"&&S(b)}).observe(document,{childList:!0,subtree:!0});function p(C){const M={};return C.integrity&&(M.integrity=C.integrity),C.referrerPolicy&&(M.referrerPolicy=C.referrerPolicy),C.crossOrigin==="use-credentials"?M.credentials="include":C.crossOrigin==="anonymous"?M.credentials="omit":M.credentials="same-origin",M}function S(C){if(C.ep)return;C.ep=!0;const M=p(C);fetch(C.href,M)}})();function Nd(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Ui={exports:{}},Fo={},Bi={exports:{}},ve={};var ed;function Nf(){if(ed)return ve;ed=1;var a=Symbol.for("react.element"),m=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),S=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),M=Symbol.for("react.provider"),b=Symbol.for("react.context"),le=Symbol.for("react.forward_ref"),te=Symbol.for("react.suspense"),F=Symbol.for("react.memo"),Y=Symbol.for("react.lazy"),X=Symbol.iterator;function ee(y){return y===null||typeof y!="object"?null:(y=X&&y[X]||y["@@iterator"],typeof y=="function"?y:null)}var Ae={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},me=Object.assign,he={};function ye(y,k,re){this.props=y,this.context=k,this.refs=he,this.updater=re||Ae}ye.prototype.isReactComponent={},ye.prototype.setState=function(y,k){if(typeof y!="object"&&typeof y!="function"&&y!=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,y,k,"setState")},ye.prototype.forceUpdate=function(y){this.updater.enqueueForceUpdate(this,y,"forceUpdate")};function We(){}We.prototype=ye.prototype;function Ze(y,k,re){this.props=y,this.context=k,this.refs=he,this.updater=re||Ae}var qe=Ze.prototype=new We;qe.constructor=Ze,me(qe,ye.prototype),qe.isPureReactComponent=!0;var Ie=Array.isArray,U=Object.prototype.hasOwnProperty,oe={current:null},Pe={key:!0,ref:!0,__self:!0,__source:!0};function He(y,k,re){var ie,de={},xe=null,je=null;if(k!=null)for(ie in k.ref!==void 0&&(je=k.ref),k.key!==void 0&&(xe=""+k.key),k)U.call(k,ie)&&!Pe.hasOwnProperty(ie)&&(de[ie]=k[ie]);var ke=arguments.length-2;if(ke===1)de.children=re;else if(1>>1,k=I[y];if(0>>1;yC(de,L))xeC(je,de)?(I[y]=je,I[xe]=L,y=xe):(I[y]=de,I[ie]=L,y=ie);else if(xeC(je,L))I[y]=je,I[xe]=L,y=xe;else break e}}return $}function C(I,$){var L=I.sortIndex-$.sortIndex;return L!==0?L:I.id-$.id}if(typeof performance=="object"&&typeof performance.now=="function"){var M=performance;a.unstable_now=function(){return M.now()}}else{var b=Date,le=b.now();a.unstable_now=function(){return b.now()-le}}var te=[],F=[],Y=1,X=null,ee=3,Ae=!1,me=!1,he=!1,ye=typeof setTimeout=="function"?setTimeout:null,We=typeof clearTimeout=="function"?clearTimeout:null,Ze=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function qe(I){for(var $=p(F);$!==null;){if($.callback===null)S(F);else if($.startTime<=I)S(F),$.sortIndex=$.expirationTime,m(te,$);else break;$=p(F)}}function Ie(I){if(he=!1,qe(I),!me)if(p(te)!==null)me=!0,ne(U);else{var $=p(F);$!==null&&Z(Ie,$.startTime-I)}}function U(I,$){me=!1,he&&(he=!1,We(He),He=-1),Ae=!0;var L=ee;try{for(qe($),X=p(te);X!==null&&(!(X.expirationTime>$)||I&&!Gt());){var y=X.callback;if(typeof y=="function"){X.callback=null,ee=X.priorityLevel;var k=y(X.expirationTime<=$);$=a.unstable_now(),typeof k=="function"?X.callback=k:X===p(te)&&S(te),qe($)}else S(te);X=p(te)}if(X!==null)var re=!0;else{var ie=p(F);ie!==null&&Z(Ie,ie.startTime-$),re=!1}return re}finally{X=null,ee=L,Ae=!1}}var oe=!1,Pe=null,He=-1,_t=5,dt=-1;function Gt(){return!(a.unstable_now()-dt<_t)}function ft(){if(Pe!==null){var I=a.unstable_now();dt=I;var $=!0;try{$=Pe(!0,I)}finally{$?Q():(oe=!1,Pe=null)}}else oe=!1}var Q;if(typeof Ze=="function")Q=function(){Ze(ft)};else if(typeof MessageChannel<"u"){var Le=new MessageChannel,Ye=Le.port2;Le.port1.onmessage=ft,Q=function(){Ye.postMessage(null)}}else Q=function(){ye(ft,0)};function ne(I){Pe=I,oe||(oe=!0,Q())}function Z(I,$){He=ye(function(){I(a.unstable_now())},$)}a.unstable_IdlePriority=5,a.unstable_ImmediatePriority=1,a.unstable_LowPriority=4,a.unstable_NormalPriority=3,a.unstable_Profiling=null,a.unstable_UserBlockingPriority=2,a.unstable_cancelCallback=function(I){I.callback=null},a.unstable_continueExecution=function(){me||Ae||(me=!0,ne(U))},a.unstable_forceFrameRate=function(I){0>I||125y?(I.sortIndex=L,m(F,I),p(te)===null&&I===p(F)&&(he?(We(He),He=-1):he=!0,Z(Ie,L-y))):(I.sortIndex=k,m(te,I),me||Ae||(me=!0,ne(U))),I},a.unstable_shouldYield=Gt,a.unstable_wrapCallback=function(I){var $=ee;return function(){var L=ee;ee=$;try{return I.apply(this,arguments)}finally{ee=L}}}})(Vi)),Vi}var od;function Mf(){return od||(od=1,Hi.exports=Rf()),Hi.exports}var ld;function Af(){if(ld)return Vt;ld=1;var a=tu(),m=Mf();function p(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"),te=Object.prototype.hasOwnProperty,F=/^[: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]*$/,Y={},X={};function ee(e){return te.call(X,e)?!0:te.call(Y,e)?!1:F.test(e)?X[e]=!0:(Y[e]=!0,!1)}function Ae(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"||Ae(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 he(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 ye={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ye[e]=new he(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ye[t]=new he(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){ye[e]=new he(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ye[e]=new he(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){ye[e]=new he(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){ye[e]=new he(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){ye[e]=new he(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){ye[e]=new he(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){ye[e]=new he(e,5,!1,e.toLowerCase(),null,!1,!1)});var We=/[\-:]([a-z])/g;function Ze(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(We,Ze);ye[t]=new he(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(We,Ze);ye[t]=new he(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(We,Ze);ye[t]=new he(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){ye[e]=new he(e,1,!1,e.toLowerCase(),null,!1,!1)}),ye.xlinkHref=new he("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){ye[e]=new he(e,1,!1,e.toLowerCase(),null,!0,!0)});function qe(e,t,n,r){var s=ye.hasOwnProperty(t)?ye[t]:null;(s!==null?s.type!==0:r||!(2d||s[u]!==l[d]){var h=` -`+s[u].replace(" at new "," at ");return e.displayName&&h.includes("")&&(h=h.replace("",e.displayName)),h}while(1<=u&&0<=d);break}}}finally{re=!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=ie(e.type,!1),e;case 11:return e=ie(e.type.render,!1),e;case 1:return e=ie(e.type,!0),e;default:return""}}function xe(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 Pe:return"Fragment";case oe:return"Portal";case _t:return"Profiler";case He:return"StrictMode";case Q:return"Suspense";case Le:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Gt:return(e.displayName||"Context")+".Consumer";case dt:return(e._context.displayName||"Context")+".Provider";case ft:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ye:return t=e.displayName||null,t!==null?t:xe(e.type)||"Memo";case ne:t=e._payload,e=e._init;try{return xe(e(t))}catch{}}return null}function je(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 xe(t);case 8:return t===He?"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 ke(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Ne(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function pt(e){var t=Ne(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 sn(e){e._valueTracker||(e._valueTracker=pt(e))}function yr(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Ne(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function On(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 yn(e,t){var n=t.checked;return L({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function we(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ke(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 Wt(e,t){t=t.checked,t!=null&&qe(e,"checked",t,!1)}function Ke(e,t){Wt(e,t);var n=ke(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")?Tt(e,t.type,n):t.hasOwnProperty("defaultValue")&&Tt(e,t.type,ke(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function St(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 Tt(e,t,n){(t!=="number"||On(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var xn=Array.isArray;function W(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=ht.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function _n(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var fe={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},Sn=["Webkit","ms","Moz","O"];Object.keys(fe).forEach(function(e){Sn.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),fe[t]=fe[e]})});function gt(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||fe.hasOwnProperty(e)&&fe[e]?(""+t).trim():t+"px"}function Wr(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=gt(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var ot=L({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 zn(e,t){if(t){if(ot[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(p(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(p(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(p(61))}if(t.style!=null&&typeof t.style!="object")throw Error(p(62))}}function bn(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 Rt=null;function wn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var on=null,pe=null,Mt=null;function Be(e){if(e=Co(e)){if(typeof on!="function")throw Error(p(280));var t=e.stateNode;t&&(t=gl(t),on(e.stateNode,e.type,t))}}function jn(e){pe?Mt?Mt.push(e):Mt=[e]:pe=e}function _r(){if(pe){var e=pe,t=Mt;if(Mt=pe=null,Be(e),t)for(e=0;e>>=0,e===0?32:31-(so(e)/fa|0)|0}var Xr=64,Ss=4194304;function Cn(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 ws(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=Cn(d):(l&=u,l!==0&&(r=Cn(l)))}else u=n&~s,u!==0?r=Cn(u):l!==0&&(r=Cn(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 sr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-At(t),e[t]=n}function Jo(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=bt),os=" ",ho=!1;function go(e,t){switch(e){case"keyup":return ja.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function vo(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ar=!1;function sl(e,t){switch(e){case"compositionend":return vo(t);case"keypress":return t.which!==32?null:(ho=!0,os);case"textInput":return e=t.data,e===os&&ho?null:e;default:return null}}function ol(e,t){if(ar)return e==="compositionend"||!mo&&go(e,t)?(e=uo(),ts=Nr=qn=null,ar=!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=As(n)}}function ou(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ou(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function lu(){for(var e=window,t=On();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=On(e.document)}return t}function ka(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 Ad(e){var t=lu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ou(n.ownerDocument.documentElement,n)){if(r!==null&&ka(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=su(n,l);var u=su(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,Is=null,Ca=null,_o=null,Na=!1;function au(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Na||Is==null||Is!==On(r)||(r=Is,"selectionStart"in r&&ka(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}),_o&&ir(_o,r)||(_o=r,r=pl(Ca,"onSelect"),0zs||(e.current=za[zs],za[zs]=null,zs--)}function ze(e,t){zs++,za[zs]=e.current,e.current=t}var Dr={},kt=Lr(Dr),Ft=Lr(!1),us=Dr;function bs(e,t){var n=e.type.contextTypes;if(!n)return Dr;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 Ut(e){return e=e.childContextTypes,e!=null}function vl(){Ue(Ft),Ue(kt)}function wu(e,t,n){if(kt.current!==Dr)throw Error(p(168));ze(kt,t),ze(Ft,n)}function ju(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(p(108,je(e)||"Unknown",s));return L({},n,r)}function yl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Dr,us=kt.current,ze(kt,e),ze(Ft,Ft.current),!0}function ku(e,t,n){var r=e.stateNode;if(!r)throw Error(p(169));n?(e=ju(e,t,us),r.__reactInternalMemoizedMergedChildContext=e,Ue(Ft),Ue(kt),ze(kt,e)):Ue(Ft),ze(Ft,n)}var cr=null,xl=!1,ba=!1;function Cu(e){cr===null?cr=[e]:cr.push(e)}function Hd(e){xl=!0,Cu(e)}function Or(){if(!ba&&cr!==null){ba=!0;var e=0,t=ge;try{var n=cr;for(ge=1;e>=u,s-=u,dr=1<<32-At(t)+s|n<se?(ct=K,K=null):ct=K.sibling;var Ee=E(x,K,_[se],R);if(Ee===null){K===null&&(K=ct);break}e&&K&&Ee.alternate===null&&t(x,K),v=l(Ee,v,se),q===null?G=Ee:q.sibling=Ee,q=Ee,K=ct}if(se===_.length)return n(x,K),Qe&&ds(x,se),G;if(K===null){for(;se<_.length;se++)K=T(x,_[se],R),K!==null&&(v=l(K,v,se),q===null?G=K:q.sibling=K,q=K);return Qe&&ds(x,se),G}for(K=r(x,K);se<_.length;se++)ct=O(K,x,se,_[se],R),ct!==null&&(e&&ct.alternate!==null&&K.delete(ct.key===null?se:ct.key),v=l(ct,v,se),q===null?G=ct:q.sibling=ct,q=ct);return e&&K.forEach(function(Vr){return t(x,Vr)}),Qe&&ds(x,se),G}function H(x,v,_,R){var G=$(_);if(typeof G!="function")throw Error(p(150));if(_=G.call(_),_==null)throw Error(p(151));for(var q=G=null,K=v,se=v=0,ct=null,Ee=_.next();K!==null&&!Ee.done;se++,Ee=_.next()){K.index>se?(ct=K,K=null):ct=K.sibling;var Vr=E(x,K,Ee.value,R);if(Vr===null){K===null&&(K=ct);break}e&&K&&Vr.alternate===null&&t(x,K),v=l(Vr,v,se),q===null?G=Vr:q.sibling=Vr,q=Vr,K=ct}if(Ee.done)return n(x,K),Qe&&ds(x,se),G;if(K===null){for(;!Ee.done;se++,Ee=_.next())Ee=T(x,Ee.value,R),Ee!==null&&(v=l(Ee,v,se),q===null?G=Ee:q.sibling=Ee,q=Ee);return Qe&&ds(x,se),G}for(K=r(x,K);!Ee.done;se++,Ee=_.next())Ee=O(K,x,se,Ee.value,R),Ee!==null&&(e&&Ee.alternate!==null&&K.delete(Ee.key===null?se:Ee.key),v=l(Ee,v,se),q===null?G=Ee:q.sibling=Ee,q=Ee);return e&&K.forEach(function(Cf){return t(x,Cf)}),Qe&&ds(x,se),G}function Xe(x,v,_,R){if(typeof _=="object"&&_!==null&&_.type===Pe&&_.key===null&&(_=_.props.children),typeof _=="object"&&_!==null){switch(_.$$typeof){case U:e:{for(var G=_.key,q=v;q!==null;){if(q.key===G){if(G=_.type,G===Pe){if(q.tag===7){n(x,q.sibling),v=s(q,_.props.children),v.return=x,x=v;break e}}else if(q.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===ne&&Mu(G)===q.type){n(x,q.sibling),v=s(q,_.props),v.ref=No(x,q,_),v.return=x,x=v;break e}n(x,q);break}else t(x,q);q=q.sibling}_.type===Pe?(v=xs(_.props.children,x.mode,R,_.key),v.return=x,x=v):(R=Wl(_.type,_.key,_.props,null,x.mode,R),R.ref=No(x,v,_),R.return=x,x=R)}return u(x);case oe:e:{for(q=_.key;v!==null;){if(v.key===q)if(v.tag===4&&v.stateNode.containerInfo===_.containerInfo&&v.stateNode.implementation===_.implementation){n(x,v.sibling),v=s(v,_.children||[]),v.return=x,x=v;break e}else{n(x,v);break}else t(x,v);v=v.sibling}v=Oi(_,x.mode,R),v.return=x,x=v}return u(x);case ne:return q=_._init,Xe(x,v,q(_._payload),R)}if(xn(_))return B(x,v,_,R);if($(_))return H(x,v,_,R);jl(x,_)}return typeof _=="string"&&_!==""||typeof _=="number"?(_=""+_,v!==null&&v.tag===6?(n(x,v.sibling),v=s(v,_),v.return=x,x=v):(n(x,v),v=Di(_,x.mode,R),v.return=x,x=v),u(x)):n(x,v)}return Xe}var Qs=Au(!0),Iu=Au(!1),kl=Lr(null),Cl=null,Hs=null,Va=null;function Ga(){Va=Hs=Cl=null}function Wa(e){var t=kl.current;Ue(kl),e._currentValue=t}function qa(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 Vs(e,t){Cl=e,Va=Hs=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Bt=!0),e.firstContext=null)}function pn(e){var t=e._currentValue;if(Va!==e)if(e={context:e,memoizedValue:t,next:null},Hs===null){if(Cl===null)throw Error(p(308));Hs=e,Cl.dependencies={lanes:0,firstContext:e}}else Hs=Hs.next=e;return t}var fs=null;function Ka(e){fs===null?fs=[e]:fs.push(e)}function Lu(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Ka(t)):(n.next=s.next,s.next=n),t.interleaved=n,pr(e,r)}function pr(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 $r=!1;function Ja(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Du(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 mr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function zr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(Ce&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,pr(e,n)}return s=r.interleaved,s===null?(t.next=t,Ka(r)):(t.next=s.next,s.next=t),r.interleaved=t,pr(e,n)}function Nl(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,js(e,n)}}function Ou(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 El(e,t,n,r){var s=e.updateQueue;$r=!1;var l=s.firstBaseUpdate,u=s.lastBaseUpdate,d=s.shared.pending;if(d!==null){s.shared.pending=null;var h=d,j=h.next;h.next=null,u===null?l=j:u.next=j,u=h;var P=e.alternate;P!==null&&(P=P.updateQueue,d=P.lastBaseUpdate,d!==u&&(d===null?P.firstBaseUpdate=j:d.next=j,P.lastBaseUpdate=h))}if(l!==null){var T=s.baseState;u=0,P=j=h=null,d=l;do{var E=d.lane,O=d.eventTime;if((r&E)===E){P!==null&&(P=P.next={eventTime:O,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var B=e,H=d;switch(E=t,O=n,H.tag){case 1:if(B=H.payload,typeof B=="function"){T=B.call(O,T,E);break e}T=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=H.payload,E=typeof B=="function"?B.call(O,T,E):B,E==null)break e;T=L({},T,E);break e;case 2:$r=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,E=s.effects,E===null?s.effects=[d]:E.push(d))}else O={eventTime:O,lane:E,tag:d.tag,payload:d.payload,callback:d.callback,next:null},P===null?(j=P=O,h=T):P=P.next=O,u|=E;if(d=d.next,d===null){if(d=s.shared.pending,d===null)break;E=d,d=E.next,E.next=null,s.lastBaseUpdate=E,s.shared.pending=null}}while(!0);if(P===null&&(h=T),s.baseState=h,s.firstBaseUpdate=j,s.lastBaseUpdate=P,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);hs|=u,e.lanes=u,e.memoizedState=T}}function $u(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=ti.transition;ti.transition={};try{e(!1),t()}finally{ge=n,ti.transition=r}}function nc(){return mn().memoizedState}function qd(e,t,n){var r=Br(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},rc(e))sc(t,n);else if(n=Lu(e,t,n,r),n!==null){var s=Ot();Dn(n,e,r,s),oc(n,t,r)}}function Kd(e,t,n){var r=Br(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(rc(e))sc(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,en(d,u)){var h=t.interleaved;h===null?(s.next=s,Ka(t)):(s.next=h.next,h.next=s),t.interleaved=s;return}}catch{}n=Lu(e,t,s,r),n!==null&&(s=Ot(),Dn(n,e,r,s),oc(n,t,r))}}function rc(e){var t=e.alternate;return e===Ge||t!==null&&t===Ge}function sc(e,t){Ro=Rl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function oc(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,js(e,n)}}var Il={readContext:pn,useCallback:Ct,useContext:Ct,useEffect:Ct,useImperativeHandle:Ct,useInsertionEffect:Ct,useLayoutEffect:Ct,useMemo:Ct,useReducer:Ct,useRef:Ct,useState:Ct,useDebugValue:Ct,useDeferredValue:Ct,useTransition:Ct,useMutableSource:Ct,useSyncExternalStore:Ct,useId:Ct,unstable_isNewReconciler:!1},Jd={readContext:pn,useCallback:function(e,t){return er().memoizedState=[e,t===void 0?null:t],e},useContext:pn,useEffect:qu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ml(4194308,4,Yu.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ml(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ml(4,2,e,t)},useMemo:function(e,t){var n=er();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=er();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=qd.bind(null,Ge,e),[r.memoizedState,e]},useRef:function(e){var t=er();return e={current:e},t.memoizedState=e},useState:Gu,useDebugValue:ii,useDeferredValue:function(e){return er().memoizedState=e},useTransition:function(){var e=Gu(!1),t=e[0];return e=Wd.bind(null,e[1]),er().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ge,s=er();if(Qe){if(n===void 0)throw Error(p(407));n=n()}else{if(n=t(),ut===null)throw Error(p(349));(ms&30)!==0||Uu(r,t,n)}s.memoizedState=n;var l={value:n,getSnapshot:t};return s.queue=l,qu(Qu.bind(null,r,l,e),[e]),r.flags|=2048,Io(9,Bu.bind(null,r,l,n,t),void 0,null),n},useId:function(){var e=er(),t=ut.identifierPrefix;if(Qe){var n=fr,r=dr;n=(r&~(1<<32-At(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Mo++,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[Xn]=t,e[ko]=r,Cc(e,t,!1,!1),t.stateNode=e;e:{switch(u=bn(n,r),n){case"dialog":Fe("cancel",e),Fe("close",e),s=r;break;case"iframe":case"object":case"embed":Fe("load",e),s=r;break;case"video":case"audio":for(s=0;sJs&&(t.flags|=128,r=!0,Lo(l,!1),t.lanes=4194304)}else{if(!r)if(e=Pl(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Lo(l,!0),l.tail===null&&l.tailMode==="hidden"&&!u.alternate&&!Qe)return Nt(t),null}else 2*ae()-l.renderingStartTime>Js&&n!==1073741824&&(t.flags|=128,r=!0,Lo(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=ae(),t.sibling=null,n=Ve.current,ze(Ve,r?n&1|2:n&1),t):(Nt(t),null);case 22:case 23:return Ai(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(rn&1073741824)!==0&&(Nt(t),t.subtreeFlags&6&&(t.flags|=8192)):Nt(t),null;case 24:return null;case 25:return null}throw Error(p(156,t.tag))}function sf(e,t){switch(Ua(t),t.tag){case 1:return Ut(t.type)&&vl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Gs(),Ue(Ft),Ue(kt),ei(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return Xa(t),null;case 13:if(Ue(Ve),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(p(340));Bs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ue(Ve),null;case 4:return Gs(),null;case 10:return Wa(t.type._context),null;case 22:case 23:return Ai(),null;case 24:return null;default:return null}}var $l=!1,Et=!1,of=typeof WeakSet=="function"?WeakSet:Set,z=null;function qs(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Je(e,t,r)}else n.current=null}function _i(e,t,n){try{n()}catch(r){Je(e,t,r)}}var Pc=!1;function lf(e,t){if(Aa=be,e=lu(),ka(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,h=-1,j=0,P=0,T=e,E=null;t:for(;;){for(var O;T!==n||s!==0&&T.nodeType!==3||(d=u+s),T!==l||r!==0&&T.nodeType!==3||(h=u+r),T.nodeType===3&&(u+=T.nodeValue.length),(O=T.firstChild)!==null;)E=T,T=O;for(;;){if(T===e)break t;if(E===n&&++j===s&&(d=u),E===l&&++P===r&&(h=u),(O=T.nextSibling)!==null)break;T=E,E=T.parentNode}T=O}n=d===-1||h===-1?null:{start:d,end:h}}else n=null}n=n||{start:0,end:0}}else n=null;for(Ia={focusedElem:e,selectionRange:n},be=!1,z=t;z!==null;)if(t=z,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,z=e;else for(;z!==null;){t=z;try{var B=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(B!==null){var H=B.memoizedProps,Xe=B.memoizedState,x=t.stateNode,v=x.getSnapshotBeforeUpdate(t.elementType===t.type?H:An(t.type,H),Xe);x.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var _=t.stateNode.containerInfo;_.nodeType===1?_.textContent="":_.nodeType===9&&_.documentElement&&_.removeChild(_.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163))}}catch(R){Je(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,z=e;break}z=t.return}return B=Pc,Pc=!1,B}function Do(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&&_i(t,n,l)}s=s.next}while(s!==r)}}function zl(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 Si(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 Tc(e){var t=e.alternate;t!==null&&(e.alternate=null,Tc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Xn],delete t[ko],delete t[$a],delete t[Bd],delete t[Qd])),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 Rc(e){return e.tag===5||e.tag===3||e.tag===4}function Mc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Rc(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 wi(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=hl));else if(r!==4&&(e=e.child,e!==null))for(wi(e,t,n),e=e.sibling;e!==null;)wi(e,t,n),e=e.sibling}function ji(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(ji(e,t,n),e=e.sibling;e!==null;)ji(e,t,n),e=e.sibling}var yt=null,In=!1;function br(e,t,n){for(n=n.child;n!==null;)Ac(e,t,n),n=n.sibling}function Ac(e,t,n){if($t&&typeof $t.onCommitFiberUnmount=="function")try{$t.onCommitFiberUnmount(Cr,n)}catch{}switch(n.tag){case 5:Et||qs(n,t);case 6:var r=yt,s=In;yt=null,br(e,t,n),yt=r,In=s,yt!==null&&(In?(e=yt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):yt.removeChild(n.stateNode));break;case 18:yt!==null&&(In?(e=yt,n=n.stateNode,e.nodeType===8?Oa(e.parentNode,n):e.nodeType===1&&Oa(e,n),Oe(e)):Oa(yt,n.stateNode));break;case 4:r=yt,s=In,yt=n.stateNode.containerInfo,In=!0,br(e,t,n),yt=r,In=s;break;case 0:case 11:case 14:case 15:if(!Et&&(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)&&_i(n,t,u),s=s.next}while(s!==r)}br(e,t,n);break;case 1:if(!Et&&(qs(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(d){Je(n,t,d)}br(e,t,n);break;case 21:br(e,t,n);break;case 22:n.mode&1?(Et=(r=Et)||n.memoizedState!==null,br(e,t,n),Et=r):br(e,t,n);break;default:br(e,t,n)}}function Ic(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new of),t.forEach(function(r){var s=gf.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Ln(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~l}if(r=s,r=ae()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*uf(r/1960))-r,10e?16:e,Ur===null)var r=!1;else{if(e=Ur,Ur=null,Ql=0,(Ce&6)!==0)throw Error(p(331));var s=Ce;for(Ce|=4,z=e.current;z!==null;){var l=z,u=l.child;if((z.flags&16)!==0){var d=l.deletions;if(d!==null){for(var h=0;hae()-Ni?vs(e,0):Ci|=n),Ht(e,t)}function Gc(e,t){t===0&&((e.mode&1)===0?t=1:(t=Ss,Ss<<=1,(Ss&130023424)===0&&(Ss=4194304)));var n=Ot();e=pr(e,t),e!==null&&(sr(e,t,n),Ht(e,n))}function hf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Gc(e,n)}function gf(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(p(314))}r!==null&&r.delete(t),Gc(e,n)}var Wc;Wc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Ft.current)Bt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Bt=!1,nf(e,t,n);Bt=(e.flags&131072)!==0}else Bt=!1,Qe&&(t.flags&1048576)!==0&&Nu(t,Sl,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ol(e,t),e=t.pendingProps;var s=bs(t,kt.current);Vs(t,n),s=ri(null,t,r,e,s,n);var l=si();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,Ut(r)?(l=!0,yl(t)):l=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Ja(t),s.updater=Ll,t.stateNode=s,s._reactInternals=t,ci(t,r,e,n),t=mi(null,t,r,!0,l,n)):(t.tag=0,Qe&&l&&Fa(t),Dt(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ol(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=yf(r),e=An(r,e),s){case 0:t=pi(null,t,r,e,n);break e;case 1:t=xc(null,t,r,e,n);break e;case 11:t=mc(null,t,r,e,n);break e;case 14:t=hc(null,t,r,An(r.type,e),n);break e}throw Error(p(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:An(r,s),pi(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:An(r,s),xc(e,t,r,s,n);case 3:e:{if(_c(t),e===null)throw Error(p(387));r=t.pendingProps,l=t.memoizedState,s=l.element,Du(e,t),El(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=Ws(Error(p(423)),t),t=Sc(e,t,r,n,s);break e}else if(r!==s){s=Ws(Error(p(424)),t),t=Sc(e,t,r,n,s);break e}else for(nn=Ir(t.stateNode.containerInfo.firstChild),tn=t,Qe=!0,Mn=null,n=Iu(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Bs(),r===s){t=hr(e,t,n);break e}Dt(e,t,r,n)}t=t.child}return t;case 5:return zu(t),e===null&&Qa(t),r=t.type,s=t.pendingProps,l=e!==null?e.memoizedProps:null,u=s.children,La(r,s)?u=null:l!==null&&La(r,l)&&(t.flags|=32),yc(e,t),Dt(e,t,u,n),t.child;case 6:return e===null&&Qa(t),null;case 13:return wc(e,t,n);case 4:return Ya(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Qs(t,null,r,n):Dt(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:An(r,s),mc(e,t,r,s,n);case 7:return Dt(e,t,t.pendingProps,n),t.child;case 8:return Dt(e,t,t.pendingProps.children,n),t.child;case 12:return Dt(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,ze(kl,r._currentValue),r._currentValue=u,l!==null)if(en(l.value,u)){if(l.children===s.children&&!Ft.current){t=hr(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 h=d.firstContext;h!==null;){if(h.context===r){if(l.tag===1){h=mr(-1,n&-n),h.tag=2;var j=l.updateQueue;if(j!==null){j=j.shared;var P=j.pending;P===null?h.next=h:(h.next=P.next,P.next=h),j.pending=h}}l.lanes|=n,h=l.alternate,h!==null&&(h.lanes|=n),qa(l.return,n,t),d.lanes|=n;break}h=h.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(p(341));u.lanes|=n,d=u.alternate,d!==null&&(d.lanes|=n),qa(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}Dt(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Vs(t,n),s=pn(s),r=r(s),t.flags|=1,Dt(e,t,r,n),t.child;case 14:return r=t.type,s=An(r,t.pendingProps),s=An(r.type,s),hc(e,t,r,s,n);case 15:return gc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:An(r,s),Ol(e,t),t.tag=1,Ut(r)?(e=!0,yl(t)):e=!1,Vs(t,n),ac(t,r,s),ci(t,r,s,n),mi(null,t,r,!0,e,n);case 19:return kc(e,t,n);case 22:return vc(e,t,n)}throw Error(p(156,t.tag))};function qc(e,t){return no(e,t)}function vf(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 gn(e,t,n,r){return new vf(e,t,n,r)}function Li(e){return e=e.prototype,!(!e||!e.isReactComponent)}function yf(e){if(typeof e=="function")return Li(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ft)return 11;if(e===Ye)return 14}return 2}function Hr(e,t){var n=e.alternate;return n===null?(n=gn(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 Wl(e,t,n,r,s,l){var u=2;if(r=e,typeof e=="function")Li(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Pe:return xs(n.children,s,l,t);case He:u=8,s|=8;break;case _t:return e=gn(12,n,t,s|2),e.elementType=_t,e.lanes=l,e;case Q:return e=gn(13,n,t,s),e.elementType=Q,e.lanes=l,e;case Le:return e=gn(19,n,t,s),e.elementType=Le,e.lanes=l,e;case Z:return ql(n,s,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case dt:u=10;break e;case Gt:u=9;break e;case ft:u=11;break e;case Ye:u=14;break e;case ne:u=16,r=null;break e}throw Error(p(130,e==null?e:typeof e,""))}return t=gn(u,n,t,s),t.elementType=e,t.type=r,t.lanes=l,t}function xs(e,t,n,r){return e=gn(7,e,r,t),e.lanes=n,e}function ql(e,t,n,r){return e=gn(22,e,r,t),e.elementType=Z,e.lanes=n,e.stateNode={isHidden:!1},e}function Di(e,t,n){return e=gn(6,e,null,t),e.lanes=n,e}function Oi(e,t,n){return t=gn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function xf(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=Qn(0),this.expirationTimes=Qn(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Qn(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function $i(e,t,n,r,s,l,u,d,h){return e=new xf(e,t,n,d,h),t===1?(t=1,l===!0&&(t|=8)):t=0,l=gn(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ja(l),e}function _f(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(a)}catch(m){console.error(m)}}return a(),Qi.exports=Af(),Qi.exports}var id;function Lf(){if(id)return ta;id=1;var a=If();return ta.createRoot=a.createRoot,ta.hydrateRoot=a.hydrateRoot,ta}var Df=Lf();const Of=Nd(Df),$f="/api";async function Se(a,m){const p=await fetch(`${$f}${a}`,{...m,headers:{"Content-Type":"application/json",...m?.headers??{}}}),S=await p.json();if(!p.ok){const C=S.error?.message??"Ошибка запроса";throw new Error(C)}return S}const Re={async loadSharedConnectionConfig(){return Se("/llm/shared-connection")},async saveSharedConnectionConfig(a){return Se("/llm/shared-connection",{method:"POST",body:JSON.stringify({llmProvider:a.llmProvider,model:a.model,baseUrl:a.baseUrl,temperature:a.temperature,maxOutputTokens:a.maxOutputTokens})})},async listModels(a){return Se("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:a.llmProvider,apiKey:a.apiKey,model:a.model,baseUrl:a.baseUrl})})},async testConnection(a){return Se("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:a.llmProvider,apiKey:a.apiKey,model:a.model,baseUrl:a.baseUrl})})},async normalize(a){return Se("/normalize",{method:"POST",body:JSON.stringify({llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion,systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples,userQuestion:a.query.userQuestion,context:{period_hint:a.query.periodHint??"",business_context:a.query.businessContext??"",expected_route:a.query.expectedRoute??""},saveAsTestCase:!!a.saveAsTestCase,useMock:!!a.useMock})})},async loadHistory(){return Se("/history")},async loadTrace(a){return Se(`/history/${a}`)},async loadPresets(){return Se("/presets")},async savePreset(a){return Se("/presets/save",{method:"POST",body:JSON.stringify(a)})},async runEval(a){return Se("/eval/run",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion,systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples},caseIds:a.caseIds,useMock:!!a.useMock,mode:a.mode??"standard",caseSetFile:a.caseSetFile,rawQuestions:a.rawQuestions,eval_target:a.evalTarget,compare_with_report_file:a.compareWithReportFile,analysis_date:a.analysisDate})})},async startEvalRunAsync(a){return Se("/eval/run-async/start",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion,systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples},caseIds:a.caseIds,useMock:!!a.useMock,mode:a.mode??"standard",caseSetFile:a.caseSetFile,rawQuestions:a.rawQuestions,eval_target:a.evalTarget,compare_with_report_file:a.compareWithReportFile,questions:a.questions,scenarioQuestions:a.scenarioQuestions,scenarioTitle:a.scenarioTitle,analysis_date:a.analysisDate})})},async loadEvalRunAsyncStatus(a){return Se(`/eval/run-async/${encodeURIComponent(a)}`)},async cancelEvalRunAsync(a){return Se(`/eval/run-async/${encodeURIComponent(a)}/cancel`,{method:"POST"})},async startRun(){return Se("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(a){return Se("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:a,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return Se("/accounting-agent/v1/runs")},async listResults(){return Se("/accounting-agent/v1/results")},async runTrace(a){return Se(`/accounting-agent/v1/trace/run/${a}`)},async sendAssistantMessage(a){return Se("/assistant/message",{method:"POST",body:JSON.stringify({session_id:a.sessionId??"",mode:"assistant",message:a.userMessage,user_message:a.userMessage,llmProvider:a.connection.llmProvider,apiKey:a.connection.apiKey,model:a.connection.model,baseUrl:a.connection.baseUrl,temperature:a.connection.temperature,maxOutputTokens:a.connection.maxOutputTokens,promptVersion:a.promptVersion??"address_query_runtime_v1",systemPrompt:a.prompts.systemPrompt,developerPrompt:a.prompts.developerPrompt,domainPrompt:a.prompts.domainPrompt,fewShotExamples:a.prompts.fewShotExamples,context:{period_hint:a.context?.periodHint??"",business_context:a.context?.businessContext??""},useMock:!!a.useMock})})},async loadAssistantSession(a){return Se(`/assistant/session/${a}`)},async saveAutoRunAssistantSession(a){return Se("/autoruns/autogen/save-assistant-session",{method:"POST",body:JSON.stringify(a)})},async loadAssistantAnnotations(a){const m=new URLSearchParams;a?.session_id&&m.set("session_id",a.session_id),typeof a?.limit=="number"&&m.set("limit",String(a.limit));const p=m.toString();return Se(`/assistant/annotations${p?`?${p}`:""}`)},async saveAssistantAnnotation(a){return Se("/assistant/annotations",{method:"POST",body:JSON.stringify(a)})},async loadAutoRunsHistory(a){const m=new URLSearchParams;a?.from&&m.set("from",a.from),a?.to&&m.set("to",a.to),a?.target&&m.set("target",a.target),a?.mode&&m.set("mode",a.mode),a?.use_mock&&m.set("use_mock",a.use_mock),a?.prompt_contains&&m.set("prompt_contains",a.prompt_contains),typeof a?.limit=="number"&&m.set("limit",String(a.limit)),typeof a?.scan_limit=="number"&&m.set("scan_limit",String(a.scan_limit));const p=m.toString();return Se(`/autoruns/history${p?`?${p}`:""}`)},async loadAutoRunDetail(a){return Se(`/autoruns/history/${encodeURIComponent(a)}`)},async loadAutoRunCaseDialog(a,m){return Se(`/autoruns/history/${encodeURIComponent(a)}/case/${encodeURIComponent(m)}/dialog`)},async loadAutoRunAnnotations(a){const m=new URLSearchParams;a?.run_id&&m.set("run_id",a.run_id),a?.case_id&&m.set("case_id",a.case_id),typeof a?.min_rating=="number"&&m.set("min_rating",String(a.min_rating)),a?.manual_case_decision&&m.set("manual_case_decision",a.manual_case_decision),typeof a?.limit=="number"&&m.set("limit",String(a.limit));const p=m.toString();return Se(`/autoruns/annotations${p?`?${p}`:""}`)},async saveAutoRunAnnotation(a){return Se("/autoruns/annotations",{method:"POST",body:JSON.stringify(a)})},async updateAutoRunAnnotation(a){return Se(`/autoruns/annotations/${encodeURIComponent(a.annotation_id)}`,{method:"PATCH",body:JSON.stringify({resolved:a.resolved,resolved_by:a.resolved_by})})},async loadAutoRunPostAnalysis(a){const m=new URLSearchParams;a?.run_id&&m.set("run_id",a.run_id),typeof a?.limit_per_queue=="number"&&m.set("limit_per_queue",String(a.limit_per_queue)),typeof a?.annotation_limit=="number"&&m.set("annotation_limit",String(a.annotation_limit)),typeof a?.scan_limit=="number"&&m.set("scan_limit",String(a.scan_limit)),a?.from&&m.set("from",a.from),a?.to&&m.set("to",a.to),a?.target&&m.set("target",a.target),a?.mode&&m.set("mode",a.mode),a?.use_mock&&m.set("use_mock",a.use_mock),a?.prompt_contains&&m.set("prompt_contains",a.prompt_contains);const p=m.toString();return Se(`/autoruns/post-analysis${p?`?${p}`:""}`)},async loadAutoRunAutogenHistory(a){const m=new URLSearchParams;a?.mode&&m.set("mode",a.mode),typeof a?.limit=="number"&&m.set("limit",String(a.limit));const p=m.toString();return Se(`/autoruns/autogen/history${p?`?${p}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return Se("/autoruns/autogen/personality-catalog")},async updateAutoRunAutogenQuestions(a){return Se(`/autoruns/autogen/history/${encodeURIComponent(a.generation_id)}/questions`,{method:"PATCH",body:JSON.stringify({questions:a.questions})})},async deleteAutoRunAutogenHistoryRecord(a){return Se(`/autoruns/autogen/history/${encodeURIComponent(a)}`,{method:"DELETE"})},async generateAutoRunQuestions(a){return Se("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(a)})}},zf=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,bf=[/\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 vr(a){try{return JSON.stringify(a,null,2)}catch{return String(a)}}function Ff(a){return a==="assistant"?"assistant":"user"}function Ed(a){const m=String(a??""),p=m.match(zf);return(p?m.slice(0,p.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(b=>b.trimEnd()).filter(b=>b.trim().length>0).filter(b=>!bf.some(le=>le.test(b))).join(` -`).trim()}function Uf(a,m,p="default"){const S=p==="technical",C=[];C.push("# Assistant conversation export"),C.push(`session_id: ${a||"n/a"}`),C.push(`export_mode: ${p}`),C.push(`exported_at: ${new Date().toISOString()}`),C.push("");for(let M=0;M0&&(S.push("### decomposition_json"),S.push("```json"),S.push(vr(a.decomposition)),S.push("```"),S.push("")),a.assistantMode&&(S.push("### assistant_mode_json"),S.push("```json"),S.push(vr(a.assistantMode)),S.push("```"),S.push("")),(a.annotations??[]).length>0&&(S.push("### annotations_json"),S.push("```json"),S.push(vr(a.annotations)),S.push("```"),S.push("")),a.runSummary&&(S.push("### run_summary_json"),S.push("```json"),S.push(vr(a.runSummary)),S.push("```"),S.push("")),a.coverage&&(S.push("### coverage_json"),S.push("```json"),S.push(vr(a.coverage)),S.push("```"),S.push("")),a.report&&(S.push("### run_report_json"),S.push("```json"),S.push(vr(a.report)),S.push("```"),S.push(""))),S.join(` -`)}function Pd({value:a}){return o.jsx("pre",{className:"json-view",children:JSON.stringify(a??{},null,2)})}function ca({title:a,subtitle:m,actions:p,className:S,hideHeader:C,children:M}){return o.jsxs("section",{className:S?`panel-frame ${S}`:"panel-frame",children:[C?null:o.jsxs("header",{className:"panel-header",children:[o.jsxs("div",{children:[o.jsx("h2",{children:a}),m?o.jsx("p",{children:m}):null]}),p?o.jsx("div",{className:"panel-actions",children:p}):null]}),o.jsx("div",{className:"panel-body",children:M})]})}function Qf(a){return a==="assistant"?"Ассистент":"Вы"}function Hf(a){const m=new Date(a);return Number.isNaN(m.getTime())?a:m.toLocaleTimeString("ru-RU")}async function Vf(a){if(navigator.clipboard&&window.isSecureContext)try{return await navigator.clipboard.writeText(a),!0}catch{}const m=document.createElement("textarea");m.value=a,m.setAttribute("readonly","true"),m.style.position="fixed",m.style.opacity="0",m.style.pointerEvents="none",document.body.appendChild(m),m.select();let p=!1;try{p=document.execCommand("copy")}catch{p=!1}finally{document.body.removeChild(m)}return p}function Gf({commented:a}){const m=a?"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 Wf(a){return a.replace(/\r\n?/g,` -`).replace(/([^\n])\s+(Блок\s+\d+\.)/gi,`$1 - -$2`).replace(/([^\n])\s+(\d+\.\s)/g,`$1 -$2`)}function qf(a){const p=Wf(a).split(` -`),S=[];let C=[];const M=()=>{C.length!==0&&(S.push(C.join(` -`)),C=[])};for(const b of p){const le=b.trimEnd(),te=le.trim();if(!te){M();continue}const F=/^Блок\s+\d+\./i.test(te),Y=/^\d+\.\s/.test(te);(F||Y)&&C.length>0&&M(),C.push(le)}return M(),S.length>0?S:[a]}function Kf(a,m){const p=[],S=/\*\*(.+?)\*\*/g;let C=0,M=0,b;for(;(b=S.exec(a))!==null;)b.index>C&&(p.push(o.jsx("span",{children:a.slice(C,b.index)},`${m}-t-${M}`)),M+=1),p.push(o.jsx("strong",{children:b[1]},`${m}-b-${M}`)),M+=1,C=S.lastIndex;return C0?p:[o.jsx("span",{children:a},`${m}-raw`)]}function Jf(a){const m=a.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 Yf(a,m=40){const p=a.replace(/\s+/g," ").trim();if(p.length<=m)return p;const S=p.split(" ").slice(0,3).join(" ").trim();return S.length>=10&&S.length<=m?`${S}…`:`${p.slice(0,m-1).trimEnd()}…`}function Td(a){return a.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Xf(a){const m=a.replace(/\r\n?/g,` -`).split(` -`).map(C=>C.trim()).find(Boolean),p=Td(m??"");return(p.split("|")[0]?.trim()??p).replace(/\s+/g," ").trim()}function Zf(a){const m=a.replace(/\r\n?/g,` -`).split(` -`).map(S=>S.trim()).find(Boolean);return!m||!/^\d+\.\s/.test(m)?!1:Td(m).includes("|")}function ep(a,m){const p=m.replace(/\r\n?/g,` -`).replace(/\*\*(.+?)\*\*/g,"$1").split(` -`).map((C,M)=>{const b=C.trim();return M===0?b.replace(/^\d+\.\s*/,""):b}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!p)return null;const S=Xf(m)||p;return{message_id:a.message_id,source_text:p,anchor_text:S,preview_text:Yf(S)}}function tp(a,m,p,S){return qf(a.text).map((M,b)=>{const le=M.split(` -`),te=a.role==="assistant"&&Zf(M),F=te?ep(a,M):null,Y=!!F&&m?.message_id===F?.message_id&&m?.source_text===F?.source_text,X=le.map((ee,Ae)=>o.jsx("p",{className:Jf(ee),children:Kf(ee,`line-${b}-${Ae}`)},`line-${b}-${Ae}`));return!te||!F?o.jsx("div",{className:"assistant-msg-block",children:X},`block-${b}`):o.jsx("div",{className:Y?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(Y){S();return}p(F)},onKeyDown:ee=>{if(!(ee.key!=="Enter"&&ee.key!==" ")){if(ee.preventDefault(),Y){S();return}p(F)}},children:X},`block-${b}`)})}function np({sessionId:a,conversation:m,inputValue:p,onInputChange:S,selectedContextChip:C,onSelectContextChip:M,onClearContextChip:b,useMock:le,onUseMockChange:te,onSend:F,onClear:Y,onSaveSession:X,busy:ee,saveBusy:Ae=!1,saveDisabled:me=!1,statusText:he,errorMessage:ye,showSaveAction:We=!1,showCommentAction:Ze=!1,onCommentAssistantMessage:qe,isAssistantMessageCommented:Ie,canCommentAssistantMessage:U}){const oe=g.useRef(null),Pe=g.useRef(!0),He=g.useRef(null),[_t,dt]=g.useState("idle"),[Gt,ft]=g.useState("чат");function Q(ne=!1){oe.current&&(ne&&(Pe.current=!0),oe.current.scrollTop=oe.current.scrollHeight)}g.useEffect(()=>{Pe.current&&Q()},[m]),g.useEffect(()=>()=>{He.current!==null&&window.clearTimeout(He.current)},[]);async function Le(ne){if(m.length===0)return;const Z=Uf(a,m,ne),I=await Vf(Z);ft(ne==="technical"?"тех":"чат"),dt(I?"success":"error"),He.current!==null&&window.clearTimeout(He.current),He.current=window.setTimeout(()=>{dt("idle")},2200)}function Ye(){if(!oe.current)return;const ne=oe.current,Z=ne.scrollHeight-ne.scrollTop-ne.clientHeight;Pe.current=Z<16}return o.jsx(ca,{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:()=>{Le("default")},disabled:m.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Le("technical")},disabled:m.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),We?o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>X?.(),disabled:Ae||me,children:Ae?"Сохраняю...":"Сохранить"}):null,o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>Y(),disabled:ee&&m.length===0,children:"Сбросить сессию"})]}),o.jsxs("div",{className:"assistant-toolbar-meta",children:[a?o.jsx("span",{className:"status-chip",children:`session: ${a}`}):null,o.jsxs("div",{className:"assistant-toolbar-meta-right",children:[he?o.jsx("span",{className:"assistant-live-status",children:he}):null,_t==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Gt,")"]}):null,_t==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),ye?o.jsx("p",{className:"error-text assistant-toolbar-error",children:ye}):null]}),o.jsx("div",{ref:oe,className:"assistant-chat-list",onScroll:Ye,children:m.map((ne,Z)=>{const I=ne.role==="assistant"&&Ze&&typeof qe=="function"&&(typeof U=="function"?U(ne,Z):!0),$=ne.role==="assistant"&&typeof Ie=="function"?Ie(ne,Z):!1;return o.jsxs("article",{className:`assistant-msg ${ne.role}`,children:[o.jsxs("header",{className:"assistant-msg-head",children:[o.jsxs("div",{className:"assistant-msg-head-main",children:[o.jsx("strong",{children:Qf(ne.role)}),o.jsx("span",{children:Hf(ne.created_at)})]}),ne.role==="assistant"&&Ze?o.jsx("div",{className:"assistant-msg-head-actions",children:o.jsx("button",{type:"button",className:$?"autoruns-comment-icon assistant-comment-btn commented":"autoruns-comment-icon assistant-comment-btn",onClick:()=>qe?.(ne,Z),disabled:!I,title:I?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":I?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:o.jsx(Gf,{commented:$})})}):null]}),o.jsx("div",{className:"assistant-msg-body",children:tp(ne,C,M,b)}),ne.role==="assistant"&&ne.debug?o.jsxs("details",{className:"assistant-debug",children:[o.jsx("summary",{children:"Показать технический разбор"}),o.jsx(Pd,{value:ne.debug})]}):null]},ne.message_id)})}),o.jsxs("div",{className:"assistant-compose",children:[C?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:C.source_text,children:[o.jsx("span",{className:"assistant-compose-context-pill-text",children:C.preview_text}),o.jsx("button",{type:"button",className:"assistant-compose-context-clear",onClick:b,"aria-label":"Убрать выбранный объект",title:"Убрать выбранный объект",children:"×"})]})]}):null,o.jsxs("label",{className:"full-width",children:["Сообщение",o.jsx("textarea",{className:"assistant-input-textarea",value:p,onChange:ne=>S(ne.target.value),rows:4,placeholder:C?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),o.jsxs("div",{className:"button-row assistant-send-row",children:[o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:le,onChange:ne=>te(ne.target.checked)}),"Mock-режим"]}),o.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{Q(!0),F()},disabled:ee||!p.trim(),children:ee?"Выполняю...":"Отправить"})]})]})]})})}const na="http://127.0.0.1:1234/v1",ud="https://api.openai.com/v1",ia="qwen2.5-14b-instruct-1m",nu="unsloth/qwen3-30b-a3b-instruct-2507",rp=[{value:ia,label:"Qwen2.5 14B Instruct 1M"},{value:nu,label:"Qwen3 30B A3B Instruct 2507"}];function sp(a){return a.llmProvider!=="local"?"openai":a.model===nu?"local_qwen3":a.model===ia?"local_qwen25":"local_custom"}function op(a,m){const p=new Map;if(m)for(const S of rp)p.set(S.value,S);for(const S of a)p.has(S)||p.set(S,{value:S,label:S});return Array.from(p.values())}function lp({value:a,modelOptions:m,modelsBusy:p,onChange:S,onReloadModels:C,onTestConnection:M,onSaveLocalConfig:b,lastStatus:le,busy:te,embedded:F=!1}){const Y=a.llmProvider==="local",X=sp(a),ee=op(m,Y),Ae=ee.some(U=>U.value===a.model),[me,he]=g.useState(String(a.temperature)),[ye,We]=g.useState(String(a.maxOutputTokens));g.useEffect(()=>{he(String(a.temperature))},[a.temperature]),g.useEffect(()=>{We(String(a.maxOutputTokens))},[a.maxOutputTokens]);const Ze=U=>{const oe=U.replace(",",".").trim();if(!oe){he(String(a.temperature));return}const Pe=Number(oe);if(!Number.isFinite(Pe)){he(String(a.temperature));return}S({...a,temperature:Pe}),he(String(Pe))},qe=U=>{const oe=U.trim();if(!oe){We(String(a.maxOutputTokens));return}const Pe=Number.parseInt(oe,10);if(!Number.isFinite(Pe)||Pe<=0){We(String(a.maxOutputTokens));return}S({...a,maxOutputTokens:Pe}),We(String(Pe))},Ie=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid-two",children:[o.jsxs("label",{children:["Provider",o.jsxs("select",{value:X,onChange:U=>{const oe=U.target.value;if(oe==="openai"){S({...a,llmProvider:"openai",baseUrl:ud});return}if(oe==="local_qwen25"){S({...a,llmProvider:"local",model:ia,baseUrl:na});return}if(oe==="local_qwen3"){S({...a,llmProvider:"local",model:nu,baseUrl:na});return}S({...a,llmProvider:"local",model:a.llmProvider==="local"?a.model:ia,baseUrl:na})},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:Ae?a.model:"__manual__",onChange:U=>{const oe=U.target.value;oe!=="__manual__"&&S({...a,model:oe})},children:[o.jsx("option",{value:"__manual__",children:"Manual input"}),ee.map(U=>o.jsx("option",{value:U.value,children:U.label},U.value))]})]}),o.jsxs("label",{children:["Model ID (manual / current)",o.jsx("input",{value:a.model,onChange:U=>S({...a,model:U.target.value}),placeholder:"qwen2.5-14b-instruct-1m or unsloth/qwen3-30b-a3b-instruct-2507"})]}),Y?null:o.jsxs("label",{className:"full-width",children:["OpenAI API Key",o.jsx("input",{type:"password",value:a.apiKey,onChange:U=>S({...a,apiKey:U.target.value}),placeholder:"sk-..."})]}),o.jsxs("label",{className:Y?"full-width":void 0,children:[Y?"Local server base URL":"Base URL",o.jsx("input",{value:a.baseUrl,onChange:U=>S({...a,baseUrl:U.target.value}),placeholder:Y?na:ud})]}),o.jsxs("label",{children:["Temperature",o.jsx("input",{type:"number",step:"0.1",value:me,onChange:U=>he(U.target.value),onBlur:U=>Ze(U.target.value),onKeyDown:U=>{U.key==="Enter"&&Ze(U.target.value)}})]}),o.jsxs("label",{children:["Max output tokens",o.jsx("input",{type:"number",value:ye,onChange:U=>We(U.target.value),onBlur:U=>qe(U.target.value),onKeyDown:U=>{U.key==="Enter"&&qe(U.target.value)}})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>b(),children:"Save local config"}),o.jsx("button",{type:"button",onClick:()=>C(),disabled:te||p,children:p?"Loading models...":"Load model list"}),o.jsx("button",{type:"button",onClick:()=>M(),disabled:te,children:te?"Checking...":"Test connection"})]})]});return F?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsxs("div",{className:"embedded-panel-section-header",children:[o.jsxs("div",{children:[o.jsx("h4",{children:"LLM Connector"}),o.jsx("p",{children:"Switch between OpenAI cloud and local OpenAI-compatible server."})]}),o.jsx("span",{className:"status-chip",children:le||"Status: not checked"})]}),Ie]}):o.jsx(ca,{title:"LLM Connector",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:o.jsx("span",{className:"status-chip",children:le||"Status: not checked"}),children:Ie})}function ap({value:a,onChange:m,presets:p,selectedPresetId:S,onSelectPreset:C,onLoadPreset:M,onSavePreset:b,onResetDefaults:le,onDiffPrevious:te,presetName:F,onPresetNameChange:Y,diffSummary:X,embedded:ee=!1}){const Ae=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"prompt-manager-grid",children:[o.jsxs("label",{children:["Системный prompt",o.jsx("textarea",{value:a.systemPrompt,onChange:me=>m({...a,systemPrompt:me.target.value}),rows:6})]}),o.jsxs("label",{children:["Developer / Instruction prompt",o.jsx("textarea",{value:a.developerPrompt,onChange:me=>m({...a,developerPrompt:me.target.value}),rows:6})]}),o.jsxs("label",{children:["Domain prompt",o.jsx("textarea",{value:a.domainPrompt,onChange:me=>m({...a,domainPrompt:me.target.value}),rows:6})]}),o.jsxs("label",{children:["Schema notes",o.jsx("textarea",{value:a.schemaNotes,onChange:me=>m({...a,schemaNotes:me.target.value}),rows:6})]}),o.jsxs("label",{className:"full-width",children:["Few-shot examples",o.jsx("textarea",{value:a.fewShotExamples,onChange:me=>m({...a,fewShotExamples:me.target.value}),rows:8})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsxs("select",{value:S,onChange:me=>C(me.target.value),children:[o.jsx("option",{value:"",children:"Выберите preset..."}),p.map(me=>o.jsx("option",{value:me.id,children:me.name},me.id))]}),o.jsx("button",{type:"button",onClick:()=>M(),children:"Загрузить preset"}),o.jsx("input",{value:F,onChange:me=>Y(me.target.value),placeholder:"Имя для сохранения"}),o.jsx("button",{type:"button",onClick:()=>b(),children:"Сохранить preset"}),o.jsx("button",{type:"button",onClick:()=>te(),children:"Diff с предыдущим"}),o.jsx("button",{type:"button",onClick:()=>le(),children:"Сбросить к default"})]}),X?o.jsx("p",{className:"diff-summary",children:X}):null]});return ee?o.jsxs("section",{className:"embedded-panel-section",children:[o.jsx("div",{className:"embedded-panel-section-header",children:o.jsxs("div",{children:[o.jsx("h4",{children:"Prompt Manager"}),o.jsx("p",{children:"Системный, developer и domain уровни управляются отдельно."})]})}),Ae]}):o.jsx(ca,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:Ae})}const Gi={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},ra="needs_dialog_policy_fix",Pt="__all__",ua="__live__:",cd="ndc_autoruns_ui_config_v1",dd="ndc-autoruns-save",ip=180,Uo=30,Wi=["Анализ запроса","Получение данных","Подготовка ответа"];function up(a,m){const p=a.trim();if(!p)return"";if(!m)return p;const S=p.toLowerCase(),C=m.anchor_text.trim(),M=C.toLowerCase();return M&&S.includes(M)?p:`По выбранному объекту "${C}": ${p}`}const eu=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function cp(a=eu){return a.reduce((m,p)=>(m[p.id]=p.defaultPrompt,m),{})}const fd={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:cp(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function qi(a){const m=String(a??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(m)?m:""}function pd(a){const m=typeof a=="number"&&Number.isFinite(a)?Math.trunc(a):160;return Math.max(110,Math.min(520,m))}function dp(a){const m=a.getFullYear(),p=String(a.getMonth()+1).padStart(2,"0"),S=String(a.getDate()).padStart(2,"0"),C=String(a.getHours()).padStart(2,"0"),M=String(a.getMinutes()).padStart(2,"0");return`${m}-${p}-${S}T${C}:${M}`}function md(){const a=new Date;return a.setDate(a.getDate()-14),dp(a)}function sa(a){if(!a.trim())return;const m=Date.parse(a);if(Number.isFinite(m))return new Date(m).toISOString()}function vn(a){if(!a)return"нет данных";const m=Date.parse(a);return Number.isFinite(m)?new Date(m).toLocaleString("ru-RU"):a}function hd(a){const m=typeof a.case_message_index=="number"?a.case_message_index:typeof a.message_index=="number"?a.message_index:null;if(m===null||m<0)return null;const p=Math.floor(m/2)+1,S=String(p).padStart(3,"0"),C=a.role==="assistant"?"ответ":"вопрос";return`${S} ${C}`}function Ki(a){return a==="saved_user_sessions"?"Пользовательские сессии":a}function Rd(a){return a?a.context?.agent_run===!0||a.context?.saved_case_set_kind==="agent_semantic_scenario"?!0:typeof a.title=="string"&&a.title.trim().toUpperCase().startsWith("AGENT"):!1}function Ji(a){const m=a.title??vn(a.created_at);return Rd(a)&&!m.trim().toUpperCase().startsWith("AGENT")?`AGENT | ${m}`:m}function fp(a){const m=a[a.length-1];return`Ручная сессия ${vn(m?.created_at??new Date().toISOString())}`}function pp(a,m){return m<=0?0:Math.max(0,Math.min(100,Number((a/m*100).toFixed(1))))}function oa(a){return typeof a!="number"?"нет данных":`${a.toFixed(1)}%`}function mp(a){return a==="assistant_stage1"?"assistant/s1":a==="assistant_stage2"?"assistant/s2":a==="assistant_p0"?"assistant/p0":a}function gd(a){return a==="up"?"Рост":a==="down"?"Регресс":"Без изменений"}function Yi(a){const m=Math.max(1,Math.min(5,Math.round(a)));return`${"●".repeat(m)}${"○".repeat(5-m)}`}function vd(a){return a.length===0?o.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):o.jsx("div",{className:"autoruns-coverage-list",children:a.map(m=>{const p=pp(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," (",p,"%)"]})]}),o.jsx("div",{className:"autoruns-coverage-bar",children:o.jsx("div",{style:{width:`${p}%`}})})]},m.domain)})})}function aa(a){return`${ua}${a}`}function Xs(a){return a.startsWith(ua)}function yd(a){return a.startsWith(ua)?a.slice(ua.length):""}function Md(a){const m=a.report_summary?.run_timestamp??a.created_at,p=Math.max(0,a.total_cases-a.completed_cases);return{run_id:aa(a.job_id),eval_target:a.eval_target,run_timestamp:m,mode:"single-pass-strict",llm_provider:null,model:null,use_mock:null,analysis_date:a.report_summary?.analysis_date??a.analysis_date??null,prompt_version:null,schema_version:null,suite_id:a.case_set_file,cases_total:a.total_cases,requests_total:null,report_path:`async_job:${a.job_id}`,score_index:a.report_summary?.score_index??null,blocking_failures:0,quality_failures:0,closed_cases:a.completed_cases,open_cases:p,domain_coverage:[{domain:"runtime",total_cases:a.total_cases,closed_cases:a.completed_cases}]}}function Bo(a,m){const p=Md(a),S=a.cases.map(Y=>({case_id:Y.case_id,domain:null,query_class:null,status:Y.status==="completed"?"closed":Y.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${a.run_id}-${Y.case_id}`,dialog_available:Y.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),M=m!==Pt&&S.some(Y=>Y.case_id===m)?m:S.length>0?Pt:"",b={ok:!0,run:p,coverage:{closed_cases:a.completed_cases,open_cases:Math.max(0,a.total_cases-a.completed_cases),domain_coverage:[{domain:"runtime",total_cases:a.total_cases,closed_cases:a.completed_cases}]},cases:S,annotations_summary:{total:0},report:a.report_summary?{run_id:a.report_summary.run_id,run_timestamp:a.report_summary.run_timestamp,score_index:a.report_summary.score_index,cases_total:a.report_summary.cases_total,analysis_date:a.report_summary.analysis_date??a.analysis_date??null}:{}},le=[];let te=0;if(M===Pt)for(const Y of a.cases)for(let X=0;XX.case_id===M)??null;for(let X=0;X<(Y?.messages.length??0);X+=1){const ee=Y?.messages[X];ee&&le.push({...ee,message_index:X,case_id:M,case_message_index:X,commented:!1,annotation:null})}}const F={ok:!0,run_id:p.run_id,case_id:M,source:"assistant_session",session_id:M===Pt?`${a.run_id}::__all__`:`${a.run_id}-${M}`,messages:le,decomposition:[],assistant_mode:{status:a.status,completed_cases:a.completed_cases,total_cases:a.total_cases},annotations:[]};return{detail:b,dialog:F,caseId:M}}function hp({commented:a}){const m=a?"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 xd({resolved:a}){return o.jsxs("svg",{className:a?"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"}),a?o.jsx("path",{d:"M5.1 8.2 7.2 10.3 11 6.5"}):null]})}function _d(){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 Sd(){return o.jsxs("svg",{className:"autoruns-question-grip-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[o.jsx("circle",{cx:"4",cy:"4",r:"1"}),o.jsx("circle",{cx:"8",cy:"4",r:"1"}),o.jsx("circle",{cx:"12",cy:"4",r:"1"}),o.jsx("circle",{cx:"4",cy:"8",r:"1"}),o.jsx("circle",{cx:"8",cy:"8",r:"1"}),o.jsx("circle",{cx:"12",cy:"8",r:"1"}),o.jsx("circle",{cx:"4",cy:"12",r:"1"}),o.jsx("circle",{cx:"8",cy:"12",r:"1"}),o.jsx("circle",{cx:"12",cy:"12",r:"1"})]})}function gp({expanded:a}){return o.jsx("svg",{className:a?"autoruns-card-chevron-svg expanded":"autoruns-card-chevron-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M3.5 6.2 8 10.4l4.5-4.2"})})}function vp(){return o.jsx("svg",{className:"autoruns-card-launch-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M5 3.8 12 8l-7 4.2Z"})})}function yp(){return o.jsx("svg",{className:"autoruns-card-stop-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("rect",{x:"4.2",y:"4.2",width:"7.6",height:"7.6",rx:"0.8"})})}async function wd(a){if(navigator.clipboard&&window.isSecureContext)try{return await navigator.clipboard.writeText(a),!0}catch{}const m=document.createElement("textarea");m.value=a,m.setAttribute("readonly","true"),m.style.position="fixed",m.style.opacity="0",m.style.pointerEvents="none",document.body.appendChild(m),m.select();let p=!1;try{p=document.execCommand("copy")}catch{p=!1}finally{document.body.removeChild(m)}return p}function la({expanded:a}){return o.jsx("svg",{className:a?"autoruns-group-chevron-svg expanded":"autoruns-group-chevron-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:o.jsx("path",{d:"M3.5 6.2 8 10.4l4.5-4.2"})})}function xp({connection:a,modelOptions:m,modelsBusy:p,connectionStatus:S,connectionBusy:C,onConnectionChange:M,onReloadModels:b,onSaveLocalConfig:le,onTestConnection:te,prompts:F,onPromptsChange:Y,promptPresets:X,selectedPresetId:ee,onSelectPreset:Ae,onLoadPreset:me,onSavePreset:he,onResetDefaults:ye,onDiffPrevious:We,presetName:Ze,onPresetNameChange:qe,diffSummary:Ie,assistantPromptVersion:U,decompositionPromptVersion:oe,showSettingsMode:Pe,showAutoRunsMode:He,showAssistantMode:_t,showProgressMode:dt,showCommentsMode:Gt,onLog:ft}){const[Q,Le]=g.useState({...Gi,fromLocal:md()}),[Ye,ne]=g.useState(""),[Z,I]=g.useState(null),[$,L]=g.useState(null),[y,k]=g.useState(null),[re,ie]=g.useState([]),[de,xe]=g.useState("all"),[je,ke]=g.useState(!1),[Ne,pt]=g.useState(null),[sn,yr]=g.useState([]),[On,yn]=g.useState(""),[we,Wt]=g.useState(""),[Ke,St]=g.useState(""),[Tt,xn]=g.useState(eu),[W,mt]=g.useState(fd),[xr,$n]=g.useState([]),[Gr,nr]=g.useState(Uo),[De,ht]=g.useState(""),[qt,_n]=g.useState(""),[fe,Sn]=g.useState([]),[gt,Wr]=g.useState(!1),[ot,zn]=g.useState(null),[bn,Rt]=g.useState(""),[wn,on]=g.useState(null),[pe,Mt]=g.useState(null),[Be,jn]=g.useState(null),[_r,qr]=g.useState(null),[Kr,Sr]=g.useState(!1),[Fn,wt]=g.useState(!1),[kn,Un]=g.useState(!1),[N,J]=g.useState(!1),[V,Te]=g.useState(!1),[et,Qo]=g.useState(!1),[_s,Ho]=g.useState(!1),[Kt,Zs]=g.useState(!1),[eo,Vo]=g.useState(""),wr=g.useRef(null),[to,no]=g.useState("idle"),[Go,da]=g.useState("чат"),[Wo,ae]=g.useState(""),[lt,Jr]=g.useState(""),[Jt,jr]=g.useState([]),[Yr,kr]=g.useState([]),[Cr,$t]=g.useState(""),[ro,At]=g.useState(null),[so,fa]=g.useState(!1),[qo,Xr]=g.useState(!1),[Ss,Cn]=g.useState(""),[ws,rr]=g.useState(""),[pa,Bn]=g.useState(String(Gi.limit)),[Ko,Qn]=g.useState(String(fd.count)),[sr,Jo]=g.useState(160),[js,ge]=g.useState(""),[ks,Yt]=g.useState(!1),[Hn,oo]=g.useState(!0),[or,lo]=g.useState(!0),[Vn,Zr]=g.useState(!0),[It,Nn]=g.useState(!0),[ue,jt]=g.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:ra,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[_e,at]=g.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),[Xt,Gn]=g.useState({open:!1,title:"",saving:!1,error:""}),[vt,es]=g.useState({open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""}),[ln,lr]=g.useState({open:!1,generationId:"",title:"",saving:!1,error:""}),Cs=g.useRef(!1),Ns=g.useRef(null),Wn=g.useRef(null),Oe=W.mode==="saved_user_sessions",En=g.useMemo(()=>Tt.find(i=>i.id===W.personalityId)??Tt[0]??eu[0],[W.personalityId,Tt]),be=g.useMemo(()=>xr.filter(i=>i.mode===W.mode),[xr,W.mode]),Yo=g.useMemo(()=>be.slice(0,Gr),[Gr,be]),ao=Math.max(0,be.length-Yo.length),$e=g.useMemo(()=>be.find(i=>i.generation_id===De)??be[0]??null,[De,be]),an=g.useMemo(()=>je?re.filter(i=>!i.resolved):re,[re,je]),Me=an.find(i=>i.annotation_id===On)??null,io=y?.messages.find(i=>i.message_index===ue.messageIndex)??null,qn=g.useMemo(()=>{if(!y||ue.messageIndex<0)return null;for(let i=ue.messageIndex-1;i>=0;i-=1){const c=y.messages[i];if(c?.role==="user")return c}return null},[ue.messageIndex,y]),Nr=g.useMemo(()=>{const i=new Map;for(const c of Yr)c.message_id&&i.set(c.message_id,c);return i},[Yr]),ts=_e.messageIndex>=0?Jt[_e.messageIndex]??null:null,uo=g.useMemo(()=>{if(_e.messageIndex<0)return null;for(let i=_e.messageIndex-1;i>=0;i-=1){const c=Jt[i];if(c?.role==="user")return c}return null},[_e.messageIndex,Jt]),zt=g.useMemo(()=>{const i=an.map(f=>({source:"autorun",key:`autorun:${f.annotation_id}`,updated_at:f.updated_at,rating:f.rating,autorun:f,assistant:null})),c=Yr.map(f=>({source:"assistant_live",key:`assistant:${f.annotation_id}`,updated_at:f.updated_at,rating:f.rating,autorun:null,assistant:f}));return[...i,...c].sort((f,w)=>Date.parse(w.updated_at)-Date.parse(f.updated_at))},[Yr,an]),ns=g.useMemo(()=>{if(zt.length===0)return null;const i=zt.reduce((c,f)=>c+f.rating,0)/zt.length;return Number(i.toFixed(2))},[zt]),Es=g.useMemo(()=>{const i=[...Z?.items??[]];return Be&&i.unshift(Md(Be)),we&&!i.some(c=>c.run_id===we)&&$?.run&&i.unshift($.run),i},[Be,Z?.items,$?.run,we]),D=g.useCallback(i=>{ft?.(`[autoruns] ${i}`)},[ft]),Pn=g.useCallback(async i=>{const c=String(i??"").trim();if(!c){kr([]);return}try{const f=await Re.loadAssistantAnnotations({session_id:c,limit:400});kr(f.items??[])}catch(f){const w=f instanceof Error?f.message:String(f);D(`Assistant live annotations load error: ${w}`)}},[D]),Kn=g.useCallback(i=>{at(c=>c.saving&&!i?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),Jn=g.useCallback(i=>{Gn(c=>c.saving&&!i?.force?c:{open:!1,title:"",saving:!1,error:""})},[]),Ps=g.useCallback(i=>{es(c=>c.saving&&!i?.force?c:{open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""})},[]),Er=g.useCallback(i=>{lr(c=>c.saving&&!i?.force?c:{open:!1,generationId:"",title:"",saving:!1,error:""})},[]);g.useEffect(()=>()=>{wr.current!==null&&window.clearTimeout(wr.current)},[]);const Pr=g.useCallback(async(i,c,f)=>{i.stopPropagation(),i.preventDefault();const w=String(c??"").trim();if(w)try{await wd(w),D(`${f} copied: ${w}`)}catch(A){const ce=A instanceof Error?A.message:String(A);ae(`Копирование ${f}: ${ce}`),D(`copy ${f} error: ${ce}`)}},[D]),Tr=g.useCallback(async i=>{if(!y||y.messages.length===0||!we)return;const c=Bf({runId:we,caseId:Ke||y.case_id||"n/a",sessionId:y.session_id,source:y.source,messages:y.messages,decomposition:y.decomposition,assistantMode:y.assistant_mode,annotations:y.annotations,runSummary:$?.run??null,coverage:$?.coverage??null,report:$?.report??null},i),f=await wd(c);da(i==="technical"?"тех":"чат"),no(f?"success":"error"),wr.current!==null&&window.clearTimeout(wr.current),wr.current=window.setTimeout(()=>{no("idle")},2200),D(f?`Dialog ${i==="technical"?"technical":"chat"} copied: run=${we} case=${Ke||y.case_id}`:`Dialog copy failed: run=${we} case=${Ke||y.case_id}`)},[y,D,$,Ke,we]);function Ts(){let i=0;Cn(Wi[0]);const c=window.setInterval(()=>{i=Math.min(i+1,Wi.length-1),Cn(Wi[i])},650);return()=>window.clearInterval(c)}const Xo=g.useCallback(()=>{Jr(""),jr([]),kr([]),$t(""),At(null),Cn(""),rr(""),Kn({force:!0}),D("Live-чат ассистента в истории автопрогонов сброшен.")},[Kn,D]),ma=g.useCallback(async()=>{const i=up(Cr,ro);if(!i)return;Xr(!0),rr(""),$t(""),jr(f=>[...f,{message_id:`autoruns-live-${Date.now()}`,session_id:lt||"pending",role:"user",text:i,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=Ts();try{const f=await Re.sendAssistantMessage({connection:a,prompts:F,userMessage:i,sessionId:lt||void 0,promptVersion:U,useMock:so});Jr(f.session_id),jr(f.conversation),await Pn(f.session_id),Cn("Ответ готов"),D(`Live-ответ ассистента получен: trace=${f.debug.trace_id}`)}catch(f){const w=f instanceof Error?f.message:String(f);rr(w),Cn("Ошибка ассистента"),D(`Live-чат ассистента: ошибка отправки сообщения: ${w}`)}finally{c(),Xr(!1)}},[Cr,ro,lt,so,U,a,Pn,D,F]),ha=g.useCallback(()=>{if(!lt.trim()||Jt.length===0){rr("Сначала получите хотя бы один ответ в живой сессии ассистента.");return}rr(""),Gn({open:!0,title:fp(Jt),saving:!1,error:""})},[Jt,lt]),ga=g.useCallback(async()=>{const i=lt.trim(),c=Xt.title.trim();if(!i){Gn(f=>({...f,error:"Активная сессия ассистента не найдена."}));return}if(!c){Gn(f=>({...f,error:"Укажите название сессии."}));return}Gn(f=>({...f,saving:!0,error:""}));try{const f=[F.systemPrompt,F.developerPrompt,F.domainPrompt,F.schemaNotes,F.fewShotExamples].join("||"),w=await Re.saveAutoRunAssistantSession({session_id:i,title:c,generated_by:W.generatedBy.trim()||void 0,context:{llm_provider:a.llmProvider,model:a.model,assistant_prompt_version:U,decomposition_prompt_version:oe,prompt_fingerprint:f}});$n(A=>[w.generation,...A.filter(ce=>ce.generation_id!==w.generation.generation_id)]),mt(A=>({...A,mode:"saved_user_sessions"})),ht(w.generation.generation_id),Jn({force:!0}),D(`Живая сессия сохранена в автопрогоны: ${w.generation.generation_id}`)}catch(f){const w=f instanceof Error?f.message:String(f);Gn(A=>({...A,saving:!1,error:w})),D(`Assistant live save error: ${w}`)}},[Xt.title,lt,U,W.generatedBy,Jn,a.llmProvider,a.model,oe,D,F.developerPrompt,F.domainPrompt,F.fewShotExamples,F.schemaNotes,F.systemPrompt]),Rs=g.useCallback(i=>{const c=i.trim();if(!c){Bn(String(Q.limit));return}if(!/^\d+$/.test(c)){Bn(String(Q.limit));return}const f=Number.parseInt(c,10);if(!Number.isFinite(f)){Bn(String(Q.limit));return}const w=Math.max(1,Math.min(500,f));w!==Q.limit&&Le(A=>({...A,limit:w})),Bn(String(w))},[Q.limit]),Zo=g.useCallback(i=>{const c=i.trim();if(!c){Qn(String(W.count));return}if(!/^\d+$/.test(c)){Qn(String(W.count));return}const f=Number.parseInt(c,10);if(!Number.isFinite(f)){Qn(String(W.count));return}const w=Math.max(1,Math.min(200,f));w!==W.count&&mt(A=>({...A,count:w})),Qn(String(w))},[W.count]),el=g.useCallback(i=>{Jo(pd(i))},[]),tl=g.useCallback(i=>{const c=i.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&el(c)},[el]),rs=g.useCallback(async()=>{Zs(!0);try{const i=await Re.loadAutoRunAnnotations({limit:800,manual_case_decision:de});ie(i.items),pt(i.manual_case_decision_schema??null),yr(i.available_manual_case_decisions??[]),yn(c=>i.items.length===0?"":i.items.some(f=>f.annotation_id===c)?c:i.items[0].annotation_id)}catch(i){D(`Annotations load error: ${i instanceof Error?i.message:String(i)}`)}finally{Zs(!1)}},[de,D]),un=g.useCallback(async()=>{J(!0);try{const i=await Re.loadAutoRunAutogenHistory({limit:ip});$n(i.items),nr(Uo)}catch(i){D(`Autogen history load error: ${i instanceof Error?i.message:String(i)}`)}finally{J(!1)}},[D]),co=g.useCallback(async()=>{try{const c=(await Re.loadAutoRunAutogenPersonalityCatalog()).items.map(f=>({id:String(f.id??"").trim(),label:String(f.label??"").trim(),domain:typeof f.domain=="string"?f.domain.trim():"",defaultPrompt:String(f.default_prompt??"").trim()})).filter(f=>f.id.length>0&&f.label.length>0);if(c.length===0)return;xn(c.map(f=>({id:f.id,label:f.label,domain:f.domain||"",defaultPrompt:f.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(i){D(`Autogen personality catalog load error: ${i instanceof Error?i.message:String(i)}`)}},[D]),Tn=g.useCallback(async()=>{Un(!0);try{const i=await Re.loadAutoRunPostAnalysis({run_id:we&&!Xs(we)?we:void 0,limit_per_queue:30,annotation_limit:1500,from:sa(Q.fromLocal),to:sa(Q.toLocal),target:Q.target,mode:Q.mode,use_mock:Q.useMock,prompt_contains:Q.promptContains.trim()||void 0});qr(i)}catch(i){D(`Post-analysis load error: ${i instanceof Error?i.message:String(i)}`),qr(null)}finally{Un(!1)}},[Q.fromLocal,Q.mode,Q.promptContains,Q.target,Q.toLocal,Q.useMock,D,we]),va=g.useCallback(async()=>{Sr(!0),ae("");try{if(W.mode==="saved_user_sessions")throw new Error("Пользовательские сессии сохраняются из живого чата, а не генерируются автоматически.");const i=W.personalityPrompts[W.personalityId]??"",c=[F.systemPrompt,F.developerPrompt,F.domainPrompt,F.schemaNotes,F.fewShotExamples].join(` -`).slice(0,900),f=await Re.generateAutoRunQuestions({mode:W.mode,count:W.count,domain:En.domain||void 0,persist_to_eval_cases:W.persistToEvalCases,generated_by:W.generatedBy.trim()||void 0,llm:{llm_provider:a.llmProvider,api_key:a.apiKey,model:a.model,base_url:a.baseUrl,temperature:a.temperature,max_output_tokens:a.maxOutputTokens},context:{llm_provider:a.llmProvider,model:a.model,assistant_prompt_version:U,decomposition_prompt_version:oe,prompt_fingerprint:c,autogen_personality_id:En.id,autogen_personality_prompt:i.trim()||void 0}});D(`Generated ${f.generation.count} questions (${f.generation.mode}) id=${f.generation.generation_id}`+(f.generation.saved_case_set_file?` saved=${f.generation.saved_case_set_file}`:"")),ht(f.generation.generation_id),Sn([...f.generation.questions??[]]),await un()}catch(i){const c=i instanceof Error?i.message:String(i);ae(`Автогенерация: ${c}`),D(`Autogen generate error: ${c}`)}finally{Sr(!1)}},[U,W.count,W.generatedBy,W.mode,W.personalityId,W.personalityPrompts,W.persistToEvalCases,a.apiKey,a.baseUrl,a.llmProvider,a.maxOutputTokens,a.model,a.temperature,oe,un,D,F.developerPrompt,F.domainPrompt,F.fewShotExamples,F.schemaNotes,F.systemPrompt,En.domain,En.id]),ss=g.useCallback(async(i,c)=>{if(Xs(i)){const f=yd(i);if(Be&&Be.job_id===f){const w=Bo(Be,c);Wt(i),St(w.caseId),k(w.dialog);return}k(null);return}Ho(!0);try{const f=await Re.loadAutoRunCaseDialog(i,c);k(f)}catch(f){const w=f instanceof Error?f.message:String(f);ae(`Диалог кейса: ${w}`),k(null),D(`Dialog load error for ${i}/${c}: ${w}`)}finally{Ho(!1)}},[Be,D]),Yn=g.useCallback(async(i,c)=>{if(Xs(i)){const f=yd(i);if(Be&&Be.job_id===f){const w=Bo(Be,c??Pt);Wt(i),St(w.caseId),L(w.detail),k(w.dialog);return}Wt(i),St(""),L(null),k(null);return}Qo(!0);try{const f=await Re.loadAutoRunDetail(i);L(f);const w=(c&&(c===Pt||f.cases.some(A=>A.case_id===c))?c:"")||(f.cases.length>0?Pt:"")||"";Wt(i),St(w),w?await ss(i,w):k(null)}catch(f){const w=f instanceof Error?f.message:String(f);ae(`Детализация прогона: ${w}`),L(null),k(null),D(`Run detail load error for ${i}: ${w}`)}finally{Qo(!1)}},[Be,ss,D]),cn=g.useCallback(async i=>{Te(!0),ae("");try{const c=await Re.loadAutoRunsHistory({from:sa(Q.fromLocal),to:sa(Q.toLocal),target:Q.target,mode:Q.mode,use_mock:Q.useMock,prompt_contains:Q.promptContains.trim()||void 0,limit:Q.limit});if(I(c),c.items.length===0){Wt(""),St(""),L(null),k(null);return}const f=i?.keepSelection??!0,w=i?.preferredRunId??"",A=i?.preferredCaseId??"",ce=f&&w&&c.items.some(nt=>nt.run_id===w)?w:c.items[0].run_id;await Yn(ce,f?A:void 0),Tn()}catch(c){const f=c instanceof Error?c.message:String(c);ae(`История прогонов: ${f}`),D(`History load error: ${f}`)}finally{Te(!1)}},[Q.fromLocal,Q.limit,Q.mode,Q.promptContains,Q.target,Q.toLocal,Q.useMock,Tn,Yn,D]),Lt=g.useCallback(()=>{Ns.current!==null&&(window.clearTimeout(Ns.current),Ns.current=null)},[]),fo=g.useCallback(async i=>{try{const c=await Re.loadEvalRunAsyncStatus(i);jn(c.job);const f=aa(i);if(we===f){const w=Bo(c.job,Ke||Pt);L(w.detail),k(w.dialog),St(w.caseId)}if(c.job.status==="completed"){Lt(),wt(!1),Yt(!1),ge("");const w=c.job.report_summary?.run_id??c.job.run_id;await cn({keepSelection:!0,preferredRunId:w||we,preferredCaseId:Pt}),await un(),jn(null);return}if(c.job.status==="failed"){Lt(),wt(!1),Yt(!1),ge(""),ae(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),D(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}if(c.job.status==="canceled"){Lt(),wt(!1),Yt(!1),ge(""),jn(null),await cn({keepSelection:!1}),await un(),D(`Autogen async run canceled: job=${c.job.job_id}`);return}Lt(),Ns.current=window.setTimeout(()=>{fo(i)},500)}catch(c){Lt(),wt(!1),Yt(!1),ge("");const f=c instanceof Error?c.message:String(c);ae(`Запуск прогонов: ${f}`),D(`Autogen async status error: ${f}`)}},[un,cn,D,Ke,we,Lt]),nl=g.useCallback(async(i,c)=>{Lt(),wt(!0),ae("");try{const f=i??$e;if(!f)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const A=(c??($e?.generation_id===f.generation_id?fe:f.questions)).map(As=>As.trim()).filter(As=>As.length>0);if(A.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const ce=Q.useMock==="true",nt=qi(Ye),Zt=f.mode==="saved_user_sessions",Mr=(await Re.startEvalRunAsync({connection:a,prompts:F,promptVersion:U,mode:"single-pass-strict",caseSetFile:Zt?void 0:f.saved_case_set_file??void 0,useMock:ce,evalTarget:"assistant_stage1",questions:Zt?void 0:A,scenarioQuestions:Zt?A:void 0,scenarioTitle:Zt?f.title??void 0:void 0,analysisDate:Zt?void 0:nt||void 0})).job;ge(f.generation_id),Yt(!1),jn(Mr);const en=aa(Mr.job_id),ir=Bo(Mr,Pt);Wt(en),St(ir.caseId),L(ir.detail),k(ir.dialog),D(`Запущен async-прогон job=${Mr.job_id}, run_id=${Mr.run_id}, вопросов=${A.length}`+(f.saved_case_set_file?`, base_case_set=${f.saved_case_set_file}`:"")+(Zt?", replay_mode=saved_user_session_scenario":nt?`, analysis_date=${nt}`:", analysis_date=current_state")),fo(Mr.job_id)}catch(f){const w=f instanceof Error?f.message:String(f);ae(`Запуск прогонов: ${w}`),D(`Autogen run error: ${w}`),wt(!1),Yt(!1),ge("")}},[Ye,U,a,fe,Q.useMock,D,fo,F,$e,Lt]),po=g.useCallback(async()=>{const i=Be?.job_id??"";if(!i){wt(!1),Yt(!1),ge(""),jn(null),Lt();return}Yt(!0),ae("");try{const c=await Re.cancelEvalRunAsync(i);Lt(),jn(null),wt(!1),Yt(!1),ge(""),await cn({keepSelection:!1}),await un(),D(`Autogen async run stopped: job=${c.job.job_id}`)}catch(c){const f=c instanceof Error?c.message:String(c);Yt(!1),ae(`Остановка прогона: ${f}`),D(`Autogen stop error: ${f}`)}},[Be,un,cn,D,Lt]),ya=g.useCallback(i=>{if(i.role!=="assistant")return;const c=i.case_id??Ke,f=i.case_message_index??i.message_index;jt({open:!0,caseId:c,caseMessageIndex:f,messageIndex:i.message_index,rating:i.annotation?.rating??3,comment:i.annotation?.comment??"",manualCaseDecision:i.annotation?.manual_case_decision??ra,annotationAuthor:i.annotation?.annotation_author??W.generatedBy,saving:!1,error:""})},[W.generatedBy,Ke]),Ms=g.useCallback(i=>{jt(c=>c.saving&&!i?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:ra,annotationAuthor:W.generatedBy,saving:!1,error:""})},[W.generatedBy]),xa=g.useCallback(async()=>{const i=we,c=ue.caseId,f=ue.caseMessageIndex;if(!(!i||!c||f<0)){if(Xs(i)){jt(w=>({...w,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ue.comment.trim()){jt(w=>({...w,error:"Добавьте комментарий."}));return}jt(w=>({...w,saving:!0,error:""}));try{await Re.saveAutoRunAnnotation({run_id:i,case_id:c,message_index:f,rating:ue.rating,comment:ue.comment.trim(),manual_case_decision:ue.manualCaseDecision,annotation_author:ue.annotationAuthor.trim()||void 0}),Ms({force:!0}),Promise.all([Yn(i,Ke),rs(),Tn()]).catch(w=>{const A=w instanceof Error?w.message:String(w);ae(`Обновление после комментария: ${A}`),D(`Comment refresh error: ${A}`)})}catch(w){jt(A=>({...A,saving:!1,error:w instanceof Error?w.message:String(w)}))}}},[Ms,ue.annotationAuthor,ue.caseId,ue.caseMessageIndex,ue.comment,ue.manualCaseDecision,ue.rating,rs,Tn,Yn,D,Ke,we]),_a=g.useCallback(i=>i.role==="assistant",[]),Sa=g.useCallback(i=>i.role==="assistant"&&Nr.has(i.message_id),[Nr]),wa=g.useCallback((i,c)=>{if(i.role!=="assistant")return;const f=lt.trim(),w=String(i.session_id??"").trim();if(!(f||w)){rr("Сначала получите ответ ассистента в активной сессии.");return}!f&&w&&Jr(w);const ce=Nr.get(i.message_id)??null;rr(""),at({open:!0,messageIndex:c,rating:ce?.rating??3,comment:ce?.comment??"",annotationAuthor:ce?.annotation_author??"manual_reviewer",saving:!1,error:""})},[Nr,lt]),ja=g.useCallback(async()=>{if(_e.messageIndex<0)return;if(!_e.comment.trim()){at(f=>({...f,error:"Добавьте комментарий."}));return}const i=Jt[_e.messageIndex]??null,c=lt.trim()||(i?.role==="assistant"?String(i.session_id??"").trim():"");if(!c){at(f=>({...f,error:"Сессия ассистента не найдена."}));return}at(f=>({...f,saving:!0,error:""}));try{const f=await Re.saveAssistantAnnotation({session_id:c,message_index:_e.messageIndex,rating:_e.rating,comment:_e.comment.trim(),annotation_author:_e.annotationAuthor.trim()||void 0});kr(w=>{const A=[...w],ce=A.findIndex(nt=>nt.annotation_id===f.annotation.annotation_id);return ce>=0?A[ce]=f.annotation:A.unshift(f.annotation),A.sort((nt,Zt)=>Date.parse(Zt.updated_at)-Date.parse(nt.updated_at))}),Kn({force:!0})}catch(f){const w=f instanceof Error?f.message:String(f);at(A=>({...A,saving:!1,error:w}))}},[_e.annotationAuthor,_e.comment,_e.messageIndex,_e.rating,Jt,lt,Kn]);g.useCallback(i=>{if(!$e||$e.mode!=="saved_user_sessions")return;const c=fe[i]??"";es({open:!0,generationId:$e.generation_id,questionIndex:i,questionText:c,saving:!1,error:""})},[fe,$e]);const mo=g.useCallback(async()=>{const i=vt.generationId,c=vt.questionIndex;if(!i||c<0)return;const f=fe.filter((w,A)=>A!==c);if(f.length===0){es(w=>({...w,error:"Нельзя удалить последний вопрос из сохраненной сессии."}));return}es(w=>({...w,saving:!0,error:""}));try{const w=await Re.updateAutoRunAutogenQuestions({generation_id:i,questions:f});$n(A=>A.map(ce=>ce.generation_id===i?w.generation:ce)),Sn(w.generation.questions),Ps({force:!0}),D(`Обновлена сохраненная сессия: ${i}`)}catch(w){const A=w instanceof Error?w.message:String(w);es(ce=>({...ce,saving:!1,error:A})),D(`Saved session question delete error: ${A}`)}},[Ps,fe,D,vt.generationId,vt.questionIndex]),bt=g.useCallback(async(i,c)=>{const f=$e?.generation_id??"",w=c?.revertQuestions??fe;if(Sn(i),!f)return!0;Wr(!0);try{const A=await Re.updateAutoRunAutogenQuestions({generation_id:f,questions:i});return $n(ce=>ce.map(nt=>nt.generation_id===f?A.generation:nt)),Sn([...A.generation.questions??[]]),c?.successLog&&D(c.successLog),!0}catch(A){const ce=A instanceof Error?A.message:String(A);return Sn(w),ae(`Вопросы к запуску: ${ce}`),D(`Autogen questions update error: ${ce}`),!1}finally{Wr(!1)}},[fe,D,$e]),rl=g.useCallback(i=>{zn(i),Rt(fe[i]??"")},[fe]),Rn=g.useCallback(()=>{zn(null),Rt("")},[]),os=g.useCallback(async i=>{if(i===null)return;const c=fe[i]??"",f=bn.trim();if(!f||f===c){Rn();return}const w=fe.map((ce,nt)=>nt===i?f:ce);await bt(w,{successLog:`Список вопросов обновлен: ${$e?.generation_id??"local"}`,revertQuestions:fe})&&Rn()},[fe,bn,$e,Rn,bt]),ho=g.useCallback(()=>{os(ot)},[os,ot]),go=g.useCallback(i=>{if(i.key==="Enter"){i.preventDefault(),os(ot);return}i.key==="Escape"&&(i.preventDefault(),Rn())},[os,ot,Rn]),vo=g.useCallback(async()=>{const i=[...fe,"Новый вопрос"],c=i.length-1;await bt(i,{successLog:`В список добавлен вопрос: ${$e?.generation_id??"local"}`,revertQuestions:fe})&&(zn(c),Rt(i[c]))},[fe,$e,bt]),ar=g.useCallback(async i=>{if(fe.length<=1){ae("В списке должен остаться хотя бы один вопрос.");return}const c=fe.filter((w,A)=>A!==i);await bt(c,{successLog:`Из списка удален вопрос: ${$e?.generation_id??"local"}`,revertQuestions:fe})&&(zn(w=>w===null?w:w===i?null:w>i?w-1:w),Rt(""))},[fe,$e,bt]),sl=g.useCallback((i,c)=>{if(gt){i.preventDefault();return}on(c),Mt(c),i.dataTransfer.effectAllowed="move",i.dataTransfer.setData("text/plain",String(c))},[gt]),ol=g.useCallback((i,c)=>{i.preventDefault(),pe!==c&&Mt(c),i.dataTransfer.dropEffect="move"},[pe]),ll=g.useCallback(async(i,c)=>{i.preventDefault();const f=wn;if(Mt(null),on(null),f===null||f===c)return;const w=[...fe],[A]=w.splice(f,1);w.splice(c,0,A),await bt(w,{successLog:`Порядок вопросов обновлен: ${$e?.generation_id??"local"}`,revertQuestions:fe})},[wn,fe,$e,bt]),yo=g.useCallback(()=>{on(null),Mt(null)},[]),al=g.useCallback(i=>{ht(i),_n(c=>c===i?"":i)},[]),Rr=g.useCallback(i=>{lr({open:!0,generationId:i.generation_id,title:i.title??`${Ki(i.mode)} ${vn(i.created_at)}`,saving:!1,error:""})},[]),ls=g.useCallback(async()=>{const i=ln.generationId.trim();if(i){lr(c=>({...c,saving:!0,error:""}));try{const c=await Re.deleteAutoRunAutogenHistoryRecord(i);$n(f=>f.filter(w=>w.generation_id!==c.generation_id)),Er({force:!0}),D(`Удален набор автопрогона: ${c.generation_id}`+(c.deleted_files.length>0?`, files=${c.deleted_files.length}`:""))}catch(c){const f=c instanceof Error?c.message:String(c);lr(w=>({...w,saving:!1,error:f})),D(`Autogen record delete error: ${f}`)}}},[ln.generationId,Er,D]),il=g.useCallback(i=>{ie(c=>c.map(f=>f.annotation_id===i.annotation_id?{...f,...i}:f)),k(c=>c&&{...c,annotations:c.annotations.map(f=>f.annotation_id===i.annotation_id?i:f),messages:c.messages.map(f=>!f.annotation||f.annotation.annotation_id!==i.annotation_id?f:{...f,commented:!0,annotation:i})})},[]),as=g.useCallback(async(i,c)=>{if(i.annotation_id){if(Xs(i.run_id)){ae("Статус выполнения можно менять только для завершённых прогонов.");return}Vo(i.annotation_id);try{const f=await Re.updateAutoRunAnnotation({annotation_id:i.annotation_id,resolved:c,resolved_by:W.generatedBy||void 0});il(f.annotation),Tn()}catch(f){const w=f instanceof Error?f.message:String(f);ae(`Смена статуса кейса: ${w}`),D(`Annotation resolve toggle error: ${w}`)}finally{Vo("")}}},[il,W.generatedBy,Tn,D]),ul=g.useCallback(async i=>{yn(i.annotation_id),await Yn(i.run_id,i.case_id),Z?.items.some(c=>c.run_id===i.run_id)||ae("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[Z?.items,Yn]);g.useEffect(()=>{Cs.current||(Cs.current=!0,cn({keepSelection:!1}),un(),co(),Tn())},[un,co,cn,Tn]),g.useEffect(()=>{Cs.current&&rs()},[de,rs]),g.useEffect(()=>{yn(i=>an.length===0?"":an.some(c=>c.annotation_id===i)?i:an[0].annotation_id)},[an]),g.useEffect(()=>{ht(i=>be.length===0?"":i&&be.some(c=>c.generation_id===i)?i:be[0].generation_id)},[be]),g.useEffect(()=>{nr(Uo)},[W.mode]),g.useEffect(()=>{if(!De)return;const i=be.findIndex(c=>c.generation_id===De);i<0||nr(c=>Math.max(c,Math.min(be.length,i+1)))},[De,be]),g.useEffect(()=>{if(!$e){Sn([]),Rn(),on(null),Mt(null);return}Sn([...$e.questions]),Rn(),on(null),Mt(null)},[$e,Rn]),g.useEffect(()=>{if(ot===null)return;const i=window.setTimeout(()=>{Wn.current?.focus(),Wn.current?.select()},0);return()=>window.clearTimeout(i)},[ot]),g.useEffect(()=>{if(!Oe){_n("");return}qt&&!be.some(i=>i.generation_id===qt)&&_n("")},[qt,Oe,be]),g.useEffect(()=>{Bn(String(Q.limit))},[Q.limit]),g.useEffect(()=>{Qn(String(W.count))},[W.count]),g.useEffect(()=>{if(!lt.trim()){kr([]);return}Pn(lt)},[lt,Pn]),g.useEffect(()=>{if(!Be)return;const i=aa(Be.job_id);if(we!==i)return;const c=Bo(Be,Ke||Pt);L(c.detail),k(c.dialog),St(c.caseId)},[Be,Ke,we]),g.useEffect(()=>()=>{Lt()},[Lt]),g.useEffect(()=>{Tt.length!==0&&mt(i=>{let c=!1;const f={...i.personalityPrompts};for(const A of Tt)(typeof f[A.id]!="string"||f[A.id].trim().length===0)&&(f[A.id]=A.defaultPrompt,c=!0);let w=i.personalityId;return Tt.some(A=>A.id===i.personalityId)||(w=Tt[0].id,c=!0),c?{...i,personalityId:w,personalityPrompts:f}:i})},[Tt]),g.useEffect(()=>{const i=localStorage.getItem(cd);if(i)try{const c=JSON.parse(i);if(c.filters){const f=c.filters;Le(w=>({...w,...f,limit:typeof f.limit=="number"?Math.max(1,Math.min(500,f.limit)):w.limit}))}typeof c.analysisDate=="string"&&ne(qi(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&Jo(pd(c.autogenPersonalityPromptHeight)),c.groupsExpanded&&(typeof c.groupsExpanded.filters=="boolean"&&oo(c.groupsExpanded.filters),typeof c.groupsExpanded.generationContext=="boolean"&&lo(c.groupsExpanded.generationContext),typeof c.groupsExpanded.autogen=="boolean"&&Zr(c.groupsExpanded.autogen),typeof c.groupsExpanded.savedSessions=="boolean"&&Nn(c.groupsExpanded.savedSessions)),c.autoGenSettings&&mt(f=>{const w={...f.personalityPrompts},A=c.autoGenSettings?.personalityPrompts??{};for(const[nt,Zt]of Object.entries(A))typeof Zt=="string"&&nt.trim().length>0&&(w[nt.trim()]=Zt);const ce=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():f.personalityId;return{...f,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"||c.autoGenSettings?.mode==="saved_user_sessions"?c.autoGenSettings.mode:f.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):f.count,personalityId:ce,personalityPrompts:w,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:f.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:f.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&xe(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&ke(c.hideResolvedAnnotations)}catch{}},[]);const xo=g.useCallback(()=>{const i={filters:Q,analysisDate:Ye,autogenPersonalityPromptHeight:sr,groupsExpanded:{filters:Hn,generationContext:or,autogen:Vn,savedSessions:It},autoGenSettings:{mode:W.mode,count:W.count,personalityId:W.personalityId,personalityPrompts:W.personalityPrompts,persistToEvalCases:W.persistToEvalCases,generatedBy:W.generatedBy},annotationDecisionFilter:de,hideResolvedAnnotations:je};localStorage.setItem(cd,JSON.stringify(i))},[Ye,de,W,Vn,sr,Q,Hn,or,je,It]);return g.useEffect(()=>{const i=()=>{xo(),D("Сохранены настройки панели автопрогонов.")};return window.addEventListener(dd,i),()=>{window.removeEventListener(dd,i)}},[D,xo]),o.jsxs(ca,{className:"autoruns-frame",title:"",hideHeader:!0,children:[o.jsxs("div",{className:"autoruns-columns",children:[Pe?o.jsxs("section",{className:"autoruns-col autoruns-settings-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Настройки"})}),o.jsxs("div",{className:"autoruns-settings-stack",children:[o.jsx(lp,{embedded:!0,value:a,modelOptions:m,modelsBusy:p,onChange:M,onReloadModels:b,onSaveLocalConfig:le,onTestConnection:te,lastStatus:S,busy:C}),o.jsx(ap,{embedded:!0,value:F,onChange:Y,presets:X,selectedPresetId:ee,onSelectPreset:Ae,onLoadPreset:me,onSavePreset:he,onResetDefaults:ye,onDiffPrevious:We,presetName:Ze,onPresetNameChange:qe,diffSummary:Ie})]})]}):null,He?o.jsxs("section",{className:"autoruns-col",children:[o.jsx("div",{className:"autoruns-col-header",children:o.jsx("h3",{children:"Автопрогоны"})}),o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Настройки выборки"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>oo(i=>!i),"aria-label":Hn?"Скрыть группу настройки выборки":"Показать группу настройки выборки",title:Hn?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:Hn})})]}),Hn?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата с",o.jsx("input",{type:"datetime-local",value:Q.fromLocal,onChange:i=>Le(c=>({...c,fromLocal:i.target.value}))})]}),o.jsxs("label",{children:["Дата по",o.jsx("input",{type:"datetime-local",value:Q.toLocal,onChange:i=>Le(c=>({...c,toLocal:i.target.value}))})]}),o.jsxs("label",{children:["Целевой контур",o.jsxs("select",{value:Q.target,onChange:i=>Le(c=>({...c,target:i.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(Z?.available.targets??[]).map(i=>o.jsx("option",{value:i,children:i},i))]})]}),o.jsxs("label",{children:["Режим",o.jsxs("select",{value:Q.mode,onChange:i=>Le(c=>({...c,mode:i.target.value})),children:[o.jsx("option",{value:"all",children:"все"}),(Z?.available.modes??[]).map(i=>o.jsx("option",{value:i,children:i},i))]})]}),o.jsxs("label",{children:["Использовать mock",o.jsxs("select",{value:Q.useMock,onChange:i=>Le(c=>({...c,useMock:i.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:pa,onChange:i=>{const c=i.target.value;(c===""||/^\d+$/.test(c))&&Bn(c)},onBlur:i=>Rs(i.target.value),onKeyDown:i=>{i.key==="Enter"&&Rs(i.target.value)}})]}),o.jsxs("label",{className:"full-width",children:["Версия промпта содержит",o.jsx("input",{value:Q.promptContains,onChange:i=>Le(c=>({...c,promptContains:i.target.value})),placeholder:"normalizer_v2_0_2 / address_query_runtime_v1",list:"autoruns-prompt-versions"})]})]}),o.jsx("datalist",{id:"autoruns-prompt-versions",children:(Z?.available.prompt_versions??[]).map(i=>o.jsx("option",{value:i},i))}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:V,onClick:()=>{cn({keepSelection:!1})},children:V?"Обновляю...":"Применить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>{Le({...Gi,fromLocal:md()}),ae("")},children:"Сбросить фильтры"})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Контур генерации"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>lo(i=>!i),"aria-label":or?"Скрыть группу контура генерации":"Показать группу контура генерации",title:or?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:or})})]}),or?o.jsxs("div",{className:"autoruns-meta-list",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Провайдер:"}),o.jsx("strong",{children:a.llmProvider})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Модель:"}),o.jsx("strong",{children:a.model||"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт ассистента:"}),o.jsx("strong",{children:U})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Промпт декомпозиции:"}),o.jsx("strong",{children:oe})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:"Автопрогоны"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>Zr(i=>!i),"aria-label":Vn?"Скрыть группу автопрогонов":"Показать группу автопрогонов",title:Vn?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:Vn})})]}),Vn?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Режимы",o.jsxs("select",{value:W.mode,onChange:i=>mt(c=>({...c,mode:i.target.value})),children:[o.jsx("option",{value:"codex_creative",children:"codex_creative"}),o.jsx("option",{value:"qwen_seed",children:"qwen_seed"}),o.jsx("option",{value:"saved_user_sessions",children:"Пользовательские сессии"})]})]}),Oe?null:o.jsxs(o.Fragment,{children:[o.jsxs("label",{children:["Кол-во",o.jsx("input",{type:"number",min:1,max:200,value:Ko,onChange:i=>{const c=i.target.value;(c===""||/^\d+$/.test(c))&&Qn(c)},onBlur:i=>Zo(i.target.value),onKeyDown:i=>{i.key==="Enter"&&Zo(i.target.value)}})]}),o.jsxs("label",{children:["Личность автогенерации",o.jsx("select",{value:W.personalityId,onChange:i=>mt(c=>({...c,personalityId:i.target.value})),children:Tt.map(i=>o.jsx("option",{value:i.id,children:i.label},i.id))})]}),o.jsxs("label",{children:["Кто генерирует",o.jsx("input",{value:W.generatedBy,onChange:i=>mt(c=>({...c,generatedBy:i.target.value})),placeholder:"manual_reviewer"})]}),o.jsxs("label",{className:"full-width",children:["Промпт личности",o.jsx("textarea",{className:"autoruns-personality-prompt",value:W.personalityPrompts[W.personalityId]??"",onChange:i=>mt(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:i.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${sr}px`},onMouseUp:tl,onTouchEnd:tl})]}),o.jsxs("label",{className:"checkbox-row",children:[o.jsx("input",{type:"checkbox",checked:W.persistToEvalCases,onChange:i=>mt(c=>({...c,persistToEvalCases:i.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]})]}),Oe?null:o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Дата анализа (срез)",o.jsx("input",{type:"date",value:Ye,onChange:i=>ne(qi(i.target.value))})]}),o.jsx("div",{className:"button-row",children:o.jsx("button",{type:"button",className:"tab",disabled:!Ye,onClick:()=>ne(""),children:"Сбросить дату среза"})})]}),o.jsxs("div",{className:"button-row",children:[Oe?null:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:Kr,onClick:()=>{va()},children:Kr?"Генерирую...":"Сгенерировать пачку"}),o.jsx("button",{type:"button",className:"tab",disabled:N,onClick:()=>{un()},children:N?"Обновляю...":"Обновить историю"})]}),o.jsx("button",{type:"button",className:"autoruns-run-launch-btn",style:Oe?{display:"none"}:void 0,disabled:ks||!Fn&&(fe.length===0||!$e),onClick:()=>{Fn?po():nl()},children:Fn?ks?"Останавливаю...":"Остановить прогон":"Запустить прогон"})]}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{className:"full-width",children:[Oe?"Сохраненная сессия":"Кейс-сет для запуска",o.jsxs("select",{value:De,onChange:i=>ht(i.target.value),disabled:be.length===0,children:[be.length===0?o.jsx("option",{value:"",children:Oe?"нет сохраненных сессий":"нет генераций"}):null,be.map(i=>o.jsxs("option",{value:i.generation_id,children:[vn(i.created_at)," | ",Ji(i)??Ki(i.mode)," | ",i.count]},i.generation_id))]})]})}),o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-generated-questions",style:Oe?{display:"none"}:void 0,children:[o.jsx("div",{className:"autoruns-generated-questions-head",children:o.jsxs("strong",{children:["Вопросы к запуску: ",fe.length]})}),fe.length===0?o.jsx("p",{className:"muted",children:Oe?"Список вопросов пуст. Сначала сохраните живую пользовательскую сессию.":"Список вопросов пуст. Сгенерируйте пачку или добавьте вопрос вручную."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:fe.map((i,c)=>o.jsxs("div",{className:["autoruns-generated-question-item",pe===c?"drag-over":"",wn===c?"dragging":"",ot===c?"editing":""].filter(Boolean).join(" "),onDragOver:f=>ol(f,c),onDrop:f=>{ll(f,c)},children:[o.jsx("button",{type:"button",className:"autoruns-question-grip-btn",draggable:!gt&&ot!==c,disabled:gt||ot===c,onDragStart:f=>sl(f,c),onDragEnd:yo,title:"Перетащить вопрос","aria-label":`Перетащить вопрос ${c+1}`,children:o.jsx(Sd,{})}),ot===c?o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:Wn,className:"autoruns-generated-question-input",value:bn,onChange:f=>Rt(f.target.value),onBlur:ho,onKeyDown:go,placeholder:"Текст вопроса",disabled:gt}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onMouseDown:f=>f.preventDefault(),onClick:()=>{ar(c)},title:"Удалить вопрос","aria-label":`Удалить вопрос ${c+1}`,disabled:gt,children:"×"})]}):o.jsxs("button",{type:"button",className:"autoruns-generated-question-text",onDoubleClick:()=>rl(c),title:"Двойной клик для редактирования",children:[c+1,". ",i]})]},`${c}-${i.slice(0,24)}`))}),o.jsx("button",{type:"button",className:"autoruns-add-question-btn",onClick:()=>{vo()},disabled:!$e||gt,children:"+"})]}),Oe?null:o.jsx("p",{className:"muted",children:"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."})]})]}):null,o.jsxs("div",{className:"autoruns-group-heading",children:[o.jsx("h4",{children:Oe?"Сохраненные пользовательские сессии":"История автогенераций"}),o.jsx("button",{type:"button",className:"autoruns-group-toggle",onClick:()=>Nn(i=>!i),"aria-label":It?Oe?"Скрыть группу сохраненных пользовательских сессий":"Скрыть группу истории автогенераций":Oe?"Показать группу сохраненных пользовательских сессий":"Показать группу истории автогенераций",title:It?"Скрыть группу":"Показать группу",children:o.jsx(la,{expanded:It})})]}),It?o.jsxs("div",{className:"autoruns-autogen-list",children:[N?o.jsx("p",{className:"muted",children:Oe?"Загружаю сохраненные пользовательские сессии...":"Загружаю историю автогенераций..."}):null,!N&&be.length===0?o.jsx("p",{className:"muted",children:Oe?"Сохраненные пользовательские сессии пока пусты.":"История автогенераций пока пустая."}):null,Yo.map(i=>{const c=Fn&&js===i.generation_id,f=Fn&&js!==i.generation_id;return o.jsxs("article",{className:["autoruns-autogen-item",De===i.generation_id?"selected":"",qt===i.generation_id?"expanded":"",Oe?"saved-session":""].filter(Boolean).join(" "),onClick:Oe?void 0:()=>ht(i.generation_id),children:[Oe?o.jsxs("div",{className:"autoruns-saved-session-topbar",children:[o.jsx("button",{type:"button",className:"autoruns-saved-session-icon-btn",disabled:ks||f,onClick:w=>{if(w.preventDefault(),w.stopPropagation(),c){po();return}ht(i.generation_id),nl(i,De===i.generation_id?fe:i.questions)},title:c?"Остановить прогон":"Запустить прогон","aria-label":`${c?"Остановить прогон":"Запустить прогон"} для ${Ji(i)}`,children:c?o.jsx(yp,{}):o.jsx(vp,{})}),o.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),Rr(i)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${i.generation_id}`,children:"×"})]}):null,o.jsxs("header",{children:[o.jsx("strong",{children:Ji(i)}),o.jsx("div",{className:"autoruns-autogen-card-actions",children:o.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),Rr(i)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${i.generation_id}`,children:"×"})})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Дата и время"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",vn(i.created_at)]})]}),o.jsxs("div",{className:"autoruns-saved-session-meta autoruns-saved-session-meta-id",children:[o.jsxs("div",{className:"autoruns-saved-session-meta-id-main",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"ID"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",i.generation_id]})]}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:w=>{Pr(w,i.generation_id,"set id")},onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),Pr(w,i.generation_id,"set id"))},title:"Скопировать id набора","aria-label":`Скопировать id набора ${i.generation_id}`,children:o.jsx(_d,{})})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Режим"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",Ki(i.mode)]})]}),o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Тип"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",Rd(i)?"АГЕНТНЫЙ ПРОГОН":"АВТОПРОГОН"]})]}),Oe?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"autoruns-saved-session-meta",children:[o.jsx("strong",{className:"autoruns-saved-session-meta-label",children:"Количество вопросов"}),o.jsxs("span",{className:"autoruns-saved-session-meta-value",children:["| ",i.questions.length]})]}),o.jsx("div",{className:"autoruns-saved-session-footer",children:o.jsx("button",{type:"button",className:"autoruns-saved-session-icon-btn",onClick:w=>{w.preventDefault(),w.stopPropagation(),al(i.generation_id)},title:qt===i.generation_id?"Скрыть вопросы":"Показать вопросы","aria-label":qt===i.generation_id?"Скрыть вопросы":"Показать вопросы",children:o.jsx(gp,{expanded:qt===i.generation_id})})}),o.jsx("div",{className:qt===i.generation_id?"autoruns-saved-session-questions expanded":"autoruns-saved-session-questions",children:o.jsxs("div",{className:"autoruns-generated-questions autoruns-generated-questions-embedded",children:[o.jsx("div",{className:"autoruns-generated-questions-head",children:o.jsxs("strong",{children:["Вопросы к запуску:"," ",De===i.generation_id?fe.length:i.questions.length]})}),(De===i.generation_id?fe:i.questions).length===0?o.jsx("p",{className:"muted",children:"Список вопросов пуст."}):o.jsx("div",{className:"autoruns-generated-questions-list",children:(De===i.generation_id?fe:i.questions).map((w,A)=>o.jsxs("div",{className:["autoruns-generated-question-item",pe===A&&De===i.generation_id?"drag-over":"",wn===A&&De===i.generation_id?"dragging":"",ot===A&&De===i.generation_id?"editing":""].filter(Boolean).join(" "),onDragOver:ce=>De===i.generation_id?ol(ce,A):void 0,onDrop:ce=>De===i.generation_id?void ll(ce,A):void 0,children:[o.jsx("button",{type:"button",className:"autoruns-question-grip-btn",draggable:De===i.generation_id&&!gt&&ot!==A,disabled:De!==i.generation_id||gt||ot===A,onDragStart:ce=>{ht(i.generation_id),sl(ce,A)},onDragEnd:yo,title:"Перетащить вопрос","aria-label":`Перетащить вопрос ${A+1}`,children:o.jsx(Sd,{})}),De===i.generation_id&&ot===A?o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:Wn,className:"autoruns-generated-question-input",value:bn,onChange:ce=>Rt(ce.target.value),onBlur:ho,onKeyDown:go,placeholder:"Текст вопроса",disabled:gt}),o.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onMouseDown:ce=>ce.preventDefault(),onClick:()=>{ar(A)},title:"Удалить вопрос","aria-label":`Удалить вопрос ${A+1}`,disabled:gt,children:"×"})]}):o.jsxs("button",{type:"button",className:"autoruns-generated-question-text",onDoubleClick:()=>{ht(i.generation_id),rl(A)},title:"Двойной клик для редактирования",children:[A+1,". ",w]})]},`${i.generation_id}-${A}-${w.slice(0,24)}`))}),o.jsx("button",{type:"button",className:"autoruns-add-question-btn",onClick:()=>{ht(i.generation_id),vo()},disabled:De!==i.generation_id||gt,children:"+"})]})})]}):null]},i.generation_id)}),ao>0?o.jsxs("button",{type:"button",className:"autoruns-autogen-load-more-btn",onClick:()=>nr(i=>Math.min(i+Uo,be.length)),children:["Показать еще ",Math.min(Uo,ao)," из ",ao]}):null]}):null,o.jsxs("details",{className:"autoruns-prompt-details",children:[o.jsx("summary",{children:"Копия активного промпта (только чтение)"}),o.jsxs("label",{children:["Системный",o.jsx("textarea",{readOnly:!0,value:F.systemPrompt})]}),o.jsxs("label",{children:["Разработчика",o.jsx("textarea",{readOnly:!0,value:F.developerPrompt})]}),o.jsxs("label",{children:["Доменный",o.jsx("textarea",{readOnly:!0,value:F.domainPrompt})]}),o.jsxs("label",{children:["Заметки по схеме",o.jsx("textarea",{readOnly:!0,value:F.schemaNotes})]}),o.jsxs("label",{children:["Примеры few-shot",o.jsx("textarea",{readOnly:!0,value:F.fewShotExamples})]})]}),Wo?o.jsx("p",{className:"error-text",children:Wo}):null]}):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:(Z?.stats.runs_total??0)+(Be?1:0)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний score"}),o.jsx("strong",{children:oa(Z?.stats.avg_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:Z?gd(Z.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Блокеры"}),o.jsx("strong",{children:Z?.stats.blocking_runs??0})]})]}),o.jsxs("div",{className:"autoruns-run-list",children:[Es.map(i=>o.jsxs("button",{type:"button",className:we===i.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{Yn(i.run_id)},children:[o.jsxs("div",{className:"autoruns-run-head",children:[o.jsx("strong",{children:vn(i.run_timestamp)}),o.jsx("span",{children:mp(i.eval_target)})]}),o.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[o.jsx("span",{children:i.run_id}),o.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{Pr(c,i.run_id,"run id")},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Pr(c,i.run_id,"run id"))},title:"Скопировать run id","aria-label":`Скопировать run id ${i.run_id}`,children:o.jsx(_d,{})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["режим=",i.mode??"нет данных"," | mock=",String(i.use_mock)]}),o.jsxs("div",{className:"autoruns-run-meta",children:["analysis_date=",i.analysis_date??"current_state"]}),i.llm_provider||i.model?o.jsxs("div",{className:"autoruns-run-meta",children:["llm=",i.llm_provider??"нет данных"," | модель=",i.model??"нет данных"]}):null,o.jsxs("div",{className:"autoruns-run-meta",children:["промпт=",i.prompt_version??"нет данных"]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["оценка: ",oa(i.score_index)]}),o.jsxs("span",{children:["закрыто/открыто: ",i.closed_cases,"/",i.open_cases]})]}),o.jsxs("div",{className:"autoruns-run-foot",children:[o.jsxs("span",{children:["блокеры: ",i.blocking_failures]}),o.jsxs("span",{children:["качество: ",i.quality_failures]})]})]},i.run_id)),Es.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:we,onChange:i=>{const c=i.target.value;Yn(c)},children:Es.map(i=>o.jsxs("option",{value:i.run_id,children:[vn(i.run_timestamp)," | ",i.run_id]},i.run_id))})]}),o.jsxs("label",{children:["Кейс",o.jsxs("select",{value:Ke,onChange:i=>{const c=i.target.value;St(c),we&&c&&ss(we,c)},children:[($?.cases.length??0)>0?o.jsx("option",{value:Pt,children:"ВСЕ кейсы подряд"}):null,($?.cases??[]).map(i=>o.jsxs("option",{value:i.case_id,children:[i.case_id," | ",i.status]},i.case_id))]})]}),o.jsxs("div",{className:"autoruns-dialog-copy-actions",children:[o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Tr("default")},disabled:_s||et||(y?.messages.length??0)===0,title:"Скопировать question-answer диалог текущего прогона",children:"Скопировать чат"}),o.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Tr("technical")},disabled:_s||et||(y?.messages.length??0)===0,title:"Скопировать диалог вместе с debug JSON и метаданными прогона",children:"Скопировать техчат"}),o.jsxs("div",{className:"autoruns-dialog-copy-status",children:[to==="success"?o.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Go,")"]}):null,to==="error"?o.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]})]})]}),o.jsxs("div",{className:"autoruns-case-list",children:[($?.cases.length??0)>0?o.jsxs("button",{type:"button",className:Ke===Pt?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{St(Pt),we&&ss(we,Pt)},children:[o.jsx("span",{children:"ВСЕ кейсы подряд"}),o.jsx("span",{children:$?.cases.length})]},Pt):null,($?.cases??[]).map(i=>o.jsxs("button",{type:"button",className:Ke===i.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{St(i.case_id),we&&ss(we,i.case_id)},children:[o.jsx("span",{children:i.case_id}),o.jsxs("span",{children:[i.status,i.commented_count>0?` | комм=${i.commented_count}`:""]})]},i.case_id))]}),o.jsxs("div",{className:"autoruns-dialog-view",children:[_s||et?o.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!_s&&!et&&(y?.messages.length??0)===0?o.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(y?.messages??[]).map((i,c)=>{const f=i.role==="assistant"?"assistant":"user";return o.jsxs("article",{className:`autoruns-msg ${f}`,children:[o.jsxs("header",{children:[o.jsx("strong",{children:f==="assistant"?"Система":"Модель/вопрос"}),o.jsxs("div",{className:"autoruns-msg-head-actions",children:[i.case_id?o.jsx("span",{className:"autoruns-msg-case-tag",children:i.case_id}):null,hd(i)?o.jsx("span",{className:"autoruns-msg-case-tag",children:hd(i)}):null,o.jsx("span",{children:i.created_at?vn(i.created_at):"нет данных"}),f==="assistant"&&!Xs(we)?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:i.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>ya(i),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(hp,{commented:i.commented})}),i.annotation?o.jsx("button",{type:"button",className:i.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{as(i.annotation,!i.annotation.resolved)},disabled:eo===i.annotation.annotation_id,title:i.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":i.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(xd,{resolved:i.annotation.resolved})}):null]}):null]})]}),o.jsx("p",{children:i.text}),f==="assistant"&&i.annotation?o.jsxs("div",{className:"autoruns-msg-annotation",children:[o.jsx("strong",{children:Yi(i.annotation.rating)}),o.jsx("span",{children:i.annotation.comment}),o.jsxs("span",{className:"muted",children:[i.annotation.manual_case_decision,i.annotation.annotation_author?` | ${i.annotation.annotation_author}`:""]})]}):null,(i.trace_id||i.reply_type)&&o.jsxs("footer",{children:[i.trace_id?o.jsxs("span",{children:["trace=",i.trace_id]}):null,i.reply_type?o.jsxs("span",{children:["reply_type=",i.reply_type]}):null]})]},i.message_id??`${f}-${c}`)})]})]}),_t?o.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:o.jsx(np,{sessionId:lt,conversation:Jt,inputValue:Cr,onInputChange:$t,selectedContextChip:ro,onSelectContextChip:At,onClearContextChip:()=>At(null),useMock:so,onUseMockChange:fa,onSend:ma,onClear:Xo,onSaveSession:ha,busy:qo,saveBusy:Xt.saving,saveDisabled:!lt.trim()||Jt.length===0||qo,statusText:Ss,errorMessage:ws,showSaveAction:!0,showCommentAction:!0,onCommentAssistantMessage:wa,isAssistantMessageCommented:Sa,canCommentAssistantMessage:_a})}):null,dt?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:oa(Z?.stats.latest_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Предыдущий"}),o.jsx("strong",{children:oa(Z?.stats.previous_score_index??null)})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Тренд"}),o.jsx("strong",{children:Z?gd(Z.stats.trend):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Пробелы качества"}),o.jsx("strong",{children:Z?.stats.quality_gap_runs??0})]})]}),o.jsx("h4",{children:"Покрытие доменов (история)"}),vd(Z?.stats.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),vd($?.coverage.domain_coverage??[]),o.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),kn?o.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,kn?null:o.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(_r?.post_analysis.stats.by_queue??{}).map(([i,c])=>o.jsxs("div",{children:[o.jsx("span",{children:i}),o.jsx("strong",{children:c})]},i))}),o.jsxs("div",{className:"autoruns-autogen-list",children:[(_r?.post_analysis.recommended_regression_candidates??[]).slice(0,12).map(i=>o.jsxs("article",{className:"autoruns-autogen-item",children:[o.jsxs("header",{children:[o.jsx("strong",{children:i.manual_case_decision}),o.jsxs("span",{children:[i.rating,"/5"]})]}),o.jsxs("div",{className:"autoruns-run-meta",children:[i.domain??"неизвестно"," / ",i.query_class??"неизвестно"]}),o.jsx("p",{children:i.comment})]},i.annotation_id)),!kn&&(_r?.post_analysis.recommended_regression_candidates.length??0)===0?o.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Gt?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:de,onChange:i=>xe(i.target.value),children:[o.jsx("option",{value:"all",children:"все"}),(sn.length>0?sn:Ne?.enum??[]).map(i=>o.jsx("option",{value:i,children:String(Ne?.labels?.[i]??i)},i))]})]}),o.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>ke(i=>!i),children:je?"Показать выполненные":"Скрыть выполненные"})]}),o.jsxs("div",{className:"autoruns-stats-grid",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Комментариев"}),o.jsx("strong",{children:zt.length})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Средний рейтинг"}),o.jsx("strong",{children:ns===null?"нет данных":`${ns.toFixed(2)} / 5`})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Последний"}),o.jsx("strong",{children:zt.length>0?vn(zt[0].updated_at):"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"Статус"}),o.jsx("strong",{children:Kt?"обновляю":"готово"})]})]}),o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",disabled:Kt,onClick:()=>{rs()},children:Kt?"Обновляю...":"Обновить список"}),o.jsx("button",{type:"button",className:"tab",disabled:kn,onClick:()=>{Tn()},children:kn?"Идет пост-анализ...":"Обновить пост-анализ"})]}),o.jsxs("div",{className:"autoruns-comments-list",children:[Kt?o.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!Kt&&zt.length===0?o.jsx("p",{className:"muted",children:re.length===0&&Yr.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,zt.map(i=>{if(i.source==="assistant_live"){const f=i.assistant;return o.jsxs("article",{className:"autoruns-comment-item",children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Yi(f.rating)}),o.jsx("div",{className:"autoruns-comment-head-actions",children:o.jsx("span",{children:vn(f.updated_at)})})]}),o.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",f.session_id]}),o.jsxs("div",{className:"autoruns-run-meta",children:["msg=",f.message_index]}),o.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",f.annotation_author?` | author=${f.annotation_author}`:""]}),f.context.question_text?o.jsxs("p",{children:["Q: ",f.context.question_text]}):null,f.context.answer_text?o.jsxs("p",{children:["A: ",f.context.answer_text]}):null,o.jsx("p",{children:f.comment})]},i.key)}const c=i.autorun;return o.jsxs("article",{className:On===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{ul(c)},role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),ul(c))},children:[o.jsxs("div",{className:"autoruns-comment-head",children:[o.jsx("strong",{children:Yi(c.rating)}),o.jsxs("div",{className:"autoruns-comment-head-actions",children:[o.jsx("span",{children:vn(c.updated_at)}),o.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:f=>{f.preventDefault(),f.stopPropagation(),as(c,!c.resolved)},disabled:eo===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:o.jsx(xd,{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:["выполнено",": ",vn(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})]},i.key)})]}),Me?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:Me.technical_context.trace_id??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"reply_type:"}),o.jsx("strong",{children:Me.technical_context.reply_type??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"domain:"}),o.jsx("strong",{children:Me.technical_context.domain??"нет данных"})]}),o.jsxs("div",{children:[o.jsx("span",{children:"query_class:"}),o.jsx("strong",{children:Me.technical_context.query_class??"нет данных"})]})]}),o.jsx("h4",{children:"JSON разбор"}),o.jsx(Pd,{value:{annotation_id:Me.annotation_id,run_id:Me.run_id,case_id:Me.case_id,message_index:Me.message_index,rating:Me.rating,comment:Me.comment,manual_case_decision:Me.manual_case_decision,annotation_author:Me.annotation_author,resolved:Me.resolved,resolved_at:Me.resolved_at,resolved_by:Me.resolved_by,context:Me.context,technical_context:Me.technical_context,case_summary:Me.case_summary?{case_id:Me.case_summary.case_id,domain:Me.case_summary.domain,query_class:Me.case_summary.query_class,checks:Me.case_summary.checks,metric_subscores:Me.case_summary.metric_subscores}:null}})]}):null]}):null]}),Xt.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&Jn()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Сохранить ручную сессию"}),o.jsx("p",{className:"muted",children:"Технический чат будет сохранен в автопрогоны как пользовательская multi-turn сессия."}),o.jsxs("label",{children:["Название",o.jsx("input",{value:Xt.title,onChange:i=>Gn(c=>({...c,title:i.target.value})),placeholder:"Например: НДС и склад на март 2020",disabled:Xt.saving})]}),Xt.error?o.jsx("p",{className:"error-text",children:Xt.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ga()},disabled:Xt.saving,children:Xt.saving?"Сохраняю...":"Сохранить"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Jn(),disabled:Xt.saving,children:"Отмена"})]})]})}):null,vt.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&Ps()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Удалить вопрос"}),o.jsx("p",{className:"muted",children:"Действительно удалить вопрос из сохраненной пользовательской сессии?"}),o.jsx("p",{className:"autoruns-comment-quote",children:vt.questionText}),vt.error?o.jsx("p",{className:"error-text",children:vt.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{mo()},disabled:vt.saving,children:vt.saving?"Удаляю...":"Да"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Ps(),disabled:vt.saving,children:"Нет"})]})]})}):null,ln.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&Er()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Удалить сохраненный набор"}),o.jsx("p",{className:"muted",children:"Будет удалена карточка истории и связанный файл кейс-сета на бэке."}),o.jsx("p",{className:"autoruns-comment-quote",children:ln.title}),ln.error?o.jsx("p",{className:"error-text",children:ln.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ls()},disabled:ln.saving,children:ln.saving?"Удаляю...":"Да"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Er(),disabled:ln.saving,children:"Нет"})]})]})}):null,_e.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&Kn()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу ассистента"}),o.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),uo?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Вопрос пользователя"}),o.jsx("p",{className:"autoruns-comment-quote",children:uo.text})]}):null,ts?o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ ассистента"}),o.jsx("p",{className:"autoruns-comment-quote",children:ts.text})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа ассистента",children:[1,2,3,4,5].map(i=>o.jsx("button",{type:"button",className:_e.rating>=i?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>at(c=>({...c,rating:i})),disabled:_e.saving,"aria-label":`Оценка ${i}`,children:_e.rating>=i?"●":"○"},i))}),o.jsx("div",{className:"autoruns-form-grid",children:o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:_e.annotationAuthor,onChange:i=>at(c=>({...c,annotationAuthor:i.target.value})),placeholder:"manual_reviewer",disabled:_e.saving})]})}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:_e.comment,onChange:i=>at(c=>({...c,comment:i.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:_e.saving})]}),_e.error?o.jsx("p",{className:"error-text",children:_e.error}):null,o.jsxs("div",{className:"button-row",children:[o.jsx("button",{type:"button",onClick:()=>{ja()},disabled:_e.saving,children:_e.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Kn(),disabled:_e.saving,children:"Отмена"})]})]})}):null,ue.open?o.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:i=>{i.target===i.currentTarget&&Ms()},children:o.jsxs("div",{className:"autoruns-comment-modal",children:[o.jsx("h3",{children:"Комментарий к ответу системы"}),o.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),io?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:qn?.text??"Вопрос в диалоге не найден."})]}),o.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[o.jsx("summary",{children:"Ответ системы"}),o.jsx("p",{className:"autoruns-comment-quote",children:io.text})]})]}):null,o.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(i=>o.jsx("button",{type:"button",className:ue.rating>=i?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>jt(c=>({...c,rating:i})),disabled:ue.saving,"aria-label":`Оценка ${i}`,children:ue.rating>=i?"●":"○"},i))}),o.jsxs("div",{className:"autoruns-form-grid",children:[o.jsxs("label",{children:["Решение по кейсу",o.jsx("select",{value:ue.manualCaseDecision,onChange:i=>jt(c=>({...c,manualCaseDecision:i.target.value})),disabled:ue.saving,children:(sn.length>0?sn:Ne?.enum??[ra]).map(i=>o.jsx("option",{value:i,children:String(Ne?.labels?.[i]??i)},i))})]}),o.jsxs("label",{children:["Автор комментария",o.jsx("input",{value:ue.annotationAuthor,onChange:i=>jt(c=>({...c,annotationAuthor:i.target.value})),placeholder:"manual_reviewer",disabled:ue.saving})]})]}),o.jsxs("label",{children:["Комментарий",o.jsx("textarea",{value:ue.comment,onChange:i=>jt(c=>({...c,comment:i.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:()=>{xa()},disabled:ue.saving,children:ue.saving?"Сохраняю...":"Готово"}),o.jsx("button",{type:"button",className:"tab",onClick:()=>Ms(),disabled:ue.saving,children:"Отмена"})]})]})}):null]})}const _p={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},jd={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."},Sp={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},Xi={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}},kd="ndc_normalizer_session_config_v1",Cd="ndc_autoruns_layout_config_v1",wp="ndc-autoruns-save",jp="autoruns",Zi="normalizer_v2_0_2",kp="address_query_runtime_v1",Cp=["normalized","fragments","scope","flags","route","raw","validation","logs"];function Np(a){return`[${new Date().toLocaleTimeString("ru-RU")}] ${a}`}function Ep(a,m){if(!m)return"Previous preset is not selected.";const S=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(C=>a[C]!==m[C]).map(C=>`${C}: ${Math.abs(a[C].length-m[C].length)} chars delta`);return S.length===0?"No changes against previous preset.":`Changed fields: ${S.length}. ${S.join(" | ")}`}function Pp(){const[a,m]=g.useState(_p),[p,S]=g.useState(jd),[C,M]=g.useState(Sp),[b,le]=g.useState(null),[te,F]=g.useState([]),[Y,X]=g.useState([]),[ee,Ae]=g.useState("normalized"),[me,he]=g.useState(!1),[ye,We]=g.useState(!1),[Ze,qe]=g.useState([]),[Ie,U]=g.useState(""),[oe,Pe]=g.useState([]),[He,_t]=g.useState(""),[dt,Gt]=g.useState("NDC custom preset"),[ft,Q]=g.useState(null),[Le,Ye]=g.useState(""),[ne,Z]=g.useState(!1),[I,$]=g.useState([]),[L,y]=g.useState(""),[k,re]=g.useState([]),[ie,de]=g.useState(!1),[xe,je]=g.useState(null),[ke,Ne]=g.useState(""),[pt,sn]=g.useState(jp),[yr,On]=g.useState(!0),[yn,we]=g.useState(!0),[Wt,Ke]=g.useState(!0),[St,Tt]=g.useState(!0),[xn,W]=g.useState(!0),[mt,xr]=g.useState(!0),[$n,Gr]=g.useState(!0),[nr,De]=g.useState(!0),[ht,qt]=g.useState(!0),[_n,fe]=g.useState(!0),[Sn,gt]=g.useState(!0),[Wr,ot]=g.useState(!0),[zn,bn]=g.useState(!0),Rt=g.useRef(!1),wn=g.useRef(!1),on=g.useRef(!1);g.useEffect(()=>{const N=document.documentElement,{colors:J}=Xi;N.style.setProperty("--rgb-background",J.backgroundRgb),N.style.setProperty("--rgb-surface-main",J.mainSurfaceRgb),N.style.setProperty("--rgb-surface-horizontal",J.horizontalSurfaceRgb),N.style.setProperty("--rgb-surface-focus",J.focusSurfaceRgb),N.style.setProperty("--rgb-assistant-chip",J.assistantChipRgb),N.style.setProperty("--rgb-assistant-chip-hover",J.assistantChipHoverRgb),N.style.setProperty("--rgb-assistant-chip-selected",J.assistantChipSelectedRgb),N.style.setProperty("--rgb-assistant-chip-selected-text",J.assistantChipSelectedTextRgb),N.style.setProperty("--rgb-active",J.activeRgb),N.style.setProperty("--rgb-active-text",J.activeTextRgb),N.style.setProperty("--rgb-text-main",J.textMainRgb),N.style.setProperty("--rgb-text-muted",J.textMutedRgb),N.style.setProperty("--rgb-danger",J.dangerRgb),N.style.setProperty("--rgb-scrollbar-track",J.scrollbarTrackRgb),N.style.setProperty("--rgb-scrollbar-thumb",J.scrollbarThumbRgb),N.style.setProperty("--rgb-scrollbar-thumb-hover",J.scrollbarThumbHoverRgb),N.style.setProperty("--mode-column-width",`${Xi.layout.modeColumnWidthPx}px`),N.style.setProperty("--mode-toggle-width",`${Xi.layout.modeToggleWidthPx}px`)},[]);const pe=N=>{X(J=>[Np(N),...J].slice(0,300))};g.useEffect(()=>{(async()=>{const V=localStorage.getItem(kd);if(V)try{const Te=JSON.parse(V);m(et=>({...et,llmProvider:Te.llmProvider==="local"?"local":"openai",model:Te.model??et.model,baseUrl:Te.baseUrl??et.baseUrl,temperature:Te.temperature??et.temperature,maxOutputTokens:Te.maxOutputTokens??et.maxOutputTokens}))}catch{}try{const Te=await Re.loadSharedConnectionConfig();Te.connection&&Te.connection.llmProvider==="local"&&(m(et=>({...et,llmProvider:"local",model:Te.connection?.model??et.model,baseUrl:Te.connection?.baseUrl??et.baseUrl,temperature:Te.connection?.temperature??et.temperature,maxOutputTokens:Te.connection?.maxOutputTokens??et.maxOutputTokens})),pe(`Shared local LLM config loaded: ${Te.connection.model}`))}catch(Te){pe(`Shared local config load error: ${Te instanceof Error?Te.message:String(Te)}`)}finally{on.current=!0}})();const J=localStorage.getItem(Cd);if(J)try{const V=JSON.parse(J);(V.uiMode==="assistant"||V.uiMode==="autoruns"||V.uiMode==="decomposition")&&sn("autoruns"),V.activeTab&&Cp.includes(V.activeTab)&&Ae(V.activeTab),typeof V.showAutorunsSettingsMode=="boolean"&&On(V.showAutorunsSettingsMode),typeof V.showAutorunsAutoRunsMode=="boolean"&&we(V.showAutorunsAutoRunsMode),typeof V.showAutorunsAssistantMode=="boolean"&&Ke(V.showAutorunsAssistantMode),typeof V.showAutorunsDecompositionMode=="boolean"&&Tt(V.showAutorunsDecompositionMode),typeof V.showAutorunsProgressMode=="boolean"&&W(V.showAutorunsProgressMode),typeof V.showAutorunsCommentsMode=="boolean"&&xr(V.showAutorunsCommentsMode),typeof V.showDecompositionConnectionMode=="boolean"&&Gr(V.showDecompositionConnectionMode),typeof V.showDecompositionPromptMode=="boolean"&&De(V.showDecompositionPromptMode),typeof V.showDecompositionQueryMode=="boolean"&&qt(V.showDecompositionQueryMode),typeof V.showDecompositionOutputMode=="boolean"&&fe(V.showDecompositionOutputMode),typeof V.showDecompositionMetricsMode=="boolean"&>(V.showDecompositionMetricsMode),typeof V.showDecompositionHistoryMode=="boolean"&&ot(V.showDecompositionHistoryMode),typeof V.showDecompositionRuntimeMode=="boolean"&&bn(V.showDecompositionRuntimeMode),V.prompts&&(S(Te=>({...Te,...V.prompts})),wn.current=!0)}catch{}Mt(),Be(),jn()},[]),g.useEffect(()=>{if(!on.current||a.llmProvider!=="local")return;const N=window.setTimeout(()=>{Re.saveSharedConnectionConfig(a).catch(J=>pe(`Shared local config sync error: ${J instanceof Error?J.message:String(J)}`))},250);return()=>window.clearTimeout(N)},[a.baseUrl,a.llmProvider,a.maxOutputTokens,a.model,a.temperature]);async function Mt(){try{const N=await Re.loadHistory();F(N.items??[])}catch(N){pe(`History load error: ${N instanceof Error?N.message:String(N)}`)}}async function Be(){try{const J=(await Re.loadPresets()).presets??[];if(Pe(J),wn.current){Rt.current=!0;return}if(Rt.current)return;const V=J.find(Te=>Te.prompt_version===Zi)??J.find(Te=>Te.id==="default-normalizer-v2_0_2");if(!V){Rt.current=!0,pe(`Preset autoload skipped: ${Zi} not found.`);return}_t(V.id),Q(p),S({systemPrompt:V.systemPrompt,developerPrompt:V.developerPrompt,domainPrompt:V.domainPrompt,schemaNotes:V.schemaNotes??"",fewShotExamples:V.fewShotExamples??""}),Rt.current=!0,pe(`Preset autoloaded: ${V.name} (${V.prompt_version}).`)}catch(N){pe(`Presets load error: ${N instanceof Error?N.message:String(N)}`)}}async function jn(){try{const N=await Re.listRuns();$(N.items??[])}catch(N){pe(`Runs load error: ${N instanceof Error?N.message:String(N)}`)}}function _r(){if(localStorage.setItem(kd,JSON.stringify({model:a.model,llmProvider:a.llmProvider,baseUrl:a.baseUrl,temperature:a.temperature,maxOutputTokens:a.maxOutputTokens})),a.llmProvider==="local"){Re.saveSharedConnectionConfig(a).then(()=>{pe("Local config saved and synced to shared agent config (without API key).")}).catch(N=>{pe(`Local config saved, but shared sync failed: ${N instanceof Error?N.message:String(N)}`)});return}pe("Local config saved (without API key).")}function qr(){localStorage.setItem(Cd,JSON.stringify({uiMode:pt,activeTab:ee,showAutorunsSettingsMode:yr,showAutorunsAutoRunsMode:yn,showAutorunsAssistantMode:Wt,showAutorunsDecompositionMode:St,showAutorunsProgressMode:xn,showAutorunsCommentsMode:mt,showDecompositionConnectionMode:$n,showDecompositionPromptMode:nr,showDecompositionQueryMode:ht,showDecompositionOutputMode:_n,showDecompositionMetricsMode:Sn,showDecompositionHistoryMode:Wr,showDecompositionRuntimeMode:zn,prompts:p})),window.dispatchEvent(new CustomEvent(wp)),pe("UI layout and prompts saved.")}async function Kr(){he(!0),Ne("");try{const N=await Re.testConnection(a);N.provider==="local"?N.model_found===!0?(U(`LOCAL OK - ${N.model}`),pe(`Local model is available: ${N.model} (catalog size=${N.models_count??"n/a"}).`)):N.model_found===!1?(U(`LOCAL OK, model not loaded - ${N.model}`),pe(`Local server is reachable, but model '${N.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(U(`LOCAL OK (model list unavailable) - ${N.model}`),pe("Local server is reachable, but model catalog could not be verified.")):(U(`OPENAI OK - ${N.model}`),pe(`OpenAI connection ok: ${N.model}`))}catch(N){const J=N instanceof Error?N.message:String(N);U("Connection error"),Ne(`Test connection: ${J}`),pe(`Test connection error: ${J}`)}finally{he(!1)}}async function Sr(){We(!0);try{const J=(await Re.listModels(a)).models??[];qe(J),J.length>0&&m(V=>V.model&&J.includes(V.model)?V:{...V,model:J[0]}),pe(`Model catalog loaded (${a.llmProvider}): ${J.length} items.`)}catch(N){const J=N instanceof Error?N.message:String(N);pe(`Load model list error: ${J}`)}finally{We(!1)}}g.useEffect(()=>{qe([])},[a.llmProvider,a.baseUrl]);function Fn(){const N=oe.find(J=>J.id===He);if(!N){pe("Preset is not selected.");return}Q(p),S({systemPrompt:N.systemPrompt,developerPrompt:N.developerPrompt,domainPrompt:N.domainPrompt,schemaNotes:N.schemaNotes??"",fewShotExamples:N.fewShotExamples??""}),pe(`Preset loaded: ${N.name}`)}async function wt(){try{await Re.savePreset({name:dt||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:p.systemPrompt,developerPrompt:p.developerPrompt,domainPrompt:p.domainPrompt,schemaNotes:p.schemaNotes,fewShotExamples:p.fewShotExamples}),pe("Preset saved."),await Be()}catch(N){pe(`Preset save error: ${N instanceof Error?N.message:String(N)}`)}}function kn(){S(jd),pe("Prompt panel reset to defaults.")}function Un(){const N=Ep(p,ft);Ye(N),pe(N)}return g.useEffect(()=>{if(!L){re([]);return}Re.runTrace(L).then(N=>re(N.items)).catch(N=>pe(`Run trace error: ${N instanceof Error?N.message:String(N)}`))},[L]),o.jsxs("main",{className:"app-root 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:"tab active",onClick:()=>sn("autoruns"),children:"Управление ассистентом"}),o.jsx("button",{type:"button",className:"tab",onClick:qr,children:"Сохранить"})]}),o.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[o.jsx("button",{type:"button",className:yr?"tab active":"tab",onClick:()=>On(N=>!N),children:"Настройки"}),o.jsx("button",{type:"button",className:yn?"tab active":"tab",onClick:()=>we(N=>!N),children:"Автопрогоны"}),o.jsx("button",{type:"button",className:Wt?"tab active":"tab",onClick:()=>Ke(N=>!N),children:"Режим ассистента"}),o.jsx("button",{type:"button",className:xn?"tab active":"tab",onClick:()=>W(N=>!N),children:"Прогресс/регресс"}),o.jsx("button",{type:"button",className:mt?"tab active":"tab",onClick:()=>xr(N=>!N),children:"Комментарии"})]})]}),o.jsx("div",{className:"layout-grid layout-grid-autoruns",children:o.jsx(xp,{connection:a,modelOptions:Ze,modelsBusy:ye,connectionStatus:Ie,connectionBusy:me,onConnectionChange:m,onReloadModels:Sr,onSaveLocalConfig:_r,onTestConnection:Kr,prompts:p,onPromptsChange:S,promptPresets:oe,selectedPresetId:He,onSelectPreset:_t,onLoadPreset:Fn,onSavePreset:wt,onResetDefaults:kn,onDiffPrevious:Un,presetName:dt,onPresetNameChange:Gt,diffSummary:Le,assistantPromptVersion:kp,decompositionPromptVersion:Zi,showSettingsMode:yr,showAutoRunsMode:yn,showAssistantMode:Wt,showProgressMode:xn,showCommentsMode:mt,onLog:pe})})]})}Of.createRoot(document.getElementById("root")).render(o.jsx(Tf.StrictMode,{children:o.jsx(Pp,{})})); diff --git a/llm_normalizer/frontend/dist/index.html b/llm_normalizer/frontend/dist/index.html index 65bbe0b..e89a0d5 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/api/client.ts b/llm_normalizer/frontend/src/api/client.ts index a7c4a39..50d8303 100644 --- a/llm_normalizer/frontend/src/api/client.ts +++ b/llm_normalizer/frontend/src/api/client.ts @@ -312,7 +312,6 @@ export const apiClient = { async sendAssistantMessage(input: { connection: ConnectionState; - prompts: PromptState; userMessage: string; sessionId?: string; promptVersion?: string; @@ -336,10 +335,6 @@ export const apiClient = { temperature: input.connection.temperature, maxOutputTokens: input.connection.maxOutputTokens, promptVersion: input.promptVersion ?? "address_query_runtime_v1", - systemPrompt: input.prompts.systemPrompt, - developerPrompt: input.prompts.developerPrompt, - domainPrompt: input.prompts.domainPrompt, - fewShotExamples: input.prompts.fewShotExamples, context: { period_hint: input.context?.periodHint ?? "", business_context: input.context?.businessContext ?? "" @@ -362,7 +357,6 @@ export const apiClient = { model?: string; assistant_prompt_version?: string; decomposition_prompt_version?: string; - prompt_fingerprint?: string; }; }): Promise<{ ok: boolean; generation: AutoGenHistoryRecord }> { return request("/autoruns/autogen/save-assistant-session", { @@ -534,35 +528,5 @@ export const apiClient = { return request(`/autoruns/autogen/history/${encodeURIComponent(generationId)}`, { method: "DELETE" }); - }, - - async generateAutoRunQuestions(input: { - mode: AutoGenMode; - count: number; - domain?: string; - persist_to_eval_cases?: boolean; - generated_by?: string; - llm?: { - llm_provider?: "openai" | "local"; - api_key?: string; - model?: string; - base_url?: string; - temperature?: number; - max_output_tokens?: number; - }; - context?: { - llm_provider?: string; - model?: string; - assistant_prompt_version?: string; - decomposition_prompt_version?: string; - prompt_fingerprint?: string; - autogen_personality_id?: string; - autogen_personality_prompt?: string; - }; - }): Promise<{ ok: boolean; generation: AutoGenHistoryRecord }> { - return request("/autoruns/autogen/generate", { - method: "POST", - body: JSON.stringify(input) - }); } }; diff --git a/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx b/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx index cde0e39..1ed3705 100644 --- a/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx +++ b/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx @@ -244,7 +244,7 @@ type UnifiedCommentListItem = }; const DEFAULT_AUTOGEN_SETTINGS: AutoGenSettingsState = { - mode: "codex_creative", + mode: "saved_user_sessions", count: 24, personalityId: "general", personalityPrompts: buildDefaultPersonalityPrompts(), @@ -723,7 +723,6 @@ export function AutoRunsHistoryPanel({ const [dragOverQuestionIndex, setDragOverQuestionIndex] = useState(null); const [activeAsyncJob, setActiveAsyncJob] = useState(null); const [postAnalysis, setPostAnalysis] = useState(null); - const [autoGenBusy, setAutoGenBusy] = useState(false); const [autogenRunBusy, setAutogenRunBusy] = useState(false); const [postAnalysisBusy, setPostAnalysisBusy] = useState(false); const [autogenHistoryBusy, setAutogenHistoryBusy] = useState(false); @@ -801,10 +800,6 @@ export function AutoRunsHistoryPanel({ const asyncJobPollTimerRef = useRef(null); const questionEditorRef = useRef(null); const isSavedUserSessionsMode = autoGenSettings.mode === "saved_user_sessions"; - const selectedPersonality = useMemo( - () => autogenPersonalities.find((item) => item.id === autoGenSettings.personalityId) ?? autogenPersonalities[0] ?? AUTOGEN_PERSONALITIES[0], - [autoGenSettings.personalityId, autogenPersonalities] - ); const visibleAutoGenHistory = useMemo( () => autoGenHistory.filter((item) => item.mode === autoGenSettings.mode), [autoGenHistory, autoGenSettings.mode] @@ -1104,7 +1099,6 @@ export function AutoRunsHistoryPanel({ try { const response = await apiClient.sendAssistantMessage({ connection, - prompts, userMessage, sessionId: assistantLiveSessionId || undefined, promptVersion: assistantPromptVersion, @@ -1132,8 +1126,7 @@ export function AutoRunsHistoryPanel({ assistantPromptVersion, connection, loadAssistantLiveAnnotationsForSession, - log, - prompts + log ]); const openAssistantLiveSaveModal = useCallback(() => { @@ -1164,13 +1157,6 @@ export function AutoRunsHistoryPanel({ setAssistantLiveSaveModal((prev) => ({ ...prev, saving: true, error: "" })); try { - const promptFingerprint = [ - prompts.systemPrompt, - prompts.developerPrompt, - prompts.domainPrompt, - prompts.schemaNotes, - prompts.fewShotExamples - ].join("||"); const payload = await apiClient.saveAutoRunAssistantSession({ session_id: sessionId, title, @@ -1179,8 +1165,7 @@ export function AutoRunsHistoryPanel({ llm_provider: connection.llmProvider, model: connection.model, assistant_prompt_version: assistantPromptVersion, - decomposition_prompt_version: decompositionPromptVersion, - prompt_fingerprint: promptFingerprint + decomposition_prompt_version: decompositionPromptVersion } }); setAutoGenHistory((prev) => [payload.generation, ...prev.filter((item) => item.generation_id !== payload.generation.generation_id)]); @@ -1202,12 +1187,7 @@ export function AutoRunsHistoryPanel({ connection.llmProvider, connection.model, decompositionPromptVersion, - log, - prompts.developerPrompt, - prompts.domainPrompt, - prompts.fewShotExamples, - prompts.schemaNotes, - prompts.systemPrompt + log ]); const commitLimitInput = useCallback( @@ -1363,87 +1343,6 @@ export function AutoRunsHistoryPanel({ } }, [filters.fromLocal, filters.mode, filters.promptContains, filters.target, filters.toLocal, filters.useMock, log, selectedRunId]); - const generateAutogenBatch = useCallback(async () => { - setAutoGenBusy(true); - setErrorText(""); - try { - if (autoGenSettings.mode === "saved_user_sessions") { - throw new Error("Пользовательские сессии сохраняются из живого чата, а не генерируются автоматически."); - } - const activePersonalityPrompt = autoGenSettings.personalityPrompts[autoGenSettings.personalityId] ?? ""; - const promptFingerprint = [ - prompts.systemPrompt, - prompts.developerPrompt, - prompts.domainPrompt, - prompts.schemaNotes, - prompts.fewShotExamples - ] - .join("\n") - .slice(0, 900); - const payload = await apiClient.generateAutoRunQuestions({ - mode: autoGenSettings.mode, - count: autoGenSettings.count, - domain: selectedPersonality.domain || undefined, - persist_to_eval_cases: autoGenSettings.persistToEvalCases, - generated_by: autoGenSettings.generatedBy.trim() || undefined, - llm: { - llm_provider: connection.llmProvider, - api_key: connection.apiKey, - model: connection.model, - base_url: connection.baseUrl, - temperature: connection.temperature, - max_output_tokens: connection.maxOutputTokens - }, - context: { - llm_provider: connection.llmProvider, - model: connection.model, - assistant_prompt_version: assistantPromptVersion, - decomposition_prompt_version: decompositionPromptVersion, - prompt_fingerprint: promptFingerprint, - autogen_personality_id: selectedPersonality.id, - autogen_personality_prompt: activePersonalityPrompt.trim() || undefined - } - }); - log( - `Generated ${payload.generation.count} questions (${payload.generation.mode}) id=${payload.generation.generation_id}` + - (payload.generation.saved_case_set_file ? ` saved=${payload.generation.saved_case_set_file}` : "") - ); - setSelectedAutogenGenerationId(payload.generation.generation_id); - setEditableGeneratedQuestions([...(payload.generation.questions ?? [])]); - await loadAutoGenHistory(); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - setErrorText(`Автогенерация: ${message}`); - log(`Autogen generate error: ${message}`); - } finally { - setAutoGenBusy(false); - } - }, [ - assistantPromptVersion, - autoGenSettings.count, - autoGenSettings.generatedBy, - autoGenSettings.mode, - autoGenSettings.personalityId, - autoGenSettings.personalityPrompts, - autoGenSettings.persistToEvalCases, - connection.apiKey, - connection.baseUrl, - connection.llmProvider, - connection.maxOutputTokens, - connection.model, - connection.temperature, - decompositionPromptVersion, - loadAutoGenHistory, - log, - prompts.developerPrompt, - prompts.domainPrompt, - prompts.fewShotExamples, - prompts.schemaNotes, - prompts.systemPrompt, - selectedPersonality.domain, - selectedPersonality.id - ]); - const loadCaseDialog = useCallback( async (runId: string, caseId: string) => { if (isLiveRunId(runId)) { @@ -2477,12 +2376,7 @@ export function AutoRunsHistoryPanel({ : prev.personalityId; return { ...prev, - mode: - parsed.autoGenSettings?.mode === "codex_creative" || - parsed.autoGenSettings?.mode === "qwen_seed" || - parsed.autoGenSettings?.mode === "saved_user_sessions" - ? parsed.autoGenSettings.mode - : prev.mode, + mode: "saved_user_sessions", count: typeof parsed.autoGenSettings?.count === "number" ? Math.max(1, Math.min(200, parsed.autoGenSettings.count)) @@ -2767,7 +2661,7 @@ export function AutoRunsHistoryPanel({ ) : null}
-

Автопрогоны

+

Сохранённые сессии

- - - ) : null} - + {!isSavedUserSessionsMode ? ( + + ) : null}
diff --git a/llm_normalizer/frontend/src/components/PromptPanel.tsx b/llm_normalizer/frontend/src/components/PromptPanel.tsx index e56ddf4..7ce8968 100644 --- a/llm_normalizer/frontend/src/components/PromptPanel.tsx +++ b/llm_normalizer/frontend/src/components/PromptPanel.tsx @@ -111,8 +111,8 @@ export function PromptPanel({
-

Prompt Manager

-

Системный, developer и domain уровни управляются отдельно.

+

Normalizer / eval prompts

+

Эти поля управляют декомпозицией и eval-прогонами, а не live-ответом ассистента.

{content} @@ -121,7 +121,7 @@ export function PromptPanel({ } return ( - + {content} );