(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,{})}));